I have a list of buttons and what I want to do is display some information on press. Here´s the code:
public class ActividadDos extends AppCompatActivity {
private Map<CharSequence, String> info = new HashMap();
private Button btnYogur;
private Button btnChocolate;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_actividad_dos);
btnYogur = (Button) findViewById(R.id.btnYogur);
btnChocolate = (Button) findViewById(R.id.btnChocolate);
info.put(btnYogur.getText(), "Lácteos");
info.put(btnChocolate.getText(), "Grasas, aceites y dulces");
}
public void displayMensaje(View v) {
Button button = (Button) v;
String nombre = (String) button.getText();
String mensaje = "Clasificación: " + info.get(nombre);
Toast.makeText(ActividadDos.this, mensaje, Toast.LENGTH_SHORT).show();
}
}
It doesn´t show any errors but when I press the buttons it doesn´t display the message.
Similar code is working on another activity.
You forgot to call displayMensaje() method.
Add this to .xml for corresponding button(As per requirement)
android:onClick="displayMensaje"
It isn't displaying anything because you aren't calling displayMensaje() method anywhere in your code at all. To solve this, please add a call to this method and your problem will be solved.
Related
im programming an app to sort numbers and display the sorting process
after the input is sorted , a new button will be showen to display the selection sort steps in a new activity
[SelectionSort activity 1
I want the output of the function SelectionSortMethod in SelectionSortclass to be displayed in a new activity activity_Ssteps
SelectionSort.java :
public class SelectionSort extends AppCompatActivity {
EditText input;
EditText output;
Button Ssteps ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_selection_sort);
input=findViewById(R.id.input);
output=findViewById(R.id.output);
Ssteps = findViewById(R.id.steps);
Ssteps.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
Intent s = new Intent(SelectionSort.this, com.example.sorted.Ssteps.class);
startActivityForResult(s, 1);
}
});}
public void sortButtonPressed(View view){
String[] numberList = input.getText().toString().split(",");
Integer[] numbers = new Integer[numberList.length];
for (int i = 0; i < numberList.length; i++) {
numbers[i] = Integer.parseInt(numberList[i]);
}
SelectionSortmethod(numbers);
output.setText(Arrays.toString(numbers));
// if button "sort " is pressed , the button "view steps "will be displayed
Ssteps.setVisibility(View.VISIBLE);
}
}
public static void SelectionSortmethod (Integer[] arr)
{
// some code for sorting and showing the steps
}
Ssteps.java :
public class Ssteps extends AppCompatActivity {
TextView steps_text ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_ssteps);
setTitle("selection sort steps ");
steps_text =findViewById(R.id.Stepstextview);
}
}
You can just use intent.extras like so:
Intent s = new Intent(SelectionSort.this, com.example.sorted.Ssteps.class);
s.putExtra("AnyID",YOURDATA);
startActivity(s);
And then in your Ssteps.class you can get the data using
the id like this:
String ss = getIntent.getExtra("AnyID"); //the id is the same as the other one above
steps_text.settext(ss);
Working with Intents like Youssof described is the way to go for small applications like yours. However as you progress in Android programming, you should definitely have a look at splitting your application in Fragments rather than Activities. They can use a Viewmodel, which makes sharing lots of data between screens much easier. Also Fragments can be use in androidx Navigation component, whos changing Fragments can be beautifully arranged in a UI. Very convenient for product reviews.
I have tried different things for quite some hours now, but I cannot seem to wrap my head around how to update a TextView when a user inputs a new text through an EditTextPreference in Android.
I use a switch statement in the onSharedPreferenceChanged method, inside an anonymous listener class. However, when i set player1View.setText(value), nothing happens. Is there an easier way of accomplishing this task – namely updating the textView through user input?
Here is the bit of code I cannot make work:
public class SettingsActivity extends AppCompatActivity
{
private TextView player1View;
private TextView player2View;
private SharedPreferences.OnSharedPreferenceChangeListener listener;
#Override
protected void onCreate(Bundle savedInstanceState)
{
player1View = findViewById(R.id.player1);
player2View = findViewById(R.id.player2);
super.onCreate(savedInstanceState);
getSupportFragmentManager().beginTransaction().replace(android.R.id.content, new SettingsFragment()).commit();
createListener();
}
private void createListener()
{
listener = new SharedPreferences.OnSharedPreferenceChangeListener()
{
#Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key)
{
EditTextPreference etp = (EditTextPreference) sharedPreferences;
String value = sharedPreferences.getString("player_one", "NULL");
switch(key)
{
case "switch_setting1":
//Do something
break;
case "player1_key":
player1View.setText(value);
break;
case "player2_key":
player2View.setText(value);
break;
}
}
};
PreferenceManager.getDefaultSharedPreferences(getApplicationContext())
.registerOnSharedPreferenceChangeListener(listener);
}
}
The screenshots below should emphasize more clearly what i mean. The fields I want to change are the ones named "Player 1" and "Player 2", and to accomplish that the user inputs new names through settings as shown.
Screenshots from the Android Emulator
Try maybe instead of:
String value = sharedPreferences.getString("player_one", "NULL");
This:
String value = sharedPreferences.getString("player_one", null);
or you might want to create two String variables(value, value2 for example), one for "player_one" and the other for "player_two" if you have forgot to add. I don't know exactly what you are trying to build.
I want to store selected checkbox values in ArrayList. There is five checkbox if I select three then they will store on ArrayList. I used String []ad = new String[5]; is it write on not to store the value of checkbox
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
List<String> mList = new ArrayList<>();
CheckBox android, java, python, php, unity3D;
Button submitButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
android = (CheckBox) findViewById(R.id.androidCheckBox);
android.setOnClickListener(this);
java = (CheckBox) findViewById(R.id.javaCheckBox);
java.setOnClickListener(this);
python = (CheckBox) findViewById(R.id.pythonCheckBox);
python.setOnClickListener(this);
php = (CheckBox) findViewById(R.id.phpCheckBox);
php.setOnClickListener(this);
unity3D = (CheckBox) findViewById(R.id.unityCheckBox);
unity3D.setOnClickListener(this);
submitButton = (Button) findViewById(R.id.submitButton);
submitButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Log.e("ArrayList Values*******",mList.toString());
}
});
}
#Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.androidCheckBox:
if (android.isChecked()) {
mList.add(String.valueOf(android.getText()));
Log.e("Android*******",mList.toString());
}
break;
case R.id.javaCheckBox:
if (java.isChecked()) {
mList.add(String.valueOf(java.getText()));
Log.e("Java*******",mList.toString());
}
break;
case R.id.phpCheckBox:
if (php.isChecked()) {
mList.add(String.valueOf(php.getText()));
Log.e("PHP*******",mList.toString());
}
break;
case R.id.pythonCheckBox:
if (python.isChecked()){
mList.add(String.valueOf(python.getText()));
Log.e("Python*******",mList.toString());
}
break;
case R.id.unityCheckBox:
if (unity3D.isChecked()){
mList.add(String.valueOf(unity3D.getText()));
Log.e("Unity*******",mList.toString());
}
break;
}
}
}
Just create a List and add values when your click events are fired:
final List<String> mList = new ArrayList<>();
mList.add("Your value");
Note: consider to implement onCheckChangeListener intead of onClickListener to handle your checkbox selection events.
No, it's not quite correct.
I strongly recommend creating the array when the user presses submitButton. Otherwise, if they check some boxes, and either
Rotate the screen, or
Put the app in the background and the Activity gets destroyed by the system (You can simulate this by selecting the "Don't keep Activities" option in Developer Options)
When they see your UI again, it will be correctly re-created - all the boxes the user has checked will still be checked, but your array will be empty! I recommend something like
submitButton = (Button) findViewById(R.id.submitButton);
submitButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String []ad = new String[5];
if (android.isChecked()) {
ad[0] = (String) android.getText();
}
if (java.isChecked()) {
ad[1] = (String) java.getText();
}
...
}
});
If you care about ad outside the context of submitting the user's choices, the best practice is to save it in the Bundle in public void onSaveInstanceState(Bundle outState) {}
and fetch and set it in your onCreate(Bundle savedInstanceState){}. This way you will not loose data even on orientation change, or on the system destroying your Activity. See this answer for details on how to do that.
Of late I was just trying to create a mems geneator app, yes I had been following the new bostons and in that buckey created them using 2 fragments and here i just want to do in a single main activity, but I just can't figure out how to retrieve the text from the edit text field and set the text of Text view to it. I know it's pretty a newbie question but still I don't know how to code it so please help...
I had just imported some widgets,views,etc and done some modified the on create function and my on create function is:
public class MainActivity extends AppCompatActivity {
public static EditText topText;
public static EditText bottomtext;
public static TextView top;
public static TextView bottom;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
topText = (EditText) findViewById(R.id.topedit);
bottomtext = (EditText) findViewById(R.id.bottomedit);
top = (TextView) findViewById(R.id.top);
bottom = (TextView) findViewById(R.id.bottom);
Button myButton = (Button) findViewById(R.id.button);
myButton.setOnClickListener(
new Button.OnClickListener() {
public void onClick(View V) {
top.setText((CharSequence) topText);
bottom.setText((CharSequence) bottomtext);
}
}
);
}
Simply do this:
if(topText.getText()!=null){
top.setText(topText.getText().toString());
}
if(bottomtext.getText()!=null){
bottom.setText(bottomtext.getText().toString());
}
Try this to get text of the EditText field:
CharSequence text = topText.getText();
And set the text above for the textView:
top.setText(text);
Use this short example to understand the concept
store=ret.getText().toString();
show.setText(store);
Explanation
ret: is the name of the edit text field;
store: is used to hold anything gotten from ret (text field)
show.setText(store) displays the result in the textview
This question has already been answered:
"Use getText() on your EditText object".
Get Value of a Edit Text field
Next time do a quick search ;)
Can anyone help me work out where I'm going wrong here. On the button click the media player plays one of the mfiles at random and I'm trying to set a textview depending on which file was played. Currently the setText if statements only match the audio playing half the time. Really not sure where I'm going wrong here.
private final int SOUND_CLIPS = 3;
private int mfile[] = new int[SOUND_CLIPS];
private Random rnd = new Random();
MediaPlayer mpButtonOne;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mfile[0] = R.raw.one;
mfile[1] = R.raw.two;
mfile[2] = R.raw.three;
//Button setup
Button bOne = (Button) findViewById(R.id.button1);
bOne.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final TextView textOne = (TextView)findViewById(R.id.textView1);
mpButtonOne = MediaPlayer.create(MainActivity.this, mfile[rnd.nextInt(SOUND_CLIPS)]);
if (mpButtonOne==null){
//display a Toast message here
return;
}
mpButtonOne.start();
if (mfile[rnd.nextInt(SOUND_CLIPS)] == mfile[0]){
textOne.setText("one");
}
if (mfile[rnd.nextInt(SOUND_CLIPS)] == mfile[1]){
textOne.setText("two");
}
if (mfile[rnd.nextInt(SOUND_CLIPS)] == mfile[2]){
textOne.setText("three");
}
mpButtonOne.setOnCompletionListener(new soundListener1());
{
}
So just to clarify the problem I am having is that the setText only matches the audio occasionally, not on every click. The rest of the time it displays the wrong text for the wrong audio.
You are choosing another random file
mfile[rnd.nextInt(SOUND_CLIPS)]
set that to a variable in onClick() then check against that variable in your if statement
public void onClick(View v) {
int song = mfile[rnd.nextInt(SOUND_CLIPS)];
final TextView textOne = (TextView)findViewById(R.id.textView1);
mpButtonOne = MediaPlayer.create(MainActivity.this, song);
if (song == mfile[0]){
textOne.setText("one");
}
Edit
To make it a member variable so you can use it anywhere in the class, just declare it outside of a method. Usually do this before onCreate() just so all member variables are in the same place and it makes your code more readable/manageable.
public class SomeClass extends Activity
{
int song;
public void onCreate()
{
// your code
}
then you can just initialize it in your onClick()
public void onClick(View v) {
song = mfile[rnd.nextInt(SOUND_CLIPS)];
final TextView textOne = (TextView)findViewById(R.id.textView1);
mpButtonOne = MediaPlayer.create(MainActivity.this, song);