如何在Android应用程序创建时只创建一次变量?

huangapple go评论74阅读模式
英文:

How to create a variable only once when app is created in Android?

问题

我正在创建一个安卓应用程序。在我的应用程序中,我需要一个变量,在应用程序首次创建时仅初始化一次。即使应用程序被更新,它也不应重新初始化。我添加了“entered”。因此,每当我打开应用程序时,我应该有一个包含“entered”字符串的ArrayList

ArrayList<String> strings = new ArrayList<String>();
strings.add("entered");
英文:

I am creating an android application. In my application, I need a variable that initializes only once when the application is first created. It should not be initialized even when the app gets updated. I added, "entered". So whenever I open the app I should have ArrayList which contains entered String.

ArrayList&lt;String&gt; strings=new ArrayList&lt;String&gt;();
strings.add(&quot;entered&quot;);

答案1

得分: 8

如 @blackapps 提到的,您可以使用 Shared Preferences

在 MainActivity.java 中:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    SharedPreferences sharedPref = getPreferences(Context.MODE_PRIVATE);
    SharedPreferences.Editor editor = sharedPref.edit();

    String yourVariable = sharedPref.getString(getString(R.string.nameOfValue), getString(R.string.defaultValue));

    if (yourVariable.equals(getString(R.string.defaultValue))) { // 应用程序第一次运行
        editor.putString(getString(R.string.nameOfValue), "要保存的字符串"); // 您要保存的值
        editor.apply();
    } else {
        // 应用程序不是第一次运行
    }
}

在 string.xml 中:

<string name="nameOfValue">NAME_OF_VALUE</string>
<string name="defaultValue">DEFAULT_VALUE</string>

我保存了 String,但您可以在 Shared Preferences 中保存任何类型。


编辑:
要保存 ArrayList,您可以使用 GSON

首先将依赖项添加到 gradle 并同步项目:

implementation 'com.google.code.gson:gson:2.8.6'

然后使用以下代码:

public class MainActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        SharedPreferences sharedPref = getPreferences(Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sharedPref.edit();

        boolean firstRun = sharedPref.getBoolean(getString(R.string.firstRun), true);
        ArrayList<String> arrayList;
        Gson gson = new Gson();

        if (firstRun) { // 应用程序第一次运行
            System.out.println("第一次运行");

            // 根据需要初始化数组
            arrayList = new ArrayList<>();
            arrayList.add("某些字符串");
            String arrayJSON = gson.toJson(arrayList);

            // 将值添加到 SharedPreferences
            editor.putString(getString(R.string.nameOfValue), arrayJSON);
            editor.putBoolean(getString(R.string.firstRun), false);

            // 应用更改
            editor.apply();
        } else { // 应用程序不是第一次运行
            System.out.println("不是第一次运行");

            String arrayJSON = sharedPref.getString(getString(R.string.nameOfValue), getString(R.string.defaultValue));
            arrayList = gson.fromJson(arrayJSON, new TypeToken<ArrayList<String>>() {}.getType());
        }

        for (String s : arrayList) {
            System.out.println(s);
        }
    }
}
英文:

As @blackapps mentioned You can use Shared Preferences

In MainActivity.java:

@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
SharedPreferences sharedPref = getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
String yourVariable = sharedPref.getString(getString(R.string.nameOfValue), getString(R.string.defaultValue));
if (yourVariable.equals(getString(R.string.defaultValue))) //app was run for 1st time
{
editor.putString(getString(R.string.nameOfValue), &quot;String which You want to save&quot;); //value that You want to put
editor.apply();
}
else
{
// app wasn&#39;t run for 1st time
}
}

In string.xml

&lt;string name=&quot;nameOfValue&quot;&gt;NAME_OF_VALUE&lt;/string&gt;
&lt;string name=&quot;defaultValue&quot;&gt;DEFAULT_VALUE&lt;/string&gt;

I saved String but You can save any type in Shared Preferences.
<hr>

Edit:
To save ArrayList You can use GSON

First add dependency to grade and sync project:

implementstion &#39;com.google.code.gson:gson:2.8.6&#39;

And then use this code:

public class MainActivity extends AppCompatActivity
{
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
SharedPreferences sharedPref = getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
boolean firstRun = sharedPref.getBoolean(getString(R.string.firstRun), true);
ArrayList&lt;String&gt; arrayList;
Gson gson = new Gson();
if (firstRun) //app was run for 1st time
{
System.out.println(&quot;First run&quot;);
// initialize array as You want
arrayList = new ArrayList&lt;&gt;();
arrayList.add(&quot;Some string&quot;);
String arrayJSON = gson.toJson(arrayList);
// add values to SharedPreferences
editor.putString(getString(R.string.nameOfValue), arrayJSON);
editor.putBoolean(getString(R.string.firstRun), false);
// apply changes
editor.apply();
}
else // app wasn&#39;t run for 1st time
{
System.out.println(&quot;Not first run&quot;);
String arrayJSON = sharedPref.getString(getString(R.string.nameOfValue), getString(R.string.defaultValue));
arrayList = gson.fromJson(arrayJSON, new TypeToken&lt;ArrayList&lt;String&gt;&gt;()
{
}.getType());
}
for (String s : arrayList)
{
System.out.println(s);
}
}
}

huangapple
  • 本文由 发表于 2020年7月24日 20:40:28
  • 转载请务必保留本文链接:https://go.coder-hub.com/63073774.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定