For my new app I need to print numbers chosen from a switch case. My switch cases should randomly pick an image and after that, the if statement should check which one was chosen and then change the score. The problem I have is, that my if statements get errors, because of Unreachable Code.
public class MainActivity extends ActionBarActivity {
TextView score;
public int newscore;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
score = (TextView) findViewById(R.id.textView1);
}
int Id() {
Random rand = new Random();
int imag = rand.nextInt(4);
switch (imag) {
case 0:
score.setText(newscore);
return R.drawable.a;
case 1:
score.setText(newscore);
return R.drawable.b;
case 2:
score.setText(newscore);
return R.drawable.c;
default:
score.setText(newscore);
return R.drawable.d;
}
if(Id() == R.drawable.a){
newscore = newscore+1;
}
if(Id() == R.drawable.b){
newscore = newscore+10;
}
if(Id() == R.drawable.c){
newscore = newscore+100;
}
if(Id() == R.drawable.d){
newscore = newscore+1000;
}
}
}
I would put the switch statement in a method, this is how your Activity should look:
public class MainActivity extends ActionBarActivity {
TextView score;
public int newscore;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
score = (TextView) findViewById(R.id.textView1);
Random rand = new Random();
int image = rand.nextInt(4);
int newImage = getImageResourceId(image);
if(newImage == R.drawable.a){
newscore = newscore+1;
score.setText(newscore);
}
if(newImage == R.drawable.b){
newscore = newscore+10;
score.setText(newscore);
}
if(newImage == R.drawable.c){
newscore = newscore+100;
score.setText(newscore);
}
if(newImage == R.drawable.d){
newscore = newscore+1000;
score.setText(newscore);
}
}
public int getImageResourceId(int image) {
switch (image) {
case 0:
return R.drawable.a;
case 1:
return R.drawable.b;
case 2:
return R.drawable.c;
case 3:
return R.drawable.d;
default:
return R.drawable.a;
}
}
}
Further Reading:
Writing your own Java Methods
Returning a value from a Method
You will do switch and always return, because switch-case with default case always returns so:
if(Id() == R.drawable.a){
newscore = newscore+1;
}
if(Id() == R.drawable.b){
newscore = newscore+10;
}
if(Id() == R.drawable.c){
newscore = newscore+100;
}
if(Id() == R.drawable.d){
newscore = newscore+1000;
}
will never run.
Related
I am making android calculator. I made some functions but the first problem is double clickable operation.I tried but couldn't. when i click two operations consequently both are appearing on the text view. i'll post my code if you can solve double clickable operation problem please post your code on comment.
public class MainActivity extends AppCompatActivity {
private TextView _screen;
private TextView _result;
private String display = "";
private String currentOperator;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
_screen = (TextView) findViewById(R.id.txtScreen);
_result = (TextView) findViewById(R.id.id_result);
}
public void updateScreen() {
_screen.setText(display);
}
public void onClickNumber(View v) {
Button b = (Button) v;
display += b.getText();
updateScreen();
}
public void onClickOperator(View v) {
Button b = (Button) v;
display += b.getText();
currentOperator = b.getText().toString();
updateScreen();
}
public void clear() {
display = "";
currentOperator = "";
}
public void onClickClear(View view) {
clear();
updateScreen();
}
public double operate(String a, String op, String b) {
switch (op) {
case "+":
return Double.valueOf(a) + Double.valueOf(b);
case "-":
return Double.valueOf(a) - Double.valueOf(b);
case "*":
return Double.valueOf(a) * Double.valueOf(b);
case "/":
return Double.valueOf(a) / Double.valueOf(b);
default:
return -1;
}
}
public void onClickEqual(View v) {
String[] operation = display.split(Pattern.quote(currentOperator));
_result.setText(String.valueOf(operate(operation[0], currentOperator, operation[1])));
}
}
what I understand from your question regarding double operation is that Let suppose you are performing operation of + and when you click again for + it gets displayed 2 times on textview (as your method updateScreen suggest). If that is the problem, you can do as mentioned below
public void updateScreen() {
if (screen.getText().toString().equalsIgnoreCase("")) {
screen.setText(display);
} else if (!display.equalsIgnoreCase(screen.getText().toString())) {
screen.setText("");
screen.setText(display);
} else {
//this is the case that means that operator is already set on the text
}
}
Hope that helps you.
i"m learning java and android SDK. for learning propers i built a calculator (not completed yet).
in my code i used ImageView Tags to get the value of the button that the user clicked on:
ImageView button = (ImageView) view;
String buttonTag = button.getTag().toString();
xml:
<ImageView
android:layout_width="80dp"
android:layout_height="80dp"
android:id="#+id/zero"
android:layout_row="17"
android:layout_column="1"
android:tag="0"
android:onClick="calcPad" />
the ImageView Tags values are: "0" - "9", "plus"/"minus" etc..
so i converted it to chars to get the numbers and converted it back to int:
char[] charTag = buttonTag.toCharArray();
for (int z=0; z < charTag.length; z++) {
if (charTag[z] == '0') {number = 0;}
if (charTag[z] == '1') {number = 1;}
...
if (charTag[z] == '9') {number = 9;}
i have tried to use 'try' and 'catch' but the app crash. this what i have tried to do:
try{
num = Integer.getInteger(buttonTag);
} catch(NumberFormatException e) {
Log.i("Exception", e.getMessage());
switch(buttonTag) {
case "Plus":
.....
default:
}
}
what i need to add in order to 'handle' the exception? i tried to add in the catch a switch that get buttonTag value (that is string) but still the same problem.
the complete code (without the try/catch section):
package com.example.idan.calculator;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import java.io.IOException;
public class MainActivity extends AppCompatActivity {
double var1 = 0; //holds the first number
double var2 = 0; //holds the second number
int decimalPoint = 0; //indicate if the user clicked on the (.)
String var1string=""; //for processing
String var2string=""; //for processing
double var1Array[]={0,0}; // the return value of var1doublemaker
double var2Array[]={0,0}; // the return value of var2doublemaker
boolean mathAction = false; // indicate if the user clicked on a mathematical button
int mathType = 0; // help me identify between + - * /
char mathValue = 'x'; // for the display
double result = 0; // final result
public double[] var1doubleMaker (String buttonTag, int decimalPoint) {
if (decimalPoint == 1) { //need to add dot to string
var1string = var1string + "." + buttonTag;
var1 = Double.valueOf(var1string);
decimalPoint = 0; // set back to 0
var1Array[0] = var1;
var1Array[1] = decimalPoint;
} else {
var1string = var1string + buttonTag; // add the last number
var1 = Double.valueOf(var1string);
var1Array[0] = var1;
var1Array[1] = decimalPoint;
}
return(var1Array);
}
public double[] var2doubleMaker (String buttonTag, int decimalPoint) {
if (decimalPoint == 1) {
var2string = var2string + "." + buttonTag;
var2 = Double.valueOf(var2string);
decimalPoint = 0;
var2Array[0] = var2;
var2Array[1] = decimalPoint;
} else {
var2string = var2string + buttonTag;
var2 = Double.valueOf(var2string);
var2Array[0] = var2;
var2Array[1] = decimalPoint;
}
return(var2Array);
}
public void calcPad(View view) throws NumberFormatException{
//check which button the user clicked on-
// first: get the ImageView by id
ImageView button = (ImageView) view; // where the user clicked on
String buttonTag = button.getTag().toString(); // hold the tag as string for the switch
char[] charTag = buttonTag.toCharArray();
int number = 111; // 111 - just for initialization
int num = 111;
/*
try{
num = Integer.getInteger(buttonTag);
} catch(NumberFormatException e) {
Log.i("Exception", e.getMessage());
}
*/
Log.i("info - num value:", String.valueOf(num));
//Log.i("info char", String.valueOf(charTag[0]));
char numberToResolve = charTag[0];
switch (numberToResolve) {
case '0':
number = 0;
break;
case '1':
number = 1;
break;
case '2':
number = 2;
break;
case '3':
number = 3;
break;
case '4':
number = 4;
break;
case '5':
number = 5;
break;
case '6':
number = 6;
break;
case '7':
number = 7;
break;
case '8':
number = 8;
break;
case '9':
number = 9;
break;
default:
Log.i("error", "cant resolve number from charTag[]");
}
//Log.i("info number value", String.valueOf(number));
TextView textView = (TextView) findViewById(R.id.calcDisplay); // create an object to print the button that the user clicked
Log.i("info", buttonTag);
// math
if (buttonTag.length() > 1) {
switch(buttonTag) {
case "divid":
mathValue = '/';
mathAction = true;
mathType = 4;
break;
case "multi":
mathValue = '*';
mathAction = true;
mathType = 3;
break;
case "Plus":
mathValue = '+';
mathAction = true;
mathType = 1;
break;
case "minus":
mathValue = '-';
mathAction = true;
mathType = 2;
break;
case "dot":
decimalPoint = 1;
case "equal":
if (mathType == 1) {
result = var1 + var2;
} else if (mathType == 2) {
result = var1 - var2;
} else if (mathType == 3) {
result = var1 * var2;
} else if (mathType == 4) {
result = var1 / var2;
}
String display = Double.toString(result);
textView.setText(display);
break;
case "cc":
var1 = 0;
var2 = 0;
mathAction = false;
decimalPoint = 0;
result = 0;
var1string=""; //for processing
var2string="";
display = Double.toString(result);
textView.setText(display);
break;
default:
Log.i("error", "cant resolve math type from buttonTag");
}
}
//Log.i("info decimalpoint", String.valueOf(decimalPoint));
if (number >= 0 && number <= 9 ) {
// user clicked on a number
//call doubleMaker
if (mathAction) {
//working on var2
double[] var2temp = var2doubleMaker(buttonTag,decimalPoint);
Double dd= var2temp[1];
decimalPoint = dd.intValue(); // set decimalPoint back to 0
// display var1 + math + var2
String display = Double.toString(var1) + Character.toString(mathValue) + Double.toString(var2temp[0]);
textView.setText(display);
} else {
// working on var1
double[] var1temp = var1doubleMaker(buttonTag,decimalPoint);
Double d= var1temp[1];
decimalPoint = d.intValue();
String display = Double.toString(var1temp[0]);
textView.setText(display);
}
}
Log.i("info - var1:", Double.toString(var1));
Log.i("info - var2:", Double.toString(var2));
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
You just need to pass your string into this : Integer.parseInt("string"). This method help you convert from string to int
ImageView button = (ImageView) view;
String buttonTag = button.getTag().toString();
int number = Integer.parseInt(buttonTag)
I'm designing a simple app to count the rows and stitches in crocheting/knitting, but I'm having issues. The actual counting itself is just a modified calculator: display a text field that holds the current number of stitches, and buttons which allow you to add or subtract 1, 5 or 10 to the count. Problem is, punching the buttons in the emulator doesn't work -- the thing compiles without issues and builds without issues, so I'm thinking it's something small I've (not) done.
My Main file:
public class mainCount extends Activity {
private EditText Scr; //Textbox screen
private int NumberBF; //saves screen before pressing button operations
private String Operation;
private ButtonClickListener btnClick;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Scr = (EditText) findViewById(R.id.stitchCount);
int idList[] = {R.id.stitchMin1, R.id.stitchMin5, R.id.stitchMin10, R.id.stitchPlus1, R.id.stitchPlus5, R.id.stitchPlus10, R.id.clearButton};
for(int id:idList){
View v;
v = (View) findViewById(id);
v.setOnClickListener(btnClick);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main_count, menu);
return true;
}
public void mMath(String str){
NumberBF = Integer.parseInt(Scr.getText().toString());
Operation = str;
Scr.setText("0");
}
private void getKeyboard(String str){
String ScrCurrent = Scr.getText().toString();
if(ScrCurrent.equals("0"))
ScrCurrent = "";
ScrCurrent += str;
Scr.setText(ScrCurrent);
}
public void mResult(String str){
int NumAf = Integer.parseInt(Scr.getText().toString());
int result = 0;
if(str.equals("+1")){
result = NumAf + 1;
}
if(str.equals("+5")){
result = NumAf + 5;
}
if(str.equals("+10")){
result = NumAf + 10;
}
if(str.equals("-1")){
result = NumAf - 1;
}
if(str.equals("-5")){
result = NumAf - 5;
}
if(str.equals("-10")){
result = NumAf - 10;
}
Scr.setText(String.valueOf(result));
}
// ButtonListener class
private class ButtonClickListener implements View.OnClickListener{
public void onClick(View v) {
switch (v.getId()) {
case R.id.clearButton: //Clears stitches for this row
Scr.setText("0");
NumberBF = 0;
Operation = "";
break;
case R.id.stitchPlus1:
Operation = "+1";
mResult(Operation);
break;
case R.id.stitchPlus5:
Operation = "+5";
mResult(Operation);
break;
case R.id.stitchPlus10:
Operation = "+10";
mResult(Operation);
break;
case R.id.stitchMin1:
Operation = "-1";
mResult(Operation);
break;
case R.id.stitchMin5:
Operation = "-5";
mResult(Operation);
break;
case R.id.stitchMin10:
Operation = "-10";
mResult(Operation);
break;
default:
String numb = ((Button) v).getText().toString();
getKeyboard(numb);
break;
}
}
}
}
You're not initializing your btnClick ButtonClickListener. Try changing your code to the following:
btnClick = new ButtonClickListener();
for(int id:idList){
View v;
v = (View) findViewById(id);
v.setOnClickListener(btnClick);
}
I was trying to make a rating type questions and i want to set the values in the radio button.. but i can't compute for the sum of the checked buttons.. this is my code..
public class MainActivity extends Activity {
public RadioButton r0,r1,r2,r3,r4,r5,r6,r7,r8,r9;
public RadioGroup rg1,rg2;
public TextView tv1;
public Button btn1;
public static int a,b,c,d,e,a1,b1,c1,d1,e1,total;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
r0 = (RadioButton)findViewById(R.id.radio0);
r1 = (RadioButton)findViewById(R.id.radio1);
r2 = (RadioButton)findViewById(R.id.radio2);
r3 = (RadioButton)findViewById(R.id.radio3);
r4 = (RadioButton)findViewById(R.id.radio4);
r5 = (RadioButton)findViewById(R.id.radio5);
r6 = (RadioButton)findViewById(R.id.radio6);
r7 = (RadioButton)findViewById(R.id.radio7);
r8 = (RadioButton)findViewById(R.id.radio8);
r9 = (RadioButton)findViewById(R.id.radio9);
btn1 = (Button)findViewById(R.id.button1);
tv1 = (TextView)findViewById(R.id.textView7);
rg1 = (RadioGroup)findViewById(R.id.radioGroup1);
rg2 = (RadioGroup)findViewById(R.id.radioGroup2);
btn1.setOnClickListener(new OnClickListener(){
public void onClick(View v) {
switch(rg1.getCheckedRadioButtonId()){
case R.id.radio0:
if (r0.isChecked()){
a =1;
}
break;
case R.id.radio1:
if (r1.isChecked()){
b = 2;
}
break;
case R.id.radio2:
if (r2.isChecked()){
c = 3;
}
break;
case R.id.radio3:
if (r3.isChecked()){
d = 4;
}
break;
case R.id.radio4:
if (r4.isChecked()){
e = 5;
}
break;
}
//no. 2
switch(rg2.getCheckedRadioButtonId()){
case R.id.radio5:
if (r5.isChecked()){
a1=1;
}
break;
case R.id.radio6:
if (r6.isChecked()){
b1 = 2;
}
break;
case R.id.radio7:
if (r7.isChecked()){
c1 = 3;
}
break;
case R.id.radio8:
if (r8.isChecked()){
d1 = 4;
}
break;
case R.id.radio9:
if (r9.isChecked()){
e1 = 5;
}
break;
}
// i want to get the two checked radio button and output the result.. pls help me
total = rg1.getCheckedRadioButtonId() + rg2.getCheckedRadioButtonId();
tv1.setText("result: "+total);
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
Look at this:
total = rg1.getCheckedRadioButtonId() + rg2.getCheckedRadioButtonId();
you are trying to add RadioButtonId's which are radio1, radio2, etc.
There are likely many ways to do this but I think I would create a sum variable that adds the chosen number to it.
case R.id.radio5:
if (r5.isChecked()){
//a1=1;
sum += 1;
}
and finally
tv1.setText("result: "+ sum);
you would need to reset sum each time so it doesn't keep adding to previous.
I'm here... again, having a lot of problems.
First, my app is parsing a local xml.
public class CountiesHandler {
final int stateUnknown = 0;
final int stateContinente = 1;
final int statePais = 2;
final int stateOperador = 3;
final int stateFrecuencia = 4;
final int stateFirma = 5;
final int stateGsm = 6;
final int stateGprs = 7;
final int stateT3g = 8;
final int statePrepago = 9;
final int stateSms = 10;
final int stateZona = 11;
final int stateEstatus = 12;
int currentState = stateUnknown;
int type;
int cm = R.xml.coberturamundial;
Counties counties;
County county;
public CountiesHandler (int _type) {
counties = new Counties();
type = _type;
}
public Counties getCounties(){
return counties;
}
public void parseCounties(Activity activity) throws XmlPullParserException, IOException {
Resources resource = activity.getResources();
XmlResourceParser xrp = resource.getXml(cm);
xrp.next();
int eventType = xrp.getEventType();
while (eventType != XmlPullParser.END_DOCUMENT){
if(eventType == XmlPullParser.START_DOCUMENT){
//START DOCUMENT
}else if(eventType == XmlPullParser.START_TAG){
//START TAG
String element = xrp.getName();
if(element.equalsIgnoreCase("county")){
county = new County();
}else if(element.equalsIgnoreCase("continente")){
currentState = stateContinente;
}else if(element.equalsIgnoreCase("pais")){
currentState = statePais;
}else if(element.equalsIgnoreCase("operador")){
currentState = stateOperador;
}else if(element.equalsIgnoreCase("frecuencia")){
currentState = stateFrecuencia;
}else if(element.equalsIgnoreCase("firma")){
currentState = stateFirma;
}else if(element.equalsIgnoreCase("gsm")){
currentState = stateGsm;
}else if(element.equalsIgnoreCase("gprs")){
currentState = stateGprs;
}else if(element.equalsIgnoreCase("t3g")){
currentState = stateT3g;
}else if(element.equalsIgnoreCase("prepago")){
currentState = statePrepago;
}else if(element.equalsIgnoreCase("sms")){
currentState = stateSms;
}else if(element.equalsIgnoreCase("zona")){
currentState = stateZona;
}else if(element.equalsIgnoreCase("estatus")){
currentState = stateEstatus;
}
}else if(eventType == XmlPullParser.END_TAG){
//END TAG
if(xrp.getName().equalsIgnoreCase("county")){
endElement();
}
}else if(eventType == XmlPullParser.TEXT){
//TEXT
String text = xrp.getText();
setElement(text);
}else{
currentState = stateUnknown;
}
eventType = xrp.next();
}
}
void setElement(String text){
switch(currentState){
case stateContinente:
county.setContinente(text);
break;
case statePais:
county.setPais(text);
break;
case stateOperador:
county.setOperador(text);
break;
case stateFrecuencia:
county.setFrecuencia(text);
break;
case stateFirma:
county.setFirma(text);
break;
case stateGsm:
county.setGsm(text);
break;
case stateGprs:
county.setGprs(text);
break;
case stateT3g:
county.setT3g(text);
break;
case statePrepago:
county.setPrepago(text);
break;
case stateSms:
county.setSms(text);
break;
case stateZona:
county.setZona(text);
break;
case stateEstatus:
county.setEstatus(text);
break;
}
}
void endElement() {
counties.add(county);
}
}
Then I have
public class CountiesAdapter {
private Activity activity;
private List<County> data;
private static LayoutInflater inflater=null;
public CountiesAdapter(Activity a, List<County> d) {
activity = a;
data=d;
inflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
public int getCount() {
return data.size();
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public static class ViewHolder{
public TextView text;
}
public View getView(int position, View convertView, ViewGroup parent) {
View vi=convertView;
ViewHolder holder;
if(convertView==null){
holder=new ViewHolder();
vi = inflater.inflate(R.layout.countylistitem, null);
holder.text = (TextView)vi.findViewById(R.id.countylistleyend);
vi.setTag(holder);
}else
holder=(ViewHolder)vi.getTag();
String txt = data.get(position).getPais();
holder.text.setText(txt);
return vi;
}
}
and I'm traying to show a search box, obviously that search, within the listview
public class SelectAdonde extends Activity {
private EditText ed;
int textlength=0;
#Override
public void onCreate(Bundle icicle)
{
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
super.onCreate(icicle);
setContentView(R.layout.countylist);
ed=(EditText)findViewById(R.id.search_box);
ed.addTextChangedListener(new TextWatcher() {
public void afterTextChanged(Editable s) {
}
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
public void onTextChanged(CharSequence s, int start, int before, int count) {
textlength=ed.getText().length();
}
});
;
}
}
But I dont know how to integrate the listview, all the examples are with ArrayAdapter and I'm a beginner with Java and even more with Android.
Could someone help me? Please! Thanks.
Store it in a database before putting it in Listview. Then retrieve the data from the database using a cursor adapter and bind the cursor adapter to the listview.