pia-sophie
pia-sophie

Reputation: 505

get JSONObject from httpURLConnection and parsing into ArrayList

I tried a bit around getting single datarows from an mysql Database on an extern server. Until now it worked quite fine. Now I tried getting a JSONArray from the Server to show it in an ListView. I try to explain the problems I have.

Remark: I deleted the real url, it's tested, the url and the php-script both are working correct. If I type the url in my browser, the script delivers the requested data in JSON Format.

Here parts of my code:

    /**
 * Background Async Task to Load all product by making HTTP Request
 */
class LoadAllProducts extends AsyncTask<String, String, String> {

    ProgressDialog pdLoading = new ProgressDialog(AllProductsActivity.this);
    HttpURLConnection conn;
    URL url = null;

    @Override
    protected void onPreExecute() {
        super.onPreExecute();

        //this method will be running on UI thread
        pdLoading.setMessage("\tLoading...");
        pdLoading.setCancelable(false);
        pdLoading.show();

    }

    @Override
    protected String doInBackground(String... params) {     //type must be a problem
        try {
            url = new URL("http://somewhere");

        } catch (MalformedURLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return "exception";
        }
        try {
            // Setup HttpURLConnection class to send and receive data from php and mysql
            conn = (HttpURLConnection) url.openConnection();
            conn.setReadTimeout(READ_TIMEOUT);
            conn.setConnectTimeout(CONNECTION_TIMEOUT);
            conn.setRequestMethod("POST");

            // setDoInput and setDoOutput method depict handling of both send and receive
            conn.setDoInput(true);
            conn.setDoOutput(true);

            // Post Parameter an URL anhängen
            Uri.Builder builder = new Uri.Builder()
                    .appendQueryParameter("loge", params[0]);
            String query = builder.build().getEncodedQuery();

            // Open connection for sending data
            OutputStream os = conn.getOutputStream();
            BufferedWriter writer = new BufferedWriter(
                    new OutputStreamWriter(os, "UTF-8"));
            writer.write(query);
            writer.flush();
            writer.close();
            os.close();
            conn.connect();

        } catch (IOException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
            return "exception";
        }
        try {
            int response_code = conn.getResponseCode();
            // Check if successful connection made
            if (response_code == HttpURLConnection.HTTP_OK) {
                // Read data sent from server
                InputStream input = conn.getInputStream();
                try {
                    BufferedReader reader = new BufferedReader(new InputStreamReader(input));
                    StringBuilder result = new StringBuilder();
                    String line;
                    while ((line = reader.readLine()) != null) {
                        result.append(line);
                    }
                    JSONObject jsonObject = new JSONObject(result.toString());
                    // Pass data to onPostExecute method
                    return jsonObject.toString();       //this might be a problem
                   // return (result.toString());
                } catch (IOException e) {
                    e.printStackTrace();
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                //if something went wrong, return null
                return null;
            } else {

                return ("unsuccessful");
            }

        } catch (IOException e) {
            e.printStackTrace();
            return "exception";
        } finally {
            conn.disconnect();
        }
    }

    protected void onPostExecute(String result) {

        //no idea how to get ths JSONObject in the parameterlist and convert it to ArrayList
        ArrayList<String> listdata = new ArrayList<String>();
        String jArray = (String) result;
        if (jArray != null) {
            for (int i=0;i<jArray.length();i++){
                listdata.add(jArray(i));
            }
        }

First problem which type would be the choice for doInBackground function, also my return should be incorrect this way? Second one, how to deliver the jsonObject to my function onPostExecute? which type ust be used in this position? And last one, how can I get the content of the jsonObject variable to my ArrayList?

Besides: Yes, I read many other post and some tutorials, but I couldn't transfer the information I got to my example.

EDIT1:part of string, which comes from the server:

[{"nr":"317","datum":"2016-02-09","zeit":"19:30:00","thema":"","kopfnr":"2","typ":"2"},{"nr":"318","datum":"2016-02-23","zeit":"20:00:00","thema":"Wandern","kopfnr":"2","typ":"6"},{"nr":"319","datum":"2016-03-01","zeit":"18:45:00","thema":"Instruktion","kopfnr":"2","typ":"7"},{"nr":"320","datum":"2016-03-01","zeit":"20:00:00","thema":"Eine Schwester stellt sich vor","kopfnr":"2","typ":"7"},{"nr":"321","datum":"2016-03-08","zeit":"19:30:00","thema":"Der Spiegel","kopfnr":"2","typ":"5"},{"nr":"322","datum":"2016-03-22","zeit":"20:00:00","thema":null,"kopfnr":"2","typ":"6"}]

EDIT2: I followed the explanation the errors vanished and ! I understood how it works. Thx I have just one problem left, how to get the arraylist from protected void onPostExecute( ArrayList<String> result) My former call of the asyncTask function was: new LoadAllProducts().execute(loge); but I probably can't onPostExecute change in an function with a returnvalue because it is called automatically during asyncTask process, right? After that everything is finished I promise

Upvotes: 0

Views: 1496

Answers (1)

ρяσѕρєя K
ρяσѕρєя K

Reputation: 132992

First problem which type would be the choice for doInBackground function

JSON String as in post is JSONArray of JSONObject's instead of JSONObject. create JSONArray from result in doInBackground :

JSONArray jsonArray = new JSONArray(result.toString());

how to deliver the jsonObject to my function onPostExecute?

Instead of JSONObject return ArrayList of items.

how can I get the content of the jsonObject variable to my ArrayList?

Parse jsonArray to get all JSONObject's from it then get required value from each JSONObject and add it to listdata

ArrayList<String> listdata = new ArrayList<String>();
for(int n = 0; n < jsonArray.length(); n++)
{
    JSONObject object = jsonArray.getJSONObject(n);
    listdata.add(object.optString("nr")); 
}

return listdata;

Upvotes: 1

Related Questions