Sqlite-demo

  开篇:

                                                                      demo地址:点击打开链接

首先介绍一下本demo中用到的东西



还有OptionMenu,以及我们的正主Sqlite,以上就是我们需要用到的东西,和需要的Gride配置


Xml布局:

  • activity_realm
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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"
    xmlns:custom="http://schemas.android.com/apk/res-auto"
    android:orientation="vertical"
    tools:context="com.example.administrator.recyclerview.RealmActivity">
    <android.support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="?attr/colorPrimary"
        app:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
        app:popupTheme="@style/ThemeOverlay.AppCompat.Light">
    </android.support.v7.widget.Toolbar>

    <com.chaychan.viewlib.PowerfulEditText
        android:id="@+id/tv_name"
        android:hint="姓名"
        android:layout_margin="15dp"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:funcType="canClear"
        />
    <com.chaychan.viewlib.PowerfulEditText
        android:hint="密码"
        android:id="@+id/tv_pwd"
        android:layout_margin="15dp"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:funcType="canWatchPwd"
        android:inputType="textPassword"
        />
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
        <Button
            android:text="增"
            android:textSize="15sp"
            android:id="@+id/btn_add"
            android:layout_width="0dp"
            android:layout_weight="1"
            android:layout_height="wrap_content"
            android:background="@drawable/ic_done"/>
        <Button
            android:text="删"
            android:textSize="15sp"
            android:id="@+id/btn_delete"
            android:layout_width="0dp"
            android:layout_weight="1"
            android:layout_height="wrap_content"
            android:background="@drawable/ic_done"/>
        <Button
            android:text="改"
            android:textSize="15sp"
            android:id="@+id/btn_gai"
            android:layout_width="0dp"
            android:layout_weight="1"
            android:layout_height="wrap_content"
            android:background="@drawable/ic_done"/>
    </LinearLayout>
    <com.dd.processbutton.iml.SubmitProcessButton
        android:layout_margin="15dp"
        android:id="@+id/btnSend"
        android:layout_width="match_parent"
        android:layout_height="48dp"
        android:minWidth="100dp"
        android:text="@string/Send"
        android:textColor="@android:color/white"
        android:textSize="18sp"
        custom:pb_textComplete="@string/Done"
        custom:pb_textProgress="@string/Loading" />
    <com.yalantis.phoenix.PullToRefreshView
        android:id="@+id/pull_to_refresh"
        android:layout_width="match_parent"
        android:layout_height="match_parent">
    <android.support.v7.widget.RecyclerView
        android:id="@+id/recyclerview"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>
</com.yalantis.phoenix.PullToRefreshView>
</LinearLayout>

activity_add_friend

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:orientation="vertical"
    >

    <android.support.v7.widget.Toolbar
        android:id="@+id/tb_toolbar"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        android:background="@color/btn_normal"
        app:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
        app:popupTheme="@style/ThemeOverlay.AppCompat.Light"
        >
        <TextView
            android:layout_gravity="center"
            android:id="@+id/tv_title"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="搜"
            android:textSize="20sp"
            android:textColor="@android:color/white"/>
    </android.support.v7.widget.Toolbar>
    <FrameLayout
        android:id="@+id/fl_container"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        >
        <ImageView
            android:id="@+id/iv_nodata"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:src="@mipmap/nodata"/>
        <android.support.v7.widget.RecyclerView
            android:id="@+id/rv_addfriend"
            android:layout_width="match_parent"
            android:layout_height="match_parent">

        </android.support.v7.widget.RecyclerView>

    </FrameLayout>
</LinearLayout>

item布局

<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_margin="10dp"
    android:elevation="5dp"
    app:cardCornerRadius="5dp"
    app:cardUseCompatPadding="true"
    android:layout_marginBottom="1dp"
    app:cardPreventCornerOverlap="true">

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@color/colorAccent"
        android:padding="10dp">

        <TextView
            android:id="@+id/tv_id"
            android:textColor="#0b0b0b"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerVertical="true"
            android:textAllCaps="false" />

        <TextView
            android:layout_centerVertical="true"
            android:layout_centerInParent="true"
            android:textColor="#0b0b0b"
            android:id="@+id/tv_name"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />

        <ImageView
            android:id="@+id/iv_like"
            android:layout_width="50dp"
            android:layout_height="50dp"
            android:layout_alignParentRight="true"
            android:layout_centerVertical="true"
            android:padding="10dp"
            android:src="@drawable/like_selector" />

    </RelativeLayout>

</android.support.v7.widget.CardView>
 optionMenu的布局文件就不贴上来了,这样代码太多了,看晕了

 

Java代码:

 主代码

import android.content.ContentValues;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.view.menu.MenuBuilder;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.dd.processbutton.iml.SubmitProcessButton;
import com.example.administrator.recyclerview.Adapter.ShowAdapter;
import com.example.administrator.recyclerview.Utils.Match;
import com.example.administrator.recyclerview.Utils.MyDbHelper;
import com.example.administrator.recyclerview.Utils.ProgressGenerator;
import com.example.administrator.recyclerview.Utils.User;
import com.example.administrator.recyclerview.event.ShowEvent;
import com.yalantis.phoenix.PullToRefreshView;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

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



public class RealmActivity extends AppCompatActivity implements ProgressGenerator.OnCompleteListener,View.OnClickListener  {
    private Toolbar toolbar;
    private EditText et_name;
    private EditText et_pwd;
    private Button   bt_add;
    private Button   bt_delet;
    private Button   bt_change;
    private RecyclerView recyclerview;
    public SQLiteDatabase db;
    public  MyDbHelper helper=new MyDbHelper(this);
    private ContentValues values;
    private Cursor cursor;
    private List<User> list;
    private ShowAdapter adapter;
    private PullToRefreshView mPullToRefreshView;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_realm);
        toolbar = findViewById(R.id.toolbar);
        final ProgressGenerator progressGenerator = new ProgressGenerator(this);
        //  inToolbar();
        inToolbar();
        //初始化
        inView();
      show();
        mPullToRefreshView =findViewById(R.id.pull_to_refresh);
        mPullToRefreshView.setOnRefreshListener(new PullToRefreshView.OnRefreshListener() {
            @Override
            public void onRefresh() {
                mPullToRefreshView.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        mPullToRefreshView.setRefreshing(false);
                       show();
                        Toast.makeText(getApplicationContext(),"刷新成功",Toast.LENGTH_SHORT).show();
                    }
                },2000);
            }
        });
        final SubmitProcessButton btnSend = (SubmitProcessButton) findViewById(R.id.btnSend);
        btnSend.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                progressGenerator.start(btnSend);
                btnSend.setEnabled(false);
            }
        });

    }
    //初始化布局
    private void inView() {
        et_name=findViewById(R.id.tv_name);
        et_pwd=findViewById(R.id.tv_pwd);
        bt_add=findViewById(R.id.btn_add);
        bt_delet=findViewById(R.id.btn_delete);
        bt_change=findViewById(R.id.btn_gai);
        recyclerview=findViewById(R.id.recyclerview);
        bt_add.setOnClickListener(this);
        bt_change.setOnClickListener(this);
        bt_delet.setOnClickListener(this);
    }

    //初始化Toolbar
    private void inToolbar() {
        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    }
    // .选项菜单(optinosMenu)
    //创建菜单的方法
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        super.onCreateOptionsMenu(menu);
        //①获取菜单的布局填充器
        MenuInflater menuInflater=getMenuInflater();
        //②通过menuInflater 把菜单对应的xml文件(在res->menu->****.xml) 加载进来
        menuInflater.inflate(R.menu.main,menu);
        //通过menubuilder 来设置显示图标
        MenuBuilder builder = (MenuBuilder) menu;
        //设置条目前面的图标可见
        builder.setOptionalIconsVisible(true);
        return true;
        //有返回值true显示,false不显示,可以动态处理
    }
    //这个方法处理菜单的点击事件
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        super.onOptionsItemSelected(item);
        switch (item.getItemId()){
            case R.id.menu_addFriend:
                Intent intent = new Intent(getApplicationContext(),AddFriendActivity.class);
                startActivity(intent);
                break;
            case R.id.menu_about:
                Toast.makeText(this, "关于", Toast.LENGTH_SHORT).show();
                break;
            case R.id.menu_scan:
                Toast.makeText(this, "扫一扫", Toast.LENGTH_SHORT).show();
                break;
        }
        return  true;
    }

    @Override
    public void onComplete() {
        Toast.makeText(this, "哈哈哈", Toast.LENGTH_LONG).show();
    }
    //点击事件
    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case  R.id.btn_add:
               ansycadd();
            break;
            case R.id.btn_gai:
                change();
                break;
            case R.id.btn_delete:
                Delete();
                break;
        }
    }
     //删除
    private void Delete() {
        String username=et_name.getText().toString().trim();
        String pwd=et_pwd.getText().toString().trim();
        db=helper.getWritableDatabase();
        if (Match.checkUsername(username)&&TextUtils.isEmpty(pwd)){
          db.delete("information","username=?",new String[]{username});
            Toast.makeText(getApplicationContext(),"删除成功",Toast.LENGTH_SHORT).show();
            return;
        }
        if (Match.checkPassword(pwd)&&TextUtils.isEmpty(username)){
            db.delete("information","pwd=?",new String[]{pwd});
            Toast.makeText(getApplicationContext(),"删除成功",Toast.LENGTH_SHORT).show();
            return;
        }
        if (!Match.checkUsername(username)||!Match.checkPassword(pwd)){
            Toast.makeText(getApplicationContext(),"删除条件不符合",Toast.LENGTH_SHORT).show();
            return;
        }
    }

    //修改
    private void change() {
        String username=et_name.getText().toString().trim();
        String pwd=et_pwd.getText().toString().trim();

        db=helper.getWritableDatabase();
        values=new ContentValues();
        if (Match.checkUsername(username)&&Match.checkPassword(pwd)){
           values.put("username",username);
            db.update("information",values,"pwd=?",new String[]{pwd});
            Toast.makeText(this,"修改成功",Toast.LENGTH_SHORT).show();
            cursor.close();
            db.close();
        }else {
            Toast.makeText(this,"请检查您输入的姓名和年龄格式是否正确",Toast.LENGTH_SHORT).show();
        }
    }

    //显示
      private void show() {
     db=helper.getReadableDatabase();
        list=new ArrayList<>();
        cursor=db.query("information",null,null,null,null,null,null);
        while (cursor.moveToNext()){
            String name=cursor.getString(cursor.getColumnIndex("username"));
            String pwd=cursor.getString(cursor.getColumnIndex("pwd"));
            User user=new User(name,pwd);
            list.add(user);
        }
        cursor.close();
        db.close();
        adapter=new ShowAdapter(getApplicationContext(),list);
        recyclerview.setAdapter(adapter);
        recyclerview.setLayoutManager(new LinearLayoutManager(RealmActivity.this, LinearLayoutManager.VERTICAL, false));
    }

    //增
    private void ansycadd() {
        db=helper.getWritableDatabase();
        values=new ContentValues();
        String name=et_name.getText().toString().trim();
        String pwd=et_pwd.getText().toString().trim();

      if(!Match.checkUsername(name)){
            Toast.makeText(getApplicationContext(),"请输入姓名",Toast.LENGTH_SHORT).show();
            return ;
        }
        if (!Match.checkPassword(pwd)){
            Toast.makeText(getApplicationContext(),"密码格式不正确",Toast.LENGTH_SHORT).show();
            return;
        }
        values.put("username",name);
        values.put("pwd",pwd);
        db.insert("information",null,values);
        EventBus.getDefault().post(new ShowEvent(true));
        Toast.makeText(this,"添加成功",Toast.LENGTH_SHORT).show();
        db.close();
        }
    @Subscribe(threadMode = ThreadMode.MAIN)//线程模式 决定了onMessageEvent 这个方法在哪个线程中执行
    //ThreadMode.MAIN 主线程
    //POSTING 那个线程发的就在那个线程中执行
    //ASYNC 异步 跟发送消息的线程在不同的线程执行
    //BACKGROUND 子线程中执行
    //MAIN_ORDERED 主线程中执行 并且放到队列中排序执行
    public void onMessageEvent(ShowEvent event) {
        //执行了这个方法说明联系人发生了变化
        //从服务器重新获取联系人
        show();
    }


    @Override
    public void onStart() {
        super.onStart();
        //当页面加载之后会执行这个onStart方法 执行了onStart之后 页面就可以被看见了
        EventBus.getDefault().register(this); //当页面可见的时候 注册eventbus的订阅者
    }

    @Override
    public void onStop() {
        super.onStop();
        //当页面要跑到后台去的时候 会执行这个方法  走了onStop 之后页面就不可见了
        EventBus.getDefault().unregister(this); //当页面不可见的时候 要注销EventBus的订阅者
    }
    }

adapter

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.example.administrator.recyclerview.R;
import com.example.administrator.recyclerview.Utils.MyDbHelper;
import com.example.administrator.recyclerview.Utils.User;
import com.example.administrator.recyclerview.event.ShowEvent;

import org.greenrobot.eventbus.EventBus;

import java.util.List;

/**
 * Created by Administrator on 2018/6/7.
 */

public class ShowAdapter extends RecyclerView.Adapter<ShowAdapter.MyViewHolder> {
    private Context context;
    private List<User>list;
    public SQLiteDatabase db;
    public MyDbHelper helper;
    View view;
    public ShowAdapter(Context context, List<User> list){
        this.context=context;
        this.list=list;
    }

    public void setContext(Context context) {
        this.context = context;
    }

    public void setList(List<User> list) {
        this.list = list;
    }

    @Override
    public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        view=View.inflate(parent.getContext(),R.layout.item_user,null);
        return new MyViewHolder(view);
    }

    @Override
    public void onBindViewHolder(MyViewHolder holder, final int position) {
                  String name=list.get(position).getName();
                  String pwd=list.get(position).getPwd();
        holder.tv_name.setText(name);
        holder.tv_pwd.setText(pwd);
        //默认情况下,全选
        holder.iv.setSelected(true);
        holder.iv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (v.isSelected()) {
                    v.setSelected(false);
                    helper=new MyDbHelper(context);
                    db=helper.getWritableDatabase();
                    String username=list.get(position).getName();
                    db.delete("information","username=?",new String[]{username});
                    Toast.makeText(context,"删除成功",Toast.LENGTH_SHORT).show();
                    EventBus.getDefault().post(new ShowEvent(true));

                } else {
                    v.setSelected(true);

                }
            }
        });
    }
    @Override
    public int getItemCount() {
        return list==null? 0:list.size();
    }

    public class MyViewHolder extends RecyclerView.ViewHolder{
         TextView tv_name;
         TextView tv_pwd;
         ImageView iv;
        public MyViewHolder(View itemView) {
            super(itemView);
            tv_name=itemView.findViewById(R.id.tv_name);
            tv_pwd=itemView.findViewById(R.id.tv_id);
            iv=itemView.findViewById(R.id.iv_like);
        }
    }
}

搜索界面的代码

import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.SearchView;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView;

import com.example.administrator.recyclerview.Adapter.ShowAdapter;
import com.example.administrator.recyclerview.Utils.Match;
import com.example.administrator.recyclerview.Utils.MyDbHelper;
import com.example.administrator.recyclerview.Utils.ThreadUtils;
import com.example.administrator.recyclerview.Utils.User;

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

public class AddFriendActivity extends AppCompatActivity {

    private Toolbar toolbar;
    private ImageView iv_nodata;
    private RecyclerView recyclerview;
     public SQLiteDatabase db;
     public MyDbHelper helper=new MyDbHelper(this);
    private Cursor cursor;
    private List<User> list;
    private ShowAdapter adapter;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add_friend);
         toolbar = (Toolbar) findViewById(R.id.tb_toolbar);
        iv_nodata = (ImageView) findViewById(R.id.iv_nodata);
        recyclerview = (RecyclerView) findViewById(R.id.rv_addfriend);
         recyclerview.setLayoutManager(new LinearLayoutManager(this));
         adapter=new ShowAdapter(null,null);
        recyclerview.setAdapter(adapter);
        initToolbar();
    }

    private void initToolbar() {

            toolbar.setTitle("");
            setSupportActionBar(toolbar);
            getSupportActionBar().setDisplayHomeAsUpEnabled(true);

    }
    public boolean onCreateOptionsMenu(Menu menu) {
        super.onCreateOptionsMenu(menu);
         //通过布局填充器.inflate加载menu菜单内容
        getMenuInflater().inflate(R.menu.menu_search,menu);
        //这样通过MenuItem获取条目是为了能够获得SearchView 从而使该控件强转成SearchView
        MenuItem item = menu.getItem(0);
        //从条目中获取到ActionView  这个ActionView就是一个SearchView
        SearchView searchView = (SearchView) item.getActionView(); //获取这个控件
        //给SearchView设置监听
        searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
            @Override
            public boolean onQueryTextSubmit(String query) {
                //确定搜索时 走这个方法
                queryFriend(query);
                return true;
            }

            @Override
            public boolean onQueryTextChange(String newText) {
                return false;
            }
        });
        return true;
    }
    private void queryFriend(final  String username) {
         list=new ArrayList<>();
        /*if (!Match.checkUsername(username)){
            iv_nodata.setVisibility(View.VISIBLE);
            recyclerview.setVisibility(View.GONE);
        }*/
        ThreadUtils.runonSubThread(new Runnable() {
            @Override
            public void run() {
           db=helper.getReadableDatabase();
        //精准查询     cursor=db.query("information",null,"username=?",new String[]{username},null,null,null);
                cursor = db.rawQuery("select * from information where username like '%" + username + "%'",null);
                while (cursor.moveToNext()){
                    String name=cursor.getString(cursor.getColumnIndex("username"));
                    String pwd=cursor.getString(cursor.getColumnIndex("pwd"));
                    User user=new User(name,pwd);
                    list.add(user);
                }
                cursor.close();
                db.close();
            }
        });
      ThreadUtils.runonUIThread(new Runnable() {
          @Override
          public void run() {
              recyclerview.setVisibility(View.VISIBLE);
              iv_nodata.setVisibility(View.GONE);
              adapter.setContext(getApplicationContext());
              adapter.setList(list);
              adapter.notifyDataSetChanged();
          }
      });


    }


}

补充一些本demo中用到的东西,解析网址:

Button      https://github.com/dmytrodanylyk/android-process-button
刷新控件    https://github.com/Yalantis/Phoenix
EditText    http://www.apkbus.com/blog-917385-68375.html  

EventBus    https://www.jianshu.com/p/dd18c2156bcc

总结:

本demo使用很多的东西,用于学习是可以的,但还是有一些地方是可以在改进的,第一点原本取名叫Realm,是因为原本是想用realm数据库的,但因为不是很熟悉导致使用的效果不是很好,所以就换成了sqlite.第二点因为本demo是用MVC模式写的所以

Activity里面的代码很多,几乎都没有抽取成方法,心疼一下activity一下子要运行那么多的代码。。。。。。

先留着,以后自己在回来改一下,希望到时候不要讲自己怎么这么傻,怎么会写出这样的代码(指的是代码的可读性,感觉代码写的有点乱,毕竟是菜鸟)


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值