Good day, I want to fetch my database data using an Adapter and display it in my RecylcerViewer. But I don't know how to implement it. Hoping that you will guide me how to accomplish these task
I want to replace these data to my database data but I don't know how to do it.
//I want to replace this dummy data to my database data
MyAdapter adapter = new MyAdapter(new String[]{"Dummy Data1", "Dummy Data2"});
AccntFragment.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);
//I want to replace this dummy data to my database data
MyAdapter adapter = new MyAdapter(new String[]{"Dummy Data1", "Dummy Data2"});
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;
}
}
SQliteHandler.java
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;
}
I am just giving you a sample code :-
If you are using String[] then you can replace List and ArrayList into String[].
I am just writing code using List.
you should fetch list of data first.
public List<HashMap<String, String>> getUserDetails() {
HashMap<String, String> user = new HashMap<>();
List<HashMap<String,String>> userList = new ArrayList<>();
// write content values into HashMap
// And add hashMap into List
// userList.add(user);
return userList;
}
And make a method in Adapter like this to notify Adapter :-
static void setList(List<HashMap> list) {
if (list != null && list.size() > 0) {
adapterList.addAll(list);
}
notifyDataSetChanged();
}
List<HashMap<String,String>> userDetailList = getUserDetails();
Once you got data from DataBase then you can call
adapter.setList(userDetailList)
Note : all database operation should do in background thread.
Lets say you can create Members class like
You can change the data type of member variables as per your need:
public class member
{
public int brachCode;
public int mem_id;
public String username;
public String email;
public Date crated_at;
public int getBrachCode() {
return brachCode;
}
public void setBrachCode(int brachCode) {
this.brachCode = brachCode;
}
public int getMem_id() {
return mem_id;
}
public void setMem_id(int mem_id) {
this.mem_id = mem_id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public Date getCrated_at() {
return crated_at;
}
public void setCrated_at(Date crated_at) {
this.crated_at = crated_at;
}
}
And change your SQliteHandler class method as below...
/**
* Getting user data from database
* */
public List<Member> getUserDetails() {
String selectQuery = "SELECT * FROM " + TABLE_MEMBERS;
List<Member> mMemberDetails = new ArrayList<>();
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// Move to first row
cursor.moveToFirst();
if (cursor.getCount() > 0) {
Member pMemebr = new Member();
pMemebr.setBrachCode(cursor.getString(0));
pMemebr.setMem(cursor.getString(1));
pMemebr.setUsername(cursor.getString(2));
pMemebr.setEmail(cursor.getString(3));
pMemebr.setCrated(cursor.getString(4));
mMemberDetails.add(pMemebr);
Log.d(TAG, "Members's data: " + user.toString());
}
else{
Log.d(TAG, "member's data is empty");
}
cursor.close();
db.close();
return mMemberDetails;
}
in your MyAdapter classs change the constructor from this...
private String[] mDataset;
to this..
private List<Member> mDataset;
// Provide a suitable constructor (depends on the kind of dataset)
public MyAdapter(String[] myDataset) {
mDataset = myDataset;
}
to this...
// Provide a suitable constructor (depends on the kind of dataset)
public MyAdapter(List<Member> mMemberDetails) {
mDataset = mMemberDetails;
}
and in onBindViewHolder() change this line :
String currentValue = mDataset[position];
Log.d("CardView", "CardView Clicked: " + currentValue);
to this...
// Provide a suitable constructor (depends on the kind of dataset)
public MyAdapter(List<Member> mMemberDetails) {
mDataset = mMemberDetails;
}
that's it. It will work now.
Related
I am working on android application I which I am using Recycler Adapter and Sqlite database to delete and update the sqlite database.
My Problem is when I Click on Item in Recycler view to delete It Deletes the data from list, But When I Click Back and open List Again The deleted data is still there.
I have checked my database From device File Explorer That The Data does not deleted from database.
Same thing happens with the Update
Here is My Recycler Adapter Class
public class UserRecyclerAdapterSavedUsers extends RecyclerView.Adapter<UserRecyclerAdapterSavedUsers.UserViewHolder> {
private List<User> listUsers;
Context mContext;
RecyclerView mRecyclerView;
ItemClickListenerLongPressed itemClickListenerLongPressed;
UserRecyclerAdapterSavedUsers userRecyclerAdapterSavedUsers;
View itemView;
public UserRecyclerAdapterSavedUsers(List<User> listUsers,RecyclerView recyclerView) {
this.listUsers = listUsers;
mRecyclerView=recyclerView;
}
#Override
public UserViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
mContext= parent.getContext();
itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.item_user_recycler_second, parent, false);
return new UserViewHolder(itemView);
}
/**
* ViewHolder class
*/
public class UserViewHolder extends RecyclerView.ViewHolder {
//public AppCompatTextView ID;
public AppCompatTextView textViewID;
public AppCompatTextView textViewName;
public AppCompatTextView textViewPassword;
public AppCompatTextView textViewRole;
LinearLayout layout;
public UserViewHolder(View view) {
super(view);
textViewID = (AppCompatTextView) view.findViewById(R.id.textViewID);
textViewName = (AppCompatTextView) view.findViewById(R.id.textViewName);
textViewPassword = (AppCompatTextView) view.findViewById(R.id.textViewPassword);
textViewRole = (AppCompatTextView) view.findViewById(R.id.textViewRole);
layout = (LinearLayout) view.findViewById(R.id.list_view);
}
}
#Override
public void onBindViewHolder(UserViewHolder holder, final int position) {
holder.textViewID.setText(listUsers.get(position).getUserid());
holder.textViewName.setText(listUsers.get(position).getName());
holder.textViewPassword.setText(listUsers.get(position).getPassword());
holder.textViewRole.setText(listUsers.get(position).getRole());
holder.layout.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
displayingAlertDialog(position);
return false;
}
});
}
public void setItemClickListenerLongPressed(ItemClickListenerLongPressed itemClickListenerLongPressed) {
this.itemClickListenerLongPressed = itemClickListenerLongPressed;
}
#Override
public int getItemCount() {
Log.v(UsersRecyclerAdapter.class.getSimpleName(),""+listUsers.size());
return listUsers.size();
}
private void displayingAlertDialog(final int position) {
final User user= new User();
//displaying alert dialog box
AlertDialog.Builder builder = new AlertDialog.Builder(itemView.getContext());
builder.setTitle("Choose Option");
builder.setMessage("Update or Delete?");
builder.setPositiveButton("Update", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
//go to update activity
gotupdateuserActivity(user.getUserid());
// dialog.cancel();
}
});
builder.setNeutralButton("Delete", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
//go to Remove Item
DatabaseHelper dbHelper = new DatabaseHelper(mContext);
dbHelper.deletePersonRecord(user.getUserid(), mContext);
listUsers.remove( position);
notifyItemRemoved(position);
mRecyclerView.removeViewAt(position);
notifyItemRangeChanged(position, listUsers.size());
notifyDataSetChanged();
dialog.cancel();
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
AlertDialog alert11 = builder.create();
alert11.show();
}
public void remove(int position) {
listUsers.remove(position);
notifyItemRemoved(position);
}
private void gotupdateuserActivity(String userid) {
Intent goToUpdate = new Intent(mContext, UpdateUserRec.class);
goToUpdate.putExtra("USER_ID", userid);
Toast.makeText(mContext, "USER REC", Toast.LENGTH_SHORT).show();
mContext.startActivity(goToUpdate);
}
}
Here is Sqlite Database Helper Class
public class DatabaseHelper extends SQLiteOpenHelper {
// Database Version
private static final int DATABASE_VERSION = 2;
Context context;
// Database Name
private static final String DATABASE_NAME = "DynamicERP.db";
public static final String table_imei = "IMEITABLE";
public static final String table_login= "USERLOGIN";
// User Table Columns names
public static final String imeiid = "IMEIID";
public static final String imei = "IMEI";
public static final String userid = "USERID";
public static final String username = "USERNAME";
public static final String password = "PASSWORD";
public static final String userrole = "USERROLE";
// create table sql query
private static final String DATABASE_CIMEI = "CREATE TABLE " + table_imei + "("
+ imeiid + " INTEGER, " + imei + " VARCHAR );" ;
private static final String DATABASE_CUSER = "CREATE TABLE " + table_login + "("
+ userid + " INTEGER, " + username + " VARCHAR, " + password + " INTEGER, " + userrole + " VARCHAR );" ;
// drop table sql query
private String DROP_IMEI_TABLE = "DROP TABLE IF EXISTS " + table_imei;
private String DROP_USER_TABLE = "DROP TABLE IF EXISTS " + table_login;
/**
* Constructor
*
* #param context
*/
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(DATABASE_CIMEI);
db.execSQL(DATABASE_CUSER);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
//Drop User Table if exist
db.execSQL(DROP_USER_TABLE);
// Create tables again
onCreate(db);
}
/**
* This method is to create user record
*
* #param user
*/
public void addUser(User user) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(userid,user.getUserid());
values.put(username, user.getName());
values.put(password, user.getPassword());
values.put(userrole, user.getRole());
// Inserting Row
db.insert(table_login, null, values);
db.close();
}
public void addIMEI(User user) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(imei,user.getImei());
values.put(imeiid, user.getImeiid());
// Inserting Row
db.insert(table_imei, null, values);
db.close();
}
/**
* This method is to fetch all user and return the list of user records
*
* #return list
*/
public List<User> getAllUser() {
// array of columns to fetch
String[] columns = {
userid,
username,
password,
userrole
};
// sorting orders
String sortOrder =
userid + " ASC";
List<User> userList = new ArrayList<User>();
SQLiteDatabase db = this.getReadableDatabase();
// query the user table
/**
* Here query function is used to fetch records from user table this function works like we use sql query.
* SQL query equivalent to this query function is
* SELECT user_id,user_name,user_email,user_password FROM user ORDER BY user_name;
*/
Cursor cursor = db.query(table_login, //Table to query
columns, //columns to return
null, //columns for the WHERE clause
null, //The values for the WHERE clause
null, //group the rows
null, //filter by row groups
sortOrder); //The sort order
// Traversing through all rows and adding to list
if (cursor.moveToFirst()) {
do {
User user = new User();
//user.setId(Integer.parseInt(cursor.getString(cursor.getColumnIndex(userid))));
user.setUserid(cursor.getString(cursor.getColumnIndex(userid)));
user.setName(cursor.getString(cursor.getColumnIndex(username)));
user.setPassword(cursor.getString(cursor.getColumnIndex(password)));
user.setRole(cursor.getString(cursor.getColumnIndex(userrole)));
// Adding user record to list
userList.add(user);
} while (cursor.moveToNext());
}
cursor.close();
db.close();
// return user list
return userList;
}
/**
* This method is to fetch all user and return the list of user records
*
* #return list
*/
public List<User> getAllImei() {
// array of columns to fetch
String[] columns = {
imeiid,
imei,
};
// sorting orders
String sortOrder =
imeiid + " ASC";
List<User> userList = new ArrayList<User>();
SQLiteDatabase db = this.getReadableDatabase();
// query the user table
/**
* Here query function is used to fetch records from user table this function works like we use sql query.
* SQL query equivalent to this query function is
* SELECT user_id,user_name,user_email,user_password FROM user ORDER BY user_name;
*/
Cursor cursor = db.query(table_imei, //Table to query
columns, //columns to return
null, //columns for the WHERE clause
null, //The values for the WHERE clause
null, //group the rows
null, //filter by row groups
sortOrder); //The sort order
// Traversing through all rows and adding to list
if (cursor.moveToFirst()) {
do {
User user = new User();
//user.setId(Integer.parseInt(cursor.getString(cursor.getColumnIndex(userid))));
user.setImei(cursor.getString(cursor.getColumnIndex(imei)));
user.setImeiid(cursor.getString(cursor.getColumnIndex(imeiid)));
// Adding user record to list
userList.add(user);
} while (cursor.moveToNext());
}
cursor.close();
db.close();
// return user list
return userList;
}
/**
* This method to update user record
*
* #param receivedUSERId
* #param updateUserRec
* #param user
*/
public void updateUser(String receivedUSERId, UpdateUserRec updateUserRec, User user) {
SQLiteDatabase db = this.getWritableDatabase();
String strSQL = "UPDATE "+table_login+ " SET "+username+" = "+user.getName()+"," +
" "+password+" = "+user.getPassword()+","+userrole+" = "+user.getRole()+"" +
" WHERE "+userid+" = "+receivedUSERId;
db.execSQL(strSQL);
db.close();
}
/**
* This method is to delete user record
*
* #param user
*/
public void deleteUser(User user) {
SQLiteDatabase db = this.getWritableDatabase();
// delete user record by id
db.delete(table_login, userid + " = ?",
new String[]{String.valueOf(user.getUserid())});
db.close();
}
/**
* This method to check user exist or not
*
#param userid
* #return true/false
*/
public boolean checkUser(String userid) {
// array of columns to fetch
String[] columns = {
userid
};
SQLiteDatabase db = this.getReadableDatabase();
// selection criteria
String selection = userid + " = ?";
// selection argument
String[] selectionArgs = {userid};
// query user table with condition
/**
* Here query function is used to fetch records from user table this function works like we use sql query.
* SQL query equivalent to this query function is
* SELECT user_id FROM user WHERE imei = 'dynamic#imei.com';
*/
Cursor cursor = db.query(table_login, //Table to query
columns, //columns to return
selection, //columns for the WHERE clause
selectionArgs, //The values for the WHERE clause
null, //group the rows
null, //filter by row groups
null); //The sort order
int cursorCount = cursor.getCount();
cursor.close();
db.close();
if (cursorCount > 0) {
return true;
}
return false;
}
/**
* This method to check user exist or not
*
* #param email
* #param password
* #return true/false
*/
public boolean checkUser(String email, String password) {
// array of columns to fetch
String[] columns = {
userid
};
SQLiteDatabase db = this.getReadableDatabase();
// selection criteria
String selection = userid + " = ?" + " AND " + password + " = ?";
// selection arguments
String[] selectionArgs = {email, password};
// query user table with conditions
/**
* Here query function is used to fetch records from user table this function works like we use sql query.
* SQL query equivalent to this query function is
* SELECT user_id FROM user WHERE user_email = 'jack#androidtutorialshub.com' AND user_password = 'qwerty';
*/
Cursor cursor = db.query(table_login, //Table to query
columns, //columns to return
selection, //columns for the WHERE clause
selectionArgs, //The values for the WHERE clause
null, //group the rows
null, //filter by row groups
null); //The sort order
int cursorCount = cursor.getCount();
cursor.close();
db.close();
if (cursorCount > 0) {
return true;
}
return false;
}
/**
* This method to check user exist or not
*
* #param userid
* #param username
* #return true/false
*/
public boolean checkUserData(String userid, String username) {
// array of columns to fetch
String[] columns = {
userid
};
SQLiteDatabase db = this.getReadableDatabase();
// selection criteria
String selection = userid + " = ?" + " AND " + username + " = ?";
// selection arguments
String[] selectionArgs = {userid, username};
// query user table with conditions
/**
* Here query function is used to fetch records from user table this function works like we use sql query.
* SQL query equivalent to this query function is
* SELECT user_id FROM user WHERE user_email = 'jack#androidtutorialshub.com' AND user_password = 'qwerty';
*/
Cursor cursor = db.query(table_login, //Table to query
columns, //columns to return
selection, //columns for the WHERE clause
selectionArgs, //The values for the WHERE clause
null, //group the rows
null, //filter by row groups
null); //The sort order
int cursorCount = cursor.getCount();
cursor.close();
db.close();
if (cursorCount > 0) {
return true;
}
return false;
}
public boolean checkUserData(String userid) {
// array of columns to fetch
String[] columns = {
userid
};
SQLiteDatabase db = this.getReadableDatabase();
// selection criteria
String selection = userid + " = ?";
// selection argument
String[] selectionArgs = {userid};
// query user table with condition
/**
* Here query function is used to fetch records from user table this function works like we use sql query.
* SQL query equivalent to this query function is
* SELECT user_id FROM user WHERE user_email = 'dynamic#data.com';
*/
Cursor cursor = db.query(table_login, //Table to query
columns, //columns to return
selection, //columns for the WHERE clause
selectionArgs, //The values for the WHERE clause
null, //group the rows
null, //filter by row groups
null); //The sort order
int cursorCount = cursor.getCount();
cursor.close();
db.close();
if (cursorCount > 0) {
return true;
}
return false;
}
public User getUser(String id){
SQLiteDatabase db = this.getWritableDatabase();
String query= "SELECT * FROM "+table_login;
Cursor cursor = db.rawQuery(query, null);
User user = new User();
if(cursor.getCount() > 0) {
cursor.moveToFirst();
user.setUserid(cursor.getString(cursor.getColumnIndex(userid)));
user.setName(cursor.getString(cursor.getColumnIndex(username)));
user.setPassword(cursor.getString(cursor.getColumnIndex(password)));
user.setRole(cursor.getString(cursor.getColumnIndex(userrole)));
}
return user;
}
public void deletePersonRecord(String useridValue, Context mContext) {
SQLiteDatabase db = this.getWritableDatabase();
db.execSQL("DELETE FROM "+table_login+" WHERE "+userid +"='"+useridValue+"'");
Toast.makeText(mContext, "Deleted successfully.", Toast.LENGTH_SHORT).show();
db.close();
}
public void deleteIMEIRecord(String imeiidValue, Context mContext) {
SQLiteDatabase db = this.getWritableDatabase();
db.execSQL("DELETE FROM "+table_imei+" WHERE "+imeiid +"='"+imeiidValue+"'");
Toast.makeText(mContext, "Deleted successfully.", Toast.LENGTH_SHORT).show();
}
public void updateIMEI(String receivedIMEIId, UpdateIMEIRec updateIMEIRec, User user) {
SQLiteDatabase db = this.getWritableDatabase();
String strSQL = "UPDATE "+table_imei+ " SET "+imei+" = "+user.getImei()+"," +
" "+imeiid+" = "+user.getImeiid()+
" WHERE "+imeiid+" = "+receivedIMEIId;
db.execSQL(strSQL);
db.close();
}
public User getIMEI(String receivedIMEIId) {
SQLiteDatabase db = this.getWritableDatabase();
String query = "SELECT * FROM " + table_imei ;
Cursor cursor = db.rawQuery(query, null);
User user = new User();
if(cursor.getCount() > 0) {
cursor.moveToFirst();
user.setImeiid(cursor.getString(cursor.getColumnIndex(imeiid)));
user.setImei(cursor.getString(cursor.getColumnIndex(imei)));
}
return user;
}
}
And Here is my Recycler List Activity Class
public class UserUpdateListActivity extends AppCompatActivity {
AppCompatActivity activity = UserUpdateListActivity.this;
AppCompatTextView textViewName;
RecyclerView recyclerViewUsers;
AppCompatButton textViewButtonNewUser;
List<User> listUsers;
UserRecyclerAdapterSavedUsers userRecyclerAdapterSavedUsers;
DatabaseHelper databaseHelper;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_user_record_updated_list);
//getSupportActionBar().setTitle("");
initViews();
initObjects();
}
#Override
public void onBackPressed() {
super.onBackPressed();
startActivity(new Intent(UserUpdateListActivity.this,AdminMain.class));
finish();
}
#Override
protected void onRestart() {
super.onRestart();
}
/**
* This method is to initialize views
*/
private void initViews() {
textViewName = (AppCompatTextView) findViewById(R.id.textViewName);
textViewButtonNewUser = (AppCompatButton) findViewById(R.id.btnaddnew);
recyclerViewUsers = (RecyclerView) findViewById(R.id.recyclerViewUsers);
textViewButtonNewUser.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(UserUpdateListActivity.this,UserRecordSaveActivity.class));
}
});
}
/**
* This method is to initialize objects to be used
*/
private void initObjects() {
listUsers = new ArrayList<>();
userRecyclerAdapterSavedUsers = new UserRecyclerAdapterSavedUsers(listUsers,recyclerViewUsers);
RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getApplicationContext());
recyclerViewUsers.setLayoutManager(mLayoutManager);
recyclerViewUsers.setItemAnimator(new DefaultItemAnimator());
recyclerViewUsers.setHasFixedSize(true);
recyclerViewUsers.setAdapter(userRecyclerAdapterSavedUsers);
databaseHelper = new DatabaseHelper(activity);
String emailFromIntent = getIntent().getStringExtra("USERS");
textViewName.setText(emailFromIntent);
getDataFromSQLite();
}
/**
* This method is to fetch all user records from SQLite
*/
private void getDataFromSQLite() {
// AsyncTask is used that SQLite operation not blocks the UI Thread.
new AsyncTask<Void, Void, Void>() {
#Override
protected Void doInBackground(Void... params) {
listUsers.clear();
listUsers.addAll(databaseHelper.getAllUser());
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
userRecyclerAdapterSavedUsers.notifyDataSetChanged();
}
}.execute();
}
}
This is the Query I am using to delete the data
public void deletePersonRecord(String useridValue, Context mContext) {
SQLiteDatabase db = this.getWritableDatabase();
db.execSQL("DELETE FROM "+table_login+" WHERE "+userid +"='"+useridValue+"'");
Toast.makeText(mContext, "Deleted successfully.", Toast.LENGTH_SHORT).show();
db.close();
}
Here is image of my recycler list
List Items
As I click on an Item It open me a Dialog like this
Dialog
When I click on delete this shows me this
Clicking on Delete
After that As I pressed back and again open the Data I deleted again open
Logcat has no Errors
Here is my update activity
public class UpdateUserRec extends AppCompatActivity {
EditText UserIDUpdate,UserNameUpdate,UserPasswordUpdate,UserRoleUpdate;
Button BtnUserRecUpdate;
DatabaseHelper dbHelper;
String receivedUSERId;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_update_record);
UserIDUpdate= (EditText) findViewById(R.id.useridupdate);
UserNameUpdate= (EditText) findViewById(R.id.usernameupdate);
UserPasswordUpdate= (EditText) findViewById(R.id.userpasswordupdate);
UserRoleUpdate= (EditText) findViewById(R.id.userroleupdate);
BtnUserRecUpdate= (Button) findViewById(R.id.userbtnupdate);
dbHelper = new DatabaseHelper(this);
try {
//get intent to get person id
receivedUSERId= getIntent().getStringExtra("USER_ID");
} catch (Exception e) {
e.printStackTrace();
}
User user= dbHelper.getUser(receivedUSERId);
UserIDUpdate.setText(user.getUserid());
UserNameUpdate.setText(user.getName());
UserPasswordUpdate.setText(user.getPassword());
UserRoleUpdate.setText(user.getRole());
BtnUserRecUpdate.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
updateUserFunction();
}
});
}
private void updateUserFunction() {
String useridupdate = UserIDUpdate.getText().toString().trim();
String usernameupdate = UserNameUpdate.getText().toString().trim();
String userpasswordupdate = UserRoleUpdate.getText().toString().trim();
String userroleupdate = UserRoleUpdate.getText().toString().trim();
if(useridupdate.isEmpty()){
//error name is empty
Toast.makeText(this, "Enter User ID", Toast.LENGTH_LONG).show();
}
if(usernameupdate.isEmpty()){
//error name is empty
Toast.makeText(this, "Enter User Name", Toast.LENGTH_LONG).show();
}
if(userpasswordupdate.isEmpty()){
//error name is empty
Toast.makeText(this, "Enter the password", Toast.LENGTH_LONG).show();
}
if(userroleupdate.isEmpty()){
//error name is empty
Toast.makeText(this, "Enter User Role", Toast.LENGTH_LONG).show();
}
//create updated person
User user = new User();
//call dbhelper update
dbHelper.updateUser(receivedUSERId, this, user);
//finally redirect back home
// NOTE you can implement an sqlite callback then redirect on success delete
goBackHome();
}
private void goBackHome() {
startActivity(new Intent(UpdateUserRec.this,UsersListActivity.class));
}
}
You are deleting data from the list that is showing data in RecyclerView. You should keep in mind Database is different entity from your list. Data base is persistent storage for data and list from where you deleting item is non persistent storage. Next time when you get data from Database the list will again fill with items that you previously deleted.
Correct method is
Delete the row from Database
Remove item from list in adapter
notifyItemRemoved(position)
You have this method in SQL class
public List<User> getAllUser() { ... }
Create one more method
public boolean deleteUser(id){
db.delete(DATABASE_TABLE, KEY_NAME + "=" + id, null)
}
On delete item call this method from your adapter with specific Id then do the same as you doing previously.
try changing your delete functionality with this and see if it works
builder.setNeutralButton("Delete", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
//go to Remove Item
DatabaseHelper dbHelper = new DatabaseHelper(mContext);
dbHelper.deletePersonRecord(listUsers.get(position).getUserid(), mContext);
listUsers.remove( position);
notifyItemRemoved(position);
mRecyclerView.removeViewAt(position);
notifyItemRangeChanged(position, listUsers.size());
notifyDataSetChanged();
dialog.cancel();
}
});
EDIT: for your new problem: about updating user
change your setPositiveButton functionality like this
builder.setPositiveButton("Update", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
//go to update activity
gotupdateuserActivity(listUsers.get(position).getUserid());
// dialog.cancel();
}
});
We can show all records in the DB no issue. When we try to limit the items to show with a sql Select the search and the RecyclerView Adapter populates correctly.
The code fails when the item is selected in the list view. The list view did not get the message about what position this record is at so the view when we navigate to the DetailActivity view from ListActivity is not the item in the ListView
My question is how to manage the position variable that the Adapter is using?
This code flow is as follows a button click on MainActivity sets the search variable goes to ListActivity that makes a call to DBHelper which returns to ListActivity with modelList which is and Array List Yes the design is MVP so we have a Model Class relevant code below
Main Activity btn Click
public void findAllData(View view){
selectSTRING = etFromDate.getText().toString();
Intent intent = new Intent( MainActivity.this, ListActivity.class );
startActivity( intent );
}
ListActivity call to DBHelper commented out line gets all data
helpher = new DBHelper(this);
dbList = new ArrayList<>();
dbList = helpher.getRangeDataFromDB();
//dbList = helpher.getDataFromDB();
DBHelper code to grab the selected record or records eventually
public List<DBModel> getRangeDataFromDB() {
List<DBModel> modelList = new ArrayList<>();
db = this.getReadableDatabase();
String query = "SELECT * FROM " + TABLE_INFO + " WHERE " + Col_PURCHASE_DATE + " ='" + selectSTRING + "'";
Cursor cursor = db.rawQuery(query, null);
//Cursor cursor = db.rawQuery("SELECT * FROM " + TABLE_INFO + " WHERE " + Col_PURCHASE_DATE + "='" + str + "'" , null);
String newBACK = selectSTRING;
if (cursor.moveToFirst()) {
DBModel model = new DBModel();
while (!cursor.isAfterLast()) {
if (newBACK == selectSTRING) {
model.setRowid(cursor.getString(0));
model.setStation_Name(cursor.getString(1));
model.setDate_of_Purchase(cursor.getString(2));
model.setGas_Cost(cursor.getString(3));
modelList.add(model);
cursor.moveToNext();
}
}
}
int sz = modelList.size();
System.out.println("========= SIZE "+sz);
db.close();
return modelList;
}
Now we use an intent to go to DetailsActivity and this is the fail
public class RecyclerAdapter extends RecyclerView.Adapter<RecyclerAdapter.ViewHolder> {
static List<DBModel> dbList;
static private Context context;
RecyclerAdapter(Context context, List<DBModel> dbList) {
RecyclerAdapter.dbList = new ArrayList<>();
RecyclerAdapter.context = context;
RecyclerAdapter.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.rowid.setText(dbList.get(position).getRowid());
holder.station.setText(dbList.get(position).getStation_Name());
System.out.println("========== new position "+position);
}
#Override
public int getItemCount() {
return dbList.size();
}
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
public TextView station, rowid;
public ViewHolder(View itemLayoutView) {
super(itemLayoutView);
rowid = (TextView) itemLayoutView.findViewById(R.id.rvROWID);
station = (TextView) itemLayoutView.findViewById(R.id.rvSTATION);
// Attach a click listener to the entire row view
itemLayoutView.setOnClickListener(this);
}
#Override // When an item in DetailsActivity is touched (selected) the RecyclerView has
// a OnClickListener attached in the above Code that implements the method below
public void onClick(View v) {
System.out.println("======RowID "+rowid);
Intent intentN = new Intent(context, DetailsActivity.class);
Bundle extras = new Bundle();
extras.putInt("POSITION", getAdapterPosition());
extras.putString("FROM_LIST_ACTIVITY", "false");
///position = getAdapterPosition();
///position = getLayoutPosition();// Both work the same
intentN.putExtras(extras);
context.startActivity(intentN);
}
}
Thought about sending the data back from the DBHelper not sure how to write an Intent in that Class. This is turning into spaghetti code!
The solution to this issue is the developer had multiple search designs in the DBHelper each being triggered by different buttons on the search Activity this design in the DBHelper lead to multiple ArrayLists all with the same name this drove the RecycleAdapter crazy as it is bound to ArrayList so OLD Mr. Boolean to the rescue! Here is the revised design code features
In the Search Activity declare public static Boolean use = false;
and Import where needed import static com..MainActivity.use;
Here is the code for each search button
public void findAllData(View view){
helper = new DBHelper(this);
helper.getDataFromDB();
use = false;
// Set Mr. Boolean
Intent intent = new Intent( MainActivity.this, ListActivity.class );
// ListActivity shows Results of the Search
startActivity( intent );
}
public void findSelect(View v){
selectSTRING = etFromDate.getText().toString();
// Get your Search variable
helper = new DBHelper(this);
helper.getDataFromDB();
etToDate.setText(sendBACK);
use = true;
Intent intent = new Intent( MainActivity.this, ListActivity.class );
startActivity( intent );
}
Now we do the desired Search in DBHelper
/* Retrive ALL data from database table named "TABLE_INFO" */
public List<DBModel> getDataFromDB(){
//String query = "SELECT * FROM " + TABLE_INFO + " WHERE " + Col_PURCHASE_DATE + " > 0 " + " ORDER BY " + Col_ID + " DESC ";
/* Notice the SPACES before AND after the words WHERE ORDER BY ASC or DESC most of all the condition " > 0 "*/
/* =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=*/
Cursor cursor = null;
List<DBModel> modelList = new ArrayList<>();
if(use == true){
String query = "SELECT * FROM " + TABLE_INFO + " WHERE " + Col_PURCHASE_DATE + " ='" + selectSTRING + "'";
db = this.getWritableDatabase();
cursor = db.rawQuery(query,null);
}
if(use == false){
String query = "SELECT * FROM " + TABLE_INFO;
db = this.getWritableDatabase();
cursor = db.rawQuery(query,null);
}
if (cursor.moveToFirst()){
do {
DBModel model = new DBModel();
model.setRowid(cursor.getInt(0));
model.setStation_Name(cursor.getString(1));
model.setDate_of_Purchase(cursor.getString(2));
model.setGas_Cost(cursor.getString(3));
modelList.add(model);
int sz = modelList.size();
int out = model.setRowid(cursor.getInt(0));
String out1 = model.setStation_Name(cursor.getString(1));
String out2 = model.setDate_of_Purchase(cursor.getString(2));
String out3 = model.setGas_Cost(cursor.getString(3));
System.out.println("==============getDataFromDB ID "+out);
System.out.println("==============getDataFromDB Station "+out1);
System.out.println("==============getDataFromDB Date "+out2);
System.out.println("==============getDataFromDB Cost "+out3);
System.out.println("======= ======getDataFromDB SIZE "+sz);
}while (cursor.moveToNext());
}
db.close();
cursor.close();
return modelList;
}
The only stumble with this is that if if you do a search by date and do an add to the DB and jump back to the ListActivity the new record is not displayed
We are working on this Stay Tuned ha ha Good Job James_Duh
You should set your OnClickListener here :
#Override
public void onBindViewHolder(ReportAdapter.ViewHolderReport holder, int position) {
final Object object = objects.get(position);
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Do Something with the object at this position
}
});
}
instead of your ViewHolder because you shouldn't trust the adapter position at a time.
I am making small app. It has 2 listview on MainActivity.
DB is SQLLite and has tree cloumns id(int), person(text), status(text).
Firt listview will be show informations from DB with this query
select * from DB where status=B
And next ListView will show information where status=A.
lv1.status=b | lv2.status=a
Person 1 | Person 2
Person 3 | Person 4
When i click lv2 on item, value of clicked lv2 field 'status' must change to 'b'.
But I can not write right query for db.
public void changeUser(){
db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_STATUS, "B");
db.update(TABLE_ORDER, values, null, null);
db.close();
}
Thanks
Here is my code
lvB = (ListView)findViewById(R.id.lvB);
listClientB();
lvA = (ListView)findViewById(R.id.lvA);
listClientA();
lvA.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
User user = (User)adapterView.getAdapter().getItem(i);
int id = user.get_id();
if (user.getStatus().contains("A")){
dbHelper.changeUser();
}
Toast.makeText(getApplicationContext(), id + "-NUMBER id", Toast.LENGTH_LONG).show();
Log.d(String.valueOf(user.get_id()), "-NUMBER id");
listClientA();
Log.d(user.getStatus(), "Pressed");
}
});
}
private void listClientA(){
list = dbHelper.allUsersA();
klientStatusAdapter = new KlientStatusAdapter(MainActivity.this, list);
lvA.setAdapter(klientStatusAdapter);
lvA.setTextFilterEnabled(true);
}
private void listClientB(){
list = dbHelper.allUsersB();
klientStatusAdapter = new KlientStatusAdapter(MainActivity.this, list);
lvB.setAdapter(klientStatusAdapter);
lvB.setTextFilterEnabled(true);
}
Here is from DB
public List<User> allUsersA(){
db = this.getReadableDatabase();
List<User> users = new ArrayList<User>();
String s = "select * from " + TABLE_ORDER + " where status = 'A'";
Cursor cursor = db.rawQuery(s, null);
if (cursor.moveToFirst()){
do {
User user = new User();
user.set_id(Integer.parseInt(cursor.getString(0)));
user.setClientName(cursor.getString(1));
user.setCleintOrderedFood(cursor.getString(2));
user.setStatus(cursor.getString(3));
users.add(user);
}while (cursor.moveToNext());
}
db.close();
return users;
}
public List<User> allUsersB(){
db = this.getReadableDatabase();
List<User> users = new ArrayList<User>();
String s = "select * from " + TABLE_ORDER + " where status = 'B'";
Cursor cursor = db.rawQuery(s, null);
if (cursor.moveToFirst()){
do {
User user = new User();
user.set_id(Integer.parseInt(cursor.getString(0)));
user.setClientName(cursor.getString(1));
user.setCleintOrderedFood(cursor.getString(2));
user.setStatus(cursor.getString(3));
users.add(user);
}while (cursor.moveToNext());
}
db.close();
return users;
}
public void changeUser(){
db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_STATUS, "B");
db.update(TABLE_ORDER, values, null, null);
db.close();
}
Here is adapter
public class ClientStatusAdapter extends BaseAdapter{
LayoutInflater inflater;
Context context;
List<User> wordsList;
DbHelper dbHelper;
public ClientStatusAdapter(Context context1, List<User> wordsList) {
this.context = context1;
this.wordsList = wordsList;
inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
dbHelper = new DbHelper(context);
}
#Override
public int getCount() {
return wordsList.size();
}
#Override
public Object getItem(int i) {
return wordsList.get(i);
}
#Override
public long getItemId(int i) {
return i;
}
#Override
public View getView(int i, View view, ViewGroup viewGroup) {
if (view == null){
view = inflater.inflate(R.layout.kliyent_status_adapter, null);
}
TextView txtIsmAdapter = (TextView)view.findViewById(R.id.txtIsmAdapter);
TextView txtOvqatAdapter = (TextView)view.findViewById(R.id.txtOvqatAdapter);
final User user = wordsList.get(i);
TextView txtCliyentNames = (TextView)view.findViewById(R.id.txtCliyentNames);
txtCliyentNames.setText(user.getClientName());
TextView txtCliyentOrderedFoood = (TextView)view.findViewById(R.id.txtCliyentOrderedFoood);
txtCliyentOrderedFoood.setText(user.getCleintOrderedFood());
TextView txtStatusAdapter = (TextView)view.findViewById(R.id.txtStatusAdapter);
txtStatusAdapter.setText(user.getStatus());
notifyDataSetChanged();
ImageView imgOn = (ImageView) view.findViewById(R.id.imgOn);
return view;
}
}
Here is entity User
public class User {
private int _id;
private String clientName;
private String cleintOrderedFood;
private String status = "A";
public User() {
}
public User(int _id, String clientName, String cleintOrderedFood) {
this._id = _id;
this.clientName = clientName;
this.cleintOrderedFood = cleintOrderedFood;
}
public User(int _id, String clientName, String cleintOrderedFood, String status) {
this._id = _id;
this.clientName = clientName;
this.cleintOrderedFood = cleintOrderedFood;
this.status = status;
}
public int get_id() {
return _id;
}
public void set_id(int _id) {
this._id = _id;
}
public String getClientName() {
return clientName;
}
public void setClientName(String clientName) {
this.clientName = clientName;
}
public String getCleintOrderedFood() {
return cleintOrderedFood;
}
public void setCleintOrderedFood(String cleintOrderedFood) {
this.cleintOrderedFood = cleintOrderedFood;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
}
If you look closely at the SQLiteDatabase.update() method, you will see it is declared as
int update (String table,
ContentValues values,
String whereClause,
String[] whereArgs)
Note the last two parameters. These are how you select which rows to update. For example, you can specify to only update rows with a given id:
public void changeUser(int userId){
db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_STATUS, "B");
String whereClause = "_id = ?";
String where = new String[] {Integer.toString(userId)};
db.update(TABLE_ORDER, values, whereClause, where);
db.close();
}
Here I am assuming you use the conventional column name _id. Of course, you can change this to suit your needs if you have a different column name.
Note that you will now need to pass a parameter to changeUser(). However, you have not shown how nor where you currently call it, so I am unable to provide any advice how to change this.
I am using Recyclerview ,Here is Json file the insert query written in Json array though the json data is not stored in SQLite.When we destroy the app and again restart it will only show
blank rows and again press a button and it will show json data aftr emptyrow ie:after destroy data gets lost.Do help me thank you
public class Recyclerview extends AppCompatActivity {
private RecyclerView mRecyclerView;
CustomAdapter cu;
ArrayList<Employee> arr, arr1;
Toolbar toolbar;
TextView t1, t2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.recyclerview);
toolbar = (Toolbar) findViewById(R.id.toolbar1);
setSupportActionBar(toolbar);
final RecyclerView rv = (RecyclerView) findViewById(R.id.rv);
rv.setHasFixedSize(true);
arr = new ArrayList<Employee>();
arr = InitializeData();
final LinearLayoutManager llm = new LinearLayoutManager(Recyclerview.this);
rv.setLayoutManager(llm);
rv.setHasFixedSize(true);
cu = new CustomAdapter(Recyclerview.this, arr);
rv.setAdapter(cu);
registerForContextMenu(rv);
final bank ban = new bank(Recyclerview.this);
ImageButton refresh = (ImageButton) findViewById(R.id.refresh);
refresh.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(Recyclerview.this, "ok", Toast.LENGTH_LONG).show();
if (isNetworkAvailable()) {
String url = ConstantValues.BASE_URL;
RequestBody formBody = new FormBody.Builder()
.add("key1", "value1")
.add("key2", "value2")
.add("key3", "value3")
.build();
try {
post(url, formBody, new Callback() {
#Override
public void onFailure(Call call, IOException e) {
Log.e("JSONDemo", "IOException", e);
}
#Override
public void onResponse(final Call call, final Response response) throws IOException {
String JSON = response.body().string();
Log.e("res", " " + JSON);
try {
JSONObject jsonObj = new JSONObject(JSON);
JSONArray resultarr = jsonObj.getJSONArray("result");
final JSONArray resultarr1 = jsonObj.getJSONArray("result1");
ban.OpenDB();
ban.OpenDB();
for (int i = 0; i < resultarr1.length(); i++) {
Employee emp = new Employee();
JSONObject result1obj = resultarr1.getJSONObject(i);
String result1Id = result1obj.getString(ConstantValues.Bank_ID);
String result1NAME = result1obj.getString(ConstantValues.Bank_NAME);
Log.e("result", " " + result1Id);
Log.e("result", " " + result1NAME);
emp.setId(result1obj.getString(ConstantValues.Bank_ID));
emp.setName(result1obj.getString(ConstantValues.Bank_NAME));
arr.add(emp);
long l = 0;
l=ban.InsertQryForTabEmpData(ConstantValues.Bank_ID,ConstantValues.Bank_NAME);
}
ban.CloseDB();
runOnUiThread(new Runnable() {
#Override
public void run() {
cu.notifyDataSetChanged();
}
});
} catch (Exception e) {
Log.e("JSONDemo", "onResponse", e);
}
}
});
} catch (Exception e) {
Log.e("JSONDemo", "Post Exception", e);
}
} else {
Toast.makeText(Recyclerview.this, "Internet not available", Toast.LENGTH_LONG).show();
}
}
});
}
private ArrayList<Employee> InitializeData() {
ArrayList<Employee> arr_emp = new ArrayList<Employee>();
bank ban = new bank(Recyclerview.this);
long l = 0;
ban.OpenDB();
arr_emp = ban.AllSelectQryForTabEmpData1();
ban.CloseDB();
return arr_emp;
}
private boolean isNetworkAvailable() {
ConnectivityManager connectivityManager
= (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
return activeNetworkInfo != null && activeNetworkInfo.isConnected();
}
private final OkHttpClient client = new OkHttpClient();
Call post(String url, RequestBody formBody, Callback callback) throws IOException {
Request request = new Request.Builder()
.url(url)
.post(formBody)
.build();
Call call = client.newCall(request);
call.enqueue(callback);
return call;
}
}
It is the query of all SQLite:
public class bank {
private Context context;
private SQLiteDatabase SQLiteDb;
public bank(Context context){
this.context=context;
}
public static class DBHelper extends SQLiteOpenHelper{
public DBHelper(Context context) {
super(context, ConstantValues.DBName, null, 1);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(" create table if not exists " + ConstantValues.TabEmpData+"("
+ ConstantValues.Bank_ID + " text, "
+ ConstantValues.Bank_NAME + " text )");
}
#Override
public void onUpgrade(SQLiteDatabase db, int i, int i1) {
db.execSQL(" create table if not exists " + ConstantValues.TabEmpData+"("
+ ConstantValues.Bank_ID + " text, "
+ ConstantValues.Bank_NAME + " text )");
}
}
public void OpenDB() {
SQLiteDb = new DBHelper(context).getWritableDatabase();
}
public void CloseDB() {
if (SQLiteDb.isOpen()) {
SQLiteDb.close();
}
}
public long InsertQryForTabEmpData(String ID, String NAME) {
ContentValues cv = new ContentValues();
cv.put(ConstantValues.Bank_ID, ID);
cv.put(ConstantValues.Bank_NAME, NAME);
long l = SQLiteDb.insert(ConstantValues.TabEmpData, null, cv);
return l;
}
public long UpdateQryForTabEmpData(String ID
, String NAME
) {
ContentValues cv = new ContentValues();
cv.put(ConstantValues.Bank_ID, ID);
cv.put(ConstantValues.Bank_NAME, NAME);
long l = SQLiteDb.update(ConstantValues.TabEmpData, cv, ConstantValues.Bank_ID+ "=" + ID, null);
return l;
}
public long DeleteQryForTabEmpData(String ID) {
long l = SQLiteDb.delete(ConstantValues.TabEmpData, ConstantValues.Bank_ID+ "=" + ID, null);
return l;
}
public ArrayList SelectQryForTabEmpData(String ID) {
ArrayList<String> data = new ArrayList();
String[] arg = {
"ID"
, "NAME"
};
String selection = " ID= " + ID;
String QRY = " SELECT ID,NAME FROM TabEmpData WHERE ID = " + ID;// +" AND EmpFName = 'test' grup by empid,fname,lastname having Empsalary > = 2000 order by fname asc,salry desc limit 100";
Cursor cursor = SQLiteDb.rawQuery(QRY, null);//
SQLiteDb.query(ConstantValues.TabEmpData, arg, selection, null, null, null, null, null);
while (cursor.moveToNext()) {
data.add(0, cursor.getString(cursor.getColumnIndex(ConstantValues.Bank_ID)));
data.add(1, cursor.getString(cursor.getColumnIndex(ConstantValues.Bank_NAME)));
}
cursor.close();
return data;
}
public ArrayList AllSelectQryForTabEmpData1() {
ArrayList<Employee> data = new ArrayList();
Cursor cursor = SQLiteDb.query(ConstantValues.TabEmpData, null, null, null, null, null, null, null);
while (cursor.moveToNext()) {
String id = cursor.getString(cursor.getColumnIndex(ConstantValues.Bank_ID));
String name = cursor.getString(cursor.getColumnIndex(ConstantValues.Bank_NAME));
data.add(new Employee(id, name));
}
cursor.close();
return data;
}
}
Its my Custom Adapter:
public class CustomAdapter extends RecyclerView.Adapter<CustomAdapter.EmpDataViewHolder> {
final bank ban = new bank(CustomAdapter.this.context);
private ArrayList<Employee> arr,filterlist;
private Context context;
public CustomAdapter(Context context, ArrayList<Employee> arr) {
this.arr=arr;
this.context=context;
Toast.makeText(context,""+arr.size(),Toast.LENGTH_LONG).show();
}
#Override
public EmpDataViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(context).inflate(R.layout.cardview, parent, false);
EmpDataViewHolder edvh = new EmpDataViewHolder(v);
return edvh;
}
#Override
public void onBindViewHolder(EmpDataViewHolder holder, int position) {
Employee emp=arr.get(position) ;
holder.id.setText(emp.getId());
holder.name.setText(emp.getName());
holder.cv.setTag(R.string.KeyForCV,position);
}
#Override
public int getItemCount() {
return arr.size();
}
public class EmpDataViewHolder extends RecyclerView.ViewHolder {
CardView cv;
TextView id;
TextView name;
public EmpDataViewHolder(View itemView) {
super(itemView);
cv= (CardView) itemView.findViewById(R.id.cv);
id= (TextView) itemView.findViewById(R.id.id);
name= (TextView) itemView.findViewById(R.id.name);
}
}
}
Do help me i want to get rid out of this problem thank you in advance
Hy guys!
I've got a problem. My app should display all routes in a listview. But there is something wrong with the arrayadapter. If i try my arrayadapter like this:
ArrayAdapter<DefineRoute> adapter = new ArrayAdapter<DefineRoute>(
this, android.R.layout.simple_list_item_1,verbindungen.getVerbindungen());
it works, but it only display the objectname of DefineRoute and i wanna display the output of the cursor.
Ithink i should try:
ArrayAdapter<String> adapter = new ArrayAdapter<String>(
this, android.R.layout.simple_list_item_1,verbindungen.getVerbindungen());
But here comes the error: Cannot resolve constructor ArrayAdapter
Here is my Acticity:
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated constructor stub
super.onCreate(savedInstanceState);
setContentView(R.layout.planausgabelayout);
//Aufruf der TextViews
TextView txtStart = (TextView)findViewById(R.id.txtAusgabeStart);
TextView txtZiel = (TextView)findViewById(R.id.txtAusgabeZiel);
TextView txtZeit = (TextView)findViewById(R.id.txtAusgabeZeit);
intent = getIntent();
txtStart.setText(intent.getStringExtra("StartHaltestelle"));
txtZiel.setText(intent.getStringExtra("ZielHaltestelle"));
txtZeit.setText(intent.getStringExtra("Zeit"));
getRoute();
}
public void getRoute() {
lvList = (ListView)findViewById(R.id.lvList);
Verbindungen verbindungen = new Verbindungen(this);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(
this, android.R.layout.simple_list_item_1,verbindungen.getVerbindungen());
lvList.setAdapter(adapter);
}
Here is my Activity Define Route:
public class DefineRoute {
private String abfahrtszeit;
private String ankunftszeit;
private String dauer;
private String umstieg;
public DefineRoute(String abfahrtszeit, String ankunftszeit, String dauer, String umstieg)
{
this.abfahrtszeit = getAbfahrtszeit();
this.ankunftszeit = getAnkunftszeit();
this.dauer = getDauer();
this.umstieg = getUmstieg();
}
public String getAbfahrtszeit() {
return abfahrtszeit;
}
public String getAnkunftszeit() {
return ankunftszeit;
}
public String getDauer() {
return dauer;
}
public String getUmstieg() {
return umstieg;
}
}
Here is my Activity Verbindungen:
public class Verbindungen {
SQLiteDatabase db;
LinkedList<DefineRoute> route;
DefineRoute[] routeArray;
Context context;
DatabaseHelper myDbHelper = null;
public Verbindungen(Context context) {
route = new LinkedList<DefineRoute>();
this.context = context;
myDbHelper = new DatabaseHelper(context);
}
public DefineRoute[] getVerbindungen() {
try {
myDbHelper.createDataBase();
} catch (IOException ioe) {
throw new Error("Unable to create database");
}
try {
myDbHelper.openDataBase();
}catch(SQLException sqle){
throw sqle;
}
db = myDbHelper.getReadableDatabase();
// Alle Daten der Datenbank abrufen mithilfe eines Cursors
Cursor cursor = db.rawQuery("SELECT strftime('%H:%M', f.abfahrt) AS Abfahrt," +
"strftime('%H:%M', f.ankunft) AS Ankunft," +
"strftime('%H:%M', strftime('%s',f.ankunft)- strftime('%s',f.abfahrt), 'unixepoch') AS Dauer," +
"r.name AS Route," +
"count(u.fahrt_id) AS Umstiege " +
"FROM scotty_fahrt f " +
"JOIN scotty_haltestelle start ON f.start_id = start.id " +
"JOIN scotty_haltestelle ziel ON f.ziel_id = ziel.id " +
"JOIN scotty_route r ON f.route_id = r.id " +
"LEFT OUTER JOIN scotty_umstiegsstelle u ON f.id = u.fahrt_id " +
"WHERE start.name = 'Linz/Donau Hbf (Busterminal)' " +
"AND ziel.name = 'Neufelden Busterminal (Schulzentrum)' " +
"GROUP BY u.fahrt_id",null);
cursor.moveToFirst();
int i=0;
while (cursor.moveToNext()){
//in this string we get the record for each row from the column "name"
i++;
}
routeArray = new DefineRoute[i];
cursor.moveToFirst();
int k =0;
while (cursor.moveToNext())
{
routeArray[k] = new DefineRoute(cursor.getString(0),cursor.getString(1),cursor.getString(2),
cursor.getString(3));
k++;
}
//here we close the cursor because we do not longer need it
//}
cursor.close();
myDbHelper.close();
return routeArray;
}
please help me.
Now i am creating a ArrayAdapter class where i define my ouput in the listview with:
public class RouteAdapter extends ArrayAdapter<DefineRoute>{
Activity context;
DefineRoute[] defineroute;
public RouteAdapter(Activity context, DefineRoute[] defineroute){
super(context, R.layout.layoutausgabe, defineroute);
this.defineroute = defineroute;
this.context = context;
}
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = context.getLayoutInflater();
View row = inflater.inflate(R.layout.layoutausgabe,null);
TextView txZeit = (TextView)row.findViewById(R.id.txZeit);
TextView txDauer = (TextView)row.findViewById(R.id.txDauer);
TextView txUmstieg = (TextView)row.findViewById(R.id.txUmstieg);
DefineRoute defineRoute = defineroute[position];
txZeit.setText(defineRoute.getAbfahrtszeit() + " - " + defineRoute.getAnkunftszeit());
txDauer.setText(defineRoute.getDauer());
txUmstieg.setText(defineRoute.getUmstieg());
return row;
}
}
How should i continue?
and what should my adapter look like?
Your ArrayAdapter<String> is type of String so pass String list to it's constructor instead of verbindungen.getVerbindungen() list of objects.
ArrarAdapter < T > is any type of class you can use
in your case ArrayAdapter so you need override toString method of DefineRoute class
in your case
#Override
public String toString() {
return ankunftszeit+" "+ankunftszeit;
//or what ever you want to displat
}
or there is other Solution is Create your Own adapter extending by BaseAdapter Class.