So,
Im getting a JSON from a REST server and I want to fill a ListView with its info. What I have is:
public class MyReservations extends ListActivity {
....
class HTTPAssync implements Runnable {
public void run () {
... //make the requestions and get a valida JSONObject (that has a JSONArray)
try {
JSONObject jsonObject = new JSONObject(payload);
reservs = jsonObject.getJSONArray("reservs");
try {
listView.setAdapter(new JSONAdapter(MyReservations.this, reservs));
}
I have created a JSONAdapter as well:
class JSONAdapter extends BaseAdapter implements ListAdapter {
private final Activity activity;
private final JSONArray jsonArray;
private LayoutInflater mInflater;
public JSONAdapter(Activity activity, JSONArray jsonArray) {
assert activity != null;
assert jsonArray != null;
this.jsonArray = jsonArray;
this.activity = activity;
}
public int getCount() {
return jsonArray.length();
}
public JSONObject getItem(int position) {
return jsonArray.optJSONObject(position);
}
public long getItemId(int position) {
JSONObject jsonObject = getItem(position);
return jsonObject.optLong("id");
}
public View getView(int position, View view, ViewGroup parent) {
if (view == null)
view = activity.getLayoutInflater().inflate(R.layout.reservation, null);
JSONObject jsonObject = getItem(position);
view = mInflater.inflate(R.layout.reservation, null);
((TextView) view.findViewById(R.id.reservationCourse)).setText("MOTHAFOCKA");
return view;
}
}
But when I make new Thread(new HTTPAssync()).start(); Im getting android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.. I tried to create a method and set the adapter from it, but got the same error. How can I do it?
It’s not the problem of JSON. You must use android.os.Handler. There are two main uses for a Handler:
(1) to schedule messages and runnables to be executed as some point in the future;
(2) to enqueue an action to be performed on a different thread than your own.
Example:
And here is a call example: