Database Storage

Keywords: Android Database SQL Apache

Database Storage

1 Store data using Shared Preferences

Scope of application: save a small amount of data, and the format of these data is very simple: string type, basic type of value. For example, application configuration information (such as whether to turn on sound effects, whether to use vibration effects, small game player points, etc.), unlock passwords, etc.
Core Principle: Keyboard-value pairs of data stored in XML files are usually used to store simple configuration information. By expanding the file browsing tree through the File Explorer panel of DDMS, it is obvious that Shared Preferences data is always stored in the / data/data//shared_prefs directory. SharedPreferences object itself can only obtain data without supporting storage and modification. Storage modification is achieved through the internal interface Editor object acquired by SharedPreferences.edit(). Shared Preferences itself is an interface. The program can not create Shared Preferences instances directly. It can only obtain Shared Preferences instances by using the getShared Preferences (String name, int mode) method provided by Context. In this method, name represents the XML file name to be operated on. The second parameter is as follows:
Context.MODE_PRIVATE: Specifies that the Shared Preferences data can only be read and written by this application.
Context.MODE_WORLD_READABLE: Specifies that the Shared Preferences data can be read by other applications, but not written.
Context.MODE_WORLD_WRITEABLE: Specifies that the Shared Preferences data can be read and written by other applications
Editor has the following main important methods:
Shared Preferences. Editor clear (): Clear all data in Shared Preferences
Shared Preferences. Editor put xxx (String key, xxx value): Save the data corresponding to the specified key to Shared Preferences, where xxx can be boolean,float,int and other basic types of data.
Shared Preferences. Editor remove (): Delete the data item corresponding to the specified key in Shared Preferences
boolean commit(): When Editor edits are completed, use this method to submit changes
The core code of the program is as follows:

class ViewOcl implements View.OnClickListener{

        @Override
        public void onClick(View v) {

            switch(v.getId()){
            case R.id.btnSet:
                //Step 1: Get the input value
                String code = txtCode.getText().toString().trim();
                //Step 2-1: create a SharedPreferences.Editor interface object, lock represents the XML file name to be written, and mode  world  writeable write operation
                SharedPreferences.Editor editor = getSharedPreferences("lock", MODE_WORLD_WRITEABLE).edit();
                //Step 2-2: Put the captured values into the file
                editor.putString("code", code);
                //Step 3: Submit
                editor.commit();
                Toast.makeText(getApplicationContext(), "Password Setting Successfully", Toast.LENGTH_LONG).show();
                break;
            case R.id.btnGet:
                //Step 1: Create a Shared Preferences interface object
                SharedPreferences read = getSharedPreferences("lock", MODE_WORLD_READABLE);
                //Step 2: Get the values in the file
                String value = read.getString("code", "");
                Toast.makeText(getApplicationContext(), "Password is:"+value, Toast.LENGTH_LONG).show();
                
                break;
                
            }
        }

2 File Storage Database

Core Principle: Context provides two methods to open file IO stream FileInputStream open FileInput (String name) and FileOutputStream (String name, int mode) in a data file. The first parameter of these two methods is used to specify the file name, and the second parameter is used to specify the mode of opening the file. Specifically, the following values are available:
MODE_PRIVATE: As the default mode of operation, it represents that the file is private data and can only be accessed by the application itself. In this mode, the content written will overwrite the content of the original file, if you want to add the newly written content to the original file. You can use Context.MODE_APPEND
MODE_APPEND: The schema checks whether a file exists, appends content to the file if it exists, or creates a new file.
MODE_WORLD_READABLE: Represents that the current file can be read by other applications;
MODE_WORLD_WRITEABLE: Represents that the current file can be written by other applications.
In addition, Context provides the following important methods:
GetDir (String name, int mode): Get or create subdirectories corresponding to name under the data folder of the application
File getFilesDir(): Get the absolute path to the application's data folder
String[] fileList(): Returns all files of the application data folder
The core code is as follows:

public String read() {
        try {
            FileInputStream inStream = this.openFileInput("message.txt");
            byte[] buffer = new byte[1024];
            int hasRead = 0;
            StringBuilder sb = new StringBuilder();
            while ((hasRead = inStream.read(buffer)) != -1) {
                sb.append(new String(buffer, 0, hasRead));
            }

            inStream.close();
            return sb.toString();
        } catch (Exception e) {
            e.printStackTrace();
        } 
        return null;
    }
    
    public void write(String msg){
        // Step 1: Get the input value
        if(msg == null) return;
        try {
            // Step 2: Create a FileOutputStream object, MODE_APPEND append mode
            FileOutputStream fos = openFileOutput("message.txt",
                    MODE_APPEND);
            // Step 3: Put the captured values into the file
            fos.write(msg.getBytes());
            // Step 4: Close the data stream
            fos.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

3 SQLite database stores data

SQLite is a lightweight embedded database engine that supports the SQL language and has good performance with very little memory. Nowadays, mainstream mobile devices like Android and iPhone use SQLite as the storage engine of complex data. When we develop applications for mobile devices, we may need to use SQLite to store a large amount of data. So we need to master the development skills of SQLite on mobile devices.
The SQLiteDatabase class provides us with many ways to do this. The above code basically covers most of the database operations; we can use it for adding, updating, and deleting.
db.executeSQL(String sql);
db.executeSQL(String sql, Object[] bindArgs);//sql statements use placeholders, and then the second parameter is the actual parameter set
In addition to the unified form, they also have their own methods of operation:
1 db.insert(String table, String nullColumnHack, ContentValues values);
2 db.update(String table, Contentvalues values, String whereClause, String whereArgs);
3 db.delete(String table, String whereClause, String whereArgs);
Addition of data
1. Using insert method

 ContentValues cv = new ContentValues();//Instantiate a ContentValues to load the data to be inserted
 cv.put("title","you are beautiful");//Add title
 cv.put("weather","sun"); //Add weather
 cv.put("context","xxxx"); //Add context
 String publish = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
                     .format(new Date());
 cv.put("publish ",publish); //Add publish
 db.insert("diary",null,cv);//Perform insert operations

Using execSQL to implement

String sql = "insert into user(username,password) values ('Jack Johnson','iLovePopMuisc');//SQL statement for insertion operation
db.execSQL(sql);//Execute SQL statements

Data deletion

String whereClause = "username=?";//Conditions for deletion
String[] whereArgs = {"Jack Johnson"};//Deleted conditional parameters
db.delete("user",whereClause,whereArgs);//Execution deletion

Data modification

ContentValues cv = new ContentValues();//Instantiate ContentValues
cv.put("password","iHatePopMusic");//Add fields and content to be changed
String whereClause = "username=?";//modify condition
String[] whereArgs = {"Jack Johnson"};//Parameters to modify conditions
db.update("user",cv,whereClause,whereArgs);//Execution modification

Data query

 db.rawQuery(String sql, String[] selectionArgs);  
 db.query(String table, String[] columns, String selection, String[] selectionArgs, String groupBy, String having, String orderBy);  
 db.query(String table, String[] columns, String selection, String[] selectionArgs, String groupBy, String having, String orderBy, String limit);  
 db.query(String distinct, String table, String[] columns, String selection, String[] selectionArgs, String groupBy, String having, String orderBy, String limit);  

4 Use ContentProvider to store data

Android is different from other operating systems. We need to remember that data is private in Android. Of course, these data include file data, database data and some other types of data. At this time, some readers will ask questions. Is there no way to exchange data between the two programs? Android is such a good system that it won't happen. ContentProvider is the main solution to this problem. A Content Provider class implements a set of standard method interfaces that allow other applications to save or read various data types of this Content Provider. In other words, a program can expose its data by implementing an abstract interface of Content Provider. It doesn't matter how the data exposed by the application is stored in the application, whether it is stored in a database or in a file or on the Internet. What matters is that the outside world can communicate with the data in the program through this set of standard and unified interfaces. Dao, can read the data of the program, can also delete the data of the program, of course, there will also be some rights involved in the middle.
A program can completely expose its own data by implementing an abstract interface of ContentProvider, and ContentProviders expose data in a way similar to tables in a database, that is to say, ContentProvider is like a "database". Then the external access to the data it provides should be basically the same as the operation of obtaining data from the database, but only the use of URI to represent the external need to access the "database".
Content Provider provides a way to share data among multiple applications, such as: contact information can be accessed by multiple applications.
Content Provider is a class that implements a set of standard methods for providing access to data for other applications. Applications can perform the following actions in Content Provider: query data modification data, add data deletion data
Standard Content Provider: Android provides some standard Content Providers that have been implemented in the system, such as contact information, picture library, etc. You can use these Content Providers to access contact information, pictures and so on stored on the device.
Query records:
The query string used in Content Provider is different from the standard SQL query. Many operations, such as select, add, delete, modify, and so on, are performed using a special URI consisting of three parts, "content:/", which represents the path of the data, and an optional ID for identifying the data.
Here are some sample URI s:
content://media/internal/images This URI will return all images stored on the device
content://contacts/people/This URI will return all contact information on the device.
content://contacts/people/45 This URI returns a single result (contact record with ID 45 in contact information)
Although this query string format is common, it still looks a bit confusing. To this end, Android provides a series of helper classes (under the android.provider package), which contain many query strings in the form of class variables. This way is easier for us to understand. See the following example:
MediaStore.Images.Media.INTERNAL_CONTENT_URI Contacts.People.CONTENT_URI
Therefore, a URI such as content://contacts/people/45 above can be written as follows:
Uri person = ContentUris.withAppendedId(People.CONTENT_URI, 45);
Then perform the data query: Cursor cur = managedQuery(person, null, null, null);
This query returns a cursor containing all data fields. We can get all data by iterating the cursor:

package com.wissen.testApp; 
public class ContentProviderDemo extends Activity { 
    @Override 
    public void onCreate(Bundle savedInstanceState) { 
        super.onCreate(savedInstanceState); 
        setContentView(R.layout.main); 
       displayRecords(); 
    } 
 
    private void displayRecords() { 
        //The array contains all the fields to be returned 
     String columns[] = new String[] { People.NAME, People.NUMBER }; 
       Uri mContacts = People.CONTENT_URI; 
       Cursor cur = managedQuery( 
           mContacts, 
          columns,  // Data fields to be returned 
       null,          // WHERE clause 
       null,         // Parameters of WHERE clause 
       null         // Order-by clause 
     ); 
       if (cur.moveToFirst()) { 
           String name = null; 
           String phoneNo = null; 
           do { 
              // Get the value of the field 
         name = cur.getString(cur.getColumnIndex(People.NAME)); 
             phoneNo = cur.getString(cur.getColumnIndex(People.NUMBER)); 
             Toast.makeText(this, name + " " + phoneNo, Toast.LENGTH_LONG).show(); 
          } while (cur.moveToNext()); 
       } 
    } 
}

Modify records:
We can use the ContentResolver.update() method to modify the data. Let's write a method to modify the data:

private void updateRecord(int recNo, String name) { 
         Uri uri = ContentUris.withAppendedId(People.CONTENT_URI, recNo); 
         ContentValues values = new ContentValues(); 
         values.put(People.NAME, name); 
         getContentResolver().update(uri, values, null, null); 
 
    }

Add records:
To add records, we can call the ContentResolver.insert() method, which accepts the target URI of an additional record and a Map object containing the new record value. The return value of the call is the URI of the new record, including the record number.
In the example above, we are all content providers based on the standard Contact Book. Now let's continue to create an insertRecord() method to add data to the Contact Book:

private void insertRecords(String name, String phoneNo) { 
  ContentValues values = new ContentValues(); 
  values.put(People.NAME, name); 
  Uri uri = getContentResolver().insert(People.CONTENT_URI, values); 
  Log.d("ANDROID", uri.toString()); 
  Uri numberUri = Uri.withAppendedPath(uri, People.Phones.CONTENT_DIRECTORY); 
  values.clear(); 
  values.put(Contacts.Phones.TYPE, People.Phones.TYPE_MOBILE); 
  values.put(People.NUMBER, phoneNo); 
  getContentResolver().insert(numberUri, values); 

}

Delete records:
The getContextResolver.delete() method in Content Provider can be used to delete records.

private void deleteRecords() {  

Uri uri = People.CONTENT_URI;  

getContentResolver().delete(uri, null, null);  

   }

Create Content Provider:
Now that we know how to use Content Provider, let's see how to create a Content Provider ourselves.
To create our own Content Provider, we need to follow the following steps:

  1. Create a class that inherits the ContentProvider parent class
  2. Defining a class variable named CONTENT_URI, which is Uri type of public static final, you must specify a unique string value for it. The best solution is to use the full name of the class.
    For example: public static final Uri CONTENT_URI = Uri.parse("content://com.google.android.MyContentProvider");
  3. Create your data storage system. Most Content Provider s use Android filesystems or SQLite databases to keep data, but you can also store it in any way you want.
  4. Define the data column name you want to return to the client. If you're using an Android database, data columns are used in the same way as other databases you've been familiar with before. However, you have to define a column for it called _id, which is used to represent the uniqueness of each record.
  5. If you want to store byte data, such as bitmap files, the data column that saves the data is actually a URI string representing the actual saved file. The client reads the corresponding file data through it. To process the Content Provider of this data type, it needs to implement a field named _data, _data field column. The exact path of the file on Android file system is given. This field can be used not only by the client, but also by ContentResolver. The client can call the ContentResolver.openOutputStream() method to process the file resources that the URI points to. If it is ContentResolver itself, it can directly access the data file because it holds higher privileges than the client.
  6. Declare a public static String variable that specifies the data column to be returned from the cursor.
  7. The query returns an object of Cursor type. All methods that perform write operations such as insert(), update(), and delete() will be monitored. We can use the ContentResover().notifyChange() method to notify the listener of information about data updates.
  8. Use tags to set up Content Provider in AndroidMenifest.xml.
  9. If the data type you are dealing with is a relatively new type, you must first define a new MIME type for ContentProvider.geType(url) to return.

5 Network Storage Data

We can call the data returned by Web Service or parse HTTP protocol to realize network data interaction.
Specific needs to be familiar with the contents of java.net. *, Android.net. * these two packages, not to mention here, please refer to the relevant documents.
The following is a query of weather forecast in this area by Region name, sending request to WebService X. net site by POST, visiting webservice. WebService X. net site to provide the service of querying weather forecast.

package com.android.weather;  
 
import java.util.ArrayList; 
import java.util.List; 
 
import org.apache.http.HttpResponse; 
import org.apache.http.NameValuePair; 
import org.apache.http.client.entity.UrlEncodedFormEntity; 
import org.apache.http.client.methods.HttpPost; 
import org.apache.http.impl.client.DefaultHttpClient; 
import org.apache.http.message.BasicNameValuePair; 
import org.apache.http.protocol.HTTP; 
import org.apache.http.util.EntityUtils; 
 
import android.app.Activity; 
import android.os.Bundle; 
 
public class MyAndroidWeatherActivity extends Activity { 
    //Define the content source address to be retrieved 
    private static final String SERVER_URL =  
        "http://www.webservicex.net/WeatherForecast.asmx/GetWeatherByPlaceName";  
 
    /** Called when the activity is first created. */ 
    @Override 
    public void onCreate(Bundle savedInstanceState) { 
        super.onCreate(savedInstanceState); 
        setContentView(R.layout.main); 
 
        HttpPost request = new HttpPost(SERVER_URL); //Create an Http request based on the content source address 
        // Add a variable  
        List<NameValuePair> params = new ArrayList<NameValuePair>();  
        // Set a locale name 
        params.add(new BasicNameValuePair("PlaceName", "NewYork"));  //Add the necessary parameters 
 
        try {  
            //Coding of setting parameters 
            request.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));  
            //Send requests and get feedback 
            HttpResponse httpResponse = new DefaultHttpClient().execute(request); 
 
            // Parse the returned content 
            if(httpResponse.getStatusLine().getStatusCode() != 404){  
               String result = EntityUtils.toString(httpResponse.getEntity());  
               System.out.println(result); 
            } 
        } catch (Exception e) { 
            e.printStackTrace(); 
       }  
    }
    ```

Posted by CrimsonSoul on Mon, 23 Sep 2019 03:49:55 -0700