I'm trying to get the parameters that are provided by the previous activities. The number of parameters is not fixed and my method should be able to read all of them (from 1 to n). The number of the parameters is given by the parameter n_inputs. I've tried to do it with the following code, which is correct by the compiler, but it has some problem and I don't know where...I think it must be something related with the array param[ ]. Could you help me, please??
double params[];
int n_inputs;
#Override
protected void onCreate(Bundle savedInstanceState)
{
//I'm gonna get the parameters from the previous activity
Bundle b = getIntent().getExtras();
//here I get the number of inputs from the previous activity
n_inputs = b.getInt("ninputs");
// I create a new array with dimension "i_inputs"
params= new double[n_inputs];
if(n_inputs>0)
{
for (int i=0;i<n_inputs;i++)
{
params[i] = b.getDouble("param"+(i+1));
}
}
super.onCreate(savedInstanceState);
setContentView(R.layout.activity);
//Now I try to show the parameters in a toast
Context context = getApplicationContext();
CharSequence text = "parameter 1 "+params[0] +" param 2 "+ params[1] ;
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
}
Thank you very much!!
You could use Bundle.putDoubleArray() and Bundle.getDoubleArray() will be simpler anyway.
Related
I am making an app that work like calculator..
Here is my code snippet.
EditText etfirst,etsecond;
Button btnadd;
etfirst = (EditText)findViewById(R.id.etfirst);
etsecond = (EditText)findViewById(R.id.etsecond);
btnadd = (Button)findViewById(R.id.btnadd);
btnadd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
int first,second,result;
first= Integer.valueOf(etfirst.getText().toString());
second = Integer.valueOf(etsecond.getText().toString());
result = first + second;
tvresult.setText("Result: " + result); }
});
My problem is that when i get integer value from EditText into TextView it is not working ..
I also tried Integer.parseInt(String a); but it is also not helpful..
Please guide me how to make my code properly
use property inputType:number or also can numberDecimal value of inputType.
because by default edittext will accept all character/number etc. but typecast to integer only will work on numeric value.
Change this line
tvresult.setText("Result: " + result);
as
tvresult.setText("Result: " + String.valueOf(result));
and in the exception it is saying NullPointerException bind the variable tvresult with your xml object.
i have a resulttextview that shows the result of a computation. I would like to pass the value of the this resulttextview so that it will show in a toast.
i have this code:
Toast.makeText(MyCalcActivity.this,message, Toast.LENGTH_LONG).show();
but this code is showing the value of the firstnumberTxt where i type the first number to be calculated instead. :(
Button plusBtn = (Button) findViewById(R.id.plusButton1);
plusBtn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
EditText inputOne = (EditText) findViewById(R.id.firstnumberTxt);
String message = inputOne.getText().toString();
EditText inputTwo = (EditText) findViewById(R.id.secondnumberTxt);
String message2 = inputTwo.getText().toString();
int first = Integer.parseInt(message);
int second = Integer.parseInt(message2);
int sum = first + second;
TextView resultTxt = (TextView) findViewById(R.id.resultTextview);
resultTxt.setText("Result is " + sum);
Toast.makeText(MyCalcActivity.this, message, Toast.LENGTH_LONG).show();
}
});
}
is there a way i can do this please?
I think you are a starter, and just copied the code without knowing it even.
So let me get it straight forward to you.
//Actual toast
Toast.makeText(MyCalcActivity.this, message, Toast.LENGTH_LONG).show();
// Exaplaining toast
Toast.makeText(1, 2, 3).show();
In first parameter 1, it is the activity where the toast will be
shown. Like you see in your code, it is MyCalcActivity.this which
means it is your current activity because of the input of this.
In the second parameter 2, it is what you want to be shown. See in your code you have used message and from your code, we can know that message is a string that has the value of an editText you have that is called inputOne. But you don't want that, right? You want the value of the textView resultTxt so why you are using message?! Replace message with resultText.getText() to get the value of the textview you want.
In the last parameter, which is 3. It is the length of the toast message. How long do you want it? That what it is for. In you code it is set for Long toast message which I think it is about 3 seconds. If you want a shorter one, use Toast.LENGTH_SHORT or a customized duration.
So at the end, This is your wanted code.
Toast.makeText(MyCalcActivity.this, resultTxt.getText().toString(), Toast.LENGTH_LONG)
.show();
Sorry for taking too long, but loved to help you. We all started from the bottom. But please next time search before you ask, there are a lot of similar questions and answers explaining them like this.
First you are calling message in the toast
Toast.makeText(MyCalcActivity.this, message, Toast.LENGTH_LONG).show();
Instead to display the value of sum in the toast do,
Toast.makeText(MyCalcActivity.this, sum, Toast.LENGTH_LONG).show();
Or if you want to display the value in the resultTextView, do
Toast.makeText(MyCalcActivity.this, resultText.getText().toString(), Toast.LENGTH_LONG).show();
Right now you're putting message into the toast, the value of "firstnumberTxt", instead of using the result that you just finished calculating.
All you need to do is use the result in the toast:
Toast.makeText(MyCalcActivity.this, sum, Toast.LENGTH_LONG).show();
You can also go the long way and get what is in the TextView:
Toast.makeText(MyCalcActivity.this, resultText.getText().toString(), Toast.LENGTH_LONG).show();
Button plusBtn = (Button) findViewById(R.id.plusButton1);
plusBtn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
EditText inputOne = (EditText) findViewById(R.id.firstnumberTxt);
String message = inputOne.getText().toString();
EditText inputTwo = (EditText) findViewById(R.id.secondnumberTxt);
String message2 = inputTwo.getText().toString();
int first = Integer.parseInt(message);
int second = Integer.parseInt(message2);
int sum = first + second;
TextView resultTxt = (TextView) findViewById(R.id.resultTextview);
resultTxt.setText(String.valueOf(sum));
Toast.makeText(MyCalcActivity.this,"Result is" + resultTxt, Toast.LENGTH_LONG).show();
}
});
}
In my app, I am trying to get my activity to change text on a button. When I call the ansGen() method in onCreate() , I get a black screen.
And after a while, an error comes up and the app closes.
But when the ansGen() method call in onCreate() is commented, it shows up alright (obviously without the functions of the ansGen() method.
Here is my code with the ansGen() method (without imports and onCreateOptionsMenu):
public class QuizActivity extends Activity
{
Button Answer1;
Button Answer2;
Button Answer3;
Button Answer4;
String[] QuestionArray =
{ "What element has atomic number 1?",
"What is the second most abundant element on Earth?",
"Element with symbol Li ?", "Has 4 protons?" };
String[] AnswerArray =
{ "Hydrogen", "Helium", "Lithium", "Beryllium", "Boron", "Carbon",
"Nitrogen" };
public String tempStringy="";
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_quiz);
int AnsArraylen=AnswerArray.length;
Answer1 = (Button) findViewById(R.id.Answer1);
Answer2 = (Button) findViewById(R.id.Answer2);
Answer3 = (Button) findViewById(R.id.Answer3);
Answer4 = (Button) findViewById(R.id.Answer4);
//AnswerArray[randAnswers[0]]
Answer1.setText("Hello");
Answer2.setText("Hello");
Answer3.setText("Hello");
Answer4.setText("Hello");
**ansGen(AnsArraylen);**
}
public void ansGen(int AnsArraylen)
{
Random randomizer=new Random();
int[] AnsVal={-1,-1,-1,-1};
int numchecker=0;
for (int x=0;x<4;x+=1)
{
int tempVal=randomizer.nextInt(AnsArraylen);
if (tempVal==AnsVal[0])
{
numchecker=1;
}
if (tempVal==AnsVal[1])
{
numchecker=1;
}
if (tempVal==AnsVal[2])
{
numchecker=1;
}
if (tempVal==AnsVal[3])
{
numchecker=1;
}
if (numchecker==0)
{
AnsVal[x]=tempVal;
}
if (numchecker==1)
{
x-=1;
}
}
tempStringy=AnswerArray[AnsVal[0]];
//Answer1.setText("Hup");
}
I have searched everywhere with no avail.
Thank you for any help!
When you call randomizer.nextInt(AnsArraylen) you can get values between 0 and 3, inclusive. If this tempVal is 0, you are fine, as you just set the AnsArray[x] to the current tempVal. However, what happens when tempVal is 1, for example? You go into none of those ifs, except for the last one, which sets x to -1, so on the next loop iteration it'll become 0 again. Besides whether this makes sense to you, the mistake is in the next line. You are in that case doing:
tempStringy=AnswerArray[AnsVal[0]];
but AnsVal[0] is still -1. You are therefore trying to do:
AnswerArray[-1]
That's where you are getting an Exception. Wrap that in a try-catch and print the stack trace to confirm. Perhaps you wanted to initialize AnsVal as:
int[] AnsVal={0,1,2,3};
I tested your code and find that
if (numchecker==1)
{
x-=1;
}
this condition in your code make the x for loop with value 1 so it will be infinitive loop each time x will be with value 2 this condition make x = 1 so the condition in loop x < 4 will not occur and you will get message with (wait or close program) message
i don't know your logic in code , so try to handler it
Within the app I have different activity pages that call for the user to enter numerical data. I think of storing the data as below so I can use it on the final activity:
public void onClick(View v) {
String variable1 = input.getText().toString();
Double.parseDouble(variable1); //stores information put into variable
{ Intent myintent = (new Intent(step1.this,step2.class));
myintent.putExtra("variable1",variable1);
startActivity(myintent);
I do this same process for all the other activities up to the final one where I have:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);{
setContentView(R.layout.activity_iie);
Bundle extras = getIntent().getExtras(); //retrieves variables stored for formula
if(extras !=null){
double variable1 = extras.getDouble("VARIABLE1");
double vari2 = extras.getDouble("VARI2");
double vari3 = extras.getDouble("VARI3");
double finalvari = extras.getDouble("finalvari");
double solution= ((((vari2 - vari1) / (vari3) + finalvari)));
String lastString = "Result:" + solution; //prints out
TextView lastText = (TextView) findViewById(R.id.solution1);
lastText.setText(lastString);
}
I don't have any errors, but when I get to this final activity it prints out "Result:NaN". I'm trying to figure out why it is printing NaN; everything is set as a double.
What could cause this?
Update
#Melquiades
Yes I replaced the strings with the doubles as shown below:
'c.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
double variable1 = Double.parseDouble(input.getText().toString()); //stores information put into variable
{ Intent myintent = (new Intent(step1.this,step2.class));
myintent.putExtra("variabele1",variabele1);
startActivity(myintent);
'
Then in my final activity that is suppose to print the answer:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);{
setContentView(R.layout.activity_iie);
Bundle extras = getIntent().getExtras(); //retrieves variables stored formula
if (extras != null){
double variable1 = extras.getDouble("variable1");
double vari2 = extras.getDouble("vari2");
double vari3 = extras.getDouble("vari3");
double engagement = extras.getDouble("engagement1");
double solution= ((((vari2-variable1)/(vari3))+finalvari));
String lastString = "Result:" +solution; //prints out
TextView lastText= (TextView) findViewById(R.id.solution1);
lastText.setText(lastString);
Decided to post some more to potentially help like you suggested.
In the launching end, you just set one extra variable1.
In the receiving end, you attempt to four values from extras:
double variable1 = extras.getDouble("VARIABLE1");
double vari2 = extras.getDouble("VARI2");
double vari3 = extras.getDouble("VARI3");
double finalvari = extras.getDouble("finalvari");
getDouble() will return 0.0 if the key is not present.
Now, in here
double solution= ((((vari2-vari1)/(vari3)+finalvari)));
you divide by zero, which in floating point math causes the result to be Not a Number (NaN).
Key issue is that put String into intent:
String variable1 = input.getText().toString();
Double.parseDouble(variable1); //stores information put into variable
//...
myintent.putExtra("variable1",variable1); <- variable1 is a string,
and when you extract it later with getDouble() you will get, quote :
0.0 if no mapping of the desired type exists for the given key
So you should put double in your intent instead :
double variable1 = Double.parseDouble(input.getText().toString());
myintent.putExtra("variable1",variable1);
Please note, it is very important to use identical key String for mapping, when you extract your double, i.e. use "variable1", case-sensitive :
double extractedVar1 = extras.getDouble("variable1");
You could use extras.containsKey() to verify that your mapping exists.
All the advices are correct. but you are doing one cardinal mistake...
When you're sending your variables, you do:
myIntent.putExtra("variable1", variable1);
Then when your receive, you do:
double variable1 = extras.getDouble("VARIABLE1");
Your keys are NOT THE SAME. 'variable1' and 'VARIABLE1' are not equal, hence instead of the value of variable 1, you are probably getting 0 instead, and all your calculations are wrong.
For this reason, it's a good practice to use static finals for keys. Declare in your first activity:
public static final String KEY_VARIABLE1 = "variable1";
Use it when inserting in an intent:
myIntent.putExtra(KEY_VARIABLE1, variable1);
And when retrieving:
double variable = extras.getDouble(ActivityWhereThisKeyIsDeclared.KEY_VARIABLE1);
Do it for all your variables.
I'm working on a android app that send and recieves data. In the app i have a button an a few texviews. When i press the button then data (two chars) will be send. And an the data that has been send will be shown in two tekst views.
I did the same with two integers and that worked now i want to do the same with bytes and chars and that failes.
The logcat gives the following error:
10-28 09:27:19.338: E/AndroidRuntime(13138): android.content.res.Resources$NotFoundException: String resource ID #0x0
Beloww is the onClick lisener code:
#Override
public void onClick(View v) {
// Control value
ArrayOutput[0] = 'B';
ArrayOutput[1] = 'B';
//Creating TextView Variable
TextView text = (TextView) findViewById(R.id.tv);
//Creating TextView Variable
TextView statustext = (TextView) findViewById(R.id.status);
//Sets the new text to TextView (runtime click event)
text.setText("You Have click the button");
// Convert string to bytes
ArrayOutput[0] = ArrayRecieved[0];
ArrayOutput[1] = ArrayRecieved[1];
final char Byte1 = (char) ArrayOutput[0];
final char Byte2 = (char) ArrayOutput[1];
final TextView Xtext = (TextView) findViewById(R.id.xtext);
final TextView Ytext = (TextView) findViewById(R.id.ytext);
Ytext.setText(Byte1);
Xtext.setText(Byte2);
try
{
statustext.setText("Sending....");
server.send(ArrayOutput);
statustext.setText("Sending succes");
}
catch (IOException e)
{
statustext.setText("Sending failed");
Log.e("microbridge", "problem sending TCP message", e);
}
}
});
Does anybody have a sugestion what the problem might be? Any suggestions is welcome! if i need to supply more information please say so.
Update
Thanks you all for your suggestions! For the onclick function it works! I tried to do the same for the recieve function. This event handler funnction is called when there is data avalable.
When i use the setText function it crashes my ap after a few cycles, in this function i have three settext operations. only the first one is called (then the app crashes). When i change the ordere of these operations then still only the first one is called. Could it be that the app displays the first settext operation but crashes? I use dummy data, so when the eventhandler function is called the actual recieved data is not used, but still the app crashes after the first operation. Does anybody have a sugestion?
On the other side data is send every second.
Below is the onRecieve (event handler)function:
#Override
public void onReceive(com.example.communicationmodulebase.Client client, byte[] data)
{
Log.e(TAG, "In handler!");
//Control value
ArrayRecieved[0] = 'C';
ArrayRecieved[1] = 'B';
if (data.length < 2){
return;
}
// Set data that has been recieved in array
//ArrayRecieved[0] = data[0];
//ArrayRecieved[1] = data[1];
char Byte1 = (char) ArrayRecieved[0] ;
char Byte2 = (char) ArrayRecieved[1] ;
TextView Xtext = (TextView) findViewById(R.id.xtext);
TextView Ytext = (TextView) findViewById(R.id.ytext);
Xtext.setText(""+Byte2);
Ytext.setText(""+Byte1);
TextView textRecvStatus = (TextView) findViewById(R.id.RecvStatusText);
textRecvStatus.setText("In handler!");
}
});
TextView has two methods like
TextView.setText(CharSequence) and TextView.setText(int).
1) first method directly assigns a text to TextView which is passed as CharSequence (can be String,StringBuffer,Spannable...)
2) second methods searches for the String resource that you define in Resources with ID passed as parameter.
and you are passing char as parameter. this char is type casted into int and invokes it as TextView.setText(int) and searches for the Resource String with that int ID whose value is not defined in Resources.
type cast char as String like String.valueOf(char) and try once...
The signature for the method you are using takes a CharSequence, hence sequence of characters. Using setText(someEmptyString + Byte1), you create a sequence of characters from the concatenation of someEmptyString (which you would define as "") and Byte1.
set with some change like
Ytext.setText(""+Byte1);
setText() expects string or resource id (int). If you want to display numeric value, you need to convert it to string, i.e.:
setText(String.valueOf(someInt));
Try out as below:
Ytext.setText(""+Byte1);
Xtext.setText(""+Byte2);