Android button loop - java

I have this code :
private ImageView d1;
private ArrayList<Integer> listaImagenes = new ArrayList<Integer>();
private ArrayList<String> listaFrases = new ArrayList<String>();
private Button button;
private Integer contador = 0;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.rellenarImagenes();
setContentView(R.layout.imagentonas);
d1 = (ImageView) findViewById(R.id.imagenes01);
while (contador < listaImagenes.size()) {
d1.setImageResource(listaImagenes.get(contador));
button = (Button) findViewById(R.id.botoncillo);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
contador++;
}
});
}
}
private void rellenarImagenes() {
listaImagenes.add(R.drawable.a01);
listaImagenes.add(R.drawable.a02);
listaImagenes.add(R.drawable.a03)
}
I am trying do a loop that when I press the button , increment contador and d1 change image.
but it is not working, application background remains black and not working.

remove while loop and setimage in onclick method.

You are expecting that modifying the value of the variable contador would result in the array item to change.
Keep in mind that in the code line d1.setImageResource(listaImagenes.get(contador));, the get function receives an int. So at the time where it's called it receives a value, not a reference to an Integer. When you change the value of contador, the value that was used to obtain the index in the array is not changed.
And even if the value did change, d1 would still be using the same resource.
What you need to do in the onClickListener is add the code to set the image. Something along the lines of
public void onClick(View v) {
++contador;
if (contador >= listaImagenes.size())
{
contador=0;
}
//you'll probably need to modify the next line to be able to access the button variable.
//one way to do it is to use a final variable in the onCreate method that creates this OnClickListener
button.setImageResource(listaImagenes.get(contador));
}
The while loop is not needed. What your code is doing is setting the image to the 3 items of the array, one after the other, and adding a new click listener 3 times.

I will try to answer and point some of the flaws you have in the code.
wat if there were 100 drawable like R01 ,R02...? Instead you can use getting drawable using string.
why are you using while loop ? since you have the counter you can directly use that.
Let me try to write the code
int contador=1;
#Override
public void onCreate (Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.imagentonas);
context=this;
d1=(ImageView)findViewById(R.id.imagenes01);
button=(Button)findViewById(R.id.botoncillo);
button=(Button)findViewById(R.id.botoncillo);
button.setOnClickListener( new View . OnClickListener () {
public void onClick ( View v ) {
int id = context.getResources().getIdentifier("a"+contador,
"drawable", context.getPackageName());
d1.setImageResource(id);
contador++;
}
});
}
Notice : int id = context.getResources().getIdentifier("a"+contador,"drawable", context.getPackageName()); Here using the string you can access the drawable this solves the issue for any number of consecutive drawables.
Hope you get the concept...
Thanks

Related

Why does for loop not work in setText Method

I am trying to create a repeating text app. So I use a for loop for repeating the text and display this text in a textview.
When I press a button then I want it to generate the text as many times as the loop runs.
Here is my code:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
enterText = findViewById(R.id.editText);
repeatText = findViewById(R.id.repeatTime);
genTxt = findViewById(R.id.genText);
genrate = findViewById(R.id.generate);
reset = findViewById(R.id.reset);
copy = findViewById(R.id.copyButton);
share = findViewById(R.id.shareButton);
genrate.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Storing text in Gen Text Area
String txt = enterText.getText().toString().trim();
//Storing Repeat value
String repeats = repeatText.getText().toString().trim();
int repealVal = Integer.parseInt(repeats);
for(int i=1;i<=repealVal;i++){
genTxt.setText(txt);
Log.d("tets","loop "+i+txt);
}
}
});
}
public void reset(View view){
enterText.setText("");
repeatText.setText("");
genTxt.setText("");
}
When I run it I only get the text one time in my textview.
Try changing your onClick method to the following:
genrate.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Storing text in Gen Text Area
String txt = enterText.getText().toString().trim();
//Storing Repeat value
String repeats = repeatText.getText().toString().trim();
int repealVal = Integer.parseInt(repeats);
for(int i=1;i<=repealVal;i++){
genTxt.setText(genTxt.getText() + txt);
Log.d("tets","loop "+i+txt);
}
}
});
Note that inside the loop you are only switching the text, not adding to the text.
To even further optimize solution, you should consider using .append() instead of .setText()
Here you are setting text to same TextView again and again.
If you want to dynamically generate multiple TextViews you can try below solution.
Give an id to your root layout in xml where you want to add text. Here I am using LinearLayout. Add it in your code as below:
LinearLayout linearLayout = findViewById(R.id.ll) //ll is the id of LinearLayout
Then add this in your onclick
TextView txtView;
for(int i = 1; i <= repealVal; i++) {
txtView = new TextView(MainActivity.this);
txtView.setText(txt);
linearLayout.addView(txtView);
}

How to take inputs in multiple textviews?

i am new to development. i am creating an android calculator app with advanced functionality.The thing is i am using text view for taking and displaying inputs/outputs. My question is, how can i take Multiple inputs in multiple Textviews.
For example i have 3 text views,when user will enter 1st input in first textview(by default) and when user press the specific button it moves automatically to next textview . In some cases i want to take 2 inputs and in some cases i want to take 3 ,
How can i achieve this
Note: I dont want to use edit text , coz all buttons of already available in my app.Using Edit text will make softkeyboard to appear, and then for hiding the softkeyboard, i need to use hiding code lines in every class
You can do something like following:
private TextView[] textViews;
private TextView tvCurrentEditing;
private Button btnNext;
private Button btnPrev;
private Button btnSetText;
private int index = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
textViews = new TextView[3];
//Initialize all your textviews like textViews[0] = findViewById(<textview-id1>);
//textViews[1] = findViewById(<textview-id2>);
//textViews[2] = findViewById(<textview-id3>);
tvCurrentEditing = textViews[index];// I am assuming this is your first
//initialzie btnSettext
btnSettext.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
tvCurrentEditing.setText("<what ever you want");
}
});
//initialize next buton
btnNext.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(index < textViews.length) {
index++;
}
tvCurrentEditing = textViews[index];
}
});
//Initialize previous button
btnPrev.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(index > 0) {
index--;
}
tvCurrentEditing = textViews[index];
}
});
}
The names of the views could be different. The point is always use tvCurrentEditing whenever you want to change data of TextView. And update tvCurrentEditing whenever needed.

changing text on textview with button's onClickListener

Hi I'm working at my first bigger app in android studio "FlashCards". I would like it to work so after you click on the button the flashcard's textview changes its text to next random flashcard untill you see all of the them how can i do something like 'continue' to my loop from inside onClick method.
here's the loop's code:
while(i < mTestDeck.size()) {
// generates random number which will represent position in deck.
int random = randomGenerator.nextInt() % mTestDeck.size();
// if random flashcard was already shown create random number again
if (mTestDeck.get(random).wasShown())
continue;
//text view that we will operate on
TextView deckTextView = (TextView) findViewById(R.id.flashcard_text_view);
// set text
deckTextView.setText(mTestDeck.get(random).getFront());
// set mWasShown to true
mTestDeck.get(random).flashcardShown();
Button myButton = (Button) findViewById(R.id.know_answer);
myButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
mTestDeck.correctAnswer();
}
});
myButton = (Button) findViewById(R.id.dont_know_answer);
myButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
}
});
}
}
First, this way, you have a potential infinite loop. And if it can happens, it will happens! It's not a good idea to "get random item and check if it's ok or try again".
I think that it's better to keep a list with all items in a random order. You just have to iterate over it.
Something like:
int currentPosition = 0;
List<Card> items = new ArrayList<Card>(mTestDeck).shuffle();
// Call this method once in onCreate or anywhere you initialize the UI
private void function setCurrentCard() {
Card currentItem = items.get(currentPosition);
[...] // Set all UI views here
myButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (currentPosition > items.size) {
// TODO? End?
return;
}
currentPosition++;
setCurrentCard();
}
});
}

How to identify which `view` has been clicked?

Look at following android code. IMGS is a 2 dimensional array of ImageView. I am adding onClickListener to it in a for loop. How to identify which view has been clicked ? I dont want to iterate over all the 36 elements using view.getId();.
private static final Integer[] Icons = {
R.drawable.r,
R.drawable.re,
R.drawable.u,
R.drawable.et,
R.drawable.w,
R.drawable.ya
};
private ImageView[][] IMGS= new ImageView[6][6];
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
IMGS[0][0] = (ImageView) findViewById(R.id.immg11);
for (int i=0; i < 6; i++)
{
for (int j=0; j<6; j++)
{
Drawable d = getResources().getDrawable(Icons[i]);
IMGS[i][j].setImageDrawable(d);
IMGS[i][j].setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
//HOW TO KNOW WHICH VIEW HAS BEEN CLICKED ?
}
});
}
}
}
Notice the View argument passed to onClick(View v)? It's the view that was clicked.
You can call v.getId() to retrieve its id.
Agreed, but there are 36 elements over which i have to iterate if I use this method. Is there a way to know the indexes of clicked IMGS ?
You can use setTag() to save whatever data you want in each view and retrieve it later with getTag().

How do I get this string array to pass over to the next class and be used

This is kind of hard to explain. Basically it's kind of like a simple game. I want the people to input their names (currently the submit button is not working correctly) hit submit for each name and when all names are in they hit play. It then opens up the next class. It needs to get the string array from the prior class as well as the number of players. It then needs to select each persons name in order and give them a task to do (which it randomly generates). Then it allows the other people to click a button scoring how they did. (I am not sure how to set up the score system. Not sure if there is a way to assign a score number to a particular array string) I would then like it after 5 rounds to display the winner. If you have any input or could help me out I would be extremely grateful. Thanks for taking the time... here are the two classes i have.
Class 1
public class Class1 extends Activity
{
int players=0;
String names[];
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.class1);
final EditText input = (EditText) findViewById(R.id.nameinput);
Button submitButton = (Button) findViewById(R.id.submit_btn);
submitButton.setOnClickListener(new View.OnClickListener()
{
public void onClick(View submit1)
{
players++;
for(int i=0; i < players; i++)
{
names[i] = input.getText().toString();
input.setText("");
}
}
});
Button doneButton = (Button) findViewById(R.id.done_btn);
doneButton.setOnClickListener(new View.OnClickListener()
{
public void onClick(View done1)
{
Intent done = new Intent(Class1.this, Class2.class);
done.putExtra("players", players);
done.putExtra("names", names[players]);
startActivity(done);
}
});
}
Class 2
public class Class2 extends Activity
{
int players, counter, score, ptasks,rindex;
String[] names, tasks;
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.class2);
Intent game = getIntent();
players = game.getIntExtra("players", 1);
names = game.getStringArrayExtra("names");
Random generator = new Random();
tasks[0]= "task1";
tasks[1]= "task2";
tasks[2]= "task3";
tasks[3]= "task4";
tasks[4]= "task5";
tasks[5]= "task6";
tasks[6]= "task7";
tasks[7]= "task8";
tasks[8]= "task9";
tasks[9]= "task10";
while (counter <5)
{
for (int i = 0; i < players; i++)
{
TextView name1 = (TextView) findViewById(R.id.pname);
name1.setText( names[i]+":");
ptasks = 10;
rindex = generator.nextInt(ptasks);
TextView task = (TextView) findViewById(R.id.task);
task.setText( tasks[rindex]);
}
Button failButton = (Button) findViewById(R.id.fail_btn);
failButton.setOnClickListener(new View.OnClickListener()
{
public void onClick(View failed)
{
//not sure what to put here to get the scores set up
}
});
Button notButton = (Button) findViewById(R.id.notbad_btn);
notButton.setOnClickListener(new View.OnClickListener()
{
public void onClick(View notbad)
{
//not sure what to put here to get the scores set up
}
});
Button champButton = (Button) findViewById(R.id.champ_btn);
champButton.setOnClickListener(new View.OnClickListener()
{
public void onClick(View champp)
{
//not sure what to put here
}
});
counter++;
}
}
I'm sure this thing is riddled with errors. And I'm sorry if it is I'm not that well experienced a programmer. Thanks again
You can pass a string array from one activity to another using a Bundle.
Bundle bundle = new Bundle();
bundle.putStringArray("arrayKey", stringArray);
You can then access this stringArray from the next activity as follows:
Bundle bundle = this.getIntent().getExtras();
String[] stringArray = bundle.getStringArray("arrayKey");
I'm not sure if this is the only thing you intend to do. I hope it helps. Also, to assign a score to a particular string array, assuming your scores are int's you could use a HashMap as follows,
HashMap<String[],int> imageData = new HashMap<String[],int>();
But I'm not sure how you would pass this Map to another activity if you intend to do so.
http://developer.android.com/reference/android/content/Intent.html#putExtra(java.lang.String,%20java.lang.String[])
Use this cheat:
In Class2, convert you array string (tasks) to string (strSavedTask)by adding "|" separator. After that, pass your strSavedTask into Bundle and start to Class1.
When return to Class1, read strSavedTask from Bundle, split it by "|".
That's my cheat to pass array between 2 activity ^^
Hope this way can help you!

Categories