This question already has an answer here:
How to receive an int through an Intent
(1 answer)
Closed 4 years ago.
I'm trying to pass an Integer (from an edittext) to another activity through an intent.
When the user clicks a button, the text in the edittext will transform into a string and then into an int, then the int will be sent through an intent to another activity, but i have to use the int after that.
Here the activity sending the intent:
public class HomeActivityPro extends ActionBarActivity {
private InterstitialAd interstitial;
EditText conttext = (EditText) findViewById ( R.id.texthome );
Button buttone = (Button) findViewById(R.id.buttone);
String maxom = conttext.getText().toString();
int maxam = Integer.parseInt(maxom);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layout_home);
View.OnClickListener maxim = new View.OnClickListener() {
#Override
public void onClick (View view) {
Intent wall = new Intent(HomeActivityPro.this, GuessOne.class);
wall.putExtra("maxPressed", maxam);
startActivity(wall);
}
};
buttone.setOnClickListener(maxim);
Here the activity receiving it:
public class GuessOne extends ActionBarActivity {
int randone;
int contone;
int wall = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layout_guess_one);
wall = getIntent().getIntExtra("maxPressed", -1);
randone = (int) (Math.random()*10+1);
contone = 0;
}
Here i'm using it:
public void guessone (View view){
contone++;
textcontone.setText(getString(R.string.attempts) + "" + contone);
if (contone >= wall ){
resultaone.setText("You Failed" + " " + wall);
Toast.makeText(this, "You Failed", Toast.LENGTH_LONG).show();
}
When i use the app, the value of the int is always -1. Where i am wrong.
You can't use findViewById without setting the xml to the activity. That means you need to use findViewById method only after you have called setContentView.
Also you need to read the EditText text value once you click on the button otherwise it always will be null/empty.
Do this
public class HomeActivityPro extends ActionBarActivity {
private InterstitialAd interstitial;
EditText conttext;
Button buttone;
String maxom;
int maxam = -1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layout_home);
conttext = (EditText) findViewById ( R.id.texthome );
buttone = (Button) findViewById(R.id.buttone);
View.OnClickListener maxim = new View.OnClickListener() {
#Override
public void onClick (View view) {
maxom = conttext.getText().toString();
maxam = Integer.parseInt(maxom);
Intent wall = new Intent(HomeActivityPro.this, GuessOne.class);
wall.putExtra("maxPressed", maxam);
startActivity(wall);
}
};
buttone.setOnClickListener(maxim);
Problem 1
Put this in the on click listener instead:
String maxom = conttext.getText().toString();
int maxam = Integer.parseInt(maxom);
You want the values to be read at the time you click the button not when you open the activity, correct?
Problem 2
The following needs to be after setContentView in onCreate:
conttext = (EditText) findViewById ( R.id.texthome );
buttone = (Button) findViewById(R.id.buttone);
Keep the declarations where they are. Just the declarations:
EditText conttext;
Button buttone;
Note
Follow the same pattern in all your activities. Declare views as field variables, assign them in onCreate after setContentLayout. Get the values at the time they're needed.
public int getIntExtra (String name, int defaultValue)
Added in API level 1 Retrieve extended data from the intent.
Parameters name The name of the desired item. defaultValue the value
to be returned if no value of the desired type is stored with the
given name. Returns the value of an item that previously added with
putExtra() or the default value if none was found. See Also
putExtra(String, int)
This means that no int was found when you called getIntExtra(valueName, defaultValue); so the default value was chosen.
You should check to see what your maxam value is before you call the new activity.
In the activity you receive it:
wall = getIntent().getIntExtra("maxPressed");
SOLVED: by getInt and String.valueOf
private static final String IMGID = "ImgID";
if (getIntent().getExtras().containsKey(IMGID)) {
//Picasso.with(this).load(getIntent().getExtras().getString(IMG)).into(mImg);
Picasso.with(this).load(getIntent().getExtras().getInt(String.valueOf(IMGID))).into(mImg);
}
Related
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 3 years ago.
It's been a month since I've kicked off with android studio, at this time I'm stuck at a point where I have to pass a set of <EditText/> values from MainActivity to UpdateActivity and then send those values to the Sqlite database for updating a table.
What I have accomplished:
Successfully sending values from MainActivity's <EditText/> to UpdateActivity's <EditText/>
How I have done that from MainActivity:
public class MainActivity extends AppCompatActivity {
DatabaseHelper myDb;
EditText editName, editSurname, editMarks;
Button btnUpdate;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myDb = new DatabaseHelper(this);
editName = (EditText) findViewById(R.id.UpdName);
editSurname = (EditText) findViewById(R.id.editTextSurname);
editMarks = (EditText) findViewById(R.id.UpdMarks);
btnUpdate = (Button)findViewById(R.id.btnUpdate);
btnUpdate.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String MainName = editName.getText().toString();
String MainSurname = editSurname.getText().toString();
String MainMarks = editMarks.getText().toString();
Intent UpdateAct = new Intent(MainActivity.this, UpdateActivity.class);
UpdateAct.putExtra("Name", MainName);
UpdateAct.putExtra("SurName",MainSurname );
UpdateAct.putExtra("Marks", MainMarks);
startActivity(UpdateAct);
}
});
}
Then inside the UpdateActivity:
public class UpdateActivity extends AppCompatActivity {
DatabaseHelper myDb;
Button btnUpd;
EditText editTextId, editUpdtName, editUpdSurname, editUpdMarks;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_update);
Intent getData = getIntent();
String Name = getData.getStringExtra("Name");
String SurName = getData.getStringExtra("SurName");
String Marks = getData.getStringExtra("Marks");
editTextId = (EditText)findViewById(R.id.editTextID);
editUpdtName = (EditText)findViewById(R.id.UpdName);
editUpdSurname = (EditText)findViewById(R.id.UpdSurname);
editUpdMarks = (EditText)findViewById(R.id.UpdMarks);
btnUpd = (Button)findViewById(R.Id.btnUpd);
editUpdtName.setText(Name);
editUpdSurname.setText(SurName);
editUpdMarks.setText(Marks);
}
What I'm stuck at is to send these values to a function named updateData();
For that I have tried to use the values from MainActivity directly to UpdateActivity but failed, then I tried to cast those <EditText/> and use it inside the function but failed again.
Inside my UpdateActivity:
..//
editUpdtName.setText(Name);
editUpdSurname.setText(SurName);
editUpdMarks.setText(Marks);
//updateData(Name, SurName, Marks);
updateData();
}
//function definiton
// public void updateData(final String Name, final String SurName, final String Marks)
public void updateData()
{
btnUpd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// boolean isUpdated = myDb.updateData(editTextId.getText().toString(), Name,SurName, Marks);
boolean isUpdated = myDb.updateData(editTextId.getText().toString(), editUpdtName.getText().toString(),
editUpdSurname.getText().toString(), editUpdMarks.getText().toString());
if(isUpdated == true){
Toast.makeText(UpdateActivity.this, "Data Updated Successfully!", Toast.LENGTH_SHORT).show();
}
else{
Toast.makeText(UpdateActivity.this, "Data NOT Updated!", Toast.LENGTH_SHORT).show();
}
}
});
}
}
The app crashes everytime the function updateData(); is called, to ensure that is the real cause I have even commented and also tried putting it in a handler to run it after 3000ms, as expcted it crashed after the time period.
Solved it by initializing the db.
myDb = new DatabaseHelper(this);
You forgot to initialize myDb.
Initialize it in your onCreate() method:
myDb = new DatabaseHelper(this);
Why not just pass the values to updateData()?
editUpdtName.setText(Name);
editUpdSurname.setText(SurName);
editUpdMarks.setText(Marks);
updateData(Name, SurName, Marks);
have you initialized btnUpd? I can not see this in your onCreate()
btnUpd = (Button) findViewById(...)
I'm struggling to figure out why I can't pass an int value from one activity to another. The app will ask you to press a button to generate a random number from 1-100 which will be displayed below the button. There is also another button which will open a new activity simply showing the random number that was rolled... but I just get 0.
I've looked into similar questions asked but to no avail.
Here's my code from MainActivity
public class MainActivity extends ActionBarActivity {
int n;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void ButtonRoll(View view) {
TextView textRoll = (TextView) findViewById(R.id.textview_roll);
Random rand = new Random();
n = rand.nextInt(100) + 1;
String roll = String.valueOf(n);
textRoll.setText("Random number is " + roll);
}
public void OpenStats(View view) {
Intent getStats = new Intent(this, Stats.class);
startActivity(getStats);
}
public int GetNumber (){ return n; }
}
Heres my 2nd class.
public class Stats extends Activity {
MainActivity statistics = new MainActivity();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.stats);
int n = statistics.GetNumber();
TextView tvStats = (TextView) findViewById(R.id.passedNumber_textview);
String number = String.valueOf(n);
tvStats.setText(number);
}
}
Is using getters the wrong way to get data from another class when using activities? Thanks for your time.
You should pass your data as an extra attached to your intent. To do this you need to first determine a global key to be used. You could do something like this in your MainActivity
public static final String SOME_KEY = "some_key";
then modify your OpenStats method to
public void OpenStats(View view) {
Intent getStats = new Intent(this, Stats.class);
getStats.putExtra(SOME_KEY, n);
startActivity(getStats);
}
and then in Stats.class onCreate method
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.stats);
int n = getIntent().getIntExtra(MainActivity.SOME_KEY, -1);
TextView tvStats = (TextView) findViewById(R.id.passedNumber_textview);
String number = String.valueOf(n);
tvStats.setText(number);
}
You obviously should make sure that you are calling ButtonRoll at least once or that you set n so that you aren't passing a null int.
Also, as note, convention states that methods should use lower camel case formatting. That is, the first word is completely lower case and the first letter of subsequent words is upper case. That would change your methods
OpenStats() -> openStats()
ButtonRoll() -> buttonRoll()
Classes/objects are upper camel case, just to help avoid confusion.
I have this code :
private ImageView d1;
private ArrayList<Integer> listaImagenes = new ArrayList<Integer>();
private ArrayList<String> listaFrases = new ArrayList<String>();
private Button button;
private Integer contador = 0;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.rellenarImagenes();
setContentView(R.layout.imagentonas);
d1 = (ImageView) findViewById(R.id.imagenes01);
while (contador < listaImagenes.size()) {
d1.setImageResource(listaImagenes.get(contador));
button = (Button) findViewById(R.id.botoncillo);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
contador++;
}
});
}
}
private void rellenarImagenes() {
listaImagenes.add(R.drawable.a01);
listaImagenes.add(R.drawable.a02);
listaImagenes.add(R.drawable.a03)
}
I am trying do a loop that when I press the button , increment contador and d1 change image.
but it is not working, application background remains black and not working.
remove while loop and setimage in onclick method.
You are expecting that modifying the value of the variable contador would result in the array item to change.
Keep in mind that in the code line d1.setImageResource(listaImagenes.get(contador));, the get function receives an int. So at the time where it's called it receives a value, not a reference to an Integer. When you change the value of contador, the value that was used to obtain the index in the array is not changed.
And even if the value did change, d1 would still be using the same resource.
What you need to do in the onClickListener is add the code to set the image. Something along the lines of
public void onClick(View v) {
++contador;
if (contador >= listaImagenes.size())
{
contador=0;
}
//you'll probably need to modify the next line to be able to access the button variable.
//one way to do it is to use a final variable in the onCreate method that creates this OnClickListener
button.setImageResource(listaImagenes.get(contador));
}
The while loop is not needed. What your code is doing is setting the image to the 3 items of the array, one after the other, and adding a new click listener 3 times.
I will try to answer and point some of the flaws you have in the code.
wat if there were 100 drawable like R01 ,R02...? Instead you can use getting drawable using string.
why are you using while loop ? since you have the counter you can directly use that.
Let me try to write the code
int contador=1;
#Override
public void onCreate (Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.imagentonas);
context=this;
d1=(ImageView)findViewById(R.id.imagenes01);
button=(Button)findViewById(R.id.botoncillo);
button=(Button)findViewById(R.id.botoncillo);
button.setOnClickListener( new View . OnClickListener () {
public void onClick ( View v ) {
int id = context.getResources().getIdentifier("a"+contador,
"drawable", context.getPackageName());
d1.setImageResource(id);
contador++;
}
});
}
Notice : int id = context.getResources().getIdentifier("a"+contador,"drawable", context.getPackageName()); Here using the string you can access the drawable this solves the issue for any number of consecutive drawables.
Hope you get the concept...
Thanks
I know this is a simpleton question, but I am not going to school for java, just learning it online.
how to a have a textview with an initial value of 0. and then everytime you press a button it ads 25 points to the score board.
At first I wanted the button press to add a random number between 42-57 to the score board.
And then how to do convert that int or long to a string to make it fit into a textview and keep the current score, and then add a new score.
EDIT: ok so someone said I should post the code so here it is.. where do i put this..
TextView txv182 = (TextView) findViewById(R.id.welcome);
txv182.setText(toString(finalScore));
Because when I do it, I get an error: The method toString() in the type Object is not applicable for the arguments (int)
public class MainActivity extends Activity {
// Create the Chartboost object
private Chartboost cb;
MediaPlayer mp = new MediaPlayer();
SoundPool sp;
int counter;
int db1 = 0;
Button bdub1;
TextView txv182;
int finalScore;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
txv182 = (TextView) findViewById(R.id.welcome);
finalScore = 100;
sp = new SoundPool(10, AudioManager.STREAM_MUSIC, 0);
db1 = sp.load(this, R.raw.snd1, 1);
bdub1 = (Button) findViewById(R.id.b4DUB1);
bdub1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (db1 != 0)
sp.play(db1, 1, 1, 0, 0, 1);
txv182.setText(finalScore);
}
});
First you need to store your score to certain integer variable say score and set it to any initial value you want and use.
TextView tv = (TextView) findViewById(R.id.myTextView);
tv.setText(toString(score));
you do not need to initialize the textview with value just in onclick() of button do score+=25and add text to your textview as above.
hope this helps
It's actually like this..
pernts+=25;
txv182.setText(String.valueOf(pernts));
in android, after the
public class MainActivity extends Activity {
but before..
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
i wrote..
int pernts;
String strI;
so then after the above #Override majigy, i wrote..
strI = "" + pernts;
pernts = 0;
because when i wrote it like.. int pernts = 0; it never worked, forcing me to add final and what not..
any way.. How to convert an integer value to string? anSwered the question..
and so the end was like this
pernts+=25;
txv182.setText(String.valueOf(pernts));
i figured out you have to add a value to the int variable not the string.. i kept wanting to add 25 and i was getting 25252525252525.., instead of 25 50 75 100.. kinda cool actually.. separating the logic of how to "add" 25 .. anyway thanks.. SOF!
30 minutes later... found this.. How can I generate random number in specific range in Android?
..
import android.app.Activity;
public class InsMenu extends Activity {
static TextView txv182;
static int pernts;
Button bdub1;
public static void addPernts() {
int min = 37;
int max = 77;
Random r = new Random();
int i1 = r.nextInt(max - min + 1) + min;
pernts+=i1;
txv182.setText(String.valueOf(pernts));
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.BLAHBLAH);
bdub1 = (Button) findViewById(R.id.b4DUB1);
txv182 = (TextView) findViewById(R.id.welcome);
bdub1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
addPernts();
}
--- i created my first objekt thanks to this too.. http://www.tutorialspoint.com/java/java_methods.htm ..
I FIGURED OUT WHAT I WAS DOING. I HAD THE VARIABLE NAME IN QUOTES WITH THE REST OF THE URL STRING.
How do you save the value of a Radio button into a variable and use that variable later.
I can see the variable Day_Item in my LogCat and the value is in there but when try using Day_Item later it does not show the valuable.
Below is a section of my code that shows the buttons.
String Day_Item = null;
public class SearchDB extends Activity {
private static final String TAG = "MyApp";
String start_log = "STARTED";
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.search_layout);
final RadioButton radio_monday = (RadioButton) findViewById(R.id.monday);
radio_monday.setOnClickListener(radio_listener);
cityspinner.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position,long arg3)
{
int id = parent.getId();
if (spinner2_count2 < spinner2_count1 ) {
spinner2_count2++; }
else
{
String city_spinner_log = "CITY SPINNER";
Log.d(TAG, city_spinner_log);
String item = cityspinner.getSelectedItem().toString();
String nameContentType = "name";
String cityURL = "GetRestaurant.php?day=Day_Item&city=" + item;
Log.d(TAG, cityURL);
String shop_data = DataCall.getJSON(cityURL,nameContentType);
Log.d(TAG, shop_data);
Bundle bundle = new Bundle();
bundle.putString("shopData", shop_data);
Intent myIntent = new Intent(SearchDB.this, ShowRestaurant.class);
myIntent.putExtras(bundle);
startActivityForResult(myIntent, 0);
}
}
}
//ONCLICKLISTENER that saves RADIO value into a variable.
public OnClickListener radio_listener = new OnClickListener() {
public void onClick(View v) {
// Perform action on clicks
RadioButton rb = (RadioButton) v;
Day_Item = (String) rb.getText();
Log.d(TAG,Day_Item);
Toast.makeText(SearchDB.this, Day_Item, Toast.LENGTH_SHORT).show();
}
};
}
You would need a bit more code to get a good solid answer. Such as how is Day_Item allocated? And is it's scope global? Are you calling it from another activity or the one it's allocated within? These are just guesses at this point:
1) Are you sure your onClickListener isn't firing multiple times? Thus setting Day_Item to an undesired text or nothing at all?
2) Rather a question/answer,
"but when try using Day_Item later it does not show the valuable"
I'm assuming this means that it is null? Well if it's being set properly, and then it is being null'd... it either is being explicitly null'd by you somewhere (such as (1)) or else the allocation and scope are the issue area I believe...