How to make TextView print the value from EditText? - java

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

Related

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- hot to have just 1 button to toggle back and forth instead of two buttons?

I have 1 button for changing an image and a text.
I wanted to make that same button so that if I click AGAIN, it would change back to the original image and the text. However, 'TextView' and 'ImageView' in Java code would tell me, I have already defined. Therefore, I guess I can't re-define them within 1 button.
I ended up creating 2 buttons: 1 to change and 2nd one to return back. How can I just have one button to change and return images and text? HELP!
package com.example.android.cookies;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
/**
* Called when the cookie should be eaten.
*/
public void eatCookie(View view) {
// TODO: Find a reference to the ImageView in the layout. Change the image.
ImageView imageView = (ImageView)
findViewById(R.id.android_cookie_image_view);
imageView.setImageResource(R.drawable.after_cookie);
// TODO: Find a reference to the TextView in the layout. Change the text.
TextView textView = (TextView) findViewById(R.id.status_text_view);
textView.setText("Im so full");
}
public void returnCookie(View view) {
ImageView imageView = (ImageView)
findViewById(R.id.android_cookie_image_view);
imageView.setImageResource(R.drawable.before_cookie);
TextView textView = (TextView) findViewById(R.id.status_text_view);
textView.setText("I'm so hungry");
}
}
]2
I have written a well maintained code for you. You can save current state.
I don't recommend boolean. Because if you take int you can save more states in future, whereas in boolean you can save only two states- true or false.
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
public class MainActivity extends Activity {
ImageView imageView;
TextView textView;
Button button;
final int STATE_HUNGRY = 1;
final int STATE_FULL = 2;
int currentState = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imageView = (ImageView) findViewById(R.id.android_cookie_image_view);
textView = (TextView) findViewById(R.id.status_text_view);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
switch (currentState) {
case STATE_FULL:
returnCookie();
break;
case STATE_HUNGRY:
eatCookie();
break;
default: // used when there is no state available
eatCookie();
}
}
});
}
public void eatCookie() {
currentState = STATE_FULL;
imageView.setImageResource(R.drawable.after_cookie);
textView.setText("Im so full");
}
public void returnCookie() {
currentState = STATE_HUNGRY;
imageView.setImageResource(R.drawable.before_cookie);
textView.setText("I'm so hungry");
}
}
Have you tried using a static variable to keep track of the currently displayed image? Static means it will maintain its state between function calls. Then toggle it each time the function is called. The initial declaration will only be called once.
static Boolean eaten = false;

Finish class and get int from class finished to main class

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

Need an easier way to set up onClickListener for several variables in Android calculator program

I'm programming an Android calculator in Eclipse. I want to be able to set up the OnClickListener for several variables instead of having to code a listener for each one. Seems like overkill. Is there a way to do this using an array, maybe? Much help would be appreciated.
package rechee.cool;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class HelloAndroidActivity extends Activity {
/** Called when the activity is first created. */
int counter=0;
//Just have two buttons so far, I'm going to have like 10 more
Button one;
Button two;
EditText display;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// Associate the button variable with the xml reference
one= (Button) findViewById(R.id.bOne);
display= (EditText) findViewById(R.id.editText1);
//When button is clicked, display the text. How do I do this for the rest of my variables?
one.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
//String string= Integer.toString(counter);
display.setText("1");
}
});
}
}
The way I'd do this is add the same onClick attribute in XML to every button, like this:
<Button android:onClick="onButtonClick"
... />
and then add the method that you used in that attribute to your activity, differentiating the buttons by id:
public void onButtonClick(View v) {
switch(v.getId()) {
case R.id.button1:
// do something when button 1 is pressed
break;
case R.id.button2:
// do something when button 2 is pressed
break;
// and so on ....
}
}
Alternatively you can use findViewById() to get each button and assign the same listener to all the buttons. Then differentiate by id inside onClick()as shown above. This adds a few useless codelines though, so I think this example here is slightly more clean.
Yes you just need to override the onClick method of the Activity and tell it to implement the OnClickListener:
import com.ewe.R;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class HelloAndroidActivity extends Activity implements OnClickListener {
/** Called when the activity is first created. */
int counter=0;
//Just have two buttons so far, I'm going to have like 10 more
Button one;
Button two;
EditText display;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// Associate the button variable with the xml reference
one= (Button) findViewById(R.id.bOne);
display= (EditText) findViewById(R.id.editText1);
//When button is clicked, display the text. How do I do this for the rest of my variables?
one.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
//String string= Integer.toString(counter);
display.setText("1");
}
});
}
#Override
public void onClick(View v){
switch (case v.getId()){
case R.id.bOne:
//Put code for bOne here
break;
case R.id.editText1:
//Put code for editText1 here
break;
}
}
}

How can a button click method find out which item is selected in a ListView?

I have a single screen with a bank of buttons below a ListView. Entries on the ListView light up in orange when I scroll so I assume that are selected. When I then press the "Delete" button I want the onClickListener to remove the currently selected entry. But getSelectedItemPosition() always gives me -1. If I can't hope to use the GUI controls in this way, please give me another way of getting the same result.
I have even tried setting the onClickListener of the List View to store the index before the button is pressed (in case pressing the button unselects the entry) but even that is always -1 it seems.
Here's the code (without the modification which didn't work)
package com.bayley;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import java.util.ArrayList;
/**
*
* #author p0074564
*/
public class September extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.main);
final ListView myListView = (ListView) findViewById(R.id.myListView);
Button addButton = (Button) findViewById(R.id.AddButton);
Button deleteButton = (Button) findViewById(R.id.DeleteButton);
final EditText editText = (EditText) findViewById(R.id.myEditText);
final ArrayList<String> todoItems = new ArrayList<String>();
todoItems.add("Monday");
todoItems.add("Tuesday");
todoItems.add("Wednesday");
final ArrayAdapter<String> aa =
new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, todoItems);
myListView.setAdapter(aa);
addButton.setOnClickListener(new
Button.OnClickListener() {
public void onClick(View v) {
todoItems.add(editText.getText().toString());
aa.notifyDataSetChanged();
}
});
deleteButton.setOnClickListener(new
Button.OnClickListener() {
public void onClick(View v) {
// always returns -1 unfortunately ie nothing is ever selected
int index = myListView.getSelectedItemPosition();
if (index >= 0) {
todoItems.remove(index);
}
aa.notifyDataSetChanged();
}
});
}
}
As I already mentioned in my comment I don't know if you can attach a OnFocusChangedListener to the items of a list, but I pretty sure that is possible some how, although it won't really help you.
But perhaps the both option below will might be interesting for you.
Implement a item context menu which appears when you long click an item. In this context menu you can provide a delete action. You will see this behavior on many different Android apps which handle some sort of lists. Have a look at this blog post.
Make you list to be capable of selecting multiple items. See this question for more infos. By this way you can delete multiple items at once.
i some what modified ur code.. its working
public class Selectlistitem extends Activity {
int pos;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.main);
final ListView myListView = (ListView) findViewById(R.id.widget34);
Button addButton = (Button) findViewById(R.id.btnadd);
Button deleteButton = (Button) findViewById(R.id.btnremove);
final EditText editText = (EditText) findViewById(R.id.txt1);
final ArrayList<String> todoItems = new ArrayList<String>();
todoItems.add("Monday");
todoItems.add("Tuesday");
todoItems.add("Wednesday");
final ArrayAdapter<String> aa =
new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, todoItems);
myListView.setAdapter(aa);
addButton.setOnClickListener(new
Button.OnClickListener() {
public void onClick(View v) {
todoItems.add(editText.getText().toString());
aa.notifyDataSetChanged();
}
});
myListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> list, View v, int pos, long id) {
aa.getItem(pos);
editText.setText(""+pos);
}
});
deleteButton.setOnClickListener(new
Button.OnClickListener() {
public void onClick(View v) {
// always returns -1 unfortunately ie nothing is ever selected
// int index = myListView.getCheckedItemPosition();
int index=pos;
if (index >= 0) {
todoItems.remove(index);
}
editText.setText(""+index);
aa.notifyDataSetChanged();
}
});
}
}

Categories