how to connect ViewModel in Fragment again after callback from viewholder - android

I made a callback by interface from a viewholder to the Fragment that has created the recyclerviewadapter with that viewholder inside.
Now I'm having trouble to connect to the viewmodel (of that fragment) with:
ViewModelProviders.of(getActivity()).get(ViewModelClass.class);
because of a null pointer exception :(
I can’t catch up to the activity again after that callback from the viewholder…
How would you solve that problem?
code:
recyclerviewadapter & viewholder:
public class BoxRecyclerViewAdapter extends RecyclerView.Adapter {
public String TAG = BoxRecyclerViewAdapter.class.getSimpleName();
Context context;
private List<Car> carList;
private CallbackBox callbackBox;
// boxType: 1 = cars | 2 = damage
private int boxType = 0;
// empty constructor
BoxRecyclerViewAdapter(){
}
// constuctor to create car boxes
public BoxRecyclerViewAdapter boxRecyclerViewAdapterCar(Context _context, List<Car> _tempList) {
this.carList = _tempList;
this.context = _context;
// hide buttons
this.boxType = 1;
return this;
}
// constuctor to create damage boxes
public BoxRecyclerViewAdapter boxRecyclerViewAdapterDamage(Context _context, List<Car> _tempList) {
this.carList = _tempList;
this.context = _context;
// show buttons
this.boxType = 2;
return this;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
/*
if ( callbackBox == null ){
Log.d(TAG, "mike: in BoxRecycler - callback = null " );
} else {
Log.d(TAG, "mike: in BoxRecycler - callback = NOT NULL " + callbackBox.toString() );
}
*/
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.box_layout, parent, false);
return new ViewHolder(view, this.callbackBox);
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
Car UploadInfo = carList.get(position);
holder.lb_title.setText(UploadInfo.getManuf());
holder.lb1.setText(UploadInfo.getModell());
holder.lb2.setText(UploadInfo.getIdentno());
holder.lb3.setText(UploadInfo.getYear());
}
#Override
public int getItemCount() {
return carList.size();
}
// register callback regarding the box listener with the ViewHolder Method
public void registerCallBackBoxListener( CallbackBox _callbackBox ){
//Log.d(TAG, "mike: callback register - complete");
this.callbackBox = _callbackBox;
}
// ******************* class ViewHolder *********************
class ViewHolder extends RecyclerView.ViewHolder {
private Context context;
private CallbackBox callbackBox;
private TextView lb_title;
private TextView lb1;
private TextView lb2;
private TextView lb3;
private TextView lb1_desc;
private TextView lb2_desc;
private TextView lb3_desc;
private Button bt_accept;
private Button bt_reject;
private ImageButton ibt_menu_edit;
private ImageButton ibt_menu_del;
private LinearLayout layout_box_buttons;
private ViewHolder(final View itemView, CallbackBox _callbackBox) {
super(itemView);
this.callbackBox = _callbackBox;
this.context = itemView.getContext();
lb_title = (TextView) itemView.findViewById(R.id.lb_title);
lb1 = (TextView) itemView.findViewById(R.id.lb1);
lb2 = (TextView) itemView.findViewById(R.id.lb2);
lb3 = (TextView) itemView.findViewById(R.id.lb3);
lb1_desc = (TextView) itemView.findViewById(R.id.lb1_desc);
lb2_desc = (TextView) itemView.findViewById(R.id.lb2_desc);
lb3_desc = (TextView) itemView.findViewById(R.id.lb3_desc);
bt_accept = (Button) itemView.findViewById(R.id.bt_accept);
bt_reject = (Button) itemView.findViewById(R.id.bt_reject);
ibt_menu_edit = (ImageButton) itemView.findViewById(R.id.ibt_menu_edit);
ibt_menu_del = (ImageButton) itemView.findViewById(R.id.ibt_menu_del);
layout_box_buttons = (LinearLayout) itemView.findViewById(R.id.layout_box_buttons);
// configure box layout
switch (boxType) {
// car
case 1:
// hide the layout with the buttons
layout_box_buttons.setVisibility( View.GONE );
lb1_desc.setText(R.string.txt_car_modell);
lb2_desc.setText(R.string.txt_car_identno);
lb3_desc.setText(R.string.txt_car_year);
break;
// damage
case 2:
layout_box_buttons.setVisibility( View.VISIBLE );
break;
}
// ******************** Listeners ****************
// start edit fragment
ibt_menu_edit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Toast.makeText(context, "menu button edit clicked", Toast.LENGTH_SHORT).show();
//Log.d(TAG, "mike: in edit onClick Listener - toString: " + callbackBox.toString() );
callbackBox.onCarEdit( lb2.getText().toString() );
}
});
// start delete (path to identNo)
ibt_menu_del.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Toast.makeText(context, "menu button del clicked", Toast.LENGTH_SHORT).show();
callbackBox.onCarDelete( lb2.getText().toString() );
}
});
// onClickListeners - Buttons
// start accept
bt_accept.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(context, "accept button clicked", Toast.LENGTH_SHORT).show();
}
});
// sharing reject
bt_reject.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(context, "reject button clicked", Toast.LENGTH_SHORT).show();
}
});
}
}
}
Fragment & callback:
public class FragmentCarDetailRequest extends Fragment implements CallbackBox{
public String TAG = FragmentCarDetailRequest.class.getSimpleName();
public ViewModelClass viewModelClass;
// Creating RecyclerView & adapter
RecyclerView recyclerView;
RecyclerView.Adapter adapter;
// Creating Progress dialog
ProgressDialog progressDialog;
// Creating List of Events class
List<Car> carList = new ArrayList<>();
private String userUid;
public static FragmentCarDetailRequest newInstance() {
return new FragmentCarDetailRequest();
}
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container,
#Nullable Bundle savedInstanceState) {
// Defines the xml file for the fragment
return inflater.inflate(R.layout.car_recyclerview, container, false);
}
#Override
public void onViewCreated(final View view, Bundle savedInstanceState) {
// Setup any handles to view objects here
this.viewModelClass = ViewModelProviders.of(getActivity()).get(ViewModelClass.class);
userUid = viewModelClass.getCurrentUser().getUid();
// Assign id to RecyclerView.
recyclerView = (RecyclerView) view.findViewById(R.id.car_recyclerView);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
// Assign activity this to progress dialog.
progressDialog = new ProgressDialog(getContext());
progressDialog.setMessage("Daten werden geladen");
progressDialog.show();
Log.d(TAG, "mike: starting livedata request ");
LiveData<DataSnapshot> liveData = viewModelClass.getDataSnapshotLiveData("cars", userUid );
liveData.observe(this, new Observer<DataSnapshot>() {
#Override
public void onChanged(#Nullable DataSnapshot dataSnapshot) {
if (dataSnapshot != null ){
carList.clear();
// retrieve the server content to add it to the list
for (DataSnapshot postSnapshot : dataSnapshot.getChildren() ) {
Car car = postSnapshot.getValue(Car.class);
carList.add(car);
}
BoxRecyclerViewAdapter boxRecyclerViewAdapter = new BoxRecyclerViewAdapter();
// register callbacks & RecyclerViewAdapter
CallbackBox callbackBox = new FragmentCarDetailRequest();
boxRecyclerViewAdapter.registerCallBackBoxListener( callbackBox );
adapter = boxRecyclerViewAdapter.boxRecyclerViewAdapterCar( getActivity().getApplicationContext(), carList );
recyclerView.setAdapter(adapter);
progressDialog.dismiss();
}
}
});
}
#Override
public void onCarDelete(String _identNo) {
Log.d(TAG, "mike: got callback to delete car..." + viewModelClass.getCurrentUser().getUid());
}
}
--------- beginning of crash
08-03 16:05:49.623 E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.wendtmichael.app2repair, PID: 6833
java.lang.NullPointerException: Attempt to invoke virtual method 'com.google.firebase.auth.FirebaseUser com.wendtmichael.app2repair.ViewModelClass.getCurrentUser()' on a null object reference
at com.wendtmichael.app2repair.FragmentCarDetailRequest.onCarDelete(FragmentCarDetailRequest.java:173)
at com.wendtmichael.app2repair.BoxRecyclerViewAdapter$ViewHolder$2.onClick(BoxRecyclerViewAdapter.java:193)
at android.view.View.performClick(View.java:5264)
at android.view.View$PerformClick.run(View.java:21297)
at android.os.Handler.handleCallback(Handler.java:743)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:150)
at android.app.ActivityThread.main(ActivityThread.java:5546)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:794)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:684)

Related

How to maintain checkbox state after clicking on previous button by using rest api call

Model 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 boolean setSelected(boolean isSelected) {
this.isSelected = isSelected;
return isSelected;
}
}
Recycler Adapter Class
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;
}
}
HealthActivity
public class HealthServicesActivity extends AppCompatActivity implements View.OnClickListener {
SharePreferenceManager<LoginModel> sharePreferenceManager;
/*
*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);
}
/*
* On Click Listner
* */
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.submit_button:
String serialNo="";
int serialNum=1;
String testListId = "";
int totalPrice = 0;
String testName = "";
String testPrice="";
List<TestListModel> stList = ((RecyclerAdapter) madapter)
.getTestList();
for (int i = 0; i < stList.size(); i++) {
TestListModel singleStudent = stList.get(i);
if (singleStudent.isSelected() == true) {
testListId = testListId+ "," + singleStudent.getTestlist_id().toString();
testName = testName + "\n" + "\n" + singleStudent.getTest_name().toString();
testPrice= testPrice+"\n" + "\n" + singleStudent.getTest_price().toString();
serialNo=serialNo + "\n" + "\n"+ Integer.parseInt(String.valueOf(serialNum));
serialNum++;
totalPrice= totalPrice+ Integer.parseInt(stList.get(i).getTest_price());
Intent in= new Intent(HealthServicesActivity.this, AmountCartActivity.class);
in.putExtra("test_id",testListId);
in.putExtra("test_name", testName);
in.putExtra("test_price", testPrice);
in.putExtra("total_price",totalPrice);
in.putExtra("serial_number",serialNo);
in.putExtra("patient_id",patientID);
startActivity(in);
}
else
Toasty.error(getApplicationContext(), "Please Select Test Lists", Toast.LENGTH_SHORT, true).show();
}
break;
/* Toast.makeText(HealthServicesActivity.this,
"Selected Lists: \n" + testName+""+testPrice, Toast.LENGTH_LONG)
.show();*/
/** back Button Click
* */
case R.id.back_to_add_patient:
startActivity(new Intent(getApplicationContext(), PatientActivity.class));
finish();
break;
default:
break;
}
}
/*
* Api Call For Displaying Test Lists
* */
private void loadJSON() {
String centerID=(sharePreferenceManager.getUserLoginData(LoginModel.class).getResult().getCenterId());
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("http://192.168.1.80/aoplnew/api/users/gettestlist/"+centerID);
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);
Toast.makeText(HealthServicesActivity.this, "APi Call Back", Toast.LENGTH_SHORT).show();
}
#Override
public void onFailure(Call<JSONResponse> call, Throwable t) {
Log.d("Error",t.getMessage());
}
});
}
#Override
public void onBackPressed() {
super.onBackPressed();
startActivity(new Intent(getApplicationContext(), PatientActivity.class));
finish();
}
}
AmountCartActivity
public class AmountCartActivity extends AppCompatActivity implements View.OnClickListener , PaymentResultListener {
SharePreferenceManager<LoginModel> sharePreferenceManager;
/*
*Setting Recycler View
* */
private RecyclerView recyclerView;
List<AmountCartModel> mydataList ;
private MyAdapter madapter;
/*
* Getting Bundle Values
* */
Bundle extras ;
String testId="";
String testName="";
String testPrice="";
String totalPrice="";
String serialNumber="";
private Button backButton;
/*
* Api Call For DashBoard
* */
String st;
Api webService = ServiceGenerator.getApi();
ProgressDialog progressDialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_amount_cart);
ButterKnife.bind(this);
progressDialog = new ProgressDialog(AmountCartActivity.this);
progressDialog.setMessage("Please Wait...");
progressDialog.setCanceledOnTouchOutside(false);
backButton=(Button) findViewById(R.id.back_button);
showcenterid(sharePreferenceManager.getUserLoginData(LoginModel.class));
backButton.setOnClickListener(this);
gettingValues();
}
#Override
public void onClick(View v) {
switch (v.getId()) {
/*
* back Button Click
* */
case R.id.back_button:
startActivity(new Intent(getApplicationContext(), HealthServicesActivity.class));
//finish();
break;
default:
break;
}
}
/*
* Getting Bundle Values and Setting Recycler View
* */
private void gettingValues() {
mydataList = new ArrayList<>();
/*
* Getting Values From BUNDLE
* */
bundle = getIntent().getExtras();
if (bundle != null) {
testId=bundle.getString("test_id");
testName = bundle.getString("test_name");
testPrice = bundle.getString("test_price");
totalPrice= String.valueOf(bundle.getInt("total_price"));
serialNumber=bundle.getString("serial_number");
//Just add your data in list
AmountCartModel mydata = new AmountCartModel(); // object of Model Class
mydata.setTestId(testId);
mydata.setTestName(testName );
mydata.setTestPrice(testPrice);
mydata.setSerialNumber(serialNumber);
mydataList.add(mydata);
totalPriceDisplay.setText("Total Amount : "+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);
}
Recycler Adapter for AmountCart
/*
* Recycler Adapter
*/
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);
}
}
}
How to maintain the checkbox state across the activities. I am displaying checkbox using recycler view in rest api call. I am selecting checkboxes from HealthActivity and clicking on submit button then the whole list is displaying in AmountCartActivity but when I m clicking on back button then i m not getting those selected checkboxes. And when I add or remove any checkbox then it should give the result as per selection only. How to maintain the state of the selected checkboxes?
In your AmountCartActivity when you listen for back button clicks you do this:
#Override
public void onClick(View v) {
switch (v.getId()) {
/*
* back Button Click
* */
case R.id.back_button:
startActivity(new Intent(getApplicationContext(), HealthServicesActivity.class));
//finish();
break;
default:
break;
}
}
You are opening a brand new HealthServicesActivity and you don't persist the data anywhere. (When you open a new HealthServicesActivity it does not know anything about your old list). So I think what you aim to do is finishing the AmountCartActivity and resuming the previous HealthServicesActivity like this:
#Override
public void onClick(View v) {
switch (v.getId()) {
/*
* back Button Click
* */
case R.id.back_button:
finish(); //JUST FINISH THE ACTIVITY AND RETURN TO THE PREVIOUS ACTIVITY
break;
default:
break;
}
}
EDIT: (added item click listener logic)
As you will be using the same HealthServiceActivity every time you submit and go back, I think you should implement an interface to keep your checkbox states updated. Make below changes in your respective methods (Please see my comments)
RecylerAdapter:
public class RecyclerAdapter extends RecyclerView.Adapter<RecyclerAdapter.ViewHolder> {
private ArrayList<TestListModel> android;
private OnItemClickListener onItemClickListener; //ADD THIS GLOBAL FIELD
/** THIS METHOD IS TO BIND YOUR NEW ITEM CLICK LISTENER **/
public void setOnItemClickListener(OnItemClickListener onItemClickListener)
{
this.onItemClickListener = onItemClickListener;
}
#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());
//YOU DON'T HAVE TO DEAL WITH TAGS, JUST USE BELOW CODE TO SET YOUR
// ITEM CLICK LISTENER TO EACH CHECKBOX
holder.chkSelected.setOnClickListener(v ->
onItemClickListener.onClickItem(position);
}
// THIS METHOD WILL SWITCH YOUR SELECT STATES AND UPDATE ITEMS ACCORDINGLY
public void updateCheckboxState(int position){
TestListModel listItem = android.get(position);
listItem.setSelected(!listItem.isSelected());
notifyDataSetChanged();
}
// ADD THIS INTERFACE
public interface OnItemClickListener {
void onClickItem(int position);
}
}
HealthServicesActivity:
//DON'T FORGET TO IMPLEMENT RecylcerAdapter.OnItemClickListener
public class HealthServicesActivity extends AppCompatActivity implements View.OnClickListener, RecyclerAdapter.OnItemClickListener {
/*
* Api Call For Displaying Test Lists
* */
private void loadJSON() {
{ ... }
#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);
madapter.setOnItemClickListener(this); // SET YOUR LISTENER HERE
recyclerView.setAdapter(madapter);
Toast.makeText(HealthServicesActivity.this, "APi Call Back", Toast.LENGTH_SHORT).show();
}
// UPDATE CHECKBOX STATES WHEN AN ITEM IS CLICKED
#Override
public void onClickItem(int position) {
madapter.updateCheckboxState(position);
}
}

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");

RecyclerView notifyDatasetChanged not working

I have a RecyclerView inside a Fragment within Activity. I need to refresh my RecyclerView from Activity. I added a method inside Fragment which called notifyDatasetChanged to refresh RecyclerView. But notifyDatasetChanged didn't work.
Here is my Fragment.
public class CategoryFragment extends Fragment{
private RecyclerView recyclerView;
private EventsAdapter adapter;
static Context context = null;
private List<Category> categories;
private List<Item> allItems = new ArrayList();
private ReminderDatabase dbHandler;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if(!checkDatabase()){
copyDatabase();
}
context = getActivity();
dbHandler = new ReminderDatabase(context);
fillAllItems();
}
public void fillAllItems(){
categories = dbHandler.getAllCategory();
for(int i=0;i<categories.size();i++){
Category category = categories.get(i);
Item categoryItem = new Item(category.getTitle(),category.getColor(),Category.CATEGORY_TYPE);
allItems.add(categoryItem);
List<Event> events = dbHandler.getEventsByCategory(category.getTitle());
for(int j=0;j<events.size();j++){
Event e = events.get(j);
Item eventItem = new Item(e.getId(),e.getTitle(),e.getDescription(),e.getPlace(),e.getCategory(),e.getTime(),e.getDate(),categoryItem.getColor(),e.isShow(),Event.EVENT_TYPE);
allItems.add(eventItem);
}
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.category_fragment, container, false);
recyclerView = (RecyclerView) v.findViewById(R.id.recyclerView);
adapter = new EventsAdapter(getContext(),allItems);
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
recyclerView.setAdapter(adapter);
return v;
}
public boolean checkDatabase(){
String path = "/data/data/com.example.materialdesign.reminder/databases/";
String filename = "Remind";
File file = new File(path+filename);
Log.d("Database","File exists -> "+file.exists());
return file.exists();
}
public void copyDatabase(){
String path = "/data/data/com.example.materialdesign.reminder/databases/Remind";
ReminderDatabase dbHandler = new ReminderDatabase(getContext());
dbHandler.getWritableDatabase();
InputStream fin;
OutputStream fout;
byte[] bytes = new byte[1024];
try {
fin = getActivity().getAssets().open("Remind");
fout = new FileOutputStream(path);
int length=0;
while((length = fin.read(bytes))>0){
fout.write(bytes,0,length);
}
fout.flush();
fout.close();
fin.close();
Log.d("Database","successfully copied database");
} catch (FileNotFoundException e) {
e.printStackTrace();
Log.d("Database","-Error" +e.getMessage());
} catch (IOException e) {
e.printStackTrace();
Log.d("Database","-Error" +e.getMessage());
}
}
#Override
public void onResume() {
super.onResume();
allItems.clear();
Log.d("TAG","onresume");
fillAllItems();
adapter.notifyDataSetChanged();
}
public void refresh(){
Log.d("c",allItems.size()+"");
allItems.clear();
fillAllItems();
Log.d("c",allItems.size()+"");
adapter.notifyDataSetChanged();
}
}
I called refresh method from MainActivity.
#Override
public void onInserted() {
fragment.refresh();
}
My Adapter is here.
public class EventsAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder>{
private Context context;
private List<Item> allItems = new ArrayList();
private HideOrShowListener hideOrShowListener;
public static final int EVENT_TYPE = 1;
public static final int CATEGORY_TYPE = 0;
private int lastPosition;
private boolean flag = false;
public EventsAdapter(Context context,List<Item> allItems){
this.context = context;
hideOrShowListener =(HideOrShowListener) context;
this.allItems = allItems;
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view;
switch (viewType){
case CATEGORY_TYPE:
view = LayoutInflater.from(context).inflate(R.layout.category_item,parent,false);
return new CategoryViewHolder(view);
case EVENT_TYPE:
view = LayoutInflater.from(context).inflate(R.layout.events_item,parent,false);
return new EventViewHolder(view);
}
return null;
}
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
final Item item = allItems.get(position);
switch (item.getType()){
case CATEGORY_TYPE:
((CategoryViewHolder)holder).tvCategoryTitle.setText(item.getTitle());
((GradientDrawable)(((CategoryViewHolder)holder).categoryColorIcon).getBackground()).setColor(Color.parseColor(item.getColor()));
((CategoryViewHolder)holder).imgAddEvent.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
hideOrShowListener.setHideOrShow(item,false);
}
});
break;
case EVENT_TYPE:
String[] time = item.getTime().trim().split(":");
int hour = Integer.parseInt(time[0]);
((EventViewHolder)holder).tvEventName.setText(item.getTitle());
((EventViewHolder)holder).tvTime.setText(hour<12?hour+" : "+time[1] +" am" : hour-12+" : "+time[1] +" pm" );
((EventViewHolder)holder).tvPlace.setText(item.getPlace());
if(item.getDescription().length()==0) {
item.setDescription("No Detail");
}
((EventViewHolder)holder).tvDescription.setText(item.getDescription());
if(item.isShow()){
((EventViewHolder)holder).descriptionLayout.animate().alpha(1).setDuration(200).setInterpolator(new AccelerateInterpolator()).start();
((EventViewHolder)holder).descriptionLayout.setVisibility(View.VISIBLE);
((EventViewHolder)holder).descriptionLayout.setSelected(true);
((EventViewHolder)holder).tvEdit.setVisibility(View.VISIBLE);
((EventViewHolder)holder).eventContainer.setSelected(true);
}else{
((EventViewHolder)holder).descriptionLayout.setVisibility(View.GONE);
((EventViewHolder)holder).descriptionLayout.animate().alpha(0).setDuration(500).start();
((EventViewHolder)holder).descriptionLayout.setSelected(false);
((EventViewHolder)holder).eventContainer.setSelected(false);
((EventViewHolder)holder).tvEdit.setVisibility(View.INVISIBLE);
}
((EventViewHolder)holder).tvEdit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
hideOrShowListener.setHideOrShow(item,true);
}
});
break;
}
}
#Override
public int getItemCount() {
Log.d("c",allItems.size()+"");
return allItems.size();
}
#Override
public int getItemViewType(int position) {
if(allItems!=null){
return allItems.get(position).getType();
}
return 0;
}
public class CategoryViewHolder extends RecyclerView.ViewHolder{
private TextView tvCategoryTitle;
private View categoryColorIcon;
private ImageView imgAddEvent;
public CategoryViewHolder(View itemView) {
super(itemView);
tvCategoryTitle = (TextView) itemView.findViewById(R.id.tvCategoryTitle);
categoryColorIcon = itemView.findViewById(R.id.categoryColorIcon);
imgAddEvent = (ImageView) itemView.findViewById(R.id.addEvent);
}
}
public class EventViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
private LinearLayout descriptionLayout;
private RelativeLayout eventContainer;
private TextView tvEventName,tvTime,tvPlace,tvDescription,tvEdit;
public EventViewHolder(View itemView) {
super(itemView);
descriptionLayout = (LinearLayout) itemView.findViewById(R.id.descriptionLayout);
eventContainer = (RelativeLayout) itemView.findViewById(R.id.eventContainer);
tvEventName = (TextView) itemView.findViewById(R.id.tvEventName);
tvTime = (TextView) itemView.findViewById(R.id.tvTime);
tvPlace = (TextView) itemView.findViewById(R.id.tvPlace);
tvDescription = (TextView) itemView.findViewById(R.id.tvDescription);
tvEdit = (TextView) itemView.findViewById(R.id.tvEdit);
eventContainer.setOnClickListener(this);
}
#Override
public void onClick(View v) {
if(flag){
allItems.get(lastPosition).setShow(false);
}
allItems.get(getAdapterPosition()).setShow(true);
flag = true;
lastPosition = getAdapterPosition();
notifyDataSetChanged();
}
}
public interface HideOrShowListener{
public void setHideOrShow(Item item , boolean isEdit);
}
}
But when I click home button and reenter my application, my RecyclerView refresh. It means that notifyDatasetChanged in onResume method works. But in my refresh method, it doesn't work. How can I do this?
Are you sure this method is being called :
#Override
public void onInserted() {
fragment.refresh();
}
Make sure that you've a correct instance of the fragment. Or you can simply user interface with the refresh() method and implement it in the fragment.

ViewPager with programmatically created recyclerView lists in it

I am having some trouble with my app, I am trying to develop a list app that you have the option to add new "Goals" to as well as new lists so that you can categorize goals to a list like the list object title can be "Eat healthy" and then you'll have goals inside like "Eat more vegetables", etc. So in order to do this I have set up a ViewPagerHost class that grabs all the List objects from a SQLite database and initializes a factory developed "List fragment" that handles all the logic of adding a goal, editing and deleting, etc. I believe I've gotten this to work correctly because everything on the database side seems to work fine, and then the other classes are just supposed to display and manipulate that information. But everything on the display side seems to be going wrong. I have each view in the recyclerview display a star next to any goal marked as "important" or "life changing" but it displays the star wherever it wants. Also the list does not load until I've click on something.
public class ViewPagerHost extends Activity_Logger {
private static final String ARG_TITLE = "title";
private ViewPager mViewPager;
private ArrayList<Fragment> mFragmentList;
private ArrayList<GoalList> goalList;
private ArrayList<Goal> goalArrayList;
Database_Controller controller;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view_pager_host);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
MobileAds.initialize(getApplicationContext(), "ad-String");
AdView adView = (AdView) findViewById(R.id.ad);
AdRequest adRequest = new AdRequest.Builder().build();
adView.loadAd(adRequest);
setSupportActionBar(toolbar);
toolbar.setTitle("Ambition");
FragmentManager fragmentManager = getSupportFragmentManager();
controller = Database_Controller.get(getApplicationContext());
goalList = controller.getAllLists();
goalArrayList = controller.getAllGoals();
mViewPager = (ViewPager)findViewById(R.id.view_fragments);
if(goalList.get(0) == null){
GoalList listOne = new GoalList();
listOne.setTitle("DEFAULT");
controller.insertList(listOne);
for(int i =0; i< goalArrayList.size(); i++){
goalArrayList.get(i).setWhich_List(listOne.getTitle());
controller.updateGoal(goalArrayList.get(i));
}
}
mFragmentList = getFragmentList(goalList);
ViewPagerAdapter adapter = new ViewPagerAdapter(fragmentManager, mFragmentList);
if(adapter == null){
}else{
mViewPager.setAdapter(adapter);
}
}
public ArrayList<Fragment> getFragmentList(ArrayList<GoalList> list){
mFragmentList = new ArrayList<>();
Bundle bundle = new Bundle();
for(int i = 0; i< list.size(); i++){
List_Fragment list_fragment = new List_Fragment();
bundle.putString(ARG_TITLE, goalList.get(i).getTitle());
list_fragment.setArguments(bundle);
mFragmentList.add(list_fragment);
}
return mFragmentList;
}
}
Here is my ViewPagerHost class that creates the factory list.
public class List_Fragment extends Fragment {
private RecyclerView mRecyclerView;
private static final String ARG_TITLE = "title";
private static final String ARG_GOALNAME ="Goal";
private static final String ARG_IMPORTANT = "Important";
private Database_Controller mDatabaseController;
private static final String ARG_ID = "ID";
ArrayList<Goal> goalList;
LinearLayoutManager manager;
public RecyclerView.Adapter adapter;
public ReceiverThread UiThread;
FragmentManager fragmentManager;
String list_title;
public List_Fragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_list_, container, false);
Bundle bundle = getArguments();
if(bundle != null){
list_title= bundle.getString(ARG_TITLE);
}
mDatabaseController = mDatabaseController.get(getContext());
goalList = mDatabaseController.getAllListsGoals(list_title);
mRecyclerView = (RecyclerView)view.findViewById(R.id.recyclerview);
manager = new LinearLayoutManager(getActivity());
UiThread = new ReceiverThread();
mRecyclerView.setLayoutManager(manager);
final RecyclerView_Adapter wrapperClass = new RecyclerView_Adapter(goalList,getContext(),this);
adapter = wrapperClass.adapter;
for(int counter =0; counter < goalList.size(); counter++){
System.out.println(goalList.get(counter).getWhich_List());
}
mRecyclerView.setAdapter(adapter);
fragmentManager= getFragmentManager();
//adapter goes here
final FloatingActionButton fab = (FloatingActionButton)view.findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Fragment fragment = List_Fragment.this;
AddNew_PopUp popUp = AddNew_PopUp.newInstance(fragment);
popUp.setTargetFragment(fragment, 0);
popUp.show(fragmentManager, "PopUpDialog");
}
});
return view;
}
public class ReceiverThread extends Thread {
#Override
public void run() {
super.run();
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
goalList.clear();
ArrayList<Goal>newGoalList = mDatabaseController.getAllGoals();
goalList.addAll(newGoalList);
adapter.notifyDataSetChanged();
}
});
}
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == 0){
if(resultCode == Activity.RESULT_OK){
Goal newGoal = new Goal();
String GoalName = data.getStringExtra(ARG_GOALNAME);
if (GoalName.isEmpty()) {
Toast.makeText(getContext(), R.string.NoGoal, Toast.LENGTH_SHORT).show();
} else {
newGoal.setmIsImportant(data.getBooleanExtra(ARG_IMPORTANT, false));
newGoal.setmGoalName(GoalName);
newGoal.setWhich_List(ARG_TITLE);
mDatabaseController.insertGoal(newGoal);
}
}
}else{
if(requestCode == 1){
if(resultCode == Activity.RESULT_OK){
String id = data.getStringExtra(ARG_ID);
Toast.makeText(getContext(),R.string.flush, Toast.LENGTH_LONG).show();
mDatabaseController.deleteGoal(id);
}
}else{
if(requestCode == 2){
if(resultCode == Activity.RESULT_OK){
String goalName = data.getStringExtra(ARG_GOALNAME);
Boolean isImportant = data.getBooleanExtra(ARG_IMPORTANT, false);
UUID id = UUID.fromString(data.getStringExtra(ARG_ID));
Goal goal = mDatabaseController.getGoal(id.toString());
goal.setmIsImportant(isImportant);
goal.setmGoalName(goalName);
mDatabaseController.updateGoal(goal);
}
}
}
}
UiThread.run();
}
public ReceiverThread getUiThread() {
return UiThread;
}
}
This is the list fragment that is created for every list in the database. It calls methods and manipulates data based off the user's actions.
public class RecyclerView_Adapter{
private ArrayList<Goal> mGoals;
MyAdapter adapter;
Context context;
private Database_Controller mDatabaseController;
MediaPlayer mediaPlayer;
Fragment fragment;
public RecyclerView_Adapter(ArrayList<Goal> goals, Context cntxt, Fragment fragments) {
mGoals = goals;
adapter = new MyAdapter(mGoals);
context = cntxt;
mediaPlayer = new MediaPlayer();
fragment = fragments;
mDatabaseController = Database_Controller.get(context);
}
//////////////////////////////////ADAPTER\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
private class MyAdapter extends RecyclerView.Adapter<MyViewHolder> {
private List<Goal> mGoals;
public MyAdapter(List<Goal> goals) {
mGoals = goals;
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from(parent.getContext());
View view = inflater.inflate(R.layout.recycler_view_item_layout, parent, false);
MyViewHolder holder = new MyViewHolder(view);
return holder;
}
#Override
public void onBindViewHolder(MyViewHolder holder, int position) {
final Goal goal = mGoals.get(position);
holder.bindGoal(goal);
}
#Override
public int getItemCount() {
return mGoals.size();
}
}
////////////////////////////////////ADAPTER\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
///////////////////////////////////VIEW HOLDER\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
public class MyViewHolder extends RecyclerView.ViewHolder {
private TextView mTextView, importantTXT;
private CheckBox mCheckBox;
private Goal mGoal;
private ImageView imgView;
public MyViewHolder(View itemView) {
super(itemView);
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
AppCompatActivity context = (AppCompatActivity) v.getContext();
FragmentManager manager = context.getSupportFragmentManager();
Edit_PopUp dialog = Edit_PopUp.newInstance(mGoal);
dialog.setTargetFragment(fragment, 2);
dialog.show(manager, "EditDialog");
}
});
itemView.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
//Add delete thingy
AppCompatActivity context = (AppCompatActivity) v.getContext();
FragmentManager manager = context.getSupportFragmentManager();
MoreOptions_PopUp dialog = MoreOptions_PopUp.newInstance(mGoal);
dialog.setTargetFragment(fragment, 1);
dialog.show(manager, "GoalDialog");
return true;
}
});
mTextView = (TextView) itemView.findViewById(R.id.text);
mCheckBox = (CheckBox) itemView.findViewById(R.id.checkbox);
imgView = (ImageView) itemView.findViewById(R.id.imageView);
importantTXT = (TextView) itemView.findViewById(R.id.Important_textView);
mCheckBox.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
mGoal.setFinished(mCheckBox.isChecked());
mDatabaseController.updateGoal(mGoal);
if (mCheckBox.isChecked() == true) {
boolean value = checkWinning(mGoals,context);
PlaySound(value, mGoal.ismIsImportant(), v);
}
}
});
}
public void bindGoal(Goal goal) {
mGoal = goal;
mCheckBox.setChecked(mGoal.isFinished());
mTextView.setText(mGoal.getmGoalName());
if (mGoal.ismIsImportant()) {
imgView.setImageResource(R.mipmap.ic_stars_pressed);
importantTXT.setText(R.string.isImportant);
}
}
public boolean checkWinning(ArrayList<Goal> goals, Context context) {
for (int i = 0; i < goals.size(); i++) {
if (goals.get(i).isFinished() == false) {
return false;
}
}
return true;
}
public void PlaySound(Boolean winningSound, boolean isImportant, View view) {
if(winningSound){
mediaPlayer = MediaPlayer.create(context,R.raw.victory);
Snackbar snackbar = Snackbar.make(view, R.string.completion, Snackbar.LENGTH_LONG);
snackbar.show();
mediaPlayer.start();
}else {
if (isImportant) {
mediaPlayer = MediaPlayer.create(context, R.raw.collect);
mediaPlayer.start();
Snackbar snackbar = Snackbar.make(view, R.string.congrats, Snackbar.LENGTH_SHORT);
snackbar.show();
} else {
mediaPlayer = MediaPlayer.create(context, R.raw.success);
Snackbar snackbar = Snackbar.make(view, R.string.lessCongrats, Snackbar.LENGTH_SHORT);
snackbar.show();
mediaPlayer.start();
}
}
}
}
////////////////////////////////////VIEW HOLDER\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
public MyAdapter getAdapter() {
return adapter;
}
public Fragment getFragment() {
return fragment;
}
}
Here is my adapter class that plays sounds OnClick and binds the view to the Recyclerview.
Any help would be greatly appreciated!
The problem with the stars displayed in every row will be caused because you might be setting them when needed but not hiding them when not needed.
You will have to implement something like this in the getView() method of your adapter.
ImageView starView = (ImageView) v.findViewById(R.id.starView);
starView.setVisibility(goals.get(position).isSpecial() ? View.Visible : View.Gone);

How to get id of sqlite when recyclerview item clicked?

Here is my doubt when i click recyclerview item need to get task id which i saved in sqlite how can i do this for example when i click recycler view need to pass that value to next page and need update that value how can i do this so far what i have tried is:
public class Task extends Fragment {
private static final String MY_PREFERENCE_KEY = "yogan";
private List<Model_Task_List> model_task_lists;
private RecyclerView recyclerView;
Task_List_Adapter taskadapter;
private RecyclerView.LayoutManager layoutManager;
SharedPreferences sharedPreferences;
private RecyclerView.Adapter adapter;
RequestQueue yog;
String user_id;
AppController app;
RequestQueue queue;
String Url;
Task_DB task_db = null;
Database_SF_APP database_sf_app;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_task, container, false);
recyclerView = (RecyclerView) view.findViewById(R.id.my_recycler_view);
LinearLayoutManager layoutManager = new LinearLayoutManager(getContext());
layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
recyclerView.setItemAnimator(new DefaultItemAnimator());
recyclerView.setLayoutManager(layoutManager);
if (model_task_lists == null) {
model_task_lists = new ArrayList<Model_Task_List>();
}
Calendar c = Calendar.getInstance();
System.out.println("Current time => " + c.getTime());
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
String formattedDate = df.format(c.getTime());
int hour=c.get(Calendar.HOUR_OF_DAY);
String hours=Integer.toString(hour);
database_sf_app = new Database_SF_APP(getActivity().getBaseContext());
int count=database_sf_app.getTaskCount();
sharedPreferences = getActivity().getSharedPreferences(LoginActivity.login, 0);
user_id = sharedPreferences.getString("user_id", null);
model_task_lists=database_sf_app.getTaskListById(user_id);
taskadapter=new Task_List_Adapter(model_task_lists,getActivity());
recyclerView.setAdapter(taskadapter);
if(taskadapter!=null){
taskadapter.setOnItemClickListener(new Task_List_Adapter.data() {
#Override
public void yog(View v, int position) {
}
});
}
queue = Volley.newRequestQueue(getContext());
Url = "http://xxx.xx.x.xx/xxx/GetActivitiesByUserID.svc/getlist/Task/" + user_id +"/" +null+"/"+hours;
ConnectivityManager cn = (ConnectivityManager) getActivity().getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo nf = cn.getActiveNetworkInfo();
if (nf != null && nf.isConnected()) {
Toast.makeText(getActivity(), "Network Available", Toast.LENGTH_LONG).show();
JsonObjectRequest jsonObjRequest = new JsonObjectRequest(Request.Method.POST, Url, new JSONObject(),
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
String server_response = response.toString();
try {
JSONObject json_object = new JSONObject(server_response);
JSONArray json_array = new JSONArray(json_object.getString("TaskResult"));
for (int i = 0; i < json_array.length(); i++) {
Model_Task_List modelobj = new Model_Task_List();
JSONObject json_arrayJSONObject = json_array.getJSONObject(i);
modelobj.setSubject(json_arrayJSONObject.getString("Subject"));
modelobj.setTaskID(json_arrayJSONObject.getInt("TaskID"));
modelobj.setUserName(json_arrayJSONObject.getString("DueDate"));
modelobj.setTaskStatus(json_arrayJSONObject.getString("TaskStatus"));
modelobj.setUserid(json_arrayJSONObject.getString("Owner"));
database_sf_app.insertorUpdate(modelobj);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getContext(), error.toString(), Toast.LENGTH_SHORT).show();
}
});
//Creating request queue
queue.add(jsonObjRequest);
}
//sync operation
//a union b
//a server
//b local storage
//a only - insert local
//b only - send to server
//a = b do nothing
//result
//bind
return view;
}
#Override
public void onResume()
{
super.onResume();
}
#Override
public void onStop() {
super.onStop();
}
}
Here is my TaskAdapter:
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import java.util.List;
public class Task_List_Adapter extends RecyclerView.Adapter<Task_List_Adapter.MyViewHolder> {
private List<Model_Task_List> dataSet;
private Context context;
private static data yog;
Model_Task_List modelTaskList=new Model_Task_List();
public void remove(int position)
{
dataSet.remove(position);
notifyItemRemoved(position);
}
public void edit(int position){
dataSet.set(position, modelTaskList);
notifyItemChanged(position);
}
public void setOnItemClickListener(data listener) {
this.yog = listener;
}
public static class MyViewHolder extends RecyclerView.ViewHolder {
// Model_Task_List Model_Task_List=new Model_Task_List();
TextView textname;
TextView textaddress;
TextView textphnum;
TextView textdegree;
TextView textemail;
ImageView call;
data datas;
public MyViewHolder(final View itemView) {
super(itemView);
this.textname = (TextView) itemView.findViewById(R.id.subject);
this.textaddress = (TextView) itemView.findViewById(R.id.username);
this.textphnum = (TextView) itemView.findViewById(R.id.status);
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(yog!=null){
yog.yog(itemView,getLayoutPosition());
}
}
});
// this.imageViewIcon = (ImageView) itemView.findViewById(R.id.imageView);
}
}
public interface data
{
void yog(View v,int position);
}
public Task_List_Adapter(List<Model_Task_List> data,Context context) {
this.dataSet = data;
this.context=context;
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent,
int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.task_list_view, parent, false);
MyViewHolder myViewHolder = new MyViewHolder(view);
return myViewHolder;
}
#Override
public void onBindViewHolder(MyViewHolder holder, int position) {
TextView textViewName = holder.textname;
TextView textViewaddress = holder.textaddress;
TextView textViewphnum = holder.textphnum;
TextView textdegree = holder.textdegree;
TextView textemail=holder.textemail;
textViewName.setText("Subject:"+dataSet.get(position).getSubject());
textViewaddress.setText("DueDate"+dataSet.get(position).getUserName());
textViewphnum.setText("Status:"+dataSet.get(position).getTaskStatus());
}
#Override
public int getItemCount() {
return dataSet.size();
}
}
IS it right way to get id:
taskadapter.setOnItemClickListener(new Task_List_Adapter.data() {
#Override
public void yog(View v, int position) {
Model_Task_List model_task_list=(Model_Task_List)model_task_lists.get(position);
String yog=model_task_list.getSubject().toString();
int yogeshs=model_task_list.getTaskID();
String yogan=Integer.toString(yogeshs);
Toast.makeText(getContext(),yogan,Toast.LENGTH_SHORT).show();
}
});
}
Where i make recyclerview clickable how to get id of sqlite when i click and need to pass the value to next page
The object you are displaying in recyclerview ,
in your case that code must be in TaskAdapter,
put id in that object so when you click on it you will get that object so retrieve ID from that object
clickedObjecj.getId();
defining onClick in the onBindViewHolder is not a good pratice
the correct way is that declare a interface in the adapter class and implement it on the Activity , Using interface we can pass the value
Steps 1:
Decalre Listener for the OnItemClickListener interface
private OnItemClickListener mListener;
Step 2 : declare an interface , this interface will forward our click and data from adapter to our activity
public interface OnItemClickListener {
void onItemClick(int elementId);
}
public void setOnItemClickListener(OnItemClickListener listener) {
mListener = listener;
}
Step 3 : define the on click on ViewHolder and pass the id
//Assigning on click listener on the item and passing the ID value of the item
itemView.setOnClickListener(new View.OnClickListener() { // we can handle the click as like we do in normal
#Override
public void onClick(View v) {
if (mListener != null) {
int elementId = dataSet.get(getAdapterPosition()).getTaskID(); // Get the id of the item on that position
mListener.onItemClick(elementId); // we catch the id on the item view then pass it over the interface and then to our activity
}
}
});
Step 4: implement TaskAdapter.OnItemClickListener in the activity
Step 6: onItemClick method you will recive the value
#Override
public void onItemClick(int itemId) {
Log.d(TAG, "onItemClick: "+String.valueOf(itemId));
}
first you have to set Cursor position into clicked one
Ex: Cursor products <- storing a set of data
to set Cursor to clicked position for example a position value from RecyclerView click event
products.moveToPosition(position);
then use getString as usual
String name = products.getString(products.getColumnIndex("NAME"));
hope it may help
Hmm, my problem just change setOnClickListener to setOnLongClickListener
i declare puplic static int posit in my Adapter
Second in onBindViewHolder of Adapter, i call:
holder.layout_item.setOnLongClickListener(new View.OnLongClickListener() { #Override public boolean online(View view) { posit = arrayList.get(position).getId(); return false; } });
Next, on MainActivity, i want delete 1 object in sqlite
Boolean checkDeleteData = phamTuanVan_sqlite.deleteData(PhamTuanVan_Adapter.posit);
hope it may help

Categories

Resources