I am making boxing countdown timer and to set how long round supposed to last I am using two button first "+" and second "-" my time add every 5 seconds ex "5,10,15,20,25..." but I always I have to click to add 5 second. I would like to hold button and my value will add automatically what should I do?
I hope I add every important information in my question
my code from buttons and display
public void dodawanie1(View view) {
iloscrund=iloscrund+1;
display(iloscrund);
public void odejmowanie1(View view) {
if(iloscrund>1){
iloscrund=iloscrund-1;
display(iloscrund);
}
}
private void display(int numer) {
TextView displayInteger=(TextView) findViewById(R.id.textView16);
displayInteger.setText("" + numer);
}
odejmowanie means decrease value
dodawanie means increase value
If you mean to determine between click and hold, use onTouchListener to determine hold button event.
onTouchListener
I think you should use Runnable and Handler class for do it.
this link should be useful.
Android: Implement a 1 second interval timer before calling a function
activity_auto_inc.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".AutoIncActivity">
<TextView
android:id="#+id/num"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="24dp"
android:gravity="center"
android:text="1"
android:textSize="26sp"
android:textColor="#color/black"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<Button
android:id="#+id/add"
android:text="add"
android:textColor="#color/white"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.498"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/num" />
</androidx.constraintlayout.widget.ConstraintLayout>
AutoIncActivity.java
import androidx.appcompat.app.AppCompatActivity;
import android.annotation.SuppressLint;
import android.os.Bundle;
import android.os.Handler;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class AutoIncActivity extends AppCompatActivity implements
View.OnLongClickListener, View.OnTouchListener {
Button add;
TextView txt;
boolean isAddPressed = false;
Handler handler;
final int TIME_INTERVAL = 100;
final int STEP = 1;
#SuppressLint("ClickableViewAccessibility")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_auto_inc);
handler = new Handler();
add = findViewById(R.id.add);
txt = findViewById(R.id.num);
add.setOnLongClickListener(this);
add.setOnTouchListener(this);
}
#Override
public boolean onLongClick(View view) {
if (view.getId() == R.id.add) {
isAddPressed = true;
handler.postDelayed(new AutoInc(), TIME_INTERVAL);
}
return false;
}
#SuppressLint("ClickableViewAccessibility")
#Override
public boolean onTouch(View view, MotionEvent motionEvent) {
if (motionEvent.getAction() == MotionEvent.ACTION_UP ||
motionEvent.getAction() == MotionEvent.ACTION_CANCEL) {
isAddPressed = false;
}
return false;
}
private class AutoInc implements Runnable {
#Override
public void run() {
if (isAddPressed) {
txt.setText(String.valueOf(Integer.parseInt(txt.getText().toString()) +
STEP));
handler.postDelayed(this, TIME_INTERVAL);
}
}
}
}
Related
I'm creating a simple little game to practice my coding but I've stumbled into a problem. It's not game breaking but it's certainly annoying. In my game, I have a class Tappable which is what my ListView is populated with. Every time you tap on a ListView element, my OnItemClickListener just adds 1 to the amount you have of a Tappable.
Long story short, I use a custom ArrayAdapter and I have AsyncTask running on a loop with handlers in order to calculate how much money you are making. This implementation of a timed AsyncTask was done so I could put calculations on another thread and then update the UI onPostExecute. However, when I tap on a ListView element, some taps are completely ignored. This happens more severely the lower the interval is between the timed AsyncTasks.
Here is my MainActivity.java
import android.os.AsyncTask;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.Locale;
public class MainActivity extends AppCompatActivity {
TextView moneyView;
ListView tappablesView;
ArrayList<Tappable> tappables = new ArrayList<>();
TappableAdapter tappableAdapter;
double money = 0; // Total amount of money you have
double time; // Var to do checks on the amount of time to finish AsyncTask
// Here is the stuff that I use as my Timer.
int millisecondsToDelay = 30;
Handler handler = new Handler();
public class WorldUpdater extends AsyncTask<Void, Integer, Double> {
#Override
protected void onPreExecute() {
super.onPreExecute();
//This is for checking how long it takes my Tasks to complete
time = System.currentTimeMillis();
}
#Override
protected Double doInBackground(Void... params) {
// Var to hold amount to add to money
double moneyAddable = 0;
// Go through the tappables arraylist
for (int i = 0; i < tappables.size(); i++) {
Tappable t = tappables.get(i);
// increase the progress to a payout for a tappable
if (t.getAmount() > 0) {
t.updateProgress();
}
// add any money that can be collected to moneyAddable
moneyAddable += t.collectMoney();
}
// To be processed in onPostExecute
return moneyAddable;
}
#Override
protected void onPostExecute(Double m) {
super.onPostExecute(m);
// add the moneyAddable from doInBackground to the amount of money you have
money += m;
// Set the moneyView text to show how much money you have
updateMoneyView();
// Tappable progress increased, so show that in the list view
tappableAdapter.notifyDataSetChanged();
// Now we see how long the task took
time = System.currentTimeMillis() - time;
// If the task took longer than the amount I want it to delay, then say how long it took
if (time > millisecondsToDelay) {
Log.i("Timer info", "Too long: " + time);
}
handler.postDelayed(new Runnable() {
#Override
public void run() {
new WorldUpdater().execute();
}
}, (((long) (millisecondsToDelay - time)) > 0)? (long) (millisecondsToDelay - time): (long) 0);
}
}
public void updateMoneyView() {
moneyView.setText(String.format(Locale.getDefault(), "$%,.2f", money));
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
moneyView = (TextView) findViewById(R.id.Money);
tappablesView = (ListView) findViewById(R.id.TappablesView);
// The two tappables in the listview
tappables.add(new Tappable("Buy me!", .25, 1, 1500));
tappables.add(new Tappable("Buy me as well!", 1, 2.25, 1000));
tappableAdapter = new TappableAdapter(this, tappables);
tappablesView.setAdapter(tappableAdapter);
tappablesView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// On item click, increase the amount of the tappable that was clicked by 1
tappables.get(position).buyAmount(1);
}
});
updateMoneyView();
// Start my timer
handler.postDelayed(new Runnable() {
#Override
public void run() {
new WorldUpdater().execute();
}
}, millisecondsToDelay);
}
#Override
protected void onDestroy() {
super.onDestroy();
handler.removeCallbacksAndMessages(null);
}
}
Here is my Tappable.java
public class Tappable {
private String title;
private double revenue, cost, revenuePerItem, costPerItem;
private int progress, progressNeeded, progressStep, amount;
private boolean canCollect = false;
private double amountToCollect = 0;
public Tappable(String title, double r, double c, int ps) {
this.title = title;
revenuePerItem = r;
amount = 0;
revenue = revenuePerItem * amount;
costPerItem = c;
cost = costPerItem * (amount + 1);
progressNeeded = 100000;
progress = 0;
progressStep = ps;
}
public void buyAmount(int n) {
amount += n;
updateCost();
updateRevenue();
}
public void updateProgress() {
progress += progressStep;
if (progress >= progressNeeded) {
progress = 0;
amountToCollect += getRevenue();
canCollect = true;
}
}
public double collectMoney() {
double amountCollectable = 0;
if (canCollect) {
amountCollectable = amountToCollect;
amountToCollect = 0;
canCollect = false;
}
return amountCollectable;
}
public void updateCost() {
cost = costPerItem * (amount + 1);
}
public void updateRevenue() {
revenue = revenuePerItem * amount;
}
public String getTitle() {
return title;
}
public int getAmount() {
return amount;
}
public double getCost() {
return cost;
}
public int getProgress() {
return progress;
}
public int getProgressNeeded() {
return progressNeeded;
}
public double getRevenue() {
return revenue;
}
}
Here is my TappableAdapter.java
import android.app.Activity;
import android.content.res.Resources;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ProgressBar;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.Locale;
public class TappableAdapter extends BaseAdapter {
private final Activity context;
private final ArrayList<Tappable> tappables;
private final Resources res;
private final LayoutInflater inflater;
public TappableAdapter(Activity context, ArrayList<Tappable> t) {
this.context = context;
tappables = t;
res = context.getResources();
inflater = context.getLayoutInflater();
}
#Override
public int getCount() {
return tappables.size();
}
#Override
public Object getItem(int position) {
return tappables.get(position);
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
Tappable t = tappables.get(position);
View rowView = inflater.inflate(R.layout.list_item, null, true);
TextView titleView, amountView, costView, revenueView;
titleView = (TextView) rowView.findViewById(R.id.Title);
amountView = (TextView) rowView.findViewById(R.id.Amount);
costView = (TextView) rowView.findViewById(R.id.Cost);
revenueView = (TextView) rowView.findViewById(R.id.Revenue);
ProgressBar p = (ProgressBar) rowView.findViewById(R.id.progressBar);
titleView.setText(t.getTitle());
amountView.setText("Amount: " + t.getAmount());
costView.setText(String.format(Locale.getDefault(), "$%,.2f", t.getCost()));
revenueView.setText(String.format(Locale.getDefault(), "$%,.2f", t.getRevenue()));
p.setMax(t.getProgressNeeded());
p.setProgress(t.getProgress());
return rowView;
}
}
Here is my activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.jake.mypointclicker.MainActivity">
<TextView
android:id="#+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="8dp"
android:layout_marginRight="8dp"
android:layout_marginTop="8dp"
android:text="Simple Point Clicker"
android:textColor="#android:color/background_light"
android:textSize="36sp"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
android:layout_marginStart="8dp"
android:layout_marginEnd="8dp"
app:layout_constraintVertical_weight="0" />
<TextView
android:id="#+id/Money"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginRight="8dp"
android:layout_marginTop="8dp"
android:text="$123,456,789.00"
android:textColor="#android:color/holo_orange_dark"
android:textSize="30sp"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toBottomOf="#+id/textView"
android:layout_marginEnd="8dp"
app:layout_constraintVertical_weight="0" />
<Button
android:id="#+id/button"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginLeft="8dp"
android:layout_marginRight="8dp"
android:layout_marginTop="8dp"
android:text="Button"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toBottomOf="#+id/Money"
android:layout_marginStart="8dp"
android:layout_marginEnd="8dp"
app:layout_constraintVertical_weight="0" />
<LinearLayout
android:layout_width="0dp"
android:layout_height="0dp"
android:layout_marginBottom="8dp"
android:layout_marginLeft="8dp"
android:layout_marginRight="8dp"
android:layout_marginTop="8dp"
android:orientation="vertical"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toBottomOf="#+id/button"
app:layout_constraintVertical_weight="0">
<ListView
android:id="#+id/TappablesView"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
</android.support.constraint.ConstraintLayout>
Here is my list_item.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#android:color/black"
android:orientation="vertical"
android:padding="8dp">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:id="#+id/Title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:gravity="top|left"
android:text="Test Title"
android:textColor="#android:color/holo_blue_light"
android:textSize="20sp" />
<TextView
android:id="#+id/Revenue"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:gravity="top|right"
android:text="$123,456,789.00"
android:textColor="#android:color/holo_green_light"
android:textSize="20sp" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:id="#+id/Amount"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:gravity="top|left"
android:text="Amount: 123456789" />
<TextView
android:id="#+id/Cost"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:gravity="top|right"
android:text="$123,456,789.00"
android:textColor="#android:color/holo_red_light"
android:textSize="20sp" />
</LinearLayout>
<ProgressBar
android:id="#+id/progressBar"
style="?android:attr/progressBarStyleHorizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
I have tried many ways of doing my timer. I tried just using Timer with a timertask which had the same effect. Line 25 or so is where my variable for how long to delay is. Lowering that increases the amount of clicks that are ignored. Raising it has the inverse effect but makes the progress bars look less smooth. Like I said, it's not a game braking problem, but I don't understand why the onItemClick is not called sometimes when I try updating the UI frequently. Is the Listener itself on the UI thread and it is being blocked when I update the UI in my AsyncTask?
I'm new to Android developing, and I just couldn't fix this problem. When I build this app, my initial text is centered, but when I click the button or long click it, the response text is left aligned. And also, double tap, scrolling and flinging gestures don't work at all. What can be the reason?
MainActivity.java:
package com.revolise.gesturehandling;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.Button;
import android.widget.TextView;
import android.view.View;
import android.view.MotionEvent;
import android.view.GestureDetector;
import android.support.v4.view.GestureDetectorCompat;
public class MainActivity extends AppCompatActivity implements
GestureDetector.OnGestureListener,GestureDetector.OnDoubleTapListener
{
private Button button1;
private GestureDetectorCompat gestureDetect;
private TextView txt1;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button1 = (Button)findViewById(R.id.button1);
txt1 = (TextView)findViewById(R.id.textView1);
this.gestureDetect = new GestureDetectorCompat(this, this);
gestureDetect.setOnDoubleTapListener(this);
button1.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View view) {
txt1.setText("clicked to the button whooaoaaa");
}
}
);
button1.setOnLongClickListener(
new View.OnLongClickListener() {
#Override
public boolean onLongClick(View view) {
txt1.setText("long clicked to the button woww");
return false;
}
}
);
}
#Override
public boolean onSingleTapConfirmed(MotionEvent motionEvent) {
return true;
}
#Override
public boolean onDoubleTap(MotionEvent motionEvent) {
txt1.setText("Hey, you double tapped");
return true;
}
#Override
public boolean onDoubleTapEvent(MotionEvent motionEvent) {
txt1.setText("Aaaand now you're swiping.");
return true;
}
#Override
public boolean onDown(MotionEvent motionEvent) {
return true;
}
#Override
public void onShowPress(MotionEvent motionEvent) {
}
#Override
public boolean onSingleTapUp(MotionEvent motionEvent) {
return true;
}
#Override
public boolean onScroll(MotionEvent motionEvent, MotionEvent motionEvent1, float v, float v1) {
txt1.setText("Scrolling weee");
return true;
}
#Override
public void onLongPress(MotionEvent motionEvent) {
txt1.setText("Long pressed");
}
#Override
public boolean onFling(MotionEvent motionEvent, MotionEvent motionEvent1, float v, float v1) {
txt1.setText("Whoaa flinginggg");
return true;
}
}
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.revolise.gesturehandling.MainActivity">
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="160dp"
android:text="#string/initial_text"
android:textSize="30sp"
app:layout_constraintBottom_toTopOf="#+id/button1"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
android:layout_marginTop="100dp"
android:layout_marginLeft="50dp"
android:layout_marginRight="50dp" />
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/button_text"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintHorizontal_bias="0.501"
android:layout_marginBottom="200dp" />
</android.support.constraint.ConstraintLayout>
For first problem (wrong text aligned)
You should set your TextView width as match_parent and gravity to center_horizontal. So your code should be something like this:
<TextView
android:id="#+id/textView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="160dp"
android:text="#string/initial_text"
android:textSize="30sp"
android:layout_gravity="center_horizontal"
app:layout_constraintBottom_toTopOf="#+id/button1"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
android:layout_marginTop="100dp"
android:layout_marginLeft="50dp"
android:layout_marginRight="50dp" />
No matter how much I edit or change to my Java code for this assignment, it refused to properly update the value of the integer variable I've set for the result. Can someone show me what on earth I'm missing here? Below is my code:
package com.example.minicalc;
import com.example.minicalc.R;
import android.app.Activity;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.EditorInfo;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.util.Log;
public class MainActivity extends Activity implements OnEditorActionListener {
private static final String TAG = "MiniCalc";
private SharedPreferences savedValues;
private EditText editText1;
private EditText editText2;
private Button button1;
private Spinner spinner1;
private TextView answerLbl;
private int ivalue1 = 0;
private int ivalue2 = 0;
private int ianswer;
private int spinChoice;
//private String[] spinner_strings = {"+", "-", "×", "÷"};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.d(TAG, "onCreate event started");
setContentView(R.layout.activity_main);
spinner1 = (Spinner) findViewById(R.id.spinner1);
button1 = (Button) findViewById(R.id.button1);
answerLbl = (TextView) findViewById(R.id.answerTxt);
editText1 = (EditText) findViewById(R.id.editText1);
editText2 = (EditText) findViewById(R.id.editText2);
editText1.setOnEditorActionListener(this);
editText2.setOnEditorActionListener(this);
savedValues = getSharedPreferences("SavedValues", MODE_PRIVATE);
spinChoice = spinner1.getSelectedItemPosition();
button1.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
Log.d(TAG, "onClick event started");
ianswer = 0;
if (spinChoice == 0) {
ianswer = ivalue1 + ivalue2;
Log.d(TAG, "ianswer VALUE IS: " + Integer.valueOf(ianswer).toString());
} else if (spinChoice == 1) {
ianswer = ivalue1 - ivalue2;
Log.d(TAG, "ianswer VALUE IS: " + Integer.valueOf(ianswer).toString());
} else if (spinChoice == 2) {
ianswer = ivalue1 * ivalue2;
Log.d(TAG, "ianswer VALUE IS: " + Integer.valueOf(ianswer).toString());
} else if (spinChoice == 3) {
ianswer = ivalue1 / ivalue2;
Log.d(TAG, "ianswer VALUE IS: " + Integer.valueOf(ianswer).toString());
}
answerLbl.setText(Integer.toString(ianswer));
//answerLbl.setText(""+ianswer);
Log.d(TAG, "answerLbl TEXT IS: " + answerLbl.getText());
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
Log.d(TAG, "onEditorAction event started");
if (actionId == EditorInfo.IME_ACTION_DONE || actionId == EditorInfo.IME_ACTION_UNSPECIFIED) {
ivalue1 = Integer.parseInt(editText1.getText().toString());
ivalue2 = Integer.parseInt(editText2.getText().toString());
}
return false;
}
#Override
public void onPause() {
Log.d(TAG, "onPause event started");
Editor editor = savedValues.edit();
editor.putString("value1", editText1.getText().toString());
editor.putString("value2", editText2.getText().toString());
editor.commit();
super.onPause();
}
#Override
public void onResume() {
super.onResume();
Log.d(TAG, "onResume event started");
editText1.setText(savedValues.getString("value1", ""));
editText2.setText(savedValues.getString("value2", ""));
}
}
Here is my layout XML, activity_main.xml:
<?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.minicalc.MainActivity" >
<TextView
android:id="#+id/valLbl1"
android:labelFor="#+id/editText1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:layout_marginStart="30dp"
android:layout_marginTop="40dp"
android:text="#string/valueLbl1" />
<TextView
android:id="#+id/valLbl2"
android:labelFor="#+id/editText2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignStart="#+id/valLbl1"
android:layout_below="#+id/editText1"
android:layout_marginTop="24dp"
android:text="#string/valueLbl2" />
<EditText
android:id="#+id/editText1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignStart="#+id/valLbl1"
android:layout_below="#+id/valLbl1"
android:layout_marginTop="20dp"
android:ems="5"
android:inputType="number">
<requestFocus />
</EditText>
<EditText
android:id="#+id/editText2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignStart="#+id/valLbl2"
android:layout_below="#+id/valLbl2"
android:layout_marginTop="16dp"
android:ems="5"
android:inputType="number" />
<TextView
android:id="#+id/answerTxt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignTop="#+id/answerLblTxt"
android:layout_centerHorizontal="true"
android:ems="7"/>
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/editText2"
android:layout_centerHorizontal="true"
android:layout_marginTop="18dp"
android:text="#string/submit" />
<TextView
android:id="#+id/answerLblTxt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignStart="#+id/editText2"
android:layout_below="#+id/button1"
android:layout_marginTop="16dp"
android:text="#string/answerLbl" />
<Spinner
android:id="#+id/spinner1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignTop="#+id/valLbl2"
android:layout_marginStart="28dp"
android:layout_toEndOf="#+id/editText2"
android:entries="#array/spinner_strings" />
</RelativeLayout>
Now, the app runs fine, the LogCat messages show up fine...except when I put them in the onClickListener. So yes, I've sorta identified WHERE the problem is, I just don't know WHAT the problem is. I'd show a screen shot of the error, but this is my first time posting. In any case, the phone I'm running the app on is a Samsung Galaxy Note 3, running Android 4.4.4. Can anyone help me?
Your spinners getSelectedItemPoisition() method is only called once in your onCreate() method and it is not called every time you click on the button, resulting in the value never being updated.
button1.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
spinChoice = spinner1.getSelectedItemPosition();
...
}
This line of code needs to be added in the onClick() method causing the new value to be read on button click.
i have coded simple calculator with two input boxes and once total button , What i have to is show a circular Progressbar for 3 seconds before i show result after pressing Total button ,here is what i have done .
package com.example.calculator;
import java.util.Timer;
import java.util.TimerTask;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends Activity
{
EditText t1;
EditText t2;
TextView tv;
TextView tv1;
Timer singleTask;
int Interval = 3000;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
t1= (EditText)findViewById(R.id.editText1);
t2= (EditText)findViewById(R.id.editText2);
tv= (TextView)findViewById(R.id.textView1);
tv1= (TextView)findViewById(R.id.textView2);
singleTask= new Timer();
}
public void loadprogressbar()
{
singleTask.schedule(new TimerTask() {
#Override
public void run() {
// have to add code for progress bar but right now just caption text added
tv1.setText("This is for 3 seconds only");
}
}, 1000);
}
#Override
protected void onDestroy(){
super.onDestroy();
if(singleTask != null)
{
singleTask.cancel();
}
}
public void Clicked(View v)
{ int total;
if(v.getId()==R.id.button1)
{
int v1 = Integer.parseInt(t1.getText().toString());
int v2 = Integer.parseInt(t2.getText().toString());
total = v1 + v2;
loadprogressbar();
tv.setText(total+"");
tv.setVisibility(1);
}
else if (v.getId()==R.id.button2)
{
t1.setText("");
t2.setText("");
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
Xml File is
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context=".MainActivity" >
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/hello_world"
android:visibility="invisible"/>
<TextView
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/hello_world"
></TextView>
<EditText
android:id="#+id/editText1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/textView1"
android:layout_below="#+id/textView1"
android:layout_marginTop="32dp"
android:ems="10"
android:inputType="number" >
<requestFocus />
</EditText>
<EditText
android:id="#+id/editText2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/editText1"
android:layout_below="#+id/editText1"
android:layout_marginTop="21dp"
android:ems="10"
android:inputType="number" />
<Button
android:id="#+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/button1"
android:layout_alignBottom="#+id/button1"
android:layout_alignRight="#+id/editText2"
android:text="Clear"
android:onClick="Clicked"
/>
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="#+id/editText2"
android:layout_marginTop="35dp"
android:text="Total"
android:onClick="Clicked"
/>
</RelativeLayout>
Problem is that i am not getting any result against Timer code ? according to my thinking it should show text for 3 seconds and then display text . My logic could be wrong as well please guide me ..
If I understand correctly what you want to do is to show a ProgressDialog to simulate that your calculator is doing some calculation. The Timer class is not what you want to use. Basically, you want to wait for 3 seconds (during that time the ProgressDialog will be visible), and then update the UI by setting the TextView with the result. As you might know, you cannot modify the UI thread from a background Thread directly, and you should not make the UI thread sleep. Hence, AsyncTask is your best bet. Below is a sample code to allow you to show a ProgressDialog for 3 seconds. You should update your TextView on the OnPostExecute method since it runs on the UI thread.
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.widget.RelativeLayout;
import android.widget.Toast;
public class MainActivity extends Activity{
ProgressDialog pd;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
pd = new ProgressDialog(this);
pd.setTitle(getString("Title"));
pd.setIndeterminate(true);
pd.show();
new MyAsycnTask().execute();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
private class MyAsycnTask extends AsyncTask <Void,Void,Void> {
#Override
protected Void doInBackground(Void... voids) {
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
pd.hide();
}
}
}
Go with E.Odebugg answer.
If you however need to display a TextView for 3 seconds and then hide, here's how to do it without using TimerTask.
textView.postDelayed(new Runnable() {
#Override
public void run() {
textView.setVisibility(View.GONE);
}
}, 3000);
The TextView is displayed by default, and after 3 seconds it's hidden. Also, note that postDelayed() is used, which will run the Runnable on UI thread.
So I think your code is wrong in loadprogressbar(). It should be:
public void loadprogressbar()
{
// have to add code for progress bar but right now just caption text added
tv1.setText("This is for 3 seconds only");
singleTask.schedule(new TimerTask() {
#Override
public void run() {
runOnUiThread(new Runnable() {
#Override
public void run() {
///hide the progressbar here...
}
});
}
}, Interval);
}
And if I were you I would change the name of your function "Clicked", because it can be a reserved word (the color also indicates it)...
O.K i have looked around this site and others and i see something similar to what i am wanting but yet it isn't what i am wanting...let me explain
i am learning to build an android app using eclipse that has a media player linked to my shoutcast server i am running, so far the apps works great but it doesn't have an icon on the top were the notification area is and when i go to a different app (a game) to play while leaving the music playing it minimizes the app .. thats fine but when i reopen the app it doesnt stop the mediaplayer infact if i play the player i will have 2 players running i will then have to force stop it using the task manager,, i know this can be done as i have apps on my phone that has icons and it will do what i am wanting
when i searched this site i found a link to youtube that has soemthing similar to what i am wanting
http://www.youtube.com/watch?v=e74z0_Z5QWI&feature=relmfu the code that is shown is as followed
import android.app.Activity;
public class StatusBar extends Activity implements OnclickListener{
NotificationManager nm;
#Override
Protected void onCreate(bundle savedInstance){
//TODO Auto-generated method Stub
super.oncreate(savedInstaceState);
setContentView(R.layout.statusbar);
Button stat = (Button)findViewById(R.id.bStatusBar);
stat.setOnClickListener(this);
nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
}
public void onClick(View v){
//TODO Auto-generated method Stub
Intent intent = new Intent(this, StatusBar.class);
PendingIntent pi = PendingIntent.getActivity(this, 0, intent, 0);
}
i have add this code to my MainActivity.java but it spits several errors to me that i have tried to fix using quickfix here is the script i currently have in my MainActivity.java file
package com.myapp.mytapp;
import android.app.Activity;
import android.content.Intent;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnBufferingUpdateListener;
import android.media.MediaPlayer.OnCompletionListener;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.widget.Button;
import android.widget.SeekBar;
public class MainActivity extends Activity implements OnClickListener, OnTouchListener, OnCompletionListener, OnBufferingUpdateListener{
private Button btn_play,
btn_pause,
btn_stop;
private SeekBar seekBar;
private MediaPlayer mediaPlayer;
private int lengthOfAudio;
private final String URL = "http://link to url:8002";
private final Handler handler = new Handler();
private final Runnable r = new Runnable() {
#Override
public void run() {
updateSeekProgress();
}
};
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
init();
}
private void init() {
btn_play = (Button)findViewById(R.id.btn_play);
btn_play.setOnClickListener(this);
btn_pause = (Button)findViewById(R.id.btn_pause);
btn_pause.setOnClickListener(this);
btn_pause.setEnabled(true);
btn_stop = (Button)findViewById(R.id.btn_stop);
btn_stop.setOnClickListener(this);
btn_stop.setEnabled(true);
seekBar = (SeekBar)findViewById(R.id.seekBar);
seekBar.setOnTouchListener(this);
mediaPlayer = new MediaPlayer();
mediaPlayer.setOnBufferingUpdateListener(this);
mediaPlayer.setOnCompletionListener(this);
}
#Override
public void onBufferingUpdate(MediaPlayer mediaPlayer, int percent) {
seekBar.setSecondaryProgress(percent);
}
#Override
public void onCompletion(MediaPlayer mp) {
btn_play.setEnabled(true);
btn_pause.setEnabled(false);
btn_stop.setEnabled(false);
}
#Override
public boolean onTouch(View v, MotionEvent event) {
if (mediaPlayer.isPlaying()) {
SeekBar tmpSeekBar = (SeekBar)v;
mediaPlayer.seekTo((lengthOfAudio / 100) * tmpSeekBar.getProgress() );
}
return false;
}
#Override
public void onClick(View view) {
try {
mediaPlayer.setDataSource(URL);
mediaPlayer.prepare();
lengthOfAudio = mediaPlayer.getDuration();
} catch (Exception e) {
//Log.e("Error", e.getMessage());
}
switch (view.getId()) {
case R.id.btn_play:
playAudio();
break;
case R.id.btn_pause:
pauseAudio();
break;
case R.id.btn_stop:
stopAudio();
break;
default:
break;
}
updateSeekProgress();
}
private void updateSeekProgress() {
if (mediaPlayer.isPlaying()) {
seekBar.setProgress((int)(((float)mediaPlayer.getCurrentPosition() / lengthOfAudio) * 100));
handler.postDelayed(r, 1000);
}
}
private void stopAudio() {
mediaPlayer.stop();
btn_play.setEnabled(true);
btn_pause.setEnabled(true);
btn_stop.setEnabled(true);
seekBar.setProgress(0);
}
private void pauseAudio() {
mediaPlayer.pause();
btn_play.setEnabled(true);
btn_pause.setEnabled(true);
}
private void playAudio() {
mediaPlayer.start();
btn_play.setEnabled(true);
btn_pause.setEnabled(true);
btn_stop.setEnabled(true);
}
public void homepage (View view) {
goToUrl ( "http://myhomepage.com/");
}
private void goToUrl (String url) {
Uri uriUrl = Uri.parse(url);
Intent launchBrowser = new Intent(Intent.ACTION_VIEW, uriUrl);
startActivity(launchBrowser);
}
}
here is what is in my activity_main.xml file
<?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:background="#color/black"
android:icon="#drawable/ic_launcher"
android:orientation="vertical"
startForeground()>
<ImageView
android:id="#+id/imageView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:src="#drawable/logo" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<TableRow
android:id="#+id/tableRow1"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<Button
android:id="#+id/homepage"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:autoLink="web"
android:clickable="true"
android:cursorVisible="true"
android:linksClickable="true"
android:onClick="homepage"
android:text="Home Page" />
</TableRow>
</LinearLayout>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="5dp"
android:gravity="center_horizontal"
android:orientation="horizontal" >
<Button
android:id="#+id/btn_play"
android:layout_width="90dp"
android:layout_height="wrap_content"
android:background="#drawable/play"
android:clickable="true"
android:cursorVisible="true"
android:src="#drawable/play" >
</Button>
<Button
android:id="#+id/btn_pause"
android:layout_width="90dp"
android:layout_height="wrap_content"
android:background="#drawable/pause"
android:clickable="true"
android:cursorVisible="true"
android:src="#drawable/pause" >
</Button>
<Button
android:id="#+id/btn_stop"
android:layout_width="90dp"
android:layout_height="wrap_content"
android:background="#drawable/stop"
android:clickable="true"
android:cursorVisible="true"
android:src="#drawable/stop" >
</Button>
</LinearLayout>
<SeekBar
android:id="#+id/seekBar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="3dp" >
</SeekBar>
<ImageView
android:id="#+id/imageView3"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:src="#drawable/scast" />
<TextView
android:id="#+id/Textview"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:gravity="center"
android:hint="#string/version" >
</TextView>
</LinearLayout>
can someone tell me what i did wrong or can rewrite what i have and still keep everything working
Thanks in advance
Rob