Retain Values from edit boxes android code - java

I have this code, I want to retain my value of the editbox from the first input after change or start of new activity.
this what happens in this code:
editbox1 = 1 > start new activity > back to recent activity > editbox1 = null
I need this to happened:
editbox1 = 1 > start new activity > back to recent activity > editbox1 = 1
CODE
package org.example.touch;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.*;
import android.widget.EditText;
public class SettingsClass extends Activity {
private EditText Alpha;
private EditText Beta;
private EditText Charlie;
private EditText Delta;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.settings);
Alpha = (EditText) findViewById(R.id.editText1);
Beta = (EditText) findViewById(R.id.editText2);
Charlie = (EditText) findViewById(R.id.editText3);
Delta = (EditText) findViewById(R.id.editText4);
}
public void buttonSBHandler (View view){
String Aint = Alpha.getText().toString();
String Bint = Beta.getText().toString();
String Cint = Charlie.getText().toString();
String Dint = Delta.getText().toString();
Intent startNewActivityOpen = new Intent(SettingsClass.this, GameUi.class);
startNewActivityOpen.putExtra("Aint", Aint);
startNewActivityOpen.putExtra("Bint", Bint);
startNewActivityOpen.putExtra("Cint", Cint);
startNewActivityOpen.putExtra("Dint", Dint);
startActivityForResult(startNewActivityOpen, 0);
//startActivity(new Intent(view.getContext(), GameUi.class));
}
}

1)One thing is that you can go with shared preference store your value in shared preference and on oncreate() method first check whether shared preference is null or not if it is not null than get the value from shared preference.
or
2)Just make those data of edit text as static like-
static String Aint = Alpha.getText().toString();
static String Bint = Beta.getText().toString();
static String Cint = Charlie.getText().toString();
static String Dint = Delta.getText().toString();
so whenever you will come back to the activity so the previous data of the edit text will be shown there.
hope these thing will work for you perfectly.
thanks

Related

Getting error in main activity on my basic calculator app

I'm creating a simple android calculator app. There is no compile time error, but when I'm tapping on any button, the app crashes.
package com.buckydroid.myapplication;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
private TextView screen;
private String str1,str2,str3,result,str,sign;
private Double a,b;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
screen = (TextView)findViewById(R.id.textview);
}
private void onClick(View v){
Button button = (Button) v;
str += button.getText().toString();
screen.setText(str);
a = Double.parseDouble(str);
str = "";
}
private void onClickSigns(View v){
Button button = (Button) v;
sign = ((Button) v).getText().toString();
screen.setText(sign);
str="";
}
private void calculate(View v){
Button button = (Button) v;
str2 = screen.getText().toString();
b = Double.parseDouble(str2);
if (sign .equals("+")){
result = a+b+"";
}
else if (sign .equals("-")){
result = a-b+"";
}
else if (sign .equals("X")){
result = a*b+"";
}
else if (sign .equals("÷")){
result = a/b+"";
}
else{
result = "Something went wrong";
}
screen.setText(result);
}
}
Error Log
10-08 19:44:59.361 19449-19449/com.buckydroid.myapplication E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.buckydroid.myapplication, PID: 19449
java.lang.IllegalStateException: Could not find method onClick(View) in a parent or ancestor Context for android:onClick attribute defined on view class android.support.v7.widget.AppCompatButton
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.resolveMethod(AppCompatViewInflater.java:327)
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:284)
at android.view.View.performClick(View.java:5198)
at android.view.View$PerformClick.run(View.java:21147)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
So if you need any other code then please comment
Thank you in advance..
Ok I got it after building in Android studio. The error is a lot bigger than what you pasted and I was able to track it down with the stack trace.
Basically you are trying to concatenate a string to a null with this line in your onClick method: str += button.getText().toString();
Since you can't do that you can fix the issue by replacing:
str += button.getText().toString();
With this:
str = button.getText().toString();
OR
Since this is a calculator app, you can initialize str in the onCreate method with str = ""; and then also remove str = ""; from the onClick method.
Full Code here:
public class MainActivity extends AppCompatActivity {
private TextView screen;
private String str1,str2,str3,result,str,sign;
private Double a,b;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
screen = (TextView)findViewById(R.id.textview);
str = "";
}
public void onClick(View v){
Button button = (Button) v;
str += button.getText().toString();
screen.setText(str);
a = Double.parseDouble(str);
}
public void onClickSigns(View v){
Button button = (Button) v;
sign = ((Button) v).getText().toString();
screen.setText(sign);
str="";
}
public void calculate(View v){
Button button = (Button) v;
str2 = screen.getText().toString();
b = Double.parseDouble(str2);
if (sign .equals("+")){
result = a+b+"";
}
else if (sign .equals("-")){
result = a-b+"";
}
else if (sign .equals("X")){
result = a*b+"";
}
else if (sign .equals("÷")){
result = a/b+"";
}
else{
result = "Something went wrong";
}
screen.setText(result);
}
}
onClick should be public not private.
also initialize your strings to empty string. Like:
private String str1 = "",str2="",str3="",result="",str="",sign="";
Hope this fixes your issue.
Way 1:
in your main_activity xml file add android:onclick="onClick" and make onClick(View view) method public.
for example
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Calculate"
android:onClick="onClick"/>
And in main_activity.java file
public void onClick(View view){
}
Hope it help you :) Happy coding..

Android: passing information from an array to a textview

I have set myself up an array with questions and answers as follows:
static String[][] question= new String[20][5];
{
question[0][0] = "what is my name?";
question[0][1] = "Mark";
question[0][2] = "Steven";
question[0][3] = "Alan";
question[0][4] = "Bob";
question[1][0] = "what is my age?";
question[1][1] = "30";
question[1][2] = "31";
question[1][3] = "32";
question[1][4] = "33";
}
first square brackets indicates the question number and the second number gives the answer number, all correct answers are in 4th answer.my intention is to build a general app of questions that randomize and to pass to the next screen. I have used this code to generate a random number for the question number. so for e.g. 1st attempt Q5 will come up, attempt 2 Q3 could come up, attempt 3 Q1 could come up etc.
This next block of code is used by the android:onClick="goToQuestions"
public void goToQuestions (View v)
{
Intent intent = new Intent (this, Questions.class);
startActivity(intent);
}
using the above code will successfully move from current activity to questions activity. If i use this code below:
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_questions);
final TextView textView1 = (TextView) findViewById(R.id.textView1);
final Button button2 = (Button) findViewById(R.id.button2);
button2.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
int randomArray = (int) (Math.random() *4);
textView1.setText(question[randomArray][0]);
}
});
}
it will allow me to generate a random number from the array of questions and print it to my text view when it is in the same activity. I have tried this code below to try to pass the information to the questions screen from the home screen:
public void goToQuestions (View v1)
{
final TextView textView1 = (TextView) findViewById(R.id.textView1);
int randomArray = (int) (Math.random() * 4);
textView1.setText(Questions.question[randomArray][0]);
Intent intent = new Intent (this, QuizActivity.class);
startActivity(intent);
}
I have assumed calling android:onClick eliminated the need for an onclick listener. Can anyone provide assistance for how I could finish this correctly. With that last piece of code the app just crashes as I hit the button.
Your data model is not ideal. Create a class that represents a question, and is Parcelable, so you can pass that to your next activity. Something like this
public class Question implements Parcelable {
private final String mQuestion;
private final List<String> mAnswers;
private final int mCorrectAnswer;
public Question(final String question, final List<String> answers, int correctAnswer) {
mQuestion = question;
mAnswers = answers;
mCorrectAnswer = correctAnswer;
}
// implement parcelable interface below
}
Then you would receive this on your next activity, deserialize it and show the data as you see fit.
Consider also using fragments instead of activities.
Found my issue, firstly thank you all for your assistance. Secondly I was able to do this task using the code I was using, I was just putting it into the wrong class files. I was able to move this code:
final TextView textView1 = (TextView) findViewById(R.id.textView1);
int randomArray = (int) (Math.random() * 4);
textView1.setText(Questions.question[randomArray][0]);
into my onCreate method and it worked fine.

Cannot pass an Integer in an Intent [duplicate]

This question already has an answer here:
How to receive an int through an Intent
(1 answer)
Closed 4 years ago.
I'm trying to pass an Integer (from an edittext) to another activity through an intent.
When the user clicks a button, the text in the edittext will transform into a string and then into an int, then the int will be sent through an intent to another activity, but i have to use the int after that.
Here the activity sending the intent:
public class HomeActivityPro extends ActionBarActivity {
private InterstitialAd interstitial;
EditText conttext = (EditText) findViewById ( R.id.texthome );
Button buttone = (Button) findViewById(R.id.buttone);
String maxom = conttext.getText().toString();
int maxam = Integer.parseInt(maxom);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layout_home);
View.OnClickListener maxim = new View.OnClickListener() {
#Override
public void onClick (View view) {
Intent wall = new Intent(HomeActivityPro.this, GuessOne.class);
wall.putExtra("maxPressed", maxam);
startActivity(wall);
}
};
buttone.setOnClickListener(maxim);
Here the activity receiving it:
public class GuessOne extends ActionBarActivity {
int randone;
int contone;
int wall = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layout_guess_one);
wall = getIntent().getIntExtra("maxPressed", -1);
randone = (int) (Math.random()*10+1);
contone = 0;
}
Here i'm using it:
public void guessone (View view){
contone++;
textcontone.setText(getString(R.string.attempts) + "" + contone);
if (contone >= wall ){
resultaone.setText("You Failed" + " " + wall);
Toast.makeText(this, "You Failed", Toast.LENGTH_LONG).show();
}
When i use the app, the value of the int is always -1. Where i am wrong.
You can't use findViewById without setting the xml to the activity. That means you need to use findViewById method only after you have called setContentView.
Also you need to read the EditText text value once you click on the button otherwise it always will be null/empty.
Do this
public class HomeActivityPro extends ActionBarActivity {
private InterstitialAd interstitial;
EditText conttext;
Button buttone;
String maxom;
int maxam = -1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layout_home);
conttext = (EditText) findViewById ( R.id.texthome );
buttone = (Button) findViewById(R.id.buttone);
View.OnClickListener maxim = new View.OnClickListener() {
#Override
public void onClick (View view) {
maxom = conttext.getText().toString();
maxam = Integer.parseInt(maxom);
Intent wall = new Intent(HomeActivityPro.this, GuessOne.class);
wall.putExtra("maxPressed", maxam);
startActivity(wall);
}
};
buttone.setOnClickListener(maxim);
Problem 1
Put this in the on click listener instead:
String maxom = conttext.getText().toString();
int maxam = Integer.parseInt(maxom);
You want the values to be read at the time you click the button not when you open the activity, correct?
Problem 2
The following needs to be after setContentView in onCreate:
conttext = (EditText) findViewById ( R.id.texthome );
buttone = (Button) findViewById(R.id.buttone);
Keep the declarations where they are. Just the declarations:
EditText conttext;
Button buttone;
Note
Follow the same pattern in all your activities. Declare views as field variables, assign them in onCreate after setContentLayout. Get the values at the time they're needed.
public int getIntExtra (String name, int defaultValue)
Added in API level 1 Retrieve extended data from the intent.
Parameters name The name of the desired item. defaultValue the value
to be returned if no value of the desired type is stored with the
given name. Returns the value of an item that previously added with
putExtra() or the default value if none was found. See Also
putExtra(String, int)
This means that no int was found when you called getIntExtra(valueName, defaultValue); so the default value was chosen.
You should check to see what your maxam value is before you call the new activity.
In the activity you receive it:
wall = getIntent().getIntExtra("maxPressed");
SOLVED: by getInt and String.valueOf
private static final String IMGID = "ImgID";
if (getIntent().getExtras().containsKey(IMGID)) {
//Picasso.with(this).load(getIntent().getExtras().getString(IMG)).into(mImg);
Picasso.with(this).load(getIntent().getExtras().getInt(String.valueOf(IMGID))).into(mImg);
}

Sending Data From One Activity to Another Without Creating a new Intent Android

i have an impending question that is mind buggling me at the moment in regards to android app development.
In my app, which works exactly the way i want it to, except for one part i have problem figuring out is how will i send a piece of data from one activity to another without making a new Intent.
In my Code, the user inputs his Name, Mass, and Height, and when the user clicks on Button calculate, it takes all the values in a new intent to a second activity, there, it calculates the BMI of the user. Now, i want to send this freshly calculated BMI back to the First activity without creating a new intent but i am now sure on how to go about that
Here are the relevant part of my Code
Main Activity.java
package mobileapp.melvin.bmicalculator;
import android.app.Activity;
import android.app.AlertDialog;
import android.os.Bundle;
import android.view.*;
import android.content.*;
import android.widget.*;
public class MainActivity extends Activity {
public String name,mass,height,bmi;
public EditText nameField, massField, heightField;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
bmi = getIntent().getStringExtra("BMI");
//Create "TextFields" By getting ID of Editviews from Main XML
nameField = (EditText) findViewById(R.id.mText_box1);
massField = (EditText) findViewById(R.id.mText_box2);
heightField = (EditText) findViewById(R.id.mText_box3);
//Button To calculate and display BMI as TextViews
Button launchBtn = (Button) findViewById(R.id.mButton_calculate);
launchBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Check is The "Textfields" have values
if(!verifyData()){
return;
}
/*Create a new Intent to Launch another activity
* To display all the Values gotten from
* The TextFields as Normal Text Values
*/
Intent launcher = new Intent(v.getContext(),BMI1.class);
//This intent then passes these values over to the next Intent
launcher.putExtra("Name", name);
launcher.putExtra("Mass", mass);
launcher.putExtra("Height", height);
//We then start this new activity with the new Intent
startActivity(launcher);
}
});
}
and BMI1.java
package mobileapp.melvin.bmicalculator;
import android.app.*;
import android.content.*;
import android.os.*;
import android.view.*;
import android.widget.*;
public class BMI1 extends Activity {
String name,mass,height,bmi;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_bmi1);
//Get data from the first activity through intent
name = getIntent().getStringExtra("Name");
mass = getIntent().getStringExtra("Mass");
height = getIntent().getStringExtra("Height");
//convert mass and height to double and calculate BMI
double m = Double.parseDouble(mass);
double h = Double.parseDouble(height);
bmi = Double.toString(calculateBMI(m, h));
((TextView) findViewById(R.id.b1_Label2)).setText(name);
((TextView) findViewById(R.id.b1_Label4)).setText(mass);
((TextView) findViewById(R.id.b1_Label6)).setText(height);
((TextView) findViewById(R.id.b1_Label8)).setText(bmi);
Button backBtn = (Button) findViewById(R.id.b1Button_back);
backBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent launcher = getIntent();
launcher.putExtra("BMI", bmi);
finish();
}
});
}
private double calculateBMI(double toMass, double toHeight){
double value;
value = toMass/(toHeight * toHeight);
return value;
}
}
I know there is no value passed because when a user clicks Display in the first Activity, it takes the values to a third Activity where a textView Should display For example "BMI: 20.66" but instead i get "BMI: null", how will i fix this error?
You don't have to always use Intent to send data between activities. You use other android storage options like Sqlite db, SharedPreferences. You can also store data on SDcard. Have a look at Android storage options
here
To solve the above problem properly, android provides startActivityForResult that basically launch an activity for which you would like a result when it finished.
For example, here's how to start an activity that allows the user to pick a contact:
static final int PICK_CONTACT_REQUEST = 1; // The request code
...
private void pickContact() {
Intent pickContactIntent = new Intent(Intent.ACTION_PICK, Uri.parse("content://contacts"));
pickContactIntent.setType(Phone.CONTENT_TYPE); // Show user only contacts w/ phone numbers
startActivityForResult(pickContactIntent, PICK_CONTACT_REQUEST);
}
Receive the Result
When the user is done with the subsequent activity and returns, the system calls your activity's onActivityResult() method. This method includes three arguments:
The request code you passed to startActivityForResult().
A result code specified by the second activity. This is either RESULT_OK if the operation was successful or RESULT_CANCELED if the user backed out or the operation failed for some reason.
An Intent that carries the result data.
For example, here's how you can handle the result for the "pick a contact" intent:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// Check which request we're responding to
if (requestCode == PICK_CONTACT_REQUEST) {
// Make sure the request was successful
if (resultCode == RESULT_OK) {
// The user picked a contact.
// The Intent's data Uri identifies which contact was selected.
// Do something with the contact here (bigger example below)
}
}
}
You can see the complete example of startActivityForResult in this article here.
For send data between Activity without using Intent you can use SharedPreferences or SQlite db.
Example for SharedPreferences:
// Create object of SharedPreferences.
SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(this);
//now get Editor
SharedPreferences.Editor editor = sharedPref.edit();
//put your value
editor.putString("userName", "stackoverlow");
//commits your edits
editor.commit();
Using putString(),putBoolean(),putInt(),putFloat(),putLong() you can save your desired dtatype.
and to fetch data:
SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(this);
String userName = sharedPref.getString("userName", "Not Available");

Logic Error; TextView returns even after setting to null

I have a logic error in a simple android app;
I have 3 Buttons (Permute, Clear and GC), 1 EditText and a TextView. When the Permute button is clicked it sends the text in the EditText box to a method from another class and sets the returned value to the TextView. The returned value is just gibberish text.
When I click the Clear, it clears the current contents of the EditText box and the TextView; (by setting the contents to a null string "").
However when I click Permute with new values in the textBox, the old (cleared) text returns along with the newer text below
Here's the code:
package com.mobinga.string;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.os.Vibrator;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import com.mob.string.Perm;
public class MoPermActivity extends Activity implements View.OnClickListener {
Button btn;
Button btn2;
Button btn3;
EditText et;
TextView tv;
Vibrator vi;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
btn = (Button) findViewById(R.id.Permute);
btn2 = (Button) findViewById(R.id.Clear);
btn3 = (Button) findViewById(R.id.GC);
btn.setOnClickListener(this);
btn2.setOnClickListener(this);
btn3.setOnClickListener(this);
et = (EditText) findViewById(R.id.Text);
tv = (TextView) findViewById(R.id.textView1);
}
public void onClick(View view){
switch(view.getId()){
case R.id.Permute:
vi = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
vi.vibrate(50);
tv.setText(Perm.perm(et.getText().toString()));
break;
case R.id.Clear:
vi = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
et.setText("");
tv.setText("");
vi.vibrate(50);
break;
case R.id.GC:
vi = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
GC();
vi.vibrate(50);
}
}
public static void GC(){
Log.d("Permute","Calling GC");
System.gc();
}
}
How do I properly and completely clear the contents of TextView, and stop it from returning? Simply put : My problem is that the supposedly cleared contents of the TextView return back even after clearing.
Edit if necessary here's the Perm Class
package com.mob.string;
public class Perm {
static String v = "";
static void permute(int level, String permuted, boolean used[], String original) {
int length = original.length();
if (level == length) {
v +=permuted+"\n";
} else {
for (int i = 0; i < length; i++) {
if (!used[i]) {
used[i] = true;
permute(level + 1, permuted + original.charAt(i), used, original);
used[i] = false;
}
}
}
}
public String perm(String s){
boolean used[] = {false, false, false, false, false,false,false};
permute(0, "", used, s);
return v;
}
}
v is never reset.
public String perm(String s){
v = "";
boolean used[] = {false, false, false, false, false,false,false};
permute(0, "", used, s);
return v;
}
However I don't see why v even exists to be honest. I would of passed it through the recursive calls.
I dont know what the calss Perm is you are using but why not just try
tv.setText(et.getText().toString());
EDIT:
You should try setting it t a String variable first.
String editText = et.getText.toString();
then pass it to your TextView
tv.setText(editText);
I think that the problem lies in your Perm class - here you've got a static String, which isn't cleared anywhere (just appended). If you hold state in your class, make this "v" string a normal field and instantiate your class when needed.
Store the state of the string in the Activity, pass it into the Perm class when you want to append values to it, and then clear the stored string at the same time you clear your TextView.
Or make a method in the Perm class called clearString which sets v = "", and call it when you clear the TextView.
You have to clear the text in TextViews by setting text "" and clearing v value in Perm class. That should do the trick.

Categories