Android - Notepad function business (complete code)

Table of contents

achieve effect

1. Build the Notepad page layout activity_notepad.xml

2. Build the Notepad interface Item layout notepad_item_layout.xml

3. Encapsulation record information entity class NotepadBean class

Fourth, write the Notepad interface list adapter NotepadAdapter class

5. Create a database

6. Realize the display function of Notepad interface NotepadAdapter.java 

7. Build the layout activity_record.xml of adding record interface and modifying record interface 

8. Realize the function of adding record interface RecordActivity.java 

9. Realize the function of modifying the record interface 

10. Delete records in Notepad 


achieve effect

1. Build the Notepad page layout activity_notepad.xml

1. Create a project

The project name is Notepad, and the specified package name is cn.itcast.notepad

Activity name is NotepadActivity, layout file name is activity_notepad

2. Import the picture to a newly created folder drawable-hdpi under the res folder

3. The page code is as follows

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#fefefe">
    <TextView
        android:id="@+id/note_name"
        android:layout_width="match_parent"
        android:layout_height="45dp"
        android:textSize="20sp"
        android:textColor="@android:color/white"
        android:gravity="center"
        android:textStyle="bold"
        android:background="#fb7a6a"
        android:text="记事本"/>
    <ListView
        android:id="@+id/listview"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:cacheColorHint="#00000000"
        android:divider="#E4E4E4"
        android:dividerHeight="1dp"
        android:fadingEdge="none"
        android:listSelector="#00000000"
        android:scrollbars="none"
        android:layout_below="@+id/note_name">
    </ListView>
    <ImageView
        android:id="@+id/add"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/add"
        android:layout_marginBottom="30dp"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true"/>
</RelativeLayout>

4. Modify the manifest file

After the project is created, there is a green default title bar at the top of all interfaces, which is not beautiful. Modify the code in AndroidManifest.xml to remove the title bar. In the <application> tag, modify it to:

android:theme="@style/Theme.AppCompat.NoActionBar"

2. Build the Notepad interface Item layout notepad_item_layout.xml

Since the Notepad interface uses the ListView control to display the record list, it is necessary to create an Item interface for the list.

1. Create a layout file

In the res/layout folder, right click [NEW] - [XML] - [Layout XML File], the name is notepad_item_layout

2. Layout notepad_item_layout.xml interface

Place two TextView controls, which are used to display part of the record and the saved time respectively.

code show as below:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#fefefe">
    <TextView
        android:id="@+id/note_name"
        android:layout_width="match_parent"
        android:layout_height="45dp"
        android:textSize="20sp"
        android:textColor="@android:color/white"
        android:gravity="center"
        android:textStyle="bold"
        android:background="#fb7a6a"
        android:text="记事本"/>
    <ListView
        android:id="@+id/listview"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:cacheColorHint="#00000000"
        android:divider="#E4E4E4"
        android:dividerHeight="1dp"
        android:fadingEdge="none"
        android:listSelector="#00000000"
        android:scrollbars="none"
        android:layout_below="@+id/note_name">
    </ListView>
    <ImageView
        android:id="@+id/add"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/add"
        android:layout_marginBottom="30dp"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true"/>
</RelativeLayout>

3. Encapsulation record information entity class NotepadBean class

Create a NotepadBean class to store the record content and save time attributes of each record.

1. Select the cn.itcast.notepad package, right click - [New] - [Package], name it bean, and create a bean package.

In the package, right-click - [New] - [JavaClass], named NotepadBean.

2. NotepadBean.java code is as follows

package cn.itcast.notepad.bean;

public class NotepadBean {
    private String id;                  //记录的id
    private String notepadContent;   //记录的内容
    private String notepadTime;       //保存记录的时间
 //右击-【Generate】-【Getter and Setter】,产生下面代码
    public String getId() {
        return id;
    }
    public void setId(String id) {
        this.id = id;
    }
    public String getNotepadContent() {
        return notepadContent;
    }
    public void setNotepadContent(String notepadContent) {
        this.notepadContent = notepadContent;
    }
    public String getNotepadTime() {
        return notepadTime;
    }
    public void setNotepadTime(String notepadTime) {
        this.notepadTime = notepadTime;
    }
}

Fourth, write the Notepad interface list adapter NotepadAdapter class

Create a data adapter NotepadAdapter to perform data adaptation on the ListView control.

1. Select the cn.itcast.notepad package, right-click - [New] - [Package], and name it adapter.

In the package, right-click - [New] - [JavaClass], named NotepadAdapter.

 2. (1) The NotepadAdapter class inherits from the BaseAdapter class, then click [Alt] + [Enter], [implement methods] rewrite the methods getCount(), getItem(), getItemId(), getView().

(2) Create a constructor

public NotepadAdapter(Context context, List<NotepadBean> list)

Use the inflate() method to load the layout file of the Item interface.

private LayoutInflater layoutInflater;
    private List<NotepadBean> list;
    public NotepadAdapter(Context context, List<NotepadBean> list){
        this.layoutInflater=LayoutInflater.from(context);
        this.list=list;
    }

(3) Create the ViewHolder class

Create a construction method in the class, and initialize the controls on the Item interface (ie notepad_item_layout.xml) in this method.

public ViewHolder(View view){
            tvNoteoadContent=(TextView) view.findViewById(R.id.item_content);
            tvNotepadTime=(TextView) view.findViewById(R.id.item_time);
        }

Then continue to write code in the getView method 

3. The code is as follows:

package cn.itcast.notepad.adapter;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;

import java.util.List;

import cn.itcast.notepad.R;
import cn.itcast.notepad.bean.NotepadBean;

public class NotepadAdapter extends BaseAdapter{
    private LayoutInflater layoutInflater;
    private List<NotepadBean> list;
    public NotepadAdapter(Context context, List<NotepadBean> list){
        this.layoutInflater=LayoutInflater.from(context);
        this.list=list;
    }
    @Override
    public int getCount() {
        return list==null ? 0 : list.size();
    }
    @Override
    public Object getItem(int position) {
        return list.get(position);
    }
    @Override
    public long getItemId(int position) {
        return position;
    }
    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder viewHolder;
        if (convertView==null){
            convertView=layoutInflater.inflate(R.layout.notepad_item_layout,null);
            viewHolder=new ViewHolder(convertView);
            convertView.setTag(viewHolder);
        }else {
            viewHolder=(ViewHolder) convertView.getTag();
        }
        NotepadBean noteInfo=(NotepadBean) getItem(position);
        viewHolder.tvNoteoadContent.setText(noteInfo.getNotepadContent());
        viewHolder.tvNotepadTime.setText(noteInfo.getNotepadTime());
        return convertView;
    }
    class ViewHolder{
        TextView tvNoteoadContent;;
        TextView tvNotepadTime;
        public ViewHolder(View view){
            tvNoteoadContent=(TextView) view.findViewById(R.id.item_content);
            tvNotepadTime=(TextView) view.findViewById(R.id.item_time);
        }
    }
}

5. Create a database

In this notepad program, storing and reading recorded data are all done by operating the database, so it is necessary to create the database class SQLiteHelper and the database tool class DBUtils.java.

(1) Create DBUtils class

In this class, define the name of the database, table name, database version, column name in the database table, and obtain information such as the current date.

1. Select the cn.itcast.notepad package, right-click - [New] - [Package], and name it utils.

In the package, right-click - [New] - [JavaClass], named DBUtils.

 2. The code of DBUtils.java is as follows

package cn.itcast.notepad.utils;

import java.text.SimpleDateFormat;
import java.util.Date;
public class DBUtils {
    public static final String DATABASE_NAME = "Notepad";//数据库名
    public static final String DATABASE_TABLE = "Note";  //表名
    public static final int DATABASE_VERION = 1;          //数据库版本
    //数据库表中的列名
    public static final String NOTEPAD_ID = "id";
    public static final String NOTEPAD_CONTENT = "content";
    public static final String NOTEPAD_TIME = "notetime";
    //获取当前日期
    public static final String getTime(){
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");
        Date date = new Date(System.currentTimeMillis());
        return simpleDateFormat.format(date);
    }
}

(2) Create the SQLiteHelper class

Create a Notepad database to realize the function of adding, deleting, modifying and checking.

1. Select the cn.itcast.notepad package, right-click - [New] - [Package], and name it database.

In the package, right-click - [New] - [JavaClass], named SQLiteHelper.

2. The SQLiteHelper.java code is as follows

package cn.itcast.notepad.database;

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

import java.util.ArrayList;
import java.util.List;

import cn.itcast.notepad.bean.NotepadBean;
import cn.itcast.notepad.utils.DBUtils;

public class SQLiteHelper extends SQLiteOpenHelper {
    private SQLiteDatabase sqLiteDatabase;
    //创建数据库
    public SQLiteHelper(Context context){
        super(context, DBUtils.DATABASE_NAME, null, DBUtils.DATABASE_VERION);//调用了DBUtils类,得到数据库名Notepad
        sqLiteDatabase = this.getWritableDatabase();
    }
    //创建表,用execSQL()方法创建一个数据表,列名分别为ID、CONTENT、TIME
    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL("create table "+DBUtils.DATABASE_TABLE+"("+DBUtils.NOTEPAD_ID+
                " integer primary key autoincrement,"+ DBUtils.NOTEPAD_CONTENT +
                " text," + DBUtils.NOTEPAD_TIME+ " text)");
    }
    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {}
    //添加数据
    public boolean insertData(String userContent,String userTime){
        ContentValues contentValues=new ContentValues();
        contentValues.put(DBUtils.NOTEPAD_CONTENT,userContent);
        contentValues.put(DBUtils.NOTEPAD_TIME,userTime);
        return
                sqLiteDatabase.insert(DBUtils.DATABASE_TABLE,null,contentValues)>0;
    }
    //删除数据
    public boolean deleteData(String id){
        String sql=DBUtils.NOTEPAD_ID+"=?";
        String[] contentValuesArray=new String[]{String.valueOf(id)};
        return
                sqLiteDatabase.delete(DBUtils.DATABASE_TABLE,sql,contentValuesArray)>0;
    }
    //修改数据
    public boolean updateData(String id,String content,String userYear){
        ContentValues contentValues=new ContentValues();
        contentValues.put(DBUtils.NOTEPAD_CONTENT,content);
        contentValues.put(DBUtils.NOTEPAD_TIME,userYear);
        String sql=DBUtils.NOTEPAD_ID+"=?";
        String[] strings=new String[]{id};
        return
                sqLiteDatabase.update(DBUtils.DATABASE_TABLE,contentValues,sql,strings)>0;
    }
    //查询数据
    public List<NotepadBean> query(){//将遍历的数据存放在一个List<NotepadBean>类型的合集中
        List<NotepadBean> list=new ArrayList<NotepadBean>();
//        通过query()方法查询数据库表中的所有数据,并返回一个Cursor对象
        Cursor cursor=sqLiteDatabase.query(DBUtils.DATABASE_TABLE,null,null,null,
                null,null,DBUtils.NOTEPAD_ID+" desc");
        if (cursor!=null){
            while (cursor.moveToNext()){//通过while循环遍历Cursor对象中的数据
                NotepadBean noteInfo=new NotepadBean();
                String id = String.valueOf(cursor.getInt
                        (cursor.getColumnIndex(DBUtils.NOTEPAD_ID)));
                String content = cursor.getString(cursor.getColumnIndex
                        (DBUtils.NOTEPAD_CONTENT));
                String time = cursor.getString(cursor.getColumnIndex
                        (DBUtils.NOTEPAD_TIME));
                noteInfo.setId(id);
                noteInfo.setNotepadContent(content);
                noteInfo.setNotepadTime(time);
                list.add(noteInfo);
            }
            cursor.close();
        }
        return list;
    }
}

6. Realize the display function of Notepad interface NotepadAdapter.java 

1. Including display list function and add button function

2. Steps

Initialize the ListView control, initialize the add button

    listView = (ListView) findViewById(R.id.listview);
    ImageView add = (ImageView) findViewById(R.id.add);

Create the initData() method to initialize the data to be written in this method

    protected void initData() {
        mSQLiteHelper= new SQLiteHelper(this); //创建数据库
        showQueryData();
   }

Create the showQueryData() method, in which the data in the database is obtained and displayed in the list.
First call the query() method to query the data stored in the database, and the return value is a collection of lists.
Then set up an adapter to transfer the acquired record data to the NotepadAdapter. Two parameters need to be passed in, one is the context information, and the second is a collection.
Finally, set the NotepadAdapter adapter for the ListView control through the setAdapter() method.

list = mSQLiteHelper.query();
adapter = new NotepadAdapter(this, list);
listView.setAdapter(adapter);

The initData() method is called in the onCreat() method.

Set click event for ImageView To
create an intent object, two parameters need to be passed in, one is the context information, and the second is the name of the activity to jump to.
Call the startActivityForResult() method to jump to the adding record interface.

add.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(NotepadActivity.this,
                        RecordActivity.class);
                startActivityForResult(intent, 1);
            }
        });

Override the onActivityResult() method, which is called when the interface for adding records is closed.

First judge whether the request code is 1 and the return code is 2 (this is set in the add record interface), if yes, call the showQueryData() method to retrieve the data and display it.

protected void onActivityResult(int requestCode,int resultCode, Intent data){
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode==1&&resultCode==2){
            showQueryData();
        }
    }

3. NotepadAdapter.java specific code is as follows

package cn.itcast.notepad;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.Toast;

import java.util.List;

import cn.itcast.notepad.adapter.NotepadAdapter;
import cn.itcast.notepad.bean.NotepadBean;
import cn.itcast.notepad.database.SQLiteHelper;

public class NotepadActivity extends Activity {
    ListView listView;
    List<NotepadBean> list;
    SQLiteHelper mSQLiteHelper;
    NotepadAdapter adapter;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_notepad);
        //用于显示便签的列表
        listView = (ListView) findViewById(R.id.listview);
        ImageView add = (ImageView) findViewById(R.id.add);
        add.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(NotepadActivity.this,
                        RecordActivity.class);
                startActivityForResult(intent, 1);
            }
        });
        initData();
    }
    protected void initData() {
        mSQLiteHelper= new SQLiteHelper(this); //创建数据库
        showQueryData();
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent,View view,int position,long id){
                NotepadBean notepadBean = list.get(position);
                Intent intent = new Intent(NotepadActivity.this, RecordActivity.class);
                intent.putExtra("id", notepadBean.getId());
                intent.putExtra("time", notepadBean.getNotepadTime()); //记录的时间
                intent.putExtra("content", notepadBean.getNotepadContent()); //记录的内容
                NotepadActivity.this.startActivityForResult(intent, 1);
            }
        });
        listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> parent, View view, final int
                    position, long id) {
                AlertDialog dialog;
                AlertDialog.Builder builder = new AlertDialog.Builder( NotepadActivity.this)
                        .setMessage("是否删除此事件?")
                        .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                NotepadBean notepadBean = list.get(position);
                                if(mSQLiteHelper.deleteData(notepadBean.getId())){
                                    list.remove(position);
                                    adapter.notifyDataSetChanged();
                                    Toast.makeText(NotepadActivity.this,"删除成功",
                                            Toast.LENGTH_SHORT).show();
                                }
                            }
                        })
                        .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.dismiss();
                            }
                        });
                dialog =  builder.create();
                dialog.show();
                return true;
            }
        });

    }
    private void showQueryData(){
        if (list!=null){
            list.clear();
        }
        //从数据库中查询数据(保存的标签)
        list = mSQLiteHelper.query();
        adapter = new NotepadAdapter(this, list);
        listView.setAdapter(adapter);
    }
    @Override
    protected void onActivityResult(int requestCode,int resultCode, Intent data){
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode==1&&resultCode==2){
            showQueryData();
        }
    }
}

7. Build the layout activity_record.xml of adding record interface and modifying record interface 

When clicking the "Add" button on the notepad interface, it will jump to the adding record interface, and when clicking an item in the list on the notepad interface, it will jump to the modifying record interface. Since the controls and functions on the two interfaces are basically the same, the same Activity and the same layout file are set to be displayed.

1. Select the cn.itcast.notepad package, right-click - [New] - [Activity], and name it RecordActivity

2. The activity_record.xml code is as follows

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#fefefe">
    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="45dp"
        android:background="#fb7a6a"
        android:orientation="horizontal">
        <ImageView
            android:id="@+id/note_back"
            android:layout_width="45dp"
            android:layout_height="wrap_content"
            android:layout_centerVertical="true"
            android:paddingLeft="11dp"
            android:src="@drawable/back" />
        <TextView
            android:id="@+id/note_name"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerInParent="true"
            android:gravity="center"
            android:text="记事本"
            android:textColor="@android:color/white"
            android:textSize="15sp"
            android:textStyle="bold" />
    </RelativeLayout>
    <TextView
        android:id="@+id/tv_time"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textSize="15sp"
        android:paddingTop="10dp"
        android:paddingBottom="10dp"
        android:gravity="center"
        android:visibility="gone"
        android:textColor="#fb7a6a"/>
    <EditText
        android:id="@+id/note_content"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_weight="1"
        android:gravity="top"
        android:hint="请输入要添加的内容"
        android:paddingLeft="5dp"
        android:textColor="@android:color/black"
        android:background="#fefefe" />
    <View
        android:layout_width="match_parent"
        android:layout_height="1dp"
        android:background="#fb7a6a"/>
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="55dp"
        android:orientation="horizontal">
        <ImageView
            android:id="@+id/delete"
            android:layout_width="0dp"
            android:layout_weight="1"
            android:layout_height="wrap_content"
            android:src="@drawable/delete"
            android:paddingBottom="15dp"
            android:paddingTop="9dp"/>
        <ImageView
            android:id="@+id/note_save"
            android:layout_width="0dp"
            android:layout_weight="1"
            android:layout_height="wrap_content"
            android:src="@drawable/save_note"
            android:paddingBottom="15dp"
            android:paddingTop="9dp"/>
    </LinearLayout>
</LinearLayout>

8. Realize the function of adding record interface RecordActivity.java 

1. Including edit record, save record, clear record function

2. Steps

Initialize interface controls and set click events.

The switch determines which control the clicked button belongs to by id.
When the "Save" button is selected, first get the content in the input box getText(), convert the text information into a string toString(), and then clear the empty string with trim().
Then judge whether the input content is > 0. If it is greater than 0, call the insertData() method to add the record to the database. Two parameters need to be passed in, one is the input content, and the other is the time when the save button is clicked.
Next, judge whether the data is saved successfully. If it is successful, a "saved successfully" prompt will pop up. If it fails, a "save failed" prompt will pop up. So you need to create a showToast() method. If the save is successful, the setResult() method should be called to return a return code: 2.

The showToast() method is used to display some information, and the makeText() method is called in this method.

Create the initData() method, which creates the database.

The initData() method is called in the onCreat() method.

3. Specific code RecordActivity.java

package cn.itcast.notepad;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import cn.itcast.notepad.database.SQLiteHelper;
import cn.itcast.notepad.utils.DBUtils;

public class RecordActivity extends Activity implements View.OnClickListener {
    ImageView note_back;
    TextView note_time;
    EditText content;
    ImageView delete;
    ImageView note_save;
    SQLiteHelper mSQLiteHelper;
    TextView noteName;
    String id;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_record);
        note_back = (ImageView) findViewById(R.id.note_back);
        note_time = (TextView)findViewById(R.id.tv_time);
        content = (EditText) findViewById(R.id.note_content);
        delete = (ImageView) findViewById(R.id.delete);
        note_save = (ImageView) findViewById(R.id.note_save);
        noteName = (TextView) findViewById(R.id.note_name);
        note_back.setOnClickListener(this);
        delete.setOnClickListener(this);
        note_save.setOnClickListener(this);
        initData();
    }
    protected void initData() {
        mSQLiteHelper = new SQLiteHelper(this);
        noteName.setText("添加记录");
        Intent intent = getIntent();
        if(intent!= null){
            id = intent.getStringExtra("id");
            if (id != null){
                noteName.setText("修改记录");
                content.setText(intent.getStringExtra("content"));
                note_time.setText(intent.getStringExtra("time"));
                note_time.setVisibility(View.VISIBLE);
            }
        }
    }
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.note_back:
                finish();
                break;
            case R.id.delete:
                content.setText("");
                break;
            case R.id.note_save:
                String noteContent=content.getText().toString().trim();
                if (id != null){//修改操作
                    if (noteContent.length()>0){
                        if (mSQLiteHelper.updateData(id, noteContent, DBUtils.getTime())){
                            showToast("修改成功");
                            setResult(2);
                            finish();
                        }else {
                            showToast("修改失败");
                        }
                    }else {
                        showToast("修改内容不能为空!");
                    }
                }else {
                    //向数据库中添加数据
                    if (noteContent.length()>0){
                        if (mSQLiteHelper.insertData(noteContent, DBUtils.getTime())){
                            showToast("保存成功");
                            setResult(2);
                            finish();
                        }else {
                            showToast("保存失败");
                        }
                    }else {
                        showToast("修改内容不能为空!");
                    }
                }
                break;
        }
    }
    public void showToast(String message){
        Toast.makeText(RecordActivity.this,message,Toast.LENGTH_SHORT).show();
    }
}

9. Realize the function of modifying the record interface 

(Remarks: The previous code already contains this content, just figure it out here)  

Compared with adding record interface, it has more functions of viewing records and modifying records.

1. Realize the function of viewing records.

(1) Each Item in the notepad interface list only displays 2 lines of record information. If you want to view more record content, you need to click the Item to enter the modification record interface to view.

(2) In the initDate() method of NotepadActivity, add the code that jumps to the modification record interface.
The click event of the Item is realized through the setOnItemClickListener() method. When the Item is clicked, the onItemClick() method will be called. In this method, the corresponding Item data is first obtained through the get() method. To create an intent object, two parameters need to be passed in, one is the context information, and the other is the name of the activity that needs to be redirected. Then encapsulate these data into the intent object through the putExtra() method, and finally call the startActivityForResult() method to jump to the modification record interface, and set the request code to 1.

protected void initData() {
        ...
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent,View view,int position,long id){
                NotepadBean notepadBean = list.get(position);
                Intent intent = new Intent(NotepadActivity.this, RecordActivity.class);
                intent.putExtra("id", notepadBean.getId());
                intent.putExtra("time", notepadBean.getNotepadTime()); //记录的时间
                intent.putExtra("content", notepadBean.getNotepadContent()); //记录的内容
                NotepadActivity.this.startActivityForResult(intent, 1);
            }
        });

(3) Find the initData() method in RecordActivity, in this method receive the record data passed by the Notepad interface and display it on the interface.
First get the intent object, and then determine whether the object is empty. If not null, gets the passed data.
Get the id first, and judge whether the id is empty. If it is not empty, you need to set the title as "Modification Record". Then obtain the record time and record content respectively through get and display them through set, and finally set the record time to the display state.

protected void initData() {
        mSQLiteHelper = new SQLiteHelper(this);
        noteName.setText("添加记录");
        Intent intent = getIntent();
        if(intent!= null){
            id = intent.getStringExtra("id");
            if (id != null){
                noteName.setText("修改记录");
                content.setText(intent.getStringExtra("content"));
                note_time.setText(intent.getStringExtra("time"));
                note_time.setVisibility(View.VISIBLE);
            }
        }
    }

2. Realize the modification record function

(1) In the onClick() method of RecordActivity, find the click event of the "Save" button. In this event, judge whether the passed id is empty. If not, it is the function of modifying the record. Pass the id of the modified record, the modified content, and the time to save the modified record to the updateData() method for modification.
If it is empty, it is to add the recording function.

(2) Specific code:

public void onClick(View v) {
        switch (v.getId()) {
            ...
            case R.id.note_save:
                String noteContent=content.getText().toString().trim();
                if (id != null){//修改操作
                    if (noteContent.length()>0){
                        if (mSQLiteHelper.updateData(id, noteContent, DBUtils.getTime())){
                            showToast("修改成功");
                            setResult(2);
                            finish();
                        }else {
                            showToast("修改失败");
                        }
                    }else {
                        showToast("修改内容不能为空!");
                    }
                }else {
                    ...
        }
    }

10. Delete records in Notepad 

(Remarks: The previous code already contains this content, just figure it out here) 

(1) When you press and hold the Item in the list, a dialog box will pop up to prompt whether to delete the record, so add the code to delete the record in the initData() method of NotepadActivity.

(2) First, set the listener for the long press event through setOnItemLongClickListener(). When the Item is long pressed, the onItemLongClick() method is called, and the long press event is implemented in this method.
Create an AlertDialog dialog box to prompt the user whether to delete. Create a Builder object and pass context information into this object.

(3) The initData() method code of NotepadActivity:

listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> parent, View view, final int
                    position, long id) {
                AlertDialog dialog;
                AlertDialog.Builder builder = new AlertDialog.Builder( NotepadActivity.this)
                        .setMessage("是否删除此事件?")
                        .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                NotepadBean notepadBean = list.get(position);
                                if(mSQLiteHelper.deleteData(notepadBean.getId())){
                                    list.remove(position);
                                    adapter.notifyDataSetChanged();
                                    Toast.makeText(NotepadActivity.this,"删除成功",
                                            Toast.LENGTH_SHORT).show();
                                }
                            }
                        })
                        .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.dismiss();
                            }
                        });
                dialog =  builder.create();
                dialog.show();
                return true;
            }
        });

Guess you like

Origin blog.csdn.net/weixin_72634509/article/details/127634062