I am trying to work on my android project but getting a null pointer exception in my main function.
So, based on the input id, i wish to set the id entered from the editText and retrieve it when i call the get function which will complete my where clause for the condition.
here is my code:
/*---GetSet.java ---- */
public class GetSet {
long gwid=0;
public void setId(long id)
{
gwid = id;
}
public long getId()
{
return gwid;
}
}
The following is my MainActivity.java file
public class MainActivity extends Activity {
EditText etGWid;
Button OKbtn;
public final static String EXTRA_MESSAGE = "com.example.myfirstapp.MESSAGE";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
etGWid = (EditText)findViewById(R.id.etGWID);
OKbtn = (Button)findViewById(R.id.OKbtn);
final GetSet obj_getset = null;
final SharedPreferences app_preferences = PreferenceManager.getDefaultSharedPreferences(this);
// Create a shared preferences variable using the SharedPreferenceManager for storing GWids
SharedPreferences.Editor editor = app_preferences.edit(); // We also need a shared preferences editor to handle the shared preference requests
// Call the edit method (library function) to editor variable can edit the key, values.
editor.putInt("47688507", 47688507); // put in the shared preferences values of user GWids and give them a key for retrieval purposes
editor.putInt("1234567", 1234567);
editor.putInt("7654321", 7654321);
editor.commit(); //commit is necessary to save the shared preferences
OKbtn.setOnClickListener(new View.OnClickListener() {
#SuppressWarnings("null")
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
String gwidCheck = etGWid.getText().toString(); //get the value user enters for GWid
if(app_preferences.contains(gwidCheck)) // this will check the stored shared preferences and compare with the value entered
{
Context context = getApplicationContext();
CharSequence text = "Login Successfull";
int duration = Toast.LENGTH_SHORT; //If it exists, then create a toast message for success
//etGWid.setText(""); // make the textbox empty
long setid = Long.parseLong(gwidCheck); // take the string gwid and convert to long
obj_getset.setId(setid); // set the gwid entered
Toast toast = Toast.makeText(context, text, duration);
toast.show();
intentfunction();
}
else
{
Context context = getApplicationContext();
CharSequence text = "Login Failed"; // If doesnt exist, create a toast for fail
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
}
}
});
}
private void intentfunction()
{
Intent intent = new Intent(this, SelectOptions.class);
//editText = (EditText) findViewById(R.id.editText1);
//editText = new EditText(this);
String message = "TestHello";
intent.putExtra(EXTRA_MESSAGE, message);
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;
}
}
Line number 69 is where i get the problem which is the foll line:
obj_getset.setId(setid);
And this is one of a method in MySQLitehelper.java file that is used to retrieve the row based on the id:
public Cursor getRecord(long rowId) throws SQLException
{
Cursor mCursor =
db.query(true, TABLE_NAME, new String[] {COLUMN_ID,
COLUMN_DATE, COLUMN_LOCATION, COLUMN_TIME},
COLUMN_ID + "=" + getset.getId(), null, null, null, null, null);
if (mCursor != null)
{
mCursor.moveToFirst();
}
return mCursor;
}
My Question is, how do I set the value entered by the user so I can get the value and based on that value, I can put the condition in my where clause just like above. Where am I going wrong ?
LogCat
11-29 21:19:22.525: D/AndroidRuntime(10323): Shutting down VM
11-29 21:19:22.525: W/dalvikvm(10323): threadid=1: thread exiting with uncaught exception (group=0x40a70930)
11-29 21:19:22.583: E/AndroidRuntime(10323): FATAL EXCEPTION: main
11-29 21:19:22.583: E/AndroidRuntime(10323): java.lang.NullPointerException
11-29 21:19:22.583: E/AndroidRuntime(10323): at com.example.upd.MainActivity$1.onClick(MainActivity.java:69)
11-29 21:19:22.583: E/AndroidRuntime(10323): at android.view.View.performClick(View.java:4202)
11-29 21:19:22.583: E/AndroidRuntime(10323): at android.view.View$PerformClick.run(View.java:17340)
11-29 21:19:22.583: E/AndroidRuntime(10323): at android.os.Handler.handleCallback(Handler.java:725)
11-29 21:19:22.583: E/AndroidRuntime(10323): at android.os.Handler.dispatchMessage(Handler.java:92)
11-29 21:19:22.583: E/AndroidRuntime(10323): at android.os.Looper.loop(Looper.java:137)
11-29 21:19:22.583: E/AndroidRuntime(10323): at android.app.ActivityThread.main(ActivityThread.java:5039)
11-29 21:19:22.583: E/AndroidRuntime(10323): at java.lang.reflect.Method.invokeNative(Native Method)
11-29 21:19:22.583: E/AndroidRuntime(10323): at java.lang.reflect.Method.invoke(Method.java:511)
11-29 21:19:22.583: E/AndroidRuntime(10323): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
11-29 21:19:22.583: E/AndroidRuntime(10323): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
11-29 21:19:22.583: E/AndroidRuntime(10323): at dalvik.system.NativeStart.main(Native Method)
11-29 21:19:25.702: I/Process(10323): Sending signal. PID: 10323 SIG: 9
Program closes down unexpectedly.
final GetSet obj_getset = null;
Well of course you're getting a nullPointerException; Your obj_getset is defined to be null right there.
Related
I was using an integer for the money factor in this little test app but I realized that long was more appropriate and I changed the code so that money is a long instead of an int and I changed SharedPreferences appropriately as well, however it does not work wheras it did when I used int. Thank you for the help!
public class Home extends AppCompatActivity {
SharedPreferences pref;
SharedPreferences.Editor editor;
Intent intent;
TextView home_money_view;
long money; // this is the variable that is causing problems
int initial;
final long TEST = (long)-1;
int gold_pieces;
int gold_price = 50;
TimerTask timerTask;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
home_money_view = (TextView) findViewById(R.id.home_money_view)
pref = getApplicationContext().getSharedPreferences("MY_PREFS", MODE_PRIVATE);
editor = pref.edit();
money = pref.getLong("temp_money",Long.MIN_VALUE); // get value
if (money==Long.MIN_VALUE){
money=0;
}
gold_pieces = pref.getInt("temp_gold",-1);
if (gold_pieces==-1){
gold_pieces=0;
}
initial = pref.getInt("initial",0);
money+=initial;
editor.putInt("initial",0);
editor.commit();
home_money_view = (TextView) findViewById(R.id.home_money_view);
home_money_view.setText(money+"");
editor.commit();
}
public void backToSplash(View view){
intent = new Intent(Home.this,BusinessSelector.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
}
public void goToSecondView(View view){
long temp_money = money;
editor.putLong("temp_money",temp_money); // set value
int temp_gold = gold_pieces;
editor.putInt("temp_gold",temp_gold);
editor.commit();
intent = new Intent(Home.this,SecondView.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
}
public void goToOtherView(View view) {
long temp_money = money;
editor.putLong("temp_money",temp_money); // set value
int temp_gold = gold_pieces;
editor.putInt("temp_gold", temp_gold);
editor.commit();
intent = new Intent(Home.this, Next.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
}
}
Logcat:
04-13 19:01:03.675 12896-12896/com.exampleryancocuzzo.ryan.markettycoon E/AndroidRuntime: FATAL EXCEPTION: main
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.exampleryancocuzzo.ryan.markettycoon/com.exampleryancocuzzo.ryan.markettycoon.Home}: java.lang.ClassCastException: java.lang.Integer cannot be cast to java.lang.Long
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1956)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1981)
at android.app.ActivityThread.access$600(ActivityThread.java:123)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1147)
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: java.lang.ClassCastException: java.lang.Integer cannot be cast to java.lang.Long
at android.app.SharedPreferencesImpl.getLong(SharedPreferencesImpl.java:228)
at com.exampleryancocuzzo.ryan.markettycoon.Home.onCreate(Home.java:56)
at android.app.Activity.performCreate(Activity.java:4466)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1049)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1920)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1981)
at android.app.ActivityThread.access$600(ActivityThread.java:123)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1147)
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)
I am working on a financial app and i have to use BigDecimal to calculate currency.Now I am trying to make one entrance activity which is searching in the SharedPreferences for a previous registration and if their is one it starts another activity , if not it starts the registration activity.The problem is the registration activity causes NumberFormatException Error while I am trying to construct a new object of time Profit (the Profit class contains BigDecimal field).Also I am not quite sure that I am using SharedPreferences right.I am not quite sure that my idea and my coding are fine because I am new at android development and i am stuck with this problem so I am giving you all the classes.
the Registration activity:
public class Registration extends Activity {
private static String enteredPassword;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
final EditText password1 = (EditText) findViewById(R.id.password1);
final EditText password2 = (EditText) findViewById(R.id.password2);
final EditText availability = (EditText) findViewById(R.id.availability);
EditText profitEditText = (EditText) findViewById(R.id.profit);
Spinner spinner = (Spinner) findViewById(R.id.period_spinner);
Button registrationButton = (Button) findViewById(R.id.registrationButton);
DatePicker picker = (DatePicker) findViewById(R.id.thePicker);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this,
R.array.periods_array, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
final String balance = availability.getText().toString().replace(",",".");
String profitPeriod = ((Period) spinner.getSelectedItem()).name();
final Profit profit = new Profit("regular_profit", profitEditText.getText().toString(),
profitPeriod ,picker);
registrationButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (password1.getText().toString().equals(password2.getText().toString())) {
enteredPassword = password1.getText().toString();
Repository.setPassword(enteredPassword, mContext);
}
Repository.setBalance(balance, mContext);
Repository.setProfit(profit, mContext);
}
});
}
}
the profit activity
public class Profit {
private Date mProfitDate;
private Date mNextProfitDate;
private BigDecimal value;
public final static String TITLE = "title";
public final static String PERIOD = "period";
Profit(String title,String value, String period, DatePicker picker) {
this.mTitle = title;
if(value!=null){this.value = new BigDecimal(value);}else{ this.value = new BigDecimal("0.0");};
this.mPeriod = Period.class.cast(period);
this.mProfitDate = Repository.getDateFromPicker(picker);
}
public long getNextProfitDate(Date profitDate, Period period){
long unixProfitDate = profitDate.getTime() / 1000L;
long nextProfitDate=0;
switch (period){
case DAILY:
nextProfitDate = DateUtils.DAY_IN_MILLIS/1000 + unixProfitDate;
break;
case WEEKLY:
nextProfitDate = DateUtils.WEEK_IN_MILLIS/1000 + unixProfitDate;
break;
case MONTHLY:
Date dateNow = new Date();
dateNow.getTime();
nextProfitDate = Repository.monthsToSeconds(Calendar.getInstance()
.get(Calendar.MONTH)) + unixProfitDate;
break;
case YEARLY:
nextProfitDate = DateUtils.YEAR_IN_MILLIS/1000 + unixProfitDate;
break;
}
return nextProfitDate;
}
}
the entrance activity
public class EnterActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_enter);
CountDownTimer timer = new CountDownTimer(3000, 100) {
public void onTick(long millisUntilFinished) {
}
public void onFinish() {
if(Repository.getPassword(mContext.getApplicationContext()).equals("No Value")){
Intent registrationIntent = new Intent(mContext, Registration.class);
startActivity(registrationIntent);
}
else{
Intent configurationIntent = new Intent(mContext, Configuration.class);
startActivity(configurationIntent);
}
}
}.start();
}
}
the Repository
public class Repository {
public static SharedPreferences sharedPreferences;
private static SharedPreferences getPrefs(Context context) {
return context.getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE);
}
public static String getPassword(Context context){
return getPrefs(context).getString(PASSWORD,"No Value");
}
public Repository() {
}
public static void setPassword(String password, Context context){
SharedPreferences.Editor editor = getPrefs(context).edit();
editor.putString(PASSWORD, password);
editor.commit();
}
public static void setBalance(String balance, Context context){
SharedPreferences.Editor editor = getPrefs(context).edit();
editor.putString(BALANCE, balance);
editor.commit();
}
public static void setProfit(Profit profit, Context context){
SharedPreferences.Editor editor = getPrefs(context).edit();
editor.putString(BALANCE, profit.getValue().toString());
editor.commit();
}
}
the output
E/AndroidRuntime: FATAL EXCEPTION: main
E/AndroidRuntime: java.lang.RuntimeException: Unable to start activity ComponentInfo{/.Registration}: java.lang.NumberFormatException: Bad offset/length: offset=0 len=0 in.length=0
E/AndroidRuntime: at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1956)
E/AndroidRuntime: at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1981)
E/AndroidRuntime: at android.app.ActivityThread.access$600(ActivityThread.java:123)
E/AndroidRuntime: at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1147)
E/AndroidRuntime: at android.os.Handler.dispatchMessage(Handler.java:99)
E/AndroidRuntime: at android.os.Looper.loop(Looper.java:137)
E/AndroidRuntime: at android.app.ActivityThread.main(ActivityThread.java:4424)
E/AndroidRuntime: at java.lang.reflect.Method.invokeNative(Native Method)
E/AndroidRuntime: at java.lang.reflect.Method.invoke(Method.java:511)
E/AndroidRuntime: at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
E/AndroidRuntime: at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
E/AndroidRuntime: at dalvik.system.NativeStart.main(Native Method)
E/AndroidRuntime: Caused by: java.lang.NumberFormatException: Bad offset/length: offset=0 len=0 in.length=0
E/AndroidRuntime: at java.math.BigDecimal.<init>(BigDecimal.java:282)
E/AndroidRuntime: at java.math.BigDecimal.<init>(BigDecimal.java:438)
E/AndroidRuntime: at .Profit.<init>(Profit.java:41)
E/AndroidRuntime: at .Registration.onCreate(Registration.java:57)
E/AndroidRuntime: at android.app.Activity.performCreate(Activity.java:4466)
E/AndroidRuntime: at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1049)
E/AndroidRuntime: at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1920)
E/AndroidRuntime: at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1981)
E/AndroidRuntime: at android.app.ActivityThread.access$600(ActivityThread.java:123)
E/AndroidRuntime: at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1147)
E/AndroidRuntime: at android.os.Handler.dispatchMessage(Handler.java:99)
E/AndroidRuntime: at android.os.Looper.loop(Looper.java:137)
E/AndroidRuntime: at android.app.ActivityThread.main(ActivityThread.java:4424)
E/AndroidRuntime: at java.lang.reflect.Method.invokeNative(Native Method)
E/AndroidRuntime: at java.lang.reflect.Method.invoke(Method.java:511)
E/AndroidRuntime: at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
E/AndroidRuntime: at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
E/AndroidRuntime: at dalvik.system.NativeStart.main(Native Method)
You instantiate a Profit in only one place in the code you presented:
Profit profit = new Profit("regular_profit", profitEditText.getText().toString(),
profitPeriod, picker);
If that causes a NumberFormatException then it must come from this code in the Profit constructor:
if(value!=null){this.value = new BigDecimal(value);}else{ this.value = new BigDecimal("0.0");};
Since the value String will have come from invoking toString() on an object, you can rely on it to not be null (and anyway, if it were null then you would end up at new BigDecimal("0.0"), and you can verify for yourself that that works fine). That leaves us with new BigDecimal(value) as the culprit. The docs for this constructor provide details of the expected format of the argument string. If the argument does not comply with that format then a NumberFormatException will be thrown.
Among the more likely malformed strings that one might imagine in a scenario such as you describe is an empty string, which is not the same as null in Java. Given that the text is coming from a UI field, you also have to watch out for fun and difficult-to-spot malformations such as leading and trailing whitespace.
Perhaps it would be better to write the affected part of the constructior like so:
if (value != null) {
value = value.trim();
this.value = value.length() == 0 ? BigDecimal.ZERO : new BigDecimal(value);
} else {
this.value = BigDecimal.ZERO;
}
Do note that even with that change, this constructor will still throw NumberFormatException in the event of other kinds of malformation. Wherever you are uncertain about the validity of the data, you should be prepared to handle such an exception.
You aren't parsing your string to a Big Decimal correctly.
The following in your Profit contructor:
if(value!=null)
{
this.value = new BigDecimal(value);
}
else
{
this.value = new BigDecimal("0.0");
}
Needs to parse the string to a BigDecimal. Like the following where this.value is of type BigDecimal:
this.value = (BigDecimal) decimalFormat.parse(value);
Also keep in mind that decimalFormat.parse can throw a ParseException. You will need to handle it with try/catch or throw it.
I am very new to android. I have a counter on some SomeActivity, but when I get to the page corresponding to SomeActivity, my app crashes :
final TextView counter = (TextView) findViewById(R.id.laws_counter);
ImageView handDown = (ImageView) findViewById(R.id.handViewDown);
counter.setText("" + 0);
I want that on click of the handown, the counter is idented by -1. Here's
handDown.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(NewsActivity.this,
"The favorite list would appear on clicking this icon",
Toast.LENGTH_LONG).show();
setDown();
}
private void setDown() {
String count = counter.getText().toString();
int now_count = Integer.parseInt(count) +1;
counter.setText(String.valueOf(now_count));
}
});
Is this code correct ?
Update : here's the logcat
10-22 00:18:05.579: ERROR/AndroidRuntime(378): FATAL EXCEPTION: main
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.donnfelker.android.bootstrap/com.donnfelker.android.bootstrap.ui.NewsActivity}: java.lang.NullPointerException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1647)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1663)
at android.app.ActivityThread.access$1500(ActivityThread.java:117)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:931)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:123)
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:839)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at com.donnfelker.android.bootstrap.ui.NewsActivity.onCreate(NewsActivity.java:41)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1611)
... 11 more
There are many ways that you can implement that functionality but think this would be an easy solution.
Make a helper method:
public class PreferencesData {
public static void saveInt(Context context, String key, int value) {
SharedPreferences sharedPrefs = PreferenceManager
.getDefaultSharedPreferences(context);
sharedPrefs.edit().putInt(key, value).commit();
}
public static int getInt(Context context, String key, int defaultValue) {
SharedPreferences sharedPrefs = PreferenceManager
.getDefaultSharedPreferences(context);
return sharedPrefs.getInt(key, defaultValue);
}
}
Then simply call the putInt method to save the counter in any Activity and getInt to get it again in any other Activity. As long as you use the same key both places.
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.
I'm developing an app for Android that lets someone send an sms to someone and send an automatic reply to that number if they text back. I'm approaching this with SharedPreferences:
public final String file = "AutoReply";
String autoReply;
public static String returned = "";
static SharedPreferences folder;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
folder = getSharedPreferences(file, 0);
returned = folder.getString("autoReplyKey", "");
if(returned.equals("")) {
SharedPreferences.Editor edit = folder.edit();
edit.putString("autoReplyKey", "Please don't respond to this phone number. Your friend borrowed my phone to text you.");
edit.commit();
}
Here's how someone changes the default message:
LayoutInflater inflater3 = LayoutInflater.from(this);
final View autoReply = inflater3.inflate(R.layout.auto_reply, null);
final EditText autoreplytext = (EditText)findViewById(R.id.autoReplyText);
final AlertDialog.Builder alert3 = new AlertDialog.Builder(this);
alert3.setTitle("Set Auto Reply Message");
alert3.setView(autoReply);
alert3.setPositiveButton("Set", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
String autoData = autoreplytext.getText().toString().trim();
SharedPreferences.Editor editor = folder.edit();
editor.putString("passwordKey", autoData);
editor.commit();
returned = folder.getString("AutoReplyKey", "couldn't load data");
}
});
alert3.show();
return true;
The problem is whenever I try to change the default message by using the AlertDialog, a NullPointerException error appears. Does anyone have any idea how to fix this?
Edit:
Here's the logcat:
09-09 19:43:23.145: E/AndroidRuntime(1370): FATAL EXCEPTION: main
09-09 19:43:23.145: E/AndroidRuntime(1370): java.lang.NullPointerException
09-09 19:43:23.145: E/AndroidRuntime(1370): at com.mshaw.avanosplus.MainActivity$16.onClick(MainActivity.java:395)
09-09 19:43:23.145: E/AndroidRuntime(1370): at com.android.internal.app.AlertController$ButtonHandler.handleMessage(AlertController.java:166)
09-09 19:43:23.145: E/AndroidRuntime(1370): at android.os.Handler.dispatchMessage(Handler.java:99)
09-09 19:43:23.145: E/AndroidRuntime(1370): at android.os.Looper.loop(Looper.java:137)
09-09 19:43:23.145: E/AndroidRuntime(1370): at android.app.ActivityThread.main(ActivityThread.java:4424)
09-09 19:43:23.145: E/AndroidRuntime(1370): at java.lang.reflect.Method.invokeNative(Native Method)
09-09 19:43:23.145: E/AndroidRuntime(1370): at java.lang.reflect.Method.invoke(Method.java:511)
09-09 19:43:23.145: E/AndroidRuntime(1370): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
09-09 19:43:23.145: E/AndroidRuntime(1370): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
09-09 19:43:23.145: E/AndroidRuntime(1370): at dalvik.system.NativeStart.main(Native Method)
As others wrote in comments, you really need to not only show the stack trace from logcat, but tell us where line 395 is. Otherwise, we can only guess which of the many possible references contained a null.
That said, I'm going to take a stab at this and guess, by elimination of other possibilities, that the culprit is autoreplytext. Although you didn't show us your XML for the views, I suspect that you need to change this line:
final EditText autoreplytext = (EditText)findViewById(R.id.autoReplyText);
to
final EditText autoreplytext = (EditText)autoReply.findViewById(R.id.autoReplyText);
The first line searches in the content view for your main activity -- in other words, it searches within R.layout.activity_main. But it looks like you're looking for a View that's contained inside the Dialog View, autoReply. To get that, you'd need the second form.