アプリ開発初心者用の学習動画です。
この動画はpreferences(プリファレンス・データの保存)の基礎学習です。
プロジェクト名
プロジェクト、カンパニードメイン、パッケージネームを同じにするとコピペエラーが減ります。
Application name MyPreference
Company Domain test.com
Package name com.test.mypreference
保存例
以下を適切な箇所にコピペすると、数値を保存できます。
// ファイルの準備 SharedPreferences preferences = getSharedPreferences("game_data",MODE_PRIVATE); // データの保存 SharedPreferences.Editor editor = preferences.edit(); editor.putInt("count",7); editor.commit();
読込例
以下を適切な場所にコピペすると、数値を読み込みます。
// ファイルの準備 SharedPreferences preferences = getSharedPreferences("game_data",MODE_PRIVATE); // データの読込 int count = preferences.getInt("count" , 0);
activity_main.xml (完成)
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:gravity="center"
tools:context="com.test.mypreference.MainActivity">
<TextView
android:id="@+id/count"
android:textSize="60sp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!" />
</RelativeLayout>
MainActivity.java(完成)
package com.test.mypreference;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// ファイルの準備
SharedPreferences preferences = getSharedPreferences("game_data",MODE_PRIVATE);
// データの保存
SharedPreferences.Editor editor = preferences.edit();
editor.putInt("count",7);
editor.commit();
// データの読込
int count = preferences.getInt("count" , 0);
// データ表示
((TextView)findViewById(R.id.count)).setText("" + count);
}
}



