Android application stops on button click - android

I am making this application and it just stops when i press some buttons
public class Menu3 extends TheMenu{
Button Buttons[] = new Button[21];
Intent open = new Intent("com.frosti.lidraedi.OPEN");
int clicked;
boolean found;
int PO1;
int GoOn;
int s,e;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ActionBar actionBar = getActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
Bundle b = getIntent().getExtras();
PO1 = b.getInt("PO", 0);
switch (PO1) {
case 21:
//when i press these buttons everything works well
setContentView(R.layout.menu21);
s=0;
e=11;
break;
case 22:
//the layout loads without error
//but when i press the buttons int the layout it just stops
setContentView(R.layout.menu22);
s=12;
e=15;
break;
case 23:
setContentView(R.layout.menu23);
s=16;
e=20;
break;
case 24:
setContentView(R.layout.menu24);
break;
case 25:
setContentView(R.layout.menu25);
break;
default:
break;
}
init();
}
private void init() {
for(int c=s; c <= e; c++){
Typeface tf = Typeface.createFromAsset(getAssets(),"fonts/SourceSansPro-Semibold.otf");
int d = c+1;
int viewId = getResources().getIdentifier("b"+Integer.toString(d), "id", getPackageName());
if(viewId!=0){
Buttons[c] =((Button)findViewById(viewId));
Buttons[c].setTypeface(tf);
Log.d("Buttons", Integer.toString(c)+" : "+Integer.toString(d));
}else{
Log.d("Buttons", "0");
}
}
}
public void ButtonOnClick(View v){
Log.d("ButtonOnClick", "I was clicked");
found=false;
int c= 0;
for(Button b:Buttons){
Log.d("for loop", "I got run");
if(b.getId() == v.getId()){
Log.d("if block", "I got found");
GoOn=c;
Log.d("M3:true:C", Integer.toString(c)+ " : "+Integer.toString(v.getId()));
found=true;
break;
}
Log.d("C var", "I will get incremented");
c++; //hehehe
Log.d("C var", "I got incremented");
}
Log.i("ButtonOnClick",Integer.toString(c));
if(found) {
Log.i("M3:clicked:GoOn",Integer.toString(GoOn));
Bundle b1 = new Bundle();
b1.putInt("GoOn",GoOn);
open.putExtras(b1);
Log.d("Activity", "I will get opened");
startActivity(open);
overridePendingTransition(R.anim.slide_in, R.anim.slide_out);
}else if(clicked != v.getId()){
clicked = v.getId();
Toast.makeText(getApplicationContext(),"Skjárinn fannst því miður ekki",Toast.LENGTH_SHORT).show();
}
}
ok so i open the application press menu 22(that executes case 22 in the switch block) press some button and it stops
These are the errors i get:
If you compare the image with the code you see it executes "Log.d("for loop", "I got run");" but then freaks out, so error should be in this line " if(b.getId() == v.getId()){" but i have no idea why this happens?
This is the xml layout code just in case if it helps.
I would really appreciate if you could help me with this

Try running the following loop right after you initialize Buttons, just to be sure of what you have:
for(Button b : Buttons){
Log.d("Have button with ID " + b.getId());
Then run the same loop at the start of your onClick(). That will at least tell you if your Buttons structure is sound. When in doubt of which item is causing a NPE, it helps to log them separately. Often times, it's a non-obvious lifetime error, especially with fragments.

you create one array of Button with:
Button Buttons[] = new Button[21];
but you have custom item in that between s to e (you get value from switch statement ).
as you don't have button in all index of your array you get NPE on b.getId(), because you don't have any button on some index.
so you can solve your problem with two way.
1- as you don't know size of your array you can use ArrayList
2- you need initialize your array in init with
Buttons[] = new Button[e - s]; // or e-s+1 test both
I suggest use ArrayList, so your code must be like:
ArrayList<Button> list = new ArrayList<Button>();
Then you can get all id in your code with:
for ( int i = 0 ; i < list.size() ; i++)
list.get(i).getId();

Related

Changing Background color every time you open the Android app

I'm very new to android programming world and i have a problem:
I made a simply app that basically change the color of the background and the color of a button when you open it (i've tried using a switch with some color set in res), but it doesn't work and every time i open it there is the same color.
This is my activity code:
public class MainActivity extends AppCompatActivity {
RelativeLayout v;
Button z;
Random r;
int randomNumber;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
v=(RelativeLayout) findViewById(R.id.mainLayout);
z=(Button) findViewById(R.id.mainButton);
r=new Random();
randomNumber=r.nextInt(10);
switch (randomNumber)
{
case 0: v.setBackgroundColor(R.color.indigo); z.setBackgroundColor(R.color.indigoB); break;
case 1: v.setBackgroundColor(R.color.deepOrange); z.setBackgroundColor(R.color.deepOrangeB); break;
case 2: v.setBackgroundColor(R.color.purple); z.setBackgroundColor(R.color.purpleB); break;
case 3: v.setBackgroundColor(R.color.blueGrey); z.setBackgroundColor(R.color.blueGreyB); break;
case 4: v.setBackgroundColor(R.color.red); z.setBackgroundColor(R.color.redB); break;
case 5: v.setBackgroundColor(R.color.green); z.setBackgroundColor(R.color.greenB); break;
case 6: v.setBackgroundColor(R.color.lime); z.setBackgroundColor(R.color.limeB); break;
case 7: v.setBackgroundColor(R.color.pink); z.setBackgroundColor(R.color.pinkB); break;
case 8: v.setBackgroundColor(R.color.yellow); z.setBackgroundColor(R.color.yellowB); break;
case 9: v.setBackgroundColor(R.color.teal); z.setBackgroundColor(R.color.tealB); break;
case 10:v.setBackgroundColor(R.color.deepPurple); z.setBackgroundColor(R.color.deepPurpleB); break;
}
}
};
why this doesn't work?
And anyone know a solution for this problem?
thanks for help.
setBackgroundColor() accepts a color integer (#ColorInt), not a color resource ID (#ColorRes). You should pass a color value instead of a resource reference.
In short, replace:
v.setBackgroundColor(R.color.indigo);
with:
v.setBackgroundColor(getColor(R.color.indigo));
If you're referencing this view from outside of a context, you will need to obtain the Resources instance from context.
Try this:
private final int colorArray[] = {
R.color.indigo, R.color.deepOrange, R.color.purple,R.color.blueGrey
};
Add this method to shuffle colors:
static void shuffleArray(int[] arr)
{
Random rnd = new Random();
for (int i = arr.length - 1; i > 0; i--)
{
int index = rnd.nextInt(i + 1);
// Swap
int a = arr[index];
arr[index] = arr[i];
arr[i] = a;
}
}
Call the shuffle method in onCreate() and pass your color array as an argument:
shuffleArray(imageArray)
Then use:
v.setBackgroundColor(colorArray[0]);
z.setBackgroundColor(colorArray[1]);
Try to use this function
public int newRandom(){
Random r;
r=new Random();
return r.nextInt(10);
}
On the OnCreate put
randomNumber = newRandom();
Try to put the code to change color in onResume rather than in onCreate event like:
#Override
protected void onResume() {
super.onResume();
// add code to change color here
}
Because there is a possiblity that the app is not actually closed and just minimized; and when you tap the icon to open the app, it just maxmize the app which triggeres the onResume event rather than onCreate; that's why the color is not changing is because the onCreate event is not triggered.

Android Studio onClick button to display ImageView in another activity

I have setup 2 activities - one and two .
For activity 1, I have a EditText and a button. When user open the app, it will show Activity One(just like the screenshot) to prompt user to key in a number. For example, 1 or 2.
What I am trying to do is that: I want to display a ImageView in activity 2 when user key in a number in EditTextfollow by a click on the button in activity 1.
If user key in 1, it will display 1.png in activity 2
If user key in 2, it will display 2.png in activity 2
If user key in 3, it will display 3.png in activity 2
etc...
the image will get from drawable folder.
Please refer to this screenshot
[![enter image description here][1]][1]
I can pass the integer value through Intent from activity 1 to 2 but I can't do it for ImageView. so that means the if else loop i have already done just that the ImageView cant display.
get_image.setBackgroundResource(R.drawable.1); // here i can only key in 01 ( it will get image from Drawable folder 1.png). i cant put int value into it.
Or i shouldn't use get_image.setBackgroundResource?? Anyone can help? I stuck here for 1 day...
thanks in advance!
please check screenshot -> http://i.stack.imgur.com/53vjy.jpg
You said that you can pass integer value from activity 1 to 2 so just use that to find your image.
ImageView imageView = (ImageView)findViewById(R.id.yourImageViewId);
if(1 == yourValue) {
//set 01.png
} else {...}
I may missing somethings because i can't understand when you said that "but i cant do it for imageview".
EDIT: after your addtional code.
So you must map your integer value with your resource file name. You could not put your integer value to get_image.setBackgroundResource(R.drawable.id).
I think in your situation you should use an array just store id of resource you need int[] drawableIds = {R.drawable.01, R.drawable.02} in your Activity2
and then use like this get_image.setBackgroundResource(drawableIds[yourIntegerValue-1]) (ofcourse you should take care array out of index when you use this method).
Try below code for your solution,
For Activity One write below code to redirect on activity 2
Intent intent = new Intent(Activity1.this, Activity2.class);
intent.putExtra("SelectedNumber", editText.getEditableText.toString());
startActivity(intent);
Now In Activity 2 write below code in onCreate method
int selectedNumber = 1;
if(getIntent().getExtras() != null)
{
selectedNumber = getIntent().getExtras().getInt("SelectedNumber");
}
switch(selectedNumber)
{
case 1: // set your 01.png Image
break;
case 2: // set your 02.png Image
break;
// And so
}
Try this way might helps you.
String mDrawableName = "1"; //editText.getText().toString();
int resID = getResources().getIdentifier(mDrawableName , "drawable", getPackageName());
then your Activity2 use,
setImageResource(resID);
(or)
setImageDrawable(getResources().getDrawable(resID));
Finally,
button.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
String mDrawableName = editText.getText().toString();
int resID = getResources().getIdentifier(mDrawableName , "drawable", getPackageName());
Intent ii=new Intent(Activity.this, Activity1.class);
ii.putExtra("resId", resID);
startActivity(ii);
}
});
Activity2
public class Activity2 extends Activity
{
private ImageView img;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.intent);
img = (ImageView)findViewById(R.id.img);
Intent iin= getIntent();
Bundle b = iin.getExtras();
if(b!=null)
{
int drawableId =(int) b.get("redId");
img.setImageResource(drawableId);
}
}
}
you can pass resource value in extras. try this way.
EditText edit = (EditText) findViewById(R.id.yourEdittext);
Button btn = (Button) findViewById(R.id.yourButton);
btn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(ActivityOne.this, ActivityTwo.class);
if(edit.getText().toString().trim().equals("1")){
i.putExtra("image", R.drawable.01);
startActivity(i);
}else if(edit.getText().toString().trim().equals("2")){
i.putExtra("image", R.drawable.02);
startActivity(i);
}else{
Toast.makeText(getApplicationContext(), "Please Enter Valid Value.",
Toast.LENGTH_SHORT).show();
}
}
});
and in your ActivityTwo.java
ImageView imageView = (ImageView)findViewById(R.id.yourImageViewId);
imageView.setImageResource(getIntent().getIntExtra("image",0));
Happy Coding.
In activity 2's on create
get_image= (ImageView)findViewById(R.id.imageView);
then use switch case for values from intent then
switch(intentValues){
case 1:
get_images.setImageDrawable(getResources().getDrawable(R.drawable.1));
break;
case 2:
get_images.setImageDrawable(getResources().getDrawable(R.drawable.2));
break;
}

Creating an android Button which can perform more than one task

I am making an android app which requires a button to perform two taks:
1. The button should show an Error message in a TextView when user supplies a wrong input in EditText.
If the user provides a correct input then on clicking the button, it will jump to another activity.
My app is a kind of a simple game which contains 4 activities(activity_1, activity_2, activity_3, activity_4).
It asks for an input in activity_2. If it gets a wrong input the it gives the Error message.
But on providing the correct input the app crashes.
code activity_2.xml :
<Button
android:id="#+id/buttonClickMe"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/textView7"
android:layout_centerHorizontal="true"
android:layout_marginTop="18dp"
android:onClick="sendMessage"
android:text="#string/button_start" />
code activity_2.java :
final Button buttonStart = (Button) findViewById(R.id.button1)
buttonStart.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
int no = Integer.valueOf(numberField.getText().toString());
switch (no)
{
case 1 : maxRand = 15; // the random number will be between 0 and maxRand
break;
case 2 : maxRand = 30;
break;
case 3 : maxRand = 50;
break;
case 4 : maxRand = 100;
break;
default : textField.setText("Invalid Argument, Please try again.");
break;
}
if(maxRand != 0){
randNumber = (int) (Math.random() * maxRand);
/*textField.setText("Now click Start button !");
buttonStart.setVisibility(View.VISIBLE);*/
startActivity(intent); //This starts a new activity
}
}
});
and the code followed by the onClick method :
public void sendMessage(View view){ //This method is called everytime when the button is clicked
intent = new Intent(this,ShowResultsActivity.class);
}
Ive declared intent as the data member of the class.
Please do help me. And remember to provide bunch of code for reference.
try initiating Intent in setOnClickListener itself
final Button buttonStart = (Button) findViewById(R.id.button1)
buttonStart.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
int no = Integer.valueOf(numberField.getText().toString());
switch (no)
{
case 1 : maxRand = 15; // the random number will be between 0 and maxRand
break;
case 2 : maxRand = 30;
break;
case 3 : maxRand = 50;
break;
case 4 : maxRand = 100;
break;
default : textField.setText("Invalid Argument, Please try again.");
break;
}
if(maxRand != 0){
randNumber = (int) (Math.random() * maxRand);
intent = new Intent(this,ShowResultsActivity.class);
startActivity(intent); //This starts a new activity
}
}
});
If it doesn't fix the problem. pate your logcat output here..
public void sendMessage(View view){
//This method is called everytime when the button is clicked
int no = Integer.valueOf(numberField.getText().toString());
switch (no)
{
case 1 : maxRand = 15; // the random number will be between 0 and maxRand
break;
case 2 : maxRand = 30;
break;
case 3 : maxRand = 50;
break;
case 4 : maxRand = 100;
break;
default :
textField.setText("Invalid Argument, Please try again.");
// add this to ensure that you won't start activity
maxRand = 0;
break;
}
if(maxRand != 0){
randNumber = (int) (Math.random() * maxRand);
intent = new Intent(this,ShowResultsActivity.class);
startActivity(intent); //This starts a new activity
} else {
// maxRand == 0 ===> ERRORS, update your textField here
textField.setText("Invalid Argument, Please try again.");
}
}

android xml reference not working with switch and case with static array

I'm trying to make my life a heck of a lot easier by cycling through buttons in my xml (because I have a ton of buttons). Why isn't this working?
Button bf[];
public static final int[] Buttons = { R.id.b1, R.id.b2, R.id.b3, R.id.b4,
R.id.b5, R.id.b6, R.id.b7, R.id.b8, R.id.b9, R.id.bBack,
R.id.bClearAll, R.id.bClear };
I have a static final int that holds some of my buttons, which is list in the header.
Within my onCreate method I set up my buttons:
for (int i = 1; i < 10; i++) {
bf[i] = (Button) findViewById(Buttons[i - 1]);
bf[i].setOnClickListener(this);
}
Nice and easy right? but then when I try to reference them in the switch and case (within my implemented onClickListener method, I'm having problems:
for (int i = 1; i < 10; i++) {
case Buttons[i-1]:
Toast.makeText(this, bf[i].getText(), Toast.LENGTH_SHORT).show();
break;
}
This doesn't work, so then I just tried a single reference:
switch (v.getId()) {
case Buttons[0]:
Toast.makeText(this, bf[1].getText(), Toast.LENGTH_SHORT).show();
break;
which doesn't work either?!?! Help please?
v is your View in the onClickListener, right?
Why don't you use:
Button b = (Button) v;
Toast.makeText(this, b.getText(), Toast.LENGTH_SHORT).show();
Some other points:
You did not post the complete code but I guess you can change your Buttons array to private.
Probably you don't even need bf[]
Edit: Also I'd suggest to use this for-loop to cycle through all of your buttons to make it more flexible:
for (int i : Buttons) {
Button b = findViewById(i);
b.setOnClickListener(myClickListener);
}

Android which button index from array was pressed

How do I set up a OnClickListener to simply tell me which index button was pressed from an array of buttons. I can change text and color of these buttons using the array. I set them up like this.
TButton[1] = (Button)findViewById(R.id.Button01);
TButton[2] = (Button)findViewById(R.id.Button02);
TButton[3] = (Button)findViewById(R.id.Button03);
up to 36.
The OnClickListener is going to receive the button itself, such as R.id.Button01. It's not going to give you back your array index, as it knows nothing about how you have references to all the buttons stored in an array.
You could just use the button that is passed into your onClickListener directly, with no extra lookups in your array needed. Such as:
void onClick(View v)
{
Button clickedButton = (Button) v;
// do what I need to do when a button is clicked here...
switch (clickedButton.getId())
{
case R.id.Button01:
// do something
break;
case R.id.Button01:
// do something
break;
}
}
If you are really set on finding the array index of the button that was clicked, then you could do something like:
void onClick(View v)
{
int index = 0;
for (int i = 0; i < buttonArray.length; i++)
{
if (buttonArray[i].getId() == v.getId())
{
index = i;
break;
}
}
// index is now the array index of the button that was clicked
}
But that really seems like the most inefficient way of going about this. Perhaps if you gave more information about what you are trying to accomplish in your OnClickListener I could give you more help.
You can set Tag value and get the Tag on Click:
TButton[1] = (Button)findViewById(R.id.Button01);
TButton[1].setTag(1);
onClick(View v)
{
if(((Integer)v.getTag())==1)
{
//do something
}
}

Categories

Resources