Simple Math Android App Not Working - android

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.*/
}
});

Related

When I close my app, all the dynamically generated content is gone, so how can I save the generated content?

Does anyone have any idea how I can save the dynamically generated Textviews? So, the next time I open the app, the TextViews will display the same content that I previously put into them.
I have looked into onSaveInstanceState, onRestoreInstanceState but None of them work. Are there any libraries I can use to save generated TextViews? Or maybe any advice on a better method of doing this. I've researched this stuff for a couple of days and have found outdated information and information that doesn't seem relevant to me. Code solutions will be very much appreciated
MainActivity.java:
package com.example.savingdynamiccontent;
import android.app.Activity;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RadioGroup;
import android.widget.TextView;
import java.util.ArrayList;
public class MainActivity extends Activity {
private LinearLayout mLayout;
private LinearLayout ListItems;
static final String counter_value = "int_value";
static final String toDoList_value = "toDolist";
private EditText mEditText;
private Button mButton;
private int counter;
private ArrayList<String> toDoList;
private ArrayList<String> keys;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
this.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
if (toDoList != null){
System.out.println("Success!");
for(int i = 0; i< toDoList.size(); i++){
System.out.println(toDoList.get(i));
ListItems.addView(createNewTextView(toDoList.get(i)));
}
}
else{
System.out.println("Nope!");
toDoList = new ArrayList<String>();
}
counter = 1;
mLayout = (LinearLayout) findViewById(R.id.linearLayout);
ListItems = (LinearLayout) findViewById(R.id.listItems);
mEditText = (EditText) findViewById(R.id.editText);
mButton = (Button) findViewById(R.id.button);
mButton.setOnClickListener(onClick());
TextView textView = new TextView(this);
textView.setText("New text");
}
private View.OnClickListener onClick() {
return new View.OnClickListener() {
#Override
public void onClick(View v) {
ListItems.addView(createNewTextView(mEditText.getText().toString()));
}
};
}
private TextView createNewTextView(String text) {
final RadioGroup.LayoutParams lparams = new RadioGroup.LayoutParams(RadioGroup.LayoutParams.WRAP_CONTENT, RadioGroup.LayoutParams.WRAP_CONTENT);
final TextView textView = new TextView(this);
textView.setLayoutParams(lparams);
textView.setFreezesText(true);
textView.setText(counter + ":" + text);
textView.setId(counter);
System.out.println(textView.getId());
toDoList.add(text);
counter++;
return textView;
}
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState){
super.onRestoreInstanceState(savedInstanceState);
counter = savedInstanceState.getInt(counter_value);
toDoList = savedInstanceState.getStringArrayList("key");
// Add this for-loop to restoring your list
for(String str : toDoList){
ListItems.addView(createNewTextView(str));
}
//REad values from the savedInstanceState" -object and put them in your textview
}
#Override
protected void onSaveInstanceState(Bundle outState){
// Save the values you need from your textview into "outSTate" -object
// outState.putParcelableArrayList("key", toDoList);
outState.putInt(counter_value, counter);
outState.putStringArrayList("key", toDoList);
super.onSaveInstanceState(outState);
}
}
Activit_Main.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:id="#+id/linearLayout"
android:weightSum="1">
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:id="#+id/listItems"></LinearLayout>
<EditText
android:id="#+id/editText"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/>
<Button
android:id="#+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Add+"
/>
</LinearLayout>

My simple app closes on button click [duplicate]

This question already has an answer here:
"Unfortunately My App has stopped" [closed]
(1 answer)
Closed 4 years ago.
The app is expected to accept two numbers, and on button click, print the sum in the textView.
The layout appears as expected as this as desired :
Layout
But on button click, the app 'stops like this : Stopping message.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<EditText
android:id="#+id/editText1"
android:layout_width="120dp"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:layout_marginStart="46dp"
android:layout_marginTop="88dp"
android:ems="10"
android:inputType="number"
android:layout_alignParentLeft="true"
android:layout_marginLeft="46dp" />
<EditText
android:id="#+id/editText2"
android:layout_width="120dp"
android:layout_height="wrap_content"
android:layout_alignParentEnd="true"
android:layout_alignTop="#+id/editText1"
android:layout_marginEnd="57dp"
android:ems="10"
android:inputType="number"
android:layout_alignParentRight="true"
android:layout_marginRight="57dp" />
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="192dp"
android:text="TextView" />
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="187dp"
android:text="Button" />
</RelativeLayout>
and the java file is.
package com.example.home.myapplication;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.SpannableStringBuilder;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextClock;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
EditText et1, et2;
TextView tv1;
Button bt1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
et1 = (EditText) findViewById(R.id.editText1);
et2 = (EditText) findViewById(R.id.editText2);
tv1 = (TextView) findViewById(R.id.textView1);
bt1 = (Button) findViewById(R.id.button1);
bt1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
int num1, num2, res;
num1 = Integer.parseInt(et1.getText().toString());
num2 = Integer.parseInt(et2.getText().toString());
res = num1 + num2;
tv1.setText(res);
}
});
}
}
When I run the app, it shows the layout as desired on the mobile and also on the emulator. It also accepts the two numbers properly. But when the button is clicked, the app stops as shown. I am using Android 3.1.3.
Kindly advise where I am going wrong ?
change this line : tv1.setText(res);
into this tv1.setText(String.valueOf(res));
The cause is tv1.setText(res). There are two methods with one parameter, which are setText(Int) and setText(CharSequence). As in your code, you accidentally called the first method as you declared res as an Integer, which is interpreted as a resource id. You should call the second one by converting res to String.
Just change the line tv1.setText(res); to tv1.setText(Integer.toString(res));
package com.example.home.myapplication;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.SpannableStringBuilder;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextClock;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
EditText et1, et2;
TextView tv1;
Button bt1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
et1 = (EditText) findViewById(R.id.editText1);
et2 = (EditText) findViewById(R.id.editText2);
tv1 = (TextView) findViewById(R.id.textView1);
bt1 = (Button) findViewById(R.id.button1);
bt1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
int num1, num2, res;
num1 = Integer.parseInt(et1.getText().toString());
num2 = Integer.parseInt(et2.getText().toString());
res = num1 + num2;
tv1.setText(Integer.toString(res));
}
});
}
}
You can read up the TextView documentation to learn more about its public methods.
You are setting an integer value in textfield, which is not allowed. So you are getting an exception. In order to solve convert integer to string.
bt1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
int num1, num2, res;
num1 = Integer.parseInt(et1.getText().toString());
num2 = Integer.parseInt(et2.getText().toString());
res = num1 + num2;
tv1.setText("" + res);
}
});
Also you should apply validation. As if user clicks the button without entering any number, the app will stop. So you should add -
if(! et1.getText().toString().equals("") && ! et2.getText().toString().equals("") ) {
num1 = Integer.parseInt(et1.getText().toString());
num2 = Integer.parseInt(et2.getText().toString());
res = num1 + num2;
tv1.setText("" + res);
}
else {
Toast.makeText(this, "Enter the numbers", Toast.LENGTH_LONG).show();
}
The res variable should be String type.

cannot be resolved or is not a field with layout textview and button

I'm getting four errors all with this message: cannot be resolved or is not a field
The errors are in two different .java files
StartScreen.java.text
tv = (TextView) findViewById(R.id.startscreen); (startscreen underlined in red)
Button startButton = (Button) findViewById(R.id.play_game); (play_game underlined in red)
I creaded a textview called startscreen and a button called startButton inside game.xml
PlayGame.java
tv2 = (TextView) findViewById(R.id.game_text); (game_text underlined in red)
Button startButton = (Button) findViewById(R.id.end_game); (end_game underlined in red)
I creaded a textview called game_text and a button called end_game inside game.xml
StartScreen.java
package com.example.startscreenapp;
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 StartScreen extends Activity {
private static final int PLAY_GAME = 1010;
private TextView tv;
private int meaningOfLife = 42;
private String userName = "Douglas Adams";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv = (TextView) findViewById(R.id.startscreen.text);
//Display initial values
tv.setText(userName + ":" + meaningOfLife);
//Set up button listener
Button startButton = (Button) findViewById(R.id.play_game);
startButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
startGame();
}
});
}
#Override
protected void onActivityResult(int requestCode,
int resultCode, Intent data) {
if (requestCode == PLAY_GAME && resultCode == RESULT_OK) {
meaningOfLife = data.getExtras().getInt("returnInt");
userName = data.getExtras().getString("returnStr");
//Show it has changed
tv.setText(userName + ":" + meaningOfLife);
}
super.onActivityResult(requestCode, resultCode, data);
}
private void startGame() {
Intent launchGame = new Intent(this, PlayGame.class);
//passing information to launched activity
launchGame.putExtra("meaningOfLife", meaningOfLife);
launchGame.putExtra("userName", userName);
startActivityForResult(launchGame, PLAY_GAME);
}
}
PlayGame.java
package com.example.startscreenapp;
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 PlayGame extends Activity {
private TextView tv2;
int answer;
String author;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.game);
tv2 = (TextView) findViewById(R.id.game_text);
//reading information passed to this activity
//Get the intent that started this activity
Intent i = getIntent();
//returns -1 if not initialized by calling activity
answer = i.getIntExtra("meaningOfLife", -1);
//returns [] if not initialized by calling activity
author = i.getStringExtra("userName");
tv2.setText(author + ":" + answer);
//Change values for an example of return
answer = answer - 41;
author = author + " Jr.";
//Set up button listener
Button startButton = (Button) findViewById(R.id.end_game);
startButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
//Return information to calling activity
Intent i = getIntent();
i.putExtra("returnInt", answer);
i.putExtra("returnStr", author);
setResult(RESULT_OK, i);
finish();
}
});
}}
activity_main.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"
tools:context="${relativePackage}.${activityClass}" >
<TextView
android:id="#+id/startscreen"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginLeft="115dp"
android:layout_marginTop="164dp"
android:text="TextView" />
<Button
android:id="#+id/play_game"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/startscreen"
android:layout_below="#+id/startscreen"
android:layout_marginTop="64dp"
android:text="Button" />
</RelativeLayout>
game.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TextView
android:id="#+id/game_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="TextView" />
<Button
android:id="#+id/end_game"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button" />
</LinearLayout>
Your textview id on your xml is startscreen
Instead of v = (TextView) findViewById(R.id.startscreen.text); just remove the .text part
in startscreen.java you have tv = (TextView) findViewById(R.id.startscreen.text); and in your activity_main.xml you have android:id="#+id/startscreen".
what you should do :
1-is removing the .text from tv = (TextView) findViewById(R.id.startscreen.text);
2- clean and build you project again. (if this didn't work , close and open eclipse again.
i suggest to use ctrl + space in completing you statement, that would help in reducing error and give suggestion.

Eclipse Android Checkbox

I would like to create checkbox with text that would behave something like what i have below in pseudo code:
Set in text in EditText field
if Button clicked:
create new Checkbox with entered text.
How do i go about doing that in Android?
So far ive got the button :) ... but dont know how to get new Checkbox with text in it ,if its clicked
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.text);
Button create = (Button) findViewById(R.id.button1);
create.setOnClickListener(this);
EditText textInCheckBox = (EditText) findViewById(R.id.editText1);
}
#Override
public void onClick(View v) {
// TODO Automatisch generierter Methodenstub
switch (v.getId()) {
case R.id.button1:
//after creating new checkbox with text in it
//Editbox should restet text field to null;
break;
}
}
}
Here is some code that will demonstrate how to add checkboxes dynamically with the title you entered into the EditText.
MainActivity.java
package com.example.test;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RadioGroup;
import android.widget.Toast;
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final EditText txtTitle = (EditText) findViewById(R.id.txtTitle);
final Button btnCreate = (Button) findViewById(R.id.btnCreate);
final RadioGroup radContainer = (RadioGroup) findViewById(R.id.radContainer);
final LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
btnCreate.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String name = txtTitle.getText().toString().trim();
if (!name.isEmpty()) {
CheckBox checkBox = new CheckBox(MainActivity.this);
checkBox.setText(name);
checkBox.setLayoutParams(params);
radContainer.addView(checkBox);
} else {
Toast.makeText(MainActivity.this, "Enter a title for the checkbox", Toast.LENGTH_SHORT).show();
}
}
});
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center_horizontal"
android:orientation="vertical"
android:padding="16dp" >
<EditText
android:id="#+id/txtTitle"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:imeOptions="actionDone" />
<Button
android:id="#+id/btnCreate"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Create Checkbox" />
<RadioGroup
android:id="#+id/radContainer"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>

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