Android, tell me my mistake please - android

I am very new to Java as well as Android programming. I was attempting to make a calculator. But as soon as I inserted the square root button, the application crashes whenever I hit divide or square root. I don't know where I'm going wrong. Help,please?
public class MainScreen extends Activity implements OnClickListener {
EditText edit1, edit2;
TextView txt;
Button butt, diff, mul, div, sqr, per;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
edit1 = (EditText)findViewById(R.id.editText1);
edit2 = (EditText)findViewById(R.id.editText2);
txt = (TextView)findViewById(R.id.textView1);
butt = (Button)findViewById(R.id.button1);
butt.setOnClickListener(this);
diff = (Button)findViewById(R.id.button2);
diff.setOnClickListener(this);
mul = (Button)findViewById(R.id.button3);
mul.setOnClickListener(this);
div = (Button)findViewById(R.id.button4);
div.setOnClickListener(this);
sqr = (Button)findViewById(R.id.button5);
sqr.setOnClickListener(this);
per = (Button)findViewById(R.id.button6);
per.setOnClickListener(this);
}
#Override
public void onClick(View v) {
String a;
// TODO Auto-generated method stub
String b;
Integer sum, sub, mul, div;
Double x ;
a= edit1.getText().toString();
b= edit2.getText().toString();
x=(double) Integer.parseInt(a);
switch (v.getId()) {
case R.id.button1:
sum = Integer.parseInt(a)+ Integer.parseInt(b);
txt.setText(sum.toString());
break;
case R.id.button2:
sub = Integer.parseInt(a)- Integer.parseInt(b);
txt.setText(sub.toString());
break;
case R.id.button3:
mul = Integer.parseInt(a)* Integer.parseInt(b);
txt.setText(mul.toString());
break;
case R.id.button4:
div = (Integer.parseInt(a))/(Integer.parseInt(b));
txt.setText(div.toString());
case R.id.button5:
txt.setText((int) Math.sqrt(x));
default:
break;
}}}

It's bad idea to use (int) Math.sqrt(x) - sqrt does not return integer.
When you write textView.setText(int) - Andrid thinks, that you provide id of string resource, and it can't find it and crashes.
Use this:
case R.id.button5:
txt.setText(String.valueOf(Math.sqrt(x)));
break;

You need to be checking the value of be to make sure you are not dividing by 0.
Can you please post the error you are receiving?

Well, you can view the errors doing $ adb logcat. Further, in the last two 'cases' you haven't put a "break".

Related

How to realise multiple text editing from one button?

Here is the goal: 1 textview, 1 button. after pressing button text in textview is editing to new string. I tryed to realise it like this, but it
doesn`t work. Please help. There is 1 activity, 1 button, 1 tv and multiple pressings to edit text.
public class Second extends AppCompatActivity {
TextView tv;
Button btn;
int i;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second2);
tv = (TextView) findViewById(R.id.tv);
btn = (Button) findViewById(R.id.btn);
i = 1;
tv.setText(R.string.s1);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
for (i=1;i<28;i++);{
switch (i){
case 1:tv.setText(R.string.s1);
break;
case 2:tv.setText(R.string.s2);
break;
case 3:tv.setText(R.string.s3);
break;
case 4:tv.setText(R.string.s4);
break;
case 5:tv.setText(R.string.s5);
break;
case 6:tv.setText(R.string.s6);
break;
case 7:tv.setBackgroundResource(R.drawable.tigs);
tv.setHeight(430);
tv.setWidth(350);
tv.setText(R.string.s6_1);
break;
default:break;
What i`m doing wrong?
At the end you will only see the value of R.string.s6 in your edit text and the background will be set as R.drawable.tigs. The for loop executes in a fraction of second and set value one by one. But due to its fast execution you will only see the last value. But if you want to see all the text one by one you can use a java thread and call its sleep method by passing the time in milliseconds.

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 application stops on button click

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

How can I set up a password activity as with only numbers?

public class Password extends Activity{
Button one, two, three, four, five, six, seven, eight, nine, zero, exit, okay;
EditText text;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.pass);
one = (Button) findViewById(R.id.button);
two = (Button) findViewById(R.id.button2);
three = (Button) findViewById(R.id.button3);
four = (Button) findViewById(R.id.button4);
five = (Button) findViewById(R.id.button5);
six = (Button) findViewById(R.id.button6);
seven = (Button) findViewById(R.id.button7);
eight = (Button) findViewById(R.id.button8);
nine = (Button) findViewById(R.id.button9);
exit = (Button) findViewById(R.id.button10);
zero = (Button) findViewById(R.id.button11);
okay = (Button) findViewById(R.id.button12);
}
public void onClick(View v){
switch (v.getId()){
case R.id.button:text.setText("1");
break;
case R.id.button2:text.setText("1");
break;
case R.id.button3:text.setText("1");
break;
case R.id.button4:text.setText("1");
break;
case R.id.button5:text.setText("1");
break;
case R.id.button6:text.setText("1");
break;
case R.id.button7:text.setText("1");
break;
case R.id.button8:text.setText("1");
break;
case R.id.button9:text.setText("1");
break;
case R.id.button10:text.setText("1");
break;
case R.id.button11:text.setText("1");
break;
case R.id.button12:text.setText("1");
break;
}
}
}
I have made the pic attached below. I want to create this activity. I read something about sharedPreferences but it is still confusing me. Could anyone tell me how to achieve this?
EDIT: Thanks a lot guys. I did some other thing. The switch case wasnt working so I added the code like
one.setOnClickListener(){.....}
to each button. It is working now.
Huge thanks to all of you. Never would have got ideas if I didnt post here.
update
try this
public void onClick(View v){
switch (v.getId()){
case R.id.button:text.setText(text.getText()+"1");
break;
case R.id.button2:text.setText(text.getText()+"2");
break;
case R.id.button3:text.setText(text.getText()+"3");
break;
case R.id.button4:text.setText(text.getText()+"4");
break;
case R.id.button5:text.setText(text.getText()+"5");
break;
case R.id.button6:text.setText(text.getText()+"6");
break;
case R.id.button7:text.setText(text.getText()+"7");
break;
case R.id.button8:text.setText(text.getText()+"8");
break;
case R.id.button9:text.setText(text.getText()+"9");
break;
case R.id.button10:text.setText("1");
break;
case R.id.button11:text.setText("1");
break;
case R.id.button12:text.setText("1");
break;
}
and for other buttons place appropriate functions
for edittext
android:inputType="number"
or
android:inputType="numberPassword"
in your edittext in xml file
and for SharedPreferences refer to Waza_Be's answer
try this may be help you
use this in your xml file
<EditText
android:id="#+id/editText1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:inputType="numberPassword" >
<requestFocus />
To set the password, you could do something like: (This in not really secure, not aimed for banking app ;-))
SharedPreferences settings= PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor prefEditor=settings.edit();
prefEditor.putString("password","123456");
// if 4 digits: prefEditor.putInt("password",1234);
prefEditor.commit();
Working with numbers is a little bit tricky because of the maximum value of integers:
Java int:int is 32 bit signed type ranges from –2,147,483,648 to
2,147,483,647.
Of course, if you force a 4 digit PIN for password, no problems to work with int, but as you will work with String in TextView/EditText, turning it to numbers sounds not the best idea
and when the user want to login to the Activity, just compare what he typed with:
settings.getInt("password",-1)

Proper way of listening to a lot of Buttons each of which does something else Android

I have a bunch of buttons to listen to.
Each button increments or decrements a value in an EditText.
Since every Button changes a different EditText I'm left with just switching.
There are quite a lot of buttons. Some buttons do the same thing except they are hidden according to user preference.
For every button in XML I did android:onClick="plusEditTexts", or android:onClick="minEditTexts" of course.
public void plusEditTexts(View v) {
switch(v.getId()) {
case R.id.firstButton1Inc:
case R.id.secondButton1Inc:
// EditText1++
break;
case R.id.firstButton2Dec:
case R.id.secondButton2Dec:
// EditText2++
break;
...
}
}
public void minEditTexts(View v) {
switch(v.getId()) {
case R.id.firstButton1Inc:
case R.id.secondButton1Inc:
// EditText1--
break;
case R.id.firstButton2Dec:
case R.id.secondButton2Dec:
// EditText2--
break;
...
}
}
I was wondering if this is the best way?
There are quite a lot of buttons. So the switch statement gets huge.
Cheers,
Daan
You could set attribute tagof your buttons with the id of the TextViewto be modified. Then, you can retrieve the int value of TextView resource id like this.-
int textResId = getResources().getIdentifier(v.getTag().toString(), "id", getPackageName());
Getting rid of the whole case sentences, so your code looked like.-
public void plusEditTexts(View v) {
int textResId = getResources().getIdentifier(v.getTag().toString(), "id", getPackageName());
EditText editText = (EditText) findViewById(textResId);
// Do your EditText stuff
}
public void minEditTexts(View v) {
int textResId = getResources().getIdentifier(v.getTag().toString(), "id", getPackageName());
EditText editText = (EditText) findViewById(textResId);
// Do your EditText stuff
}

Categories

Resources