0

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.

Rutvik Bhatt
  • 3,185
  • 1
  • 16
  • 28
shalini negi
  • 5
  • 1
  • 1
  • 5

6 Answers6

0

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)

just
  • 1,900
  • 4
  • 25
  • 46
0
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

  • Shahnavaz , You mean to say that I add this code to my MainActivity to get the access of the data stored in sharedpreferences. After this how do I display this data to user !! – shalini negi Mar 22 '19 at 13:31
  • Yes and depends on how do you want to display it. You can use a Toast.makeText(this,"This is your data" + task,Toast.LENGTH_SHORT).show(); or you could use a TextView to display it [link](https://developer.android.com/reference/android/widget/TextView) – Shahnawaz Ansari Mar 22 '19 at 13:33
0

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, "");
Kristiyan Varbanov
  • 2,439
  • 2
  • 17
  • 37
  • what if our sharedpreferences contain more than one data, then what will be the string in yourValue ? Basically, I want to know how prefs.getString(PREF_NAME, "") works – shalini negi Mar 22 '19 at 13:48
0

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.

0

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();
Abhinav Gupta
  • 2,225
  • 1
  • 14
  • 30
0

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", "");
Gourav
  • 2,746
  • 5
  • 28
  • 45