Android paging mechanism handle - java

How do I handle paging mechanism?
I have created a code to create paging of data. But when I specify a limit that has expired, the application will be damaged and force closed.
My paging class :
public class SetPaging {
public static final String[] PAGING = new String[] {
"0,5","5,5","10,5","15,5","20,5"
};
}
My listener :
pullRefresh = ((PullAndLoadListView) listView);
pullRefresh.setOnLoadMoreListener(new OnLoadMoreListener() {
public void onLoadMore() {
new LoadMoreData().execute();
}
});
My async code :
private class LoadMoreData extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
page = page + 1;
if (page > SetPaging.PAGING.length) {
page = 0;
}
}
protected Void doInBackground(Void... params) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
}
try {
ArrayList<UtamaBean> NextUtama = new ArrayList<UtamaBean>();
NextUtama = PushServer.getNextUtama(SetPaging.PAGING[page]);
if (page > 0) {
utamabean.addAll(NextUtama);
} else {
utamabean = PushServer.getNextUtama(SetPaging.PAGING[page]);
}
} catch (Exception e) {
netError.setVisibility(View.VISIBLE);
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
listView.setVisibility(View.VISIBLE);
adapter.setItem(utamabean);
pullRefresh.onLoadMoreComplete();
}
#Override
protected void onCancelled() {
pullRefresh.onLoadMoreComplete();
}
}
All went smoothly. Only when the sixth paging applications (outside the rules "20,5") then the application will be immediately force closed.
How best to conduct the sixth restrictions if paging is done, the application will not be entered into async function and request the data?
Thanks
===UPDATE===
My LogCat :
11-24 19:59:40.587: E/AndroidRuntime(16223): FATAL EXCEPTION: AsyncTask #1
11-24 19:59:40.587: E/AndroidRuntime(16223): java.lang.RuntimeException: An error occured while executing doInBackground()
11-24 19:59:40.587: E/AndroidRuntime(16223): at android.os.AsyncTask$3.done(AsyncTask.java:299)
11-24 19:59:40.587: E/AndroidRuntime(16223): at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:352)
11-24 19:59:40.587: E/AndroidRuntime(16223): at java.util.concurrent.FutureTask.setException(FutureTask.java:219)
11-24 19:59:40.587: E/AndroidRuntime(16223): at java.util.concurrent.FutureTask.run(FutureTask.java:239)
11-24 19:59:40.587: E/AndroidRuntime(16223): at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
11-24 19:59:40.587: E/AndroidRuntime(16223): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
11-24 19:59:40.587: E/AndroidRuntime(16223): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
11-24 19:59:40.587: E/AndroidRuntime(16223): at java.lang.Thread.run(Thread.java:841)
11-24 19:59:40.587: E/AndroidRuntime(16223): Caused by: java.lang.ArrayIndexOutOfBoundsException: length=5; index=5
11-24 19:59:40.587: E/AndroidRuntime(16223): at com.joris.babe.F_Test$LoadMoreData.doInBackground(F_Test.java:156)
11-24 19:59:40.587: E/AndroidRuntime(16223): at com.joris.babe.F_Test$LoadMoreData.doInBackground(F_Test.java:1)
11-24 19:59:40.587: E/AndroidRuntime(16223): at android.os.AsyncTask$2.call(AsyncTask.java:287)
11-24 19:59:40.587: E/AndroidRuntime(16223): at java.util.concurrent.FutureTask.run(FutureTask.java:234)
11-24 19:59:40.587: E/AndroidRuntime(16223): ... 4 more

You have this
netError.setVisibility(View.VISIBLE);
Updating ui from doInbackground.doInbackground is invoked on the background thread.
Hence the exception. Update ui on the ui thread. Return a value in doInbackground. Based on the value returned set the visibility accrodingly in onPostExecute.

Related

AsyncTask with progressbar

The following code is a part of my app and it isn't working and I don't know why.
I don't know at which place I can put the "new MormaKaugummi().execute();". At any place the App crashed and gave me the error "Unfortunately, Criminal Life has stopped."
The "counter textview" is in an another activity in the same app.
(The name of the App is Criminal Life).
I need a unique solution because I'm new in Android programming.
public class Morma extends AppCompatActivity {
class MormaKaugummi extends AsyncTask<String, String, String> {
private int count = 0;
private void count() {
count++;
}
private void update() {
TextView counter = (TextView) findViewById(R.id.counter);
String Kcounter = Integer.toString(count);
counter.setText(Kcounter);
}
#Override
protected String doInBackground(String... params) {
count();
update();
return null;
}
}
private ProgressBar progressBarKaugummi;
private int progressStatusKaugummi = 0;
private Handler handlerKaugummi = new Handler();
#Override
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_morma);
Button buttonMormaKaugummiKlauen = (Button) findViewById(R.id.buttonMormaKaugummiKlauen);
buttonMormaKaugummiKlauen.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
progressBarKaugummi = (ProgressBar) findViewById(R.id.progressBarMormaKaugummi);
new Thread(new Runnable() {
public void run() {
while (progressStatusKaugummi < 100) {
progressStatusKaugummi += 1;
handlerKaugummi.post(new Runnable() {
public void run() {
progressBarKaugummi.setProgress(progressStatusKaugummi);
}
});
try {
Thread.sleep(4000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}).start();
if (progressStatusKaugummi == 100) {
progressBarKaugummi.setProgress(0);
recreate();
new MormaKaugummi().execute();
}
}
});
That's the logcat
11-07 13:48:34.964 622-1376/peppermine_studios.criminallife E/AndroidRuntime: FATAL EXCEPTION: AsyncTask #1
11-07 13:48:34.964 622-1376/peppermine_studios.criminallife E/AndroidRuntime: java.lang.RuntimeException: An error occured while executing doInBackground()
11-07 13:48:34.964 622-1376/peppermine_studios.criminallife E/AndroidRuntime: at android.os.AsyncTask$3.done(AsyncTask.java:299)
11-07 13:48:34.964 622-1376/peppermine_studios.criminallife E/AndroidRuntime: at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:273)
11-07 13:48:34.964 622-1376/peppermine_studios.criminallife E/AndroidRuntime: at java.util.concurrent.FutureTask.setException(FutureTask.java:124)
11-07 13:48:34.964 622-1376/peppermine_studios.criminallife E/AndroidRuntime: at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:307)
11-07 13:48:34.964 622-1376/peppermine_studios.criminallife E/AndroidRuntime: at java.util.concurrent.FutureTask.run(FutureTask.java:137)
11-07 13:48:34.964 622-1376/peppermine_studios.criminallife E/AndroidRuntime: at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
11-07 13:48:34.964 622-1376/peppermine_studios.criminallife E/AndroidRuntime: at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
11-07 13:48:34.964 622-1376/peppermine_studios.criminallife E/AndroidRuntime: at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
11-07 13:48:34.964 622-1376/peppermine_studios.criminallife E/AndroidRuntime: at java.lang.Thread.run(Thread.java:856)
11-07 13:48:34.964 622-1376/peppermine_studios.criminallife E/AndroidRuntime: Caused by: java.lang.NullPointerException
11-07 13:48:34.964 622-1376/peppermine_studios.criminallife E/AndroidRuntime: at peppermine_studios.criminallife.Morma$MormaKaugummi.update(Morma.java:26)
11-07 13:48:34.964 622-1376/peppermine_studios.criminallife E/AndroidRuntime: at peppermine_studios.criminallife.Morma$MormaKaugummi.doInBackground(Morma.java:32)
11-07 13:48:34.964 622-1376/peppermine_studios.criminallife E/AndroidRuntime: at peppermine_studios.criminallife.Morma$MormaKaugummi.doInBackground(Morma.java:15)
11-07 13:48:34.964 622-1376/peppermine_studios.criminallife E/AndroidRuntime: at android.os.AsyncTask$2.call(AsyncTask.java:287)
11-07 13:48:34.964 622-1376/peppermine_studios.criminallife E/AndroidRuntime: at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
11-07 13:48:34.964 622-1376/peppermine_studios.criminallife E/AndroidRuntime: at java.util.concurrent.FutureTask.run(FutureTask.java:137)
11-07 13:48:34.964 622-1376/peppermine_studios.criminallife E/AndroidRuntime: at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
11-07 13:48:34.964 622-1376/peppermine_studios.criminallife E/AndroidRuntime: at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
11-07 13:48:34.964 622-1376/peppermine_studios.criminallife E/AndroidRuntime: at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
11-07 13:48:34.964 622-1376/peppermine_studios.criminallife E/AndroidRuntime: at java.lang.Thread.run(Thread.java:856)
11-07 13:48:35.514 622-622/peppermine_studios.criminallife W/EGL_emulation: eglSurfaceAttrib not implemented
11-07 13:48:35.674 622-622/peppermine_studios.criminallife W/EGL_emulation: eglSurfaceAttrib not implemented
11-07 13:48:37.364 622-1376/? I/Process: Sending signal. PID: 622 SIG: 9
You are trying to do findviewbyId and update the text view in your doInBackground method via the update function, which you cannot do.
As for the crash its happening because of a null pointer exception as you can read for yourself in the logcat's caused by clause it tells you the exact line number where the null pointer exception is thrown
Caused by: java.lang.NullPointerException
11-07 13:48:34.964 622-1376/peppermine_studios.criminallife E/AndroidRuntime: at peppermine_studios.criminallife.Morma$MormaKaugummi.update(Morma.java:26)
as you can see here, its caused by null pointer at line 26 in Morma.java and I am guessing that your TextView counter is null since you are trying to initialize a variable to reference a UI element from a non-UI thread, the counter variable will be initialized as null obviously.
Now for the solution:
What you need to do is put the update function in the onPostExecute method for the async task class. Reason: onPostExceute runs on whatever thread the asyntcTask.execute method was called from so you are supposed to do your UI update in the onPostExecute method
#Override
protected String doInBackground(String... params) {
count();
return null;
}
#Override
protect void onPostExecute(String result) {
update();
}
Also since you are returning null from doInBackground anyway you should Extend AsyncTask<String,String,Void> ideally.
EDIT 1:
Added code
public class Morma extends AppCompatActivity {
// make the text view class variable if you want to update it outside of onCreate.
private TextView mCounterTextView;
class MormaKaugummi extends AsyncTask<Void, Void, Void> {
private int count = 0;
private void count() {
count++;
}
private void update() {
String Kcounter = Integer.toString(count);
mCounterTextView.setText(Kcounter);
}
#Override
protected void doInBackground(Void... aVoid) {
count();
}
#Override
protected void onPostExecute(Void aVoid) {
update();
}
}
private ProgressBar progressBarKaugummi;
private int progressStatusKaugummi = 0;
private Handler handlerKaugummi = new Handler();
#Override
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_morma);
Button buttonMormaKaugummiKlauen = (Button) findViewById(R.id.buttonMormaKaugummiKlauen);
// initiate all your view items in onCreate.
mCounterTextView = (TextView) findViewById(R.id.counter);
buttonMormaKaugummiKlauen.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
progressBarKaugummi = (ProgressBar) findViewById(R.id.progressBarMormaKaugummi);
new Thread(new Runnable() {
public void run() {
while (progressStatusKaugummi < 100) {
progressStatusKaugummi += 1;
handlerKaugummi.post(new Runnable() {
public void run() {
progressBarKaugummi.setProgress(progressStatusKaugummi);
}
});
try {
Thread.sleep(4000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}).start();
if (progressStatusKaugummi == 100) {
progressBarKaugummi.setProgress(0);
recreate();
new MormaKaugummi().execute();
}
}
});
You need to initialize all your view elements like the textview in onCreate itself and keep the reference as a class variable if you are going to use that view outside of onCreate.

ASyncTask with progressdialog and button

I am beginner and I had a test. I did all tasks, but I have a problem -
public class HttpTask extends AsyncTask<Integer, String, String> {####
ProgressDialog dialog;
Context context;
public HttpTask(Activity activity) {
//init progress dialog
dialog = new ProgressDialog(context);****
dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
}
protected void onPreExecute() {
// show progress dialog
dialog.setMessage("Loading...");
dialog.setCancelable(false);
}
protected String doInBackground(Integer... params) {
//freeze system to 5 seconds
try {
int seconds = params[0]*5;####
TimeUnit.SECONDS.sleep(seconds);
} catch (InterruptedException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(final String success) {
// if there is progress dialog hide it
dialog.dismiss();
}
}
It crashes, when I try to compile it (I showed where are problems with * sign):
08-03 10:43:10.873 29441-29441/? E/AndroidRuntime﹕ FATAL EXCEPTION: main
java.lang.NullPointerException
at android.app.AlertDialog.resolveDialogTheme(AlertDialog.java:142)
at android.app.AlertDialog.<init>(AlertDialog.java:98)
at android.app.ProgressDialog.<init>(ProgressDialog.java:77)
at net.joerichard.androidtest.main.f.HttpTask.<init>(HttpTask.java:26)
at net.joerichard.androidtest.main.f.F_Networking_Activity$1.onClick(F_Networking_Activity.java:27)
at android.view.View.performClick(View.java:4107)
at android.view.View$PerformClick.run(View.java:17166)
at android.os.Handler.handleCallback(Handler.java:615)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:155)
at android.app.ActivityThread.main(ActivityThread.java:5559)
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:1074)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:841)
at dalvik.system.NativeStart.main(Native Method)
08-03 10:43:10.913 754-877/? E/EmbeddedLogger﹕ App crashed! Process: net.joerichard.androidtest
08-03 10:43:10.913 754-877/? E/EmbeddedLogger﹕ App crashed! Package: net.joerichard.androidtest v1 (1.0)
08-03 10:43:10.913 754-877/? E/EmbeddedLogger﹕ Application Label: AndroidTest
This is class of main activity.
public class F_Networking_Activity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_f__networking_);
// bDownload: start HttpTask
Button bDownload = (Button) findViewById(R.id.bDownload);
bDownload.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
HttpTask task = new HttpTask(F_Networking_Activity.this);****
task.execute();
}
});
}
Thank you for your answers. Now I have another problem (I showed with # sign of second problems)
08-03 11:28:18.292 754-877/? E/EmbeddedLogger﹕ App crashed! Process: net.joerichard.androidtest'
08-03 11:28:18.292 754-877/? E/EmbeddedLogger﹕ App crashed! Package: net.joerichard.androidtest v1 (1.0)
08-03 11:28:18.292 754-877/? E/EmbeddedLogger﹕ Application Label: AndroidTest
08-03 11:28:18.292 30544-30726/? E/AndroidRuntime﹕ FATAL EXCEPTION: AsyncTask #1
java.lang.RuntimeException: An error occured while executing doInBackground()
at android.os.AsyncTask$3.done(AsyncTask.java:299)
at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:273)
at java.util.concurrent.FutureTask.setException(FutureTask.java:124)
at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:307)
at java.util.concurrent.FutureTask.run(FutureTask.java:137)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
at java.lang.Thread.run(Thread.java:864)
Caused by: java.lang.ArrayIndexOutOfBoundsException: length=0; index=0
at net.joerichard.androidtest.main.f.HttpTask.doInBackground(HttpTask.java:40)
at net.joerichard.androidtest.main.f.HttpTask.doInBackground(HttpTask.java:20)
at android.os.AsyncTask$2.call(AsyncTask.java:287)
at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
at java.util.concurrent.FutureTask.run(FutureTask.java:137)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
at java.lang.Thread.run(Thread.java:864)
Actually, your context is null because you didn't initialize it.
Add one extra line inside your HttpTask:
public HttpTask(Activity activity) {
this.context = activity;
dialog = new ProgressDialog(context);
dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
}
and change Context to Activity like this:
Activity context;
Now call this context anywhere in your class.
Yes you must get NullPointer. Because your context is null.
Change this like
public HttpTask(Context _context) {
context = _context;
//init progress dialog
dialog = new ProgressDialog(context);****
dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
}

how to send data from one activity to another in android?

I am trying to send my web service response from one activity to another .when I move one activity to another activity without response it work fine .but when I send response it give me error .could you please help me removing this exception ..
Actually I am sending like this:I think problem in this line i.putExtra("test", data);
I do like this..
10-25 21:13:47.619: E/AndroidRuntime(962): FATAL EXCEPTION: main
10-25 21:13:47.619: E/AndroidRuntime(962): java.lang.RuntimeException: Unable to start activity
ComponentInfo{com.firstgroup.applicationload/com.firstgroup.ui.screens.Departuredashboardscreen}: java.lang.NullPointerException
10-25 21:13:47.619: E/AndroidRuntime(962): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2180)
10-25 21:13:47.619: E/AndroidRuntime(962): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
10-25 21:13:47.619: E/AndroidRuntime(962): at android.app.ActivityThread.access$600(ActivityThread.java:141)
10-25 21:13:47.619: E/AndroidRuntime(962): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
10-25 21:13:47.619: E/AndroidRuntime(962): at android.os.Handler.dispatchMessage(Handler.java:99)
10-25 21:13:47.619: E/AndroidRuntime(962): at android.os.Looper.loop(Looper.java:137)
10-25 21:13:47.619: E/AndroidRuntime(962): at android.app.ActivityThread.main(ActivityThread.java:5041)
10-25 21:13:47.619: E/AndroidRuntime(962): at java.lang.reflect.Method.invokeNative(Native Method)
10-25 21:13:47.619: E/AndroidRuntime(962): at java.lang.reflect.Method.invoke(Method.java:511)
10-25 21:13:47.619: E/AndroidRuntime(962): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
10-25 21:13:47.619: E/AndroidRuntime(962): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
10-25 21:13:47.619: E/AndroidRuntime(962): at dalvik.system.NativeStart.main(Native Method)
10-25 21:13:47.619: E/AndroidRuntime(962): Caused by: java.lang.NullPointerException
10-25 21:13:47.619: E/AndroidRuntime(962): at android.os.Parcel.readListInternal(Parcel.java:2237)
10-25 21:13:47.619: E/AndroidRuntime(962): at android.os.Parcel.readList(Parcel.java:1531)
10-25 21:13:47.619: E/AndroidRuntime(962): at com.firstgroup.dto.deparaturedaseboarddto.<init>(deparaturedaseboarddto.java:209)
10-25 21:13:47.619: E/AndroidRuntime(962): at com.firstgroup.dto.deparaturedaseboarddto.<init>(deparaturedaseboarddto.java:193)
10-25 21:13:47.619: E/AndroidRuntime(962): at com.firstgroup.dto.deparaturedaseboarddto$1.createFromParcel(deparaturedaseboarddto.java:185)
10-25 21:13:47.619: E/AndroidRuntime(962): at com.firstgroup.dto.deparaturedaseboarddto$1.createFromParcel(deparaturedaseboarddto.java:1)
10-25 21:13:47.619: E/AndroidRuntime(962): at android.os.Parcel.readParcelable(Parcel.java:2103)
10-25 21:13:47.619: E/AndroidRuntime(962): at android.os.Parcel.readValue(Parcel.java:1965)
10-25 21:13:47.619: E/AndroidRuntime(962): at android.os.Parcel.readMapInternal(Parcel.java:2226)
10-25 21:13:47.619: E/AndroidRuntime(962): at android.os.Bundle.unparcel(Bundle.java:223)
10-25 21:13:47.619: E/AndroidRuntime(962): at android.os.Bundle.getParcelable(Bundle.java:1173)
10-25 21:13:47.619: E/AndroidRuntime(962): at android.content.Intent.getParcelableExtra(Intent.java:4330)
10-25 21:13:47.619: E/AndroidRuntime(962): at com.firstgroup.ui.screens.Departuredashboardscreen.onCreate(Departuredashboardscreen.java:21)
10-25 21:13:47.619: E/AndroidRuntime(962): at android.app.Activity.performCreate(Activity.java:5104)
10-25 21:13:47.619: E/AndroidRuntime(962): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1080)
10-25 21:13:47.619: E/AndroidRuntime(962): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2144)
10-25 21:13:47.619: E/AndroidRuntime(962): ... 11 more
#Override
public void getWebserviceResponse(String result) {
// TODO Auto-generated method stub
//JSONObject js=new Jso(result);
deparaturedaseboarddto data = new Gson().fromJson(result, deparaturedaseboarddto.class);
/*listView=(ListView)findViewById(R.id.listView1);
adapter = new CustomListAdapter(this, data.getData());
listView.setAdapter(adapter);*/
Intent i = new Intent(Appliacationload.this,Departuredashboardscreen.class);
i.putExtra("test", data);
startActivity(i);
finish();
Log.d("----", "========");
}
Second Activity:
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.departure_dashboard);
Intent i = getIntent();
deparaturedaseboarddto myParcelableObject = (deparaturedaseboarddto) i.getParcelableExtra("test");
Log.d("===", "hhhh");
}
**Model class :**
public class deparaturedaseboarddto implements Parcelable{
ArrayList<deparaturedaseboarddto> data;
public ArrayList<deparaturedaseboarddto> getData() {
return data;
}
public void setData(ArrayList<deparaturedaseboarddto> data) {
this.data = data;
}
#SerializedName("alertsId")
int alertsId;
#SerializedName("destExpArrival")
String destExpArrival;
#SerializedName("destSchArrival")
String destSchArrival;
#SerializedName("expDepart")
String expDepart;
#SerializedName("filteredStation")
String filteredStation;
#SerializedName("platformNo")
String platformNo;
#SerializedName("rid")
String rid;
#SerializedName("schDepart")
String schDepart;
#SerializedName("toc")
String toc;
#SerializedName("toExpArrival")
String toExpArrival;
#SerializedName("toSchArrival")
String toSchArrival;
#SerializedName("trainID")
String trainID;
#SerializedName("trainLastReportedAt")
String trainLastReportedAt;
#SerializedName("destinationStation")
DestinationStation destinationStation;
public deparaturedaseboarddto(String trainID,String toc,String trainLastReportedAt, String platformNo, String schDepart, String expDepart, int alertsId, String rid, String destSchArrival, String filteredStation, String destExpArrival, String toSchArrival, String toExpArrival,DestinationStation destinationStation){
super();
this.trainID=trainID;
this.toc=toc;
this.trainLastReportedAt=trainLastReportedAt;
this.platformNo=platformNo;
this.schDepart=schDepart;
this.expDepart=expDepart;
this.alertsId=alertsId;
this.destinationStation=destinationStation;
this.toExpArrival=toExpArrival;
this.toSchArrival=toSchArrival;
this.destExpArrival=destExpArrival;
this.filteredStation=filteredStation;
this.destSchArrival=destSchArrival;
this.rid=rid;
}
public DestinationStation getDestinationStation() {
return destinationStation;
}
public void setDestinationStation(DestinationStation destinationStation) {
this.destinationStation = destinationStation;
}
public int getAlertsId() {
return alertsId;
}
public void setAlertsId(int alertsId) {
this.alertsId = alertsId;
}
public String getDestExpArrival() {
return destExpArrival;
}
public void setDestExpArrival(String destExpArrival) {
this.destExpArrival = destExpArrival;
}
public String getDestSchArrival() {
return destSchArrival;
}
public void setDestSchArrival(String destSchArrival) {
this.destSchArrival = destSchArrival;
}
public String getExpDepart() {
return expDepart;
}
public void setExpDepart(String expDepart) {
this.expDepart = expDepart;
}
public String getFilteredStation() {
return filteredStation;
}
public void setFilteredStation(String filteredStation) {
this.filteredStation = filteredStation;
}
public String getPlatformNo() {
return platformNo;
}
public void setPlatformNo(String platformNo) {
this.platformNo = platformNo;
}
public String getRid() {
return rid;
}
public void setRid(String rid) {
this.rid = rid;
}
public String getSchDepart() {
return schDepart;
}
public void setSchDepart(String schDepart) {
this.schDepart = schDepart;
}
public String getToc() {
return toc;
}
public void setToc(String toc) {
this.toc = toc;
}
public String getToExpArrival() {
return toExpArrival;
}
public void setToExpArrival(String toExpArrival) {
this.toExpArrival = toExpArrival;
}
public String getToSchArrival() {
return toSchArrival;
}
public void setToSchArrival(String toSchArrival) {
this.toSchArrival = toSchArrival;
}
public String getTrainID() {
return trainID;
}
public void setTrainID(String trainID) {
this.trainID = trainID;
}
public String getTrainLastReportedAt() {
return trainLastReportedAt;
}
public void setTrainLastReportedAt(String trainLastReportedAt) {
this.trainLastReportedAt = trainLastReportedAt;
}
#Override
public int describeContents() {
// TODO Auto-generated method stub
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeInt(alertsId);
dest.writeString(destExpArrival);
dest.writeString(destSchArrival);
dest.writeString(expDepart);
dest.writeString(filteredStation);
dest.writeString(platformNo);
dest.writeString(rid);
dest.writeString(schDepart);
dest.writeString(toc);
dest.writeString(toExpArrival);
dest.writeString(toSchArrival);
dest.writeString(trainID);
dest.writeString(trainLastReportedAt);
dest.writeParcelable(this.destinationStation, flags);
dest.writeList(data);
}
public static final Parcelable.Creator<deparaturedaseboarddto> CREATOR = new Parcelable.Creator<deparaturedaseboarddto>() {
public deparaturedaseboarddto createFromParcel(Parcel in) {
return new deparaturedaseboarddto(in);
}
public deparaturedaseboarddto[] newArray(int size) {
return new deparaturedaseboarddto[size];
}
};
private deparaturedaseboarddto(Parcel in) {
this.alertsId=in.readInt();
this.destExpArrival=in.readString();
this.destSchArrival=in.readString();
this.expDepart=in.readString();
this.filteredStation=in.readString();
this.platformNo=in.readString();
this.rid=in.readString();
this.schDepart=in.readString();
this.toc=in.readString();
this.toExpArrival=in.readString();
this.toSchArrival=in.readString();
this.trainID=in.readString();
this.trainLastReportedAt=in.readString();
this.destinationStation = in.readParcelable(DestinationStation.class.getClassLoader());
in.readList(data,deparaturedaseboarddto.class.getClassLoader());
}
}
package com.firstgroup.dto;
import android.os.Parcel;
import android.os.Parcelable;
import com.google.gson.annotations.SerializedName;
public class DestinationStation implements Parcelable {
#SerializedName("crsCode")
String crsCode;
#SerializedName("stationName")
String stationName;
public DestinationStation(String crsCode, String stationName) {
// TODO Auto-generated constructor stub
super();
this.crsCode=crsCode;
this.stationName=stationName;
}
public String getCrsCode() {
return crsCode;
}
public void setCrsCode(String crsCode) {
this.crsCode = crsCode;
}
public String getStationName() {
return stationName;
}
public void setStationName(String stationName) {
this.stationName = stationName;
}
#Override
public int describeContents() {
// TODO Auto-generated method stub
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(crsCode);
dest.writeString(stationName);
}
public static final Parcelable.Creator<DestinationStation> CREATOR = new Parcelable.Creator<DestinationStation>() {
public DestinationStation createFromParcel(Parcel in) {
return new DestinationStation(in);
}
public DestinationStation[] newArray(int size) {
return new DestinationStation[size];
}
};
private DestinationStation(Parcel in) {
this.crsCode=in.readString();
this.stationName=in.readString();
}
}
Updated one..
#Override
public void getWebserviceResponse(String result) {
// TODO Auto-generated method stub
//JSONObject js=new Jso(result);
deparaturedaseboarddto data = new Gson().fromJson(result, deparaturedaseboarddto.class);
/*listView=(ListView)findViewById(R.id.listView1);
adapter = new CustomListAdapter(this, data.getData());
listView.setAdapter(adapter);*/
Intent i = new Intent(Appliacationload.this,Departuredashboardscreen.class);
EventBus.getDefault().postSticky(data);
//i.putExtra("test", (Parcelable)data);
startActivity(i);
finish();
Log.d("----", "========");
}
Next Activity:
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.departure_dashboard);
Intent i = getIntent();
deparaturedaseboarddto myParcelableObject = (deparaturedaseboarddto) EventBus.getDefault().getStickyEvent(deparaturedaseboarddto.class);
Log.d("===", "hhhh");
}
Exception:
10-26 00:56:36.052: E/AndroidRuntime(806): FATAL EXCEPTION: AsyncTask #3
10-26 00:56:36.052: E/AndroidRuntime(806): java.lang.RuntimeException: An error occured while executing doInBackground()
10-26 00:56:36.052: E/AndroidRuntime(806): at android.os.AsyncTask$3.done(AsyncTask.java:299)
10-26 00:56:36.052: E/AndroidRuntime(806): at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:352)
10-26 00:56:36.052: E/AndroidRuntime(806): at java.util.concurrent.FutureTask.setException(FutureTask.java:219)
10-26 00:56:36.052: E/AndroidRuntime(806): at java.util.concurrent.FutureTask.run(FutureTask.java:239)
10-26 00:56:36.052: E/AndroidRuntime(806): at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
10-26 00:56:36.052: E/AndroidRuntime(806): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
10-26 00:56:36.052: E/AndroidRuntime(806): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
10-26 00:56:36.052: E/AndroidRuntime(806): at java.lang.Thread.run(Thread.java:856)
10-26 00:56:36.052: E/AndroidRuntime(806): Caused by: android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.
10-26 00:56:36.052: E/AndroidRuntime(806): at android.view.ViewRootImpl.checkThread(ViewRootImpl.java:4746)
10-26 00:56:36.052: E/AndroidRuntime(806): at android.view.ViewRootImpl.requestLayout(ViewRootImpl.java:823)
10-26 00:56:36.052: E/AndroidRuntime(806): at android.view.View.requestLayout(View.java:15473)
10-26 00:56:36.052: E/AndroidRuntime(806): at android.view.View.setFlags(View.java:8444)
10-26 00:56:36.052: E/AndroidRuntime(806): at android.view.View.setVisibility(View.java:5716)
10-26 00:56:36.052: E/AndroidRuntime(806): at android.app.Dialog.hide(Dialog.java:294)
10-26 00:56:36.052: E/AndroidRuntime(806): at com.firstgroup.webservice.RequestTask.doInBackground(RequestTask.java:66)
10-26 00:56:36.052: E/AndroidRuntime(806): at com.firstgroup.webservice.RequestTask.doInBackground(RequestTask.java:1)
10-26 00:56:36.052: E/AndroidRuntime(806): at android.os.AsyncTask$2.call(AsyncTask.java:287)
10-26 00:56:36.052: E/AndroidRuntime(806): at java.util.concurrent.FutureTask.run(FutureTask.java:234)
10-26 00:56:36.052: E/AndroidRuntime(806): ... 4 more
10-26 00:56:40.424: E/WindowManager(806): Activity com.firstgroup.applicationload.Appliacationload has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView{40f6b308 G.E..... R.....ID 0,0-729,324} that was originally added here
10-26 00:56:40.424: E/WindowManager(806): android.view.WindowLeaked: Activity com.firstgroup.applicationload.Appliacationload has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView{40f6b308 G.E..... R.....ID 0,0-729,324} that was originally added here
10-26 00:56:40.424: E/WindowManager(806): at android.view.ViewRootImpl.<init>(ViewRootImpl.java:354)
10-26 00:56:40.424: E/WindowManager(806): at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:216)
10-26 00:56:40.424: E/WindowManager(806): at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:69)
10-26 00:56:40.424: E/WindowManager(806): at android.app.Dialog.show(Dialog.java:281)
10-26 00:56:40.424: E/WindowManager(806): at com.firstgroup.webservice.RequestTask.onPreExecute(RequestTask.java:36)
10-26 00:56:40.424: E/WindowManager(806): at android.os.AsyncTask.executeOnExecutor(AsyncTask.java:586)
10-26 00:56:40.424: E/WindowManager(806): at android.os.AsyncTask.execute(AsyncTask.java:534)
10-26 00:56:40.424: E/WindowManager(806): at com.firstgroup.applicationload.Appliacationload.calldeparutureWebservice(Appliacationload.java:130)
10-26 00:56:40.424: E/WindowManager(806): at com.firstgroup.applicationload.Appliacationload.access$1(Appliacationload.java:126)
10-26 00:56:40.424: E/WindowManager(806): at com.firstgroup.applicationload.Appliacationload$2.onClick(Appliacationload.java:91)
10-26 00:56:40.424: E/WindowManager(806): at android.view.View.performClick(View.java:4204)
10-26 00:56:40.424: E/WindowManager(806): at android.view.View$PerformClick.run(View.java:17355)
10-26 00:56:40.424: E/WindowManager(806): at android.os.Handler.handleCallback(Handler.java:725)
10-26 00:56:40.424: E/WindowManager(806): at android.os.Handler.dispatchMessage(Handler.java:92)
10-26 00:56:40.424: E/WindowManager(806): at android.os.Looper.loop(Looper.java:137)
10-26 00:56:40.424: E/WindowManager(806): at android.app.ActivityThread.main(ActivityThread.java:5041)
10-26 00:56:40.424: E/WindowManager(806): at java.lang.reflect.Method.invokeNative(Native Method)
10-26 00:56:40.424: E/WindowManager(806): at java.lang.reflect.Method.invoke(Method.java:511)
10-26 00:56:40.424: E/WindowManager(806): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
10-26 00:56:40.424: E/WindowManager(806): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
10-26 00:56:40.424: E/WindowManager(806): at dalvik.system.NativeStart.main(Native Method)
Should be something like this:
#Override
public void getWebserviceResponse(String result) {
// TODO Auto-generated method stub
//JSONObject js=new Jso(result);
deparaturedaseboarddto data = new Gson().fromJson(result, deparaturedaseboarddto.class);
/*listView=(ListView)findViewById(R.id.listView1);
adapter = new CustomListAdapter(this, data.getData());
listView.setAdapter(adapter);*/
Intent i = new Intent(Appliacationload.this,Departuredashboardscreen.class);
//i.putExtra("test", data);
EventBus.getDefault().postSticky(deparaturedaseboarddto);
startActivity(i);
finish();
Log.d("----", "========");
}
and in Departuredashboardscreen
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.departure_dashboard);
deparaturedaseboarddto myParcelableObject = EventBus.getDefault().getStickyEvent(deparaturedaseboarddto.class);
Log.d("===", "hhhh");
}
Try using getExtra()
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.departure_dashboard);
//use getExtra()
Intent i = getIntent().getExtras();
deparaturedaseboarddto myParcelableObject =
(deparaturedaseboarddto) i.getParcelableExtra("test");
Log.d("===", "hhhh");
}

ListView updating data from another thread

I have activity where Im viewing data in listView. But I have to fill data from another thread. As you can see in following code. On every data change I'm calling handler message which triggers notifyDataSetChanged(). When I'm updating data less than 1 change per second it works ok, but when Im changing data faster It throws IllegalStateException. Is there any chance to catch this exception?
Is there any more clear solution how to update data from another thread?
full code link: https://www.dropbox.com/s/nxyac1xd88g2y71/TestListThreadFill.zip
Activity:
public class MainActivity extends Activity {
private ListView list;
private TestAdapter adapter;
public static MainActivity magic;
/**
* Called when the activity is first created.
*/
#Override public void onCreate( Bundle savedInstanceState) {
magic = this;
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
list = (ListView)findViewById( R.id.list);
adapter = new TestAdapter( getApplicationContext());
new FillThread().execute((Object) null);
Data.getInstance().addHandler(this, new Handler(){
#Override public void dispatchMessage(Message msg) {
update();
super.dispatchMessage(msg);
}
});
}
public void update(){
adapter.notifyDataSetChanged();
}
#Override protected void onResume() {
list.setAdapter( adapter);
super.onResume();
}
}
Data continer:
public class Data extends Vector<DataItem> {
private static Data instance = null;
private HashMap< Object, Handler> handlerList;
public Data() {
handlerList = new HashMap< Object, Handler>();
}
public static Data getInstance(){
if( instance == null)
instance = new Data();
return instance;
}
#Override public synchronized boolean add( DataItem object) {
boolean result = super.add(object);
for( Map.Entry< Object, Handler> handler : handlerList.entrySet())
{
handler.getValue().sendEmptyMessage( 0);
}
return result;
}
public synchronized void addHandler( Object object, Handler handler){
handlerList.put( object, handler);
}
public synchronized void addHandler( Handler handler){
addHandler( handler, handler);
}
public synchronized void removeHandler( Object object){
handlerList.remove( object);
}
}
Data filler thread:
public class FillThread extends AsyncTask{
#Override protected Object doInBackground(Object... params) {
while( true) {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
Data.getInstance().add( new DataItem( "L", "TOP", "BOTTOM"));
}
}
}
Logcat:
05-23 13:20:23.900 25260-25260/com.example.TestListThreadFill E/AndroidRuntime﹕ FATAL EXCEPTION: main
java.lang.IllegalStateException: The content of the adapter has changed but ListView did not receive a notification. Make sure the content of your adapter is not modified from a background thread, but only from the UI thread. [in ListView(2131034115, class android.widget.ListView) with Adapter(class com.example.TestListThreadFill.TestAdapter)]
at android.widget.ListView.layoutChildren(ListView.java:1549)
at android.widget.AbsListView.onLayout(AbsListView.java:2170)
at android.view.View.layout(View.java:13846)
at android.view.ViewGroup.layout(ViewGroup.java:4466)
at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1649)
at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1507)
at android.widget.LinearLayout.onLayout(LinearLayout.java:1420)
at android.view.View.layout(View.java:13846)
at android.view.ViewGroup.layout(ViewGroup.java:4466)
at android.widget.FrameLayout.onLayout(FrameLayout.java:448)
at android.view.View.layout(View.java:13846)
at android.view.ViewGroup.layout(ViewGroup.java:4466)
at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1649)
at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1507)
at android.widget.LinearLayout.onLayout(LinearLayout.java:1420)
at android.view.View.layout(View.java:13846)
at android.view.ViewGroup.layout(ViewGroup.java:4466)
at android.widget.FrameLayout.onLayout(FrameLayout.java:448)
at android.view.View.layout(View.java:13846)
at android.view.ViewGroup.layout(ViewGroup.java:4466)
at android.view.ViewRootImpl.performLayout(ViewRootImpl.java:2149)
at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1907)
at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1127)
at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:4606)
at android.view.Choreographer$CallbackRecord.run(Choreographer.java:747)
at android.view.Choreographer.doCallbacks(Choreographer.java:567)
at android.view.Choreographer.doFrame(Choreographer.java:536)
at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:733)
at android.os.Handler.handleCallback(Handler.java:615)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:153)
at android.app.ActivityThread.main(ActivityThread.java:4987)
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:821)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:584)
at dalvik.system.NativeStart.main(Native Method)
05-23 13:20:30.923 25260-25265/com.example.TestListThreadFill D/jdwp﹕ processIncoming
05-23 13:20:30.923 25260-25265/com.example.TestListThreadFill D/jdwp﹕ handlePacket : cmd=0x1, cmdSet=0xC7, len=0x13, id=0x4000016E, flags=0x0, dataLen=0x8
05-23 13:20:31.421 25260-25265/com.example.TestListThreadFill D/jdwp﹕ processIncoming
05-23 13:20:31.421 25260-25265/com.example.TestListThreadFill D/jdwp﹕ handlePacket : cmd=0x1, cmdSet=0xC7, len=0x17, id=0x4000016F, flags=0x0, dataLen=0xC
05-23 13:20:31.429 25260-25265/com.example.TestListThreadFill D/jdwp﹕ processIncoming
05-23 13:20:31.429 25260-25265/com.example.TestListThreadFill D/jdwp﹕ handlePacket : cmd=0x1, cmdSet=0xC7, len=0x13, id=0x40000170, flags=0x0, dataLen=0x8
05-23 13:20:31.429 25260-25265/com.example.TestListThreadFill D/jdwp﹕ processIncoming
05-23 13:20:31.429 25260-25265/com.example.TestListThreadFill D/jdwp﹕ handlePacket : cmd=0x1, cmdSet=0xC7, len=0x13, id=0x40000171, flags=0x0, dataLen=0x8
It's pretty clear the error message :
Make sure the content of your adapter is not modified from a background thread, but only from the UI thread.
You could try something like this :
public class FillThread extends AsyncTask<Void, Void, DataItem> {
#Override
protected DataItem doInBackground(Void... params) {
return new DataItem();
}
#Override
protected void onPostExecute(DataItem dataItem) {
// call an update method that adds the dataItem and notifies the adapter
}
}

RSS AsyncTask - ArrayAdapter is undefined

I am creating an RSS reader application for android 4.0+. I have put the reader code in AsyncTask because of the NetworkOnMainThreadException. The code almost works fine, however one line has an error. This is my code:
Java code:
private class PostTask extends AsyncTask<String, Integer, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(String... params) {
String url=params[0];
headlines = new ArrayList();
links = new ArrayList();
//Download and parse xml feed
headlines = new ArrayList();
links = new ArrayList();
try {
URL url1 = new URL("http://feeds.pcworld.com/pcworld/latestnews");
XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
factory.setNamespaceAware(false);
XmlPullParser xpp = factory.newPullParser();
// We will get the XML from an input stream
xpp.setInput(getInputStream(url1), "UTF_8");
/* We will parse the XML content looking for the "<title>" tag which appears inside the "<item>" tag.
* However, we should take in consideration that the rss feed name also is enclosed in a "<title>" tag.
* As we know, every feed begins with these lines: "<channel><title>Feed_Name</title>...."
* so we should skip the "<title>" tag which is a child of "<channel>" tag,
* and take in consideration only "<title>" tag which is a child of "<item>"
*
* In order to achieve this, we will make use of a boolean variable.
*/
boolean insideItem = false;
// Returns the type of current event: START_TAG, END_TAG, etc..
int eventType = xpp.getEventType();
while (eventType != XmlPullParser.END_DOCUMENT) {
if (eventType == XmlPullParser.START_TAG) {
if (xpp.getName().equalsIgnoreCase("item")) {
insideItem = true;
} else if (xpp.getName().equalsIgnoreCase("title")) {
if (insideItem)
headlines.add(xpp.nextText()); //extract the headline
} else if (xpp.getName().equalsIgnoreCase("link")) {
if (insideItem)
links.add(xpp.nextText()); //extract the link of article
}
}else if(eventType==XmlPullParser.END_TAG && xpp.getName().equalsIgnoreCase("item")){
insideItem=false;
}
eventType = xpp.next(); //move to next element
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (XmlPullParserException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return "Feed parsed!";
}
#Override
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
// Binding data
ArrayAdapter adapter = new ArrayAdapter(this,
android.R.layout.simple_list_item_1, headlines);
setListAdapter(adapter);
}
}
in this code snippet i get an error:
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
// Binding data
ArrayAdapter adapter = new ArrayAdapter(this,
android.R.layout.simple_list_item_1, headlines);
setListAdapter(adapter);
}
Error: The constructor ArrayAdapter(MainActivity.PostTask, int, List) is undefined.
Logcat:
01-26 20:55:53.811: E/AndroidRuntime(1830): FATAL EXCEPTION: AsyncTask #1
01-26 20:55:53.811: E/AndroidRuntime(1830): java.lang.RuntimeException: An error occured while executing doInBackground()
01-26 20:55:53.811: E/AndroidRuntime(1830): at android.os.AsyncTask$3.done(AsyncTask.java:278)
01-26 20:55:53.811: E/AndroidRuntime(1830): at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:273)
01-26 20:55:53.811: E/AndroidRuntime(1830): at java.util.concurrent.FutureTask.setException(FutureTask.java:124)
01-26 20:55:53.811: E/AndroidRuntime(1830): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:307)
01-26 20:55:53.811: E/AndroidRuntime(1830): at java.util.concurrent.FutureTask.run(FutureTask.java:137)
01-26 20:55:53.811: E/AndroidRuntime(1830): at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:208)
01-26 20:55:53.811: E/AndroidRuntime(1830): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
01-26 20:55:53.811: E/AndroidRuntime(1830): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
01-26 20:55:53.811: E/AndroidRuntime(1830): at java.lang.Thread.run(Thread.java:856)
01-26 20:55:53.811: E/AndroidRuntime(1830): Caused by: java.lang.IllegalArgumentException
01-26 20:55:53.811: E/AndroidRuntime(1830): at org.kxml2.io.KXmlParser.setInput(KXmlParser.java:1615)
01-26 20:55:53.811: E/AndroidRuntime(1830): at com.mysoftware.mysoftwareos.mobile.MainActivity$PostTask.doInBackground(MainActivity.java:343)
01-26 20:55:53.811: E/AndroidRuntime(1830): at com.mysoftware.mysoftwareos.mobile.MainActivity$PostTask.doInBackground(MainActivity.java:1)
01-26 20:55:53.811: E/AndroidRuntime(1830): at android.os.AsyncTask$2.call(AsyncTask.java:264)
01-26 20:55:53.811: E/AndroidRuntime(1830): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
01-26 20:55:53.811: E/AndroidRuntime(1830): ... 5 more
Could anyone please look into my problem and come up with a solution? Or tell me if i should do anything different? Thanks a lot!
Change it to:
ArrayAdapter adapter = new ArrayAdapter(MainActivity.this,
android.R.layout.simple_list_item_1, headlines);
this refers to the AsyncTask, so you have to explicitly reference MainActivity's this.
use Activity Context instead of AsyncTask to Create ArrayAdapter inside onPostExecute method as :
ArrayAdapter<String> adapter =
new ArrayAdapter<String>(Your_Current_Activity.this,
android.R.layout.simple_list_item_1, headlines);
setListAdapter(adapter);
EDIT :
after log posted also change
xpp.setInput(getInputStream(url1), "UTF_8");
to
xpp.setInput(url1.openConnection().getInputStream(), "UTF_8");

Categories