I have AsyncTask.class in here i parse json and return List, and in postExecute i need add this List to my Adapter and notify to change, but LogCat give Error, how i can fix this?
My Adapter have public state, why i cant add to him results?
FATAL EXCEPTION: main
java.lang.NullPointerException
at com.gazetaimage.LoadTask.onPostExecute(LoadTask.java:84)
at com.gazetaimage.LoadTask.onPostExecute(LoadTask.java:1)
at android.os.AsyncTask.finish(AsyncTask.java:631)
at android.os.AsyncTask.access$600(AsyncTask.java:177)
at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:644)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:5191)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:795)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:562)
at dalvik.system.NativeStart.main(Native Method)
LoadTask.java
public class LoadTask extends AsyncTask<Void, Void, List<String>> {
MainActivity main = new MainActivity();
private int page = 1;
public int addPage(int i){
return page = i;
}
@Override
protected List<String> doInBackground(Void... params) {
InputStream ips = null;
JSONObject jsonObj = null;
String json = "";
try {
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpResponse response = httpClient.execute(new HttpPost("http://iapp.gazeta.uz/fotolenta?page="+page));
ips = response.getEntity().getContent();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader bufff = new BufferedReader(new InputStreamReader(ips, "UTF-8"));
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = bufff.readLine()) != null){
sb.append(line + "\n");
}
ips.close();
json = sb.toString();
} catch (Exception e) {
e.printStackTrace();
}
try {
jsonObj = new JSONObject(json);
} catch (JSONException e) {
e.printStackTrace();
}
if(jsonObj != null){
JSONArray array = jsonObj.optJSONArray("img_list");
for (int i = 0; i < array.length(); i++) {
main.thumbs.add(array.optJSONObject(i).optString("thumbnail"));
}
}
else{
Log.d("Log", "Nullll");
}
return main.thumbs;
}
@Override
protected void onPostExecute(List<String> result) {
if (result != null){
main.adapter.add(result);// HERE I HAVE Error 84
}
}
}
You cannot create an instance of the activity inside the task, and expect it will be the same activity running..
Instead, You can create
interface, pass it toAsyncTask(in constructor), and then call method inonPostExecuteFor example:
Your interface:
Your Activity:
And your AsyncTask:
taken from https://stackoverflow.com/a/9963705/1434631