First of, I'm a noob in Android development....
So, my problem is - I have a Activity with a EditText view, so someone can put his name in it.
And what I want to do with that input - I want it to be displayed in all activities in TextViews where it needs to be.
Example - Like in a book -> Input name: What are you doing kid? Kir: "I don't know..." Input name: "Just don't do it anymore..."ect.
And then in the next Activity by clicking a Button, the same, I want that same input name to display in ALL ACTIVITES , TextViews where it needs to be, but I don't know how to declare it, where to declare it, what code ect.
I hope you all will understand what i mean.
And thank you for your support.
One way is by passing data into intents before starting the activity.
Intent intent = new Intent(context, MyActivity.class);
intent.putExtra("key_name", "John Cena");
context.startActivity(intent);
Then retrieve the data in MyActivity by:
Bundle extras = getIntent().getExtras();
String name = extras.getString("key_name"); // name should be John Cena
Simillar functionality also exists for Fragments.
Basically you wants to Preserve the Value\Data. For such scenarios, it is best to use [Preferences] where you can save your data on disk in a private file and read it anytime and anywhere.
Android Preferences
Related
Intent myIntent = new Intent(this,Q1.class);
In my app I have 1000 different activities namely Q1,Q2,Q3....Q1000.
I have a button on each activity and I want when a user clicks on it, he should land on some random activity.
How to achieve this ?
Although this is terrible, I'll still show a possible way to do this. But just remember, this is TERRIBLE.
You can store all the activity classes in an ArrayList.
ArrayList<Class<Activity>> activities = new ArrayList<> ();
And then you add all the activities into the ArrayList. Yeah, I know, this part is tedious. For example,
activities.add (Activity1.class);
And then you create a Random called rand and use that to access an element in the list:
list.get (rand.nextInt (list.size()));
Here is another "better" way to do it, but it's still kinda bad. I strongly advise you to store teh questions in a database. Anyway, here's the better-but-still-bad method.
You create a question class:
public class Question {
//here you can put correctAnswer, questionText etc
}
After that, you make an ArrayList of Questions i.e. ArrayList<Question>.
ArrayList<Question> questions = new ArrayList<> ();
And still, you need to add 1000 questions to the array list. Then you can just use a Random to access it.
When you want to display a question in one activity, you can just putExtra in Intent before starting the activity. putExtra basically passes some "parameter" thingys to the activity. Then in the activity, you can just get the "Extra" and use the Question object to display. e.g. set the text of a TextView to the question text.
this can be also used:
try {
Random rand=new Random();
Intent i = new Intent(this, Class.forName("test.hu.test.Q"+rand.nextInt(1000)+"")); // get activity's class by reflection
startActivity(i);
}catch (Exception e)
{
}
But i also suggest to use DB.
This is a real noob question I'm sure, but I am finding it quite perplexing.
Why an earth would you want to ever use intent.putExtra method to share information between classes in Android?
Let me explain. I am making my first Android app following the instructions from the developers guide (I am already at a moderate level with Java) and I am using some code that looks like this:
//Class field
//key holds string????? not fully understanding this...
public static final String EXTRA_MESSAGE = "self.anon.myfirstapp.MESSAGE";
//this method is activated by a button being pressed
public void sendMessage(View view) {
Intent intent = new Intent(this,DisplayMessageActivity.class);
EditText editText = (EditText) findViewById(R.id.edit_message);
String message = editText.getText().toString();
//puts string message inside the string EXTRA_MESSAGE - why????
intent.putExtra(EXTRA_MESSAGE, message);
startActivity(intent);
}
OK firstly I want to point out I see what is happening and for the most part how it works (am just confused by the field declaration = "myClassPath" why?)...
BUT....
Surely it would be easier just to have a static field called:
public static String message;
then my method would look like this:
public void sendMessage(View view) {
Intent intent = new Intent(this,DisplayMessageActivity.class);
EditText editText = (EditText) findViewById(R.id.edit_message);
message = editText.getText().toString();
startActivity(intent);
}
Then when my class DisplayMessageActivity needs the string message he just calls for:
String message = myClass.message;
That seems so much more straight forward. What is with the creation of the new string EXTRA_MESSAGE which just seems to hold the string message and why send it with the intent when my other class can access this info directly anyway -- and what does the field declaration with the "self.anon.myfirstapp.MESSAGE" mean? I can find no such folder or path leading to anything.
As someone else stated there are often situations (such as a screen rotate) in which the android system destroys and restarts the app - so all variable data is lost. It would only work consistently the way you suggest if your data is hard coded as a final variable. That is not the only reason for using intents though.
The great thing with using an intent to pass information is that you can use the intent not just to communicate with sub-activities within your own application but to any activity installed on that android system. For example you may want to launch an intent which starts the phone application and include as an extra the number that you want to call.
Perhaps a better question than yours though is "why would you not use intents to pass information?" The intent.putExtra() method allows you a convenient flexible and straight forward method to pass as much information as you like in a safe and secure way to any other activity.
intent.putExtra(EXTRA_MESSAGE, message);
works like a key value pair, when you want to retrieve the information from the intent you can simply do intent.get<type>Extra and get said information, in this case, intent.getStringExtra("self.redway.myfirstapp.MESSAGE'). its simply the key to retrieve the information, it does not have to be your entire classpath.
it could just as easily be intent.putExtra("message",message).
They are helpful when passing information that you don't necessarily want to reveal to another class but you do want it to be able to get that information in another manner from what i have found.
message = myClass.message It is not always certain that this will retain its value especially when it extends Android framework classes like Activity. When your activity is recreated(change of screen orientation) then message can lose its current value and be assigned a default value. myClass.message would work if message was a static field or else you would need to provide getter and setter methods for object of the Activity Class. Well creating objects of activity class is unheard of in my experience.
I still am a beginner in Android development and will try to make my question as clear as possible with a schema of what I have in my mind.
Purpose of this application:
- I want the user to have the choice between a few buttons and when clicking on any of them, it would open a list view with different content according to the button.
ex : if you click on "Category_1" button, only elements with a fitting id will appear in the listview.
So far, I have :
- defined my "handler" class (extends SQLiteOpenHelper) : name/path of DB, definition of CRUD, .getReadableDatabase, etc.
- define a class for my table, in my case "Restaurants.java" with getters/setters and constructor.
- defined my MainActivity with empty listeners for my button.
- defined my "DatabaseAdapter.java" in which I want to define the methods/sql requests which will communicate with the database and get the information I want from it.
- defined my ListViewActivity with nothing to display so far.
Here is a schema of what I want with the idea of how to make it to try to optimize my application :
To sum up:
- I want a listener for each button setting a variable to a certain value (for example: "if you click on 1 then set the value of A to 1") and opening the ListViewActivity.
- There would be a method defined in "...Adapter.java" sending a request to the database and having the variable A defined earlier as an input.
- And then, when clicking on the button, the ListViewActivity will open and call the method from "..Adapter.java", and finally display the results.
So, here are my questions :
- First of all, is the design optimized enough to allow my application to run fast? I think it should as all the button open only one activity and there is only one method defined for all buttons.
- I have a hard time defining the method in "...Adapter.java" which will be called from my ListViewAcitivity. The input should be the variable obtained when clicking on the button but I don't really know how to get a variable in one activity, open a second activity where to display results by using the variable in a third activity... :s
Is it fine to set a variable to a certain value when we click on a button and use this variable in another class as an input for a method?
public findNameInTable(int A){
string sql = " select NAME from MY_TABLE where CAT1 = " + A;
c = database.rawQuery(sql, null); }
Thanks in advance for any indications, suggestions or links which could help me to make my application come true, and sorry if some questions really sounds newbie, I am starting !
Have a good day !
Part 1: The best way I have found to pass variables to other activities is with a putExtra(String, variable);. Say you change the variable name on a button press, you can then call:
YourNewActivityClassName var = new YourNewActivityClassName();
Intent i = new Intent(context, YourNewActivityClassName.class);
i.putExtra("name", name);
startActivity(i);
Then in the activity you just created, you can call this in the onCreate method:
Intent i = getIntent();
final String name = i.getStringExtra("name");
Of course this is assuming the variable was defined as a String before the putExtra was called.
If you want to use other variable types, there are different get***Extra commands you can call like getIntExtra(int, defaultval) but the putExtra will still be used to send it.
Part 2: For calling a method with a variable assigned in a button click, I have found the best way to do this is with a "holder class" this holder can be defined as a final, and a button press assigns a value to one of it's slots. Here is my holder for Integers:
public class holder {
int to;
public void setTo(int to){
this.to = to;
}
public int getTo(){
return to;
}
}
I instantiate my class as final within my on create final holder hold = new holder();
then call my hold.setTo(int); within a list click listener. When I want to get the data, I simply call hold.getTo(); and I have my integer.
Heres a similar post: Pass value outside of public void onClick
Hope this helps!
Mike
This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
How do I pass data between activities in Android?
I have been banging my head across the table for days trying to figure this out. I'm new to both Java and the Android platform and I am writing my second application. In a nutshell, I want the user to enter in some information in the first activity. That activity then takes those inputs and runs a series of mathematical computations and then displays the results in several editTexts in a separate activity. In my mind, the application takes the input, runs the computations and then stores them in some variables. The variables then need to be passed to the second activity which then displays the results. I have most of the application coded and I can get it to work properly if I keep the inputs and displayed results in one activity. Any Ideas on how I can get the displayed results to show up on another activity? Any direction here is much appreciated.
This can be done with use of intent. one of the use of Intent is to pass the data between activities. In your scenario what you need to do is
STEP 1
After taking input from the user, do computation, store result in
the variables
bundle that in the intent which you are using to
start next activity. You can achieve this by below code
Intent intent = new Intent();
intent.putExtra("KeyForResult1", <your variable>);
intent.putExtra("KeyForResult2",<your variable>);
startActivity(this, nextactivity.class);
in the nextactivity you need to get the intent and extract the values in the variable
which can be achieved
variabletype variable = getIntent().getExtras().get("KeyForResult1");
variabletype variable = getIntent().getExtras().get("KeyForResult2");
You can use this:
ActivityOne.class:
//compute the data and get the result here
//suppose results are,
int resultInt=24;
String resultString="abc";
Intent intent=new Intent(getApplicationContext(),ActivityTwo.class);
intent.putExtra("ResultInInteger",resultInt);
intent.putExtra("ResultInString",resultString);
startActivity(intent);
this will open ActivityTwo.class,where you can get the data like:
int resultInt=getIntent().getIntExtra("ResultInInteger");
String resultString=getIntent().getStringExtra("ResultInString");
I was able to figure it out with a mixture of data I had researched. It seems what finally worked was
int resultInt=24;
Intent myIntent = new Intent(CalPalActivity.this, ResultsActivity.class);
myIntent.putExtra("intVariableName", resultInt);
startActivity(myIntent);
in the first activity and
Intent mIntent = getIntent();
int intValue = mIntent.getIntExtra("intVariableName", 0);
in the second. Why it worked like this and kept giving me errors such as "the method getIntExtra(String, int) in the type Intent is not applicable for the arguments (String)" in the second activity I'll never know. Even the Quick-fixes didn't fix it (I just kept getting new errors). All in all, it's an expensive (5 hour +) but well learned lesson. All of your help was much appreciated. I was able to understand and learn a great deal more about the language. Thank you!
You should read up on Intents. You can store extras in an intent, much like URL parameters. If you use that intent to start your next activity, it will be able to extract the data from the intent's extras.
There are several options. For your task I'd choose passing the data in Intent's extras.
For all options read this
Here is an option.
In first Activity:
Intent yourNextActivityIn=new Intent(this,yourNextActivity.class);
yourNextActivityIn.putExtra("tag",valueToBePassed);
startActivity(yourNextActivityIn);
In second Activity:
//If value is an Integer with default value 1
int value = getIntent().getIntExtra("tag", 1);
else
//if value is a string
String value = getIntent().getStringExtra("tag");
In my app I have 5 String arrays that represent different fields of objects.
i.e.
String_A[1],
String_B[1],
String_C[1],
String_D[1],
String_E[1],
All are attributes of the same object (which is not really an object).
Now I want to store those in order to be able to use them in a new activity that I am creating. Since you are not able to pass objects around I thought that i should save them in Shared preferences.
My question is: Should I save them as separate strings or create a new class with all those fields and then serialize the objects?
Which is the best way in terms of memory usage? In fact is there any other way that you might achieve similar functionality?
Thanks in advance
Mike
If each of those String Arrays are big "enough" and it appears you do want to store them - have you considered Sqlite? SharedPreferences is most effective to store primitive data in key-value pairs. Check this link - it has neat comparison about the options you have - http://developer.android.com/guide/topics/data/data-storage.html
You can pass around objects via an intent. The extras function of an intent can store a bundle and send it to specified activities, however they cannot be called at any time (like from a later activity without being explicitly sent). If this is a one time pass to a different activity, the you'd probably want to use that.
http://developer.android.com/reference/android/content/Intent.html#putExtras%28android.content.Intent%29
Here is an example from a test app I made a while back:
public void onClick(View v) {
switch(v.getId()) { //this references the unique ID of the view that was clicked
case R.id.Button01: //this is what happens when the Button in the XML with android:id="#+id/Button01" is clicked
Intent nameGreet = new Intent(this, MainMenu.class);//creates Intent which will send the EditText input
String theName = firstName.getText().toString();// creates a new string named "theName" which is the text from an EditText called "firstName"
nameGreet.putExtra("helloName", theName);//puts the input from EditText into the Intent, this is a key/value pair
this.startActivity(nameGreet);//setting off the Intent
break;
Then you catch it like so:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.setContentView(R.layout.main_menu);
String personsname = this.getIntent().getStringExtra("helloName");
welcome = (TextView)this.findViewById(R.id.TextView01);
welcome.setText(personsname);
Hope this helps.
You can pass a Serializable using an Intent.
Intent.putExtra(String name, Serializable value).