Displaying list values with each button click - java

How can i display list items on each button click. Lets say there are 4 names in the list. When I press next it displays the first name. Then when you press next it displays the second name and so on.
The only way I think is using the list.get() method. however I dont know how to use the method so that it knows how many values there are in the list and displaying then on each button hit. I think i need to use for method however I hadnt had any luck with it.
public class ZaidimasActivity extends ZaidejaiActivity {
public TextView mPlayer;
public TextView mKlausimas;
public Button mNext;
public Button mBack;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_zaidimas);
/** //get the player list from ZaidejaiActivity
Bundle recdData = getIntent().getExtras();
String myVal = recdData.getString("playerList"); */
Intent zaidejuInfo = getIntent();
Bundle extrasBundle = zaidejuInfo.getExtras();
final ArrayList<String> players = extrasBundle.getStringArrayList("playerList");
//show the first players name
mPlayer = (TextView)findViewById(R.id.ZaidejoVardas);
players.size();
mPlayer.setText(players.get(0));
mNext = (Button)findViewById(R.id.KitasBtn);
mNext.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mPlayer.setText(players.get(1));
}
});
mBack = (Button)findViewById(R.id.GryztiMeniuBtn);
mBack.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent gryztiMeniu = new Intent(ZaidimasActivity.this, ZaidejaiActivity.class);
startActivity(gryztiMeniu);
}
});
}

Here you go, maintain a variable for storing the global array index and increment it every time the button is clicked.
private int count = 0; // Global array index. Make it as class field
final ArrayList<String> players = extrasBundle.getStringArrayList("playerList");
mPlayer = (TextView)findViewById(R.id.ZaidejoVardas);
players.size();
mPlayer.setText(players.get(0));
mNext = (Button)findViewById(R.id.KitasBtn);
mNext.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
count++;
mPlayer.setText(players.get((count)%players.size())); //Incrementing global count and making sure it never exceeds the players list size
}
});

Related

How can I transfer integer value from one activity to another?

i'm trying to compile 4 integers from 4 different activities. the first activity is one of the 4 integer. the second activity is where i compile them.. I don't know what's the best way to send a value from different activites. Most of the intent methods i saw uses startActivity but still won't work.
public class QuizSecond extends AppCompatActivity implements View.OnClickListener{
TextView totalQuestionsTextView2;
TextView questionTextView2;
Button ansA2, ansB2, ansC2, ansD2;
Button submitBtn2;
int score= 0;
int totalQuestion2 = QuestionAnswer2.question2.length;
int currentQuestionIndex2 = 0;
String selectedAnswer2 = "";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_quiz_second);
totalQuestionsTextView2 = findViewById(R.id.total_question2);
questionTextView2 = findViewById(R.id.question_preview);
ansA2 = findViewById(R.id.ans_A2);
ansB2 = findViewById(R.id.ans_B2);
ansC2 = findViewById(R.id.ans_C2);
ansD2 = findViewById(R.id.ans_D2);
submitBtn2 = findViewById(R.id.submit_btn2);
ansA2.setOnClickListener(this);
ansB2.setOnClickListener(this);
ansC2.setOnClickListener(this);
ansD2.setOnClickListener(this);
submitBtn2.setOnClickListener(this);
totalQuestionsTextView2.setText("Total questions : "+totalQuestion2);
loadNewQuestion();
}
#Override
public void onClick(View view) {
ansA2.setBackgroundColor(Color.WHITE);
ansB2.setBackgroundColor(Color.WHITE);
ansC2.setBackgroundColor(Color.WHITE);
ansD2.setBackgroundColor(Color.WHITE);
Button clickedButton = (Button) view;
if(clickedButton.getId()==R.id.submit_btn2){
if(selectedAnswer2.equals(QuestionAnswer2.correctAnswers2[currentQuestionIndex2])) {
score++;
}
currentQuestionIndex2++;
loadNewQuestion();
Intent quizIntent = new Intent(QuizSecond.this,ComputeActivity.class);
quizIntent.putExtra("EXTRA_NUMBER",score);
}
else{
//choices button clicked
selectedAnswer2 = clickedButton.getText().toString();
clickedButton.setBackgroundColor(Color.MAGENTA);
}
}
void loadNewQuestion(){
if(currentQuestionIndex2 == totalQuestion2 ){
startActivity(new Intent(QuizSecond.this, ComputeActivity.class));
return;
}
questionTextView2.setText(QuestionAnswer2.question2[currentQuestionIndex2]);
ansA2.setText(QuestionAnswer2.choices2[currentQuestionIndex2][0]);
ansB2.setText(QuestionAnswer2.choices2[currentQuestionIndex2][1]);
ansC2.setText(QuestionAnswer2.choices2[currentQuestionIndex2][2]);
ansD2.setText(QuestionAnswer2.choices2[currentQuestionIndex2][3]);
}
}
second activity:
int number = getIntent().getIntExtra("EXTRA_NUMBER",0); if (number > 3){ Toast.makeText(ComputeActivity.this, "Your Message", Toast.LENGHT_LONG).show();}
Update this
Intent quizIntent = new Intent(QuizSecond.this, ComputeActivity.class);
quizIntent.putExtra("TRANSFER_NUMBER", score);
startActivity(quizIntent);

how to call the output of a method in another Activity 's textview?

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.

how to store selected checkbox values in ArrayList

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.

How to get and store multiple genrated edittext value in android?

I am adding multiple Edittext at the click of button. I am also getting the value of these Edittext, but I am unable to store data in array.
EditText textIn;
Button buttonAdd, buttonShow;
LinearLayout container;
List<EditText> allEds = new ArrayList<EditText>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
buttonAdd = (Button)findViewById(R.id.add);
buttonShow = (Button) findViewById(R.id.show);
container = (LinearLayout)findViewById(R.id.container);
buttonAdd.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
LayoutInflater layoutInflater =
(LayoutInflater) getBaseContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
final View addView = layoutInflater.inflate(R.layout.row, null);
EditText editText1 = (EditText) addView.findViewById(R.id.editText1);
EditText editText2 = (EditText) addView.findViewById(R.id.editText2);
allEds.add(editText1);
allEds.add(editText2);
Button buttonRemove = (Button) addView.findViewById(R.id.remove);
buttonRemove.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
((LinearLayout) addView.getParent()).removeView(addView);
}
});
container.addView(addView);
}
});
buttonShow.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
String[] strings = new String[allEds.size()];
for(int i=0; i < allEds.size(); i++){
strings[i] = allEds.get(i).getText().toString();
Log.e("My data", strings[i]);
}
}
});
Here I am getting all value using strings[i], but I want to store value in array like this. [{"Name": "Smith","Age", "26"},{"Name": "Jhon","Age", "30"}]. Here I will get Smith,26 and Jhon, 30 from multiple generated Edittext. Array will be extended after generating more dynamic fields.
Please help me.
You say you have to get it as an array. As I see it, you're already getting it as a String array. What else do you want? The way you're describing the expected result looks like a half-baked json output. Perhaps you can create a class that represents the Person whose info you want and then create an ArrayList of the Person type. Also to make things easier to stuff in the Person object you can declare a constructor that takes name and age as parameter. In your loop you can create a Person object using that constructor and then add that object to the ArrayList.
This would help :
class Person{
String name;
int age;
Person(String name, int age){
this.name=name;
this.age=age;
}
}
Then before going into your loop, declare an ArrayList of type Person
ArrayList<Person>persons=new ArrayList<Person>();
And finally in your loop :
Person temp = new Person(*get the name, get the age*);
persons.add(temp);
And voila!, you have your person ArrayList ready.

Text view if statement not working

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

Categories

Resources