What exactly is causing this NullPointerException? [duplicate] - java

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);
...
}

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 - MediaRecorder.stop() crashes the app

Everybody,
I'm trying to record audio.
The audio is record perfectly when record button is clicked.
I try to stop the record and the app crashing immediately after the stop button is clicked.
Can you please help me on fixing this code so i could continue building my project.
Here's part of the code:
public class window2 extends AppCompatActivity implements AdapterView.OnItemSelectedListener{
Spinner spinner;//choice between record and Speech-2-text.
Button play,stop,record;//record, stop and replay buttons.
String outputFile;//the record file.
MediaRecorder myAudioRecorder;//the record method.
int reRecord = 0;//reRecord value.
int pathVal = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_window2);
spinner = findViewById(R.id.spinner);
spinner.setOnItemSelectedListener(this);//upon change between record and S2T.
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
SharedPreferences.Editor edit = sharedPreferences.edit();
if( sharedPreferences.getInt("pathVal",0) == 0)
edit.putInt("pathVal",1);
else {
pathVal = sharedPreferences.getInt("pathVal", pathVal);
edit.putInt("pathVal",pathVal+1);
}
pathVal = sharedPreferences.getInt("pathVal", 0);
edit.commit();
//3 buttons for record,stop and replay.
play = findViewById(R.id.button14);
stop = findViewById(R.id.button13);
record = findViewById(R.id.button11);
//to immune issues that may start if the buttons are enabled.
stop.setEnabled(false);
play.setEnabled(false);
//the file of recording.
outputFile = Environment.getExternalStorageDirectory().getAbsolutePath() + "/"+pathVal+".3gp";
//record settings.
myAudioRecorder = new MediaRecorder();
myAudioRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
myAudioRecorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);
myAudioRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
myAudioRecorder.setOutputFile(outputFile);
//record button click.
record.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
play.setEnabled(false);
try{
//if we want to re record.
if(reRecord == 1)
{
//we build the settings again.
myAudioRecorder = new MediaRecorder();
myAudioRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
myAudioRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
myAudioRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
myAudioRecorder.setOutputFile(outputFile);
}
//prepare and start methods.
myAudioRecorder.prepare();
myAudioRecorder.start();
}catch (IllegalStateException ise) {
//something
}catch (IOException ioe){
//something
}
record.setEnabled(false);
stop.setEnabled(true);
Toast.makeText(window2.this, "Recording...", Toast.LENGTH_SHORT).show();
}
});
//stop button click.
stop.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
myAudioRecorder.stop();
myAudioRecorder.reset();
reRecord = 1;
myAudioRecorder = null;
record.setEnabled(true);
stop.setEnabled(false);
play.setEnabled(true);
Toast.makeText(window2.this, "Recorded!", Toast.LENGTH_SHORT).show();
}
});
play.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
MediaPlayer mediaPlayer = new MediaPlayer();
try {
mediaPlayer.setDataSource(outputFile);
mediaPlayer.prepare();
mediaPlayer.start();
Toast.makeText(window2.this, "Playing.", Toast.LENGTH_SHORT).show();
} catch (Exception e){
//something
}
}
});
}
public void OpenWindow4(View view)
{
Spinner spinner = findViewById(R.id.spinner3);
String SpinTxt = spinner.getSelectedItem().toString();
EditText edit2 = findViewById(R.id.editText);
String editTextTxt = edit2.getText().toString();
Intent intent = new Intent(this,window4.class);
intent.putExtra("THE_TEXT",editTextTxt);
intent.putExtra("SPIN_CHOICE",SpinTxt);
startActivity(intent);
}
public void OpenWindow4Speech(View view)
{
Spinner spinner = findViewById(R.id.spinner4);
String SpinTxt = spinner.getSelectedItem().toString();
EditText edit2 = findViewById(R.id.editText2);
String editTextTxt = edit2.getText().toString();
Intent intent = new Intent(this,window4.class);
intent.putExtra("THE_RECORD",outputFile);
intent.putExtra("SPIN_CHOICE",SpinTxt);
intent.putExtra("THE_TEXT",editTextTxt);
startActivity(intent);
}
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
String item = adapterView.getItemAtPosition(i).toString();
if (item.equals("S2T"))
{
Intent intent = new Intent(this,windows2B.class);
startActivity(intent);
}
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
}
and here is the logcat:
01-13 08:42:27.105 1031-1031/com.example.simplenigal.prealphabuilt V/MediaRecorder: prepare
01-13 08:42:27.105 1031-1031/com.example.simplenigal.prealphabuilt V/MediaRecorder: start
01-13 08:42:27.105 1031-1031/com.example.simplenigal.prealphabuilt E/MediaRecorder: start failed: -38
01-13 08:42:27.757 1031-1038/com.example.simplenigal.prealphabuilt I/art: Do partial code cache collection, code=115KB, data=106KB
01-13 08:42:27.757 1031-1038/com.example.simplenigal.prealphabuilt I/art: After code cache collection, code=115KB, data=106KB
01-13 08:42:27.757 1031-1038/com.example.simplenigal.prealphabuilt I/art: Increasing code cache capacity to 512KB
01-13 08:42:27.759 1031-1038/com.example.simplenigal.prealphabuilt I/art: Compiler allocated 6MB to compile void android.view.ViewRootImpl.performTraversals()
01-13 08:42:31.382 1031-1031/com.example.simplenigal.prealphabuilt I/ViewRootImpl: ViewRoot's Touch Event : ACTION_DOWN
01-13 08:42:31.452 1031-1031/com.example.simplenigal.prealphabuilt I/ViewRootImpl: ViewRoot's Touch Event : ACTION_UP
01-13 08:42:31.462 1031-1031/com.example.simplenigal.prealphabuilt V/MediaRecorder: stop
01-13 08:42:31.462 1031-1031/com.example.simplenigal.prealphabuilt E/MediaRecorder: stop called in an invalid state: 0
01-13 08:42:31.463 1031-1031/com.example.simplenigal.prealphabuilt D/AndroidRuntime: Shutting down VM
01-13 08:42:31.468 1031-1031/com.example.simplenigal.prealphabuilt E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.simplenigal.prealphabuilt, PID: 1031
java.lang.IllegalStateException
at android.media.MediaRecorder.native_stop(Native Method)
at android.media.MediaRecorder.stop(MediaRecorder.java:896)
at com.example.simplenigal.prealphabuilt.window2$2.onClick(window2.java:102)
at android.view.View.performClick(View.java:5624)
at android.view.View$PerformClick.run(View.java:22441)
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:6316)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:872)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:762)
thanks to every one who paying attention and helping.
Still looking for help

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

ClassCastException android Integer to Long

I was using an integer for the money factor in this little test app but I realized that long was more appropriate and I changed the code so that money is a long instead of an int and I changed SharedPreferences appropriately as well, however it does not work wheras it did when I used int. Thank you for the help!
public class Home extends AppCompatActivity {
SharedPreferences pref;
SharedPreferences.Editor editor;
Intent intent;
TextView home_money_view;
long money; // this is the variable that is causing problems
int initial;
final long TEST = (long)-1;
int gold_pieces;
int gold_price = 50;
TimerTask timerTask;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
home_money_view = (TextView) findViewById(R.id.home_money_view)
pref = getApplicationContext().getSharedPreferences("MY_PREFS", MODE_PRIVATE);
editor = pref.edit();
money = pref.getLong("temp_money",Long.MIN_VALUE); // get value
if (money==Long.MIN_VALUE){
money=0;
}
gold_pieces = pref.getInt("temp_gold",-1);
if (gold_pieces==-1){
gold_pieces=0;
}
initial = pref.getInt("initial",0);
money+=initial;
editor.putInt("initial",0);
editor.commit();
home_money_view = (TextView) findViewById(R.id.home_money_view);
home_money_view.setText(money+"");
editor.commit();
}
public void backToSplash(View view){
intent = new Intent(Home.this,BusinessSelector.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
}
public void goToSecondView(View view){
long temp_money = money;
editor.putLong("temp_money",temp_money); // set value
int temp_gold = gold_pieces;
editor.putInt("temp_gold",temp_gold);
editor.commit();
intent = new Intent(Home.this,SecondView.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
}
public void goToOtherView(View view) {
long temp_money = money;
editor.putLong("temp_money",temp_money); // set value
int temp_gold = gold_pieces;
editor.putInt("temp_gold", temp_gold);
editor.commit();
intent = new Intent(Home.this, Next.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
}
}
Logcat:
04-13 19:01:03.675 12896-12896/com.exampleryancocuzzo.ryan.markettycoon E/AndroidRuntime: FATAL EXCEPTION: main
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.exampleryancocuzzo.ryan.markettycoon/com.exampleryancocuzzo.ryan.markettycoon.Home}: java.lang.ClassCastException: java.lang.Integer cannot be cast to java.lang.Long
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1956)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1981)
at android.app.ActivityThread.access$600(ActivityThread.java:123)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1147)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4424)
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:784)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.ClassCastException: java.lang.Integer cannot be cast to java.lang.Long
at android.app.SharedPreferencesImpl.getLong(SharedPreferencesImpl.java:228)
at com.exampleryancocuzzo.ryan.markettycoon.Home.onCreate(Home.java:56)
at android.app.Activity.performCreate(Activity.java:4466)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1049)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1920)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1981) 
at android.app.ActivityThread.access$600(ActivityThread.java:123) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1147) 
at android.os.Handler.dispatchMessage(Handler.java:99) 
at android.os.Looper.loop(Looper.java:137) 
at android.app.ActivityThread.main(ActivityThread.java:4424) 
at java.lang.reflect.Method.invokeNative(Native Method) 

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