Why does this cause a NullPointerException? - java

I have a program which is as follows, Can anyone tell me what is the reason for getting an NPE.
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
secondClass x = new secondClass();
x.sText("Test Spring");
}
}
public class secondClass extends MainActivity {
public void sText(String s) {
TextView text = (TextView) findViewById(R.id.text);
text.setText(s);
}
}
Mainfest
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
...
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/hello_world"
android:id="#+id/text"
/>
</RelativeLayout>
LogCat
08-16 01:31:11.320 15032-15032/? E/Trace: error opening trace file: No such file or directory (2)
08-16 01:31:11.420 836-987/? E/EmbeddedLogger: App crashed! Process: com.example.myapplication
08-16 01:31:11.420 836-987/? E/EmbeddedLogger: App crashed! Package: com.example.myapplication v1 (1.0)
08-16 01:31:11.420 836-987/? E/EmbeddedLogger: Application Label: My Application
08-16 01:31:11.420 15032-15032/? E/AndroidRuntime: FATAL EXCEPTION: main
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.myapplication/com.example.myapplication.MainActivity}: java.lang.NullPointerException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java)
at android.app.ActivityThread.access$600(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java)
at android.os.Handler.dispatchMessage(Handler.java)
at android.os.Looper.loop(Looper.java)
at android.app.ActivityThread.main(ActivityThread.java)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java)
at de.robv.android.xposed.XposedBridge.main(XposedBridge.java:110)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at android.app.Activity.findViewById(Activity.java)
at com.example.myapplication.secondClass.sText(secondClass.java:13)
at com.example.myapplication.MainActivity.onCreate(MainActivity.java:14)
at android.app.Activity.performCreate(Activity.java)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java)
To my understanding, this should instantiate and initialize a secondClass object then call its sText() method. The sText method should then store a reference in TextView. Next it calls the setText() method on TextView, which changes the text in the TextView to what was passed into sText().
The logcat says it throws a NullPointerException but I'm not entirely sure why. If this is a rookie mistake, it's because I am a rookie. Thank you.

You need to Override onCreate in your secondActivity and have setContentView(R.layout.mylayout). Then you can initialize your textview.
Also you need to start an Activity using intent
Intent intent = new Intent(MainActivtiy.this,SecondActivity.class);
startActivity(intent);
Remember to make an entry for the activity (SecondActivtiy) in manifest file
If you need to pass the string to second activity use intent.putExtra
Intent intent = new Intent(MainActivtiy.this,SecondActivity.class);
intent.putExtra("key",mystring);
startActivity(intent);
Then in secondActivity
TextView tv ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.mysecondlayout);
tv = (TextView) findViewByid(R.id.textView1);
Bundle extras = getIntent().getExtras();
if (extras != null) {
String value = extras.getString("key");
tv.setText(value);
//get the value based on the key
}
http://developer.android.com/reference/android/content/Intent.html#putExtra(java.lang.String, android.os.Bundle)
You can findViewById of the current view herarchy set to the activity.
Also you need to startActivity using intent rather doing this econdClass x = new secondClass()

Related

ClassCastException Error?

Just started learning how to develop using Android Studio and upon executing my application I receive this error:
06-10 22:53:56.819 11735-11735/com.example.jakey.new_application E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.jakey.new_application, PID: 11735
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.jakey.new_application/com.example.jakey.new_application.MainActivity}: java.lang.ClassCastException: android.support.constraint.ConstraintLayout cannot be cast to android.widget.LinearLayout
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2545)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2605)
at android.app.ActivityThread.access$1100(ActivityThread.java:165)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1473)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:179)
at android.app.ActivityThread.main(ActivityThread.java:5730)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:791)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:681)
Caused by: java.lang.ClassCastException: android.support.constraint.ConstraintLayout cannot be cast to android.widget.LinearLayout
at com.example.jakey.new_application.MainActivity.onCreate(MainActivity.java:20)
at android.app.Activity.performCreate(Activity.java:6439)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1108)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2498)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2605) 
at android.app.ActivityThread.access$1100(ActivityThread.java:165) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1473) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:179) 
at android.app.ActivityThread.main(ActivityThread.java:5730) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:791) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:681) 
The error is in the onCreate function you provided:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
background = (LinearLayout) findViewById(R.id.layout); //here is the error
myButton = (Button) findViewById(R.id.myButton);
myButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
background.setBackgroundColor(Color.parseColor("#00aa00"));
}
});
}
When you call findViewById(R.id.layout), it returns a ConstraintLayout, which you are then casting to LinearLayout, and that causes the error.
To fix it, just replace this line:
background = (LinearLayout) findViewById(R.id.layout);
with this one:
background = (ConstraintLayout) findViewById(R.id.layout);

Error starting Activity from a Class on Android

I have the following class SubMenuToolBar which I usually instantiate from an activity (MainActivity) that passes itself (this) in the constructor upon instantiation:
public class SubMenuToolBar extends Activity {
private android.support.v7.widget.Toolbar mToolbar;
private Activity mActivity;
RelativeLayout mLayout;
public SubToolbar(android.support.v7.widget.Toolbar toolbar, Activity activity) {
mActivity = activity;
mToolbar = toolbar;
mLayout = (RelativeLayout) mToolbar.findViewById(R.id.layout_toolbar);
mLayout.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent(mActivity, UserMessagesActivity.class);
startActivity(intent);
}
});
}
MainActivity.cs
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
new SubMenuToolBar ((android.support.v7.widget.Toolbar) findViewById(R.id.sub_toolbar), this);
}
Everytime I click on the element registered with the click event handler (in the activity) I get the popular error:
java.lang.NullPointerException: Attempt to invoke virtual method 'android.app.ActivityThread$ApplicationThread android.app.ActivityThread.getApplicationThread()' on a null object reference
11-20 08:31:33.422 23802-23802/com.xxx.apps.xxx E/AndroidRuntime: at android.app.Activity.startActivityForResult(Activity.java:3918)
11-20 08:31:33.422 23802-23802/com.xxx .apps.xxx E/AndroidRuntime: at android.app.Activity.startActivityForResult(Activity.java:3877)
11-20 08:31:33.422 23802-23802/com.xxx.apps.xxx E/AndroidRuntime: at android.app.Activity.startActivity(Activity.java:4200)
11-20 08:31:33.422 23802-23802/com.xxx.apps.xxx E/AndroidRuntime: at android.app.Activity.startActivity(Activity.java:4168)
11-20 08:31:33.422 23802-23802/com.xxx.apps.xxx E/AndroidRuntime: at com.xxx.apps.xxx.SubMenuToolBar$1.onClick(SubToolbar.java:28)
I have tried using the Activity in the Intent, the Context of the activity, getApplicationContext, and getBaseContext. All throws the same error on line:
Intent intent = new Intent(mActivity, MessagesActivity.class);
I have checked SO and various web resource where most of them point to the activity need to be passed to the class so it's Context is used in the Intent, I have done that as you can see above and made sure all details of the calling Activity is passed and used, the problem is still there.
Any idea what I'm doing wrong here?
try replace this:
Intent intent = new Intent(mActivity, UserMessagesActivity.class);
startActivity(intent);
to this:
Intent intent = new Intent(mActivity, UserMessagesActivity.class);
mActivity.startActivity(intent);
You are a little confused. Activity must not be instantiated with new. You have to start it using Intent. There is two activities but I think you only need one.
public class SubMenuToolBar extends Activity {
RelativeLayout mLayout;
#Override
protected void onCreate(Bundle savedInstance) {
super.onCreate(savedInstance);
setContentView(R.layout.your_activity_layout);
android.support.v7.widget.Toolbar mToolbar = (android.support.v7.widget.Toolbar) findViewById(R.id.sub_toolbar);
mLayout = (RelativeLayout)mToolbar.findViewById(R.id.layout_toolbar);
mLayout.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent(mActivity, UserMessagesActivity.class);
startActivity(intent);
});
}
And use SubMenuToolBar as your main activity.

Broadcast the method ArrayList.add from one Class to another Class with Intent

I try to use Intent to broadcast my text from the EditText field to my spinner witch using a ArrayList.
One class looks like:
MainActivity.java
public class MainActivity extends AppCompatActivity {
ArrayList<String> server_name_list;
...
...
spinner = (Spinner) findViewById(R.id.server_spinner);
server_name_list = getIntent().getStringArrayListExtra("server_name_list");
server_name_list = new ArrayList<String>();
ArrayAdapter<String> server_adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, server_name_list);
server_adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(server_adapter);
So I try to get the new item to my ArrayList by using
AddIP.java
public class AddIP extends AppCompatActivity {
ArrayList<String> server_name_list;
...
...
/* Add IP Button */
btn_add = (Button)findViewById(R.id.btn_add);
btn_add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
new_server_name = server_name.getText().toString();
server_name_list.add(new_server_name);
In the same class it works.
But I have one class with the EditText field and one with the spinner (in the MainActivity.class).
And here is the Intent method
Intent intent = new Intent(AddIP.this, MainActivity.class);
intent.putStringArrayListExtra("server_name_list", server_name_list);
But if I click on the "Add IP" button my programm crashs.
What did I wrong?
Error-Code while debuggin
11-13 15:19:27.875 7422-7422/de.kwietzorek.fulcrumwebview D/AndroidRuntime: Shutting down VM
11-13 15:19:27.876 7422-7422/de.kwietzorek.fulcrumwebview E/AndroidRuntime: FATAL EXCEPTION: main
11-13 15:19:27.876 7422-7422/de.kwietzorek.fulcrumwebview E/AndroidRuntime: Process: de.kwietzorek.fulcrumwebview, PID: 7422
11-13 15:19:27.876 7422-7422/de.kwietzorek.fulcrumwebview E/AndroidRuntime: java.lang.NullPointerException: Attempt to invoke virtual method 'boolean java.util.ArrayList.add(java.lang.Object)' on a null object reference
11-13 15:19:27.876 7422-7422/de.kwietzorek.fulcrumwebview E/AndroidRuntime: at de.kwietzorek.fulcrumwebview.AddIP$2.onClick(AddIP.java:49)
11-13 15:19:27.876 7422-7422/de.kwietzorek.fulcrumwebview E/AndroidRuntime: at android.view.View.performClick(View.java:5198)
11-13 15:19:27.876 7422-7422/de.kwietzorek.fulcrumwebview E/AndroidRuntime: at android.view.View$PerformClick.run(View.java:21147)
11-13 15:19:27.876 7422-7422/de.kwietzorek.fulcrumwebview E/AndroidRuntime: at android.os.Handler.handleCallback(Handler.java:739)
11-13 15:19:27.876 7422-7422/de.kwietzorek.fulcrumwebview E/AndroidRuntime: at android.os.Handler.dispatchMessage(Handler.java:95)
11-13 15:19:27.876 7422-7422/de.kwietzorek.fulcrumwebview E/AndroidRuntime: at android.os.Looper.loop(Looper.java:148)
11-13 15:19:27.876 7422-7422/de.kwietzorek.fulcrumwebview E/AndroidRuntime: at android.app.ActivityThread.main(ActivityThread.java:5417)
11-13 15:19:27.876 7422-7422/de.kwietzorek.fulcrumwebview E/AndroidRuntime: at java.lang.reflect.Method.invoke(Native Method)
11-13 15:19:27.876 7422-7422/de.kwietzorek.fulcrumwebview E/AndroidRuntime: at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
11-13 15:19:27.876 7422-7422/de.kwietzorek.fulcrumwebview E/AndroidRuntime: at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
EDIT
MainActivity.java
public class MainActivity extends AppCompatActivity {
...
...
ArrayList<String> server_name_list;
...
...
#Override
protected void onCreate(Bundle savedInstanceState) {
...
//Spinner
spinner = (Spinner) findViewById(R.id.server_spinner);
server_name_list = getIntent().getStringArrayListExtra("server_name_list");
server_name_list = new ArrayList<String>();
ArrayAdapter<String> server_adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, server_name_list);
server_adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(server_adapter);
AddIP.java
public class AddIP extends AppCompatActivity {
Button btn_back, btn_add;
EditText server_ip, server_name;
String new_server_ip, new_server_name;
ArrayList<String> server_name_list = new ArrayList<String>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.add_ip);
server_ip = (EditText)this.findViewById(R.id.edit_server_address);
server_name = (EditText)this.findViewById(R.id.edit_server_name);
/* Back Button */
btn_back = (Button)findViewById(R.id.btn_back);
btn_back.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(getApplicationContext(), MainActivity.class);
startActivity(intent);
}
});
/* Add IP Button */
btn_add = (Button)findViewById(R.id.btn_add);
btn_add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
/*new_server_ip = server_ip.getText().toString();
MainActivity.server_array_ip.add(new_server_ip);*/
new_server_name = server_name.getText().toString();
server_name_list = new ArrayList<String>();
server_name_list.add(new_server_name);
Intent intent = new Intent(AddIP.this, MainActivity.class);
intent.putStringArrayListExtra("server_name_list", server_name_list);
}
});
}
}
You should use OTTO Event Bus for sending data to other activity or you can make your arraylist that you want to edit as static, like this:
public static ArrayList<String> server_name_list;
and then access it in you onClick() as:
MainActivity.server_name_list.add(new_server_name);
then notify the adapter where you want to show the list.
the field server_name_list is null in AddIP.java.
it should either be
ArrayList<String> server_name_list = new Arraylist<String>;
at the top of the class or in the onClick method.
#Override
public void onClick(View view) {
new_server_name = server_name.getText().toString();
server_name_list = new Arraylist<String>;
server_name_list.add(new_server_name);
Maybe if in the MainActivity if you would remove server_name_list = new ArrayList<String>(); after server_name_list = getIntent().getStringArrayListExtra("server_name_list"); the arraylist will be filled with the parcelable data?
Update:
the first crash can easily be debugged. When something crashes always check the stack trace in the log. Alway check the log for the last reference to your own code in this case that is at de.kwietzorek.fulcrumwebview.AddIP$2.onClick(AddIP.java:49). Pointing to the line 49 the onClick method in the AddIP class. The error message java.lang.NullPointerException: Attempt to invoke virtual method 'boolean java.util.ArrayList.add(java.lang.Object)' on a null object reference means you are calling a method on a Object that is null and therefore cannot be executed. Which would translate the object server_name_list which is an java.util.ArrayList is null and should be initialized before using.
The second issue could easily be resolved by running through the code with the debugger enabled and setting a breakpoint on the first assignment of server_name_list and then stepping through the code line by line.

Calling getActivity() inside a Fragment returns null

excuse the trouble I was trying to make a listview for parsing a page for my app, I'll explain: I have a actionbar formed by Fragment.
When instazia the fragment, opening the app the first time "getActivity" does not return null, is the next time, when I start the AsyncTask
In the fragment in which I will stop parsing this error:
java.lang.NullPointerException
at android.widget.ArrayAdapter.init(ArrayAdapter.java:310)
at android.widget.ArrayAdapter.<init>(ArrayAdapter.java:104)
at com.megadown.megacodownloader.ParsingArrayAdapter.<init>(ParsingArrayAdapter.java:30)
at com.megadown.megacodownloader.Tab_Search$ParsingPaginaWeb.onPostExecute(Tab_Search.java:264)
at com.megadown.megacodownloader.Tab_Search$ParsingPaginaWeb.onPostExecute(Tab_Search.java:125)
at android.os.AsyncTask.finish(AsyncTask.java:631)
at android.os.AsyncTask.access$600(AsyncTask.java:177)
at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:644)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4898)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1006)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:773)
at dalvik.system.NativeStart.main(Native Method)
Code Java that refers:
protected void onPostExecute(String result)
{
// dopo che ho eseguito il parsing mostro i dati nella listview
adapter = new ParsingArrayAdapter(myActivity, titoli, descrizioni,immagini);
lista.setAdapter(adapter);
}
If you want I can post the code of the ArrayAdapter.
Thank you in advance
First, make sure myActivity has the correct value:
protected void onPostExecute(String result) {
Activity myActivity = getActivity();
adapter = new ParsingArrayAdapter(myActivity, titoli, descrizioni,immagini);
lista.setAdapter(adapter);
}
Next, point is, you can't be sure that your activity and fragment is still active in onPostExecute().
For example, the user could have pressed 'back' button or rotated the screen, which would re-create the activites and fragments.
So, the good code is:
protected void onPostExecute(String result) {
Activity myActivity = getActivity();
if (myActivity==null) return; // Fragment not active anymore, bail out
adapter = new ParsingArrayAdapter(myActivity, titoli, descrizioni,immagini);
lista.setAdapter(adapter);
}
Fragment's getActivity() will only return expectable value while the associated activity has done onCreate method.

NullPointerException in Activity when click on button

I have 2 activity screens. The 1st one has 2 buttons.
Button1 processes the data based from the user inputs while Button2 leads the user to the next activity screen based from the result of the process.
Whenever I click Button1, nothing happens, and
when i click Button2, the app stops working and gives the "Unfortunately..." message. At first, everything is going well but then I added a few codes then the app won't run.
MainActivity
public class MainActivity extends Activity
{
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//for the header
View title = getWindow().findViewById(android.R.id.title);
if (title != null)
{
ViewParent titleBar = title.getParent();
if (titleBar != null && (titleBar instanceof View))
{
View parentView = (View)titleBar;
parentView.setBackgroundColor(Color.RED);
}
}
//for button2
Button next = (Button) findViewById(R.id.DGButton);
next.setOnClickListener(new View.OnClickListener()
{
public void onClick(View view)
{
Intent myIntent = new Intent(view.getContext(), Activity2.class);
startActivityForResult(myIntent, 0);
}
});
}
public void calculateClickHandler(View view)
{
//handle the click of button1
if (view.getId() == R.id.CalculateButton)
{
//some codes
//the next activity screen uses the calculated value for some outputs
Intent intent1 = new Intent(MainActivity.this, Activity2.class);
Bundle b = new Bundle();
b.putDouble("key", bmiValue);
intent1.putExtras(b);
startActivityForResult(intent1,0);
}
}
Activity2:
public class Activity2 extends Activity
{
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
Button next = (Button) findViewById(R.id.BackToBMI);
next.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Intent intent = new Intent();
setResult(RESULT_OK, intent);
finish();
}
});
//some codes
Bundle b = getIntent().getExtras(); //the nullpointerexception is here
double bmival = b.getDouble("key");
}
}
Logcat:
12-27 05:15:03.263: E/AndroidRuntime(1091): FATAL EXCEPTION: main
12-27 05:15:03.263: E/AndroidRuntime(1091): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.bmicaldg/com.example.bmicaldg.Activity2}: java.lang.NullPointerException
12-27 05:15:03.263: E/AndroidRuntime(1091): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2180)
12-27 05:15:03.263: E/AndroidRuntime(1091): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
12-27 05:15:03.263: E/AndroidRuntime(1091): at android.app.ActivityThread.access$600(ActivityThread.java:141)
12-27 05:15:03.263: E/AndroidRuntime(1091): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
12-27 05:15:03.263: E/AndroidRuntime(1091): at android.os.Handler.dispatchMessage(Handler.java:99)
12-27 05:15:03.263: E/AndroidRuntime(1091): at android.os.Looper.loop(Looper.java:137)
12-27 05:15:03.263: E/AndroidRuntime(1091): at android.app.ActivityThread.main(ActivityThread.java:5039)
12-27 05:15:03.263: E/AndroidRuntime(1091): at java.lang.reflect.Method.invokeNative(Native Method)
12-27 05:15:03.263: E/AndroidRuntime(1091): at java.lang.reflect.Method.invoke(Method.java:511)
12-27 05:15:03.263: E/AndroidRuntime(1091): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
12-27 05:15:03.263: E/AndroidRuntime(1091): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
12-27 05:15:03.263: E/AndroidRuntime(1091): at dalvik.system.NativeStart.main(Native Method)
12-27 05:15:03.263: E/AndroidRuntime(1091): Caused by: java.lang.NullPointerException
12-27 05:15:03.263: E/AndroidRuntime(1091): at com.example.bmicaldg.Activity2.onCreate(Activity2.java:33)
12-27 05:15:03.263: E/AndroidRuntime(1091): at android.app.Activity.performCreate(Activity.java:5104)
12-27 05:15:03.263: E/AndroidRuntime(1091): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1080)
12-27 05:15:03.263: E/AndroidRuntime(1091): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2144)
12-27 05:15:03.263: E/AndroidRuntime(1091): ... 11 more
And also this is the XML file for the MainActivity:
Button1:
<Button
android:id="#+id/CalculateButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="#+id/textView4"
android:layout_alignParentRight="true"
android:layout_marginBottom="14dp"
android:background="#FF0000"
android:minHeight="30dip"
android:minWidth="65dip"
android:onClick="calculateClickHandler"
android:text="#string/CalculateButton"
android:textColor="#FFFFFF"
android:textSize="14sp" />
Button2:
<Button
android:id="#+id/DGButton"
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:background="#FF0000"
android:minHeight="30dip"
android:onClick="calculateClickHandler"
android:text="#string/DGButton"
android:textColor="#FFFFFF" />
I'm a beginner in Android Mobile programming so any help would be appreciated.
This error is occurred because you are not passing double value in intent on click event of next button.
Write below code
Intent intent1 = new Intent(MainActivity.this, Activity2.class);
intent1.putExtra("key", bmiValue);
startActivity(intent1);
instead of below code on click event of next button and intent code of calculateClickHandler() method.
Intent myIntent = new Intent(view.getContext(), Activity2.class);
startActivityForResult(myIntent, 0);
it will solve your problem.
try replacing following code:
//for button2
Button next = (Button) findViewById(R.id.DGButton);
next.setOnClickListener(new View.OnClickListener()
{
public void onClick(View view)
{
Intent myIntent = new Intent(view.getContext(), Activity2.class);
startActivityForResult(myIntent, 0);
}
});
with this:
//for button2
Button next = (Button) findViewById(R.id.DGButton);
next.setOnClickListener(new View.OnClickListener()
{
public void onClick(View view)
{
Intent myIntent = new Intent(MainActivity.this, Activity2.class);
startActivityForResult(myIntent, 0);
}
});
EDIT1: updated after logcat logs..
in the last line of the method double bmival = b.getDouble("key"); you are trying to read value from the bundle. As per the following javadoc for the method getExtras():
it returns the map of all extras previously added with putExtra(), or
null if none have been added.
Now since you are not setting any value in the MainActivity by using putExtra(), you are getting null in the response to the call to getExtras(). So you need to call putExtra() in the MainActivity to pass some value to Activity2 like following code:
//for button2
Button next = (Button) findViewById(R.id.DGButton);
next.setOnClickListener(new View.OnClickListener()
{
public void onClick(View view)
{
Intent myIntent = new Intent(view.getContext(), Activity2.class);
//Assuming bmival is a class variable that has the value that you want to pass on to Activity2
myIntent.putExtra("key",bmival);
startActivityForResult(myIntent, 0);
}
});
Also please put a null check before reading value form the bundle like in the following code:
if(b!=null){
double bmival = b.getDouble("key");
}
There might be few errors,
First and the most possible case might be that you have not defined your second Activity in your manifest file. So first check that whether you have defined all of your activities in manifest file.
The following statement is completely wrong.
Intent myIntent = new Intent(view.getContext(), Activity2.class);
Here you are using View of Buttin's onClickListener, but instead you should be using either the Activity Context, like MyActivity.this or the Application's Context, like this getApplicationContext().
Try to use
startActivity(myIntent);
instead of
startActivityForResult(myIntent, 0);
If at all your problem is not solved, the last not so possible case might be,
try adding flags to the intent, like this
myIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
You are not setting any values in the Intent Extras, Although it would give you an error in the next Activity,
myIntent.putExtra("key", bmiValue);
I think you looking for this, try this
//for button2
Button next = (Button) findViewById(R.id.DGButton);
next.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Intent myIntent = new Intent(MainActivity.this, Activity2.class);
Bundle b = new Bundle();
b.putDouble("key", bmiValue);
intent1.putExtras(b);
startActivityForResult(myIntent, 0);
}
});
Its better to Use startActivity() instead of startActivityForResult(intent1,0)
and also in your receiving side check whether the you are getting extras are not
So Try like this
Bundle extras = getIntent().getExtras();
if(extras != null)
{
double bmival = extras.getDouble("key");
}

Categories