Android 使用相同的AsyncTask子类对不同的URL进行API调用
我将从API请求返回的JSON解析的数据存储到Firebase数据库中Android 使用相同的AsyncTask子类对不同的URL进行API调用,android,json,android-asynctask,Android,Json,Android Asynctask,我将从API请求返回的JSON解析的数据存储到Firebase数据库中 submitButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String APIURL = "https://api.github.com/users/" + idInput.getText().toString();
submitButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String APIURL = "https://api.github.com/users/" + idInput.getText().toString();
String repoURL = "https://api.github.com/users/" + idInput.getText().toString() + "/repos";
new JSONTask().execute(APIURL);
//new JSONTask().execute(repoURL);
String parsedUserID = idInput.getText().toString();
SM.sendDataToProfile(parsedUserID);
viewPager.setCurrentItem(1);
//addUser(parsedUserID);
}
});
单击该按钮时,它会在APIRL上调用一个新的JSONTask(asynctask)
JSONTask
public class JSONTask extends AsyncTask<String, String, String> {
@Override
// Any non-UI thread process is running in this method. After completion, it sends the result to OnPostExecute
protected String doInBackground(String... params) {
HttpURLConnection connection = null;
BufferedReader reader = null;
try {
// Pass in a String and convert to URL
URL url = new URL(params[0]);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
InputStream stream = connection.getInputStream();
// Reads the data line by line
reader = new BufferedReader(new InputStreamReader(stream));
StringBuffer strBuffer = new StringBuffer();
String line = "";
while ((line = reader.readLine()) != null) {
strBuffer.append(line);
}
// If we are able to get the data do below :
String retreivedJson = strBuffer.toString();
return retreivedJson;
// When we are not able to retreive the Data
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (connection != null) {
// close both connection and the reader
connection.disconnect();
}
try {
if (reader != null) {
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
公共类JSONTask扩展异步任务{
@凌驾
//任何非UI线程进程都在此方法中运行。完成后,它将结果发送到OnPostExecute
受保护的字符串doInBackground(字符串…参数){
HttpURLConnection=null;
BufferedReader reader=null;
试一试{
//传入字符串并转换为URL
URL=新URL(参数[0]);
connection=(HttpURLConnection)url.openConnection();
connection.connect();
InputStream=connection.getInputStream();
//逐行读取数据
reader=新的BufferedReader(新的InputStreamReader(流));
StringBuffer strBuffer=新的StringBuffer();
字符串行=”;
而((line=reader.readLine())!=null){
strBuffer.append(行);
}
//如果我们能够获得数据,请执行以下操作:
字符串retreivedJson=strBuffer.toString();
返回RetrievedJSON;
//当我们无法检索数据时
}捕获(格式错误){
e、 printStackTrace();
}捕获(IOE异常){
e、 printStackTrace();
}最后{
if(连接!=null){
//关闭连接和读卡器
连接断开();
}
试一试{
if(读卡器!=null){
reader.close();
}
}捕获(IOE异常){
e、 printStackTrace();
}
}
返回null;
}
它在另一个函数中进行解析
我的问题是,正如您在我的setOnClickListener上看到的,我试图在两个不同的URL上创建两个JSONTask,因为第一个URL为我提供了用户信息,第二个URL(repoURL)为我提供了信息提供用户存储库的信息。我试图获取用户的repo信息并将其存储到数据库中,但这似乎是一种错误的方法
在两个不同的URL上调用两个单独的AsyncTask的正确方法是什么
编辑
private void addUserRepo(final String githubID, final String[] repoList) {
DatabaseReference users = databaseReference.child("users");
users.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
List list = new ArrayList<String>(Arrays.asList(repoList));
databaseReference.child("users").child(githubID).child("Repos").setValue(list);
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
private void addUserRepo(最终字符串githubID,最终字符串[]repoList){
DatabaseReference用户=DatabaseReference.child(“用户”);
users.addListenerForSingleValueEvent(新的ValueEventListener()){
@凌驾
公共void onDataChange(DataSnapshot DataSnapshot){
List List=newarraylist(Arrays.asList(repoList));
databaseReference.child(“用户”).child(githubID).child(“Repos”).setValue(列表);
}
@凌驾
已取消的公共void(DatabaseError DatabaseError){
}
});
}
使用从中解析的数据
public void formatJSONArray(String results){
try {
JSONArray jsonArray = new JSONArray(results);
RepoInfo[] repoList = new RepoInfo[jsonArray.length()];
for(int i = 0; i < jsonArray.length(); i++){
JSONObject jsonObject=jsonArray.getJSONObject(i);
if(jsonObject.optString("name") != null) {
repoList[i].setRepoName(jsonObject.getString("name"));
//repoNameList.add(jsonObject.getString("name"));
}
if(jsonObject.optString("description") != null) {
repoList[i].setDescription(jsonObject.getString("description"));
//descriptionList.add(jsonObject.getString("description"));
}
if(jsonObject.optJSONObject("owner") != null){
JSONObject ownerObject=jsonObject.getJSONObject("owner");
if(ownerObject.optString("login")!=null) {
repoList[i].setOwner(ownerObject.getString("login"));
//userNameList.add(ownerObject.getString("login"));
}
}
}
} catch (JSONException jsonException){
}
}
public void formatJSONArray(字符串结果){
试一试{
JSONArray JSONArray=新JSONArray(结果);
RepoInfo[]repoList=newrepoinfo[jsonArray.length()];
for(int i=0;i
两个不同URL的响应肯定不相似。因此,您需要为它们提供不同的解析方法
一种懒惰的方法是为两个不同的URL使用两个不同的AsyncTasks
子类
另一种方法是在asynctask中存储一个标志,指示它是处理user还是repo
public class JSONTask extends AsyncTask <String , String , String> {
boolean fetchingRepo;
@Override
protected String doInBackground (String... params) {
fetchingRepo = params[0].endsWith("/repos");
//other statements
}
你能更好地描述这两个异步调用应该做什么吗?它们是相互依赖的还是相互独立的?抱歉。在“API中,它有用户的基本配置文件信息,还有用户存储库的API URL”。我正在尝试先将基本配置文件信息存储到firebase DB中(我成功地做到了),但我无法从repos URL调用另一个API调用,然后将repos信息存储到列表中,然后将其添加到数据库中。请检查我的编辑以将repoList添加到数据库中。我将把它作为注释而不是回答,但如果您停止使用AsyncTask并切换到使用RxJava,则可以完成此操作。RxJava允许异步执行代码,但您可以使用诸如
flatMap
之类的运算符将相互依赖的调用链接在一起。如果我使用flag方法,那么如果我调用两次JSONTask是否有效?例如,new JSONTask().execute(APIURL);new JSONTask().execute(repoURL);是的,会的。如果我认为它不管用,我为什么要发布它?你为什么不试试呢?
if(fetchingRepo){
//parse one way
} else {
//parse another way
}