App crashing at the end of array - android

My app is crashing at the end of the array in bluestacks. I have no idea why.
When I click the next button at the end of the array, the app crashes. I also tested it on my phone, same result. The rest of the app functions as intended.
From what I know "i %= image_elements.length;" is supposed to be the function that loops the array.
I am pretty sure this is where the crash is coming from.
i++;
element.setImageResource(image_elements[i]);
name.setImageResource(image_names[i]);
i %= image_elements.length;
Full code below
public class Practice extends MainMenuActivity {
int i = 0;
final int[] image_elements = {
R.drawable.spr_elements_0,
R.drawable.spr_elements_1,
[...]
R.drawable.spr_elements_86,
R.drawable.spr_elements_87,
};
final int[] image_names = {
R.drawable.spr_name_0,
R.drawable.spr_name_1,
[...]
R.drawable.spr_name_86,
R.drawable.spr_name_87,
};
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.practice);
final ImageView element = (ImageView) findViewById(R.id.element);
final ImageView name = (ImageView) findViewById(R.id.name);
Button nextButton = (Button) findViewById(R.id.buttonNext);
nextButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
i++;
element.setImageResource(image_elements[i]);
name.setImageResource(image_names[i]);
i %= image_elements.length;
}
});
}
public void backButton(View view) {
Intent z = new Intent(this, MainMenuActivity.class);
startActivity(z);
}
}

You'll need to rearrange your code from this:
i++;
element.setImageResource(image_elements[i]);
name.setImageResource(image_names[i]);
i %= image_elements.length;
to this:
i++;
i %= image_elements.length;
element.setImageResource(image_elements[i]);
name.setImageResource(image_names[i]);
What happens otherwise is that the index is incremented beyond the boundaries of the array, and that is corrected afterwards with the modulus operator. You'll need to the the correction before you use the index.
i %= image_elements.length in this particular case, is essentially the same as
if( i == image_elements.length ) {
i = 0;
}
Arrays indices go from 0 to length-1.
You could get rid of the arrays entirely by looking up the resources by name, such as this:
final static int MAX_ELEMENTS = 88; // this includes 0..87
private int index = 0;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.practice);
final ImageView element = (ImageView) findViewById(R.id.element);
final ImageView name = (ImageView) findViewById(R.id.name);
final Resources res = this.getResources();
final String pkgName = this.getPackageName();
Button nextButton = (Button) findViewById(R.id.buttonNext);
nextButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
final int imgId = res.getIdentifier( "spr_elements_" + index, "drawable", pkgName );
final int nameId = res.getIdentifier( "spr_name_" + index, "drawable", pkgName );
element.setImageResource( imgId );
name.setImageResource( nameId );
index = (index+1) % MAX_ELEMENTS;
}
});
}

Related

Click Button To Do two things And Vice Versa

I want to make button which will call two function on click I am using this code currently but when I click it on 3rd time nothing happens and I want to do vice versa like when user click on button 3rd time it will call count 1 again.. this code is currently I am using
#Override
public void onClick(View v) {
clickcount=clickcount+1;
if(clickcount==1)
{
Random i = new Random ();
int c= i.nextInt(7-1) + 1;
bck.setBackgroundColor(Color.BLACK);
TextView textresult = (TextView) findViewById(R.id.textView);
textresult.setTextColor(Color.WHITE);
}
else
{
Random i = new Random ();
int c= i.nextInt(7-1) + 1;
bck.setBackgroundColor(Color.WHITE);
TextView textresult = (TextView) findViewById(R.id.textView);
textresult.setTextColor(Color.BLACK);
}
}
Hello mate Please do like this
clickcount=0;
#Override
public void onClick(View v) {
clickcount = clickcount + 1;
if(clickcount%2 == 1) {
Random i = new Random ();
int c = i.nextInt(7 - 1) + 1;
bck.setBackgroundColor(Color.BLACK);
TextView textresult = (TextView) findViewById(R.id.textView);
textresult.setTextColor(Color.WHITE);
} else {
Random i = new Random ();
int c = i.nextInt(7 - 1) + 1;
bck.setBackgroundColor(Color.WHITE);
TextView textresult = (TextView) findViewById(R.id.textView);
textresult.setTextColor(Color.BLACK);
}
}
Another solution with boolean:
boolean check = true;
#Override
public void onClick(View v) {
Random i = new Random ();
TextView textresult = (TextView) findViewById(R.id.textView);
int c= i.nextInt(7-1) + 1;
bck.setBackgroundColor(check ? Color.BLACK : Color.WHITE);
textresult.setTextColor(check ? Color.WHITE : Color.BLACK);
check = !check;
}
Or if you want two functions:
boolean check = true;
#Override
public void onClick(View v) {
if(check) {
// first function
} else {
// second function
}
check = !check;
}

Using Text Only Once Through Random Method

I am new to Android. I am showing Text in the TextView on Button click Randomly. On 1st Textview the Heading and on 2nd the explaination of that heading. I am able to show the Heading and Explaination Randomly and now I want if the Text is shown once should not be shown again means it will be removed. This is the point where I stuck. I am not able to remove the texts. Any help will be appreciated. I am posting my code here.
MainActivity.java
TextView text_heading,text_explain;
Button click;
Random random;
Integer [] array_heading ,array_explain ;
Integer int_text;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
text_heading = (TextView) findViewById(R.id.text_heading);
text_explain = (TextView) findViewById(R.id.text_explain);
click = (Button) findViewById(R.id.click);
click.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
text_heading.setText(array_heading.get(int_text)); //getting error
text_explain(array_explain.get(int_text)); //getting error
array_heading.remove(int_text); //getting error
array_explain.remove(int_text); //getting error
}
});
random = new Random();
array_heading = new Integer []{R.string.source_text1, R.string.source_text2, R.string.source_text3,
R.string.source_text6, R.string.source_text5, R.string.source_text4, R.string.source_text7,
R.string.source_text8, R.string.source_text9};
array_explain = new Integer []{R.string.source_text1_explain, R.string.source_text2_explain,
R.string.source_text3_explain,
R.string.source_text4_explain, R.string.source_text5_explain, R.string.source_text6_explain,
R.string.source_text7_explain,
R.string.source_text8_explain, R.string.source_text9_explain};
ArrayList<Integer> array_headingList = new ArrayList<Integer>(Arrays.asList(array_heading));
ArrayList<Integer>array_explainList = new ArrayList<Integer>(Arrays.asList(array_explain));
int_text = random.nextInt(array_headingList.size() - 1);
}
}
I am not able to remove the texts. Any help will be appreciated. I am
posting my code here.
To clean the content of the TextView you could pass null to setText. E.g
text_heading.setText(null);
If you want to change the content every time you click on the button, you have to move
int_text = random.nextInt(array_heading.length);
your onClick callback,
You should be aware of the fact that next int returns an int between [0, n). array_heading.length -1 is necessary only if you want to exclude R.string.source_text9_explain from the possible texts you want to show. Keep also in mind that if array_heading contains more items than array_explain you could get ArrayIndexOutBoundException
I would keep the strings together in an object:
public class Item {
private final int textId;
private final int textExplanationId;
public class Item(int textId, int textExplanationId){
this.textId = textId;
this.textExplanationId = textExplanationId;
}
public int getTextId(){return textId;}
public int getTextExplanationId(){return textExplanationId;}
}
Then I would store those in an ArrayList:
List<Item> items = new ArrayList<Item>(new Item[]{
new Item(R.string.source_text1, R.string.source_text1_explain),
new Item(R.string.source_text2, R.string.source_text2_explain),
//etc
});
Then I would shuffle that array once:
Collections.shuffle(items);
And read from it in order:
Item current = items.get(currentIndex++);
text_heading.setText(current.getTextId());
text_explain.setText(current.getTextExplanationId());
TextView text_heading,text_explain;
Button click;
Random random;
Integer [] array_heading ,array_explain ;
Integer int_text;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
text_heading = (TextView) findViewById(R.id.text_heading);
text_explain = (TextView) findViewById(R.id.text_explain);
click = (Button) findViewById(R.id.click);
random = new Random();
array_heading = new Integer []{R.string.source_text1, R.string.source_text2, R.string.source_text3,
R.string.source_text6, R.string.source_text5, R.string.source_text4, R.string.source_text7,
R.string.source_text8, R.string.source_text9};
array_explain = new Integer []{R.string.source_text1_explain, R.string.source_text2_explain,
R.string.source_text3_explain,
R.string.source_text4_explain, R.string.source_text5_explain, R.string.source_text6_explain,
R.string.source_text7_explain,
R.string.source_text8_explain, R.string.source_text9_explain};
ArrayList<Integer> array_headingList = new ArrayList<Integer>(Arrays.asList(array_heading));
ArrayList<Integer> array_explainList = new ArrayList<Integer>(Arrays.asList(array_explain));
int_text = random.nextInt(array_headingList.size() - 1);
click.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
text_heading.setText(array_headingList.get(int_text)); //getting error
text_explain.setText(array_explainList.get(int_text)); //getting error
array_headingList.remove(int_text); //getting error
array_explainList.remove(int_text); //getting error
}
});
}
}
You must use ArrayList for it.
ArrayList<Integer> heading = Arrays.asList(array_heading);
ArrayList<Integer> explain = Arrays.asList(array_explain);
Now set text from this arraylists. And when its set once remove it from the arraylist so it cannot be shown again.
Use like this
random = new Random();
array_heading = new Integer []{R.string.source_text1, R.string.source_text2, R.string.source_text3,
R.string.source_text6, R.string.source_text5, R.string.source_text4, R.string.source_text7,
R.string.source_text8, R.string.source_text9};
array_explain = new Integer []{R.string.source_text1_explain, R.string.source_text2_explain,
R.string.source_text3_explain,
R.string.source_text4_explain, R.string.source_text5_explain, R.string.source_text6_explain,
R.string.source_text7_explain,
R.string.source_text8_explain, R.string.source_text9_explain};
ArrayList<Integer> array_headingList = new ArrayList<Integer>(Arrays.asList(array_heading));
ArrayList<Integer> array_explainList = new ArrayList<Integer>(Arrays.asList(array_explain));
int_text = random.nextInt(array_headingList.size());
click.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
text_heading.setText(array_headingList.get(int_text));
text_explain.setText(array_explainList.get(int_text));
array_headingList.remove(int_text);
array_explainList.remove(int_text);
if(array_headingList.size() == 0){
click.setEnabled(false);
Toast.makeText(getApplicationContext(),"All text finished",Toast.LENGTH_SHORT).show();
} else if(array_headingList.size() == 1){
int_text = 0;
} else {
int_text = random.nextInt(array_headingList.size());
}
}
});

how do I set up a next and previous button

Hello as the title state I'm trying to setup a next and previous buttons but I'm still new at coding so this has me a little confused.
I tried to use if statements with an enum within a single button but it defaults to last if statement when the event is handled here's the code-
private enum EVENT{
pe1, pe2, pe3, pe4;
}
EVENT currentEvent = EVENT.pe1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_one_liners);
nextBtn = (Button) findViewById(R.id.nextBtn);
olText = (TextView) findViewById(R.id.olText);
nextBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (currentEvent==EVENT.pe1) {
olText.setText("PE1");
olText.startAnimation(AnimationUtils.loadAnimation(olText.this, android.R.anim.slide_in_left));
currentEvent=EVENT.pe2;
}
if (currentEvent==EVENT.pe2){
olText.setText("PE2");
olText.startAnimation(AnimationUtils.loadAnimation(olText.this, android.R.anim.slide_in_left));
currentEvent=EVENT.pe3;
}
}
});
}
I tried to use the enumerator to assign a number to each if statement so when the user hit previous it would subtract and when they hit next it would add, each number would have some text or image within its if statement but as I said it defaults to the last if statement- Any help is much appreciated.
How about this?
int eventNum = 0;
int maxEvents = XXX;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_one_liners);
prevBtn = (Button) findViewById(R.id.prevBtn);
nextBtn = (Button) findViewById(R.id.nextBtn);
olText = (TextView) findViewById(R.id.olText);
setEventData(true);
View.OnClickListener listener = new View.OnClickListener() {
#Override
public void onClick(View v) {
if(v.equals(prevBtn) && eventNum > 0) {
eventNum--;
setEventData(false);
return;
}
if(v.equals(nextBtn) && eventNum < maxEvents - 1) {
eventNum++;
setEventData(true);
return;
}
}
}
nextBtn.setOnClickListener(listener);
prevBtn.setOnClickListener(listener);
}
private void setEventData(boolean animLeft) {
olText.setText("PE" + (eventNum + 1));
if(animLeft) {
olText.startAnimation(AnimationUtils.loadAnimation(olText.this, android.R.anim.slide_in_left));
} else {
olText.startAnimation(AnimationUtils.loadAnimation(olText.this, android.R.anim.slide_in_right));
}
}
You'll want to create a class variable that keeps track of which text your TextView is showing. So in the following example, I create a list of Strings that I just store in a String array. Then I create an iterator variable which stores which String from the list I'm currently viewing in the TextView. Every time you click the previous or next button, you simply store your current state in the iterator variable so you can recall it the next time a click event comes in.
String[] labels = {"one", "two", "three", "four"};
int currentView = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void onPreviousButtonClicked(View view) {
TextView textView = (TextView) findViewById(R.id.clickableLink);
currentView--; //decrement our iterator
if(currentView < 0) currentView = 0; //check to make sure we didn't go below zero
textView.setText(labels[currentView]);
}
public void onNextButtonClicked(View view) {
TextView textView = (TextView) findViewById(R.id.clickableLink);
currentView++; //increment our iterator
if(currentView > labels.length-1) currentView = labels.length-1; //check to make sure we didn't go outside the array
textView.setText(labels[currentView]);
}

How to generate random order for a strings list?

Every time an user click on the button it has to show "John - Sue" or "Sue - John".
I tried with this code:
public class MyActivity extends Activity {
ArrayList<String> names = new ArrayList<String>();
int p1, p2;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.myactivity);
names.add("John");
names.add("Sue");
Button b = (Button) findViewById(R.id.mybutton);
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
p1 = (int)Math.random();
if (p1 == 0)
p2 = 1;
else
p2 = 0;
String msg = names.get(p1) + " - " + names.get(p2);
AlertDialog msgbox = new AlertDialog.Builder(About.this).setTitle("Click here").setMessage(msg).create();
//msgbox.setPositiveButton("OK", null);
msgbox.setCancelable(true);
msgbox.show();
TextView textView = (TextView) msgbox.findViewById(android.R.id.message);
textView.setTextSize(16);
}
});
}
}
But i get always the same order, even i close and run again the app. How to do that?
If you want shuffle list:
Collections.shuffle(names)
If you want random int between 0 or 1 (nextInt(int) javadoc):
Random random = new Random();
int randomInt = random.nextInt(2);
Math.random() returns a number between 0 and 1. So when you cast it to int it will always be 0.
Try this:
p1 = (int)(Math.random()*2);
It happens because
p1 = (int)Math.random();
always gives you zero.

Browse an array of strings in a TextView

I wonder how I could navigate between the strings within an array, using the previous and next buttons, these strings will be displayed in a TextView. Thank you!
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView (R.layout.activity_f3);
setTitleFromActivityLabel (R.id.title_text);
TextView cumulos = (TextView) findViewById(R.id.cumulos);
TextView respostas = (TextView)findViewById(R.id.respostas);
Random randPhrase = new Random();
String[] cum = getResources().getStringArray(R.array.cumulos);
String[] resp = getResources().getStringArray(R.array.resp_cumulos);
String textout = "";
String textresp = "";
for (int i = 0; i < cum.length; i++) {
for (int j = 0; j < resp.length; j++) {
textresp = resp[j];
}
textout = cum[i];
}
cumulos.setText(textout);
respostas.setText(textresp);
}
Declare one int for index starting with 0 then in NextButton do
if(!index > resp.length-1 ) //not greater than array length
{
setText(resp[index++]);
}
else { nextButton.setEnabled(false); nextButton.setClicable(false); } //not clickable anymore
in PreviousButton do
if(!index < 0)
{
setText(resp[index--]);
}
else{
prevButton.setEnabled(false);
prevButton.setClicable(false);
}
Something like this? Mind this code is not tested, might throw exceptions.
It just to give you an idea.
You will need to create a next button and set an onClickListener for your button to navigate through the array. Lets say you also have a previous and next button. Try this:
Button btnNext = (Button) findViewById(R.id.yourNextbutton);
Button btnPrevious = (Button) findViewById(R.id.yourPreviousbutton);
int i = 0;
btnNext.setOnClickListener(new OnClickListener(){
public void onClick(View arg0) {
if(i<cum.length-1){
i+=1;
cumulos.setText(cum[i]);
respostas.setText(resp[i]);
}
}
});
btnPrevious.setOnClickListener(new OnClickListener(){
public void onClick(View arg0) {
if(i>0){
i-=1;
cumulos.setText(cum[i]);
respostas.setText(resp[i]);
}
}
});

Categories

Resources