Data store (file store, SharedPreferences, database store)

Posted by theweirdone on Fri, 31 Jan 2020 18:42:22 +0100

data storage

File store, SharedPreferences, database store

  • File store
    In the way of Java flow
public class MainActivity extends AppCompatActivity {

    private EditText editText;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        editText = (EditText) findViewById(R.id.edit);

        String inputText = load();

        /*This method is a double judgment of string, that is, it is not null or empty*/
        if(!TextUtils.isEmpty(inputText)){
            editText.setText(inputText);
//            Move the cursor to the end of the string
            editText.setSelection(inputText.length());
            Toast.makeText(this, "recovery was successful", Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    protected void onDestroy()  {
        super.onDestroy();
        String inputText = editText.getText().toString();
        save(inputText);
    }

    /*File store*/
    public void save(String inputText) {
        FileOutputStream out = null;
        BufferedWriter writer = null;
        try {
            out = openFileOutput("data", Context.MODE_PRIVATE);
            writer = new BufferedWriter(new OutputStreamWriter(out));
            writer.write(inputText);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (writer != null) {
                    writer.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /*File recovery*/
    public String load() {
        FileInputStream in = null;
        BufferedReader reader = null;
        StringBuilder content = new StringBuilder();
        try {
            in = openFileInput("data");
            reader = new BufferedReader(new InputStreamReader(in));
            String line = "";
            while ((line = reader.readLine()) != null) {
                content.append(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return content.toString();
    }

}

Layout setting an edit box
Android Device Monitor has been deprecated in android studio3.0 and above. You can View the file in View → Tool Windows → Device File Explorer
The file directory is / data/data / package name / files /

  • SharedPreferences
    Using key value method
public class MainActivity extends AppCompatActivity {
    private Button saveData;
    private  Button restoreData;
    private TextView showData;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        saveData=(Button)findViewById(R.id.save_data);
        restoreData=(Button)findViewById(R.id.restore_data);
        showData=(TextView)findViewById(R.id.show_data);
        /*Store data*/
        saveData.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                SharedPreferences.Editor editor=getSharedPreferences("data",MODE_PRIVATE).edit();
                editor.putString("name","Tom");
                editor.putInt("age",28);
                editor.putBoolean("married",false);
                editor.apply();
            }
        });

        /*Restore data*/
        restoreData.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                SharedPreferences pref=getSharedPreferences("data",MODE_PRIVATE);
                String name=pref.getString("name","");
                int age=pref.getInt("age",0);
                boolean married=pref.getBoolean("married",false);
                showData.setText("name is "+name+"\n"+"age is "+age+"\n"+"married is "+married);
            }
        });
    }
}

Layout is two buttons and one text
* database
Use SQLITE
Layout six buttons

    <Button
        android:id="@+id/create_database"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Create database"
        />

    <Button
        android:id="@+id/add_data"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Add data"
        />

    <Button
        android:id="@+id/up_date"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Update data"
        />

    <Button
        android:id="@+id/delete_data"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Delete data"
        />

    <Button
        android:id="@+id/query_data"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Query data"
        />

New MyDatabaseHelper class

public class MyDatabaseHelper extends SQLiteOpenHelper {

    public static final String CREATE_BOOK="create table Book ("
            +"id integer primary key autoincrement,"
            +"author text,"
            +"price real,"
            +"pages integer,"
            +"name text)";

    public static final String CREATE_CATEGORY="create table Category ("
            +"id integer primary key autoincrement,"
            +"category_name text,"
            +"category_code integer)";

    private Context mContext;

    public MyDatabaseHelper(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) {
        super(context, name, factory, version);
        mContext=context;
    }

    @Override
    public void onCreate(SQLiteDatabase sqLiteDatabase) {
        sqLiteDatabase.execSQL(CREATE_BOOK);

        /*onCreate() method is required to create a new table*/
        sqLiteDatabase.execSQL(CREATE_CATEGORY);
        //onCreate(sqLiteDatabase);
    }

    @Override
    public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {

    }
}

Modify MainActivity

public class MainActivity extends AppCompatActivity {

    public static final String TAG="MainActivity";

    private Button createDatabase;

    private Button addData;

    private Button updateData;

    private Button deleteData;

    private Button queryData;

    private MyDatabaseHelper dbHelper;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        createDatabase=(Button)findViewById(R.id.create_database);
        addData=(Button)findViewById(R.id.add_data);
        updateData=(Button)findViewById(R.id.up_date);
        deleteData=(Button)findViewById(R.id.delete_data);
        queryData=(Button)findViewById(R.id.query_data);

        /*The version number needs to be changed when adding a new table*/
        dbHelper=new MyDatabaseHelper(this,"BookStore.db",null,2);

        /*Create database*/
        createDatabase.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dbHelper.getWritableDatabase();
            }
        });

        /*Add data*/
        addData.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                SQLiteDatabase sqLiteDatabase=dbHelper.getWritableDatabase();
                ContentValues values=new ContentValues();
                //Start filling in the first data
                values.put("name","discrete mathematics");
                values.put("author","Qu Wan Ling");
                values.put("pages",300);
                values.put("price",33.33);
                //Insert first data
                sqLiteDatabase.insert("Book",null,values);
                values.clear();
                //Start filling in the second data
                values.put("name","18 lectures on Advanced Mathematics");
                values.put("author","Zhang Yu");
                values.put("pages",400);
                values.put("price",44.44);
                sqLiteDatabase.insert("Book",null,values);
            }
        });

        /*Update data*/
        updateData.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                SQLiteDatabase sqLiteDatabase=dbHelper.getWritableDatabase();
                ContentValues values=new ContentValues();
                values.put("author","Su Yun Gong");
                sqLiteDatabase.update("Book",values,"name=?",new String[]{"discrete mathematics"});
            }
        });

        /*Delete data*/
        deleteData.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                SQLiteDatabase sqLiteDatabase=dbHelper.getWritableDatabase();
                sqLiteDatabase.delete("Book","name=?",new String[]{"18 lectures on Advanced Mathematics"});
            }
        });

        /*Query data*/
        queryData.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                SQLiteDatabase sqLiteDatabase=dbHelper.getWritableDatabase();
                Cursor cursor=sqLiteDatabase.query("Book",null,null,null,null,null,null);
                if (cursor.moveToFirst()){
                    do {
                        String name=cursor.getString(cursor.getColumnIndex("name"));
                        String author=cursor.getString(cursor.getColumnIndex("author"));
                        int pages=cursor.getInt(cursor.getColumnIndex("pages"));
                        double price=cursor.getDouble(cursor.getColumnIndex("price"));
                        Log.d(TAG, "book name is "+name);
                        Log.d(TAG, "book author is "+author);
                        Log.d(TAG, "book pages is "+pages);
                        Log.d(TAG, "book price is "+price);
                    }while (cursor.moveToNext());
                }
                cursor.close();
            }
        });
    }
}

Use LitePal operation, go first Project Home View the latest version
implementation 'org.litepal.android:core:2.0.0'
Under main, create a new assets directory (New → Floder → AssetsFloder), and then create literal.xml in it

<?xml version="1.0" encoding="utf-8"?>
<litepal>
    <dbname value="BookStore">
    </dbname>
    <version value="1">
    </version>
    <list>
        <mapping class="com.example.litepaltest.Book">
        </mapping>
    </list>
</litepal>

Then register
android:name="org.litepal.LitePalApplication"
1. Create database
Add entity class and map, then call LitePal.getDatabase(); that is, create table

public class Book {

    private int id;

    private String author;

    private double price;

    private int pages;

    private String name;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getAuthor() {
        return author;
    }

    public void setAuthor(String author) {
        this.author = author;
    }

    public void setPrice(double price) {
        this.price = price;
    }

    public double getPrice() {
        return price;
    }

    public void setPages(int pages) {
        this.pages = pages;
    }

    public int getPages() {
        return pages;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }
}
<list>
    <mapping class="com.example.litepaltest.Book">
    </mapping>
</list>
public class MainActivity extends AppCompatActivity {
    private Button createDatabase;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        createDatabase=(Button)findViewById(R.id.create_database);
        createDatabase.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                LitePal.getDatabase();
            }
        });
    }
}

2 upgrade database
Add or create a new entity class in the entity class, and then change the version number in literal.xml to map

public class Category {

    private int id;

    private  String categoryName;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getCategoryName() {
        return categoryName;
    }

    public void setCategoryName(String categoryName) {
        this.categoryName = categoryName;
    }
}
<version value="2">
</version>
<list>
    <mapping class="com.example.litepaltest.Book">
    </mapping>
        <mapping class="com.example.litepaltest.Category">
    </mapping>
</list>

3. Add data to LitePal (add)
Just to create a database, you don't need to inherit the structure. To perform CRUD (add, delete, modify and query), entity classes need to inherit litepalmsupport
To add data, just call the set method of entity class and the save() method of DataSupport
public class Book extends LitePalSupport

addData.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Book book=new Book();
                book.setName("discrete mathematics");
                book.setAuthor("Qu Wan Ling");
                book.setPages(400);
                book.setPrice(40.35);
                book.setPress("tsinghua university press ");
                book.save();
            }
        });

4. Update data

updataData.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {
        Book book = new Book();
               book.setAuthor("Su Yun Gong");
               book.updateAll("author=?","Qu Wan Ling");
    }
});

5. Delete data
LitePal.deleteAll(Book.class,"price<?","15");
6. Query data

List<Book>books=LitePal.findAll(Book.class);
               for(Book book:books){
                   Log.d("MainActivity","book name is "+book.getName());
                   Log.d("MainActivity","book author is "+book.getAuthor());
                   Log.d("MainActivity","book pages is "+book.getPages());
                   Log.d("MainActivity","book price is "+book.getPrice());
                   Log.d("MainActivity","book press is "+book.getPress());

Topics: Android Database xml Java