从REST URL获取JSON字符串的最简单直接方法

时间:2018-01-30 07:40:50

标签: android json

我正在尝试从网址获取JSON字符串并将其保存到我的Android应用程序中的SQLite中。

我正在尝试一些教程然后意识到建议的方法有一个void返回类型。有没有更简单直接的方法来获取JSON字符串并将其放入arraylist准备保存到SQLite中?

以下是我在一个从url获取数据的帮助程序类中遇到的问题 正如他们所说主线程OnCreate不允许像这样的后台进程。有没有办法改变AsyncTask的返回类型,还是有更简单的方法来获取带有android的JSON字符串?

public class FetchData extends AsyncTask<Void, Void, Void> {
    @Override
    protected void doInBackground(ArrayList<String>... voids) {
        try {
            URL url = new URL("http://192.168.403.211/api/wordsupdate.php");


            HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
            InputStream inputStream = httpURLConnection.getInputStream();
            BufferedReader bufferedReader = new BufferedReader (new InputStreamReader(inputStream));
            String line ="";
            while (line != null) {
                line = bufferedReader.readLine();
            }       

        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
}

6 个答案:

答案 0 :(得分:2)

使用Volley API。检查下面演示POST请求的代码。希望您能获得有用的信息。

public void getAddress(final String uid) {

    String url = "Add Url Here"; // Request a string response from the provided URL.
    StringRequest stringRequest = new StringRequest(Request.Method.POST, url,
            new Response.Listener<String>() {
                @Override
                public void onResponse(String response) {

                    JSONArray dataArray;
                    JSONObject jsonObject;

                    address_ids = new ArrayList<>();
                    address_names = new ArrayList<>();
                    address_line1 = new ArrayList<>();
                    address_line2 = new ArrayList<>();
                    address_state = new ArrayList<>();
                    address_district = new ArrayList<>();
                    address_taluka = new ArrayList<>();
                    address_pincode = new ArrayList<>();
                    address_status = new ArrayList<>();
                    address_default = new ArrayList<>();


                    try {
                        jsonObject = new JSONObject(response);
                        dataArray = jsonObject.getJSONArray(JSON_ARRAY);

                        //adding response values to respective array
                        for (int i = 0; i < dataArray.length(); i++) {
                            //Creating a json object of the current index
                            JSONObject obj;
                            try {
                                //getting json object from current index
                                obj = dataArray.getJSONObject(i);
                                address_ids.add(obj.getString(TAG_ADDRESS_ID));
                                address_names.add(obj.getString(TAG_ADDRESS_NAME));
                                address_line1.add(obj.getString(TAG_ADDRESSLINE_FIRST));
                                address_line2.add(obj.getString(TAG_ADDRESSLINE_SECOND));
                                address_state.add(obj.getString(TAG_STATE));
                                address_district.add(obj.getString(TAG_DISTRICT));
                                address_taluka.add(obj.getString(TAG_TALUKA));
                                address_pincode.add(obj.getString(TAG_PINCODE));
                                address_status.add(obj.getString(TAG_ADDRESS_STATUS));

                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        }


                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    //setting up response values to the fragment
                    //Toast.makeText(getActivity(), "Error:"+response, Toast.LENGTH_LONG).show();
                    Log.e(TAG, "onResponse: " + response);
                    address_name.setText("Name : " + address_names.get(0));
                    address.setText("Address : " + address_line1.get(0) + "," + address_line2.get(0) + "-" + address_pincode.get(0));
                    taluka.setText("Taluka : " + address_taluka.get(0));
                    district.setText("District : " + address_district.get(0));
                    state.setText("State : " + address_state.get(0));
                    mCircularProgressBar.setIndeterminate(false);
                }
            }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            Toast.makeText(getApplication(), "Taking bit longer", Toast.LENGTH_LONG).show();
        }

    }) {
        @Override
        protected Map<String, String> getParams() {
            Map<String, String> params = new HashMap<String, String>();
            params.put("mk_address_id", address_id);
            return params;
        }
    };
    queue.add(stringRequest);
}

答案 1 :(得分:2)

点击此链接from Android developer,您可以找到更多信息。

在您的代码中更改&#34;扩展&#34;来自

AsyncTask<Void, Void, Void>

AsyncTask<Void, Void, String>

和doInBackground方法

protected String doInBackground(ArrayList<String>... voids) 

您将在onPostExecute方法中获取字符串

答案 2 :(得分:1)

是的,有办法更改退货类型:看看您的AsyncTask<Void, Void, Void>:它说<Params, Progress, Result>

根据Android Developers,这意味着ArrayList<String>... voids

这意味着你的 Params也不会工作,因为您将ArrayList<String>部分设置为Void但尝试获得Void

因此,要解决您的问题,请将三个$this->db->update()更改为输入和输出所需的任何内容。

但是,要反序列化JSON,您应该使用外部库(或者使用第三方库来完成REST调用)。

答案 3 :(得分:1)

// AsyncTask有onPostExecute,它将在后台执行后调用,你将在mainthread中获得结果

class FetchData extends AsyncTask<Void, Void, String> {
    @Override
    protected String doInBackground(Void... voids) {
        try {
            URL url = new URL("http://192.168.403.211/api/wordsupdate.php");

            HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
            InputStream inputStream = httpURLConnection.getInputStream();
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
            StringBuilder builder = new StringBuilder();
            String line;
            while ((line = bufferedReader.readLine()) != null) {
                builder.append(line);
            }
            return builder.toString();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    protected void onPostExecute(String result) {
        //Your result String is here which runs on MAIN THREAD
        super.onPostExecute(result);
    }
}

答案 4 :(得分:0)

改造2 将帮助您 - 简单易用

编辑:对于异步任务,请参阅此处的最佳答案

What arguments are passed into AsyncTask<arg1, arg2, arg3>?

答案 5 :(得分:0)

在您的代码段中,您指定的AsyncTask params类型为Void。无效意味着,它没有任何返回值。根据AsyncTask语法,
您必须指定三个参数。 1- InputType- DoInBanckground 2- ProgressType - 发布进度。 3- OutputType - OnPostExecute。

异步任务使用的三种类型如下:

Params,执行时发送给任务的参数类型。 进度,后台计算期间发布的进度单元的类型。 结果,后台计算结果的类型。

在你的代码片段中,doInBackground方法和AsycTask类型不匹配。

有关详细信息:https://developer.android.com/reference/android/os/AsyncTask.html