使用db helper和recycleView完成android cardView

时间:2016-09-22 11:18:25

标签: java android sql android-recyclerview android-cardview

我对这个整个Android开发很新,但我希望创建一个简单的Android应用程序,利用sql数据库,cardViews和RecycleView。 我到目前为止的应用程序工作,但我试图添加一个按钮到DetailedActivity,这将允许我从数据库中删除条目。

enter image description here

enter image description here

enter image description here

所需的工作流程将是:

  1. 获取数据
  2. 选择CardView
  3. 点击新按钮(将是 删除)
  4. 返回CardView,删除按钮所在的条目 按下并填充CardView。
  5. RecyclerAdapter.java

    package com.example.prabhu.databasedemo;
    
    import android.content.Context;
    import android.content.Intent;
    import android.os.Bundle;
    import android.support.v7.widget.RecyclerView;
    import android.view.LayoutInflater;
    import android.view.View;
    import android.view.ViewGroup;
    import android.widget.TextView;
    import android.widget.Toast;
    
    import java.util.ArrayList;
    import java.util.List;
    
    public class RecyclerAdapter extends RecyclerView.Adapter<RecyclerAdapter.ViewHolder> {
    
      static   List<DatabaseModel> dbList;
        static  Context context;
        RecyclerAdapter(Context context, List<DatabaseModel> dbList ){
            this.dbList = new ArrayList<DatabaseModel>();
            this.context = context;
            this.dbList = dbList;
    
        }
    
        @Override
        public RecyclerAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    
            View itemLayoutView = LayoutInflater.from(parent.getContext()).inflate(
                    R.layout.item_row, null);
    
            // create ViewHolder
    
            ViewHolder viewHolder = new ViewHolder(itemLayoutView);
            return viewHolder;
        }
    
        @Override
        public void onBindViewHolder(RecyclerAdapter.ViewHolder holder, int position) {
    
            holder.name.setText(dbList.get(position).getName());
            holder.email.setText(dbList.get(position).getEmail());
    
        }
    
        @Override
        public int getItemCount() {
            return dbList.size();
        }
    
        public static class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
    
            public TextView name,email;
    
            public ViewHolder(View itemLayoutView) {
                super(itemLayoutView);
                name = (TextView) itemLayoutView
                        .findViewById(R.id.rvname);
                email = (TextView)itemLayoutView.findViewById(R.id.rvemail);
                itemLayoutView.setOnClickListener(this);
    
            }
    
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(context,DetailsActivity.class);
    
                Bundle extras = new Bundle();
                extras.putInt("position",getAdapterPosition());
                intent.putExtras(extras);
    
                /*
                int i=getAdapterPosition();
                intent.putExtra("position", getAdapterPosition());*/
                context.startActivity(intent);
                Toast.makeText(RecyclerAdapter.context, "you have clicked Row " + getAdapterPosition(), Toast.LENGTH_SHORT).show();
            }
        }
    }
    

    DatabaseHelper.java

    package com.example.prabhu.databasedemo;
    import android.content.ContentValues;
    import android.content.Context;
    import android.database.Cursor;
    import android.database.sqlite.SQLiteDatabase;
    import android.database.sqlite.SQLiteOpenHelper;
    import android.util.Log;
    import android.widget.Toast;
    
    import java.util.ArrayList;
    import java.util.List;
    
    public class DatabaseHelpher extends SQLiteOpenHelper {
        private static final String DATABASE_NAME="student";
        private static final int DATABASE_VERSION = 1;
        private static final String STUDENT_TABLE = "stureg";
        private static final String STU_TABLE = "create table "+STUDENT_TABLE +"(name TEXT,email TEXT primary key,roll TEXT,address TEXT,branch TEXT)";
    
        Context context;
    
        public DatabaseHelpher(Context context) {
            super(context, DATABASE_NAME, null, DATABASE_VERSION);
            this.context = context;
        }
    
        @Override
        public void onCreate(SQLiteDatabase db) {
    
            db.execSQL(STU_TABLE);
        }
    
        @Override
        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    
            db.execSQL("DROP TABLE IF EXISTS " + STUDENT_TABLE);
    
            // Create tables again
            onCreate(db);
        }
    
        /* Insert into database*/
        public void insertIntoDB(String name,String email,String roll,String address,String branch){
            Log.d("insert", "before insert");
    
            // 1. get reference to writable DB
            SQLiteDatabase db = this.getWritableDatabase();
    
            // 2. create ContentValues to add key "column"/value
            ContentValues values = new ContentValues();
            values.put("name", name);
            values.put("email", email);
            values.put("roll", roll);
             values.put("address", address);
            values.put("branch", branch);
    
            // 3. insert
            db.insert(STUDENT_TABLE, null, values);
            // 4. close
            db.close();
            Toast.makeText(context, "insert value", Toast.LENGTH_SHORT);
            Log.i("insert into DB", "After insert");
        }
    
        /* Retrive  data from database */
        public List<DatabaseModel> getDataFromDB(){
            List<DatabaseModel> modelList = new ArrayList<DatabaseModel>();
            String query = "select * from "+STUDENT_TABLE;
    
            SQLiteDatabase db = this.getWritableDatabase();
            Cursor cursor = db.rawQuery(query,null);
    
            if (cursor.moveToFirst()){
                do {
                    DatabaseModel model = new DatabaseModel();
                    model.setName(cursor.getString(0));
                    model.setEmail(cursor.getString(1));
                    model.setRoll(cursor.getString(2));
                    model.setAddress(cursor.getString(3));
                    model.setBranch(cursor.getString(4));
    
                    modelList.add(model);
                }while (cursor.moveToNext());
            }
    
    
            Log.d("student data", modelList.toString());
    
    
            return modelList;
        }
    
    
        /*delete a row from database*/
    
        public void deleteARow(String email){
            SQLiteDatabase db= this.getWritableDatabase();
            db.delete(STUDENT_TABLE, "email" + " = ?", new String[] { email });
            db.close();
        }
    
    }
    

    DatabaseModel.java

    package com.example.prabhu.databasedemo;
    
    
    public class DatabaseModel {
        private String name;
        private String roll;
        private String address;
        private String branch;
        private String email;
    
        public String getName() {
            return name;
        }
    
        public void setName(String name) {
            this.name = name;
        }
    
        public String getRoll() {
            return roll;
        }
    
        public void setRoll(String roll) {
            this.roll = roll;
        }
    
        public String getAddress() {
            return address;
        }
    
        public void setAddress(String address) {
            this.address = address;
        }
    
        public String getBranch() {
            return branch;
        }
    
        public void setBranch(String branch) {
            this.branch = branch;
        }
    
        public String getEmail() {
            return email;
        }
    
        public void setEmail(String email) {
            this.email = email;
        }
    }
    

    MainActivity.java

    package com.example.prabhu.databasedemo;
    
    import android.content.Intent;
    import android.support.v7.app.AppCompatActivity;
    import android.os.Bundle;
    import android.support.v7.widget.Toolbar;
    import android.view.Menu;
    import android.view.MenuItem;
    import android.view.View;
    import android.widget.Button;
    import android.widget.EditText;
    import android.widget.Toast;
    
    import java.util.ArrayList;
    import java.util.List;
    
    public class MainActivity extends AppCompatActivity {
        EditText etName,etRoll,etAddress,etBranch,etEmail;
        Button btnSubmit,btngetdata;
        DatabaseHelpher helpher;
        List<DatabaseModel> dbList;
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
            setSupportActionBar(toolbar);
            dbList= new ArrayList<DatabaseModel>();
            etName = (EditText)findViewById(R.id.etName);
            etRoll = (EditText)findViewById(R.id.etRoll);
            etAddress =(EditText)findViewById(R.id.etAddress);
            etBranch = (EditText)findViewById(R.id.etBranch);
            etEmail = (EditText)findViewById(R.id.etEmail);
            btnSubmit  =(Button)findViewById(R.id.btnSubmit);
            btngetdata =(Button)findViewById(R.id.btngetdata);
            btngetdata.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    startActivity(new Intent(MainActivity.this, SecondActivity.class));
    
                   // startActivity(new Intent(MainActivity.this, DetailsActivity.class));
    
                }
            });
    
            btnSubmit.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
    
                    String name=etName.getText().toString();
                    String email=etEmail.getText().toString();
                    String roll=etRoll.getText().toString();
                    String address=etAddress.getText().toString();
                    String branch=etBranch.getText().toString();
    
                if(name.equals("") || email.equals("") || roll.equals("") ||address.equals("")||branch.equals("")){
                    Toast.makeText(MainActivity.this,"Please fill all the fields",Toast.LENGTH_SHORT).show();
                }else {
                    helpher = new DatabaseHelpher(MainActivity.this);
                    helpher.insertIntoDB(name, email, roll, address, branch);
                }
                    etName.setText("");
                    etRoll.setText("");
                    etAddress.setText("");
                    etBranch.setText("");
                    etEmail.setText("");
    
                    Toast.makeText(MainActivity.this, "insert value", Toast.LENGTH_SHORT);
    
                }
            });
    
        }
    
    
    }
    

    SecondActivity.java

    package com.example.prabhu.databasedemo;
    
    import android.support.v7.app.AppCompatActivity;
    import android.os.Bundle;
    import android.support.v7.widget.LinearLayoutManager;
    import android.support.v7.widget.RecyclerView;
    
    import android.support.v7.widget.Toolbar;
    import android.view.Menu;
    import android.view.MenuItem;
    
    import java.util.ArrayList;
    import java.util.List;
    
    public class SecondActivity extends AppCompatActivity {
        DatabaseHelpher helpher;
        List<DatabaseModel> dbList;
        RecyclerView mRecyclerView;
        private RecyclerView.Adapter mAdapter;
        private RecyclerView.LayoutManager mLayoutManager;
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_second);
            Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
            setSupportActionBar(toolbar);
            getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    
    
            helpher = new DatabaseHelpher(this);
            dbList= new ArrayList<DatabaseModel>();
            dbList = helpher.getDataFromDB();
    
    
            mRecyclerView = (RecyclerView)findViewById(R.id.recycleview);
    
            mRecyclerView.setHasFixedSize(true);
    
            // use a linear layout manager
            mLayoutManager = new LinearLayoutManager(this);
            mRecyclerView.setLayoutManager(mLayoutManager);
    
            // specify an adapter (see also next example)
            mAdapter = new RecyclerAdapter(this,dbList);
            mRecyclerView.setAdapter(mAdapter);
    
        }
    
        @Override
        public boolean onCreateOptionsMenu(Menu menu) {
            // Inflate the menu; this adds items to the action bar if it is present.
            getMenuInflater().inflate(R.menu.menu_second, menu);
            return true;
        }
    
    
    
        @Override
        public boolean onOptionsItemSelected(MenuItem item) {
            switch (item.getItemId()) {
                case android.R.id.home:
                    finish();
                    return true;
            }
            return super.onOptionsItemSelected(item);
        }
    }
    

    DetailedActivity.java

    package com.example.prabhu.databasedemo;
    
    import android.content.Intent;
    import android.support.v7.app.AppCompatActivity;
    import android.os.Bundle;
    import android.support.v7.widget.Toolbar;
    import android.view.Menu;
    import android.view.MenuItem;
    import android.widget.TextView;
    import android.widget.Toast;
    
    import java.util.ArrayList;
    import java.util.List;
    
    public class DetailsActivity extends AppCompatActivity {
        DatabaseHelpher helpher;
        List<DatabaseModel> dbList;
        int position;
        TextView tvname,tvemail,tvroll,tvaddress,tvbranch;
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
    
            setContentView(R.layout.activity_details);
    
            Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
            setSupportActionBar(toolbar);
            getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    
    
            Intent intent = getIntent();
            Bundle bundle = intent.getExtras();
    
            // 5. get status value from bundle
             position = bundle.getInt("position");
    
            tvname =(TextView)findViewById(R.id.name);
            tvemail =(TextView)findViewById(R.id.email);
            tvroll =(TextView)findViewById(R.id.roll);
            tvaddress =(TextView)findViewById(R.id.address);
            tvbranch =(TextView)findViewById(R.id.branch);
            helpher = new DatabaseHelpher(this);
            dbList= new ArrayList<DatabaseModel>();
            dbList = helpher.getDataFromDB();
    
            if(dbList.size()>0){
                String name= dbList.get(position).getName();
                String email=dbList.get(position).getEmail();
                String roll=dbList.get(position).getRoll();
                String address=dbList.get(position).getAddress();
                String branch=dbList.get(position).getBranch();
                tvname.setText(name);
                tvemail.setText(email);
                tvroll.setText(roll);
                tvaddress.setText(address);
                tvbranch.setText(branch);
            }
    
            Toast.makeText(DetailsActivity.this, dbList.toString(), Toast.LENGTH_SHORT);
        }
    
    
        public boolean onCreateOptionsMenu(Menu menu) {
            // Inflate the menu; this adds items to the action bar if it is present.
            getMenuInflater().inflate(R.menu.menu_details, menu);
            return true;
        }
    
    
    
        @Override
        public boolean onOptionsItemSelected(MenuItem item) {
            switch (item.getItemId()) {
                case android.R.id.home:
                    finish();
                    return true;
            }
            return super.onOptionsItemSelected(item);
        }
    
    
    }
    

    我在DetailedAvtivity.java中添加了一个带有OnClickListener的按钮(findViewByID)。但是,最初只显示吐司,当点击任何详细视图上的按钮时,没有任何反应 - 没有吐司。

    所以,问题是:

    1. 我在哪里定义按钮以及在哪里实现onClickListener?
    2. 如何让按钮删除条目?现在我很高兴使用来自电子邮件TextView(tvemail)的电子邮件,但我将不得不返回并刷新卡片。
    3. 提前全部谢谢

1 个答案:

答案 0 :(得分:0)

过了一段时间我找到了答案。我正在做的是正确的,但搞砸了吐司的命令。

基本上需要做的是

delButton = (Button) findViewById(R.id.button);

delButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Toast.makeText(getApplicationContext(), tvemail.getText() + " deleted", Toast.LENGTH_SHORT).show();
            startActivity(new Intent(DetailsActivity.this, MainActivity.class));
            helpher.deleteARow((String) tvemail.getText());
        }
    });