Not able to access global variables across activity - java

In this code, I want the strings sh1, shg2 and shg3 to be displayed according to the users input in text edit. I have created a saver class to set and retrieve the variables. But although they are global variables, shg1 ,sh2 and sh3 do not store the values and don't display anything. Thanks for your help
Saver class:
public class Saver extends Application {
public String shg1,shg2,shg3;
public String getShg1() {
return shg1;
}
public void setShg1(String s1) {
shg1= s1;
}
public String getShg2() {
return shg2;
}
public void setShg2(String s1) {
shg2= s1;
}
public String getShg3() {
return shg3;
}
public void setShg3(String s1) {
shg3= s1;
}
}
SHGDetails class:
public class SHGDetails extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_shgdetails);
final EditText e1 = (EditText) findViewById(R.id.shg1);
final EditText e2 = (EditText) findViewById(R.id.shg2);
final EditText e3 = (EditText) findViewById(R.id.shg3);
final Button b1 = (Button) findViewById(R.id.b3);
final LinearLayout l = findViewById(R.id.linearl);
final TextView t1 = findViewById(R.id.textView2);
final TextView t2 = findViewById(R.id.textView3);
final TextView t3 = findViewById(R.id.textView4);
b1.setVisibility(View.INVISIBLE);
e1.setVisibility(View.INVISIBLE);
e2.setVisibility(View.INVISIBLE);
e3.setVisibility(View.INVISIBLE);
Boolean isFirstRun = getSharedPreferences("PREFERENCE", MODE_PRIVATE)
.getBoolean("isFirstRun", true);
Saver s = new Saver();
if (isFirstRun) {
//show start activity
b1.setVisibility(View.VISIBLE);
e1.setVisibility(View.VISIBLE);
e2.setVisibility(View.VISIBLE);
e3.setVisibility(View.VISIBLE);
String text = e1.getText().toString();
String text2 = e2.getText().toString();
String text3 = e3.getText().toString();
((Saver) this.getApplication()).setShg1(text);
((Saver) this.getApplication()).setShg2(text2);
((Saver) this.getApplication()).setShg3(text3);
b1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
l.removeView(e1);
l.removeView(e2);
l.removeView(e3);
l.removeView(b1);
getSharedPreferences("PREFERENCE", MODE_PRIVATE).edit()
.putBoolean("isFirstRun", false).commit();
}
});
}
else {
Toast.makeText(getApplicationContext(), s.getShg1(),Toast.LENGTH_LONG).show();
t1.setText(((Saver) this.getApplication()).getShg1());
t2.setText(((Saver) this.getApplication()).getShg2());
t3.setText(((Saver) this.getApplication()).getShg3());
}
}
}

You need to fetch data and set when user press the button so there's no values before button click so do this
b1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//
String text = e1.getText().toString();
String text2 = e2.getText().toString();
String text3 = e3.getText().toString();
((Saver) SHGDetails.this.getApplication()).setShg1(text);
((Saver) SHGDetails.this.getApplication()).setShg2(text2);
((Saver) SHGDetails.this.getApplication()).setShg3(text3);
l.removeView(e1);
l.removeView(e2);
l.removeView(e3);
l.removeView(b1);
getSharedPreferences("PREFERENCE", MODE_PRIVATE).edit()
.putBoolean("isFirstRun", false).commit();
}
});
and seems like you already have registered your application in manifest.

Related

How can i set textview text to names that the user input every time i hit a button?

I'm making a truth or dare app and i need a code that show the user input one by one every time i hit a button
I try somethink i watch in youtube.
So here's the activity that the user input names for the players playing.
public class NameInput1Activity extends AppCompatActivity {
Button SBtn;
Button RTMBtn;
EditText PN1;
EditText PN2;
EditText PN3;
EditText PN4;
EditText PN5;
EditText PN6;
EditText PN7;
EditText PN8;
EditText PN9;
EditText PN10;
String PI1;
String PI2;
String PI3;
String PI4;
String PI5;
String PI6;
String PI7;
String PI8;
String PI9;
String PI10;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_name_input1);
SBtn = findViewById(R.id.SBtn);
RTMBtn = findViewById(R.id.RTMBtn);
PN1 = findViewById(R.id.player1NameInput);
PN2 = findViewById(R.id.player2NameInput);
PN3 = findViewById(R.id.player3NameInput);
PN4 = findViewById(R.id.player4NameInput);
PN5 = findViewById(R.id.player5NameInput);
PN6 = findViewById(R.id.player6NameInput);
PN7 = findViewById(R.id.player7NameInput);
PN8 = findViewById(R.id.player8NameInput);
PN9 = findViewById(R.id.player9NameInput);
PN10 = findViewById(R.id.player10NameInput);
SBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent PlayConf = new Intent(NameInput1Activity.this,PlayConf.class);
PI1 = PN1.getText().toString();
PI2 = PN2.getText().toString();
PI3 = PN3.getText().toString();
PI4 = PN4.getText().toString();
PI5 = PN5.getText().toString();
PI6 = PN6.getText().toString();
PI7 = PN7.getText().toString();
PI8 = PN8.getText().toString();
PI9 = PN9.getText().toString();
PI10 = PN10.getText().toString();
PlayConf.putExtra("Player1",PI1);
PlayConf.putExtra("Player2",PI2);
PlayConf.putExtra("Player3",PI3);
PlayConf.putExtra("Player4",PI4);
PlayConf.putExtra("Player5",PI5);
PlayConf.putExtra("Player6",PI6);
PlayConf.putExtra("Player7",PI7);
PlayConf.putExtra("Player8",PI8);
PlayConf.putExtra("Player9",PI9);
PlayConf.putExtra("Player10",PI10);
startActivity(PlayConf);
}
});
RTMBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent RTMBtn = new Intent(NameInput1Activity.this, MainActivity.class);
PN1.setText("");
PN1.setHint("Enter a name");
PN2.setText("");
PN2.setHint("Enter a name");
PN3.setText("");
PN3.setHint("Enter a name");
PN4.setText("");
PN4.setHint("Enter a name");
PN5.setText("");
PN5.setHint("Enter a hint");
PN6.setText("");
PN6.setHint("Enter a hint");
PN7.setText("");
PN7.setHint("Enter a hint");
PN8.setText("");
PN8.setHint("Enter a hint");
PN9.setText("");
PN9.setHint("Enter a hint");
PN10.setText("");
PN10.setHint("Enter a hint");
startActivity(RTMBtn);
}
});
}
}
So i have some 'edittext' that the player input the names and a 'OnClickListener' that passe's the input to 'PlayConf' Activity.
That's the 'PlayConf' Activity:
public class PlayConf extends AppCompatActivity {
Button AddMoreBtn;
Button MoveToToD;
Button RTMBtn;
String PI1;
String PI2;
String PI3;
String PI4;
String PI5;
String PI6;
String PI7;
String PI8;
String PI9;
String PI10;
TextView PTV1;
TextView PTV2;
TextView PTV3;
TextView PTV4;
TextView PTV5;
TextView PTV6;
TextView PTV7;
TextView PTV8;
TextView PTV9;
TextView PTV10;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(com.example.myapplication.R.layout.activity_play_conf);
AddMoreBtn = findViewById(R.id.AddMoreBtn);
MoveToToD = findViewById(R.id.MoveToToD);
RTMBtn =findViewById(R.id.RTMBtn);
PTV1 = findViewById(R.id.Player1NameConf);
PTV2 = findViewById(R.id.Player2NameConf);
PTV3 = findViewById(R.id.Player3NameConf);
PTV4 = findViewById(R.id.Player4NameConf);
PTV5 = findViewById(R.id.Player5NameConf);
PTV6 = findViewById(R.id.Player6NameConf);
PTV7 = findViewById(R.id.Player7NameConf);
PTV8 = findViewById(R.id.Player8NameConf);
PTV9 = findViewById(R.id.Player9NameConf);
PTV10 = findViewById(R.id.Player10NameConf);
PI1 = getIntent().getExtras().getString("Player1");
PI2 = getIntent().getExtras().getString("Player2");
PI3 = getIntent().getExtras().getString("Player3");
PI4 = getIntent().getExtras().getString("Player4");
PI5 = getIntent().getExtras().getString("Player5");
PI6 = getIntent().getExtras().getString("Player6");
PI7 = getIntent().getExtras().getString("Player7");
PI8 = getIntent().getExtras().getString("Player8");
PI9 = getIntent().getExtras().getString("Player9");
PI10 = getIntent().getExtras().getString("Player10");
PTV1.setText(PI1);
PTV2.setText(PI2);
PTV3.setText(PI3);
PTV4.setText(PI4);
PTV5.setText(PI5);
PTV6.setText(PI6);
PTV7.setText(PI7);
PTV8.setText(PI8);
PTV9.setText(PI9);
PTV10.setText(PI10);
AddMoreBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent AddMore = new Intent(PlayConf.this,
NameInput1Activity.class);
startActivity(AddMore);
}
});
RTMBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent RTMBtn = new Intent(PlayConf.this, MainActivity.class);
PTV1.setText("");
PTV2.setText("");
PTV3.setText("");
PTV4.setText("");
PTV5.setText("");
PTV6.setText("");
PTV7.setText("");
PTV8.setText("");
PTV9.setText("");
PTV10.setText("");
startActivity(RTMBtn);
}
});
MoveToToD.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent MoveToToD = new Intent(PlayConf.this, TruthOrDare.class);
MoveToToD.putExtra("Player1",PI1);
MoveToToD.putExtra("Player1",PI2);
MoveToToD.putExtra("Player1",PI3);
MoveToToD.putExtra("Player1",PI4);
MoveToToD.putExtra("Player1",PI5);
MoveToToD.putExtra("Player1",PI6);
MoveToToD.putExtra("Player1",PI7);
MoveToToD.putExtra("Player1",PI8);
MoveToToD.putExtra("Player1",PI9);
MoveToToD.putExtra("Player1",PI10);
startActivity(MoveToToD);
}
});
}
}
That's the 'PlayConf' Activity, it shows the input so the user see all the input's he enter.So i get the input from the previous Activity 'NameInput1Activity' and make another String from the input 'PI1'.Then i pass the input to the 'TruthOrDare' Activity with the Button 'MoveToToD'.
So that's where i have the problem the 'Truth or Dare' Activity:
public class TruthOrDare extends AppCompatActivity {
String PI1;
String PI2;
String PI3;
String PI4;
String PI5;
String PI6;
String PI7;
String PI8;
String PI9;
String PI10;
TextView PlayerView;
Integer TurnCount = 1;
Button RTMBtn;
Button Darebtn;
Button Truthbtn;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_truth_or_dare);
PI1 = getIntent().getExtras().getString("Player1");
PI2 = getIntent().getExtras().getString("Player2");
PI3 = getIntent().getExtras().getString("Player3");
PI4 = getIntent().getExtras().getString("Player4");
PI5 = getIntent().getExtras().getString("Player5");
PI6 = getIntent().getExtras().getString("Player6");
PI7 = getIntent().getExtras().getString("Player7");
PI8 = getIntent().getExtras().getString("Player8");
PI9 = getIntent().getExtras().getString("Player9");
PI10 = getIntent().getExtras().getString("Player10");
PlayerView = findViewById(R.id.PlayerNameTextView);
RTMBtn = findViewById(R.id.RTMBtn);
RTMBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent RTMBtn = new Intent(TruthOrDare.this, MainActivity.class);
startActivity(RTMBtn);
}
});
Truthbtn = findViewById(R.id.TruthBtn);
Darebtn = findViewById(R.id.Darebtn);
Truthbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent Truth = new Intent(TruthOrDare.this, TruthActivity.class);
TurnCount++;
startActivity(Truth);
}
});
Darebtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
TurnCount++;
}
});
}
public void ResetCount(View view) {
TurnCount = 1;
}
public void TurnCountIfElse(View view) {
if (TurnCount == 1) {
PlayerView.setText(PI1);
} else if (TurnCount == 2) {
PlayerView.setText(PI2);
} else if (TurnCount == 3) {
PlayerView.setText(PI3);
} else if (TurnCount == 4) {
PlayerView.setText(PI4);
} else if (TurnCount == 5) {
PlayerView.setText(PI5);
} else if (TurnCount == 6) {
PlayerView.setText(PI6);
} else if (TurnCount == 7) {
PlayerView.setText(PI7);
} else if (TurnCount == 8) {
PlayerView.setText(PI8);
} else if (TurnCount == 9) {
PlayerView.setText(PI9);
} else if (TurnCount == 10) {
PlayerView.setText(PI10);
}
else {
TurnCount = 1;
}
}
}
So what i do here is i make an 'onclicklistener' for the 'Truthbtn'
that add 1 to 'TurnCount' so the when i click the 'TurnCount' Value equals 2
so is set the textview to 'PI2' but instead of that it goes to the last 'else if' and set textview text to 'PI10'
IF YOU NEED ANY OTHER INFO LIKE XML'S JUST SAY IT PLS.
Dear Friend You made minor mistake during implementation. You send Same key value During intent on MoveToToD Button Click.
You use Same key Value Player1 for all player list value.That's the actual problem.So kindly Change Your MoveToToD click method and Write Below Code.
MoveToToD.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent MoveToToD = new Intent(PlayConf.this, TruthOrDare.class);
MoveToToD.putExtra("Player1",PI1);
MoveToToD.putExtra("Player2",PI2);
MoveToToD.putExtra("Player3",PI3);
MoveToToD.putExtra("Player4",PI4);
MoveToToD.putExtra("Player5",PI5);
MoveToToD.putExtra("Player6",PI6);
MoveToToD.putExtra("Player7",PI7);
MoveToToD.putExtra("Player8",PI8);
MoveToToD.putExtra("Player9",PI9);
MoveToToD.putExtra("Player10",PI10);
startActivity(MoveToToD);
}
});

Spinner string not retrieved and passed to volleyrequest

I am wanting to get the string value from the spinner. I am currently using Volley in passing data but then it wasn't successful then. This is my RegisterActivity class:
public class RegUserPassClient extends AppCompatActivity implements AdapterView.OnItemSelectedListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_reg_user_pass_client);
final Spinner spinner = findViewById(R.id.genderSpinner);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this, R.array.genderString, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
spinner.setOnItemSelectedListener(this);
final EditText regUserClient= (EditText) findViewById(R.id.regUserClient);
final EditText regPassClient= (EditText) findViewById(R.id.regPassClient);
final EditText regClientName = (EditText) findViewById(R.id.registerClientName);
final EditText regClientNumber = (EditText) findViewById(R.id.registerClientNumber);
final EditText regClientAddress = (EditText) findViewById(R.id.registerClientAddress);
final EditText regClientOccupation = (EditText) findViewById(R.id.registerClientOccupation);
final EditText regClientGender = (EditText) findViewById(R.id.registerClientGender);
final EditText regClientBirthDate = (EditText) findViewById(R.id.registerClientBirthDate);
final TextView clientUser = (TextView) findViewById(R.id.clientUserType);
final Button regClientBtn = (Button) findViewById(R.id.regClient);
final CheckBox toggle = (CheckBox) findViewById(R.id.checkBoxLog);
toggle.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
if(b){
regPassClient.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
}else{
regPassClient.setTransformationMethod(PasswordTransformationMethod.getInstance());
}
}
});
regClientBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final String username = regUserClient.getText().toString();
final String password = regPassClient.getText().toString();
final String name = regClientName.getText().toString();
final String number = regClientNumber.getText().toString();
final String gender = spinner.toString();
final String address = regClientAddress.getText().toString();
final String occupation = regClientOccupation.getText().toString();
final String birthDate = regClientBirthDate.getText().toString();
final String userType = clientUser.getText().toString();
if(!username.isEmpty() && !password.isEmpty() &&
!name.isEmpty() && !address.isEmpty() &&
!occupation.isEmpty() && !gender.isEmpty() &&
!birthDate.isEmpty() && !number.isEmpty()) {
Response.Listener<String> responseListener = new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonResponse = new JSONObject(response);
boolean success = jsonResponse.getBoolean("success");
if (success) {
Intent intent = new Intent(RegUserPassClient.this, LoginRegister.class);
RegUserPassClient.this.startActivity(intent);
Toast.makeText(RegUserPassClient.this,"SuccessFully Registered! Log in your details now!",Toast.LENGTH_LONG).show();
} else {
AlertDialog.Builder builder = new AlertDialog.Builder(RegUserPassClient.this);
builder.setMessage("Username Has already been taken!")
.setNegativeButton("Retry", null)
.create()
.show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
};
RegUserPassClientRequest registerRequest = new RegUserPassClientRequest(username, password, name, number, gender, address, occupation, birthDate, userType, responseListener);
RequestQueue queue = Volley.newRequestQueue(RegUserPassClient.this);
queue.add(registerRequest);
}else if(username.isEmpty()){
regUserClient.setError("Please insert a username");
}else if(password.isEmpty()){
regPassClient.setError("Please put your password");
}else if(name.isEmpty()){
regClientName.setError("Please input your name");
}else if(number.isEmpty()){
regClientNumber.setError("Put your phone number please");
}else if(address.isEmpty()){
regClientGender.setError("Please state your gender");
}else if(occupation.isEmpty()){
regClientAddress.setError("Please put your address");
}else if(gender.isEmpty()){
regClientOccupation.setError("Please state occupation");
}else if(birthDate.isEmpty()){
regClientBirthDate.setError("Please select your Birth Date");
}
}
});
}
#Override
public void onItemSelected(AdapterView<?> parent, View view, int i, long l) {
final String text = parent.getItemAtPosition(i).toString();
Toast.makeText(parent.getContext(), text, Toast.LENGTH_SHORT).show();
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
}
My functions for getting the spinner value are under the volleyrequest. I guess that is where my code is wrong but I don't really know what to put and where is the wrong thing.
It was just
final String gender = spinner.getSelectedItem().toString();
after all! Thanks anyways for viewing guys!

Sending radio button values in Android

Here is my AddLift.java:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_lift);
final EditText Origin = (EditText)findViewById(R.id.addOrigin);
final EditText Destination =
(EditText)findViewById(R.id.addDestination);
final EditText Time = (EditText)findViewById(R.id.setTime);
final EditText Seats = (EditText)findViewById(R.id.numOfSeats);
final RadioGroup DriverLifter = (RadioGroup)findViewById(driverLifter);
final RadioButton selectedButton =
(RadioButton)findViewById(selectedButton);
Button submit = (Button)findViewById(R.id.submitButton);
submit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String addOrigin = Origin.getText().toString();
String addDestination = Destination.getText().toString();
String setTime = Time.getText().toString();
String numOfSeats = Seats.getText().toString();
int selectedId = DriverLifter.getCheckedRadioButtonId();
selectedButton = (RadioButton)findViewById(selectedId);
Intent intent = new Intent(AddLift.this, ViewLiftBoard.class);
intent.putExtra("ORIGIN", addOrigin);
intent.putExtra("DESTINATION", addDestination);
intent.putExtra("TIME", setTime);
intent.putExtra("SEATS", numOfSeats);
intent.putExtra("RADIO", driverLifter);
startActivity(intent);
}
});
And here is my ViewLiftBoard.java:
public class ViewLiftBoard extends AppCompatActivity {
String Origin;
String Destination;
String Time;
String Seats;
int DriverLifter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view_lift_board);
Origin = getIntent().getExtras().getString("ORIGIN");
Destination = getIntent().getExtras().getString("DESTINATION");
Time = getIntent().getExtras().getString("TIME");
Seats = getIntent().getExtras().getString("SEATS");
DriverLifter = getIntent().getExtras().getInt("RADIO");
TextView textView = (TextView)findViewById(R.id.textView);
textView.setText("Origin:"+ "
"+Origin+'\n'+"Destination:"+""+Destination+'\n'+"Time:"+"
"+Time+'\n'+"Number of Seats:"+" "+Seats+'\n'+"Type:"+" "+DriverLifter);
}
}
But when I run the app the "Type" comes up as a number rather than the value of the selected radio button? Any help would be great
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_lift);
final EditText Origin = (EditText)findViewById(R.id.addOrigin);
final EditText Destination =
(EditText)findViewById(R.id.addDestination);
final EditText Time = (EditText)findViewById(R.id.setTime);
final EditText Seats = (EditText)findViewById(R.id.numOfSeats);
final RadioGroup DriverLifter = (RadioGroup)findViewById(driverLifter);
final RadioButton selectedButton =
(RadioButton)findViewById(selectedButton);
Button submit = (Button)findViewById(R.id.submitButton);
submit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String addOrigin = Origin.getText().toString();
String addDestination = Destination.getText().toString();
String setTime = Time.getText().toString();
String numOfSeats = Seats.getText().toString();
int selectedId = DriverLifter.getCheckedRadioButtonId();
selectedButton = (RadioButton)findViewById(selectedId);
String selectedradio=selectedButton.gettex();
Intent intent = new Intent(AddLift.this, ViewLiftBoard.class);
intent.putExtra("ORIGIN", addOrigin);
intent.putExtra("DESTINATION", addDestination);
intent.putExtra("TIME", setTime);
intent.putExtra("SEATS", numOfSeats);
intent.putExtra("RADIO", selectedradio);
startActivity(intent);
}
});
ViewLiftBoard.java:
public class ViewLiftBoard extends AppCompatActivity {
String Origin;
String Destination;
String Time;
String Seats;
String DriverLifter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view_lift_board);
Origin = getIntent().getExtras().getString("ORIGIN");
Destination = getIntent().getExtras().getString("DESTINATION");
Time = getIntent().getExtras().getString("TIME");
Seats = getIntent().getExtras().getString("SEATS");
DriverLifter = getIntent().getExtras().getString("RADIO");
TextView textView = (TextView)findViewById(R.id.textView);
textView.setText("Origin:"+ "
"+Origin+'\n'+"Destination:"+""+Destination+'\n'+"Time:"+"
"+Time+'\n'+"Number of Seats:"+" "+Seats+'\n'+"Type:"+" "+DriverLifter);
}
}
If you want to get text from selected radio button, you can use next combination:
RadioGroup driverLifter = (RadioGroup)findViewById(R.id.driverLifter);
String selectedButtonText = ((RadioButton)findViewById(driverLifter.getCheckedRadioButtonId())).getText().toString();
By the way, according to Java naming conventions, your variables should start from lower case.
That's because you are retrieving an Integer DataType from the intent extra
DriverLifter= getIntent().getExtras().getInt("RADIO");
To solve your problem you have to put this extra as a string in the intent, so instead of doing this :
intent.putExtra("RADIO", driverLifter);
Do this :
intent.putExtra("RADIO", (RadioButton) findValueById(DriverLifter .getCheckedRadioButton()). getText(). toString()) ;
And extract the Extra like this :
DriverLifter= getIntent().getExtras().getString("RADIO");

My app crashes when entering value to edit text as well as it doesn't display the correct value

I am new to Android Studio. I have gone through the official developer.android.com training and I decided to create a new and simple app called Grocery+ in which user will enter the price and quantity of particular item and app will display total sum.
I have done all UI based work then today I switched to programming. I am an experienced programmer of Java. I have also done all the work in it but:
1- my app crashes when I try to enter the first .
Then I have to enter any other value first then first value.
2- even after above hack my app doesn't display anything on 'grand total
Plese help :(((
package com.amostrone.akash.grocery;
import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.EditText; import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
static int Quantity[] = new int[4];
static float Price[] = new float[4];
public static double total=0;
static TextView txtValue;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
txtValue = (TextView) findViewById(R.id.txtExample);
}
/////////// QUANTITY
public void input_Quantity(View view) {
EditText x = (EditText) findViewById(R.id.editQuantity);
calc();
}
public void input_Quantity2(View view) {
EditText x = (EditText) findViewById(R.id.editQuantity2);
Quantity[1] = Integer.parseInt(x.toString());
calc();
}
public void input_Quantity3(View view) {
EditText x = (EditText) findViewById(R.id.editQuantity3);
Quantity[2] = Integer.parseInt(x.toString());
calc();
}
public void input_Quantity4(View view) {
EditText x = (EditText) findViewById(R.id.editQuantity4);
Quantity[3] = Integer.parseInt(x.toString());
calc();
}
public void input_Quantity5(View view) {
EditText x = (EditText) findViewById(R.id.editQuantity5);
Quantity[4] = Integer.parseInt(x.toString());
calc();
}
/////////////// Quantity
////////////// Price
public void input_Price(View view) {
EditText x = (EditText) findViewById(R.id.editPrice);
Price[0] = Float.parseFloat(x.toString());
calc();
}
public void input_Price2(View view) {
EditText x = (EditText) findViewById(R.id.editPrice2);
Price[1] = Float.parseFloat(x.toString());
calc();
}
public void input_Price3(View view) {
EditText x = (EditText) findViewById(R.id.editPrice3);
Price[2] = Float.parseFloat(x.toString());
calc();
}
public void input_Price4(View view) {
EditText x = (EditText) findViewById(R.id.editPrice4);
Price[3] = Float.parseFloat(x.toString());
calc();
}
public void input_Price5(View view) {
EditText x = (EditText) findViewById(R.id.editPrice5);
calc();
}
///////////// Price
/////////////// Calculate
public static void calc()
{
for(int i=0;i<=4;i++)
total += (Quantity[i] * Price[i]);
String str = Double.toString(total);
txtValue.setText(str);
}
////////////// Calculate }
Looking at your code it appears your are triggering EditText value get and calculation on click event (via xml). This does not work this way as they are triggered immediately. One of the approaches to solve this problem is to go the TextWatcher route. Check the below code built around that, I also refactored it a bit (should be lesser prone to memory leaks now):
public double mTotal;
private TextView mTextView;
private EditText[] mQuantityEditTexts = new EditText[5];
private EditText[] mPriceEditTexts = new EditText[5];
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mTextView = (TextView) findViewById(R.id.txtExample);
mQuantityEditTexts[0] = (EditText) findViewById(R.id.editQuantity);
mQuantityEditTexts[1] = (EditText) findViewById(R.id.editQuantity2);
mQuantityEditTexts[2] = (EditText) findViewById(R.id.editQuantity3);
mQuantityEditTexts[3] = (EditText) findViewById(R.id.editQuantity4);
mQuantityEditTexts[4] = (EditText) findViewById(R.id.editQuantity5);
mPriceEditTexts[0] = (EditText) findViewById(R.id.editPrice);
mPriceEditTexts[1] = (EditText) findViewById(R.id.editPrice2);
mPriceEditTexts[2] = (EditText) findViewById(R.id.editPrice3);
mPriceEditTexts[3] = (EditText) findViewById(R.id.editPrice4);
mPriceEditTexts[4] = (EditText) findViewById(R.id.editPrice5);
for (int i = 0; i < 5; i++) {
mQuantityEditTexts[i].addTextChangedListener(mTextWatcher);
mPriceEditTexts[i].addTextChangedListener(mTextWatcher);
}
}
private TextWatcher mTextWatcher = new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
calc();
}
#Override
public void afterTextChanged(Editable s) {
}
};
public void calc()
{
try {
for (int i = 0; i <= 4; i++)
mTotal += Integer.parseInt(mQuantityEditTexts[i].getText().toString()) *
Double.parseDouble(mPriceEditTexts[i].getText().toString());
String str = Double.toString(mTotal);
mTextView.setText(str);
} catch (NumberFormatException e) {
Toast.makeText(this, "WTF! Enter valid numbers!", Toast.LENGTH_SHORT).show();
}
}
I have created custom edittext which does not hangs.
SearchTimerEditText

Difficulty saving and storing

I am trying to save and store data in an android app using java. At the moment the data will not save and it causes my app to crash. Can anyone make any suggestions to my code? Part of my page includes a total budget and I am difficulty storing and saving the total budget.
public class Summary extends Activity implements TextWatcher, View.OnClickListener
{
DecimalFormat df = new DecimalFormat("£0.00");
int noOfGifts, giftsPurchased;
double cost;
EditText budgetEntered;
double savedBudget = 0;
String budgetString;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.summary);
budgetEntered = (EditText) findViewById(R.id.s2TotalBudget);
budgetEntered.addTextChangedListener(this);
Button saveBudget = (Button) findViewById(R.id.s2ViewList);
saveBudget.setOnClickListener(saveButtonListener);
if(savedBudget != 0)
{
saveBudget.setText(budgetString);
}
Bundle passedInfo = getIntent().getExtras();
if (passedInfo != null)
{
cost = passedInfo.getDouble("cost");
noOfGifts = passedInfo.getInt("noOfGifts");
giftsPurchased = passedInfo.getInt("giftsPurchased");
}
Button logoutButton = (Button) findViewById(R.id.s2LogoutButton);
logoutButton.setOnClickListener(new View.OnClickListener()
{
public void onClick(View view)
{
Intent myIntent = new Intent(Summary.this, MainActivity.class);
startActivity(myIntent);
}
});
Button viewList = (Button) findViewById(R.id.s2ViewList);
viewList.setOnClickListener(new View.OnClickListener()
{
public void onClick(View view)
{
Intent myIntent = new Intent(Summary.this, GiftList.class);
startActivity(myIntent);
}
});
String [][] summary = {{"Number of Presents to buy: ", (noOfGifts + "")},
{"Number of Presents bought:", (giftsPurchased + "")},
{"Cost: £", (cost + "")},
{"Budget: £", "50"}};
String passedBudget=null;
//convert totalPresents to double from String
String tempPresents = summary[0][1];
int presents = Integer.parseInt(tempPresents);
//convert presentsBought to double from String
String tempBought = summary[1][1];
int presentsToBuy = Integer.parseInt(tempBought);
//Number of presents
TextView s2PresentResult = (TextView) findViewById(R.id.s2PresentsResult);
s2PresentResult.setText(summary[0][1]);
//Number of presents to buy
TextView s2PresentsBuyResult = (TextView) findViewById(R.id.s2PresntsBuyResult);
s2PresentsBuyResult.setText((noOfGifts - giftsPurchased) + "");
Bundle passedId = getIntent().getExtras();
if (passedId != null)
{
passedBudget = passedId.getString("Enter Budget");
}
//EditText s2TotalBudget = (EditText) findViewById(R.id.s2TotalBudget);
//s2TotalBudget .addTextChangedListener((android.text.TextWatcher) this);
//s2TotalBudget .setText(passedBudget, TextView.BufferType.EDITABLE);
//Number of people
//TextView s2TotalBudget = (TextView) findViewById(R.id.s2TotalBudget);
//s2TotalBudget.setText("Enter budget");
//Number of people
TextView s2TotalCost = (TextView) findViewById(R.id.s2TotalCost);
s2TotalCost.setText(df.format(Double.parseDouble(summary[2][1])));
//Output if over or under budget
TextView s2CalculateOverBudget = (TextView) findViewById(R.id.s2CalculateOverBudget);
//convert totalCost to double from String
String temp = summary[2][1];
double totalCost = Double.parseDouble(temp);
//convert totalBudget to double from String
String tempTwo = "14";
double totalBudget = Double.parseDouble(tempTwo);
if((totalCost>totalBudget)&&(totalBudget!=0))
{
s2CalculateOverBudget.setTextColor(Color.rgb(209,0,0));
s2CalculateOverBudget.setText("You are over budget");
}
else if(totalBudget==0){
s2CalculateOverBudget.setText("");
}
else {
s2CalculateOverBudget.setText("You are within budget");
}
}
public View.OnClickListener saveButtonListener = new View.OnClickListener()
{
#Override
public void onClick(View v)
{
if(budgetEntered.getText().length()>0)
{
budgetString = budgetEntered.getText().toString();
}
}
};
public void onClick(View v)
{
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after)
{
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count)
{
}
#Override
public void afterTextChanged(Editable s)
{
this it the best way to store and load value in Android:
save values: (put this where you want to save the values, for example in the onStop or onPause method. Or, in your case, in the onClick method)
SharedPreferences settings = getSharedPreferences("MyPref", 0);
SharedPreferences.Editor editor = settings.edit();
editor.putInt("testValue", value);
editor.commit();
load values:
SharedPreferences settings = getSharedPreferences("MyPref", 0);
value = settings.getInt("testValue", defValue);

Categories

Resources