简体   繁体   English

任何人都可以帮助我理解 Android Studio 中的 SharedPreferences

[英]Can anyone please help me understand SharedPreferences in Android Studio

I am building a pokedex app in which the app needs to remember the saved pokemons but the documentation for SharedPreferences is very confusing.我正在构建一个 pokedex 应用程序,该应用程序需要记住保存的 pokemons,但 SharedPreferences 的文档非常混乱。 How do i add that in PokemonActivity.我如何在 PokemonActivity 中添加它。 I know that it needs to be added along with button for "Catch/Release" but how do i do that.我知道它需要与“捕获/释放”按钮一起添加,但我该怎么做。 Is it like a variable for like a function is what i am really confused about.它是不是像一个函数一样的变量,我真的很困惑。

 PokemonActivity.java import androidx.appcompat.app.AppCompatActivity; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.os.AsyncTask; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.ImageView; import android.widget.TextView; import com.android.volley.Request; import com.android.volley.RequestQueue; import com.android.volley.Response; import com.android.volley.VolleyError; import com.android.volley.toolbox.JsonObjectRequest; import com.android.volley.toolbox.Volley; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.io.IOException; import java.net.URL; public class PokemonActivity extends AppCompatActivity { private TextView nameTextView; private TextView numberTextView; private TextView type1TextView; private TextView type2TextView; private String url; private RequestQueue requestQueue; private Button button; ImageView imageView; private TextView pokemondesc; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_pokemon); requestQueue = Volley.newRequestQueue(getApplicationContext()); url = getIntent().getStringExtra("url"); nameTextView = findViewById(R.id.pokemon_name); numberTextView = findViewById(R.id.pokemon_number); type1TextView = findViewById(R.id.pokemon_type1); type2TextView = findViewById(R.id.pokemon_type2); button = findViewById(R.id.catchbutton); imageView = findViewById(R.id.pokemon_image); pokemondesc = findViewById(R.id.pokemon_desc); load(); } public void load() { type1TextView.setText(""); type2TextView.setText(""); JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() { @Override public void onResponse(JSONObject response) { try { pokemonid = response.getInt("id"); String url1 = "https://pokeapi.co/api/v2/pokemon-species/" + pokemonid + "/"; final JsonObjectRequest requestdisc = new JsonObjectRequest(Request.Method.GET, url1, null, new Response.Listener<JSONObject>() { @Override public void onResponse(JSONObject response) { try { JSONArray flavorEntries = response.getJSONArray("flavor_text_entries"); for (int i = 0; i < flavorEntries.length(); i++) { JSONObject description = flavorEntries.getJSONObject(i); String lang = description.getJSONObject("language").getString("name"); if(lang.equals("en")){ String flavorText = description.getString("flavor_text"); pokemondesc.setText(flavorText); break; } } } catch (JSONException e) { Log.e("cs50", "Json error", e); } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { Log.e("cs50", "flavorText list error", error); } }); requestQueue.add(requestdisc); nameTextView.setText(response.getString("name")); numberTextView.setText(String.format("#%03d", response.getInt("id"))); String imgUrl = response.getJSONObject("sprites").getString("front_default"); new DownloadSpriteTask().execute(imgUrl); JSONArray typeEntries = response.getJSONArray("types"); for (int i = 0; i < typeEntries.length(); i++) { JSONObject typeEntry = typeEntries.getJSONObject(i); int slot = typeEntry.getInt("slot"); String type = typeEntry.getJSONObject("type").getString("name"); if (slot == 1) { type1TextView.setText(type); } else if (slot == 2) { type2TextView.setText(type); } } } catch (JSONException e) { Log.e("cs50", "Pokemon json error", e); } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { Log.e("cs50", "Pokemon details error", error); } }); requestQueue.add(request); } public boolean pokemonIsCaught = false; public void toggleCatch(View view) { // gotta catch 'em all! if (!pokemonIsCaught) { pokemonIsCaught = true; button.setText("Release"); } else { pokemonIsCaught = false; button.setText("Catch"); } } private class DownloadSpriteTask extends AsyncTask<String, Void, Bitmap> { @Override protected Bitmap doInBackground(String... strings) { try { URL url = new URL(strings[0]); return BitmapFactory.decodeStream(url.openStream()); } catch (IOException e) { Log.e("cs50", "Download sprite error", e); return null; } } @Override protected void onPostExecute(Bitmap bitmap) { // load the bitmap into the ImageView! imageView.setImageBitmap(bitmap); } } public static int pokemonid = 0; }
EDIT 1: I Changed my code to add that SharedPreferences part like this but it does not seem to work, can anyone please help me point out the issue here. 编辑 1:我更改了我的代码以添加这样的 SharedPreferences 部分,但它似乎不起作用,任何人都可以帮我在这里指出问题。

 package edu.harvard.cs50.pokedex; import androidx.appcompat.app.AppCompatActivity; import android.content.Context; import android.content.SharedPreferences; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.os.AsyncTask; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.ImageView; import android.widget.TextView; import com.android.volley.Request; import com.android.volley.RequestQueue; import com.android.volley.Response; import com.android.volley.VolleyError; import com.android.volley.toolbox.JsonObjectRequest; import com.android.volley.toolbox.Volley; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.io.IOException; import java.net.URL; public class PokemonActivity extends AppCompatActivity { private TextView nameTextView; private TextView numberTextView; private TextView type1TextView; private TextView type2TextView; private String url; private RequestQueue requestQueue; private Button button; ImageView imageView; private TextView pokemondesc; SharedPreferences sharedpreferences; public static final String savedpok = ""; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_pokemon); requestQueue = Volley.newRequestQueue(getApplicationContext()); url = getIntent().getStringExtra("url"); nameTextView = findViewById(R.id.pokemon_name); numberTextView = findViewById(R.id.pokemon_number); type1TextView = findViewById(R.id.pokemon_type1); type2TextView = findViewById(R.id.pokemon_type2); button = findViewById(R.id.catchbutton); imageView = findViewById(R.id.pokemon_image); pokemondesc = findViewById(R.id.pokemon_desc); sharedpreferences = getSharedPreferences(savedpok, Context.MODE_PRIVATE); load(); } public void load() { type1TextView.setText(""); type2TextView.setText(""); JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() { @Override public void onResponse(JSONObject response) { try { pokemonid = response.getInt("id"); String url1 = "https://pokeapi.co/api/v2/pokemon-species/" + pokemonid + "/"; final JsonObjectRequest requestdisc = new JsonObjectRequest(Request.Method.GET, url1, null, new Response.Listener<JSONObject>() { @Override public void onResponse(JSONObject response) { try { JSONArray flavorEntries = response.getJSONArray("flavor_text_entries"); for (int i = 0; i < flavorEntries.length(); i++) { JSONObject description = flavorEntries.getJSONObject(i); String lang = description.getJSONObject("language").getString("name"); if(lang.equals("en")){ String flavorText = description.getString("flavor_text"); pokemondesc.setText(flavorText); break; } } } catch (JSONException e) { Log.e("cs50", "Json error", e); } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { Log.e("cs50", "flavorText list error", error); } }); requestQueue.add(requestdisc); nameTextView.setText(response.getString("name")); numberTextView.setText(String.format("#%03d", response.getInt("id"))); String imgUrl = response.getJSONObject("sprites").getString("front_default"); new DownloadSpriteTask().execute(imgUrl); JSONArray typeEntries = response.getJSONArray("types"); for (int i = 0; i < typeEntries.length(); i++) { JSONObject typeEntry = typeEntries.getJSONObject(i); int slot = typeEntry.getInt("slot"); String type = typeEntry.getJSONObject("type").getString("name"); if (slot == 1) { type1TextView.setText(type); } else if (slot == 2) { type2TextView.setText(type); } } } catch (JSONException e) { Log.e("cs50", "Pokemon json error", e); } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { Log.e("cs50", "Pokemon details error", error); } }); requestQueue.add(request); } public boolean pokemonCaught = false; public void toggleCatch(View view) { SharedPreferences.Editor editor = sharedpreferences.edit(); String name = nameTextView.getText().toString(); // gotta catch 'em all! if (!pokemonCaught) { editor.putString(name, name); editor.apply(); editor.commit(); pokemonCaught = true; button.setText("Release"); } else { editor.remove(name); editor.apply(); editor.commit(); pokemonCaught = false; button.setText("Catch"); } } private class DownloadSpriteTask extends AsyncTask<String, Void, Bitmap> { @Override protected Bitmap doInBackground(String... strings) { try { URL url = new URL(strings[0]); return BitmapFactory.decodeStream(url.openStream()); } catch (IOException e) { Log.e("cs50", "Download sprite error", e); return null; } } @Override protected void onPostExecute(Bitmap bitmap) { // load the bitmap into the ImageView! imageView.setImageBitmap(bitmap); } } public static int pokemonid = 0; }

If you are confusing in shared preference you can include my gist in your project and call your desired function its help you如果您对共享偏好感到困惑,您可以将我的要点包含在您的项目中,并调用您想要的功能来帮助您

Click here and get Shared Preference File In Java 单击此处获取 Java 中的共享首选项文件

In your case在你的情况下

Save value保值

AppPreference.saveData(this, true, "KEY")

Get value获取价值

AppPreference.getSavedData(this, "KEY")

Here's a sample code that can help you get started with SharedPreferences.下面是一个示例代码,可以帮助您开始使用 SharedPreferences。 You can make it your base structure to develop on it further.您可以将其作为基础结构以进一步发展。

private SharedPreferences mPref;
private static final String SETTINGS_NAME = "default_settings";


//Initiate the shared pref
// Here, SETTINGS_NAME is a name for your shared pref
mPref = context.getSharedPreferences(SETTINGS_NAME, Context.MODE_PRIVATE);

Once you have initiated your shared pref, you can get the data like this:启动共享首选项后,您可以获得如下数据:

//Here FieldName is a name for your data, in this case can be pokemon name
//If there is no data with the FieldName, the default value will be returned.
mPref.getString("FieldName", "DefaultValue");
mPref.getBoolean("AnotherFieldName", false);

To set a data, use this code:要设置数据,请使用以下代码:

//We use the Editor class of shared pref to add data
private SharedPreferences.Editor mEditor;
mEditor = mPref.edit();
mEditor.putString("FieldName", YOUR_VALUE);
mEditor.putBoolean("AnotherFieldName", BOOLEAN_VALUE);
mEditor.commit();

Read more at : Android Shared Preferences阅读更多信息: Android 共享首选项

Well in your case, change the code in toogleCatch method to be like this:那么在您的情况下,将toogleCatch 方法中的代码更改为如下所示:

public void toggleCatch(View view) {公共无效toggleCatch(查看视图){

    SharedPreferences pokemonPrefs = getSharedPreferences("pokemon", 0);
    SharedPreferences.Editor editor = pokemonPrefs.edit();

    String name = nameTextView.getText().toString();

    // gotta catch 'em all!
    if (!pokemonCaught) {
        editor.putString("pokemon_name", name);
        pokemonCaught = true;
        button.setText("Release");
    } else {
        editor.putString("pokemon_name", "empty");
        pokemonCaught = false;
        button.setText("Catch");
    }
    editor.apply();

} }

Then call this when you want to get the pokemon name:然后当你想获得 pokemon 名称时调用它:

SharedPreferences pokemonPrefs = this.getSharedPreferences("pokemon", 0); SharedPreferences pokemonPrefs = this.getSharedPreferences("pokemon", 0);

String pokemonName = pokemonPrefs.getString("pokemon_name", "empty"); String pokemonName = pokemonPrefs.getString("pokemon_name", "empty");

Change the hardcoded strings to constant later after you understand it.理解后将硬编码的字符串更改为常量。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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