Passing numerical data between EditText and Variables, and vice versa - java

In the following code, I'm trying to pass numerical data from two EditText fields to two variables, perform a computation (multiplication), then have the result displayed in a third EditText field.
I have tried two different scenarios but whenever I try running the code, the the program crashes. Below is the first scenario:
package edu.arizona.uas.fonji.bmicalculator;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import java.text.DecimalFormat;
public class BmiCalculator extends ActionBarActivity {
Button reset_button, calculate_button;
EditText height_text;
EditText weight_text;
EditText bmi_text;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_bmi_calculator);
EditText height_text = (EditText)findViewById(R.id.height); //get value from height text box
String height_string = height_text.getText().toString(); //convert to string
final float height_value = Integer.parseInt(height_string); //convert to number
EditText weight_text = (EditText)findViewById(R.id.weight); //get value from weight text box
String weight_string = weight_text.getText().toString(); //convert to string
final float weight_value = Integer.parseInt(weight_string); //convert to number
calculate_button.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
DecimalFormat df = new DecimalFormat("#.0");
double adouble = weight_value*height_value;
bmi_text.setText("Number is " + df.format(adouble));
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.bmi_calculator, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
Having the impression this code crashes because I try to collect the data and convert (height_text and weight_text) outside OnClickListener(), resulting in possibly no data being collected at all I modified it in the scenario below and I also tried to safeguard from run time exceptions such as invalid input as follows:
package edu.arizona.uas.fonji.bmicalculator;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import java.text.DecimalFormat;
public class BmiCalculator extends ActionBarActivity {
Button reset_button, calculate_button;
EditText height_text;
EditText weight_text;
EditText bmi_text;
TextView myTextView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_bmi_calculator);
calculate_button.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
float height_value = 0;
float weight_value = 0;
EditText height_text = (EditText)findViewById(R.id.height); //get value from height text box
try{
String height_string = height_text.getText().toString(); //convert to string
height_value = Integer.parseInt(height_string); //convert to number
}catch(Exception e){
myTextView.setText("Error, invalid character");
}
EditText weight_text = (EditText)findViewById(R.id.weight); //get value from weight text box
try{
String weight_string = weight_text.getText().toString(); //convert to string
weight_value = Integer.parseInt(weight_string); //convert to number
}catch(Exception e){
myTextView.setText("Error, Invalid character");
}
DecimalFormat df = new DecimalFormat("#.0");
double adouble = weight_value*height_value;
bmi_text.setText("Number is " + df.format(adouble));
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.bmi_calculator, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
In either case, I still can't get this to work properly. How can I fix this problem? The .xml code is listed below:
<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="edu.arizona.uas.fonji.bmicalculator.BmiCalculator" >
<Button
android:id="#+id/reset"
android:layout_width="300dp"
android:layout_height="wrap_content"
android:layout_above="#+id/calculate"
android:layout_alignParentLeft="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="26dp"
android:text="reset" />
<Button
android:id="#+id/calculate"
android:layout_width="300dp"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_marginBottom="37dp"
android:text="calculate" />
<EditText
android:id="#+id/height"
android:layout_width="100dp"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_marginTop="16dp"
android:ems="10"
android:inputType="number"
android:hint="height" >
</EditText>
<EditText
android:id="#+id/weight"
android:layout_width="100dp"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/height"
android:layout_below="#+id/height"
android:ems="10"
android:hint="weight"
android:inputType="number"
/>
<EditText
android:id="#+id/bmi"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/weight"
android:layout_below="#+id/weight"
android:layout_marginTop="36dp"
android:ems="10"
android:hint="bmi">
<requestFocus />
</EditText>
<TextView
android:id="#+id/report_error"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignRight="#+id/reset"
android:layout_alignTop="#+id/height"
android:padding="24dp"
/>
</RelativeLayout>

Related

Android Button not working?

I want to make an app that takes input as feet and inches, and cost per feet, and calculates the cost of rod. It is a pretty simple app,I have done most of the work, but when I click at the calculate Button, in place of "result", my answer should come.
Now here is the XML code:
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="#string/ft"
android:id="#+id/feet"
android:layout_marginTop="41dp"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
<EditText
android:layout_width="100dp"
android:layout_height="wrap_content"
android:id="#+id/feet1"
android:layout_alignBottom="#+id/feet"
android:layout_toRightOf="#+id/feet"
android:inputType="text" />
<EditText
android:layout_width="100dp"
android:layout_height="wrap_content"
android:id="#+id/inches"
android:layout_alignBottom="#+id/feet"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:inputType="text" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="#string/in"
android:id="#+id/Inches"
android:layout_alignBottom="#+id/feet"
android:layout_toLeftOf="#+id/inches"
android:layout_toStartOf="#+id/inches" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="#string/cost"
android:id="#+id/cost"
android:layout_marginTop="60dp"
android:layout_below="#+id/feet"
android:layout_toRightOf="#+id/feet"
android:layout_toEndOf="#+id/feet" />
<EditText
android:layout_width="100dp"
android:layout_height="wrap_content"
android:id="#+id/calcost"
android:layout_alignBottom="#+id/cost"
android:layout_toRightOf="#+id/cost"
android:layout_toEndOf="#+id/cost"
android:inputType="text" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/cal"
android:id="#+id/calculate"
android:layout_below="#+id/cost"
android:layout_centerHorizontal="true"
android:layout_marginTop="73dp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="#string/ans"
android:id="#+id/result"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="123dp" />
And here is the Java code:
package com.example.baqir.saecost;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;
public class MainActivity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void add(View v)
{
RelativeLayout rel= (RelativeLayout) findViewById(R.id.rel);
final TextView result= (TextView)findViewById(R.id.result);
EditText et1= (EditText)findViewById(R.id.feet1);
EditText et2= (EditText) findViewById(R.id.inches);
EditText ct= (EditText)findViewById(R.id.calcost);
final double a=Double.parseDouble(String.valueOf(et1.getText()));
final double b=Double.parseDouble(String.valueOf(et2.getText()));
final double c=Double.parseDouble(String.valueOf(ct.getText()));
final Button button = (Button) findViewById(R.id.calculate);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View g) {
double i;
i=(a+(b/12))*c;
result.setText(i+" Rs");
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
Change your code like this:
public void add(View v)
{
RelativeLayout rel= (RelativeLayout) findViewById(R.id.rel);
final TextView result= (TextView)findViewById(R.id.result);
EditText et1= (EditText)findViewById(R.id.feet1);
EditText et2= (EditText) findViewById(R.id.inches);
EditText ct= (EditText)findViewById(R.id.calcost);
final double a=Double.parseDouble(String.valueOf(et1.getText()));
final double b=Double.parseDouble(String.valueOf(et2.getText()));
final double c=Double.parseDouble(String.valueOf(ct.getText()));
final Button button = (Button) findViewById(R.id.calculate);
// button.setOnClickListener(new View.OnClickListener() {
// public void onClick(View g) {
double i;
i=(a+(b/12))*c;
result.setText(i+" Rs");
// }
// });
}
and in your XML change add onClick, as:
<Button
android:onClick="add"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/cal"
android:id="#+id/calculate"
android:layout_below="#+id/cost"
android:layout_centerHorizontal="true"
android:layout_marginTop="73dp" />
I got it your issue just add this line in XML layout where your Button is
android:onClick="add"
public class MainActivity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
RelativeLayout rel= (RelativeLayout) findViewById(R.id.rel);
final TextView result= (TextView)findViewById(R.id.result);
EditText et1= (EditText)findViewById(R.id.feet1);
EditText et2= (EditText) findViewById(R.id.inches);
EditText ct= (EditText)findViewById(R.id.calcost);
final double a=Double.parseDouble(String.valueOf(et1.getText()));
final double b=Double.parseDouble(String.valueOf(et2.getText()));
final double c=Double.parseDouble(String.valueOf(ct.getText()));
final Button button = (Button) findViewById(R.id.calculate);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View g) {
double i;
i=(a+(b/12))*c;
result.setText(i+" Rs");
}
});
}
}
remove method and write your code in oncreate method.
package com.example.baqir.saecost;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;
public class MainActivity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
RelativeLayout rel= (RelativeLayout) findViewById(R.id.rel);
final TextView result= (TextView)findViewById(R.id.result);
EditText et1= (EditText)findViewById(R.id.feet1);
EditText et2= (EditText) findViewById(R.id.inches);
EditText ct= (EditText)findViewById(R.id.calcost);
final Button button = (Button) findViewById(R.id.calculate);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View g) {
double i;
final double a=Double.parseDouble(String.valueOf(et1.getText()));
final double b=Double.parseDouble(String.valueOf(et2.getText()));
final double c=Double.parseDouble(String.valueOf(ct.getText()));
i=(a+(b/12))*c;
result.setText(i+" Rs");
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
As long as the XML files are ok (The IDs are the one you actually used ,not mixed up or anything) ,this should fix your problem.
You were taking the values from the editTexts before pressing the button...so practically, after you wrote anything in there, the code that was grabbing the values, was executed already.
Initialize your all views in oncreate method it should work

Total values in a TextView and put the total in another textview for android

I have some values in one textView. as example:
200
300
100
500
How to total up these values and put it in another textview? When i open the application, it stopped. Help me..3 days now i'm stuck here
This is the code:
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;
public class MainActivity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView textView = (TextView) findViewById(R.id.t1);
TextView textView1 = (TextView) findViewById(R.id.t2);
textView.setText(100+"\n" + 200+"\n" + 300+"\n");
String toParse = textView.getText().toString(); //get the text from the source textview
String [] numbers = toParse.split("\\r?\\n");
int total = 0;
for(String s : numbers)
{
total += Integer.parseInt(s);
}
textView1.setText(total); //set the text to the target textview
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
layout:
<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:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin" tools:context=".MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="100 200 300 400"
android:id="#+id/t1"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="New Text"
android:id="#+id/t2"
android:layout_below="#+id/t1"
android:layout_centerHorizontal="true"
android:layout_marginTop="82dp" />
</RelativeLayout>
btw, i'm still new to android.:D
You can get the text from your textview and split them by newline which is then stored in array and adding them by converting the string to integer
String toParse = tvObject.getText().toString(); //get the text from the source textview
String [] numbers = toParse.split("\\r?\\n");
int total = 0;
for(String s : numbers)
{
total += Integer.parseInt(s);
}
secondTvObject.setText(total); //set the text to the target textview

How do i make list of items and amounts with an add item button that displays a new item with a button click?

I have created the start of an item/amount list with EditText fields but would like it so the total sits directly under the amount and for every new item/amount I add, they would sit just underneath the item/amount above them and the total would then jump down to sit under the newest amount field.
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="com.paulk.homebillcalc.HomeBills" >
<TextView
android:id="#+id/monthNameTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:layout_marginLeft="86dp"
android:layout_marginStart="86dp"
android:layout_marginTop="31dp"
android:text="#string/month" />
<Spinner
android:id="#+id/monthchooser"
android:entries="#array/months_list"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_marginTop="23dp"
android:layout_toEndOf="#+id/monthNameTextView"
android:layout_toRightOf="#+id/monthNameTextView"
android:prompt="#string/months" />
<TextView
android:id="#+id/PoundSign"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/itemAmountText"
android:layout_alignBottom="#+id/itemAmountText"
android:layout_marginStart="10dp"
android:layout_marginLeft="10dp"
android:layout_toLeftOf="#+id/itemAmountText"
android:layout_toStartOf="#+id/itemAmountText"
android:text="#string/pound_sign"
android:textSize="20sp" />
<Button
android:id="#+id/addItemButton"
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="52dp"
android:text="#string/add_item" />
<EditText
android:id="#+id/itemAmountText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/monthchooser"
android:layout_marginTop="26dp"
android:layout_toEndOf="#+id/addItemButton"
android:layout_toRightOf="#+id/addItemButton"
android:ems="5"
android:hint="#string/item_amount"
android:inputType="numberDecimal" />
<TextView
android:id="#+id/PoundSign1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/totalAmountText"
android:layout_alignBottom="#+id/totalAmountText"
android:layout_toLeftOf="#+id/totalAmountText"
android:layout_toStartOf="#+id/totalAmountText"
android:text="#string/pound_sign"
android:textSize="20sp" />
<EditText
android:id="#+id/itemNameText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/PoundSign"
android:layout_alignBottom="#+id/PoundSign"
android:layout_toLeftOf="#+id/addItemButton"
android:layout_toStartOf="#+id/itemAmountText"
android:ems="8"
android:hint="#string/item_name"
android:inputType="text" >
<requestFocus />
</EditText>
<EditText
android:id="#+id/totalAmountText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignRight="#+id/itemAmountText"
android:layout_alignEnd="#+id/itemAmountText"
android:layout_alignLeft="#+id/itemAmountText"
android:layout_below="#+id/itemAmountText"
android:layout_marginTop="18dp"
android:ems="5"
android:hint="#string/total_amount"
android:inputType="numberDecimal" />
</RelativeLayout>
Code
package com.paulk.homebillcalc;
import android.support.v7.app.ActionBarActivity;
import android.text.Editable;
import android.text.TextWatcher;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
public class HomeBills extends ActionBarActivity implements OnClickListener{
private final static String MONTH_OF_YEAR = "MONTH_OF_YEAR";
private final static String NAME_OF_ITEM = "NAME_OF_ITEM";
private final static String ITEM_AMOUNT = "ITEM_AMOUNT";
private final static String TOTAL = "TOTAL";
private Spinner monthChooser;
private String itemName;
private double itemAmount;
private double total;
EditText itemNameEdit;
EditText itemAmountEdit;
EditText totalEdit;
Button addField;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home_bills);
addListenerToMonthSelector();
addListenerOnButton();
//if new session
if(savedInstanceState ==null){
itemName = "";
itemAmount = 0;
total = 0;
}else{
//if its a saved session
itemName = savedInstanceState.getString(NAME_OF_ITEM);
itemAmount = savedInstanceState.getDouble(ITEM_AMOUNT);
total = savedInstanceState.getDouble(TOTAL);
}
itemNameEdit = (EditText) findViewById(R.id.itemNameText);
itemAmountEdit = (EditText) findViewById(R.id.itemAmountText);
totalEdit = (EditText) findViewById(R.id.totalAmountText);
addField = (Button) findViewById(R.id.addItemButton);
addField.setOnClickListener(this);
itemAmountEdit.addTextChangedListener(itemAmountListener);
}
private TextWatcher itemAmountListener = new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
try{
itemAmount = Double.parseDouble(s.toString());
}catch(Exception e){
itemAmount = 0;
}
updateTotalAmount();
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
// TODO Auto-generated method stub
}
#Override
public void afterTextChanged(Editable s) {
// TODO Auto-generated method stub
}
};
private void updateTotalAmount() {
//the pulls out the characters from the field, and converts the double value to a string
double itemAmount = Double.parseDouble(itemAmountEdit.getText().toString());
double total = itemAmount;
totalEdit.setText(String.format("%.02f", total));
}
private void addListenerOnButton() {
monthChooser = (Spinner) findViewById(R.id.monthchooser);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.home_bills, menu);
return true;
}
public void addListenerToMonthSelector(){
monthChooser = (Spinner) findViewById(R.id.monthchooser);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onClick(View v) {
if(v == addField){
itemNameEdit = (EditText) findViewById(R.id.itemNameText);
itemAmountEdit = (EditText) findViewById(R.id.itemAmountText);
itemAmountEdit.setVisibility(View.VISIBLE);
}
}
}

ParseUser search

I am trying to create a simple user search page for my app. I tried to create a ParseQuery and display results in a Listview in my main activity page. However, when I run program, I could not get a result of a search, program displays nothing. I will be happy if I get an answer.
Here is my MainActivity.java;
package com.example.searchtest;
import java.util.ArrayList;
import java.util.List;
import com.parse.*;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
public class MainActivity extends ActionBarActivity {
private Button search;
private EditText searchArea;
private ListView userList;
private String uName;
private ArrayAdapter<ParseUser> mainAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Parse.initialize(this, "WHz2GmkGFIUxBir6ZEDt2FIG4WUcE1kfKZmPayxy", "IAs1RCaRt5LM1E1ZW7LFXy5uDjtZEQ5CDa3LKJt2");
setContentView(R.layout.activity_main);
search = (Button) findViewById(R.id.searchButton);
searchArea = (EditText) findViewById(R.id.searchField);
userList = (ListView) findViewById(R.id.results);
mainAdapter = new ArrayAdapter<ParseUser>(this, R.layout.activity_main, R.layout.search_list );
//mainAdapter.setTextKey("username");
userList.setAdapter(mainAdapter);
//mainAdapter.loadObjects();
uName = searchArea.getText().toString();
search.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
ParseQuery<ParseUser> query = ParseUser.getQuery();
query.whereEqualTo("username", uName);
query.findInBackground(new FindCallback<ParseUser>() {
public void done(List<ParseUser> objects, ParseException e) {
if (e == null) {
for(int i=0; i<objects.size();i++)
{
mainAdapter.add((ParseUser)objects.get(i));
}
} else {
// Something went wrong.
e.printStackTrace();
}
}
});
userList.setAdapter(mainAdapter);
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
And my main activity 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"
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="com.example.searchtest.MainActivity" >
<EditText
android:id="#+id/searchField"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginTop="29dp"
android:ems="10" >
<requestFocus />
</EditText>
<Button
android:id="#+id/searchButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/editText1"
android:layout_alignParentRight="true"
android:text="Search" />
<ListView
android:id="#+id/results"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/editText1"
android:layout_centerHorizontal="true"
android:layout_marginTop="19dp" >
</ListView>
</RelativeLayout>
I solved this problem. Here is updated version of code;
package com.example.searchtest;
import java.util.ArrayList;
import java.util.List;
import com.parse.*;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends ActionBarActivity {
private Button search;
private EditText searchArea;
private ListView userList;
//private String uName;
private ArrayAdapter<ParseUser> mainAdapter;
private ArrayList<ParseUser> resultList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Parse.initialize(this, "WHz2GmkGFIUxBir6ZEDt2FIG4WUcE1kfKZmPayxy", "IAs1RCaRt5LM1E1ZW7LFXy5uDjtZEQ5CDa3LKJt2");
setContentView(R.layout.activity_main);
search = (Button) findViewById(R.id.searchButton);
searchArea = (EditText) findViewById(R.id.searchField);
userList = (ListView) findViewById(R.id.userResultList);
resultList = new ArrayList<ParseUser>();
mainAdapter = new ArrayAdapter<ParseUser>(this, R.layout.list_item, R.id.user_results,resultList);
//mainAdapter.setTextKey("username");
//userList.setAdapter(mainAdapter);
//mainAdapter.loadObjects();
search.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
final String uName = searchArea.getText().toString();
final ParseQuery<ParseUser> query = ParseUser.getQuery();
query.whereEqualTo("username", uName);
query.findInBackground(new FindCallback<ParseUser>() {
public void done(List<ParseUser> objects, ParseException e) {
if (e == null) {
for(int i=0; i<objects.size();i++)
{
resultList.add((ParseUser)objects.get(i));
}
userList.setAdapter(mainAdapter);
Toast.makeText(getApplicationContext(), "User is Found",
Toast.LENGTH_LONG).show();
} else {
// Something went wrong.
e.printStackTrace();
Toast.makeText(getApplicationContext(), "User is not Found",
Toast.LENGTH_LONG).show();
}
}
});
userList.setAdapter(mainAdapter);
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
Moreover I need one more xml file to display the list. it is list_item.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" >
<!-- Single ListItem -->
<!-- Product Name -->
<TextView android:id="#+id/user_results"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:padding="10dip"
android:textSize="16dip"
android:textStyle="bold"/>
</LinearLayout>
and main xml file, 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"
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="com.example.searchtest.MainActivity" >
<EditText
android:id="#+id/searchField"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginTop="29dp"
android:ems="10" >
<requestFocus />
</EditText>
<Button
android:id="#+id/searchButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/editText1"
android:layout_alignParentRight="true"
android:text="Search" />
<ListView
android:id="#+id/userResultList"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/searchField"
android:layout_below="#+id/searchField"
android:layout_marginTop="39dp" >
</ListView>
</RelativeLayout>
put uName = searchArea.getText().toString(); inside the listener, you are setting uName only once when the view is created, so it will be empty. You need to get the text after the user enters input and the button is clicked.

Can't get text from editText Android

I'm having some issues with my school project. I can't get the text from the textbox. I searched for a solution but nothing found.. I'll be grateful if somebody help me :)
So here is my Java code:
package com.src.vicnote;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBar;
import android.support.v4.app.Fragment;
import android.content.Context;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.os.Build;
public class NewNoteActivity extends ActionBarActivity {
Button saveButton;
EditText textData;
Context context;
String text;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_new_note);
saveButton = (Button) this.findViewById(R.id.buttonSave);
saveButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
textData = (EditText) findViewById(R.id.editText);
text = textData.getText().toString();
//text = "this is sparta!";
Log.d("ADebugTag", "string: \"" + text + "\" end of note text");
new SaveClass(text/*, context.getApplicationContext()*/);
}
});
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment()).commit();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.new_note, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_new_note,
container, false);
return rootView;
}
}
}
And my XML
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.src.vicnote.NewNoteActivity"
tools:ignore="MergeRootFrame" >
<Button
android:id="#+id/buttonSave"
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:text="Save" />
<EditText
android:id="#+id/editText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:layout_below="#+id/buttonSave"
android:ems="10"
android:gravity="top"
android:inputType="textMultiLine" >
<requestFocus />
</EditText>
</RelativeLayout>
Also I want to ask you what will happen if the text is cyrillic? Will be there any problem?
Can't really tell what your error is without a logCat.
but one thing that might fix your problem is replacing
textData = (EditText) findViewById(R.id.editText);
text = textData.getText().toString();
with
textData = (EditText)getActivity().findViewById(R.id.editText);
text = textData.getText().toString();
// Toast for debugging purposes
Toast.makeText(getActivity(),text,0).show();
When using Fragments you should really read about getView() & getActivity().
Update
where in the xml have you set the text?
you need to set your text to something before you actually call the getText() command.
<EditText
android:id="#+id/editText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:layout_below="#+id/buttonSave"
android:ems="10"
android:gravity="top"
----- add this line ------
android:text="whatever you want"
--------------------------
android:inputType="textMultiLine" >
Good Luck
Adding a getActivity() did the trick before accessing the editText.
For example:
EditText addressText = (EditText) getActivity().findViewById(R.id.location);
getEditableText return an editable object, and you can't edit the object like that, so it is null.
simply use "getText" instead.
I don't know about Cyrillic, but it shouldn't cause any problems.

Categories