-1

I am trying to get the data from URL and convert it into String Array, but when I try to show it on TextView its show nothing. The link and itemId that I use is already right.

There's no Error warning on logcat.

I can't figure it out why. Is there anyone can't help me?

Here's my json data

[{"image":"http://cdn-data.apps.com/category_item/05d92b217f916c9b9d87ab9121662d87.jpg"},
{"image":"http://cdn-data.apps.com/category_item/0424ef5a980255ff989fe5b20eaa5dcd.jpg"},
{"image":"http://cdn-data.apps.com/category_item/02b5bce4a9ca8fa3e53ceea2c7e273ff.jpg"},
{"image":"http://cdn-data.apps.com/category_item/dd15419113c091c93eafb3695eb65153.jpg"},
{"image":"http://cdn-data.apps.com/category_item/1ddfd2d7a489678e3c66e7f012ceb951.jpg"}]

Here's my Java code

    if(in.getStringExtra("TAG_IMAGE_COUNT").equals("0")) {
        ViewPager imagePager = (ViewPager) findViewById(R.id.viewPagerGallery);
        imagePager.setVisibility(View.GONE);
        CirclePageIndicator imageIndicator = (CirclePageIndicator) findViewById(R.id.indicator);
        imageIndicator.setVisibility(View.GONE);
    }
    else {
        ViewPager imagePager = (ViewPager) findViewById(R.id.viewPagerGallery);
        imagePager.setVisibility(View.VISIBLE);
        CirclePageIndicator imageIndicator = (CirclePageIndicator) findViewById(R.id.indicator);
        imageIndicator.setVisibility(View.VISIBLE);

        try {

            DefaultHttpClient defaultClient = new DefaultHttpClient();
            HttpGet httpGetRequest = new HttpGet("http://api.apps.com/category_item/get_image/" + itemId);
            HttpResponse httpResponse = defaultClient.execute(httpGetRequest);

            BufferedReader reader = new BufferedReader(new InputStreamReader(httpResponse.getEntity().getContent(),"UTF-8"));

            String json = reader.readLine();

            //JSONObject jsonObject = new JSONObject(json);
            JSONArray arr = new JSONArray(httpResponse);
            List<String> list = new ArrayList<String>();
            for(int i = 0; i < arr.length(); i++){
                list.add(arr.getJSONObject(i).getString("image"));
            }
            String[] stringArr = list.toArray(new String[list.size()]);

            TextView array = (TextView)findViewById(R.id.testarray);

            array.setText(Arrays.toString(stringArr));
            Log.d("", json);

            //Toast.makeText(getApplicationContext(), json, Toast.LENGTH_SHORT).show();

        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

I try to show it on testarray but its show nothing.

Matthew
  • 95
  • 4
  • 14

1 Answers1

0

First of all your have to parse a String not Httpresponse:

here you do:

 HttpResponse httpResponse = defaultClient.execute(httpGetRequest);
 JSONArray arr = new JSONArray(httpResponse);

Change a little like:

 HttpResponse httpResponse = defaultClient.execute(httpGetRequest);

        BufferedReader reader = new BufferedReader(new InputStreamReader(httpResponse.getEntity().getContent(),"UTF-8"));
        String returnValues = "";

        while((returnValues = reader .readLine()) != null){
          JSONArray arr = new JSONArray(returnValues);

        //Define this list globally ,so you can use it any where of this class after adding data
        List<String> list = new ArrayList<String>();

        for(int i = 0; i < arr.length(); i++){
            list.add(arr.getJSONObject(i).getString("image"));
        }
      }

And finally set the list data as you want in your textView out of the background thread. you should not use any UI thread views (e.g button, textview, edittext ..) in background thread.

EDIT:

private class GetImages extends AsyncTask<String, Integer, ArrayList<String>>{
   ArrayList<String> list = new ArrayList<String>();
    @Override
    protected ArrayList<String> doInBackground(String... params) {
        try {

        HttpClient defaultClient = new DefaultHttpClient();
        HttpGet httpGetRequest = new HttpGet("http://api.apps.com/category_item/get_image/" + itemId);
        HttpResponse httpResponse = defaultClient.execute(httpGetRequest);

        BufferedReader reader = new BufferedReader(new InputStreamReader(httpResponse.getEntity().getContent()));
        String returnValues = "";

        while((returnValues = reader .readLine()) != null){
          JSONArray arr = new JSONArray(returnValues);

        //Define this list globally ,so you can use it any where of this class after adding data           
        for(int i = 0; i < arr.length(); i++){
            list.add(arr.getJSONObject(i).getString("image"));
        }
      }
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
        return list;
  }

    @Override
    protected void onPostExecute(ArrayList<String> result) {
        //use this result and put in your textView
    }
}
Ranjit
  • 5,130
  • 3
  • 30
  • 66
  • In this example, returnValues will just be a line from the response, not the entire array. – JamesB Jul 29 '14 at 07:28
  • its ok..but as i know we have do network operation in background thread..ok let me edit the full answer for you.. – Ranjit Jul 29 '14 at 07:30
  • @RanjitPati before I call try, I check it first, if there're an images it call this function. So I think I can't use this one . Check My code, I edit it – Matthew Jul 29 '14 at 07:47
  • @Matthew do all network operations in background thread/asynctask. otherwise it will throw NetworkOnMainthreadException.. – Ranjit Jul 29 '14 at 08:22
  • @RanjitPati so I need to create a new class that only contain asynctask and then call it on other activity? Sorry if i ask to much, I am new at this – Matthew Jul 29 '14 at 08:28
  • @Matthew it depends on you. if you have a small things to do.then no need to create extra class. just create one inner class which extends AsyncTask.. Do all network operations and put the Json images strings in arraylist/string array inside doInBackground method..then return the string collection and put it in your textview inside onPostExecute method like I show in my answer. – Ranjit Jul 29 '14 at 08:33
  • I try your code but I got an error on `return list` "type missmatch : cannot convert from `List` to `ListArray` – Matthew Jul 29 '14 at 08:37
  • Ok thanks, but when I convert it into array, its still show nothing. – Matthew Jul 29 '14 at 08:55
  • in while loop put a log and see the returneddata..like `while((returnValues = reader .readLine()) != null){ Log.v("Returned Data", returnValues );` ...and see what your url returns.. – Ranjit Jul 29 '14 at 08:57
  • It doesn't show on log cat. Its like that GetImages never get called. The type FoodDetail.GetImages never use locally. – Matthew Jul 29 '14 at 09:03
  • do you have internet and Internet-Permission in your manifest ? – Ranjit Jul 29 '14 at 09:04
  • I edit my comment Before. And about the permission. Yes I put it on manifest and I connected to internet – Matthew Jul 29 '14 at 09:05
  • are you properly executing the class ...like `new GetImages().execute()` – Ranjit Jul 29 '14 at 09:05
  • @Matthew just check this url and make sure u did your asynctask and execute perfectly.. http://stackoverflow.com/questions/9671546/asynctask-android-example – Ranjit Jul 29 '14 at 09:08
  • I put it like this `new GetImages().execute(); String[] stringArr = list.toArray(new String[list.size()]); TextView array = (TextView)findViewById(R.id.testarray); array.setText(Arrays.toString(stringArr));` inside onPostExecute – Matthew Jul 29 '14 at 09:10
  • @RanjitPati thanks, Now it show the result. I put the execute on the wrong place. Thanks a lot – Matthew Jul 29 '14 at 09:13
  • @Matthew you are welcome..Its good if you read the Asynctask tutorial clearly..it will help you so much in your future.. happy programming friend.. – Ranjit Jul 29 '14 at 09:20