Converting String to int from intent - java

I have 2 activities, and I'm passing edit number editText data to 2nd activity with intent. But in second activity I can't convert data from String to int with any functions. Here is my code:
This is main function:
public class MainActivity extends ActionBarActivity {
public EditText mAge;
public Button mCalculate;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mAge = (EditText) findViewById(R.id.numberImputEditText);
mCalculate = (Button) findViewById(R.id.calculateButton);
mCalculate.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String age = mAge.getText().toString();
Intent mIntent = new Intent(getApplicationContext(),FinalActivity.class);
mIntent.putExtra("age", age);
startActivity(mIntent);
}
});
}
}
and this is 2nd activity where is data passed:
public class FinalActivity extends Activity {
public Button mCalculateAgain;
public TextView mMinAge;
public TextView mMaxAge;
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_final);
Intent mIntent = getIntent();
String age = mIntent.getStringExtra("age");
mCalculateAgain = (Button) findViewById(R.id.calculateAgainButton);
mMinAge = (TextView) findViewById(R.id.minAgeTextView);
mMaxAge = (TextView) findViewById(R.id.maxAgeTextView);
Integer i = Integer.parseInt(age);
mMinAge.setText((i/2)+7);
mMaxAge.setText((i-7)*2);
Toast.makeText(getApplicationContext(), age, Toast.LENGTH_LONG).show();
mCalculateAgain.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent mIntent = new Intent(getApplicationContext(),MainActivity.class);
startActivity(mIntent);
}
});
}
}
here's the log:
`java.lang.RuntimeException: Unable to start activity ComponentInfo{com.robigroza.halfyourage/com.robigroza.halfyourage.FinalActivity}: android.content.res.Resources$NotFoundException: String resource ID #0x12
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2114)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2139)
at android.app.ActivityThread.access$700(ActivityThread.java:143)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1241)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4960)
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:1038)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:805)
at dalvik.system.NativeStart.main(Native Method)
Caused by: android.content.res.Resources$NotFoundException: String resource ID #0x12
at android.content.res.Resources.getText(Resources.java:1058)
at android.widget.TextView.setText(TextView.java:3857)
at com.robigroza.halfyourage.FinalActivity.onCreate(FinalActivity.java:35)
at android.app.Activity.performCreate(Activity.java:5203)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1094)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2078)

There's a few types of TextView.setText(...). One takes a CharSequence, which is probably what you expected to use, and another commonly used variant takes an int. The int form expects the parameter to be a resource ID.
mMinAge.setText((i/2)+7);
mMaxAge.setText((i-7)*2);
Given that (i/2)+7 isn't likely to resolve to a string resource, you could do:
mMinAge.setText("" + (i/2)+7);
mMaxAge.setText("" + (i-7)*2);
or better:
mMinAge.setText(String.valueOf((i/2)+7));
mMaxAge.setText(String.valueOf((i-7)*2));

Use this code in MainActivity.java
int age = Integer.parseInt(mage.getText().toString());
Intent i = new Intent(MainActivity.this,FinalActivity.class);
i.putExtra("age", age);
startActivity(i);
Code for FinalActivity .java
Bundle extras = getIntent().getExtras();
int age = extras.getInt("age");
In this way you can send integer value to other activity.
EnJoY coding :)

Related

Null Pointer Exception on Edit Text Android [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 5 years ago.
I'm writing a program to save user input from the edit text and inserting the text into a listview. I keep getting this null exception even though I've declared the Edit Text already.
public class AddEditAlbum extends AppCompatActivity {
/**
* These keys are to send back and forth information between the bundles and intents
*/
public static final String ALBUM_INDEX = "albumIndex";
public static final String ALBUM_NAME = "albumName";
EditText input;
Button save, cancel;
int albumIndex;
#Override
protected void onCreate(Bundle savedInstanceState) {
save = (Button) findViewById(R.id.save);
cancel = (Button) findViewById(R.id.cancel);
input = (EditText) findViewById(R.id.add);
// see if info was passed in to populate field
Bundle bundle = getIntent().getExtras();
if (bundle != null) {
albumIndex = bundle.getInt(ALBUM_INDEX);
input.setText(bundle.getString(ALBUM_NAME));
}
super.onCreate(savedInstanceState);
setContentView(R.layout.add_album);
}
public void Cancel(View view) {
setResult(RESULT_CANCELED);
finish(); //Returns to previous page on call stack
}
public void addAlbum(View view){
String name = input.getText().toString(); //Fix this, goes to null pointer
//Checks to see if input is null and returns
if(name == null || name.length()==0){
Toast.makeText(AddEditAlbum.this, "Enter valid album name", Toast.LENGTH_SHORT).show();
Bundle bundle = new Bundle();
bundle.putString(AlbumDialog.MESSAGE_KEY, "Album Name Required");
DialogFragment newFragment = new AlbumDialog();
newFragment.setArguments(bundle);
newFragment.show(getFragmentManager(), "badfields");
return;
}
//Toast.makeText(AddEditAlbum.this, "Enter valid album name", Toast.LENGTH_SHORT).show();
Bundle bundle = new Bundle();
bundle.putInt(ALBUM_INDEX, albumIndex);
bundle.putString(ALBUM_NAME, name);
// send back to caller
Intent intent = new Intent();
intent.putExtras(bundle);
setResult(RESULT_OK,intent);
finish();
}
}
public class MainActivity extends AppCompatActivity {
ListView listView;
private ArrayList<Album> albums;
public static final int EDIT_ALBUM_CODE = 1;
public static final int ADD_ALBUM_CODE = 2;
#Override
protected void onCreate(Bundle savedInstanceState) {
listView = (ListView) findViewById(R.id.album_list);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void Create(View view){
Intent intent = new Intent(this, AddEditAlbum.class);
startActivityForResult(intent, ADD_ALBUM_CODE);
}
protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
if (resultCode != RESULT_OK) {
return;
}
Bundle bundle = intent.getExtras();
if (bundle == null) {
return;
}
// gather all info passed back by launched activity
String name = bundle.getString(AddEditAlbum.ALBUM_NAME);
int index = bundle.getInt(AddEditAlbum.ALBUM_INDEX);
if (requestCode == EDIT_ALBUM_CODE){
Album album = albums.get(index);
album.albumName = name;
}
else if (requestCode == ADD_ALBUM_CODE){
ArrayList<Photo> photos = new ArrayList<>();
albums.add(new Album(name, photos));
}
// redo Adapter since source content has changed
//listView.setAdapter(new ArrayAdapter<Album>(this, album, albums));
}
So this is the full error I'm getting,
FATAL EXCEPTION: main
Process: com.example.mustu.androidphotos31, PID: 9965
java.lang.IllegalStateException: Could not execute method for android:onClick
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:293)
at android.view.View.performClick(View.java:5610)
at android.view.View$PerformClick.run(View.java:22265)
at android.os.Handler.handleCallback(Handler.java:751)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6077)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)
Caused by: java.lang.reflect.InvocationTargetException
at java.lang.reflect.Method.invoke(Native Method)
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:288)
at android.view.View.performClick(View.java:5610) 
at android.view.View$PerformClick.run(View.java:22265) 
at android.os.Handler.handleCallback(Handler.java:751) 
at android.os.Handler.dispatchMessage(Handler.java:95) 
at android.os.Looper.loop(Looper.java:154) 
at android.app.ActivityThread.main(ActivityThread.java:6077) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755) 
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.text.Editable android.widget.EditText.getText()' on a null object reference
at com.example.mustu.androidphotos31.AddEditAlbum.addAlbum(AddEditAlbum.java:54)
at java.lang.reflect.Method.invoke(Native Method) 
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:288) 
at android.view.View.performClick(View.java:5610) 
at android.view.View$PerformClick.run(View.java:22265) 
at android.os.Handler.handleCallback(Handler.java:751) 
at android.os.Handler.dispatchMessage(Handler.java:95) 
at android.os.Looper.loop(Looper.java:154) 
at android.app.ActivityThread.main(ActivityThread.java:6077) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755) 
super.onCreate(savedInstanceState);
setContentView(R.layout.add_album);
This has to be executed first, otherwise the contentView is not set and findViewById will not find anything, resulting in the EditText being null.
update your onCreate() like this.
we should call setContentView(R.layout.your_layout) for passing the layout to the java class, then only it's views can be used.. failing to do so, will lead to NPE.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.add_album);
save = (Button) findViewById(R.id.save);
cancel = (Button) findViewById(R.id.cancel);
input = (EditText) findViewById(R.id.add);
// see if info was passed in to populate field
Bundle bundle = getIntent().getExtras();
if (bundle != null) {
albumIndex = bundle.getInt(ALBUM_INDEX);
input.setText(bundle.getString(ALBUM_NAME));
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = (ListView) findViewById(R.id.album_list);
}
Also You are calling your listview before onCreate method thus giving you a NPE

When the list view is clicked, the application crashes! Why?

I have created a list view. And have added a 'OnItemClickListener()' to it. I am passing an intent and passing some data through the intent.
contactListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent intent = new Intent(MainActivity.this, ContactInfo.class);
Contact ParseContactID = contactAdapter.getItem(position);
intent.putExtra("ParseContactID", (Parcelable) ParseContactID);
startActivity(intent);
}
});
And I am retrieving the data in another class.
Intent intent = getIntent();
Bundle cBundle = intent.getExtras();
String ContactInfo = cBundle.getString("ParseContactID");
But the app crashes when I try and click the any lists. Here is the image of the app and app crash
The log cat has some fatal errors don't know how to fix those.
04-18 10:33:22.547 3528-3528/cm0573.contactsapp.user.contactsapp E/AndroidRuntime: FATAL EXCEPTION: main
Process: cm0573.contactsapp.user.contactsapp, PID: 3528
java.lang.ClassCastException: cm0573.contactsapp.user.contactsapp.Contact cannot be cast to android.os.Parcelable
at cm0573.contactsapp.user.contactsapp.MainActivity$4.onItemClick(MainActivity.java:135)
at android.widget.AdapterView.performItemClick(AdapterView.java:299)
at android.widget.AbsListView.performItemClick(AbsListView.java:1113)
at android.widget.AbsListView$PerformClick.run(AbsListView.java:2904)
at android.widget.AbsListView$3.run(AbsListView.java:3638)
at android.os.Handler.handleCallback(Handler.java:733)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5017)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
at dalvik.system.NativeStart.main(Native Method)
HELP!
You are putting a Contact object into the Extra but when you are extracting, you are trying to get a String. A Contact object and String object are not the same. Right?
You can make your Contact class implement the Serializable interface and after that, you can do this.
Bundle bundle = new Bundle();
bundle.putSerializable("ParseContactID", ParseContactID);
intent.putExtras(bundle);
Retrieving the data in another class
Bundle bundle = getIntent().getExtras();
Contact contact = (Contact)bundle.getSerializable("ParseContactID");
Or if you want to implement parcelable you can read This
public class ContactInfo extends AppCompatActivity {
TextView ContactInfoFamily_Name;
TextView ContactInfoFirst_Name;
TextView ContactInfoHouse_Number_ ;
TextView ContactInfoStreet_Name;
TextView ContactInfoTown_;
TextView ContactInfoCounty_;
TextView ContactInfoPost_Code;
TextView ContactInfoPhone_Number;
DatabaseHandler dbHandler = new DatabaseHandler(getApplicationContext());
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_contact_info);
ContactInfoFamily_Name = (TextView) findViewById(R.id.ContactInfoFamilyName);
ContactInfoFirst_Name = (TextView) findViewById(R.id.ContactInfoFirstName);
ContactInfoHouse_Number_ = (TextView) findViewById(R.id.ContactInfoHouseNumber);
ContactInfoStreet_Name = (TextView) findViewById(R.id.ContactInfoStreetName);
ContactInfoTown_ = (TextView) findViewById(R.id.ContactInfoTown);
ContactInfoCounty_ = (TextView) findViewById(R.id.ContactInfoCounty);
ContactInfoPost_Code = (TextView) findViewById(R.id.ContactInfoPostCode);
ContactInfoPhone_Number = (TextView) findViewById(R.id.ContactInfoPhone);
Intent intent = getIntent();
Bundle cBundle = intent.getExtras();
Contact ContactInfo = (Contact) cBundle.getSerializable("ParseContactID");
ContactInfoFamily_Name.setText(ContactInfo.getID());
ContactInfoFirst_Name.setText(getIntent().getExtras().getString("FirstNameKey"));
ContactInfoHouse_Number_.setText(getIntent().getExtras().getString("HouseNumberKey"));
ContactInfoStreet_Name.setText(getIntent().getExtras().getString("StreetNameKey"));
ContactInfoTown_.setText(getIntent().getExtras().getString("TownKey"));
ContactInfoCounty_.setText(getIntent().getExtras().getString("CountyKey"));
ContactInfoPost_Code.setText(getIntent().getExtras().getString("TownKey"));
ContactInfoPhone_Number.setText(getIntent().getExtras().getString("PhoneNumberKey"));
}
}
In your class Contact made it implements Serializable.
public class Contact implements Serializable{
}
Make sure your Contact class implements Parcelable.
public class Contact implements Parcelable {
...........
...............
}
Send Contact to ContactInfo Activity as below:
Intent intent = new Intent(MainActivity.this, ContactInfo.class);
Contact contact = contactAdapter.getItem(position);
intent.putExtra("ParseContactID", contact);
startActivity(intent);
Retrieving the Contact in ContactInfo Activity.
Contact contact = (Contact) getIntent().getParcelableExtra("ParseContactID");
Here is good Tutorial about using Parcelable.
Hope this will help~
ContactInfo class -
package cm0573.contactsapp.user.contactsapp;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
public class ContactInfo extends AppCompatActivity {
TextView ContactInfoFamily_Name = (TextView) findViewById(R.id.ContactInfoFamilyName);
TextView ContactInfoFirst_Name = (TextView) findViewById(R.id.ContactInfoFirstName);
TextView ContactInfoHouse_Number_ = (TextView) findViewById(R.id.ContactInfoHouseNumber);
TextView ContactInfoStreet_Name = (TextView) findViewById(R.id.ContactInfoStreetName);
TextView ContactInfoTown_ = (TextView) findViewById(R.id.ContactInfoTown);
TextView ContactInfoCounty_ = (TextView) findViewById(R.id.ContactInfoCounty);
TextView ContactInfoPost_Code = (TextView) findViewById(R.id.ContactInfoPostCode);
TextView ContactInfoPhone_Number = (TextView) findViewById(R.id.ContactInfoPhone);
DatabaseHandler dbHandler = new DatabaseHandler(getApplicationContext());
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_contact_info);
Intent intent = getIntent();
Bundle cBundle = intent.getExtras();
Contact ContactInfo = (Contact) cBundle.getSerializable("ParseContactID");
ContactInfoFamily_Name.setText(ContactInfo.getID());
ContactInfoFirst_Name.setText(getIntent().getExtras().getString("FirstNameKey"));
ContactInfoHouse_Number_.setText(getIntent().getExtras().getString("HouseNumberKey"));
ContactInfoStreet_Name.setText(getIntent().getExtras().getString("StreetNameKey"));
ContactInfoTown_.setText(getIntent().getExtras().getString("TownKey"));
ContactInfoCounty_.setText(getIntent().getExtras().getString("CountyKey"));
ContactInfoPost_Code.setText(getIntent().getExtras().getString("TownKey"));
ContactInfoPhone_Number.setText(getIntent().getExtras().getString("PhoneNumberKey"));
}
}

How to use interface between two activities [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 5 years ago.
I am passing my data from one activity to another activity via intent using a bundle.now this bundle is received by another activity here i am gonna display the values i passed.now when the a button is clicked it is suppose to fire a interface which has a function .There it is showing a null point error.
MainActivity.class
public class MainActivity extends AppCompatActivity implements WILO.Communicator {
int Tap=0,loss=9;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
CountDowntimer();
}
public void CountDowntimer()
{
new CountDownTimer(3000, 1000) {
#Override
public void onTick(long millisUntilFinished)
{
Tap+=1;
loss-=2;
}
#Override
public void onFinish()
{
Bundle arg=new Bundle();
arg.putInt("Tap",Tap);
arg.putInt("Loss",loss);
Intent i=new Intent(getBaseContext(),WILO.class);
i.putExtras(arg);
startActivity(i);
}
}.start();
}
#Override
public void Restart()
{
CountDowntimer();
}
}
WILO.class
public class WILO extends Activity {
Communicator communicator;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_wilo);
Bundle arg=getIntent().getExtras();
Button Restart;
TextView Tap,Loss;
Restart= (Button) findViewById(R.id.Restart);
Tap= (TextView) findViewById(R.id.Tap);
Loss= (TextView) findViewById(R.id.Loss);
Loss.setText(String.valueOf(arg.getInt("Loss")));
Tap.setText(String.valueOf(arg.getInt("Tap")));
Restart.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
communicator.Restart();
finish();
}
});
}
interface Communicator
{
public void Restart();
}
}
Error
FATAL EXCEPTION: main
Process: com.matrix.storm.question, PID: 27805
java.lang.NullPointerException
at com.matrix.storm.question.WILO$1.onClick(WILO.java:34)
at android.view.View.performClick(View.java:4452)
at android.view.View$PerformClick.run(View.java:18451)
at android.os.Handler.handleCallback(Handler.java:733)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5421)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at
com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:979)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:795)
at dalvik.system.NativeStart.main(Native Method)
How to use interface between two activities
You can not connect two activities using interfaces. If you want to send receive data between two activities, you can use the help of intent arguments and ActivityResult method.
Intent intent=new Intent(MainActivity.this,SecondActivity.class);
startActivityForResult(intent, 2);
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
}

App crashes when Intent is passed

I've MainActivity as following:
public class MainActivity extends AppCompatActivity {
DatabaseHelper myDb;
TextView textView;
Button button;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myDb =new DatabaseHelper(this);
Cursor res= myDb.getAllData();
if(res.getCount()==0)
{
textView = (TextView)findViewById(R.id.textView);
textView.setText("No Reminders");
button = (Button)findViewById(R.id.button);
button.setText("Create a Reminder");
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) { //on click 2nd activity is called.
Intent myIntent = new Intent(MainActivity.this, Main2Activity.class);
//myIntent.putExtra("key", value); //Optional parameters
startActivity(myIntent);
}
});
return;
}
StringBuffer buffer=new StringBuffer();
while(res.moveToNext())
{
buffer.append("Id : " +res.getString(0)+"\n");
buffer.append("Event : " +res.getString(1)+"\n");
buffer.append("Location : " +res.getString(2)+"\n");
}
textView = (TextView)findViewById(R.id.textView);
textView.setText(buffer.toString());
}
}
I've another activity named main2activity. But when I press the button in 1st activity, The app crashes and log gives NullPointerException. But this is not duplicate of any other such NullPointerException questions.
Because when I run only my second activity Main2Activity, separately, it does not give to this error. But when It is called from mainActivity, It is giving error. I can't understand why setting listener on button giving NullPointerException.
My Main2Activity is :
public class Main2Activity extends AppCompatActivity {
private static final int PLACE_PICKER_REQUEST = 1;
private TextView mName;
private TextView mAddress;
private TextView mAttributions;
private GoogleApiClient mGoogleApiClient;
public TextView tv4;
private static final LatLngBounds BOUNDS_MOUNTAIN_VIEW = new LatLngBounds(
new LatLng(37.398160, -122.180831), new LatLng(37.430610, -121.972090));
private boolean flag = false;
DatabaseHelper myDb;
EditText newevent;
Button submit;
Button viewremainders;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent intent = getIntent();
setContentView(R.layout.activity_main);
myDb =new DatabaseHelper(this);
newevent=(EditText)findViewById(R.id.newEvent);
submit=(Button)findViewById(R.id.submit);
viewremainders=(Button)findViewById(R.id.view);
Button pickerButton = (Button) findViewById(R.id.pickerButton);
tv4 = (TextView)findViewById(R.id.textView4);
pickerButton.setOnClickListener(new View.OnClickListener() { // <-- Error is here. (NullPointerException.)
#Override
public void onClick(View v) {
try {
PlacePicker.IntentBuilder intentBuilder =
new PlacePicker.IntentBuilder();
intentBuilder.setLatLngBounds(BOUNDS_MOUNTAIN_VIEW);
Intent intent = intentBuilder.build(Main2Activity.this);
startActivityForResult(intent, PLACE_PICKER_REQUEST);
} catch (GooglePlayServicesRepairableException
| GooglePlayServicesNotAvailableException e) {
e.printStackTrace();
}
}
});
AddData();
viewremainders();
}
Here I've mentioned where the error is occurring in comment. And I've other methods with this but only included necessary part.
Thanks in advance!
EDIT:
Log:
08-18 21:48:05.421 29655-29655/com.example.kaushal28.locationbasedreminder E/test: Exception
08-18 21:48:05.424 29655-29655/com.example.kaushal28.locationbasedreminder E/AndroidRuntime: FATAL EXCEPTION: main
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.kaushal28.locationbasedreminder/com.example.kaushal28.locationbasedreminder.Main2Activity}: java.lang.NullPointerException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2306)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2358)
at android.app.ActivityThread.access$600(ActivityThread.java:156)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1340)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:153)
at android.app.ActivityThread.main(ActivityThread.java:5299)
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:833)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:600)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at com.example.kaushal28.locationbasedreminder.Main2Activity.onCreate(Main2Activity.java:85)
at android.app.Activity.performCreate(Activity.java:5182)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1081)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2270)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2358) 
at android.app.ActivityThread.access$600(ActivityThread.java:156) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1340) 
at android.os.Handler.dispatchMessage(Handler.java:99) 
at android.os.Looper.loop(Looper.java:153) 
at android.app.ActivityThread.main(ActivityThread.java:5299) 
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:833) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:600) 
at dalvik.system.NativeStart.main(Native Method) 
You are setting the same layout in both activities. Make sure and add correct layout.
setContentView(R.layout.activity_main);
public class Main2Activity extends AppCompatActivity {
.
.
.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent intent = getIntent();
setContentView(R.layout.activity_main); // here is issue same layout is used for both activity
}
}

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.

Categories