App which displays List does not work - java

I try to make an App with button which after the push will display all elements from list in editText.
But I have a problem, currently after I push the button I see only "second" in editText
In my opinion I need a tips from you about how to do it. Maybe I shouldn't use a loop ?
public class MainActivity extends AppCompatActivity {
private Button button;
private EditText editText;
private ArrayList<String> list = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = (Button) findViewById(R.id.button);
editText = (EditText) findViewById(R.id.editText);
list.add(0, "first");
list.add(1, "second");
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
for (String abc: list){
editText.setText(abc);
}
}
});
}
}
____ edit
public class MainActivity extends AppCompatActivity {
private Button button;
private EditText editText;
private ArrayList<String> list = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = (Button) findViewById(R.id.button);
editText = (EditText) findViewById(R.id.editText);
list.add(0, "first");
list.add(1, "second");
list.add(2, "3");
list.add(3, "4");
list.add(4, "5");
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String final_text = "";
for (String abc: list){
final_text = final_text + "\n" + abc;
}
editText.setText(final_text);
}
});
}
}
enter image description here

You are overwriting the text in editText. Accumulate the strings from the list and do a setText outside the loop:-
#Override
public void onClick(View v) {
String final_text ="";
for (String abc: list){
final_text = final_text +"\n" + abc;
}
editText.setText(final_text);
}

On this loop you will always get the last string of the list into the edittext
for (String abc: list){
editText.setText(abc);
}
You need to create multiple edittext to add multiple value from your list, or else you need to compile all value from list to one string like #Zakir has propose.

Related

When adding Values to Arraylist from one class to another, Listview does not display updated values

I am having one Array list in Class-A and two textfields one from Class-A and other from Class-B,
While adding values to Array List through Class-A textfield it works fine for me,
and when trying to add from Class-B textfield, it gets added to Array list but does not display the updated list in the listview(Blank)
Below is the code i have tried till now
Class-A :-
public static ArrayList<String> arrayList = new ArrayList<>();
ArrayAdapter<String> arrayAdapter;
ListView listView;
EditText quickTask;
Button addButton;
Button moreButton;
public static ArrayList<String> addToList( String i ) {
arrayList.add(i);
return arrayList;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
quickTask = (EditText) findViewById(R.id.quicktaskeditText);
listView = (ListView) findViewById(R.id.TasksListView);
arrayAdapter = new ArrayAdapter<String>(ClassA.this, android.R.layout.simple_list_item_1,arrayList);
addButton = (Button) findViewById(R.id.Addbutton);
addButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String task = quickTask.getText().toString();
arrayList.add(task);
listView.setAdapter(arrayAdapter);
arrayAdapter.notifyDataSetChanged();
}
});
moreButton = (Button) findViewById(R.id.moreButton);
moreButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent secondActIntent = new Intent(getApplicationContext(),ClassB.class);
startActivity(secondActIntent);
}
});
}
Class-B :-
EditText Title;
Button AddButton;
ArrayList<String> alist;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
Title = (EditText) findViewById(R.id.Title);
AddButton = (Button) findViewById(R.id.secondAddButton);
AddButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String task = Title.getText().toString();
//Adding text to Class-A arraylist
alist = ClassA.addToList(task);
Intent startIntent = new Intent(getApplicationContext(),ClassA.class);
startActivity(startIntent);
}
});
}
Because you don't notify ListView that contents of ArrayList changed.
You have notifyDataSetChanged only in button listener. You need to add it in Class-A#onResume or in addTolist.

How can you make a random not repeat it self?

I'v created a list of strings which I choose randomly to display, and so I want to make it that it won't repeat its self. How can I do that.
public class qustionsActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_qustions);
final String[] questions = getResources().getStringArray(R.array.coupleQuestions);
final String randomQuestions = questions[new Random().nextInt(questions.length)];
final TextView theQuestion = findViewById(R.id.theQustion);
theQuestion.setText(randomQuestions);
Button nextQuestion = findViewById(R.id.nextQuestion);
nextQuestion.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String randomQuestions = questions[new Random().nextInt(questions.length)];
theQuestion.setText(randomQuestions);
}
});
}
The reason that I have two "randomQuestions" string is because I want a question to display as soon as you get into the activity and that on the click of a button it will randomise a new string.
Instead of everytime randomizing the pick, you can randomly shuffle the questions and sequentially take the next (random) question.
private final List<String> randomQuestions;
private int questionI;
// Cycling endlessly
private String nextQuestion() {
String question = randomQuestions.get(questionI);
++questionI;
if (questionI > randomQuestions.size()) {
questionI = 0;
}
}
// Once through the list:
private String nextQuestion() {
return randomQuestions.remove(0); // Always take the first, removing it.
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_qustions);
final String[] questions = getResources().getStringArray(R.array.coupleQuestions);
randomQuestions = Collections.shuffle(Arrays.asList(questions));
Maybe you can create a list where you put the list of existing number like :
public class qustionsActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_qustions);
int a=new Random().nextInt(questions.length);
final String[] questions = getResources().getStringArray(R.array.coupleQuestions);
ArrayList<Integer> existingNumber=new ArrayList<>();
final String randomQuestions = questions[a];
existingNumber.add(a);
final TextView theQuestion = findViewById(R.id.theQustion);
theQuestion.setText(randomQuestions);
Button nextQuestion = findViewById(R.id.nextQuestion);
nextQuestion.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
do{
a=new Random().nextInt(questions.length);
}while(!existingNumber.add(a))
String randomQuestions = questions[a];
theQuestion.setText(randomQuestions);
}
});
}
public class qustionsActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_qustions);
final String[] questions = getResources().getStringArray(R.array.coupleQuestions);
final int index = new Random().nextInt(questions.length);
final String randomQuestions = questions[index];
questions[index] = questions[questions.length-1];
final TextView theQuestion = findViewById(R.id.theQustion);
theQuestion.setText(randomQuestions);
Button nextQuestion = findViewById(R.id.nextQuestion);
nextQuestion.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String randomQuestions = questions[new Random().nextInt(questions.length-1)];
theQuestion.setText(randomQuestions);
}
});
}
Use ArrayList to store your questions and after every retrieval of a question from a random index value, remove the same from ArrayList
Below is the code:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
metadata = getIntent().getStringExtra("metadata");
final ArrayList<String> questions = new ArrayList<String>(Arrays.asList(getResources().getStringArray(R.array.questions)));
int i=new Random().nextInt(questions.size());
final String randomQuestions = questions.get(i);
questions.remove(i);
final TextView theQuestion = findViewById(R.id.theQustion);
theQuestion.setText(randomQuestions);
Button nextQuestion = findViewById(R.id.nextQuestion);
nextQuestion.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(questions.size()==0) //To make sure we don't access the empty ArrayList
{
theQuestion.setText("End of questions");
return;
}
int i=new Random().nextInt(questions.size());
String randomQuestions =questions.get(i);
questions.remove(i);
theQuestion.setText(randomQuestions);
}
});
}

How to create EditText & Button so that EditText should take new input whenever button is pressed storing prev value?

What i did exactly is that user provides input in the EditText and it gets stored in the arrray and later when the button is pressed it clears the field
and now i incremented "number" but when i click button it always takes the previous value of "number". How can i send my incremented value of "number" in OnCreate?
so that whenever i click the button it should take incremented value of "number".
Thanks in Advance!
I tried using for loop it goes endlessly i.e it crashes.pls, help.
public class thirdactivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_thirdactivity);
Intent intent1 = getIntent();
final int no = intent1.getIntExtra(MainActivity.EXTRA_NUMBER4, 0);
Button Next = (Button)findViewById(R.id.button2);
Next.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
validate(no);
}
});
}
public void validate(int number){
/**
*created an Array to store the value
*/
int DLPoints[] = new int[number];
/**
*taking inptut from user and store in userDLPV
*/
EditText editText1 = (EditText) findViewById(R.id.points);
int userDLPV = Integer.parseInt(editText1.getText().toString());
DLPoints[number] = userDLPV;
editText1.setText("");
number++
}
}
public class thirdactivity extends AppCompatActivity {
ArrayList<Integer> userInput = new ArrayList();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_thirdactivity);
Intent intent1 = getIntent();
int no = intent1.getIntExtra(MainActivity.EXTRA_NUMBER4, 0) + 1;
Button Next = (Button)findViewById(R.id.button2);
Next.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
validate(no);
}
});
}
public void validate(int number){
/**
*taking input from user and store in userDLPV
*/
EditText editText1 = (EditText) findViewById(R.id.points);
editText1.setText("" + number);
userInput.add(number);
}
}

Select editText view contents randomly from stored array

Basically what I am trying to accomplish is storing editText view Strings in an array and returning the value of a randomly selected array element. The editText views can be dynamically added and removed so I had to take that into account. I've gone over my method and cannot find what I'm getting wrong.
the problem is is getAnswer(). Currently this is crashing the app
Java:
public class MainActivity extends AppCompatActivity {
private LinearLayout mEditTextContainer;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mEditTextContainer = (LinearLayout)findViewById(R.id.linearLayoutDecisions);
setContentView(activity_main);
//Button to choose random editText contents
final Button button = (Button) findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
getAnswer();
}
});
//Button to add editText Field
final Button add_button = (Button) findViewById(R.id.add_button);
add_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Add_Line();
}
});
//Button to remove editText Field
final Button remove_button = (Button) findViewById(R.id.remove_button);
remove_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Remove_Line();
}
});
}
public void Add_Line() {
LinearLayout ll = (LinearLayout)findViewById(R.id.linearLayoutDecisions);
// add edittext
EditText et = new EditText(this);
LinearLayout.LayoutParams p = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.WRAP_CONTENT);
et.setLayoutParams(p);
et.setText(null);
et.setHint("Enter Answer #" + (mEditTextContainer.getChildCount()+1));
et.setGravity(Gravity.CENTER);
mEditTextContainer.addView(et);
}
public void Remove_Line() {
int count = mEditTextContainer.getChildCount();
if(count == 2)
return;
else
mEditTextContainer.removeViewAt(mEditTextContainer.getChildCount()-1);
}
public void getAnswer() {
//get number of possible answers
int count = mEditTextContainer.getChildCount();
//create array to hold answers
String[] options = new String[count--];
//create temporary view to store editText view contents
View tempView;
//Loop to collect and store editText contents
for(int i = 1; i < count-1; i++) {
tempView = mEditTextContainer.getChildAt(i);
if(tempView instanceof EditText){
String tempText = ((EditText) tempView).getText().toString();
if(tempText != null){
options[i] = tempText;
}
else
return;
}
}
int number = (int)(Math.random() * count-1);
String answer = options[number];
TextView answerBox = (TextView)findViewById(R.id.textView7);
answerBox.setText(answer);
}
}
For anyone curious, I found the answer. The variable 'count' should not have been decremented by 1 in my method. Changing this fixed the whole thing.

unable to match edittext with image name

Learning android by making a simple guessing game, I have set the images in an Arraylist and applied random operation on it, but now I'm confused how to match edit text value with image name so that I can set score.
public class MainActivity extends AppCompatActivity {
private EditText editText;
private Button button;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ArrayList<Integer> list = new ArrayList<Integer>();
ImageView random_image = (ImageView) findViewById(R.id.imageView);
final int[] images = {R.drawable.kung_fu_panda, R.drawable.mr_nobody, R.drawable.toy_story};
list.add(R.drawable.kung_fu_panda);
list.add(R.drawable.mr_nobody);
list.add(R.drawable.toy_story);
int position = new Random().nextInt(list.size());
random_image.setImageResource((Integer) list.get(position));
list.remove(position);
button = (Button) findViewById(R.id.button);
editText = (EditText) findViewById(R.id.editText);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
validateInput();
}
});
}
private void validateInput() {
String input = editText.getText().toString();
}
You can try definition name's array of images, and get the name by random position, and use currentName save the name.
String currentName;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ArrayList<Integer> list = new ArrayList<Integer>();
ImageView random_image = (ImageView) findViewById(R.id.imageView);
final String imageNames = {"kung fu panda", "mr nobody", "toy story"};
list.add(R.drawable.kung_fu_panda);
list.add(R.drawable.mr_nobody);
list.add(R.drawable.toy_story);
int position = new Random().nextInt(list.size());
random_image.setImageResource((Integer) list.get(position));
currentName = imageNames[position];
list.remove(position);
button = (Button) findViewById(R.id.button);
editText = (EditText) findViewById(R.id.editText);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
validateInput();
}
});
}
Then, in your validateInput() method, you can use currentName to compare, notice case, use String.toLowerCase() to format input string.
private boolean validateInput() {
String input = editText.getText().toString();
if(!TextUtils.isEmpty(input)){
input = input..toLowerCase();
if(input.equeals(currentName)){
return true;
}
}
return false;
}

Categories

Resources