实现一个简单的记事本APP

这篇具有很好参考价值的文章主要介绍了实现一个简单的记事本APP。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

这个例子主要是使用android开发出一个简单的记事本应用,可以实现数据的增加、修改以及删除等操作。
主要参考:哔哩哔哩up主:子林android。

主要涉及的相关知识:
1、控件RecyclerView的使用
2、轻量级数据库SQLite的使用
3、activity之间的跳转以及参数传递
首先创建MainActivity
为方便这里使用的是帧布局FrameLayout,主要包含两个控件,一个是用于显示记事本相关信息的RecyclerView,另一个是用于进行添加记事信息FloatingActionButton按钮,布局文件代码如下:

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">
    
    <androidx.recyclerview.widget.RecyclerView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/rlv"/>
        
    <com.google.android.material.floatingactionbutton.FloatingActionButton
        android:id="@+id/btn_add"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/ic_baseline_add_24"
        android:layout_gravity="bottom|right"
        android:layout_margin="20dp"
        android:background="@color/green_200"
        android:onClick="add"/>
</FrameLayout>

接下来是对应的Java代码。首先是控件的一些初始化工作,这些在onCreate()函数中的 initView()中完成,MainActivity的对应代码如下:

public class MainActivity extends AppCompatActivity {
    private final String DB_Name="mySQLite.db";
    private RecyclerView mRecyclerView;
    private FloatingActionButton mButton;
    private List<NewsBean> newsBeanList;
    private NewsAdapter newsAdapter;
    private MySQILOpenHelper mySQILOpenHelper;
    
    @RequiresApi(api = Build.VERSION_CODES.N)
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initView();
        initData();
        initEvent();
    }

    @Override
    protected void onResume() {
        super.onResume();
        refreshDataFromDB();
    }

    private void refreshDataFromDB() {
        newsBeanList=getDataFromDB();
        newsAdapter.refreshData(newsBeanList);
    }

    private void initEvent() {
        newsAdapter=new NewsAdapter(newsBeanList,this);
        mRecyclerView.setAdapter(newsAdapter);
        LinearLayoutManager layoutManager=new LinearLayoutManager(this);
        mRecyclerView.setLayoutManager(layoutManager);
    }
    
    private void initData() {
        newsBeanList= new ArrayList<>();
        mySQILOpenHelper=new MySQILOpenHelper(this);
        newsBeanList=getDataFromDB();
    }

    private List<NewsBean> getDataFromDB() {
        return newsBeanList=mySQILOpenHelper.query();
    }

    private void initView() {
        mRecyclerView=findViewById(R.id.rlv);

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_main,menu);
        SearchView searchView= (SearchView) menu.findItem(R.id.menu_serach).getActionView();
        searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
            @Override
            public boolean onQueryTextSubmit(String query) {
                return false;
            }

            @Override
            public boolean onQueryTextChange(String newText) {
                List<NewsBean> List = mySQILOpenHelper.queryByTitle(newText);
                newsAdapter.refreshData(List);
                return true;
            }
        });
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        return super.onOptionsItemSelected(item);
    }

    public void add(View view) {
        Intent intent=new Intent(MainActivity.this,AddActivity.class);
        startActivity(intent);
    }
*

注意:当其他Activity跳转到MainActivity时,由于生命周期的原因,onCreate()函数不在执行,因此此时必须重写onResume() 函数,在onResume()中重新查询数据库相关操作,并刷新当前适配器adapter对应数据,否则MainActivity界面不会有显示信息。

其次,RecyclerView的实现还需相关的数据源,以及两者之间的桥梁适配器adapter。记事本主要有三部分信息:标题、内容和创建时间。此处我们用一个标准的JavaBean类来封装这个实体类,并使其实现Serializable从而用于后文中activity之间跳转时自定义参数的传递,代码如下:


public class NewsBean implements Serializable {
private String title;
private String content;
private String createdTime;
private int id;
public String getTitle() {
return title;
}

public void setTitle(String title) {
    this.title = title;
}

public String getContent() {
    return content;
}

public void setContent(String content) {
    this.content = content;
}

public String getCreatedTime() {
    return createdTime;
}

public void setCreatedTime(String createdTime) {
    this.createdTime = createdTime;
}

public int getId() {
    return id;
}

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

@Override
public String toString() {
    return "NewsBean{" +
            "title='" + title + '\'' +
            ", content='" + content + '\'' +
            ", createdTime='" + createdTime + '\'' +
            ", id=" + id +
            '}';
}
接下来定义一个名为NewsAdapter的适配器,继承自 RecyclerView.Adapter,代码如下,其中适配器中用到了一个布局文件new_layout.xml,用于指定记事本信息显示格式如下:
            ![在这里插入图片描述](https://img-blog.csdnimg.cn/1d8aa91ddada44e2a7a8623160859837.png)
适配器NewsAdapter的代码如下

public class NewsAdapter extends RecyclerView.Adapter<NewsAdapter.MyViewHolder> {
private List newsBeanList;
private LayoutInflater layoutInflater;
private Context context;

public NewsAdapter(List<NewsBean> newsBeanList, Context context) {
    this.newsBeanList = newsBeanList;
    this.context = context;
    layoutInflater=LayoutInflater.from(context);
}

@Override
public int getItemCount() {
    return newsBeanList.size();
}

@NonNull
@Override
public MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
    View view = layoutInflater.inflate(R.layout.new_layout, parent, false);
    MyViewHolder myViewHolder=new MyViewHolder(view);
    return myViewHolder;
}

@Override
public void onBindViewHolder(@NonNull MyViewHolder holder, @SuppressLint("RecyclerView") int position) {
    NewsBean newsBean = newsBeanList.get(position);
    holder.tvContent.setText(newsBean.getContent());
    holder.tvTitle.setText(newsBean.getTitle());
    holder.tvTime.setText(newsBean.getCreatedTime());
    holder.rlContainer.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent intent=new Intent(context, EditActivity.class);
            intent.putExtra("new",newsBean);
            context.startActivity(intent);
        }
    });
    holder.rlContainer.setOnLongClickListener(new View.OnLongClickListener() {
        @Override
        public boolean onLongClick(View v) {
            Dialog dialog=new Dialog(context,
            android.R.style.ThemeOverlay_Material_Dialog_Alert);
            View view = layoutInflater.inflate(R.layout.diag_layout, null);
            TextView tvDelete=view.findViewById(R.id.tv_delete);
            TextView tvEdit=view.findViewById(R.id.tv_edit);
            tvDelete.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    int row = mySQILOpenHelper.deleteFromDbById(newsBean.getId());
                    if(row>0){
                        deleteData(position);

                        Toast.makeText(context,"删除成功",Toast.LENGTH_SHORT).show();
                    }else {
                        Toast.makeText(context,"删除失败",Toast.LENGTH_SHORT).show();
                    }
                    dialog.dismiss();
                }
            });

            tvEdit.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent=new Intent(context, EditActivity.class);
                    intent.putExtra("new",newsBean);
                    context.startActivity(intent);
                    dialog.dismiss();
                }
            });
            dialog.setContentView(view);
            dialog.show();
            return true;
        }
    });
}

public void refreshData(List<NewsBean>list){
    this.newsBeanList=list;
    notifyDataSetChanged();
    //notifyDataSetChanged();

}

public void deleteData(int position){
    newsBeanList.remove(position);
    notifyItemRemoved(position);
}

class MyViewHolder extends RecyclerView.ViewHolder{
    TextView tvTitle,tvContent,tvTime;
    ViewGroup rlContainer;

    public MyViewHolder(@NonNull View itemView) {
        super(itemView);
        this.tvTime=itemView.findViewById(R.id.tv_time);
        this.tvContent=itemView.findViewById(R.id.tv_content);
        this.tvTitle=itemView.findViewById(R.id.tv_title);
        this.rlContainer=itemView.findViewById(R.id.rl_item_container);
    }
}

}


上述代码中,在viewHolder中为new_layout.xml整个区域设计了长按弹对话框模式(包含删除和编辑当前记事本信息),以及短按跳转至编辑界面的点击事件。

接下来是编辑界面和添加界面
分别创建名为AddActivity和EditActivity两个Activity,两个界面基本一致,界面如下:
android记事本,android,sqlite,java
对应的布局文件xml比较简单,详细代码如下:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".EditActivity"
    android:orientation="vertical"
    android:padding="10dp">
    
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:gravity="center_vertical">
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="标题"
            android:textSize="30sp"/>
        <EditText
            android:padding="5dp"
            android:background="@drawable/edit_bg"
            android:id="@+id/et_edit_title"
            android:layout_width="match_parent"
            android:layout_height="40dp"
            android:layout_marginLeft="10dp"/>
    </LinearLayout>

    <LinearLayout
        android:layout_marginTop="10dp"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical">
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="内容"
            android:textSize="30sp"/>
        <EditText
            android:padding="5dp"
            android:layout_marginTop="10dp"
            android:id="@+id/et_edit_content"
            android:layout_width="match_parent"
            android:layout_height="250dp"
            android:background="@drawable/edit_bg"/>
    </LinearLayout>
    <Button
        android:layout_marginTop="10dp"
        android:id="@+id/save"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@drawable/btn_bg"
        android:text="保存"
        android:textSize="25sp"
        android:textColor="@color/white"
        android:onClick="save"/>
</LinearLayout>

接下来最重要的就是数据库SQLite的创建,这里使用数据库帮助类SQLiteOpenHelper 来实现,包含了增,删,改和查四种操作,其代码如下:

public class MySQILOpenHelper extends SQLiteOpenHelper {
    private static final String DB_Name="mySQLite.db";
    private static final String TABLE_NAME="note";
    private static final String sql="create table "+TABLE_NAME+" (id integer primary key autoincrement,title text,content,text,createdTime text)";

    public MySQILOpenHelper(Context context){
        super(context,DB_Name,null,1);
    }
    /*public MySQILOpenHelper(Context context,String name){
        super(context,name,null,1);
    }*/


    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL(sql);

    }

    public long insertData(NewsBean newsBean){
        SQLiteDatabase db=getWritableDatabase();
        ContentValues value=new ContentValues();
        value.put("title",newsBean.getTitle());
        value.put("content",newsBean.getContent());
        value.put("createdTime",newsBean.getCreatedTime());
        return db.insert(TABLE_NAME,null,value);
    }

    public int updateData(NewsBean newsBean){
        //Log.d("TAG", "updateData: "+newsBean);
        SQLiteDatabase db=getWritableDatabase();
        ContentValues value=new ContentValues();
        //value.put("id",newsBean.getId());
        value.put("title",newsBean.getTitle());
        value.put("content",newsBean.getContent());
        value.put("createdTime",newsBean.getCreatedTime());
        return db.update(TABLE_NAME,value,"id like ?",new String[]{String.valueOf(newsBean.getId())});
    }

    public List<NewsBean> query(){
        SQLiteDatabase db=getWritableDatabase();
        List<NewsBean>newsBeanList=new ArrayList<>();
        Cursor cursor = db.query(TABLE_NAME, null, null, null, null, null, null);
        if(cursor!=null){
            while ((cursor.moveToNext())){
               @SuppressLint("Range") int id=Integer.parseInt(cursor.getString(cursor.getColumnIndex("id")));

                @SuppressLint("Range") String title=cursor.getString(cursor.getColumnIndex("title"));
                @SuppressLint("Range") String content=cursor.getString(cursor.getColumnIndex("content"));
                @SuppressLint("Range") String createdTime=cursor.getString(cursor.getColumnIndex("createdTime"));
                NewsBean newsBean=new NewsBean();
                newsBean.setId(id);
                newsBean.setCreatedTime(createdTime);
                newsBean.setContent(content);
                newsBean.setTitle(title);
                newsBeanList.add(newsBean);
            }
            cursor.close();
        }
        return newsBeanList;
    }

    public List<NewsBean> queryByTitle(String title1){
        if(TextUtils.isEmpty(title1))
        {
            return query();
        }
        SQLiteDatabase db=getWritableDatabase();
        List<NewsBean>newsBeanList=new ArrayList<>();
        Cursor cursor = db.query(TABLE_NAME, null, "title like ?", new String[]{"%"+title1+"%"}, null, null, null);
        if(cursor!=null){
            while ((cursor.moveToNext())){
                @SuppressLint("Range") int id=Integer.parseInt(cursor.getString(cursor.getColumnIndex("id")));
                //@SuppressLint("Range") String id=cursor.getString(cursor.getColumnIndex("id"));
                @SuppressLint("Range") String title=cursor.getString(cursor.getColumnIndex("title"));
                @SuppressLint("Range") String content=cursor.getString(cursor.getColumnIndex("content"));
                @SuppressLint("Range") String createdTime=cursor.getString(cursor.getColumnIndex("createdTime"));
                NewsBean newsBean=new NewsBean();
                newsBean.setId(id);
                newsBean.setCreatedTime(createdTime);
                newsBean.setContent(content);
                newsBean.setTitle(title);
                newsBeanList.add(newsBean);
            }
            cursor.close();
        }
        return newsBeanList;
    }


    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

    }

    public int deleteFromDbById(int id) {
        SQLiteDatabase db=getWritableDatabase();
        return db.delete(TABLE_NAME,"id like ?",new String[]{String.valueOf(id)});
    }
}

写到这里,基本上已经完成了一个简单记事本APP的开发,最后运行成功的界面如下:
android记事本,android,sqlite,java
android记事本,android,sqlite,java
android记事本,android,sqlite,java
android记事本,android,sqlite,java文章来源地址https://www.toymoban.com/news/detail-518650.html

到了这里,关于实现一个简单的记事本APP的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • 简单的手机记事本哪个好用?

    在快节奏的现代生活中,我们经常需要记录下来重要的信息,而手机记事本成为了不可或缺的工具。然而,市面上琳琅满目的手机记事本软件,让人眼花缭乱,不知道该选择哪一个。 敬业签是功能强大、操作简单的手机记事本,它可以让你快速记录下重要的信息,同时还支持

    2024年02月11日
    浏览(39)
  • 用Java制作简单的记事本

    目录 前言 主界面设计 功能实现 打开 另存为 保存 查找 替换 成员变量 其他方法 警告弹窗 不移动光标更新文本框内容 源代码 总结 考完试想写敲一下代码就写了一下这个程序,整个也是写了怎么久,救命,因为要搞三下乡活动,还要写调查问卷,所以这个程序断断续续写了

    2024年02月11日
    浏览(32)
  • Android开发_记事本(1)

    TextView中有下述几个属性: id: 为TextView设置一个组件id,根据id,我们可以在Java代码中通过findViewById()的方法获取到该对象,然后进行相关属性的设置,又或者使用RelativeLayout时,参考组件用的也是id! layout_width: 组件的宽度,一般写: wrap_content 或者 match_parent(fill_parent) ,前

    2023年04月10日
    浏览(53)
  • Android Studio——记事本案例

    一、布局界面         1、记事本界面布局 main_notepad.xml         2、记事本Item布局界面 activity_item.xml         3、添加、修改界面布局 activity_record.xml 二、封装记录信息实体类         记事本的每个记录都会有记录内容和记录时间这两个属性,因此需要建立一个实体类用于存

    2024年02月05日
    浏览(34)
  • Android——记事本功能业务(完整代码)

    目录 实现效果 一、搭建记事本页面布局activity_notepad.xml 二、搭建记事本界面Item布局notepad_item_layout.xml 三、封装记录信息实体类NotepadBean类 四、编写记事本界面列表适配器NotepadAdapter类 五、创建数据库 六、实现记事本界面的显示功能NotepadAdapter.java  七、搭建添加记录界面和

    2024年02月03日
    浏览(53)
  • Android:实现安卓小程序-记事本(备忘录)的开发,教你如何增加拿到BAT大厂offer几率

    public MyBaseAdapter(Context context, List data) { this.context = context; this.data = data; } @Override public Object getItem(int i) { return null; } @Override public long getItemId(int i) { return 0; } @Override public int getCount() { if(data==null) return 0; return data.size(); } } 接着在编写NoteAdapter类继承上类,初始化view, 将Note条目的

    2024年04月25日
    浏览(39)
  • Android——多功能记事本(Android Studio)

    拍照 添加画板 录音 书写转文字 添加图片 1,主页面 2,功能 贴代码: 1,AndroidManifest.xml文件(添加权限) 2,Activity文件 ActivityRecord AddActivity DatabaseOperation GetCutBitampLocation HandWriteActivity LineEditActivity MainActivity PaintActivity PaintView ShowPicture ShowRecord TouchView 3,最后res中drawable文件

    2024年02月11日
    浏览(35)
  • 简单的手机记事本app怎么查看提醒列表?

    很多人平时都有随手记事的习惯,在记录事情的时候使用手机上的记事本app是一个不错的选择。有的记事本功能比较完善,不但能记事还能设置提醒,当有多条提醒内容存在时,简单的手机记事本app怎么查看提醒列表呢?以iPhone手机端敬业签为例: 1、打开iPhone手机上的敬业

    2024年02月12日
    浏览(64)
  • 基于Android Studio 开发的简易记事本

    🍅 文章末尾有获取完整项目源码方式 🍅 目录 一、引言 视频效果展示: 图片效果展示: 二、详细设计 1.首页 2.添加和修改页面 3.登录页 4.注册页 三、获取源码          Android初学者开发第一个完整的基础实例项目应该就属《记事本》了,该项目基于Android Studio开发使用

    2024年02月05日
    浏览(39)
  • 基于Android的记事本设计和模块开发

    有一万五千字论文,完美运行。 由于编程技术的迅速发展,各种记事本APP随处可见,在人们的日常生活中经常使用的到。于是各种记事本APP也跟着发展起来。本文在通过在Android Studio开发平台上开发一个简单的多功能语音输入记事本APP的过程,同时了解记事本APP的功能实现,

    2024年02月03日
    浏览(41)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包