我将从我的 API 请求返回的 JSON 中解析的数据存储到 Firebase 数据库中。
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);
}
});
单击按钮时,它会在 APIURL 上调用一个新的 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;
}
它在另一个函数中进行解析。
我的问题是,正如您在我的 setOnClickListener 中看到的那样,我尝试在两个不同的 URL 上创建两个 JSONTask,因为第一个 URL 为我提供了用户的信息,第二个 URL (repoURL) 为我提供了用户的信息存储库。我试图获取用户的 repo 信息并将其存储到数据库中,但似乎这是一种错误的方法。
在两个不同的 URL 上调用两个单独的 AsyncTasks 的正确方法是什么?
编辑
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) {
}
});
}
使用从中解析的数据
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){
}
}
最佳答案
两个不同的 URL 的响应肯定不会相似。因此,您需要为它们使用不同的解析方法。
一种懒惰的方法是为两个不同的 url 使用两个不同的 AsyncTasks
子类。
另一种方法是在 asynctask 中存储一个标志,指示它是在处理用户还是 repo。
public class JSONTask extends AsyncTask <String , String , String> {
boolean fetchingRepo;
@Override
protected String doInBackground (String... params) {
fetchingRepo = params[0].endsWith("/repos");
//other statements
}
现在在 onPostExecute 中:
if(fetchingRepo){
//parse one way
} else {
//parse another way
}
关于android - 使用相同的 AsyncTask 子类对不同的 URL 进行 API 调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47007074/