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"
Related
My application gets serial USB input with FTDI chip, I managed to do it.
As I press a button I get 3 input float type numbers displayed on my app.
Here is the onClick:
public void onReadClick(View view) throws UnsupportedEncodingException {
// [FTDriver] Create Read Buffer
byte[] rbuf = new byte[27]; // 1byte <--slow-- [Transfer Speed] --fast--> 4096 byte
// [FTDriver] Read from USB Serial
len = mSerial.read(rbuf);
for(i=0; i<len; i++) {
mText1.append((char) rbuf[i]);
}
Text = mText1.toString();
String[] Splited = Text.split("#");
Long r = Long.parseLong(Splited[1], 16);
Float f = Float.intBitsToFloat(r.intValue());
d1 = f.toString();
val.setText(d1);
Long r2 = Long.parseLong(Splited[2], 16);
Float f2 = Float.intBitsToFloat(r2.intValue());
d2 = f2.toString();
val2.setText(d2);
Long r3 = Long.parseLong(Splited[3], 16);
Float f3 = Float.intBitsToFloat(r3.intValue());
d3 = f3.toString();
val3.setText(d3);
Monitor.setText(Splited[1]);
Monitor2.setText(Splited[2]);
Monitor3.setText(Splited[3]);
}
It was very good until I wanted to make my application do this steps outside of the button onClick, so i take it outside (I'm really new with java) :
package com.application.i;
import java.io.UnsupportedEncodingException;
import jp.ksksue.driver.serial.FTDriver;
import android.app.Activity;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.hardware.usb.UsbManager;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
public class FTDI extends Activity{
// [FTDriver] Object
FTDriver mSerial;
// [FTDriver] Permission String
private static final String ACTION_USB_PERMISSION = "jp.ksksue.tutorial.USB_PERMISSION";
Button btnRead;
TextView Monitor,Monitor2,Monitor3;
TextView val,val2,val3;
TextView indicator;
StringBuffer mText1 = new StringBuffer();
int i,len;
String Text=null;
boolean doIT = true;
String number=null,number2=null,number3=null, hadar1=null, hadar2=null, hadar3=null, d1=null, d2=null, d3=null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.ftdisub);
btnRead = (Button) findViewById(R.id.btnRead);
Monitor = (TextView)findViewById(R.id.onitor);
Monitor2 = (TextView)findViewById(R.id.onitor2);
Monitor3 = (TextView)findViewById(R.id.onitor3);
val = (TextView)findViewById(R.id.dec);
val2 = (TextView)findViewById(R.id.dec2);
val3 = (TextView)findViewById(R.id.dec3);
indicator = (TextView)findViewById(R.id.indicator);
// [FTDriver] Create Instance
mSerial = new FTDriver((UsbManager)getSystemService(Context.USB_SERVICE));
// [FTDriver] setPermissionIntent() before begin()
PendingIntent permissionIntent = PendingIntent.getBroadcast(this, 0, new Intent(ACTION_USB_PERMISSION), 0);
mSerial.setPermissionIntent(permissionIntent);
// [FTDriver] Open USB Serial
if(mSerial.begin(FTDriver.BAUD115200)) {
btnRead.setEnabled(true);
Toast.makeText(this, "connected", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, "cannot connect", Toast.LENGTH_SHORT).show();
}
}
#Override
protected void onResume() {
if (doIT==true){
// [FTDriver] Create Read Buffer
byte[] rbuf = new byte[27]; // 1byte <--slow-- [Transfer Speed] --fast--> 4096 byte
// [FTDriver] Read from USB Serial
len = mSerial.read(rbuf);
for(i=0; i<len; i++) {
mText1.append((char) rbuf[i]);
}
Text = mText1.toString();
String[] Splited = Text.split("#");
Long r = Long.parseLong(Splited[1], 16);
Float f = Float.intBitsToFloat(r.intValue());
d1 = f.toString();
val.setText(d1);
Long r2 = Long.parseLong(Splited[2], 16);
Float f2 = Float.intBitsToFloat(r2.intValue());
d2 = f2.toString();
val2.setText(d2);
Long r3 = Long.parseLong(Splited[3], 16);
Float f3 = Float.intBitsToFloat(r3.intValue());
d3 = f3.toString();
val3.setText(d3);
Monitor.setText(Splited[1]);
Monitor2.setText(Splited[2]);
Monitor3.setText(Splited[3]);
doIT=false;
}
};
#Override
public void onDestroy() {
super.onDestroy();
// [FTDriver] Close USB Serial
mSerial.end();
}
public void onReadClick(View view) throws UnsupportedEncodingException {
doIT=true;
}
}
I just want to read it once without the Button, and for each additive time next, as i press the button the application will do the process again.
The main thing is that i want it outside of the button, especially to do it once as FTDI activity is being activated.
The FTDI activity is activated as I click a button on my application main screen.
problem:
When i click the FTDI button on the main screen it should start FTDI activity and display 3 float numbers, instead the application is finished with error and close message.
LogCat:
05-15 11:04:46.855: E/AndroidRuntime(9598): FATAL EXCEPTION: main
05-15 11:04:46.855: E/AndroidRuntime(9598): java.lang.RuntimeException: Unable to resume activity {com.application.i/com.application.i.FTDI}: java.lang.NullPointerException
05-15 11:04:46.855: E/AndroidRuntime(9598): at android.app.ActivityThread.performResumeActivity(ActivityThread.java:2616)
05-15 11:04:46.855: E/AndroidRuntime(9598): at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:2644)
05-15 11:04:46.855: E/AndroidRuntime(9598): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2130)
05-15 11:04:46.855: E/AndroidRuntime(9598): at android.app.ActivityThread.access$600(ActivityThread.java:140)
05-15 11:04:46.855: E/AndroidRuntime(9598): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1227)
05-15 11:04:46.855: E/AndroidRuntime(9598): at android.os.Handler.dispatchMessage(Handler.java:99)
05-15 11:04:46.855: E/AndroidRuntime(9598): at android.os.Looper.loop(Looper.java:137)
05-15 11:04:46.855: E/AndroidRuntime(9598): at android.app.ActivityThread.main(ActivityThread.java:4898)
05-15 11:04:46.855: E/AndroidRuntime(9598): at java.lang.reflect.Method.invokeNative(Native Method)
05-15 11:04:46.855: E/AndroidRuntime(9598): at java.lang.reflect.Method.invoke(Method.java:511)
05-15 11:04:46.855: E/AndroidRuntime(9598): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1006)
05-15 11:04:46.855: E/AndroidRuntime(9598): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:773)
05-15 11:04:46.855: E/AndroidRuntime(9598): at dalvik.system.NativeStart.main(Native Method)
05-15 11:04:46.855: E/AndroidRuntime(9598): Caused by: java.lang.NullPointerException
05-15 11:04:46.855: E/AndroidRuntime(9598): at jp.ksksue.driver.serial.FTDriver.read(FTDriver.java:271)
05-15 11:04:46.855: E/AndroidRuntime(9598): at jp.ksksue.driver.serial.FTDriver.read(FTDriver.java:257)
05-15 11:04:46.855: E/AndroidRuntime(9598): at com.application.i.FTDI.onResume(FTDI.java:83)
05-15 11:04:46.855: E/AndroidRuntime(9598): at android.app.Instrumentation.callActivityOnResume(Instrumentation.java:1188)
05-15 11:04:46.855: E/AndroidRuntime(9598): at android.app.Activity.performResume(Activity.java:5280)
05-15 11:04:46.855: E/AndroidRuntime(9598): at android.app.ActivityThread.performResumeActivity(ActivityThread.java:2606)
05-15 11:04:46.855: E/AndroidRuntime(9598): ... 12 more
P.S : this FTDI activity works fine:
public class FTDI extends Activity{
// [FTDriver] Object
FTDriver mSerial;
// [FTDriver] Permission String
private static final String ACTION_USB_PERMISSION = "jp.ksksue.tutorial.USB_PERMISSION";
Button btnRead;
TextView Monitor,Monitor2,Monitor3;
TextView val,val2,val3;
TextView indicator;
StringBuffer mText1 = new StringBuffer();
int i,len;
String Text=null;
boolean doIT = true;
String number=null,number2=null,number3=null, hadar1=null, hadar2=null, hadar3=null, d1=null, d2=null, d3=null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.ftdisub);
btnRead = (Button) findViewById(R.id.btnRead);
Monitor = (TextView)findViewById(R.id.onitor);
Monitor2 = (TextView)findViewById(R.id.onitor2);
Monitor3 = (TextView)findViewById(R.id.onitor3);
val = (TextView)findViewById(R.id.dec);
val2 = (TextView)findViewById(R.id.dec2);
val3 = (TextView)findViewById(R.id.dec3);
indicator = (TextView)findViewById(R.id.indicator);
// [FTDriver] Create Instance
mSerial = new FTDriver((UsbManager)getSystemService(Context.USB_SERVICE));
// [FTDriver] setPermissionIntent() before begin()
PendingIntent permissionIntent = PendingIntent.getBroadcast(this, 0, new Intent(ACTION_USB_PERMISSION), 0);
mSerial.setPermissionIntent(permissionIntent);
// [FTDriver] Open USB Serial
if(mSerial.begin(FTDriver.BAUD115200)) {
btnRead.setEnabled(true);
Toast.makeText(this, "connected", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, "cannot connect", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onDestroy() {
super.onDestroy();
// [FTDriver] Close USB Serial
mSerial.end();
}
public void onReadClick(View view) throws UnsupportedEncodingException {
// [FTDriver] Create Read Buffer
byte[] rbuf = new byte[27]; // 1byte <--slow-- [Transfer Speed] --fast--> 4096 byte
// [FTDriver] Read from USB Serial
len = mSerial.read(rbuf);
for(i=0; i<len; i++) {
mText1.append((char) rbuf[i]);
}
Text = mText1.toString();
String[] Splited = Text.split("#");
Long r = Long.parseLong(Splited[1], 16);
Float f = Float.intBitsToFloat(r.intValue());
d1 = f.toString();
val.setText(d1);
Long r2 = Long.parseLong(Splited[2], 16);
Float f2 = Float.intBitsToFloat(r2.intValue());
d2 = f2.toString();
val2.setText(d2);
Long r3 = Long.parseLong(Splited[3], 16);
Float f3 = Float.intBitsToFloat(r3.intValue());
d3 = f3.toString();
val3.setText(d3);
Monitor.setText(Splited[1]);
Monitor2.setText(Splited[2]);
Monitor3.setText(Splited[3]);
}
}
You have to check the life cycle of your activity. I guess your mSerial is not initialized when the on resume method is called and try to do the stuff in on start
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
I'm having a tremendous amount of trouble figuring out how and why I am getting a java.lang.NullPointerException. I have no idea what is going on because it seems to happen before my program loads. I've set a breakpoint at the first line of my onCreate function and my android log still shows that I have a this exception thrown but the program continues to start and I reach my breakpoint. But stepping through I get very weird behavior. I will post the code in question as well as the log. if any other info needed to help me with this please ask. Also please excuse the indention. I'm fairly new to stack overflow
package com.example.facta.myapplication;
import android.content.Context;
import android.content.res.XmlResourceParser;
import android.util.Log;
import org.xmlpull.v1.XmlPullParser;
import java.util.ArrayList;
import java.util.Arrays;
/**
* Created by facta on 11/21/2014.
*/
public class SiteConfig {
private XmlResourceParser configParser;
ArrayList<RSSProviderInfo> RSSProviderInfos;
ArrayList<String> RSSProviderNames;
public SiteConfig()
{
RSSProviderInfos = new ArrayList<RSSProviderInfo>();
RSSProviderNames = new ArrayList<String>();
}
public ArrayList<RSSProviderInfo> getProvierInfos()
{
return RSSProviderInfos;
}
public ArrayList<String> getProvierNames()
{
return RSSProviderNames;
}
public void loadConfig(Context context, int resourceId)
{
configParser = context.getResources().getXml(resourceId);
RSSProviderInfos.clear();
RSSProviderInfo providerInfo = new RSSProviderInfo();
ArrayList<String> providerNames = loadProviders(configParser);
for(int i=0; i < providerNames.size(); i++)
{
providerInfo = LoadProviderInfo(configParser, providerNames.get(i));
if(providerInfo != null && providerInfo.isComplete()) {
RSSProviderInfos.add(providerInfo);
}
}
}
private RSSProviderInfo LoadProviderInfo(XmlResourceParser parser, String provider) {
RSSProviderInfo info = new RSSProviderInfo();
String attrName = new String();
try {
parser.next();
int eventType = parser.getEventType();
while (eventType != XmlPullParser.END_DOCUMENT) {
if (eventType == XmlPullParser.START_TAG
&& parser.getName().equalsIgnoreCase("site" )) {
attrName = parser.getAttributeValue(null, "name");
if(attrName.equalsIgnoreCase(provider + ".enabled"))
{
/*
String value = parser.getAttributeValue(null, "value");
if(value.equalsIgnoreCase("no")) {
Log.d("LoadProviderInfo", "value does equal no");
return null; //If it's not enabled don't include it in the config
}
*/
}
else if(attrName.equalsIgnoreCase(provider + ".elementTag"))
{
info.setElementTag(parser.getAttributeValue(null, "value"));
}
else if(attrName.equalsIgnoreCase(provider + ".titleTag"))
{
info.setTitleTag(parser.getAttributeValue(null, "value"));
}
else if(attrName.equalsIgnoreCase(provider + ".linkTag"))
{
info.setLinkTag(parser.getAttributeValue(null, "value"));
}
else if(attrName.equalsIgnoreCase(provider + ".descriptionTag"))
{
info.setDescriptionTag(parser.getAttributeValue(null,"value"));
}
else if(attrName.equalsIgnoreCase(provider + ".url"))
{
info.addUrl(parser.getAttributeValue(null, "value"));
}
break;
}
eventType = parser.next();
}
}
catch (Exception e)
{
Log.d("loadProviderInfo", "Caught an exeption: " + e.toString() + e.getMessage());
e.printStackTrace();
StackTraceElement st[] = e.getStackTrace();
for(int i=0; i < st.length; i++)
{
Log.d("loadProviderInfo", "StackTraceElement[" + i + "] " + st[i].getLineNumber());
}
}
return null;
}
private ArrayList<String> loadProviders(XmlResourceParser parser) {
ArrayList<String> names = new ArrayList<String>();
try {
parser.next();
int eventType = parser.getEventType();
while (eventType != XmlPullParser.END_DOCUMENT) {
if (eventType == XmlPullParser.START_TAG
&& parser.getName().equalsIgnoreCase("siteproviders")) {
String[] parsedNames = parser.getAttributeValue(null, "value").split(",");
for (int i=0; i < parsedNames.length; i++)
{
names.add(i, parsedNames[i]);
}
break;
}
eventType = parser.next();
}
}
catch (Exception e)
{
Log.d("loadProviderInfo", "Caught an exeption: " + e.toString() + e.getMessage());
e.printStackTrace();
StackTraceElement st[] = e.getStackTrace();
for(int i=0; i < st.length; i++)
{
Log.d("loadProviderInfo", "StackTraceElement[" + i + "] " + st[i].getLineNumber());
}
}
return names;
}
}
Log Below
11-23 18:20:40.830 537-537/com.example.facta.myapplication D/dalvikvm﹕ Not late-enabling CheckJNI (already on)
11-23 18:20:41.569 537-542/com.example.facta.myapplication I/dalvikvm﹕ threadid=3: reacting to signal 3
11-23 18:20:41.580 537-542/com.example.facta.myapplication I/dalvikvm﹕ Wrote stack traces to '/data/anr/traces.txt'
11-23 18:20:42.040 537-537/com.example.facta.myapplication D/loadProviders﹕ Caught an exeption: java.lang.NullPointerException
11-23 18:20:42.040 537-537/com.example.facta.myapplication W/System.err﹕ java.lang.NullPointerException
11-23 18:20:42.040 537-537/com.example.facta.myapplication W/System.err﹕ at com.example.facta.myapplication.SiteConfig.loadProviders(SiteConfig.java:119)
11-23 18:20:42.040 537-537/com.example.facta.myapplication W/System.err﹕ at com.example.facta.myapplication.SiteConfig.loadConfig(SiteConfig.java:42)
11-23 18:20:42.040 537-537/com.example.facta.myapplication W/System.err﹕ at com.example.facta.myapplication.ResultsActivity.fetch(ResultsActivity.java:94)
11-23 18:20:42.040 537-537/com.example.facta.myapplication W/System.err﹕ at com.example.facta.myapplication.ResultsActivity.onCreate(ResultsActivity.java:62)
11-23 18:20:42.040 537-537/com.example.facta.myapplication W/System.err﹕ at android.app.Activity.performCreate(Activity.java:4465)
11-23 18:20:42.040 537-537/com.example.facta.myapplication W/System.err﹕ at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1049)
11-23 18:20:42.040 537-537/com.example.facta.myapplication W/System.err﹕ at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1920)
11-23 18:20:42.040 537-537/com.example.facta.myapplication W/System.err﹕ at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1981)
11-23 18:20:42.040 537-537/com.example.facta.myapplication W/System.err﹕ at android.app.ActivityThread.access$600(ActivityThread.java:123)
11-23 18:20:42.040 537-537/com.example.facta.myapplication W/System.err﹕ at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1147)
11-23 18:20:42.040 537-537/com.example.facta.myapplication W/System.err﹕ at android.os.Handler.dispatchMessage(Handler.java:99)
11-23 18:20:42.040 537-537/com.example.facta.myapplication W/System.err﹕ at android.os.Looper.loop(Looper.java:137)
11-23 18:20:42.040 537-537/com.example.facta.myapplication W/System.err﹕ at android.app.ActivityThread.main(ActivityThread.java:4424)
11-23 18:20:42.040 537-537/com.example.facta.myapplication W/System.err﹕ at java.lang.reflect.Method.invokeNative(Native Method)
11-23 18:20:42.040 537-537/com.example.facta.myapplication W/System.err﹕ at java.lang.reflect.Method.invoke(Method.java:511)
11-23 18:20:42.040 537-537/com.example.facta.myapplication W/System.err﹕ at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
11-23 18:20:42.040 537-537/com.example.facta.myapplication W/System.err﹕ at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
11-23 18:20:42.040 537-537/com.example.facta.myapplication W/System.err﹕ at dalvik.system.NativeStart.main(Native Method)
11-23 18:20:42.070 537-542/com.example.facta.myapplication I/dalvikvm﹕ threadid=3: reacting to signal 3
11-23 18:20:42.080 537-542/com.example.facta.myapplication I/dalvikvm﹕ Wrote stack traces to '/data/anr/traces.txt'
11-23 18:20:42.270 537-537/com.example.facta.myapplication D/gralloc_goldfish﹕ Emulator without GPU emulation detected.
11-23 18:37:36.440 669-669/com.example.facta.myapplication W/ActivityThread﹕ Application com.example.facta.myapplication is waiting for the debugger on port 8100...
11-23 18:37:36.490 669-669/com.example.facta.myapplication I/System.out﹕ Sending WAIT chunk
11-23 18:37:36.701 669-675/com.example.facta.myapplication I/dalvikvm﹕ Debugger is active
11-23 18:37:36.740 669-669/com.example.facta.myapplication I/System.out﹕ Debugger has connected
11-23 18:37:36.740 669-669/com.example.facta.myapplication I/System.out﹕ waiting for debugger to settle...
11-23 18:37:36.900 669-674/com.example.facta.myapplication I/dalvikvm﹕ threadid=3: reacting to signal 3
11-23 18:37:36.910 669-674/com.example.facta.myapplication I/dalvikvm﹕ Wrote stack traces to '/data/anr/traces.txt'
11-23 18:37:36.940 669-669/com.example.facta.myapplication I/System.out﹕ waiting for debugger to settle...
11-23 18:37:37.140 669-669/com.example.facta.myapplication I/System.out﹕ waiting for debugger to settle...
11-23 18:37:37.680 669-669/com.example.facta.myapplication I/System.out﹕ waiting for debugger to settle...
11-23 18:37:37.880 669-669/com.example.facta.myapplication I/System.out﹕ waiting for debugger to settle...
11-23 18:37:38.079 669-669/com.example.facta.myapplication I/System.out﹕ waiting for debugger to settle...
11-23 18:37:38.279 669-669/com.example.facta.myapplication I/System.out﹕ waiting for debugger to settle...
11-23 18:37:38.369 669-674/com.example.facta.myapplication I/dalvikvm﹕ threadid=3: reacting to signal 3
11-23 18:37:38.379 669-674/com.example.facta.myapplication I/dalvikvm﹕ Wrote stack traces to '/data/anr/traces.txt'
Calling Activity Below
package com.example.facta.myapplication;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;
import java.util.ArrayList;
/* TODO
Need to make a config file that has the following format.
site.names = CNN,FOX,NBC,AP
site.CNN.enabled = yes
site.CNN.searchtag = item
site.CNN.titletag = title
site.CNN.linktag = link
site.CNN.descriptiontag = description
site.CNN.numurls = 10
site.CNN.url.1 = "https://www.cnn.com/top_stories.rss
site.CNN.url.2 = "https://www.cnn.com/world_politics.rss
site.FOX.enabled = no
site.FOX.searchtag = story
*/
public class ResultsActivity extends Activity {
private ArrayList<String> finalUrls = new ArrayList<String>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_results);
finalUrls.add("http://rss.cnn.com/rss/cnn_topstories.rss");
finalUrls.add("http://rss.cnn.com/rss/cnn_world.rss");
finalUrls.add("http://rss.cnn.com/rss/cnn_us.rss");
finalUrls.add("http://rss.cnn.com/rss/money_latest.rss");
finalUrls.add("http://rss.cnn.com/rss/cnn_allpolitics.rss");
finalUrls.add("http://rss.cnn.com/rss/cnn_crime.rss");
finalUrls.add("http://rss.cnn.com/rss/cnn_tech.rss");
finalUrls.add("http://rss.cnn.com/rss/cnn_health.rss");
finalUrls.add("http://rss.cnn.com/rss/cnn_showbiz.rss");
finalUrls.add("http://rss.cnn.com/rss/cnn_travel.rss");
finalUrls.add("http://rss.cnn.com/rss/cnn_living.rss");
finalUrls.add("http://rss.cnn.com/rss/cnn_freevideo.rss");
finalUrls.add("http://rss.cnn.com/rss/cnn_studentnews.rss");
finalUrls.add("http://rss.cnn.com/rss/cnn_mostpopular.rss");
finalUrls.add("http://rss.cnn.com/rss/cnn_latest.rss");
finalUrls.add("http://rss.ireport.com/feeds/oncnn.rss");
finalUrls.add("http://rss.cnn.com/rss/cnn_behindthescenes.rss");
this.fetch();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_results, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
private void fetch() {
/**TODO possibly load config then for each provider pass in RSSProviderInfo into HandleXML
That way HandleXML can set all the tags it needs and then parse the urls from the param
*/
SiteConfig siteConfig = new SiteConfig();
siteConfig.loadConfig(this, R.xml.sites);
ArrayList<RSSProviderInfo> siteConfigProvierInfos = siteConfig.getProvierInfos();
for (int k = 0; k < siteConfigProvierInfos.size(); k++) {
HandleXML obj = new HandleXML(siteConfigProvierInfos.get(k));
obj.fetchXML();
while (!obj.parsingComplete) {
try {
Thread.sleep(500, 0);
} catch (InterruptedException e) {
e.printStackTrace();
}
final ArrayList<RSSInfo> rssInfos = obj.getRssInfos();
final TableLayout tableLayout = (TableLayout) findViewById(R.id.results_table);
Log.d("fetch", "Size of rssinfos " + rssInfos.size());
for (int i = 0; i < rssInfos.size(); i++) {
final int index = i;
final TableRow tableRow = new TableRow(this);
tableRow.setLayoutParams(new TableLayout.LayoutParams(TableLayout.LayoutParams.WRAP_CONTENT, TableLayout.LayoutParams.WRAP_CONTENT));
//Get information from infos
final TextView textView = new TextView(this);
textView.setText(rssInfos.get(index).getTitle());
textView.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.WRAP_CONTENT, TableRow.LayoutParams.WRAP_CONTENT));
tableRow.setClickable(true);
tableRow.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(rssInfos.get(index).getLink()));
startActivity(intent);
}
});
tableRow.addView(textView);
tableLayout.addView(tableRow);
}
Log.d("fetch", "tableLayout = " + tableLayout.toString());
}
}
}
}
Sorry for the confusion. I think I need to review Android Studio. That is an error from a previous version of my code (notice the date of yesterday 11-23). I thought "clear all" in logcat literally cleared all and delete it. I just found out I am wrong. There are no NPEs at this time that I am aware of. Sorry for the waste of time....lesson learned for me using android studio. After noticing this I was able to find the logical error that caused the program to exit shortly after. Thanks all for the help
Hello guys I am making an Android app that convert from binary to decimal and I have made a class called Binary and a class called Decimal and a function in the Binary class that convert from decimal to binary
public Binary DtoB(Decimal decimal)
{
String temp = null;
do
{
if(decimal.decimal%2!=0)
temp+='1';
else
temp+='0';
decimal.decimal/=2;
}while(decimal.decimal>0);
while(temp.length()%4!=0)
temp+='0';
for(int i=temp.length()-1;i>=0;i--)
{
this.bn+=temp.charAt(i);
}
return this;
}
and in the activity there's a button that converts, but when I test and press on the button the app breaks
b1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
d1.decimal=Integer.parseInt(e1.getText().toString());
b.DtoB(d1);
t1.setText(b.bn);
}
});
can any one help me please ???
Here is the logcat:
10-26 09:16:15.831: E/AndroidRuntime(280): FATAL EXCEPTION: main
10-26 09:16:15.831: E/AndroidRuntime(280): java.lang.NullPointerException
10-26 09:16:15.831: E/AndroidRuntime(280): at com.example.converter.MainActivity$1.onClick(MainActivity.java:34)
10-26 09:16:15.831: E/AndroidRuntime(280): at android.view.View.performClick(View.java:2408)
10-26 09:16:15.831: E/AndroidRuntime(280): at android.view.View$PerformClick.run(View.java:8816)
10-26 09:16:15.831: E/AndroidRuntime(280): at android.os.Handler.handleCallback(Handler.java:587)
10-26 09:16:15.831: E/AndroidRuntime(280): at android.os.Handler.dispatchMessage(Handler.java:92)
10-26 09:16:15.831: E/AndroidRuntime(280): at android.os.Looper.loop(Looper.java:123) 10-26 09:16:15.831: E/AndroidRuntime(280): at android.app.ActivityThread.main(ActivityThread.java:4627)
10-26 09:16:15.831: E/AndroidRuntime(280): at java.lang.reflect.Method.invokeNative(Native Method) 10-26 09:16:15.831: E/AndroidRuntime(280): at java.lang.reflect.Method.invoke(Method.java:521)
Try this...!
public class BinaryToDecimal {
public int getDecimalFromBinary(int binary){
int decimal = 0;
int power = 0;
while(true){
if(binary == 0){
break;
} else {
int tmp = binary%10;
decimal += tmp*Math.pow(2, power);
binary = binary/10;
power++;
}
}
return decimal;
}
public static void main(String a[]){
BinaryToDecimal bd = new BinaryToDecimal();
System.out.println("11 ===> "+bd.getDecimalFromBinary(11));
System.out.println("110 ===> "+bd.getDecimalFromBinary(110));
System.out.println("100110 ===> "+bd.getDecimalFromBinary(100110));
}
}
check variable all are initialize perfectly . because some time objectc are created but it is null so can't work and throw java.lang.NullPointerException .....
b1 , d1 , b ,t1
The code below was working perfectly. To be honest I don't even think I changed something. It stopped working. I have a custom Listview, and the error is on search inside that custom listview. I created a custom Adapter, etc.
// Products Activity:
listView = (ListView) findViewById(R.id.product_listview);
inputSearch = (EditText) findViewById(R.id.inputSearch);
adapter = new itemAdapter(this,R.layout.row, display_products);
listView.setAdapter(adapter);
/**
* Enabling Search Filter
* */
inputSearch.addTextChangedListener(new TextWatcher() {
#Override
public void afterTextChanged(Editable arg0) {
// TODO Auto-generated method stub
String text = inputSearch.getText().toString().toLowerCase(Locale.getDefault());
adapter.filter(text);
}
#Override
public void beforeTextChanged(CharSequence arg0, int arg1,
int arg2, int arg3) {
// TODO Auto-generated method stub
}
#Override
public void onTextChanged(CharSequence arg0, int arg1, int arg2,
int arg3) {
// TODO Auto-generated method stub
}
});
And this is filter on custom adapter (I didn't put the getView method because it's working..but if you need let me know.):
public class itemAdapter extends ArrayAdapter<oc_product_display> {
private final Context context;
private final List<oc_product_display> lista;
private ArrayList<oc_product_display> arraylist;
private final int rowResourceId;
public itemAdapter(Context context, int textViewResourceId, List<oc_product_display> objects) {
super(context, textViewResourceId, objects);
this.context = context;
this.lista = objects;
this.rowResourceId = textViewResourceId;
this.arraylist = new ArrayList<oc_product_display>();
this.arraylist.addAll(lista);
}
public void filter(String charText) {
charText = charText.toLowerCase(Locale.getDefault());
lista.clear();
if (charText.length() == 0) {
lista.addAll(arraylist);
} else {
for (oc_product_display wp : arraylist) {
if (wp.get_name().toLowerCase(Locale.getDefault())
.contains(charText)) {
lista.add(wp);
}
}
}
notifyDataSetChanged();
}
}
LogCat
And this is the error: 10-04 06:29:08.576: E/AndroidRuntime(10284):
FATAL EXCEPTION: main 10-04 06:29:08.576: E/AndroidRuntime(10284):
java.lang.RuntimeException: Unable to start activity
ComponentInfo{com.example.myExample/com.example.myExample.ProductsActivity}:
java.lang.NullPointerException 10-04 06:29:08.576:
E/AndroidRuntime(10284): at
android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2211)
10-04 06:29:08.576: E/AndroidRuntime(10284): at
android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2261)
10-04 06:29:08.576: E/AndroidRuntime(10284): at
android.app.ActivityThread.access$600(ActivityThread.java:141) 10-04
06:29:08.576: E/AndroidRuntime(10284): at
android.app.ActivityThread$H.handleMessage(ActivityThread.java:1256)
10-04 06:29:08.576: E/AndroidRuntime(10284): at
android.os.Handler.dispatchMessage(Handler.java:99) 10-04
06:29:08.576: E/AndroidRuntime(10284): at
android.os.Looper.loop(Looper.java:137) 10-04 06:29:08.576:
E/AndroidRuntime(10284): at
android.app.ActivityThread.main(ActivityThread.java:5103) 10-04
06:29:08.576: E/AndroidRuntime(10284): at
java.lang.reflect.Method.invokeNative(Native Method) 10-04
06:29:08.576: E/AndroidRuntime(10284): at
java.lang.reflect.Method.invoke(Method.java:525) 10-04 06:29:08.576:
E/AndroidRuntime(10284): at
com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
10-04 06:29:08.576: E/AndroidRuntime(10284): at
com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553) 10-04
06:29:08.576: E/AndroidRuntime(10284): at
dalvik.system.NativeStart.main(Native Method) 10-04 06:29:08.576:
E/AndroidRuntime(10284): Caused by: java.lang.NullPointerException
10-04 06:29:08.576: E/AndroidRuntime(10284): at
com.example.myExample.ProductsActivity.onCreate(ProductsActivity.java:46)
10-04 06:29:08.576: E/AndroidRuntime(10284): at
android.app.Activity.performCreate(Activity.java:5133) 10-04
06:29:08.576: E/AndroidRuntime(10284): at
android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
10-04 06:29:08.576: E/AndroidRuntime(10284): at
android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2175)
10-04 06:29:08.576: E/AndroidRuntime(10284): ... 11 more
As you may see it gives on line:
10-04 06:29:08.576: E/AndroidRuntime(10284): at com.example.myExample.ProductsActivity.onCreate(ProductsActivity.java:46)
Which is:
inputSearch.addTextChangedListener(new TextWatcher() {
If I remove the option of search, the products are displayed and I don't get any error.
Thanks.
Logcat says it all:
Caused by: java.lang.NullPointerException at com.example.myExample.ProductsActivity.onCreate(ProductsActivity.java:46)
Check this line if it is null or not.
If that line is the one you declared on question... Then probably your "inputSearch" is null. Be sure that you find this view on correct layout.
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.