I have been trying for a long time to work on a button onClick listener that performs the following
launch a loading screen (progress bar).
Send an sms msg in the background to a specific number.
wait for the reply using broadcast listener, which is a message containing a link.
dismiss the loading screen.
then take this link and use it to start another activity.
The code shows no errors, however each time I press the button it doesn't show the progress bar, it only sends a message then waits for the specified time then crashes.
Here's the code
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button1 = (Button) findViewById(R.id.button1);
button1.setOnClickListener(new OnClickListener(){
#Override
`public void onClick(View arg0) {
// TODO Auto-generated method stub
new LoadTracker().execute();
}});
}
protected void sendSMS() {
// TODO Auto-generated method stub
String Phoneno = "***********";
String Message = "www.google.com";
SmsManager manager= SmsManager.getDefault();
manager.sendTextMessage(Phoneno, null, Message, null, null);
}
private BroadcastReceiver Receiver = new BroadcastReceiver(){
public static final String SMS_BUNDLE = "pdus";
#Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
Bundle intentExtras = intent.getExtras();
if (intentExtras != null) {
Object[] sms = (Object[]) intentExtras.get(SMS_BUNDLE);
for (int i = 0; i < sms.length; ++i) {
SmsMessage smsMessage = SmsMessage.createFromPdu((byte[]) sms[i]);
String smsBody = smsMessage.getMessageBody().toString();
Intent in = new Intent(Intent.ACTION_VIEW, Uri.parse(smsBody));
startActivity(in);
}
}
}};
private class LoadTracker extends AsyncTask<Void, Integer, Void>{
protected void onPreExecute(){
progressDialog = new ProgressDialog(MainActivity.this);
progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
progressDialog.setTitle("Sending Signal");
progressDialog.setMessage("Receiving Signal, Please Wait");
progressDialog.setCancelable(false);
progressDialog.setIndeterminate(false);
progressDialog.setMax(100);
progressDialog.setProgress(0);
progressDialog.show();
}
#Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
try{
synchronized (this){
IntentFilter IF = new IntentFilter("android.provider.Telephony.SMS_RECEIVED");
sendSMS();
registerReceiver(Receiver,IF);
this.wait(10000);
this.wait(10000);
publishProgress(100);
}
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
protected void onProgressUpdate(Integer... values){
progressDialog.setProgress(values[0]);
}
#Override
protected void onPostExecute(Void result)
{
//close the progress dialog
progressDialog.dismiss();
//initialize the View
setContentView(R.layout.activity_main);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
protected void onDestroy() {
super.onDestroy();
unregisterReceiver(Receiver);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
Note: The Phone number belongs to the phone on which the application is running so it should open google after it receives the reply
All the uses permissions are in place too.
Update: I discovered the problem with the progress dialog, the "O" letter in OnPreExecute Should've been lower case. Now the progress Dialog appears and the app sends the message however, the app crashes as soon as the reply sms message is received. How can I solve this?
Logcat:
04-20 19:45:45.950: W/dalvikvm(15877): threadid=1: thread exiting with uncaught exception (group=0x40c4b1f8)
04-20 19:45:45.974: E/AndroidRuntime(15877): FATAL EXCEPTION: main
04-20 19:45:45.974: E/AndroidRuntime(15877): java.lang.RuntimeException: Error receiving broadcast Intent { act=android.provider.Telephony.SMS_RECEIVED flg=0x10 (has extras) } in com.example.finalprototype.MainActivity$1#4162c988
04-20 19:45:45.974: E/AndroidRuntime(15877): at android.app.LoadedApk$ReceiverDispatcher$Args.run(LoadedApk.java:741)
04-20 19:45:45.974: E/AndroidRuntime(15877): at android.os.Handler.handleCallback(Handler.java:605)
04-20 19:45:45.974: E/AndroidRuntime(15877): at android.os.Handler.dispatchMessage(Handler.java:92)
04-20 19:45:45.974: E/AndroidRuntime(15877): at android.os.Looper.loop(Looper.java:137)
04-20 19:45:45.974: E/AndroidRuntime(15877): at android.app.ActivityThread.main(ActivityThread.java:4512)
04-20 19:45:45.974: E/AndroidRuntime(15877): at java.lang.reflect.Method.invokeNative(Native Method)
04-20 19:45:45.974: E/AndroidRuntime(15877): at java.lang.reflect.Method.invoke(Method.java:511)
04-20 19:45:45.974: E/AndroidRuntime(15877): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:982)
04-20 19:45:45.974: E/AndroidRuntime(15877): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:749)
04-20 19:45:45.974: E/AndroidRuntime(15877): at dalvik.system.NativeStart.main(Native Method)
04-20 19:45:45.974: E/AndroidRuntime(15877): Caused by: android.content.ActivityNotFoundException: No Activity found to handle Intent { act=android.intent.action.VIEW dat=www.google.com }
04-20 19:45:45.974: E/AndroidRuntime(15877): at android.app.Instrumentation.checkStartActivityResult(Instrumentation.java:1535)
04-20 19:45:45.974: E/AndroidRuntime(15877): at android.app.Instrumentation.execStartActivity(Instrumentation.java:1387)
04-20 19:45:45.974: E/AndroidRuntime(15877): at android.app.Activity.startActivityForResult(Activity.java:3190)
04-20 19:45:45.974: E/AndroidRuntime(15877): at android.support.v4.app.FragmentActivity.startActivityForResult(FragmentActivity.java:817)
04-20 19:45:45.974: E/AndroidRuntime(15877): at android.app.Activity.startActivity(Activity.java:3297)
04-20 19:45:45.974: E/AndroidRuntime(15877): at com.example.finalprototype.MainActivity$1.onReceive(MainActivity.java:75)
04-20 19:45:45.974: E/AndroidRuntime(15877): at android.app.LoadedApk$ReceiverDispatcher$Args.run(LoadedApk.java:732)
04-20 19:45:45.974: E/AndroidRuntime(15877): ... 9 more
04-20 19:45:56.013: I/Process(15877): Sending signal. PID: 15877 SIG: 9
Not sure but from the following line
ActivityNotFoundException: No Activity found to handle Intent { act=android.intent.action.VIEW dat=www.google.com ...
I think your URL should be like http://www.google.com. Its missing the protocol http without which it might not recognize the right activity to handle the Intent.
Related
I am writing an app that uses internet, i have given it the following permissions:
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.NETWORK"/>
<uses-permission android:name="android.permission.GET_ACCOUNTS" />
<uses-permission android:name="android.permission.USE_CREDENTIALS" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
all is fine when on WIFI but when it connects to H+ 3G or 4G it stops working at a POST or GET. I already put all the tasks that request or post something to the server in a aSyncTask but to no result.
Is there something i am missing?
EDIT:
a activity with code
public class ParkeerActivity extends ActionBarActivity {
#
Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_parkeer);
DatePicker datePicker = (DatePicker) findViewById(R.id.datePicker);
Calendar calendar = Calendar.getInstance();
calendar.setTime(new Date());
datePicker.init(calendar.get(Calendar.DAY_OF_MONTH), calendar.get(Calendar.MONTH), calendar.get(Calendar.YEAR), new DatePicker.OnDateChangedListener() {#
Override
public void onDateChanged(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
updateSpacesLeft();
}
});
RadioGroup rg = (RadioGroup) findViewById(R.id.radioGroup);
rg.setOnCheckedChangeListener(new OnCheckedChangeListener() {#
Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
updateSpacesLeft();
}
});
Button reservationBtn = (Button) findViewById(R.id.reservationButton);
reservationBtn.setEnabled(false);
reservationBtn.setOnClickListener(new View.OnClickListener() {#
Override
public void onClick(View v) {
reservationClicked();
}
});
}
#
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_parkeer, menu);
return true;
}
#
Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public void reservationClicked() {
AsyncTask < Void, Void, String > task = new AsyncTask < Void, Void, String > () {#
Override
protected String doInBackground(Void...params) {
String formattedDate = getFormattedDateForUrl();
String selectedTime = getSelectedTime();
EditText commentText = (EditText) findViewById(R.id.editText);
String comment = commentText.getText().toString();
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(ParkeerActivity.this);
String accessToken = prefs.getString("accessToken", null);
Ion.with(ParkeerActivity.this)
.load("http://-/reservations")
.setBodyParameter("accessToken", accessToken)
.setBodyParameter("date", formattedDate)
.setBodyParameter("time", selectedTime)
.setBodyParameter("comment", comment)
.asJsonObject()
.withResponse()
.setCallback(new FutureCallback < Response < JsonObject >> () {#
Override
public void onCompleted(Exception e, Response < JsonObject > result) {
if (result.getHeaders().code() == 201) {
AlertDialog.Builder alert = new AlertDialog.Builder(ParkeerActivity.this);
alert.setMessage("Reservering gelukt");
alert.show();
} else if (result.getHeaders().code() != 201) {
AlertDialog.Builder alert = new AlertDialog.Builder(ParkeerActivity.this);
alert.setMessage("Reservering mislukt");
alert.show();
};
}
});
return null;
}
};
task.execute();
}
it crashes at reservationClicked()
logcat will be posted once i have found a cable to connect my phone to pc
EDIT2: Logcat exception on mobile device (not emulator)
04-18 13:48:48.489 18475-19199/com.parkeerapp.-.parkeerapp D/MyLogs﹕ (296 ms) http://-/parkingspaces/available: Connecting socket
04-18 13:48:48.489 18475-19199/com.parkeerapp.-.parkeerapp D/MyLogs﹕ (0 ms) http://-/parkingspaces/available: Executing request.
04-18 13:48:48.499 18475-19199/com.parkeerapp.-.parkeerapp D/MyLogs﹕ (2 ms) http://-/parkingspaces/available: Connecting socket
04-18 13:48:58.549 18475-19199/com.parkeerapp.-.parkeerapp D/MyLogs﹕ (10357 ms) http://-/parkingspaces/available: Response is not cacheable
04-18 13:48:58.559 18475-19199/com.parkeerapp.-.parkeerapp D/MyLogs﹕ (10359 ms) http://-/parkingspaces/available: Connection successful
04-18 13:48:58.569 18475-19199/com.parkeerapp.-.parkeerapp D/MyLogs﹕ (10078 ms) http://-/parkingspaces/available: Response is not cacheable
04-18 13:48:58.569 18475-19199/com.parkeerapp.-.parkeerapp D/MyLogs﹕ (10079 ms) http://-/parkingspaces/available: Connection successful
04-18 13:48:58.579 18475-18475/com.parkeerapp.-.parkeerapp D/AndroidRuntime﹕ Shutting down VM
04-18 13:48:58.579 18475-18475/com.parkeerapp.-.parkeerapp W/dalvikvm﹕ threadid=1: thread exiting with uncaught exception (group=0x41859da0)
04-18 13:48:58.579 18475-19199/com.parkeerapp.-.parkeerapp D/MyLogs﹕ (10386 ms) http://-/parkingspaces/available: Recycling keep-alive socket
04-18 13:48:58.579 18475-18475/com.parkeerapp.indivirtual.parkeerapp E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.parkeerapp.-.parkeerapp, PID: 18475
java.lang.NullPointerException
at com.parkeerapp.-.parkeerapp.ParkeerActivity$5$1.onCompleted(ParkeerActivity.java:154)
at com.parkeerapp.-.parkeerapp.ParkeerActivity$5$1.onCompleted(ParkeerActivity.java:151)
at com.koushikdutta.async.future.SimpleFuture.handleCallbackUnlocked(SimpleFuture.java:107)
at com.koushikdutta.async.future.SimpleFuture.setComplete(SimpleFuture.java:141)
at com.koushikdutta.async.future.SimpleFuture.setComplete(SimpleFuture.java:124)
at com.koushikdutta.ion.IonRequestBuilder$1.run(IonRequestBuilder.java:244)
at com.koushikdutta.async.AsyncServer$RunnableWrapper.run(AsyncServer.java:57)
at android.os.Handler.handleCallback(Handler.java:733)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:146)
at android.app.ActivityThread.main(ActivityThread.java:5679)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1291)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1107)
at dalvik.system.NativeStart.main(Native Method)
04-18 13:48:58.589 18475-19199/com.parkeerapp.-.parkeerapp D/MyLogs﹕ (10094 ms) http://-/parkingspaces/available: Recycling keep-alive socket
If you are using Ion this way, you need not use AsyncTask.
You should check result for null before blindly going with it.
I have faced similar issues sometimes. If the connectivity breaks, it sometimes returns result as null.
#Override
public void onCompleted(Exception e, JsonObject result) {
if (e != null) {
// failed.
// return
}
if (result == null) {
// failed
// return
}
}
Sometimes even if the exception is null, result is also null.
the problem has been that there is use of a proxy on 3G and 4G
Ion.with(ParkeerActivity.this)
.load(url )
.proxy(ip_adres, 8080)
did the trick
current problem is google Oauth saying need permission but that will be a new thread
I switched from running my app on a phone to a nexus 10 tablet and now it says "unfortunately the application has stopped."
The tablet is running 4.4.2, my target api is set to 19 in the manifest.
When I run it in debug mode I get Source Not Found. I tried clicking edit source lookup path and adding my project and had no luck.
I've looked all over the internet and haven't had any luck solving this problem. Any suggestions would be a big help.
"java.lang.RuntimeException: Unable to start activity ComponentInfo{com.looper.video/com.looper.video.MainActivity}: java.lang.NullPointerException"
Edit:
MainActivity:
package com.looper.video;
public class MainActivity extends Activity {
private VideoView video;
private MediaController ctlr;
final Uri firstVideoPath = Uri.parse("android.resource://com.looper.video/" + R.raw.wildlife);
final Uri secondVideoPath = Uri.parse("android.resource://com.looper.video/" + R.raw.wildlife1);
private String videosPath = Environment.getExternalStorageDirectory() + "/videos/";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
File folder = new File(videosPath);
File[] customFiles = folder.listFiles();
List<String> customFileNames = new ArrayList<String>();
for(File file : customFiles) {
customFileNames.add(file.getName());
}
ArrayAdapter<String> spinnerArrayAdapter = new ArrayAdapter<String>(
this, android.R.layout.simple_spinner_item, customFileNames);
spinnerArrayAdapter.setDropDownViewResource( android.R.layout.simple_spinner_dropdown_item );
Spinner spinner = (Spinner)findViewById(R.id.spinnerCustomFiles);
spinner.setAdapter(spinnerArrayAdapter);
video = (VideoView)findViewById(R.id.videoView1);
ctlr = new MediaController(this);
final Button firstVideoBtn = (Button) findViewById(R.id.firstVideoBtn);
firstVideoBtn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Perform action on click
playFirstVideo();
}
});
final Button secondVideoBtn = (Button) findViewById(R.id.secondVideoBtn);
secondVideoBtn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Perform action on click
playSecondVideo();
}
});
}
public void playFeatured(View v) {
try {
Spinner spinner = (Spinner)findViewById(R.id.spinnerCustomFiles);
String strPath = videosPath + spinner.getSelectedItem().toString();
Toast.makeText(this, strPath, Toast.LENGTH_LONG).show();
//Uri path = Uri.parse(videosPath + spinner.getSelectedItem().toString());
video.setVideoPath(strPath);
ctlr.setMediaPlayer(video);
video.setMediaController(ctlr);
video.requestFocus();
video.start();
video.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer vmp) {
playSecondVideo();
}
});
} catch(Exception e) {
System.out.println(e.getMessage());
}
}
public void playFirstVideo() {
video.setVideoURI(firstVideoPath);
ctlr.setMediaPlayer(video);
video.setMediaController(ctlr);
video.requestFocus();
video.start();
video.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer vmp) {
playSecondVideo();
}
});
}
public void playSecondVideo() {
SharedPreferences sp = getSharedPreferences("schedule", Context.MODE_PRIVATE);
//SimpleDateFormat sdf = new SimpleDateFormat("hh:mm");
String startTime = sp.getString("startTime", "");
String endTime = sp.getString("endTime", "");
/*
//SimpleDateFormat parser = new SimpleDateFormat("HH:mm");
//Date dateStartTime = parser.parse(startTime);
//Date dateEndTime = parser.parse(endTime);
Date now = new Date();
try {
if (userDate.after(ten) && userDate.before(eighteen)) {
}
} catch (ParseException e) {
// Invalid date was entered
}
System.out.println("Now:"+now);
System.out.println("Start"+startTime);
System.out.println("End:"+endTime);
//if(now.before(dateEndTime) && now.after(dateStartTime)){
//disableAll();
//} else {
*
*/
video.setVideoURI(secondVideoPath);
ctlr.setMediaPlayer(video);
video.setMediaController(ctlr);
video.requestFocus();
video.start();
video.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer vmp) {
playSecondVideo();
}
});
//}
}
public void admin(View view)
{
//MySQLiteHelper db = new MySQLiteHelper(this);
//final String password = db.getUser(7).getPassword();
//db.close();
final AlertDialog.Builder alert = new AlertDialog.Builder(this);
final EditText pass = new EditText(this);
alert.setView(pass);
alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
String value = pass.getText().toString().trim();
SharedPreferences sp1 = getSharedPreferences("Login", 0);
//String username = sp1.getString("UserName", "");
String password = sp1.getString("Password", "");
if(value.equals(password)) {
Intent intent = new Intent(getBaseContext(),Admin.class);
startActivity(intent);
}
//Toast.makeText(getApplicationContext(), password + " " + value, Toast.LENGTH_SHORT).show();
}
});
alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
dialog.cancel();
}
});
alert.show();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public void disableAll(){
Button firstVideoBtn = (Button)findViewById(R.id.firstVideoBtn);
firstVideoBtn.setEnabled(false);
Button secondVideoBtn = (Button)findViewById(R.id.secondVideoBtn);
secondVideoBtn.setEnabled(false);
Spinner spinner = (Spinner)findViewById(R.id.spinnerCustomFiles);
spinner.setEnabled(false);
Button btnPlay = (Button)findViewById(R.id.btnPlayFeatured);
btnPlay.setEnabled(false);
VideoView videoView = (VideoView)findViewById(R.id.videoView1);
videoView.setEnabled(false);
}
}
Full logcat:
D/dalvikvm(2817): GC_FOR_ALLOC freed 58K, 4% free 3441K/3568K, paused 20ms, total 20ms
10-08 15:23:17.965: D/dalvikvm(2817): GC_FOR_ALLOC freed 2K, 4% free 3505K/3632K, paused 7ms, total 7ms
10-08 15:23:17.975: I/dalvikvm-heap(2817): Grow heap (frag case) to 8.739MB for 5515216-byte allocation
10-08 15:23:17.985: D/dalvikvm(2817): GC_FOR_ALLOC freed <1K, 2% free 8891K/9020K, paused 7ms, total 7ms
10-08 15:23:18.055: D/AndroidRuntime(2817): Shutting down VM
10-08 15:23:18.055: W/dalvikvm(2817): threadid=1: thread exiting with uncaught exception (group=0x4155eba8)
10-08 15:23:18.055: E/AndroidRuntime(2817): FATAL EXCEPTION: main
10-08 15:23:18.055: E/AndroidRuntime(2817): Process: com.looper.video, PID: 2817
10-08 15:23:18.055: E/AndroidRuntime(2817): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.looper.video/com.looper.video.MainActivity}: java.lang.NullPointerException
10-08 15:23:18.055: E/AndroidRuntime(2817): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2195)
10-08 15:23:18.055: E/AndroidRuntime(2817): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2245)
10-08 15:23:18.055: E/AndroidRuntime(2817): at android.app.ActivityThread.access$800(ActivityThread.java:135)
10-08 15:23:18.055: E/AndroidRuntime(2817): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
10-08 15:23:18.055: E/AndroidRuntime(2817): at android.os.Handler.dispatchMessage(Handler.java:102)
10-08 15:23:18.055: E/AndroidRuntime(2817): at android.os.Looper.loop(Looper.java:136)
10-08 15:23:18.055: E/AndroidRuntime(2817): at android.app.ActivityThread.main(ActivityThread.java:5017)
10-08 15:23:18.055: E/AndroidRuntime(2817): at java.lang.reflect.Method.invokeNative(Native Method)
10-08 15:23:18.055: E/AndroidRuntime(2817): at java.lang.reflect.Method.invoke(Method.java:515)
10-08 15:23:18.055: E/AndroidRuntime(2817): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
10-08 15:23:18.055: E/AndroidRuntime(2817): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
10-08 15:23:18.055: E/AndroidRuntime(2817): at dalvik.system.NativeStart.main(Native Method)
10-08 15:23:18.055: E/AndroidRuntime(2817): Caused by: java.lang.NullPointerException
10-08 15:23:18.055: E/AndroidRuntime(2817): at com.looper.video.MainActivity.onCreate(MainActivity.java:52)
10-08 15:23:18.055: E/AndroidRuntime(2817): at android.app.Activity.performCreate(Activity.java:5231)
10-08 15:23:18.055: E/AndroidRuntime(2817): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
10-08 15:23:18.055: E/AndroidRuntime(2817): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2159)
10-08 15:23:18.055: E/AndroidRuntime(2817): ... 11 more
android.view.WindowManager$BadTokenException: Unable to add window -- token android.os.BinderProxy#406a6678 is not valid; is your activity running?
at android.view.ViewRoot.setView(ViewRoot.java:528)
at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:177)
at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:91)
at android.view.Window$LocalWindowManager.addView(Window.java:424)
at android.app.Dialog.show(Dialog.java:241)
at android.app.Activity.showDialog(Activity.java:2569)
at android.app.Activity.showDialog(Activity.java:2527)
at MyCode$8$4.run(MyCode.java:557)
at android.os.Handler.handleCallback(Handler.java:587)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:130)
at android.app.ActivityThread.main(ActivityThread.java:3683)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:507)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:878)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:636)
at dalvik.system.NativeStart.main(Native Method)
I am getting above exception when following code is executed. This file dialog will shown once the processing is done and progressbar reaches 100%. FileSaveDialog extends Dialog and implements OnCompletionListener
runOnUiThread(new Runnable() {
#Override
public void run() {
showDialog(error.Code());//Line 557
}
});
#Override
protected Dialog onCreateDialog(int id) {
Dialog dialog;
AlertDialog.Builder builder;
final ScrollView scrollView = new ScrollView(this);
final TextView textView = new TextView(this);
switch (id) {
// Other cases are here
case 4:
File playFile = new File(mediaPath, TEMP_WAV_FILE_NAME);
dialog = new FileSaveDialog(this, getResources(),
playFile.getAbsolutePath(), saveDiscardHandler);
dialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
#Override
public void onCancel(DialogInterface dialog) {
// do whatever you want the back key to do
cleanUp();
}
});
break;
// Other cases are here
default:
dialog = null;
}
return dialog;
}
You must check activity isFinishing() If the activity is finishing, returns true; else returns false.
Hi I have developed android phonegap app and when dialog is shown and screen orientation changes,showing the error in logcat.How to solve this
Here is my logcat error:
E/WindowManager(5759): Activity com.example.Service.NotificationAlert has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView#412c93c0 that was originally added here
E/WindowManager(5759): android.view.WindowLeaked: Activity com.example.Service.NotificationAlert has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView#412c93c0 that was originally added here
E/WindowManager(5759): at android.view.ViewRootImpl.<init>(ViewRootImpl.java:344)
E/WindowManager(5759): at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:267)
E/WindowManager(5759): at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:215)
E/WindowManager(5759): at android.view.WindowManagerImpl$CompatModeWrapper.addView(WindowManagerImpl.java:140)
E/WindowManager(5759): at android.view.Window$LocalWindowManager.addView(Window.java:537)
E/WindowManager(5759): at android.app.Dialog.show(Dialog.java:278)
E/WindowManager(5759): at com.example.Service.NotificationAlert$1.handleMessage(NotificationAlert.java:103)
E/WindowManager(5759): at android.os.Handler.dispatchMessage(Handler.java:99)
E/WindowManager(5759): at android.os.Looper.loop(Looper.java:137)
E/WindowManager(5759): at android.app.ActivityThread.main(ActivityThread.java:4424)
E/WindowManager(5759): at java.lang.reflect.Method.invokeNative(Native Method)
E/WindowManager(5759): at java.lang.reflect.Method.invoke(Method.java:511)
E/WindowManager(5759): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
E/WindowManager(5759): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
E/WindowManager(5759): at dalvik.system.NativeStart.main(Native Method)
Please tell me the solution.Thanks In Advance.
Here is my code:
AlertDialog alertDialog = new AlertDialog.Builder(NotificationAlert.this).create();
alertDialog.setTitle("Mobilyzer");
msgCountBundle = getIntent().getExtras();
messageCount = msgCountBundle.getInt("Count");
userId = msgCountBundle.getInt("userid");
if (messageCount > 1) {
alertDialog
.setMessage("You have " + messageCount + " New Messages");
} else {
alertDialog.setMessage("You have " + messageCount + " New Message");
}
alertDialog.show();
new Timer().schedule(new task(), 30000);
private class task extends TimerTask
{
public void run()
{
toastHandler.sendEmptyMessage(0);
}
}
private final Handler toastHandler = new Handler() {
public void handleMessage(Message msg) {
if(alertDialog.isShowing())
{
try
{
alertDialog.dismiss();
finish();
Log.i("alertdialog","hide alert dialog");
}
catch(IllegalArgumentException e)
{
Log.e("illegal ","illegal exception in dialog"+e);
}
catch(Exception e)
{
Log.e("illegal ","exception in dialog"+e);
}
}
Log.i("alertdialog","show alert dialog");
}
};
In NotificationAlert Activity you are showing a Dialog that was not dismissed by explicitly calling dismiss() on it when Activity was paused. Keep a reference to your Dialog object and in onPause() call dismiss() on it.
#Override
protected void onPause() {
if (myDialog != null) {
myDialog.dismiss();
}
super.onPause();
}
Check the flow of application .In application you are adding dialog more than one time i think.So, try to solve by adding only one dialog in to activity view.
It is because of some other exception the app is crashing and because the dialog is showing the window leak exception is thrown.
Anyways the window leak exception occurs when the dialog is not null and the activity is finished. So the dialog has to be made null either in onPause() as mentioned above or where the activity is moving to a new screen like before starting an intent. Here you can nullify the dailog in the catch so that the window leak exception can be handled, but there is some other exception in your code. Provide the complete logcat.
i'm trying to study how to make apps for Android.
Following a tutorial made by Google with my modification i get this error
12-26 10:42:23.848: D/dalvikvm(1302): GC_CONCURRENT freed 362K, 15% free 2737K/3216K, paused 70ms+89ms, total 204ms
12-26 10:42:23.898: D/AndroidRuntime(1302): Shutting down VM
12-26 10:42:23.898: W/dalvikvm(1302): threadid=1: thread exiting with uncaught exception (group=0x40a70930)
12-26 10:42:23.928: E/AndroidRuntime(1302): FATAL EXCEPTION: main
12-26 10:42:23.928: E/AndroidRuntime(1302): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.startactivity/com.example.startactivity.DisplayMessageActivity}: java.lang.NullPointerException
12-26 10:42:23.928: E/AndroidRuntime(1302): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2180)
12-26 10:42:23.928: E/AndroidRuntime(1302): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
12-26 10:42:23.928: E/AndroidRuntime(1302): at android.app.ActivityThread.access$600(ActivityThread.java:141)
12-26 10:42:23.928: E/AndroidRuntime(1302): at android.app.ActivityThread$H.handleMessage(ActivityThread.java: 1234)
12-26 10:42:23.928: E/AndroidRuntime(1302): at android.os.Handler.dispatchMessage(Handler.java:99)
12-26 10:42:23.928: E/AndroidRuntime(1302): at android.os.Looper.loop(Looper.java:137)
12-26 10:42:23.928: E/AndroidRuntime(1302): at android.app.ActivityThread.main(ActivityThread.java:5039)
12-26 10:42:23.928: E/AndroidRuntime(1302): at java.lang.reflect.Method.invokeNative(Native Method)
12-26 10:42:23.928: E/AndroidRuntime(1302): at java.lang.reflect.Method.invoke(Method.java:511)
12-26 10:42:23.928: E/AndroidRuntime(1302): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
12-26 10:42:23.928: E/AndroidRuntime(1302): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
12-26 10:42:23.928: E/AndroidRuntime(1302): at dalvik.system.NativeStart.main(Native Method)
12-26 10:42:23.928: E/AndroidRuntime(1302): Caused by: java.lang.NullPointerException
12-26 10:42:23.928: E/AndroidRuntime(1302): at com.example.startactivity.DisplayMessageActivity.onCreate(DisplayMessageActivity.java:20)
12-26 10:42:23.928: E/AndroidRuntime(1302): at android.app.Activity.performCreate(Activity.java:5104)
12-26 10:42:23.928: E/AndroidRuntime(1302): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1080)
12-26 10:42:23.928: E/AndroidRuntime(1302): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2144)
12-26 10:42:23.928: E/AndroidRuntime(1302): ... 11 more
12-26 10:43:11.418: I/Process(1302): Sending signal. PID: 1302 SIG: 9
this is the code of MainActivity
public class MainActivity extends Activity {
public final static String EXTRA_MESSAGE = "com.example.startactivity.MESSAGE";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
public void sendMessage(View view){
Intent intent = new Intent(this,DisplayMessageActivity.class);
EditText edit_nome = (EditText) findViewById(R.id.edit_nome);
EditText edit_cognome = (EditText) findViewById(R.id.edit_cognome);
Bundle bundle = new Bundle();
bundle.putString("nome", edit_nome.getText().toString());
bundle.putString("cognome", edit_cognome.getText().toString());
intent.putExtra(EXTRA_MESSAGE, bundle);
startActivity(intent);
}
}
And this is the code of DisplayMessageActivity
public class DisplayMessageActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_display_message);
// Show the Up button in the action bar.
getActionBar().setDisplayHomeAsUpEnabled(true);
Intent intent = getIntent();
String nome = intent.getBundleExtra("nome").toString();
String cognome = intent.getBundleExtra("cognome").toString();
TextView textNome = new TextView(this);
TextView textCognome = new TextView(this);
textNome.setTextSize(40);
textCognome.setTextSize(40);
textNome.setText(nome);
textCognome.setText(cognome);
setContentView(textNome);
setContentView(textCognome);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
NavUtils.navigateUpFromSameTask(this);
return true;
}
return super.onOptionsItemSelected(item);
}
}
Thanks for help.
You are calling to the toString method of the Bundle instead of retrieving the string stored on it. In addition, you are trying to get a Bundle with a key that is stored into it. Try chaning
String nome = intent.getBundleExtra("nome").toString();
String cognome = intent.getBundleExtra("cognome").toString();
to
Bundle bundle = intent.getBundleExtra(MainActivity.EXTRA_MESSAGE);
if (bundle != null) {
String nome = bundle.getString("nome");
String cognome = bundle.getString("cognome");
}
Take in consideration that if the intent received is not your, and it comes with no Bundle, or a different one, your nome and cognome strings will be null, not empty strings.
The logcat shows the problem at-
com.example.startactivity/com.example.startactivity.DisplayMessageActivity
So, the best guess is the nome and cognome values might be null at the point where you set the text in the texviews in the DisplayMessageActivity
Try adding a debug point at the line with text
String nome = intent.getBundleExtra("nome").toString();
and see for any null values.
Hope this jelps
Change MainActivity code to
public class MainActivity extends Activity {
public final static String EXTRA_MESSAGE = "com.example.startactivity.MESSAGE";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Intent intent = new Intent(this,DisplayMessageActivity.class);
EditText edit_nome = (EditText) findViewById(R.id.edit_nome);
EditText edit_cognome = (EditText) findViewById(R.id.edit_cognome);
Bundle bundle = new Bundle();
bundle.putString("nome", edit_nome.getText().toString());
bundle.putString("cognome", edit_cognome.getText().toString());
intent.putExtra(EXTRA_MESSAGE, bundle);
startActivity(intent);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
Make sure that entry in manifest file:
<activity android:name=".DisplayMessageActivity"></activity>