i am new to Android development. I have two activities A and B. In activity A I use a xml parser to gain objects with each about 10 strings included. I want to pass these objects to activity B and there should be a listview showing all the objects. Clicking on a object in the listview should show the 10 strings.
I am not sure if I have to use a SQLite database or if I only can use SharedPreferences?
Or can I even store it on the internal memory?
The objects should be saved even if i kill the app.
Hope someone can give me some hints, thanks!
this may helps you
you can pass your string data both way as you like [1] Using Intent [2] Using Share Prefrence
like [1] Intent
in your First ActivityA
Intent myintent= new Intent(FirstActivity.this,SecondActivity.class);
myintent.putExtra("Name1", "your String");
myintent.putExtra("Name2", "your String");
myintent.putExtra("Name3", "your String");
myintent.putExtra("Name4", "your String");
startActivity(myintent);
in Second ActivityB
Intent myintent = getIntent();
if(null!=myintent.getExtras()){
String Name1 = myintent.getExtras().getString("Name1");
String Name2 = myintent.getExtras().getString("Name2");
String Name3 = myintent.getExtras().getString("Name3");
String Name4 = myintent.getExtras().getString("Name4");
Toast.makeText(getApplicationContext(),""+Name,12).show();
}
else
{
Toast.makeText(getApplicationContext(),"No Recor Here..",12).show();
}
like SharedPreferences[2]
in your First ActivityA
Intent myintent= new Intent(FirstActivity.this,SecondActivity.class);
SharedPreferences spref = this.getSharedPreferences("mynotifyid", MODE_WORLD_WRITEABLE);
SharedPreferences.Editor spreedit = spref.edit();
spreedit.putString("Name1", str1.toString());
spreedit.putString("Name2", str2.toString());
spreedit.putString("Name3", str3.toString());
spreedit.putString("Name4", str4.toString());
spreedit.commit();
startActivity(myintent);
in your Second ActivityB
SharedPreferences spref = context.getSharedPreferences("mynotifyid", Context.MODE_WORLD_WRITEABLE);
String str1 = spref.getString("Name1","");
String str2 = spref.getString("Name2","");
String str3 = spref.getString("Name3","");
String str4 = spref.getString("Name4","");
for your object saving purpose use SharedPreferences
Let these objects implement the interface Serializable so you can pass the objects to another Activity using an Intent
Maybe this small(!) example can help you:
public class MyModel implements Serializable {
...
}
public A extends Activity {
public void onCreate(Bundle savedInstanceBundle) {
...
//fetchData
...
MyModel data = new MyModel(fetchedData);
Intent intent = new Intent(this, B.class);
intent.putExtra("KEY", data);
startActivity(intent);
}
}
public B extends Activity {
public void onCreate(Bundle savedInstanceBundle) {
Bundle extras = getIntent().getExtas();
MyModel data = (MyModel) extras.getSerializable("KEY");
...
//handle data
...
}
}
For those 10 strings I wouldn't use database.
SharedPreferences easy to use, lot of examples and will deal with your needs.
If a none string need later, than you can use internal memory ( binary mode ), but now no reason, imho.
Related
When Transferring data from one activity to another, can you transfer from one EditText to another EditText of the other Activity
I'm trying to transfer data from EditText of one Activity to EditText of another Activity.
1 ) Way
First activity
Intent i = new Intent(this, ActivityTwo.class);
AutoCompleteTextView textView = (AutoCompleteTextView) findViewById(R.id.autocomplete);
String getrec=textView.getText().toString();
//Create the bundle
Bundle bundle = new Bundle();
//Add your data to bundle
bundle.putString(“data”, getrec);
//Add the bundle to the intent
i.putExtras(bundle);
//Fire that second activity
startActivity(i);
Sceond Activity where you get
//Get the bundle
Bundle bundle = getIntent().getExtras();
//Extract the data…
String stuff = bundle.getString(“data”);
2)Way
public static AutoCompleteTextView textView;
you can access textview with
SceondActivity.textview;
3 Way
Store value in Preference or database
You can send the content of 1st EditText as an intent extra to another activity. In the destination Activity, call getIntent() to extract the intent extras and then you can call setText() on that Activity's EditText
Activity A:
String data=myEditText.getText().toString();
Intent i=new Intent(ActivityA.this,ActivityB.class); //Create Intent to call ActivityB
i.putExtra("editTextKey",data);
startActivity(i);
Activity B:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_b_layout);
EditText newEditText=findViewById(R.id.new_edittext_id); //Get the reference to your edittext
String receivedData = getIntent().getStringExtra("editTextKey");
newEditText.setText(receivedData); //Set the data to new editteext
...
}
Ref : What's the best way to share data between activities?
You can achive this by
Send data inside intent
Static fields
HashMap of WeakReferences
Persist objects (sqlite, share preferences, file, etc.)
TL;DR: there are two ways of sharing data: passing data in the intent's extras or saving it somewhere else. If data is primitives, Strings or user-defined objects: send it as part of the intent extras (user-defined objects must implement Parcelable). If passing complex objects save an instance in a singleton somewhere else and access them from the launched activity.
Some examples of how and why to implement each approach:
Send data inside intents
Intent intent = new Intent(FirstActivity.this, SecondActivity.class);
intent.putExtra("some_key", value);
startActivity(intent);
On the second activity:
Bundle bundle = getIntent().getExtras();
int value = bundle.getInt("some_key");
Intents are used for communication between Activities. You should get the text from EditText using EditText.getText().toString() and create an Intent to wrap up the value to be passed eg;
Intent in = new Intent(FirstActivity.this, TargetActivity.class).putExtra("STRING IDENTIFIER","string value from edittext");
You can retrieve this value and set it in EditText
Option B use shared preferences like this class I use:
class QueryPreferences
{
private static final String TEXT_ID = "2";
static void setPreferences(String text, Context context)
{
PreferenceManager.getDefaultSharedPreferences(context)
.edit()
.putString(TEXT_ID,text)
.apply();
}
static String getPreferences(Context context)
{
return PreferenceManager.getDefaultSharedPreferences(context).getString(TEXT_ID,"");
}
}
So basically I'm trying to pass an EditText String to another fragment which is in the same Activity. Then pass that data to another Activity, depending on which button the pressed. My problem is the application works fine but I just don't see the string being created. I've tried to use a textview just to check if it works when I pass it through the first data, but nothing shows.
I just want to pass the string to another fragment then depending on the button they press pass it on the whichever Activity.
This is my code
Passing my Data to the next Fragment and going to the fragment.
mNextBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(getActivity(), ItemStorageFragment.class);
intent.putExtra("itemName", addName.getText().toString());
((AddInventoryActivity)getActivity()).ToExpiration(null);
}
});
Grabbing the data from my First Fragment
Intent intent = getActivity().getIntent();
value = intent.getStringExtra("itemName");
Then Sending it to the Activity
mToFreezer.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent in = new Intent(getActivity(), FreezerActivity.class);
in.putExtra("itemNameToFreezer", value);
startActivity(in);
}
});
Then Adding it to my RecyclerView
Intent i = getIntent();
String string = i.getStringExtra("itemNameToFreezer");
mDataset.add(string);
mAdapter.notifyDataSetChanged();
Intent extras are fine to share data between Activities, but you cannot use them for Fragments directly, as you did in your code. I assume, you are a beginner, so I recommend you read in depth about Intents here: Android - Intents and Filters
There are several ways of passing data between Activities and Fragments, most common of which is passing arguments. Yet, in your situation I'd recommend using SharedPreferences. You can store String data at any point inside your Fragment or Activity and then easily take it out with these simple steps:
Input data into SharedPreferences:
SharedPreferences.Editor editor = getSharedPreferences("YourPrefsFile", MODE_PRIVATE).edit();
editor.putString("name", "Elena");
editor.putInt("idName", 12);
editor.apply();
Get data from SharedPreferences:
SharedPreferences prefs = getSharedPreferences("YourPrefsFile", MODE_PRIVATE);
String restoredText = prefs.getString("text", null);
if (restoredText != null) {
String name = prefs.getString("name", "");
int idName = prefs.getInt("idName", 0);
}
I am novice programming on Android. I have one question, I have 2 activities. Firs I pass a parameter from the Activity A to the B like this:
Intent intent = new Intent(getBaseContext(), ActivityB.class);
intent.putExtra("ALMACEN_ANTES", almacen.getText().toString());
startActivity(intent);
And now in the activity B y get the extras. Later since the Activity B, I pass parameters to the A too.
My question is, is it possible to pass parameters to another activity without doing
Intent intent = new Intent(getBaseContext(), ActivityB.class) because I don´t want to open 2 times the same activity.
Thank you!
Yes . You can save the value using SharedPreferences
It will be stored in an internal xml file and you can save it and retrive whenever you want. It need not start the activity when value passing.
An example shows below
SharedPreferences sharedpreferences;
Editor editor = sharedpreferences.edit();
editor.putString(Name, n);
editor.putString(Phone, ph);
editor.commit;
you can retrive this value from the activity where you need to access these values. It can be done by:
SharedPreferences sharedpreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
String name=sharedpreferences.getString("Name","");
String ph=sharedpreferences.getString("Phone","");
You want to update a value in the activity A , you mean? because if you don't open it why sending a value to it ?
you can share data between two activities by other ways. In your case the best one would be a Singleton class:
you create a class which is inheriting from Application and containing your data, and from every activity you can update you data or get it...
Your singleton class:
import android.app.Application;
public class MyApplication extends Application {
private String data;
public String getData() {return data;}
public void setData(String data) {this.data = data;}
}
From activity B , you can set your data:
MyApplication app = (MyApplication) getApplicationContext();
app.setData(someData);
And teh Ativity A can have them like this:
MyApplication app = (MyApplication) getApplicationContext();
String data = app.getData();
See this answer
at begining i want to say sorry for my bad english i hope u understand me.
I want to copy one string to another activity so i create :
package com.example.kliker;
import android.app.Application;
public class GlobalClass extends Application{
private String name;
private String email;
public String getName() {
return name;
}
public void setName(String aName) {
name = aName;
}
public String getEmail() {
return email;
}
public void setEmail(String aEmail) {
email = aEmail;
}
}
and in activity to set i use:
final GlobalClass globalVariable = (GlobalClass) getApplicationContext();
globalVariable.setEmail("1");
globalVariable.setName("1");
and when i want get:
final GlobalClass globalVariable = (GlobalClass) getApplicationContext();
a = globalVariable.getEmail();
b = globalVariable.getName();
mTextView.setText(a);
But it doesn't work ? I should refresh activity or something like that ?
http://speedy.sh/dvt94/Desktop.rar
Manifest,activity from i get and set, activity set, activity get
I would like to make one activity outstay data about category and food also i want to make another activity when we are in it and when we click on food it send informations about itself category and chosen food, main activity download that information and by means of them it build graphic sentence
Use Bundle API - http://developer.android.com/reference/android/os/Bundle.html.
In your A Activity -
Intent intent = new Intent(A.this, B.class);
Bundle bundle = new Bundle();
bundle.putString("value", "String Value");
intent.putExtras(bundle);
startActivity(intent);
And, in B Activity -
Intent i = getIntent();
Bundle extras = i.getExtras();
String value = extras.getString("value");
You would be interested in this http://hmkcode.com/android-passing-data-to-another-activities/
You are instantiating your GlobalClass class twice so you are getting different variables. Try something like this in the same activity and see if it works.
final GlobalClass globalVariable = (GlobalClass) getApplicationContext();
globalVariable.setEmail("1");
globalVariable.setName("1");
a = globalVariable.getEmail();
b = globalVariable.getName();
mTextView.setText(a);
I can think of at least three decent choices:
1) Use a singleton (pros - simple; cons - won't persist across application lifetime).
2) Use SharedPreferences (easy enough to research); if you're really using it for something like username for the application (which is what it appears from the example) then SharedPreferences are appropriate.
3) Use an Intent to trigger the next activity from your current one, and pass the string as an extra (intent.putExtra(...), intent.getStringExtra(...)).
i am new developer in android applications.i would like to save the data using shared preference concept.i am saving the data in one activity and get the same data in another activity.here i would like to send the String a[]={"one","two","three"} one activity to another activity.i have written code as follows
Main1.java
public class Main1 extends Activity
{
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
SharedPreferences shp=getSharedPreferences("TEXT", 0);
final Editor et=shp.edit();
((Button)findViewById(R.id.button1)).setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
String s1=((EditText)findViewById(R.id.editText1)).getText().toString();
et.putString("DATA", s1);
String s2[]={"one","two","three"};
//here i would like to save the string array
et.commit();
Intent it=new Intent(Main1.this,Main2.class);
startActivity(it);
}
});
}
Main2.java
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.main2);
String kk=getSharedPreferences("TEXT", 0).getString("DATA", null);
//here i would like to get the string array of Main1.java
((EditText)findViewById(R.id.editText1)).setText(kk);
}
can we get the string array values from Main1.java to Main2.java?
Put it into the starting intent:
Intent it = new Intent(Main1.this,Main2.class);
it.putExtra("MY_STRING_ARRAY", s2);
Get it back in the second activity:
String[] myStringArray = getIntent().getStringArrayExtra("MY_STRING_ARRAY");
If you want to send data from one activity to another then the best way would be send data using Intent object's putExtra method
Intent i = new Intent(Activity1.this, Activity2.class);
i.putExtra("data1", "some data");
i.putExtra("data2", "another data");
i.putExtra("data3", "more data");
startActivity(i);
and you can get the data from receiving activity Activity2 like this
Object data1 = getIntent().getExtras().get("data1");
Hope that helps
If you want to save your information via SharedPreference not just pass it along activities, use some code like this:
SharedPreferences settings = getSharedPreferences(GAME_PREFERENCES, MODE_PRIVATE);
SharedPreferences.Editor prefEditor = settings.edit();
prefEditor.putString("string_preference", "some_string");
prefEditor.putInt("int_preference", 18);
prefEditor.commit();
The commit command is the responsable of actually saving data to SharedPreferences.