JSONParser when retrieving from MySQL error.

  • Replies:0
  • OpenNot stickiedUnanswered
  • Forum posts: 1

Feb 1, 2017 11:07:44 PM via Website

I have a php file with results:

{"groups":[{"id_group":"1"},{"nazwa":"Informatyka 2013-2017"},{"id_group":"2"},{"nazwa":"MIBM 2016-2017"},{"id_group":"3"},{"nazwa":"Informatyka 2015-2019"},{"id_group":"5"},{"nazwa":"UwB Fizyka 2012-2015"}]}

It should desplay all rows from table with clickable option in each row.

JSONParser.java

package com.brzozowski.marcin.inzynierka.activities;

import android.util.Log;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.List;

public class JSONParser {

    static InputStream is = null;
    static JSONObject jObj = null;
    static String json = "";

    // constructor
    public JSONParser() {

    }

    // function get json from url
    // by making HTTP POST or GET mehtod
    public JSONObject makeHttpRequest(String url, String method,
                                      List<NameValuePair> params) {

        // Making HTTP request
        try {

            // check for request method
            if(method == "POST"){
                // request method is POST
                // defaultHttpClient
                DefaultHttpClient httpClient = new DefaultHttpClient();
                HttpPost httpPost = new HttpPost(url);
                httpPost.setEntity(new UrlEncodedFormEntity(params));

                HttpResponse httpResponse = httpClient.execute(httpPost);
                HttpEntity httpEntity = httpResponse.getEntity();
                is = httpEntity.getContent();

            }else if(method == "GET"){
                // request method is GET
                DefaultHttpClient httpClient = new DefaultHttpClient();
                String paramString = URLEncodedUtils.format(params, "utf-8");
                url += "?" + paramString;
                HttpGet httpGet = new HttpGet(url);

                HttpResponse httpResponse = httpClient.execute(httpGet);
                HttpEntity httpEntity = httpResponse.getEntity();
                is = httpEntity.getContent();
            }

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    is, "iso-8859-1"), 8);
            StringBuilder sb = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
            is.close();
            json = sb.toString();
        } catch (Exception e) {
            Log.e("Buffer Error", "Error converting result " + e.toString());
        }

        // try parse the string to a JSON object
        try {
            jObj = new JSONObject(json);
        } catch (JSONException e) {
            Log.e("JSON Parser", "Error parsing data " + e.toString());
        }

        // return JSON String
        return jObj;

    }
}

ChooseGroupActivity.java

package com.brzozowski.marcin.inzynierka.activities;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;

import com.brzozowski.marcin.inzynierka.R;
import com.brzozowski.marcin.inzynierka.models.Group;

import org.apache.http.NameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

public class ChooseGroupActivity extends Activity {
    private ProgressDialog pDialog;
    JSONParser jParser = new JSONParser();
    private static String url_all_products = "/getAllGroups.php";
    private static final String TAG_SUCCESS = "success";
    private static final String TAG_PRODUCTS = "groups";
    private static final String TAG_ID_GROUP = "id_group";
    private static final String TAG_NAME = "name";
    JSONArray products = null;
    private ListView listView;
    private LinearLayout llContainer;
    private ChooseGroupAdapter adapter;
    private EditText inputSearch;
    private ArrayList<Group> groupList;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_choosegroup);

        listView = (ListView) findViewById(R.id.listView);
        inputSearch = (EditText) findViewById(R.id.inputSearch);
        groupList = new ArrayList<Group>();

        new LoadAllProducts().execute();

        //
        adapter = new ChooseGroupAdapter(ChooseGroupActivity.this, groupList);
        listView.setAdapter(adapter);
        //

        // Add Text Change Listener to EditText
        inputSearch.addTextChangedListener(new TextWatcher() {

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                adapter.getFilter().filter(s.toString());
            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count,int after) {
            }

            @Override
            public void afterTextChanged(Editable s) {
            }
        });
    }

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

        adapter = new ChooseGroupAdapter(ChooseGroupActivity.this, groupList);
        listView.setAdapter(adapter);
    }

//    @Override
//    protected void onPause() {
//        if(isFinishing()){
//            if (pDialog!= null) {
//                pDialog.dismiss();
//                pDialog= null;
//            }
//        }
//    }

    class LoadAllProducts extends AsyncTask<String, String, String> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pDialog = new ProgressDialog(ChooseGroupActivity.this);
            pDialog.setMessage("Loading groups. Please wait...");
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(false);
            pDialog.show();
        }

        protected String doInBackground(String... args) {
            // Building Parameters
            List<NameValuePair> params = new ArrayList<NameValuePair>();
            // getting JSON string from URL
            JSONObject json = jParser.makeHttpRequest(url_all_products, "GET", params);

            // Check your log cat for JSON reponse
            Log.d("All Products: ", json.toString());

            try {
                // Checking for SUCCESS TAG
//                int success = json.getInt(TAG_SUCCESS);

//                if (success == 1) {
                    // products found
                    // Getting Array of Products
                    products = json.getJSONArray(TAG_PRODUCTS);

                    // looping through All Products
                    for (int i = 0; i < products.length(); i++) {
                        JSONObject c = products.getJSONObject(i);

                        // Storing each json item in variable
                        String id = c.getString(TAG_ID_GROUP);
                        String name = c.getString(TAG_NAME);

                        Group group = new Group(name);

                        groupList.add(group);
                    }
                ///} else {
                    // no products found
                    // Launch Add New product Activity
                    Intent i = new Intent(getApplicationContext(),
                            NewGroupActivity.class);
                    // Closing all previous activities
                    i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                    startActivity(i);
               // }
            } catch (JSONException e) {
                e.printStackTrace();
            }

            return null;
        }

        /**
         * After completing background task Dismiss the progress dialog
         * **/
        protected void onPostExecute(String file_url) {
            // dismiss the dialog after getting all products
            pDialog.dismiss();
            // updating UI from Background Thread
            runOnUiThread(new Runnable() {
                public void run() {
                    /**
                     * Updating parsed JSON data into ListView
                     * */
                    ArrayAdapter<Group> adapter = new ArrayAdapter<Group> (
                            ChooseGroupActivity.this,
                    R.layout.row, groupList);
                }
            });

        }
    }
}

The error:

 E/WindowManager: android.view.WindowLeaked: Activity com.brzozowski.marcin.inzynierka.activities.ChooseGroupActivity has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView{2a82618a V.E..... R......D 0,0-1026,348} that was originally added here
                         at android.view.ViewRootImpl.<init>(ViewRootImpl.java:363)
                         at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:271)
                         at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:85)
                         at android.app.Dialog.show(Dialog.java:298)
                         at com.brzozowski.marcin.inzynierka.activities.ChooseGroupActivity$LoadAllProducts.onPreExecute(ChooseGroupActivity.java:103)
                         at android.os.AsyncTask.executeOnExecutor(AsyncTask.java:591)
                         at android.os.AsyncTask.execute(AsyncTask.java:539)
                         at com.brzozowski.marcin.inzynierka.activities.ChooseGroupActivity.onCreate(ChooseGroupActivity.java:51)
                         at android.app.Activity.performCreate(Activity.java:5990)
                         at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1106)
                         at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2278)
                         at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2387)
                         at android.app.ActivityThread.access$800(ActivityThread.java:151)
                         at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303)
                         at android.os.Handler.dispatchMessage(Handler.java:102)
                         at android.os.Looper.loop(Looper.java:135)
                         at android.app.ActivityThread.main(ActivityThread.java:5254)
                         at java.lang.reflect.Method.invoke(Native Method)
                         at java.lang.reflect.Method.invoke(Method.java:372)
                         at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
                         at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)

I have no idea how to solve this problem.