How to check if an item already exists in a Room Database? - android

I have this adapter with a button that dependent on if a object already exists in my Room Database or not will have a differente behavior when it´s clicked. Basically what I want to do is if the object exists I want to remove it. In case it doesn´t I want to add it to my database. I created this method in Dao and a Task to check the existence. Since the Task is asynchronous ,how can I do the verification?
My Adapter
public class RestaurantAdapter extends RecyclerView.Adapter<RestaurantAdapter.RestaurantViewHolder> {
private Context mContext;
private List<Restaurant_> mRestaurants;
private Activity act;
private FirebaseAuth mAuth;
private String currentUserId;
private View rView;
public RestaurantAdapter(Context context, List<Restaurant_> restaurants, Activity activity) {
mRestaurants = restaurants;
mContext = context;
act = activity;
}
#Override
public RestaurantViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
// Get layout inflater from context
Context context = parent.getContext();
LayoutInflater inflater = LayoutInflater.from(context);
// Inflate layout
rView = inflater.inflate(R.layout.item_restaurant, parent, false);
// Return a new holder instance
return new RestaurantViewHolder(rView);
}
#Override
public void onBindViewHolder(RestaurantViewHolder viewHolder, final int position) {
// Get the data model based on position
final Activity activity = act;
final Restaurant_ restaurant = mRestaurants.get(position);
mAuth = FirebaseAuth.getInstance();
currentUserId = mAuth.getCurrentUser().getUid();
final TextView name = viewHolder.nameTextView;
name.setText(restaurant.getName());
final TextView rating = viewHolder.ratingTextView;
rating.setText((restaurant.getUserRating().getAggregateRating()));
final TextView distance = viewHolder.distanceTextView;
distance.setText(String.valueOf(restaurant.getDistance()) + " Km");
final ImageButton addToWishlistButton = viewHolder.addToWishlistButton;
addToWishlistButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Wishlist wishlist = new Wishlist(currentUserId, restaurant.getId());
//if(alreadyExists){
//RemoveWLTask rlt=new RemoveWLTask(wishlist,activity);
//rlt.execute()
// }
// else{
AddWLTask wlt = new AddWLTask(wishlist, activity);
wlt.execute();
//}
}
});
final ImageButton addToFavoritesButton = viewHolder.addToFavoritesButton;
addToFavoritesButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
addToFavoritesButton.getBackground().setTint(activity.getResources().getColor(R.color.red));
addToFavorites();
}
});
viewHolder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
LiveFragment.getListener().onRestaurantClicked(restaurant.getId());
}
});
}
#Override
public int getItemCount() {
return mRestaurants.size();
}
public class RestaurantViewHolder extends RecyclerView.ViewHolder {
public TextView nameTextView;
public TextView ratingTextView;
public TextView distanceTextView;
public ImageButton addToWishlistButton;
public ImageButton addToFavoritesButton;
public RestaurantViewHolder(View itemView) {
super(itemView);
nameTextView = itemView.findViewById(R.id.restaurantName);
ratingTextView = itemView.findViewById(R.id.restaurantRating);
distanceTextView = itemView.findViewById(R.id.restaurantDistance);
addToWishlistButton = itemView.findViewById(R.id.button_wishlist);
addToFavoritesButton = itemView.findViewById(R.id.button_favorites);
}
}
}
My DAO
#Dao
public interface DAO {
#Insert
public void addToWishlist(Wishlist wishlist);
#Delete
public void deleteFromWishlist(Wishlist wishlist);
#Query("Select restaurantId From wishlist Where userId=:id")
public String[] loadWishlist(String id);
#Query("Select restaurantId From wishlist where userId=:userID AND restaurantId=:restaurantID")
public String[]checkExists(String userID, String restaurantID);
}
##My Task ##
public class CheckWLTask extends AsyncTask<Void, Void, Void> {
private DB db;
private Activity activity;
private String userId;
private String restaurantId;
private String [] response;
public CheckWLTask(Activity activity, String idUser, String idRestaurant) {
this.activity = activity;
this.userId = idUser;
this.restaurantId = idRestaurant;
db = Room.databaseBuilder(activity.getApplicationContext(), DB.class, "sample-db").build();
}
#Override
protected Void doInBackground(Void... voids) {
while (!isCancelled()) {
this.response=db.daoAcess().checkExists(userId,restaurantId);
break;
}
return null;
}
}
``

Related

How to retrieve just specific data in Recycler View using Firebase Database?

I have a problem with retrieving specific data from Firebase Realtime Database. My problem is that I want to display in RecyclerView just the materials that has the Course_ID (as you can see in the image below) equals to the Course_ID (see Course -> Teacher-Courses in Firebase). How can I accomplish that thing? I will attach the code used in the RecyclerView and the class that contains the model.
As a mention: 1.I have tried to add all the course id's from Firebase and store them to a List, but the app doesn't show anything and 2. In another class I have an Intent that sends me here and also send a extra String with Course_ID that I have accesed.
I am waiting for your responses. Thank you!
FileMaterial.class
public class FileMaterial {
private String Course_ID;
private String Denumire_material;
private String Locatie_material;
private String Teacher_ID;
public FileMaterial() {
}
public FileMaterial(String course_ID, String denumire_material, String locatie_material, String teacher_ID) {
Course_ID = course_ID;
Denumire_material = denumire_material;
Locatie_material = locatie_material;
Teacher_ID = teacher_ID;
}
public String getCourse_ID() {
return Course_ID;
}
public void setCourse_ID(String course_ID) {
Course_ID = course_ID;
}
public String getDenumire_material() {
return Denumire_material;
}
public void setDenumire_material(String denumire_material) {
Denumire_material = denumire_material;
}
public String getLocatie_material() {
return Locatie_material;
}
public void setLocatie_material(String locatie_material) {
Locatie_material = locatie_material;
}
public String getTeacher_ID() {
return Teacher_ID;
}
public void setTeacher_ID(String teacher_ID) {
Teacher_ID = teacher_ID;
}
CourseMaterial.class
public class CourseMaterial extends AppCompatActivity {
private RecyclerView recyclerView;
private DatabaseReference reference, userReference;
private FirebaseAuth mAuth;
FirebaseRecyclerOptions<FileMaterial> options;
FirebaseRecyclerAdapter<FileMaterial, CourseMaterial.FileViewHolder> adapter;
ImageView btnAddMaterial;
ImageView deleteMaterial;
StorageReference storageReference;
FirebaseStorage firebaseStorage;
String urlReference;
String value;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_course_material);
value = getIntent().getStringExtra("course id").toString();
mAuth = FirebaseAuth.getInstance();
reference = FirebaseDatabase.getInstance().getReference().child("Materials").child(mAuth.getCurrentUser().getUid());
recyclerView = findViewById(R.id.recyclerView_fileMaterials);
recyclerView.setLayoutManager(new LinearLayoutManager(getApplicationContext()));
btnAddMaterial = findViewById(R.id.addMaterials);
btnAddMaterial.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(CourseMaterial.this, UploadFile.class));
}
});
}
#Override
public void onStart() {
super.onStart();
options = new FirebaseRecyclerOptions.Builder<FileMaterial>().setQuery(reference, FileMaterial.class).build();
adapter = new FirebaseRecyclerAdapter<FileMaterial, FileViewHolder>(options) {
#Override
protected void onBindViewHolder(#NonNull final FileViewHolder fileViewHolder, int i, #NonNull final FileMaterial fileMaterial) {
fileViewHolder.denumire_material.setText(fileMaterial.getDenumire_material());
}
#NonNull
#Override
public FileViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.youtube_view,parent, false);
FileViewHolder fileViewHolder = new FileViewHolder(v);
return fileViewHolder;
}
};
adapter.startListening();
recyclerView.setAdapter(adapter);
}
public static class FileViewHolder extends RecyclerView.ViewHolder{
TextView denumire_material, dataMaterial;
ImageView deleteMaterial;
public FileViewHolder(#NonNull View itemView) {
super(itemView);
denumire_material = itemView.findViewById(R.id.txtDenMaterial);
deleteMaterial = itemView.findViewById(R.id.imgDeleteMaterial);
}
}
Maybe make a query and pass it to the options of the adapter:
#Override
public void onStart() {
super.onStart();
Query query = reference.orderByChild("Course_ID").equalTo(value);
options = new FirebaseRecyclerOptions.Builder<FileMaterial>().setQuery(query, FileMaterial.class).build();
.......
.......
.......

how to remove item from Recyclerview

friends...
In my project, I am creating a list of images from the server and showing in Recyclerview.
now I want to remove a particular item from the list when I click on the verify button.
I tried to hide holder.itemview but its see again when I scroll.
I just want to remove or hide that item which is verified once.
here is my code :
1) Main activity
public class MainActivity extends AppCompatActivity {
private static final String url = "www.mysite.com/api/api-id-list.php?action=imgs";
private ProgressDialog mDetailProgress;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layout_main_activity);
LoadRecyclerView();
}
private void LoadRecyclerView() {
mDetailProgress = new ProgressDialog(this);
mDetailProgress.setTitle("Loading images");
mDetailProgress.setMessage("Please Wait...");
mDetailProgress.setCanceledOnTouchOutside(false);
mDetailProgress.show();
final RecyclerView imgList = (RecyclerView) findViewById(R.id.imgList);
imgList.setLayoutManager(new LinearLayoutManager(this));
StringRequest request = new StringRequest(url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
GsonBuilder gsonBuilder = new GsonBuilder();
Gson gson = gsonBuilder.create();
Image[] images = gson.fromJson(response, Image[].class);
imgList.setAdapter(new ImageAdapter(MainActivity.this, images));
mDetailProgress.dismiss();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getBaseContext(), "Something went wrong..!", Toast.LENGTH_LONG);
}
});
RequestQueue queue = Volley.newRequestQueue(this);
queue.add(request);
}}
2) ImageAdapter
public class ImageAdapter extends RecyclerView.Adapter<ImageAdapter.ImageViewHolder> {
private ProgressDialog mDetailProgress;
private Context context;
private Image[] data;
Button btn_ban, btn_verify;
private View view;
public ImageAdapter (Context context, Image[] data) {
this.context = context;
this.data = data;
}
#NonNull
#Override
public ImageViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int i) {
LayoutInflater inflater = LayoutInflater.from(parent.getContext());
view = inflater.inflate(R.layout.single_item, parent, false);
return new ImageViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull final ImageViewHolder holder, final int position) {
final Image imagelist = data[position];
holder.userCode.setText(imagelist.getCode());
Glide.with(holder.userImage.getContext()).load(imagelist.getIdPhoto()).into(holder.userImage);
btn_verify.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
holder.itemView.setVisibility(View.GONE);
}
});
}
#Override
public int getItemCount() { return data.length; }
public class ImageViewHolder extends RecyclerView.ViewHolder {
TextView userCode;
ImageView userImage;
public ImageViewHolder(#NonNull View itemView) {
super(itemView);
userImage = (ImageView) itemView.findViewById(R.id.card_iv_img);
userCode = (TextView) itemView.findViewById(R.id.card_tv_code);
btn_ban = (Button) itemView.findViewById(R.id.btn_ban);
btn_verify = (Button) itemView.findViewById(R.id.btn_verify);
}
}}
3) Image.java
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class Image {
#SerializedName("per_ID")
#Expose
private String perID;
#SerializedName("code")
#Expose
private String code;
#SerializedName("first_nm")
#Expose
private String firstNm;
#SerializedName("last_nm")
#Expose
private String lastNm;
#SerializedName("photo_ID")
#Expose
private String photoID;
#SerializedName("id_photo")
#Expose
private String idPhoto;
public String getPerID() {
return perID;
}
public void setPerID(String perID) {
this.perID = perID;
}
public Image withPerID(String perID) {
this.perID = perID;
return this;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public Image withCode(String code) {
this.code = code;
return this;
}
public String getFirstNm() {
return firstNm;
}
public void setFirstNm(String firstNm) {
this.firstNm = firstNm;
}
public Image withFirstNm(String firstNm) {
this.firstNm = firstNm;
return this;
}
public String getLastNm() {
return lastNm;
}
public void setLastNm(String lastNm) {
this.lastNm = lastNm;
}
public Image withLastNm(String lastNm) {
this.lastNm = lastNm;
return this;
}
public String getPhotoID() {
return photoID;
}
public void setPhotoID(String photoID) {
this.photoID = photoID;
}
public Image withPhotoID(String photoID) {
this.photoID = photoID;
return this;
}
public String getIdPhoto() {
return idPhoto;
}
public void setIdPhoto(String idPhoto) {
this.idPhoto = idPhoto;
}
public Image withIdPhoto(String idPhoto) {
this.idPhoto = idPhoto;
return this;
}}
First make data not array, but List, so it's easy to remove item;
Secondly set listener for verify button inside ViewHolder and inside OnClick remove item and notify adapter.
btn_verify.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int position = getAdapterPosition();
data.remove(position);
notifyItemRemoved(position);
}
});
Note: Setting OnClickListener inside ViewHolder makes sure that only correct item is removed by using getAdapterPosition() to get correct position.
Position provided by onBindViewHolder might be invalid after new items are inserted.

add integer values selected by checkbox

TestListModel.class
public class TestListModel {
private String testlist_id;
private String test_price;
private String test_name;
private boolean isSelected;
public TestListModel(String testlist_id, String test_price, String test_name,boolean isSelected) {
this.testlist_id = testlist_id;
this.test_price = test_price;
this.test_name = test_name;
this.isSelected = isSelected;
}
public String getTestlist_id() {
return testlist_id;
}
public void setTestlist_id(String testlist_id) {
this.testlist_id = testlist_id;
}
public String getTest_price() {
return test_price;
}
public void setTest_price(String test_price) {
this.test_price = test_price;
}
public String getTest_name() {
return test_name;
}
public void setTest_name(String test_name) {
this.test_name = test_name;
}
public boolean isSelected() {
return isSelected;
}
public void setSelected(boolean isSelected) {
this.isSelected = isSelected;
}
}
JsonResponse.java
public class JSONResponse {
private TestListModel[] result;
public TestListModel[] getResult() {
return result;
}
public void setResult(TestListModel[] result) {
this.result = result;
}
}
HealthActivity.java
public class HealthServicesActivity extends AppCompatActivity implements View.OnClickListener {
/*
*Api call
* */
private RecyclerView recyclerView;
private ArrayList<TestListModel> data;
private RecyclerAdapter madapter;
private Button submitButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_health_services);
ButterKnife.bind(this);
sharePreferenceManager = new SharePreferenceManager<>(getApplicationContext());
submitButton=(Button) findViewById(R.id.submit_button);
showcenterid(sharePreferenceManager.getUserLoginData(LoginModel.class));
initViews();
submitButton.setOnClickListener(this);
/*
* On Click Listner
* */
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.submit_button:
int totalAmount = 0;
int totalPrice = 0;
String testName = "";
String testPrice="";
int count = 0;
List<TestListModel> stList = ((RecyclerAdapter) madapter)
.getTestList();
for (int i = 0; i < stList.size(); i++) {
TestListModel singleStudent = stList.get(i);
//AmountCartModel serialNumber = stList.get(i);
if (singleStudent.isSelected() == true) {
testName = testName + "\n" + singleStudent.getTest_name().toString();
testPrice = testPrice+"\n" + singleStudent.getTest_price().toString();
count++;
totalAmount = Integer.parseInt(stList.get(i).getTest_price());
totalPrice = totalPrice + totalAmount;
}
}
Toast.makeText(HealthServicesActivity.this,
"Selected Lists: \n" + testName+ "" + testPrice, Toast.LENGTH_LONG)
.show();
Intent in= new Intent(HealthServicesActivity.this, AmountCartActivity.class);
in.putExtra("test_name", testName);
in.putExtra("test_price", testPrice);
//in.putExtra("total_price",totalPrice);
in.putExtra("total_price", totalPrice);
in.putExtra("serialNumber", count);
startActivity(in);
finish();
break;
/** back Button Click
* */
case R.id.back_to_add_patient:
startActivity(new Intent(getApplicationContext(), PatientActivity.class));
finish();
break;
default:
break;
}
}
/** show center Id in action bar
* */
#Override
protected void onResume() {
super.onResume();
showcenterid(sharePreferenceManager.getUserLoginData(LoginModel.class));
}
private void showcenterid(LoginModel userLoginData) {
centerId.setText(userLoginData.getResult().getGenCenterId());
centerId.setText(userLoginData.getResult().getGenCenterId().toUpperCase());
deviceModeName.setText(userLoginData.getResult().getDeviceModeName());
}
private void initViews() {
recyclerView = (RecyclerView)findViewById(R.id.test_list_recycler_view);
recyclerView.setHasFixedSize(true);
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getApplicationContext());
recyclerView.setLayoutManager(layoutManager);
loadJSON();
}
private void loadJSON() {
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(" http://192.168.1.80/aoplnew/api/")
//
.baseUrl("https://earthquake.usgs.gov/fdsnws/event/1/query?")
.addConverterFactory(GsonConverterFactory.create())
.build();
ApiInterface request = retrofit.create(ApiInterface.class);
Call<JSONResponse> call = request.getTestLists();
call.enqueue(new Callback<JSONResponse>() {
#Override
public void onResponse(Call<JSONResponse> call, Response<JSONResponse> response) {
JSONResponse jsonResponse = response.body();
data = new ArrayList<>(Arrays.asList(jsonResponse.getResult()));
madapter = new RecyclerAdapter(data);
recyclerView.setAdapter(madapter);
}
#Override
public void onFailure(Call<JSONResponse> call, Throwable t) {
Log.d("Error",t.getMessage());
}
});
}
HealthRecyclerAdapter.java
public class RecyclerAdapter extends
RecyclerView.Adapter<RecyclerAdapter.ViewHolder> {
private ArrayList<TestListModel> android;
public RecyclerAdapter(ArrayList<TestListModel> android) {
this.android = android;
}
#Override
public RecyclerAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.test_list_row,parent,false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(RecyclerAdapter.ViewHolder holder, final int position) {
holder.test_name.setText(android.get(position).getTest_name());
holder.test_price.setText(android.get(position).getTest_price());
holder.chkSelected.setChecked(android.get(position).isSelected());
holder.chkSelected.setTag(android.get(position));
holder.chkSelected.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
CheckBox cb = (CheckBox) v;
TestListModel contact = (TestListModel) cb.getTag();
contact.setSelected(cb.isChecked());
android.get(position).setSelected(cb.isChecked());
Toast.makeText(
v.getContext(),
"Clicked on Checkbox: " + cb.getText() + " is " + cb.isChecked(), Toast.LENGTH_LONG).show();
}
});
}
#Override
public int getItemCount() {
return android.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
private TextView test_name;
private TextView test_price;
public CheckBox chkSelected;
public TestListModel testLists;
public ViewHolder(View itemView) {
super(itemView);
test_name = (TextView)itemView.findViewById(R.id.test_name);
test_price = (TextView)itemView.findViewById(R.id.price_name);
chkSelected = (CheckBox) itemView.findViewById(R.id.check_box);
}
}
// method to access in activity after updating selection
public List<TestListModel> getTestList() {
return android;
}
AmountCartModel.java
public class AmountCartModel {
private String testName;
private String testPrice;
private Integer serialNumber;
private Integer totalPrice;
public AmountCartModel() {
this.testName = testName;
this.testPrice = testPrice;
this.serialNumber = serialNumber;
this.totalPrice = totalPrice;
}
public String getTestName() {
return testName;
}
public void setTestName(String testName) {
this.testName = testName;
}
public String getTestPrice() {
return testPrice;
}
public void setTestPrice(String testPrice) {
this.testPrice = testPrice;
}
public Integer getSerialNumber() {
return serialNumber;
}
public void setSerialNumber(Integer serialNumber) {
this.serialNumber = serialNumber;
}
public Integer getTotalPrice() {
return totalPrice;
}
public void setTotalPrice(Integer totalPrice) {
this.totalPrice = totalPrice;
}
}
AmountCartActivity.java
public class AmountCartActivity extends AppCompatActivity implements View.OnClickListener {
#BindView(R.id.total_price)
TextView totalPriceDisplay;
SharePreferenceManager<LoginModel> sharePreferenceManager;
private RecyclerView recyclerView;
List<AmountCartModel> mydataList ;
private MyAdapter madapter;
Bundle extras ;
String testName="";
String testPrice="";
String totalPrice= "";
int counting = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_amount_cart);
ButterKnife.bind(this);
sharePreferenceManager = new SharePreferenceManager<>(getApplicationContext());
showcenterid(sharePreferenceManager.getUserLoginData(LoginModel.class));
mydataList = new ArrayList<>();
/*
* Getting Values From BUNDLE
* */
extras = getIntent().getExtras();
if (extras != null) {
testName = extras.getString("test_name");
testPrice = extras.getString("test_price");
totalPrice = String.valueOf(extras.getInt("total_price"));
counting = extras.getInt("serialNumber");
//Just add your data in list
AmountCartModel mydata = new AmountCartModel(); // object of Model Class
mydata.setTestName(testName );
mydata.setTestPrice(testPrice);
mydata.setTotalPrice(Integer.valueOf(totalPrice));
mydata.setSerialNumber(counting);
mydataList.add(mydata);
//totalPriceDisplay.setText(totalPrice);
}
madapter=new MyAdapter(mydataList);
madapter.setMyDataList(mydataList);
recyclerView = (RecyclerView)findViewById(R.id.recyler_amount_cart);
recyclerView.setHasFixedSize(true);
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getApplicationContext());
recyclerView.setLayoutManager(layoutManager);
recyclerView.setAdapter(madapter);
RecyclerAdapter.java //RecyclerAdapter for AmountCart
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder>
{
private List<AmountCartModel> context;
private List<AmountCartModel> myDataList;
public MyAdapter(List<AmountCartModel> context) {
this.context = context;
myDataList = new ArrayList<>();
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType)
{
// Replace with your layout
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.amount_cart_row, parent, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
// Set Your Data here to yout Layout Components..
// to get Amount
/* myDataList.get(position).getTestName();
myDataList.get(position).getTestPrice();*/
holder.testName.setText(myDataList.get(position).getTestName());
holder.testPrice.setText(myDataList.get(position).getTestPrice());
holder.textView2.setText(myDataList.get(position).getSerialNumber());
}
#Override
public int getItemCount() {
/*if (myDataList.size() != 0) {
// return Size of List if not empty!
return myDataList.size();
}
return 0;*/
return myDataList.size();
}
public void setMyDataList(List<AmountCartModel> myDataList) {
// getting list from Fragment.
this.myDataList = myDataList;
notifyDataSetChanged();
}
public class ViewHolder extends RecyclerView.ViewHolder {
TextView testName,testPrice,textView2;
public ViewHolder(View itemView) {
super(itemView);
// itemView.findViewById
testName=itemView.findViewById(R.id.test_name_one);
testPrice=itemView.findViewById(R.id.test_price);
textView2=itemView.findViewById(R.id.textView2);
}
}
}
#Override
public void onBackPressed() {
super.onBackPressed();
startActivity(new
Intent(AmountCartActivity.this,HealthServicesActivity.class));
finish();
}
}
This is my code.
Here I am taking HealthActivity and in this class by using recycler view I have displayed testList in recycler view. I am passing testList whichever I am selecting through checkbox to AmountCartActivity of recycler View, And, I am calculating total amount of the selected testList and I am getting the result and that result I am passing to the AmountCart Activity through bundle and I am getting correct result in bundle, but, when I am trying to display total amount in a textView its showing me nothing.
And, my second problem is,
I am trying to display serial number to to my AmountCartActivity of recycler view whichever I am selecting from previous HealthCartActivity using checkbox. And, I have implemented some code but I am not getting how to solve it. please help me.
For Issue#1
Data should be passed onto the Adapter through constructor. The issue could simply be adding another parameter to the constructor:
public MyAdapter(List<AmountCartModel> context, List<AmountCartModel> myDataList) {
this.context = context;
myDataList = this.myDataList;
}
Or,
To add selection support to a RecyclerView instance:
Determine which selection key type to use, then build a ItemKeyProvider.
Implement ItemDetailsLookup: it enables the selection library to access information about RecyclerView items given a MotionEvent.
Update item Views in RecyclerView to reflect that the user has selected or unselected it.
The selection library does not provide a default visual decoration for the selected items. You must provide this when you implement onBindViewHolder() like,
In onBindViewHolder(), call setActivated() (not setSelected()) on the View object with true or false (depending on if the item is selected).
Update the styling of the view to represent the activated status.
For Issue #2
Try using passing data through intents.
The easiest way to do this would be to pass the serial num to the activity in the Intent you're using to start the activity:
Intent intent = new Intent(getBaseContext(), HealthServicesActivity.class);
intent.putExtra("EXTRA_SERIAL_NUM", serialNum);
startActivity(intent);
Access that intent on next activity
String sessionId= getIntent().getStringExtra("EXTRA_SERIAL_NUM");

how to update database using room persistance library and livedata

I am trying to update my database using Room persistence Library and Livedata. I am very new to java, so, with the manual and various tutorial, I have setup the DAO, entity etc. But I am still struggling with how to actually add the data.
This is my database defination:
#Entity
public class PlaceSaved {
#PrimaryKey(autoGenerate = true)
private int id;
private String place;
private String lati;
private String longi;
public PlaceSaved(String place, String lati, String longi) {
this.place = place;
this.lati = lati;
this.longi = longi;
}
public String getPlace() {
return place;
}
public void setPlace(String place) {
this.place = place;
}
public String getLongi() {
return longi;
}
public void setLongi(String longi) {
this.longi = longi;
}
public String getLati() {
return lati;
}
public void setLati(String lati) {
this.lati = lati;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
}
DAO
#Dao
public interface DatabaseInterface {
#Query("SELECT * FROM placesaved")
LiveData<List<PlaceSaved>> getAllItems();
#Insert
void insertAll(PlaceSaved... placeSaveds);
#Delete
void delete(PlaceSaved... placeSaveds);
#Update
void update(PlaceSaved... placeSaveds);
}
Adapter
public class PlacesAdapter extends RecyclerView.Adapter<PlacesAdapter.RecyclerViewHolder>{
private List<PlaceSaved> items;
private View.OnClickListener ClickListener;
public PlacesAdapter(List<PlaceSaved> items){//}, View.OnClickListener ClickListener) {
this.items = items;
//this.ClickListener = ClickListener;
}
#Override
public RecyclerViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
return new RecyclerViewHolder(LayoutInflater.from(parent.getContext())
.inflate(R.layout.places_list_item, parent, false));
}
#Override
public void onBindViewHolder(final RecyclerViewHolder holder, int position) {
PlaceSaved placeSaved = items.get(position);
holder.itemTextView.setText(placeSaved.getPlace());
holder.nameTextView.setText(placeSaved.getLati());
holder.dateTextView.setText(placeSaved.getLongi());
/* holder.dateTextView.setText(borrowModel.getBorrowDate().toLocaleString().substring(0, 11));
holder.itemView.setTag(borrowModel);
holder.itemView.setOnLongClickListener(longClickListener);*/
}
#Override
public int getItemCount() {
return items.size();
}
public void addItems(List<PlaceSaved> items) {
this.items = items;
notifyDataSetChanged();
}
static class RecyclerViewHolder extends RecyclerView.ViewHolder {
private TextView itemTextView;
private TextView nameTextView;
private TextView dateTextView;
RecyclerViewHolder(View view) {
super(view);
itemTextView = (TextView) view.findViewById(R.id.firstLine);
nameTextView = (TextView) view.findViewById(R.id.secondLine);
dateTextView = (TextView) view.findViewById(R.id.longitude);
}
}
}
and the ViewModel
public class PlacesViewModel extends AndroidViewModel {
private final LiveData<List<PlaceSaved>> PlacedatabaseList;
private PlaceDatabase appDatabase;
public PlacesViewModel(Application application) {
super(application);
appDatabase = PlaceDatabase.getDatabase(this.getApplication());
PlacedatabaseList = appDatabase.PlacedatabaseInterface().getAllItems();
}
public LiveData<List<PlaceSaved>> getPlaceList() {
return PlacedatabaseList;
}
public void deleteItem(PlaceSaved placeSaved) {
new deleteAsyncTask(appDatabase).execute(placeSaved);
}
private static class deleteAsyncTask extends AsyncTask<PlaceSaved, Void, Void> {
private PlaceDatabase db;
deleteAsyncTask(PlaceDatabase appDatabase) {
db = appDatabase;
}
#Override
protected Void doInBackground(final PlaceSaved... params) {
db.PlacedatabaseInterface().delete(params[0]);
return null;
}
}
}
Now, I am trying to add an item to database with OnClick of a fab as:
public class PlacesActivity extends AppCompatActivity {
private PlacesViewModel viewModel;
private PlacesAdapter placesAdapter;
private RecyclerView recyclerView;
FloatingActionButton fab, fab1, fab2, fab3;
LinearLayout fabLayout1, fabLayout2, fabLayout3;
boolean isFABOpen = false;
View fabBGLayout;
PlaceDatabase db;
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.places_layout);
viewModel = ViewModelProviders.of(this).get(PlacesViewModel.class);
Runnable r =new Runnable() {
#Override
public void run() {
recyclerView = findViewById(R.id.my_recycler_view);
placesAdapter = new PlacesAdapter(new ArrayList<PlaceSaved>());//, this);
recyclerView.setLayoutManager(new LinearLayoutManager(getApplication()));
recyclerView.setAdapter(placesAdapter);
}
};
Thread newThread = new Thread(r);
newThread.start();
fab1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Dialog
/*
Add location manually
*/
AlertDialog.Builder placeLLDialog = new AlertDialog.Builder(PlacesActivity.this);
LayoutInflater inflater = getLayoutInflater();
final View view = inflater.inflate(R.layout.place_add_dialog, null);
placeLLDialog.setView(view);
final EditText todo = view.findViewById(R.id.placeN);
final EditText time = view.findViewById(R.id.placell);
final EditText longi = view.findViewById(R.id.placell2);
placeLLDialog.setTitle("Add Place with Latitude and Longitude")
.setPositiveButton("Add", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
if (!todo.getText().toString().equals("") &&
!time.getText().toString().equals("") &&
!longi.getText().toString().equals("")) {
Snackbar.make(view, "Running", Snackbar.LENGTH_LONG).show();
/* HERE I AM TRYING TO ADD THE DATA, WHICH IS NOT WORKING
final PlaceSaved placeSaved = new PlaceSaved(todo.getText().toString(),
time.getText().toString(), longi.getText().toString());
AsyncTask.execute(new Runnable() {
#Override
public void run() {
db.databaseInterface().insertAll(placeSaved);
items = db.databaseInterface().getAllItems();
runOnUiThread(new Runnable() {
#Override
public void run() {
adapter = new PlacesAdapter(items, db, null);
adapter.notifyDataSetChanged();
recyclerView.setAdapter(adapter);
closeFABMenu();
}
});
}
});*/
}
}
})
.setNegativeButton("Cancel", null);
AlertDialog alertDialog = placeLLDialog.create();
alertDialog.show();
alertDialog.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE | WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM);
alertDialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
}
});
since I am very new to java, I can't find out how to add the data to the database, which is inside fab1.setOnClickListner.
I will be grateful if someone kindly helps.
UPDATE
I forgot to add database itself, here it is:
#Database(entities = {PlaceSaved.class},version = 1)
public abstract class PlaceDatabase extends RoomDatabase {
private static PlaceDatabase INSTANCE;
public static PlaceDatabase getDatabase(Context context){
if (INSTANCE == null){
INSTANCE = Room.databaseBuilder(context.getApplicationContext(), PlaceDatabase.class,
"places_db").build();
}
return INSTANCE;
}
public abstract DatabaseInterface PlacedatabaseInterface();
Create Class AddBorrowViewModel
public class AddBorrowViewModel extends AndroidViewModel
{
private PlaceDatabase appDatabase;
public AddBorrowViewModel(#NonNull Application application) {
super(application);
appDatabase = PlaceDatabase.getDatabase(this.getApplication());
}
public void addBorrow(PlaceSaved placedSaved)
{
new addAsyncTask(appDatabase).execute(placedSaved);
}
private class addAsyncTask extends AsyncTask<PlaceSaved , Void, Void>
{
private PlaceDatabase appDatabase_;
addAsyncTask(PlaceDatabase appDatabase)
{
appDatabase_ = appDatabase;
}
#Override
protected Void doInBackground(PlaceSaved... placedSaved) {
appDatabase_.itemAndPersonModel().addBorrow(placedSaved[0]);
return null;
}
}
}
add this variable in your PlacesActivity
private AddBorrowViewModel addBorrowViewModel;
in OnCreate add this
addBorrowViewModel = ViewModelProviders.of(this).get(AddBorrowViewModel.class);
in onClickListener Of alertDilaog after snackbar
addBorrowViewModel.addBorrow(new PlaceSaved(
todo.getText().toString(),
time.getText().toString(), longi.getText().toString()
));
In your PlaceDatabase add
public abstract Dao itemAndPersonModel();

How to fetch data from another classes via Adapter in Android

Here I'm trying to make a quiz application without using databases (requirement). Each question has 4 options.
I had made a class for Questions. Now, in the activity in which I want to show my data, I'm unable to get method to fetch the data from the QuestionModelClass.
I had made 2D Array but it gets more complicated to get it. Is there any way to bind 3 of the classes (QuestionModelClass, Adapter class, and Activity class)?
public class QuestionsModelClass {
private String sQuestion;
private String sRightAnswer;
private List<String> sOptions;
QuestionsModelClass(){
sQuestion = null;
sRightAnswer = null;
sOptions = null;
}
public QuestionsModelClass(String sQuestion, String sRightAnswer, List<String> sOptions) {
this.sQuestion = sQuestion;
this.sRightAnswer = sRightAnswer;
this.sOptions = sOptions;
}
public String getsQuestion() {
return sQuestion;
}
public void setsQuestion(String sQuestion) {
this.sQuestion = sQuestion;
}
public String getsRightAnswer() {
return sRightAnswer;
}
public void setsRightAnswer(String sRightAnswer) {
this.sRightAnswer = sRightAnswer;
}
public List<String> getsOptions() {
return sOptions;
}
public void setsOptions(List<String> sOptions) {
this.sOptions = sOptions;
}
}
And my Adapter Class
public class QuizAdapter extends BaseAdapter {
private Context context;
private List<QuestionsModelClass> questionClassList;
private String[][] options;
private LayoutInflater inflater;
private QuizAdapter(Context c, List<QuestionsModelClass> l){
this.context= c;
this.questionClassList = l;
inflater = LayoutInflater.from(context);
}
#Override
public int getCount() {
return questionClassList.size();
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
convertView = inflater.inflate(R.layout.questionpattern, parent,false);
QuestionsModelClass questions = questionClassList.get(position);
TextView quesText= convertView.findViewById(R.id.questionTextView);
RadioButton radioButtonA = convertView.findViewById(R.id.optionA);
RadioButton radioButtonB = convertView.findViewById(R.id.optionB);
RadioButton radioButtonC = convertView.findViewById(R.id.optionC);
RadioButton radioButtonD = convertView.findViewById(R.id.optionD);
return convertView;
}
And this is the Activity class in which I am trying to implement all the functions
public class QuizActivity extends Activity {
final Context context= this;
private List<QuestionsModelClass> classObject;
Button okayButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_quiz);
String[] question= new String[]{"Q1. ABDE", "Q2. ADDASD"};
String[][] op;
String[] right = new String[]{"abc","def"};
classObject = new ArrayList<>();
op= new String[][]{
{"a1", "2", "3", "4"},
{"b1","b2","b3","b4"}};
final Dialog dialog = new Dialog(context);
dialog.setContentView(R.layout.customdialoguebox);
dialog.show();
okayButton = (Button) dialog.findViewById(R.id.okayButton);
okayButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(QuizActivity.this,"Good Luck!", Toast.LENGTH_SHORT).show();
dialog.cancel();
}
});
}

Categories

Resources