当前位置: 动力学知识库 > 问答 > 编程问答 >

android - trying to use AsyncTask to avoid NetworkOnSameThread errors

问题描述:

I am trying to implement an asynctask to run my network related task. but it doesnt seem to work, i keep getting nullpointerexception i am using lazy list.

public class Homepage extends ActionBarActivity{

ListView list;

LazyAdapter adapter;

private static String url = "http://192.168.1.6/webservice/events.php";

static final String TAG_IMG = "event_img";

static final String TAG_SPONSER= "sponser";

static final String TAG_TITLE= "title";

static final String TAG_LOCATION="event_location";

static final String TAG_TIME="event_time";

static final String TAG_ENDTIME="event_endtime";

static final String TAG_WHOINVITED="event_whoinvited";

static final String TAG_MESSAGE="message";

static final String TAG_DRESSCODE="event_dresscode";

//private List<String> _list = null;

//private String[] mStrings = null;

ViewFlipper flippy;

ArrayList<HashMap<String, String>> eventList = new ArrayList<HashMap<String, String>>();

@Override

public void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.homepage);

//StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();

//StrictMode.setThreadPolicy(policy);

jsonThread jsonresult = new jsonThread();

jsonresult.execute();

adapter=new LazyAdapter(this, eventList);

Button b=(Button)findViewById(R.id.button1);

b.setOnClickListener(listener);

}//end of onCreate\\\

private class jsonThread extends AsyncTask<String, String, JSONArray>{

@Override

protected JSONArray doInBackground(String... params) {

// TODO Auto-generated method stub

ServiceHandler sh = new ServiceHandler();

String jsonStr = sh.makeServiceCall(url, ServiceHandler.GET);

JSONArray jArray = null;

JSONObject json;

//_list = new ArrayList<String>();

try {

json = new JSONObject(jsonStr);

jArray = json.getJSONArray("posts");

Log.d("jarray", "jarray post "+jArray);

} catch (JSONException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

return jArray;

}

@Override

protected void onPreExecute() {

// TODO Auto-generated method stub

super.onPreExecute();

}

@Override

protected void onPostExecute(JSONArray result) {

// TODO Auto-generated method stub

super.onPostExecute(result);

for(int u=0;u<result.length();u++){

HashMap<String, String> map = new HashMap<String, String>();

JSONObject json_data;

try {

json_data = result.getJSONObject(u);

String myevent_img = json_data.getString(TAG_IMG);

String sponser = json_data.getString(TAG_SPONSER);

String title = json_data.getString(TAG_TITLE);

String location = json_data.getString(TAG_LOCATION);

String time = json_data.getString(TAG_TIME);

String endtime = json_data.getString(TAG_ENDTIME);

String message = json_data.getString(TAG_MESSAGE);

String whoinvited = json_data.getString(TAG_WHOINVITED);

String dresscode = json_data.getString(TAG_DRESSCODE);

//_list.add(myevent_img);

map.put(TAG_SPONSER, sponser);

map.put(TAG_TITLE, title);

map.put(TAG_LOCATION, location);

map.put(TAG_TIME, time);

map.put(TAG_ENDTIME, endtime);

map.put(TAG_MESSAGE, message);

map.put(TAG_WHOINVITED, whoinvited);

map.put(TAG_DRESSCODE, dresscode);

map.put(TAG_IMG, myevent_img);

Log.d("jobj ", "event_img"+myevent_img);

Log.d("hashmap ", "sponser "+map.get("sponser").toString());

// need to put this to transfer the list to mstrings.

//mStrings=new String[_list.size()];

//mStrings = _list.toArray(mStrings);

eventList.add(map);

} catch (JSONException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

}

list=(ListView)findViewById(R.id.list);

list.setAdapter(adapter);

}

}

}

The code works just fine if i just put everything in onCreate and add

StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();

StrictMode.setThreadPolicy(policy);

//// edited

public class Homepage extends ActionBarActivity{

ListView list;

LazyAdapter adapter;

private static String url = "http://192.168.1.6/webservice/events.php";

static final String TAG_IMG = "event_img";

static final String TAG_SPONSER= "sponser";

static final String TAG_TITLE= "title";

static final String TAG_LOCATION="event_location";

static final String TAG_TIME="event_time";

static final String TAG_ENDTIME="event_endtime";

static final String TAG_WHOINVITED="event_whoinvited";

static final String TAG_MESSAGE="message";

static final String TAG_DRESSCODE="event_dresscode";

//private List<String> _list = null;

//private String[] mStrings = null;

ViewFlipper flippy;

ArrayList<HashMap<String, String>> eventList = new ArrayList<HashMap<String, String>>();

@Override

public void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.homepage);

jsonThread jsonresult = new jsonThread();

jsonresult.execute();

Button b=(Button)findViewById(R.id.button1);

b.setOnClickListener(listener);

}//end of onCreate\\\

private class jsonThread extends AsyncTask<String, String, ArrayList<HashMap<String, String>>>{

@Override

protected ArrayList<HashMap<String,String>> doInBackground(String... params) {

// TODO Auto-generated method stub

ServiceHandler sh = new ServiceHandler();

String jsonStr = sh.makeServiceCall(url, ServiceHandler.GET);

JSONArray jArray = null;

JSONObject json;

//_list = new ArrayList<String>();

try {

json = new JSONObject(jsonStr);

jArray = json.getJSONArray("posts");

Log.d("jarray", "jarray post "+jArray);

} catch (JSONException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

for(int u=0;u<jArray.length();u++){

HashMap<String, String> map = new HashMap<String, String>();

JSONObject json_data;

try {

json_data = jArray.getJSONObject(u);

String myevent_img = json_data.getString(TAG_IMG);

String sponser = json_data.getString(TAG_SPONSER);

String title = json_data.getString(TAG_TITLE);

String location = json_data.getString(TAG_LOCATION);

String time = json_data.getString(TAG_TIME);

String endtime = json_data.getString(TAG_ENDTIME);

String message = json_data.getString(TAG_MESSAGE);

String whoinvited = json_data.getString(TAG_WHOINVITED);

String dresscode = json_data.getString(TAG_DRESSCODE);

//_list.add(myevent_img);

map.put(TAG_SPONSER, sponser);

map.put(TAG_TITLE, title);

map.put(TAG_LOCATION, location);

map.put(TAG_TIME, time);

map.put(TAG_ENDTIME, endtime);

map.put(TAG_MESSAGE, message);

map.put(TAG_WHOINVITED, whoinvited);

map.put(TAG_DRESSCODE, dresscode);

map.put(TAG_IMG, myevent_img);

Log.d("jobj ", "event_img"+myevent_img);

Log.d("hashmap ", "sponser "+map.get("sponser").toString());

// need to put this to transfer the list to mstrings.

//mStrings=new String[_list.size()];

//mStrings = _list.toArray(mStrings);

eventList.add(map);

} catch (JSONException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

}

return eventList;

}

@Override

protected void onPreExecute() {

// TODO Auto-generated method stub

super.onPreExecute();

}

@Override

protected void onPostExecute(ArrayList<HashMap<String,String>> result) {

// TODO Auto-generated method stub

super.onPostExecute(result);

list=(ListView)findViewById(R.id.list);

adapter=new LazyAdapter(Homepage.this, eventList);

list.setAdapter(adapter);

}

}

}

/////////LOGCAT\\\\

04-05 22:24:34.204: W/dalvikvm(5680): threadid=1: thread exiting with uncaught exception (group=0x41465700)

04-05 22:24:34.524: E/AndroidRuntime(5680): FATAL EXCEPTION: main

04-05 22:24:34.524: E/AndroidRuntime(5680): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.wordpress.yourhappening.happening/com.wordpress.yourhappening.happening.Homepage}: java.lang.NullPointerException

04-05 22:24:34.524: E/AndroidRuntime(5680): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2211)

04-05 22:24:34.524: E/AndroidRuntime(5680): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2261)

04-05 22:24:34.524: E/AndroidRuntime(5680): at android.app.ActivityThread.access$600(ActivityThread.java:141)

04-05 22:24:34.524: E/AndroidRuntime(5680): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1256)

04-05 22:24:34.524: E/AndroidRuntime(5680): at android.os.Handler.dispatchMessage(Handler.java:99)

04-05 22:24:34.524: E/AndroidRuntime(5680): at android.os.Looper.loop(Looper.java:137)

04-05 22:24:34.524: E/AndroidRuntime(5680): at android.app.ActivityThread.main(ActivityThread.java:5103)

04-05 22:24:34.524: E/AndroidRuntime(5680): at java.lang.reflect.Method.invokeNative(Native Method)

04-05 22:24:34.524: E/AndroidRuntime(5680): at java.lang.reflect.Method.invoke(Method.java:525)

04-05 22:24:34.524: E/AndroidRuntime(5680): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)

04-05 22:24:34.524: E/AndroidRuntime(5680): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)

04-05 22:24:34.524: E/AndroidRuntime(5680): at dalvik.system.NativeStart.main(Native Method)

04-05 22:24:34.524: E/AndroidRuntime(5680): Caused by: java.lang.NullPointerException

04-05 22:24:34.524: E/AndroidRuntime(5680): at com.wordpress.yourhappening.happening.Homepage.onCreate(Homepage.java:94)

04-05 22:24:34.524: E/AndroidRuntime(5680): at android.app.Activity.performCreate(Activity.java:5133)

04-05 22:24:34.524: E/AndroidRuntime(5680): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)

04-05 22:24:34.524: E/AndroidRuntime(5680): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2175)

04-05 22:24:34.524: E/AndroidRuntime(5680): ... 11 more

网友答案:

adapter is null when you try to set it to your ListView in onPostExecute().

Move

adapter=new LazyAdapter(Homepage.this, eventList);

to onPostExecute() before

list.setAdapter(adapter);

Also, your for loop there should probably be in doInBackground()

And don't use strict mode as you have pointed out that works. You can see why in the docs and tons of posts about it on SO.

Edit after seeing logcat and comments

Move

list=(ListView)findViewById(R.id.list);

from onPostExecute() to onCreate() before setting the listener. That's causing your NPE.

分享给朋友:
您可能感兴趣的文章:
随机阅读: