Sometimes i get this crash error in my app
java.lang.RuntimeException: An error occured while executing doInBackground()
This is the full logCat:
java.lang.RuntimeException: An error occured while executing doInBackground()
at android.os.AsyncTask$3.done(AsyncTask.java:200)
at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:274)
at java.util.concurrent.FutureTask.setException(FutureTask.java:125)
at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:308)
at java.util.concurrent.FutureTask.run(FutureTask.java:138)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1088)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:581)
at java.lang.Thread.run(Thread.java:1019)
Caused by: java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
at android.os.Handler.<init>(Handler.java:121)
at android.widget.Toast.<init>(Toast.java:68)
at android.widget.Toast.makeText(Toast.java:231)
at kostas.menu.olympiakos.nea.loadFeed(nea.java:84)
at kostas.menu.olympiakos.nea.access$1(nea.java:75)
at kostas.menu.olympiakos.nea$BackgroundAsyncTask_nea.doInBackground(nea.java:242)
at kostas.menu.olympiakos.nea$BackgroundAsyncTask_nea.doInBackground(nea.java:1)
at android.os.AsyncTask$2.call(AsyncTask.java:185)
at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:306)
... 4 more
and this is my .nea class code:
package kostas.menu.olympiakos;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import android.app.Dialog;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.view.animation.AnimationSet;
import android.view.animation.LayoutAnimationController;
import android.view.animation.TranslateAnimation;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;
public class nea extends ListActivity{
private List<Message> messages;
List<String> des = new ArrayList<String>();//to prosthesa gia na anoigei to keimeno sto alert
List<String> text = new ArrayList<String>();//to prosthesa gia na anoigei o titlos sto alert
List<URL> url = new ArrayList<URL>();//to prosthesa gia to koumpi pou pigainei sto link
List<String> imgl = new ArrayList<String>();//to prosthesa gia na anoigei to keimeno sto alert
@Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.main2);
if(isInternetOn()) {
new BackgroundAsyncTask_nea().execute();
}else{
Toast.makeText(nea.this,R.string.no_connection, Toast.LENGTH_SHORT).show();
finish();
}
}
private void loadFeed(AsyncTask<Void, Void, Void> asyncTask){
try{
BaseFeedParser parser = new BaseFeedParser();
messages = parser.parse();
}
catch (Throwable t){
Log.e("OSFP.News",t.getMessage(),t);
Toast.makeText(nea.this, "Χρειάζεστε σύνδεση στο internet",
Toast.LENGTH_SHORT).show();
finish();
}
}
private void displayRss(){
ArrayList<HashMap<String, String>> List_nea = new ArrayList<HashMap<String, String>>(messages.size());
for (Message msg : messages){
des.add(msg.getDescription());// keimeno
text.add(msg.getTitle());// titlos
url.add(msg.getLink());// link
imgl.add(msg.getImgLink());
HashMap<String, String> map = new HashMap<String, String>();
map.put("name", msg.getTitle());
map.put("date", msg.getDate());
List_nea.add(map);
ListAdapter mSchedule = new SimpleAdapter(this, List_nea, R.layout.row,
new String[] {"name", "date"}, new int[] {R.id.TextView01, R.id.TextView02});
this.setListAdapter(mSchedule);
}
AnimationSet set = new AnimationSet(true);
Animation animation = new AlphaAnimation(0.0f, 1.0f);
animation.setDuration(400);
set.addAnimation(animation);
animation = new TranslateAnimation(
Animation.RELATIVE_TO_SELF, 0.0f,Animation.RELATIVE_TO_SELF, 0.0f,
Animation.RELATIVE_TO_SELF, -1.0f,Animation.RELATIVE_TO_SELF, 0.0f
);
animation.setDuration(400);
set.addAnimation(animation);
LayoutAnimationController controller = new LayoutAnimationController(set, 0.5f);
ListView listViewn = getListView();
listViewn.setLayoutAnimation(controller);
}
protected void onListItemClick(ListView l, View v, final int position, long id) {
super.onListItemClick(l, v, position, id);
Dialog dialog = new Dialog(this);
String description = des.get(position).toString().replaceAll("\<.*?>","");
String imagee=imgl.get(position).toString();
final URL link = url.get(position);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setContentView(R.layout.single);
dialog.setCancelable(true);
Toast msg = Toast.makeText(nea.this, "The url is : "+imagee, Toast.LENGTH_LONG);
msg.show();
//xrisimopoiisa toast gia na elegxw poio link pernw apo to site
TextView title_dialog = (TextView) dialog.findViewById(R.id.title_dialog);
title_dialog.setText(text.get(position));
TextView text = (TextView) dialog.findViewById(R.id.descr);
text.setText(description);
ImageView image1 = (ImageView) dialog.findViewById(R.id.image1);
try {
//where imageUrl is what you pulled out from the rss feed
Bitmap bitmap = BitmapFactory.decodeStream((InputStream)new URL(imagee).getContent());
image1.setImageBitmap(bitmap);
} catch (MalformedURLException e) {
//log exception here
} catch (IOException e) {
//log exception here
}
Button btnt = (Button) dialog.findViewById(R.id.btnrss);//ti kanei to koumpi otan to patas gia to link
btnt.setOnClickListener(new View.OnClickListener() {
public void onClick (View view) {
Intent viewMessage = new Intent(Intent.ACTION_VIEW, Uri.parse(link.toExternalForm()));
startActivityForResult(viewMessage, 0);
}
});
dialog.show();
}
//options menu
@Override
public boolean onCreateOptionsMenu(Menu menu2) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu2, menu2);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.refresh:
new BackgroundAsyncTask_nea().execute();
break;
}
return true;
}
public class BackgroundAsyncTask_nea extends
AsyncTask<Void, Void, Void> {
private ProgressDialog dialog;
int myProgress;
@Override
protected void onPostExecute(Void result) {
displayRss();
dialog.dismiss();
}
@Override
protected void onPreExecute() {
// TODO Auto-generated method stub
dialog = ProgressDialog.show(nea.this, "", "Loading. Please wait...", true);
myProgress = 0;
}
protected void onProgressUpdate(Integer... progress) {
// TODO Auto-generated method stub
//super.onProgressUpdate(values);
dialog.setProgress(progress[0]);
}
@Override
protected Void doInBackground(Void... arg0) {
// TODO Auto-generated method stub
loadFeed(this);
return null;
}
}
public final boolean isInternetOn() {
ConnectivityManager connec = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
// ARE WE CONNECTED TO THE NET
if ( connec.getNetworkInfo(0).getState() == NetworkInfo.State.CONNECTED ||
connec.getNetworkInfo(0).getState() == NetworkInfo.State.CONNECTING ||
connec.getNetworkInfo(1).getState() == NetworkInfo.State.CONNECTING ||
connec.getNetworkInfo(1).getState() == NetworkInfo.State.CONNECTED ) {
// MESSAGE TO SCREEN FOR TESTING (IF REQ)
//Toast.makeText(this, connectionType + ” connected”, Toast.LENGTH_SHORT).show();
return true;
} else if ( connec.getNetworkInfo(0).getState() == NetworkInfo.State.DISCONNECTED || connec.getNetworkInfo(1).getState() == NetworkInfo.State.DISCONNECTED ) {
//System.out.println(“Not Connected”);
return false;
}
return false;
}
}
Why am i getting this error?How can i solve it?Thanks
EDIT:
Public void toast_doInBck(View view) {
// Do something long
Runnable runnable = new Runnable() {
@Override
public void run() {
for (int i = 0; i <= 10; i++) {
Toast.makeText(nea.this,R.string.no_connection, Toast.LENGTH_SHORT).show();
handler.post(new Runnable() {
@Override
public void run() {
}
});
}
}
};
new Thread(runnable).start();
}
EDIT2:
private void loadFeed(AsyncTask<Void, Void, Void> asyncTask){
try{
BaseFeedParser parser = new BaseFeedParser();
messages = parser.parse();
}
catch (Throwable t){
Log.e("OSFP.News",t.getMessage(),t);
Looper.prepare();
Toast.makeText(nea.this, "Παρακαλώ προσπαθήστε αργότερα..",
Toast.LENGTH_SHORT).show();
finish();
Looper.loop();
}
}
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and
privacy statement. We’ll occasionally send you account related emails.
Already on GitHub?
Sign in
to your account
Closed
rockerhieu opened this issue
Aug 24, 2017
· 61 comments
Assignees
Comments
Crash happened with 1.2.0-alpha3 on Pixel running 8.0.0. Here’s the stacktrace:
Fatal Exception: java.lang.RuntimeException: An error occurred while executing doInBackground()
at android.os.AsyncTask$3.done(AsyncTask.java:353)
at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:383)
at java.util.concurrent.FutureTask.setException(FutureTask.java:252)
at java.util.concurrent.FutureTask.run(FutureTask.java:271)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1162)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:636)
at java.lang.Thread.run(Thread.java:764)
Caused by java.lang.SecurityException: Caller no longer running, last stopped +25s437ms because: timed out while starting
at android.os.Parcel.readException(Parcel.java:1942)
at android.os.Parcel.readException(Parcel.java:1888)
at android.app.job.IJobCallback$Stub$Proxy.dequeueWork(IJobCallback.java:191)
at android.app.job.JobParameters.dequeueWork(JobParameters.java:196)
at android.support.v4.app.JobIntentService$JobServiceEngineImpl.dequeueWork(JobIntentService.java:309)
at android.support.v4.app.JobIntentService.dequeueWork(JobIntentService.java:627)
at android.support.v4.app.JobIntentService$CommandProcessor.doInBackground(JobIntentService.java:384)
at android.support.v4.app.JobIntentService$CommandProcessor.doInBackground(JobIntentService.java:377)
at android.os.AsyncTask$2.call(AsyncTask.java:333)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1162)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:636)
at java.lang.Thread.run(Thread.java:764)
Closing because of inactivity.
Issue still present as of 1.2.0-RC3
.
Issue, maybe not the same but similar is still present in 1.2.0:
Fatal Exception: java.lang.RuntimeException: An error occurred while executing doInBackground()
at android.os.AsyncTask$3.done(AsyncTask.java:353)
at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:383)
at java.util.concurrent.FutureTask.setException(FutureTask.java:252)
at java.util.concurrent.FutureTask.run(FutureTask.java:271)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1162)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:636)
at java.lang.Thread.run(Thread.java:764)
Caused by java.lang.SecurityException: Caller no longer running, last stopped +663ms because: timed out while starting
at android.os.Parcel.readException(Parcel.java:1942)
at android.os.Parcel.readException(Parcel.java:1888)
at android.app.job.IJobCallback$Stub$Proxy.dequeueWork(IJobCallback.java:191)
at android.app.job.JobParameters.dequeueWork(JobParameters.java:196)
at android.support.v4.app.JobIntentService$JobServiceEngineImpl.dequeueWork(JobIntentService.java:314)
at android.support.v4.app.JobIntentService.dequeueWork(JobIntentService.java:639)
at android.support.v4.app.JobIntentService$CommandProcessor.doInBackground(JobIntentService.java:389)
at android.support.v4.app.JobIntentService$CommandProcessor.doInBackground(JobIntentService.java:382)
at android.os.AsyncTask$2.call(AsyncTask.java:333)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1162)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:636)
at java.lang.Thread.run(Thread.java:764)
My question is, is this a long running job issue? I can’t find limits stated anywhere for jobs, but guessing they exist? And this is a problem as I’m doing network communication and timeouts would cause havoc on run length limits…
@KennyGoers Which version of the support library are you using? My problems went away when I upgraded from the beta version to the production version.
This is in the 26.1.0 version, build with the 3.0 Android Studio and I haven’t seen the problem myself with a Nexus 5X with 8.0 and not 8.1, only shows with my users in Fabric and it’s pretty common there. I don’t know if it just happens occasionally and reruns later or continually.
I’ve had over 127 users with this crash with production code. This error, closed, it should not be.
Can you please file a ticket at b.android.com? That’s an issue in the support library. Thanks.
Caused by java.lang.SecurityException: Caller no longer running, last stopped +1s803ms because: unexpectedly disconnected
at android.os.Parcel.readException(Unknown Source:69)
at android.os.Parcel.readException(Unknown Source:10)
at android.app.job.IJobCallback$Stub$Proxy.completeWork(Unknown Source:29)
at android.app.job.JobParameters.completeWork(Unknown Source:12)
at android.support.v4.app.JobIntentService$JobServiceEngineImpl$WrapperWorkItem.complete(JobIntentService.java:267)
at android.support.v4.app.JobIntentService$CommandProcessor.doInBackground(JobIntentService.java:393)
at android.support.v4.app.JobIntentService$CommandProcessor.doInBackground(JobIntentService.java:382)
at android.os.AsyncTask$2.call(Unknown Source:22)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1162)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:636)
at java.lang.Thread.run(Thread.java:764)
java.lang.RuntimeException: An error occurred while executing doInBackground()
at android.os.AsyncTask$3.done(AsyncTask.java:353)
at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:383)
at java.util.concurrent.FutureTask.setException(FutureTask.java:252)
at java.util.concurrent.FutureTask.run(FutureTask.java:271)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1162)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:636)
at java.lang.Thread.run(Thread.java:764)
Caused by: java.lang.SecurityException: Caller no longer running, last stopped +2s519ms because: timed out while starting
at android.os.Parcel.readException(Parcel.java:2004)
at android.os.Parcel.readException(Parcel.java:1950)
at android.app.job.IJobCallback$Stub$Proxy.dequeueWork(IJobCallback.java:191)
at android.app.job.JobParameters.dequeueWork(JobParameters.java:208)
at android.support.v4.app.JobIntentService$f.b(SourceFile:314)
at android.support.v4.app.JobIntentService.d(SourceFile:639)
at android.support.v4.app.JobIntentService$a.a(SourceFile:389)
at android.support.v4.app.JobIntentService$a.doInBackground(SourceFile:382)
at android.os.AsyncTask$2.call(AsyncTask.java:333)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
... 3 more
java.lang.SecurityException: Caller no longer running, last stopped +2s519ms because: timed out while starting
at android.os.Parcel.readException(Parcel.java:2004)
at android.os.Parcel.readException(Parcel.java:1950)
at android.app.job.IJobCallback$Stub$Proxy.dequeueWork(IJobCallback.java:191)
at android.app.job.JobParameters.dequeueWork(JobParameters.java:208)
at android.support.v4.app.JobIntentService$f.b(SourceFile:314)
at android.support.v4.app.JobIntentService.d(SourceFile:639)
at android.support.v4.app.JobIntentService$a.a(SourceFile:389)
at android.support.v4.app.JobIntentService$a.doInBackground(SourceFile:382)
at android.os.AsyncTask$2.call(AsyncTask.java:333)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1162)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:636)
at java.lang.Thread.run(Thread.java:764)
That fix would be sufficient for us. We’re seeing this as one of our top crashes in an app with widespread use as well, increasing each day the more users that onboard via O.
We’re seeing this issue with a high number of crashes +100K.
I have experienced this crash using android-job version 1.2.5. Downgraded it to 1.2.2 and the issue was gone.
@henriquenfaria this is not fixing it. We have this exact issue as far back as 1.2.1.
I am wondering that JobScheduler really have timeout.
Interestingly, only seeing this issue reported from HUAWEI devices. Anyone else seeing that?
We see it on all kinds of devices. We’re in the 1000s of users with this crash.
Our spread is:
Samsung 55%
Google 17%
HMD Global 12%
Huawei 4%
Other… 12%
From what we can tell yigit’s job library doesn’t have this issue, so we are experimenting with moving off the evernote library since it’s getting to be a year with this issue at large.
https://github.com/yigit/android-priority-jobqueue
I’ve found a way for me to reproduce this crash. I only need to start debug from Android Studio for my app.
Always getting
Caused by: java.lang.SecurityException: Caller no longer running, last stopped +12s589ms because: timed out while starting
I hope this helps to find a solution for this. I’m willing to investigate if anyone wants me to try something.
I can also confirm that this crash happens occasionally across all kind of devices. Unfortunately I also couldn’t find a way to reliably reproduce the issue…
EDIT: @Jeff11 how did you reproduce the issue? Can you please provide all steps?
@Agraphie I just needed to start the app with the debugger from Android Studio and would get this crash. My app has a rather big Application class and JobManager.create(this) is in onCreate().
Strangely, the crash is not happening anymore when starting the debugger.
has anyone find solution ? I am facing this problem when I start app with debugger
@vRallev I understand but I can’t use something with «alpha» in its name our production app. Do you have any idea when 1.3.0 will be official / stable ?
Soonish if no errors are reported. I’m on vacation for a week, probably after that.
Hi everyone!
I’m not using android-job in my current project, but I also have this error (mostly in Huawei devices):
java.lang.RuntimeException: at android.os.AsyncTask$3.done (AsyncTask.java:365) at java.util.concurrent.FutureTask.finishCompletion (FutureTask.java:383) at java.util.concurrent.FutureTask.setException (FutureTask.java:252) at java.util.concurrent.FutureTask.run (FutureTask.java:271) at java.util.concurrent.ThreadPoolExecutor.runWorker (ThreadPoolExecutor.java:1162) at java.util.concurrent.ThreadPoolExecutor$Worker.run (ThreadPoolExecutor.java:636) at java.lang.Thread.run (Thread.java:784) Caused by: java.lang.SecurityException: at android.os.Parcel.readException (Parcel.java:1945) at android.os.Parcel.readException (Parcel.java:1891) at android.app.job.IJobCallback$Stub$Proxy.dequeueWork (IJobCallback.java:191) at android.app.job.JobParameters.dequeueWork (JobParameters.java:196) at android.support.v4.app.JobIntentService$JobServiceEngineImpl.dequeueWork (JobIntentService.java:314) at android.support.v4.app.JobIntentService.dequeueWork (JobIntentService.java:639) at android.support.v4.app.JobIntentService$CommandProcessor.doInBackground (JobIntentService.java:2389) at android.os.AsyncTask$2.call (AsyncTask.java:345) at java.util.concurrent.FutureTask.run (FutureTask.java:266)
How stable is 1.3.0-alpha06? I’m seeing this issue on Android 8 devices (LG-H870DS & Motorola G6) with version 1.2.6.
The WorkManager library is still very much alpha and has been very buggy, especially with periodic jobs. I strongly suggest staying with the default android-job implementation for now. I certainly am
Is there any solution for this issue? Because it seems that this issue occurs while using WorkManager as well.
Hi there ! Still no solution ? It’s the same for me, I can’t put your alpha version in production…
Is there any fix schedule for the 1.2 version ?
galex
added a commit
to galex/android-job
that referenced
this issue
Nov 8, 2018
ema987
added a commit
to ema987/cloudinary_android
that referenced
this issue
Nov 9, 2018
I will test 1.2.7 in our app.
Is the fix solution based on the same thing like this one?
optimizely/android-sdk#194
Seems to me, yes.
I’m curious if the above solution has been verified and if there are any plans to release 1.2.7?
A release with the fix for this would be much appreciated.
alexxxdev
pushed a commit
to alexxxdev/android-job
that referenced
this issue
Apr 17, 2019
alexxxdev
pushed a commit
to alexxxdev/android-job
that referenced
this issue
Apr 17, 2019
alexxxdev
pushed a commit
to alexxxdev/android-job
that referenced
this issue
Apr 17, 2019
Is there any solution found for below exception, I am using androidx 1.0.0
only android Oreo users facing this problem for my app
Fatal Exception: java.lang.RuntimeException: An error occurred while executing doInBackground()
at android.os.AsyncTask$3.done(AsyncTask.java:353)
at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:383)
at java.util.concurrent.FutureTask.setException(FutureTask.java:252)
at java.util.concurrent.FutureTask.run(FutureTask.java:271)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1162)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:636)
at java.lang.Thread.run(Thread.java:764)
Caused by java.lang.SecurityException: Caller no longer running, last stopped +325ms because: timed out while starting
at android.os.Parcel.readException(Parcel.java:2029)
at android.os.Parcel.readException(Parcel.java:1975)
at android.app.job.IJobCallback$Stub$Proxy.dequeueWork(IJobCallback.java:191)
at android.app.job.JobParameters.dequeueWork(JobParameters.java:208)
at androidx.core.app.JobIntentService$JobServiceEngineImpl.dequeueWork(JobIntentService.java:315)
at androidx.core.app.JobIntentService.dequeueWork(JobIntentService.java:640)
at androidx.core.app.JobIntentService$CommandProcessor.doInBackground(JobIntentService.java:390)
at androidx.core.app.JobIntentService$CommandProcessor.doInBackground(JobIntentService.java:383)
at android.os.AsyncTask$2.call(AsyncTask.java:333)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1162)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:636)
at java.lang.Thread.run(Thread.java:764)
Please help with the solution
Is there any new androidx release to solve this problem ?
Recently, a bug was added to the task list to be resolved in this sprint. The stack information of the bug is as follows:
Fatal Exception: java.lang.RuntimeException: An error occurred while executing doInBackground()
at android.os.AsyncTask$3.done(AsyncTask.java:353)
at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:383)
at java.util.concurrent.FutureTask.setException(FutureTask.java:252)
at java.util.concurrent.FutureTask.run(FutureTask.java:271)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1162)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:636)
at java.lang.Thread.run(Thread.java:764)
Caused by java.lang.SecurityException: Caller no longer running, last stopped +25s437ms because: timed out while starting
at android.os.Parcel.readException(Parcel.java:1942)
at android.os.Parcel.readException(Parcel.java:1888)
at android.app.job.IJobCallback$Stub$Proxy.dequeueWork(IJobCallback.java:191)
at android.app.job.JobParameters.dequeueWork(JobParameters.java:196)
at android.support.v4.app.JobIntentService$JobServiceEngineImpl.dequeueWork(JobIntentService.java:309)
at android.support.v4.app.JobIntentService.dequeueWork(JobIntentService.java:627)
at android.support.v4.app.JobIntentService$CommandProcessor.doInBackground(JobIntentService.java:384)
at android.support.v4.app.JobIntentService$CommandProcessor.doInBackground(JobIntentService.java:377)
at android.os.AsyncTask$2.call(AsyncTask.java:333)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1162)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:636)
at java.lang.Thread.run(Thread.java:764)
According to the above bug information, it can be known that the system JobIntentService
, AsyncTask doInBackground is called, while doInBackground
calls dequeueWork
. The following is the source code (source code of androidx 1.1.0) :
final class CommandProcessor extends AsyncTask<Void, Void, Void> {
@Override
protected Void doInBackground(Void... params) {
GenericWorkItem work;
if (DEBUG) Log.d(TAG, "Starting to dequeue work...");
while ((work = dequeueWork()) != null) {
if (DEBUG) Log.d(TAG, "Processing next work: " + work);
onHandleWork(work.getIntent());
if (DEBUG) Log.d(TAG, "Completing work: " + work);
work.complete();
}
if (DEBUG) Log.d(TAG, "Done processing work!");
return null;
}
dequeueWork()
source code is as follows, let’s focus on mJobImpl! = null
part, will enter mjobimpl.dequeuework ()
part:
GenericWorkItem dequeueWork() {
if (mJobImpl != null) {
return mJobImpl.dequeueWork();
} else {
synchronized (mCompatQueue) {
if (mCompatQueue.size() > 0) {
return mCompatQueue.remove(0);
} else {
return null;
}
}
}
}
mJobImpl
is actually a , CompatJobEngine
, source code and is the implementation class JobServiceEngineImpl
as follows:
interface CompatJobEngine {
IBinder compatGetBinder();
GenericWorkItem dequeueWork();
}
@RequiresApi(26)
static final class JobServiceEngineImpl extends JobServiceEngine
implements JobIntentService.CompatJobEngine {
@Override
public JobIntentService.GenericWorkItem dequeueWork() {
JobWorkItem work;
synchronized (mLock) {
if (mParams == null) {
return null;
}
work = mParams.dequeueWork();
}
if (work != null) {
work.getIntent().setExtrasClassLoader(mService.getClassLoader());
return new WrapperWorkItem(work);
} else {
return null;
}
}
}
As you can see from the bug information at the beginning of the article, it goes to mparams.dequeuework (); Binder
, then enter the Binder
mechanism, the source code is as follows, so we can conclude that there is a problem here, throwing an exception, but because this is part of the source code, it should not be our responsibility.
public @Nullable JobWorkItem dequeueWork() {
try {
return getCallback().dequeueWork(getJobId());
} catch (RemoteException e) {
throw e.rethrowFromSystemServer();
}
}
/** @hide */
@UnsupportedAppUsage
public IJobCallback getCallback() {
return IJobCallback.Stub.asInterface(callback);
}
After query source, found that the problem appeared in the framework layer, and there are already online issue of the problem: https://github.com/evernote/android-job/issues/255
https://issuetracker.google.com/issues/63622293 online encounter this kind of problem a lot of a lot of people, but so far, I have checked the latest Google androidx library ("androidx.core:core-ktx:1.2.0-rc01"
) and still haven’t solved this problem. App . In this package, a new class SafeJobIntentService</code b> is inserted into the
JobIntentService
. The reason for this is that the dequeueWork()
method is not public. We have to write in the same package to override its methods and fix bugs.
@RestrictTo({Scope.LIBRARY})
public abstract class SafeJobIntentService extends JobIntentService {
public SafeJobIntentService() {
}
GenericWorkItem dequeueWork() {
try {
return super.dequeueWork();//1 Here we do a try/catch operation on this method
} catch (SecurityException var2) {
var2.printStackTrace();
return null;
}
}
public void onCreate() {
super.onCreate();
if (VERSION.SDK_INT >= 26) {
this.mJobImpl = new SafeJobServiceEngineImpl(this);
} else {
this.mJobImpl = null;
}
}
}
@RequiresApi(26)
public class SafeJobServiceEngineImpl extends JobServiceEngine implements CompatJobEngine {
static final String TAG = "JobServiceEngineImpl";
static final boolean DEBUG = false;
final JobIntentService mService;
final Object mLock = new Object();
JobParameters mParams;
SafeJobServiceEngineImpl(JobIntentService service) {
super(service);
this.mService = service;
}
public IBinder compatGetBinder() {
return this.getBinder();
}
public boolean onStartJob(JobParameters params) {
this.mParams = params;
this.mService.ensureProcessorRunningLocked(false);
return true;
}
public boolean onStopJob(JobParameters params) {
boolean result = this.mService.doStopCurrentWork();
synchronized(this.mLock) {
this.mParams = null;
return result;
}
}
public GenericWorkItem dequeueWork() {
JobWorkItem work = null;
synchronized(this.mLock) {
if (this.mParams == null) {
return null;
}
try {
work = this.mParams.dequeueWork();
} catch (SecurityException var5) {
var5.printStackTrace();
}
}
if (work != null) {
work.getIntent().setExtrasClassLoader(this.mService.getClassLoader());
return new SafeJobServiceEngineImpl.WrapperWorkItem(work);
} else {
return null;
}
}
final class WrapperWorkItem implements GenericWorkItem {
final JobWorkItem mJobWork;
WrapperWorkItem(JobWorkItem jobWork) {
this.mJobWork = jobWork;
}
public Intent getIntent() {
return this.mJobWork.getIntent();
}
public void complete() {
synchronized(SafeJobServiceEngineImpl.this.mLock) {
if (SafeJobServiceEngineImpl.this.mParams != null) {
try {
SafeJobServiceEngineImpl.this.mParams.completeWork(this.mJobWork);
} catch (SecurityException | IllegalArgumentException var4) {
// 2 Here we also perform a try/catch operation on the completeWork
var4.printStackTrace();
}
}
}
}
}
}
On the basis of the source code, the above code only handles Exception
at 1
and 2</code b>. The rest of the code does not change, so we can compare the source code to see the comparison. If you have a three-party library in your project that has introduced this
SafeJobIntentService
class, but because you can't use this class of them, and you refer to such as implementation 'com.evernote:android-job:1.4.2'
library, duplicate class found in the module
. If this problem occurs, we can rename the class and follow the above code to deal with it. Hopefully Google will add a solution to this problem in future libraries.
JSON has three methods for parsing data
Java.lang.RuntimeException: Произошла ошибка во время выполнения doInBackground ()
Иногда я получаю эту ошибку при сбое в моем приложении
Это полный logCat:
И это мой код .nea class:
Почему я получаю эту ошибку? Как я могу ее решить? Спасибо 🙂
Вероятно, это потому, что вы пытаетесь отобразить что-то на doInBackground (). DoInBackground запускается в рабочем потоке, который не может выполнять какой-либо пользовательский интерфейс (включая показ Тостов, что вы делаете). Вместо этого все работы пользовательского интерфейса должны выполняться onPostExecute ().
Вы не можете работать с графическим интерфейсом в фоновом потоке. Вместо этого вы должны отправить Runnable в обработчик, созданный в потоке GUI, чтобы заставить Toast выполнить правильную нить.
EDIT: поскольку ярлык домашней работы был удален, я дам наброски, как это сделать;
- New () вверх обработчик в вашем потоке графического интерфейса (onCreate – хорошее место) и сохраните его в переменной-члене, скажем, «обработчик».
- Перемещение, показывающее ваш Toast на Runnable (анонимный класс для этого хорош)
- Чтобы показать тост, выполните handler.post () с помощью Runnable в качестве параметра. Runnable будет выполняться в потоке GUI.
Полный пример приведен в этой статье .
Вы показываете Toast в loadFeed который вызывается в doInBackground для вашей AsyncTask . Оттуда вы не должны получать доступ к пользовательскому интерфейсу.
Я думаю, что в этом кодексе Toast делает проблему для вас,
Поскольку вы пытаетесь выполнить UI operation из рабочего потока AsyncTask это никогда не будет разрешено.
UPDATE: если вы хотите что-то обновить из doInBackGround() для AsyncTask используйте publishProgress(Progress. ) и onProgressUpdate(Progress. ) .
Источник
ОБНОВЛЕНО: Android: java.lang.RuntimeException: не удалось запустить Activity ComponentInfo
UPDATE **, поэтому я сделал почти все, что было сказано ниже, и до сих пор получил эту ошибку (см. Новый файл logcat). Его разные, хотя я не знаю, как это исправить. ** Хорошо, поэтому я начинаю, поэтому я действительно не знаю, что происходит. Когда я пытаюсь запустить это приложение в эмуляторе, все это «к сожалению, это приложение остановилось». Я ищу все вопросы, подобные этому, но не смог найти ответ. Кстати, это не готовое приложение или даже даже началось, но я хочу запустить его, прежде чем продолжить. Heres the log cat file thing.
Теперь heres activty_main.xml
Затем вот файл mainActivity.java
То второе действие DisplayMessageActivity.java
И, наконец, файл mainfest
Так оно и есть. Кто-то, пожалуйста, помогите спасибо!
Я заметил одно: вы не указали правильные значения id в некоторых своих xml.
И как мудрый для ваших других деклараций id.
Вы заметите, что в вашей трассе стека он дает номер строки в вашем xml для определения местоположения ошибки.
Это может быть что-то другое. Но по существу у вас плохо сформировался xml.
Ошибка 2
Вам нужно просмотреть трассировку стека назад, чтобы найти источник вашей ошибки, тогда вы, скорее всего, найдете решение самостоятельно.
Сверху вниз вы попадете на строку MainActivity.oncreateOptionsMenu () Выше того, что вы увидите, что она пытается раздуть (ваше меню опций xml), то есть loadXmlResourceParser ()
Это не значит, что вы указываете номер строки xml, но он говорит вам, что проблема с идентификатором ресурса недействительна.
Вам нужно будет опубликовать свои варианты xml в своем вопросе, если вы хотите получить ответ. Но я посмотрю, сможешь ли ты сначала разобраться с этим. Попробуйте прокомментировать элементы и верните их, чтобы посмотреть, что сломано. Я говорю это, потому что на вопрос должен ответить только один вопрос о переполнении стека.
Есть проблемы с вашим XML – вы можете сказать по строке:
Одна вещь, которую я заметил, это то, что, когда вы объявляете атрибут android: id, он должен иметь + в нем, например:
Это связано с тем, что вы создаете идентификатор, а не только для ранее существовавшего, определенного в другом месте (например, вы можете иметь строку, например, «@ string / hello» может находиться в папке значений).
В объявлении для одного из ваших TextViews вас есть:
textSize должен быть числом или размером, например:
Источник
ОБНОВЛЕНО: Android: java.lang.RuntimeException: не удалось запустить Activity ComponentInfo
UPDATE **, поэтому я сделал почти все, что было сказано ниже, и до сих пор получил эту ошибку (см. Новый файл logcat). Его разные, хотя я не знаю, как это исправить. ** Хорошо, поэтому я начинаю, поэтому я действительно не знаю, что происходит. Когда я пытаюсь запустить это приложение в эмуляторе, все это «к сожалению, это приложение остановилось». Я ищу все вопросы, подобные этому, но не смог найти ответ. Кстати, это не готовое приложение или даже даже началось, но я хочу запустить его, прежде чем продолжить. Heres the log cat file thing.
Теперь heres activty_main.xml
Затем вот файл mainActivity.java
То второе действие DisplayMessageActivity.java
И, наконец, файл mainfest
Так оно и есть. Кто-то, пожалуйста, помогите спасибо!
Я заметил одно: вы не указали правильные значения id в некоторых своих xml.
И как мудрый для ваших других деклараций id.
Вы заметите, что в вашей трассе стека он дает номер строки в вашем xml для определения местоположения ошибки.
Это может быть что-то другое. Но по существу у вас плохо сформировался xml.
Ошибка 2
Вам нужно просмотреть трассировку стека назад, чтобы найти источник вашей ошибки, тогда вы, скорее всего, найдете решение самостоятельно.
Сверху вниз вы попадете на строку MainActivity.oncreateOptionsMenu () Выше того, что вы увидите, что она пытается раздуть (ваше меню опций xml), то есть loadXmlResourceParser ()
Это не значит, что вы указываете номер строки xml, но он говорит вам, что проблема с идентификатором ресурса недействительна.
Вам нужно будет опубликовать свои варианты xml в своем вопросе, если вы хотите получить ответ. Но я посмотрю, сможешь ли ты сначала разобраться с этим. Попробуйте прокомментировать элементы и верните их, чтобы посмотреть, что сломано. Я говорю это, потому что на вопрос должен ответить только один вопрос о переполнении стека.
Есть проблемы с вашим XML – вы можете сказать по строке:
Одна вещь, которую я заметил, это то, что, когда вы объявляете атрибут android: id, он должен иметь + в нем, например:
Это связано с тем, что вы создаете идентификатор, а не только для ранее существовавшего, определенного в другом месте (например, вы можете иметь строку, например, «@ string / hello» может находиться в папке значений).
В объявлении для одного из ваших TextViews вас есть:
textSize должен быть числом или размером, например:
Источник
Open
Issue created Mar 05, 2019 by Jesse Larner@jlarne
java.lang.RuntimeException: An error occurred while executing doInBackground
- Device OS and version: Android 8.1.0
- Device model/manufacturer: Nokia 1, TA-1056
- F-Droid version (in the About screen): 1.3.1 / 1.5.1 / 1.6_alpha 1
- F-Droid privileged extension version (if installed):
What did you do? (clear steps if possible)
I have used FDroid for a fairly brief amount of time. I cannot think of any direct action or strange settings that make this app crash repeatedly. I have attempted to clear the data and cache, uninstall, re-install, reboot, etc.. Nothing seems to help. Unfortunately I can’t clarify anymore at this point. The app has become completely unusable
What did you expect to see?
What did you see instead?
The app crashes on almost any tab about 2 min after running. It has been in the process of updating repositories.
CUSTOM_DATA=
ANDROID_VERSION=8.1.0
PACKAGE_NAME=org.fdroid.fdroid
APP_VERSION_NAME=1.3.1
STACK_TRACE=java.lang.RuntimeException: An error occurred while executing doInBackground()
at android.os.AsyncTask$3.done(AsyncTask.java:353)
at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:383)
at java.util.concurrent.FutureTask.setException(FutureTask.java:252)
at java.util.concurrent.FutureTask.run(FutureTask.java:271)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1162)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:636)
at java.lang.Thread.run(Thread.java:764)
Caused by: android.database.sqlite.SQLiteConstraintException: NOT NULL constraint failed: fdroid_installedApp.hash (code 1299)
at android.database.sqlite.SQLiteConnection.nativeExecuteForLastInsertedRowId(Native Method)
at android.database.sqlite.SQLiteConnection.executeForLastInsertedRowId(SQLiteConnection.java:783)
at android.database.sqlite.SQLiteSession.executeForLastInsertedRowId(SQLiteSession.java:788)
at android.database.sqlite.SQLiteStatement.executeInsert(SQLiteStatement.java:86)
at android.database.sqlite.SQLiteDatabase.insertWithOnConflict(SQLiteDatabase.java:1548)
at android.database.sqlite.SQLiteDatabase.replaceOrThrow(SQLiteDatabase.java:1491)
at org.fdroid.fdroid.data.InstalledAppProvider.insert(InstalledAppProvider.java:299)
at android.content.ContentProvider$Transport.insert(ContentProvider.java:266)
at android.content.ContentResolver.insert(ContentResolver.java:1539)
at org.fdroid.fdroid.data.InstalledAppProviderService.insertAppIntoDb(InstalledAppProviderService.java:313)
at org.fdroid.fdroid.data.InstalledAppProviderService.onHandleWork(InstalledAppProviderService.java:250)
at android.support.v4.app.JobIntentService$CommandProcessor.doInBackground(JobIntentService.java:391)
at android.support.v4.app.JobIntentService$CommandProcessor.doInBackground(JobIntentService.java:382)
at android.os.AsyncTask$2.call(AsyncTask.java:333)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
… 3 more
android.database.sqlite.SQLiteConstraintException: NOT NULL constraint failed: fdroid_installedApp.hash (code 1299)
at android.database.sqlite.SQLiteConnection.nativeExecuteForLastInsertedRowId(Native Method)
at android.database.sqlite.SQLiteConnection.executeForLastInsertedRowId(SQLiteConnection.java:783)
at android.database.sqlite.SQLiteSession.executeForLastInsertedRowId(SQLiteSession.java:788)
at android.database.sqlite.SQLiteStatement.executeInsert(SQLiteStatement.java:86)
at android.database.sqlite.SQLiteDatabase.insertWithOnConflict(SQLiteDatabase.java:1548)
at android.database.sqlite.SQLiteDatabase.replaceOrThrow(SQLiteDatabase.java:1491)
at org.fdroid.fdroid.data.InstalledAppProvider.insert(InstalledAppProvider.java:299)
at android.content.ContentProvider$Transport.insert(ContentProvider.java:266)
at android.content.ContentResolver.insert(ContentResolver.java:1539)
at org.fdroid.fdroid.data.InstalledAppProviderService.insertAppIntoDb(InstalledAppProviderService.java:313)
at org.fdroid.fdroid.data.InstalledAppProviderService.onHandleWork(InstalledAppProviderService.java:250)
at android.support.v4.app.JobIntentService$CommandProcessor.doInBackground(JobIntentService.java:391)
at android.support.v4.app.JobIntentService$CommandProcessor.doInBackground(JobIntentService.java:382)
at android.os.AsyncTask$2.call(AsyncTask.java:333)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1162)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:636)
at java.lang.Thread.run(Thread.java:764)
USER_COMMENT=
BRAND=Nokia
TOTAL_MEM_SIZE=5659688960
DISPLAY=0.currentSizeRange.smallest=[480,449]
0.currentSizeRange.largest=[782,751]
0.flags=FLAG_SUPPORTS_PROTECTED_BUFFERS+FLAG_SECURE
0.height=782
0.metrics.density=1.275
0.metrics.densityDpi=204
0.metrics.scaledDensity=x1.275
0.metrics.widthPixels=480
0.metrics.heightPixels=782
0.metrics.xdpi=221.672
0.metrics.ydpi=219.107
0.name=Built-in Screen
0.orientation=0
0.pixelFormat=1
0.realMetrics.density=1.275
0.realMetrics.densityDpi=204
0.realMetrics.scaledDensity=x1.275
0.realMetrics.widthPixels=480
0.realMetrics.heightPixels=854
0.realMetrics.xdpi=221.672
0.realMetrics.ydpi=219.107
0.realSize=[480,854]
0.rectSize=[0,0,480,782]
0.refreshRate=59.34
0.rotation=ROTATION_0
0.size=[480,782]
0.width=480
0.isValid=true
PRODUCT=Frontier_00WW
STACK_TRACE_HASH=7358df48
AVAILABLE_MEM_SIZE=747286528
PHONE_MODEL=Nokia 1
Edited Mar 11, 2019 by Jesse Larner
I want to get json objects from a webservice and display them in a list view but an error occurs
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Get the view from listview_main.xml
setContentView(R.layout.activity_contacte);
// Execute DownloadJSON AsyncTask
new DownloadJSON().execute();
}
// create the class DownloadJSON
private class DownloadJSON extends AsyncTask<Integer, Integer, Integer> {
@Override
protected Integer doInBackground(Integer... requests) {
// try and catch
try {
// Create an array
arraylist = new ArrayList<HashMap<String, String>>();
// Retrieve JSON Objects from the given URL address
jsonobject = JSONfunctions.getJSONfromURL("http://192.168.1.64:8080/attijarimobile.service-1/service/contacte");
for (int i = 0; i < jsonarray.length(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
jsonobject = jsonarray.getJSONObject(i);
// Retrive JSON Objects
map.put("nomagence", jsonobject.getString("nomagence"));
map.put("adresse", jsonobject.getString("adresse"));
map.put("tel", jsonobject.getString("tel"));
map.put("mail", jsonobject.getString("mail"));
// Set the JSON Objects into the array
arraylist.add(map);
}
} // catch
catch (JSONException e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return 0;
}
}
this is the logcat
04-28 09:07:44.468 8648-9077/attijari.com.attijarimobileapp E/log_tag﹕ Error parsing data org.json.JSONException: Value [{"id":1,"mail":"[email protected]","adresse":" AGENCE KHEIREDDINE, Avenue Habib Bourguiba,La Goulette ,2060tunis","nomagence":"AGENCE KHEIREDDINE","tel":"(+216) 71 730 373/71 730 374"},{"id":2,"mail":"[email protected]","adresse":"53, AVENUE DE PARIS CP 1000 - Tunis","nomagence":"LE PASSAGE","tel":"(+216) 71 342278"},{"id":3,"mail":"[email protected]","adresse":" AGENCE CHARGUIA AEROPORT; rue des des entrepreneurs Immeuble Hertz, Z.I charguia2 ,2035tunis","nomagence":"AGENCE CHARGUIA AEROPORT","tel":"(+216) 71 941 855/71 941 844"},{"id":4,"mail":"[email protected]","adresse":" AGENCE EL MANAR ; 16 avenue abdelaziz al saoud el manar2 ,2092 el manar2","nomagence":"AGENCE EL MANAR","tel":"(+216) 71 871 731/71 888 024"},{"id":5,"mail":"[email protected]","adresse":" IMMEUBLE AZIZ, RUE 8368 MONTPLAISIR CP 1073 - Tunis","nomagence":"MONTPLAISIR","tel":"(+216) 71 950 913/71 950 414"},{"id":6,"mail":"[email protected]","adresse":"RUE DU LAC ANNECY CP 1053 - Tunis","nomagence":"LES BERGES DU LAC","tel":"(+216) 71 964 654"},{"id":7,"mail":"[email protected]","adresse":"RESIDENCE ESPLANADE AVENUE HABIB BOURGUIBA CP 2007 - Marsa Plage","nomagence":"LA MARSA","tel":"(+216) 71 729 481"},{"id":8,"mail":"[email protected]","adresse":"ANGLE DE AVENUE FETHI ZOUHEIR ET RUE DE PALESTINE CP 2083 - Ariana","nomagence":"EL GHAZELA","tel":"(+216) 71 877 716"},{"id":9,"mail":"[email protected]","adresse":"9, AVENUE HABIB BOURGUIBA CP 2080 - Ariana","nomagence":"ARIANA","tel":"(+216) 71 710 305"},{"id":10,"mail":"[email protected]","adresse":"39 BIS AVENUE HEDI NOUIRA CP 2037 - Ariana","nomagence":"ENNASR II","tel":"(+216) 70 830 012"},{"id":11,"mail":"[email protected]","adresse":" ANGLE DE L AVENUE DE L'UMA ET RUE EL MOEZ IBN BADIS CP 2036 - Ariana","nomagence":"SOUKRA","tel":"(+216) 70 696 150/70 696 081"}] of type org.json.JSONArray cannot be converted to JSONObject
04-28 09:07:44.538 8648-9077/attijari.com.attijarimobileapp 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:856)
Caused by: java.lang.NullPointerException
at attijari.com.attijarimobileapp.Agences$DownloadJSON.doInBackground(Agences.java:89)
at attijari.com.attijarimobileapp.Agences$DownloadJSON.doInBackground(Agences.java:61)
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:856)
I can’t see jsonarray
declaration or initialization. So you need to change your code :
try {
// Create an array
arraylist = new ArrayList<HashMap<String, String>>();
// Retrieve JSON Objects from the given URL address
jsonobject = JSONfunctions.getJSONfromURL("http://192.168.1.64:8080/attijarimobile.service-1/service/contacte");
JSONArray jsonarray = jsonobject.getJSONArray("Value");
for (int i = 0; i < jsonarray.length(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
jsonobject = jsonarray.getJSONObject(i);
// Retrive JSON Objects
map.put("nomagence", jsonobject.getString("nomagence"));
map.put("adresse", jsonobject.getString("adresse"));
map.put("tel", jsonobject.getString("tel"));
map.put("mail", jsonobject.getString("mail"));
// Set the JSON Objects into the array
arraylist.add(map);
}
} // catch
catch (JSONException e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
If you have already declared jsonArray
then just write this
jsonarray = jsonobject.getJSONArray("Value");
Хочу вывести данные с хостинга MySQL в приложение Android, но при старте приложение крашится и вываливается ошибка.
Код главной активити:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;
public class MainActivity extends Activity {
private String jsonResult;
private String url = "http://cpriyankara.coolpage.biz/employee_details.php";
private ListView listView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = (ListView) findViewById(R.id.listView1);
accessWebService();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
// Async Task to access the web
private class JsonReadTask extends AsyncTask<String, Void, String> {
@Override
protected String doInBackground(String... params) {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(params[0]);
try {
HttpResponse response = httpclient.execute(httppost);
jsonResult = inputStreamToString(
response.getEntity().getContent()).toString();
}
catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
private StringBuilder inputStreamToString(InputStream is) {
String rLine = "";
StringBuilder answer = new StringBuilder();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
try {
while ((rLine = rd.readLine()) != null) {
answer.append(rLine);
}
}
catch (IOException e) {
// e.printStackTrace();
Toast.makeText(getApplicationContext(),
"Error..." + e.toString(), Toast.LENGTH_LONG).show();
}
return answer;
}
@Override
protected void onPostExecute(String result) {
ListDrwaer();
}
}// end async task
public void accessWebService() {
JsonReadTask task = new JsonReadTask();
// passes values for the urls string array
task.execute(new String[] { url });
}
// build hash set for list view
public void ListDrwaer() {
List<Map<String, String>> employeeList = new ArrayList<Map<String, String>>();
try {
JSONObject jsonResponse = new JSONObject(jsonResult);
JSONArray jsonMainNode = jsonResponse.optJSONArray("emp_info");
for (int i = 0; i < jsonMainNode.length(); i++) {
JSONObject jsonChildNode = jsonMainNode.getJSONObject(i);
String name = jsonChildNode.optString("employee name");
String number = jsonChildNode.optString("employee no");
String outPut = name + "-" + number;
employeeList.add(createEmployee("employees", outPut));
}
} catch (JSONException e) {
Toast.makeText(getApplicationContext(), "Error" + e.toString(),
Toast.LENGTH_SHORT).show();
}
SimpleAdapter simpleAdapter = new SimpleAdapter(this, employeeList,
android.R.layout.simple_list_item_1,
new String[] { "employees" }, new int[] { android.R.id.text1 });
listView.setAdapter(simpleAdapter);
Toast.makeText(getApplication(), "c", Toast.LENGTH_SHORT).show();
}
private HashMap<String, String> createEmployee(String name, String number) {
HashMap<String, String> employeeNameNo = new HashMap<String, String>();
employeeNameNo.put(name, number);
return employeeNameNo;
}
}
А вот листинг ошибки:
HostConnection::get() New Host Connection established 0xaff4a5f0, tid 19118
07-26 07:39:42.075 19118-19162/devbyte.grinvichkino E/AndroidRuntime: FATAL EXCEPTION: AsyncTask #1
Process: devbyte.grinvichkino, PID: 19118
java.lang.RuntimeException: An error occurred while executing doInBackground()
markOneDEr 0 / 0 / 0 Регистрация: 20.01.2018 Сообщений: 17 |
||||
1 |
||||
17.02.2018, 20:58. Показов 6267. Ответов 6 Метки нет (Все метки)
ХЗ из за чего это кто может это расшифровать ? FATAL EXCEPTION: AsyncTask #3 Добавлено через 18 минут
Вроде все работает но иногда приложение вылетает при запуске… Ну и выше код ошибки , но расшифровать его не могу.
__________________
0 |
1560 / 1161 / 423 Регистрация: 08.05.2012 Сообщений: 5,207 |
|
17.02.2018, 23:04 |
2 |
Ошибка тут:
Underlying input stream returned zero bytes
0 |
0 / 0 / 0 Регистрация: 20.01.2018 Сообщений: 17 |
|
18.02.2018, 09:24 [ТС] |
3 |
protected String doInBackground(String… arg) { } catch (IOException e) { Как можно это исправить ?
0 |
11 / 10 / 1 Регистрация: 09.08.2017 Сообщений: 62 |
|
18.02.2018, 11:57 |
4 |
да ты шутишь, просто подумай. У тебя функция, тип возвращаемого значения — String. А что возвращаешь ты? — null. Вообще код у тебя странный, в postExecute ты никак этот самый String не используешь, тогда зачем он тебе?
0 |
markOneDEr 0 / 0 / 0 Регистрация: 20.01.2018 Сообщений: 17 |
||||
18.02.2018, 12:39 [ТС] |
5 |
|||
Тогда так будет правильнее ?
0 |
Pablito 2882 / 2294 / 769 Регистрация: 12.05.2014 Сообщений: 7,978 |
||||
19.02.2018, 11:42 |
6 |
|||
вангую, что виноваты эти убогие строки
идешь отладчиком или расставляешь после каждой строки логи и смотришь что там
Тогда так будет правильнее ? нет, не будет
0 |
0 / 0 / 0 Регистрация: 20.01.2018 Сообщений: 17 |
|
19.02.2018, 13:41 [ТС] |
7 |
вангую, что виноваты эти убогие строки Тут я решил немного подстраховаться.
0 |