Clearing certain activity variables with onResume - android

I'm creating a simple Android app with 2 Activities. Activity B displays a bunch of data passed from A. When the user press the back button from B I need to clear some variables in order to not duplicate the data shown on B, but both variables I'm erasing on onResume() aren't clearing at all. Here's my code:
public class MainActivity extends AppCompatActivity {
List<Camarera> camareras = new ArrayList<Camarera>();
List<String> resultados = new ArrayList<String>();
int camHabs = 0;
Button boton;
TextView dinero;
TextView camarera1, camarera2, camarera3, camarera4, camarera5;
EditText hora1, hora2, hora3, hora4, hora5;
EditText resta1, resta2, resta3, resta4, resta5;
Switch switch1, switch2, switch3, switch4, switch5;
#Override
public void onResume()
{
super.onResume();
resultados = new ArrayList<>();
camHabs = 0;
Toast.makeText(getApplicationContext(),"Resumiendo", Toast.LENGTH_LONG).show();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
boton = (Button) findViewById(R.id.Boton);
camHabs = 0;
boton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Calcular();
}
});
}
void Calcular(){
dinero = (TextView) findViewById(R.id.Dinero);
camarera1 = (TextView) findViewById(R.id.Camarera1);
camarera2 = (TextView) findViewById(R.id.Camarera2);
camarera3 = (TextView) findViewById(R.id.Camarera3);
camarera4 = (TextView) findViewById(R.id.Camarera4);
camarera5 = (TextView) findViewById(R.id.Camarera5);
hora1 = (EditText) findViewById(R.id.C_Horas1);
hora2 = (EditText) findViewById(R.id.C_Horas2);
hora3 = (EditText) findViewById(R.id.C_Horas3);
hora4 = (EditText) findViewById(R.id.C_Horas4);
hora5 = (EditText) findViewById(R.id.C_Horas5);
resta1 = (EditText) findViewById(R.id.C_Resta1);
resta2 = (EditText) findViewById(R.id.C_Resta2);
resta3 = (EditText) findViewById(R.id.C_Resta3);
resta4 = (EditText) findViewById(R.id.C_Resta4);
resta5 = (EditText) findViewById(R.id.C_Resta5);
switch1 = (Switch) findViewById(R.id.C_Switch1);
switch2 = (Switch) findViewById(R.id.C_Switch2);
switch3 = (Switch) findViewById(R.id.C_Switch3);
switch4 = (Switch) findViewById(R.id.C_Switch4);
switch5 = (Switch) findViewById(R.id.C_Switch5);
List<TextView> nombres = Arrays.asList(camarera1, camarera2, camarera3, camarera4, camarera5);
List<EditText> horas = Arrays.asList(hora1, hora2, hora3, hora4, hora5);
List<EditText> restas = Arrays.asList(resta1, resta2, resta3, resta4, resta5);
List switches = Arrays.asList(switch1, switch2, switch3, switch4, switch5);
int resultado;
int maxHoras = 0;
int Dinero = Integer.parseInt(dinero.getText().toString());
for (int i = 0; i < nombres.size(); i++) {
Camarera cam = new Camarera();
cam.SetNombre(nombres.get(i).getText().toString());
cam.SetHoras(horas.get(i).getText().toString());
maxHoras += cam.GetHoras();
cam.SetResta(restas.get(i).getText().toString());
Switch var = (Switch) switches.get(i);
cam.activa = var.isChecked();
camareras.add(cam);
}
for (int i = 0; i < camareras.size(); i++) {
Camarera cam = camareras.get(i);
if (cam.activa) {
camHabs++;
if (cam.error) {
Toast.makeText(getApplicationContext(),cam.error_S, Toast.LENGTH_LONG).show();
return;
}
resultado = ((cam.GetHoras() * Dinero) / maxHoras) - cam.GetResta();
resultados.add(cam.GetNombre() + " se lleva " + resultado + "€");
}
}
Intent intent = new Intent(MainActivity.this, Tabla.class);
intent.putExtra("lista", (ArrayList<String>) resultados);
intent.putExtra("habs", camHabs);
startActivity(intent);
}
Could you help me please? Been stuck with this the whole day.

Try to equal them to null into on Resume and then after that recreate the empty value as you've already done. Let me know if it works.

From the docs on OnResume:
Be aware that the system calls this method every time your activity comes into the foreground, including when it's created for the first time.
It is even called when you press home button/switch apps, so I don't think it is a good idea to do this here.
Why not just do it before you call your startActivity call:
Intent intent = new Intent(MainActivity.this, Tabla.class);
intent.putExtra("lista", (ArrayList<String>) resultados);
intent.putExtra("habs", camHabs);
//Reset variables here
resultados = new ArrayList<>();
camHabs = 0;
startActivity(intent);

Actually, the error wasn't on those two variables, it was on a third one called "camareras" I wasn't clearing it and because I use it in each cycle it would add again and again to "camHabs".
Thanks anyways!

Related

Get a button index using onClick method

So , I was not making my self clear. I'm having a little trouble trying to get a button index from a matrix.
I have this matrix bt[4][4], and each button has a value like this :
btn11 = bt[0][0].
Now what I want to do is, whenever I click on a Button, I get it´s "cordinates".
Ex: Bt11 would give [0] and [0] .
Now the problems that I'm having:
I've set listeners to each button, but I can't implement a "onClick" method.
Whenever I try to implement here "public class easy extends Activity" I get an error message.
Second problem, I don't know to get the cordinates from bt[x][y].
To sum it up. I want to set a onClick method so every time you click on a button you get it's [x][y] cordinates.
Here's my code:
public class easy extends Activity { //Can't implement OnClick Listener
Button bt[][] = new Button[4][4];
Button up;
Button down;
Button left;
Button right;
int listaTroca[] = new int[10]; // lista pra receber os valores de retorno da logica
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_easy);
//Linha 1
bt[0][0] = (Button) findViewById(R.id.bt11);
bt[0][0].setOnClickListener((View.OnClickListener) this);
bt[0][1] = (Button) findViewById(R.id.bt12);
bt[0][1].setOnClickListener((View.OnClickListener) this);
bt[0][2] = (Button) findViewById(R.id.bt13);
bt[0][2].setOnClickListener((View.OnClickListener) this);
bt[0][3] = (Button) findViewById(R.id.bt14);
bt[0][3].setOnClickListener((View.OnClickListener) this);
//--------------------- Linha 2
bt[1][0] = (Button) findViewById(R.id.bt21);
bt[1][0].setOnClickListener((View.OnClickListener) this);
bt[1][1] = (Button) findViewById(R.id.bt22);
bt[1][1].setOnClickListener((View.OnClickListener) this);
bt[1][2] = (Button) findViewById(R.id.bt23);
bt[1][2].setOnClickListener((View.OnClickListener) this);
bt[1][3] = (Button) findViewById(R.id.bt24);
bt[1][3].setOnClickListener((View.OnClickListener) this);
//------------------------Linha 3
bt[2][0] = (Button) findViewById(R.id.bt31);
bt[2][0].setOnClickListener((View.OnClickListener) this);
bt[2][1] = (Button) findViewById(R.id.bt32);
bt[2][1].setOnClickListener((View.OnClickListener) this);
bt[2][2] = (Button) findViewById(R.id.bt33);
bt[2][2].setOnClickListener((View.OnClickListener) this);
bt[2][3] = (Button) findViewById(R.id.bt34);
bt[2][3].setOnClickListener((View.OnClickListener) this);
//---------------------Linha 4
bt[3][0] = (Button) findViewById(R.id.bt41);
bt[3][0].setOnClickListener((View.OnClickListener) this);
bt[3][1] = (Button) findViewById(R.id.bt42);
bt[3][1].setOnClickListener((View.OnClickListener) this);
bt[3][2] = (Button) findViewById(R.id.bt43);
bt[3][2].setOnClickListener((View.OnClickListener) this);
bt[3][3] = (Button) findViewById(R.id.bt44);
bt[3][3].setOnClickListener((View.OnClickListener) this);
//----------------------FIM DECLARAÇÃO + OUVIDOS
listaTroca = Logic.Logic_main(1,1,1);
}
}
I'm not completely sure what your question is here, but from what i understand you want a View.OnClickListener() on each button, and when the button is being clicked you want to do something right?
EDITED: I've edited the answer as the question was clarified in the comments below.
What you want to do, is simply iterate your bt[][] to find the right button, like so:
public class Easy extends Activity {
Button[][] bt = new Button[4][4];
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_easy);
//Linha 1
bt[0][0] = (Button) findViewById(R.id.bt11);
bt[0][0].setOnClickListener(mOnClickListener);
bt[0][1] = (Button) findViewById(R.id.bt12);
bt[0][1].setOnClickListener(mOnClickListener);
// ADD YOUR OTHER findViewByID
}
View.OnClickListener mOnClickListener = new View.OnClickListener() {
#Override
public void onClick(View v) {
ButtonCoordinate bc = getButtonCoordinate(v);
if (bc != null) {
// You now have your button, and the coordinates
Log.d("Easy", "Button.position[ x:" + bc.x + ", y:" + bc.y + " ]");
}
}
};
private ButtonCoordinate getButtonCoordinate(View v) {
for (int x = 0 ; x < bt.length ; x++ ) {
for (int y = 0 ; y < bt[x].length ; y++) {
Button b = bt[x][y];
if (v == b) {
return new ButtonCoordinate(x, y, b);
}
}
}
return null;
}
public static class ButtonCoordinate {
public final int x;
public final int y;
public final Button button;
public ButtonCoordinate(int x, int y, Button button) {
this.x = x;
this.y = y;
this.button = button;
}
}
}
you just need to call getButtonCoordinate(View) which will return a ButtonCoordinate containing the Button and it's x and y coordinates in the bt[][]

How to generate random order for a strings list?

Every time an user click on the button it has to show "John - Sue" or "Sue - John".
I tried with this code:
public class MyActivity extends Activity {
ArrayList<String> names = new ArrayList<String>();
int p1, p2;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.myactivity);
names.add("John");
names.add("Sue");
Button b = (Button) findViewById(R.id.mybutton);
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
p1 = (int)Math.random();
if (p1 == 0)
p2 = 1;
else
p2 = 0;
String msg = names.get(p1) + " - " + names.get(p2);
AlertDialog msgbox = new AlertDialog.Builder(About.this).setTitle("Click here").setMessage(msg).create();
//msgbox.setPositiveButton("OK", null);
msgbox.setCancelable(true);
msgbox.show();
TextView textView = (TextView) msgbox.findViewById(android.R.id.message);
textView.setTextSize(16);
}
});
}
}
But i get always the same order, even i close and run again the app. How to do that?
If you want shuffle list:
Collections.shuffle(names)
If you want random int between 0 or 1 (nextInt(int) javadoc):
Random random = new Random();
int randomInt = random.nextInt(2);
Math.random() returns a number between 0 and 1. So when you cast it to int it will always be 0.
Try this:
p1 = (int)(Math.random()*2);
It happens because
p1 = (int)Math.random();
always gives you zero.

Android run time error

I am a beginner Android developer and I have a runtime error in my code: when I want to run it in a emulator or a device it show "force close" massage. My log is here:
http://upir.ir/934/1_5e07a.jpg
My Java code:
public class Third extends Activity
{
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Button d = (Button) findViewById(R.id.btn4);
d.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
dialog();
}
});
}
public void dialog(){
final Dialog dialog = new Dialog(Third.this);
dialog.setContentView(R.layout.dialog);
dialog.setTitle("واحد عدد وارد شده را انتخاب کنید");
dialog.show();
RadioGroup rg = (RadioGroup) dialog.findViewById(R.id.rg);
final RadioButton rb1 = (RadioButton) dialog.findViewById(R.id.rb1);
final RadioButton rb2 = (RadioButton) dialog.findViewById(R.id.rb2);
rg.setOnCheckedChangeListener(new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup arg0, int arg1) {
if(rb1.isChecked()) {
dialog.dismiss();
Button t = (Button)findViewById(R.id.btn5);
t.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
EditText ft1 = (EditText)findViewById(R.id.f3);
TextView foot = (TextView)findViewById(R.id.foot);
TextView mile = (TextView)findViewById(R.id.mile);
TextView inch = (TextView)findViewById(R.id.inch);
TextView yard = (TextView)findViewById(R.id.yard);
TextView mm = (TextView)findViewById(R.id.millymeter);
TextView dm = (TextView)findViewById(R.id.decimeter);
TextView mim = (TextView)findViewById(R.id.micrometer);
TextView nm = (TextView)findViewById(R.id.nanometer);
TextView hand = (TextView)findViewById(R.id.hand);
TextView iron = (TextView)findViewById(R.id.iron);
TextView point = (TextView)findViewById(R.id.point);
if(ft1.getText().toString().length() == 0 ){return;}
int first = Integer.parseInt(ft1.getText().toString());
double equal = first *0.0328;
DecimalFormat formatf = new DecimalFormat("#.####");
String x = formatf.format(equal)+" فوت";
foot.setText(x);
first = Integer.parseInt(ft1.getText().toString());
equal = first * 0.000005;
DecimalFormat formatm = new DecimalFormat("#.####");
x = formatm .format(equal)+"مایل";
mile.setText(x);
equal = first * 0.393;
DecimalFormat formati = new DecimalFormat("#.####");
x = formati.format(equal)+"اینچ";
inch.setText(x);
equal = first * 0.0109;
DecimalFormat formaty = new DecimalFormat("#.#####");
x = formaty.format(equal)+"یارد";
yard.setText(x);
equal = first / 10;
DecimalFormat formatmi = new DecimalFormat("#.##");
x = formatmi.format(equal)+"دسی متر";
dm.setText(x);
int equalmm = first * 10;
x = equalmm+"میلی متر";
mm.setText(x);
int equalm = first * 10000;
x = equalm+"میکرو متر";
mim.setText(x);
int equaln = first * 10000000;
x = equaln + "نانو متر";
nm.setText(x);
equal = first * 0.098;
DecimalFormat formath = new DecimalFormat("#####.#####");
x = formath.format(equal)+"هَند";
hand.setText(x);
equal = first * 19;
x = equal+"آیرون";
iron.setText(x);
equal = first * 28;
x = equal+"پوینت";
point.setText(x);
}
});
}
You need to inflate your activity with a layout resource first before you can use the findViewById() method to retrieve views. If there's no layout, then there are no views which could possibly be found.
You are missing an important part. You need to add a view to your Activity in order to find the elements of that view like the Button you are trying to instantiate.
In your OnCreate method add this:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.the_xml_file); //Here add the xml file with the view you want to show
Button d = (Button) findViewById(R.id.btn4);
d.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
dialog();
}
});
}
After your super.onCreate(savedInstanceState); are you setting the content view?
e.g.
setContentView(R.layout.nameofxmlfilehere);

How can I give a value to a variable in one Onclicklistener and use that value in another Onclicklistener in Android?

I can't figure out how to fix this problem in my code: I am making a small app which randomly asks you for 20 words from Dutch (nederlands) to English (engels). I have saved the words in arrays and the words are randomly picked now. There are 2 buttons: One for picking a random word and one for checking if the answer is correct. The variable iwoord is given a random value when pressing button Newword and i want the same value to be used in the next OnClickListener, so I can compare the arrays and see if the answer is correct. But the variable cannot be resolved in the second OnClickListener. Can anybody help me solving my problem?
public class MainActivity extends Activity {
EditText NederlandsEdit;
EditText EngelsEdit;
Button ControleerButton;
Button NieuwwoordButton;
Random woord = new Random();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final String[] nederlands = new String[20];
nederlands[0] = "bij";
nederlands[1] = "paraplu";
nederlands[2] = "hond";
nederlands[3] = "kaas";
nederlands[4] = "eekhoorn";
nederlands[5] = "fiets";
nederlands[6] = "auto";
nederlands[7] = "vis";
nederlands[8] = "maan";
nederlands[9] = "aarde";
nederlands[10] = "vuur";
nederlands[11] = "boom";
nederlands[12] = "blaadje";
nederlands[13] = "soep";
nederlands[14] = "sok";
nederlands[15] = "potlood";
nederlands[16] = "kat";
nederlands[17] = "muis";
nederlands[18] = "zeep";
nederlands[19] = "ring";
final String[] engels = new String[20];
engels[0] = "bee";
engels[1] = "umbrella";
engels[2] = "dog";
engels[3] = "cheese";
engels[4] = "squirrel";
engels[5] = "bicycle";
engels[6] = "car";
engels[7] = "fish";
engels[8] = "moon";
engels[9] = "earth";
engels[10] = "fire";
engels[11] = "tree";
engels[12] = "leaf";
engels[13] = "soup";
engels[14] = "sock";
engels[15] = "pencil";
engels[16] = "cat";
engels[17] = "mouse";
engels[18] = "soap";
engels[19] = "ring";
NederlandsEdit = (EditText) findViewById(R.id.editnederlands);
EngelsEdit = (EditText) findViewById(R.id.editengels);
ControleerButton = (Button) findViewById(R.id.butcontroleer);
NieuwwoordButton = (Button) findViewById(R.id.butnieuwwoord);
NieuwwoordButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
NieuwwoordButton.setEnabled(false);
ControleerButton.setEnabled(true);
int iwoord = woord.nextInt(20 - 0) + 0;
NederlandsEdit.setText(nederlands[iwoord]);
}
});
ControleerButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(EngelsEdit.getText().toString().equals(engels[iwoord])){
Toast.makeText(getBaseContext(), "correct!", Toast.LENGTH_SHORT).show();
}
else
{
i = i + 1;
}
}
});
}
The int "iwoord" should be declared globally just like the edittexts. I have posted the code just in case.
package com.example.stack_test;
import java.util.Random;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends Activity {
EditText NederlandsEdit;
EditText EngelsEdit;
Button ControleerButton;
Button NieuwwoordButton;
Random woord = new Random();
int i,iwoord;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final String[] nederlands = new String[20];
nederlands[0] = "bij";
nederlands[1] = "paraplu";
nederlands[2] = "hond";
nederlands[3] = "kaas";
nederlands[4] = "eekhoorn";
nederlands[5] = "fiets";
nederlands[6] = "auto";
nederlands[7] = "vis";
nederlands[8] = "maan";
nederlands[9] = "aarde";
nederlands[10] = "vuur";
nederlands[11] = "boom";
nederlands[12] = "blaadje";
nederlands[13] = "soep";
nederlands[14] = "sok";
nederlands[15] = "potlood";
nederlands[16] = "kat";
nederlands[17] = "muis";
nederlands[18] = "zeep";
nederlands[19] = "ring";
final String[] engels = new String[20];
engels[0] = "bee";
engels[1] = "umbrella";
engels[2] = "dog";
engels[3] = "cheese";
engels[4] = "squirrel";
engels[5] = "bicycle";
engels[6] = "car";
engels[7] = "fish";
engels[8] = "moon";
engels[9] = "earth";
engels[10] = "fire";
engels[11] = "tree";
engels[12] = "leaf";
engels[13] = "soup";
engels[14] = "sock";
engels[15] = "pencil";
engels[16] = "cat";
engels[17] = "mouse";
engels[18] = "soap";
engels[19] = "ring";
NederlandsEdit = (EditText) findViewById(R.id.editnederlands);
EngelsEdit = (EditText) findViewById(R.id.editengels);
ControleerButton = (Button) findViewById(R.id.butcontroleer);
NieuwwoordButton = (Button) findViewById(R.id.butnieuwwoord);
NieuwwoordButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
NieuwwoordButton.setEnabled(false);
ControleerButton.setEnabled(true);
iwoord = woord.nextInt(20 - 0) + 0;
NederlandsEdit.setText(nederlands[iwoord]);
}
});
ControleerButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(EngelsEdit.getText().toString().equals(engels[iwoord])){
Toast.makeText(getBaseContext(), "correct!", Toast.LENGTH_SHORT).show();
}
else
{
i = i + 1;
}
}
});
}
}
Declare your variable globally and you can able assign value from first onclicklistener and use it frm the second onclicklistener
In case you are facing problems that listeners ask you to make your variable final, use a setter and a getter method for your variable. You cant change the value of an integer variable once you have initialized it for the first time. Don't use it directly in the Listener code, and you wont have to make it final.
Read this article if you need to be familiar with getters and setters.

Browse an array of strings in a TextView

I wonder how I could navigate between the strings within an array, using the previous and next buttons, these strings will be displayed in a TextView. Thank you!
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView (R.layout.activity_f3);
setTitleFromActivityLabel (R.id.title_text);
TextView cumulos = (TextView) findViewById(R.id.cumulos);
TextView respostas = (TextView)findViewById(R.id.respostas);
Random randPhrase = new Random();
String[] cum = getResources().getStringArray(R.array.cumulos);
String[] resp = getResources().getStringArray(R.array.resp_cumulos);
String textout = "";
String textresp = "";
for (int i = 0; i < cum.length; i++) {
for (int j = 0; j < resp.length; j++) {
textresp = resp[j];
}
textout = cum[i];
}
cumulos.setText(textout);
respostas.setText(textresp);
}
Declare one int for index starting with 0 then in NextButton do
if(!index > resp.length-1 ) //not greater than array length
{
setText(resp[index++]);
}
else { nextButton.setEnabled(false); nextButton.setClicable(false); } //not clickable anymore
in PreviousButton do
if(!index < 0)
{
setText(resp[index--]);
}
else{
prevButton.setEnabled(false);
prevButton.setClicable(false);
}
Something like this? Mind this code is not tested, might throw exceptions.
It just to give you an idea.
You will need to create a next button and set an onClickListener for your button to navigate through the array. Lets say you also have a previous and next button. Try this:
Button btnNext = (Button) findViewById(R.id.yourNextbutton);
Button btnPrevious = (Button) findViewById(R.id.yourPreviousbutton);
int i = 0;
btnNext.setOnClickListener(new OnClickListener(){
public void onClick(View arg0) {
if(i<cum.length-1){
i+=1;
cumulos.setText(cum[i]);
respostas.setText(resp[i]);
}
}
});
btnPrevious.setOnClickListener(new OnClickListener(){
public void onClick(View arg0) {
if(i>0){
i-=1;
cumulos.setText(cum[i]);
respostas.setText(resp[i]);
}
}
});

Categories

Resources