How to pass/get value checkbox from adapter recycleview to another activity - java

There is something I want to ask, I have recycle view where is pass from adapter to activity, my question is :
I need to get value/data checkbox from adapter viewHolder Recycleview to activity who is use the adapter for show recycleview
CartAdapter.java
private Context mContext;
private ArrayList<CartModel> mCartList;
public boolean isSelectedAll = true;
public CartAdapter(Context context, ArrayList<CartModel> CartList){
mContext = context;
mCartList = CartList;
}
#NonNull
#Override
public CartViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
View v = LayoutInflater.from(mContext).inflate(R.layout.masteritem_cardview_cart, viewGroup, false);
return new CartViewHolder(v);
}
#Override
public void onBindViewHolder(#NonNull CartViewHolder cartViewHolder, int i) {
CartModel currentItem = mCartList.get(i);
cartViewHolder.mCartCheckbox.setChecked(true); //i want pass this value
ShoppingCartActivity.java
private RecyclerView mRecyclerView;
private CartAdapter mCartAdapter;
private ArrayList<CartModel> mCartModelList;
private RequestQueue mRequestQueue;
boolean cartfirst;
private Button mButtonCheckout;
public CheckBox mCartCheckAll;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_shopping_cart);
cartfirst = false;
mNavigationView = findViewById(R.id.navigation_view);
mNavigationView.setNavigationItemSelectedListener(this);
mDrawerLayout = (DrawerLayout) findViewById(R.id.cart_drawer);
mToogle = new ActionBarDrawerToggle(this,mDrawerLayout,R.string.open,R.string.close);
mDrawerLayout.addDrawerListener(mToogle);
mToogle.syncState();
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
mRecyclerView = findViewById(R.id.recycler_view_cart);
mRecyclerView.setHasFixedSize(true);
mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
mCartModelList = new ArrayList<>();
mRequestQueue = Volley.newRequestQueue(this);
parseJsonCartItem();
mButtonCheckout = findViewById(R.id.checkOut_btn);
mCartCheckAll = findViewById(R.id.cartChecKall_checkBox);
//firsttime checkall
mCartCheckAll.setChecked(true);
mButtonCheckout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
AlertDialog.Builder builder = new AlertDialog.Builder(ShoppingCartActivity.this);
builder.setTitle("Confirm Checkout");
builder.setMessage("Do you really want to Checkout?");
builder.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
for (int i = 0; i < mCartModelList.size(); i++){
//to here, for checking value if true they will checkout, else do nothing
//checkOutChartJSON();
}
}
startActivity(new Intent(getApplicationContext(),ShoppingCartActivity.class));
finish(); //finish current activity
overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_left);
}});
builder.setNegativeButton(android.R.string.no, null);
builder.create().show();
}
});
To check validation if checkbox is true they will do function checkOutChartJSON, else do nothing

If you wanna pass the data or value from an adapter to new activity then you can do it by using Intent and if you wanna pass the value to existing activity then interface is the best way to do it.
For new activity.
// Passing data to TargetActivity.class
Intent intent = new Intent(CurrentActivity.this, TargetActivity.class);
intent.putExtra("message", str);
startActivity(intent);
// Get the data in TargetActivity.class
Intent intent=getIntent();
String msg = intent.getStringExtra("message");
For existing activity.
First, make an interface. OnPassingData
public interface OnPassingData {
void onPassing(int value1, String value2,...,int valueN);
}
In the adapter.
OnPassingData onPassingData;
if (onPassingData != null) {
onPassingData .onPassing(value1, value2,..,valueN);
}
public void setOnPassingData(OnPassingData onPassingData) {
this.onPassingData= onPassingData;
}
At the adapter calling in activity.
adapter.setOnPassingData((value1, value2,...,valueN) -> {
Log.i(TAG, "value1 : " + value1);
Log.i(TAG, "value2 : " + value2);
});

Related

Images are not displayed in android list view

I'm making a todo app and when an item is marked as finished an image should be displayed in front of the list item. But images are not visible in the list view even if the item status in the database is changed as finished.
This is my adapter class.
public class ToDoAdapter extends ArrayAdapter {
private Context context;
private int resource;
List<ToDoModel> todos;
public ToDoAdapter(#NonNull Context context, int resource, #NonNull List<ToDoModel> objects) {
super(context, resource, objects);
this.context = context;
this.resource = resource;
this.todos = objects;
}
#NonNull
#Override
public View getView(int position, #Nullable View convertView, #NonNull ViewGroup parent) {
//Inflate card view
LayoutInflater inflater = LayoutInflater.from(context);
View row = inflater.inflate(resource, parent, false);
TextView title = row.findViewById(R.id.title);
TextView description = row.findViewById(R.id.txtDescription);
ImageView img = (ImageView)row.findViewById(R.id.img_done);
img.setVisibility(View.VISIBLE);
//Set data in card view
ToDoModel todo = todos.get(position);
title.setText(todo.getTitle());
description.setText(todo.getDescription());
//Show done image
if(todo.getFinished() > 0){
img.setVisibility(View.VISIBLE);
}
return row;
}
}
This is MainActivity.
public class MainActivity extends AppCompatActivity {
private ListView todoList;
private TextView countTxt;
private Button addTodo;
private List<ToDoModel> toDos;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
todoList = (ListView)findViewById(R.id.listViewToDo);
countTxt = (TextView)findViewById(R.id.txtCount);
addTodo = (Button)findViewById(R.id.btnAdd);
toDos = new ArrayList<>();
addTodo.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Go to next activity
startActivity(new Intent(getApplicationContext(), AddToDO.class));
}
});
}
#Override
protected void onResume() {
super.onResume();
DBHandler dbh = new DBHandler(getApplicationContext());
//Set count
int count = dbh.getCountTODO();
countTxt.setText("You have " + count + " TODOs");
//Save list
toDos = dbh.getAllToDos();
//Set adapter to list
ToDoAdapter toDoAdapter = new ToDoAdapter(getApplicationContext(), R.layout.todo_cardview, toDos);
todoList.setAdapter(toDoAdapter);
//Add click listener to list element
todoList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//Get clicked item
ToDoModel todo = toDos.get(position);
//Dialog box
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setTitle(todo.getTitle());
builder.setMessage(todo.getDescription());
//Buttons
builder.setNegativeButton("Delete", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dbh.deleteItem(todo.getId());
Toast.makeText(getApplicationContext(), "ToDo Deleted", Toast.LENGTH_SHORT).show();
startActivity(new Intent(getApplicationContext(), MainActivity.class));
}
});
builder.setPositiveButton("Finished", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
long time = System.currentTimeMillis();
//Update status
dbh.updateFinished(todo.getId(), time);
startActivity(new Intent(getApplicationContext(), MainActivity.class));
}
});
builder.setNeutralButton("Edit", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(MainActivity.this, AddToDO.class);
intent.putExtra("id", todo.getId());
intent.putExtra("title", todo.getTitle());
intent.putExtra("description", todo.getDescription());
intent.putExtra("finished", todo.getFinished());
startActivity(intent);
}
});
builder.show();
}
});
}
}
Use Glide or Picasso Library to Displaying Image with any other Shape.
Glide Example:
Glide.with(mContext).load(responseList.getLogoUrl()).apply(RequestOptions.circleCropTransform()).into(holder.imageName);
Picasso Example:
Picasso.get().load(clsobjname.getLogoUrl())
.into(viewHolder.imagename);

How to add AdMob Banner AD in RecyclarView after 5 or 10 CardView using FirebaseRecyclerAdapter

I am working on an android app where I am showing some text coming through the firebase database, now I want to show AdMob Banner AD after 5 CardView in the RecyclarView but I am not understand how to do that because I am beginner in Java and Android Programming language. Can anyone help me to do this implementation.
MY JAVA CODE
POJO CLASS
private String shaData;
public Model(){
}
public Model(String sha) {
this.shaData = sha;
}
public String getShaData() {
return shaData;
}
public void setShaData(String shaData) {
this.shaData = shaData;
}
}
MY VIEW HOLDER CLASS
public class Holder extends RecyclerView.ViewHolder{
public TextView txtShayari;
public Button copyButton, shareButton, whatsappButton;
public Holder(#NonNull View itemView) {
super(itemView);
txtShayari = (TextView)itemView.findViewById(R.id.textView);
copyButton = (Button) itemView.findViewById(R.id.copyBtn);
shareButton = (Button) itemView.findViewById(R.id.shBtn);
whatsappButton = (Button) itemView.findViewById(R.id.waBtn);
}
}
MY MAIN ACTIVITY
public class MainActivity extends AppCompatActivity {
RecyclerView recyclerView;
ProgressBar progressBar;
ImageView imageView;
FirebaseRecyclerAdapter<Model, Holder> recyclerAdapter;
RecyclerView.LayoutManager layoutManager;
FirebaseDatabase database;
DatabaseReference databaseReference;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
database = FirebaseDatabase.getInstance();
databaseReference = database.getReference("MyQuotes");
recyclerView = (RecyclerView)findViewById(R.id.recyclerView);
recyclerView.setHasFixedSize(true);
layoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutManager);
progressBar = findViewById(R.id.progress);
loadData();
}
private void loadData()
{
FirebaseRecyclerOptions options =
new FirebaseRecyclerOptions.Builder<Model>()
.setQuery(databaseReference,Model.class)
.build();
recyclerAdapter = new FirebaseRecyclerAdapter<Model, Holder>(options) {
int AD_TYPE = 0;
int CONTENT_TYPE = 1;
#Override
protected void onBindViewHolder(#NonNull final Holder holder, int position, #NonNull final Model model) {
holder.txtShayari.setText(model.getShaData());
progressBar.setVisibility(View.GONE);
holder.copyButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
ClipboardManager clipboard = (ClipboardManager)holder.itemView.getContext().getSystemService(CLIPBOARD_SERVICE);
ClipData clip = ClipData.newPlainText(Intent.EXTRA_TEXT, model.getShaData());
clipboard.setPrimaryClip(clip);
Toast.makeText(holder.itemView.getContext(), "Shayari Copied", Toast.LENGTH_SHORT).show();
}
});
holder.whatsappButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent whatsappIntent = new Intent(Intent.ACTION_SEND);
whatsappIntent.setType("text/plain");
whatsappIntent.setPackage("com.whatsapp");
whatsappIntent.putExtra(Intent.EXTRA_TEXT, model.getShaData());
try {
holder.itemView.getContext().startActivity(whatsappIntent);
} catch (android.content.ActivityNotFoundException ex) {
Toast.makeText(holder.itemView.getContext(), "Whatsapp have not been installed", Toast.LENGTH_SHORT).show();
}
}
});
holder.shareButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent();
intent .setAction(Intent.ACTION_SEND);
intent.putExtra(Intent.EXTRA_TEXT, model.getShaData());
intent.setType("text/plain");
intent = Intent.createChooser(intent, "Share With");
holder.itemView.getContext().startActivity(intent);
}
});
}
#NonNull
#Override
public Holder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(viewGroup.getContext())
.inflate(R.layout.item_view,viewGroup,false);
return new Holder(view);
}
};
recyclerAdapter.notifyDataSetChanged();
recyclerAdapter.startListening();
recyclerView.setAdapter(recyclerAdapter);
}
}
This is my whole code too fetch text data from the Firebase server and it is working very well, Simply now I am want too show AdMob banner ads after 5 cardviews on the recyclarview, So please anyone guide me.

How do I send data from fragment to another activity [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 3 years ago.
In my app, i have an activity that have recyclerview inside a fragment and the recycleview retrieve data from cloud store Firebase. I want to open new activity that will retrieve the data according to the link(that display on the recycler view) user has clicked.
How do i get the data and display it in new activity?
From ForumTitle.java > Show ReviewFragment.java > User click a value > Show ForumInterface.java
ForumTitle.java
public class ForumTitle extends AppCompatActivity {
private FirebaseFirestore db = FirebaseFirestore.getInstance();
ImageButton IVReview,IVTechnical,IVHardware;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_forum_title);
View.OnClickListener listener = new View.OnClickListener() {
#Override
public void onClick(View v) {
Fragment selectedFragment = null;
if (v == findViewById(R.id.iBReview)){
selectedFragment = new ReviewFragment();
}
else if (v == findViewById(R.id.iBTech)){
selectedFragment = new TechnicalSupportFragment();
}
else if (v == findViewById(R.id.iBHardware)){
selectedFragment = new HardwareFragment();
}
FragmentManager manager = getSupportFragmentManager();
FragmentTransaction transaction = manager.beginTransaction();
transaction.replace(R.id.fragment_container,selectedFragment);
transaction.commit();
}
};
IVReview = (ImageButton)findViewById(R.id.iBReview);
IVTechnical = (ImageButton)findViewById(R.id.iBTech);
IVHardware = (ImageButton)findViewById(R.id.iBHardware);
IVReview.setOnClickListener(listener);
IVTechnical.setOnClickListener(listener);
IVHardware.setOnClickListener(listener);
}
}
ReviewFragment.java
public class ReviewFragment extends Fragment {
private FirebaseFirestore db = FirebaseFirestore.getInstance();
private CollectionReference userRef = db.collection("Review");
private ForumAdapter adapter;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_review,container,false);
return view;
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
Query query = userRef.orderBy("DatePosted",Query.Direction.DESCENDING);
FirestoreRecyclerOptions<Forum> options = new
FirestoreRecyclerOptions.Builder<Forum>()
.setQuery(query,Forum.class)
.build();
adapter = new ForumAdapter(options);
RecyclerView recyclerView = (RecyclerView)view.findViewById(R.id.rvReview);
recyclerView.setHasFixedSize(true);
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(this.getActivity());
recyclerView.setLayoutManager(layoutManager);
recyclerView.setAdapter(adapter);
adapter.setOnItemClickListener(new ForumAdapter.OnItemClickListener() {
#Override
public void onItemClick(DocumentSnapshot documentSnapshot, int position) {
Forum forum = documentSnapshot.toObject(Forum.class);
String title = forum.getTitle();
String id = documentSnapshot.getId();
Intent intent = new Intent(getActivity(), ForumInterface.class);
Bundle extras = intent.getExtras();
extras.putString("FORUM_TYPE","Review");
extras.putString("FORUM_ID",id);
extras.putString("TITLE",title);
startActivity(intent);
}
});
}
#Override
public void onStart() {
super.onStart();
adapter.startListening();
}
#Override
public void onStop() {
super.onStop();
adapter.stopListening();
}
ForumInterface.java
public class ForumInterface extends AppCompatActivity {
private FirebaseFirestore db = FirebaseFirestore.getInstance();
Intent intent = getIntent();
Bundle extras = intent.getExtras();
String forum_title = extras.getString("TITLE");
String forum_type = extras.getString("FORUM_TYPE");
String forum_id = extras.getString("FORUM_ID");
private CollectionReference userRef = db.collection(forum_type).document(forum_id).collection(forum_title);
private ForumAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_forum_interface);
TextView test = (TextView)findViewById(R.id.tvForumTitle);
test.setText(forum_title);
}
}
ForumAdapter.java
public class ForumAdapter extends FirestoreRecyclerAdapter<Forum,ForumAdapter.ForumHolder> {
private OnItemClickListener listener;
public ForumAdapter(FirestoreRecyclerOptions<Forum> options) {
super(options);
}
#Override
public void onBindViewHolder(ForumHolder forumHolder, int i, Forum forum) {
forumHolder.textViewTitle.setText(forum.getTitle());
forumHolder.textViewDescription.setText(forum.getDescription());
forumHolder.timeStamp.setText(forum.getDatePosted().toString());
}
#NonNull
#Override
public ForumHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
android.view.View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.cardviewforumtitle,parent,false);
return new ForumHolder(v);
}
class ForumHolder extends RecyclerView.ViewHolder{
TextView textViewTitle;
TextView textViewDescription;
TextView timeStamp;
public ForumHolder(View itemView) {
super(itemView);
textViewTitle = itemView.findViewById(R.id.title);
textViewDescription = itemView.findViewById(R.id.description);
timeStamp = itemView.findViewById(R.id.timestamp);
textViewTitle.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int position = getAdapterPosition();
// NO_POSITION to prevent app crash when click -1 index
if(position != RecyclerView.NO_POSITION && listener !=null ){
listener.onItemClick(getSnapshots().getSnapshot(position),position);
}
}
});
}
}
public interface OnItemClickListener{
void onItemClick(DocumentSnapshot documentSnapshot, int position);
}
public void setOnItemClickListener(OnItemClickListener listener){
this.listener = listener;
}
#Override
public int getItemCount() {
return super.getItemCount();
}
}
With the code above i run it, i got an error
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.os.Bundle.putString(java.lang.String, java.lang.String)' on a null object reference
at my.edu.fsktm.um.finalproject.Fragment.ReviewFragment$1.onItemClick(ReviewFragment.java:61)
at my.edu.fsktm.um.finalproject.ForumTitle.ForumAdapter$ForumHolder$1.onClick(ForumAdapter.java:56)
The picture of my app
When I clicked the title "GTX 1660 Ti Gaming X"
You try to set content on a Bundle which is null in your ReviewFragment's onClick. Use new Bundle() instead of intent.getExtras(); to instantiate Bundle
Bundle extras = new Bundle();
extras.putString("FORUM_TYPE","Review");
extras.putString("FORUM_ID",id);
extras.putString("TITLE",title);
//You have to set the bundle to intent
intent.putExtras(extras);
startActivity(intent);
Beside this move below code inside onCreate of ForumInterface Activity
Intent intent = getIntent();
Bundle extras = intent.getExtras();
String forum_title = extras.getString("TITLE");
String forum_type = extras.getString("FORUM_TYPE");
String forum_id = extras.getString("FORUM_ID");
And here is the complete Activity.
public class ForumInterface extends AppCompatActivity {
private FirebaseFirestore db;
private CollectionReference userRef;
private ForumAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_forum_interface);
Intent intent = getIntent();
Bundle extras = intent.getExtras();
String forum_title = extras.getString("TITLE");
String forum_type = extras.getString("FORUM_TYPE");
String forum_id = extras.getString("FORUM_ID");
db = FirebaseFirestore.getInstance();
userRef = db.collection(forum_type).document(forum_id).collection(forum_title);
TextView test = (TextView)findViewById(R.id.tvForumTitle);
test.setText(forum_title);
}
}

Update TAB 2 Recyclerview When Data Added in TAB 1's RecyclerView

I have kind of to-do app. In profile activity, there are 2 tabs.
To-do and Done. In Tab 1, user can check as "done" of their "to-do". In this case, I want to update TAB 2's recyclerview.
I tried several things, but didn't work. Here is TAB 1 codes, it's almost same as TAB 2.
TAB 1 Class
public class Tab_Profile_1 extends Fragment {
private RecyclerView recyclerView_tab_todo;
private List<Model_ListItem> itemList;
private Adapter_Profile_ToDo adapter_profile_toDo;
SharedPreferences mSharedPref;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_profile_tab_1, container, false);
//TO-DO
//
recyclerView_tab_todo = view.findViewById(R.id.recyclerView_tab_todo);
//
fetchUserToDo();
return view;
}
public void fetchUserToDo() {
itemList = new ArrayList<>();
//First Settings
mSharedPref = PreferenceManager.getDefaultSharedPreferences(getContext());
String session_user_id = mSharedPref.getString("session_user_id", "");
API_Service api_service = Client.getRetrofitInstance().create(API_Service.class);
Call<List<Model_ListItem>> call = api_service.fetchUserToDo(session_user_id);
call.enqueue(new Callback<List<Model_ListItem>>() {
#Override
public void onResponse(Call<List<Model_ListItem>> call, Response<List<Model_ListItem>> response) {
itemList = response.body();
adapter_profile_toDo = new Adapter_Profile_ToDo(getContext(), itemList);
recyclerView_tab_todo.setHasFixedSize(true);
LinearLayoutManager layoutManager
= new LinearLayoutManager(getContext(), LinearLayoutManager.VERTICAL, false);
recyclerView_tab_todo.setLayoutManager(layoutManager);
recyclerView_tab_todo.setAdapter(adapter_profile_toDo);
}
#Override
public void onFailure(Call<List<Model_ListItem>> call, Throwable t) {
}
});
}}
TAB 1 RecyclerView Adapter
public class Adapter_Profile_ToDo extends RecyclerView.Adapter {
private Context context;
private List<Model_ListItem> itemList;
private String url_extension_images = URL_Extension.url_extension_images;
SharedPreferences mSharedPref;
ProgressDialog progressDialog;
View view;
public Adapter_Profile_ToDo(Context context, List<Model_ListItem> itemList) {
this.context = context;
this.itemList = itemList;
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_profile_todo, parent, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull ViewHolder holder, final int position) {
Glide.with(context).load(url_extension_images + itemList.get(position).getItem_image()).into(holder.imageView_profile_todo);
holder.textView_profile_todo_name.setText(itemList.get(position).getItem_name());
holder.textView_profile_todo_desc.setText(itemList.get(position).getItem_description());
holder.layout_profile_todo_detail.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//detail
}
});
holder.layout_profile_todo_add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final AlertDialog.Builder builder = new AlertDialog.Builder(view.getRootView().getContext(), R.style.AlertStyle);
builder.setTitle("\"" + itemList.get(position).getItem_name() + "\"" + "\n");
builder.setIcon(R.drawable.ic_bookmark);
builder.setPositiveButton("YAPTIM", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
showProgressDialog();
addDone("" + itemList.get(position).getItem_id(), position);
}
});
builder.setNegativeButton("SİL", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
showProgressDialog();
deleteUserToDo("" + itemList.get(position).getItem_id(), position);
}
});
builder.setNeutralButton("İptal", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
builder.show();
}
});
}
#Override
public int getItemCount() {
return itemList.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
ImageView imageView_profile_todo;
TextView textView_profile_todo_name, textView_profile_todo_desc;
LinearLayout layout_profile_todo_detail, layout_profile_todo_add;
public ViewHolder(View itemView) {
super(itemView);
imageView_profile_todo = itemView.findViewById(R.id.imageView_profile_todo);
textView_profile_todo_name = itemView.findViewById(R.id.textView_profile_todo_name);
textView_profile_todo_desc = itemView.findViewById(R.id.textView_profile_todo_desc);
layout_profile_todo_detail = itemView.findViewById(R.id.layout_profile_todo_detail);
layout_profile_todo_add = itemView.findViewById(R.id.layout_profile_todo_add);
}
}
public void deleteUserToDo(final String listId, final int clicked) {
mSharedPref = PreferenceManager.getDefaultSharedPreferences(context);
String session_user_id = mSharedPref.getString("session_user_id", "");
API_Service api_service = Client.getRetrofitInstance().create(API_Service.class);
Call<Response_Success> call = api_service.deleteUserToDo(session_user_id, listId);
call.enqueue(new Callback<Response_Success>() {
#Override
public void onResponse(Call<Response_Success> call, Response<Response_Success> response) {
if (response.code() == 200) {
if (progressDialog.isShowing()) {
progressDialog.dismiss();
progressDialog = null;
}
if (response.body().getSuccess().matches("true")) {
Toast.makeText(context, "Silindi!", Toast.LENGTH_SHORT).show();
itemList.remove(itemList.get(clicked));
notifyItemRemoved(clicked);
notifyItemRangeChanged(clicked, itemList.size());
} else {
Toast.makeText(context, "Bilinmeyen bir hata oluştu!", Toast.LENGTH_SHORT).show();
}
}
}
#Override
public void onFailure(Call<Response_Success> call, Throwable t) {
Toast.makeText(context, "Bilinmeyen bir hata oluştu!", Toast.LENGTH_SHORT).show();
}
});
}
public void addDone(String listId, final int clicked) {
mSharedPref = PreferenceManager.getDefaultSharedPreferences(context);
String session_user_id = mSharedPref.getString("session_user_id", "");
API_Service apiService = Client.getRetrofitInstance().create(API_Service.class);
Call<Response_Success> call = apiService.addDone(session_user_id, listId);
call.enqueue(new Callback<Response_Success>() {
#Override
public void onResponse(Call<Response_Success> call, Response<Response_Success> response) {
if (response.code() == 200) {
if (progressDialog.isShowing()) {
progressDialog.dismiss();
progressDialog = null;
}
if (response.body().getSuccess().matches("true")) {
Toast.makeText(context, "Eklendi", Toast.LENGTH_SHORT).show();
itemList.remove(itemList.get(clicked));
notifyItemRemoved(clicked);
notifyItemRangeChanged(clicked, itemList.size());
} else {
Toast.makeText(context, "Bilinmeyen bir hata oluştu!", Toast.LENGTH_SHORT).show();
}
}
}
#Override
public void onFailure(Call<Response_Success> call, Throwable t) {
}
});
}
public void showProgressDialog() {
progressDialog = new ProgressDialog(view.getRootView().getContext());
progressDialog.setMessage("Yükleniyor");
progressDialog.setCancelable(false);
progressDialog.show();
}
}
If i'm reading this correctly, you have two tabs and a backend database that stores the to do items and their state? To get the second list to update, you just need to do the same thing that you're doing in your first list, and update the adapter's data set and notify that the data set changed. How you trigger this action in your second tab is really the question.
You can either use an interface and have your adapter notify your activity that recycler view 1 had an action on it, and you can then tell adapter 2 to update its data. You can either pass back the data and only notify one row, or you could notify the entire data set. If you're doing this all service based, you could just reload the recycler view from the service and it will have the new data.
I think all you need to figure out is how you want to notify tab 2 that it needs to update its data. My recommendation is:
public interface AdapterInterface
{
void itemCompleted(Item hereIsTheItemThatNeedsToBeAddedTo2);
}
Then inside your adapter have a property with getters/setters such as:
private AdapterInterface adapterInterfaceListener;
Inside your Fragment/Activity implement AdapterInterface and implement the itemCompleted function.
And then set your adapter.setAdapterInterfaceLisetener to that function that you implemented. Then inside your adapter when the user clicks the checkbook to mark it as done, you can call the adapterInterfaceListener.itemCompleted() function, and it will send that information to your Fragment/Activity. From there you can give that new data to adapter2, or recall the API, however you want to get the new data.
Does this help?

How to get data from the db in activity a, when activity b is closed in Android with ActiveAndroid

im new to this and have some problems, thanks for your help.
Situation:
I have a MainActivity and a second Activity called MainAddMedActivity. I get data from the second activity through an EditText and save it in the database. My intention is to display the data from the EditText in a ListView in the MainActivity by taking it from the database. How to do it the right way ?
Med:
#Table(name = "Med")
public class Med extends Model {
// Zähler für eindeutige IDs
private static long counter = 0;
#Column(name = "_id", unique = true, onUniqueConflict = Column.ConflictAction.REPLACE)
public long id;
#Column(name = "Description", index = true)
public String description;
public Med() {
super();
}
public Med(String message) {
super();
id = counter++;
description = message;
}
}
MedDAO:
public class MedDAO {
public static List<Med> getAll(String text) {
return new Select()
.from(Med.class)
.where("Description like ?", new String[]{'%' + text + '%'})
.orderBy("Description")
.limit(40)
.execute();
}
public static List<Med> getAll() {
return new Select()
.all()
.from(Med.class)
.execute();
}
public static List<Med> getOneItem(String text) {
return new Select()
.from(Med.class)
.where("Description = ?", text)
.execute();
}
public static void insertMed(String msg){
new Med(msg).save();
}
public static void remove(String text) {
new Delete().from(Med.class).where("Description = ?", text).execute();
}
}
MainActivity:
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
private ArrayAdapter<String> listAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(view.getContext(), MainAddMedActivity.class);
startActivity(intent);
}
});
ListView mainListView = (ListView) findViewById(R.id.listView);
mainListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String item = listAdapter.getItem(position);
//Aus DB entfernen
MedDAO.remove(item);
//Aus Liste im Gui entfernen
listAdapter.remove(item);
Toast.makeText(getBaseContext(), item + "gelöscht", Toast.LENGTH_SHORT).show();
}
});
//TODO: ArrayAdapter bugt
//Adapter für die Liste erzeugen
listAdapter = new ArrayAdapter<String>(this, R.layout.single_row, R.id.listMedNrPart);
mainListView.setAdapter(listAdapter);
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public void onStart() {
super.onStart();
}
#Override
public void onStop() {
super.onStop();
}
#Override
public void onResume() {
super.onResume();
// MedDAO.getLatestItem();
/*int max = listAdapter.getCount();
int i = 0;
while (i < max){
Log.d("MainActivity", listAdapter.getItem(i));
i++;
}*/
// listAdapter.add(MedDAO.getLatestItem().toString());
}
}
MainAddMedActivity:
public class MainAddMedActivity extends AppCompatActivity {
private EditText txtSearchMedicament;
private EditText txtNumberMedicament;
private TextView txtAlarmPrompt;
private TimePickerDialog timePickerDialog;
private Switch switchReminder;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_add_med);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
EditText description = (EditText) findViewById(R.id.txtSearchMedicament);
String text = description.getText().toString();
**//SAVE IN DATABASE**
MedDAO.insertMed(text);
//TODO: Close Activity
}
});
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
this.txtSearchMedicament = (EditText) findViewById(R.id.txtSearchMedicament);
this.txtNumberMedicament = (EditText) findViewById(R.id.txtNumberMedicament);
this.txtAlarmPrompt = (TextView) findViewById(R.id.txtAlarmPrompt);
this.switchReminder = (Switch) findViewById(R.id.switchReminder);
switchReminder.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
cancelSwitch();
}
}
});
A Content Provider could be used. It takes a good amount of code to implement but it binds your database to your view.
Here is an example of a Content Provider I have implemented in the past.
You construct a ContentValue object (basically a set of values to mimic a database row) for your database keys and set your new data there. You then use getContentResolver() to insert the ContentValue into your Content Provider, which in turn updates your database with your new data.
ContentValues values = new ContentValues();
values.put(DatabaseHelper.KEY_VENUE_NAME, store.getName());
values.put(DatabaseHelper.KEY_VENUE_CITY, store.getCity());
values.put(DatabaseHelper.KEY_VENUE_STATE, store.getState());
//insert row
context.getContentResolver().insert(Uri.parse(ContentProvider.base_CONTENT_URI + index), values);
Here's an example of the Content Provider Class (too much code for here) which implements the logic for inserting, deleting, querying, editing, and constructing URI paths to your database.
You can then set up and use a Cursor, which iterates through your data source, to access the data from your Content Provider, more specifically you can extend CursorAdapter to directly bind your views to database queries. Here is what one looks like:
public class StoreCursorAdapter extends SimpleCursorAdapter {
private static final String TAG = "VenueCursorAdapter";
DatabaseHelper databaseHelper;
private Context context;
private int layout;
private int selection; //MapsActivity.getStoreSelection();
public StoreCursorAdapter(Context context, int layout, Cursor c, String[] from, int[] to, int flags) {
super(context, layout, c, from, to, flags);
databaseHelper = DatabaseHelper.getInstance(context);
this.context = context;
this.layout = layout;
}
#Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
final LayoutInflater inflater = LayoutInflater.from(context);
View v = inflater.inflate(layout, parent, false);
return v;
}
#Override
public void bindView(View v, Context context, Cursor c) {
selection = ((MapsActivity) context).getStoreSelection();
int position = c.getPosition();
int nameColumn = c.getColumnIndex(DatabaseHelper.KEY_VENUE_NAME);
String name = c.getString(nameColumn);
TextView nameText = (TextView) v.findViewById(R.id.nameTextView);
TextView ratingText = (TextView) v.findViewById(R.id.ratingTextView);
if(nameText != null && ratingText != null) {
nameText.setText(name);
}
}
}

Categories

Resources