Finish class and get int from class finished to main class - java

I have a MainClass which one is the full app, when I click one button I go to another class (PopupValores) which one I make it looks like a popup. In this class I have a EditText where you type a integer and a button to close this class. My question is how to get that int typed in PopupClass and use it in MainClass. Heres the code for the PopupValores.
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class PopupValores extends Activity implements OnClickListener {
TextView texto;
String mensaje;
EditText editable;
Button ok;
public static int cantidad;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.popupvalores);
ok = (Button) findViewById (R.id.Bok);
texto = (TextView) findViewById (R.id.textView1);
editable = (EditText) findViewById (R.id.editText1);
mensaje = editable.getText().toString();
ok.setOnClickListener(this);
ok.setOnLongClickListener(new View.OnLongClickListener() {
public boolean onLongClick(View arg0) {
finish();
return true;
}
});
}
public void onClick(View v){
switch(v.getId()){
case R.id.Bok:
String mensaje;
mensaje = editable.getText().toString();
cantidad = Integer.parseInt(mensaje);
texto.setText("New value " + cantidad + ".");
}
}
}
Then in my MainClass I click a button and it shows the int
int id, vaas = PopupValores.cantidad;
public void onClick (View v)
{
posicion = (ImageCell) v;
seleccion = posicion.mCellNumber;
if (seleccion == -1){
....
toast (id + " " + vaas);
....
}
}
But instead of showing the value declared in PopupValores it shows 0. What I'm doing wrong here?

You need to call the popup Activity with Activity.startActivityForResult()
Once finishing the popup Activity, set the requested result via Activity.setResult() (you can save your data in the intent's bundle)
In your main Activity, override onActivityResult and retrieve the data

Its called startActivityforResult
and has been answered soo many times here on stackoverflow Here is one

Related

How to make TextView print the value from EditText?

I want the EditText element print the value I have entered in the UserInputs Array. I have tried Log.v and doInBackground,but that doesn't work.
I would be happy if you can explain how do I print the needed value in the EditText in the future, because I'm new in the Adnroid development.
I can send .xml file if needed.
Also, don't mind comments inside the code...
This is the code:
import androidx.appcompat.app.AppCompatActivity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Button;
import android.widget.Toast;
import java.util.*;
public class MainActivity extends AppCompatActivity {
private EditText user_input;
private EditText user_input1;
private Button Button;
private TextView result;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
user_input = findViewById(R.id.user_input);
Button = findViewById(R.id.Button);
result = findViewById(R.id.result);
user_input1 = findViewById(R.id.user_input1);
Button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(user_input.getText().toString().trim().equals("")&&user_input1.getText().toString().trim().equals(""))
Toast.makeText(MainActivity.this, "Введите хотя бы 2 варианта", Toast.LENGTH_LONG).show();
else{
//creating method for randomly choosing one of the user inputs
Random rand = new Random();
EditText[] userInputs = {user_input, user_input1};
int randomAnswer = rand.nextInt(userInputs.length);
result = userInputs[randomAnswer];
Log.v("EditText", result.getText().toString());
}}
});
}
private class getResult extends AsyncTask<String, String, TextView> {
#Override
protected TextView doInBackground(String... strings) {
return result;
}
}
}
Actually, I want to print the value in ResuRrect how to do that?
can you please explain me where exactly you want to print values??
So that I can help you.
If you want to print whatever inserted by user you can use textview to display it.
for that just add two textview in xml find it by id in java and on button click perform set text on it.
for example you have two textview
TextView tv1 = findViewById(R.id.tv1);
TextView tv2 = findViewById(R.id.tv2);
and button click will be as follows
Button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (TextUtils.isEmpty(user_input.getText().toString().trim()) &&
TextUtils.isEmpty(user_input1.getText().toString().trim())) {
Toast.makeText(MainActivity.this, "Введите хотя бы 2 варианта", Toast.LENGTH_LONG).show();
} else {
//creating method for randomly choosing one of the user inputs
tv1.setText(user_input.getText().toString().trim());
tv2.setText(user_input1.getText().toString().trim());
Log.e("EditText1", user_input.getText().toString().trim());
Log.e("EditText2", user_input2.getText().toString().trim());
}
}
});
Your question isn't clear but if you want to display text to the user, it is better to use TextView.
for the set text of EditText or TextView, you should use setText method.
user_input.setText("hello")
So anyway I made it work. Now when user enters two values in EditText, program will randomly choose on of the inputs and print it in the TextView.
Here is the code:
public void onClick(View v) {
if(user_input.getText().toString().trim().equals("")&&user_input1.getText().toString().trim().equals(""))
Toast.makeText(MainActivity.this, "Введите хотя бы 2 варианта", Toast.LENGTH_LONG).show();
else{
//creating method for randomly choosing one of the user inputs
Random rand = new Random();
String[] key = {user_input1.getText().toString().trim(), user_input.getText().toString().trim()};
int randomAnswer = rand.nextInt(key.length);
result.setText(key[randomAnswer].toString().trim());
}}

Save Text in textview after leaving activity

Is there a way for me to keep the entered text in the text view after leaving the activity?
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class ClassDatabase extends AppCompatActivity {
TextView students;
TextView averages;
String studentNames;
String studentAvgs;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_class_database);
students = findViewById(R.id.data);
averages = findViewById(R.id.avgs);
displays the intent;
displayIntent();
back to previous activity where u enter new text
BacktoAdd();
}
private void BacktoAdd(){
Button Back2Add = (Button) findViewById(R.id.backtoadd);
Back2Add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(ClassDatabase.this, Add.class));
}
});
}
adds new text to text view
private void displayIntent(){
studentNames = getIntent().getExtras().getString("class");
studentAvgs = getIntent().getExtras().getString("avg");
students.append(studentNames);
students.append(" \n");
averages.append(studentAvgs);
averages.append(" \n");
}
}
Currently it gets the text from the previous activity and appends the text to the textview but when I go back to the previous activity and repeat the actions the previous text wasn't saved
You can use SharedPreferences https://developer.android.com/training/data-storage/shared-preferences

Java Variable Scope Global

im trying to understand variable scope with simple example.
I need help with this code
package com.varialescope.examplevariablescope;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
private Button buttonOne;
private Button buttonTwo;
private String mText = "Hello World";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//Initialialize UI elements
buttonOne = (Button) findViewById(R.id.button_one);
buttonOne = (Button) findViewById(R.id.button_two);
//Button One click listener
buttonOne.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//Set new text
mText = "ONE";
Toast.makeText(MainActivity.this, mText, Toast.LENGTH_SHORT).show();
}
});
//Button Two click listener
buttonTwo.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(MainActivity.this, mText, Toast.LENGTH_SHORT).show();
}
});
}
}
How can i access to mText string from click listener method ?
and how can i set a new string for mText clicking button One and make it accessible globally?
thanks for help
you create anonymous class Object for clicklistener any anonymous class or inner class object has information about the outside class object , then it had the right to access the methods and variables of the outside class object

Buttons onClick method restarts if clicked to fast

I have little application where you can tell your fortune (it's actualy just random), there are four edittextfields that you can type in and one button that choose one of the edittextfields, and remove it. Pretty simple. But i have problem, if someone presses the button multiple times too fast then all of the code in the onClick() method doesn't execute (probably because it is called again). Is there some way that I can prevent this from happening (I want all of the code in the onClick() method to execute before it can be called again)?
Here is the code:
package com.foretell.lukas.spamedprick;
import android.graphics.Bitmap;
import android.media.MediaPlayer;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.Collections;
public class MainActivity extends AppCompatActivity {
ArrayList<EditText> tfa = new ArrayList<EditText>();
int x = 0;
boolean tf = true;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// References to XML widgets
final RelativeLayout rl = (RelativeLayout) findViewById(R.id.background);
final Button daButton = (Button) findViewById(R.id.button);
Button restartButton = (Button) findViewById(R.id.restartButton);
final EditText ruta1 = (EditText) findViewById(R.id.editText);
final EditText ruta2 = (EditText) findViewById(R.id.editText2);
final EditText ruta3 = (EditText) findViewById(R.id.editText3);
final EditText ruta4 = (EditText) findViewById(R.id.editText4);
final TextView outputText = (TextView) findViewById(R.id.outputText);
tfa.add(ruta1);
tfa.add(ruta2);
tfa.add(ruta3);
tfa.add(ruta4);
final MediaPlayer mp = MediaPlayer.create(this, R.raw.spar);
final MediaPlayer mp2 = MediaPlayer.create(this, R.raw.hurra);
daButton.setOnClickListener(
new Button.OnClickListener() {
public void onClick(View v) {
if(tf) {
daButton.setEnabled(false);
mp.start();
try {
tf = false;
Thread.sleep(2000);
} catch (InterruptedException e) {
e.getStackTrace();
outputText.setText("Nått gick åt h***ete!");
}
Collections.shuffle(tfa);
x++;
if (x <= 2) {
outputText.setText("Det är inte " + tfa.get(0).getText() + "...");
tfa.get(0).setText("");
tfa.remove(0);
} else if (x == 3) {
outputText.setText("Det är...");
} else if (x == 4) {
tfa.get(1).setText("");
tfa.remove(1);
outputText.setText("Det är " + tfa.get(0).getText() + "!");
mp2.start();
}
tf = true;
daButton.setEnabled(true);
}else{
System.out.println("YO!");
}
}
}
);
restartButton.setOnClickListener(
new Button.OnClickListener() {
public void onClick(View v) {
tfa.add(ruta1);
tfa.add(ruta2);
tfa.add(ruta3);
tfa.add(ruta4);
ruta1.requestFocus();
outputText.setText("");
x = 0;
ruta1.setText("");
ruta2.setText("");
ruta3.setText("");
ruta4.setText("");
}
}
);
}
}
Thanks.
I dont think that an "onClick" can be started before the last "onClick" is finished.
Here is the qoute from the android documentation:
The system does not create a separate thread for each instance of a component. All components that run in the same process are instantiated in the UI thread, and system calls to each component are dispatched from that thread. Consequently, methods that respond to system callbacks (such as onKeyDown() to report user actions or a lifecycle callback method) always run in the UI thread of the process.
http://developer.android.com/guide/components/processes-and-threads.html
Maybe you do something in the onClick method, that makes trouble, but without the code it is hard to tell:)
You have to do something like this
Button button= (Button) findViewById(R.id.buttonId);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
button.setEnabled(false);
// do your work here
// make it true after your work is done
button.setEnabled(true);
}
});

I want to make password protected android application

I want to make password protected android app, but when in this simple program system is not matching two strings.
package com.pokmgr;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.text.Editable;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
public class MainPM extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.pm_layout);
final EditText pin = (EditText) findViewById(R.id.pinET);
final String pass = pin.getText().toString();
final String code = "ajaj";
Button enter = (Button) findViewById(R.id.enterBtn);
enter.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
if (pass.equals(code)) {
Intent in = new Intent(MainPM.this, Menu.class);
startActivity(in);
}
else {
Intent in = new Intent(MainPM.this, Menu2.class);
startActivity(in);
}
}
});
}
/*#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.pm_layout, menu);
return true;
}*/
}
I have made Menu and Menu2 class, but every time Menu2 class is accessed. Even if I enter same pass that is "ajaj" [in this code to test]
i have defined both activities in manifest file.
Can't understand why pass.eqals(code) is not working
The problem is that you are setting pass to the contents of the EditText when the activity gets created. Instead you have to retrieve the contents of your EditText inside the OnClickListener.
Like this:
public void onClick(View v) {
final String pass = pin.getText().toString();
if (pass.equals(code)) {
// do something
} else {
// do something different
}
}
Put pin.getText().toString(); inside onClick of button. You are setting variable pass before the user actually entered something in pinEt EditText.

Categories