0

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

6
  • 1
    Show String which getting from server in result Commented Jan 2, 2017 at 17:59
  • JSON String contains many items which you want to add in ArrayList? Commented Jan 2, 2017 at 18:17
  • I highly recommend you switch to using something like Retrofit. You can use a converter to automatically parse responses like this. Commented Jan 2, 2017 at 18:36
  • @orbit I don't know exactly what you mean, could you deliver an example please Commented Jan 2, 2017 at 18:41
  • @ρяσѕρєя K yes, in the end I want to show all of the columns, for the beginning to have a better idea, how everything works, I'm happy if it shows nr :-) Commented Jan 2, 2017 at 18:42

1 Answer 1

1

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;
Sign up to request clarification or add additional context in comments.

6 Comments

I changed everything in doInBackground. With this return listdata.toString() I get a string in onPostExecute. Hm so how to bind result to my listview? Its in the same activity, name of avtivity is: public class AllProductsActivity extends ListActivity, listview is established in my xml file all_products.xml <ListView android:id="@android:id/list" android:layout_width="fill_parent" android:layout_height="wrap_content"/>
@pia-sophie: NOT listdata.toString() just return listdata
@pia-sophie: to show data in ListView pass listdata to your Adapter in onPostExecute method
then android studio shows an error: incompatible types, so I should change the return type of the function ..to what type ? protected ArrayList<String> doInBackground(ArrayList<String>... params)?
@pia-sophie: dude change AsyncTask<String, String, String> to AsyncTask<String, String, ArrayList<String>> and onPostExecute( ArrayList<String> result) no need to change doInBackground(String... params)
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.