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);
}
Related
I really need your help. I've searched Google many days with many keywords, but I couldn't get it. So, I decided to ask to you.
So, here it is. Actually, I have one button in RecyclerView, but this button is repeated as much amount of data available, there are: Button with text "Baca 3x", "Baca 4x", and so on. I want, if I click button with text "Baca 3x" 3 times, it will change to "Baca 2x" >> "Baca 1x" >> remove item. Also if I click button with text "Baca 4x" 4 times, it will change to "Baca 3x" >> "Baca 2x" >> "Baca 1x" >> remove item.
But my problem is, I can't treat every button with different treatment, because every time the item has been deleted, position of data changes automatically. Because of this, I can't get specific button. For example: There is two button,
1. Button "Baca 3x" on position 0
2. Button "Baca 4x" on position 1
If button "Baca 3x" on position 0 has been deleted, so button "Baca 4x" changed it's position automatically to 0. The problem lays here.
Until now I just get every button based on their positions, which is a problem for me. Because of this I am thinking about How to Delete Item Without Deleting Position in Recycler View? Can you guys solve my problem? Should I use DiffUtil?And how to use it? Below the complete code I use:
ModelDoa.java
public class ModelDoa {
public static final int DOA_PAGI = 0;
public static final int DOA_SORE = 1;
public static final int DOA_MASJID = 2;
public static final int DOA_BANGUNT = 3;
public static final int DOA_MAU_TIDUR = 4;
private String mName;
private String bName;
private int mType;
public ModelDoa(String name, String butong, int type) {
this.mName = name;
this.bName = butong;
this.mType = type;
}
public String getName() {
return mName;
}
public void setName(String name) {
this.mName = name;
}
public int getType() {
return mType;
}
public void setType(int type) { this.mType = type; }
public String ambilName() {
return bName;
}
public void setNama(String butonk) {
this.bName = butonk;
}
}
AdapterDoa.java
public class AdapterDoa extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
public List<ModelDoa> mList;
public AdapterDoa(List<ModelDoa> list) {
this.mList = list;
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
switch (viewType) {
case DOA_PAGI:
View vieu = LayoutInflater.from(parent.getContext()).inflate(R.layout.content_doa, parent, false);
PagiViewHolder rcv = new PagiViewHolder(vieu, this);
return rcv;
case DOA_SORE:
View doa = LayoutInflater.from(parent.getContext()).inflate(R.layout.content_doa, parent, false);
SoreViewHolder mdoa = new SoreViewHolder(doa);
return mdoa;
case DOA_MASJID:
View dMasjid = LayoutInflater.from(parent.getContext()).inflate(R.layout.content_doa, parent, false);
MasjidViewHolder mMasjid = new MasjidViewHolder(dMasjid);
return mMasjid;
case DOA_BANGUNT:
View dBangunt = LayoutInflater.from(parent.getContext()).inflate(R.layout.content_doa, parent, false);
BanguntViewHolder mBangunt = new BanguntViewHolder(dBangunt);
return mBangunt;
case DOA_MAU_TIDUR:
View regut = LayoutInflater.from(parent.getContext()).inflate(R.layout.content_doa, parent, false);
MauTidurViewHolder turu = new MauTidurViewHolder(regut);
return turu;
}
return null;
}
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
ModelDoa object = mList.get(position);
if (object != null) {
switch (object.getType()) {
case DOA_PAGI:
((PagiViewHolder) holder).mTitle.setText(object.getName());
((PagiViewHolder) holder).tombolbaca.setText(object.ambilName());
break;
case DOA_SORE:
((SoreViewHolder) holder).mTitle.setText(object.getName());
((SoreViewHolder) holder).tombolbaca.setText(object.ambilName());
break;
case DOA_MASJID:
((MasjidViewHolder) holder).mTitle.setText(object.getName());
((MasjidViewHolder) holder).tombolbaca.setText(object.ambilName());
break;
case DOA_BANGUNT:
((BanguntViewHolder) holder).mTitle.setText(object.getName());
((BanguntViewHolder) holder).tombolbaca.setText(object.ambilName());
break;
case DOA_MAU_TIDUR:
((MauTidurViewHolder) holder).mTitle.setText(object.getName());
((MauTidurViewHolder) holder).tombolbaca.setText(object.ambilName());
break;
}
}
}
public void deleteItem(int position) {
mList.remove(position); // hapus list
notifyItemRemoved(position); // hapus tampilan
// notifyItemRangeChanged( position, mList.size());
}
#Override
public int getItemCount() {
if (mList == null)
return 0;
return mList.size();
}
#Override
public int getItemViewType(int position) {
if (mList != null) {
ModelDoa object = mList.get(position);
if (object != null) {
return object.getType();
}
}
return 0;
}
}
PagiViewHolder.java
public class PagiViewHolder extends RecyclerView.ViewHolder {
public TextView mTitle;
public Button tombolbaca;
public Button teksbaca;
public Button tombolshare;
private RelativeLayout rl2;
private int klik10 = 10;
private AdapterDoa myAdapter;
public PagiViewHolder(View itemView, AdapterDoa myAdapter) {
super(itemView);
this.myAdapter = myAdapter;
itemView.setOnClickListener(mainViewClickListener);
mTitle = (TextView) itemView.findViewById(R.id.titleTextView);
tombolbaca = (Button) itemView.findViewById(R.id.buttonbaca);
tombolshare = (Button) itemView.findViewById(R.id.buttonshare);
tombolbaca.setOnClickListener(bacaClickListener);
tombolshare.setOnClickListener(shareClickListener);
rl2 = (RelativeLayout) itemView.findViewById(R.id.relmasjid);
}
private View.OnClickListener bacaClickListener = new View.OnClickListener() {
#Override
public void onClick(View v) {
teksbaca = (Button) v.findViewById(R.id.buttonbaca);
// Baca 10x
if( getAdapterPosition() ==0 ) {
klik10--;
teksbaca.setText("Baca " + klik10 + "x");
if (klik10 <= 0)
{
// modify listItems however you want... add, delete, shuffle, etc
myAdapter.deleteItem(getAdapterPosition());
}
}
} // onclick
};
private View.OnClickListener shareClickListener = new View.OnClickListener() {
#Override
public void onClick(View v) {
// Do button click handling here
Intent sendIntent = new Intent();
sendIntent.setAction(Intent.ACTION_SEND);
sendIntent.putExtra(Intent.EXTRA_TEXT, mTitle.getText().toString() + "\n \n download aplikasinya di: http://www.tauhid.or.id" );
sendIntent.setType("text/plain");
Intent.createChooser(sendIntent,"Share via");
v.getContext().startActivity(sendIntent);
}
};
private View.OnClickListener mainViewClickListener = new View.OnClickListener() {
#Override
public void onClick(View v) {
// Do button click handling here
}
};
}
DoaPagi.java
public class DoaPagi extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_doa_pagi);
// toolbar
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
//this line shows back button
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
List<ModelDoa> rowListItem = getData();
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(DoaPagi.this);
RecyclerView mRecyclerView = (RecyclerView) findViewById(R.id.recyclerView);
mRecyclerView.setLayoutManager(linearLayoutManager);
mRecyclerView.setHasFixedSize(true);
AdapterDoa rcAdapter = new AdapterDoa(rowListItem);
mRecyclerView.setAdapter(rcAdapter);
}
private List<ModelDoa> getData() {
String[] data = getResources().getStringArray(R.array.doapagi);
String[] baca = getResources().getStringArray(R.array.bacapagi);
List<ModelDoa> list = new ArrayList<ModelDoa>();
for (int i = 0; i < data.length; i++) {
list.add(new ModelDoa(data[i], baca[i], ModelDoa.DOA_PAGI));
}
return list;
}
// Agar back button pada halaman induk settings berfungsi
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
this.finish();
return true;
}
return super.onOptionsItemSelected(item);
}
}
UPDATE (FIX CODE) By: Krishna Sharma:
https://github.com/seadclark/RecyclerViewWithButtonClicks
Here is the fix. just update the ModelDoa constructor as below. I have verified myself and working as expected now. Also sent you pull request on github.
public ModelDoa(String name, String butong, int type) {
this.mName = name;
this.bName = butong;
this.mType = type;
String[] data = butong.split("\\s");
if (data.length > 0) {
String count = data[1].substring(0, data[1].length() - 1);
read10 = Integer.parseInt(count);
}
}
Instead of removing the item from your list AND updating the interface, have two methods. One of them (deleteItem) will only delete the item and the other (deleteItemAndUpdate) will delete the item and update the interface.
public void deleteItem(int position) {
mList.remove(position); // hapus list
}
public void deleteItemAndUpdate(int position) {
mList.remove(position); // hapus list
notifyItemRemoved(position); // hapus tampilan
}
In the future, you can decide whether you want to only remove the item from your list OR remove the item and update the UI.
EDIT 1:
You need to keep track of the amount of times that each item was clicked. We can call this value readCount. Every time that the item is clicked, we subtract 1 from this value. When this value reaches 0, we remove it from the list.
ModelDoa:
public class ModelDoa {
private int readCount = 10;
public int getReadCount() {
return this.readCount;
}
public void setReadCount(int readCount) {
this.readCount = readCount;
}
}
PagiViewHolder:
private View.OnClickListener bacaClickListener = new View.OnClickListener() {
#Override
public void onClick(View v) {
teksbaca = (Button) v.findViewById(R.id.buttonbaca);
ModelDoa modelDoa = mAdapter.getItem(getAdapterPosition());
if (modelDoa != null) {
modelDoa.setReadCount(modelDoa.getReadCount() - 1);
if (modelDoa.getReadCount() <= 0) {
myAdapter.deleteItem(getAdapterPosition());
}
teksbaca.setText("Baca " + modelDoa.getReadCount() + "x");
}
}
};
AdapterDoa:
public ModelDoa getItem(int position) {
if (position > -1 && position < getItemCount()) {
return this.mList.get(position);
} else {
return null;
}
}
EDIT 2:
The idea is to set the readCount variable when you instantiate the object. You do not have multiple variables that do the same thing. You just change the single readCount variable to be either 7 or 10 when you are creating it and use the same getItem method when retrieving the model (not variable!) itself.
ModelDoa:
public class ModelDoa {
private String name;
private String butong;
private int type;
private int readCount;
public ModelDoa(String name, String butong, int type, int readCount) {
this.mName = name;
this.bName = butong;
this.mType = type;
this.readCount = readCount;
}
public int getReadCount() {
return this.readCount;
}
public void setReadCount(int readCount) {
this.readCount = readCount;
}
}
DoaPagi:
private List<ModelDoa> getData() {
String[] data = getResources().getStringArray(R.array.doapagi);
String[] baca = getResources().getStringArray(R.array.bacapagi);
List<ModelDoa> list = new ArrayList<ModelDoa>();
for (int i = 0; i < data.length; i++) {
// Here is where you would set the value of readCount.
list.add(new ModelDoa(data[i], baca[i], ModelDoa.DOA_PAGI, i));
}
return list;
}
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 having trouble on displaying an output on my interface.
My program should be able to display respective outputs upon inputting some parameters. If no parameters were entered, it shall display "No results" which is what I have implemented.
However, even with parameters entered . It still displays "No results" instead of the answer according to formula given.
My code is as follow:
public class FreeSpaceActivity extends Fragment implements OnClickListener {
DecimalFormat disp_W = new DecimalFormat("0.000E0");
DecimalFormat disp_dBm = new DecimalFormat("0.000");
EditText tPowerEdit = null;
EditText tGainEdit = null;
EditText rGainEdit = null;
EditText freqEdit = null;
EditText distanceEdit = null;
EditText lightEdit = null;
Button calButton = null;
Button graphButton = null;
Button clearButton = null;
Button plotButton = null;
EditText radEdit = null;//testing
private ScrollView llLayout;
private FragmentActivity faActivity;
//private Switch switch1;
// Changes here
private double mResult = 0;
private Switch mSelectUnit;
private TextView mTextFreeSpaces;
private boolean mIsCalculated;// flag to show the result only when you click on calculate button
private boolean flag;
//#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
super.onCreate(null);
faActivity = (FragmentActivity) this.getActivity();
llLayout = (ScrollView) inflater.inflate(R.layout.activity_free_space, container, false);
tPowerEdit = (EditText)llLayout.findViewById(R.id.editText1);
tGainEdit = (EditText)llLayout.findViewById(R.id.editText2);
rGainEdit = (EditText)llLayout.findViewById(R.id.editText3);
freqEdit = (EditText)llLayout.findViewById(R.id.editText4);
distanceEdit = (EditText)llLayout.findViewById(R.id.editText7);
lightEdit = (EditText)llLayout.findViewById(R.id.editText8);
calButton = (Button)llLayout.findViewById(R.id.button1);
calButton.setOnClickListener(this);
graphButton = (Button)llLayout.findViewById(R.id.button2);
graphButton.setOnClickListener(this);
clearButton = (Button)llLayout.findViewById(R.id.button3);
clearButton.setOnClickListener(this);
plotButton =(Button)llLayout.findViewById(R.id.plot_button);
plotButton.setOnClickListener(this);
radEdit = (EditText)llLayout.findViewById(R.id.editText28);//testing
// Changes here
mTextFreeSpaces = (TextView) llLayout.findViewById(R.id.textFreeSpaces);
mSelectUnit =(Switch)llLayout.findViewById(R.id.switch1);
mSelectUnit.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
updateFreeSpacesText(isChecked);
}
});
return llLayout;
}
/*private ActionBar getSupportActionBar() {
return null;
}*/
private void updateFreeSpacesText(boolean isSwitcherChecked) {
if(mIsCalculated && flag==true){
if(isSwitcherChecked){
double dBm=10 * Math.log10(mResult* 1000);
mTextFreeSpaces.setText(disp_dBm.format(dBm));//display dbm
Toast.makeText(getActivity().getApplicationContext(),"Unit Chosen is dBm", Toast.LENGTH_LONG).show();
} else {
double W=mResult;
mTextFreeSpaces.setText(disp_W.format(W));//display W
Toast.makeText(getActivity().getApplicationContext(),"Unit Chosen is W", Toast.LENGTH_LONG).show();
}
}
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
super.onCreateOptionsMenu(menu, inflater);
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
String tPowerStr = tPowerEdit.getText().toString();
String tGainStr = tGainEdit.getText().toString();
String rGainStr = rGainEdit.getText().toString();
String freqStr = freqEdit.getText().toString();
String distanceStr = distanceEdit.getText().toString();
String lightStr = lightEdit.getText().toString();
double tPower = Double.parseDouble(!tPowerStr.isEmpty() ? tPowerStr : "0");
double tGain = Double.parseDouble(!tGainStr.isEmpty() ? tGainStr : "0");
double rGain = Double.parseDouble(!rGainStr.isEmpty() ? rGainStr : "0");
double freq = Double.parseDouble(!freqStr.isEmpty() ? freqStr : "0");
double distance = Double.parseDouble(!distanceStr.isEmpty() ? distanceStr : "1");
double light = Double.parseDouble(!lightStr.isEmpty() ? lightStr : "1");
String radStr = radEdit.getText().toString();//testing
double radius = Double.parseDouble(!radStr.isEmpty() ? radStr : "0");//testing
if (v == calButton) {
if(mResult!=0) {
double lamda = 300000000 / freq;
mResult = tPower * tGain * rGain * Math.pow(lamda / (4 * Math.PI * distance), 2) / light / 100;
mIsCalculated = true;
flag = true;
updateFreeSpacesText(mSelectUnit.isChecked());
}
else
mTextFreeSpaces.setText("No results");
}
else if (v == graphButton) {
Intent intent = new Intent(getActivity(), GraphActivity.class);
intent.putExtra("model", "freeSpace");
intent.putExtra("tp", tPower);
intent.putExtra("tg", tGain);
intent.putExtra("rg", rGain);
intent.putExtra("f", freq);
intent.putExtra("l", light);
this.startActivity(intent);
} else if (v == clearButton) {
flag=false;
double lamda = 300000000 / freq;
((EditText) llLayout.findViewById(R.id.editText1)).setText(null);
((EditText) llLayout.findViewById(R.id.editText2)).setText(null);
((EditText) llLayout.findViewById(R.id.editText3)).setText(null);
((EditText) llLayout.findViewById(R.id.editText4)).setText(null);
((EditText) llLayout.findViewById(R.id.editText7)).setText(null);
((EditText) llLayout.findViewById(R.id.editText8)).setText(null);
((EditText) llLayout.findViewById(R.id.editText28)).setText(null);
((TextView) llLayout.findViewById(R.id.textFreeSpaces)).setText(null);
//((TextView) llLayout.findViewById(R.id.textFreeSpacePrd)).setText("");
//mIsCalculated = true;
//updateFreeSpacesText(mSelectUnit.isChecked());
//mResult=tPower * tGain * rGain * Math.pow(lamda / (4 * Math.PI * distance), 2) / light / 100;
//mTextFreeSpaces.setText("");
} else if (v == plotButton) {
//double radius = Double.parseDouble(radius.getText().toString());
Intent intent = new Intent(getActivity(), MapActivity.class);
Bundle b = new Bundle();
//b.putDouble("radius", result);
intent.putExtras(b);
this.startActivity(intent);
}
}
}
My interface:
I think Stultuske is right but my Reputation is to low to comment.
I would prefer that you change the statement of the IF-Clause
if (v == calButton) {
if(mResult!=0) {
.
.
.
}
else
mTextFreeSpaces.setText("No results");
otherway you're running in the else-branch everytime because your variable mResult is still 0 and hasn't changed.
Maybe you can retreive if the Edittexts are not empty like
if(tPowerStr.matches("") && The other Edittexts) {
.
.
.
}
else
mTextFreeSpaces.setText("No results");
EDIT:
By the way I'm interested in your App because I'm a directional radio and satellite communication engineer.
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.