SQLITE+Recycleview 实现添加联系人功能

SQLITE+Recycleview 实现添加联系人功能_第1张图片主要分为两部分:
数据库部分和Fragment部分

数据库部分:
DbHelper.java:

public class DbHelper extends SQLiteOpenHelper {
    public String TB_NAME="friends";
    public DbHelper(@Nullable Context context, @Nullable String name, @Nullable SQLiteDatabase.CursorFactory factory, int version) {
        super(context, name, factory, version);
    }

    @Override
    public void onCreate(SQLiteDatabase sqLiteDatabase) {
        sqLiteDatabase.execSQL("CREATE TABLE IF NOT EXISTS " +
                TB_NAME + "( f_id integer primary key autoincrement," +
                "f_name varchar" + ")");
    }

    @Override
    public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {
        sqLiteDatabase.execSQL("DROP TABLE IF EXISTS " + TB_NAME);
        onCreate(sqLiteDatabase);
    }
}

MYDAO.java:

public class MYDAO {
    private SQLiteDatabase mydb;
    private DbHelper dbhelper;

    public MYDAO(Context context) {  //构造方法,参数为上下文对象
        //第1参数为上下文,第2参数为数据库名
        dbhelper = new DbHelper(context,"test.db",null,1);
    }

    public Cursor AllQuerry(String tablename){
        mydb=dbhelper.getReadableDatabase();
        return mydb.rawQuery("select * from "+tablename,null);
    }

    public  int getRecordsNumber(String tablename){  //返回数据表记录数
        mydb = dbhelper.getReadableDatabase();
        Cursor cursor= mydb.rawQuery("select * from "+tablename,null);
        return cursor.getCount();
    }
    public void insertInfo(String name,String tablename){  //插入记录
        mydb = dbhelper.getWritableDatabase();
        ContentValues values = new ContentValues();
        values.put("f_name", name);
        long rowid=mydb.insert(tablename, null, values);
        if(rowid==-1)
            Log.i("myDbDemo", "数据插入失败!");
        else
            Log.i("myDbDemo", "数据插入成功!"+rowid);
    }
    public void deleteInfo(String selId,String tablename){  //删除记录
        String where = "f_id=" + selId;
        int i = mydb.delete(tablename, where, null);
        if (i > 0)
            Log.i("myDbDemo", "数据删除成功!");
        else
            Log.i("myDbDemo", "数据未删除!");
    }
    public void updateInfo(String name,String selId,String tablename){  //修改记录
        //方法中的第三参数用于修改选定的记录
        ContentValues values = new ContentValues();
        values.put("f_name", name);
        String where="f_id="+selId;
        int i=mydb.update(tablename, values, where, null);

        //上面几行代码的功能可以用下面的一行代码实现
        //myDb.execSQL("update friends set name = ? ,age = ? where _id = ?",new Object[]{name,age,selId});

        if(i>0)
            Log.i("myDbDemo","数据更新成功!");
        else
            Log.i("myDbDemo","数据未更新!");
    }
}

Fragment部分:
因为添加联系人的加号图标只在切换到通讯录的时候出现,所以要准备两个topFragment进行切换,在切换content时同时切换top中的装填的fragment,这个比较简单就不放上来了。

接着就是一个小难点,需要提前在xml中准备好一个visibility="gone"的LinearLayout,里面存放EditText之类的,用于添加联系人,在topContactFragment中点击添加图标,需要在contactFragment里响应,setVisibility(view.VISIBLE),这就涉及到Fragment之间的传值了,我采用了Fragment->Acitivity->Fragment的方法,进行传值。recycleview的部分之前的博客写过,不重复了。
tab_contact.xml:

<LinearLayout
    android:id="@+id/tab_add_friend"
    android:layout_width="match_parent"
    android:layout_height="60dp"
    android:orientation="horizontal"
    android:visibility="gone">
    <TextView
        android:layout_width="wrap_content"
        android:layout_marginLeft="30dp"
        android:layout_height="40dp"
        android:text="名称:" />
    <EditText
        android:id="@+id/f_name"
        android:layout_width="240dp"
        android:layout_height="60dp"/>
    <Button
        android:id="@+id/add_friend"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="5dp"
        android:text="确认添加"/>
</LinearLayout>

topContactFragment.java:

public class topContactFragment extends Fragment implements View.OnClickListener {

    private ImageButton mImageAddFriend;
    private View view1;

    public topContactFragment() {
        // Required empty public constructor
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        view1=inflater.inflate(R.layout.top_contact, container, false);
        mImageAddFriend=(ImageButton) view1.findViewById(R.id.show_add_friend);
        mImageAddFriend.setOnClickListener(this);
        return view1;
    }
    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.show_add_friend:
                ((MainActivity)getActivity()).setAflag("show");
                break;
        }
    }
}

MainActivity.java:

private String Aflag;
public String getAflag(){
    return Aflag;
}
public void setAflag(String aflag){
    this.Aflag=aflag;
}

contactFragment.java:

public class contactFragment extends Fragment implements View.OnClickListener {

    private Button mButtonAddFriend;
    private MYDAO mydao;
    private List<String> mList=new ArrayList<>();
    private vertical_adapter adapter;
    private RecyclerView recyclerView;
    private String tablename="friends";
    private LinearLayout editTextAdd;
    private Serializable flag;

    private EditText f_name;
    private String f_id=null;
    private View view1;
    private boolean isGetData = false;

    public contactFragment() {
        // Required empty public constructor
    }


    private void initverticalview(){
        adapter=new vertical_adapter(mList);
        recyclerView=view1.findViewById(R.id.recyclerview_contact);
        LinearLayoutManager manager = new LinearLayoutManager(getContext());
        manager.setOrientation(LinearLayoutManager.VERTICAL);
        recyclerView.setLayoutManager(manager);
        recyclerView.setHasFixedSize(true);
        recyclerView.setAdapter(adapter);
    }


    @Override
    public Animation onCreateAnimation(int transit, boolean enter, int nextAnim) {
        if (enter && !isGetData){
            isGetData = true;
            flag=((MainActivity)getActivity()).getAflag();
            if(flag=="show"){
                editTextAdd.setVisibility(view1.VISIBLE);
            }else if(flag=="none"){
                editTextAdd.setVisibility(view1.GONE);
            }
        }else{
            isGetData = false;
        }
        return super.onCreateAnimation(transit, enter, nextAnim);
    }

    @Override
    public void onPause() {
        super.onPause();
        isGetData=false;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        view1=inflater.inflate(R.layout.tab_contact, container, false);
        mButtonAddFriend=(Button)view1.findViewById(R.id.add_friend);
        editTextAdd=(LinearLayout)view1.findViewById(R.id.tab_add_friend);
        f_name=(EditText)view1.findViewById(R.id.f_name);

        mButtonAddFriend.setOnClickListener(this);
        mydao=new MYDAO(getContext());
        if(mydao.getRecordsNumber("friends")==0){
            mydao.insertInfo("张三",tablename);
            mydao.insertInfo("李四",tablename);
        }
        displayRecords();
        initverticalview();
        return view1;
    }

        private void displayRecords(){
        mList.clear();
        Cursor cursor=mydao.AllQuerry(tablename);
        while (cursor.moveToNext()){
            int id=cursor.getInt(cursor.getColumnIndex("f_id"));
            String name=cursor.getString(cursor.getColumnIndex("f_name"));
            mList.add(name);
        }
    }
    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.add_friend:
                String p1 = f_name.getText().toString().trim();
                mydao.insertInfo(p1, tablename);
                editTextAdd.setVisibility(view.GONE);
                ((MainActivity)getActivity()).setAflag("none");
                displayRecords();
        }
    }
}

码云中放了部分的代码,两个主要的Fragment和vertical_adapter
https://gitee.com/kadd/android/tree/master/add

你可能感兴趣的:(android)