Android - contacts

Posted by monstro on Mon, 10 Jan 2022 02:01:35 +0100

1, Experimental purpose

Practice mastering the basic programming technology of Android Software development, the use of SQLite database of Android system, the use of calls and SMS, and design and make an Android address book software.

2, Experimental content

The realized address book function and interface can be designed by each student in the experimental development, but the address book information must be saved by SQLite database. The following functions and software interfaces are for reference: follow the use interface and functions of general mobile phone address book, and the main functions can include: (1) you can add and delete contacts
(2) Contact information includes: name, mobile phone number, work unit, group, e-mail and mobile phone ring tone
(3) After selecting a contact, you can quickly perform operations, such as making a call, sending a short message, viewing details, moving out of a group, moving a group, deleting a contact, etc. When viewing details, the phone number, group, and set ringtone as well as the call record with the contact will be displayed.
(4) In the contact interface, you can view groups. Click the group to pop up the corresponding contact.
(5) There is a dial-up keyboard. Click the number to display the number, and you can delete the mobile phone number
(6) You can send information and display information records
(7) When sending messages, you can quickly select existing contacts.

3, Experimental requirements

(1) Each student independently designs software functions and completes software development and testing.
(2) Each student completes the experiment report independently (according to the template) and submits it to the online classroom.

4, Screenshot of data code and operation results

All codes are shown in the figure

//mainactivity. There are too many Java codes, so the codes of other files are not pasted.
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.core.app.NotificationCompat;
import androidx.core.view.GravityCompat;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;
import android.app.AlertDialog;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.content.Context;
import android.content.SharedPreferences;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.Toast;
import com.google.android.material.navigation.NavigationView;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.pan.coursedesign.recyclerview.Person;
import com.pan.coursedesign.recyclerview_logs.recording;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.params.HttpMethodParams;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.litepal.crud.DataSupport;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.List;
import java.util.Map;
import java.util.Set;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class MainActivity extends AppCompatActivity {
    AlertDialog.Builder builder5;//custom
    AlertDialog dialog;
    private int tag = 0;
    private int DataDownTag = 0;
    private DrawerLayout mDrawerLayout;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        //Customize the Toolbar and set it into the system
        Toolbar toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        //Because the sliding menu is not easy to be known by the user, a folding button is added
        ActionBar actionBar = getSupportActionBar();//Get the instance of actionBar (implemented by toolbar, that is, toolbar object)
        if (actionBar != null) { //If so
            actionBar.setDisplayHomeAsUpEnabled(true); //A home button is displayed. The id of the HomeAsUp button is always home
            actionBar.setHomeAsUpIndicator(R.drawable.ic_menu); //Set an icon
        }

        //Gets an instance of a drawer and the events used to open and close the drawer
        mDrawerLayout = findViewById(R.id.my_drawer);

        //Default loaded fragment, text1
        replaceFragment(new Contacts_Fragment());


        //Start pop-up
        //Read tag data from file
        SharedPreferences preferences = getSharedPreferences("statata", MODE_PRIVATE);
        tag = preferences.getInt("tag", 0);
        if (tag == 0) { //The tag has not been modified. A pop-up window is displayed
            loding();
        }
        //Set the click event of the side munu
        NavigationView navigationView = (NavigationView) findViewById(R.id.my_nav_view);
        navigationView.setCheckedItem(R.id.nav_text1);
        navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
            @Override
            public boolean onNavigationItemSelected(MenuItem item) {
                //Click event of drawer menu in detailed design
                switch (item.getItemId()) {
                    case R.id.nav_text1:
                        replaceFragment(new Contacts_Fragment());
                        mDrawerLayout.closeDrawer(navigationView);
                        break;
                    case R.id.nav_text2:
                        replaceFragment(new Call_Fragment());
                        mDrawerLayout.closeDrawer(navigationView);
                        break;
                    case R.id.nav_text3:
                        replaceFragment(new Call_logs_Fragment());
                        mDrawerLayout.closeDrawer(navigationView);
                        break;
                    case R.id.nav_text4:
                        replaceFragment(new Help_Fragment());
                        mDrawerLayout.closeDrawer(navigationView);
                        break;
                    case R.id.nav_text5:
                        replaceFragment(new About_Fragment());
                        mDrawerLayout.closeDrawer(navigationView);
                        break;
                    default:
                        break;
                }
                return true;
            }
        });
    }


    //Dynamic replacement of fragments
    private void replaceFragment(Fragment fragment) {
        FragmentManager fragmentManager = getSupportFragmentManager();
        FragmentTransaction transaction = fragmentManager.beginTransaction();
        transaction.replace(R.id.DTFragment, fragment);
        transaction.commit();
    }

// ----toolbar logic----

    //The traditional method realizes menu implantation (command + O shortcut key)
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        //Set a menu
        getMenuInflater().inflate(R.menu.toolbar, menu);
        return true;
    }


    //tab key event
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        //Set menu option click event
        switch (item.getItemId()) {
            case android.R.id.home://This is built-in
                mDrawerLayout.openDrawer(GravityCompat.START);//The sliding menu is displayed, and the drawer opening parameters are consistent with the xml settings
                break;
            case R.id.DataDown:
                DataDown();//Download json data from Apache server
                break;
            case R.id.DataUp:
                try {
                    UpData(GetJsonString());//First, export the data into json text and upload it to the server as data
                } catch (JSONException e) {
                    e.printStackTrace();
                }
//                Toast.makeText(this, "this function is under development...", Toast.LENGTH_LONG).show();
                break;
            case R.id.settings:
                try {
                    ExportData();
                    Toast.makeText(this, "Export succeeded: Internal directory file Under folder", Toast.LENGTH_LONG).show();
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                break;
            case R.id.settings_1:
                if (Import().isEmpty()) {
                    Toast.makeText(this, "Import failed, no data", Toast.LENGTH_LONG).show();
                } else {
                    ImportData();
                    Toast.makeText(this, "Import succeeded", Toast.LENGTH_LONG).show();
                }
                break;
            case R.id.settings_2:
                delall();
                break;
            default:
        }
        return true;
    }


    //1. Prompt box during downloading
    public void DataDown() {
        //Start pop-up
        //Read tag data from file
        SharedPreferences preferences = getSharedPreferences("DataDown", MODE_PRIVATE);
        DataDownTag = preferences.getInt("DataDownTag", 0);
        if (DataDownTag == 0) { //The tag has not been modified. A pop-up window is displayed
            //The inflate method returns a view (custom one),
            View loginview = LayoutInflater.from(this).inflate(R.layout.datadown_dialog_info, null);
            //Declare the control in loginview
            CheckBox checkBox = loginview.findViewById(R.id.info_2);
            Button btnLogin = loginview.findViewById(R.id.datadown);

            btnLogin.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    //Record the status in the file for next reading
                    if (checkBox.isChecked()) {//If selected
                        SharedPreferences.Editor editor = getSharedPreferences("DataDown", MODE_MULTI_PROCESS).edit();
                        editor.putInt("DataDownTag", 1);
                        editor.apply();
                    }
                    dialog.dismiss();
                    DownData();
                }
            });
            //Set Dialog and View
            builder5 = new AlertDialog.Builder(this);
            dialog = builder5.setTitle("Important tips").setView(loginview).setCancelable(false).show();
        } else {
            DownData();
        }
    }

    //Download json data from the server
    public void DownData() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    OkHttpClient client = new OkHttpClient();
                    Request request = new Request.Builder()
                            // The server address specified for access is local to the computer
                            .url("http://172.20.10.5:8081/pro")
                            .build();
                    Response response = client.newCall(request).execute();
                    String responseData = response.body().string();
                    parseJSONWithGSON(responseData);//Download json data import parsing
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    //Method of importing json for parsing
    private void parseJSONWithGSON(String jsonData) {

        //Log.d("aaaaa---", jsonData);
        Contacts_Fragment contacts_fragment = (Contacts_Fragment) getSupportFragmentManager().findFragmentById(R.id.DTFragment);
        Gson gson = new Gson();
        List<Person> appList = gson.fromJson(jsonData, new TypeToken<List<Person>>() {
        }.getType());
        //c=appList;
        int tag = 0;
        //Traverse and store the data into the database first
        for (Person person : appList) {
            person.setTel(formatInviteCode(person.getTel()));//The acquired data should also be processed
            if (RemoveRepetition(person.getName())) { //Update only if the database does not exist
                contacts_fragment.Persons.add(person);
                person.save();
                tag = 1;
            }
        }
        if (tag == 1) {//Refresh as long as there is a change
            //This method is executed in the task thread. You need to update the ui in the main thread
            //Add a notification of successful download
            DataNotification();
            MainActivity.this.runOnUiThread(new Runnable() {
                public void run() {
                    contacts_fragment.load();
                }
            });
        } else {
            DataFailNotification();//Server not found / all imported data
        }
    }

    public Boolean RemoveRepetition(String name) {
        List<Person> Persons = DataSupport.select("name", "Tel", "Email").where("name like ?", "%" + name + "%").find(Person.class);
        if (Persons.size() != 0) {
            return false;//If the database has, do not update
        }
        return true;
    }

    //Notification of successful download
    public void DataNotification() {
        NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        Notification notification = new NotificationCompat.Builder(this, "5996773")
                .setContentTitle("Notification of file download")//Title Content
                .setContentText("Import data succeeded!")//Text content
                .setWhen(System.currentTimeMillis())//Specifies when the notification is created
                .setSmallIcon(R.mipmap.ic_launcher)//Set notification Mini Icon
                .setLargeIcon(BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher))//Set notification large icon
                .setVibrate(new long[]{0, 1000, 1000, 1000})//When the notice arrives, the mobile phone vibrates
                .setLights(Color.GREEN, 1000, 1000)//Set the display effect of the front LED of the mobile phone
                .setPriority(NotificationCompat.PRIORITY_MAX)//Set the importance of the notification
                .build();//build completion is the completion of the notification object
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationChannel channel = new NotificationChannel("5996773", "Notice of Android 10", NotificationManager.IMPORTANCE_HIGH);
            channel.enableLights(true);//Whether to display small red dots in the upper right corner of desktop icon
            channel.setLightColor(Color.GREEN);//Small red dot color
            channel.setShowBadge(false); //Do you want to display notifications for this channel when you press the desktop icon for a long time
            manager.createNotificationChannel(channel);//Set channel into manager
        }
        //The id is unique
        manager.notify(1, notification);
    }

    //Notification of download failure
    public void DataFailNotification() {
        NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        Notification notification = new NotificationCompat.Builder(this, "5996774")
                .setContentTitle("Notification of file download")//Title Content
                .setContentText("The file was downloaded successfully, but you do not need to import it!")//Text content
                .setWhen(System.currentTimeMillis())//Specifies when the notification is created
                .setSmallIcon(R.mipmap.ic_launcher)//Set notification Mini Icon
                .setLargeIcon(BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher))//Set notification large icon
                .setVibrate(new long[]{0, 1000, 1000, 1000})//When the notice arrives, the mobile phone vibrates
                .setLights(Color.GREEN, 1000, 1000)//Set the display effect of the front LED of the mobile phone
                .setPriority(NotificationCompat.PRIORITY_MAX)//Set the importance of the notification
                .build();//build completion is the completion of the notification object
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationChannel channel = new NotificationChannel("5996774", "Notice of Android 10", NotificationManager.IMPORTANCE_HIGH);
            channel.enableLights(true);//Whether to display small red dots in the upper right corner of desktop icon
            channel.setLightColor(Color.GREEN);//Small red dot color
            channel.setShowBadge(false); //Do you want to display notifications for this channel when you press the desktop icon for a long time
            manager.createNotificationChannel(channel);//Set channel into manager
        }
        //The id is unique
        manager.notify(2, notification);
    }


    //2. Upload json to the server
    public void  UpData(String body){
        new Thread(new Runnable(){
            @Override
            public void run(){
                String url="http://172.20.10.5:8081/air "; / / the address you want to visit
                String mesg = null;//Define the results returned by the server
                HttpClient httpClient = new HttpClient();//Build HttpClient instance
                httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(60000); //Set request timeout
                httpClient.getHttpConnectionManager().getParams().setSoTimeout(60000);//Set response timeout
                PostMethod postMethod=new PostMethod(url);//Construct an instance of PostMethod
                postMethod.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET,"utf-8");
                String jsonString="{'data':" + body + "}";
                //com.alibaba.fastjson.JSONObject means importing parseobject from Ali. The first parameter of parseobject is json object
                Map<String,Object> map = com.alibaba.fastjson.JSONObject.parseObject(jsonString,Map.class);
                Set<String> set = map.keySet();
                for(String s : set){
                    postMethod.addParameter(s,map.get(s).toString());
                }
                try {
                    httpClient.executeMethod(postMethod);//Execute post request
                    mesg = postMethod.getResponseBodyAsString();//The message returned from the response can be processed
                    //Log.d("aaaa--", mesg);// Get success!!!!
                } catch (HttpException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }finally{
                    if(mesg!=null){//Have data
                        DataupNotification();//Notification of successful file upload
                    }
                    //Method of closing connection to release resources
                    postMethod.releaseConnection();
                    httpClient.getHttpConnectionManager().closeIdleConnections(0);
                }
            }
        }).start();
    }

    //Notification of successful upload
    public void DataupNotification() {
        NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        Notification notification = new NotificationCompat.Builder(this, "599111")
                .setContentTitle("Notification of file upload")//Title Content
                .setContentText("Upload data succeeded!")//Text content
                .setWhen(System.currentTimeMillis())//Specifies when the notification is created
                .setSmallIcon(R.mipmap.ic_launcher)//Set notification Mini Icon
                .setLargeIcon(BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher))//Set notification large icon
                .setVibrate(new long[]{0, 1000, 1000, 1000})//When the notice arrives, the mobile phone vibrates
                .setLights(Color.GREEN, 1000, 1000)//Set the display effect of the front LED of the mobile phone
                .setPriority(NotificationCompat.PRIORITY_MAX)//Set the importance of the notification
                .build();//build completion is the completion of the notification object
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationChannel channel = new NotificationChannel("599111", "Notice of Android 10", NotificationManager.IMPORTANCE_HIGH);
            channel.enableLights(true);//Whether to display small red dots in the upper right corner of desktop icon
            channel.setLightColor(Color.GREEN);//Small red dot color
            channel.setShowBadge(false); //Do you want to display notifications for this channel when you press the desktop icon for a long time
            manager.createNotificationChannel(channel);//Set channel into manager
        }
        //The id is unique
        manager.notify(3, notification);
    }


    //3. Export json to file
    public void ExportData() throws JSONException {
        String str = GetJsonString();
        save(str);
    }

    //Export json text
    public String GetJsonString() throws JSONException {
        //Gets a fragment instance to call a method in the fragment
        Contacts_Fragment contacts_fragment = (Contacts_Fragment) getSupportFragmentManager().findFragmentById(R.id.DTFragment);
        List<Person> Persons = contacts_fragment.Persons;

        //Convert list to json
        JSONArray jsonArray = new JSONArray();
        JSONObject jsonObject = new JSONObject();//This huge pit, pay attention to the bag
        JSONObject tmpObj = null;
        int count = Persons.size();
        for (int i = 0; i < count; i++) {
            tmpObj = new JSONObject();
            tmpObj.put("name", Persons.get(i).getName());
            tmpObj.put("Email", Persons.get(i).getEmail());
            tmpObj.put("Tel", Persons.get(i).getTel());
            jsonArray.put(tmpObj);
            tmpObj = null;
        }
        String personInfos = jsonArray.toString(); // Convert JSONArray to String
        //Log.d("DDDDD",personInfos);
        return personInfos;
    }
    //Save a piece of json text to a file
    public void save(String inputText) {
        FileOutputStream out = null;
        BufferedWriter writer = null;
        //command + alt + t fast generation
        try {
            File file = new File(getCacheDir().getPath(), "data.json");
            if (file != null) {
                file.delete();
            } else {
                file.createNewFile();
            }
            out = openFileOutput("data.json", Context.MODE_PRIVATE);
//             out = new FileOutputStream(file);
            // OutputStreamWriter is a bridge from character stream to byte stream: byte stream becomes character stream and is passed to buffer stream
            writer = new BufferedWriter(new OutputStreamWriter(out));
            // write in
            writer.write(inputText);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (writer != null) {
                    writer.close();//When the upper stream (buffer stream) is closed, the lower data stream will be closed automatically
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    //4. Import json from file
    public void ImportData() {
        String str1 = Import();
        parseJSONWithGSON(str1);//display
    }
    //Read json file from file
    public String Import() {
        //Ready to read data from file
        FileInputStream in = null;
        //Buffered stream, input
        BufferedReader reader = null;
        StringBuilder content = new StringBuilder();
        try {
            in = openFileInput("data.json");
            reader = new BufferedReader(new InputStreamReader(in));
            String line = "";
            //reader.readLine() is to read one 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();
    }
    //Initialize load
    private void loding() {
        //The inflate method returns a view (custom one),
        View loginview = LayoutInflater.from(this).inflate(R.layout.ui_dialog_info, null);
        //Declare the control in loginview
        CheckBox checkBox = loginview.findViewById(R.id.info_2);
        
Button btnLogin = loginview.findViewById(R.id.info_3);
        btnLogin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
//              Record the status in the file for next reading
                if (checkBox.isChecked()) {//If selected
                    SharedPreferences.Editor editor = getSharedPreferences("statata", MODE_MULTI_PROCESS).edit();
                    editor.putInt("tag", 1);
                    editor.apply();
                }
                dialog.dismiss();
            }
        });
        //Set Dialog and View
        builder5 = new AlertDialog.Builder(this);
        dialog = builder5.setTitle("important information ").setView(loginview).setCancelable(false).show();
    }
    //5. One click Delete
    public void delall() {
        DataSupport.deleteAll(Person.class);
        DataSupport.deleteAll(recording.class);
        Toast.makeText(this, "Delete all data successfully!", Toast.LENGTH_SHORT).show();
    }
    //Handle the - / space of the string when the system obtains the contact
    public String formatInviteCode(String str1) {
        String str2 = "";
        for (int i = 0; i < str1.length(); i++) {
            if (Character.isDigit(str1.charAt(i))) {//Judge whether the character at the index is a number
                str2 += str1.charAt(i);
            }
        }
        return str2;
    }
}

5, Error summary

1. Error:

no such column: userName

Solution: format error. There must be a space in front of type TEXT!

UserInfoEntry.COLUMN_USER_NAME + " TEXT NOT NULL, " 

2. Spaces are added in front of all types, and an error is still reported:

no such column: userName

Solution: the database is not updated. Update the version number. In a production application, this method may be modified to change the table rather than delete it so that existing data is not deleted.
Novice learning, do not know how to modify.
//If you change the database schema, you must increase the database version

private static final int DATABASE_VERSION = 4; 
   @Override
    public void onUpgrade(SQLiteDatabase sqLiteDatabase, int oldVersion, int newVersion) {
//        //In onUpgrade, delete the table if it exists
        sqLiteDatabase.execSQL("DROP TABLE IF EXISTS " + UserInfoEntry.TABLE_NAME);
//        //Call onCreate and pass in SQLiteDatabase (pass in onUpgrade). Remember to update the version number
        onCreate(sqLiteDatabase);
    }

3. Error:

android.database.CursorIndexOutOfBoundsException: Index -1 requested,
with a size of 1

Solution: the subscript is out of bounds. The cursor subscript starts from - 1 instead of 0. You need to move and add an if statement. In fact, I still don't quite understand why it's OK to move to the first one.

if (cursor.moveToFirst()){
queryPassword=cursor.getString(cursor.getColumnIndex(UserInfoContract.UserInfoEntry.COLUMN_USER_PASSWORD));
}

4. Error:

android.database.sqlite.SQLiteException: no such column:

Error example:

return mDb.update(DATABASE_TABLE, args, KEY_SSID + "=" + ssid , null) > 0;

reason:
When adding, deleting, modifying, and querying databases, such as update and query, the parameters passed in are of string type.
In fact, these methods will splice the parameters into sql statements, and the string type needs to be enclosed in quotation marks
Therefore, the error code above should be changed to:

return mDb.update(DATABASE_TABLE, args, KEY_SSID + "='" + ssid + "'", null) > 0;

6, Personal experience

Basic data types of SQLite: byte, Long, Short, Integer, Float, Double, String, Boolean, byte []
The theoretical storage capacity is 140TB
SQLiteOpenHelper
Since it is the addition, deletion, modification and query of the database, we first need a database, and the database should be generated through the subclass of SQLiteOpenHelper, so we first need to create a class to inherit SQLiteOpenHelper. Since this class is an abstract class, we need to implement its constructor and abstract methods. So:

public class DBHelper extends SQLiteOpenHelper {
    // Database default name
    public static final String db_name = "test.db";
    public DBHelper(Context context, int version) {
        super(context, db_name, null, version);
    }
    @Override
    public void onCreate(SQLiteDatabase db) {
    }
    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    }
}

Methods that need to be overloaded
onCreate: creates a table and some basic properties.
onUpgrade: used when the database needs to be updated, provided that the same database already exists, a new table needs to be added, or the original table fields need to be modified.
Example: now create a table named table1: execute the SQL statement directly

public class DBHelper extends SQLiteOpenHelper {
    public static final String db_name = "test.db";
    public DBHelper(Context context, int version) {
        super(context, db_name, null, version);
    }
    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL("create table table1 (" +
                " _byte byte," +
                " _long long," +
                " _text text," +
                " _short short," +
                " _int int," +
                " _float float," +
                " _double double," +
                " _boolean boolean," +
                " _blob blob" +
                ")");
    }
    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    }
}

Addition, deletion, modification and query of table

public class DBManger {
    private Context context;
    private static DBManger instance;
    // Add, delete, modify and query the objects of the operation table
    private SQLiteDatabase writableDatabase;
    private DBManger(Context context) {
        this.context = context;
        DBHelper dbHelper = new DBHelper(context, 1);
//Get SQLiteDatabase object through getWritableDatabase method of DBHelper, and SQLiteDatabase can operate database tables
        writableDatabase = dbHelper.getWritableDatabase();
    }
    public static DBManger getInstance(Context context) {
        if (instance == null) {
            synchronized (DBManger.class) {
                if (instance == null) {
                    instance = new DBManger(context);
                }
            }
        }
        return instance;
    }
}

Add:

public void add() {
        ContentValues contentValues = new ContentValues();
        byte _byte = Byte.MAX_VALUE;
        contentValues.put("_byte", _byte);
        long _long = Long.MAX_VALUE;
        contentValues.put("_long", _long);
        String _text = "character string";
        contentValues.put("_text", _text);
        short _short = Short.MAX_VALUE;
        contentValues.put("_short", _short);
        int _int = Integer.MAX_VALUE;
        contentValues.put("_int", _int);
        float _float = Float.MAX_VALUE;
        contentValues.put("_float", _float);
        double _double = Double.MAX_VALUE;
        contentValues.put("_double", _double);
        boolean _boolean = true;
        contentValues.put("_boolean", _boolean);
        byte[] _byteArr = {Byte.MIN_VALUE, Byte.MAX_VALUE};
        contentValues.put("_blob", _byteArr);
        writableDatabase.insert("table1", null, contentValues);
    }

Delete: delete_ int = Integer.MAX_VALUE

public void del() {
        writableDatabase.delete("table1", "_int = ?", new String[]{Integer.MAX_VALUE + ""});
}

Change: call the update method, and the parameters are: table name, package, condition and condition value

public void update() {
        ContentValues contentValues = new ContentValues();
        contentValues.put("_text", "Modified string");
        writableDatabase.update("table1", contentValues, "_text = ?", new String[]{"character string"});
 }

Query: first, the query method returns a Cursor object to locate.
Query parameters:
String table: table name
String[] columns: the column name to be queried
String selection: represents how many pieces of data to query. For example, if you only query 10 pieces of data, you can directly pass a 10.
String[] selectionArgs: represents how many pieces of data are queried. For example, if only 10 pieces of data are queried, just pass a 10 directly.
String groupBy: divides the same values into a group
String having: parameter for condition judgment, but it should exist at the same time as the parameter groupby, that is, it should be used at the same time. In other words, in the data filtered by group by, use the so-called having to filter again.
String orderBy: represents sorting. It can be passed to a field, such as_ byte, which means sorting according to this field. The default is ascending, that is, sorting from small to large. We can pass parameters in this way to arrange them in descending order_ byte desc, if yes_ byte asc is in ascending order. Because the default ascending order is, this asc is omitted.
String limit: represents how many pieces of data to query. For example, if you only query 10 pieces of data, you can directly pass a 10.

public String select() {
    Cursor cursor = writableDatabase.query("table1", null, null, null, null, null, null, null);
    int position = cursor.getPosition();
    Log.e(TAG, "select: Cursor default position:" + position);
    String result = "";
    while (cursor.moveToNext()) {
        byte _byte = (byte) cursor.getShort(cursor.getColumnIndex("_byte"));
        long _long = cursor.getLong(cursor.getColumnIndex("_long"));
        String _text = cursor.getString(cursor.getColumnIndex("_text"));
        short _short = cursor.getShort(cursor.getColumnIndex("_short"));
        int _int = cursor.getInt(cursor.getColumnIndex("_int"));
        float _float = cursor.getFloat(cursor.getColumnIndex("_float"));
        double _double = cursor.getDouble(cursor.getColumnIndex("_double"));
        boolean _boolean = cursor.getInt(cursor.getColumnIndex("_boolean")) == 1 ? true : false;
        byte[] _byteArr = cursor.getBlob(cursor.getColumnIndex("_blob"));
        result += String.format("_byte = %s, _long = %s, _text = %s, _short = %s, _int = %s, _float = %s, _double = %s, _boolean = %s, _byteArr = %s",
                _byte, _long, _text, _short, _int, _float, _double, _boolean, _byteArr) + "\n";
    }
    return result;
}

Topics: Java Android SQLite