Implementing OnValueChange to a NumberPicker in Android - android

I"m trying to add the onValueChangeListener to my number picker (np1) in android 4.2.2.
Here's what I have so far
public class main extends Activity {
ViewFlipper vf = null;
HttpClient client = null;
private ArrayList<String> captionList = new ArrayList<String>();
ListView lv = null;
private String custid = null;
ImageView iv = null;
private int vfloginview = 0;
private int vflistview = 0;
private boolean vfsentinal = false;
NumberPicker np1 = null;
TextView totalcost = null;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.mystuffmobile);
vf = (ViewFlipper) findViewById(R.id.vf);
client = new DefaultHttpClient();
lv = (ListView) findViewById(R.id.lv);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
np1 = (NumberPicker) findViewById(R.id.np1);
np1.setMinValue(1);
np1.setMaxValue(400);
//np1.setOnValueChangedListener;
//np1.setOnValueChangedListener(onValueChange);
}
to try to test it's functionality I've been using this
public void onValueChange (NumberPicker np1, int oldVal, int newVal) {
Log.v("NumberPicker", np1.getValue() +"");
}
Does anyone know an easy way to implement this listener without having my main activity implement NumberPicker.OnValueChangeListener?
Note: the only reason I'm opposed to having my main activity implement NumberPicker.OnValueChangeListener is because then I have to set main to abstract and my application won't run.

You're going to do this just like a click listener on a button.
np1.setOnValueChangedListener(new OnValueChangeListener() {
#Override
public void onValueChange(NumberPicker picker, int oldVal, int newVal) {
// do something here
}
});
A fully working example can be found here: http://samplecodez.com/android/numberpicker.php
Some stylistic points ...
Main should be capitalized and it's a good practice to make it more descriptive like MainActivity.
Use fields only when necessary. I'm guessing you're not using most of those variables outside of onCreate() so make them local variables instead.
TextView totalCost is your best named variable of the lot :) Consider using verbose names. You'll thank yourself 6 months down the road when you look back at this code for the first time in a long time.
No magic values (or Strings)! Create a constant for your min and max values and those should be private static final int with the your fields.
In Eclipse setup the java save actions in preferences to auto format all lines of code when you save.
Of course none of those things will make your code run any better, but it sure will be easier to read.

Related

How do I pass a variable from one Class to another in Android

How do I assign user input (from a TextView) into a variable then call that variable in another class?
From my MainActivity, I have the followingn where user input is taken:
Button confirm;
EditText inputField;
String typedChar;
char[] cars = typedChar.toCharArray();
#SuppressLint("WrongViewCast")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
confirm = (Button)findViewById(R.id.btConfirmInput);
inputField = (EditText) findViewById(R.id.etInputChars);
confirm.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
typedChar = inputField.getText().toString();
}
}
);
I'm trying to store the input and convert it to char
String typedChar;
char[] cars = typedChar.toCharArray();
Now I want to use cars in another class in the following method which print to a custom view:
private void drawText() {
for (int i = 0; i < txtPosByColumn.length; i++) {
canvas.drawText("" + cars[RANDOM.nextInt(cars.length)], i * fontSize, txtPosByColumn[i] * fontSize, paintTxt);
if (txtPosByColumn[i] * fontSize > height && Math.random() > 0.975) {
txtPosByColumn[i] = 0;
}
txtPosByColumn[i]++;
}
I'm however able to assign hardcoded value to cars like bellow:
private char[] chars = "010101".toCharArray();
but I want it come from user input
Anyone please kindly advice, guide. I know I'm doing things wrong but can't figure out...
PS: Noob here
You put your variable in an Intent like this:
confirm.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
typedChar = inputField.getText().toString();
char[] chars = typedChar.toCharArray();
Intent intent = new Intent(MyCurrentActivity.this, MySecondActivity.class);
intent.putExtra("somethingWithARelevantName", chars);
startActivity(intent);
}
}
);
And you get it in your second activity like this:
Intent intent = getIntent();
char[] chars = intent.getExtras().getCharArray("somethingWithARelevantName");
edit: if want your variable in a class that is not an activity, you can pass it in the constructor:
class MyClass{
char[] chars;
MyClass(char[] chars){
this.chars = chars;
}
}
You should specified what is the type of that other class.
If it is a simple Java class you can pass it as a field to your drawText(char[] array);
If however you are dealing with activities the :
In your first activity, before launching the other activity, use Extra intent to send data between activities as the answer show before.

get value from SpinnerWheel

I'm trying to get the value from Android SpinnerWheel. There are very few post in SO giving answer for this and not one post shows any true information. I found only one link which was a bit descriptive but still didn't have the result I wanted. So if anyone can show me how exactly we can get the value and set it in a TextView, it will be really great
My Code
public class MainActivity extends Activity {
TextView textvalue;
String value;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textvalue = (TextView)findViewById(R.id.textvalue);
final AbstractWheel mins = (AbstractWheel) findViewById(R.id.mins);
NumericWheelAdapter minAdapter = new NumericWheelAdapter(this, 0, 59, "%02d");
minAdapter.setItemResource(R.layout.wheel_text_centered_dark_back);
minAdapter.setItemTextResource(R.id.text);
mins.setViewAdapter(minAdapter);
//OnWheelChangedListener listener = null;
//mins.addChangingListener(listener);
}
private OnWheelChangedListener changedListener = new OnWheelChangedListener() {
public void onChanged(AbstractWheel wheel, int oldValue, int newValue) {
String value = String.valueOf(newValue);
textvalue.setText(value);
}
};
}
.
The only thing I see is, that You haven´t added the listener to Your wheel, because You had commented it out:
//mins.addChangingListener(listener);
It must be:
mins.addChangingListener(changedListener);

Android intent's data not carried out correctly on another activity

I am sending data from one activity to another through intent. I am sending two different strings but getting same value for both variable on next activity.
Here is my code :
public class Quizzes extends ActionBarActivity {
protected static final String QUIZ_TITLE = null;
protected static final String COURSE = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_quizzes);
listView = (ListView) findViewById(R.id.listview);
String[] values = new String[] { "Quiz # 2" };
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1, android.R.id.text1, values);
listView.setAdapter(adapter);
// ListView Item Click Listener
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
final String item = (String) parent.getItemAtPosition(position);
Intent intent = new Intent(getApplicationContext(), QuizDetail.class);
intent.putExtra(QUIZ_TITLE, item);
final String course = (String)textview.getText();
intent.putExtra(COURSE, course);
startActivity(intent);
}
});
}
}
If you see i am passing two string intent object :
1. QUIZ_TITLE
2. COURSE
When i debugged the application, I can see values like
1. QUIZ_TITLE = "Quiz # 1"
2. COURSE = "Intro to Computing"
All fine until here, but when i am retrieving these string on other activity, I am getting value "Intro to Computing" for both, here is code from that class.
public class QuizDetail extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_quiz_detail);
Intent intent = getIntent();
String quizTitle = intent.getStringExtra(Quizzes.QUIZ_TITLE);
TextView quizTitleTextView = (TextView) findViewById(R.id.quizTitle);
quizTitleTextView.setText(quizTitle+" : TESTING..");
String courseTitle = intent.getStringExtra(Quizzes.COURSE);
TextView courseTitleTextView = (TextView) findViewById(R.id.courseTitle);
courseTitleTextView.setText(courseTitle);
}
}
I am not sure why I am getting same value "Intro to computing" from Quizzes.QUIZ_TITLE and Quizzes.COURSE.
Any help would be highly appreciated.
Thanks..
Anjum
You are using bad the intent.putExtra(),
You need to put a key (you need to know) as first param, to get the object in the other activity like:
...
String item = ...;
intent.putExtra("COURSE", item);
...
And you get the extras with:
...
intent.getStringExtra("COURSE");
...
Edited !!!
There's a couple of things here that should be mentioned.
QUIZ_TITLE and COURSE are both null (I can't see where they're set)
When you add something to the Extras Bundle, you're placing values in to a dictionary. The key for this dictionary you're using, in this case, is null. This means the second time you're putting in to the dictionary, QUIZ_TITLE (null) is being replaced with the key COURSE (null).
If you change QUIZ_TITLE and COURSE to an actual String value, it should sort that problem.
The second thing to note, is that there's a difference between getExtraString and getExtras.getString. I have written about this here
Hope that helps.
Please try this
Intent intent = getIntent();
String quizTitle = intent.getExtras().getString(Quizzes.QUIZ_TITLE);
String courseTitle = iintent.getExtras().getString(Quizzes.COURSE);
Update:
Oh now i see it too:
protected static final String QUIZ_TITLE = null;
protected static final String COURSE = null;
is really fatal because using a null value for a key is not useful and even if it is possible you are setting your value for the key 'null' first and overwrite it then by setting the value for key 'null' again.
Change it to:
protected static final String QUIZ_TITLE = "extra_quiz_title"
protected static final String COURSE = "extra_course";
for example

Passing a counter from one Activity to another

I have an class Voice, which extends Activity, and contains a counter. When the user answers correctly, the counter adds one via counter++;
public class Voice extends Activity implements OnClickListener{
ListView lv;
static final int check = 111;
int counter_score;
TextView txView;
MediaPlayer ourSong;
ImageView display;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.letter_a);
initialize();
}
private void initialize() {
lv = (ListView)findViewById(R.id.lvVoiceReturn);
Button b = (Button)findViewById(R.id.imageButtonSelector);
txView = (TextView)findViewById(R.id.counter);
b.setOnClickListener(this);
counter_score=0;
}
This score, is bundled and passed on to the next activity "What" within a string "your score is 1".
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == check && resultCode == RESULT_OK) {
ArrayList<String> results = data.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
lv.setAdapter( new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, results));
if(results.contains("hey") || results.contains("a") || results.contains("ay")) {
//toast referenced to xml the after 400ms
counter_score++;
txView.setText("Your Score is" + " " + counter_score);
AlertDialog dialogBuilder = new AlertDialog.Builder(this).create();
dialogBuilder.setTitle("AWSOME");
dialogBuilder.setMessage("¡Your current score is" + counter_score);
dialogBuilder.setIcon(R.drawable.ic_mark);
dialogBuilder.show();
ourSong = MediaPlayer.create(Voice.this, R.raw.rightsound2);
ourSong.start();
Thread timer = new Thread() {
public void run(){
try {
sleep(2500);
}catch (InterruptedException e){
e.printStackTrace();
} finally {
String score = txView.getText().toString();
Bundle keeper = new Bundle();
keeper.putString("key", score);
Intent putScore = new Intent(Voice.this, What.class);
putScore.putExtras(keeper);
startActivity(putScore);
}
}
};
timer.start();
}
}
The next Activity, What, gets this Bundle and displays it fine using setText(gotScore)
public class What extends Activity implements OnClickListener {
ListView lv;
static final int check = 111;
private int counter_score;
TextView txView;
MediaPlayer ourSong;
ImageView display;
String gotScore;
String classes[] = {"What", "Pagina", "What", "example3", "example4", "example5",
"example6"};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.letter_b);
initialize();
Bundle gotKeeper = getIntent().getExtras();
gotScore = gotKeeper.getString("key");
txView.setText(gotScore);
}
private void initialize() {
// TODO Auto-generated method stub
lv = (ListView)findViewById(R.id.lvVoiceReturn);
Button b = (Button)findViewById(R.id.imageButtonSelector);
txView = (TextView)findViewById(R.id.counter);
b.setOnClickListener(this);
..this is when things go bad :(
On What I have another question tied to a counter as well. When the user answers correctly the counter adds one via counter++; and it does. However, it changes the txview string to "your score is 1". I can't get it to add 1 to the counter result passed from the previous activity within the string, so that the counter on What reads "your score is 2". This gets passes to the next activity in Bundle keeper, which holds the aggregate score.
I've read a few tutorials on passing an int verses a string, but some of the code they use like getInt is not recognized. I'm stumped.
What you're bundling and passing to the What activity is not the counter but the string "Your score is 1". If you want to increment that number in the next activity then you should be sending just the integer value and constructing whatever string you need there instead.
I ve read a few tuts on passing an int vs a string..but some of the code they use like getInt is not recognized..anywho Im stumped..
I'm not too sure I know what you mean by getInt() is not recognized. In any case, make things easier for yourself when passing counter from one activity to another. If it is an int and you plan on manipulating like an int in the receiving activity then add it to the bundle as an int. For example:
Bundle keeper = new Bundle();
keeper.putInt("key", counter_score);
And retrieve it from the bundle with:
Bundle gotKeeper = getIntent().getExtras();
int score = gotKeeper.getInt("key");
What if you make a "global" class to be shared across the different activities, and use it to keep the variables used "in sync"?
For example - Globals.java:
public class Globals {
public int counter_score;
}
And then reference that variable using Globals.counter_score
You can of course also use that shared class for other variables and functions as well - for example common operations.
Update
As the commenters pointed out, this method isn't particularily good - I forgot that the code is simply referenced, and doesn't "live" on its own to keep information for the other activities (thanks for correcting me on that one, I'm still learning...)
Something that COULD work better, though, is to pass the current state of the counter_score variable in the intent when you launch your second activity - for example:
IntentToLaunchTheOtherActivity( counter_score );
And then maybe pass the variable back to the previous activity if it's changed afterwards...
I got it work. Essentially I needed to what what TJ Third suggested converting keeper.putString("key", counter_score); to keeper.putInt("key", counter_score);, I also needed to convert the bundle being received to an int within the "What" activity. Within "What" activity I renamed int counter_score; and int gotKeeper;(this was String gotKeeper) then instead of calling counter_score =0; now that the bundle passed is an int,I called counter_score = gotKeeper; under initialize(); so the counter score equals the result generated from the previous activity "Voice".
Now when the user answers correctly, counter++; adds one to the existing counter_score and bundles it and send it to the next activity, and rinse a repeat.
static final int check = 111;
int counter_score;
TextView txView;
MediaPlayer ourSong;
ImageView display;
int gotKeeper;
String classes[] = {"What", "Pagina", "What", "example3", "example4", "example5",
"example6"};
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.letter_b);
initialize();
Bundle gotKeeper = getIntent().getExtras();
gotKeeper = gotScore.getInt("key");
counter_score = gotKeeper;
Again thnx to everyone for your suggestions and insight.Huge help to a newbie.

OnClickListener error: Source not found

I'm brand new to Android development and right now I am building a simple calculator for healthcare workers. My program implements the OnClickListener class, but every time I click on the button to initiate the calculation, I get an error saying the "Source is not Found".
Here is the code:
public class KidneyeGFR extends Activity implements OnClickListener {
TextView EditAge;
TextView EditSerum;
TextView Gfrtext;
RadioButton Male;
RadioButton Female;
RadioButton EveryoneElse;
RadioButton African;
Button Calculate;
double gender;
double race;
double finalgfr;
private static final int GFRCONST = 186;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
EditAge = (TextView)this.findViewById(R.id.EditAge);
EditSerum = (TextView)this.findViewById(R.id.EditSerum);
Male = (RadioButton)this.findViewById(R.id.Male);
Male.setChecked(true);
Female = (RadioButton)this.findViewById(R.id.Female);
EveryoneElse = (RadioButton)this.findViewById(R.id.EveryoneElse);
EveryoneElse.setChecked(true);
African = (RadioButton)this.findViewById(R.id.African);
Calculate = (Button)this.findViewById(R.id.Calculate);
Calculate.setOnClickListener(this);
}
public void onClick(View v) {
if (Female.isChecked()) {
gender = 0.742;
}
else {
gender = 1.0;
}
if (African.isChecked()) {
race = 1.212;
}
else {
race = 1.0;
}
calculateGFR();
}
protected void calculateGFR() {
int age = Integer.parseInt(EditAge.getText().toString());
double serum = Double.parseDouble(EditSerum.getText().toString());
finalgfr = GFRCONST * Math.pow(serum, -1.154) * Math.pow(age, -0.203) * gender * race;
Gfrtext.setText(Double.toString(finalgfr));
}
define the TextView Gfrtext...
Gfrtext = (TextView)this.findViewById(R.id.Gfrtext);
Actually you are getting a NullPointerException, check the LogCat or Debug view to have more specific details about your app exceptions.
Thats the big problem!!! =)
I think that you are missing the initialization of Female/African/EditAge/etc. in the onCreate method. Here you should load all of these using the findViewById method. This can easily be checked when debugging (try placing a breakpoint on the first line of the onClick method).
By the way, the convention in Java is that members and methods of an object always start with a lower case and that object names start with an upper case.
Your code doesn't have any trouble ! thats an Eclipse Exception
check this...
Eclipse debugging “source not found”

Categories

Resources