Android program problem, NullPointerExc - java

Well, my program keeps giveing me a null point exception and I don't know why? I know it has something to do with the lvl variable, but I don't know what? What can I do to fix this problem?
Logcat:
03-18 16:14:55.852: ERROR/AndroidRuntime(277): FATAL EXCEPTION: main
03-18 16:14:55.852: ERROR/AndroidRuntime(277): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.games.think/com.games.think.Think}: java.lang.NullPointerException
03-18 16:14:55.852: ERROR/AndroidRuntime(277): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2663)
03-18 16:14:55.852: ERROR/AndroidRuntime(277): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2679)
03-18 16:14:55.852: ERROR/AndroidRuntime(277): at android.app.ActivityThread.access$2300(ActivityThread.java:125)
03-18 16:14:55.852: ERROR/AndroidRuntime(277): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2033)
03-18 16:14:55.852: ERROR/AndroidRuntime(277): at android.os.Handler.dispatchMessage(Handler.java:99)
03-18 16:14:55.852: ERROR/AndroidRuntime(277): at android.os.Looper.loop(Looper.java:123)
03-18 16:14:55.852: ERROR/AndroidRuntime(277): at android.app.ActivityThread.main(ActivityThread.java:4627)
03-18 16:14:55.852: ERROR/AndroidRuntime(277): at java.lang.reflect.Method.invokeNative(Native Method)
03-18 16:14:55.852: ERROR/AndroidRuntime(277): at java.lang.reflect.Method.invoke(Method.java:521)
03-18 16:14:55.852: ERROR/AndroidRuntime(277): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
03-18 16:14:55.852: ERROR/AndroidRuntime(277): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
03-18 16:14:55.852: ERROR/AndroidRuntime(277): at dalvik.system.NativeStart.main(Native Method)
03-18 16:14:55.852: ERROR/AndroidRuntime(277): Caused by: java.lang.NullPointerException
03-18 16:14:55.852: ERROR/AndroidRuntime(277): at com.games.think.Think.onCreate(Think.java:38)
03-18 16:14:55.852: ERROR/AndroidRuntime(277): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
03-18 16:14:55.852: ERROR/AndroidRuntime(277): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2627)
03-18 16:14:55.852: ERROR/AndroidRuntime(277): ... 11 more
Here is some of my code:
package com.games.think;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.RadioButton;
public class Think extends Activity implements OnClickListener{
int question = 1, lvl;
/** Called when the activity is first created. */
RadioButton lvl1;
RadioButton lvl2;
RadioButton lvl3;
RadioButton lvl4;
RadioButton lvl5;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button play = (Button)findViewById(R.id.play);
play.setOnClickListener(this);
Button level = (Button)findViewById(R.id.level);
level.setOnClickListener(this);
Button exit = (Button)findViewById(R.id.exit);
exit.setOnClickListener(this);
Button setLevel = (Button)findViewById(R.id.setLevel);
setLevel.setOnClickListener(this);
lvl1 = (RadioButton)findViewById(R.id.lvl1);
lvl2 = (RadioButton)findViewById(R.id.lvl2);
lvl3 = (RadioButton)findViewById(R.id.lvl3);
lvl4 = (RadioButton)findViewById(R.id.lvl4);
lvl5 = (RadioButton)findViewById(R.id.lvl5);
lvl = getLevel();
if(lvl == -1) {
lvl=getLevel();
}
}
#SuppressWarnings("null")
private int getLevel() {
String FILENAME = "think_level";
FileInputStream fis;
byte[] buffer = new byte[1000];
try {
fis = openFileInput(FILENAME);
} catch (FileNotFoundException e) {
setLevel("1");
return -1;
}
try {
fis.read(buffer,0,1000);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
fis.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String level = buffer.toString();
int iLevel = Integer.valueOf(level);
return iLevel;
}
private void setLevel(String level) {
String FILENAME = "think_level";
String string = level;
FileOutputStream fos;
try {
fos = openFileOutput(FILENAME, Context.MODE_PRIVATE);
fos.write(string.getBytes());
fos.close();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
#Override
public void onClick(View v) {
switch( v.getId()){
case R.id.play:
setContentView(R.layout.play);
setQuestion();
case R.id.level:
setContentView(R.layout.level);
switch(getLevel()) {
case 1:
lvl1.setChecked(true);
case 2:
lvl2.setChecked(true);
case 3:
lvl3.setChecked(true);
case 4:
lvl4.setChecked(true);
case 5:
lvl5.setChecked(true);
}
case R.id.setLevel:
if(lvl1.isChecked()) {
setLevel("1");
}
if(lvl2.isChecked()) {
setLevel("2");
}
if(lvl3.isChecked()) {
setLevel("3");
}
if(lvl4.isChecked()) {
setLevel("4");
}
if(lvl5.isChecked()) {
setLevel("5");
}
}
}
private void setQuestion() {
}
}

Check if the button with id "setLevel" is in your main.xml. If it is somewhere else, you can not find it like this:
Button setLevel = (Button)findViewById(R.id.setLevel);
But you need an inflater.

If iunderstand this is 37-38 lines
Button setLevel = (Button)findViewById(R.id.setLevel);
setLevel.setOnClickListener(this);
Seems like setLevel is null. Is button with id setLevel described in xml layout ?

Button setLevel = (Button)findViewById(R.id.setLevel);
This line is not returning an object. Make sure you have the id right and that there is a button registered with it.

Related

Why does my App crush?

Can someone point me out the error in this code. I am learning to code and I was trying to run my first app from tutorial I saw, until I found this message "Unfortunately, The New Boston has stopped". This the message I get when every time I tried to open it after installation. I even tried on three different phone and in my Emulator and the same thing happened. I looked at my code and I found no error on any line of code. And then I tried to debug it. Here is the entire code and the logcat report respectively.
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBar;
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import android.os.Build;
public class MainActivity extends ActionBarActivity {
int counter;
Button add,sub;
TextView display;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment())
.commit();
add = (Button) findViewById(R.id.bAdd);
add = (Button) findViewById(R.id.sSub);
display = (TextView) findViewById(R.id.tvDisplat);
add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
counter++;
display.setText("Your total is" + counter);
}
});
sub.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
counter--;
display.setText("Your total is" + counter);
}
});
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, 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();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
return rootView;
}
}
}
Logcat output
07-18 21:28:21.047: E/AndroidRuntime(10601): FATAL EXCEPTION: main
07-18 21:28:21.047: E/AndroidRuntime(10601): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.thenewbostone/com.thenewbostone.MainActivity}: java.lang.NullPointerException
07-18 21:28:21.047: E/AndroidRuntime(10601): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2663)
07-18 21:28:21.047: E/AndroidRuntime(10601): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2679)
07-18 21:28:21.047: E/AndroidRuntime(10601): at android.app.ActivityThread.access$2300(ActivityThread.java:125)
07-18 21:28:21.047: E/AndroidRuntime(10601): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2033)
07-18 21:28:21.047: E/AndroidRuntime(10601): at android.os.Handler.dispatchMessage(Handler.java:99)
07-18 21:28:21.047: E/AndroidRuntime(10601): at android.os.Looper.loop(Looper.java:123)
07-18 21:28:21.047: E/AndroidRuntime(10601): at android.app.ActivityThread.main(ActivityThread.java:4627)
07-18 21:28:21.047: E/AndroidRuntime(10601): at java.lang.reflect.Method.invokeNative(Native Method)
07-18 21:28:21.047: E/AndroidRuntime(10601): at java.lang.reflect.Method.invoke(Method.java:521)
07-18 21:28:21.047: E/AndroidRuntime(10601): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:871)
07-18 21:28:21.047: E/AndroidRuntime(10601): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:629)
07-18 21:28:21.047: E/AndroidRuntime(10601): at dalvik.system.NativeStart.main(Native Method)
07-18 21:28:21.047: E/AndroidRuntime(10601): Caused by: java.lang.NullPointerException
07-18 21:28:21.047: E/AndroidRuntime(10601): at com.thenewbostone.MainActivity.onCreate(MainActivity.java:34)
07-18 21:28:21.047: E/AndroidRuntime(10601): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
07-18 21:28:21.047: E/AndroidRuntime(10601): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2627)
07-18 21:28:21.047: E/AndroidRuntime(10601): ... 11 more
You just have problem with this, sub should be on the second line, not add.
add = (Button) findViewById(R.id.bAdd);
add = (Button) findViewById(R.id.sSub);
So, it crashes then on this line
sub.setOnClickListener(new View.OnClickListener() {
cause sub wasn't initialized.

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 application has stopped unexpectedly. Please try again

This is my code:
Line no. 94 corresponds to my method of getting all ids.
Always I get an error : Your application has stopped unexpectedly.
package karan.app.caloriecalculator;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
public class Main extends Activity implements AdapterView.OnItemSelectedListener {
Button bcal;
TextView intro, choose, duration, min, weight, kg;
EditText dur, weigh;
Spinner sel;
String temp;
public double w, d, calories;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
get_all_ids();
setArrayAdapter();
sel.setOnItemSelectedListener(this);
bcal.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
w = Float.valueOf(weigh.getText().toString());
d = Float.valueOf(dur.getText().toString());
if (temp.contentEquals("Aerobics:general")){
calories = 0.11*w*d;
}
else if (temp.contentEquals("Badminton")){
calories = (w/13)*d;
}
else if (temp.contentEquals("Basketball")){
calories = (w/7.45)*d;
}
else if (temp.contentEquals("Bicycling:slow (10-12 mph)")){
calories = (w/9.65)*d;
}
else if (temp.contentEquals("Bicycling:general (12-14 mph)")){
calories = (w/7.2)*d;
}
else if (temp.contentEquals("Bicycling:moderate (14-16 mph)")){
calories = (w/6)*d;
}
else if (temp.contentEquals("Bicycling:fast (16+ mph)")){
calories = (w/5)*d;
}
else if (temp.contentEquals("Bowling")){
calories = (w/19.1)*d;
}
else if (temp.contentEquals("Boxing: punching bag")){
calories = (w/9.6)*d;
}
else if (temp.contentEquals("Boxing: sparring")){
calories = (w/6.375)*d;
}
/* Thread t = new Thread(){
public void run(){
try{
sleep(1);
}
catch (InterruptedException e){
e.printStackTrace();
}
finally{
Intent openResult = new Intent("karan.app.caloriecalculator.RESULT");
startActivity(openResult);
}
}
}; // close the thread with a ;
*/
}});
}
public void get_all_ids() {
bcal.findViewById(R.id.b1);
intro.findViewById(R.id.tv1);
choose.findViewById(R.id.tv2);
duration.findViewById(R.id.tv3);
min.findViewById(R.id.tv4);
weight.findViewById(R.id.tv5);
kg.findViewById(R.id.tv6);
dur.findViewById(R.id.et2);
weigh.findViewById(R.id.et1);
sel.findViewById(R.id.sp1);
}
public double getCalories() {
return calories;
}
public void setArrayAdapter(){
//The createFromResource() method allows you to create an ArrayAdapter from the string array
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this, R.array.choices, android.R.layout.simple_spinner_dropdown_item);
//You should then call setDropDownViewResource(int) to specify the layout the adapter should use to display the list of spinner choices
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
//Call setAdapter() to apply the adapter to your Spinner.
sel.setAdapter(adapter);
}
public void onItemSelected(AdapterView<?> parent, View view, int position,
long id) {
// TODO Auto-generated method stub
Object item = parent.getItemAtPosition(position);
temp = item.toString();
}
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
}
LogCat:
07-28 14:10:03.545: E/AndroidRuntime(266): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2663)
07-28 14:10:03.545: E/AndroidRuntime(266): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2679)
07-28 14:10:03.545: E/AndroidRuntime(266): at android.app.ActivityThread.access$2300(ActivityThread.java:125)
07-28 14:10:03.545: E/AndroidRuntime(266): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2033)
07-28 14:10:03.545: E/AndroidRuntime(266): at android.os.Handler.dispatchMessage(Handler.java:99)
07-28 14:10:03.545: E/AndroidRuntime(266): at android.os.Looper.loop(Looper.java:123)
07-28 14:10:03.545: E/AndroidRuntime(266): at android.app.ActivityThread.main(ActivityThread.java:4627)
07-28 14:10:03.545: E/AndroidRuntime(266): at java.lang.reflect.Method.invokeNative(Native Method)
07-28 14:10:03.545: E/AndroidRuntime(266): at java.lang.reflect.Method.invoke(Method.java:521)
07-28 14:10:03.545: E/AndroidRuntime(266): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
07-28 14:10:03.545: E/AndroidRuntime(266): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
07-28 14:10:03.545: E/AndroidRuntime(266): at dalvik.system.NativeStart.main(Native Method)
07-28 14:10:03.545: E/AndroidRuntime(266): Caused by: java.lang.NullPointerException
07-28 14:10:03.545: E/AndroidRuntime(266): at karan.app.caloriecalc.MainActivity.get_all_ids(MainActivity.java:96)
07-28 14:10:03.545: E/AndroidRuntime(266): at karan.app.caloriecalc.MainActivity.onCreate(MainActivity.java:28)
07-28 14:10:03.545: E/AndroidRuntime(266): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
07-28 14:10:03.545: E/AndroidRuntime(266): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2627)
07-28 14:10:03.545: E/AndroidRuntime(266): ... 11 more
You are incorrectly fetching views in get_all_ids().
To get a view, you must do:
TextView intro;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
intro = (TextView) findViewById(R.id.tv1);
....
}
// You can now use intro and methods of TextView class.
I recommend you read the Android Beginner Guides.

App Crashes when Button is clicked (Passing a string between two classes.)

I've started on another class that get's two strings from another class, I've only set up one so far, but I just tested it out, but when I fill in my two edit text's and hit submit it crashes.
First Class (Launcher Class)
package com.gta5news.bananaphone;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import android.R.string;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class LogIn extends Activity implements OnClickListener {
Button send;
EditText user;
EditText pass;
CheckBox staySignedIn;
FileOutputStream Fos;
String FILENAME = "userandpass";
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.login);
send = (Button) findViewById(R.id.bLogIn);
user = (EditText) findViewById(R.id.eTuser);
pass = (EditText) findViewById(R.id.eTpassword);
staySignedIn = (CheckBox) findViewById(R.id.Cbstay);
send.setOnClickListener(this);
try {
Fos = openFileOutput(FILENAME, Context.MODE_PRIVATE);
Fos.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (staySignedIn.isChecked()) {
String a = user.getText().toString();
String b = pass.getText().toString();
File f = new File(FILENAME);
try {
Fos = new FileOutputStream(f);
//Write some Data
Fos.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.bLogIn:
if (pass.length() == 0)
Toast.makeText(this,
"Try to type in your username and password again!",
Toast.LENGTH_LONG).show();
else if (user.length() == 0)
Toast.makeText(this,
"Try to type in your username and password again!",
Toast.LENGTH_LONG).show();
else {
String u = user.getText().toString();
String p = pass.getText().toString();
Bundle send = new Bundle();
send.putString("key", u);
send.putString("key", p);
Intent a = new Intent(LogIn.this, logincheck.class);
startActivity(a);
Toast.makeText(this, "Were signing you in!", Toast.LENGTH_LONG)
.show();
break;
}
}
}
}
Second Class:
package com.gta5news.bananaphone;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
public class logincheck extends Activity {
String GotBread;
TextView user;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.logincheck);
user = (TextView) findViewById(R.layout.logincheck);
SetUp();
}
public void SetUp() {
// TODO Auto-generated method stub
Bundle GotData = getIntent().getExtras();
GotBread = GotData.getString("key");
user.setText(GotBread); {
}
}
}
LogCat:
01-19 08:53:56.641: E/AndroidRuntime(3319): ... 11 more
01-19 08:56:28.561: E/AndroidRuntime(3384): FATAL EXCEPTION: main
01-19 08:56:28.561: E/AndroidRuntime(3384): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.gta5news.bananaphone/com.gta5news.bananaphone.logincheck}: java.lang.NullPointerException
01-19 08:56:28.561: E/AndroidRuntime(3384): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2663)
01-19 08:56:28.561: E/AndroidRuntime(3384): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2679)
01-19 08:56:28.561: E/AndroidRuntime(3384): at android.app.ActivityThread.access$2300(ActivityThread.java:125)
01-19 08:56:28.561: E/AndroidRuntime(3384): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2033)
01-19 08:56:28.561: E/AndroidRuntime(3384): at android.os.Handler.dispatchMessage(Handler.java:99)
01-19 08:56:28.561: E/AndroidRuntime(3384): at android.os.Looper.loop(Looper.java:123)
01-19 08:56:28.561: E/AndroidRuntime(3384): at android.app.ActivityThread.main(ActivityThread.java:4627)
01-19 08:56:28.561: E/AndroidRuntime(3384): at java.lang.reflect.Method.invokeNative(Native Method)
01-19 08:56:28.561: E/AndroidRuntime(3384): at java.lang.reflect.Method.invoke(Method.java:521)
01-19 08:56:28.561: E/AndroidRuntime(3384): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
01-19 08:56:28.561: E/AndroidRuntime(3384): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
01-19 08:56:28.561: E/AndroidRuntime(3384): at dalvik.system.NativeStart.main(Native Method)
01-19 08:56:28.561: E/AndroidRuntime(3384): Caused by: java.lang.NullPointerException
01-19 08:56:28.561: E/AndroidRuntime(3384): at com.gta5news.bananaphone.logincheck.SetUp(logincheck.java:24)
01-19 08:56:28.561: E/AndroidRuntime(3384): at com.gta5news.bananaphone.logincheck.onCreate(logincheck.java:17)
01-19 08:56:28.561: E/AndroidRuntime(3384): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
01-19 08:56:28.561: E/AndroidRuntime(3384): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2627)
01-19 08:56:28.561: E/AndroidRuntime(3384): ... 11 more
Get Bundle in Oncreate Method
And
Use Like
Intent i = new Intent(Login.this,logincheck.class);
i.putExtra("key", user);
i.putExtra("key1", pass);
startActivity(i);
And
user = (TextView) findViewById(R.layout.logincheck);
Instead of
user = (TextView) findViewById(R.id.logincheck);
So User is Null
On your main activity you're creating the Bundle and inserting the content in it, but you're not sending it to the the intent.
You should put the information on the Intent before starting the second activity. Do something like this:
Intent a = new Intent(LogIn.this, logincheck.class);
a.putExtra("key", u);
a.putExtra("key", p);
startActivity(a);
I will try to give u a clue how to solve it..it can be even more fail-proffed but this should work for u..
Intent i = new Intent(LogIn.this, logincheck.class);
i.putExtra("username", sUsername);
i.putExtra("password", SPassword);
To get the saved data in new activity try with:
String newString;
if(extras == null) {
sUsernameInNewActivity = null;
sPasswordInNewActivity = null;
} else {
sUsernameInNewActivity = extras.getString("username");
sPasswordInNewActivity = extras.getString("password");
}
btw. A lot of bad practice in your code.. :( I have troubles to read it easy..
for example:
you have two variables with different scope and type but exactly the same name (try to find it)
did u want to join something with this code or???
send.putString("key", u);
send.putString("key", p);
how u thought to get them later? together/separately?
Hope u will solve it. Cheers

Code keeps thowing a NPE, cannot find the cause

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.

Categories

Resources