how to get the timer counted value in Android? - android

How to create an android mobile application that will do a counting in miliseconds (start from 0), and ask user to type"I Like to eat" in EditText and click submit. After user click submit, counting will stop and a dialog box will appear and show the counting result.
package com.example.labex4;
import java.util.Timer;
import java.util.TimerTask;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends Activity implements OnClickListener {
TextView textView1,textView2,textView3,textView4,displayValue;
EditText nameTxt;
Button button1;
int count = 0;
Timer T;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
T=new Timer();
T.scheduleAtFixedRate(new TimerTask() {
#Override
public void run() {
runOnUiThread(new Runnable()
{
#Override
public void run()
{
displayValue.setText("count="+count);
count++;
}
});
}
}, 0, 1);
textView1 = (TextView)findViewById(R.id.textView1);
textView2 = (TextView)findViewById(R.id.textView2);
textView3 = (TextView)findViewById(R.id.textView3);
textView4 = (TextView)findViewById(R.id.textView4);
displayValue = (TextView)findViewById(R.id.displayValue);
nameTxt = (EditText)findViewById(R.id.nameTxt);
button1 = (Button)findViewById(R.id.button1);
button1.setOnClickListener(this);
}
#Override
public void onClick(View v) {
T.cancel();
dialog.editext.setText(""+count);
}
}
***Here is The XML file***
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="${relativePackage}.${activityClass}" >
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:text="(Type Faster)"
android:textAppearance="?android:attr/textAppearanceLarge" />
<TextView
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/textView1"
android:layout_below="#+id/textView1"
android:layout_marginTop="25dp"
android:text="Miliseconds: " />
<TextView
android:id="#+id/displayValue"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/textView2"
android:layout_toRightOf="#+id/textView2"
android:text="displayvalue" />
<TextView
android:id="#+id/textView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/textView2"
android:layout_centerHorizontal="true"
android:layout_marginTop="26dp"
android:text="Type this words: " />
<TextView
android:id="#+id/textView4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/textView3"
android:layout_centerHorizontal="true"
android:layout_marginTop="17dp"
android:text="Frankie Jones Anak Saing"
android:textAppearance="?android:attr/textAppearanceMedium" />
<EditText
android:id="#+id/nameTxt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:layout_below="#+id/textView4"
android:layout_marginTop="38dp"
android:ems="10" />
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/nameTxt"
android:layout_centerHorizontal="true"
android:layout_marginTop="37dp"
android:text="Check" />
</RelativeLayout>

Global Variable
int count = 0;
Timer T;
Put the below code in onCreate after setContentView
T=new Timer();
T.scheduleAtFixedRate(new TimerTask() {
#Override
public void run() {
runOnUiThread(new Runnable()
{
#Override
public void run()
{
//myTextView.setText("count="+count);
count++;
}
});
}
}, 0, 1);
At Button OnCLick
UPDATE
T.cancel();
//Open popup or dialog or alert as per your choice and print the count value
//dialog.editext.setText(""+count);
AlertDialog alertDialog = new AlertDialog.Builder(<YourActivityName>this).create(); //Read Update
alertDialog.setTitle("You total time count");
alertDialog.setMessage(String.valueof(count));
alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// here you can add functions
alertDialog.dismiss();
}
});
alertDialog.show(); //<-- See This!
}
As Per Your Requirement I am pasting the whole class
import android.app.Activity;
import android.app.Dialog;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import java.util.Timer;
import java.util.TimerTask;
public class MainActivity extends Activity implements OnClickListener {
TextView textView1,textView2,textView3,textView4,displayValue;
EditText nameTxt;
Button button1;
int count = 0;
Timer T;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
T=new Timer();
T.scheduleAtFixedRate(new TimerTask() {
#Override
public void run() {
runOnUiThread(new Runnable()
{
#Override
public void run()
{
displayValue.setText("count="+count);
count++;
}
});
}
}, 0, 1);
textView1 = (TextView)findViewById(R.id.textView1);
textView2 = (TextView)findViewById(R.id.textView2);
textView3 = (TextView)findViewById(R.id.textView3);
textView4 = (TextView)findViewById(R.id.textView4);
displayValue = (TextView)findViewById(R.id.displayValue);
nameTxt = (EditText)findViewById(R.id.nameTxt);
button1 = (Button)findViewById(R.id.button1);
button1.setOnClickListener(this);
}
#Override
public void onClick(View v) {
T.cancel();
//Open popup or dialog or alert as per your choice and print the count value
//dialog.editext.setText(""+count);
final Dialog dialog = new Dialog(MainActivity.this);
dialog.setContentView(R.layout.custom_popup);
dialog.setTitle("Typing Result!");
// set the custom dialog components - text, image and button
TextView titletext = (TextView) dialog.findViewById(R.id.titletext);
//titletext.setText("Typing Result!");
titletext.setVisibility(View.GONE);
TextView text = (TextView) dialog.findViewById(R.id.text);
text.setText("Frankie Jones Igat, Your Typing Speed "+String.valueOf(count)+" miliseconds");
Button dialogButtonOK = (Button) dialog.findViewById(R.id.dialogButtonOK);
// if button is clicked, close the custom dialog
dialogButtonOK.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
dialog.dismiss();
}
});
dialog.show();
}
}
And Custom pop up layout in layout folder custom_popup.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#999999"
android:layout_marginTop="10dp">
<TextView
android:id="#+id/titletext"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:text="title"
android:textSize="18sp"
android:textColor="#android:color/black"/>
<TextView
android:id="#+id/text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/titletext"
android:layout_marginTop="5dp"
android:textSize="16sp"
android:text="titlekiefsjisejefsjeaij"
android:textColor="#android:color/black"
android:layout_centerHorizontal="true"
/>
<Button
android:id="#+id/dialogButtonOK"
android:layout_width="80dp"
android:layout_height="40dp"
android:text=" Ok "
android:layout_marginTop="10dp"
android:layout_marginRight="5dp"
android:layout_below="#+id/text"
android:textSize="18sp"
android:textColor="#android:color/black"
android:layout_centerHorizontal="true"
android:gravity="center"
android:background="#FF0000"
android:layout_marginBottom="10dp"
/>
</RelativeLayout>

Related

Create multiplication table layout

I am trying to generate Multiplication Table of any number that is input by user. I have developed the interface for the application but cannot understand where to start with the logical part(coding). What i want is when a user inputs a number into the EditText then in the TextView (id: printArea) should show the table of the input number in the format as given in image 2. [Just to show you example i used TextView in the printArea part and i do not know what to use instead]
<?xml version="1.0" encoding="utf-8"?>
<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"
tools:context=".MainActivity"
android:weightSum="1">
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="16dp"
android:text="Please Enter a Number: "
android:textSize="20sp" />
<EditText
android:id="#+id/num"
android:layout_width="90dp"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:layout_marginLeft="30dp"
android:textSize="20sp" />
</LinearLayout>
<Button
android:id="#+id/calculate"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:layout_below="#+id/log"
android:onClick="submitNumber"
android:text="Get Table" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1.0"
android:id="#+id/printArea" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<Button
android:id="#+id/clear"
android:layout_width="125dp"
android:layout_height="wrap_content"
android:layout_marginLeft="2dp"
android:layout_marginRight="1dp"
android:text="Clear" />
<Button
android:id="#+id/credits"
android:layout_width="125dp"
android:layout_height="wrap_content"
android:layout_marginLeft="1dp"
android:layout_marginRight="1dp"
android:text="Credits" />
<Button
android:id="#+id/exit"
android:layout_width="125dp"
android:layout_height="wrap_content"
android:layout_marginLeft="1dp"
android:layout_marginRight="2dp"
android:text="Exit" />
</LinearLayout>
</LinearLayout>
and the MainActivity.java is:
package com.example.tara.multiplicationtable;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
EditText num;
Button credits;
Button calculate;
Button clear;
Button exit;
TextView printArea;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
num = new EditText(this);
clear = new Button(this);
calculate = new Button(this);
credits = new Button(this);
calculate = new Button(this);
printArea = new TextView(this);
num = (EditText) findViewById(R.id.num);
credits = (Button) findViewById(R.id.credits);
clear = (Button) findViewById(R.id.clear);
exit = (Button) findViewById(R.id.exit);
printArea = (TextView) findViewById(R.id.printArea);
calculate = (Button) findViewById(R.id.calculate);
calculate.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
//change the integer value into string
int num1 = Integer.parseInt(num.getText().toString());
// Perform action on click
for (int i = 1; i <= 10; i++) {
printArea.setText(num1 + "X" + i + "=" + i * num1);
}
}
});
clear.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
num.setText("");
}
});
credits.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(MainActivity.this, Credits.class);
startActivity(i);
}
});
exit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
finish();
System.exit(0);
}
});
}
}
when application is launched it should show like thisThe initial state of application
and i want to make the application show the table like this if user input is 2 The Final Result
Make a Listview and then in its adapter add your table data.
Make adapter's layout like this:
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="2" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="*" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="2" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="=" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="4" />
Here are the codes that i used to build the Multiplication Table that i imagined to build. The code for activity_main.xml file will be:
<?xml version="1.0" encoding="utf-8"?>
<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"
tools:context=".MainActivity">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:layout_marginEnd="1dp"
android:layout_marginStart="2dp"
android:text="#string/Enter_number"
android:textSize="16sp" />
<EditText
android:id="#+id/num"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:layout_marginEnd="2dp"
android:layout_marginStart="1dp"
android:digits="0123456789"
android:hint="#string/hidden_text"
android:inputType="number"
android:maxLength="3"
android:textSize="16sp" />
</LinearLayout>
<Button
android:id="#+id/calculate"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#string/calculate"
android:imeOptions="actionDone"
android:textSize="16sp"/>
<!--android:onClick="submitNumber"-->
<TextView
android:id="#+id/printArea"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:textSize="20sp"
android:background="#drawable/backimage" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<Button
android:id="#+id/clear"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:layout_marginEnd="1dp"
android:layout_marginStart="2dp"
android:textSize="16sp"
android:text="#string/clear"
/>
<Button
android:id="#+id/credits"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:layout_marginEnd="1dp"
android:layout_marginStart="1dp"
android:textSize="16sp"
android:text="#string/credits" />
<Button
android:id="#+id/exit"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginEnd="2dp"
android:layout_marginStart="1dp"
android:layout_weight="1"
android:textSize="16sp"
android:text="#string/exit" />
</LinearLayout>
</LinearLayout>
The Code for the MainActivity.java file will be:
package com.example.tara.multiplicationtable;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
EditText num;
Button credits;
Button calculate;
Button clear;
Button exit;
TextView printArea;
//private static final String result = MainActivity.class.getSimpleName();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
num = new EditText(this);
clear = new Button(this);
calculate = new Button(this);
credits = new Button(this);
calculate = new Button(this);
printArea = new TextView(this);
num = (EditText) findViewById(R.id.num);
credits = (Button) findViewById(R.id.credits);
clear = (Button) findViewById(R.id.clear);
exit = (Button) findViewById(R.id.exit);
calculate = (Button) findViewById(R.id.calculate);
printArea = (TextView) findViewById(R.id.printArea);
calculate.setOnClickListener(new View.OnClickListener() {
// Perform action on Get Table Button click
public void onClick(View v) {
if (num.getText().length() == 0 ){
printArea.setText(R.string.err_msg);
}
else {
//change the integer value into string
printArea.setText("");
int num1 = Integer.parseInt(num.getText().toString());
String result;
for (int i = 1; i <= 10; i++) {
result = (num1 + " X " + i + " = " + i * num1);
printArea.append("\n" + result);
}
}
}
});
clear.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
num.setText("");
printArea.setText("");
}
});
credits.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(MainActivity.this, Credits.class));
}
});
exit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(MainActivity.this, "Good Bye, User!", Toast.LENGTH_SHORT).show();
finish();
}
});
}
}
Thank you everyone for the guidance.

Android Studio:App crashes when countdown timer is started

I made an app that counts the scored goals in a match (When you're playing with friends and you're too lazy to count the scores :D ) I want to make a countdown timer to count the time for the match.
My app crashes when I push a Start button to start the countdown timer.I have 2 Activities.The Main activity is the code that counts the scores for the 2 teams.
This is my Second Activity code(Where the CountDowntimer should be.):
package com.example.robert.scorecount;
import android.os.CountDownTimer;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import java.util.concurrent.TimeUnit;
public class SecondActivity extends AppCompatActivity {
Button StartButton,StopButton;
TextView TimerText;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
Button StartButton = (Button) findViewById(R.id.StartButton);
Button StopButton = (Button) findViewById(R.id.StopButton);
TextView TimerText = (TextView) findViewById(R.id.Timer);
TimerText.setText("00:00:00");
final CounterClass timer = new CounterClass(3600000,1000);
assert StartButton != null;
StartButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
timer.start();
}
});
assert StopButton != null;
StopButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
timer.cancel();
}
});
}
public class CounterClass extends CountDownTimer{
public CounterClass(long millisInFuture, long countDownInterval) {
super(millisInFuture, countDownInterval);
}
#Override
public void onTick(long millisUntilFinished) {
String HourMinutesSeconds = String.format("%02d:%02d:%02d", TimeUnit.MILLISECONDS.toHours(millisUntilFinished),
TimeUnit.MILLISECONDS.toMinutes(millisUntilFinished) - TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS.toHours(millisUntilFinished)),
TimeUnit.MILLISECONDS.toSeconds(millisUntilFinished) - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(millisUntilFinished)));
TimerText.setText(HourMinutesSeconds);
}
#Override
public void onFinish() {
TimerText.setText("Finished.");
}
}
}
And This is my layout code:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.example.robert.scorecount.SecondActivity">
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Timer Settings"
android:id="#+id/textView"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:textSize="20dp"
android:textAlignment="center" />
<Button
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Start"
android:id="#+id/StartButton"
android:layout_marginBottom="37dp"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="00:00"
android:id="#+id/Timer"
android:textSize="30dp"
android:layout_marginTop="88dp"
android:layout_below="#+id/ThirtyMinMatch"
android:layout_centerHorizontal="true" />
<Button
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Stop"
android:id="#+id/StopButton"
android:layout_above="#+id/StartButton"
android:layout_centerHorizontal="true" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="30 Minutes"
android:id="#+id/ThirtyMinMatch"
android:layout_marginTop="24dp"
android:layout_below="#+id/textView"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_toLeftOf="#+id/Timer"
android:layout_toStartOf="#+id/Timer" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="1 Hour"
android:id="#+id/OneHourMinMatch"
android:layout_alignTop="#+id/ThirtyMinMatch"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:layout_toRightOf="#+id/Timer"
android:layout_toEndOf="#+id/Timer" />
</RelativeLayout>
Your code:
TextView TimerText = (TextView) findViewById(R.id.Timer);
Change this line and just delete "TextView", it's already on top.
TimerText = (TextView) findViewById(R.id.Timer);

How can store Data text view data?

In this file i have two Edit text and one textview.I want to sum two number.then result are show in text view.Then i want to store Textview data. please help.i am trying but i am fail.
Activity_main.xml//
/>
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/Edit"
/>
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/Edit1"/>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:layout_gravity="center">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/Add"
android:id="#+id/add"
android:onClick="add"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/sub"
android:id="#+id/sub"
android:onClick="sub"/>
</LinearLayout>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical"
android:layout_gravity="center"
android:paddingBottom="30dp">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/pr"
android:text="Previoues Data"
/>
</LinearLayout>
</LinearLayout>
the java file is
MainActivity.java
import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity {
EditText Edit,Edit1;
Button add, sub, pr;
TextView view;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Edit = (EditText) findViewById(R.id.Edit);
Edit1 = (EditText) findViewById(R.id.Edit1);
add = (Button) findViewById(R.id.add);
sub = (Button) findViewById(R.id.sub);
pr = (Button) findViewById(R.id.pr);
view = (TextView) findViewById(R.id.view);
Edit.setText("0");
add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int value1 = Integer.parseInt(Edit.getText().toString());
int value2 = Integer.parseInt(Edit1.getText().toString());
int result = value1 + value2;
view.setText(Integer.toString(result));
// Edit.setText(Integer.toString(result));
SharedPreferences sharedPreferences=getSharedPreferences("Mydata",Context.MODE_PRIVATE);
SharedPreferences.Editor editor=sharedPreferences.edit();
editor.putInt("value",result);
editor.commit();
}
});
sub.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int value1 = Integer.parseInt(Edit.getText().toString());
int value2 = Integer.parseInt(Edit1.getText().toString());
int result = value1 - value2;
view.setText(Integer.toString(result));
Edit.setText(Integer.toString(result));
}
});
pr.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
SharedPreferences sharedPreferences=getSharedPreferences("Mydata",Context.MODE_PRIVATE);
// int defaultValue = getResources().getInteger(R.string.saved_high_score_default);
String v=sharedPreferences.getInt("value","");
view.setText(v);
}
});
}
}
update your xml file remove onClick from your button
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/Add"
android:id="#+id/add"
/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/sub"
android:id="#+id/sub"
/>
Problem is with your getting value from sharedPreference
String v=sharedPreferences.getInt("value","");
why are you passing string as default value and your
try this String
v = Integer.toString(sharedPreferences.getInt("value",0));
in the layout you´ve got android:onClick="add" there should be a public void add(View v) to handle the event. Do the sum inside that handler.
Please, follow the documentation
http://developer.android.com/reference/android/widget/Button.html and see the :onCLick handling.

Datepicker and TimePicker dialogs take two clickes of button

So for the life of me I can not find the reason behind needing to click twice on the start date and start time for the picker dialog to open. I have searched these forums many times and they have all been mostly related to edit text fields whereas mine is a simple button but the onClickListener takes two hits. Thanks in advance.
This is my Class:
package com.shotsevolved.app
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.FragmentActivity;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.Toast;
import com.parse.FindCallback;
import com.parse.Parse;
import com.parse.ParseException;
import com.parse.ParseGeoPoint;
import com.parse.ParseObject;
import com.parse.ParseQuery;
import com.parse.SaveCallback;
import java.util.List;
public class DealCreator extends FragmentActivity {
String mUsername;
String companyName;
ParseGeoPoint location;
String title;
double mOldPrice;
double mNewPrice;
boolean isFree;
boolean isUnlimited;
String mDescription;
int mUses;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Parse.initialize(this, "Ztgl9DAaj4XPrDnS2Ro8jNHiaNnTPFCeF6V1Gm71", "26QMHWwfHmxKfwMvKemaEXH2XsFxpO5sR8Csuo9v");
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_deal_creator);
final Button create = (Button)findViewById(R.id.createButton);
final ProgressBar progress = (ProgressBar)findViewById(R.id.progressIcon);
final LinearLayout view = (LinearLayout)findViewById(R.id.linView);
final LinearLayout view1 = (LinearLayout)findViewById(R.id.linView1);
final LinearLayout main = (LinearLayout)findViewById(R.id.mainLinear);
final CheckBox freeBox = (CheckBox)findViewById(R.id.freeBox);
final EditText oldPrice = (EditText)findViewById(R.id.oldPrice);
final EditText newPrice = (EditText)findViewById(R.id.newPrice);
final CheckBox unlimited = (CheckBox)findViewById(R.id.unlimitedBox);
final EditText uses = (EditText)findViewById(R.id.uses);
final Button date = (Button)findViewById(R.id.startDate);
final Button time = (Button)findViewById(R.id.startTime);
create.setVisibility(View.INVISIBLE);
Intent intent = getIntent();
mUsername = intent.getStringExtra("key");
ParseQuery<ParseObject> query = ParseQuery.getQuery("appUsers");
query.whereEqualTo("username", mUsername);
query.findInBackground(new FindCallback<ParseObject>() {
public void done(List<ParseObject> user, ParseException e) {
if(user.size() == 1 && e == null){
int admin = user.get(0).getInt("admin");
if(admin == 2){
ParseQuery<ParseObject> query = ParseQuery.getQuery("AdminNames");
query.whereEqualTo("username", mUsername);
query.findInBackground(new FindCallback<ParseObject>() {
#Override
public void done(final List<ParseObject> user, ParseException e) {
if(user.size() == 1 && e == null){
unlimited.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if(isChecked == true){
uses.setVisibility(View.INVISIBLE);
view1.removeView(uses);
}else{
uses.setVisibility(View.VISIBLE);
view1.addView(uses);
}
}
});
freeBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if(isChecked == true){
oldPrice.setVisibility(View.INVISIBLE);
newPrice.setVisibility(View.INVISIBLE);
view.removeView(oldPrice);
view.removeView(newPrice);
}else{
oldPrice.setVisibility(View.VISIBLE);
newPrice.setVisibility(View.VISIBLE);
view.addView(oldPrice);
view.addView(newPrice);
}
}
});
date.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
showDatePickerDialog(main);
}
});
time.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
showTimePickerDialog(main);
}
});
progress.setVisibility(View.GONE);
view.removeView(progress);
create.setVisibility(View.VISIBLE);
create.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(freeBox.isChecked()){
isFree = true;
mOldPrice = 0;
mNewPrice = 0;
}else{
mOldPrice = Double.parseDouble(oldPrice.getText().toString());
mNewPrice = Double.parseDouble(newPrice.getText().toString());
isFree = false;
}
if(unlimited.isChecked()){
isUnlimited = true;
mUses = 0;
}else{
mUses = Integer.parseInt(uses.getText().toString());
isUnlimited = false;
}
//Call create deal class
deal();
}
});
}else{
Context context = getApplicationContext();
CharSequence text = "Error!!! Database Hacked!";
int duration = Toast.LENGTH_LONG;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
}
}
});
}else{
Context context = getApplicationContext();
CharSequence text = "Error!!! You are not an Admin!";
int duration = Toast.LENGTH_LONG;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
}
}else{
Context context = getApplicationContext();
CharSequence text = "Error!!! Database Hacked!";
int duration = Toast.LENGTH_LONG;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
}
}
});
}
private void deal() {
ParseObject newDeal = new ParseObject("Deals");
newDeal.put("uses", mUses);
newDeal.put("unlimitedUses", isUnlimited);
newDeal.put("description", mDescription);
newDeal.put("free", isFree);
newDeal.put("title", title);
newDeal.put("oldPrice", mOldPrice);
newDeal.put("newPrice", mNewPrice);
newDeal.put("location", location);
newDeal.put("username", mUsername);
newDeal.put("companyName", companyName);
newDeal.saveInBackground(new SaveCallback() {
#Override
public void done(ParseException e) {
Context context = getApplicationContext();
CharSequence text = "Deal Saved";
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
}
});
}
public void showTimePickerDialog(View v) {
DialogFragment newFragment = new TimePickerFragment();
newFragment.show(getSupportFragmentManager(), "timePicker");
}
public void showDatePickerDialog(View v) {
DialogFragment newFragment = new DatePickerFragment();
newFragment.show(getSupportFragmentManager(), "datePicker");
}
}
And these are my Fragments:
Date:
package com.shotsevolved.app;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.widget.DatePicker;
import java.util.Calendar;
public class DatePickerFragment extends DialogFragment
implements DatePickerDialog.OnDateSetListener {
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
// Use the current date as the default date in the picker
final Calendar c = Calendar.getInstance();
int year = c.get(Calendar.YEAR);
int month = c.get(Calendar.MONTH);
int day = c.get(Calendar.DAY_OF_MONTH);
// Create a new instance of DatePickerDialog and return it
return new DatePickerDialog(getActivity(), this, year, month, day);
}
public void onDateSet(DatePicker view, int year, int month, int day) {
// Do something with the date chosen by the user
}
}
Time:
package com.shotsevolved.app;
import android.app.Dialog;
import android.app.TimePickerDialog;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.text.format.DateFormat;
import android.widget.TimePicker;
import java.util.Calendar;
public class TimePickerFragment extends DialogFragment
implements TimePickerDialog.OnTimeSetListener {
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
// Use the current time as the default values for the picker
final Calendar c = Calendar.getInstance();
int hour = c.get(Calendar.HOUR_OF_DAY);
int minute = c.get(Calendar.MINUTE);
// Create a new instance of TimePickerDialog and return it
return new TimePickerDialog(getActivity(), this, hour, minute,
DateFormat.is24HourFormat(getActivity()));
}
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
// Do something with the time chosen by the user
}
}
And finally my XML:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:background="#1e1c1c"
android:id="#+id/root"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="#dimen/height"
android:layout_alignParentTop="true"
android:background="#color/purple"
xmlns:android="http://schemas.android.com/apk/res/android">
<LinearLayout
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<ImageButton
android:id="#+id/btn_backFromSettings"
android:layout_width="#dimen/width"
android:layout_height="fill_parent"
android:background="#drawable/ui_button_purple"
android:contentDescription="#string/desc"
android:src="#drawable/ico_left" />
<LinearLayout
android:layout_width="#dimen/divider_size"
android:layout_height="fill_parent"
android:background="#color/dark_purple" >
</LinearLayout>
<TextView
android:id="#+id/mainLogin"
android:layout_width="0dip"
android:layout_height="fill_parent"
android:layout_weight="1"
android:gravity="center"
android:tag="bold"
android:text="#string/dealCreator"
android:textColor="#color/white"
android:textSize="#dimen/tex_size_xxlarge" />
<LinearLayout
android:layout_width="#dimen/divider_size"
android:layout_height="fill_parent"
android:background="#color/dark_purple" >
</LinearLayout>
</LinearLayout>
</LinearLayout>
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent" >
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
android:id="#+id/mainLinear">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:padding="#dimen/dim_20"
android:id="#+id/linView">
<ProgressBar
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/progressIcon"
android:layout_gravity="center_horizontal" />
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/titleOfDeal"
style="#style/EditText_Purple"
android:hint="Title of Deal"
android:layout_gravity="center_horizontal" />
<EditText
android:layout_width="match_parent"
android:layout_height="200dp"
android:id="#+id/dealDescription"
android:gravity="top"
android:layout_marginTop="#dimen/dim_10"
style="#style/EditText_Purple"
android:hint="Describe company and deal"
android:layout_gravity="center_horizontal" />
<CheckBox
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Free"
android:layout_marginTop="#dimen/dim_10"
style="#style/CheckBox_Purple"
android:textColor="#color/offwhite"
android:id="#+id/freeBox" />
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/oldPrice"
android:layout_marginTop="#dimen/dim_10"
style="#style/EditText_Purple"
android:hint="Old cost of product"
android:inputType="numberDecimal"
android:layout_gravity="center_horizontal" />
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/newPrice"
android:layout_marginTop="#dimen/dim_10"
android:inputType="numberDecimal"
style="#style/EditText_Purple"
android:hint="New cost of product"
android:layout_gravity="center_horizontal" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:id="#+id/linView1"
android:paddingRight="#dimen/dim_20"
android:paddingLeft="#dimen/dim_20">
<CheckBox
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Unlimited uses"
style="#style/CheckBox_Purple"
android:textColor="#color/offwhite"
android:id="#+id/unlimitedBox" />
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/uses"
android:layout_marginTop="#dimen/dim_10"
style="#style/EditText_Purple"
android:hint="Number of uses per customer"
android:inputType="number"
android:layout_gravity="center_horizontal" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:id="#+id/linView2"
android:gravity="center_horizontal"
android:layout_marginTop="#dimen/dim_10"
android:paddingRight="#dimen/dim_20"
android:paddingLeft="#dimen/dim_20">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/startDate"
android:layout_marginTop="#dimen/dim_10"
style="#style/EditText_Purple"
android:hint="Start Date"
android:layout_marginRight="#dimen/dim_10"
android:layout_gravity="center_horizontal" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/startTime"
android:layout_marginTop="#dimen/dim_10"
style="#style/EditText_Purple"
android:hint="Start Time"
android:layout_gravity="center_horizontal" />
</LinearLayout>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical">
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:layout_marginTop="#dimen/dim_10"
android:gravity="center_horizontal">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Set expiry date"
android:layout_marginRight="#dimen/dim_10"
android:padding="#dimen/dim_10"
style="#style/Button_Purple"
android:id="#+id/dateButtonEnd"
android:layout_gravity="center_horizontal" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Set expiry time"
android:padding="#dimen/dim_10"
style="#style/Button_Purple"
android:id="#+id/timeButtonEnd"
android:layout_gravity="center_horizontal" />
</LinearLayout>
</LinearLayout>
<Button
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Create"
android:padding="#dimen/dim_10"
android:layout_marginTop="#dimen/dim_10"
android:layout_marginLeft="#dimen/dim_20"
android:layout_marginRight="#dimen/dim_20"
style="#style/Button_Purple"
android:id="#+id/createButton"
android:layout_gravity="center_horizontal" />
</LinearLayout>
</ScrollView>
</LinearLayout>
Hmm, your code looks ok. Can you try adding android:focusable="false" to your buttons. I'm curious if the problem is that you're just requesting focus the first click and the second actually initiates the click.
Also, if this doesn't help, can you put some logs in your click listener and also in the public void showTimePickerDialog(View v) { method as well ... to see if it's triggered the first click at all.
Try to add delay on button click it will avoid multi click
date.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
date.setEnabled(false);
showDatePickerDialog(main);
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
date.setEnabled(true);
}
}, 100);
}
});

Android Calculator App

I'm new to android app development. I was building a basic calculator app in android. I have no compile time errors in the code but when i'm trying to run this app it shows "Unfortunately calculator has stopped working". I have copied XML Layout and .java file one after the other.
`
<LinearLayout
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:orientation="horizontal">
<TextView
android:id="#+id/tv1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/input1"/>
<EditText
android:id="#+id/ed1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:hint="#string/input1"/>
</LinearLayout>
<LinearLayout
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:orientation="horizontal">
<TextView
android:id="#+id/tv3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/input2"/>
<EditText
android:id="#+id/ed3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="14sp"
android:hint="#string/input2"/>
</LinearLayout>
<LinearLayout
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:orientation="horizontal">
<TextView
android:id="#+id/tv2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/result"/>
<EditText
android:id="#+id/ed2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:hint="#string/result"/>
</LinearLayout>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:layout_marginTop="20dp" >
<Button
android:id="#+id/btn1"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:text="#string/add"/>
<Button
android:id="#+id/btn2"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:text="#string/sub"/>
</LinearLayout>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<Button
android:id="#+id/btn3"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:text="#string/mul"/>
<Button
android:id="#+id/btn4"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:text="#string/div"/>
</LinearLayout>
</LinearLayout>
package com.example.calculator;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
public class MainActivity extends Activity
{
public Integer int3;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final EditText input1=(EditText) findViewById(R.id.ed1);
final EditText input2=(EditText) findViewById(R.id.ed2);
final Integer int1=Integer.parseInt(input1.getText().toString());
final Integer int2=Integer.parseInt(input2.getText().toString());
Button add=(Button) findViewById(R.id.btn1);
add.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
int3=int1+int2;
}
});
Button sub=(Button) findViewById(R.id.btn2);
sub.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
int3=int1-int2;
}
});
Button mul=(Button) findViewById(R.id.btn3);
mul.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
int3=int1*int2;
}
});
Button div=(Button) findViewById(R.id.btn4);
div.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
int3=int1/int2;
}
});
final EditText result=(EditText) findViewById(R.id.ed2);
result.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
result.setText(Integer.toString(int3));
}
});
}
}'
Do not Add this on onCreate()
final Integer int1=Integer.parseInt(input1.getText().toString());
final Integer int2=Integer.parseInt(input2.getText().toString()); )
DELETE IT !!
Otherwise, You have to add this convert sentences when you create onClickListener !
you should add these line in every onClick methods like this.
add.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
Integer int1=Integer.parseInt(input1.getText().toString());
Integer int2=Integer.parseInt(input2.getText().toString());
int3=int1+int2;
}
});
Button sub=(Button) findViewById(R.id.btn2);
sub.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
Integer int1=Integer.parseInt(input1.getText().toString());
Integer int2=Integer.parseInt(input2.getText().toString());
int3=int1-int2;
}
});
There will be no error.
Additionally you should consider how about clicking without edittext value, it can cause just the error you got !Actually, you have to void assigning null(space) value to integer. Your error is putting space to integer. Edittext have space value and you are changing it to integer. Your Error !!

Categories

Resources