I am trying to have an alert appear on a certain time. I was able to do that, but when I press the snooze button it works, I get another alert but I also get some errors.
Find the errors below:
11-19 12:50:26.755: E/AndroidRuntime(452): FATAL EXCEPTION: main
11-19 12:50:26.755: E/AndroidRuntime(452): java.lang.NullPointerException
11-19 12:50:26.755: E/AndroidRuntime(452): at android.app.PendingIntent.getActivity(PendingIntent.java:191)
11-19 12:50:26.755: E/AndroidRuntime(452): at com.example.servicealarmdemo2.MainActivity.repeat(MainActivity.java:124)
11-19 12:50:26.755: E/AndroidRuntime(452): at com.example.servicealarmdemo2.AlertDemo$2.onClick(AlertDemo.java:58)
11-19 12:50:26.755: E/AndroidRuntime(452): at com.android.internal.app.AlertController$ButtonHandler.handleMessage(AlertController.java:159)
11-19 12:50:26.755: E/AndroidRuntime(452): at android.os.Handler.dispatchMessage(Handler.java:99)
11-19 12:50:26.755: E/AndroidRuntime(452): at android.os.Looper.loop(Looper.java:123)
11-19 12:50:26.755: E/AndroidRuntime(452): at android.app.ActivityThread.main(ActivityThread.java:3683)
11-19 12:50:26.755: E/AndroidRuntime(452): at java.lang.reflect.Method.invokeNative(Native Method)
11-19 12:50:26.755: E/AndroidRuntime(452): at java.lang.reflect.Method.invoke(Method.java:507)
11-19 12:50:26.755: E/AndroidRuntime(452): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
11-19 12:50:26.755: E/AndroidRuntime(452): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
11-19 12:50:26.755: E/AndroidRuntime(452): at dalvik.system.NativeStart.main(Native Method)
the function that repeats the alert is in MainActivity.java
public void repeat() {
Intent i = new Intent("com.example.servicealarmdemo2.demoactivity");
PendingIntent operation = PendingIntent.getActivity(getBaseContext(), 0, i, Intent.FLAG_ACTIVITY_NEW_TASK);
AlarmManager alarmManager = (AlarmManager) getBaseContext().getSystemService(ALARM_SERVICE);
long time= System.currentTimeMillis();
EditText text=(EditText)findViewById(R.id.editText1);
String str = text.getText().toString();
long t=Long.parseLong(str);
alarmManager.set(AlarmManager.RTC_WAKEUP, time+( t*60*1000), operation);
}
and the following two classes are for the alerts:
AlertDemo.java
package com.example.servicealarmdemo2;
import android.app.Activity;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.ComponentName;
import android.content.Intent;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.view.WindowManager.LayoutParams;
import android.widget.EditText;
public class AlertDemo extends DialogFragment {
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
/** Turn Screen On and Unlock the keypad when this alert dialog is displayed */
getActivity().getWindow().addFlags(LayoutParams.FLAG_TURN_SCREEN_ON | LayoutParams.FLAG_DISMISS_KEYGUARD);
/** Creating a alert dialog builder */
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
/** Setting title for the alert dialog */
builder.setTitle("Alarm");
/** Setting the content for the alert dialog */
builder.setMessage("An Alarm by AlarmManager");
/** Defining an OK button event listener */
builder.setPositiveButton("Take", new OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
/** Exit application on click OK */
getActivity().finish();
}
});
builder.setNegativeButton("Snooze", new OnClickListener() {
// #Override
public void onClick(DialogInterface dialog, int which) {
/** Exit application on click OK */
//getActivity().finish();
// repeat();
System.out.println("REPEAT");
new MainActivity().repeat();
//System.out.println("Activities: "+m);
}
});
/** Creating the alert dialog window */
return builder.create();
}
/** The application should be exit, if the user presses the back button */
#Override
public void onDestroy() {
super.onDestroy();
getActivity().finish();
}
// public void repeat() {
// MainActivity.repeat();
// }
// public void repeat() {
// Intent i = new Intent("com.example.servicealarmdemo2.demoactivity");
//// PendingIntent operation = PendingIntent.getActivity(getBaseContext(), 0, i, Intent.FLAG_ACTIVITY_NEW_TASK);
// PendingIntent operation = PendingIntent.getActivity(getActivity().getBaseContext(), 0, i, Intent.FLAG_ACTIVITY_NEW_TASK);
// AlarmManager alarmManager = (AlarmManager) getActivity().getBaseContext().getSystemService(getActivity().ALARM_SERVICE);
// long time= System.currentTimeMillis();
// EditText text=(EditText)getActivity().findViewById(R.id.editText1);
// String str = text.getText().toString();
// long t=Long.parseLong(str);
// alarmManager.set(AlarmManager.RTC_WAKEUP, time+( t*60*1000), operation);
//
// }
}
and DemoActivity.java
package com.example.servicealarmdemo2;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.view.WindowManager.LayoutParams;
import android.widget.Toast;
public class DemoActivity extends FragmentActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
/** Creating an Alert Dialog Window */
AlertDemo alert = new AlertDemo();
/** Opening the Alert Dialog Window */
alert.show(getSupportFragmentManager(), "AlertDemo");
}
}
new MainActivity().repeat();
Never instantiate activities using new, only via Intent.
Reason for NPE is that the code is trying to use the activity as a Context but it has not been properly initialized for such use.
Technically, getBaseContext() returns null and getActivity() unconditionally calls a method on the passed-in context.
The way you did code its not look good, and Null-pointer is because of wrong Context.
PendingIntent operation = PendingIntent.getActivity(getBaseContext(), 0, i, Intent.FLAG_ACTIVITY_NEW_TASK);
Try to pass activity context while calling repeat() function.
new MainActivity().repeat(Activity context); //pass here activity context.
public void repeat(Activity ctx) {
Intent i = new Intent("com.example.servicealarmdemo2.demoactivity");
PendingIntent operation = PendingIntent.getActivity(ctx, 0, i, Intent.FLAG_ACTIVITY_NEW_TASK);
.
.
.
.
}
But not a good way to achieve!
Related
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 5 years ago.
My application stopped when I finished working on the quiz application. I'm learning to make an Android application quiz using MySQL database, but I get the problem when the last question will move to the scoring page.
10-28 01:02:25.816 31874-31874/com.example.nuvo.myapplication
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.nuvo.myapplication, PID: 31874
java.lang.RuntimeException: Unable to start activity
ComponentInfo{com.example.nuvo.myapplication/com.example.nuvo.myapplication.Complete}:
java.lang.NullPointerException
at
android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2429)
at
android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2493)
at android.app.ActivityThread.access$800(ActivityThread.java:166)
at
android.app.ActivityThread$H.handleMessage(ActivityThread.java:1283)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5584)
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:1268)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1084)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at
com.example.nuvo.myapplication.Complete.onCreate(Complete.java:18)
at android.app.Activity.performCreate(Activity.java:5442)
at
android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1094)
at
android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2393)
at
android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2493)
at android.app.ActivityThread.access$800(ActivityThread.java:166)
at
android.app.ActivityThread$H.handleMessage(ActivityThread.java:1283)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5584)
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:1268)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1084)
at dalvik.system.NativeStart.main(Native Method)
Complate.java
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
public class Complete extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_complete);
int score = getIntent().getExtras().getInt("score");
AlertDialog.Builder builder = new AlertDialog.Builder(Complete.this);
builder.setTitle("Quiz Complete");
builder.setMessage("Your Score is: " +score+ " out of 10");
builder.show();
builder.setPositiveButton("Play Again", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
//do things
Intent intent = new Intent(Complete.this, QuizActivity.class);
startActivity(intent);
}
});
builder.setNegativeButton("Done", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
//do things
}
});
AlertDialog alert = builder.create();
alert.show();
}
public void restartQuiz(View view)
{
Intent intent = new Intent(Complete.this, QuizActivity.class);
startActivity(intent);
}
public void mainMenu(View view)
{
Intent intent = new Intent(Complete.this, MainActivity.class);
startActivity(intent);
}
}
QuizActivity.java
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
public class Complete extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_complete);
int score = getIntent().getExtras().getInt("score");
AlertDialog.Builder builder = new AlertDialog.Builder(Complete.this);
builder.setTitle("Quiz Complete");
builder.setMessage("Your Score is: " +score+ " out of 10");
builder.show();
builder.setPositiveButton("Play Again", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
//do things
Intent intent = new Intent(Complete.this, QuizActivity.class);
startActivity(intent);
}
});
builder.setNegativeButton("Done", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
//do things
}
});
AlertDialog alert = builder.create();
alert.show();
}
public void restartQuiz(View view)
{
Intent intent = new Intent(Complete.this, QuizActivity.class);
startActivity(intent);
}
public void mainMenu(View view)
{
Intent intent = new Intent(Complete.this, MainActivity.class);
startActivity(intent);
}
}
This line is problematic in your code:
int score = getIntent().getExtras().getInt("score");
It seems that your Intent, which opened your Complete activity did not have an integer "score" and hence returned null, which caused NullPointerException. To avoid such problems consider using another method getInt(String key, int defaultValue) s.a. this:
int score = getIntent().getExtras().getInt("score", 0);
This way you'll not get an exception if your Intent arrives without a value, but it will be set to 0 by default.
I am making a simple reminder app. I am getting a null pointer exception when the reminder goes off.
Here the key info from Logcat: Caused by: java.lang.NullPointerException
at com.joshbgold.move.AlarmReceiver.onReceive(AlarmReceiver.java:34)
Evidently I am not initializing AlarmActivity inst properly. I know this is probably a simple fix, thanks for your patience with a newer Java programmer.
AlarmReceiver.java:
import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.media.MediaPlayer;
import android.support.v4.content.WakefulBroadcastReceiver;
/**
* Created by JoshG on 7/6/2015.
*/
public class AlarmReceiver extends WakefulBroadcastReceiver {
#Override
public void onReceive(final Context context, Intent intent) {
//MediaPlayer is used to play an mp3 file
final MediaPlayer mediaPlayer = MediaPlayer.create(context, R.drawable.om_mani_short);
mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mediaplayer) {
mediaplayer.stop();
mediaplayer.release();
}
});
mediaPlayer.start();
//this will update the UI with message
AlarmActivity inst = AlarmActivity.instance();
inst.setAlarmText("stretch");
//this will send a notification message
ComponentName comp = new ComponentName(context.getPackageName(),
AlarmService.class.getName());
startWakefulService(context, (intent.setComponent(comp)));
setResultCode(Activity.RESULT_OK);
}
}
AlarmActivity.java:
package com.joshbgold.move;
import android.app.Activity;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.ToggleButton;
import java.util.Calendar;
/**
* Created by JoshG on 7/6/2015.
*/
public class AlarmActivity extends Activity {
AlarmManager alarmManager;
private PendingIntent pendingIntent;
private TimePicker alarmTimePicker;
private static AlarmActivity inst;
private TextView alarmTextView;
public static AlarmActivity instance() {
return inst;
}
#Override
public void onStart() {
super.onStart();
inst = this;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
alarmTimePicker = (TimePicker) findViewById(R.id.alarmTimePicker);
alarmTextView = (TextView) findViewById(R.id.alarmText);
ToggleButton alarmToggle = (ToggleButton) findViewById(R.id.alarmToggle);
final Button exitButton = (Button) findViewById(R.id.exitButton);
alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
final MediaPlayer mediaPlayer = MediaPlayer.create(this, R.drawable.om_mani_short);
mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mediaplayer) {
mediaplayer.stop();
mediaplayer.release();
}
});
mediaPlayer.start();
View.OnClickListener quitApp = new View.OnClickListener() { //this block stops music when exiting
#Override
public void onClick(View view) {
if (mediaPlayer != null) try {
if (mediaPlayer.isPlaying()) {
mediaPlayer.stop();
mediaPlayer.release();
}
} catch (Exception e) {
Log.d("Alarm Activity", e.toString());
}
finish();
}
};
exitButton.setOnClickListener(quitApp);
}
public void onToggleClicked(View view) {
if (((ToggleButton) view).isChecked()) {
Log.d("MyActivity", "Alarm On");
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, alarmTimePicker.getCurrentHour());
calendar.set(Calendar.MINUTE, alarmTimePicker.getCurrentMinute());
Intent myIntent = new Intent(AlarmActivity.this, AlarmReceiver.class);
pendingIntent = PendingIntent.getBroadcast(AlarmActivity.this, 0, myIntent, 0);
alarmManager.set(AlarmManager.RTC, calendar.getTimeInMillis(), pendingIntent);
} else {
alarmManager.cancel(pendingIntent);
setAlarmText("Alarm Off");
Log.d("MyActivity", "Alarm Off");
}
}
public void setAlarmText(String alarmText) {
alarmTextView.setText(alarmText);
}
}
Alarm Service.java
package com.joshbgold.move;
import android.app.IntentService;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.support.v4.app.NotificationCompat;
import android.util.Log;
/**
* Created by JoshG on 7/6/2015.
*/
public class AlarmService extends IntentService {
private NotificationManager alarmNotificationManager;
public AlarmService() {
super("AlarmService");
}
#Override
public void onHandleIntent(Intent intent) {
sendNotification("stretch");
}
private void sendNotification(String msg) {
Log.d("AlarmService", "Preparing to send notification...: " + msg);
alarmNotificationManager = (NotificationManager) this
.getSystemService(Context.NOTIFICATION_SERVICE);
PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
new Intent(this, AlarmActivity.class), 0);
NotificationCompat.Builder alarmNotificationBuilder = new NotificationCompat.Builder(
this).setContentTitle("Reminder").setSmallIcon(R.mipmap.ic_launcher)
.setStyle(new NotificationCompat.BigTextStyle().bigText(msg))
.setContentText(msg);
alarmNotificationBuilder.setContentIntent(contentIntent);
alarmNotificationManager.notify(1, alarmNotificationBuilder.build());
Log.d("AlarmService", "Notification sent.");
}
}
Here is the contents of Logcat. I have it set to Log Level of Error:
07-07 18:53:13.119 13065-13065/com.joshbgold.move E/﹕ mali: REVISION=Linux-r3p2-01rel2 BUILD_DATE=Mon Nov 18 21:41:36 KST 2013
07-07 19:00:11.569 16746-16746/com.joshbgold.move E/AndroidRuntime﹕ FATAL EXCEPTION: main
java.lang.RuntimeException: Unable to start receiver com.joshbgold.move.AlarmReceiver: java.lang.NullPointerException
at android.app.ActivityThread.handleReceiver(ActivityThread.java:2469)
at android.app.ActivityThread.access$1600(ActivityThread.java:158)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1372)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:176)
at android.app.ActivityThread.main(ActivityThread.java:5365)
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:1102)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:869)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at com.joshbgold.move.AlarmReceiver.onReceive(AlarmReceiver.java:34)
at android.app.ActivityThread.handleReceiver(ActivityThread.java:2462)
at android.app.ActivityThread.access$1600(ActivityThread.java:158)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1372)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:176)
at android.app.ActivityThread.main(ActivityThread.java:5365)
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:1102)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:869)
at dalvik.system.NativeStart.main(Native Method)
If this is the class, line 34 is
inst.setAlarmText("stretch");
which points to the line above it not getting an actual activity
AlarmActivity inst = AlarmActivity.instance();
Check your AlarmActivity class to make sure inst is not null when it is created with the instance() method.
Can you post your AlarmActivity class to see how you are creating/fetching your instance?
//this will update the UI with message
AlarmActivity inst = AlarmActivity.instance();
inst.setAlarmText("stretch");
inst is null. You should check AlarmActivity.instance()
public static AlarmActivity instance() {
if (inst == null) {
// Do something such as inst = ...
}
return inst;
}
I took a sharp right turn, and did a different implementation when the reminder/alarm goes off. While I am doing something a little different then originally intended, the above answers provided led me in the correct direction.
Here is what I am using for AlarmReceiver.java:
package com.joshbgold.move;
import android.content.Context;
import android.content.Intent;
import android.support.v4.content.WakefulBroadcastReceiver;
public class AlarmReceiver extends WakefulBroadcastReceiver {
#Override
public void onReceive(final Context context, Intent intent) {
//this will change to new activity for Reminder(s) at the appropriate time
Intent myIntent = new Intent();
myIntent.setClassName("com.joshbgold.move", "com.joshbgold.move.ReminderActivity");
myIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(myIntent);
}
}
i am new to android development and i am writing an app for my college project .The app transmits a string of data stored in shared preferences .The data is stored by one time setup screen which is never shown again.The issue is after first time,when app is started again it shows that "app has unfortunately stopped working "and when i click ok the app starts.Can anybody tell me why this is happening?
Code:
package com.example.homeautomation.zigbeehomeauto;
import android.annotation.TargetApi;
import android.content.SharedPreferences;
import android.nfc.NdefMessage;
import android.nfc.NdefRecord;
import android.nfc.NfcAdapter;
import android.os.Build;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.View;
import android.widget.Toast;
public class MainScreen extends ActionBarActivity {
NdefMessage msg;
NfcAdapter nfcadapter;
public static final String PREFS_NAME = "MyPrefsFile";
public String pass2 ;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_screen);
SharedPreferences check = getSharedPreferences(PREFS_NAME, 0);
String Pass = check.getString("Str", "Nothing");
pass2 = Pass;
nfcadapter = NfcAdapter.getDefaultAdapter(this);
if (nfcadapter == null) {
Toast.makeText(this, "NFC is not available User", Toast.LENGTH_LONG)
.show();
finish();
}
}
public void ExApp(View v) {
finish();
System.exit(0);
}
#TargetApi(Build.VERSION_CODES.JELLY_BEAN)
public void Nsend(View v)
{
byte[] stringBytes = pass2.getBytes();
nfcadapter.setNdefPushMessage(msg = new NdefMessage(new NdefRecord[]{NdefRecord.createMime("text/plain", stringBytes)
}),this);
}
}
Logcat Ouput:
04-07 12:04:38.478 10836-10836/com.example.homeautomation.zigbeehomeauto E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.example.homeautomation.zigbeehomeauto, PID: 10836
android.util.SuperNotCalledException: Activity {com.example.homeautomation.zigbeehomeauto/com.example.homeautomation.zigbeehomeauto.SetupScreen} did not call through to super.onCreate()
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2510)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2603)
at android.app.ActivityThread.access$900(ActivityThread.java:174)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1321)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:146)
at android.app.ActivityThread.main(ActivityThread.java:5752)
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)
Check in your SetupScreen.java do you have super.onCreate(savedInstanceState);
after onCreate() Method is starts .
post your SetupScreen.java code also ..
Your onCreate() method of class SetupScreen do not call the super.onCreate(). Add the statement and the error should go away.
I have an app that when logged in by user the user redirects to main activity which had his personal details displayed and had two buttons to click: dashboard button redirected to his dashboard manager settings and a button log out. When logged in all is working fine showing his personal details and when I clicked dashboard button for his dashboard settings the app is unfortunately stopped. It said errors in my log cat which I can't fix with my own. I am new to Android. I searched and tried threads here in SO that has same problems with me but still can not be solved. Anybody with a great heart can help me to solve this? It's been quiet a week I'm stuck on this.
note* my dashboard button is calling another layout that contains two buttons
This is my main activity java :
package com.myapp;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONObject;
import library.JSONParser;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
public class ProfileView extends Activity implements OnClickListener{
private Button bLogout, backdashboard;
private TextView tvusername, tvfullname;
// Progress Dialog
private ProgressDialog pDialog;
// Creating JSON Parser object
JSONParser jsonParser = new JSONParser();
// Profile json object
JSONArray user;
JSONObject display;
//String name for my sharedpref extras
String ngalan;
// Profile JSON url
private static final String PROFILE_URL = "http://10.0.2.2/webservice/profile.php";
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.profile);
//setup textview
tvusername=(TextView)(findViewById(R.id.tvusernamedisplay));
tvfullname=(TextView)(findViewById(R.id.tvfullname));
//settup buttons
backdashboard=(Button)(findViewById(R.id.backdashboard));
bLogout=(Button)(findViewById(R.id.blogout));
//button listener
backdashboard.setOnClickListener(this);
bLogout.setOnClickListener(this);
Bundle extras = getIntent().getExtras();
if (extras.containsKey("username")) {
ngalan = extras.getString("username");
// Loading Profile in Background Thread
new LoadProfile().execute();
}
}
#Override
public void onClick(View args) {
// TODO Auto-generated method stub
switch (args.getId()) {
case R.id.backdashboard:
Intent r = new Intent(this, Dashboard.class);
startActivity(r);
finish();
break;
case R.id.blogout:
new AlertDialog.Builder(this)
.setTitle("Logout")
.setMessage("Would you like to logout?")
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// logout
Intent myIntent = new Intent(ProfileView.this, LoginActivity.class);
myIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);// clear back stack
startActivity(myIntent);
finish();
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// user doesn't want to logout
}
})
.show();
default:
break;
}
}
class LoadProfile extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(ProfileView.this);
pDialog.setMessage("Loading Profile ...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
/**
* getting Profile JSON
* */
protected String doInBackground(String... args) {
// Building Parameters
String json = null;
try {
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("username", ngalan));
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(PROFILE_URL);
httppost.setEntity(new UrlEncodedFormEntity(params));
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
HttpEntity resEntity = response.getEntity();
json = EntityUtils.toString(resEntity);
Log.i("Profile JSON: ", json.toString());
} catch (Exception e) {
e.printStackTrace();
}
return json;
}
#Override
protected void onPostExecute(String json) {
super.onPostExecute(json);
// dismiss the dialog after getting all products
pDialog.dismiss();
try
{
display = new JSONObject(json);
JSONArray user = display.getJSONArray("user");
JSONObject jb= user.getJSONObject(0);
String idnum = jb.getString("username");
String fulname = jb.getString("lastname");
// displaying all data in textview
tvusername.setText(idnum );
tvfullname.setText(fulname);
}catch(Exception e)
{
e.printStackTrace();
}
}
}
}
This is my Dashboard activity java another activity calls when dashboard button is clicked...
package com.myapp;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class Dashboard extends Activity implements OnClickListener{
private Button view, manage, logout;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.dashboard);
initialise();
}
private void initialise() {
// TODO Auto-generated method stub
//settup buttons
manage=(Button)(findViewById(R.id.bManage));
view=(Button)(findViewById(R.id.bView));
logout=(Button)(findViewById(R.id.blogout));
//button listener
manage.setOnClickListener(this);
view.setOnClickListener(this);
logout.setOnClickListener(this);
}
#Override
public void onClick(View item) {
// TODO Auto-generated method stub
switch (item.getId()) {
case R.id.bManage:
Intent r = new Intent(this, Manage.class);
startActivity(r);
finish();
break;
case R.id.bView:
Intent l = new Intent(this, View.class);
startActivity(l);
finish();
break;
case R.id.blogout:
new AlertDialog.Builder(this)
.setTitle("Logout")
.setMessage("Would you like to logout?")
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// logout
Intent myIntent = new Intent(Dashboard.this, LoginActivity.class);
myIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);// clear back stack
startActivity(myIntent);
finish();
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// user doesn't want to logout
}
})
.show();
default:
break;
}
}
}
This is my log cat error message"
08-23 18:59:36.949: E/AndroidRuntime(900): FATAL EXCEPTION: main
08-23 18:59:36.949: E/AndroidRuntime(900): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.myapp/com.myapp.Dashboard}: java.lang.NullPointerException
Please help me guys :(
This is the full logcat message:
Unable to start activity ComponentInfo{com.myapp/com.myapp.Dashboard}: java.lang.NullPointerException
08-23 18:59:36.949: E/AndroidRuntime(900): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2180)
08-23 18:59:36.949: E/AndroidRuntime(900): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
08-23 18:59:36.949: E/AndroidRuntime(900): at android.app.ActivityThread.access$600(ActivityThread.java:141)
08-23 18:59:36.949: E/AndroidRuntime(900): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
08-23 18:59:36.949: E/AndroidRuntime(900): at android.os.Handler.dispatchMessage(Handler.java:99)
08-23 18:59:36.949: E/AndroidRuntime(900): at android.os.Looper.loop(Looper.java:137)
08-23 18:59:36.949: E/AndroidRuntime(900): at android.app.ActivityThread.main(ActivityThread.java:5039)
08-23 18:59:36.949: E/AndroidRuntime(900): at java.lang.reflect.Method.invokeNative(Native Method)
08-23 18:59:36.949: E/AndroidRuntime(900): at java.lang.reflect.Method.invoke(Method.java:511)
08-23 18:59:36.949: E/AndroidRuntime(900): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
08-23 18:59:36.949: E/AndroidRuntime(900): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
08-23 18:59:36.949: E/AndroidRuntime(900): at dalvik.system.NativeStart.main(Native Method)
08-23 18:59:36.949: E/AndroidRuntime(900): Caused by: java.lang.NullPointerException
08-23 18:59:36.949: E/AndroidRuntime(900): at com.myapp.Dashboard.onCreate(Dashboard.java:27)
08-23 18:59:36.949: E/AndroidRuntime(900): at android.app.Activity.performCreate(Activity.java:5104)
08-23 18:59:36.949: E/AndroidRuntime(900): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1080)
08-23 18:59:36.949: E/AndroidRuntime(900): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2144)
08-23 18:59:36.949: E/AndroidRuntime(900): ... 11 more
I guess that NPE occurs in this line: grade.setOnClickListener(this);
You don't initialize this variable anywhere.
All right, so I've been a few hours on this, and can't get it to work.
Basically, I wanna call an intent from a clickable listview. I'm displaying car models and it's code on a list, when you click, you're supposed to be taken to another screen to edit the car's properties, however, I'm beggining to think it's impossible
listAdapter = new ArrayAdapter<String>(this, R.layout.simplerow, arrayListCarros);
mainListView.setAdapter( listAdapter );
db.close();
mainListView.setClickable(true);
mainListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3) {
Intent i = new Intent(listagemcarro.this,com.example.trabalhosql.edicao.class);
startActivity(i);
}
});
The rest of the code:
public class listagemcarro extends Activity {
Button buttonCadastro;
Button buttonListagem;
Button buttonBusca;
Button button1;
Intent itListagem = new Intent();
Intent itCadastro = new Intent();
Intent itBusca = new Intent();
//Intent itEdicao = new Intent();
Intent itEdicao2 = new Intent();
String id="";
public SQLiteDatabase db;
public String BANCO = "banco.db";
public String TABELA = "carro";
int posicao=123123;
private ListView mainListView ;
private ArrayAdapter<String> listAdapter ;
public void toast(int position){
Context context = getApplicationContext();
Toast toast = Toast.makeText(context, position, Toast.LENGTH_SHORT);
toast.show();
}
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.listagemcarro);
Intent itRecebeParametros = getIntent();
if(itRecebeParametros != null){
id = itRecebeParametros.getStringExtra("id");
}
db = openOrCreateDatabase(BANCO, Context.MODE_PRIVATE, null);
Cursor linhas = db.query(TABELA, new String[] {"ID_PESSOA, MODELO"},"id_pessoa = '"+id+"'", null, null, null, null);
mainListView = (ListView) findViewById( R.id.mainListView );
ArrayList <String>arrayListCarros = new ArrayList<String> ();
if(linhas.moveToFirst()){
do{
arrayListCarros.add(linhas.getString(0) +" " + linhas.getString(1));
}
while(linhas.moveToNext());
}
listAdapter = new ArrayAdapter<String>(this, R.layout.simplerow, arrayListCarros);
mainListView.setAdapter( listAdapter );
db.close();
mainListView.setClickable(true);
mainListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3) {
Intent i = new Intent(listagemcarro.this,com.example.trabalhosql.edicao.class);
startActivity(i);
}
});
}
error
11-19 23:18:09.136: W/dalvikvm(1784): threadid=3: thread exiting with uncaught exception (group=0x4001b188)
11-19 23:18:09.136: E/AndroidRuntime(1784): Uncaught handler: thread main exiting due to uncaught exception
11-19 23:18:09.147: E/AndroidRuntime(1784): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.trabalhosql/com.example.trabalhosql.edicao}: java.lang.NullPointerException
11-19 23:18:09.147: E/AndroidRuntime(1784): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2496)
11-19 23:18:09.147: E/AndroidRuntime(1784): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2512)
11-19 23:18:09.147: E/AndroidRuntime(1784): at android.app.ActivityThread.access$2200(ActivityThread.java:119)
11-19 23:18:09.147: E/AndroidRuntime(1784): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1863)
11-19 23:18:09.147: E/AndroidRuntime(1784): at android.os.Handler.dispatchMessage(Handler.java:99)
11-19 23:18:09.147: E/AndroidRuntime(1784): at android.os.Looper.loop(Looper.java:123)
11-19 23:18:09.147: E/AndroidRuntime(1784): at android.app.ActivityThread.main(ActivityThread.java:4363)
11-19 23:18:09.147: E/AndroidRuntime(1784): at java.lang.reflect.Method.invokeNative(Native Method)
11-19 23:18:09.147: E/AndroidRuntime(1784): at java.lang.reflect.Method.invoke(Method.java:521)
11-19 23:18:09.147: E/AndroidRuntime(1784): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:860)
11-19 23:18:09.147: E/AndroidRuntime(1784): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:618)
11-19 23:18:09.147: E/AndroidRuntime(1784): at dalvik.system.NativeStart.main(Native Method)
11-19 23:18:09.147: E/AndroidRuntime(1784): Caused by: java.lang.NullPointerException
11-19 23:18:09.147: E/AndroidRuntime(1784): at com.example.trabalhosql.edicao.onCreate(edicao.java:42)
11-19 23:18:09.147: E/AndroidRuntime(1784): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
11-19 23:18:09.147: E/AndroidRuntime(1784): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2459)
11-19 23:18:09.147: E/AndroidRuntime(1784): ... 11 more
edicao.class
package com.example.trabalhosql;
import java.util.ArrayList;
import android.os.Bundle;
import android.app.Activity;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
public class edicao extends Activity {
String id="";
String modeloCarro = "";
TextView textViewCarroEscolhido;
public SQLiteDatabase db;
public String BANCO = "banco.db";
public String TABELA = "carro";
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.listagemcarro);
Intent itRecebeParametros = getIntent();
if(itRecebeParametros != null){
id = itRecebeParametros.getStringExtra("id");
modeloCarro = itRecebeParametros.getStringExtra("modeloCarro");
}
textViewCarroEscolhido = (TextView) findViewById(R.id.textViewCarroEscolhido);
textViewCarroEscolhido.setText(modeloCarro);
}
}
EDIT
I'm guessing that this part of the edicao class is incorrect:
setContentView(R.layout.listagemcarro);
That itself might not have thrown the error, but trying to finding views (like your textView) in it that don't exist would.
textViewCarroEscolhido is null. Make sure that it exists in listagemcarro.xml
In case anyone comes here for calling intents in drawing situations such as canvas. Ensure you are not calling the intent multiple times. In my situation the invalidate() method kept getting called and made many intent calls. Ensure to use some sort of flip mechanism to stop invalidate() from being called. Will work like a charm.