Whenever I try to press a radio button on my emulator, it just force closes!
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button b = (Button)this.findViewById(R.id.btn_confirm);
b.setOnClickListener(this);
RadioButton radio_ctf = (RadioButton) findViewById(R.id.radio_ctf);
RadioButton radio_ftc = (RadioButton) findViewById(R.id.radio_ftc);
radio_ctf.setOnClickListener(this);
radio_ftc.setOnClickListener(this);
}
#Override
public void onClick(View v)
{
TextView tv = (TextView)this.findViewById(R.id.tv_result);
EditText et = (EditText)this.findViewById(R.id.et_name);
RadioButton radio_ctf = (RadioButton) findViewById(R.id.radio_ctf);
RadioButton radio_ftc = (RadioButton) findViewById(R.id.radio_ftc);
double y = 0;
int x = Integer.parseInt(et.getText().toString());
if(radio_ctf.isChecked())
{
y = ((double)x * 1.8) + 32;
}
if(radio_ftc.isChecked())
{
y = ((double)x - 32) * 0.555;
}
String text = "Result:" + y;
tv.setText(text);
first of all, look at the error (DDMS button, if you use eclipse) in the DDMS console.
There are a lot of reason for such error. Practically it mean, that there is unhandled java exception.
my guess that you are getting an Exception due to the value that you pass to Integer.parseInt()
you need to validate the string before parsing it.
to validate the string read the following post:
Java library to check whether a String contains a number without exceptions
Related
I'm trying to run a simple iris classifier in an Android app. I created a MLP in keras, converted it into .pb format and put it into an assets folder. The keras model:
data = sklearn.datasets.load_iris()
x=data.data
y=data.target
x=np.array(x)
y=np.array(y)
x_train, x_test, y_train, y_test= train_test_split(x, y, test_size = 0.25)
inputs=Input(shape=(4,))
x=Dense(10,activation="relu",name="input_layer")(inputs)
x=Dense(10,activation="relu")(x)
x=Dense(15,activation="relu")(x)
x=Dense(3,activation="softmax",name="output_layer")(x)
model=Model(inputs,x)
sgd = SGD(lr=0.05, momentum=0.9, decay=0.0001, nesterov=False)
model.compile(optimizer=sgd, loss="sparse_categorical_crossentropy", metrics=["accuracy"])
model.fit(x_train,y_train,batch_size=20, epochs=100, verbose=0)
The code in AndroidStudio(I have 4 fields for input numbers,1 output field and 1 Button. The predictClick method gets called when the button gets clicked):
static{
System.loadLibrary("tensorflow_inference");
}
String model_name ="file:///android_asset/iris_model.pb";
String output_name = "output_layer";
String input_name = "input_data";
TensorFlowInferenceInterface tfinterface;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tfinterface = new TensorFlowInferenceInterface(getAssets(),model_name);
}
public void predictClick(View v){
TextView antwort = (TextView)findViewById(R.id.antwort);
EditText number1 = (EditText)findViewById(R.id.number1);
EditText number2 = (EditText)findViewById(R.id.number2);
EditText number3 = (EditText)findViewById(R.id.number3);
EditText number4 = (EditText)findViewById(R.id.number4);
Button predict = (Button)findViewById(R.id.button);
float[] result = {};
String zahl1 = number1.getText().toString();
String zahl2 = number2.getText().toString();
String zahl3 = number3.getText().toString();
String zahl4 = number4.getText().toString();
float n1 = Float.parseFloat(zahl1);
float n2 = Float.parseFloat(zahl2);
float n3 = Float.parseFloat(zahl3);
float n4 = Float.parseFloat(zahl4);
float[] inputs={n1,n2,n3,n4};
//im pretty sure these lines cause the error
tfinterface.feed(input_name,inputs,4,1);
tfinterface.run(new String[]{output_name});
tfinterface.fetch(output_name,result);
antwort.setText(Float.toString(result[0]));
}
The build runs without error, but when I hit the predict button the app chrashes. When I leave the the lines
tfinterface.feed(input_name,inputs,4,1);
tfinterface.run(new String[]{output_name});
tfinterface.fetch(output_name,result);
out the app runs correctly, so I think that's were the error comes from.
Your model's input layer is named "input_layer" in the python code, but "input_data" in the Java code.
Also check your logcat output. You should get an error message stating, that the model doesn't have the input layer you're searching for.
Im doing an App on Android Studio and im trying to add all my checkbox IDs into an array, so i can use it , without doing it manually.
I tried to do it on another way, but i didn´t find nothing on google that help me,
So here is my goal:
I want to get all my Checkbox ids, so i can get their text. And i don´t want to do it manually because i got alot of checkboxs.
I tried to write a code by myself but i´m getting an message error.
Here is my code:
CheckBox[] MinhaCheckBox;
SharedPreferences Dados;
String MinhaPasta = "Pasta";
String valor;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void btn_Gerar(View v)
{
Dados = getSharedPreferences(MinhaPasta,0);
SharedPreferences.Editor Edita = Dados.edit();
int IDTexBoz[] = {R.id.checkBox,R.id.checkBox2,R.id.checkBox3,R.id.checkBox4,R.id.checkBox5,
R.id.checkBox6,R.id.checkBox7,R.id.checkBox8};
for(int i = 0 ; i < IDTexBoz.length; i++)
{
*//I GOT AN ERRO HERE. please help me.*
* // when i try to put mycheckbox on my array, i got th error!*
MinhaCheckBox[i] = (CheckBox)findViewById(IDTexBoz[i]);
}
for (int a= 0; a < MinhaCheckBox.length;a++)
{
if(MinhaCheckBox[a].isChecked())
valor += MinhaCheckBox[a].getText().toString() + ";";
}
Edita.putString("Dado", valor);
Edita.commit();
Intent MeuIntent = new Intent(this,Main2Activity.class);
startActivity(MeuIntent);
}
}
You need to initialize your checkbox array.
Maybe this example could help, you don't need to store the ID name, do something like this..
for(int i=1;i<=12 ;i++){
int resID = getResources().getIdentifier("checkBox"+i, "id",getPackageName());
CheckBox cb = (CheckBox) findViewById(resID);
//Handle cb object here
}
It's Very Simple.
int IDTexBoz[] = {R.id.checkBox,R.id.checkBox2,R.id.checkBox3,R.id.checkBox4,R.id.checkBox5,
R.id.checkBox6,R.id.checkBox7,R.id.checkBox8};
//Here is code for array initialization.
MinhaCheckBox = new CheckBox[IDTexBoz.length];
Recently I've started to mess around with Android Studio and decided to make an app. I've made the most of my app, but I encounter a little problem. I need to memorize in a variable a number from user input, but I don't know how to that, I've tried solutions found on the internet, even here but I get an error.
Can somebody help me with some ideas or the code edited which I must put in my app ?
This is the java code for the activity:
public class calc_medie_teza extends ActionBarActivity implements View.OnClickListener {
EditText adaug_nota;
static final int READ_BLOCK_SIZE = 100;
TextView afisare;
TextView afisare2;
Button calc;
EditText note_nr;
EditText nota_teza;
int suma;
double medie;
double medieteza;
int nr_note = 0;
int notamedie;
int notateza;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_calc_medie_teza);
afisare = (TextView) findViewById(R.id.afisare);
afisare2 = (TextView) findViewById(R.id.afisare2);
calc = (Button) findViewById(R.id.calc);
calc.setOnClickListener(this);
note_nr = (EditText) findViewById(R.id.note_nr);
nota_teza = (EditText) findViewById(R.id.nota_teza);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_calc_medie_teza, menu); // creare meniu
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId(); // meniu
return id == R.id.action_settings || super.onOptionsItemSelected(item);
}
public void onClick(View v) // afisare medie
{
calcul_medie();
}
public void buton_adauga(View v)
{
if(note_nr == )
suma = suma + notamedie;
nr_note = nr_note + 1;
}
public double calcul_medie() // calculul mediei
{
medie = suma / nr_note;
medieteza = ((medie * 3)+ notateza)/4;
return medieteza;
}
Here is a photo with the activity: http://onlypro.ro/img/images/ootllv2f55hnwdgi0xlv.png
Basically the app needs to add the input number to variable when I press the "Adauga nota" [Add grade] button and then I have to insert the "teza" number and when press the "Calculeaza media" [Calculate] the app will then calculate the calcul_medie() and return a decimal number. Between "Introduceti notele aici" [Add grades here] and "Adaugata nota"[Add grade] I have a Number enter text, the same is between "Introduceti teza aici" [Add thesis bere] and "Calculeaza media" [Calculate]. I don't know how to store the number the user puts in and sum it in "notamedie" variable.
I hope you understand my problem.
For any questions you'll have I'll respond as soon as I can.
Thanks in advance !
Well, I think your probably asked how to get the input of the String from the UI and translate them into Integer/BigDecimal. If so, here is some solution:
first, you get get the string from the UI:
String input = note_nr.getText().toString().trim();
change the string input to integer/BigDecimal:
int number1 = Integer.parseInt(input);
BigDecimal number2 = new BigDecimal(input);
Correct me if misunderstood your questions. Thanks.
I did not understand the problem at all. Please clearly define the problem and use english if you can. As fas the I understood there will be a Edittext to which the user will input the value. Gets its value in the activity and then use it.
EditText edittext;
editext = (EditText) findViewById(R.id.editext);
String value = edit text.getText().toString(); // the value that the user inputted in String data format
// Here for addition you will need the value in int or decimal for that
int valueInt = Integer.parse(value); // this will be the value in int type
double valueInt = = Double.parseDouble(value); // this will be the value (user inputted) in double data type ( which you will need if you want to use decimal numbers).
When you press a button just retrieve the appropriate value from the edittext in the following way
edittext = (EditText)layout.findViewById(R.id.txtDescription);
String string = edittext.getText().toString();
to retrieve the text do this
String string = note_nr.getText().toString();
// Converting String to int
int myValue =Integer.parseInt(string);
I tried that one more time, but the IDE says that the variable I used for "string" is never used, but I've used it.
number1= (EditText) findViewById(R.id.number1);
String number_1 = number1.getText().toString();
number2= (EditText) findViewById(R.id.number2);
String number_2= number2.getText().toString();
R3muSGFX, can you post the whole codes?
String number_1 = number1.getText().toString(); this line codes just mean that you initialized a String variable "number_1".
and you will used it when app perform a math function, like you wrote in the beginning:
public double calcul_medie()
{
medie = suma / nr_note;
medieteza = ((medie * 3)+ notateza)/4;
return medieteza;
}
but if you did not use "number_1" at all, IDE will imply you the warning message
:the variable I used for "string" is never used
So i'm having a problem in my code which is probably simple to solve but its my first app so cut me some slack. When I enter no values in my editText box my app crashes. Im semi aware why it occurs but I cant seem to solve it.
public void onButtonClick( View v)
{
Double n1 , n2 , answer1;
EditText e1 = (EditText) findViewById(R.id.num1);
EditText e2 = (EditText) findViewById(R.id.num2);
TextView t1 = (TextView) findViewById(R.id.answer);
n1 = Double.parseDouble(e1.getText().toString());
n2 = Double.parseDouble(e2.getText().toString());
if (n1.toString().length()< 0 || n2.toString().length()< 0){
t1.setText("Please enter a number into both the base and height");
}else {
answer1 = ((n1 * n2) / 2);
t1.setText(Double.toString(answer1));
}
}
First check if there is input in both EditTexts and only if there is convert it to Double:
if (e1.getText().length() == 0 || e2.getText().length() == 0) {
t1.setText("Please enter a number into both the base and height");
} else {
n1 = Double.parseDouble(e1.getText().toString());
n2 = Double.parseDouble(e2.getText().toString());
answer1 = ((n1 * n2) / 2);
t1.setText(Double.toString(answer1));
}
EditText.getText() will never return null (as per source code) so it's safe to use methods on it (such as length().
if (!e1.getText().toString().isEmpty()) {
// do stuff
}
I am developing a simple questionnaire-like app which includes lots of radio buttons joined into groups and spinners. I have multiple activities (6); some of them having RBs and some Spinners to let the user answer the questions.
The following step, which I have trouble with, is how to fetch lots of selections (of all the radio buttons/choices) and possibly do that in a for loop (so I don't have to initialize each new variable 30+ times in a row for just one activity). I've already assigned IDs to all of the views, but am having a hard time how to actually fetch the selection, initialize a new var corresponding to the selection (let's say radio button 1 in radio group 1 gives me a new variable with a value of 1) and then make the variables available to all of the activities (should I use global when initializing?).
My failed attempt on generating 10 variables for the first "page"
public void goTo2(View v) {
checkRB();
Intent intent1 = new Intent(Vprasalnik1.this, Vprasalnik2.class);
startActivity(intent1);
finish();
}
public void checkRB()
{
for (int i=0;i<9;i++)
{
RadioButton "vRB" + i; //I'd like to loop and initialize vars by adding a number to them (vRB1, vRB2, ...)
}
}
Put variables into array like a
int size = 9;
RadioButton[] views = new RadioButton[size];
public static checkRB()
{
for(int i=0;i<size;i++)
{
views[i] = (RadioButton)findViewByID(...);//For example
}
}
Or make a structure :
public class Choise
{
int mRadioButtonChoise;
int mSpinnerChoise;
}
And use something like this:
...
Choise c = new Choise();
c.mRadioButtonChoise = yourRadioButtonID;
c.mSpinnerChoise = youtSpinnerChoiseID;
...
Using a variable to identify a resource:
RadioButton[] rb = new RadioButton[size];
public static checkRB()
{
for(int i=0;i<size;i++)
{
int id = context.getResources().getIdentifier("vRB" + i, "id", context.getPackageName())
rb[i] = (RadioButton)findViewByID(id);
}
}
If you have an array of RadioButtons then you can get all the values at the same time, however initializing them will have to be manual.
RadioButton rb[];
boolean rbc[];
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
rbc=new boolean[200];
rb=new RadioButton[200]();
rb[0]=(RadioButton)findViewById(R.id.rb1);
rb[1]=(RadioButton)findViewById(R.id.rb2);
rb[2]=(RadioButton)findViewById(R.id.rb3);
rb[3]=(RadioButton)findViewById(R.id.rb4);
// many more.
}
public void checkRB()
{
for (int i=0;i<9;i++)
{
rbc[i]=rb.isChecked(); //I'd like to loop and initialize vars by adding a number to them (vRB1, vRB2, ...)
}
}
Then before starting your intent add all relevant data to it.
So I've managed to cramp up the radio buttons activity, so that it finally works. If anyone is interested - I've used tags in xml code to properly assign values (1, 2 and 3 for each group of buttons) and managed to get an output in my testToast. At least I didn't have to initialize all of the variables manually - I've been saving the values into an ArrayList and then appended to them via StringBuilder.
Thanks to everyone who tried to help - it turned out I've needed a bit more research, testing and teasing my half-awake brain.
btn = (Button) findViewById(R.id.v3_btn1);
btn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
for(int i = 1; i <= 36; i++)
{
tmpRGid = "radioGroup_v3q" + i;
tmp2RGid = getResources().getIdentifier(tmpRGid, "id", getPackageName());
RGid = (RadioGroup) findViewById(tmp2RGid);
selectedOption = RGid.getCheckedRadioButtonId();
RBid = (RadioButton) findViewById(selectedOption);
addToIDList.add((String)RBid.getTag());
}
String testToast = "";
StringBuilder builder = new StringBuilder();
builder.append("Vaša izbira (");
for (int z=0; z < addToIDList.size(); z++) {
testToast = addToIDList.get(z);
builder.append(testToast + ", ");
}
builder.setLength(builder.length() - 2);
builder.append(") je bila shranjena.");
Toast.makeText(Vprasalnik3.this, builder, Toast.LENGTH_LONG).show();