Fundamentals of mobile application design -- final examination -- comprehensive practice of login interface and simple diary

Final report of fundamentals of mobile application design

Project Name:

On machine assessment of mobile application development foundation

Tools, software and environment used:

JDK,Android Studio

1, Subject background

In the final computer examination, the contents of Experiment 4 and Experiment 5 and the small experiments completed in class are combined to complete the final examination.  

2, Task content

Assessment content: write a simple diary program on the computer. The interface includes: user login, user registration, diary home page, adding and editing diary.

Note: the following * * * is the first letter of the Pinyin word of your name (e.g. Yu Chenghai - ych).

1. User login

Layout: activity_login.xml, as shown in the following figure, the resource image username PNG and password Png, the layout requires embedded pictures on the left, as shown in the figure. (10 points)

Figure 1 login interface layout

 

Implementation function: loginactivity java

  1. The input fields include user name, password and ok. Click ok (10 points)
    1. If the user name and password exist in SharedPreferences, jump to dialyactivity;
    2. Click Register to jump to the user registration interface RegisterActivity
    3. If the user name and password do not exist or are inconsistent in SharedPreferences, jump to the user registration interface RegisterActivity, and Toast will prompt "username, please register your information first, * * * program friendly prompt!" as shown in the figure below.

be careful:

  1. When registering, write SharePreferences, file name user, and save the values username and password;
  2. When logging in, read the username and password in SharePreferences (file name user)

 

2. User registration

Interface layout: activity_register.xml, as shown in the following figure, the resource image username PNG and password Png, the layout requires embedded pictures on the left, as shown in the middle figure below. (10 points)

Function implementation: registeractivity java. Click register, insert the user name and password into SharePreferences (file name user, saved values username and password), return to the login interface, and Toast pops up "registration succeeded, please log in, * * * program friendly prompt!", As shown above. (10 points)

3. Diary home page

Interface layout: activity_diary.xml, as shown in the following figure, including AppBarLayout, Listview and FloatingActionButton. (10 points)

Function implementation: dialyactivity java,

  1. Get database***_ DiaryDB.db, and display the journal data in listview. (10 points)
  2. Click the edit picture button in the list item, and the interface will jump to the diary addition and editing interface (DiaryInfoActivity). (5 points)
  3. Click the edit picture button (bianji.png) in the edit_tv list item on the AppBar to replace it with delete picture (delete.png), and the editing is changed to cancel, as shown in the following figure. Click the delete picture button to delete this item in the list and delete the data in the database at the same time. Click Cancel to cancel and change back to edit. The delete picture (delete.png) in the list item is replaced by the edit picture button (bianji.png). (10 points)

 

3, Interface design and Implementation (bonus points for describing design ideas and concepts)

The login interface adopts a simple and common linerLayout layout, and the registration interface is the same

The main interface of journal adopts CoordinatorLayout layout, and the listview adopts RelativeLayout layout

 

The editing journal interface adopts the CoordinatorLayout layout

 

4, Function flow and Implementation (add points by using design ideas, design patterns, UML diagrams and flow diagrams)

flow chart:

The core java code file and the layout file of the login interface after experiment 5 are shown in the figure below.

  

Code file: (the code file has a resource package, and the download link is at the end of the article)

//AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    package="com.example.sqlitedemo">
    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity
            android:name=".Login"
            android:label="Every diary"
            android:theme="@style/AppTheme.NoActionBar">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity android:name=".Register"/>
        <activity android:name=".MainActivity"/>
        <activity android:name=".DiaryInfoActivity"/>



    </application>
</manifest>

//Login.java
package com.example.sqlitedemo;

import android.content.Context;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.os.Build;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;

public class Login extends AppCompatActivity {

    static int p=0;
    static public EditText usenameEdtxt,passwordEdtxt;
    public Button registerButton,submitbutton;


    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        usenameEdtxt=(EditText)findViewById(R.id.usename_edtxt);
        passwordEdtxt=(EditText)findViewById(R.id.password_edtxt);
        submitbutton=(Button)findViewById(R.id.submit_button);
        registerButton=(Button)findViewById(R.id.register_button);
        //Login button monitoring

        submitbutton.setOnClickListener(new View.OnClickListener() {
            @RequiresApi(api = Build.VERSION_CODES.GINGERBREAD)
            @Override
            public void onClick(View v) {
                String usename=usenameEdtxt.getText().toString();
                String password=passwordEdtxt.getText().toString();


                if(usename.isEmpty()){
                    usenameEdtxt.setError("User name cannot be empty");
                    usenameEdtxt.requestFocus();
                    return;
                }
                if(password.isEmpty()){
                    passwordEdtxt.setError("Password cannot be empty");
                    passwordEdtxt.requestFocus();
                    return;
                }

                if(p==0){
                    Toast.makeText(com.example.sqlitedemo.Login.this, usename+"Please register your information first,Shao Yonggang program friendly tips!", Toast.LENGTH_SHORT).show();
                    Intent it=new Intent();
                    Context packageContext;
                    it.setClass(com.example.sqlitedemo.Login.this, Register.class);
                    com.example.sqlitedemo.Login.this.startActivity(it);
                    return;

                }

                if(usename.length()>0&&password.length()>0&&usename.equals(Register.usenameEdtxt1.getText().toString())&&p==1&&password.equals(Register.passwordEdtxt1.getText().toString())){

                    Toast.makeText(com.example.sqlitedemo.Login.this, "Login succeeded", Toast.LENGTH_SHORT).show();
                    Intent it=new Intent();
                    Context packageContext;
                    it.setClass(com.example.sqlitedemo.Login.this, MainActivity.class);
                    com.example.sqlitedemo.Login.this.startActivity(it);

                }
                else {
                    Toast.makeText(com.example.sqlitedemo.Login.this, usename+"Please register your information first,Shao Yonggang program friendly tips!", Toast.LENGTH_SHORT).show();
                    Intent it=new Intent();
                    Context packageContext;
                    it.setClass(com.example.sqlitedemo.Login.this, Register.class);
                    com.example.sqlitedemo.Login.this.startActivity(it);
                }

            }


        });
        registerButton.setOnClickListener(new View.OnClickListener() {
            @RequiresApi(api = Build.VERSION_CODES.GINGERBREAD)
            @Override
            public void onClick(View v) {

                    Toast.makeText(com.example.sqlitedemo.Login.this, "Register", Toast.LENGTH_SHORT).show();
                    Intent it=new Intent();
                    Context packageContext;
                    it.setClass(com.example.sqlitedemo.Login.this, Register.class);
                    com.example.sqlitedemo.Login.this.startActivity(it);

            }


        });

    }

}

 

//Register.java
package com.example.sqlitedemo;

import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;

public class Register extends AppCompatActivity {

    static public EditText usenameEdtxt1,passwordEdtxt1;
    public Button registerButton;

    protected void onCreate(Bundle savedInstanceState) {

        Login.p=1;
        super.onCreate(savedInstanceState);
        setContentView(R.layout.register);
        usenameEdtxt1=(EditText)findViewById(R.id.usename_edtxt);
        passwordEdtxt1=(EditText)findViewById(R.id.password_edtxt);
        registerButton=(Button)findViewById(R.id.register_button);

        registerButton.setOnClickListener(new View.OnClickListener() {
            @RequiresApi(api = Build.VERSION_CODES.GINGERBREAD)
            @Override
            public void onClick(View v) {
                String usename=usenameEdtxt1.getText().toString();
                String password=passwordEdtxt1.getText().toString();


                if(usename.isEmpty()){
                    usenameEdtxt1.setError("User name cannot be empty");
                    usenameEdtxt1.requestFocus();
                    return;
                }
                if(password.isEmpty()){
                    passwordEdtxt1.setError("Password cannot be empty");
                    passwordEdtxt1.requestFocus();
                    return;
                }

                if(usename.length()>0&&password.length()>0){

                    Toast.makeText(com.example.sqlitedemo.Register.this, "Registration is successful, please log in, Shao Yonggang program friendly tips!", Toast.LENGTH_SHORT).show();
                    Intent it=new Intent();
                    Context packageContext;
                    it.setClass(com.example.sqlitedemo.Register.this, com.example.sqlitedemo.Login.class);
                    com.example.sqlitedemo.Register.this.startActivity(it);

                }


            }


        });

    }
}
//MainActivity.java
package com.example.sqlitedemo;

import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Build;
import android.os.Bundle;

import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.android.material.snackbar.Snackbar;

import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;

import android.util.Log;
import android.view.View;

import android.view.Menu;
import android.view.MenuItem;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static android.os.Build.VERSION.SDK_INT;

public class MainActivity extends AppCompatActivity {
    private static final String TAG = "MainActivity";
    private TextView editTv;
    private ListView diaryList;
    private FloatingActionButton fab;
    private List<Map<String, String>> listData;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        listData = new ArrayList<>();
        fab = (FloatingActionButton) findViewById(R.id.fab);
        editTv = (TextView) findViewById(R.id.edit_tv);
        diaryList = (ListView) findViewById(R.id.list_view);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Log.e(TAG, "onClick: " );

                Intent intent = new Intent(MainActivity.this, DiaryInfoActivity.class);
                intent.putExtra("FLAG", 0);
                startActivity(intent);
            }
        });
        editTv.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                Log.e(TAG, "on" );
                int length = queryData().size();
                if (editTv.getText().toString().equals("cancel")){
                    editTv.setText("edit");
                    for (int i = 0;i<length;i++){
                        diaryList.getChildAt(i).findViewById(R.id.edit_ib).setVisibility(View.VISIBLE);
                        diaryList.getChildAt(i).findViewById(R.id.delete_ib).setVisibility( View.INVISIBLE);
                    }
                }
                else {
                    editTv.setText("cancel");
                    for (int i = 0;i<length;i++){
                        diaryList.getChildAt(i).findViewById(R.id.edit_ib).setVisibility(View.INVISIBLE);
                        diaryList.getChildAt(i).findViewById(R.id.delete_ib).setVisibility( View.VISIBLE);
                    }
                }
            }
        });
        diaryList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Intent intent = new Intent(MainActivity.this,DiaryInfoActivity.class);
                intent.putExtra("FLAG",1);
                intent.putExtra(SQLiteContract.DiaryEntry.COLUMN_NAME_TITLE,listData.get(position).get(SQLiteContract.DiaryEntry.COLUMN_NAME_TITLE));
                intent.putExtra(SQLiteContract.DiaryEntry.COLUMN_NAME_CONTENT,listData.get(position).get(SQLiteContract.DiaryEntry.COLUMN_NAME_CONTENT ));
                startActivity(intent);
            }
        });
        diaryList.setAdapter(new DiaryListAdapter(MainActivity.this,queryData()));
    }
    @Override
    protected void onResume() {
        super.onResume();
        //Re query adaptation
        diaryList.setAdapter(new DiaryListAdapter(MainActivity.this,queryData()));
    }
    /**
     * Query all data from Sqlite
     *
     * @return Data list
     */
    public List<Map<String,String>> queryData(){
        listData = new ArrayList<>();
        DiaryDbHelper dbHelper = new DiaryDbHelper(this);
        SQLiteDatabase db = dbHelper.getReadableDatabase();
        String[] projection = {
                SQLiteContract.DiaryEntry._ID,SQLiteContract.DiaryEntry.COLUMN_NAME_TITLE,
                SQLiteContract.DiaryEntry.COLUMN_NAME_CONTENT,SQLiteContract.DiaryEntry.COLUMN_NAME_TIME };
        String sortOrder = SQLiteContract.DiaryEntry.COLUMN_NAME_TIME+" DESC";
        Cursor c = db.query(SQLiteContract.DiaryEntry.TABLE_NAME,projection,null,null, null,null,sortOrder);
        while (c.moveToNext()){
            Map<String,String> map = new HashMap<>();
            map.put(SQLiteContract.DiaryEntry._ID,c.getString(c.getColumnIndex( SQLiteContract.DiaryEntry._ID)));
            map.put(SQLiteContract.DiaryEntry.COLUMN_NAME_TITLE,c.getString(c.getColumnIndex(SQLiteContract.DiaryEntry.COLUMN_NAME_TITLE)));
            map.put(SQLiteContract.DiaryEntry.COLUMN_NAME_CONTENT,c.getString(c .getColumnIndex(SQLiteContract.DiaryEntry.COLUMN_NAME_CONTENT)));
            map.put(SQLiteContract.DiaryEntry.COLUMN_NAME_TIME,c.getString(c.getColumnIndex(SQLiteContract.DiaryEntry.COLUMN_NAME_TIME)));
            listData.add(map);
        }
        c.close();
        db.close();
        return listData;
    }
}
//DiaryInfoActivity.java
package com.example.sqlitedemo;

import android.content.ContentValues;
import android.database.sqlite.SQLiteDatabase;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.Toolbar;

import androidx.annotation.NonNull;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;

import java.lang.reflect.Method;
import java.text.SimpleDateFormat;
import java.util.Date;

import static android.os.Build.VERSION.SDK_INT;

public class DiaryInfoActivity extends AppCompatActivity {
    private TextView titleTv,contentTv;
    private EditText titleEt,contentEt;
    private ImageButton submitIb;
    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_diary_info);

        Log.e("TAG","onResume()");

        androidx.appcompat.widget.Toolbar toolbar = (androidx.appcompat.widget.Toolbar) findViewById(R.id.toolbar_info);
        setSupportActionBar(toolbar);
        ActionBar actionBar = getSupportActionBar();
        //Add back button

        actionBar.setDisplayHomeAsUpEnabled(true);
        //Hide title
        actionBar.setDisplayShowTitleEnabled(false);
        titleTv = (TextView)findViewById(R.id.info_title_tv);
        contentTv = (TextView)findViewById(R.id.info_content_tv);
        titleEt = (EditText)findViewById(R.id.info_title_et);
        contentEt = (EditText)findViewById(R.id.info_content_et);
        submitIb = (ImageButton)findViewById(R.id.submit_ib);
        //Get passed parameters
        int flag = getIntent().getIntExtra("FLAG",-1);
        final String id = getIntent().getStringExtra(SQLiteContract.DiaryEntry._ID);
        final String title = getIntent().getStringExtra(SQLiteContract.DiaryEntry.COLUMN_NAME_TITLE);
        String content = getIntent().getStringExtra(SQLiteContract.DiaryEntry.COLUMN_NAME_CONTENT);
        //New journal
        if(flag==0){
            submitIb.setVisibility(View.VISIBLE);
            titleTv.setVisibility(View.INVISIBLE);
            contentTv.setVisibility(View.INVISIBLE);
            titleEt.setVisibility(View.VISIBLE);
            contentEt.setVisibility(View.VISIBLE);
            submitIb.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if(titleEt==null
                            || titleEt.getText().toString().trim().equals("")){
                        Toast.makeText(DiaryInfoActivity.this, "Please enter a title",
                                Toast.LENGTH_LONG).show();
                        return;
                    }
                    if(contentEt==null
                            || contentEt.getText().toString().trim().equals("")){
                        Toast.makeText(DiaryInfoActivity.this, "Please enter the content",
                                Toast.LENGTH_LONG).show();
                        return;
                    }
                    //Insert a message into Sqlite
                    DiaryDbHelper dbHelper = new DiaryDbHelper(DiaryInfoActivity.this);
                    SQLiteDatabase db = dbHelper.getWritableDatabase();
                    //Format time
                    SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM-dd HH:mm");
                    String date = sd.format(new Date());
                    //Set insertion value
                    ContentValues values = new ContentValues();
                    values.put(SQLiteContract.DiaryEntry.COLUMN_NAME_TITLE,
                            titleEt.getText().toString());
                    values.put(SQLiteContract.DiaryEntry.COLUMN_NAME_CONTENT,
                            contentEt.getText().toString());
                    values.put(SQLiteContract.DiaryEntry.COLUMN_NAME_TIME, date);
                    //Execute insert method
                    long newRowId = db.insert(SQLiteContract.DiaryEntry.TABLE_NAME, null, values);
                    DiaryInfoActivity.this.finish();
                }
            });
        }
        //View diary
        else if(flag==1){
            submitIb.setVisibility(View.INVISIBLE);
            titleTv.setVisibility(View.VISIBLE);
            contentTv.setVisibility(View.VISIBLE);
            titleEt.setVisibility(View.INVISIBLE);
            contentEt.setVisibility(View.INVISIBLE);
            titleTv.setText(title);
            contentTv.setText(content);
        }
        //Modify Journal
        else if(flag==2){
            submitIb.setVisibility(View.VISIBLE);
            titleTv.setVisibility(View.INVISIBLE);
            contentTv.setVisibility(View.INVISIBLE);
            titleEt.setVisibility(View.VISIBLE);
            contentEt.setVisibility(View.VISIBLE);
            titleEt.setText(title);
            contentEt.setText(content);
            submitIb.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if(titleEt==null || titleEt.getText().toString().trim().equals("")){
                        Toast.makeText(DiaryInfoActivity.this, "Please enter a title",
                                Toast.LENGTH_LONG).show();
                        return;
                    }
                    if(contentEt==null || contentEt.getText().toString().trim().equals("")){
                        Toast.makeText(DiaryInfoActivity.this, "Please enter the content",
                                Toast.LENGTH_LONG).show();
                        return;
                    }
                    //Update a message from Sqlite
                    DiaryDbHelper dbHelper = new DiaryDbHelper(DiaryInfoActivity.this);
                    SQLiteDatabase db = dbHelper.getWritableDatabase();
                    //Format time
                    SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM-dd HH:mm");
                    String date = sd.format(new Date());
                    ContentValues values = new ContentValues();
                    values.put(SQLiteContract.DiaryEntry.COLUMN_NAME_TITLE,titleEt.getText().toString());
                    values.put(SQLiteContract.DiaryEntry.COLUMN_NAME_CONTENT,contentEt. getText().toString());
                    values.put(SQLiteContract.DiaryEntry.COLUMN_NAME_TIME,date);
                    //Execute update method
                    String selection = SQLiteContract.DiaryEntry._ID+"=?"; String[] selectionArgs = {id};
                    int count = db.update( SQLiteContract.DiaryEntry.TABLE_NAME, values, selection,selectionArgs );
                    DiaryInfoActivity.this.finish();
                }
            });
        }
    }

    private void setSupportActionBar(Toolbar toolbar) {
    }

    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        switch (item.getItemId()){
            //Override the behavior of the ToolBar return button to close this Activity
            case android.R.id.home: finish(); return true; }return super.onOptionsItemSelected(item);
    }
}

//DiaryListAdapter.java
package com.example.sqlitedemo;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageButton;
import android.widget.TextView;

import java.util.List;
import java.util.Map;

public class DiaryListAdapter extends BaseAdapter {
    private static final String TAG="DiaryListAdapter";
    private Context context;
    private List<Map<String, String>> list;
    public DiaryListAdapter(Context context, List<Map<String, String>> list) {
        this.context = context;
        this.list = list;
    }
    @Override
    public int getCount() {
        return list.size();
    }
    @Override
    public Object getItem(int position) {
        return list.get(position);
    }
    @Override
    public long getItemId(int position) {
        return 0;
    }
    @Override
    public View getView(final int position, View convertView, ViewGroup parent) {
        ViewHolder holder;
        if (convertView == null) {
            final LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            convertView = inflater.inflate(R.layout.listview_item,null);
            holder = new ViewHolder();
            holder.titleTv = (TextView) convertView.findViewById(R.id.title_tv);
            holder.timeTv = (TextView) convertView.findViewById(R.id.time_tv);
            holder.editIb = (ImageButton) convertView.findViewById(R.id.edit_ib);
            holder.deleteIb = (ImageButton) convertView.findViewById(R.id.delete_ib);
            convertView.setTag(holder);
        } else {
            holder = (ViewHolder) convertView.getTag();
        }
        holder.titleTv.setText(list.get(position).get(SQLiteContract.DiaryEntry.COLUMN_NAME_TITLE));
        holder.timeTv.setText(list.get(position).get(SQLiteContract.DiaryEntry.COLUMN_NAME_TIME));
        holder.editIb.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //Intent intent = new Intent(context, DiaryInfoActivity.class);
                Intent intent = new Intent(context,DiaryInfoActivity.class);
                intent.putExtra("FLAG",2);
                intent.putExtra(SQLiteContract.DiaryEntry._ID,list.get(position).get(SQLiteContract.DiaryEntry._ID));
                intent.putExtra(SQLiteContract.DiaryEntry.COLUMN_NAME_TITLE,list.get(position).get(SQLiteContract.DiaryEntry.COLUMN_NAME_TITLE));
                intent.putExtra(SQLiteContract.DiaryEntry.COLUMN_NAME_CONTENT,list. get(position).get(SQLiteContract.DiaryEntry.COLUMN_NAME_CONTENT));
                context.startActivity(intent);
            }
        });
        holder.deleteIb.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                AlertDialog.Builder builder = new AlertDialog. Builder                                                                  (context);
                builder.setTitle("Tips")
                        .setMessage("Confirm deletion?")
                        .setPositiveButton("determine", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                DiaryDbHelper dbHelper = new DiaryDbHelper(context);
                                SQLiteDatabase db = dbHelper.getWritableDatabase();
                                String selection = SQLiteContract.DiaryEntry._ID+" = ?";
                                String[] selectionArgs = {
                                        list.get(position).get(SQLiteContract.DiaryEntry._ID)
                                };
                                db.delete(SQLiteContract.DiaryEntry.TABLE_NAME,selection,selectionArgs);
                                db.close();
                                list.remove(position);
                                notifyDataSetChanged();
                            }
                        })
                        .setNegativeButton("cancel", null);
                builder.show();
            }
        });
        return convertView;
    }
    static class ViewHolder {
        TextView titleTv, timeTv;
        ImageButton editIb, deleteIb;
    }
}

//DiaryDbHelper.java
package com.example.sqlitedemo;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

public class DiaryDbHelper extends SQLiteOpenHelper {
    public static final int DATABASE_VERSION = 1;
    public static final String DATABASE_NAME = "DiaryDB.db";
    private static final String TEXT_TYPE = " TEXT";
    private static final String DATE_TYPE = " DATE";
    private static final String COMMA_SEP = ",";
    private static final String SQL_CREATE_ENTRIES =
            "CREATE TABLE " + SQLiteContract.DiaryEntry.TABLE_NAME+"("+ SQLiteContract.DiaryEntry._ID+ " " +
                    "INTEGER PRIMARY KEY AUTOINCREMENT,"+ SQLiteContract.DiaryEntry.COLUMN_NAME_TITLE+ TEXT_TYPE+COMMA_SEP+
                    SQLiteContract.DiaryEntry.COLUMN_NAME_CONTENT+ TEXT_TYPE+COMMA_SEP+ SQLiteContract.DiaryEntry.COLUMN_NAME_TIME+
                    DATE_TYPE+")";
    private static final String SQL_DELETE_ENTRIES =
            "DROP TABLE IF EXISTS " + SQLiteContract.DiaryEntry.TABLE_NAME;
    public DiaryDbHelper(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }
    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL(SQL_CREATE_ENTRIES);
    }
    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        db.execSQL(SQL_DELETE_ENTRIES);
        onCreate(db);
    }
}

//SQLiteContract.java
package com.example.sqlitedemo;

import android.provider.BaseColumns;

public final class SQLiteContract {
    //To prevent the user from accidentally instantiating the class constructor,
    //Privatize constructors
    private SQLiteContract() {}
    //This inner class defines the contents of the table
    public static class DiaryEntry implements BaseColumns {
        public static final String TABLE_NAME = "diary";
        public static final String COLUMN_NAME_TITLE = "title";
        public static final String COLUMN_NAME_CONTENT = "content";
        public static final String COLUMN_NAME_TIME = "time";
    }
}
//activity_login.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">

        <Space
            android:layout_width="match_parent"
            android:layout_height="197dp" />

        <EditText
            android:id="@+id/usename_edtxt"
            android:layout_width="275dp"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:drawableLeft="@drawable/username"
            android:drawablePadding="12dp"
            android:gravity="center|left"
            android:hint="enter one user name"
            android:textColorHint="@android:color/darker_gray"
            android:textSize="24sp"
            tools:ignore="MissingConstraints" />

        <Space
            android:layout_width="match_parent"
            android:layout_height="46dp" />

        <EditText
            android:id="@+id/password_edtxt"
            android:layout_width="272dp"
            android:layout_height="55dp"
            android:drawableLeft="@drawable/password"
            android:drawablePadding="12dp"
            android:gravity="center|left"
            android:hint="Please input a password"
            android:layout_gravity="center"
            android:inputType="textPassword"
            android:textColorHint="@android:color/darker_gray"
            android:textSize="24sp"
            tools:ignore="MissingConstraints" />

        <Space
            android:layout_width="match_parent"
            android:layout_height="60dp" />

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="horizontal">

            <Space
                android:layout_width="47dp"
                android:layout_height="50dp" />

            <Button
                android:id="@+id/submit_button"
                android:layout_width="80dp"
                android:layout_height="wrap_content"
                android:backgroundTint="@color/white"
                android:text="determine"
                tools:ignore="MissingConstraints" />

            <Space
                android:layout_width="150dp"
                android:layout_height="53dp" />

            <Button
                android:id="@+id/register_button"
                android:layout_width="80dp"
                android:layout_height="wrap_content"
                android:backgroundTint="@color/white"
                android:text="register"

                tools:ignore="DuplicateIds,MissingConstraints" />

        </LinearLayout>

    </LinearLayout>

</androidx.constraintlayout.widget.ConstraintLayout>

//register.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">

        <Space
            android:layout_width="match_parent"
            android:layout_height="197dp" />

        <EditText
            android:id="@+id/usename_edtxt"
            android:layout_width="275dp"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:drawableLeft="@drawable/username"
            android:drawablePadding="12dp"
            android:gravity="center|left"
            android:hint="enter one user name"
            android:textColorHint="@android:color/darker_gray"
            android:textSize="24sp"
            tools:ignore="MissingConstraints" />

        <Space
            android:layout_width="match_parent"
            android:layout_height="46dp" />

        <EditText
            android:id="@+id/password_edtxt"
            android:layout_width="272dp"
            android:layout_height="55dp"
            android:drawableLeft="@drawable/password"
            android:drawablePadding="12dp"
            android:gravity="center|left"
            android:hint="Please input a password"
            android:layout_gravity="center"
            android:inputType="textPassword"
            android:textColorHint="@android:color/darker_gray"
            android:textSize="24sp"
            tools:ignore="MissingConstraints" />

        <Space
            android:layout_width="match_parent"
            android:layout_height="60dp" />

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="horizontal">

            <Space
                android:layout_width="150dp"
                android:layout_height="53dp" />

            <Button
                android:id="@+id/register_button"
                android:layout_width="80dp"
                android:layout_height="wrap_content"
                android:backgroundTint="@color/white"
                android:text="register"

                tools:ignore="DuplicateIds,MissingConstraints" />

        </LinearLayout>

    </LinearLayout>

</androidx.constraintlayout.widget.ConstraintLayout>

5, Subject realization display

 

 

Enter the login interface and enter the user name and password. This cannot be blank. At this time, the entered user name is not registered, so it will enter the registration interface (please register first) or directly click the registration button to enter the registration interface (register). Register, enter the user name and password, click the register button to display (successful registration), and you will return to the login interface. Enter the previously registered user name and password, and you will enter the main interface of the journal to display (successful login).  

 

Click Edit to delete the diary content. Click the plus sign to add the diary content. Click tick to save.  

 

Click the edit picture button on the right of the journal title to enter the modification interface.  

  

Click the Journal Title line to view the journal content. Click Edit to delete the journal, click × A deletion prompt appears.  

6, Summary and experience

The login and registration interface is designed through advanced controls. At the same time, SQLiteOpenHelper abstract class and contract class SQLiteContract are used to create subclasses of SQLiteOpenHelper and override onCreate method. The assessment content is basically completed. Learning the use of database makes me better master the application of Android database. Through searching data and learning, I finish the production of log in and jump into the diary first. Through this experiment, I gained a lot, reviewed my previous knowledge and learned new content, which is of great help to my future study.

 

 

Download resource pack:

 https://download.csdn.net/download/weixin_48388330/76315152

The pictures and contents in the resources are only applicable to learning

Keywords: Java Android Android Studio Design Pattern

Added by tomkleijkers on Tue, 18 Jan 2022 21:37:49 +0200