Code keeps thowing a NPE, cannot find the cause - java

i cannot find the null pointer exception in my code, i was wondering if anyone could help me find what is giving an error.
code:
package com.dingle.ubat;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.PowerManager;
import android.view.Display;
import android.view.MotionEvent;
import android.widget.Toast;
public class UltraBrightAndroidTorchActivity extends Activity {
/** Called when the activity is first created. */
PowerManager pm;
PowerManager.WakeLock wl;
public boolean flash = false;
public boolean enableFlash = false;
public boolean dimDisplay = false;
Display display = getWindowManager().getDefaultDisplay();
public int windowWidth = display.getWidth();
public int windowHeight = display.getHeight();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
wl = pm.newWakeLock(PowerManager.FULL_WAKE_LOCK, "My Tag");
flash = this.getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA_FLASH);
if(flash == true && enableFlash == true){
try {
DroidLED led = new DroidLED();
led.enable(!led.isEnabled());
}
catch(Exception e) {
Toast.makeText(this, "Error interacting with LED.", Toast.LENGTH_SHORT).show();
throw new RuntimeException(e);
} }
wl.acquire();
}
#Override
public boolean onTouchEvent(MotionEvent event) {
//int tx = (int) event.getRawX();
int ty = (int) event.getRawY();
if (ty <= (windowHeight/2)){
dimDisplay = !dimDisplay;
}
if (ty >= (windowHeight/2)){
enableFlash = !enableFlash;
}
return super.onTouchEvent(event);
}
#Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
wl.release();
}
#Override
protected void onNewIntent(Intent intent) {
// TODO Auto-generated method stub
super.onNewIntent(intent);
wl.release();
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
wl.release();
}
#Override
protected void onStop() {
// TODO Auto-generated method stub
super.onStop();
wl.release();
}
}
Error list:
12-10 20:40:42.224: W/dalvikvm(274): threadid=3: thread exiting with uncaught exception (group=0x4001b188)
12-10 20:40:42.232: E/AndroidRuntime(274): Uncaught handler: thread main exiting due to uncaught exception
12-10 20:40:42.282: E/AndroidRuntime(274): java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.dingle.ubat/com.dingle.ubat.UltraBrightAndroidTorchActivity}: java.lang.NullPointerException
12-10 20:40:42.282: E/AndroidRuntime(274): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2417)
12-10 20:40:42.282: E/AndroidRuntime(274): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2512)
12-10 20:40:42.282: E/AndroidRuntime(274): at android.app.ActivityThread.access$2200(ActivityThread.java:119)
12-10 20:40:42.282: E/AndroidRuntime(274): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1863)
12-10 20:40:42.282: E/AndroidRuntime(274): at android.os.Handler.dispatchMessage(Handler.java:99)
12-10 20:40:42.282: E/AndroidRuntime(274): at android.os.Looper.loop(Looper.java:123)
12-10 20:40:42.282: E/AndroidRuntime(274): at android.app.ActivityThread.main(ActivityThread.java:4363)
12-10 20:40:42.282: E/AndroidRuntime(274): at java.lang.reflect.Method.invokeNative(Native Method)
12-10 20:40:42.282: E/AndroidRuntime(274): at java.lang.reflect.Method.invoke(Method.java:521)
12-10 20:40:42.282: E/AndroidRuntime(274): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:860)
12-10 20:40:42.282: E/AndroidRuntime(274): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:618)
12-10 20:40:42.282: E/AndroidRuntime(274): at dalvik.system.NativeStart.main(Native Method)
12-10 20:40:42.282: E/AndroidRuntime(274): Caused by: java.lang.NullPointerException
12-10 20:40:42.282: E/AndroidRuntime(274): at com.dingle.ubat.UltraBrightAndroidTorchActivity.<init>(UltraBrightAndroidTorchActivity.java:20)
12-10 20:40:42.282: E/AndroidRuntime(274): at java.lang.Class.newInstanceImpl(Native Method)
12-10 20:40:42.282: E/AndroidRuntime(274): at java.lang.Class.newInstance(Class.java:1479)
12-10 20:40:42.282: E/AndroidRuntime(274): at android.app.Instrumentation.newActivity(Instrumentation.java:1021)
12-10 20:40:42.282: E/AndroidRuntime(274): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2409)
12-10 20:40:42.282: E/AndroidRuntime(274): ... 11 more
any help and criticism is greatly appreciated
code is being compiled for android 2.1. code is a basic, crappily coded torch app.
thanx

The code is bailing out on one of these two lines:
Display display = getWindowManager().getDefaultDisplay();
public int windowWidth = display.getWidth();
Either getWindowManager() is returning a null and that first initializer will fail, or getDefaultDisplay() is, and the second one will.
You should probably move these initializations to the onCreate handler. Having them at instance initialization sounds a bit risky - the activity's "environment" might not be completely set up yet at that point.
(And check the return values.)

Activity is full available only after it has been created. This line does not do the intended purpose:
 Display display = getWindowManager().getDefaultDisplay();
Move this line and subsequent ones inside onCreate method.

Related

Android : saving value for app language

I want language change feature in my app which can provide user feature to change application language from settings but at start i want default application to open so i created dummy project to test it where i am accessing Langugage preference from a class which is defining factor for language Here its code(Clearly I know I am not using sharedPreference the right way and i know the error was because of that so please help in setting shared preference in this app):
public class LanguagePreferences extends Activity {
public int language;
int check;
SharedPreferences settings = getSharedPreferences("mysettings",
Context.MODE_PRIVATE);
public LanguagePreferences()
{
language=settings.getInt("language", 0);
}
public void changeLang()
{
check=settings.getInt("language",0);
if(check==0)
{
settings.edit().putInt("language", 1);
settings.edit().comment();
}
else
{
settings.edit().putInt("language", 1);
settings.edit().comment();
}
}
}
and a button to change application Language in settings Here its Code:
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.change);
btnLang=(Button)findViewById(R.id.change);
btnLang.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
LanguagePreferences l= new LanguagePreferences();
l.changeLang();
}
});
}
and main Activity where i am changing text value if language is different code:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView tv = (TextView) findViewById(R.id.text);
Button btnLang = (Button) findViewById(R.id.buttonlang);
SharedPreferences settings = getSharedPreferences("mysettings",
Context.MODE_PRIVATE);
btnLang.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent i = new Intent(MainActivity.this, Change.class);
startActivity(i);
}
});
LanguagePreferences l = new LanguagePreferences();
if (l.language == 0) {
tv.setText("Germany");
} else {
tv.setText("English");
}
}
I am using shared preferences to save data but at start activity closes and not responding error shows. Any Help is appreciated.
Error Log:
09-11 17:44:26.200: D/AndroidRuntime(13952): Shutting down VM
09-11 17:44:26.200: W/dalvikvm(13952): threadid=1: thread exiting with uncaught exception (group=0x414112a0)
09-11 17:44:26.208: E/AndroidRuntime(13952): FATAL EXCEPTION: main
09-11 17:44:26.208: E/AndroidRuntime(13952): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.dummy/com.example.dummy.MainActivity}: java.lang.NullPointerException
09-11 17:44:26.208: E/AndroidRuntime(13952): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2097)
09-11 17:44:26.208: E/AndroidRuntime(13952): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2122)
09-11 17:44:26.208: E/AndroidRuntime(13952): at android.app.ActivityThread.access$600(ActivityThread.java:140)
09-11 17:44:26.208: E/AndroidRuntime(13952): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1228)
09-11 17:44:26.208: E/AndroidRuntime(13952): at android.os.Handler.dispatchMessage(Handler.java:99)
09-11 17:44:26.208: E/AndroidRuntime(13952): at android.os.Looper.loop(Looper.java:137)
09-11 17:44:26.208: E/AndroidRuntime(13952): at android.app.ActivityThread.main(ActivityThread.java:4895)
09-11 17:44:26.208: E/AndroidRuntime(13952): at java.lang.reflect.Method.invoke(Method.java:511)
09-11 17:44:26.208: E/AndroidRuntime(13952): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:994)
09-11 17:44:26.208: E/AndroidRuntime(13952): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:761)
09-11 17:44:26.208: E/AndroidRuntime(13952): at dalvik.system.NativeStart.main(Native Method)
09-11 17:44:26.208: E/AndroidRuntime(13952): Caused by: java.lang.NullPointerException
09-11 17:44:26.208: E/AndroidRuntime(13952): at android.content.ContextWrapper.getApplicationContext(ContextWrapper.java:101)
09-11 17:44:26.208: E/AndroidRuntime(13952): at com.example.dummy.LanguagePreferences.<init>(LanguagePreferences.java:18)
09-11 17:44:26.208: E/AndroidRuntime(13952): at com.example.dummy.MainActivity.onCreate(MainActivity.java:36)
09-11 17:44:26.208: E/AndroidRuntime(13952): at android.app.Activity.performCreate(Activity.java:5163)
09-11 17:44:26.208: E/AndroidRuntime(13952): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1094)
09-11 17:44:26.208: E/AndroidRuntime(13952): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2061)
09-11 17:44:26.208: E/AndroidRuntime(13952): ... 11 more
09-11 17:44:43.325: I/Process(13952): Sending signal. PID: 13952 SIG: 9
As mentioned in the comments, most likely the settings variable is the problem.
Try initializing it in your onCreate() method.
#Override
protected void onCreate(Bundle state){
super.onCreate(state);
SharedPreferences settings = getSharedPreferences("mysettings", Context.MODE_PRIVATE);
}
You can find more information on how to use these shared preferences here.
From your example:
LanguagePreferences l = new LanguagePreferences();
You are creating a new Activity object here.
You're not supposed to do that. Activities are managed by android. You should use the lifecycle methods and callbacks to interact with them.
Store the language only in the shared preferences, not in a member variable of the activity.
You are Trying to create an instance of an Activity with at the line below, which is wrong.
LanguagePreferences l = new LanguagePreferences();
You cannot reach the activity's method like this. You can Add an Application Class and write a public static method like:
public class ApplicationClass extends Application {
public static SharedPreferences mSharedPrefs;
public static SharedPreferences.Editor mPrefsEditor;
private static ApplicationClass instance;
public ApplicationClass() {
instance = this;
}
#Override
public void onCreate() {
super.onCreate();
mSharedPrefs = getSharedPreferences("mysettings", MODE_PRIVATE);
mPrefsEditor = mSharedPrefs.edit();
}
public static SharedPreferences getmSharedPrefs() {
if (mSharedPrefs == null) {
mSharedPrefs = getContext().getSharedPreferences("mysettings",
MODE_PRIVATE);
}
return mSharedPrefs;
}
public static SharedPreferences.Editor getmPrefsEditor() {
if (mPrefsEditor == null || mSharedPrefs == null) {
mSharedPrefs = getContext().getSharedPreferences("mysettings",
MODE_PRIVATE);
mPrefsEditor = mSharedPrefs.edit();
}
return mPrefsEditor;
}
}
And you can use this like:
ApplicationClass.getmPrefsEditor().putString("key","value").commit();
And this:
ApplicationClass.getmSharedPrefs().getString("key");
in your Activities and Fragments.

Text to Speech producing error

So I am attempting to implement text to speech into my app for the first time ever. I continue to get an error thought when the speech is called. Here is the log that I am getting:
01-23 18:52:29.825: E/AndroidRuntime(24380): FATAL EXCEPTION: main
01-23 18:52:29.825: E/AndroidRuntime(24380): Process: com.rcd.league, PID: 24380
01-23 18:52:29.825: E/AndroidRuntime(24380): java.lang.NullPointerException
01-23 18:52:29.825: E/AndroidRuntime(24380): at com.rcd.league.speakActivity.speakOut(speakActivity.java:60)
01-23 18:52:29.825: E/AndroidRuntime(24380): at com.rcd.league.spawnTimers$15.onClick(Timers.java:350)
01-23 18:52:29.825: E/AndroidRuntime(24380): at android.view.View.performClick(View.java:4442)
01-23 18:52:29.825: E/AndroidRuntime(24380): at android.view.View$PerformClick.run(View.java:18423)
01-23 18:52:29.825: E/AndroidRuntime(24380): at android.os.Handler.handleCallback(Handler.java:733)
01-23 18:52:29.825: E/AndroidRuntime(24380): at android.os.Handler.dispatchMessage(Handler.java:95)
01-23 18:52:29.825: E/AndroidRuntime(24380): at android.os.Looper.loop(Looper.java:137)
01-23 18:52:29.825: E/AndroidRuntime(24380): at android.app.ActivityThread.main(ActivityThread.java:5083)
01-23 18:52:29.825: E/AndroidRuntime(24380): at java.lang.reflect.Method.invokeNative(Native Method)
01-23 18:52:29.825: E/AndroidRuntime(24380): at java.lang.reflect.Method.invoke(Method.java:515)
01-23 18:52:29.825: E/AndroidRuntime(24380): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:777)
01-23 18:52:29.825: E/AndroidRuntime(24380): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:593)
01-23 18:52:29.825: E/AndroidRuntime(24380): at dalvik.system.NativeStart.main(Native Method)
Here is my code:
package com.rcd.league;
import java.util.Locale;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.speech.tts.TextToSpeech;
import android.util.Log;
public class speakActivity extends Activity implements TextToSpeech.OnInitListener {
private int MY_DATA_CHECK_CODE = 0;
private TextToSpeech tts;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent checkTTSIntent = new Intent();
checkTTSIntent.setAction(TextToSpeech.Engine.ACTION_CHECK_TTS_DATA);
startActivityForResult(checkTTSIntent, MY_DATA_CHECK_CODE);
tts = new TextToSpeech(this, this);
}
#Override
public void onDestroy() {
// Don't forget to shutdown tts!
if (tts != null) {
tts.stop();
tts.shutdown();
}
super.onDestroy();
}
#Override
public void onInit(int status) {
if (status == TextToSpeech.SUCCESS) {
int result = tts.setLanguage(Locale.US);
if (result == TextToSpeech.LANG_MISSING_DATA
|| result == TextToSpeech.LANG_NOT_SUPPORTED) {
Log.e("TTS", "This Language is not supported");
} else {
speakOut();
}
} else {
Log.e("TTS", "Initilization Failed!");
}
}
public void speakOut() {
String text = "test";
tts.speak(text, TextToSpeech.QUEUE_FLUSH, null);
}
}
I am calling speakOut(); from another activity. Here is the clip of that code:
speakActivity speak = new speakActivity();
...
bt.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (btTimer.getText().toString().contains(":50")){
cd[0].start();
speak.speakOut();
} else {
cd[0].cancel();
cd[0].onFinish();
}
}
});
Any help would be greatly appreciated!
Thanks!
EDIT: I have also tried QUEUE_ADD instead of QUEUE_FLUSH and that didnt work either :/
You created the speakActivity Activity, but in the code you have posted you never started the Activity. Because the activity was never started, onCreate() was never called and therefore tts is not initialized. That is why you get a NullPointerException when you call
tts.speak(text, TextToSpeech.QUEUE_FLUSH, null);
in speakOut().
See this stackoverflow question for more information about when onCreate() is called: Is onCreate called when an Activity object is created?

how to find null pointer exception with logcat

I'm trying to build a small app that takes a data file in external storage and emails it. I keep getting 'null pointer exceptions' right away in logcat and then my app dies. I can't seem to locate my exception and I am wondering if there is a way to determine the line of code that is causing this. I have the MainActivity class and then a class called SendData- the code is below. I'm new at this so any help would be greatly appreciated- thank you.
private static final String TAG = "MainActivity_ErrorLog";
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#Override
public boolean onCreateOptionsMenu(Menu menu)
{
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
// Create the getData intent
Intent intentgetData = new Intent(MainActivity.this, SendData.class);
public void onStart()
{
{
try
{
File sd = Environment.getExternalStorageDirectory();
File data = Environment.getDataDirectory();
if (sd.canWrite())
{
// verify the paths
String currentDBPath = "TLC_COMMON/database.db";
String backupDBPath = "database.db";
File currentDB = new File(data, currentDBPath);
File backupDB = new File(sd, backupDBPath);
if (currentDB.exists())
{
FileChannel src = new FileInputStream(currentDB).getChannel();
FileChannel dst = new FileOutputStream(backupDB).getChannel();
dst.transferFrom(src, 0, src.size());
src.close();
dst.close();
}
}
}
catch (Exception e)
{
// change the V below to E when complete
Log.v(TAG,"ERROR: Database file not created");
}
startActivity(intentgetData);
}
}
}
--new class
public class SendData extends Activity
{
private static final String TAG = "MainActivity";
/* Checks if external storage is available to read */
public boolean isExternalStorageReadable()
{
String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state) ||
Environment.MEDIA_MOUNTED_READ_ONLY.equals(state))
{
return true;
}
return false;
}
/** Called when the user clicks the Send My Data button */
public SendData(View view)
{
// Send data by email
{
File root = Environment.getExternalStorageDirectory();
// verify it is saving as this file name; also path in previous class
String fileName = "database.db";
if (root.canWrite())
{
File attachment = new File(root, fileName);
Intent email = new Intent(Intent.ACTION_SENDTO);
email.putExtra(android.content.Intent.EXTRA_SUBJECT, "Exercise data");
email.putExtra(android.content.Intent.EXTRA_EMAIL, new String[]{"test#gmail.com"});
// is the Uri necessary?
email.putExtra(android.content.Intent.EXTRA_TEXT, Uri.fromFile(attachment));
// look at this VVV
startActivity(Intent.createChooser(email, "Send the data via Email"));}
else
{
// Change the V below to E when complete
Log.v(TAG, "Email send failed");
}
}
}
public void finish()
{
}
}
11-13 13:29:37.343: W/dalvikvm(3319): threadid=1: thread exiting with uncaught exception (group=0x418e3300)
11-13 13:29:37.343: E/AndroidRuntime(3319): FATAL EXCEPTION: main
11-13 13:29:37.343: E/AndroidRuntime(3319): java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.va.datasender/com.example.va.datasender.MainActivity}: java.lang.NullPointerException
11-13 13:29:37.343: E/AndroidRuntime(3319): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1983)
11-13 13:29:37.343: E/AndroidRuntime(3319): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2084)
11-13 13:29:37.343: E/AndroidRuntime(3319): at android.app.ActivityThread.access$600(ActivityThread.java:130)
11-13 13:29:37.343: E/AndroidRuntime(3319): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1195)
11-13 13:29:37.343: E/AndroidRuntime(3319): at android.os.Handler.dispatchMessage(Handler.java:99)
11-13 13:29:37.343: E/AndroidRuntime(3319): at android.os.Looper.loop(Looper.java:137)
11-13 13:29:37.343: E/AndroidRuntime(3319): at android.app.ActivityThread.main(ActivityThread.java:4745)
11-13 13:29:37.343: E/AndroidRuntime(3319): at java.lang.reflect.Method.invokeNative(Native Method)
11-13 13:29:37.343: E/AndroidRuntime(3319): at java.lang.reflect.Method.invoke(Method.java:511)
11-13 13:29:37.343: E/AndroidRuntime(3319): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
11-13 13:29:37.343: E/AndroidRuntime(3319): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
11-13 13:29:37.343: E/AndroidRuntime(3319): at dalvik.system.NativeStart.main(Native Method)
11-13 13:29:37.343: E/AndroidRuntime(3319): Caused by: java.lang.NullPointerException
11-13 13:29:37.343: E/AndroidRuntime(3319): at android.content.ContextWrapper.getPackageName(ContextWrapper.java:127)
11-13 13:29:37.343: E/AndroidRuntime(3319): at android.content.ComponentName.<init>(ComponentName.java:75)
11-13 13:29:37.343: E/AndroidRuntime(3319): at android.content.Intent.<init>(Intent.java:3301)
11-13 13:29:37.343: E/AndroidRuntime(3319): at com.example.va.datasender.MainActivity.<init>(MainActivity.java:36)
11-13 13:29:37.343: E/AndroidRuntime(3319): at java.lang.Class.newInstanceImpl(Native Method)
11-13 13:29:37.343: E/AndroidRuntime(3319): at java.lang.Class.newInstance(Class.java:1319)
11-13 13:29:37.343: E/AndroidRuntime(3319): at android.app.Instrumentation.newActivity(Instrumentation.java:1053)
11-13 13:29:37.343: E/AndroidRuntime(3319): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1974)
11-13 13:29:37.343: E/AndroidRuntime(3319): ... 11 more
Find the lowest "Caused by" and continue down until you reach a line from your code:
Caused by: java.lang.NullPointerException
at android.content.ContextWrapper.getPackageName(ContextWrapper.java:127)
at android.content.ComponentName.<init>(ComponentName.java:75)
at android.content.Intent.<init>(Intent.java:3301)
at com.example.va.datasender.MainActivity.<init>(MainActivity.java:36)
The <init> means you are doing something as a class variable or inside a constructor before the Activity has a valid Context... But the specific problem is on line 36.
I would guess that you are trying to create an Intent with this. Initialize your Intent inside onCreate() instead.
Found it. Change this:
// Create the getData intent
Intent intentgetData = new Intent(MainActivity.this, SendData.class);
to:
Intent intentgetData;
and inside onCreate() (or onStart() just before calling startActivity()) add:
intentgetData = new Intent(MainActivity.this, SendData.class);
Your problem comes from line 36 on your MainActivity. Check there for the problem.
11-13 13:29:37.343: E/AndroidRuntime(3319): at com.example.va.datasender.MainActivity.<init>(MainActivity.java:36)
The exeption from line number 36: at com.example.va.datasender.MainActivity.<init>(MainActivity.java:36).
Since the error log also shows android.content.Intent.<init> after the MainActivity.java:36, I would check the value for the first parameter in the following line, when instantiating intentgetData:
Intent intentgetData = new Intent(MainActivity.this, SendData.class);
Instead of having the instatiation done there, try doing it in the onStart() method just before calling startActivity(intentgetData);:
Intent intentgetData = new Intent(MainActivity.this, SendData.class);
startActivity(intentgetData);

Fatal Exception in android.widget.Button

I'm pretty new to Java and Android. I'm trying to make an app that calculates a volume of a liquid in a cylinder, then return the result to a textView box. But now when I click the button to Calculate, it is crashing and I don't know what I'm missing. Everything compiles fine.
package com.somename.fuel.volume.calculator;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.app.Activity;
public class CalculateCylinder extends Activity {
EditText length, width, height, depth;
TextView result;
Button calculate;
double firstNum, secNum, thirdNum, volume, area;
double liqVolume;
double radius;
double a, l, aSide,aTop,b,Arc,FluidSurfaceAreaTotal,r,d,v,h,fsal;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.calculate_cylinder);
calculate = (Button) findViewById(R.id.buttonCylCalc);
length = (EditText) findViewById(R.id.editCylLength);
height = (EditText) findViewById(R.id.editCylHeight);
depth = (EditText) findViewById(R.id.editCylDepth);
result = (TextView) findViewById(R.id.buttonCylResult);
calculate.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
//Toast.makeText(getApplicationContext(), (CharSequence) result, Toast.LENGTH_LONG).show();
try {
calculate();
} catch (Exception e) {
e.printStackTrace();
}
result.setText((CharSequence) result);
}
public TextView calculate() throws Exception {
// TODO Auto-generated method stub
double firstNum = Double.valueOf(length.getText().toString());
double secNum = Double.valueOf(height.getText().toString());
double thirdNum = Double.valueOf(depth.getText().toString());
radius = (secNum/2);
area = ((secNum*secNum)*3.14);
//liqVolume = (firstNum) * (radius*radius)(acos(radius-depth/radius))
// Cubic Volume
v = aSide * l;
// Fluid surface Area, Side
aSide = (r*r)*(3.14 / 2 -Math.acos(1-h/r)) - (r-h)*Math.sqrt(h*(2*r-h));
// Fluid Surface Area Top
aTop = 2*Math.sqrt((r*r)-((r-h)*(r-h) * l));
// Fluid Surface Area Bottom
b = fsal*l;
// Fluid Surface Area Total
FluidSurfaceAreaTotal = 2*aSide+aTop+b;
// Cylinder Radius
r = d/2;
// Cylinder Diameter
d = 2*r;
if (h <= r )
// Fluid Side Arc Length
fsal = 2*r*Math.acos((r-h)/r);
else if (h > r)
fsal = 2*r*(3.14-Math.acos((h-r)/r));
return result;
}
});
}
}
Here is a logcat:
10-18 05:24:38.893: E/AndroidRuntime(964): FATAL EXCEPTION: main
10-18 05:24:38.893: E/AndroidRuntime(964): java.lang.ClassCastException: android.widget.Button
10-18 05:24:38.893: E/AndroidRuntime(964): at com.dbryant423.fuel.volume.calculator.CalculateCylinder$1.onClick(CalculateCylinder.java:55 )
10-18 05:24:38.893: E/AndroidRuntime(964): at android.view.View.performClick(View.java:2408)
10-18 05:24:38.893: E/AndroidRuntime(964): at android.view.View$PerformClick.run(View.java:8816)
10-18 05:24:38.893: E/AndroidRuntime(964): at android.os.Handler.handleCallback(Handler.java:587)
10-18 05:24:38.893: E/AndroidRuntime(964): at android.os.Handler.dispatchMessage(Handler.java:92)
10-18 05:24:38.893: E/AndroidRuntime(964): at android.os.Looper.loop(Looper.java:123)
10-18 05:24:38.893: E/AndroidRuntime(964): at android.app.ActivityThread.main(ActivityThread.java:4627)
10-18 05:24:38.893: E/AndroidRuntime(964): at java.lang.reflect.Method.invokeNative(Native Method)
10-18 05:24:38.893: E/AndroidRuntime(964): at java.lang.reflect.Method.invoke(Method.java:521)
10-18 05:24:38.893: E/AndroidRuntime(964): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
10-18 05:24:38.893: E/AndroidRuntime(964): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
10-18 05:24:38.893: E/AndroidRuntime(964): at dalvik.system.NativeStart.main(Native Method)
I've been wracking my brains to try to figure out how to do the math on this, and I've not been able to find the answer to why it's crashing. I'm sure it's probably something simple that I've missed somewhere. If you need more information from the other files let me know, but this one seem the be the only one with the problem. I also know that there is unused variables that I've not removed yet.
result.setText((CharSequence) result);
This line cause Exception because you are casting Android View class to CharSequence Class.
Possible Solution:
Change return type of your method public TextView calculate() to
public String calculate()
Now in method public String calculate() return String of result fsal
And your button's Click() is something like,
calculate.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
//Toast.makeText(getApplicationContext(), (CharSequence) result, Toast.LENGTH_LONG).show();
String resultValue = "";
try {
resultValue = calculate();
} catch (Exception e) {
e.printStackTrace();
}
result.setText( resultValue);
}
result = (TextView) findViewById(R.id.buttonCylResult);
Are you casting properly? based on the naming, i would say that you are casting from a button to TextView. Try changing to,
result = (Button) findViewById(R.id.buttonCylResult);

The program is showing null pointer exception....converting double to int

My program causes a null pointer exception... I think the problem is in converting lat3 and lon3 from double to int... Is there some other way of parsing the location in double to int to give it to GeoPoint?
Code:
public class mapLoc extends com.google.android.maps.MapActivity implements LocationListener
{
TextView t ;
int lat2,lon2,lat3,lon3;
Double presentlon,presentlat;
Drawable d;
MapView mv;
MapController mc;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.map);
t = (TextView)findViewById(R.id.maptxt);
Intent intent = getIntent();
Bundle extra = intent.getExtras();
String latitude = extra.getString("latitude");
String longitude = extra.getString("longitude");
t.append(latitude+"\t");
t.append(longitude);
Float lat1 = Float.parseFloat(latitude);
Float lon1 = Float.parseFloat(longitude);
lat2 = (int) (lat1*1E6);
lon2 = (int) (lon1*1E6);
mv = (MapView)findViewById(R.id.maps);
mc = mv.getController();
mc.setZoom(14);
mv.setBuiltInZoomControls(true);
mv.displayZoomControls(true);
mv.setClickable(true);
List<Overlay> mapOverlays = mv.getOverlays();
Drawable drawable = this.getResources().getDrawable(R.drawable.marker);
overlay itemizedoverlay = new overlay(drawable, this);
lat3 = (int)(presentlat * 1E6);
lon3 = (int)(presentlon * 1E6);
GeoPoint point = new GeoPoint(lat3, lon3);
OverlayItem overlayitem = new OverlayItem(point, "Hello, user", "This is your present location");
mc.animateTo(point);
itemizedoverlay.addOverlay(overlayitem);
mapOverlays.add(itemizedoverlay);
GeoPoint point2 = new GeoPoint(lat2, lon2);
OverlayItem overlayitem2 = new OverlayItem(point2, "This is your","saved location");
itemizedoverlay.addOverlay(overlayitem2);
mapOverlays.add(itemizedoverlay);
}
#Override
public void onLocationChanged(Location location)
{
presentlat = location.getLatitude();
presentlon = location.getLongitude();
}
#Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
#Override
protected boolean isRouteDisplayed() {
// TODO Auto-generated method stub
return false;
};
}
Logcat errors:
05-25 10:21:52.444: W/dalvikvm(342): threadid=3: thread exiting with uncaught exception (group=0x4001b188)
05-25 10:21:52.444: E/AndroidRuntime(342): Uncaught handler: thread main exiting due to uncaught exception
05-25 10:21:52.454: E/AndroidRuntime(342): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.loc/com.loc.mapLoc}: java.lang.NullPointerException
05-25 10:21:52.454: E/AndroidRuntime(342): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2496)
05-25 10:21:52.454: E/AndroidRuntime(342): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2512)
05-25 10:21:52.454: E/AndroidRuntime(342): at android.app.ActivityThread.access$2200(ActivityThread.java:119)
05-25 10:21:52.454: E/AndroidRuntime(342): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1863)
05-25 10:21:52.454: E/AndroidRuntime(342): at android.os.Handler.dispatchMessage(Handler.java:99)
05-25 10:21:52.454: E/AndroidRuntime(342): at android.os.Looper.loop(Looper.java:123)
05-25 10:21:52.454: E/AndroidRuntime(342): at android.app.ActivityThread.main(ActivityThread.java:4363)
05-25 10:21:52.454: E/AndroidRuntime(342): at java.lang.reflect.Method.invokeNative(Native Method)
05-25 10:21:52.454: E/AndroidRuntime(342): at java.lang.reflect.Method.invoke(Method.java:521)
05-25 10:21:52.454: E/AndroidRuntime(342): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:860)
05-25 10:21:52.454: E/AndroidRuntime(342): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:618)
05-25 10:21:52.454: E/AndroidRuntime(342): at dalvik.system.NativeStart.main(Native Method)
05-25 10:21:52.454: E/AndroidRuntime(342): Caused by: java.lang.NullPointerException
05-25 10:21:52.454: E/AndroidRuntime(342): at com.loc.mapLoc.onCreate(mapLoc.java:71)
05-25 10:21:52.454: E/AndroidRuntime(342): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
05-25 10:21:52.454: E/AndroidRuntime(342): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2459)
In code snippet I dont think these presentlat and presentlon are getting initialized and hence throwing NPE.
lat3 = (int)(presentlat * 1E6); // NPE
lon3 = (int)(presentlon * 1E6);
Either initialize them before use or have a null check.
Keep in mind that Double (capital D) is not a primitive type, but a reference type that happens to be able to hold only boxed double (note the difference) values - or null. The Java language doesn't treat unboxing differently than other object accesses through a reference. If the reference is null (which obviously is the case here), it'll throw a NPE. The real difference with unboxing is that such access happens implicitly through something like ref.doubleValue() when you use the reference in arithmetic expressions.
You are right, your app is blowing up because presentlat and presentlon are private variables that have not been initialised. You should move that code into your onLocationChanged function.

Categories

Resources