1

Okay so here's my problem. I am trying to create an expandable list view by fetching data from server. But my app is not responding.

Here's my code MainActivity.java

public class MainActivity extends AppCompatActivity {
    HashMap<String, List<String>> Movies_category;
    List<String> Movies_list;
    ExpandableListView Exp_list;
    MoviesAdapter adapter;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Exp_list = (ExpandableListView) findViewById(R.id.exp_list);
        Movies_category = DataProvider.getInfo();
        Movies_list = new ArrayList<String>(Movies_category.keySet());
        adapter = new MoviesAdapter(this, Movies_category, Movies_list);
        Exp_list.setAdapter(adapter);

    }

}

Here's code for DataProvider.java

public class DataProvider {
    private static HashMap<String,List<String>> MoviesDetails;

    public static HashMap<String, List<String>> getInfo(){
        String[] SecondArray = {"One","Two","Three"};
        String[] Category = {"Action_Movies","Romantic_Movies","Horror_Movies"};
        new JSONTask().execute("http://pruthvi.co/tests/ems/machine-query.php");
        JSONTask json = new JSONTask();
        try {
            //json.get();
            MoviesDetails =  json.get();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
        return MoviesDetails;
    }


    public static class JSONTask extends AsyncTask<String,String,HashMap<String,List<String>>> {


        @Override
        protected HashMap<String,List<String>> doInBackground(String... params) {
            HttpURLConnection connection = null;
            BufferedReader reader = null;

            try {
                URL url = new URL(params[0]);
                connection = (HttpURLConnection)url.openConnection();
                connection.connect();
//                    connecting to the url

                //Reading the data in bytes stream
                InputStream stream = connection.getInputStream();
                reader = new BufferedReader(new InputStreamReader(stream));
//Reading the data by creating a buffer
                StringBuffer buffer = new StringBuffer();
                String line="";
                while((line = reader.readLine())!= null){
                    buffer.append(line);
                }

                String finalJson = buffer.toString();
                JSONObject parentObject = new JSONObject(finalJson);

                List<String> list = new ArrayList<String>();
                JSONArray array = parentObject.getJSONArray("machine-array");
                for(int i = 0 ; i < array.length() ; i++){
                    list.add(array.getJSONObject(i).getString("name")+"\n");
                }

                HashMap<String,List<String>> map = new HashMap<String,List<String>>();
                for(int ij=0; ij<list.size();ij++){
                    map.put(list.get(ij),list);
                }


                return map;
                //return list.toArray(new String[list.size()]);
//                    setting text view from the url
            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } catch (JSONException e) {
                e.printStackTrace();
            } finally{
                if(connection !=null) {
                    connection.disconnect();
                }

                try {
                    if (reader != null)
                    {
                        reader.close();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            return null;
        }

        @Override
        protected void onPostExecute(HashMap<String,List<String>> result) {
            super.onPostExecute(result);
            HashMap<String, List<String>> MoviesDetails = new HashMap<String, List<String>>();
            String[] SecondArray = {"One","Two","Three","four","five","six"};
            String[] resultArray = (String[]) result.values().toArray();

            for(int j=0; j<resultArray.length;j++) {
                MoviesDetails.put(resultArray[j], new ArrayList<String>());
            }

            for(int k=0;k<resultArray.length;k++)
            {
                for (int i=0;i<SecondArray.length; i++) {
                    MoviesDetails.get(resultArray[k]).add(SecondArray[i]);
                }
            }
        }
    }

}

Could someone help me out where I am going wrong? In onCreate Method, I am fetching expandableListView and thereafter I am calling DataProvider class for method getInfo();

I suspect Dataprovider class is taking a long time for execution. Also, Someone could help me how I can debug the execution time for the same.

Thanks in Advance

Vadim
  • 1,916
  • 2
  • 19
  • 39
Ishq Mehta
  • 387
  • 1
  • 5
  • 13
  • Do you know what line of code your app is hanging? There are several for and while loops in your code, that is a prime location to investigate when your code hangs. Try putting a System.out.println("Hi"); at each step in the loops to see where a loop could be out of control. Identify each loop with a different string. – bakoyaro Jan 20 '16 at 18:24
  • @bakoyaro Okay! So I tried doing what you suggested. And all works fine until the doInBackground method. System prints the returned hashMap value. But when I try to catch and print result in onPostExecute. Nothing prints. Could you help me with this? – Ishq Mehta Jan 20 '16 at 19:19
  • Try putting a System.out.println() on the first line of the onPostExecute method. If the message isn't printed then the system is not calling that method. Once you are sure you are calling the method you can put a System.out.println() on each line to see where the code is executing. – bakoyaro Jan 20 '16 at 20:03

2 Answers2

1

If your app is not responding, it means, something is being executed in UI thread.

You can find out the piece of code, which is now being executed, if you do the following steps (assuming, you are using Android Studio, we start from top-left menu):

Run ->

Attach debugger to android process ->

choose process on corresponding device, press ok ->

press "Debug" on the bottom bar (if it didnt show up by itself) ->

pause program (from the left) ->

in "frames" find the one which contains "main" in its name (it is your main thread, which should be "RUNNING") ->

choose that one, so you will see its stack trace.

On top of your stack you will see the place of code, where your program is held now.

When you find out, where your program is held, I hope, you will be able to solve your problem.

Eugene Chumak
  • 3,272
  • 7
  • 34
  • 52
0
JSONTask json = new JSONTask();
try {
    //json.get();
    MoviesDetails =  json.get();

You just made a AsyncTask synchronous. Do not do that.

Just have new JSONTask().execute("http://pruthvi.co/tests/ems/machine-query.php"); and leave it, and handle the response correctly from onPostExecute.

For example, How to get the result of OnPostExecute() to main activity because AsyncTask is a separate class?

Or use Volley, or even Retrofit since you are dealing with JSON.

OneCricketeer
  • 179,855
  • 19
  • 132
  • 245