Android 4 SDK text.getText() error in Eclipse - android

I been thinking about developing for Android for some time now, and I finally took the plunge.
Eclipse is set up, Android SDK, and ADT Plugin for eclipse is also.
I found a tutorial on line and was following it's instructions.
My problem that I can not figure out is that Eclipse generates and error with the following code, primarily the text.setText() and text.getText() calls, it underlines the text portion of it:
Am I missing an import?
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.Toast;
public class testActivity extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
// This method is called at button click because we assigned the name to the
// "On Click property" of the button
public void myClickHandler(View view) {
switch (view.getId()) {
case R.id.button1:
RadioButton celsiusButton = (RadioButton) findViewById(R.id.radioButton1);
RadioButton fahrenheitButton = (RadioButton) findViewById(R.id.radioButton2);
if (text.getText().length() == 0) {
Toast.makeText(this, "Please enter a valid number",
Toast.LENGTH_LONG).show();
return;
}
float inputValue = Float.parseFloat(text.getText().toString());
if (celsiusButton.isChecked()) {
text.setText(String
.valueOf(convertFahrenheitToCelsius(inputValue)));
celsiusButton.setChecked(false);
fahrenheitButton.setChecked(true);
} else {
text.setText(String
.valueOf(convertCelsiusToFahrenheit(inputValue)));
fahrenheitButton.setChecked(false);
celsiusButton.setChecked(true);
}
break;
}
}
// Converts to celsius
private float convertFahrenheitToCelsius(float fahrenheit) {
return ((fahrenheit - 32) * 5 / 9);
}
// Converts to fahrenheit
private float convertCelsiusToFahrenheit(float celsius) {
return ((celsius * 9) / 5) + 32;
}
}

Instead of your code use this,
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.Toast;
public class ConvertActivity extends Activity {
private EditText text;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
text = (EditText) findViewById(R.id.editText1);
}
// This method is called at button click because we assigned the name to the
// "On Click property" of the button
public void myClickHandler(View view) {
switch (view.getId()) {
case R.id.button1:
RadioButton celsiusButton = (RadioButton) findViewById(R.id.radio0);
RadioButton fahrenheitButton = (RadioButton) findViewById(R.id.radio1);
if (text.getText().length() == 0) {
Toast.makeText(this, "Please enter a valid number",
Toast.LENGTH_LONG).show();
return;
}
float inputValue = Float.parseFloat(text.getText().toString());
if (celsiusButton.isChecked()) {
text.setText(String
.valueOf(convertFahrenheitToCelsius(inputValue)));
celsiusButton.setChecked(false);
fahrenheitButton.setChecked(true);
} else {
text.setText(String
.valueOf(convertCelsiusToFahrenheit(inputValue)));
fahrenheitButton.setChecked(false);
celsiusButton.setChecked(true);
}
break;
}
}
// Converts to celsius
private float convertFahrenheitToCelsius(float fahrenheit) {
return ((fahrenheit - 32) * 5 / 9);
}
// Converts to fahrenheit
private float convertCelsiusToFahrenheit(float celsius) {
return ((celsius * 9) / 5) + 32;
}
}
main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#color/myColor"
android:orientation="vertical" >
<EditText
android:id="#+id/editText1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="numberDecimal|numberSigned" >
</EditText>
<RadioGroup
android:id="#+id/radioGroup1"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<RadioButton
android:id="#+id/radio0"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:checked="true"
android:text="#string/celsius" >
</RadioButton>
<RadioButton
android:id="#+id/radio1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/fahrenheit" >
</RadioButton>
</RadioGroup>
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="myClickHandler"
android:text="#string/calc" >
</Button>
</LinearLayout>

You didn't declare the textedit object.
In your onCreate method add:
text = (EditText) findViewById(R.id.editText1);
editText1 maybe different, depending on ur main.xml layout file
Also add, before the onCreate method this:
private EditText text;

Seems like you have not declared text, what is it a TextView or an EditText?
Define it like this
public class testActivity extends Activity {
/** Called when the activity is first created. */
TextView text;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
text = (TextView)findViewById(R.id.yourTextViewId);
}
After declaring it this way you wouldn't see the error.

Related

Android RadioGroup Cannot resolve symbol getCheckedRadioButtonId

I am new to android. At the moment I am working on some examples in my starter book "Android 5"
In the example I am working there is some code which is not working.
XML:
<RadioGroup
android:id="#+id/rg_art"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<RadioButton
android:id="#+id/rb_art_netto"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/txt_netto"
android:textSize="16dp"
android:checked="true" />
<RadioButton
android:id="#+id/rb_art_brutto"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/txt_brutto"
android:textSize="16dp" />
</RadioGroup>
Activity:
package com.example.raven.tax_calc;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.RadioGroup;
public class FormularActivity extends Activity {
public static final String BETRAG_KEY = "betrag";
public static final String BETRAG_ART = "art";
public static final String UST_PROZENT = "ust";
// Betrag
public void onClickBerechnen(View button) {
final EditText txtBetrag = (EditText) findViewById(R.id.edt_betrag);
final String tmpBetrag = txtBetrag.getText().toString();
float betrag = 0.0f;
if(tmpBetrag.length() > 0 ){
betrag = Float.parseFloat(tmpBetrag);
}
}
// Art des Betrages (Brutto, Netto)
boolean isNetto = true;
final RadioGroup rg = (RadioGroup) findViewById(R.id.rg_art);
switch (rg.getCheckedRadioButtonId()) {
case R.id.rb_art_netto:
isNetto = "true";
break;
case R.id.rb_art_brutto:
isNetto = false;
break;
default:
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.formular_activity);
}
}
rg.getCheckedRadioButtonId is red highlighted and mouse-over says "Cannot resolve symbol"
What am I doing wrong? Can't find an mistake :-(
You should place following block of code into your on click meaning cut it and paste right after your if statement. The issue is with braces and the fact that you assign string into boolean: (isNetto = "true";)
// Art des Betrages (Brutto, Netto)
boolean isNetto = true;
final RadioGroup rg = (RadioGroup) findViewById(R.id.rg_art);
switch (rg.getCheckedRadioButtonId()) {
case R.id.rb_art_netto:
isNetto = true;
break;
case R.id.rb_art_brutto:
isNetto = false;
break;
default:
}

Android: Activity loop causes ad to refresh

In my Android Quiz app i've implemented Admob. But everytime an Answer is given and the Questions changes, Admob refreshes, too, which takes about 3-4 seconds. But by that time the Question changes again and so on.
QuestionActivity.class:
package com.tsc.walkingdead;
import java.util.List;
import com.google.ads.*;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.RadioButton;
import android.widget.TextView;
import android.widget.Toast;
import com.tsc.walkingdead.R;
import com.tsc.walkingdead.quiz.GamePlay;
import com.tsc.walkingdead.quiz.Question;
import com.tsc.walkingdead.util.Utility;
public class QuestionActivity extends Activity implements OnClickListener{
private Question currentQ;
private GamePlay currentGame;
;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.question);
// Look up the AdView as a resource and load a request.
AdView adView = (AdView)this.findViewById(R.id.adView);
adView.loadAd(new AdRequest());
/**
* Configure current game and get question
*/
currentGame = ((WalkingDeadApplication)getApplication()).getCurrentGame();
currentQ = currentGame.getNextQuestion();
Button nextBtn = (Button) findViewById(R.id.nextBtn);
nextBtn.setOnClickListener(this);
/**
* Update the question and answer options..
*/
setQuestions();
}
/**
* Method to set the text for the question and answers from the current games
* current question
*/
private void setQuestions() {
//set the question text from current question
String question = Utility.capitalise(currentQ.getQuestion()) + "??";
TextView qText = (TextView) findViewById(R.id.question);
qText.setText(question);
//set the available options
List<String> answers = currentQ.getQuestionOptions();
TextView option1 = (TextView) findViewById(R.id.answer1);
option1.setText(Utility.capitalise(answers.get(0)));
TextView option2 = (TextView) findViewById(R.id.answer2);
option2.setText(Utility.capitalise(answers.get(1)));
TextView option3 = (TextView) findViewById(R.id.answer3);
option3.setText(Utility.capitalise(answers.get(2)));
TextView option4 = (TextView) findViewById(R.id.answer4);
option4.setText(Utility.capitalise(answers.get(3)));
}
#Override
public void onClick(View arg0) {
//Log.d("Questions", "Moving to next question");
/**
* validate a checkbox has been selected
*/
if (!checkAnswer()) return;
/**
* check if end of game
*/
if (currentGame.isGameOver()){
Intent i = new Intent(this, EndgameActivity.class);
startActivity(i);
finish();
}
else{
Intent i = new Intent(this, QuestionActivity.class);
startActivity(i);
finish();
}
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event)
{
switch (keyCode)
{
case KeyEvent.KEYCODE_BACK :
return true;
}
return super.onKeyDown(keyCode, event);
}
/**
* Check if a checkbox has been selected, and if it
* has then check if its correct and update gamescore
*/
private boolean checkAnswer() {
String answer = getSelectedAnswer();
if (answer==null){
//Log.d("Questions", "No Checkbox selection made - returning");
return false;
}
else {
//Log.d("Questions", "Valid Checkbox selection made - check if correct");
if (currentQ.getAnswer().equalsIgnoreCase(answer))
{
//Log.d("Questions", "Correct Answer!");
currentGame.incrementRightAnswers();
Toast.makeText(this, "Correct!", Toast.LENGTH_LONG).show();
}
else{
//Log.d("Questions", "Incorrect Answer!");
currentGame.incrementWrongAnswers();
Toast.makeText(this, "Wrong!", Toast.LENGTH_LONG).show();
}
return true;
}
}
/**
*
*/
private String getSelectedAnswer() {
RadioButton c1 = (RadioButton)findViewById(R.id.answer1);
RadioButton c2 = (RadioButton)findViewById(R.id.answer2);
RadioButton c3 = (RadioButton)findViewById(R.id.answer3);
RadioButton c4 = (RadioButton)findViewById(R.id.answer4);
if (c1.isChecked())
{
return c1.getText().toString();
}
if (c2.isChecked())
{
return c2.getText().toString();
}
if (c3.isChecked())
{
return c3.getText().toString();
}
if (c4.isChecked())
{
return c4.getText().toString();
}
return null;
}
}
question.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#drawable/walking_dead_background2"
xmlns:ads="http://schemas.android.com/apk/lib/com.google.ads"
android:gravity="center"
android:orientation="vertical"
>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:gravity="center">
<RadioGroup
android:id="#+id/group1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:gravity="center_vertical">
<TextView
android:id="#+id/question"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
style="#style/myStyle1"
android:layout_marginBottom="10dp"/>
<RadioButton
android:id="#+id/answer1"
android:checked="false"
style="#style/myStyle"/>
<RadioButton
android:id="#+id/answer2"
android:checked="false"
style="#style/myStyle"/>
<RadioButton
android:id="#+id/answer3"
android:checked="false"
style="#style/myStyle"/>
<RadioButton
android:id="#+id/answer4"
android:checked="false"
style="#style/myStyle"/>
<Button
android:id="#+id/nextBtn"
style="#style/myStyle"
android:layout_width="80dip"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:background="#drawable/button_selector"
android:paddingBottom="5dip"
android:paddingTop="5dip"
android:text="Next"
android:textColor="#ffffff" />
</RadioGroup>
</LinearLayout>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="bottom"
android:id="#+id/mainLayout">
<com.google.ads.AdView android:id="#+id/adView"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
ads:adUnitId="ca-app-pub-6195077402939893/2503837566"
ads:adSize="BANNER"
ads:testDevices="TEST_EMULATOR"/>
</LinearLayout>
</LinearLayout>
Is it possible to let the Ad show the whole time, though the questions are changing?
Thank you
Your problem is that you are starting a new Activity in #onClick.
Don't start a new Activity, reuse the current Activity.
In this case somethig like:
#Override
public void onClick(View arg0) {
//Log.d("Questions", "Moving to next question");
/**
* validate a checkbox has been selected
*/
if (!checkAnswer()) return;
/**
* check if end of game
*/
if (currentGame.isGameOver()){
Intent i = new Intent(this, EndgameActivity.class);
startActivity(i);
finish();
}
else{
currentQ = currentGame.getNextQuestion();
setQuestions();
}
}
Try removing
adView.loadAd(new AdRequest());
from your onCreate and adding
ads:loadAdOnCreate="true"
to your ads XML.

How to keep state of RadioButton in Android?

Hi I'm trying to develop an application which runs for every interval time, lets say for every 1 minute it will display some Toast message.
But problem is I'm using RadioButton functionality is perfect but when I tap on one radio button it will be green, but when I close and re-open the activity I'll get as none of the radio buttons selected.
Here is my MainActivity.java
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void onRadioButtonClicked(View view) {
// Is the button now checked?
boolean checked = ((RadioButton) view).isChecked();
// Check which radio button was clicked
switch(view.getId()) {
case R.id.radio_one_min:
if (checked)
{
//some code
}
break;
case R.id.radio_ten_min:
if (checked)
{
//some code
}
break;
case R.id.radio_disable:
if (checked)
{
//some code
}
break;
}
}
}
and here is my activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RadioGroup xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:id="#+id/radio">
<RadioButton android:id="#+id/radio_disable"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Disable"
android:onClick="onRadioButtonClicked"/>
<RadioButton android:id="#+id/radio_one_min"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="1 minute"
android:onClick="onRadioButtonClicked"/>
<RadioButton android:id="#+id/radio_ten_min"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="10 minute"
android:onClick="onRadioButtonClicked"/>
</RadioGroup>
Please help me to solve this riddle.
Thanks in advance...
This code is useful for store the ratingbar state, when we start new activity, you will see the previous rating state..
package com.example.ratingbar;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.app.Activity;
import android.content.SharedPreferences;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.RatingBar;
import android.widget.RatingBar.OnRatingBarChangeListener;
import android.widget.TextView;
import android.widget.Toast;
public class RatingbarMainActivity extends Activity {
RatingBar ratingbarClick;
Button sub_btn;
TextView textRatingView , textRatingViewSave;
Boolean val = true;
float ans = (float) 0.0;
//--------------------------------------------------------------------------------------------
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_ratingbar_main);
ratingbarClick = (RatingBar) findViewById(R.id.ratingBar1);
ratingbarClick.setOnRatingBarChangeListener(rateObj);
SharedPreferences sharePref = PreferenceManager.getDefaultSharedPreferences
(RatingbarMainActivity.this);
ans = sharePref.getFloat("Get_Rating", 0.0f);
System.out.println("--------------------------------------ans = " + ans);
if(val) {
ratingbarClick.setRating(ans);
}
else {
ratingbarClick.setRating(ans);
}
textRatingView = (TextView) findViewById(R.id.ratingView);
}
//--------------------------------------------------------------------------------------------
//--------------------------------------------------------------------------------------------
RatingBar.OnRatingBarChangeListener rateObj = new RatingBar.OnRatingBarChangeListener() {
#Override
public void onRatingChanged(RatingBar ratingBar, float rating,boolean fromUser) {
//textRatingView.setText(String.valueOf(rating));
ans = ratingbarClick.getRating();
SharedPreferences sharePref = PreferenceManager.getDefaultSharedPreferences
(RatingbarMainActivity.this);
SharedPreferences.Editor edit = sharePref.edit();
edit.putFloat("Get_Rating", ans);
edit.commit();
val = false;
}
};
//--------------------------------------------------------------------------------------------
}
---------------------------------------------------------------------------------------------------
activity_ratingbar_main.xml file
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<TextView
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/ratingBar1"
android:layout_alignParentTop="true"
android:layout_marginLeft="15dp"
android:layout_marginTop="23dp"
android:text="Select Your Rating Bar Here"
tools:context=".RatingbarMainActivity" />
<RatingBar
android:id="#+id/ratingBar1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginLeft="21dp"
android:layout_marginTop="63dp" />
<TextView
android:id="#+id/ratingView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/ratingBar1"
android:text="TextView" />
<Button
android:id="#+id/button1"
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_centerVertical="true"
android:text="Click To Save Rating In TextBox" />
</RelativeLayout>
it is the simplest way to do so,no need of sharedpreference at all.you will get confused while using it.keep the things simple like this
public class MainActivity extends Activity {
Public static int flag=0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if(flag==1)
radio_one_min.setChecked(true);
else if(flag==2)
radio_ten_min.setCheckek(true);
else if(flag==3)
radio_disable.setCheckek(true);
}
public void onRadioButtonClicked(View view) {
// Is the button now checked?
boolean checked = ((RadioButton) view).isChecked();
// Check which radio button was clicked
switch(view.getId()) {
case R.id.radio_one_min:
if (checked)
{
flag =1;
//some code
}
break;
case R.id.radio_ten_min:
if (checked)
{
flag=2 ;
//some code
}
break;
case R.id.radio_disable:
if (checked)
{
flag=3;
//some code
}
break;
}
}
}
[EDITED]
I found developer.android.com/training/basics/activity-lifecycle/recreating.html document first, so my first guess was using Bundles and on Save/Resume Instace State methods. However this does not seem to work well. Here's my final attempt at a working solution (using SharedPreferences class, as suggested by some users):
import android.app.Activity;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.view.View;
import android.widget.RadioButton;
public class MainActivity extends Activity {
final String PREFERENCES = "prefs";
final String RADIO_BUTTON = "prefsval";
SharedPreferences sp;
Editor e;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sp = this.getSharedPreferences(PREFERENCES, MODE_PRIVATE);
e = sp.edit();
}
#Override
protected void onResume() {
super.onResume();
if (sp != null) {
if (sp.getInt(RADIO_BUTTON, 0) != 0) {
RadioButton rb;
rb = (RadioButton) findViewById(sp.getInt(RADIO_BUTTON, 0));
rb.setChecked(true);
}
}
}
public void onRadioButtonClicked(View view) {
e.putInt(RADIO_BUTTON, view.getId());
e.apply();
}
}

Simple Math Android App Not Working

I am new to Android developing and I am trying to make a simple app as practice. All it consists of is you type one number into the first box, a number into the second box, press a button and the result prints into a textview. The problem is, when I press the send button Nothing is happening. Eclipse is not showing any errors, nor is LogCat. So I am officially stumped as to why when I run this I'm not getting anything out. Hopefully you guys can help.
Here is the XML:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context=".MainActivity" >
<LinearLayout
android:id="#+id/linearLayout1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="172dp"
android:orientation="vertical" >
</LinearLayout>
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginLeft="16dp"
android:layout_marginTop="48dp"
android:text="First Number:"
android:textAppearance="?android:attr/textAppearanceMedium" />
<TextView
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignRight="#+id/textView1"
android:layout_below="#+id/textView1"
android:layout_marginTop="40dp"
android:text="Second Number:"
android:textAppearance="?android:attr/textAppearanceMedium" />
<EditText
android:id="#+id/editText1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/linearLayout1"
android:layout_alignTop="#+id/textView1"
android:ems="10"
android:inputType="number" >
<requestFocus />
</EditText>
<EditText
android:id="#+id/editText2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignTop="#+id/textView2"
android:layout_toRightOf="#+id/linearLayout1"
android:ems="10"
android:inputType="number" />
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignRight="#+id/editText2"
android:layout_below="#+id/editText2"
android:text="Calc" />
<TextView
android:id="#+id/textView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="#+id/linearLayout1"
android:layout_centerHorizontal="true"
android:text="TextView" />
</RelativeLayout>
And here is the Java:
package com.example.mathbox;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends Activity {
Button sum;
EditText num1, num2;
TextView tv;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public void main(String[] args){
num1 = (EditText) findViewById(R.id.editText1);
num2 = (EditText) findViewById(R.id.editText2);
tv = (TextView) findViewById(R.id.textView3);
num1.getText().toString();
num2.getText().toString();
int x =Integer.parseInt("num1");
int y =Integer.parseInt("num2");
int nas = x + y;
tv.setText(nas);
findViewById(R.id.button1).setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {}
});}}
You are parsing the wrong string..
num1.getText().toString();
num2.getText().toString();
int x =Integer.parseInt("num1");
int y =Integer.parseInt("num2");
What you are doing now is parsing the strings "num1" and "num2" into a string and I don't think that is what you want. So it should be:
int x = Integer.parseInt(num1.getText().toString());
int y = Integer.parseInt(num2.getText().toString());
And also move the code into the onCreate() method just like #AndroidEnthusiastic suggested.
public void main(String[] args)
For Android it is a simple method,not an entry point that by the way supposed to be :
public static void main(String[] args)
I can't see that you are calling your main method in your code.
num1.getText().toString();
num2.getText().toString();
You just get the values without assigning it to any properties.
This code is totally wrong.
I suggest you to start from the beginning with official Android Training : Building Your First App.
Hye Diamond you are doing something wrong. Its ok your beginner. see you are creating main mothod. In java main method public static void main get executed first but here once activity created oncreate method will execute. So you can do it in following ways:
//inside oncreate method do like this
num1 = (EditText) findViewById(R.id.editText1);
num2 = (EditText) findViewById(R.id.editText2);
tv = (TextView) findViewById(R.id.textView3);
findViewById(R.id.button1).setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v)
{
int val1 = num1.getText().toString();
int val2 = num2.getText().toString();
int x =Integer.parseInt(val1);
int y =Integer.parseInt(val2);
int nas = x + y;
tv.setText(nas);
}
});
this might be help you. It's not tested. May be you have to do some changes.
Here is the complete solution
package com.example.mathbox;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends Activity {
Button sum;
EditText num1, num2;
TextView tv;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
num1 = (EditText) findViewById(R.id.editText1);
num2 = (EditText) findViewById(R.id.editText2);
tv = (TextView) findViewById(R.id.textView3);
Button button = (Button)findViewById(R.id.button1);
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
num1.getText().toString();
num2.getText().toString();
int x =Integer.parseInt("num1");
int y =Integer.parseInt("num2");
int nas = x + y;
tv.setText(nas);
}
});
}
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
Please take a look at this link
Find this code.. hope it helps
public class MainActivity extends Activity {
Button sum;
EditText num1, num2;
TextView tv;
String x;
String y;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
num1 = (EditText) findViewById(R.id.editText1);
num2 = (EditText) findViewById(R.id.editText2);
tv = (TextView) findViewById(R.id.textView3);
sum = (Button) findViewById(R.id.button1);
sum.setOnClickListener(new clicker());
}
class clicker implements Button.OnClickListener {
public void onClick(View v) {
Integer nas;
x = num1.getText().toString();
y = num2.getText().toString();
nas = Integer.parseInt(x) + Integer.parseInt(y);
tv.setText(nas.toString());
}
}
}
Please try this code,
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class add extends Activity {
Button button1;
EditText txtbox1,txtbox2;
TextView tv;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
txtbox1= (EditText) findViewById(R.id.txtbox1);
button1 = (Button) findViewById(R.id.button1);
tv = (TextView) findViewById(R.id.lbl1);
txtbox2= (EditText) findViewById(R.id.txtbox2);
button1.setOnClickListener(new clicker());
}
class clicker implements Button.OnClickListener
{
public void onClick(View v)
{
String a,b;
Integer vis;
a = txtbox1.getText().toString();
b = txtbox2.getText().toString();
vis = Integer.parseInt(a)+Integer.parseInt(b);
tv.setText(vis.toString());
}
}
}
Try this,
int x =Integer.valueof(""+num1.getText().toString());
int y =Integer.valueof(""+num2.getText().toString());
int nas = x + y;
tv.setText(""+String.valueof(nas));
Please refrain from using the main function. It's not really required in an activity class and also not a general practice. #AndroidEnthusiastic has given the correct code.
Added:
Since the aforementioned answer of mine was downvoted, I'll go ahead and just tell you what you've done wrong in your code(there's a lot of code in the other answers given here).
num1 = (EditText) findViewById(R.id.editText1);
num2 = (EditText) findViewById(R.id.editText2);
tv = (TextView) findViewById(R.id.textView3);
num1.getText().toString();//Store this in a string say a
num2.getText().toString();//Store this in a string say b
/*you're actually the passing the literal "num1" or "num2". Something which you don't want.
Instead, pass the strings a and b instead of num1 and num2 respectively*/
int x =Integer.parseInt("num1");
int y =Integer.parseInt("num2");
int nas = x + y;
tv.setText(nas);
findViewById(R.id.button1).setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
/*You need to put the code here. i.e. You need to take the values from the
editTexts and store them in strings and finally integers when the button is clicked.*/
}
});

Taking double numbers back to previous activity

This is what i want to do with my application:
Open overview screen, go to calculator by button.
Than multiply two numbers.
By clicking calculate the intent will finish.
Outcome of multiply will be shown in first (main) activity.
I do not know how to do the last bit, someone any idea?
Code first (main) activity, OverviewpageActivity.java
package com.tip.calc;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class OverviewpageActivity extends Activity {
private TextView multiplydisplay2;
private Button btntocalculator;
private double multiply = 0;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.overview);
multiplydisplay2 = (TextView)findViewById(R.id.multiplydisplay2);
btntocalculator = (Button)findViewById(R.id.btntocalculator);
btntocalculator.setOnClickListener(new Button.OnClickListener() {
public void onClick (View v) {
Intent intent = new Intent(OverviewpageActivity.this,
TipcalcActivity.class);
startActivity(intent);
}
});
}
}
Code calculator acticvity, TipcalcActivity.java:
package com.tip.calc;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class TipcalcActivity extends Activity {
private EditText number1;
private EditText number2;
private TextView multiplydisplay;
private Button btncalculate;
private Button btnreset;
private double number1calc = 0;
private double number2calc = 0;
private double multiply = 0;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
initControls();
}
private void initControls() {
number1 = (EditText)findViewById(R.id.number1);
number2 = (EditText)findViewById(R.id.number2);
multiplydisplay = (TextView)findViewById(R.id.multiplydisplay);
btncalculate = (Button)findViewById(R.id.btncalculate);
btnreset = (Button)findViewById(R.id.btnreset);
btncalculate.setOnClickListener(new Button.OnClickListener() { public void
onClick (View v){ calculate(); }});
btnreset.setOnClickListener(new Button.OnClickListener() { public void
onClick (View v){ reset(); }});
}
private void calculate() {
// check if zero
if(number1.getText().toString().trim().length() < 1 ){number1calc=0;}
else{number1calc=Double.parseDouble(number1.getText().toString());}
if(number2.getText().toString().trim().length() < 1 ){number2calc=0;}
else{number2calc=Double.parseDouble(number2.getText().toString());}
//calculate
multiply=(number1calc*number2calc);
multiplydisplay.setText(Double.toString(multiply));
finish();
}
private void reset() {
multiplydisplay.setText("");
number1.setText("");
number2.setText("");
finish();
}
}
Layout file, overview.xml:
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<!-- multiply -->
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:layout_marginTop="20dp" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="multiply:" />
<TextView
android:id="#+id/multiplydisplay2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text=""
android:layout_marginLeft="20dp" />
</LinearLayout>
<Button
android:id="#+id/btntocalculator"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="To the calculator" />
</LinearLayout>
Use startActivityforResult instead of startActivity in OverviewpageActivity.java and also override OnactivityResult in OverviewpageActivity.java.
Then in second activity you can set the result using setResult. Pass the intent in setresult which will have the double value.
In OnactivityResult you can get the intent from which you can extract double

Categories

Resources