App crashes when Intent is passed - java

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
}
}

Related

My app is crashing when I try to go to another activity

I'm trying to make a clickable image button redirect to the mainactivity
But since I've putted this code, the app crash when I click on the button to go to the 2nd Activity.
This id the first time I'm making an application.
Activity_good.java
public class Activity_good extends AppCompatActivity {
private Button backGood;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_good);
final TextView txtBien = (TextView) findViewById(R.id.txtBien);
Button genBien = (Button) findViewById(R.id.genBien);
final String[] pBien={"« Pour réussir, votre désir de réussite doit être plus grand que votre peur de l’échec. » Bill Cosby", "trql", "oui", "non"};
genBien.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int rando = (int) (Math.random()*4);
txtBien.setText(pBien[rando]);
}
});
backGood = (Button) findViewById(R.id.backGood);
backGood.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
openMainActivity();
}
});
}
public void openMainActivity(){
Intent intent = new Intent(this, MainActivity.class);
startActivity(intent);
}
}
MainActivity.java
public class MainActivity extends AppCompatActivity {
private Button button1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final MediaPlayer pianoman = MediaPlayer.create(this, R.raw.piano);
button1 = (Button) findViewById(R.id.button1);
button1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
pianoman.start();
openActivity_good();
}
});
}
public void openActivity_good() {
Intent intent = new Intent(this, Activity_good.class);
startActivity(intent);
}
}
Crash log ?
E/MediaPlayer: error (1, -19)
D/AndroidRuntime: Shutting down VM
E/AndroidRuntime: FATAL EXCEPTION: main
Process: fr.gab.artapp, PID: 9016
java.lang.RuntimeException: Unable to start activity ComponentInfo{fr.gab.artapp/fr.gab.artapp.Activity_good}: java.lang.ClassCastException: android.support.v7.widget.AppCompatImageButton cannot be cast to android.widget.Button
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2325)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2387)
at android.app.ActivityThread.access$800(ActivityThread.java:151)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5254)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
Caused by: java.lang.ClassCastException: android.support.v7.widget.AppCompatImageButton cannot be cast to android.widget.Button
at fr.gab.artapp.Activity_good.onCreate(Activity_good.java:30)
at android.app.Activity.performCreate(Activity.java:5990)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1106)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2278)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2387) 
at android.app.ActivityThread.access$800(ActivityThread.java:151) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:135) 
at android.app.ActivityThread.main(ActivityThread.java:5254) 
at java.lang.reflect.Method.invoke(Native Method) 
at java.lang.reflect.Method.invoke(Method.java:372) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698) 
Application terminated.
I exprected to to get back on mainactivity when I click on the button backGood.+
Change this line:
backGood = (Button) findViewById(R.id.backGood);
To this:
backGood = (AppCompatImageButton) findViewById(R.id.backGood);
You are casting a AppCompatImageButton as a Button.

Android- Null pointer exception from getStringExtra using intent send a value to another activity by button click

I am facing the problem when I use Intent to send a value to another activity by click a button. I have tried to solve it in many ways but it always show NullPointerException although I declared it clearly.
Here is my code.
Manufacturer.java
package com.example.student.macheckcar;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
public class Manufacturer extends AppCompatActivity {
public String message;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_manufacturer);
Button toyota = (Button) findViewById(R.id.Toyota);
Button subaru = (Button) findViewById(R.id.Subaru);
Button audi = (Button) findViewById(R.id.Audi);
toyota.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
message = "Toyota";
goAnother(message.toString());
}
});
subaru.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
message = "Subaru";
goAnother(message);
}
});
audi.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
message = "Audi";
goAnother(message);
}
});
}
protected void goAnother(String brand){
Intent i = new Intent(Manufacturer.this, ShowCarPrice.class);
i.putExtra("brand", brand);
startActivity(i);
}
}
Showcarprice.java
package com.example.student.macheckcar;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.view.Window;
import java.util.ArrayList;
public class ShowCarPrice extends AppCompatActivity {
private Cursor cursor;
private ArrayList<String> price;
private ArrayAdapter<String> aa;
private DBprice dbPrice;
private Manufacturer maFact;
SQLiteDatabase db;
ListView list;
Intent intent = getIntent();
String brand = intent.getStringExtra("brand");
#Override
protected void onCreate(Bundle savedInstanceState) {
requestWindowFeature(Window.FEATURE_NO_TITLE);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_show_car_price);
list = (ListView) findViewById(R.id.listView);
dbPrice = new DBprice(this);
db = dbPrice.getWritableDatabase();
cursor = db.rawQuery("SELECT " + dbPrice.KEY_TASK + " FROM " + dbPrice.TABLE_NAME + " WHERE Manufacturer = ?", new String[] {brand});
price = new ArrayList<String>();
cursor.moveToFirst();
while ( !cursor.isAfterLast() ){
price.add(cursor.getString(cursor.getColumnIndex(dbPrice.KEY_TASK)));
cursor.moveToNext();
}
aa = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, price);
list.setAdapter(aa);
}
public void onPause() {
super.onPause();
dbPrice.close();
db.close();
}
}
And the error:
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.student.macheckcar, PID: 934
java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.student.macheckcar/com.example.student.macheckcar.ShowCarPrice}: java.lang.NullPointerException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2110)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2233)
at android.app.ActivityThread.access$800(ActivityThread.java:135)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5001)
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:785)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at com.example.student.macheckcar.ShowCarPrice.<init>(ShowCarPrice.java:22)
at java.lang.Class.newInstanceImpl(Native Method)
at java.lang.Class.newInstance(Class.java:1208)
at android.app.Instrumentation.newActivity(Instrumentation.java:1061)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2101)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2233) 
at android.app.ActivityThread.access$800(ActivityThread.java:135) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:136) 
at android.app.ActivityThread.main(ActivityThread.java:5001) 
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:785) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601) 
at dalvik.system.NativeStart.main(Native Method) 
Please help.
UPDATE
public class ShowCarPrice extends AppCompatActivity {
// OK, Create the objects, variables here if needed
Intent intent;
String brand;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.your_activity_layout);
// You should assign the intent here (in onCreate method)
intent = getIntent();
// Then, the string variable
brand = intent.getStringExtra("brand");
// You can also check whether or not received a valid value
if (brand != null && !brand.isEmpty())
// do something with brand value
else
// brand value is null or empty
}
}
Well, you call getIntent() at the wrong position. You should call getIntent() in method onCreate() , and I don't know why you keep intent as a member of your activity. If I were you I just do
String brand = getIntent().getStringExtra("brand");
in onCreate() method.
get your intent and extras of intent in onCreate() method of activity just check below link for this
https://stackoverflow.com/a/5265952/5316836

What exactly is causing this NullPointerException? [duplicate]

This question already has answers here:
Android: NullPointerException Working With SharedPreferences
(3 answers)
Closed 7 years ago.
I'm pretty new to Android development and am currently working on an app which is supposed to save the current time and date when a button is pressed, store it to SharedPreferences and then present the String when a different button is pressed. I got it working but did some tinkering today and now I'm getting a NullPointerException that I can't solve, even after having spent about 45 minutes on Google and Stackoverflow trying different code fragments. Can anyone who is better at this than me tell me what I'm missing?
Here is the relevant code:
public class GetTimeStamp extends AppCompatActivity {
private String date;
public void setDate (View view){
DateFormat df = new SimpleDateFormat("dd.MM.yyy 'om' HH:mm");
date = df.format(Calendar.getInstance().getTime());
}
public String getDate(){
return date;
}
SharedPreferences prefs = this.getSharedPreferences("SharedPrefs", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_get_time_stamp);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fabSaveTimeStamp);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
setDate(view);
editor.putString("storedDate", date);
editor.commit();
Toast.makeText(getBaseContext(), "blablabla", Toast.LENGTH_SHORT).show();
}
})
FloatingActionButton fab3 = (FloatingActionButton) findViewById(R.id.fabShowTimeStamp);
fab3.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//retrieve the date from SharedPreferences and store it to a local String
String retrievedDate = prefs.getString("storedDate", null);
if (retrievedDate!=null){
AlertDialog alertDialog = new AlertDialog.Builder(GetTimeStamp.this).create(); //Read Update
alertDialog.setTitle("");
alertDialog.setMessage("somemessage" + retrievedDate);
alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
}
});
alertDialog.show();
}else {
//create an alert dialog explaining to the user that no date has been saved yet
AlertDialog alertDialog = new AlertDialog.Builder(GetTimeStamp.this).create(); //Read Update
alertDialog.setTitle("Error");
alertDialog.setMessage("errorexplanation");
alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
}
});
alertDialog.show();
}
}
});
And here are the errors:
02-08 22:49:36.142 19735-19735/? W/dalvikvm: threadid=1: thread exiting with uncaught exception (group=0x41ed7ce0)
02-08 22:49:36.152 19735-19735/? E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.user.appname, PID: 19735
java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.user.appname/com.example.user.appname.GetTimeStamp}: java.lang.NullPointerException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2131)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2264)
at android.app.ActivityThread.access$800(ActivityThread.java:144)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1205)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5139)
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:796)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:612)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at android.content.ContextWrapper.getSharedPreferences(ContextWrapper.java:173)
at com.example.user.appname.GetTimeStamp.<init>(GetTimeStamp.java:36)
at java.lang.Class.newInstanceImpl(Native Method)
at java.lang.Class.newInstance(Class.java:1208)
at android.app.Instrumentation.newActivity(Instrumentation.java:1061)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2122)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2264) 
at android.app.ActivityThread.access$800(ActivityThread.java:144) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1205) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:136) 
at android.app.ActivityThread.main(ActivityThread.java:5139) 
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:796) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:612) 
at dalvik.system.NativeStart.main(Native Method) 
You are trying to initialize the following class field before you are allowed to:
SharedPreferences prefs = this.getSharedPreferences("SharedPrefs", Context.MODE_PRIVATE);
Only declare the field:
SharedPreferences prefs;
and then assign it in your onCreate() method:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
prefs = getSharedPreferences("SharedPrefs", Context.MODE_PRIVATE);
...
}

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.

Converting String to int from intent

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 :)

Categories