How to automatically send a sms to a predefined phone number - java

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.

Related

How to fix error in Dialog after dismiss and click again?

I'm developing webview app, the problem in OnJsAlert that when i click on the Dialog it opens after dismiss it and click again it stop my app, for sorry i can't get the problem from debugging.
This is my MainActivity.class
#Override
public boolean onJsAlert(WebView view, String url, final String alertSource, final JsResult alertResult) {
alertDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
alertDialog.setContentView(R.layout.activity_alert);
alertDialog.setCancelable(true);
TextView alertMessage = alertDialog.findViewById(R.id.alert_text);
alertMessage.setText(alertSource);
alertDialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
alertDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
#Override
public void onCancel(DialogInterface dialog) {
alertResult.cancel();
}
});
alertDialog.show();
return true;
}
Edited : Log
W/InputEventReceiver: Attempted to finish an input event but the input event receiver has already been disposed.
E/ViewRootImpl: sendUserActionEvent() mView == null
W/System.err: android.util.AndroidRuntimeException: requestFeature() must be called before adding content
W/System.err: at com.android.internal.policy.impl.PhoneWindow.requestFeature(PhoneWindow.java:331)
at android.app.Dialog.requestWindowFeature(Dialog.java:1057)
at com.xcoder.stepview.MainActivity$4.onJsAlert(MainActivity.java:285)
at com.android.webview.chromium.WebViewContentsClientAdapter.handleJsAlert(WebViewContentsClientAdapter.java:606)
at com.android.org.chromium.android_webview.AwContentsClientBridge.handleJsAlert(AwContentsClientBridge.java:73)
at com.android.org.chromium.base.SystemMessageHandler.nativeDoRunLoopOnce(Native Method)
at com.android.org.chromium.base.SystemMessageHandler.handleMessage(SystemMessageHandler.java:27)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:146)
at android.app.ActivityThread.main(ActivityThread.java:5641)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
W/System.err: at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1288)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1104)
at dalvik.system.NativeStart.main(Native Method)
A/libc: Fatal signal 6 (SIGABRT) at 0x00002c6d (code=-6), thread 11373 (xcoder.stepview)
Application terminated.
Your alertDialog is created before public boolean onJsAlert(...) method called and when it's called second time you got AndroidRuntimeException: requestFeature() must be called before adding content because of you can't use requestWindowFeature() with created dialog. You have to create new instance of dialog in this method or reuse global defined dialog.

My AsyncTask in another class is causing NullPointerException when it is called in this class

I am quite new to android development and I am facing a NullPointerException when I am trying to call an AsyncTask which is an inner class in another class.
I believe it is the way I am instantiating it but this is what I have:
// This onClick is in my adapter class - which is a separate Java File and class
#Override
public void onClick(View v) {
UploadRes uploadRes = new UploadRes();
UploadRes.UploadResConfirm uploadResConfirm = uploadRes.new UploadResConfirm(v.getContext());
uploadResConfirm.execute(fileName, filePath);
}
public class UploadResConfirm extends AsyncTask<String, String, String> {
Dialog dialog;
Context context;
public UploadResConfirm(Context context){
this.context = context;
}
#Override
protected void onPreExecute(){
dialog = new Dialog(UploadRes.this);
dialog.setTitle("Currently uploading");
dialog.show();
}
I believe it has got something to do with the dialog box itself being instantiated in the AsyncTask class.
The error stack trace on Logcat - its the Dialog, I think its in the wrong place...
java.lang.NullPointerException
at codeman.androapp.UploadRes$UploadResConfirm.onPreExecute(UploadRes.java:246)
at android.os.AsyncTask.executeOnExecutor(AsyncTask.java:586)
at android.os.AsyncTask.execute(AsyncTask.java:534)
at android.view.View.performClick(View.java:4240)
at android.view.View$PerformClick.run(View.java:17721)
at android.os.Handler.handleCallback(Handler.java:730)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:5103)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:525)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
at dalvik.system.NativeStart.main(Native Method)
Some help if any would be much obliged.
Instead of dialog = new Dialog(UploadRes.this);
Try
dialog = new Dialog(context);
your are passing a wrong context to create dialog.

Android Orientation change results in app crashing

This has only happened once but I'm a bit concerned with it. I was testing the app changing the orientation and the application crashed. Never happened before so just want to see if anyone else has had this issue and what I could do to fix it. Please see the log below:
05-15 12:13:07.304: E/AndroidRuntime(2596): FATAL EXCEPTION: main
05-15 12:13:07.304: E/AndroidRuntime(2596): java.lang.RuntimeException: Unable to start activity ComponentInfo{com./.hearing.InstructionsActivity}: android.view.InflateException: Binary XML file line #8: Error inflating class <unknown>
05-15 12:13:07.304: E/AndroidRuntime(2596): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2211)
05-15 12:13:07.304: E/AndroidRuntime(2596): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2261)
05-15 12:13:07.304: E/AndroidRuntime(2596): at android.app.ActivityThread.handleRelaunchActivity(ActivityThread.java:3740)
05-15 12:13:07.304: E/AndroidRuntime(2596): at android.app.ActivityThread.access$700(ActivityThread.java:141)
05-15 12:13:07.304: E/AndroidRuntime(2596): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1262)
05-15 12:13:07.304: E/AndroidRuntime(2596): at android.os.Handler.dispatchMessage(Handler.java:99)
05-15 12:13:07.304: E/AndroidRuntime(2596): at android.os.Looper.loop(Looper.java:137)
05-15 12:13:07.304: E/AndroidRuntime(2596): at android.app.ActivityThread.main(ActivityThread.java:5103)
05-15 12:13:07.304: E/AndroidRuntime(2596): at java.lang.reflect.Method.invokeNative(Native Method)
05-15 12:13:07.304: E/AndroidRuntime(2596): at java.lang.reflect.Method.invoke(Method.java:525)
05-15 12:13:07.304: E/AndroidRuntime(2596): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
05-15 12:13:07.304: E/AndroidRuntime(2596): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
05-15 12:13:07.304: E/AndroidRuntime(2596): at dalvik.system.NativeStart.main(Native Method)
05-15 12:13:07.304: E/AndroidRuntime(2596): Caused by: android.view.InflateException: Binary XML file line #8: Error inflating class <unknown>
05-15 12:13:07.304: E/AndroidRuntime(2596): at android.view.LayoutInflater.createView(LayoutInflater.java:620)
05-15 12:13:07.304: E/AndroidRuntime(2596): at com.android.internal.policy.impl.PhoneLayoutInflater.onCreateView(PhoneLayoutInflater.java:56)
05-15 12:13:07.304: E/AndroidRuntime(2596): at android.view.LayoutInflater.onCreateView(LayoutInflater.java:669)
05-15 12:13:07.304: E/AndroidRuntime(2596): at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:694)
05-15 12:13:07.304: E/AndroidRuntime(2596): at android.view.LayoutInflater.rInflate(LayoutInflater.java:755)
05-15 12:13:07.304: E/AndroidRuntime(2596): at android.view.LayoutInflater.inflate(LayoutInflater.java:492)
05-15 12:13:07.304: E/AndroidRuntime(2596): at android.view.LayoutInflater.inflate(LayoutInflater.java:397)
05-15 12:13:07.304: E/AndroidRuntime(2596): at android.view.LayoutInflater.inflate(LayoutInflater.java:353)
05-15 12:13:07.304: E/AndroidRuntime(2596): at com.android.internal.policy.impl.PhoneWindow.setContentView(PhoneWindow.java:267)
05-15 12:13:07.304: E/AndroidRuntime(2596): at com.actionbarsherlock.internal.ActionBarSherlockNative.setContentView(ActionBarSherlockNative.java:133)
05-15 12:13:07.304: E/AndroidRuntime(2596): at com.actionbarsherlock.app.SherlockActivity.setContentView(SherlockActivity.java:229)
05-15 12:13:07.304: E/AndroidRuntime(2596): at .InstructionsActivity.onCreate(InstructionsActivity.java:40)
05-15 12:13:07.304: E/AndroidRuntime(2596): at android.app.Activity.performCreate(Activity.java:5133)
05-15 12:13:07.304: E/AndroidRuntime(2596): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
05-15 12:13:07.304: E/AndroidRuntime(2596): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2175)
05-15 12:13:07.304: E/AndroidRuntime(2596): ... 12 more
05-15 12:13:07.304: E/AndroidRuntime(2596): Caused by: java.lang.reflect.InvocationTargetException
05-15 12:13:07.304: E/AndroidRuntime(2596): at java.lang.reflect.Constructor.constructNative(Native Method)
05-15 12:13:07.304: E/AndroidRuntime(2596): at java.lang.reflect.Constructor.newInstance(Constructor.java:417)
05-15 12:13:07.304: E/AndroidRuntime(2596): at android.view.LayoutInflater.createView(LayoutInflater.java:594)
05-15 12:13:07.304: E/AndroidRuntime(2596): ... 26 more
05-15 12:13:07.304: E/AndroidRuntime(2596): Caused by: java.lang.OutOfMemoryError
05-15 12:13:07.304: E/AndroidRuntime(2596): at android.graphics.BitmapFactory.nativeDecodeAsset(Native Method)
05-15 12:13:07.304: E/AndroidRuntime(2596): at android.graphics.BitmapFactory.decodeStream(BitmapFactory.java:503)
05-15 12:13:07.304: E/AndroidRuntime(2596): at android.graphics.BitmapFactory.decodeResourceStream(BitmapFactory.java:356)
05-15 12:13:07.304: E/AndroidRuntime(2596): at android.graphics.drawable.Drawable.createFromResourceStream(Drawable.java:800)
05-15 12:13:07.304: E/AndroidRuntime(2596): at android.content.res.Resources.loadDrawable(Resources.java:2105)
05-15 12:13:07.304: E/AndroidRuntime(2596): at android.content.res.TypedArray.getDrawable(TypedArray.java:601)
05-15 12:13:07.304: E/AndroidRuntime(2596): at android.widget.ImageView.<init> (ImageView.java:127)
05-15 12:13:07.304: E/AndroidRuntime(2596): at android.widget.ImageView.<init>(ImageView.java:117)
05-15 12:13:07.304: E/AndroidRuntime(2596): ... 29 more
So to me it looks like it had a issue with inflating the layout. I don't see how because I'd changed the orientation about 4 times before it crashed.
A bit further down there is a java.lang.OutOfMemoryError error so I assume this has caused the android.view.InflateException.
Any help of this would be greatly appreciated. Thanks
Edit:
Here is the activity it crashed on:
public class InstructionsActivity extends MenuActivity {
private ScrollView mScrollButton;
private WebView topContent;
private WebView bottomContent;
private boolean mMoreInfoTop = false;
private int mYdelta = 0;
private int mBottomOffset = 0;
private ActivityHelper activityHelper;
private boolean isPhone;
private String topHtml;
private String bottomHtml;
private String flag;
#TargetApi(Build.VERSION_CODES.HONEYCOMB)
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.instructions);
activityHelper = new ActivityHelper(this);
activityHelper.getScreenTag(R.id.instructions);
activityHelper.getDrawableFolder();
activityHelper.setTitleTextSize(R.string.Hearing_Test, true);
isPhone = activityHelper.isPhone();
if(isPhone){
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
}
mScrollButton = (ScrollView) findViewById(R.id.scroll_view);
flag = String.valueOf(getIntent().getStringExtra("Flag"));
if (flag.equalsIgnoreCase("firstInstructions")) {
topHtml = this.getString(R.string.top_content);
Button startTest = (Button) findViewById(R.id.test);
startTest.setText(R.string.start_test);
}else if(flag.equalsIgnoreCase("secondInstructions")){
topHtml = this.getString(R.string.switch_file);
Button startTest = (Button) findViewById(R.id.test);
startTest.setText(R.string.continue_test);
}
bottomHtml = this.getString(R.string.bottom_content);
topContent = (WebView) findViewById(R.id.top_content);
topContent.setBackgroundColor(0);
bottomContent = (WebView) findViewById(R.id.bottom_content);
bottomContent.setBackgroundColor(0);
bottomContent.getSettings().setUseWideViewPort(false);
topContent.loadUrl("file:///android_asset/html/" + topHtml);
bottomContent.loadUrl("file:///android_asset/html/" + bottomHtml);
getMargins();
setResult(RESULT_OK);
}
public void getMargins() {
ViewTreeObserver viewTreeObserver = topContent.getViewTreeObserver();
viewTreeObserver.addOnPreDrawListener(new OnPreDrawListener() {
#Override
public boolean onPreDraw() {
int topHeight = topContent.getMeasuredHeight();
int bottomHeight = bottomContent.getMeasuredHeight();
if (isPhone) {
if (topHeight != 0) {
Log.d("Web View Height", "Continue Height: "
+ topHeight);
if (mScrollButton != null) {
RelativeLayout instructions = (RelativeLayout) findViewById(R.id.more_info);
instructions.post(mAddMargin);
topContent.getViewTreeObserver()
.removeOnPreDrawListener(this);
}
topContent.getViewTreeObserver()
.removeOnPreDrawListener(this);
}
} else if (!isPhone) {
if (topHeight != 0 && bottomHeight != 0) {
Log.d("Web View Height", "top Height: " + topHeight
+ "bottom height:" + bottomHeight);
RelativeLayout instructions = (RelativeLayout) findViewById(R.id.more_info);
instructions.post(mAddMargin);
topContent.getViewTreeObserver()
.removeOnPreDrawListener(this);
}
}
return false;
}
});
}
Runnable mAddMargin = new Runnable() {
#Override
public void run() {
try {
int marginHeight;
if (isPhone) {
marginHeight = activityHelper.getMarginHeight(R.id.more_info, R.id.bottom_content);
RelativeLayout buttonHolder = (RelativeLayout) findViewById(R.id.instructionsLayout);
mBottomOffset = buttonHolder.getBottom();
mScrollButton = (ScrollView) findViewById(R.id.scroll_view);
mYdelta = mScrollButton.getScrollY();
activityHelper.setMarginHeight(marginHeight, R.id.instructionsLayout);
} else if (!isPhone) {
// int sideMargin = activityHelper.getWebViewMargin(R.id.bottom_content);
// if(sideMargin != 0){
// activityHelper.setWebViewMargin(sideMargin, R.id.top_content);
// activityHelper.setWebViewMargin(sideMargin, R.id.bottom_content);
// }
marginHeight = activityHelper.getMarginHeight(R.id.more_info, R.id.bottom_content);
activityHelper.setMarginHeight(marginHeight, R.id.more_info);
}
} catch (Exception e) {
Log.e("Scroll View", "Couldn't run mAddMargin:", e);
}
}
};
public void onClickHandler(View aView) {
if (flag.equalsIgnoreCase("firstInstructions")) {
Intent intent = new Intent(this, HearingTestActivity.class);
startActivity(intent);
}else if(flag.equalsIgnoreCase("secondInstructions")){
finish();
}
}
public void infoView(View aView) {
Intent intent = new Intent(this, InfoActivity.class);
startActivity(intent);
}
public void onMoreInstructions(View aView) {
// Scroll the start button to the top of the screen.
mScrollButton.post(new Runnable() {
#Override
public void run() {
if (mMoreInfoTop) {
mMoreInfoTop = false;
mScrollButton.scrollTo(0, mYdelta);
} else {
mMoreInfoTop = true;
mScrollButton.scrollTo(0, mBottomOffset);
}
}
});
}
}
Do you need any other code from me?
New code:
This is my updated code:
public void getMargins() {
ViewTreeObserver viewTreeObserver = topContent.getViewTreeObserver();
x = new OnPreDrawListener() {
#Override
public boolean onPreDraw() {
int topHeight = topContent.getMeasuredHeight();
int bottomHeight = bottomContent.getMeasuredHeight();
if (isPhone) {
if (topHeight != 0) {
Log.d("Web View Height", "Continue Height: "
+ topHeight);
if (mScrollButton != null) {
RelativeLayout instructions = (RelativeLayout) findViewById(R.id.more_info);
instructions.post(mAddMargin);
topContent.getViewTreeObserver()
.removeOnPreDrawListener(this);
}
topContent.getViewTreeObserver()
.removeOnPreDrawListener(this);
}
} else if (!isPhone) {
if (topHeight != 0 && bottomHeight != 0) {
Log.d("Web View Height", "top Height: " + topHeight
+ "bottom height:" + bottomHeight);
RelativeLayout instructions = (RelativeLayout) findViewById(R.id.more_info);
instructions.post(mAddMargin);
topContent.getViewTreeObserver()
.removeOnPreDrawListener(this);
}
}
return false;
}
};
viewTreeObserver.addOnPreDrawListener(x);
}
Here I now save the listener to a variable x.
onDestroy method:
#Override
protected void onDestroy() {
super.onDestroy();
if(x != null){
topContent.getViewTreeObserver()
.removeOnPreDrawListener(x);
}
}
I then check to see if the variable x is null, if it is remove the listener?
Am I correct in this? Thanks
This looks like a classic memory leak situation.
Most likely, you're keeping a live reference to some UI component (or maybe even the Activity) in a listener or an AsyncTask which causes the Activity instance to be leaked (kept from being garbage collected) when you turn the device -- because due to orientation change another Activity instance is created and the old one is supposed to be destroyed and collected.
After you turn the device 3 times you have 4 copies of everything -- hence the OOM.
Another possibility is that you're decoding a Bitmap manually and not calling recycle() on it when your Activity is destroyed.
And yep, as the guys suggest in the comments, nothing more specific can be said until you post your code.
UPD Oh, yeah, now that the code is there, most likely the source of your problem is somewhere in the anonymous classes (the OnPreDrawListener and the Runnable). First, not all conditions guarantee that your listener gets removed -- I'm not sure this is exactly what's causing the leak but consider checking if the listener is still around and removing it in onDestroy() also. But the more general idea is that any untrivial anonymous and nested non-static classes are a bad idea because they store an implicit reference to the instance of the containing class -- in this case, the Activity. Should anything unsuspected happen with any of that code -- it can cause the containing instance to be retained.
So, safest strategy is to avoid using non-static nested (let alone anonymous) classes unless the logic they carry is so trivial that you're absolutely sure about the implications.
My go-to approach is to create static nested Listeners (or AsyncTasks, Runnables, etc.) that refer to everything they need via WeakReference. Most obvious solution is to store the reference to the Activity in a member WeakReference<InstructionsActivity> and check it for null when the corresponding code gets executed. If it returns null - that means your Activity got destroyed, just return immediately.
UPD
Also, consider using Eclipse MAT (here's a good article, google around for more) to detect memory leaks. It has an awesome ability to run OQL queries on an HPROF dump file, this way you can query for your suspect leaked class (the activity class) and if there are two or more of them -- you know you have a problem. It will even show you what objects keep them retained -- look for paths to GC root
This may be causes of configuration change add below property in your mainifest file inside the activity.you can change as per your requirement
android:configChanges="orientation|screenSize|keyboard|screenLayout"

adding a counter in an android activity

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.

NullPointerException when trying to set the id entered by a user

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.

Categories