get value from SpinnerWheel - android

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);

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.

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

Android Eclipse changing text on a snake game

How do i go to the next text when my snake eat a food? (When the snake eat the food, the text will change from testing to success.) I'm using the snake game provided by eclipse. This is the code i have done so far. I am doing this for my project so i appreciate all the help i can get.
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
public class Snake extends Activity {
/**
* Constants for desired direction of moving the snake
*/
public static int MOVE_LEFT = 0;
public static int MOVE_UP = 1;
public static int MOVE_DOWN = 2;
public static int MOVE_RIGHT = 3;
private static String ICICLE_KEY = "snake-view";
private SnakeView mSnakeView;
/**
* Called when Activity is first created. Turns off the title bar, sets up the content views,
* and fires up the SnakeView.
*
*/
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.snake_layout);
init();
mSnakeView = (SnakeView) findViewById(R.id.snake);
mSnakeView.setDependentViews((TextView) findViewById(R.id.text),
findViewById(R.id.arrowContainer), findViewById(R.id.background));
if (savedInstanceState == null) {
// We were just launched -- set up a new game
mSnakeView.setMode(SnakeView.READY);
} else {
// We are being restored
Bundle map = savedInstanceState.getBundle(ICICLE_KEY);
if (map != null) {
mSnakeView.restoreState(map);
}
}
}
#Override
public void onSaveInstanceState(Bundle outState) {
// Store the game state
outState.putBundle(ICICLE_KEY, mSnakeView.saveState());
}
private int currentQuestion;
private String [] questions;
private TextView questionView;
public void init() {
questions = new String[]{"testing","success"};
currentQuestion = -1;
questionView = (TextView) findViewById(R.id.QuestionTextView);
showQuestion();
}
public void showQuestion() {
currentQuestion++;
if(currentQuestion == questions.length)
currentQuestion =0;
questionView.setText(questions[currentQuestion]);
}
}
After checking out the source code (which I did here: http://grepcode.com/file/repository.grepcode.com/java/ext/com.google.android/android-apps/4.2_r1/com/example/android/snake/SnakeView.java), I dont think it's possible to add this functionality without altering the source code...
However, if u want to edit the source to make it work, I would suggest the following:
create an interface to use as a listener
public interface AppleEatenListener{
public void appleEaten(int size);
}
Then add a variable of this interface to the SnakeView class
private AppleEatenListener mAppleEatenListener;
Create a setter in the SnakeView class to set the mAppleEatenListener
public void setAppleEatenListener(AppleEatenListener listener){
this.mAppleEatenListener = listener;
}
After that, make your way down to the updateSnake() method in the SnakeView class and find the following piece of code (consider using ctrl+f (search function)):
This snippet comes from the current source code:
// except if we want the snake to grow
if (!growSnake) {
mSnakeTrail.remove(mSnakeTrail.size() - 1);
}
And here we want to add, that if the snake should grow, we call the AppleEatenListener's function appleEaten(), like so:
// except if we want the snake to grow
if (!growSnake) {
mSnakeTrail.remove(mSnakeTrail.size() - 1);
}
else{
if(mAppleEatenListener != null){
mAppleEatenListener.appleEaten(mSnakeTrail.size());
}
}
Now, we should return to your own Snake class and add the following in onCreate():
mSnakeView.setOnAppleEatenListener(new AppleEatenListener() {
#Override
public void appleEaten(int size) {
showQuestion();
//size is the current size of the snake after the apple was eaten
}
});
Note that I've added that the listener requests a "size" parameter, I'm supposing it could be useful to know the size of the snake after it has eaten an apple, since I didn't see a function for requesting the size of the snake in the API either...
I have not tested this code, but I hope this helps u at least a little

Implementing OnValueChange to a NumberPicker in 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.

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