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");
Related
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();
}
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.
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.
ProgressBar in AsyncTask causes crash. This code essentially loads an image from a URL, and while doing so shows a progress spinner. The first image in the group loads fine, but following that the app crashes.
public class LoadImageTask extends AsyncTask<String, Void, Bitmap> {
ImageView bmImage;
ProgressBar progressBar;
public LoadImageTask(ImageView bmImage, ProgressBar progressBar) {
this.bmImage = bmImage;
this.progressBar = progressBar;
}
protected Bitmap doInBackground(String... urls) {
progressBar.setVisibility(View.VISIBLE);
String urldisplay = urls[0];
Bitmap scaledImage = null;
try {
InputStream in = new java.net.URL(urldisplay).openStream();
Bitmap image = BitmapFactory.decodeStream(in);
scaledImage = Bitmap.createScaledBitmap(image, 380, 250, false);
} catch (Exception e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return scaledImage;
}
protected void onPostExecute(Bitmap result) {
progressBar.setVisibility(View.GONE);
bmImage.setImageBitmap(result);
}
}
Console printout:
02-03 02:45:44.014 24125-24375/simplewall.ryandushane.com.simplewall E/AndroidRuntime﹕ FATAL EXCEPTION: AsyncTask #5
Process: simplewall.ryandushane.com.simplewall, PID: 24125
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.requestLayout(ViewRootImpl.java:867)
at android.view.View.requestLayout(View.java:17364)
at android.view.View.requestLayout(View.java:17364)
at android.view.View.requestLayout(View.java:17364)
at android.view.View.requestLayout(View.java:17364)
at android.view.View.requestLayout(View.java:17364)
at android.view.View.requestLayout(View.java:17364)
at android.widget.RelativeLayout.requestLayout(RelativeLayout.java:360)
at android.view.View.requestLayout(View.java:17364)
at android.widget.AbsListView.requestLayout(AbsListView.java:1975)
at android.view.View.requestLayout(View.java:17364)
at android.widget.RelativeLayout.requestLayout(RelativeLayout.java:360)
at android.view.View.requestLayout(View.java:17364)
at android.view.View.setFlags(View.java:9633)
at android.view.View.setVisibility(View.java:6663)
at android.widget.ProgressBar.setVisibility(ProgressBar.java:1563)
at simplewall.ryandushane.com.simplewall.LoadImageTask.doInBackground(LoadImageTask.java:27)
at simplewall.ryandushane.com.simplewall.LoadImageTask.doInBackground(LoadImageTask.java:17)
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)
CalledFromWrongThreadException: Only the original thread that created
a view hierarchy can touch its views
Because you are calling progressBar.setVisibility method from doInBackground which run on non-ui thread.
Override onPreExecute() method of AsyncTask which run on Main UI Thread to change Visibility of progress bar:
#Override
protected void onPreExecute() {
progressBar.setVisibility(View.VISIBLE);
}
You cannot set progressBar.setVisibility(View.VISIBLE); in doInBackground. its a different thread
or
protected Bitmap doInBackground(String... urls) {
runOnUiThread (new Runnable () {
#Override
public void run () {
progressBar.setVisibility(View.VISIBLE);
}
});
String urldisplay = urls[0];
Bitmap scaledImage = null;
try {
InputStream in = new java.net.URL(urldisplay).openStream();
Bitmap image = BitmapFactory.decodeStream(in);
scaledImage = Bitmap.createScaledBitmap(image, 380, 250, false);
} catch (Exception e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return scaledImage;
}
Move progressBar.setVisibility(View.VISIBLE); in onPreExecute
Put this progressBar.setVisibility(View.VISIBLE) in onPreExecute() method of AsyncTask and remove this line from doInBackground method.
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
}
}