简体   繁体   中英

How to pass sharedpreferences from one activity to another activity?

I have two activities in my project one activity is MainActivity and another is Main2activity, In Main2activity I'm taking input from the user and storing it in SharedPreference, Now I want to pass this data to MainActivity and display that data to the user.

The code for Main2activity is

 package com.example.to_doapp;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.EditText;
import java.io.Serializable;
import java.util.ArrayList;
public class Main2Activity extends AppCompatActivity {




public void BackMain ( View view )
{
    Intent intent = new Intent( getApplicationContext() ,MainActivity.class ) ;
    SharedPreferences sharedPreferences = this.getSharedPreferences( "com.example.to_doapp;", Context.MODE_PRIVATE);
    EditText editText = ( EditText) findViewById( R.id.editText3) ;
    String s = editText.getText().toString();
    sharedPreferences.edit().putString("task" , s ) .apply();

    //intent.putStringArrayListExtra("key",arr);
    startActivity(intent);



}

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main2);
    Toolbar toolbar = findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    FloatingActionButton fab = findViewById(R.id.fab);
    fab.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                    .setAction("Action", null).show();
        }
    });
}

}

code foe Mainactivity is

package com.example.to_doapp;

import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import java.io.Serializable;
import java.util.ArrayList;

public class MainActivity extends AppCompatActivity {


public void onclick (View view){

    Intent intent = new Intent(getApplicationContext(), Main2Activity.class );
    startActivity(intent);
}

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Toolbar toolbar = findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    FloatingActionButton fab = findViewById(R.id.fab);
    fab.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                    .setAction("Action", null).show();
        }
    });

    Intent intent = getIntent();


 }

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_main, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) {
        return true;
    }

    return super.onOptionsItemSelected(item);
}

}

I want to know how to pass sharedpreferences and how to display that data to user in listview. Thank you for help in advance.

You can use SharedPreferences getString() method in your second activity. Here is the documentation: https://developer.android.com/reference/android/content/SharedPreferences.html#getString(java.lang.String,%20java.lang.String)

SharedPreferences sharedPreferences = this.getSharedPreferences( "com.example.to_doapp;", Context.MODE_PRIVATE);
sharedPreferences.getString("task", "");

You can use the above code to get the data from shared preference any time until it is cleared. But i would suggest you create a class for the same and carry out all the Preference related task in the same

The simplest way is:

Set SharedPref:

SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getContext());
Editor editor = prefs.edit();
editor.putString(PREF_NAME, "someValue");
editor.commit();

Get SharedPref:

SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getContext());
String yourValue = prefs.getString(PREF_NAME, "");

No need to pass SharedPreferences . you get any activity or fragment on SharedPreferences value..

SharedPreferences shared = getSharedPreferences("Your SharedPreferences name", MODE_PRIVATE);
String data= shared.getString("key", "");

Note : key should be same as edit or save data time used. also SharedPreferences name same.

I am sharing you easiest way to set and get sharedpreference data :

First make a class for Shared Preference like that :

public class MySharedPreferences {

private static String MY_PREFS = "MyPrefs";
private static String IS_LOGGED_IN = "is_logged_in";
private static String USERNAME_ID = "username"

public static MySharedPreferences instance;
private Context context;
private SharedPreferences sharedPreferences;
private SharedPreferences.Editor editor;


public static MySharedPreferences getInstance(Context context) {
    if (instance == null)
        instance = new MySharedPreferences(context);
    return instance;
}

private MySharedPreferences(Context context) {
    this.context = context;
    sharedPreferences = context.getSharedPreferences(MY_PREFS, Context.MODE_PRIVATE);
    editor = sharedPreferences.edit();
}

public void deleteAllSharePrefs(Context context){
    this.context = context;
    sharedPreferences = context.getSharedPreferences(MY_PREFS,Context.MODE_PRIVATE);
    editor.clear().commit();
}

public Boolean getIsLoggedIn(boolean b) {
    return sharedPreferences.getBoolean(IS_LOGGED_IN, false);
}

public void setIsLoggedIn(Boolean isLoggedIn) {
    editor.putBoolean(IS_LOGGED_IN, isLoggedIn);
    editor.commit();
}


public String getUsername() {
    return sharedPreferences.getString(USERNAME_ID, "");
}

public void setUsername(String username) {
    editor.putString(USERNAME_ID, username);
    editor.commit();
}

then where you want to set SharedPreference :

public void BackMain ( View view ){
EditText editText = ( EditText) findViewById( R.id.editText3) ;
MySharedPreferences.getInstance(Main2Activity.this).setUsername(editText.getText().toString());
Intent intent = new Intent( getApplicationContext() ,MainActivity.class ) 
startActivity(intent);
}

Now, get SharedPreference in your Second Activity:

MySharedPreferences.getInstance(ACTIVITYNAME.this).getUsername();

or in Fragment :

MySharedPreferences.getInstance(getActivity()).getUsername();

or in Adapter :

MySharedPreferences.getInstance(context).getUsername();

When you add a shared preference for the app, it can be accessed from anywhere within the app.

SharedPreferences shared = PreferenceManager.getDefaultSharedPreferences(getContext());
String data= shared.getString("nameOfValue", "");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM