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
.