Button becomes blank(text) when Onclick method executed - java

This is the xml code:
<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:layout_marginTop="20dp"
android:text="eBay Search"
android:textSize="13pt"
android:textStyle="bold"
android:textColor="#000099"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true">
</TextView>
<TableLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="80dp"
android:id="#+id/tableLayout">
<TableRow
android:layout_marginTop="15dp">
<TextView
android:layout_height="wrap_content"
android:layout_width="0dp"
android:text="Keyword:"
android:textSize="10pt"
android:layout_weight="2">
</TextView>
<EditText
android:id="#+id/keyword"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="3"
>
</EditText>
</TableRow>
<TableRow
android:layout_marginTop="15dp">
<TextView
android:layout_height="wrap_content"
android:layout_width="0dp"
android:text="Price From:"
android:textSize="10pt"
android:layout_weight="2">
</TextView>
<EditText
android:id="#+id/from"
android:layout_width="0dp"
android:inputType="numberDecimal"
android:layout_height="wrap_content"
android:layout_weight="3"
>
</EditText>
</TableRow>
<TableRow
android:layout_marginTop="15dp">
<TextView
android:layout_width="0dp"
android:layout_height="wrap_content"
android:text="Price To:"
android:textSize="10pt"
android:layout_weight="2">
</TextView>
<EditText
android:id="#+id/to"
android:layout_height="wrap_content"
android:layout_gravity="right"
android:layout_weight="3"
android:inputType="numberDecimal"
android:layout_width="0dp"
>
</EditText>
</TableRow>
<TableRow
android:layout_marginTop="15dp">
<TextView
android:layout_width="0dp"
android:layout_height="wrap_content"
android:text="Sort By:"
android:textSize="10pt"
android:layout_weight="2">
</TextView>
<Spinner
android:id="#+id/sortby"
android:layout_height="wrap_content"
android:prompt="#string/op1"
android:layout_width="fill_parent"
android:entries="#array/sortlist">
</Spinner>
</TableRow>
<TableRow
android:layout_marginTop="15dp"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Clear"
android:id="#+id/Clear"
android:onClick="clearForm"
android:layout_marginLeft="50dp"
/>
<Button
android:layout_width="90dp"
android:layout_height="wrap_content"
android:text="Search"
android:textColor="#color/black"
android:id="#+id/search"
android:layout_marginLeft="50dp"
/>
</TableRow>
</TableLayout>
<TextView
android:id="#+id/keyerror"
android:layout_marginTop="420dp"
android:layout_centerHorizontal="true"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text=""
android:textSize="7pt"
android:textColor="#color/red"
>
</TextView>
<TextView
android:id="#+id/priceerror"
android:layout_marginTop="445dp"
android:layout_centerHorizontal="true"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text=""
android:textSize="7pt"
android:textColor="#color/red"
>
</TextView>
This is the mainactivity code which has onclicklistener method for the search button:
package com.example.hrishikesh.hw9;
import android.app.AlertDialog;
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.Spinner;
import android.widget.TextView;
import java.net.URLEncoder;
public class MainActivity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final Button search = (Button)findViewById(R.id.search);
search.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int error=0;
EditText text1 = (EditText) findViewById(R.id.keyword);
EditText text2 = (EditText) findViewById(R.id.from);
EditText text3 = (EditText) findViewById(R.id.to);
TextView keyerror = (TextView) findViewById(R.id.keyerror);
TextView priceerror = (TextView) findViewById(R.id.priceerror);
String keyword = text1.getText().toString();
String from = text2.getText().toString();
String to = text3.getText().toString();
String reg = "^[0-9]+$";
if (keyword == null || keyword.length() < 1 || keyword.trim().length() < 1) {
keyerror.setText("Enter a valid keyword");
error=1;
}
else
{
keyerror.setText("");
error=0;
}
if(to.matches(reg) || to.length()==0)
{
}
else
{
priceerror.setText("Enter a valid positive number for maximum price");
error=1;
}
if(from.matches(reg) || from.length()==0)
{
}
else
{
priceerror.setText("Enter a valid positive number for minimum price");
error=1;
}
if(from.length()>0 && to.length()>0)
if(Integer.parseInt(from) - Integer.parseInt(to)>=0){
priceerror.setText("Minimum price has to be less than maximum price");
error=1;
}
}
});
}
#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);
}
public void clearForm(View v){
EditText text1 = (EditText)this.findViewById(R.id.keyword);
EditText text2 = (EditText)this.findViewById(R.id.from);
EditText text3 = (EditText)this.findViewById(R.id.to);
if (text1 != null) text1.setText("");
if (text2 != null) text2.setText("");
if (text3 != null) text3.setText("");
Spinner spin1 = (Spinner)this.findViewById(R.id.sortby);
spin1.setSelection(0);
}
public void validate(View v){
}
public void search(String keywords,int from,int to,String sortorder){
String url;
int i=0;
url = "http://hrishisaraf-env.elasticbeanstalk.com/";
}
}
Whenever the onclick method gets executed and an error is detected like the keyword being blank. The error text is set and the Search button becomes blank.

No idea why but Setting the width to wrap_content solved the problem.

Related

error in navigating from one activity to another activity

/* i have tried many times but i am not able to navigate to another activity while clicking on the item in the navigation drawer and when i click on that Item the app crashes(error:open app again).*/
drawer.xml
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:id="#+id/admin"
android:title="Admin Profile"
android:icon="#drawable/ic_dashboard"/>
<item
android:id="#+id/createaccount"
android:title="User Registration"
android:icon="#drawable/ic_event_black_24dp"/>
<item
android:id="#+id/manageuser"
android:title="Manage User"
android:icon="#drawable/ic_settings_black_24dp"/>
<item
android:id="#+id/us"
android:title="About us"
android:icon="#drawable/ic_call_to_action_black_24dp"/>
<item
android:id="#+id/logout"
android:title="Logout"
android:icon="#drawable/ic_cancel_black_24dp"/>
</menu>
/activity_navigation_bar.xml/
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout
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:id="#+id/drawer"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="16dp"
android:paddingRight="16dp"
android:paddingBottom="16dp"
android:paddingTop="16dp"
tools:context="com.ereports.navigationBar">
<android.support.v7.widget.LinearLayoutCompat
android:background="#drawable/bg"
android:layout_width="match_parent"
android:layout_height="match_parent">
</android.support.v7.widget.LinearLayoutCompat>
<android.support.design.widget.NavigationView
app:headerLayout="#layout/header"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:background="#color/white"
app:itemTextColor="#color/darkgray"
app:itemIconTint="#color/darkgray"
app:menu="#menu/drawermenu"
android:layout_gravity="start">
</android.support.design.widget.NavigationView>
</android.support.v4.widget.DrawerLayout>
/navigationBar.java/
package com.ereports;
import android.content.Intent;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.MenuItem;
import static com.ereports.R.id.us;
public class navigationBar extends AppCompatActivity {
private DrawerLayout mDrawerLayout;
private ActionBarDrawerToggle mToggle;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_navigation_bar);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer);
mToggle = new ActionBarDrawerToggle(this, mDrawerLayout, R.string.Open, R.string.Close);
mDrawerLayout.addDrawerListener(mToggle);
mToggle.syncState();
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
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.us) {
Intent intent = new Intent(this,Registration.class);
this.startActivity(intent);
return true;
}
if (id == R.id.action_search) {
Toast.makeText(this, "Android Menu is Clicked", Toast.LENGTH_LONG).show();
return true;
}
if (id == R.id.action_settings) {
Toast.makeText(this, "Android Menu is Clicked", Toast.LENGTH_LONG).show();
return true;
}
return super.onOptionsItemSelected(item);
}
}
}
/*another activity to navigate for::
'Registration.java*/
package com.ereports;
import android.annotation.SuppressLint;
import android.content.res.ColorStateList;
import android.content.res.XmlResourceParser;
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.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Registration extends Fragment implements OnClickListener {
private static View view;
private static EditText fullName, emailId, mobileNumber, location,
password, confirmPassword;
private static TextView login;
private static Button signUpButton1;
private static CheckBox terms_conditions;
public Registration() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
view = inflater.inflate(R.layout.activity_registration, container, false);
initViews();
setListeners();
return view;
}
// Initialize all views
private void initViews() {
fullName = (EditText) view.findViewById(R.id.fullName);
emailId = (EditText) view.findViewById(R.id.userEmailId);
mobileNumber = (EditText) view.findViewById(R.id.mobileNumber);
location = (EditText) view.findViewById(R.id.location);
password = (EditText) view.findViewById(R.id.password);
confirmPassword = (EditText) view.findViewById(R.id.confirmPassword);
signUpButton1 = (Button) view.findViewById(R.id.signUpBtn);
login = (TextView) view.findViewById(R.id.already_user);
terms_conditions = (CheckBox) view.findViewById(R.id.terms_conditions);
// Setting text selector over textviews
#SuppressLint("ResourceType") XmlResourceParser xrp = getResources().getXml(R.drawable.text_selector);
try {
ColorStateList csl = ColorStateList.createFromXml(getResources(),
xrp);
login.setTextColor(csl);
terms_conditions.setTextColor(csl);
} catch (Exception e) {
}
}
// Set Listeners
private void setListeners() {
signUpButton1.setOnClickListener(this);
login.setOnClickListener(this);
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.signUpBtn1:
// Call checkValidation method
checkValidation();
break;
}
}
// Check Validation Method
private void checkValidation() {
// Get all edittext texts
String getFullName = fullName.getText().toString();
String getEmailId = emailId.getText().toString();
String getMobileNumber = mobileNumber.getText().toString();
String getLocation = location.getText().toString();
String getPassword = password.getText().toString();
String getConfirmPassword = confirmPassword.getText().toString();
// Pattern match for email id
Pattern p = Pattern.compile(Utils.regEx);
Matcher m = p.matcher(getEmailId);
// Check if all strings are null or not
if (getFullName.equals("") || getFullName.length() == 0
|| getEmailId.equals("") || getEmailId.length() == 0
|| getMobileNumber.equals("") || getMobileNumber.length() == 0
|| getLocation.equals("") || getLocation.length() == 0
|| getPassword.equals("") || getPassword.length() == 0
|| getConfirmPassword.equals("")
|| getConfirmPassword.length() == 0)
new CustomToast().Show_Toast(getActivity(), view,
"All fields are required.");
// Check if email id valid or not
else if (!m.find())
new CustomToast().Show_Toast(getActivity(), view,
"Your Email Id is Invalid.");
// Check if both password should be equal
else if (!getConfirmPassword.equals(getPassword))
new CustomToast().Show_Toast(getActivity(), view,
"Both password doesn't match.");
// Make sure user should check Terms and Conditions checkbox
else if (!terms_conditions.isChecked())
new CustomToast().Show_Toast(getActivity(), view,
"Please select Terms and Conditions.");
// Else do signup or do your stuff
else
Toast.makeText(getActivity(), "User Registered", Toast.LENGTH_SHORT)
.show();
}
}
activity_registration.java
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
android:padding="20dp" >
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:padding="10dp"
android:text="#string/signUp"
android:textColor="#color/white_greyish"
android:textSize="25sp"
android:textStyle="bold" />
<EditText
android:id="#+id/fullName"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:background="#android:color/transparent"
android:drawableLeft="#drawable/user"
android:drawablePadding="8dp"
android:gravity="center_vertical"
android:hint="#string/fullName"
android:inputType="textCapWords"
android:padding="10dp"
android:singleLine="true"
android:textColor="#color/white"
android:textColorHint="#color/white"
android:textSize="16sp" />
<View
android:layout_width="fill_parent"
android:layout_height="1px"
android:background="#color/white_greyish" />
<EditText
android:id="#+id/userEmailId"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="5dp"
android:background="#android:color/transparent"
android:drawableLeft="#drawable/email"
android:drawablePadding="8dp"
android:gravity="center_vertical"
android:hint="#string/email"
android:inputType="textEmailAddress"
android:padding="10dp"
android:singleLine="true"
android:textColor="#color/white"
android:textColorHint="#color/white"
android:textSize="16sp" />
<View
android:layout_width="fill_parent"
android:layout_height="1px"
android:background="#color/white_greyish" />
<EditText
android:id="#+id/mobileNumber"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="5dp"
android:background="#android:color/transparent"
android:drawableLeft="#drawable/phone"
android:drawablePadding="8dp"
android:gravity="center_vertical"
android:hint="#string/mobileNumber"
android:inputType="phone"
android:padding="10dp"
android:singleLine="true"
android:textColor="#color/white"
android:textColorHint="#color/white"
android:textSize="16sp" />
<View
android:layout_width="fill_parent"
android:layout_height="1px"
android:background="#color/white_greyish" />
<EditText
android:id="#+id/location"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="5dp"
android:background="#android:color/transparent"
android:drawableLeft="#drawable/location"
android:drawablePadding="8dp"
android:gravity="center_vertical"
android:hint="#string/location"
android:inputType="textCapWords"
android:padding="10dp"
android:singleLine="true"
android:textColor="#color/white"
android:textColorHint="#color/white"
android:textSize="16sp" />
<View
android:layout_width="fill_parent"
android:layout_height="1px"
android:background="#color/white_greyish" />
<EditText
android:id="#+id/password"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="5dp"
android:background="#android:color/transparent"
android:drawableLeft="#drawable/password"
android:drawablePadding="8dp"
android:gravity="center_vertical"
android:hint="#string/passowrd"
android:inputType="textPassword"
android:padding="10dp"
android:singleLine="true"
android:textColor="#color/white"
android:textColorHint="#color/white"
android:textSize="16sp" />
<View
android:layout_width="fill_parent"
android:layout_height="1px"
android:background="#color/white_greyish" />
<EditText
android:id="#+id/confirmPassword"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="5dp"
android:background="#android:color/transparent"
android:drawableLeft="#drawable/confirm_password"
android:drawablePadding="8dp"
android:gravity="center_vertical"
android:hint="#string/confirmPassword"
android:inputType="textPassword"
android:padding="10dp"
android:singleLine="true"
android:textColor="#color/white"
android:textColorHint="#color/white"
android:textSize="16sp" />
<CheckBox
android:id="#+id/terms_conditions"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="7dp"
android:text="#string/terms_conditions"
android:textColor="#color/white"
android:textSize="14sp" />
<Button
android:id="#+id/signUpBtn1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="15dp"
android:background="#drawable/loginbutton_selector"
android:padding="3dp"
android:text="Register"
android:textColor="#color/background_color"
android:textSize="17sp"
android:textStyle="bold" />
</LinearLayout>
/*app is crashing
expected results: it should navigate to Registration.java
actual results: app is crashing*/
Use fragments to switch between activities
[https://www.youtube.com/watch?v=J8GB_b8qyK8]
this covers with a good explanation. I tried it myself

Android: Code Runtime Error

I am writing a simple calculator, but unfortunately it doesn't work.
LogCat says that the error is in my onClick:
at android.view.View$1.onClick(View.java:2072)
But I'm sorry to say I can't find it. So please help me.
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=".MainActivity" >
<EditText
android:id="#+id/editText1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginLeft="54dp"
android:layout_marginTop="60dp"
android:ems="10" />
<EditText
android:id="#+id/editText2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/editText1"
android:layout_below="#+id/editText1"
android:layout_marginTop="74dp"
android:ems="10" />
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/editText1"
android:layout_alignParentTop="true"
android:layout_marginTop="38dp"
android:text="Input first number" />
<TextView
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/editText2"
android:layout_below="#+id/editText1"
android:layout_marginTop="36dp"
android:text="Input 2nd number" />
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="functionCalculator"
android:layout_alignLeft="#+id/editText2"
android:layout_below="#+id/editText2"
android:layout_marginTop="26dp"
android:text="+"/>
<TextView
android:id="#+id/textView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="#+id/button1"
android:layout_marginTop="28dp"
android:text="Your result here" />
<TextView
android:id="#+id/textView4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignTop="#+id/textView3"
android:layout_marginLeft="20dp"
android:layout_toRightOf="#+id/button1"
android:text="Result"
android:textAppearance="?android:attr/textAppearanceLarge" />
<Button
android:id="#+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/button1"
android:layout_alignRight="#+id/textView4"
android:text="-"
android:onClick="functionCalculator" />
</RelativeLayout>
ActivityMain.java:
package com.example.caculator;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends Activity {
EditText e1,e2;
TextView t1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
e1= (EditText)findViewById(R.id.editText1);
e2 = (EditText)findViewById(R.id.editText2);
t1 = (TextView)findViewById(R.id.textView4);
}
public void functionCalculator(View view) {
int number1 , number2 , result;
if (view.getId()==R.id.button1) {
number1 = Integer.parseInt(e1.getText().toString());
number2 = Integer.parseInt(e2.getText().toString());
result = number1+number2;
t1.setText(Integer.toString(result));
}
if (view.getId()==R.id.button2) {
number1 = Integer.parseInt(e1.getText().toString());
number2 = Integer.parseInt(e2.getText().toString());
result = number1-number2;
t1.setText(Integer.toString(result));
}
}
#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;
}
}
I ran your code and didn't run into any issues as long as I put integers in e1 and e2. As soon as I entered decimal numbers, I ran into exact same issue as you mention. This is because you are trying to parse integers out of the input which may not always be successful and will result in a NumberFormatException. You should write your code so that it never crashes no matter what the case. Just assume your users are idiots. Try the code below, it shouldn't crash:
public void functionCalculator(View view) {
try {
// Firstly checking for integers
int number1, number2;
number1 = Integer.parseInt(e1.getText().toString());
number2 = Integer.parseInt(e2.getText().toString());
if (view.getId() == R.id.button1)
t1.setText(Integer.toString(number1 + number2));
else if (view.getId() == R.id.button2)
t1.setText(Integer.toString(number1 - number2));
} catch (NumberFormatException e) {
float number1, number2;
try {
// Now checking for decimals
number1 = Float.parseFloat(e1.getText().toString());
number2 = Float.parseFloat(e2.getText().toString());
if (view.getId() == R.id.button1)
t1.setText(Float.toString(number1 + number2));
else if (view.getId() == R.id.button2)
t1.setText(Float.toString(number1 - number2));
} catch (NumberFormatException e2) {
// No numbers :(
Toast.makeText(this, "WTF! Enter number here you dingus!", Toast.LENGTH_SHORT).show();
}
}
}

Android Simple Calculator App Crashing and Logic

I'm making an android app for a simple calculator. The most important part is that it uses a "rolling" textView, so for example if you did 1+1, then if you pressed another arithmetic operator, "+" for example, the textView would then turn into 2+(enter new number, 3 for example) and then if you clicked multiply, it would then show 5* etc etc.
Right now the error is at line34 showing a null pointer error when I click the number 1 on the calculator. Wondering if anybody can assist me on this / other logic errors if you see them.
Basically if you click to use an arithmetic operator on the calculator, and if there's already an operator in the textView on the calculator, then it calculates the current textView and spits that new arithmetic operator beside it. Otherwise if there are no arithmetic operators on the calculator, it just puts the operator beside the first number.
What I'm trying to do is:
if the user clicks a number, then set rollingBar to that number
if the user clicks an operator
if it is the first operator then there must be only 1 string inside of
the rollingBar, so assign that string to leftNum, and assign the first
operator type to the text of the button eg. "1".
get text in rolling bar, assign it to text1, make text2 and assign
it to text1 + stringButton(which would be 1,2,3,4 etc.. name of btn.
set the first operator to false
if it's not the first operator, then you need to calculate by splitting
the function at the first arithmetic operator, assign the last number
from the split into rightNum
switch to the first operator type
do the math
assign this second operator to the next rollingBar
Right now I'm getting some problems... I'll show a picture and the java file...
Picture:
http://imgur.com/35hy4Ze
Java File:
package com.example.w0273754.calcfinal;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import java.lang.String;
public class MainActivity extends AppCompatActivity {
//declarations
TextView rollingBar;//where all of the text goes when the user clicks a button
String leftNum;
String rightNum;
boolean firstOptr;
String firstOptrType;
String number;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
rollingBar = (TextView) findViewById(R.id.rollingBar);
leftNum = "";
rightNum = "";
firstOptr = true;
number = "";
}
public void number(View v){
Button button = (Button) v;
number += button.getText().toString();
rollingBar.setText(number);
}
//i can click 1 and it outputs 1
// i can click + and it outputs +
// when I click next number it just outputs the number, nothing else
public void operater(View v) {
Button button = (Button) v;
String stringButton = button.getText().toString();
//if it's the first operator being done, then set the rollbar text to text1,
// then add the operator string to text1 and store it in text 2.
if (firstOptr) {
leftNum = rollingBar.getText().toString();
firstOptrType = stringButton;
number += stringButton;
rollingBar.setText(number);
firstOptr = false;
}
//if it's not the first operator, then you need to calculate leftnum and the right num
else {
String fullString = (String) rollingBar.getText().toString();
String[] bits = fullString.split("[-+*/]");
rightNum = bits[bits.length - 1];
switch (firstOptrType) {
case "+":
add(leftNum, rightNum);
break;
case "-":
break;
case "*":
break;
case "/":
break;
default:
rollingBar.setText("OPERATOR METHOD PROBLEM");
}
}
}
public void add(String leftNum, String rightNum){
int parsedLeftNum = Integer.parseInt(leftNum);
int parsedRightNum = Integer.parseInt(rightNum);
rollingBar.setText(parsedLeftNum + parsedRightNum);
}
#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);
}
}
XML file:
<TableLayout android:id="#+id/TableLayout"
tools:context=".MainActivity"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:layout_height="match_parent"
android:layout_width="match_parent"
xmlns:tools="http://schemas.android.com/tools"
xmlns:android="http://schemas.android.com/apk/res/android">
<TableRow android:paddingBottom="10dp" android:layout_height="match_parent" android:layout_width="match_parent">
<TextView android:id="#+id/rollingBar" android:layout_height="wrap_content" android:layout_width="wrap_content" android:layout_column="1" android:layout_span="4" android:text="#string/rollingBar"/>
</TableRow>
<TableRow android:layout_height="match_parent"
android:layout_width="match_parent">
<Button android:id="#+id/buttonClear" android:layout_height="wrap_content" android:layout_width="wrap_content" android:text="#string/buttonClear" />
<Button android:id="#+id/buttonPlusMinus" android:layout_height="wrap_content" android:layout_width="wrap_content" android:layout_span="1" android:text="#string/buttonPlusMinus" android:onClick="onClick1"/>
<Button android:id="#+id/buttonDelete" android:layout_height="wrap_content" android:layout_width="wrap_content" android:layout_span="1" android:text="#string/buttonDelete" />
<Button android:id="#+id/buttonDivide" android:layout_height="wrap_content" android:layout_width="wrap_content" android:layout_column="3" android:text="#string/buttonDivide" android:onClick="operater"/>
</TableRow>
<TableRow android:paddingBottom="10dp" android:layout_height="match_parent" android:layout_width="match_parent">
<Button android:id="#+id/button7" android:layout_height="wrap_content" android:layout_width="wrap_content" android:text="#string/button7" android:onClick="number" android:nestedScrollingEnabled="false"/>
<Button android:id="#+id/button8" android:layout_height="wrap_content" android:layout_width="wrap_content" android:text="#string/button8" android:onClick="number"/>
<Button android:id="#+id/button9" android:layout_height="wrap_content" android:layout_width="wrap_content" android:text="#string/button9" android:onClick="number"/>
<Button android:id="#+id/buttonMultiply" android:layout_height="wrap_content" android:layout_width="wrap_content" android:layout_column="3" android:text="#string/buttonMultiply" android:onClick="operater"/>
</TableRow>
<TableRow android:paddingBottom="10dp" android:layout_height="match_parent" android:layout_width="match_parent">
<Button android:id="#+id/button4" android:layout_height="wrap_content" android:layout_width="wrap_content" android:text="#string/button4" android:onClick="number"/>
<Button android:id="#+id/button5" android:layout_height="wrap_content" android:layout_width="wrap_content" android:text="#string/button5" android:onClick="number"/>
<Button android:id="#+id/button6" android:layout_height="wrap_content" android:layout_width="wrap_content" android:text="#string/button6" android:onClick="number"/>
<Button android:id="#+id/buttonSubtract" android:layout_height="wrap_content" android:layout_width="wrap_content" android:layout_column="3" android:text="#string/buttonSubtract" android:onClick="operater"/>
</TableRow>
<TableRow android:paddingBottom="10dp" android:layout_height="wrap_content" android:layout_width="match_parent">
<Button android:id="#+id/button1" android:layout_height="wrap_content" android:layout_width="wrap_content" android:layout_span="1" android:text="#string/button1" android:onClick="number"/>
<Button android:id="#+id/button2" android:layout_height="wrap_content" android:layout_width="wrap_content" android:layout_span="1" android:text="#string/button2" android:onClick="number"/>
<Button android:id="#+id/button3" android:layout_height="wrap_content" android:layout_width="wrap_content" android:layout_span="1" android:text="#string/button3" android:onClick="number"/>
<Button android:id="#+id/buttonAdd" android:layout_height="wrap_content" android:layout_width="wrap_content" android:layout_column="3" android:text="#string/buttonAdd" android:onClick="operater"/>
</TableRow>
<TableRow android:paddingBottom="10dp" android:layout_height="match_parent" android:layout_width="match_parent">
<Button android:id="#+id/button0" android:layout_height="wrap_content" android:layout_width="wrap_content" android:layout_span="2" android:text="#string/button0" android:onClick="number"/>
<Button android:id="#+id/buttonDecimal" android:layout_height="wrap_content" android:layout_width="wrap_content" android:layout_span="1" android:text="#string/buttonDecimal"/>
<Button android:id="#+id/buttonEqual" android:layout_height="match_parent" android:layout_width="wrap_content" android:layout_span="1" android:text="#string/buttonEqual" android:onClick="operater"/>
</TableRow>
<TableRow android:layout_height="match_parent" android:layout_width="match_parent">
<TextView android:id="#+id/textView" android:layout_height="wrap_content" android:layout_width="wrap_content" android:text="0"/>
</TableRow>
<TableRow android:layout_height="match_parent" android:layout_width="match_parent">
<TextView android:id="#+id/errorMessage" android:layout_height="wrap_content" android:layout_width="wrap_content"/>
</TableRow>
</TableLayout>
Thank you very much,for the help!
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView rollingBar = (TextView) findViewById(R.id.rollingBar); // <-- HERE
String leftNum = "";
String rightNum = "";
boolean firstOptr = true;
String firstOptrType;
}
You declare a local variable rollingBar in onCreate which shadow the member variable of your Activity, so the member variable rollingBar always null, delete the TextView:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
rollingBar = (TextView) findViewById(R.id.rollingBar);
String leftNum = "";
String rightNum = "";
boolean firstOptr = true;
String firstOptrType;
}

Trying to run program in Android Studio but get error that my app has stopped working

I keep getting the error in my Android Studio Emulator (Nexus_7_API_21) that my app has stopped working whenever i try to run it. I launched LogCat and I think the error is due to a null pointer reference but i don't know where the problem is.
Here is my .java main file.
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Button;
import android.view.View;
import android.widget.RadioButton;
import android.widget.RelativeLayout;
public class MainActivity extends ActionBarActivity
{
RelativeLayout bg;
RadioButton r1;
RadioButton r2;
RadioButton r3;
RadioButton r4;
Button b;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
bg = (RelativeLayout) findViewById(R.id.back);
r1 = (RadioButton) findViewById(R.id.rButton1);
r2 = (RadioButton) findViewById(R.id.rButton2);
r1 = (RadioButton) findViewById(R.id.rButton3);
r1 = (RadioButton) findViewById(R.id.rButton4);
r1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
return;
}
});
r2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
return;
}
});
r3.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
return;
}
});
r4.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
return;
}
});
}
#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);
}
}
Here is my 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:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:id="#+id/back"
android:paddingBottom="#dimen/activity_vertical_margin" tools:context=".MainActivity"
android:background="#210d0a0d">
<LinearLayout
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_alignParentEnd="true">
<LinearLayout
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="200dp">
<LinearLayout
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="35dp" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="#string/welcomeString"
android:id="#+id/textView"
android:layout_gravity="center_horizontal"
android:textStyle="bold" />
</LinearLayout>
<LinearLayout
android:orientation="horizontal"
android:layout_width="180dp"
android:layout_height="150dp" >
<TableLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<TableRow
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<RadioButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/rButton1"
android:id="#+id/rButton1"
android:layout_gravity="center_vertical"
android:checked="false" />
</TableRow>
<TableRow
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<RadioButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/rButton2"
android:id="#+id/rButton2"
android:layout_gravity="center_vertical" />
</TableRow>
<TableRow
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<RadioButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/rButton3"
android:id="#+id/rButton3"
android:layout_gravity="center_vertical" />
</TableRow>
<TableRow
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<RadioButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/rButton4"
android:id="#+id/rButton4"
android:layout_gravity="center_vertical" />
</TableRow>
</TableLayout>
</LinearLayout>
</LinearLayout>
<LinearLayout
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/button"
android:id="#+id/button"
android:layout_gravity="center_horizontal"
android:textSize="25dp" />
</LinearLayout>
</LinearLayout>
</RelativeLayout>
r1 = (RadioButton) findViewById(R.id.rButton3);
r1 = (RadioButton) findViewById(R.id.rButton4);
is problem. You are using r1 instead of r3 and r4.
r3 = (RadioButton) findViewById(R.id.rButton3);
r4 = (RadioButton) findViewById(R.id.rButton4);

button error viewflipper android

i`m trying to do android viewflipper. i have 3 views i would to be changed on button click (next & previous). i wrote these code and the log said there is button widget error. How to solve this?
my xml layout
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:background="#drawable/radial_background">
<RelativeLayout
android:id="#+id/relative_buy1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true">
<Button
android:id="#+id/buy_previous"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true">
</Button>
<Button
android:id="#+id/buy_next"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="#id/buy_previous">
</Button>
<Button
android:id="#+id/buy_submit"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="#id/buy_next">
</Button>
</RelativeLayout>
<RelativeLayout
android:layout_alignTop="#id/relative_buy1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true">
<ViewFlipper
android:id="#+id/ViewFlipper01"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<TextView
android:id="#+id/buy_item_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true">
</TextView>
<EditText
android:id="#+id/buy_item_name_et"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:layout_below="#id/buy_item_name">
</EditText>
</RelativeLayout>
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<TextView
android:id="#+id/buy_ques_category"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true">
</TextView>
<Button
android:id="#+id/buy_food_cat_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:layout_below="#id/buy_ques_category">
</Button>
<Button
android:id="#+id/buy_education_cat_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:layout_below="#id/buy_food_cat_button">
</Button>
<Button
android:id="#+id/buy_personal_cat_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:layout_below="#id/buy_education_cat_button">
</Button>
</RelativeLayout>
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<TextView
android:id="#+id/buy_ques_cost"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true">
</TextView>
<EditText
android:id="#+id/buy_ques_cost_et"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:layout_below="#id/buy_ques_cost">
</EditText>
</RelativeLayout>
</ViewFlipper>
</RelativeLayout>
my activity
package apps.questions;
import android.app.Activity;
import android.content.ContentValues;
import android.graphics.PixelFormat;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.ViewFlipper;
import apps.project.R;
public class BuyActivity extends Activity implements OnClickListener {
ViewFlipper vf;
private static final String FOOD = "Food/Drinks";
private static final String EDUCATION = "Education";
private static final String PERSONAL = "Personal";
Button food_cat;
Button education_cat;
Button personal_cat;
Button next;
Button previous;
Button submit;
TextView item_name;
TextView item_cost;
TextView item_cat;
EditText name;
EditText cost;
ContentValues cv;
String iName;
double iPrice;
String iCategory;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.buy_advice_layout);
inflateView();
/*food_cat.setOnClickListener(this);
education_cat.setOnClickListener(this);
personal_cat.setOnClickListener(this);*/
}
public void onAttachedToWindow() {
super.onAttachedToWindow();
Window window = getWindow();
window.setFormat(PixelFormat.RGBA_8888);
}
private void inflateView() {
// TODO Auto-generated method stub
cv = new ContentValues();
vf = (ViewFlipper) findViewById(R.id.ViewFlipper01);
next = (Button)findViewById(R.id.buy_next);
previous = (Button)findViewById(R.id.buy_previous);
submit = (Button)findViewById(R.id.buy_submit);
/*food_cat = (Button)findViewById(R.id.buy_food_cat_button);
education_cat = (Button)findViewById(R.id.buy_education_cat_button);
personal_cat = (Button)findViewById(R.id.buy_personal_cat_button);*/
item_name = (TextView)findViewById(R.id.buy_item_name);
item_name.setText("Please enter the name of the item you wish to buy");
item_cat = (TextView)findViewById(R.id.buy_ques_category);
item_cat.setText("Please select the category of the item you wish to buy by clicking on the category button");
item_cost = (TextView)findViewById(R.id.buy_ques_cost);
item_cost.setText("Please enter the price of the item you wish to buy");
name = (EditText)findViewById(R.id.buy_item_name_et);
cost = (EditText)findViewById(R.id.buy_ques_cost_et);
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (v == next) {
vf.setAnimation(AnimationUtils.loadAnimation(v.getContext(), R.anim.push_left_in));
vf.showNext();
}
if (v == previous) {
vf.setAnimation(AnimationUtils.loadAnimation(v.getContext(), R.anim.push_left_out));
vf.showPrevious();
}
if (v == submit) {
//vf.showPrevious();
}
if (v == food_cat) {
iCategory = FOOD;
}
if (v == education_cat) {
iCategory = EDUCATION;
}
if (v == personal_cat) {
iCategory = PERSONAL;
}
}
}
It looks like you are missing the assignment of your click listeners to your buttons. Use the following code just below your find view by id calls for the buttons.
next = (Button)findViewById(R.id.buy_next);
previous = (Button)findViewById(R.id.buy_previous);
submit = (Button)findViewById(R.id.buy_submit);
//New code
next.setOnClickListener(this);
previous.setOnClickListener(this);
submit.setOnClickListener(this);

Categories

Resources