1

I have a method that is supposed to get a JSON response. Here it is:

public  HttpResponse getJson() {
        HttpResponse response = null;
        try {        
                HttpClient client = new DefaultHttpClient();
                HttpGet request = new HttpGet();
                request.setURI(new URI("https://mysite.com/android/showJson.php"));
                response = client.execute(request);
            } catch (URISyntaxException e) {
                e.printStackTrace();
            } catch (ClientProtocolException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }   
            return response;
        }

The showJson.php returns this: ["item 1","item 2"]

The problem I'm facing is that I can't call getJson inside of onCreate, because It's throwing an error: android.os.NetworkOnMainThreadException

I noticed that my method should be inside of a seperate class in order to call it inside of onCreate, but I can't manage it. I'm really going to cry, I can't understand the syntax of the asyncTask! I know that I'm missing something small, but I'm not able to spot it as a beginner.

Here is the onCreate method:

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

        getJson();
        String[] myStringArray = {"a","b","c","a","b","c","a","b","c","a","b","c","a","b","c","a","b","c"};

        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, 
                android.R.layout.simple_list_item_1, myStringArray);

        ListView listView = (ListView) findViewById(R.id.topJokesList);
        listView.setAdapter(adapter);

        listView.setOnItemClickListener(new OnItemClickListener() {
            public void onItemClick(AdapterView<?> parent, View view,
                    int position, long id) {
                // When clicked, show a toast with the TextView text
                Toast.makeText(getApplicationContext(),
                ((TextView) view).getText(), Toast.LENGTH_SHORT).show();
            }
        });

    }

I'm filling an array with some test values and passing them to the listView, but now I need to fill it with the items of getJson.

chility
  • 746
  • 1
  • 9
  • 22

2 Answers2

1

There are lots of examples on how to use asynctasks, here is one:

AsyncTask Android example

basicly you should add new class that will extend AsyncTask, and add you background task ( getJson(); in your case ) to doInBackground. In Your onCreate you call execute() on your AsyncTask instance. When AsyncTask finishes it will execute onPostExecute which will execute on UI thread, this is where you can update your UI.

In onCreate you can set list adapter to your listview with empty array. Inside onPostExecute you should update your ListView with new values. Actually it is a good idea to parse your json inside doInBackground, and return fron it reference to ArrayList that will be used in onPostExecute to update ListView.

Community
  • 1
  • 1
marcinj
  • 48,511
  • 9
  • 79
  • 100
1

You need an AsyncTask, where you do your request in the doInBackground method.
When you received your response, you need to notify your main thread(ui) by using the onPostExecute method.

private class JsonTaskTask extends AsyncTask<Void, Void, Void> {
 private HttpResponse response;
 protected Long doInBackground(Void... params) {
     reponse = getJson();
     return null;
 }

 protected void onPostExecute(Void params) {
     //Show Your Listview
 }

 public  HttpResponse getJson() {
    HttpResponse response = null;
    try {        
            HttpClient client = new DefaultHttpClient();
            HttpGet request = new HttpGet();
            request.setURI(new URI("https://mysite.com/android/showJson.php"));
            response = client.execute(request);
        } catch (URISyntaxException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }   
        return response;
    }
  }

Call your AsyncTask via

new JsonTaskTask().execute(void, void, void);


To notify your UI and update your ListView you can use a listener interface. e.g. like I have shown in this answer.

Community
  • 1
  • 1
Stephan
  • 15,704
  • 7
  • 48
  • 63