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.
Related
I'm developing an app where I have many activites. And when the user ends interacting with the content of each activity it launchs an Activity called WellDone! where the user can see the average of the lessons (it's a course). 100% completed and it has a button for the next lesson. I want to get the name of the previous activities for example activity_lesson1, activity_lesson2 to show in a TextView to have a Title.
When ends the lesson1 it launchs the WellDone! Activity and I want to set in a TextView (title) the name of the lessons that have just learned.
package com.flixarts.ar.**;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;
public class welldone extends AppCompatActivity {
private TextView title;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_pantallanextsesion);
title = (TextView)findViewById(R.id.tituloActivity);
title.setText() //Here the title of the previous activity that have come from intent
}
}
My impression is that the answer to the literal question is "no" - you cannot get the name of previous activity. But there's probably another way to accomplish what you need.
If these are all your activities, why not put an extra in the Intent (when going in the forward direction) which says which activity it is coming from.
You can then decide what name of the activity to display based on checking that extra, which should tell you what the previous activity was.
Maybe you could use SharedPreferences, which allow you to easily save some String value in one activity and read it in another. In previous activity e.g activity_lesson1 you could override method onPause (or onDestroy if you finish your activity while proceeding to next one by calling finish() method) and save the name of activity as String like this:
#Override
public void onPause() {
super.onPause();
SharedPreferences sharedPref = this.getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putString("LAST_ACTIVITY_NAME", this.getClass().getSimpleName());
editor.apply();
}
Then you can read saved value inside WellDone activity like this:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
SharedPreferences sharedPref = this.getPreferences(Context.MODE_PRIVATE);
String lastActivityName = sharedPref.getString("LAST_ACTIVITY_NAME", "default_value");
title.setText(lastActivityName);
}
Two ways to pass previous activity name
Use Intent
FirstActivity
String TAG=FirstActivity.class.getSimpleName();
submitBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
name=nameEt.getText().toString();
mobile_number=mobileEt.getText().toString();
Intent intent=new Intent(FirstActivity.this,SecondActivity.class);
intent.putExtra("Last_Activity_Name",TAG);
startActivity(intent);
}
});
SecondActivity
String lastActivityName;
lastActivityName=getIntent().getStringExtra("Last_Activity_Name");
**use SharedPreferences **
FirstActivity
SharedPreferences sharedPref = this.getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putString("Last_Activity_Name", TAG);
editor.apply();
SecondActivity
SharedPreferences sharedPref = this.getPreferences(Context.MODE_PRIVATE);
String lastActivityName = sharedPref.getString("Last_Activity_Name",
"default_value");
title.setText(lastActivityName);
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 have an app that on the first activity asks the persons name on the second page it displays the name in a sentence i want to use the name in the third fourth or 9th activity how do i properly declare it (public?) and call it when and where ever i need it? this is my code sending it
Main
public class MainActivity extends Activity {
Button ok;
EditText name;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
name=(EditText)findViewById(R.id.editText);
Typeface font_a = Typeface.createFromAsset(getAssets(),"fonts/MarkerFelt.ttf");
name.setTypeface(font_a);
ok=(Button)findViewById(R.id.button);
Typefacefont_b=Typeface.createFromAsset(getAssets(),
"fonts/SignPaintersGothicShaded.ttf");
ok.setTypeface(font_b);
ok.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
String nameStr = name.getText().toString();
Intent intent = new Intent(getApplicationContext(), SecondActivity.class);
intent.putExtra("NAMEDATA",nameStr);
startActivity(intent);
}
});
}
and this is activity 2 receiving it
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
t = (TextView)findViewById(R.id.textView3);
Typeface font_b = Typeface.createFromAsset(getAssets(),"fonts/MarkerFelt.ttf");
t.setTypeface(font_b);
String n = this.getIntent().getStringExtra("NAMEDATA");
t.setText(n);
so please how would i reuse this?
Use SharedPreferences to save the name or whatever variable you need, then read whenever you need it. First, create global in MainActivity which will be used as preference file name:
public static final String PREFS_NAME = "MyPrefsFile";
Then, to save:
SharedPreferences settings = getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = settings.edit();
editor.putString("name", name);
editor.commit();
to load:
SharedPreferences settings = getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
String name = settings.getString("name", "John");
Once saved, the prefs are accessible for every activity.
So in your case, save the name when ok button is pressed:
ok.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
String nameStr = name.getText().toString();
SharedPreferences settings = getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = settings.edit();
editor.putString("name", nameStr);
editor.commit();
Intent intent = new Intent(getApplicationContext(), SecondActivity.class);
startActivity(intent);
}
});
Then read it:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
t = (TextView)findViewById(R.id.textView3);
Typeface font_b = Typeface.createFromAsset(getAssets(),"fonts/MarkerFelt.ttf");
t.setTypeface(font_b);
SharedPreferences settings = getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
String n = settings.getString("name", "defaultName");
t.setText(n);
You can do similarly in every activity you need it. See docs here.
You have a number of different approaches to share data between activities. I would say which one you use depends on the ultimate source and destination of the data.
Pass through intents - This is the method you are currently using. To proceed, just keep passing the name to the next intent.
Save to SharedPreference - This method you save the information to the "preference" file of the application. This is useful if the the user is setting up a profile or other semi-fixed information.
Write it to a DB - Here you would create a a new SQLite table for user information and write new rows to it for the name, password, and other info. This has way more overhead and is really only useful if you have multiple users in the same application
Save to a singleton - In this case you create a static class with public properties that can be set. This would be least favorable all the information is lost on application close, but could be useful for temporary creation and retention across many activities. Be warned: bad programming can make singletons a nightmare
Create class extending from Application class.
Implement setter and getter inside that class like,
public class GlobalClass extends Application {
//create setters and getters here
public void setUserInfo(String userInfo) {
}
public void getUserInfo() {
return userInfo;
}
}
then you can use this from any activity like,
GlobalClass app = (GlobalClass ) getApplication();
app.getUserInfo();
hi all i am new to android development my question is that how to call input edit text data in any activity where i required just like local storage in hmtl5 how to set value and get them where i required in any activity but not in the intent activity where i mentioned in the below example i want to show in some other activity means i need to get the values
here is my code
public class Autoinput extends Activity {
EditText Engines, Drivers;
Button next;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.autoinputvalues);
Engines = (EditText) findViewById(R.id.noofengines);
Drivers = (EditText) findViewById(R.id.noofdrivers);
next = (Button) findViewById(R.id.autoinputnext);
next.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent autoinputscreen = new Intent (getApplicationContext(), autocoverage.class);
startActivity(autoinputscreen);
}
});
}
}
if we write put extra in intent it will go to that particular activity which we mention intent and there only we can get it my intention is to call in any activity and show them.
You should use shared preference. You should refer this link
You can do this in two ways, one is using Bundle and the another one throught Intent.
Using Bundle,
To Send:
Intent passIntent = new Intent(CurrentActivity.this, SecondActivity.class);
Bundle bundle = new Bundle();
bundle.putString("Key", "Value");
passIntent.putExtras(bundle);
startActivity(passIntent);
To Receive:
Bundle bundle = getIntent().getExtras();
String recText = bundle.getString("Key");
Using Through Intent:
To Send:
Intent passIntent = new Intent(CurrentActivity.this, SecondActivity.class);
passIntent.putExtras("Key", "Value");
startActivity(passIntent);
To Receive:
String recText = getIntent().getExtras().getString("Key");
For your Code, in your FirstActivity
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Log.d(TAG, "clicked on item: " + position);
Intent passIntent = new Intent(CurrentActivity.this, SecondActivity.class);
passIntent.putExtras("Key", position);
startActivity(passIntent);
}
});
In SecondActivity,
details.setText(getIntent().getExtras().getString("Key"));
If you want the data to be destroyed after your application is closed or crashed you can use something like global variables: For example refer to this
On the other hand if you want your data to be persisted even after application crash, you can use shared preferences:
SharedPreferences pref;
pref=context.getSharedPreferences(PREF_NAME, PRIVATE_MODE);
editor=pref.edit();
Set data:
editor.putString("Engines", Engines.getText().toString());
editor.putString("Drivers", Drivers.getText().toString());
Then retrieve from anywhere:
String engines=pref.getString(("Engines",null);
String drivers=pref.getString(("Drivers",null);
if you want save your data and required in any activity must use Database or Share preference
To obtain shared preferences, use the following method In your activity:
SharedPreferences prefs = this.getSharedPreferences(
"com.example.app", Context.MODE_PRIVATE);
To read preferences:
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
Vboolean IsTurnOn = preferences.getBoolean("Key", Default_Value);
To edit and set preferences
Editor editor = preferences.edit();
editor.putBoolean("Key", Value);
editor.commit();
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.