Concatenation from 2 methods in Android - android

I am trying to take the value of an integer newVal (string) from one method, to use in the toast message in another method.
Although I have declared this int newVal at the top of the class, it is only showing a 0 in the toast nessage. (And even that maybe the int value).
Everything else ie checkbox results are showing up OK, but the number picker result, newVal isn't. Yet it looks correct.
Can anyone see where I'm going wrong with the toast message ie adding/finding the value of newVal??
Many thanks in advance!
Below is the MainActivity and activity_main.xml..
package com.example.frytest;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.NumberPicker;
import android.view.View;
import android.widget.TextView;
import android.view.View.OnClickListener;
import android.widget.Toast;
import android.widget.NumberPicker.OnValueChangeListener;
public class MainActivity extends Activity {
int newVal;
private TextView tv;
Button button;
Button btnDisplay;
private CheckBox chk1, chk2, chk3, chk4;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setupUI();
addListenerOnChkIos();
}
public void setupUI()
{
tv = (TextView) findViewById(R.id.tvId);
NumberPicker np = (NumberPicker) findViewById(R.id.npId);
np.setOnValueChangedListener(new OnValueChangeListener()
{
public void onValueChange(NumberPicker picker, int oldVal,
int newVal)
{
tv.setText(String.valueOf(newVal));
}
});
np.setMaxValue(12);
np.setMinValue(0);
}
public void addListenerOnChkIos() {
chk1 = (CheckBox) findViewById(R.id.chk1);
chk2 = (CheckBox) findViewById(R.id.chk2);
chk3 = (CheckBox) findViewById(R.id.chk3);
chk4 = (CheckBox) findViewById(R.id.chk4);
btnDisplay = (Button) findViewById(R.id.btnDisplay);
btnDisplay.setOnClickListener(new OnClickListener() {
//Run when button is clicked
#Override
public void onClick(View v) {
StringBuffer result = new StringBuffer();
result.append("Haddock-Large : ").append(chk1.isChecked());
result.append("\nHaddock-Medium : ").append(chk2.isChecked());
result.append("\nHaddock-Small :").append(chk3.isChecked());
result.append("\nKids Corner : ").append(chk4.isChecked());
Toast.makeText(MainActivity.this, result.toString() + " " + String.valueOf(newVal),
Toast.LENGTH_LONG).show();
}
});
}
}
activity_main.xml
<LinearLayout 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.frytest.MainActivity"
android:background="#e83a43"
android:orientation="vertical" >
<CheckBox
android:id="#+id/chk1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Haddock(large) £4-40"
android:textColor="#ffffff"
android:textSize="20dp"
android:textStyle="bold" />
<NumberPicker android:id="#+id/npId"
android:layout_marginTop="5dp"
android:layout_width="40dp"
android:layout_height="40dp"
android:layout_marginLeft="5dp"
android:textStyle="bold"
android:background="#ffffff" />
<TextView
android:id="#+id/tvId"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="5dp"
android:layout_marginLeft="5dp"
android:textColor="#ffffff"
android:textStyle="bold"
android:text="0"
android:textSize="20sp" />
<CheckBox
android:id="#+id/chk2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Haddock(Medium) £3-00"
android:textColor="#ffffff"
android:textSize="20dp"
android:textStyle="bold" />
<CheckBox
android:id="#+id/chk3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Haddock(Small) £2.30"
android:textColor="#ffffff"
android:textSize="20dp"
android:textStyle="bold" />
<CheckBox
android:id="#+id/chk4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Chips £1-40"
android:textColor="#ffffff"
android:textSize="20dp"
android:textStyle="bold" />
<Button
android:id="#+id/btnDisplay"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button" />
</LinearLayout>

You are never calling a method that writes a value to newVal so it would be initialized with 0 by default.

it because you never change the value of newValue, when onValueChange is invoked
public void onValueChange(NumberPicker picker, int oldVal,
int newVal)
{
MainActivity.this.newVal = newVal;
tv.setText(String.valueOf(newVal));
}
or you could simply read it back from the TextView (tv), before showing the Toast

Related

My app crashed for unknown reason when I tried to setOnClickListener for a button in ListView

I'm building a Contact app using ListView. My ListView has 2 button. In this app, to test the respond ability of the buttons, I intended to set the button "Edit" so that when I click on it, it will change to "Clicked", and the button "Delete" will change to "Clicked", too. When I ran the Debug, the app stopped working and I couldn't get it work again (before I added the onClickListener, this app had worked property).
I don't know what is the error, and have tried many ways to fix.
Here is my row_listview.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent" android:layout_margin="10dp">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:weightSum="5">
<ImageView
android:id="#+id/imgAvatar"
android:layout_width="0dp"
android:layout_height="70dp"
android:layout_weight="1"
android:src="#drawable/if_male3_403019" />
<LinearLayout
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="2.7"
android:orientation="vertical"
android:weightSum="2">
<TextView
android:id="#+id/tvName"
android:layout_width="wrap_content"
android:layout_height="0dp"
android:layout_weight="1"
android:paddingLeft="15dp"
android:text="Akai Shuichi"
android:textSize="16dp"
android:textColor="#000"
android:gravity="center_vertical"
/>
<TextView
android:id="#+id/tvNumber"
android:layout_width="wrap_content"
android:layout_height="0dp"
android:layout_weight="1"
android:paddingLeft="15dp"
android:text="0982xxxxxx"
android:textSize="16dp"
android:textColor="#000"
android:gravity="center_vertical"
/>
</LinearLayout>
<LinearLayout
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1.3"
android:weightSum="2"
android:orientation="vertical">
<Button
android:id="#+id/btnEdit"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:backgroundTint="#3FE0FF"
android:onClick="myClickHandler"
android:text="Edit"
android:textColor="#fff"
android:textStyle="bold" />
<Button
android:id="#+id/btnDelete"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:backgroundTint="#F73131"
android:onClick="myClickHandler"
android:text="Delete"
android:textColor="#fff"
android:textStyle="bold" />
</LinearLayout>
</LinearLayout>
And here is my MainActivity.java:
package com.huy9515gmail.mycontact;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Toast;
import java.util.ArrayList;
import butterknife.BindView;
import butterknife.ButterKnife;
public class MainActivity extends AppCompatActivity {
#BindView(R.id.edt_inputName) EditText edtName;
#BindView(R.id.btnAdd) Button btnAdd;
#BindView(R.id.btnEdit) Button btnEdit;
#BindView(R.id.btnDelete) Button btnDelete;
#BindView(R.id.edt_inputNumber) EditText edtNumber;
#BindView(R.id.rdbtn_male) RadioButton rdbtn_male;
#BindView(R.id.rdbtn_female) RadioButton rdbtn_female;
#BindView(R.id.rdbtn_others) RadioButton rdbtn_others;
#BindView(R.id.gender) RadioGroup genderSelection;
private ListView lvContact;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButterKnife.bind(this);
lvContact = (ListView) findViewById(R.id.lv_contact);
final ArrayList<Contact> arrContact = new ArrayList<>();
btnAdd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//validating contact info
if (((edtName.getText().toString().trim()) == "") || (edtNumber.getText().toString().trim() == "") || ((rdbtn_male.isChecked()==false) && (rdbtn_female.isChecked()==false) &&(rdbtn_others.isChecked()==false))) {
Toast.makeText(MainActivity.this, "Invalid contact info! Please try again!", Toast.LENGTH_SHORT).show();
}
//adding contact info
else {
Contact contact = new Contact(Gender.male, "", "");
//adding info
contact.setName(edtName.getText().toString());
contact.setNumber(edtNumber.getText().toString());
arrContact.add(contact);
}
CustomAdapter customAdapter = new CustomAdapter(MainActivity.this, R.layout.row_listview, arrContact);
lvContact.setAdapter(customAdapter);
}
});
}
public void myClickHandler(View v) {
LinearLayout vwParentRow = (LinearLayout) v.getParent();
Button btnEdit = (Button) vwParentRow.getChildAt(0);
Button btnDelete = (Button) vwParentRow.getChildAt(1);
btnEdit.setText("Clicked");
btnDelete.setText("Clicked");
}
}
And here is the row_listview.xml layout:
Instead of setting the android:onClick in XML, do the same as you did for btnAdd.
Find the view by id or use butterknife, then put the following in onCreate()
btnEdit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Your code here
}
});
btnDelete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Your code here
}
});
Make sure you have an element in your XML file with the id like this:
android:id="#+id/btnAdd"

how to make number picker work in fragment with on clicklistener

I have a tab layout, number picker in the fragment doesn't seem to be working, the values remain 0 always.
Basically I am making random number app.
there are three number pickers in my fragment, one gives minimum number, one gives maximum number and one gives quantity of random numbers.
after setting these values in number picker user hits a button to get random numbers.
for me button is not doing anything when the values are set.
Please suggest me how to do this.
My fragment activity
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.app.AppCompatActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.NumberPicker;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.Collections;
public class TabFragment2 extends Fragment {
//declare Spinner object
Spinner generatorType;
Button getRandomNumberBtn;
int minimumNumber;
int maximumNumber;
int quantity1;
TextView randNumbText;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.tab_fragment_2, container, false);
getRandomNumberBtn = (Button) view.findViewById(R.id.get_number);
NumberPicker miniText;
final TextView minimumTextView = (TextView) view.findViewById(R.id.textView3);
miniText = (NumberPicker) view.findViewById(R.id.start_number);
miniText.setMinValue(0);
miniText.setMaxValue(10000);
miniText.setWrapSelectorWheel(true);
miniText.setOnValueChangedListener(new NumberPicker.OnValueChangeListener() {
#Override
public void onValueChange(NumberPicker picker, int oldVal1, int newVal1) {
//Display the newly selected number from picker
minimumTextView.setText("Min: " + newVal1);
}
});
minimumNumber = miniText.getValue();
NumberPicker maxiText;
final TextView maximumTextView = (TextView) view.findViewById(R.id.textView2);
maxiText = (NumberPicker) view.findViewById(R.id.end_number);
maxiText.setMinValue(0);
maxiText.setMaxValue(10000);
maxiText.setWrapSelectorWheel(true);
maxiText.setOnValueChangedListener(new NumberPicker.OnValueChangeListener() {
#Override
public void onValueChange(NumberPicker picker, int oldVal2, int newVal2) {
//Display the newly selected number from picker
maximumTextView.setText("Max: " + newVal2);
}
});
maximumNumber = maxiText.getValue();
NumberPicker quantity;
final TextView quantityTextView = (TextView) view.findViewById(R.id.quantity_text);
quantity = (NumberPicker) view.findViewById(R.id.quantity_picker);
quantity.setMinValue(0);
quantity.setMaxValue(100);
quantity.setWrapSelectorWheel(true);
quantity.setOnValueChangedListener(new NumberPicker.OnValueChangeListener() {
#Override
public void onValueChange(NumberPicker picker, int oldVal3, int newVal3) {
//Display the newly selected number from picker
quantityTextView.setText("Quantity: " + newVal3);
}
});
quantity1 = quantity.getValue();
randNumbText = (TextView) view.findViewById(R.id.random_number_display);
getRandomNumberBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
int b = maximumNumber + 1;
int a = minimumNumber;
int c = quantity1;
String multipleRandoms = "";
ArrayList<Integer> list = new ArrayList<Integer>();
ArrayList<Integer> list1 = new ArrayList<Integer>();
for (int i = a; i < b; i++) {
list.add(new Integer(i));
}
int k = list.size();
Collections.shuffle(list);
if (k>c) {
for (int i = 1; i <= c; i++) {
list1.add(new Integer(list.get(i)));
multipleRandoms = list1.toString();
}
}else if (k==c) {
multipleRandoms = list.toString();
} else {
Toast toast = Toast.makeText(getActivity(),"Quantity can not be greater than numbers in range", Toast.LENGTH_LONG);
toast.show();
}
randNumbText.setText(multipleRandoms);
}
});
return view;
}
My fragment layout
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/tab_fragment_2"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:focusable="true"
android:focusableInTouchMode="true"
tools:context="com.example.tabstrial2.TabFragment2">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingTop="#dimen/activity_vertical_margin">
<LinearLayout
android:id="#+id/linear_layout1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#id/generator_type_spinner"
android:orientation="horizontal">
<LinearLayout
android:id="#+id/linear_layout2"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:orientation="vertical">
<TextView
android:id="#+id/textView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:layout_marginTop="10px"
android:text="Min" />
<NumberPicker
android:id="#+id/start_number"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:layout_marginBottom="20px"
android:layout_marginTop="20px" />
</LinearLayout>
<LinearLayout
android:layout_width="2px"
android:layout_height="match_parent"
android:background="#android:color/black">
</LinearLayout>
<LinearLayout
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_weight="1"
android:orientation="vertical">
<TextView
android:id="#+id/quantity_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:layout_marginTop="10px"
android:text="Quantity" />
<NumberPicker
android:id="#+id/quantity_picker"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:layout_marginBottom="20px"
android:layout_marginTop="20px" />
</LinearLayout>
<LinearLayout
android:layout_width="2px"
android:layout_height="match_parent"
android:background="#android:color/black">
</LinearLayout>
<LinearLayout
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:orientation="vertical">
<TextView
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:layout_marginTop="10px"
android:text="Max" />
<NumberPicker
android:id="#+id/end_number"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_below="#+id/textView2"
android:layout_gravity="center_horizontal"
android:layout_marginBottom="20px"
android:layout_marginTop="20px" />
</LinearLayout>
</LinearLayout>
<TextView
android:id="#+id/random_number_display"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/linear_layout1"
android:layout_centerHorizontal="true"
android:layout_margin="10px"
android:textColor="#android:color/black"
android:textSize="40dp" />
<Button
android:id="#+id/get_number"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/random_number_display"
android:layout_centerHorizontal="true"
android:background="#android:color/holo_orange_light"
android:focusable="true"
android:focusableInTouchMode="true"
android:onClick="getRandomNumber"
android:paddingLeft="20px"
android:paddingRight="20px"
android:text="Get Random Number" />
</RelativeLayout>
</ScrollView>

How to Fix java.lang.ClassCastException: com.gc.materialdesign.views.ButtonFlat cannot be cast to android.widget.EditText

I am creating an android application that consists of registration form in dialog. Here, I placed a drop down spinner in registration dialog. But,here it was showing type casting error even i did the correct type casting. Please check it and make it solve. I am trying to solve since 2 hours. This is my code:
package com.example.testingsample;
import com.gc.materialdesign.views.ButtonFlat;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.Dialog;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;
public class MainActivity extends Activity
{
Button checking,spinner_check;
EditText username,password,confirm,seq_answer;
ButtonFlat clear,register;
Spinner spinner;
String[] questions = {
"What is your first name.?",
"What is your first pet name.?",
"What is your school name.?",
"What is your date of birth.?",
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
checking = (Button)findViewById(R.id.button1);
checking.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
android.app.Dialog registration_dialog = new android.app.Dialog(MainActivity.this);
registration_dialog.setContentView(R.layout.signup);
registration_dialog.setTitle("MedeQuip Registration");
username = (EditText)registration_dialog.findViewById(R.id.Dialog_edittext_username);
password = (EditText)registration_dialog.findViewById(R.id.Dialog_edittext_password);
confirm = (EditText)registration_dialog.findViewById(R.id.Dialog_edittext_confirmpassword);
spinner = (Spinner)registration_dialog.findViewById(R.id.spinner1);
ArrayAdapter adpter = new ArrayAdapter(MainActivity.this ,android.R.layout.simple_dropdown_item_1line,questions);
spinner.setAdapter(adpter);
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent,
View view, int position, long id)
{
Toast.makeText(MainActivity.this, questions[position], Toast.LENGTH_LONG).show();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
// TODO Auto-generated method stub
}
});
seq_answer = (EditText)registration_dialog.findViewById(R.id.editText1);
clear = (ButtonFlat)registration_dialog.findViewById(R.id.dialog_button_clear);
register = (ButtonFlat)registration_dialog.findViewById(R.id.Dialog_button_register);
//seq_answer = (EditText)registration_dialog.findViewById(R.id.editText1);*/
/*spinner_check.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
Toast.makeText(MainActivity.this, "Checking", Toast.LENGTH_LONG).show();
}
});*/
registration_dialog.show();
}
});
}}
This is my dialog xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/RelativeLayout1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center_vertical"
android:orientation="vertical" >
<EditText
android:id="#+id/Dialog_edittext_password"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="#+id/Dialog_edittext_username"
android:ems="10"
android:hint="Password"
android:inputType="textPassword" >
<requestFocus />
</EditText>
<EditText
android:id="#+id/Dialog_edittext_confirmpassword"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="#+id/Dialog_edittext_password"
android:ems="10"
android:hint="Confirm Password"
android:inputType="textPassword" />
<EditText
android:id="#+id/Dialog_edittext_username"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:ems="10"
android:hint="User Name" />
<Spinner
android:id="#+id/spinner1"
android:layout_width="345dp"
android:layout_height="60dp"
android:layout_below="#+id/Dialog_edittext_confirmpassword"
android:layout_centerHorizontal="true" />
<com.gc.materialdesign.views.ButtonFlat
android:id="#+id/Dialog_button_register"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignTop="#+id/dialog_button_clear"
android:text="Register"
android:textColor="#ffffff" >
</com.gc.materialdesign.views.ButtonFlat>
<com.gc.materialdesign.views.ButtonFlat
android:id="#+id/dialog_button_clear"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/editText1"
android:layout_marginRight="52dp"
android:layout_marginTop="59dp"
android:layout_toLeftOf="#+id/Dialog_button_register"
android:text="clear"
android:textColor="#ffffff" >
</com.gc.materialdesign.views.ButtonFlat>
<EditText
android:id="#+id/editText1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:layout_below="#+id/spinner1"
android:layout_marginTop="67dp"
android:ems="10"
android:hint="Enter your answer for security question" />
</RelativeLayout>
Same problem i faced but i solved that problem with following solutions
-> If you are implementing in Eclipse once clean the project then test it.
-> If above also not works once restart your Eclipse.
Hope it will helps you.

Getting value from dynamically created textview in android

MainActivity's code
How can I get values from the text boxes and the qty box in that user will input the value. price will come from server and than i want to calculate the bill and show it in next layout. plz give me some easy explanation as i am not expert in it. thanks in advance.
MainActivity .java
package com.example.myone;
import java.util.ArrayList;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
public class MainActivity extends Activity {
EditText textIn;
Button buttonAdd;
LinearLayout container;
private Button done;
private TextView tv;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textIn = (EditText)findViewById(R.id.textin);
buttonAdd = (Button)findViewById(R.id.add);
container = (LinearLayout)findViewById(R.id.container);
done = (Button) findViewById(R.id.cal);
tv= (TextView) findViewById(R.id.tv);
buttonAdd.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View arg0) {
LayoutInflater layoutInflater =
(LayoutInflater) getBaseContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
final View addView = layoutInflater.inflate(R.layout.row, null);
TextView textOut = (TextView)addView.findViewById(R.id.textout);
textOut.setText(textIn.getText().toString());
//(int1);
Button buttonRemove = (Button)addView.findViewById(R.id.remove);
buttonRemove.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
((LinearLayout)addView.getParent()).removeView(addView);
}});
container.addView(addView);
}});
}
}
MainActivity.xml
<LinearLayout
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"
android:orientation="vertical"
android:background="#drawable/mainbg"
tools:context=".MainActivity" >
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<EditText
android:id="#+id/textin"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:hint="Enter your item here"
/>
<Button
android:id="#+id/cal"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:layout_below="#+id/textin"
android:text="Done!"
android:layout_alignParentLeft="true"
/>
<Button
android:id="#+id/add"
android:text="Add"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignBaseline="#+id/cal"
/>
</RelativeLayout>
<LinearLayout
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
</LinearLayout>
</LinearLayout>
Row.xml
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:background="#drawable/borderbg"
android:orientation="horizontal"
android:id="#+id/rel"
android:layout_height="wrap_content">
<TextView
android:id="#+id/textout"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:hint="Item"
android:layout_marginTop="10dp"
android:layout_marginLeft="5dp"
/>
<EditText
android:id="#+id/qty"
android:layout_width="wrap_content"
android:layout_height="30dp"
android:layout_alignTop="#+id/price"
android:layout_toRightOf="#+id/price"
android:layout_marginLeft="50dp"
android:textSize="12sp"
android:hint="Qty" />
<TextView
android:id="#+id/price"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/textout"
android:layout_alignBottom="#+id/textout"
android:layout_marginLeft="42dp"
android:layout_toRightOf="#+id/textout"
android:hint="Price" />
<Button
android:id="#+id/remove"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:gravity="left"
android:text="remove" />
</RelativeLayout>
Simply I want to create a basic shopping app that have 20 products. the price and product name will come from server and quantity will input by user so how do I that?
You are looking for something like this
int count = container.getChildCount();
for (int i = 0; i < count; i++) {
final View row = container.getChildAt(i);
TextView textOut = (TextView)row.findViewById(R.id.textout);
String data = textOut.getText().toString();
}
Where container is your LinearLayout in which you have added your inflated rows.
Try this:-
To take user input from text box:-
int qty = Integer.parseInt(qtyTextBox.getText().toString());
Caluculate bill:-
double bill = price*qty;
Send bill value to next activity:-
Intent in = new Intent();
in.putExtra("Bill", bill);
startActivity(in);
Get bill value in next activity:-
Intent in = getIntent();
int mBill = in.getExtra("Bill");
string bill = String.valueOf(mBill);
Now you can set the value of 'bill' to the TextView where you want to display it.

Simple calculator application in Android

When I click on the add button without entring anything on the edittext,unfortunately calculator has stopped.
package com.example.calculator;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class Calci extends Activity {
TextView t1;
EditText e1,e2;
Button add,sub,mul,div;
Context c;;
String b,a;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_calci);
e1=(EditText) findViewById(R.id.EditText01);
e2=(EditText) findViewById(R.id.EditText02);
add=(Button) findViewById(R.id.add);
sub=(Button) findViewById(R.id.sub);
mul=(Button) findViewById(R.id.mul);
div=(Button) findViewById(R.id.div);
t1=(TextView) findViewById(R.id.textView1);
a=e1.getText().toString();
b=e2.getText().toString();
}
public void doSomething(View v){
if(v.getId()==R.id.add){
if (a==null & b==null){
Toast.makeText(c,"PLEASE ENTER SOMETHING", Toast.LENGTH_LONG).show();
}
else{
int result=Integer.parseInt(a) + Integer.parseInt(b);
t1.setText(Integer.toString(result));
}
}
}
}
When I click on the add button,unfortunately calculator has stopped.
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"
tools:context=".Calci" >
<EditText
android:id="#+id/EditText01"
android:layout_width="150dp"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:ems="10"
android:inputType="number" />
<EditText
android:id="#+id/EditText02"
android:layout_width="100dp"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:layout_toRightOf="#+id/EditText01"
android:ems="10"
android:inputType="number" />
<Button
android:id="#+id/add"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:layout_below="#+id/EditText01"
android:layout_marginTop="20dp"
android:text="ADD"
android:onClick="doSomething"/>
<TextView
android:id="#+id/textView1"
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/button4"
android:layout_marginTop="44dp"
android:gravity="center"
android:textAppearance="?android:attr/textAppearanceLarge" />
<Button
android:id="#+id/sub"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:layout_below="#+id/add"
android:onClick="doSomething"
android:text="SUBTRACT" />
<Button
android:id="#+id/mul"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:layout_below="#+id/sub"
android:onClick="doSomething"
android:text="MULTIPLY" />
<Button
android:id="#+id/div"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:layout_below="#+id/mul"
android:onClick="doSomething"
android:text="DIVIDE" />
</RelativeLayout>
When I click on the add button,unfortunately calculator has stopped.\
what shuold i do now
First of all initialize
t1=(TextView) findViewById(R.id.textView1);
And you can put validation for empty check on button click listener before furthe process like
if(!(t1.getText.toString().equals(""))) to show alerts
I think problem is that you have not declared your text-view, try to declare it like below and then try.
t1=(TextView) findViewById(R.id.textView1);
Edit
if (e1.getText.toString().trim() == "" && e2.getText.toString().trim() == "")
{
// alert
}
else
{
// do your code
}
So your final code would be
public void doSomething(View v){
if(v.getId()==R.id.add){
a=e1.getText().toString();
b=e2.getText().toString();
if (a == "" && b == "")
{
// alert
}
else
{
int result=Integer.parseInt(a) + Integer.parseInt(b);
t1.setText(Integer.toString(result));
}
}
}
At first you have mistake in your function - you should call e1.setText(), not t1, t1 undeclared and not initialized. And next you should use OnClickListener like this:
public class Calci extends Activity {
TextView t1;
EditText e1,e2;
Button add,sub,mul,div;
String b,a;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_calci);
e1=(EditText) findViewById(R.id.EditText01);
e2=(EditText) findViewById(R.id.EditText02);
add=(Button) findViewById(R.id.add);
sub=(Button) findViewById(R.id.sub);
mul=(Button) findViewById(R.id.mul);
div=(Button) findViewById(R.id.div);
add.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
a=e1.getText().toString();
b=e2.getText().toString();
int result=Integer.parseInt(a) + Integer.parseInt(b);
e1.setText(Integer.toString(result));
}
});
}
}
And yes, check the textfield for not empty String.
if((!a.isEmpty())&(!b.isEmpty())) { your code }
And the best way - use try-catch for catching FormatNumberException
try {
int result=Integer.parseInt(a) + Integer.parseInt(b);
e1.setText(Integer.toString(result));
}
catch (FormatNumberException e) {
Log.d("Exception", e.getMessage());
}
So you can prevent all crashes.

Categories

Resources