Save Data from RecyclerView into SQLite DataBase - android

I'm making an app that gets image , text, url from json url in recyclerview and display the text and image in cardview. and when the user will click on the item it will open new webview activity and pass the url to this activity . everything work fine . but now i want to make a favorite list. when user click on button on the recyclerview item it will save this item data into the SQLite Database . I did everything as in Tutorials but it's not working
when i click on favbtn it's saying Failed . it means the data isn't saved in the database.
please any idea where is my mistake , I'm stuck on this for 3 days and can't find answer
here is my code
RecyclerAdapter.java
public class RecyclerAdapter extends RecyclerView.Adapter<RecyclerAdapter.ViewHolder> {
private Context mContext;
private List<Model> modelList;
public RecyclerAdapter(Context context, List<Model> listData) {
this.modelList = listData;
this.mContext = context;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.row, parent, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
final Model model = modelList.get(position);
holder.title.setText(modelList.get(position).getTitle());
Picasso.get().load(modelList.get(position).getImage()).into(holder.imageView);
}
#Override
public int getItemCount() {
return modelList.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
TextView title;
ImageView imageView;
Button favBtn;
public ViewHolder(View itemView) {
super(itemView);
title = itemView.findViewById(R.id.Title);
imageView = itemView.findViewById(R.id.ImageView);
favBtn = itemView.findViewById(R.id.favBtn);
favBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
DatabaseHandler favDB = new DatabaseHandler(mContext);
int position = getAdapterPosition();
Model model = modelList.get(position);
favDB.insertIntoTheDataBase(model.getTitle(),
model.getImage().trim(),model.getUrl().trim());
}
});
itemView.setClickable(true);
mContext = itemView.getContext();
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String Url = modelList.get(getAdapterPosition()).getUrl();
Intent i = new Intent(mContext, WebViewActivity.class);
i.putExtra("url1", modelList.get(getAdapterPosition()).getUrl());
mContext.startActivity(i);
}
});
}
}
}
DataBaseHandler.java
public class DatabaseHandler extends SQLiteOpenHelper {
Context context;
private static final String DATABASE_NAME = "Library.db";
private static final int DATABASE_VERSION = 1;
private static final String TABLE_Demo = "Favorites";
private static final String KEY_ID = "id";
private static final String KEY_TITLE= "title";
private static final String KEY_IMAGE= "image";
private static final String KEY_URL= "url";
public DatabaseHandler(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
this.context = context;
}
#Override
public void onCreate(SQLiteDatabase db) {
String CREATE_DEMO_TABLE = "CREATE TABLE " + TABLE_Demo +
" (" + KEY_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
KEY_TITLE + " TEXT, " +
KEY_IMAGE + " TEXT, " +
KEY_URL + " TEXT);";
db.execSQL(CREATE_DEMO_TABLE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_Demo);
onCreate(db);
}
public void insertIntoTheDataBase(String title, String image, String url){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_TITLE, title);
values.put(KEY_IMAGE,image);
values.put(KEY_URL, url);
Long result = db.insert(TABLE_Demo , null, values);
if (result == -1){
Toast.makeText(context,"Failed", Toast.LENGTH_LONG).show();
}else {
Toast.makeText(context,"Added Successfully", Toast.LENGTH_LONG).show();
}
}
}
Model.java
public class Model {
String title, image, url ;
public Model() {
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getTitle() {
return title;
}
public String getImage() {
return image;
}
public void setTitle(String title) {
this.title = title;
}
public void setImage(String image) {
this.image = image;
}
}
HomeFragment.java
public class HomeFragment extends Fragment {
private final String Data = "https://medicalibrary.net/wp-content/uploads/Allergy.json";
private RecyclerView recyclerView;
private JsonArrayRequest jsonArrayRequest;
RequestQueue requestQueue;
private ArrayList<Model> modelList = new ArrayList<>();
private RecyclerAdapter recyclerAdapter;
public static HomeFragment newInstans() {
HomeFragment homeFragment = new HomeFragment();
return homeFragment;
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.home_fragment_acivity, container, false);
recyclerView = view.findViewById(R.id.recyclerview2);
recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
recyclerView.setHasFixedSize(true);
httpGet();
return view;
}
private void httpGet() {
requestQueue = Volley.newRequestQueue(getContext());
jsonArrayRequest = new JsonArrayRequest(Request.Method.GET, Data, null, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
for (int i = 0; i < response.length(); i++) {
DatabaseHandler db = new DatabaseHandler (getContext());
try {
JSONObject jsonObject = response.getJSONObject(i);
Model model = new Model();
model.setTitle(jsonObject.getString("title"));
model.setImage(jsonObject.getString("image"));
model.setUrl(jsonObject.getString("url"));
modelList.add(model);
recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
recyclerAdapter = new RecyclerAdapter(getContext(), modelList);
recyclerView.setAdapter(recyclerAdapter);
// context of your activity or fragment
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d("Tag", "onErrorResponse" + error.getMessage());
}
});
requestQueue.add(jsonArrayRequest);
}
}

Related

I am getting a nullpointer for my RecyclerView Possibly because of my context

I am writing this code in my RecyclerViewAdapter and I have a separate Java File from which I want to set an ItemOnClickListener and Context for my adapter class. However, they come out as null. This is the method from the Java File for the recyclerView.
public void update(){
userRef.get()
.addOnSuccessListener(new OnSuccessListener<QuerySnapshot>() {
#Override
public void onSuccess(QuerySnapshot queryDocumentSnapshots) {
String imageUrl;
String name;
String extra;
String ready;
String ingredients;
String id;
List<DocumentSnapshot> list = queryDocumentSnapshots.getDocuments();
for( int i = 0; i < list.size(); i++){
DocumentSnapshot documentSnapshot = list.get(i);
if(documentSnapshot.exists()){
Map<String, Object> favFood = documentSnapshot.getData();
name = favFood.get(KEY_NAME).toString();
imageUrl = favFood.get(KEY_URL).toString();
extra = favFood.get(KEY_XTRAINFO).toString();
ready = favFood.get(KEY_READY).toString();
Log.d("TAGG", ready);
ingredients = favFood.get(KEY_INGREDIENTS).toString();
id = favFood.get(KEY_ID).toString();
allFavoritedFoods.add(new FoodItem(imageUrl, name, ready, extra, ingredients, id, FirebaseAuth.getInstance().getCurrentUser().getUid()));
}
}
foodAdapter = new FoodAdapter(allFavoritedFoods, FavItem.this);
recyclerView.setAdapter(foodAdapter);
foodAdapter.setOnItemClickListener(FavItem.this);
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
}
});
}
This is for the relevant code from the Adapter Class:
public class FoodAdapter extends RecyclerView.Adapter<FoodAdapter.ViewHolder> {
private ArrayList<FoodItem> foodItems;
private Context context;
static String id;
private OnItemClickListener mListener;
public interface OnItemClickListener{
void onItemClick(int position);
}
public void setOnItemClickListener(OnItemClickListener listener){
mListener = listener;
}
#Override
public int getItemCount() {
return foodItems.size();
}
public class ViewHolder extends RecyclerView.ViewHolder{
public TextView name, readyTime, ingredients, extraInfo;
public ImageView picture;
Button favBtn;
FirebaseFirestore db = FirebaseFirestore.getInstance();
public static final String KEY_URL = "imageUrl", KEY_INGREDIENTS = "ingredients", KEY_READY = "ready";
public static final String KEY_NAME = "name";
public static final String KEY_XTRAINFO = "info";
public static final String KEY_ID = "id";
public static final String KEY_FAV = "favorited";
//public Button favBtn;
public ViewHolder(View itemView){
super(itemView);
name = itemView.findViewById(R.id.title);
picture = itemView.findViewById(R.id.thumbnail);
readyTime = itemView.findViewById(R.id.readyInMinutes);
ingredients = itemView.findViewById(R.id.ingredients);
extraInfo = itemView.findViewById(R.id.extraInfo);
itemView.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
if(mListener!=null){
int position = getAdapterPosition();
if(position != RecyclerView.NO_POSITION){
mListener.onItemClick(position);
}
}
}
});
favBtn = itemView.findViewById(R.id.favBtn);
favBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int position = getAdapterPosition();
FoodItem foodItem = foodItems.get(position);
Map<String, Object> favFood = new HashMap<>();
favFood.put(KEY_NAME, foodItem.getTitle());
favFood.put(KEY_URL, foodItem.getImageUrl());
favFood.put(KEY_ID, foodItem.getId());
favFood.put(KEY_INGREDIENTS, foodItem.getIngredients());
favFood.put(KEY_READY, foodItem.getReadyTime());
favFood.put(KEY_XTRAINFO, foodItem.getExtraInfo());
db.collection(FirebaseAuth.getInstance().getCurrentUser().getEmail()).document(id+"").set(favFood)
.addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
Toast.makeText(itemView.getContext(), "Added to Favorites", Toast.LENGTH_SHORT);
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(itemView.getContext(), "Deleted From Favorites", Toast.LENGTH_SHORT);
Log.d("Error in Storing", e.toString());
}
});
}
});
}
}
public FoodAdapter(ArrayList<FoodItem> foodItems, Context context){
this.foodItems = foodItems;
this.context = context;
}
For the MainActivity.java, this worked, but foodAdapter.setOnItemClickListener(MainActivity.this);. But it isn't working similarly to the other Java File.
For the context what would I put and what would I put for the onItemClickListener for the method from the other Java File?
If you are writing update() method inside a fragment, pass context as follows.
foodAdapter = new FoodAdapter(allFavoritedFoods, getActivity());
If you are writing update() method inside an activity, pass context as follows.(assume activity name is MainActivity)
foodAdapter = new FoodAdapter(allFavoritedFoods, MainActivity.this);

Read Data from SQLite Databse in Another Activity using ID

I have already Read Data from Sqlite database in recyclerview
But when user click next_button it fetch more data from same row using BANK_ID
In First Activity I have read some data from sqlite database in recyclerView And When user click next_button its fetch more data from sqlite database using same row I've already pass BANK_ID which is autoIncrement
Here is my code...
DataModel Class
public class DataModel {
public String BANK_ID;
public String id;
public String farmer_insure_name;
public String farmer_bank_hypo;
public String farmer_name;
public String village;
public String taluka;
public String district;
public String tagging_date;
public String tag_no;
public String animal_species;
public String animal_breed;
public String body_color;
public String shape_right;
public String shape_left;
public String tail_switch;
public String other_marks;
public String prag_status;
public String lactations;
public String milk_qty;
public String sum_insured;
public String tag_photo;
public String head_photo;
public String left_photo;
public String right_photo;
public String farmer_photo;
public String getBANK_ID() {
return BANK_ID;
}
public void setBANK_ID(String BANK_ID) {
this.BANK_ID = BANK_ID;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getFarmer_insure_name() {
return farmer_insure_name;
}
public void setFarmer_insure_name(String farmer_insure_name) {
this.farmer_insure_name = farmer_insure_name;
}
public String getFarmer_bank_hypo() {
return farmer_bank_hypo;
}
public void setFarmer_bank_hypo(String farmer_bank_hypo) {
this.farmer_bank_hypo = farmer_bank_hypo;
}
public String getFarmer_name() {
return farmer_name;
}
public void setFarmer_name(String farmer_name) {
this.farmer_name = farmer_name;
}
public String getVillage() {
return village;
}
public void setVillage(String village) {
this.village = village;
}
public String getTaluka() {
return taluka;
}
public void setTaluka(String taluka) {
this.taluka = taluka;
}
public String getDistrict() {
return district;
}
public void setDistrict(String district) {
this.district = district;
}
public String getTagging_date() {
return tagging_date;
}
public void setTagging_date(String tagging_date) {
this.tagging_date = tagging_date;
}
public String getTag_no() {
return tag_no;
}
public void setTag_no(String tag_no) {
this.tag_no = tag_no;
}
public String getAnimal_species() {
return animal_species;
}
public void setAnimal_species(String animal_species) {
this.animal_species = animal_species;
}
public String getAnimal_breed() {
return animal_breed;
}
public void setAnimal_breed(String animal_breed) {
this.animal_breed = animal_breed;
}
public String getBody_color() {
return body_color;
}
public void setBody_color(String body_color) {
this.body_color = body_color;
}
public String getShape_right() {
return shape_right;
}
public void setShape_right(String shape_right) {
this.shape_right = shape_right;
}
public String getShape_left() {
return shape_left;
}
public void setShape_left(String shape_left) {
this.shape_left = shape_left;
}
public String getTail_switch() {
return tail_switch;
}
public void setTail_switch(String tail_switch) {
this.tail_switch = tail_switch;
}
public String getOther_marks() {
return other_marks;
}
public void setOther_marks(String other_marks) {
this.other_marks = other_marks;
}
public String getPrag_status() {
return prag_status;
}
public void setPrag_status(String prag_status) {
this.prag_status = prag_status;
}
public String getLactations() {
return lactations;
}
public void setLactations(String lactations) {
this.lactations = lactations;
}
public String getMilk_qty() {
return milk_qty;
}
public void setMilk_qty(String milk_qty) {
this.milk_qty = milk_qty;
}
public String getSum_insured() {
return sum_insured;
}
public void setSum_insured(String sum_insured) {
this.sum_insured = sum_insured;
}
public String getTag_photo() {
return tag_photo;
}
public void setTag_photo(String tag_photo) {
this.tag_photo = tag_photo;
}
public String getHead_photo() {
return head_photo;
}
public void setHead_photo(String head_photo) {
this.head_photo = head_photo;
}
public String getLeft_photo() {
return left_photo;
}
public void setLeft_photo(String left_photo) {
this.left_photo = left_photo;
}
public String getRight_photo() {
return right_photo;
}
public void setRight_photo(String right_photo) {
this.right_photo = right_photo;
}
public String getFarmer_photo() {
return farmer_photo;
}
public void setFarmer_photo(String farmer_photo) {
this.farmer_photo = farmer_photo;
}
}
DatabaseHelper Class
public class DatabaseHelper extends SQLiteOpenHelper {
private DatabaseHelper mDbHelper;
private SQLiteDatabase mDb;
public static final String DATABASE_NAME = "SNVINSURANCE.db";
public static final String TABLE_NAME_IMAGES = "images_table";
private static final int DATABASE_VERSION = 1;
private static final String IMAGES_TABLE = "ImagesTable";
public static final String COLUMN_ID = "ID";
public static final String BANK_COLUMN = "BANK_NAME";
public static final String INSURED_COLUMN = "INSURED_NAME";
public static final String BNAKHYPO_COLUMN = "BANKHYPO_NAME";
public static final String COLUMN_STATUS = "status";
public static final String FARMERNAME_ID = "ID";
public static final String SNV_ID = "SNV";
public static final String FARMERNAME_COLUMN = "FARMER_NAME";
public static final String VILLAGE_COLUMN = "VILLAGE";
public static final String TALUKA_COLUMN = "TALUKA";
public static final String DISTRICT_COLUMN = "DISTRICT";
public static final String TAGGING_DATE_COLUMN = "TAGGING_DATE";
public static final String ANIMAL_ID = "ID";
public static final String TAG_COLUMN = "TAG";
public static final String ANIMAL_SPECIES_COLUMN = "ANIMAL_SPECIES";
public static final String ANIMAL_BREED_COLUMN = "ANIMAL_BREED";
public static final String ANIMAL_BODY_COLOR_COLUMN = "ANIMAL_BODY_COLOR";
public static final String ANIMAL_SHAPE_RIGHT_COLUMN = "ANIMAL_SHAPE_RIGHT";
public static final String ANIMAL_SHAPE_LEFT_COLUMN = "ANIMAL_SHAPE_LEFT";
public static final String ANIMAL_SWITCH_OF_TAIL_COLUMN = "ANIMAL_SWITCH_OF_TAIL";
public static final String AGE_COLUMN = "AGE";
public static final String ANIMAL_OTHER_MARKS_COLUMN = "ANIMAL_OTHER_MARKS";
public static final String PRAG_STATUS_COLUMN = "PRAG_STATUS";
public static final String NUMBER_OF_LACTATION_COLUMN = "NUMBER_OF_LACTATION";
public static final String CURRENT_MILK_COLUMN = "CURRENT_MILK";
public static final String SUM_INSURED_COLUMN = "SUM_INSURED";
public static final String TAG_IMAGE_COLUMN = "TAG_IMAGE";
public static final String HEAD_IMAGE_COLUMN = "HEAD_IMAGE";
public static final String LEFT_SIDE_IMAGE_COLUMN = "LEFT_SIDE_IMAGE";
public static final String RIGHT_SIDE_IMAGE_COLUMN = "RIGHT_SIDE_IMAGE";
public static final String TAIL_IMAGE_COLUMN = "TAIL_IMAGE";
public static final String IDPROOF_IMAGE_COLUMN = "IDPROOF_IMAGE";
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, 1);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("create table " + TABLE_NAME_IMAGES + "(BANK_ID INTEGER PRIMARY KEY AUTOINCREMENT,BANK_NAME TEXT,INSURED_NAME TEXT,BANKHYPO_NAME TEXT,FARMER_NAME TEXT,VILLAGE TEXT,TALUKA TEXT,DISTRICT TEXT,TAGGING_DATE DATE, TAG NUMBER,ANIMAL_SPECIES TEXT,ANIMAL_BREED TEXT,ANIMAL_BODY_COLOR TEXT,ANIMAL_SHAPE_RIGHT TEXT,ANIMAL_SHAPE_LEFT TEXT,ANIMAL_SWITCH_OF_TAIL TEXT,AGE NUMBER,ANIMAL_OTHER_MARKS TEXT,PRAG_STATUS TEXT,NUMBER_OF_LACTATION NUMBER,CURRENT_MILK NUMBER,SUM_INSURED NUMBER,TAG_IMAGE BLOB NOT NULL,HEAD_IMAGE BLOB NOT NULL,LEFT_SIDE_IMAGE BLOB NOT NULL,RIGHT_SIDE_IMAGE BLOB NOT NULL,TAIL_IMAGE BLOB NOT NULL,IDPROOF_IMAGE BLOB NOT NULL)");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME_IMAGES);
onCreate(db);
}
public boolean insertImage(String bank, String insurename, String bankhypo, String farmername, String village, String taluka, String district, String tagging_date, String tag, String animal_species, String animal_breeds, String animal_body_color, String shape_right, String shape_left, String tail, String age, String marks_other, String prag, String lactation, String current_milk, String sum, byte[] tag_image, byte[] head_image, byte[] left_image, byte[] right_image, byte[] tail_image, byte[] id_proof_image) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(BANK_COLUMN, bank);
contentValues.put(INSURED_COLUMN, insurename);
contentValues.put(BNAKHYPO_COLUMN, bankhypo);
contentValues.put(FARMERNAME_COLUMN, farmername);
contentValues.put(VILLAGE_COLUMN, village);
contentValues.put(TALUKA_COLUMN, taluka);
contentValues.put(DISTRICT_COLUMN, district);
contentValues.put(TAGGING_DATE_COLUMN, tagging_date);
contentValues.put(TAG_COLUMN, tag);
contentValues.put(ANIMAL_SPECIES_COLUMN, animal_species);
contentValues.put(ANIMAL_BREED_COLUMN, animal_breeds);
contentValues.put(ANIMAL_BODY_COLOR_COLUMN, animal_body_color);
contentValues.put(ANIMAL_SHAPE_RIGHT_COLUMN, shape_right);
contentValues.put(ANIMAL_SHAPE_LEFT_COLUMN, shape_left);
contentValues.put(ANIMAL_SWITCH_OF_TAIL_COLUMN, tail);
contentValues.put(AGE_COLUMN, age);
contentValues.put(ANIMAL_OTHER_MARKS_COLUMN, marks_other);
contentValues.put(PRAG_STATUS_COLUMN, prag);
contentValues.put(NUMBER_OF_LACTATION_COLUMN, lactation);
contentValues.put(CURRENT_MILK_COLUMN, current_milk);
contentValues.put(SUM_INSURED_COLUMN, sum);
contentValues.put(TAG_IMAGE_COLUMN, tag_image);
contentValues.put(HEAD_IMAGE_COLUMN, head_image);
contentValues.put(LEFT_SIDE_IMAGE_COLUMN, left_image);
contentValues.put(RIGHT_SIDE_IMAGE_COLUMN, right_image);
contentValues.put(TAIL_IMAGE_COLUMN, tail_image);
contentValues.put(IDPROOF_IMAGE_COLUMN, id_proof_image);
long result = db.insert(TABLE_NAME_IMAGES, null, contentValues);
if (result == -1)
return false;
else
return true;
}
public DatabaseHelper open() throws SQLException {
SQLiteDatabase db = this.getWritableDatabase();
return this;
}
public List<DataModel> getdata() {
// DataModel dataModel = new DataModel();
List<DataModel> data = new ArrayList<>();
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery("select BANK_ID,BANK_NAME,INSURED_NAME,BANKHYPO_NAME,FARMER_NAME,VILLAGE,TALUKA,DISTRICT,TAGGING_DATE from " + TABLE_NAME_IMAGES + " ;", null);
StringBuffer stringBuffer = new StringBuffer();
DataModel dataModel = null;
while (cursor.moveToNext()) {
dataModel = new DataModel();
String BANK_ID = cursor.getString(cursor.getColumnIndexOrThrow("BANK_ID"));
String name = cursor.getString(cursor.getColumnIndexOrThrow("BANK_NAME"));
String country = cursor.getString(cursor.getColumnIndexOrThrow("INSURED_NAME"));
String city = cursor.getString(cursor.getColumnIndexOrThrow("BANKHYPO_NAME"));
String FARMER_NAME = cursor.getString(cursor.getColumnIndexOrThrow("FARMER_NAME"));
String VILLAGE = cursor.getString(cursor.getColumnIndexOrThrow("VILLAGE"));
String TALUKA = cursor.getString(cursor.getColumnIndexOrThrow("TALUKA"));
String DISTRICT = cursor.getString(cursor.getColumnIndexOrThrow("DISTRICT"));
String TAGGING_DATE = cursor.getString(cursor.getColumnIndexOrThrow("TAGGING_DATE"));
dataModel.setBANK_ID(BANK_ID);
dataModel.setId(name);
dataModel.setFarmer_insure_name(city);
dataModel.setFarmer_bank_hypo(country);
dataModel.setFarmer_name(FARMER_NAME);
dataModel.setVillage(VILLAGE);
dataModel.setTaluka(TALUKA);
dataModel.setDistrict(DISTRICT);
dataModel.setTagging_date(TAGGING_DATE);
stringBuffer.append(dataModel);
// stringBuffer.append(dataModel);
data.add(dataModel);
}
for (DataModel mo : data) {
Log.e("Hellomo", "" + mo.getFarmer_insure_name());
}
//
return data;
}
}
First Activity Class
public class SyncAllActivity extends AppCompatActivity {
Cursor model = null;
Cursor mode = null;
MyCustomAdapter adapter = null;
Button show;
DatabaseHelper database;
private RecyclerView recyclerview;
RecycleAdapter recycler;
List<DataModel> datamodel;
private ProgressDialog pdialog;
Context context;
private RecyclerView.LayoutManager mLayoutManager;
private MyCustomAdapter myCustomAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.sync_all_activity);
context = this;
datamodel = new ArrayList<DataModel>();
recyclerview = findViewById(R.id.recycle);
database = new DatabaseHelper(SyncAllActivity.this);
datamodel = database.getdata();
recycler = new RecycleAdapter(datamodel);
Log.e("data", "" + datamodel);
LinearLayoutManager layoutManager = new LinearLayoutManager(context);
layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
recyclerview.setLayoutManager(layoutManager);
recyclerview.setHasFixedSize(true);
myCustomAdapter = new MyCustomAdapter(datamodel);
recyclerview.setAdapter(myCustomAdapter);
}
public class MyCustomAdapter extends RecyclerView.Adapter<MyCustomAdapter.MyViewHolder> {
List<DataModel> moviesList;
public class MyViewHolder extends RecyclerView.ViewHolder {
TextView bank_company, insured_name, bank_hypo;
CardView cardView;
MaterialRippleLayout next_button_main_activity;
public MyViewHolder(View view) {
super(view);
context = itemView.getContext();
bank_company = itemView.findViewById(R.id.tvInsuranceList);
insured_name = itemView.findViewById(R.id.tvInsuredName);
bank_hypo = itemView.findViewById(R.id.tvBankHypo);
cardView = itemView.findViewById(R.id.cardViewMain);
next_button_main_activity = itemView.findViewById(R.id.next_button_main_activity);
}
}
public MyCustomAdapter(List<DataModel> moviesList) {
this.moviesList = moviesList;
}
#Override
public MyCustomAdapter.MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.sam1
, parent, false);
return new MyCustomAdapter.MyViewHolder(itemView);
}
public void clear() {
int size = this.moviesList.size();
if (size > 0) {
for (int i = 0; i < size; i++) {
this.moviesList.remove(0);
}
this.notifyItemRangeRemoved(0, size);
}
}
#Override
public void onBindViewHolder(final MyCustomAdapter.MyViewHolder holder, final int position) {
final DataModel dataModel = moviesList.get(position);
holder.bank_company.setText(dataModel.getId());
holder.insured_name.setText(dataModel.getFarmer_insure_name());
holder.bank_hypo.setText(dataModel.getFarmer_bank_hypo());
holder.cardView.setVisibility(View.VISIBLE);
holder.next_button_main_activity.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent(context, SyncFarmerActivity.class);
intent.putExtra("BANK_ID", moviesList.get(position).getBANK_ID() + "");
Log.e("id", moviesList.get(position).getBANK_ID() + "");
startActivity(intent);
}
});
}
#Override
public int getItemCount() {
return moviesList.size();
}
}
}
Second Activity Class
public class SyncFarmerActivity extends AppCompatActivity {
Button show;
DatabaseHelper database;
private RecyclerView recyclerview;
RecycleAdapter recycler;
List<DataModel> datamodel;
String id;
Context context;
private RecyclerView.LayoutManager mLayoutManager;
private MyCustomAdapter myCustomAdapter;
DataModel dataModel;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sync_farmer);
context = this;
Intent i = getIntent();
id = i.getStringExtra("BANK_ID");
Log.e("BANK_ID", id + "");
datamodel = new ArrayList<DataModel>();
recyclerview = findViewById(R.id.recycle);
database = new DatabaseHelper(SyncFarmerActivity.this);
datamodel = database.getdata();
recycler = new RecycleAdapter(datamodel);
Log.e("HIteshdata", "" + datamodel);
LinearLayoutManager layoutManager = new LinearLayoutManager(context);
layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
recyclerview.setLayoutManager(layoutManager);
recyclerview.setHasFixedSize(true);
myCustomAdapter = new MyCustomAdapter(datamodel);
recyclerview.setAdapter(myCustomAdapter);
}
public class MyCustomAdapter extends RecyclerView.Adapter<MyCustomAdapter.MyViewHolder> {
List<DataModel> moviesList;
public class MyViewHolder extends RecyclerView.ViewHolder {
TextView tvFarmerName, tvCity, tvTaluka, farmer_name, tvDistrict, tvTaggingDate, district, tagging_date;
CardView cardView;
MaterialRippleLayout next_button_main_activity;
public MyViewHolder(View view) {
super(view);
context = itemView.getContext();
tvFarmerName = itemView.findViewById(R.id.tvFarmerName);
tvCity = itemView.findViewById(R.id.tvCity);
tvTaluka = itemView.findViewById(R.id.tvTaluka);
tvDistrict = itemView.findViewById(R.id.tvDistrict);
tvTaggingDate = itemView.findViewById(R.id.tvTaggingDate);
}
}
public MyCustomAdapter(List<DataModel> moviesList) {
this.moviesList = moviesList;
}
#Override
public MyCustomAdapter.MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.sam
, parent, false);
return new MyCustomAdapter.MyViewHolder(itemView);
}
public void clear() {
int size = this.moviesList.size();
if (size > 0) {
for (int i = 0; i < size; i++) {
this.moviesList.remove(0);
}
this.notifyItemRangeRemoved(0, size);
}
}
#Override
public void onBindViewHolder(MyCustomAdapter.MyViewHolder holder, final int position) {
DataModel dataModel = moviesList.get(position);
holder.tvFarmerName.setText(dataModel.getFarmer_name());
holder.tvCity.setText(dataModel.getVillage());
holder.tvTaluka.setText(dataModel.getTaluka());
holder.tvDistrict.setText(dataModel.getDistrict());
holder.tvTaggingDate.setText(dataModel.getTagging_date());
}
#Override
public int getItemCount() {
return moviesList.size();
}
}
}
Can anyone help me..
Thank You in advance.
You have to create another method in your Database class to select values from specific id that you are passing from first activity like:
DatabaseHelper Class
public List<DataModel> getSpecificData(String id) {
// DataModel dataModel = new DataModel();
List<DataModel> data = new ArrayList<>();
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery("select BANK_ID,BANK_NAME,INSURED_NAME,BANKHYPO_NAME,FARMER_NAME,VILLAGE,TALUKA,DISTRICT,TAGGING_DATE from " + TABLE_NAME_IMAGES + "WHERE BANK_ID = " + id + ";", null);
StringBuffer stringBuffer = new StringBuffer();
DataModel dataModel = null;
while (cursor.moveToNext()) {
//Rest of your code
return data;
}
And use this method in your second activity like
Intent i = getIntent();
id = i.getStringExtra("BANK_ID");
database = new DatabaseHelper(SyncFarmerActivity.this);
datamodel = database.getSpecificData(id);

how to store data fetch from retrofit to sqlite database

I have retrieve data from Server using Retrofit
and now I am trying to store with sqlite database.
But program not run get error in BaseApter class and MainFragment
My Model Class Post
in that class I set getter and setter
public class Post {
#SerializedName("id")
#Expose
private int id;
#SerializedName("name")
#Expose
private String name;
#SerializedName("age")
#Expose
private String age;
#SerializedName("city")
#Expose
private String city;
#SerializedName("mob")
#Expose
private String mob;
My interface
public interface ApiInterface {
#GET("fetch.php")
Call<List<Post>> getContacts();
}
Retrofit Client
public class RetrofitClient {
private static Retrofit retrofit = null;
public static Retrofit getClient(String baseUrl) {
Gson gson = new GsonBuilder()
.setLenient()
.create();
if (retrofit == null) {
retrofit = new Retrofit.Builder()
.baseUrl(baseUrl)
.addConverterFactory(GsonConverterFactory.create(gson))
.build();
}
return retrofit;
}
}
Database class where I want to store the data
public class DatabaseHelper extends SQLiteOpenHelper {
public static final String DATABASE_NAME = "ApointmentDb.db";
public static final String TABLE_NAME = "ApointList";
public static final String TAG_ID = "id";
public static final String TAG_NAME = "name";
public static final String TAG_AGE = "age";
public static final String TAG_CITY = "city";
public static final String TAG_MOB = "mob";
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, 1);
}
#Override
public void onCreate(SQLiteDatabase db) {
String createTable = "CREATE TABLE " + TABLE_NAME + "" +
"("
+ TAG_ID + " id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,"
+ TAG_NAME + " TEXT,"
+ TAG_AGE + " TEXT,"
+ TAG_CITY + " TEXT, "
+ TAG_MOB + " TEXT)";
db.execSQL(createTable);
}
#Override
public void onUpgrade(SQLiteDatabase db, int i, int i1) {
db.execSQL("DROP IF TABLE EXISTS" + TABLE_NAME);
}
public void addData(Post post) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(TAG_ID, post.getId());
contentValues.put(TAG_NAME, post.getName());
contentValues.put(TAG_AGE, post.getName());
contentValues.put(TAG_CITY, post.getName());
contentValues.put(TAG_MOB, post.getName());
db.insert(TABLE_NAME, null, contentValues);
db.close();
}
and Adapter class
public class ApointmentAdapter extends BaseAdapter {
Context mContext;
private List<Post> mContact;
public ApointmentAdapter(List<Post> mContact, Context mContext) {
this.mContact = mContact;
this.mContext = mContext;
}
public class ViewHolder {
public TextView tvId;
public TextView tvName;
public TextView tvAge;
public TextView tvCity;
public TextView tvMob;
}
#Override
public int getCount() {
return mContact.size();
}
#Override
public Object getItem(int position) {
return mContact.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
public void addPost(Post post) {
mContact.add(post);
notifyDataSetChanged();
}
#Override
public View getView(int position, View convertView, ViewGroup viewGroup) {
View vi = convertView;
ViewHolder holder;
if (convertView == null) {
LayoutInflater inflater;
inflater = (LayoutInflater) mContext.getSystemService( Context.LAYOUT_INFLATER_SERVICE );
vi = inflater.inflate(R.layout.status_item_layout, null);
holder = new ViewHolder();
holder.tvId = (TextView) vi.findViewById(R.id.tv_status_id);
holder.tvName = (TextView) vi.findViewById(R.id.tv_status_name);
holder.tvAge = (TextView) vi.findViewById(R.id.tv_status_age);
holder.tvCity = (TextView) vi.findViewById(R.id.tv_status_city);
holder.tvMob = (TextView) vi.findViewById(R.id.tv_status_mob);
vi.setTag(holder);
} else
holder = (ViewHolder) vi.getTag();
// now set your text view here like
holder.tvId.setText(String.valueOf(mContact.get(position).getId()));
holder.tvName.setText(mContact.get(position).getName());
holder.tvAge.setText(mContact.get(position).getAge());
holder.tvCity.setText(mContact.get(position).getCity());
holder.tvMob.setText(mContact.get(position).getMob());
// return your view
return vi;
}
}
And Last MainFragment Class
public class StatusFragment extends Fragment implements LoaderManager.LoaderCallbacks<Post> {
private ListView listView;
private List<Post> contacts;
private ApointmentAdapter adapter;
private ApiInterface apiInterface;
private SimpleCursorAdapter mAdapter;
private boolean firstTimeLoad = false;
LoaderManager mLoaderManager;
private DatabaseHelper myDb;
private final String TAG = SaveToDatabase.class.getSimpleName();
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup v,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootView = inflater.inflate(R.layout.fragment_status, v, false);
LinearLayout linearLayout = (LinearLayout) rootView.findViewById(R.id.ly_apointment_status);
listView = (ListView)rootView.findViewById(R.id.lv_apnt_status);
((ViewGroup)linearLayout.getParent()).removeView(linearLayout);
adapter = new ApointmentAdapter(contacts,getActivity());
listView.setAdapter(adapter);
apiInterface = APIClient.getApiClient().create(ApiInterface.class);
Call<List<Post>> call = apiInterface.getContacts();
call.enqueue(new Callback<List<Post>>() {
#Override
public void onResponse(Call<List<Post>> call, Response<List<Post>> response) {
if (response.isSuccessful()){
List<Post> contacts = response.body();
for (int i=0; i < contacts.size(); i++){
Post post = contacts.get(i);
SaveToDatabase task = new SaveToDatabase();
task.execute(post);
adapter.addPost(post);
}
}else {
}
}
#Override
public void onFailure(Call<List<Post>> call, Throwable t) {
Toast.makeText(getActivity(), "Error" + t.toString(), Toast.LENGTH_SHORT).show();
}
});
return linearLayout;
}
public class SaveToDatabase extends AsyncTask<Post, Void , Void>{
#Override
protected Void doInBackground(Post... params) {
Post postt = params[0];
try{
myDb.addData(postt);
}catch (Exception e){
Log.d(TAG, e.getMessage());
Toast.makeText(getActivity(), "Error" +e.getMessage(), Toast.LENGTH_SHORT).show();
}
return null;
}
the error in Adapter class in getcount method
#Override
public int getCount() {
return mContact.size();
}
and in Main Class
listView.setAdapter(adapter);
where did I do a mistake?
Logcat
FATAL EXCEPTION: main
Process: com.example.s2r1.appointment, PID: 6560
java.lang.NullPointerException
at com.example.s2r1.appointment.ApointmentAdapter.getCount(ApointmentAdapter.java:42)
at android.widget.ListView.setAdapter(ListView.java:480)
at com.example.s2r1.appointment.StatusFragment.onCreateView(StatusFragment.java:65)
at android.support.v4.app.Fragment.performCreateView(Fragment.java:2080)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1108)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1290)
at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:801)
at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1677)
at android.support.v4.app.FragmentManagerImpl$1.run(FragmentManager.java:536)
at android.os.Handler.handleCallback(Handler.java:733)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5241)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:818)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java)
at dalvik.system.NativeStart.main(Native Method)

How to insert data in SQLite and display it using RecyclerView

i made RecyclerView to display data from Mysql and it work good now i want to make a favourite button when i clicked on it save this item in a favourite and display it in new activity in RecyclerView
I think i should use Sqlite to save data in it then display in favourite activity but i don't know how i can make that please help me
I tried to make Sqlite
public class DB_Sqlit extends SQLiteOpenHelper {
public static final String BDname = "mdata.db";
public DB_Sqlit(Context context) {
super(context, BDname, null, 1);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("create table favorite ( id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, img TEXT, url TEXT, num TEXT, size TEXT)");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS favorite");
onCreate(db);
}
public Boolean Insert_to_favorite(String name, String img, String url, String num, String size) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put("name", name);
contentValues.put("img", img);
contentValues.put("url", url);
contentValues.put("num", num);
contentValues.put("size", size);
long result = db.insert("favorite", null, contentValues);
if (result == -1)
return false;
else
return true;
}
public ArrayList getAllList_Favorite() {
ArrayList<listitem_gib> arraylist = new ArrayList<listitem_gib>();
SQLiteDatabase db = this.getReadableDatabase();
Cursor rs = db.rawQuery("select * from favorite", null);
rs.moveToFirst();
while (!rs.isAfterLast()) {
String id = rs.getString(rs.getColumnIndex("id"));
String name = rs.getString(rs.getColumnIndex("name"));
String img = rs.getString(rs.getColumnIndex("img"));
String url = rs.getString(rs.getColumnIndex("url"));
String num = rs.getString(rs.getColumnIndex("num"));
String size = rs.getString(rs.getColumnIndex("size"));
arraylist.add(new listitem_gib());
rs.moveToNext();
}
return arraylist;
}
public int get_check_List_Favorite(String Title) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor rs = db.rawQuery("select * from favorite Where name like '"+ Title +"'", null);
rs.moveToFirst();
int count = rs.getCount();
return count;
}
public Integer Delete(String id) {
SQLiteDatabase db = this.getWritableDatabase();
return db.delete("favorite", "id = ?", new String[]{id});
}}
RecyclerView Activity
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_r_arabic);
GetDataAdapter1 = new ArrayList<>();
recyclerView = (RecyclerView) findViewById(R.id.recyclerView);
progressBar = (ProgressBar) findViewById(R.id.progress_bar);
recyclerView.setHasFixedSize(true);
recyclerViewlayoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(recyclerViewlayoutManager);
progress_layout = (LinearLayout) findViewById(R.id.progress_layout);
progress_layout.setVisibility(View.VISIBLE);
JSON_DATA_WEB_CALL();
}
public void JSON_DATA_WEB_CALL(){
Intent intent = getIntent();
story_type = intent.getStringExtra("story_type");
String GET_JSON_DATA_HTTP_URL = "http://grassyhat.com/android/" + story_type + ".php";
jsonArrayRequest = new JsonArrayRequest(GET_JSON_DATA_HTTP_URL,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
progress_layout.setVisibility(View.GONE);
JSON_PARSE_DATA_AFTER_WEBCALL(response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
requestQueue = Volley.newRequestQueue(this);
requestQueue.add(jsonArrayRequest);
}
public void JSON_PARSE_DATA_AFTER_WEBCALL(JSONArray array){
for(int i = 0; i<array.length(); i++) {
listitem_gib GetDataAdapter2 = new listitem_gib();
JSONObject json = null;
try {
json = array.getJSONObject(i);
GetDataAdapter2.setId(json.getString(id));
GetDataAdapter2.setName(json.getString(name));
GetDataAdapter2.seturl(json.getString(url));
GetDataAdapter2.setimg(json.getString(img));
GetDataAdapter2.setnum(json.getString(num));
GetDataAdapter2.setsize(json.getString(size));
} catch (JSONException e) {
e.printStackTrace();
}
GetDataAdapter1.add(GetDataAdapter2);
}
recyclerViewadapter = new RecyclerViewAdapter(GetDataAdapter1, this);
//RecyclerView needs a layout manager in order to display data so here we create one
StaggeredGridLayoutManager layoutManager = new StaggeredGridLayoutManager(3, StaggeredGridLayoutManager.VERTICAL);
//Here we set the layout manager and the adapter to the listview
recyclerView.setLayoutManager(layoutManager);
recyclerView.setAdapter(recyclerViewadapter);
}
RecyclerViewAdapter
public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.ViewHolder> {
Context context;
List<listitem_gib> getDataAdapter;
public RecyclerViewAdapter(List<listitem_gib> getDataAdapter, Context context){
super();
this.getDataAdapter = getDataAdapter;
this.context = context;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.cardview_layout, parent, false);
ViewHolder viewHolder = new ViewHolder(v,context,getDataAdapter);
return viewHolder;
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
listitem_gib getDataAdapter1 = getDataAdapter.get(position);
holder.name.setText(getDataAdapter1.getName());
holder.num.setText(getDataAdapter1.getnum());
Picasso.with(context).load("http://grassyhat.com/android/image/" + getDataAdapter1.getimg()).into(holder.img1);
}
#Override
public int getItemCount() {
return getDataAdapter.size();
}
class ViewHolder extends RecyclerView.ViewHolder
implements View.OnClickListener{
public TextView name;
public TextView num;
public ImageView img1;
Context context;
List<listitem_gib> getDataAdapter;
public ViewHolder(View itemView, Context context ,List<listitem_gib> getDataAdapter ) {
super(itemView);
itemView.setOnClickListener(this);
this.getDataAdapter = getDataAdapter;
this.context = context;
name = (TextView) itemView.findViewById(R.id.Main_Text) ;
num = (TextView) itemView.findViewById(R.id.Second_Text) ;
img1 = (ImageView) itemView.findViewById(R.id.img1) ;
}
#Override
public void onClick(View v) {
int position = getAdapterPosition();
listitem_gib getDataAdapter =this.getDataAdapter.get(position);
Intent intent = new Intent(this.context,Rewaya_info.class);
intent.putExtra("name",getDataAdapter.getName());
intent.putExtra("url",getDataAdapter.geturl());
intent.putExtra("img",getDataAdapter.getimg());
intent.putExtra("num",getDataAdapter.getnum());
intent.putExtra("size",getDataAdapter.getsize());
this.context.startActivity(intent);
}
}}
ListItem
public class listitem_gib {
String id;
String name;
String url;
String img;
String num;
String size;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getid() {
return id;
}
public void setId(String id1) {
this.id = id1;
}
public String geturl() {
return url;
}
public void seturl(String url1) {
this.url = url1;
}
public String getimg() {
return img;
}
public void setimg(String img1) {
this.img = img1;
}
public String getnum() {
return num;
}
public void setnum(String num1) {
this.num = num1;
}
public String getsize() {
return size;
}
public void setsize(String size1) {
this.size = size1;
}}
you need to use SQLite database to store fav items data offline
create one table containing all data fields by make a class extends SQLiteOpenHelper and override onCreate() to write your create table command in it, and you don't need to write anything in onUpdate() method in your case
in your Detail activity make a button for fav which will implement insert this item in the SQLite database
to view the data from SQLite in RecyclerView:
make an arraylist from your item type "class"
retrieve each item data from SQLite database using cursor
add item data in the arraylist and send it to the adapter of the RecyclerView
you can use this tutorial to build RecyclerView :
Arabic Version
or English Version

recyclerView doesn't show the 'real' data for my list items

I have implemented a recyclerView and a SQLite database to save/retrieve data for the recylerview, but the data I get on the recyclerView is not the data that should show. The recyclerView worked as it should without the SQLite db.
When the plus sign is clicked, a dialog will popup with editext fields, where the user can type the information:
Here is the DialogFragment class where the user shall write their information:
public class DialogAdd extends DialogFragment {
private Button okButton;
private EditText name, quantity, location, normalPrice, offerPrice;
private List<ShopListItem> shopListItem;
private Context context;
DatabaseHelper dbHelper;
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
dbHelper = new DatabaseHelper(getContext());
shopListItem = new ArrayList<>();
context = getActivity();
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
final View rootView = inflater.inflate(R.layout.add_productdialog,container, false);
getDialog().setCanceledOnTouchOutside(false);
getDialog().setTitle("Add to shoplist");
name = (EditText) rootView.findViewById(R.id.dialog_productname);
quantity = (EditText) rootView.findViewById(R.id.dialog_qantity);
location = (EditText) rootView.findViewById(R.id.dialog_location);
normalPrice = (EditText) rootView.findViewById(R.id.dialog_normalPrice);
offerPrice = (EditText) rootView.findViewById(R.id.dialog_offerPrice);
okButton = (Button) rootView.findViewById(R.id.dialog_okButton);
okButton.getBackground().setColorFilter(Color.parseColor("#2fbd4b"), PorterDuff.Mode.MULTIPLY);
okButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (name.getText().toString().isEmpty()) {
Toast.makeText(context, "You must add a name", Toast.LENGTH_LONG).show();
} else {
dbHelper.insertData(name.toString() ,quantity.toString(),location.toString(),normalPrice.toString(),offerPrice.toString());
getDialog().dismiss();
}
}
});
return rootView;
}
This is the mainActivity class where I create the recylerview, adapters and Database:
public class MainActivity extends AppCompatActivity{
private ImageButton addbutton;
private DialogAdd dialogAdd;
public static RecyclerView recyclerView;
private List<ShopListItem> shopListItems;
private SQLiteDatabase db;
private Cursor cursor;
private DatabaseHelper databaseHelper;
private ShoplistAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.shoppinglist_mainactivity);
databaseHelper = new DatabaseHelper(this);
addbutton = (ImageButton) findViewById(R.id.addbtn);
addbutton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dialogAdd = new DialogAdd();
dialogAdd.show(getSupportFragmentManager(), "addDialog");
}
});
//RecyclerView
recyclerView = (RecyclerView)findViewById(R.id.rv_shoppinglist);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(App.getAppContex());
linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
recyclerView.setLayoutManager(linearLayoutManager);
initializeData();
adapter = new ShoplistAdapter(shopListItems);
recyclerView.setAdapter(adapter);
}
private void initializeData(){
shopListItems = new ArrayList<>();
Cursor resultset = databaseHelper.getAllData();
if (resultset.moveToFirst()){
while(!resultset.isAfterLast()){
shopListItems.add(new ShopListItem(resultset.getString(1), resultset.getString(2), resultset.getString(3), resultset.getString(4), resultset.getString(5)));
resultset.moveToNext();
}
}
resultset.close();
shopListItems.add(new ShopListItem("Potato", "2 KG", "MALL", "7 kr", ""));
}
This class is where the database is defined:
public class DatabaseHelper extends SQLiteOpenHelper {
public static final String DATABASE_NAME ="dbshoplist.db";
public static final String TABLE_NAME ="product_table";
public static final String COL_ID = "ID";
public static final String COL_NAME ="NAME";
public static final String COL_QTY ="QUANTITY";
public static final String COL_LOCATION ="LOCATION";
public static final String COL_PRICE1 ="PRICE1";
public static final String COL_PRICE2 ="PRICE2";
/*
This constructor creates the database
*/
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, 1);
SQLiteDatabase db = this.getWritableDatabase();
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE " + TABLE_NAME + " (ID INTEGER PRIMARY KEY AUTOINCREMENT,NAME TEXT,QUANTITY TEXT,LOCATION TEXT,PRICE1 TEXT,PRICE2 TEXT)");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
onCreate(db);
}
public boolean insertData(String name, String qty, String location, String price1, String price2){
SQLiteDatabase db = this.getWritableDatabase();
// content value is a row, and we fill it with the put();
ContentValues contentValues = new ContentValues();
contentValues.put(COL_NAME, name);
contentValues.put(COL_QTY, qty);
contentValues.put(COL_LOCATION, location);
contentValues.put(COL_PRICE1, price1);
contentValues.put(COL_PRICE2, price2);
long result = db.insert(TABLE_NAME, null,contentValues);
if(result == -1) {
return false;
}else{
return true;
}
}
public Cursor getAllData(){
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursorResults = db.rawQuery("SELECT * FROM " + TABLE_NAME, null);
return cursorResults;
}
My recyclerView adapter class:
public class ShoplistAdapter extends RecyclerView.Adapter<ShoplistAdapter.ViewHolder>{
List<ShopListItem> shopListItems;
public ShoplistAdapter(List<ShopListItem> shopListItems) {
this.shopListItems = shopListItems;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
Context context = parent.getContext();
LayoutInflater inflater = LayoutInflater.from(context);
View shoplist_itemView = inflater.inflate(R.layout.shop_list_item, parent, false);
ViewHolder viewHolder = new ViewHolder(shoplist_itemView);
return viewHolder;
}
#Override
public void onBindViewHolder(final ViewHolder holder, final int position) {
holder.location.setText(shopListItems.get(position).location.toString());
holder.normalPrice.setText(shopListItems.get(position).normalprice.toString());
holder.offerPrice.setText(shopListItems.get(position).offerprice.toString());
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append(shopListItems.get(position).quantity + " " + shopListItems.get(position).name);
holder.productname.setText(stringBuilder);
if(!shopListItems.get(position).offerprice.toString().isEmpty()){
holder.normalPrice.setPaintFlags(holder.normalPrice.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG);
}
if(shopListItems.get(position).normalprice.isEmpty()){
holder.normalPrice.setVisibility(View.GONE);
}
holder.checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if(isChecked == true){
holder.productname.setPaintFlags(holder.productname.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG);
holder.productname.setTextColor(Color.parseColor("#40000000"));
}else{
holder.productname.setPaintFlags(0 | Paint.ANTI_ALIAS_FLAG);
holder.productname.setTextColor(Color.BLACK);
}
}
});
}
#Override
public int getItemCount() {
return shopListItems.size();
}
public static class ViewHolder extends RecyclerView.ViewHolder{
private CheckBox checkBox;
private TextView productname, quantity, location, normalPrice, offerPrice;
private ImageButton edit_icon, delete_icon;
public ViewHolder(View itemView) {
super(itemView);
productname = (TextView)itemView.findViewById(R.id.product_name);
location = (TextView)itemView.findViewById(R.id.product_location);
normalPrice = (TextView)itemView.findViewById(R.id.product_price);
offerPrice = (TextView)itemView.findViewById(R.id.product_offer_price);
edit_icon = (ImageButton)itemView.findViewById(R.id.editShopItem_Icon);
delete_icon = (ImageButton)itemView.findViewById(R.id.shopitem_delete_icon);
checkBox = (CheckBox) itemView.findViewById(R.id.bought_checkbox);
}
}
#Override
public void onAttachedToRecyclerView(RecyclerView recyclerView) {
super.onAttachedToRecyclerView(recyclerView);
}
This is happening because you're calling the toString() method of fields of the ShopListItem object: shopListItems.get(position).location.toString().
Instead, create getter methods for the fields of your ShopListItem class, e.g.
public getLocation() {
return location;
}
and just call these to get the data.

Categories

Resources