Select editText view contents randomly from stored array - java

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.

Related

access to dynamic layout

I have created dynamic layouts, but I don't know how to access their information,search on the interent and I got to this code, but it does not enter the first if
Button add, send,delete;
EditText size;
LinearLayout list, list2,list3;
ArrayList<String> text = new ArrayList<>();
Context context;
#SuppressLint("MissingInflatedId")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
add = findViewById(R.id.add);
size = findViewById(R.id.size);
send = findViewById(R.id.send);
list =findViewById(R.id.list);
list2 =findViewById(R.id.list2);
list3 =findViewById(R.id.list3);
delete = findViewById(R.id.delete);
context = this;
//Toast.makeText(context,""+et.getText().toString(),Toast.LENGTH_SHORT).show();
send.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Log.e("tag","4444444");
for (int i = 0; i<4-list.getChildCount(); i++){
Log.e("tag","555555");
if (list.getChildAt(i) instanceof LinearLayoutCompat) {
Log.d("tag","333333");
LinearLayoutCompat ll = (LinearLayoutCompat) list.getChildAt(i);
for (int j = 0; j < ll.getChildCount() ; j++) {
Log.d("tag","77777");
if(ll.getChildAt(j) instanceof EditText)
{
Log.d("tag","22222222");
EditText et = (EditText) ll.getChildAt(j);
if(et.getId() == R.id.size){
Log.d("tag","1111111");
Toast.makeText(context,""+et.getText().toString(),Toast.LENGTH_SHORT).show();
}
}
}
}
}
}
});
add.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view){
addView();
}
});
}
what I expected was that in the for it would print the values ​​that I enter in my textView through the toast

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

How to move between the elements of recyclerview inside its adapters

I couldn't phrase the question perfectly with my problem, but basically what I want to achieve is this:-
I have recyclerview of items that contains textview for example, when the item is clicked; a custom dialog will show containing the same content of the clicked element.
so far so good, in the same dialog there's two arrow (left & right) at each of its sides, the arrows buttons should navigate between the recyclerview items and update the content according to the new position.
Here's what I did:
#Override
public void onBindViewHolder(final ViewHolder holder, final int position) {
holder.tvTitle.setText(data.get(position).getTitle());
holder.itemView.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
//Initializing the custom dailog
final Dialog dialog = new Dialog(context);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.getWindow() .setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT));
dialog.getWindow().getAttributes().gravity = Gravity.TOP;
dialog.setContentView(R.layout.dailog);
dialog.show();
ImageView RightArrow = (ImageView) dialog.findViewById(R.id.dia_right_arrow);
ImageView LeftArrow = (ImageView) dialog.findViewById(R.id.dia_left_arrow);
final TextView textViewTitle = (TextView) dialog.findViewById(R.id.dia_tvTtile);
textViewTitle.setText(data.get(position).getTitle());
RightArrow.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int curPosi = 0;
if (data.size() != 0) {
curPosi = position+1;
}
textViewTitle.setText(data.get(position).getTitle());
}
});
LeftArrow.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int curPosi = 0;
if (data.size() != 0) {
curPosi = position-1;
}
textViewTitle.setText(data.get(position).getTitle());
} });
}});
}
The Result:
When I click on the right arrow it works 100% , but if I click again nothing happens !!
And If click the left arrow at anytime it gives crash with this exception:
java.lang.ArrayIndexOutOfBoundsException: length=10; index=-1
Is it possible to achieve a loop effect, what I mean is when I reach
the last index and the click again it shows the first index and vice
versa..!
Any help?
It seems the issue is from how you check your click limits. You can try this
Add curPosi as a class member variable
private int curPosi;
#Override
public void onBindViewHolder(final ViewHolder holder, final int position) {
holder.tvTitle.setText(data.get(position).getTitle());
holder.itemView.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
curPosi = position
//Initializing the custom dailog
final Dialog dialog = new Dialog(context);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.getWindow() .setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT));
dialog.getWindow().getAttributes().gravity = Gravity.TOP;
dialog.setContentView(R.layout.dailog);
dialog.show();
ImageView RightArrow = (ImageView) dialog.findViewById(R.id.dia_right_arrow);
ImageView LeftArrow = (ImageView) dialog.findViewById(R.id.dia_left_arrow);
final TextView textViewTitle = (TextView) dialog.findViewById(R.id.dia_tvTtile);
textViewTitle.setText(data.get(position).getTitle());
RightArrow.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int lastIndex = data.size()-1;
if (lastIndex == curPosi ) { // this prevents the crash, so if the next button is clicked while the last index is showing it will reset and show the first one..!
curPosi = 0;
} else if(curPosi < data.size()) {
curPosi++;
}
textViewTitle.setText(data.get(curPosi).getTitle());
}
});
LeftArrow.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//same thing here with this "if", when the previous button clicked from the first; it will show the last item..!
if (curPosi == 0) {
curPosi = data.size();
}
if (curPosi > 0) {
curPosi--;
}
textViewTitle.setText(data.get(curPosi).getTitle());
} });
}});
}

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

Clicking Elements in Android Doesn't Display the Correct Values

I apologize if this code looks a bit like a mess (considering the length); I figured I'd just include everything that goes on in my program at the moment.
I'm attempting to create a fairly simple Tic Tac Toe app for Android. I've set up my UI nicely so far so that there are a "grid" of TextViews. As a sort of "debug" right now, I have it so that when one clicks on a TextView, it should display the value of buttonId in a message box. Right now, it displays the correct assigned value for the first element I click, but no matter what I click afterwards, it always just displays the first value buttonID had. I attempted to debug it but couldn't exactly find a point where it would pull the old value (to the best of my knowledge, it reassigned the value).
There's a good possibility I'm missing something small, because this is my first Android project (of any note). Can someone help get different values of buttonId to appear or point out the error in my logic?
The code:
package com.TicTacToe.app;
import com.TicTacToe.app.R;
//Other import statements
public class TicTacToe extends Activity {
public String player = "X";
public int ALERT_ID;
public int buttonId;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//Sets up instances of UI elements
final TextView playerText = (TextView)findViewById(R.id.CurrentPlayerDisp);
final Button button = (Button) findViewById(R.id.SetPlayer);
final TextView location1 = (TextView)findViewById(R.id.location1);
final TextView location2 = (TextView)findViewById(R.id.location2);
final TextView location3 = (TextView)findViewById(R.id.location3);
final TextView location4 = (TextView)findViewById(R.id.location4);
final TextView location5 = (TextView)findViewById(R.id.location5);
final TextView location6 = (TextView)findViewById(R.id.location6);
final TextView location7 = (TextView)findViewById(R.id.location7);
final TextView location8 = (TextView)findViewById(R.id.location8);
final TextView location9 = (TextView)findViewById(R.id.location9);
playerText.setText(player);
//Handlers for events
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Perform action on click
if (player.equals("X")){
player = "O";
playerText.setText(player);
}
else if(player.equals("O")){
player = "X";
playerText.setText(player);
}
//Sets up the dialog
buttonId = 0;
ALERT_ID = 0;
onCreateDialog(ALERT_ID);
showDialog(ALERT_ID);
}
});
location1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Sets up the dialog
buttonId = 1;
ALERT_ID = 0;
onCreateDialog(ALERT_ID);
showDialog(ALERT_ID);
}
});
location2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Sets up the dialog
buttonId = 2;
ALERT_ID = 0;
onCreateDialog(ALERT_ID);
showDialog(ALERT_ID);
}
});
location3.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Sets up the dialog
buttonId = 3;
ALERT_ID = 0;
onCreateDialog(ALERT_ID);
showDialog(ALERT_ID);
}
});
location4.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Sets up the dialog
buttonId = 4;
ALERT_ID = 0;
onCreateDialog(ALERT_ID);
showDialog(ALERT_ID);
}
});
location5.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Sets up the dialog
buttonId = 5;
ALERT_ID = 0;
onCreateDialog(ALERT_ID);
showDialog(ALERT_ID);
}
});
location6.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Sets up the dialog
buttonId = 6;
ALERT_ID = 0;
onCreateDialog(ALERT_ID);
showDialog(ALERT_ID);
}
});
location7.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Sets up the dialog
buttonId = 7;
ALERT_ID = 0;
onCreateDialog(ALERT_ID);
showDialog(ALERT_ID);
}
});
location8.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Sets up the dialog
buttonId = 8;
ALERT_ID = 0;
onCreateDialog(ALERT_ID);
showDialog(ALERT_ID);
}
});
location9.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Sets up the dialog
buttonId = 9;
ALERT_ID = 0;
onCreateDialog(ALERT_ID);
showDialog(ALERT_ID);
}
});
}
protected Dialog onCreateDialog(int id){
String msgString = "You are on spot " + buttonId;
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage(msgString)
.setCancelable(false)
.setNeutralButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog alert = builder.create();
return alert;
}
}
You shouldn't be calling onCreateDialog() yourself. Android does that for you when you call showDialog().
I'm sure it only calls onCreateDialog() once and caches the value internally, which is why you're only getting the correct value the first time, and then getting the same value for the rest.
You'll have to think of another way to do what you're trying to do. Perhaps passing a different ID to showDialog() (be sure to handle that ID by creating the correct dialog in onCreateDialog()) is the way to go.
Also, don't import R manually.

Categories

Resources