android - 使用相同的 AsyncTask 子类对不同的 URL 进行 API 调用

标签 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();
            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/

相关文章:

android - 无法在 SQLite 中插入,错误代码 :19

javascript - 在 D3 Javascript 中显示 .json map

android - 无法立即读取下载的文本文件

android - 使用asynctask调用android中的函数

安卓+mysql : Connection class returns a Null object

java - Android 2.1 :Caused by: java. lang.ClassNotFoundException: fragment

javascript - 如何使用 NodeJs 的 JSONAPI-Serializer 模块反序列化数据

java - 为 AsyncTask 实现一个常规的 JSON 解析器函数

java - PagerActivity 中 ImageView 中的图像大小

javascript - 如何通过为每个对象指定过滤器类型来过滤 AngularJS 中的对象?