I am trying to pass some data to another activity, but I need pass the data when I click in a button , but not start the new activity and when i have multiple past data, launch the new activity and see all the content that I have passed before.
The process is similar to a shopping cart, add products and then another activity you see the list of the cart.
I have been trying with SharePrerences, but I only pass one data.
final SharedPreferences mSettings = this.getSharedPreferences(PREFS_NAME, 0);
SharedPreferences.Editor editor = mSettings.edit();
editor.putString(NOMBRE_TAG, tvNotas.getText().toString());
editor.putString(PRECIO_TAG, pantalla.getText()+"");
editor.commit();
with putExtra I do not think it works, because I dont know how much data I will pass
Intent intent = new Intent(this, NAME.class);
intent.putextra("SOMETHING","value");
startActivity(intent);
String data = getIntent().getExtras().getString("SOMETHING");
And i dont know other forms to do it.
The process is similar like
when you use shared preference every "key" like your tags(NOMBRE_TAG,PRECIO_TAG)
will save only one item.
which mean, everytime you save item with this keys it will replace the old items.
i recommender using SQLITE database.
here some example how to start:
Android SQLite Example
You could use a static class, or singleton? This way you can put whatever you want in it from the first activity and retrieve it from the second activity. The only drawback is that it will not survive an application restart.
Use putParcelableArrayList to pass all the data as a array list ---
#Override
public void onSaveInstanceState(final Bundle outState) {
outState.putParcelableArrayList("data", myData);
super.onSaveInstanceState(outState);
}
Then to get this data just use ----
ArrayList<String> myData = new ArrayList<String>();
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState)
{
super.onCreateView(inflater, container, savedInstanceState);
if (savedInstanceState != null) {
try
{
myData = savedInstanceState.getParcelableArrayList("data");
}
}
myData.add(0, tvNotas.getText().toString());
myData.add(1, pantalla.getText()+"");
}
Related
I am trying to find best way to show textview we have clicked on first and second activity, in third one.
Like i have three activities AccountFrom, AccountTo and transferDetails.
I want to know that on what accounttype user has clicked so that i can show in third activity.
1. on AccountFrom Activity
Intent intent = new Intent(AccountFrom.this, AccountTo.class);
**intent.putExtra("accounttype","accountTypeVariable");**
startActivity(intent);
2. Receive intent on AccountTo Activity
Intent intent = getIntent();
if (intent != null)
{
String accountTypeValue = intent.getStringExtra("accounttype")
}
Consider using a view model.
You create the view model in the first Activity and then it is accessible in all activities that you open from it.
Here is simple workflow:
Create view model class that extends ViewModel and has the values you need to keep around
public class MyViewModel extends ViewModel {
private String value1 = "";
private boolean isValue2 = false;
// ...
}
In the first activity create your view model class member
private MyViewModel viewModel;
In the OnCreate you can get the view model like this:
viewModel = ViewModelProviders.of(this).get(MyViewModel.class);
You can do it also in the activities that are launched from this activity - they will share the same view model object. You can set the values in the activities and access them in other activities from the same 'launch-chain'.
When the initial activity (your first one) gets destroyed then the view model also does.
PS. using view model is also good when you need to handle screen orientation changes.
Save the text from TextView on sharedPreferences when it is clicked. Then read it on your third activity.
Call this on your first activity where the user chooses the account type.
void saveText(String stringFromTextView)
{
SharedPreferences sharedpreferences = getSharedPreferences("account", Context.MODE_PRIVATE);
Editor editor = sharedpreferences.edit();
editor.putString("account_type", stringFromTextView);
editor.commit();
}
And on your third activity, call this on onCreate() to get the account type.
String getAccountType()
{
SharedPreferences sharedpreferences = this.getSharedPreferences("account", Context.MODE_PRIVATE);
String accountType = sharedpreferences.getString("account_type", null);
return accountType;
}
i have a spinner and a button for registration. the spinner works as...
typeofcompany.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
ba = typeofcompany.getSelectedItem().toString();
typeofcompany.getItemAtPosition(i);
sss = companycode.get(i);
SelectType(companycode.get(i));
sessionmanager.tosaveRegionName(sss);
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
when i select an item of the spinner,that item should be passed inside the button's Activity.
i have used the bundle method for the same
like
Intent intent = new Intent(MainActivity.this, CustRegActivity.class);
intent.putExtra("spinneritem", abc);
startActivity(intent);
but this startActivity(intent) is directly getting me inside the the second activity. i just want to send the data withour intent how can i do that....
You can make use of shared preferences. In my case i usually use TinyDB which is very easy to use.
go ahead and sync this statement in your gradle
compile 'com.mukesh:tinydb:1.0.1'
Usage is quite simple.
Just create a new instance of tinyDB and pass the application context. This way
TinyDB tinyDB = new TinyDB(getApplicationContext());
initiate it in the onCreate, then store data this way :
tinyDB.putString("spinneritem", abc);
You can retrieve this string from any activity in the app. In the activity you want to get the data declare a new instance of TinyDB once more just as shown above and retrieve the data stored in the following way:
tinyDB.getString("spinneritem");
You can store all variable types this way, whether its int,boolean or even arrays and objects.
you can add a method to the second activity like this
public void setSpinnerItem(String abc){
.....
}
to set a variable(or static variable) to save the content,
then call it in onItemSelected in the first activity
or better
add a observer interface in first activity with a method called onSpinnerItemSelected(String abc), then set the observer in the second activity.
you can also save the data in the first activity in sp, sqlitedb, or simply in a data class's instance variables, then get them in the second activity
new to droid programming. im having a small problem that im sure is simply fixed but ive done some searching and a bunch of tutorials but cant seem to find just what i need so i figured id ask. My app has 2 activites, the first activity is just a simple form where a user enters course information(class title, professor..etc.)
the first activity passes the data which is supposed to be stored in a list in the second activity. problem is that only the first course gets stored in the list, after the first time nothing new gets added to the second activity. Can someone point me in the right direction please? thanks in advance
First Activity
public class CourseDetail extends Activity {
//Course c = new Course();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button save=(Button)findViewById(R.id.save);
save.setOnClickListener(onSave);
}
private View.OnClickListener onSave=new View.OnClickListener() {
public void onClick(View v) {
EditText course=(EditText)findViewById(R.id.course);
EditText professor=(EditText)findViewById(R.id.professor);
EditText location=(EditText)findViewById(R.id.location);
EditText officehrs=(EditText)findViewById(R.id.officehrs);
Intent i=new Intent(CourseDetail.this, CourseList.class);
i.putExtra("myCourse", course.getText().toString());
i.putExtra("myProfessor", professor.getText().toString());
i.putExtra("myLocation", location.getText().toString());
i.putExtra("myOfficehrs", officehrs.getText().toString());
startActivity(i);
}
};
}
Second Activity
public class CourseList extends Activity {
Button btnCourse;
List<Course> model = new ArrayList<Course>();
CourseAdapter adapter=null;
private String dCourse="";
private String dProfessor="";
private String dLocation="";
private String dOfficehrs="";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.clist);
ListView list =(ListView)findViewById(R.id.courses);
adapter=new CourseAdapter();
list.setAdapter(adapter);
Course c = new Course();
Bundle extras = getIntent().getExtras();
dCourse = extras !=null ? extras.getString("myCourse") :"no value entered";
dProfessor = extras !=null ? extras.getString("myProfessor") :"no value entered";
dLocation = extras !=null ? extras.getString("myLocation") :"no value entered";
dOfficehrs = extras !=null ? extras.getString("myOfficehrs") :"no value entered";
c.setCourse(dCourse);
c.setProfessor(dProfessor);
c.setLocation(dLocation);
c.setOfficeHrs(dOfficehrs);
btnCourse =(Button)findViewById(R.id.btnCourse);
btnCourse.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
finish();
}
});
}
You are just getting the user entered value in CourseDetail activity and displaying the received value inside the CourseList activity, that means you are not storing these values permanently.
Go through this Android - Data Storage document.
When you move to 2nd activity i.e. CourseList activity, at that time fetch the data from the SQLite table and display the same. whenever you get new values from previous activity, at that time just update the list by adding the new data in ArrayList and make a call on adapter.notifyDataSetChanged()
Some suggestions:
Have your CourseList extend ListActivity instead of just Activity - check out some tutorials on that which should help you set things up correctly.
There seems to be a bit of confusion with how you're handling your lists - you have your model variable but don't seem to be doing anything with it. Again, have a look at a ListView tutorial (just google "android listview tutorial").
You seem to have figured out that you can use "intents" to pass information from one activity to another, but since you're only doing this in the onCreate() method, it's only happening once. Try doing this in your ListActivity's adapter once for each item.
Don't give up on Android, keep trying :-)
Some suggestion:
You have to add your object to the adapter: adapter.add(c); after you get the data.
Call adapter.notifyDataSetChanged() to notify the system that your data for the listView has been changed. Call list.invalidate() to refresh it.
I noticed that you set the button with the finish() method. Hmm, if you do so, the next time you get to CourseList Activity from CourseDetail, the adapter will be null again. No previously received data will be available. Is this what you really want?
The problem is you are not adding the newly added items to the List.So before setting adapter you have to add all your objects like
list.add(c);
My java skills are not strong. Only been programming in it for a month or 2 so forgive my stupidness.
I'm trying to pass values between methods in a bundle to allow me to save and load some game settings but although I think my values are transferring, I can't get a value out of the 'on create method' to use in the rest of my programme.
I'm loading and bundling up my boolean value here (I've snipped out lots or hopefully irrelevant stuff) :
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
vV = new VortexTouch(this);
CONTEXT = this;
// LOAD DATA
SharedPreferences settings = getSharedPreferences("GAME_DATA",MODE_PRIVATE);
_dPad = settings.getBoolean("GamePad", true);
// PASS DATA
intent = new Intent();
intent.setClass(this,VortexRenderer.class);
intent.putExtra("my_data", true); // should be _dPad but put 'true' in there for now.
startActivity(intent);
// PASS DATA END
setContentView(vV);
}
The boolean value is then received in my VortexRenderer class:
public class VortexRenderer extends Activity implements GLSurfaceView.Renderer {
private static final String LOG_TAG = VortexRenderer.class.getSimpleName();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Bundle bundle = getIntent().getExtras();
_dPad = bundle.getBoolean("my_data");
_dPad = true; // testing to see if value carries, it doesn't :-(
finish();
}
public boolean _dPad;
public void SomeGameAction(){
//try to do something with _dPad but it has not taken on a value of true. why?
}
so i think the value of _dPad is getting from one activity to the other but it's not getting out of the VortexRenderer 'onCrate' method.. Clearly I'm not understanding something.. can anyone help? Thanks.
My game was built around this excellent tutorial if that helps (not that there's much left of the original now):
http://www.droidnova.com/android-3d-game-tutorial-part-i,312.html
Less helpful but if you're interested this is what I'm trying to add the code to:
https://market.android.com/details?id=com.clockworkrobot.spacewarz
In the first activity, instead of
intent.putExtra("my_data", true);
use
Bundle bundle = new Bundle();
bundle.putBoolean("my_data", true);
intent.putExtra("android.intent.extra.INTENT", bundle);
Then in the second activity, instead of
Bundle bundle = getIntent().getExtras();
use
Bundle bundle = getIntent().getBundleExtra("android.intent.extra.INTENT");
I have to be honest... I'm not sure what you're truly trying to do here.
Calling finish in your onCreate will end your activity as soon as you start it.
You do appear to be passing/receiving the boolean with the intent properly, but then hardcoding _dPad to true I hope is just for debug because it certainly makes it unnecessary to pass it with the intent.
What is the overall purpose of your VortexRenderer activity? I imagine there will be a better way to accomplish your goal without creating a new activity.
I also recommend using the Log.v(tag, message); utility and logcat to help yourself debug challenges.
Code indentation will also most certainly help code readability.
The best way that works for me every time is that you use Global Static class to hold your temporary data. Use setters and getters it will be much more easy and understandable.
I'm confused when it comes down to saving a state. So I know that onSaveInstanceState(Bundle) is called when the activity is about to be destroyed. But how do you store your information in it and bring it back to its original state in onCreate(Bundle savedInstanceState)? I don't understand how this bundle will restore information. It would be helpful if someone can provide an example.
The Dev guide doesn't do a good job of explaining this.
public class Conversation extends Activity {
private ProgressDialog progDialog;
int typeBar;
TextView text1;
EditText edit;
Button respond;
private String name;
private String textAtView;
private String savedName;
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.dorothydialog);
text1 = (TextView)findViewById(R.id.dialog);
edit = (EditText)findViewById(R.id.repsond);
respond = (Button)findViewById(R.id.button01);
if(savedInstanceState != null){
savedInstanceState.get(savedName);
text1.setText(savedName);
}
else{
text1.setText("Hello! What is your name?");
respond.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
name = edit.getText().toString();
text1.setText("Nice to meet you "+ name);
}
});
}
}
#Override
public void onSaveInstanceState(Bundle outState){
super.onSaveInstanceState(outState);
outState.putString(savedName, name);
}
}
The Bundle is a container for all the information you want to save. You use the put* functions to insert data into it. Here's a short list (there are more) of put functions you can use to store data in the Bundle.
putString
putBoolean
putByte
putChar
putFloat
putLong
putShort
putParcelable (used for objects but they must implement Parcelable)
In your onCreate function, this Bundle is handed back to the program. The best way to check if the application is being reloaded, or started for the first time is:
if (savedInstanceState != null) {
// Then the application is being reloaded
}
To get the data back out, use the get* functions just like the put* functions. The data is stored as a name-value pair. This is like a hashmap. You provide a key and the value, then when you want the value back, you give the key and the function gets the value. Here's a short example.
#Override
public void onSaveInstanceState(Bundle outState) {
outState.putString("message", "This is my message to be reloaded");
super.onSaveInstanceState(outState);
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (savedInstanceState != null) {
String message = savedInstanceState.getString("message");
Toast.makeText(this, message, Toast.LENGTH_LONG).show();
}
}
Your saved message will be toasted to the screen.
One major note that all new Android developers should know is that any information in Widgets (TextView, Buttons, etc.) will be persisted automatically by Android as long as you assign an ID to them. So that means most of the UI state is taken care of without issue. Only when you need to store other data does this become an issue.
From Android Docs:
The only work required by you is to
provide a unique ID (with the
android:id attribute) for each widget
you want to save its state. If a
widget does not have an ID, then it
cannot save its state
A good information: you don't need to check whether the Bundle object is null into the onCreate() method. Use the onRestoreInstanceState() method, which the system calls after the onStart() method. The system calls onRestoreInstanceState() only if there is a saved state to restore, so you do not need to check whether the Bundle is null
Store information:
static final String PLAYER_SCORE = "playerScore";
static final String PLAYER_LEVEL = "playerLevel";
#Override
public void onSaveInstanceState(Bundle savedInstanceState) {
// Save the user's current game state
savedInstanceState.putInt(PLAYER_SCORE, mCurrentScore);
savedInstanceState.putInt(PLAYER_LEVEL, mCurrentLevel);
// Always call the superclass so it can save the view hierarchy state
super.onSaveInstanceState(savedInstanceState);
}
If you don't want to restore information in your onCreate-Method:
Here are the examples: Recreating an Activity
Instead of restoring the state during onCreate() you may choose to implement onRestoreInstanceState(), which the system calls after the onStart() method. The system calls onRestoreInstanceState() only if there is a saved state to restore, so you do not need to check whether the Bundle is null
public void onRestoreInstanceState(Bundle savedInstanceState) {
// Always call the superclass so it can restore the view hierarchy
super.onRestoreInstanceState(savedInstanceState);
// Restore state members from saved instance
mCurrentScore = savedInstanceState.getInt(PLAYER_SCORE);
mCurrentLevel = savedInstanceState.getInt(PLAYER_LEVEL);
}
Basically onSaveInstanceState(Bundle outBundle) will give you a bundle.
When you look at the Bundle class, you will see that you can put lots of different stuff inside it. At the next call of onCreate(), you just get that Bundle back as an argument.
Then you can read your values again and restore your activity.
Lets say you have an activity with an EditText. The user wrote some text inside it.
After that the system calls your onSaveInstanceState().
You read the text from the EditText and write it into the Bundle via Bundle.putString("edit_text_value", theValue).
Now onCreate is called. You check if the supplied bundle is not null. If thats the case,
you can restore your value via Bundle.getString("edit_text_value") and put it back into your EditText.
This is for extra information.
Imagine this scenario
ActivityA launch ActivityB.
ActivityB launch a new ActivityAPrime by
Intent intent = new Intent(getApplicationContext(), ActivityA.class);
startActivity(intent);
ActivityAPrime has no relationship with ActivityA.
In this case the Bundle in ActivityAPrime.onCreate() will be null.
If ActivityA and ActivityAPrime should be the same activity instead of different activities,
ActivityB should call finish() than using startActivity().
If Data Is not Loaded From savedInstanceState use following code.
The problem is url call is not to complete fully so, check if data is loaded then to show the instanceState value.
//suppose data is not Loaded to savedInstanceState at 1st swipe
if (savedInstanceState == null && !mAlreadyLoaded){
mAlreadyLoaded = true;
GetStoryData();//Url Call
} else {
if (listArray != null) { //Data Array From JsonArray(ListArray)
System.out.println("LocalData " + listArray);
view.findViewById(R.id.progressBar).setVisibility(View.GONE);
}else{
GetStoryData();//Url Call
}
}