value of local variable not used? - java

I am new to android app development, so this may be easy for you. I have searched this forum before I posted so please take a look before marking it as duplicate. I am not declaring static variables in the updatestandard method. Here is my program:
package com.example.new1;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.text.TextWatcher;
import android.text.Editable;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
public class MainActivity extends ActionBarActivity {
private static final String BILL_TOTAL = "BILL_TOTAL";
private static final String CUSTOM_PERCENT = "CUSTOM_PERCENT";
private double currentBillTotal;
private int currentCustomPercent;
private EditText tip10EditText;
private EditText total10EditText;
private EditText tip15EditText;
private EditText total15EditText;
private EditText billEditText;
private EditText tip20EditText;
private EditText total20EditText;
private TextView customTipTextView;
private EditText tipCustomEditText;
private EditText totalCustomEditText;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if( savedInstanceState ==null)
{
currentBillTotal=0.0;
currentCustomPercent=0;
}
else
{
currentBillTotal=savedInstanceState.getDouble(BILL_TOTAL);
currentCustomPercent=savedInstanceState.getInt(CUSTOM_PERCENT);
}
tip10EditText=(EditText) findViewById(R.id.tip10editText);
tip15EditText=(EditText) findViewById(R.id.tip15editText);
tip20EditText=(EditText) findViewById(R.id.tip20editText);
total10EditText=(EditText) findViewById(R.id.totaltenEditText);
total20EditText=(EditText) findViewById(R.id.totaltwentyEditText);
total15EditText=(EditText) findViewById(R.id.totalfifteenEditText);
tipCustomEditText=(EditText) findViewById(R.id.tipcustomeditText);
totalCustomEditText=(EditText) findViewById(R.id.totaltcustomeditText);
billEditText=(EditText) findViewById(R.id.billeditText1);
billEditText.addTextChangedListener(billEditTextWatcher);
SeekBar customSeekBar = (SeekBar) findViewById(R.id.customSeekBar);
customSeekBar.setOnSeekBarChangeListener(customSeekBarListner);
customTipTextView = (TextView) findViewById(R.id.customTipTextView);
}
private void updateStandard()
{
double tenPercentTip= currentBillTotal * .1;
double tenPercentTotal = currentBillTotal+tenPercentTip;
total10EditText.setText(String.format("%.02f,tenPercentTotal"));
double fifteenPercentTip= currentBillTotal * .15;
double fifteenPercentTotal= currentBillTotal+fifteenPercentTip;
double twentyPercentTip= currentBillTotal * .20;
double twentyPercentTotal= currentBillTotal+twentyPercentTip;
tip10EditText.setText(String.format("%.02f",tenPercentTip));
tip15EditText.setText(String.format("%.02f",fifteenPercentTip));
total15EditText.setText(String.format("%.02f,fifteenPercentTotal"));
tip20EditText.setText(String.format("%.02f",twentyPercentTip));
total20EditText.setText(String.format("%.02f,twentyPercentTotal"));
}
private void updateCustom()
{
customTipTextView.setText(currentCustomPercent+"%");
double customTipAmount=currentBillTotal*currentCustomPercent*.01;
tipCustomEditText.setText(String.format("%.02f",customTipAmount));
double customTotalAmount=currentBillTotal+customTipAmount;
totalCustomEditText.setText(String.format("%.02f",customTotalAmount));
}
#Override
protected void onSaveInstanceState(Bundle outState)
{
super.onSaveInstanceState(outState);
outState.putDouble(BILL_TOTAL, currentBillTotal);
outState.putInt(CUSTOM_PERCENT, currentCustomPercent);
}
private OnSeekBarChangeListener customSeekBarListner=new OnSeekBarChangeListener()
{
#Override
public void onProgressChanged(SeekBar seekBar, int progress,
boolean fromUser) {
currentCustomPercent=seekBar.getProgress();
updateCustom();
// TODO Auto-generated method stub1
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
};
private TextWatcher billEditTextWatcher=new TextWatcher()
{
#Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
try
{
currentBillTotal=Double.parseDouble(s.toString());
}
catch(NumberFormatException e)
{
currentBillTotal=0.0;
}
updateStandard();
updateCustom();
// TODO Auto-generated method stub
}
#Override
public void onTextChanged(CharSequence s, int start, int before,
int count) {
// TODO Auto-generated method stub
}
#Override
public void afterTextChanged(Editable s) {
// TODO Auto-generated method stub
}
};
#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);
}
}
so in eclipse it says in the update standard lines that the variables are not used the tenPercentTotal,fifteenPercentTotal and twentyPercentTotal idk why it says that they are used in the next lines below it pls help this exact program worked before i right clicked my project and selected export android app option that messed up many things idk what happened.

You're spelling their names out in the formatting strings instead of actually using them as arguments in the String#format() method calls.

Eclipse is not wrong (maybe refresh project + Validate if hes outdated).
Assigning values to variable does not count as usage.

Related

Android thread test does not work

Hi I'm beginner with android development and I have a problem with my following test code:
Main Activity:
package com.test.thread;
import java.util.concurrent.ExecutionException;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends Activity {
TextView txt = null;
Button btStart = null;
Button btStop = null;
TestClass test = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
txt = (TextView)findViewById(R.id.txtView);
btStart = (Button)findViewById(R.id.bt_start);
btStop = (Button)findViewById(R.id.bt_stop);
test = new TestClass(this, txt);
btStop.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
test.Stop();
}
});
btStart.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Thread t = new Thread(){
#Override
public void run() {
// TODO Auto-generated method stub
try{
synchronized (this) {
wait(50);
runOnUiThread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
while(test.isStop()){
try {
wait(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
test.DoSomeThing();
}
}
});
}
}catch( InterruptedException e)
{
e.printStackTrace();
}
}
};
t.start();
}
});
}
#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);
}
}
TestCLas.java:
package com.tutorial.sample;
import android.content.Context;
import android.widget.TextView;
import android.widget.Toast;
public class TestClass{
private boolean stopIter = false;
private TextView txtV = null;
private int count = 0;
private Context ctx = null;
public TestClass(Context ct, TextView tv) {
// TODO Auto-generated constructor stub
txtV = tv;
stopIter = false;
count = 0;
ctx = ct;
}
public boolean isStop() { return stopIter; }
public void Stop()
{
Toast.makeText(ctx, "stop the test" , Toast.LENGTH_LONG).show();
count = 0;
txtV.setText(Integer.toString(count));
stopIter = true;
}
public void DoSomeThing(){
txtV.setText(Integer.toString(count));
}
}
I want to manage my activity's viewer with threads. I launch a thread in order to modify TextView's text (each sec) when the start button is clicked and stop it when stop button is clicked. But it does not work, it crashes without any exception. Can someone help me please?
wait(1000);
This should NEVER be done on the UI thread.
The UI thread is the one that update the GUI, and communicates with Android to say everything is working as expected. When you have a thread delay on the UI thread, the message to and from the android system get held back, and you app appears to the system as if it has crashed.

Person Detail App

I am quite new to programming Android (7 months), and I am having a problem with creating an app.
What I am trying to do is create a "Person Detail" test app for my own Android learning, by having EditText on the Main Activity with TextViews next to them (displaying default values at first), open up another activity called EditData (with a button on the main) which displays the values the user entered into the EditText (via Parcelable), return back to the Main Activty (via another button) and have those entered values displayed in the TextViews next to the EditText (upon a "Update Info" button click) instead of the default ones. I have managed to get everything working right except for displaying the changed values. Everything checks out, no errors in LogCat, but when the user / I clicks the update button, what shows are the default values. Can someone help me?
Here is my Main Activity code:
import android.app.Activity;
import android.content.Intent;
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;
public class MainActivity extends Activity {
final Person firstPerson = new Person();
TextView displayName, displayAge, displayHeight, displayWeight;
EditText editName, editAge, editHeight, editWeight;
Button editActivity, update;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_activity);
instantiateUi();
editActivity.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
firstPerson.setPersonName(editName.getText().toString());
firstPerson.setPersonAge(Integer.parseInt(editAge.getText().toString()));
firstPerson.setPersonHeight(Integer.parseInt(editHeight.getText().toString()));
firstPerson.setPersonWeight(Integer.parseInt(editWeight.getText().toString()));
Intent editIntent = new Intent(MainActivity.this, EditData.class);
editIntent.putExtra("First_Person_Data", firstPerson);
MainActivity.this.startActivity(editIntent);
}
});
update.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
displayName.setText(firstPerson.getPersonName());
displayAge.setText(String.valueOf(firstPerson.getPersonAge()));
// String.valueOf is needed to set int for TextViews
displayHeight.setText(String.valueOf(firstPerson.getPersonHeight()));
displayWeight.setText(String.valueOf(firstPerson.getPersonWeight()));
}
});
}
private void instantiateUi() {
editName = (EditText)findViewById(R.id.edit_name);
editAge = (EditText)findViewById(R.id.edit_age);
editHeight = (EditText)findViewById(R.id.edit_height);
editWeight = (EditText)findViewById(R.id.edit_weight);
displayName = (TextView)findViewById(R.id.display_name);
displayAge = (TextView)findViewById(R.id.display_age);
displayHeight = (TextView)findViewById(R.id.display_height);
displayWeight = (TextView)findViewById(R.id.display_weight);
editActivity = (Button)findViewById(R.id.edit_activity);
update = (Button)findViewById(R.id.update_info);
}
#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, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_settings:
break;
default:
return super.onOptionsItemSelected(item);
}
return true;
}
}
My EditData activity code:
import android.content.Intent;
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.TextView;
public class EditData extends ActionBarActivity {
TextView changedName, changedAge, changedHeight, changedWeight;
Button MainActivity;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.edit_activity);
Person incomingObject = getIntent().getParcelableExtra("First_Person_Data");
instantiateUi();
changedName.setText(incomingObject.getPersonName());
changedAge.setText(String.valueOf(incomingObject.getPersonAge()));
changedHeight.setText(String.valueOf(incomingObject.getPersonHeight()));
changedWeight.setText(String.valueOf(incomingObject.getPersonWeight()));
MainActivity.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent EditActivity = new Intent(EditData.this, MainActivity.class);
EditData.this.startActivity(EditActivity);
}
});
}
private void instantiateUi() {
changedName = (TextView)findViewById(R.id.changed_name);
changedAge = (TextView)findViewById(R.id.changed_age);
changedHeight = (TextView)findViewById(R.id.changed_height);
changedWeight = (TextView)findViewById(R.id.changed_weight);
MainActivity = (Button)findViewById(R.id.main_activity);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.edit_data_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.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
And my Parcelable class used for transferring data values:
import android.os.Parcel;
import android.os.Parcelable;
public class Person implements Parcelable{
String personName;
int personAge, personHeight, personWeight;
public Person(){
personName = "No Name!";
personAge = 0;
personHeight = 0;
personWeight = 0;
}
public Person(String pName, int pAge, int pHeight, int pWeight) {
personName = pName;
personAge = pAge;
personHeight = pHeight;
personWeight = pWeight;
}
public Person(Parcel in) {
personName = in.readString();
personAge = in.readInt();
personHeight = in.readInt();
personWeight = in.readInt();
}
public String getPersonName() {
return personName;
}
public void setPersonName(String personName) {
this.personName = personName;
}
public int getPersonAge() {
return personAge;
}
public void setPersonAge(int personAge) {
this.personAge = personAge;
}
public int getPersonHeight() {
return personHeight;
}
public void setPersonHeight(int personHeight) {
this.personHeight = personHeight;
}
public int getPersonWeight() {
return personWeight;
}
public void setPersonWeight(int personWeight) {
this.personWeight = personWeight;
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(personName);
dest.writeInt(personAge);
dest.writeInt(personHeight);
dest.writeInt(personWeight);
}
public static final Parcelable.Creator<Person> CREATOR =
new Parcelable.Creator<Person>() {
#Override
public Person createFromParcel(Parcel in) {
return new Person(in);
}
#Override
public Person[] newArray(int size) {
return new Person[size];
}
};
}
Sorry if there are problems, this is my first question and I would very much appreciate what help you can give to a noob C0D3R :P
You shouldn't start variable names with capital letters. Your button MainActivity is very confusing. Better name it something like btMainActivity or something like that.
It think your problem is, that you forget to put an extra to your MainActivity, like you did when starting EditData:
editActivity.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
firstPerson.setPersonName(editName.getText().toString());
firstPerson.setPersonAge(Integer.parseInt(editAge.getText().toString()));
firstPerson.setPersonHeight(Integer.parseInt(editHeight.getText().toString()));
firstPerson.setPersonWeight(Integer.parseInt(editWeight.getText().toString()));
Intent editIntent = new Intent(MainActivity.this, EditData.class);
editIntent.putExtra("First_Person_Data", firstPerson);
MainActivity.this.startActivity(editIntent);
}
});
MainActivity.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent EditActivity = new Intent(EditData.this, MainActivity.class);
// put your extra here
EditData.this.startActivity(EditActivity);
}
});
For what you want, you could also use startActivityForResult. Take a look at it! You should also check out AndroidAnnotations. It can safe you a lot of code and time. I can't imagine making an Android app without it anymore.

Attach onDoubleTapListener to a text view

Okay, so I've been stuck for a couple of days now working with gestures within my app. All it is, is a basic stopWatch application and also a count down application it uses swipeable views to swap between the 2 different activities.
My problem is in my first fragment for the stopWatch part of the app I use a runnable to create and start the timer which works fine and it is currently set up so if the user taps on the timer Text view, it'll start the runnable and the timer will begin counting up. However the way I have set it up it can only accept one input method which is a single tap. This is where the gestures come in. I want to be able to single click to start the timer, double tap to pause the timer and a long press to stop and clear the timer Text view.
I've tried attaching a gesture detector to just the TextView but anything I try doesn't seem to work, I believe I can set the fragment up so if I were to click anywhere on the screen it would do what I wish but I don't want it to work like that. I want it to only work when the user clicks the timer Text view. I've come to a point where I thought I could get it to work, but that involves putting an onDoubleTapListener to my TextView, but for some reason I cannot do that, so does anyone have a way to do that or a way for my code to work?
Sorry for the long explanation but I figure the more information there is on what I want, the easier it would be for someone to help :)
Below is my code, I know it doesn't look too organised (Thats something I'm trying to work on) but hopefully you can see where I'm going wrong. Thanks!
(Also I know some of the views aren't used at all at the moment purely because I'm trying to get it working one step at a time :P also the part of commented out code, is the current way I'm running the timer I thought I'd leave it in here in case someone is wondering how I am currently starting the timer.)
package com.leccles.swipetabs;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.support.v4.view.GestureDetectorCompat;
import android.view.GestureDetector;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
/**
* A simple {#link android.support.v4.app.Fragment} subclass.
*
*/
public class FragmentA extends Fragment implements
GestureDetector.OnGestureListener, GestureDetector.OnDoubleTapListener {
Button lapButton;
TextView timerText;
ListView lapListView;
TextView mMilliTextView;
String milliText;
long startTime = 0;
long timeInMilliSeconds = 0;
GestureDetectorCompat gDetector;
Handler timerHandler = new Handler();
Runnable timerRunnable = new Runnable() {
#Override
public void run() {
long millis = System.currentTimeMillis() - startTime;
int seconds = (int) (millis / 1000);
int minutes = seconds / 60;
seconds = seconds % 60;
timerText.setText(String.format("%d:%02d", minutes, seconds));
timerHandler.postDelayed(this, 500);
}
};
public FragmentA() {
// Required empty public constructor
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
// Inflate the layout for this fragment
mMilliTextView = (TextView) getView().findViewById(R.id.milliTextView);
lapButton = (Button) getView().findViewById(R.id.lapButton);
timerText = (TextView) getView().findViewById(R.id.timerText);
lapListView = (ListView) getView().findViewById(R.id.lapListView);
this.gDetector = new GestureDetectorCompat(getActivity(), this);
timerText.setOnDoubleTapListener(this);
/*
* timerText.setOnClickListener(new View.OnClickListener() {
*
* #Override public void onClick(View v) { TextView timerText =
* (TextView) v; if (timerText.getText().equals(
* getView().findViewById(R.string.stopWatchTime))) {
* timerHandler.removeCallbacks(timerRunnable);
*
* } else {
*
* startTime = System.currentTimeMillis();
* timerHandler.postDelayed(timerRunnable, 0);
*
* }
*
* }
*
* });
*/
}
#Override
public boolean onSingleTapConfirmed(MotionEvent e) {
// TODO Auto-generated method stub
return true;
}
#Override
public boolean onDoubleTap(MotionEvent e) {
// TODO Auto-generated method stub
return true;
}
#Override
public boolean onDoubleTapEvent(MotionEvent e) {
// TODO Auto-generated method stub
return true;
}
#Override
public boolean onDown(MotionEvent e) {
// TODO Auto-generated method stub
return true;
}
#Override
public void onShowPress(MotionEvent e) {
// TODO Auto-generated method stub
}
#Override
public boolean onSingleTapUp(MotionEvent e) {
// TODO Auto-generated method stub
return true;
}
#Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX,
float distanceY) {
// TODO Auto-generated method stub
return true;
}
#Override
public void onLongPress(MotionEvent e) {
// TODO Auto-generated method stub
}
#Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,
float velocityY) {
// TODO Auto-generated method stub
return true;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
return inflater.inflate(R.layout.fragment_a, container, false);
}
}
I figured out the problem it was so simple. I didn't need to use an onDoubleTapListener. A simple onTouchListener worked(I had previously tried and failed at using this) I was trying to use it wrong. I didn't put the Gesture Detector into the on touch so it wouldn't ever work. Here is the working code below with the onTouchListener. I also didn't change the boolean in onTouch to true to state that the touch had been handled.
package com.leccles.swipetabs;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.support.v4.view.GestureDetectorCompat;
import android.view.GestureDetector;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
/**
* A simple {#link android.support.v4.app.Fragment} subclass.
*
*/
public class FragmentA extends Fragment implements
GestureDetector.OnGestureListener, GestureDetector.OnDoubleTapListener {
Button lapButton;
TextView timerText;
ListView lapListView;
TextView mMilliTextView;
String milliText;
long startTime = 0;
String sPauseTime;
long iPauseTime;
long timeInMilliSeconds = 0;
GestureDetectorCompat gDetector;
Handler timerHandler = new Handler();
Runnable pauseRunnable = new Runnable() {
#Override
public void run() {
long millis = System.currentTimeMillis() + startTime;
int seconds = (int) (millis / 1000);
int minutes = seconds / 60;
seconds = seconds % 60;
timerText.setText(String.format("%02d:%02d", minutes, seconds));
timerHandler.postDelayed(this, 500);
}
};
Runnable timerRunnable = new Runnable() {
#Override
public void run() {
long millis = System.currentTimeMillis() - startTime;
int seconds = (int) (millis / 1000);
int minutes = seconds / 60;
seconds = seconds % 60;
timerText.setText(String.format("%02d:%02d", minutes, seconds));
timerHandler.postDelayed(this, 500);
}
};
public FragmentA() {
// Required empty public constructor
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
// Inflate the layout for this fragment
mMilliTextView = (TextView) getView().findViewById(R.id.milliTextView);
lapButton = (Button) getView().findViewById(R.id.lapButton);
timerText = (TextView) getView().findViewById(R.id.timerText);
lapListView = (ListView) getView().findViewById(R.id.lapListView);
this.gDetector = new GestureDetectorCompat(getActivity(), this);
timerText.setOnTouchListener(new OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
gDetector.onTouchEvent(event);
return true;
}
});
/*
* timerText.setOnClickListener(new View.OnClickListener() {
*
* #Override public void onClick(View v) { TextView timerText =
* (TextView) v; if (timerText.getText().equals(
* getView().findViewById(R.string.stopWatchTime))) {
* timerHandler.removeCallbacks(timerRunnable);
*
* } else {
*
* startTime = System.currentTimeMillis();
* timerHandler.postDelayed(timerRunnable, 0);
*
* }
*
* }
*
* });
*/
}
#Override
public boolean onSingleTapConfirmed(MotionEvent e) {
sPauseTime = timerText.getText().toString();
startTime = System.currentTimeMillis();
timerHandler.postDelayed(timerRunnable, 0);
return true;
}
#Override
public boolean onDoubleTap(MotionEvent e) {
sPauseTime = timerText.getText().toString();
timerHandler.removeCallbacks(timerRunnable);
return true;
}
#Override
public boolean onDoubleTapEvent(MotionEvent e) {
// TODO Auto-generated method stub
return true;
}
#Override
public boolean onDown(MotionEvent e) {
// TODO Auto-generated method stub
return true;
}
#Override
public void onShowPress(MotionEvent e) {
// TODO Auto-generated method stub
}
#Override
public boolean onSingleTapUp(MotionEvent e) {
// TODO Auto-generated method stub
return true;
}
#Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX,
float distanceY) {
// TODO Auto-generated method stub
return true;
}
#Override
public void onLongPress(MotionEvent e) {
timerHandler.removeCallbacks(timerRunnable);
timerText.setText("00:00");
}
#Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,
float velocityY) {
// TODO Auto-generated method stub
return true;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
return inflater.inflate(R.layout.fragment_a, container, false);
}
}

Get input from edittext using an anonymous class, android

Long story short I an trying to make an app to convert Celsius to Fahrenheit and back. I want to get input from an edit text so I can use that for my math, but I can't figure it out, nor can I get the button to work right to close it. I want to use an internal anonymous class to do the calculations and read in the value, but again no idea what to do. Does anyone have any idea where to start?
here is what I have
package com.example.a4;
import android.os.Bundle;
import android.app.Activity;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.Menu;
import android.widget.Button;
import android.widget.EditText;
public class MainActivity extends Activity implements TextWatcher {
EditText mt=(EditText) findViewById(R.id.et1),
mt2=(EditText) findViewById(R.id.et2);
Button bt = (Button) findViewById(R.id.btn1);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//mt=(EditText) findViewById(R.id.et1);
// mt2=(EditText) findViewById(R.id.et2);
}
OnClickListener oclBtnOk = new OnClickListener() {
#Override
public void onClick(DialogInterface arg0, int arg1) {
// TODO Auto-generated method stub
}
};
/*
buttonExit.setOnClickListener(
new View.OnClickListener() {
public void onClick(View v) {
System.exit(0);
}
}
);*/
#Override
public void afterTextChanged(Editable s) {
// TODO Auto-generated method stub
int c = Integer.parseInt(s.toString());
ftoc(c);
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
// TODO Auto-generated method stub
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
// TODO Auto-generated method stub
}
void ftoc(int c){
int f = ((9/5)*c) + 32;
mt2.setText(f);
}
/*
#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;
}
*/
}
You need to move your mt = (EditText)findViewById stuff back to onCreate. Then, if you want to use anonymous classes, do something like:
mt.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
...
}
});
Also, make sure you're using View.OnClickListener and not DialogInterface.OnClickListener as you are now (check your imports).

Android SeekBar extension

I have multiple Seek Bars on my activity (4) and for each there is a textView that suppose to show the progress of each SeekBar. I thought to extend the SeekBar Class and add to it's constructor a TextView Parameter so I can bind the two -> SeekBar and TextView . Here is my extended SeekBar class:
import android.content.Context;
import android.widget.SeekBar;
import android.widget.TextView;
public class SeekBarPlus extends SeekBar {
private TextView numberOfDrills;
public SeekBarPlus(Context context, TextView text) {
super(context);
// TODO Auto-generated constructor stub
numberOfDrills = (TextView) text;
}
public void onStartTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
public void onStopTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
public void onProgressChanged(SeekBar seekBar, int progress,
boolean fromUser) {
// TODO Auto-generated method stub
numberOfDrills.setText(progress);
}
}
What is the Context option?
Now here is my MainActivity:
package com.simplemathgame;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.TextView;
import com.simplemathgame.SeekBarPlus;
public class MainActivity extends Activity{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView numberOfAddDrills = (TextView) findViewById(R.id.add_drills_number);
TextView numberOfSubDrills = (TextView) findViewById(R.id.sub_drills_number);
TextView numberOfMulDrills = (TextView) findViewById(R.id.mul_drills_number);
TextView numberOfDivDrills = (TextView) findViewById(R.id.div_drills_number);
SeekBarPlus addSeekBar = SeekBarPlus((SeekBar) findViewById(R.id.add_seek_bar), numberOfAddDrills);
SeekBarPlus subSeekBar = SeekBarPlus((SeekBar) findViewById(R.id.sub_seek_bar), numberOfAddDrills);
SeekBarPlus mulSeekBar1 = SeekBarPlus((SeekBar) findViewById(R.id.mul_seek_bar), numberOfAddDrills);
SeekBarPlus divSeekBar1 = SeekBarPlus((SeekBar) findViewById(R.id.div_seek_bar), numberOfAddDrills);
}
}
I don't know how to it wright! Any suggestions would be appreciated!!!
try to use setter instead of constructor in your custom SeekBar:
public void setTextView(TextView text) {
numberOfDrills = text;
}
then in your activity, use
SeekBarPlus subSeekBar = (SeekBarPlus) findViewById(R.id.sub_seek_bar);
subSeekBar.setTextView(numberOfAddDrills);
you can also use normal Seekbar with OnSeekBarChangeListener:
SeekBar subSeekBar = (SeekBar) findViewById(R.id.sub_seek_bar);
subSeekBar.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {
#Override
public void onStopTrackingTouch(SeekBar seekBar) { }
#Override
public void onStartTrackingTouch(SeekBar seekBar) { }
#Override
public void onProgressChanged(SeekBar seekBar, int progress,
boolean fromUser) {
numberOfDrills.setText(String.valueOf(progress));
}
});

Categories