使用适配器,Recylerviewer显示SQLite数据

时间:2017-07-31 07:54:53

标签: android android-recyclerview android-sqlite android-adapter

如何显示我的SQLite数据并将其绑定到适配器,然后将其显示在recylcerviewer android中。

这是我下面课程的全部代码。是否有可能我不需要让SQLite数据库直接通过json响应发布我的数据?如果可能的话我应该怎么做?我只是按照一些教程

Login.java

public class LoginActivity extends Activity {

    private static final String TAG = RegisterActivity.class.getSimpleName();
    private Button btnLogin;
    private Button btnLinkToRegister;
    private EditText inputUsername;
    private EditText inputPassword;
    private ProgressDialog pDialog;
    private SessionManager session;
    private SQLiteHandler db;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);

        inputUsername = (EditText) findViewById(R.id.username);
        inputPassword = (EditText) findViewById(R.id.password);
        btnLogin = (Button) findViewById(R.id.btnLogin);
        btnLinkToRegister = (Button) findViewById(R.id.btnLinkToRegisterScreen);
        // Progress dialog
        pDialog = new ProgressDialog(this);
        pDialog.setCancelable(false);
        // SQLite database handler
        db = new SQLiteHandler(getApplicationContext());
        // Session manager
        session = new SessionManager(getApplicationContext());
        // Check if user is already logged in or not
        if (session.isLoggedIn()) {
            // User is already logged in. Take him to main activity
            Intent intent = new Intent(LoginActivity.this, MainActivity.class);
            startActivity(intent);
            finish();
        }
        // Login button Click Event
        btnLogin.setOnClickListener(new View.OnClickListener() {

            public void onClick(View view) {
                String username = inputUsername.getText().toString().trim();
                String password = inputPassword.getText().toString().trim();

                // Check for empty data in the form
                if (!username.isEmpty() && !password.isEmpty()) {
                    // login user
                    checkLogin(username, password);
                } else {
                    // Prompt user to enter credentials
                    Toast.makeText(getApplicationContext(),
                            "Please enter the credentials!", Toast.LENGTH_LONG)
                            .show();
                }
            }
        });
        // Link to Register Screen
        btnLinkToRegister.setOnClickListener(new View.OnClickListener() {

            public void onClick(View view) {
                Uri uri = Uri.parse("http://gsac.ph/iaccswebportal/register.php");
                Intent intent = new Intent(Intent.ACTION_VIEW, uri);
                startActivity(intent);
            }
        });
    }
    /**
     * function to verify login details in mysql db
     * */
    private void checkLogin(final String username, final String password) {
        // Tag used to cancel the request
        String tag_string_req = "req_login";

        pDialog.setMessage("Logging in ...");
        showDialog();

        StringRequest strReq = new StringRequest(Method.POST,
                AppConfig.URL_LOGIN, new Response.Listener<String>() {

            @Override
            public void onResponse(String response) {
                Log.d(TAG, "Login Response: " + response.toString());
                hideDialog();
                try {
                    JSONObject jsonObject = new JSONObject(response.toString());
                    Log.d(TAG, "Checking JSON Object" +jsonObject);
                    // Check for error node in json
                    if (!jsonObject.isNull("login")) {
                        JSONObject loginObject = (JSONObject) jsonObject.get("login");
                        // access individual json object thru jsonObject.get("FIELD_NAME")
                        Log.d("TEST", "-error attribute             : " + loginObject.get("error").toString());
                        Log.d("TEST", "-user attribute             : " + loginObject.get("user").toString());
                        // user successfully logged in
                        // Create login session
                        session.setLogin(true);
                        if (!loginObject.isNull("user")) {
                            // handle user login data
                            JSONObject userJSONObject = (JSONObject) loginObject.get("user");
                                Log.d("USER", "User Object                  : " + userJSONObject.toString());
                            String br_code =  userJSONObject.getString("br_code");
                                Log.d("USER", "-br_code attribute           : " + userJSONObject.get("br_code").toString());
                            String mem_id = userJSONObject.getString("mem_id");
                                Log.d("USER", "-mem_id attribute            : " + userJSONObject.get("mem_id").toString());
                            String username = userJSONObject.getString("username");
                                Log.d("USER", "-username attribute          : " + userJSONObject.get("username").toString());
                            String email = userJSONObject.getString("email");
                                Log.d("USER", "-email attribute             : " + userJSONObject.get("email").toString());
                            String created_at = userJSONObject.getString("created_at");
                                Log.d("USER", "-created_at attribute        : " + userJSONObject.get("created_at").toString());
                                Log.d("USER", "--------------------------------------------------------------------------------------------");
                            // Inserting row in users table
                            db.addUser(br_code, mem_id, username, email, created_at);
                        } else {
                            // a new JSON string that doesn't have user in login Object
                            Log.d("USER", "Unknown JSON String              : " + loginObject.toString());
                        }
                        //SL Details
                        if (!jsonObject.isNull("accounts")) {
                            JSONObject accountsObject = (JSONObject) jsonObject.get("accounts");
                            // access individual json object thru jsonObject.get("FIELD_NAME")
                            Log.d("SL_SUMM", "-error attribute             : " + accountsObject.get("error").toString());
                            JSONArray slArray = accountsObject.optJSONArray("sl_summ");
                            // Check if its login data i.e. user present
                            if (slArray != null) {
                                // handle account data
                                JSONArray array = ((JSONArray)accountsObject.getJSONArray("sl_summ"));
                                // access individual json array thru jsonObject.getJSONArray("FIELD_NAME")
                                Log.d("SL_SUMM", "-sl_summ array                       : " + accountsObject.getJSONArray("sl_summ").toString());
                                for (int index=0; index<array.length(); index++) {
                                    JSONObject object = (JSONObject)array.get(index);
                                    String sl_desc= object.getString("sl_desc");
                                        Log.d("SL_SUMM", "-sl_desc attribute           : " + object.get("sl_desc").toString());
                                    String tr_date= object.getString("tr_date");
                                        Log.d("SL_SUMM", "-tr_date attribute           : " + object.get("tr_date").toString());
                                    String actual_balance= object.getString("actual_balance");
                                        Log.d("SL_SUMM", "-actual_balance attribute    : " + object.get("actual_balance").toString());
                                    String available_balance= object.getString("available_balance");
                                        Log.d("SL_SUMM", "-available_balance attribute : " + object.get("available_balance").toString());
                                        Log.d("SL_SUMM", "----------------------------------------------------------------------------------");
                                    db.addUserSLDTL(sl_desc, tr_date, actual_balance, available_balance);
                                }
                            } else {
                                // a new JSON string that doesn't have sl_summ as member variable so display it and write new handler code
                                Log.d("SL_SUMM", "Unknown JSON String          : " + jsonObject.toString());
                            }
                        }
                        // Launch main activity
                        Intent intent = new Intent(LoginActivity.this, MainActivity.class);
                        startActivity(intent);
                        finish();
                    } else {
                        // Error in login. Get the error message
                        String errorMsg = jsonObject.getString("error_msg");
                        Toast.makeText(getApplicationContext(),errorMsg, Toast.LENGTH_LONG).show();
                    }
                } catch (JSONException e) {
                    // JSON error
                    e.printStackTrace();
                    Log.d("TEST", e.toString());
                    Toast.makeText(getApplicationContext(), "Json error: " + e.getMessage(), Toast.LENGTH_LONG).show();
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Log.e(TAG, "Login Error: " + error.getMessage());
                Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_LONG).show();
                hideDialog();
            }
        }) {
            @Override
            protected Map<String, String> getParams() {
                // Posting parameters to login url
                Map<String, String> params = new HashMap<String, String>();
                params.put("username", username);
                params.put("password", password);

                return params;
            }
        };
        // Adding request to request queue
        AppController.getInstance().addToRequestQueue(strReq, tag_string_req);
    }
    private void showDialog() {
        if (!pDialog.isShowing())
            pDialog.show();
    }
    private void hideDialog() {
        if (pDialog.isShowing())
            pDialog.dismiss();
    }
}

SQLiteHanlder.java

public class SQLiteHandler extends SQLiteOpenHelper {

    private static final String TAG = SQLiteHandler.class.getSimpleName();

    // All Static variables
    // Database Version
    private static final int DATABASE_VERSION = 1;

    // Database Name
    private static final String DATABASE_NAME = "test_db";

    // Table name
    private static final String TABLE_MEMBERS = "members";
    private static final String TABLE_MEMBERS_SLDTL = "sldtl";

    // members Table Column name
    private static final String BR_CODE = "br_code";
    private static final String MEM_ID = "mem_id";
    private static final String MEM_USERNAME = "username";
    private static final String MEM_EMAIL = "email";
    private static final String MEM_CREATED_AT = "created_at";

    // sldtl Table Column name
    private static final String SL_DESC = "sl_desc";
    private static final String TR_DATE = "trans_date";
    private static final String ACTUAL_BALANCE = "actual_balance";
    private static final String AVAILABLE_BALANCE = "available_balance";

    // Table Create Statements
    // Members table create statement
    private static final String CREATE_MEMBERS_TABLE = "CREATE TABLE "  + TABLE_MEMBERS + "("
            + BR_CODE + " INTEGER,"
            + MEM_ID + " INTEGER PRIMARY KEY,"
            + MEM_USERNAME + " TEXT,"
            + MEM_EMAIL + " TEXT UNIQUE,"
            + MEM_CREATED_AT + " TEXT" + ")";

    // SLDTL table create statement
    private static final String CREATE_SLDTL_TABLE = "CREATE TABLE " + TABLE_MEMBERS_SLDTL + "("
            + SL_DESC + " TEXT,"
            + TR_DATE + " DATETIME,"
            + ACTUAL_BALANCE + " REAL,"
            + AVAILABLE_BALANCE + " REAL" + ")";

    public SQLiteHandler(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }
    @Override
    public void onCreate(SQLiteDatabase db) {
        // Creating required tables
        db.execSQL(CREATE_MEMBERS_TABLE);
        db.execSQL(CREATE_SLDTL_TABLE);
        Log.d(TAG, "Table members and sldtl was successfully created");
    }
    // Upgrading database
    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        // on upgrade drop existing tables
        db.execSQL("DROP TABLE IF EXISTS " + TABLE_MEMBERS);
        db.execSQL("DROP TABLE IF EXISTS " + TABLE_MEMBERS_SLDTL);

        Log.d(TAG, "Drop table members and sldtl if exists");
        // Creating new tables
        onCreate(db);
    }
    /**
     * Storing user details in database
     * */
    public void addUser(String br_code, String mem_id, String username, String email, String created_at) {
        SQLiteDatabase db = this.getWritableDatabase();

        ContentValues values = new ContentValues();
        values.put(BR_CODE, br_code); // branch code
        values.put(MEM_ID, mem_id); // mem id
        values.put(MEM_USERNAME, username); // username
        values.put(MEM_EMAIL, email); // Email
        values.put(MEM_CREATED_AT, created_at); // Created At

        // Inserting Row
        long id = db.insertOrThrow(TABLE_MEMBERS, null, values);

        db.close(); // Closing database connection

        Log.d(TAG, "Member's info was inserted successfully: " + id);
        Log.d(TAG, "BR CODE: " + br_code);
        Log.d(TAG, "Member ID: " + mem_id);
        Log.d(TAG, "Username: " + username);
        Log.d(TAG, "Email: " + email);
        Log.d(TAG, "Created at: " + created_at);
        Log.d(TAG, "---------------------------------");
    }
    /**
     * Getting user data from database
     * */
    public HashMap<String, String> getUserDetails() {
        HashMap<String, String> user = new HashMap<String, String>();
        String selectQuery = "SELECT * FROM " + TABLE_MEMBERS;

        SQLiteDatabase db = this.getReadableDatabase();
        Cursor cursor = db.rawQuery(selectQuery, null);
        // Move to first row
        cursor.moveToFirst();
        if (cursor.getCount() > 0) {
            user.put("br_code", cursor.getString(0));
            user.put("mem_id", cursor.getString(1));
            user.put("username", cursor.getString(2));
            user.put("email", cursor.getString(3));
            user.put("created_at", cursor.getString(4));

            Log.d(TAG, "Members's data: " + user.toString());
        }
        else{
            Log.d(TAG, "member's data is empty");
        }
        cursor.close();
        db.close();
        // return user
        Log.d(TAG, "Member's info was successfully fetch: " + user.toString());

        return user;
    }
    /**
     * Storing user SL details in database
     * */
    public void addUserSLDTL(String sl_desc, String tr_date, String  actual_balance, String available_balance){
        SQLiteDatabase db = this.getWritableDatabase();

        ContentValues values = new ContentValues();
        values.put(SL_DESC, sl_desc); // sl desc
        values.put(TR_DATE, tr_date); // trans date
        values.put(ACTUAL_BALANCE, actual_balance); // actual balance
        values.put(AVAILABLE_BALANCE, available_balance); // availabe balance

        // Inserting Row
        long id = db.insertOrThrow(TABLE_MEMBERS_SLDTL, null, values);
        db.close(); // Closing database connection

        Log.d(TAG, "Members's SL Details was successfully: " + id);
        Log.d(TAG, "SL Desc: " + sl_desc);
        Log.d(TAG, "Transaction Date: " + tr_date);
        Log.d(TAG, "Actual Balance: " + actual_balance);
        Log.d(TAG, "Available Balance: " + available_balance);
    }
    /**
     * Getting user SL details data from database
     * */
    public HashMap<String, String> getUserSLDTL() {
        HashMap<String, String> sl_summ = new HashMap<String, String>();
        String selectQuery = "SELECT * FROM " + TABLE_MEMBERS_SLDTL;

        SQLiteDatabase db = this.getReadableDatabase();
        Cursor cursor = db.rawQuery(selectQuery, null);
        // Move to first row
        cursor.moveToFirst();
        if (cursor.getCount() > 0) {
            sl_summ.put("sl_desc", cursor.getString(0));
            sl_summ.put("tr_date", cursor.getString(1));
            sl_summ.put("actual_balance", cursor.getString(2));
            sl_summ.put("available_balance", cursor.getString(3));

            Log.d(TAG, "Member's SL Details: " + sl_summ.toString());
        }
        else{
            Log.d(TAG, "member's SLDTL data is empty");
        }
        cursor.close();
        db.close();

        // return user
        Log.d(TAG, "Member's SL Details was successfully fetch: " + sl_summ.toString());

        return sl_summ;
    }
    /**
     * Getting user data from database
     * */
    public List<Datas> getUserSLDetails() {

        String selectQuery = "SELECT * FROM " + TABLE_MEMBERS;
        List<Datas>  mMemberDetails =  new ArrayList<>();

        SQLiteDatabase db = this.getReadableDatabase();
        Cursor cursor = db.rawQuery(selectQuery, null);
        // Move to first row
        cursor.moveToFirst();
        if (cursor.getCount() > 0) {

            Datas pMemebr = new Datas();

            pMemebr.setSL_DESC(cursor.getString(0));
            pMemebr.setTR_DATE(cursor.getString(1));
            pMemebr.setACTUAL_BALANCE(cursor.getString(2));
            pMemebr.setAVAILABLE_BALANCE(cursor.getString(3));

            mMemberDetails.add(pMemebr);
            Log.d(TAG, "Members's data: " + pMemebr.toString());
        }
        else{
            Log.d(TAG, "member's data is empty");
        }
        cursor.close();
        db.close();

        return mMemberDetails;

    }
    /**
     * Re create database Delete all tables and create them again
     * */
    public void deleteUsers() {
        SQLiteDatabase db = this.getWritableDatabase();
        // Delete All Rows
        db.delete(TABLE_MEMBERS, null, null);
        db.close();

        Log.d(TAG, "All member's info are now deleted in sqlite");
    }
    /**
     * Re create database Delete all tables and create them again
     * */
    public void deleteUserSLDTL() {
        SQLiteDatabase db = this.getWritableDatabase();
        // Delete All Rows
        db.delete(TABLE_MEMBERS_SLDTL, null, null);
        db.close();

        Log.d(TAG, "All member's SLDTL info are now deleted in sqlite");
    }
}

AccountsFragment.java

public class AccountsFragment extends Fragment {

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

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View rootView = inflater.inflate(R.layout.fragment_accounts, container, false);
        RecyclerView rv = (RecyclerView) rootView.findViewById(R.id.rv_recycler_view);
        rv.setHasFixedSize(true);
        MyAdapter adapter = new MyAdapter(new String[]{"test one", "test two"});
        rv.setAdapter(adapter);

        LinearLayoutManager llm = new LinearLayoutManager(getActivity());
        rv.setLayoutManager(llm);

        return rootView;
    }
}

MyAdapter.java

public class MyAdapter extends RecyclerView.Adapter<MyAdapter.MyViewHolder> {

    private String[] mDataset;

    // Provide a reference to the views for each data item
    // Complex data items may need more than one view per item, and
    // you provide access to all the views for a data item in a view holder
    public static class MyViewHolder extends RecyclerView.ViewHolder {

        public CardView mCardView;
        public TextView account_type;
        public TextView accnt_description;
        public TextView balance_label;
        public TextView account_balance;

        public MyViewHolder(View v) {
            super(v);

            mCardView = (CardView) v.findViewById(R.id.card_view);

            account_type = (TextView) v.findViewById(R.id.lblShareCapital);
            balance_label = (TextView) v.findViewById(R.id.lblAvailableBalance);

            accnt_description = (TextView) v.findViewById(R.id.sl_desc);
            account_balance = (TextView) v.findViewById(R.id.actual_balance);
        }
    }
    // Provide a suitable constructor (depends on the kind of dataset)
        public MyAdapter(String[] myDataset) {
            mDataset = myDataset;
        }

    // Create new views (invoked by the layout manager)
    @Override
    public MyAdapter.MyViewHolder onCreateViewHolder(ViewGroup parent,
                                                     int viewType) {
        // create a new view
        View v = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.card_item, parent, false);
        // set the view's size, margins, paddings and layout parameters
        MyViewHolder vh = new MyViewHolder(v);
        return vh;
    }
    @Override
    public void onBindViewHolder(MyViewHolder holder, final int position) {
        holder.account_type.setText(mDataset[position]);
        holder.mCardView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String currentValue = mDataset[position];
                Log.d("CardView", "CardView Clicked: " + currentValue);
            }
        });
    }
    @Override
    public int getItemCount() {
        return mDataset.length;
    }
}

Datas.java

public class Datas {

private String SL_DESC;
private String TR_DATE;
private String ACTUAL_BALANCE;
private String AVAILABLE_BALANCE;

public String getSL_DESC() {
    return SL_DESC;
}

public void setSL_DESC(String SL_DESC) {
    this.SL_DESC = SL_DESC;
}

public String getTR_DATE() {
    return TR_DATE;
}

public void setTR_DATE(String TR_DATE) {
    this.TR_DATE = TR_DATE;
}

public String getACTUAL_BALANCE() {
    return ACTUAL_BALANCE;
}

public void setACTUAL_BALANCE(String ACTUAL_BALANCE) {
    this.ACTUAL_BALANCE = ACTUAL_BALANCE;
}

public String getAVAILABLE_BALANCE() {
    return AVAILABLE_BALANCE;
}

public void setAVAILABLE_BALANCE(String AVAILABLE_BALANCE) {
    this.AVAILABLE_BALANCE = AVAILABLE_BALANCE;
}

}

1 个答案:

答案 0 :(得分:0)

更改 AccountFragment 以下行

MyAdapter adapter = new MyAdapter(new String[]{"test one", "test two"});

SQLiteHandler db = new SQLiteHandler(getActivity());
MyAdapter adapter = new MyAdapter(db.getUserSLDetails());

然后在 MyAdapter 类中将第一行中的数据集声明更改为 -

private List<Datas> mDataset;

构造函数

public MyAdapter(List<Datas> myDataset) {
        mDataset = myDataset;
    }

然后在onBindViewHolder方法中

Datas datas = mDataset.get(position);
holder.account_balance.setText(datas.getACTUAL_BALANCE());

完成所有3个更改,然后编译并运行。