I am closing an activity via finish().
It works fine on several devices but on a Samsung Galaxy S3 Neo running Android 4.4 I get the following issue:
java.lang.RuntimeException
android.app.ActivityThread.performDestroyActivity(ActivityThread.java:3706)
android.app.ActivityThread.handleDestroyActivity(ActivityThread.java:3724)
android.app.ActivityThread.access$1500(ActivityThread.java:169)
android.app.ActivityThread$H.handleMessage(ActivityThread.java:1330)
android.os.Handler.dispatchMessage(Handler.java:102)
android.os.Looper.loop(Looper.java:136)
android.app.ActivityThread.main(ActivityThread.java:5476)
java.lang.reflect.Method.invokeNative(Native Method)
java.lang.reflect.Method.invoke(Method.java:515)
com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1283)
com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1099)
dalvik.system.NativeStart.main(Native Method)
Caused by: android.util.Log.println_native(Native Method)
android.util.Log.e(Log.java:307)
com.ads.adstimer.fragment.Registration.RegistrationActivity.onDestroy(RegistrationActivity.java:214)
android.app.Activity.performDestroy(Activity.java:5623)
android.app.Instrumentation.callActivityOnDestroy(Instrumentation.java:1123)
android.app.ActivityThread.performDestroyActivity(ActivityThread.java:3693)
android.app.ActivityThread.handleDestroyActivity(ActivityThread.java:3724)
android.app.ActivityThread.access$1500(ActivityThread.java:169)
android.app.ActivityThread$H.handleMessage(ActivityThread.java:1330)
android.os.Handler.dispatchMessage(Handler.java:102)
android.os.Looper.loop(Looper.java:136)
android.app.ActivityThread.main(ActivityThread.java:5476)
java.lang.reflect.Method.invokeNative(Native Method)
java.lang.reflect.Method.invoke(Method.java:515)
com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1283)
com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1099)
dalvik.system.NativeStart.main(Native Method)
I have found two posts about that subject: First, Second
But they did not help me.
My activity code. Note that I am using AppIntro:
public class RegistrationActivity extends AppIntro {
private AsyncTaskRegisterInBackground registerPushToken;
(...)
#Override
public void onDonePressed() {
(...)
if (regid.isEmpty()) {
registerPushToken = new AsyncTaskRegisterInBackground();
registerPushToken.setParams(activity, gcm, regid);
registerPushToken.execute();
}
(...)
}
#Override
public void onTaskCompleted(String responseRegid) {
try {
// load authToken from Server: JsonObjectRequest
builderOnFailureDialog = new MaterialDialog.Builder(activity)
.title(getResources().getString(R.string.registrierung_dialog_registrieren_failure_retry_title))
.content(onFailureDialogContent)
.positiveText(getResources().getString(R.string.registrierung_dialog_registrieren_failure_retry_positive_text))
.negativeText(getResources().getString(R.string.registrierung_dialog_registrieren_failure_retry_negative_text))
.onNegative(new MaterialDialog.SingleButtonCallback() {
#Override
public void onClick(#NonNull MaterialDialog dialog, #NonNull DialogAction which) {
activity.finish();
}
});
} catch (JSONException e) {
e.printStackTrace();
}
}
#Override
protected void onDestroy() {
super.onDestroy();
try {
onFailureDialog.dismiss();
onSuccessDialog.dismiss();
} catch (Exception e) {
Log.e("Activity.onDestroy()", e.getMessage());
}
}
}
Or is the reason for the problem the async task running in background?
call finish() inside runOnUiThread().
i.e.
replace
finish();
with
runOnUiThread(new Runnable() {
public void run() {
finish()
}
});
When i run my application i get unfortunately stop app message, following is my code. Please take a look.
#Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.dublayout);
outputFile = Environment.getExternalStorageDirectory().
getAbsolutePath() + "/javacodegeeksRecording.3gpp";
myRecorder = new MediaRecorder();
myRecorder.setAudioSource(MediaRecorder.AudioSource.DEFAULT);
myRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
myRecorder.setAudioEncoder(MediaRecorder.OutputFormat.AMR_NB);
myRecorder.setOutputFile(outputFile);
addListenerButton();
}
private void addListenerButton() {
recbtn = (Button)findViewById(R.id.recbut);
recbtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
start(v);
}
});
}
public void start(View view){
if (recbtn.getText() == getString(R.string.recBtn)){
try {
myRecorder.prepare();
myRecorder.start();
recbtn.setText(getString(R.string.stopBtn));
} catch (IllegalStateException e) {
// start:it is called before prepare()
// prepare: it is called after start() or before setOutputFormat()
e.printStackTrace();
} catch (IOException e) {
// prepare() fails
e.printStackTrace();
}
Toast.makeText(getApplicationContext(), "Start recording...",
Toast.LENGTH_SHORT).show();
}
else{
try {
myRecorder.stop();
myRecorder.release();
myRecorder = null;
recbtn.setText(getString(R.string.recBtn));
Toast.makeText(getApplicationContext(), "Stop recording...",
Toast.LENGTH_SHORT).show();
} catch (IllegalStateException e) {
// it is called before start()
e.printStackTrace();
} catch (RuntimeException e) {
// no valid audio/video data has been received
e.printStackTrace();
}
}
}
it is not recording i tried everything still i cannot get it working sorry but i am still new to this kind of language.
In logcat it says:
02-05 08:01:09.853: D/OpenGLRenderer(1565): TextureCache::get: create
texture(0xb87af490): name, size, mSize = 22, 9216, 9149524 02-05
08:01:19.125: E/MediaRecorder(1565): stop called in an invalid state:
4 02-05 08:01:19.125: W/System.err(1565):
java.lang.IllegalStateException 02-05 08:01:19.129:
W/System.err(1565): at android.media.MediaRecorder.stop(Native
Method) 02-05 08:01:19.129: W/System.err(1565): at
com.example.mixpad.DubActivity.start(DubActivity.java:136) 02-05
08:01:19.129: W/System.err(1565): at
com.example.mixpad.DubActivity$2.onClick(DubActivity.java:99) 02-05
08:01:19.129: W/System.err(1565): at
android.view.View.performClick(View.java:4084) 02-05 08:01:19.133:
W/System.err(1565): at
android.view.View$PerformClick.run(View.java:16966) 02-05
08:01:19.137: W/System.err(1565): at
android.os.Handler.handleCallback(Handler.java:615) 02-05
08:01:19.137: W/System.err(1565): at
android.os.Handler.dispatchMessage(Handler.java:92) 02-05
08:01:19.141: W/System.err(1565): at
android.os.Looper.loop(Looper.java:137) 02-05 08:01:19.141:
W/System.err(1565): at
android.app.ActivityThread.main(ActivityThread.java:4745) 02-05
08:01:19.141: W/System.err(1565): at
java.lang.reflect.Method.invokeNative(Native Method) 02-05
08:01:19.145: W/System.err(1565): at
java.lang.reflect.Method.invoke(Method.java:511) 02-05 08:01:19.145:
W/System.err(1565): at
com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
02-05 08:01:19.145: W/System.err(1565): at
com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553) 02-05
08:01:19.149: W/System.err(1565): at
dalvik.system.NativeStart.main(Native Method)
can anyone help please
In your start(...) method...
if (recbtn.getText() == getString(R.string.recBtn))
You can't compare strings in Java using ==. You need to use equals(...).
Your problem is using == will always fail which means the else condition will always be called and myRecorder.stop(); will throw the IllegalStateException as your MediaRecorder has never been prepared / started.
Change that line to...
if (recbtn.getText().equals(getString(R.string.recBtn)))
I have the following code:
public String test(){
URL url = null;
try {
url = new URL("http://api.heroesofnewerth.com/player_statistics/ranked/nickname/Hieratic/?token=0CZGH8ZI7UR8J2GN");
} catch (MalformedURLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
BufferedReader reader = null;
String x = "";
try {
reader = new BufferedReader(new InputStreamReader(url.openStream(), "UTF-8"));
for (String line; (line = reader.readLine()) != null;) {
System.out.println(line);
x = line;
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally{
if (reader !=null) try{reader.close();} catch (IOException ignore) {
}{}
}
JsonElement root = new JsonParser().parse(x);
return x;
}
}
now i want to insert the text into the following textView.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_create_competetion);
TextView tv = (TextView) findViewById(R.id.competetion_text);
JsonCollector jc = new JsonCollector();
tv.setText(jc.test());
However when i try to run it. i get the following error:
FATAL EXCEPTION: main
E/AndroidRuntime(1800): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.konkurrencesigner/com.example.konkurrencesigner.CreateCompetetion}: android.os.NetworkOnMainThreadException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2180)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
E/AndroidRuntime(1800): at android.app.ActivityThread.access$600(ActivityThread.java:141)
E/AndroidRuntime(1800): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
E/AndroidRuntime(1800): at android.os.Handler.dispatchMessage(Handler.java:99)
E/AndroidRuntime(1800): at android.os.Looper.loop(Looper.java:137)
E/AndroidRuntime(1800): at android.app.ActivityThread.main(ActivityThread.java:5039)
E/AndroidRuntime(1800): at java.lang.reflect.Method.invokeNative(Native Method)
E/AndroidRuntime(1800): at java.lang.reflect.Method.invoke(Method.java:511)
E/AndroidRuntime(1800): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
E/AndroidRuntime(1800): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
E/AndroidRuntime(1800): at dalvik.system.NativeStart.main(Native Method)
E/AndroidRuntime(1800): Caused by: android.os.NetworkOnMainThreadException
E/AndroidRuntime(1800): at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1117)
E/AndroidRuntime(1800): at java.net.InetAddress.lookupHostByName(InetAddress.java:385)
E/AndroidRuntime(1800): at java.net.InetAddress.getAllByNameImpl(InetAddress.java:236)
E/AndroidRuntime(1800): at java.net.InetAddress.getAllByName(InetAddress.java:214)
E/AndroidRuntime(1800): at libcore.net.http.HttpConnection.<init>(HttpConnection.java:70)
E/AndroidRuntime(1800): at libcore.net.http.HttpConnection.<init>(HttpConnection.java:50)
E/AndroidRuntime(1800): at libcore.net.http.HttpConnection$Address.connect(HttpConnection.java:340)
E/AndroidRuntime(1800): at libcore.net.http.HttpConnectionPool.get(HttpConnectionPool.java:87)
E/AndroidRuntime(1800): at libcore.net.http.HttpConnection.connect(HttpConnection.java:128)
E/AndroidRuntime(1800): at libcore.net.http.HttpEngine.openSocketConnection(HttpEngine.java:316)
E/AndroidRuntime(1800): at libcore.net.http.HttpEngine.connect(HttpEngine.java:311)
E/AndroidRuntime(1800): at libcore.net.http.HttpEngine.sendSocketRequest(HttpEngine.java:290)
E/AndroidRuntime(1800): at libcore.net.http.HttpEngine.sendRequest(HttpEngine.java:240)
E/AndroidRuntime(1800): at libcore.net.http.HttpURLConnectionImpl.getResponse(HttpURLConnectionImpl.java:282)
Can anyone tell me why this is happening?
please note that i have already added the following line in my android manifest:
<uses-permission android:name="android.permission.INTERNET" />
You are doing HTTP communication on the main thread, that's why you're getting a NetworkOnMainThreadException. Do it in a separate thread, using an AsyncTask would be an ideal solution, here's an example of how you could implement it:
private TextView tv;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_create_competetion);
tv = (TextView) findViewById(R.id.competetion_text);
JsonCollector jc = new JsonCollector();
// Create and execute a new AsyncTask, the TextView will
// be updated asynchronously when the task has finished.
updateTextView();
}
private void updateTextView() {
new AsyncTask<Void, Void, String>() {
#Override
/* Runs on a separate thread */
protected String doInBackground(Void... params) {
String result = null;
BufferedReader reader = null;
try {
URL url = new URL("http://api.heroesofnewerth.com/player_statistics/ranked/nickname/Hieratic/?token=0CZGH8ZI7UR8J2GN");
reader = new BufferedReader(new InputStreamReader(url.openStream(), "UTF-8"));
for (String line; (line = reader.readLine()) != null;) {
System.out.println(line);
result = line;
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
// Ignore
}
}
}
return result;
}
#Override
/* Runs on the UI/Main thread when doInBackground()
* has finished */
protected void onPostExecute(String result) {
if(result != null) {
// Update the TextView only if we got a result
// from the HTTP request
tv.setText(result);
}
}
}.execute();
}
If you need networking in main thread add these lines of code in the onCreate() method
StrictMode.ThreadPolicy policy =
new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
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..
I am working on a project in which I have a TCP connection with a server via Android.
I am using the following code:
public class MyService extends Service {
private static final String TAG = "MyService";
MediaPlayer player;
Socket s;
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate() {
Toast.makeText(this, "My Service Created", Toast.LENGTH_LONG).show();
Log.d(TAG, "onCreate");
player = MediaPlayer.create(this, R.raw.braincandy);
player.setLooping(false); // Set looping
}
#Override
public void onDestroy() {
Toast.makeText(this, "My Service Stopped", Toast.LENGTH_LONG).show();
Log.d(TAG, "onDestroy");
player.stop();
try {
s.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
#Override
public void onStart(Intent intent, int startid) {
Toast.makeText(this, "My Service Started", Toast.LENGTH_LONG).show();
Log.d(TAG, "onStart");
player.start();
try {
s = new Socket("192.168.1.54", 64000);
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
I am running the connection as a service.
The real problem is I can make a connection with my Android phone (2.3.7) and with the emulator (2.3.3) but when I want to test in on my tablet (4.0.3), my app always crashes when I want to start the connection.
Can someone help me with this?
Here is the logcat log:
FATAL EXCEPTION: main
java.lang.RuntimeException: Unable to start service
com.gunther.servicetcp.MyService#412b0a98 with Intent
{ cmp=com.gunther.servicetcp/.MyService }: android.os.NetworkOnMainThreadException
at android.app.ActivityThread.handleServiceArgs(ActivityThread.java:2376)
at android.app.ActivityThread.access$1900(ActivityThread.java:123)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1210)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4424)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
at dalvik.system.NativeStart.main(Native Method)
Caused by: android.os.NetworkOnMainThreadException
0at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1099)
at libcore.io.BlockGuardOs.connect(BlockGuardOs.java:84)
at libcore.io.IoBridge.connectErrno(IoBridge.java:127)
at libcore.io.IoBridge.connect(IoBridge.java:112)
at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:192)
at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:172)
at java.net.Socket.startupSocket(Socket.java:566)
at java.net.Socket.tryAllAddresses(Socket.java:127)
at java.net.Socket.<init>(Socket.java:177)
at java.net.Socket.<init>(Socket.java:149)
at com.gunther.servicetcp.MyService.onStart(MyService.java:53)
at android.app.Service.onStartCommand(Service.java:438)
at android.app.ActivityThread.handleServiceArgs(ActivityThread.java:2359)
: ... 10 more
You shouldn't do network operations on the main thread. This will lead to your app being unresponsive. Before Honeycomb you could get away with it, but Honeycomb and newer Android versions will check and throw the exception you're getting. See also this page of the Android Developers API
Services's onStart() method runs on the main thread, (yes, services seem to run on the main thread of the application.) so you should fork another thread in the onStart() method and do everything you need to do in that thread.