AsyncTask Class Runtime Error : concurrent.FutureTask.finishCompletion - java

i m new in android and trying to make simple program that can print variable in AsyncTask Class
here is my code
int a,b,c;
#Override
protected String doInBackground(String... arg0) {
// TODO Auto-generated method stub
a =10;
b=10;
c=a+b;
Context ctx = null;
show(c, ctx );
return null;
}
public void show(int c2 ,Context c) {
// TODO Auto-generated method stub
Toast.makeText(c, "AsyncTask classs + c2 ", Toast.LENGTH_SHORT).show();
}
after running this program , i m getting run time Error
here us LogCat file view
Process: com.example.asycclass, PID: 2539
java.lang.RuntimeException: An error occured while executing doInBackground()
at android.os.AsyncTask$3.done(AsyncTask.java:300)
at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:355)
at java.util.concurrent.FutureTask.setException(FutureTask.java:222)
at java.util.concurrent.FutureTask.run(FutureTask.java:242)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
at java.lang.Thread.run(Thread.java:841)
Caused by: java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
at android.os.Handler.<init>(Handler.java:200)
at android.os.Handler.<init>(Handler.java:114)
at android.widget.Toast$TN.<init>(Toast.java:327)
at android.widget.Toast.<init>(Toast.java:92)
at android.widget.Toast.makeText(Toast.java:241)
at com.example.asycclass.MainActivity$AttemptLogin.show(MainActivity.java:74)
at com.example.asycclass.MainActivity$AttemptLogin.doInBackground(MainActivity.java:65)
at com.example.asycclass.MainActivity$AttemptLogin.doInBackground(MainActivity.java:1)
at android.os.AsyncTask$2.call(AsyncTask.java:288)
at java.util.concurrent.FutureTask.run(FutureTask.java:237)

Move your show Toast code inside runOnUiThread like :
runOnUiThread(new Runnable() {
#Override
public void run() {
show(c, ctx );
}
});

I guess that the problem is that you're trying to create a Toast not from the main thread.
You must create a handler and Runnable for that and use handler.post()
For example
Runnable showToast = new Runnable() {
public void run() {
// Create your Toast here or whatever you want
}
}

Related

whenever i try to enter my settings logcat show me this error and i don't know what is wrong

I'm trying to list all installed applications on my setting Listview but whenever I try to enter to it it freezes and closed iI don't know why, it seems everything is fine.
I even tried some ready answers but logcat keeps showing me this error.
2019-02-01 23:27:17.563 7458-7479/com.example.sony.econet1 E/AndroidRuntime: FATAL EXCEPTION: AsyncTask #1
Process: com.example.sony.econet1, PID: 7458
java.lang.RuntimeException: An error occurred while executing doInBackground()
at android.os.AsyncTask$3.done(AsyncTask.java:318)
at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:354)
at java.util.concurrent.FutureTask.setException(FutureTask.java:223)
at java.util.concurrent.FutureTask.run(FutureTask.java:242)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:243)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1133)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:607)
at java.lang.Thread.run(Thread.java:761)
Caused by: java.lang.ArrayIndexOutOfBoundsException: length=0; index=0
at com.example.sony.econet1.My_Settings$LoaddAppsInfoTask.doInBackground(My_Settings.java:79)
at com.example.sony.econet1.My_Settings$LoaddAppsInfoTask.doInBackground(My_Settings.java:65)
at android.os.AsyncTask$2.call(AsyncTask.java:304)
at java.util.concurrent.FutureTask.run(FutureTask.java:237)
this is my AsyncTask
class LoaddAppsInfoTask extends AsyncTask <Integer, Integer,List<AppInfo>>
{
#Override
protected void onPreExecute() {
super.onPreExecute();
//loaded();
//loadappsinfo
}
#Override
protected List<AppInfo> doInBackground(Integer... params) {
List<AppInfo> apps=new ArrayList<>();
PackageManager packageManager =getPackageManager();
List<ApplicationInfo> infos = packageManager.getInstalledApplications(params[0]);
for (ApplicationInfo info:infos)
{
if (mIncludeSystemApps && (info.flags & ApplicationInfo.FLAG_SYSTEM) == 1)
{
continue;
}
AppInfo app = new AppInfo();
app.info = info;
app.label = (String)info.loadLabel(packageManager);
apps.add(app);
}
return null;
}
#Override
protected void onPostExecute(List<AppInfo> appInfos) {
super.onPostExecute(appInfos);
listView.setAdapter(new Appadapter(My_Settings.this,appInfos));
Snackbar.make(listView,appInfos.size() + "Applications loaded", Snackbar.LENGTH_LONG).show();
}

App crashes while can't perform AsyncTask

I have a problem with AsyncTask in my app. AsyncTask is located in SplashScreenAcivity.java. It downloads data using json for MainActivity.java while showing splash screen. When data is loaded, app shows MainActivity screen. However, when i turn off internet connection app crashes. Instead of it i would like to move to MainActivity.java and show toast that internet connection must be turned on. SplashScreen.java loads data for listView in MainActivity.
SplashActivityScreen.java
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_splash_screen);
new DownloadData().execute();
}
private class DownloadData extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... voids) {
SyncHttpClient clientOne = new SyncHttpClient();
clientOne.get("https://api.themoviedb.org/3/tv/top_rated?api_key=d253f520df9cd868af7db8daaa0db8fb&language=en-US", new JsonHttpResponseHandler() {
#Override
public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
try {
tvseries0 = response.getJSONArray("results").getJSONObject(0).getString("name");
tvseries1 = response.getJSONArray("results").getJSONObject(1).getString("name");
tvseries2 = response.getJSONArray("results").getJSONObject(2).getString("name");
tvseries3 = response.getJSONArray("results").getJSONObject(3).getString("name");
tvseries4 = response.getJSONArray("results").getJSONObject(4).getString("name");
tvseries5 = response.getJSONArray("results").getJSONObject(5).getString("name");
tvseries6 = response.getJSONArray("results").getJSONObject(6).getString("name");
tvseries7 = response.getJSONArray("results").getJSONObject(7).getString("name");
tvseries8 = response.getJSONArray("results").getJSONObject(8).getString("name");
tvseries9 = response.getJSONArray("results").getJSONObject(9).getString("name");
tvseries10 = response.getJSONArray("results").getJSONObject(10).getString("name");
tvseries11 = response.getJSONArray("results").getJSONObject(11).getString("name");
tvseries12 = response.getJSONArray("results").getJSONObject(12).getString("name");
tvseries13 = response.getJSONArray("results").getJSONObject(13).getString("name");
tvseries14 = response.getJSONArray("results").getJSONObject(14).getString("name");
tvseries15 = response.getJSONArray("results").getJSONObject(15).getString("name");
tvseries16 = response.getJSONArray("results").getJSONObject(16).getString("name");
tvseries17 = response.getJSONArray("results").getJSONObject(17).getString("name");
tvseries18 = response.getJSONArray("results").getJSONObject(18).getString("name");
tvseries19 = response.getJSONArray("results").getJSONObject(19).getString("name");
} catch (JSONException e) {
e.printStackTrace();
}
}
#Override
public void onFailure(int statusCode, Header[] headers,Throwable e , JSONObject response) {
Toast.makeText(SplashScreenActivity.this, "Turn on the internet and swipe to refresh.", Toast.LENGTH_SHORT).show();
}
});
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
Intent i = new Intent(getApplicationContext(), MainActivity.class);
i.putExtra("tvseries0", tvseries0);
i.putExtra("tvseries1", tvseries1);
i.putExtra("tvseries2", tvseries2);
i.putExtra("tvseries3", tvseries3);
i.putExtra("tvseries4", tvseries4);
i.putExtra("tvseries5", tvseries5);
i.putExtra("tvseries6", tvseries6);
i.putExtra("tvseries7", tvseries7);
i.putExtra("tvseries8", tvseries8);
i.putExtra("tvseries9", tvseries9);
i.putExtra("tvseries10", tvseries10);
i.putExtra("tvseries11", tvseries11);
i.putExtra("tvseries12", tvseries12);
i.putExtra("tvseries13", tvseries13);
i.putExtra("tvseries14", tvseries14);
i.putExtra("tvseries15", tvseries15);
i.putExtra("tvseries16", tvseries16);
i.putExtra("tvseries17", tvseries17);
i.putExtra("tvseries18", tvseries18);
i.putExtra("tvseries19", tvseries19);
startActivity(i);
finish();
}
}
}
Crash 1
04-30 13:15:35.165 12349-12365/przemo.me.recommend.recommendme E/AndroidRuntime: FATAL EXCEPTION: AsyncTask #1
Process: przemo.me.recommend.recommendme, PID: 12349
java.lang.RuntimeException: An error occurred while executing doInBackground()
at android.os.AsyncTask$3.done(AsyncTask.java:318)
at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:354)
at java.util.concurrent.FutureTask.setException(FutureTask.java:223)
at java.util.concurrent.FutureTask.run(FutureTask.java:242)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:243)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1133)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:607)
at java.lang.Thread.run(Thread.java:761)
Caused by: java.lang.RuntimeException: java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
at com.loopj.android.http.AsyncHttpResponseHandler.onUserException(AsyncHttpResponseHandler.java:304)
at com.loopj.android.http.AsyncHttpResponseHandler.handleMessage(AsyncHttpResponseHandler.java:395)
at com.loopj.android.http.AsyncHttpResponseHandler.sendMessage(AsyncHttpResponseHandler.java:401)
at com.loopj.android.http.AsyncHttpResponseHandler.sendFailureMessage(AsyncHttpResponseHandler.java:319)
at com.loopj.android.http.AsyncHttpRequest.run(AsyncHttpRequest.java:109)
at com.loopj.android.http.SyncHttpClient.sendRequest(SyncHttpClient.java:95)
at com.loopj.android.http.AsyncHttpClient.get(AsyncHttpClient.java:1078)
at com.loopj.android.http.AsyncHttpClient.get(AsyncHttpClient.java:1037)
at przemo.me.recommend.recommendme.SplashScreenActivity$DownloadData.doInBackground(SplashScreenActivity.java:64)
at przemo.me.recommend.recommendme.SplashScreenActivity$DownloadData.doInBackground(SplashScreenActivity.java:56)
at android.os.AsyncTask$2.call(AsyncTask.java:304)
at java.util.concurrent.FutureTask.run(FutureTask.java:237)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:243) 
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1133) 
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:607) 
at java.lang.Thread.run(Thread.java:761) 
Caused by: java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
at android.os.Handler.<init>(Handler.java:200)
at android.os.Handler.<init>(Handler.java:114)
at android.widget.Toast$TN.<init>(Toast.java:346)
at android.widget.Toast.<init>(Toast.java:101)
at android.widget.Toast.makeText(Toast.java:260)
at przemo.me.recommend.recommendme.SplashScreenActivity$DownloadData$1.onFailure(SplashScreenActivity.java:103)
at com.loopj.android.http.JsonHttpResponseHandler.onFailure(JsonHttpResponseHandler.java:233)
at com.loopj.android.http.AsyncHttpResponseHandler.handleMessage(AsyncHttpResponseHandler.java:359)
at com.loopj.android.http.AsyncHttpResponseHandler.sendMessage(AsyncHttpResponseHandler.java:401) 
at com.loopj.android.http.AsyncHttpResponseHandler.sendFailureMessage(AsyncHttpResponseHandler.java:319) 
at com.loopj.android.http.AsyncHttpRequest.run(AsyncHttpRequest.java:109) 
at com.loopj.android.http.SyncHttpClient.sendRequest(SyncHttpClient.java:95) 
at com.loopj.android.http.AsyncHttpClient.get(AsyncHttpClient.java:1078) 
at com.loopj.android.http.AsyncHttpClient.get(AsyncHttpClient.java:1037) 
at przemo.me.recommend.recommendme.SplashScreenActivity$DownloadData.doInBackground(SplashScreenActivity.java:64) 
at przemo.me.recommend.recommendme.SplashScreenActivity$DownloadData.doInBackground(SplashScreenActivity.java:56) 
at android.os.AsyncTask$2.call(AsyncTask.java:304) 
at java.util.concurrent.FutureTask.run(FutureTask.java:237) 
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:243) 
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1133) 
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:607) 
at java.lang.Thread.run(Thread.java:761) 
Crash 2
04-30 13:15:35.162 12349-12365/przemo.me.recommend.recommendme E/AsyncHttpRH: User-space exception detected!
java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
at android.os.Handler.<init>(Handler.java:200)
at android.os.Handler.<init>(Handler.java:114)
at android.widget.Toast$TN.<init>(Toast.java:346)
at android.widget.Toast.<init>(Toast.java:101)
at android.widget.Toast.makeText(Toast.java:260)
at przemo.me.recommend.recommendme.SplashScreenActivity$DownloadData$1.onFailure(SplashScreenActivity.java:103)
at com.loopj.android.http.JsonHttpResponseHandler.onFailure(JsonHttpResponseHandler.java:233)
at com.loopj.android.http.AsyncHttpResponseHandler.handleMessage(AsyncHttpResponseHandler.java:359)
at com.loopj.android.http.AsyncHttpResponseHandler.sendMessage(AsyncHttpResponseHandler.java:401)
at com.loopj.android.http.AsyncHttpResponseHandler.sendFailureMessage(AsyncHttpResponseHandler.java:319)
at com.loopj.android.http.AsyncHttpRequest.run(AsyncHttpRequest.java:109)
at com.loopj.android.http.SyncHttpClient.sendRequest(SyncHttpClient.java:95)
at com.loopj.android.http.AsyncHttpClient.get(AsyncHttpClient.java:1078)
at com.loopj.android.http.AsyncHttpClient.get(AsyncHttpClient.java:1037)
at przemo.me.recommend.recommendme.SplashScreenActivity$DownloadData.doInBackground(SplashScreenActivity.java:64)
at przemo.me.recommend.recommendme.SplashScreenActivity$DownloadData.doInBackground(SplashScreenActivity.java:56)
at android.os.AsyncTask$2.call(AsyncTask.java:304)
at java.util.concurrent.FutureTask.run(FutureTask.java:237)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:243)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1133)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:607)
at java.lang.Thread.run(Thread.java:761)
You can not do UI operations from non UI thread. Like in your code you are showing Toast in Async task thread.
You should replace
Toast.makeText(SplashScreenActivity.this, "Turn on the internet and swipe to refresh.", Toast.LENGTH_SHORT).show();
with this
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(SplashScreenActivity.this, "Turn on the internet and swipe to refresh.", Toast.LENGTH_SHORT).show();
}
});
use -
SplashScreenActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(SplashScreenActivity.this, "Turn on the internet and swipe to refresh.", Toast.LENGTH_SHORT).show();
}
});
Here is a server connection AsyncTask task that I created years ago in Android Java. The background task works successfully. I used it to update in the background the data repository in the App I developed at that time.
public class DataExchangeStore extends Application {
public void startServerConnection(Context contextGlobal, Activity activityGlobal) {
this.contextGlobal = contextGlobal;
this.activityGlobal = activityGlobal;
connectTask = new ConnectTask();
connectTask.execute("");
}
private ConnectTask connectTask;
public class ConnectTask extends AsyncTask<String, String, TCPClient> {
#Override
protected TCPClient doInBackground(String... message) {
android.os.Process.setThreadPriority( android.os.Process.THREAD_PRIORITY_BACKGROUND);
// we create a TCPClient object
mTcpClient = new TCPClient(new TCPClient.OnMessageReceived() {
#Override
// here the messageReceived method is implemented
public void messageReceived(ChatMessage message) {
// this method calls the onProgressUpdate
publishProgress(message.getMessage());
}
}, contextGlobal, activityGlobal);
mTcpClient.run();
return null;
}
#Override
protected void onProgressUpdate(String... values) {
super.onProgressUpdate(values);
System.err.println(values[0]);
// do your stuff here
}
}
Import is to permanently lock the screen orientation of the activity, specifying the screenOrientation attribute in the Android-Manifest file with portrait or landscape values:
<activity android:screenOrientation="portrait" />
Although previous answers are not wrong, using runOnUiThread() to jump out of the background thread in the AsyncTask is not a good practice. You have the onPostExecute() method for that.
What you should be doing is passing a result object to onPostExecute(). This object would encapsulate the result state (ie: error or success) and the actual data received. Then in onPostExecute() you check the result state and display a Toast if the state is error.
And do yourself a favor and replace your 20 TvSerie objects by a List<TvSerie> and do a loop in you AsyncTask to populate the list.
Please refer to the AsyncTask documentation for details on how to properly use it.

Android app is crashing with An error occurred while executing doInBackground()

Not able to set the data in the database in server...getting values from editText and passing them in doBackground() but error occured while executing in background...any help will be appreciated...thanx in advance...log added......
Here is the log
9 10:27:05.333 3245-3523/com.amar.schooladmin E/AndroidRuntime: FATAL EXCEPTION: AsyncTask #7
Process: com.amar.schooladmin, PID: 3245
java.lang.RuntimeException: An error occurred while executing doInBackground()
at android.os.AsyncTask$3.done(AsyncTask.java:309)
at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:354)
at java.util.concurrent.FutureTask.setException(FutureTask.java:223)
at java.util.concurrent.FutureTask.run(FutureTask.java:242)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:234)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588)
at java.lang.Thread.run(Thread.java:818)
Caused by: java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
at android.os.Handler.<init>(Handler.java:200)
at android.os.Handler.<init>(Handler.java:114)
at android.widget.Toast$TN.<init>(Toast.java:703)
at android.widget.Toast.<init>(Toast.java:145)
at android.widget.Toast.makeText(Toast.java:458)
at com.amar.schooladmin.AddRecord$CreateNewProduct.doInBackground(AddRecord.java:77)
at com.amar.schooladmin.AddRecord$CreateNewProduct.doInBackground(AddRecord.java:61)
at android.os.AsyncTask$2.call(AsyncTask.java:295)
at java.util.concurrent.FutureTask.run(FutureTask.java:237)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:234) 
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113) 
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588) 
at java.lang.Thread.run(Thread.java:818) 
01-19 10:27:0
MainActivity.java
button7.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
new CreateNewProduct().execute();
roll=editText.getText().toString();
name=editText2.getText().toString();
address=editText3.getText().toString();
fname=editText4.getText().toString();
mname=editText5.getText().toString();
}
});
}
public class CreateNewProduct extends AsyncTask<String, String, String>
{
#Override
protected String doInBackground(String... strings) {
List<NameValuePair> parms = new ArrayList<>();
parms.add(new BasicNameValuePair("roll", roll));
parms.add(new BasicNameValuePair("name", name));
parms.add(new BasicNameValuePair("address", address));
parms.add(new BasicNameValuePair("fname", fname));
parms.add(new BasicNameValuePair("mname", mname));
JSONObject jsonObject = jsonParser.makeHttpRequest(url, "POST", parms);
try {
int success= jsonObject.getInt("TAG SUCCESSFULLY");
} catch (Exception e) {
Toast.makeText(AddRecord.this, ""+e.toString(), Toast.LENGTH_SHORT).show();
}
return null;
}
The problem is you are showing Toast in doInBackground(). try this
((Activity) context).runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(AddRecord.this, ""+e.toString(), Toast.LENGTH_SHORT).show();
}
});
You can't write show() method of Toast in doInBackground() because it is not UI thread it is worker thread. You can write Toast in onPostExecute().
Toast is causing the crash to occur, because Toast requires UI Thead to display and currently it is in background thread.
Also, you are getting exception at
int success= jsonObject.getInt("TAG SUCCESSFULLY");
and hence in catch Toast line is getting executed.
Please check if TAG SUCCESSFULLY key exists in jsonObject or not. Use
if(jsonObject.has("TAG SUCCESSFULLY"))
success= jsonObject.getInt("TAG SUCCESSFULLY");

Android populate listview from arraylist Error

I am trying to populate a listview in my android App (android studio) from a list to which I dynamically added Strings.
First, the list is declared as an attribute of the activity:
private List<String> your_array_list = new ArrayList<String>();
Then, I have the class where the method populatelist() is called. There are other methods called in it, but they all work fine, populatelist() is the only method that gives me an error:
private class SendMessage extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... params) {
try {
parse(message);
populatelist();
}
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
And this is the method itself:
public void populatelist() {
// String[] myitems = {"World Weather Online","Open Weather Map","Weather"};
Log.d("Matcher", "Populate! Test 1");
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,R.layout.items,R.id.textting,your_array_list);
Log.d("Matcher", "Populate! Test 2");
ListView list;
Log.d("Matcher", "Populate! Test 3");
list = (ListView) findViewById(R.id.services);
Log.d("Matcher", "Populate! Test 4");
list.setAdapter(adapter);
Log.d("Matcher", "Populate! Test 5");
}
All the logs print except the last one "Test 5". When I run my app, I get the following error:
07-19 21:13:32.399 1575-1591/com.example.othmane.servicefinder E/AndroidRuntime﹕ FATAL EXCEPTION: AsyncTask #2
Process: com.example.othmane.servicefinder, PID: 1575
java.lang.RuntimeException: An error occured while executing doInBackground()
at android.os.AsyncTask$3.done(AsyncTask.java:300)
at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:355)
at java.util.concurrent.FutureTask.setException(FutureTask.java:222)
at java.util.concurrent.FutureTask.run(FutureTask.java:242)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
at java.lang.Thread.run(Thread.java:818)
Caused by: android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.
at android.view.ViewRootImpl.checkThread(ViewRootImpl.java:6247)
at android.view.ViewRootImpl.focusableViewAvailable(ViewRootImpl.java:2855)
at android.view.ViewGroup.focusableViewAvailable(ViewGroup.java:679)
at android.view.ViewGroup.focusableViewAvailable(ViewGroup.java:679)
at android.view.ViewGroup.focusableViewAvailable(ViewGroup.java:679)
at android.view.ViewGroup.focusableViewAvailable(ViewGroup.java:679)
at android.view.ViewGroup.focusableViewAvailable(ViewGroup.java:679)
at android.view.ViewGroup.focusableViewAvailable(ViewGroup.java:679)
at android.view.ViewGroup.focusableViewAvailable(ViewGroup.java:679)
at android.view.View.setFlags(View.java:9603)
at android.view.View.setFocusableInTouchMode(View.java:6741)
at android.widget.AdapterView.checkFocus(AdapterView.java:722)
at android.widget.ListView.setAdapter(ListView.java:488)
at com.example.othmane.servicefinder.MainActivity.populatelist(MainActivity.java:277)
at com.example.othmane.servicefinder.MainActivity$SendMessage.doInBackground(MainActivity.java:100)
at com.example.othmane.servicefinder.MainActivity$SendMessage.doInBackground(MainActivity.java:67)
at android.os.AsyncTask$2.call(AsyncTask.java:288)
at java.util.concurrent.FutureTask.run(FutureTask.java:237)
            at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
            at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
            at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
            at java.lang.Thread.run(Thread.java:818)
Does anyone see any mistake of how I try to populate the list ? I followed a tutorial to do it, but I don't know why it does not work.
Read the logcat and you will see the answer:
android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views. at
The error is caused by you are trying to populate view in the background thread. In order to perform work in the main thread, you need to call onPostExecute method.
Here is the example from one of my app:
public class FetchArtistData extends AsyncTask<String,Void, List<Artist>> {
private static final String TAG="FetchArtistData";
#Override
protected List<Artist> doInBackground(String... params) {
SpotifyApi api=new SpotifyApi();
SpotifyService spotify=api.getService();
ArtistsPager results=spotify.searchArtists(params[0]);
List<Artist> list=results.artists.items;
Log.d(TAG, list.toString());
return list;
}
#Override
protected void onPostExecute(List<Artist> artists) {
mArtistList=(ArrayList<Artist>)artists;
Log.d(TAG,Integer.toString(mArtistList.size()));
updateAdapter(mArtistList);
}
}
Noticed that I update the view in onPostExecute.

Exception occurs in Async task

I am getting this exception. When, i'm trying to run my program. In my program i am executing an AsyncTask For each download and upload tasks, I have created new AsyncTask object and tried to run it in background. I tried to find my mistake. But i can't find where i am going wrong. Below are my stack trace and code of my program -
05-07 10:00:44.899: E/AndroidRuntime(367): FATAL EXCEPTION: AsyncTask #1
05-07 10:00:44.899: E/AndroidRuntime(367): java.lang.RuntimeException: An error occured while executing doInBackground()
05-07 10:00:44.899: E/AndroidRuntime(367): at android.os.AsyncTask$3.done(AsyncTask.java:200)
05-07 10:00:44.899: E/AndroidRuntime(367): at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:274)
05-07 10:00:44.899: E/AndroidRuntime(367): at java.util.concurrent.FutureTask.setException(FutureTask.java:125)
05-07 10:00:44.899: E/AndroidRuntime(367): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:308)
05-07 10:00:44.899: E/AndroidRuntime(367): at java.util.concurrent.FutureTask.run(FutureTask.java:138)
05-07 10:00:44.899: E/AndroidRuntime(367): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1088)
05-07 10:00:44.899: E/AndroidRuntime(367): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:581)
05-07 10:00:44.899: E/AndroidRuntime(367): at java.lang.Thread.run(Thread.java:1019)
05-07 10:00:44.899: E/AndroidRuntime(367): Caused by: java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
05-07 10:00:44.899: E/AndroidRuntime(367): at android.os.Handler.<init>(Handler.java:121)
05-07 10:00:44.899: E/AndroidRuntime(367): at android.widget.Toast.<init>(Toast.java:68)
05-07 10:00:44.899: E/AndroidRuntime(367): at android.widget.Toast.makeText(Toast.java:231)
05-07 10:00:44.899: E/AndroidRuntime(367): at com.android.test.Helper.downloadTask(t.java:269)
05-07 10:00:44.899: E/AndroidRuntime(367): at com.android.test.Helper.doInBackground(t.java:132)
05-07 10:00:44.899: E/AndroidRuntime(367): at com.android.test.Helper.doInBackground(t.java:1)
05-07 10:00:44.899: E/AndroidRuntime(367): at android.os.AsyncTask$2.call(AsyncTask.java:185)
05-07 10:00:44.899: E/AndroidRuntime(367): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:306)
05-07 10:00:44.899: E/AndroidRuntime(367): ... 4 more
This is my AsynTask Helper
class Helper extends AsyncTask<Integer, Void, Void>
{
private SmbFile dfile;
private String dfilepath;
private SmbFile dfolder;
private String dfolderpath;
private File ufolder;
private SmbFile ufoldersmb;
private NtlmPasswordAuthentication auth;
private int upstate=0;
private int downstate=0;
private Context context;
private ArrayList<SmbFile> smbArray=new ArrayList<SmbFile>();
private String ext;
private int tasknumber;
private String taskname;
public Context getcontext()
{
return context;
}
public int gettasknumber()
{
return tasknumber;
}
public String gettaskname()
{
return taskname;
}
public int getupstate()
{
return upstate;
}
public int getdownstate()
{
return downstate;
}
public void setdfile(SmbFile a)
{
this.dfile = a;
}
public void setdfilepath(String b)
{
this.dfilepath = b;
}
public void setdfolder(SmbFile c)
{
this.dfolder = c;
}
public void setdfolderpath(String d)
{
this.dfolderpath = d;
}
public void setufolder(File g)
{
this.ufolder = g;
}
public void setufoldersmb(SmbFile h)
{
this.ufoldersmb = h;
}
public void setauthentication(NtlmPasswordAuthentication i)
{
this.auth = i;
}
public void setupstate(int j)
{
upstate = j;
}
public void setdownstate(int k)
{
downstate = k;
}
public void setcontext(Context l)
{
context = l;
}
public void setarraysmb(SmbFile m)
{
this.smbArray.add(m);
}
public void setextstorage(String n)
{
this.ext=n;
}
public void settasknumber(int o)
{
this.tasknumber=o;
}
public void settaskname(String p)
{
this.taskname=p;
}
#Override
protected Void doInBackground(Integer... params)
{
//check flag to execute exactly method
switch (params[0])
{
case 0:
downloadTask();
break;
case 1:
Toast.makeText(context, "AccessPC Upload task "+tasknumber+" Started", Toast.LENGTH_LONG).show();
uploadFolder(ufolder,ufoldersmb);
break;
default:break;
}
return null;
}
void downloadFile(SmbFile dfile,String dpath)
{
StatFs statFs = new StatFs(Environment.getExternalStorageDirectory().getAbsolutePath());
long blockSize = statFs.getBlockSize();
long freeSize = statFs.getFreeBlocks()*blockSize;
try
{
if(!((freeSize-dfile.length())<0))
{
SmbFileInputStream din=new SmbFileInputStream(dfile);
FileOutputStream dout=new FileOutputStream(dpath);
int c;
while((c=din.read())!=-1)
{
dout.write(c);
}
if (din != null)
{
din.close();
}
if (dout != null)
{
dout.close();
}
}
else
{
Toast.makeText(context, "AccessPC Download Task failed ",Toast.LENGTH_LONG).show();
}
}
catch(Exception e)
{
Toast.makeText(context, "AccessPC Download Task failed "+e,Toast.LENGTH_LONG).show();
}
}
void downloadFolder(SmbFile dfolder,String dfolderpath)
{
try
{
dfolderpath=dfolderpath+dfolder.getName();
if(!(new File(dfolderpath)).exists())
{
(new File(dfolderpath)).mkdir();
}
SmbFile[] temp=dfolder.listFiles();
if(temp.length==0)
{
Toast.makeText(context, "df,downstate="+downstate,Toast.LENGTH_LONG).show();
return;
}
for(SmbFile m:temp)
{
if(m.isFile())
{
downloadFile(m,dfolderpath+m.getName());
}
else
{
downloadFolder(m,dfolderpath);
}
}
}
catch (Exception e)
{
Toast.makeText(context, "AccessPC Download Task failed "+e,Toast.LENGTH_LONG).show();
}
}
void uploadFile(File ufile,SmbFile ufilesmb)
{
try
{
FileInputStream uin=new FileInputStream(ufile);
SmbFile tempSmb=new SmbFile(ufilesmb.getPath()+ufile.getName(),auth);
SmbFileOutputStream uout=new SmbFileOutputStream(tempSmb);
int c;
while((c=uin.read())!=-1)
{
uout.write(c);
}
if (uin != null)
{
uin.close();
}
if (uout != null)
{
uout.close();
}
}
catch(Exception e)
{
Toast.makeText(context, "AccessPC Upload Task failed "+e, Toast.LENGTH_LONG).show();
}
}
void uploadFolder(File ufolder,SmbFile ufoldersmb)
{
try
{
SmbFile tempSmb=new SmbFile(ufoldersmb.getPath()+ufolder.getName()+"/",auth);
if(!tempSmb.exists())
{
tempSmb.mkdir();
}
File[] ftemp=ufolder.listFiles();
if(ftemp.length==0)
{
setupstate(2);
return;
}
for(File m:ftemp)
{
if(m.isFile())
{
uploadFile(m,tempSmb);
}
else
{
uploadFolder(m,tempSmb);
}
}
}
catch (Exception e)
{
Toast.makeText(context, "AccessPC Upload Task failed "+e,Toast.LENGTH_LONG).show();
}
}
void downloadTask()
{
Toast.makeText(context, "AccessPC download task "+tasknumber+" Started", Toast.LENGTH_LONG).show();
try
{
for(SmbFile m:smbArray)
{
if(m.isFile())
{
setdfile(m);
setdfilepath(ext+m.getName());
downloadFile(dfile,dfilepath);
}
else
{
setdfolder(m);
setdfolderpath(ext);
downloadFolder(dfolder,dfolderpath);
}
}
setdownstate(2);
}
catch (Exception e)
{
Toast.makeText(context,"Download error "+e,Toast.LENGTH_LONG).show();
}
}
#Override
protected void onPostExecute(Void result)
{
if(upstate==2)
{
setupstate(0);
Toast.makeText(context, "AccessPC "+taskname+" task "+tasknumber+" Finished", Toast.LENGTH_LONG).show();
}
if(downstate==2)
{
setdownstate(0);
Toast.makeText(context, "AccessPC "+taskname+" task "+tasknumber+" Finished", Toast.LENGTH_LONG).show();
}
}
}
This is my options menu. I ve used this to do my asyn task
variable i have used in my main activity which helps this task:
String extStorage=Environment.getExternalStorageDirectory()+"/t/";
ArrayList<Helper> helpobject=new ArrayList<Helper>();
int uptask=0;
int downtask=0;
public boolean onOptionsItemSelected(MenuItem item)
{
switch(item.getItemId())
{
case DOWNLOAD1:
MENU_STATE=MENU_DOWNLOAD;
map=display_check(current);
return true;
case UPLOAD:
if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED))
{
if(current.getShare()==null)
{
Toast.makeText(this,"UPLOAD FAILED",Toast.LENGTH_LONG).show();
}
else
{
File f=new File(extStorage);
Helper help=new Helper();
help.setufolder(f);
help.setufoldersmb(current);
help.setauthentication(auth);
help.setupstate(1);
help.settasknumber(uptask);
uptask++;
help.settaskname("Upload");
help.setcontext(this.getApplicationContext());
help.execute(1);
}
}
else
{
Toast.makeText(this,"UPLOAD FAILED--NO SD CARD FOUND",Toast.LENGTH_LONG).show();
}
return true;
case DELETE1:
MENU_STATE=MENU_DELETE;
map=display_check(current);
return true;
case QUIT:
int x=0;
for(Helper k:helpobject)
{
if(k.getStatus().equals(AsyncTask.Status.RUNNING)||k.getStatus().equals(AsyncTask.Status.RUNNING))
{
Toast.makeText(k.getcontext(), "AccessPC "+k.gettaskname()+" "+k.gettasknumber()+" Cancelled", Toast.LENGTH_SHORT).show();
k.cancel(true);
}
helpobject.remove(x);
x++;
}
return true;
case DOWNLOAD2:
if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED))
{
int tempcount=0;
for(int i=0;i<object.getCount();i++)
{
if(object.getter(i)==true)
{
tempcount++;
}
}
if(tempcount==0)
{
Toast.makeText(this,"Please choose atleast one item for download!!",Toast.LENGTH_LONG).show();
}
else
{
Helper help=new Helper();
helpobject.add(help);
help.settasknumber(downtask);
downtask++;
help.settaskname("Download");
help.setcontext(this.getApplicationContext());
help.setextstorage(extStorage);
help.setdownstate(1);
for(int i=0;i<object.getCount();i++)
{
if(object.getter(i)==true)
{
help.setarraysmb(map.get(object.getItem(i)));
}
}
help.execute(0);
}
}
else
{
Toast.makeText(this,"DOWNLOAD FAILED--NO SD CARD FOUND",Toast.LENGTH_LONG).show();
}
return true;
case DELETE2:
for(int i=0;i<object.getCount();i++)
{
if(object.getter(i)==true)
{
try
{
map.get(object.getItem(i)).delete();
}
catch (Exception e)
{
Toast.makeText(this,"cannot be deleted "+e,Toast.LENGTH_LONG).show();
}
}
}
return true;
case CANCEL:
MENU_STATE=MENU_GENERAL;
map=display(current);
return true;
case FINISH:
finish();
default:
return super.onOptionsItemSelected(item);
}
}
hi,when i tried to display the toast, as mentioned in one of the below comments, ive got the same exception .please see the code below whih i ve used to dispaly Toast in my async task:
(new Activity()).runOnUiThread(new Runnable(){#Override public void run() {//Your Toast
Toast.makeText(context, "AccessPC Download Task failed ",Toast.LENGTH_LONG).show();
}});
Do i need to make any changes to my async task code or options menu code?
I ve used handler like this:
public Handler handler = new Handler() {
public void handleMessage(Message msg)
{
Bundle b = msg.getData();
String key = b.getString(null);
Toast.makeText(getApplicationContext(),key, Toast.LENGTH_SHORT).show();
}
};
and i am calling handler like this:
Message msg = new Message();
Bundle b = new Bundle();
b.putString(null, "AccessPC "+taskname+" task "+tasknumber+" Finished");
msg.setData(b);
//this is error
t.handler.sendMessage(msg);
But how can i call a non-static method?do i need to create an object for my main class(class t extends list activity)?
Hi, please see another exception that ive got when i select 'QUIT' operation from options menu for the above async task and menu ive posted. how to avoid this exception:
05-07 16:24:07.573: E/AndroidRuntime(13466): FATAL EXCEPTION: main
05-07 16:24:07.573: E/AndroidRuntime(13466): java.util.ConcurrentModificationException
05-07 16:24:07.573: E/AndroidRuntime(13466): at java.util.ArrayList$ArrayListIterator.next(ArrayList.java:576)
05-07 16:24:07.573: E/AndroidRuntime(13466): at com.android.test.t.onOptionsItemSelected(t.java:622)
05-07 16:24:07.573: E/AndroidRuntime(13466): at android.app.Activity.onMenuItemSelected(Activity.java:2205)
05-07 16:24:07.573: E/AndroidRuntime(13466): at com.android.internal.policy.impl.PhoneWindow.onMenuItemSelected(PhoneWindow.java:748)
05-07 16:24:07.573: E/AndroidRuntime(13466): at com.android.internal.view.menu.MenuItemImpl.invoke(MenuItemImpl.java:143)
05-07 16:24:07.573: E/AndroidRuntime(13466): at com.android.internal.view.menu.MenuBuilder.performItemAction(MenuBuilder.java:855)
05-07 16:24:07.573: E/AndroidRuntime(13466): at com.android.internal.view.menu.IconMenuView.invokeItem(IconMenuView.java:532)
05-07 16:24:07.573: E/AndroidRuntime(13466): at com.android.internal.view.menu.IconMenuItemView.performClick(IconMenuItemView.java:122)
05-07 16:24:07.573: E/AndroidRuntime(13466): at android.view.View$PerformClick.run(View.java:9080)
05-07 16:24:07.573: E/AndroidRuntime(13466): at android.os.Handler.handleCallback(Handler.java:587)
05-07 16:24:07.573: E/AndroidRuntime(13466): at android.os.Handler.dispatchMessage(Handler.java:92)
05-07 16:24:07.573: E/AndroidRuntime(13466): at android.os.Looper.loop(Looper.java:123)
05-07 16:24:07.573: E/AndroidRuntime(13466): at android.app.ActivityThread.main(ActivityThread.java:3683)
05-07 16:24:07.573: E/AndroidRuntime(13466): at java.lang.reflect.Method.invokeNative(Native Method)
05-07 16:24:07.573: E/AndroidRuntime(13466): at java.lang.reflect.Method.invoke(Method.java:507)
05-07 16:24:07.573: E/AndroidRuntime(13466): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
05-07 16:24:07.573: E/AndroidRuntime(13466): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
05-07 16:24:07.573: E/AndroidRuntime(13466): at dalvik.system.NativeStart.main(Native Method)
Can't create handler inside thread that has not called Looper.prepare(), the error message is rather straightforward.
You created a Handler object in your AsyncTask.doInBackground()(a background thread), which requires a message pump in that thread, that's the Looper.prepare() thing.
I think it may be easier to just move the creation of your Handler object out of AysncTask, to the UI thread.
Below is the edit after the OP edited his/her question
Toast.makeText(context, "AccessPC Upload task "+tasknumber+" Started", Toast.LENGTH_LONG).show();
The line above is simply not allowed in a background thread, showing a Toast message is something updating the UI, which must happen in the UI thread.
EDIT again
You can use a Handler, which is created in the UI thread, to send a message, and in the Handler, handle that message by showing your desired Toast message.
EDIT again 2
private final static int TOAST_MSG_ID_1 = 1;
private final static int TOAST_MSG_ID_2 = 2;
private final static int TOAST_MSG_ID_3 = 3;
// declare a Handler as an instance variable
Handler msgHandler = new Handler(){
#Override
public void handleMessage(Message msg) {
switch(msg.what()) {
case TOAST_MSG_ID_1:
Toast.makeText(...msg1...).show();
break;
case TOAST_MSG_ID_2:
Toast.makeText(...msg2...).show();
break;
.... other messages follow....
}
}
};
// and you will use the following to show a Toast message:
msgHandler.sendEmptyMessage(TOAST_MSG_ID_1);
msgHandler.sendEmptyMessage(TOAST_MSG_ID_2);
msgHandler.sendEmptyMessage(TOAST_MSG_ID_3);
...
For more info about Handler, take a look at the javadoc first. and google will bring you more.
write Toast message as below I hope it will work.
getApplicationContext().runOnUiThread(new Runnable() {
#Override
public void run() {
//Your Toast
}
});
Comment your all Toast message which you are showing using with Non-UI thread. I think this the problem..

Categories

Resources