Why is my Android app showing up blank and then crashing? - android

Moved from Code Review: https://codereview.stackexchange.com/questions/56123/why-is-my-android-app-showing-up-blank-and-then-crashing
Every time I try to run my Android app, it shows the title bar with no content below it. After two minutes or so, it crashes. Here's the logcat:
http://pastebin.com/UFKeywgC
I know the problem stems from me trying to use a fragment structure for the first time. Here's my code:
TipCalculator.java
/* My verion of the Deitel Tip Calculator */
package org.bh.tipcalculator2;
import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.NotificationManager;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.SeekBar;
import android.widget.TableLayout;
import android.widget.TextView;
import android.widget.Toast;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class TipCalculator extends Activity {
// constants used when saving/restoring state
private static final String BILL_TOTAL = "BILL_TOTAL";
private static final String CUSTOM_PERCENT = "CUSTOM_PERCENT";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_tip_calculator);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.tip_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);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
private double currentBillTotal; // Bill as entered by the user
private int currentCustomPercent; // Custom tip % as set by user
private EditText billEditText; // Bill input widget
private EditText tip10EditText; // 10% tip output
private EditText tip15EditText; // 15% tip output
private EditText tip20EditText; // 20% tip output
private EditText tipCustomEditText; // ##% tip output
private EditText total10EditText; // 10% total output
private EditText total15EditText; // 15% total output
private EditText total20EditText; // 20% total output
private EditText totalCustomEditText; // ##% total output
private TextView customTipTextView; // Custom tip % output
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
if (savedInstanceState == null)
{
getFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment())
.commit();
currentBillTotal = 0;
currentCustomPercent = 18;
}
else
{
currentBillTotal = savedInstanceState.getDouble(BILL_TOTAL);
currentCustomPercent = savedInstanceState.getInt(CUSTOM_PERCENT);
}
View rootView = inflater.inflate(R.layout.fragment_tip_calculator, container, false);
tip10EditText = (EditText) rootView.findViewById(R.id.tip10EditText);
tip15EditText = (EditText) rootView.findViewById(R.id.tip15EditText);
tip20EditText = (EditText) rootView.findViewById(R.id.tip20EditText);
tipCustomEditText = (EditText) rootView.findViewById(R.id.tipCustomEditText);
total10EditText = (EditText) rootView.findViewById(R.id.total10EditText);
total15EditText = (EditText) rootView.findViewById(R.id.total15EditText);
total20EditText = (EditText) rootView.findViewById(R.id.total20EditText);
totalCustomEditText = (EditText) rootView.findViewById(R.id.totalCustomEditText);
customTipTextView = (TextView) rootView.findViewById(R.id.customTipTextView);
billEditText = (EditText) rootView.findViewById(R.id.billEditText);
//System.out.print(billEditText);
billEditText.addTextChangedListener(billEditTextWatcher);
SeekBar customSeekBar = (SeekBar) rootView.findViewById(R.id.customSeekBar);
customSeekBar.setOnSeekBarChangeListener(customSeekBarListener);
return rootView;
}
/**
* Calls {#link #updateStandard()} and then {#link #updateCustom()}.
*
* #see #updateStandard()
* #see #updateCustom()
*/
public void updateAll()
{
updateStandard();
updateCustom();
}
public void updateStandard()
{
calculateTipAndTotal(tip10EditText, total10EditText, .1);
calculateTipAndTotal(tip15EditText, total15EditText, .15);
calculateTipAndTotal(tip20EditText, total20EditText, .2);
}
public void updateCustom()
{
customTipTextView.setText(currentCustomPercent + "%");
calculateTipAndTotal(tipCustomEditText, totalCustomEditText, currentCustomPercent);
}
public void calculateTipAndTotal(EditText tipEditText, EditText totalEditText, double tip)
{
tipEditText .setText(String.format("%.02f", currentBillTotal * tip));
totalEditText.setText(String.format("%.02f", currentBillTotal * (tip + 1)));
}
#Override
public void onSaveInstanceState(Bundle outState)
{
super.onSaveInstanceState(outState);
outState.putDouble(BILL_TOTAL, currentBillTotal);
outState.putInt(CUSTOM_PERCENT, currentCustomPercent);
}
private SeekBar.OnSeekBarChangeListener customSeekBarListener =
new SeekBar.OnSeekBarChangeListener()
{
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
currentCustomPercent = seekBar.getProgress();
updateCustom();
}
#Override public void onStartTrackingTouch(SeekBar seekBar){}
#Override public void onStopTrackingTouch(SeekBar seekBar){}
}
;
private TextWatcher billEditTextWatcher =
new TextWatcher()
{
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
try
{
currentBillTotal = extractDouble(s);
}
catch (NumberFormatException ex) // if we still didn't get a number
{
currentBillTotal = 0;
}
updateAll();
}
#Override public void beforeTextChanged(CharSequence s, int start, int count, int after){}
#Override public void afterTextChanged(Editable editable){}
}
;
/**
* Attempts to extract the first double found. This ideally works with percents, currency
* notation, and other formats where the double is surrounded by delimiters and text, but is
* not interrupted by it.<br/>
*<br/>
* A double may look like any one of these, where {#code #} represents any number of digits 0
* through 9:
*
* <ul>
* <li>{#code #}</li>
* <li>{#code .#}</li>
* <li>{#code #.#}</li>
* </ul>
*
* #param possibleDouble a character sequence that might contain a double
*
* #return the extracted double
*
* #throws java.lang.NumberFormatException if a double could not be found
*/
public static double extractDouble(CharSequence possibleDouble)
{
/**
* Matches at least one digit, optionally preceded by a radix point, optionally preceded by
* any number of digits
*/
Matcher matcher = Pattern.compile("([0-9]*\\.)?[0-9]+").matcher(possibleDouble);
matcher.find();
return Double.parseDouble(matcher.group());
}
}
}
activity_tip_calculator.xml
<FrameLayout 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=".TipCalculator"
tools:ignore="MergeRootFrame" >
<fragment
android:layout_width="match_parent"
android:layout_height="match_parent"
android:name="org.bh.tipcalculator2.TipCalculator$PlaceholderFragment"
android:id="#+id/fragmentTipCalculator"
android:layout_gravity="center"
tools:layout="#layout/fragment_tip_calculator" />
</FrameLayout>
fragment_tip_calculator.xml
<TableLayout 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=".TipCalculator$PlaceholderFragment"
android:id="#+id/tableLayout"
android:stretchColumns="#string/tableLayoutStretchColumns">
<TableRow
android:layout_width="match_parent"
android:layout_height="fill_parent"
android:id="#+id/tableRow0"
android:gravity="center_vertical|right">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/billTotalLabel"
android:id="#+id/billTextView"
android:textColor="#android:color/secondary_text_dark" />
<EditText
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="#+id/billEditText"
android:inputType="numberDecimal"
android:layout_span="3"
android:text="#string/zeroCurrency"
android:selectAllOnFocus="false"
android:focusable="true"
android:focusableInTouchMode="true"
android:editable="true"
android:textIsSelectable="false"
android:textColor="#android:color/primary_text_dark"
android:hint="#string/billTotalHint"
android:enabled="true" />
<!--NumberPicker
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="#+id/billNumberPicker"
android:layout_span="3" /-->
</TableRow>
<TableRow
android:layout_width="match_parent"
android:layout_height="fill_parent"
android:id="#+id/tableRow2" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/tipTextLabel"
android:id="#+id/tipLabelTextView"
android:gravity="center_vertical|right"
android:textColor="#android:color/secondary_text_dark" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="number"
android:id="#+id/tip10EditText"
android:layout_weight="0"
android:focusable="#bool/outputEditable"
android:enabled="#bool/outputEditable"
android:editable="#bool/outputEditable"
android:longClickable="#bool/outputEditable"
android:focusableInTouchMode="#bool/outputEditable"
android:clickable="#bool/outputEditable"
android:textColor="#android:color/primary_text_dark"
android:text="#string/zeroCurrency" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="number"
android:id="#+id/tip15EditText"
android:layout_weight="0"
android:focusable="#bool/outputEditable"
android:enabled="#bool/outputEditable"
android:editable="#bool/outputEditable"
android:longClickable="#bool/outputEditable"
android:focusableInTouchMode="#bool/outputEditable"
android:clickable="#bool/outputEditable"
android:textColor="#android:color/primary_text_dark"
android:text="#string/zeroCurrency" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="number"
android:id="#+id/tip20EditText"
android:layout_weight="0"
android:focusable="#bool/outputEditable"
android:enabled="#bool/outputEditable"
android:editable="#bool/outputEditable"
android:longClickable="#bool/outputEditable"
android:focusableInTouchMode="#bool/outputEditable"
android:clickable="#bool/outputEditable"
android:textColor="#android:color/primary_text_dark"
android:text="#string/zeroCurrency" />
</TableRow>
<TableRow
android:layout_width="match_parent"
android:layout_height="fill_parent"
android:id="#+id/tableRow1">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/tenPercent"
android:id="#+id/tenTextView"
android:layout_column="1"
android:gravity="center_horizontal|bottom"
android:textColor="#android:color/secondary_text_dark" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/fifteenPercent"
android:id="#+id/fifteenTextView"
android:gravity="center_horizontal|bottom"
android:textColor="#android:color/secondary_text_dark" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/twentyPercent"
android:id="#+id/twentyTextView2"
android:gravity="center_horizontal|bottom"
android:textColor="#android:color/secondary_text_dark" />
</TableRow>
<TableRow
android:layout_width="match_parent"
android:layout_height="fill_parent"
android:id="#+id/tableRow3" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/totalTextLabel"
android:id="#+id/textView"
android:gravity="center_vertical|right"
android:textColor="#android:color/secondary_text_dark" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="number"
android:id="#+id/total10EditText"
android:layout_weight="0"
android:text="#string/zeroCurrency"
android:focusable="#bool/outputEditable"
android:enabled="#bool/outputEditable"
android:editable="#bool/outputEditable"
android:longClickable="#bool/outputEditable"
android:focusableInTouchMode="#bool/outputEditable"
android:clickable="#bool/outputEditable"
android:textColor="#android:color/primary_text_dark" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="number"
android:id="#+id/total15EditText"
android:layout_weight="0"
android:text="#string/zeroCurrency"
android:focusable="#bool/outputEditable"
android:enabled="#bool/outputEditable"
android:editable="#bool/outputEditable"
android:longClickable="#bool/outputEditable"
android:focusableInTouchMode="#bool/outputEditable"
android:clickable="#bool/outputEditable"
android:textColor="#android:color/primary_text_dark" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="number"
android:id="#+id/total20EditText"
android:layout_weight="0"
android:text="#string/zeroCurrency"
android:focusable="#bool/outputEditable"
android:enabled="#bool/outputEditable"
android:editable="#bool/outputEditable"
android:longClickable="#bool/outputEditable"
android:focusableInTouchMode="#bool/outputEditable"
android:clickable="#bool/outputEditable"
android:textColor="#android:color/primary_text_dark" />
</TableRow>
<TableRow
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:id="#+id/spacerTableRow"
android:layout_weight="1">
</TableRow>
<TableRow
android:layout_width="match_parent"
android:layout_height="fill_parent"
android:id="#+id/tableRow4"
android:layout_gravity="bottom">
<TextView
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:text="#string/customTextLabel"
android:id="#+id/customTextView"
android:gravity="center_vertical|right"
android:textColor="#android:color/secondary_text_dark" />
<SeekBar
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/customSeekBar"
android:indeterminate="false"
android:indeterminateOnly="false"
android:layout_span="2"
android:max="200"
android:progress="18" />
<TextView
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:text="#string/customTipReadoutPlaceholder"
android:id="#+id/customTipTextView"
android:gravity="center_vertical|left" />
</TableRow>
<TableRow
android:layout_width="match_parent"
android:layout_height="fill_parent"
android:id="#+id/tableRow5"
android:layout_gravity="bottom">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceSmall"
android:text="#string/tipTextLabel"
android:id="#+id/tipCustomTextView"
android:gravity="center_vertical|right"
android:textColor="#android:color/secondary_text_dark" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="number"
android:id="#+id/tipCustomEditText"
android:layout_weight="0"
android:focusable="#bool/outputEditable"
android:enabled="#bool/outputEditable"
android:editable="#bool/outputEditable"
android:longClickable="#bool/outputEditable"
android:focusableInTouchMode="#bool/outputEditable"
android:clickable="#bool/outputEditable"
android:textColor="#android:color/primary_text_dark"
android:text="#string/zeroCurrency" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/totalTextLabel"
android:id="#+id/totalCustomTextView"
android:gravity="center_vertical|right"
android:textColor="#android:color/secondary_text_dark" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="number"
android:id="#+id/totalCustomEditText"
android:layout_weight="0"
android:text="#string/zeroCurrency"
android:focusable="#bool/outputEditable"
android:enabled="#bool/outputEditable"
android:editable="#bool/outputEditable"
android:longClickable="#bool/outputEditable"
android:focusableInTouchMode="#bool/outputEditable"
android:clickable="#bool/outputEditable"
android:textColor="#android:color/primary_text_dark" />
</TableRow>
</TableLayout>

Problem is here:
public static class PlaceholderFragment extends Fragment {
...
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
if (savedInstanceState == null)
{
getFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment())
.commit();
currentBillTotal = 0;
currentCustomPercent = 18;
}
When you create the view for the PlaceholderFragment, you're actually creating another PlaceholderFragment and adding it too. This will keep running and consuming memory until it's completely exhausted (and crashes).
In short, you should remove that part. The fragment has already been added.

Related

How to indicate an error if an user inputs letters into the edit text for age? (Android Studio)

I am trying to make an app which intakes student details. Part of that detail is the students age which is supposed to be only a number input. If letters are entered into the edit text field, the app must indicate an error.
I have the coding below, however it seems like there are no changes to the app as it still crashes whenever I enter a letter for age.
//xml content
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingTop="40dp"
android:background="#F0F8FF"
>
<TableLayout
android:id="#+id/add_table"
android:layout_width="match_parent"
android:layout_height="606dp"
android:paddingTop="40dp">
<TableRow>
<TextView
android:layout_marginLeft="25dp"
android:padding="3dip"
android:text="Student ID:" />
<EditText
android:id="#+id/sid"
android:layout_width="190dp"
android:layout_height="wrap_content" />
</TableRow>
<TableRow>
<TextView
android:layout_marginLeft="25dp"
android:padding="3dip"
android:text="First Name:" />
<EditText
android:id="#+id/fn"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:minWidth="150dip" />
</TableRow>
<TableRow>
<TextView
android:layout_marginLeft="25dp"
android:padding="3dip"
android:text="Last Name:" />
<EditText
android:id="#+id/ln"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:minWidth="150dip" />
</TableRow>
<TableRow>
<TextView
android:layout_marginLeft="25dp"
android:padding="3dip"
android:layout_marginTop="5dp"
android:text="Gender:" />
<RadioGroup
android:id="#+id/ge"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="5dp"
android:orientation="horizontal">
<RadioButton
android:id="#+id/male"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:scaleX="0.9"
android:scaleY="0.9"
android:text="Male" />
<RadioButton
android:id="#+id/female"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:scaleX="0.9"
android:scaleY="0.9"
android:text="Female" />
</RadioGroup>
</TableRow>
<TableRow>
<TextView
android:layout_marginLeft="25dp"
android:padding="3dip"
android:text="Course Study:" />
<EditText
android:id="#+id/cs"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:minWidth="150dip" />
</TableRow>
<TableRow>
<TextView
android:layout_marginLeft="25dp"
android:inputType="number"
android:digits="0123456789"
android:padding="3dip"
android:text="Age:" />
<EditText
android:id="#+id/ag"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:minWidth="150dip" />
</TableRow>
<TableRow>
<TextView
android:layout_marginLeft="25dp"
android:padding="3dip"
android:text="Address:" />
<EditText
android:id="#+id/ad"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:minWidth="150dip" />
</TableRow>
<Button
android:id="#+id/add_button"
android:layout_width="207dp"
android:layout_height="wrap_content"
android:layout_marginLeft="118dp"
android:layout_marginRight="52dp"
android:layout_marginTop="14dp"
android:padding="6dip"
android:text="Add Student" />
<ImageView
android:id="#+id/imageView4"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingTop="10dp"
app:srcCompat="#mipmap/man" />
</TableLayout>
//Java
package com.user.project3;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.IdRes;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Toast;
public class Addrecord extends AppCompatActivity {
DatabaseManager myDb;
EditText sid, fn, ln, cs, ag, ad;
RadioGroup radioGenderGroup;
RadioButton radioGenderButton;
Button btnAddStudent;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setTitle(null);
myDb = new DatabaseManager(this);
sid = (EditText)findViewById(R.id.sid);
fn = (EditText)findViewById(R.id.fn);
ln = (EditText)findViewById(R.id.ln);
cs = (EditText)findViewById(R.id.cs);
ag = (EditText)findViewById(R.id.ag);
ad = (EditText)findViewById(R.id.ad);
btnAddStudent = (Button)findViewById(R.id.add_button);
AddStudentRecord();
}
public void AddStudentRecord() {
btnAddStudent.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
radioGenderGroup = (RadioGroup) findViewById(R.id.ge);
int selectedid = radioGenderGroup.getCheckedRadioButtonId();
radioGenderButton = (RadioButton) findViewById(selectedid);
boolean isInserted = myDb.insertDataStudent(
Integer.parseInt(sid.getText().toString()),
fn.getText().toString(),
ln.getText().toString(),
radioGenderButton.getText().toString(),
cs.getText().toString(),
Integer.parseInt(ag.getText().toString()),
ad.getText().toString()
);
String strNumber=ag.getText().toString().trim();
if(TextUtils.isEmpty(strNumber) || Integer.parseInt(strNumber)>100){
Toast.makeText(Addrecord.this,"Please input a number",Toast.LENGTH_LONG).show();
}
if(isInserted == true)
Toast.makeText(Addrecord.this,"Data Inserted",Toast.LENGTH_LONG).show();
else
Toast.makeText(Addrecord.this,"Data not Inserted",Toast.LENGTH_LONG).show();
}
}
);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.screen2_menu, 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.home2) {
Intent intent = new Intent(Addrecord.this, Home.class);
startActivity(intent);
return true;
}
if (id == R.id.viewarecord) {
Intent intent = new Intent(Addrecord.this, Viewstudent.class);
startActivity(intent);
return true;
}
return super.onOptionsItemSelected(item);
}
}
//crash log
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.supriya.project3, PID: 2274
java.lang.NumberFormatException: For input string: "j"
at java.lang.Integer.parseInt(Integer.java:608)
at java.lang.Integer.parseInt(Integer.java:643)
at
com.supriya.project3.Addrecord$1.onClick(Addrecord.java:72)
at android.view.View.performClick(View.java:6891)
at
android.widget.TextView.performClick(TextView.java:12651)
at
android.view.View$PerformClick.run(View.java:26083)
at
android.os.Handler.handleCallback(Handler.java:789)
at
android.os.Handler.dispatchMessage(Handler.java:98)
at android.os.Looper.loop(Looper.java:164)
at
android.app.ActivityThread.main(ActivityThread.java:6938)
at java.lang.reflect.Method.invoke(Native Method)
at
com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:327)
at
com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1374)
Application terminated.
Try this
youredittext.addTextChangedListener(new TextWatcher()
{
#Override
public void afterTextChanged(Editable mEdit)
{
String regexStr = "^[0-9]*$";
if(your_editText.getText().toString().trim().matches(regexStr))
{
//write code here for success
}
else{
// write code here on failure
}
}
public void beforeTextChanged(CharSequence s, int start, int count, int after){}
public void onTextChanged(CharSequence s, int start, int before, int count){}
});
let me know if this is working or not
You can use android:inputType="number" . If you also want to filter the number that user input, you can addTextChangeListener.
String strNumber = ag.getText().toString().trim();
if(TextUtils.isEmpty(strNumber)){
Toast.makeText(Addrecord.this,"Please input a number",Toast.LENGTH_LONG).show();
}else{
String regexStr = "^[0-9]*$";
if(your_editText.getText().toString().trim().matches(regexStr))
{
//write code here for success
your_editText.setError(null) // to clear any errors
}
else{
your_editText.setError(“please insert numbers only”);
}
}
}
Use this regex to find if a string has numbers or not:
Pattern pattern = Pattern.compile(".*[^0-9].*");
pattern.matcher(you input in edittext).matches());

How to add onClick for buttons?

I'm trying to figure out why my app crashes when my AddThreeToTeamA button crashes my application upon clicking. I have addded my XML and my Java code.
I am following a tutorial however it obviously does not crash and I have tried several different solutions.
Any hint will be appreciated.
package com.themovingmonkey.courtcounter;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
int score = 0;
int scoreTeamA;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void addThreeForTeamA() {
scoreTeamA = score + 3;
displayForTeamA(scoreTeamA);
}
public void addTwoForTeamA() {
scoreTeamA = score + 2;
displayForTeamA(scoreTeamA);
}
public void addOneForTeamA() {
scoreTeamA = score + 1;
displayForTeamA(scoreTeamA);
}
public void displayForTeamA(int score) {
TextView scoreView = (TextView) findViewById(R.id.Team_A_Score);
scoreView.setText(String.valueOf(scoreTeamA));
}
}
////////////////////////////////////////////////////////////////
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="16dp"
android:paddingRight="16dp"
android:orientation="vertical"
>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:text= "Team A"
android:padding="4dp"/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:text="0"
android:padding="4dp"
android:id="#+id/Team_A_Score"/>
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="3 Points"
android:layout_margin="8dp"
android:onClick="addThreeForTeamA"
/>
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="2 Points"
android:layout_margin="8dp"
android:onClick="addTwoForTeamA"
/>
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="1 Point"
android:layout_margin="8dp"
android:onClick="addOneForTeamA"
/>
</LinearLayout>
All methods defined using the android:onClick="someMethod" attribute. Then they have to be public and should pass a View as the only parameter, Change your methods to:
public void someMethod(View view){
//Everything else!
}
Your methods do not pass a View as the only parameter at all currently!

onFocusChange Doesnt respond from within a view pager

Reposting this as I initially posted it originally with the wrong title and so it got lost in the void of questions.
I'm creating a small timetable app, and am currently creating a screen with some tabs. Each tab is a seperate fragment and each have 20 edit texts inside of them. What I aim to do, is if the user types in one of the edit texts, then clicks off of it and the focus is lost, to send the text from the edit text field to the main activity. Then, when the confirm button is clicked, any text that is in the edit texts is then saved to an SQLite database.
My problem is that the focus listener doesn't seem to be working.
Here is one of the fragment's code:
package com.example.schoolandrevisiontimetable;
import android.support.v4.app.Fragment;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnFocusChangeListener;
import android.view.ViewGroup;
import android.widget.EditText;
public class Input_slessontime_monday extends Fragment implements OnFocusChangeListener{
OnMondayEditTextChangedListener monCallback;
private String mondayString;
private int mondayPeriod;
private int mondayPosition;
public void MondayEditTextChanged(String mondayEditText, int period, int position){
mondayString = mondayEditText;
mondayPeriod = period;
mondayPosition=position;
monCallback.onMondayEditTextChanged(mondayString, mondayPeriod, mondayPosition);
}
public interface OnMondayEditTextChangedListener {
public void onMondayEditTextChanged(String mondayEditText, int period, int position);
}
EditText[][] mondayInput = new EditText[11][2];
String [][] mondayStrings = new String [11][2];
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootView = inflater.inflate(R.layout.fragment_input_slessontime_monday,
container, false);
mondayInput[1][0] = (EditText) rootView.findViewById(R.id.mondayslesson1start);
mondayInput[1][1] = (EditText) rootView.findViewById(R.id.mondayslesson1end);
mondayInput[2][0] = (EditText) rootView.findViewById(R.id.mondayslesson2start);
mondayInput[2][1] = (EditText) rootView.findViewById(R.id.mondayslesson2end);
...
//this continues up to 10. Had to delete the rest due to character limitations
Log.v("Monday", "Edit texts all set");
return rootView;
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
// This makes sure that the container activity has implemented
// the callback interface. If not, it throws an exception
try {
monCallback = (OnMondayEditTextChangedListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement OnMondayEditTextChanged");
}
}
#Override
public void onFocusChange(View v, boolean hasFocus) {
Log.v("monday", "focus change!");
String edittext;
if(!hasFocus)
switch(v.getId()){
case R.id.mondayslesson1start:
edittext = mondayInput[1][0].getText().toString();
MondayEditTextChanged(edittext,1,0);
break;
case R.id.mondayslesson1end:
edittext = mondayInput[1][1].getText().toString();
MondayEditTextChanged(edittext,1,1);
break;
case R.id.mondayslesson2start:
edittext = mondayInput[2][0].getText().toString();
MondayEditTextChanged(edittext,2,0);
break;
case R.id.mondayslesson2end:
edittext = mondayInput[2][1].getText().toString();
MondayEditTextChanged(edittext,2,1);
break;
//this continues up to 10. Had to delete the rest due to character limitations
}
}
}
Here is the activity's code:
package com.example.schoolandrevisiontimetable;
import java.util.List;
import com.astuetz.PagerSlidingTabStrip;
import Database.DatabaseHelper;
import Database.MC_sschoolday;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.util.TypedValue;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
/**DETECTIVEREPORT:
* onfocuschange does nothing
* but it seems that getCount() is called everytime you click onto another textbox, or scroll. probably unrelated.
* **/
public class Input_slessontime extends FragmentActivity implements
Input_slessontime_monday.OnMondayEditTextChangedListener,
Input_slessontime_tuesday.OnTuesdayEditTextChangedListener,
Input_slessontime_wednesday.OnWednesdayEditTextChangedListener{
//this class uses the pagerslidingtabstrip library from https://github.com/astuetz/PagerSlidingTabStrip to create a tab layout.
MC_sschoolday[] sday = new MC_sschoolday[7]; //new array of schooldays
int amountOfDays;
List<MC_sschoolday> schoolday;
DatabaseHelper db;
public static FragmentManager fgmanger;
private PagerSlidingTabStrip tabs;
private ViewPager pager;
private MyPagerAdapter adapter;
Input_slessontime_monday mondayFragment;
String[][][] slessonTimes = new String[8][11][2];
int numberOfLessonTimes=0;
String[] slessonPointer = new String[140];
#Override
protected void onCreate(Bundle savedInstanceState) {
Log.v("LessonTimeInput", "oncreate");
db = new DatabaseHelper(getApplicationContext());
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_input_slessontime);
fgmanger = getSupportFragmentManager();
schoolday = db.getAllSSchoolDays();
amountOfDays = getAmountOfDaysUsed();
tabs = (PagerSlidingTabStrip)findViewById(R.id.tabs); //set the tabs
pager = (ViewPager) findViewById(R.id.pager); //set the pager
adapter = new MyPagerAdapter(fgmanger); //set the adapter
pager.setAdapter(adapter); //set the adapter to the pager
final int pageMargin = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 4, getResources()
.getDisplayMetrics());
pager.setPageMargin(pageMargin);
tabs.setViewPager(pager);
db.close();
}
#Override
public void onMondayEditTextChanged(String mondayEditText, int period, int position) {
slessonTimes[1][period][position] = mondayEditText;
Log.v("LessonTimeInput", "MondayLessontime Added "+ period + " " + position);
slessonPointer[numberOfLessonTimes] = ("1"+period+position);
numberOfLessonTimes++;
}
#Override
public void onTuesdayEditTextChanged(String tuesdayEditText, int period,
int position) {
Log.v("LessonTimeInput", "TuesdayLessontime Added "+ period + " " + position);
slessonTimes[2][period][position] = tuesdayEditText;
slessonPointer[numberOfLessonTimes] = ("2"+period+position);
numberOfLessonTimes++;
}
#Override
public void onWednesdayEditTextChanged(String wednesdayEditText, int period,
int position) {
Log.v("LessonTimeInput", "TuesdayLessontime Added "+ period + " " + position);
slessonTimes[3][period][position] = wednesdayEditText;
slessonPointer[numberOfLessonTimes] = ("3"+period+position);
numberOfLessonTimes++;
}
public void confirmslesson(View v){
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.input_slessontime, 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.
*/
//this gets the amount of days used, so that the code knows how many tabs to generate
public int getAmountOfDaysUsed(){
db = new DatabaseHelper(getApplicationContext()); //open the database
int amountOfDaysUsed=0; //initialise this int
for (int i =0; i<7; i++){
sday[i]=schoolday.get(i); //stores the lessons in an array
}
for (int i =0; i<7; i++){
if(sday[i].getUsed().toString().equals("y")){ //find how many days are used
amountOfDaysUsed++;
}
}
db.close(); //close the database
Log.v("LessonTimeInput", "amount of days used " + amountOfDaysUsed);
return amountOfDaysUsed; //return the int
}
//small subclass for the pageradapter
public class MyPagerAdapter extends FragmentPagerAdapter {
public MyPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public CharSequence getPageTitle(int position) {
String[] days = new String[7];
db = new DatabaseHelper(getApplicationContext());
int usedCount2=0;
for (int i =0; i< 7; i++){
sday[i]=schoolday.get(i);
if(sday[i].getUsed().toString().equals("y")){
days[usedCount2] = sday[i].getschool_day();
usedCount2++;
}
}
db.close();
Log.v("LessonTimeInput", "getPageTitle");
return days[position];
}
#Override
public int getCount() {
Log.v("LessonTimeInput", "getCount");
return getAmountOfDaysUsed();
}
public Fragment switchFragmentDay(int num) {
DatabaseHelper db;
db = new DatabaseHelper(getApplicationContext());
MC_sschoolday[] sday = new MC_sschoolday[7];
int usedCount1=amountOfDays;
int [] dayID = new int[usedCount1];
int usedCount2=0;
for (int i =0; i< amountOfDays; i++){
sday[i]=schoolday.get(i);
if(sday[i].getUsed().toString().equals("y")){
dayID[usedCount2] = (int) sday[i].getSchool_day_id();
usedCount2++;
}
}
db.close();
switch (dayID[num]){
case 1:
return new Input_slessontime_monday();
case 2:
return new Input_slessontime_tuesday();
case 3:
return new Input_slessontime_wednesday();
case 4:
return new Input_slessontime_thursday();
case 5:
return new Input_slessontime_friday();
case 6:
return new Input_slessontime_saturday();
case 7:
return new Input_slessontime_sunday();
}
return null;
}
#Override
public Fragment getItem(int position) {
switch (position){
case 0:
return switchFragmentDay(0);
case 1:
return switchFragmentDay(1);
case 2:
return switchFragmentDay(2);
case 3:
return switchFragmentDay(3);
case 4:
return switchFragmentDay(4);
case 5:
return switchFragmentDay(5);
case 6:
return switchFragmentDay(6);
}
return null;
}
}
public void StartIntent(Class<?> intentclass) {
// TODO Auto-generated method stub
Intent intent = new Intent(this, intentclass);
startActivity(intent);
}
}
The XML for the fragment:
<ScrollView
android:id="#+id/monday_fragment"
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
tools:context="com.pipturner.timetable.Input_slessontime_monday"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<CheckBox
android:id="#+id/mondayslesson1used"
android:layout_width="wrap_content"
android:layout_height="80dp"
android:text="#string/prompt_lesson" />
<EditText
android:id="#+id/mondayslesson1start"
android:inputType="textMultiLine"
android:hint="#string/start"
android:dependency="mondayslesson1used"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="2"
android:ems="10" />
<EditText
android:id="#+id/mondayslesson1end"
android:inputType="textMultiLine"
android:hint="#string/end"
android:dependency="mondayslesson2used"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="2"
android:ems="10" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<CheckBox
android:id="#+id/mondayslesson2used"
android:layout_width="wrap_content"
android:layout_height="80dp"
android:text="#string/prompt_lesson" />
<EditText
android:id="#+id/mondayslesson2start"
android:inputType="textMultiLine"
android:hint="#string/start"
android:dependency="mondayslesson1used"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="2"
android:ems="10" />
<EditText
android:id="#+id/mondayslesson2end"
android:inputType="textMultiLine"
android:hint="#string/end"
android:dependency="mondayslesson2used"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="2"
android:ems="10" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<CheckBox
android:id="#+id/mondayslesson3used"
android:layout_width="wrap_content"
android:layout_height="80dp"
android:text="#string/prompt_lesson" />
<EditText
android:id="#+id/mondayslesson3start"
android:inputType="textMultiLine"
android:hint="#string/start"
android:dependency="mondayslesson3used"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="2"
android:ems="10" />
<EditText
android:id="#+id/mondayslesson3end"
android:inputType="textMultiLine"
android:hint="#string/end"
android:dependency="mondayslesson3used"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="2"
android:ems="10" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<CheckBox
android:id="#+id/mondayslesson4used"
android:layout_width="wrap_content"
android:layout_height="80dp"
android:text="#string/prompt_lesson" />
<EditText
android:id="#+id/mondayslesson4start"
android:inputType="textMultiLine"
android:hint="#string/start"
android:dependency="mondayslesson4used"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="2"
android:ems="10" />
<EditText
android:id="#+id/mondayslesson4end"
android:inputType="textMultiLine"
android:hint="#string/end"
android:dependency="mondayslesson4used"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="2"
android:ems="10" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<CheckBox
android:id="#+id/mondayslesson5used"
android:layout_width="wrap_content"
android:layout_height="80dp"
android:text="#string/prompt_lesson" />
<EditText
android:id="#+id/mondayslesson5start"
android:inputType="textMultiLine"
android:hint="#string/start"
android:dependency="mondayslesson5used"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="2"
android:ems="10" />
<EditText
android:id="#+id/mondayslesson5end"
android:inputType="textMultiLine"
android:hint="#string/end"
android:dependency="mondayslesson5used"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="2"
android:ems="10" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<CheckBox
android:id="#+id/mondayslesson6used"
android:layout_width="wrap_content"
android:layout_height="80dp"
android:text="#string/prompt_lesson" />
<EditText
android:id="#+id/mondayslesson6start"
android:inputType="textMultiLine"
android:hint="#string/start"
android:dependency="mondayslesson6used"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="2"
android:ems="10" />
<EditText
android:id="#+id/mondayslesson6end"
android:inputType="textMultiLine"
android:hint="#string/end"
android:dependency="mondayslesson6used"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="2"
android:ems="10" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<CheckBox
android:id="#+id/mondayslesson7used"
android:layout_width="wrap_content"
android:layout_height="80dp"
android:text="#string/prompt_lesson" />
<EditText
android:id="#+id/mondayslesson7start"
android:inputType="textMultiLine"
android:hint="#string/start"
android:dependency="mondayslesson7used"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="2"
android:ems="10" />
<EditText
android:id="#+id/mondayslesson7end"
android:inputType="textMultiLine"
android:hint="#string/end"
android:dependency="mondayslesson7used"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="2"
android:ems="10" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<CheckBox
android:id="#+id/mondayslesson8used"
android:layout_width="wrap_content"
android:layout_height="80dp"
android:text="#string/prompt_lesson" />
<EditText
android:id="#+id/mondayslesson8start"
android:inputType="textMultiLine"
android:hint="#string/start"
android:dependency="mondayslesson8used"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="2"
android:ems="10" />
<EditText
android:id="#+id/mondayslesson8end"
android:inputType="textMultiLine"
android:hint="#string/end"
android:dependency="mondayslesson8used"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="2"
android:ems="10" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<CheckBox
android:id="#+id/mondayslesson9used"
android:layout_width="wrap_content"
android:layout_height="80dp"
android:text="#string/prompt_lesson" />
<EditText
android:id="#+id/mondayslesson9start"
android:inputType="textMultiLine"
android:hint="#string/start"
android:dependency="mondayslesson9used"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="2"
android:ems="10" />
<EditText
android:id="#+id/mondayslesson9end"
android:inputType="textMultiLine"
android:hint="#string/end"
android:dependency="mondayslesson9used"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="2"
android:ems="10" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<CheckBox
android:id="#+id/mondayslesson10used"
android:layout_width="wrap_content"
android:layout_height="80dp"
android:text="#string/prompt_lesson" />
<EditText
android:id="#+id/mondayslesson10start"
android:inputType="textMultiLine"
android:hint="#string/start"
android:dependency="mondayslesson10used"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="2"
android:ems="10" />
<EditText
android:id="#+id/mondayslesson10end"
android:inputType="textMultiLine"
android:hint="#string/end"
android:dependency="mondayslesson10used"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="2"
android:ems="10" />
</LinearLayout>
</LinearLayout>
</ScrollView>
and the XML for the activity:
<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:orientation="vertical" >
<com.astuetz.PagerSlidingTabStrip
android:id="#+id/tabs"
android:layout_width="match_parent"
android:layout_height="48dip"
android:background="#drawable/background_tabs" />
<android.support.v4.view.ViewPager
android:id="#+id/pager"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
tools:context=".Input_slessontime" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<Button
style="?android:attr/borderlessButtonStyle"
android:id="#+id/cancelslessontime"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#string/cancel"
android:layout_weight="1" />
<Button
style="?android:attr/borderlessButtonStyle"
android:id="#+id/confirmslessontime"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#string/confirm"
android:layout_weight="1"
android:onClick="confirmslesson" />
</LinearLayout>
</LinearLayout>
Something that may be related, is that when I click on or off an edit text, or scroll the fragment, getCount() is called. Probably unrelated.
Thanks in advance!
needed to set an onFocusListener.
//Thanks for the help guys//
¬¬

multiply with zero, double no number

I am trying to build a calculator for android, i am trying to multiply two numbers.
If i give number 1 and leave number 2 open, i want to get zero as an answer.
I first thought it could be the problem of not having a value for the double.
So i tried: if (Double.isNaN(number1)) { number1=0; }
But it did not work.
How do i make this happen?
R.layout.main:
<?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" >
<!-- 1 -->
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="number:" />
<EditText
android:id="#+id/number1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:hint="0"
android:inputType="number"
android:layout_marginLeft="20dp" />
</LinearLayout>
<!-- 2 -->
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="number:" />
<EditText
android:id="#+id/number2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:hint="0"
android:inputType="number"
android:layout_marginLeft="20dp" />
</LinearLayout>
<!-- multiply -->
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:layout_marginTop="20dp" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="multiply:" />
<TextView
android:id="#+id/multiplydisplay"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text=""
android:layout_marginLeft="20dp" />
</LinearLayout>
<Button
android:id="#+id/btncalculate"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Calculate"/>
<Button
android:id="#+id/btnreset"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Reset" />
</LinearLayout>
TipcalcActivity.java
package com.tip.calc;
import android.app.Activity;
import android.os.Bundle;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Button;
import android.view.View;
public class TipcalcActivity extends Activity {
private EditText number1;
private EditText number2;
private TextView multiplydisplay;
private Button btncalculate;
private Button btnreset;
private double number1calc = 0;
private double number2calc = 0;
private double multiply = 0;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
initControls();
}
private void initControls() {
number1 = (EditText)findViewById(R.id.number1);
number2 = (EditText)findViewById(R.id.number2);
multiplydisplay = (TextView)findViewById(R.id.multiplydisplay);
btncalculate = (Button)findViewById(R.id.btncalculate);
btnreset = (Button)findViewById(R.id.btnreset);
btncalculate.setOnClickListener(new Button.OnClickListener() { public void
onClick (View v){ calculate(); }});
btnreset.setOnClickListener(new Button.OnClickListener() { public void
onClick (View v){ reset(); }});
}
private void calculate() {
number1calc=Double.parseDouble(number1.getText().toString());
number2calc=Double.parseDouble(number2.getText().toString());
multiply=(number1calc*number2calc);
multiplydisplay.setText(Double.toString(multiply));
}
private void reset() {
multiplydisplay.setText("");
number1.setText("");
number2.setText("");
}
}
you should just check that the content of the textfield of the value is different than "". If not, just assign the value 0.
In calculate :
private void calculate() {
number1calc=(number1.getText().toString() != "" ) ? Double.parseDouble(number1.getText().toString()) : 0;
number2calc=(number2.getText().toString() != "" ) ? Double.parseDouble(number2.getText().toString()) : 0;
multiply=(number1calc*number2calc);
multiplydisplay.setText(Double.toString(multiply));
}
if(numberOne.getText().toString().trim().length() < 1 || numberTwo.getText().toString().length() < 1){
multiplyDisplay.setText("0");
}
else{
//default handling
}
If the edittext is left blank, this is obviously not a number(NaN). Doing any operation with NaN in Java will cause the result of this operation to be NaN.

Android To make part of the visible screen scrollable

I searched net to find the answer for my following problem. But no answer found. I myself tried several ways, but I am still a novice at Android. What I found on net related to scrolling is official documentation and examples of scrolling on http://developer.android.com, Mr. Senthilkumar's How to scroll the screen, Kakka47's ScrollView only part of the screen, darrinps A scroll view with only part of the screen scrolling, etc.
This is very common requirement as is clear from above titles. I have following screen layout as shown in figure.
The screen from top to column titles is stable. The table records, below column titles needs to scroll. I have AbsoluteLayout (I know it is deprecated but that is the only one I can use for by specific need), inside it a scrollview and inside scrollview a TableLayout.
User clicks "Add" button to add the orders received. One order in one row. As rows increase, they go beyond visible area. Therefore, I want it to scroll so user can access it. But this part is not scrolling. I have given the listing of my code. Please tell me what to do.
Code:
package com.BookOrders;
import java.util.Calendar;
import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.content.Context;
import android.os.Bundle;
import android.view.View;
import android.widget.AbsoluteLayout;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ScrollView;
import android.widget.Spinner;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;
//import android.widget.TableRow.LayoutParams;
#SuppressWarnings("deprecation")
public class BookOrders extends Activity implements ScrollViewListener{
/** Called when the activity is first created. */
private TextView BookingDateDisplay;
private Button ChangeDate, AddRec, DeleteRec, SaveAll;
private CheckBox SelectedAll, SelectedRec;
private ObservableScrollView CustomScroller = null;
private ObservableScrollView CustomScrolled = null;
private int ChangedYear;
private int ChangedMonth;
private int ChangedDay;
public Context CurrentContext, UsedContext;
static final int DATE_DIALOG_ID = 0;
int IdGenerator = 100000;
int Number_of_Records = 0;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
#SuppressWarnings("deprecation")
final AbsoluteLayout main = (AbsoluteLayout)findViewById(R.id.widget0);
CurrentContext = main.getContext();
//final ScrollView ScrollControl = (ScrollView)findViewById(R.id.scroller);
//final AbsoluteLayout LayerControl = (AbsoluteLayout)findViewById(R.id.FinalLayer);
// UsedContext = LayerControl.getContext();
// capture our View elements
CustomScroller = (ObservableScrollView) findViewById(R.id.scrollContainer);
BookingDateDisplay = (TextView) findViewById(R.id.BookedDate);
ChangeDate = (Button) findViewById(R.id.pickDate);
AddRec = (Button) findViewById(R.id.AddRecord);
DeleteRec = (Button) findViewById(R.id.DeleteRecord);
SaveAll = (Button) findViewById(R.id.SaveRecord);
SelectedAll = (CheckBox) findViewById(R.id.SelectAll);
// add a click listener to the button
ChangeDate.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
showDialog(DATE_DIALOG_ID);
}
});
AddRec.setOnClickListener(new View.OnClickListener() {
public void onClick(View AddRecView) {
IdGenerator = IdGenerator+10;
UsedContext = AddRecView.getContext();
TableRow Tr = new TableRow(UsedContext);
for (int controls=0; controls<6; controls++) {
if (controls==0){
CheckBox RecordCheck = new CheckBox(UsedContext);
RecordCheck.setId(IdGenerator+controls);
RecordCheck.setTag("CheckBoxTag");
RecordCheck.setHeight(20);
RecordCheck.setWidth(25);
Tr.addView(RecordCheck);
}
if ((0 < controls ) && (controls<5)){
Spinner Record = new Spinner(UsedContext);
Record.setId(IdGenerator+controls);
//Record.setMinimumHeight(20);
//Record.setMinimumWidth(90);
Tr.addView(Record);
}
if (controls==5){
EditText OrderQuantity = new EditText(UsedContext);
OrderQuantity.setId(IdGenerator+controls);
//OrderQuantity.setHeight(20);
//OrderQuantity.setWidth(90);
Tr.addView(OrderQuantity);
}
}
TableLayout Orders = (TableLayout)findViewById(R.id.OrderData);
Orders.addView(Tr);
// Scrolls to line before last - why?
final ScrollView ScrollAttempt = (ScrollView) findViewById(R.id.scrollContainer);
ScrollAttempt.post(new Runnable() {
public void run() {
ScrollAttempt.fullScroll(View.FOCUS_DOWN);
}
});
Number_of_Records = Number_of_Records + 1;
}
});
// updates the date in the TextView
private void updateDisplay() {
BookingDateDisplay.setText(
new StringBuilder()
.append(ChangedDay).append("-")
.append(ChangedMonth + 1).append("-") // Month is 0 based so add 1
.append(ChangedYear).append(" "));
}
// the call back received when the user "sets" the date in the dialog
private DatePickerDialog.OnDateSetListener DateSetListener =
new DatePickerDialog.OnDateSetListener(){
public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
ChangedYear = year;
ChangedMonth = monthOfYear;
ChangedDay = dayOfMonth;
updateDisplay();
}
};
#Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case DATE_DIALOG_ID:
return new DatePickerDialog(this, DateSetListener, ChangedYear, ChangedMonth, ChangedDay);
}
return null;
}
public void onScrollChanged(ObservableScrollView scrollView, int x, int y, int oldx, int oldy) {
if(scrollView == CustomScroller) {
CustomScrolled.scrollTo(x, y);
} else if(scrollView == CustomScrolled) {
CustomScroller.scrollTo(x, y);
}
}
}
My main.xml:
<?xml version="1.0" encoding="utf-8"?>
<AbsoluteLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/widget0"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<!-- <ImageButton android:text="Date" android:layout_height="20px" android:layout_width="32px" android:id="#+id/BDate" android:layout_x="274dip" android:layout_y="51dip"></ImageButton> -->
<TextView
android:id="#+id/Title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_x="81dip"
android:layout_y="10dip"
android:background="#0ff0ff"
android:gravity="center"
android:text="Order Booking"
android:textColor="#330000"
android:textSize="20sp"
android:textStyle="bold"
android:typeface="serif" >
</TextView>
<TextView
android:id="#+id/BDate_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_x="277dip"
android:layout_y="52dip"
android:gravity="right"
android:text="Booked on:"
android:textSize="12sp" >
</TextView>
<TextView
android:id="#+id/BookedDate"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_x="350dip"
android:layout_y="52dip"
android:text=""
android:textSize="12sp" >
</TextView>
<Button
android:id="#+id/pickDate"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_x="400dip"
android:layout_y="15dip"
android:text="Change Date"
android:textSize="10sp" >
</Button>
<View
android:layout_width="wrap_content"
android:layout_height="36dp"
android:layout_y="68dp"
android:background="#drawable/gradient" >
</View>
<Button
android:id="#+id/AddRecord"
android:layout_width="120dp"
android:layout_height="34dp"
android:layout_x="10dip"
android:layout_y="71dip"
android:text="Add"
android:textSize="10sp" >
</Button>
<Button
android:id="#+id/DeleteRecord"
android:layout_width="120dp"
android:layout_height="34dp"
android:layout_x="140dp"
android:layout_y="71dp"
android:text="Delete"
android:textSize="10sp" >
</Button>
<Button
android:id="#+id/ClearRecord"
android:layout_width="120dp"
android:layout_height="34dp"
android:layout_x="270dp"
android:layout_y="71dp"
android:text="Clear"
android:textSize="10sp" >
</Button>
<Button
android:id="#+id/SaveRecord"
android:layout_width="120dp"
android:layout_height="34dp"
android:layout_x="400dp"
android:layout_y="71dp"
android:text="Save"
android:textSize="10sp" >
</Button>
<View
android:layout_width="wrap_content"
android:layout_height="1dp"
android:layout_y="110dp"
android:background="#drawable/gradient" >
</View>
<CheckBox
android:id="#+id/SelectAll"
android:layout_width="wrap_content"
android:layout_height="20dp"
android:layout_x="10dip"
android:layout_y="115dip"
android:text="Select All"
android:textSize="10sp" >
</CheckBox>
<TextView
android:id="#+id/Company"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_x="95dip"
android:layout_y="115dip"
android:background="#666666"
android:text="Company"
android:textColor="#000000"
android:textSize="12sp" >
</TextView>
<TextView
android:id="#+id/Product"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_x="200dip"
android:layout_y="115dip"
android:background="#666666"
android:text="Product"
android:textColor="#000000"
android:textSize="12sp" >
</TextView>
<TextView
android:id="#+id/Code"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_x="300dip"
android:layout_y="115dip"
android:background="#666666"
android:text="Code"
android:textColor="#000000"
android:textSize="12sp" >
</TextView>
<TextView
android:id="#+id/Model"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_x="380dp"
android:layout_y="115dp"
android:background="#666666"
android:text="Model"
android:textColor="#000000"
android:textSize="12sp" >
</TextView>
<TextView
android:id="#+id/Quantity"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_x="470dp"
android:layout_y="115dp"
android:background="#666666"
android:text="Quantity"
android:textColor="#000000"
android:textSize="12sp" >
</TextView>
<View
android:id="#+id/view1"
android:layout_width="wrap_content"
android:layout_height="1dp"
android:layout_x="0dip"
android:layout_y="134dip"
android:background="#drawable/gradient" >
</View>
<com.BookOrders.ObservableScrollView
android:id="#+id/scrollContainer"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:layout_x="1dp"
android:layout_y="140dp"
android:clickable="true"
android:fadeScrollbars="false"
android:fillViewport="true" >
<TableLayout
android:id="#+id/OrderData"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:stretchColumns="0,1,2,3,4" />
</com.BookOrders.ObservableScrollView>
</AbsoluteLayout>
Have you tried a ScrollView? You can find more about ScrollView here
Here is an example of how to use ScrollView:
<ScrollView
android:id="#+id/coupons_details_scroll_view"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<!--You can nest any other views here, and they will be scrollable, but take care of views that have their own scrolling capabilities like ListView -->
</ScrollView>
Good luck with it :)
I worked out the solution for this. For those who would like to know can first go through the following link
http://blog.stylingandroid.com/archives/447
I used this logic. However, I create rows dynamically when user clicks "Add" button. The only problem is, if you use spinner you won't be able to set its height zero.
Nitin

Categories

Resources