Как передать общие предпочтения из одного занятия в другое? - PullRequest
0 голосов
/ 22 марта 2019

У меня есть два действия в моем проекте, одно из которых - MainActivity, а другое - Main2activity. В Main2activity я беру информацию от пользователя и сохраняю ее в SharedPreference. Теперь я хочу передать эти данные в MainActivity и отобразить эти данные вuser.

Код для Main2activity -

 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 Mainacctivity -

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хотите знать, как передавать разделяемые предпочтения и как отображать эти данные пользователю в виде списка.Заранее спасибо за помощь.

Ответы [ 6 ]

0 голосов
/ 22 марта 2019

При добавлении общего предпочтения для приложения к нему можно получить доступ из любого места в приложении.

SharedPreferences shared = PreferenceManager.getDefaultSharedPreferences(getContext());
String data= shared.getString("nameOfValue", "");
0 голосов
/ 22 марта 2019

Я делюсь с вами самым простым способом установить и получить sharedpreference данные:

Сначала создайте класс для Shared Preference вот так:

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();
}

тогда, где вы хотите установить 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);
}

Теперь получите SharedPreference во втором упражнении:

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

или во фрагменте:

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

или в адаптере:

MySharedPreferences.getInstance(context).getUsername();
0 голосов
/ 22 марта 2019

Нет необходимости передавать SharedPreferences. Вы получаете любую активность или фрагмент по значению SharedPreferences ..

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

Примечание: ключ должен совпадать с используемым временем редактирования или сохранения данных. также имя SharedPreferences так же.

0 голосов
/ 22 марта 2019

Самый простой способ:

Установить SharedPref:

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

Получить SharedPref:

SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getContext());
String yourValue = prefs.getString(PREF_NAME, "");
0 голосов
/ 22 марта 2019
SharedPreferences sharedPreferences = this.getSharedPreferences( "com.example.to_doapp;", Context.MODE_PRIVATE);
sharedPreferences.getString("task", "");

Вы можете использовать приведенный выше код для получения данных из общих настроек в любое время, пока они не будут очищены.Но я бы посоветовал вам создать класс для одного и того же и выполнить все задачи, связанные с настройками, в одном

0 голосов
/ 22 марта 2019

Вы можете использовать метод SharedPreferences getString() во втором упражнении. Вот документация: https://developer.android.com/reference/android/content/SharedPreferences.html#getString(java.lang.String,%20java.lang.String)

...