I want to add item to RecyclerView when i choose Contact from contactbook
It's can be use in text view i can but i find how to use in recycler
i get two String like contactname and numberphne from Contact book and i need add it to view and show in recyclerview
Here is my code for RecyclerView Adapter
public class SettingCallAdapter extends RecyclerView.Adapter<SettingCallAdapter.ViewHolder>{
private Context context;
private List<Hospital> data;
private int lastSelectedPosition = 0;
public SettingCallAdapter( Context context , List<Hospital> data){
this.context = context;
this.data = data;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_setting_message_radio , parent , false);
ViewHolder viewHolder = new ViewHolder(view);
return viewHolder;
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
Hospital hospital = data.get(position);
holder.name.setText(hospital.getHos_name());
holder.num.setText(hospital.getHos_tel());
holder.selectionState.setChecked(lastSelectedPosition == position);
}
#Override
public int getItemCount() {
return data.size() ;
}
public class ViewHolder extends RecyclerView.ViewHolder {
public TextView name , num;
public RadioButton selectionState;
public ViewHolder(View itemView) {
super(itemView);
name = itemView.findViewById(R.id.set_name);
num = itemView.findViewById(R.id.set_num);
selectionState = itemView.findViewById(R.id.select_state);
selectionState.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
lastSelectedPosition = getAdapterPosition();
notifyDataSetChanged();
}
});
}
}
Here is my MainActivity
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.view_setting);
TextView title = findViewById(R.id.toolbar_title);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayShowTitleEnabled(false);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
toolbar.setNavigationIcon(getResources().getDrawable(R.drawable.ic_back));
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
onBackPressed();
}
});
title.setText(toolbar.getTitle());
title.setText("การแจ้งเหตุฉุกเฉิน");
mDatabase = FirebaseDatabase.getInstance();
mRef = mDatabase.getReference().child("setting").child("hospital");
set_button = findViewById(R.id.setting_edit_button);
set_button.setOnClickListener(this);
save_button = findViewById(R.id.setting_save_button);
save_button.setOnClickListener(this);
show_num = findViewById(R.id.show_num_call);
add_num = findViewById(R.id.add_num_call);
add_contact_message = findViewById(R.id.add_contact_message);
message = findViewById(R.id.set_message);
message.setEnabled(false);
add_num_call = findViewById(R.id.recycler_add_num_call);
show_num_message_list = findViewById(R.id.recycler_show_num_message);
add_num_message_list = findViewById(R.id.recycler_add_num_message);
select_contact = findViewById(R.id.add_contact_call);
select_contact.setOnClickListener(this);
//Check Keyboard
View view = this.getCurrentFocus();
if (view != null) {
InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
}
mRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot dataSnapshot1 : dataSnapshot.getChildren()){
Hospital mHospital = dataSnapshot1.getValue(Hospital.class);
list_hospital.add(mHospital);
}
mAdapter = new SettingCallAdapter(SettingActivity.this , list_hospital);
mAdapter.notifyDataSetChanged();
add_num_call.setAdapter(mAdapter);
add_num_call.setHasFixedSize(true);
add_num_call.setLayoutManager(new LinearLayoutManager(SettingActivity.this));
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
#Override
public void onClick(View view) {
switch (view.getId())
{
case R.id.setting_edit_button:
set_button.setVisibility(View.GONE);
save_button.setVisibility(View.VISIBLE);
show_num.setVisibility(View.GONE);
add_num.setVisibility(View.VISIBLE);
add_contact_message.setVisibility(View.VISIBLE);
show_num_message_list.setVisibility(View.GONE);
message.setEnabled(true);
addNumSOS();
break;
case R.id.setting_save_button:
save_button.setVisibility(View.GONE);
set_button.setVisibility(View.VISIBLE);
show_num.setVisibility(View.VISIBLE);
add_num.setVisibility(View.GONE);
add_contact_message.setVisibility(View.GONE);
show_num_message_list.setVisibility(View.VISIBLE);
message.setEnabled(false);
addMessageSOS();
break;
case R.id.add_contact_call:
Intent contactIntent = new Intent(Intent.ACTION_PICK, ContactsContract.CommonDataKinds.Phone.CONTENT_URI);
startActivityForResult(contactIntent , RESULT_PICK_CONTACT);
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == RESULT_PICK_CONTACT && resultCode == RESULT_OK) {
Uri contactUri = data.getData();
Cursor cursor = getContentResolver().query(contactUri, null, null, null, null);
cursor.moveToFirst();
int phoneIndex = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER);
int nameIndex = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME);
name_contact = cursor.getString(nameIndex);
num_contact = cursor.getString(phoneIndex);
}
Hospital hospital= new Hospital();
hospital.setHos_name(name_contact);
hospital.setHos_tel(num_contact);
list_hospital.add(hospital);
mAdapter.notifyItemInserted(list_hospital.size()-1);
}
EDIT: How i can use difference View in my code it mean like i feed form data use view_1 and when i add data use view_2
This Image show difference view when i add view_2 have a delete button it form ios phone
I found a few things wrong with your code. Since you have add a ValueEventListener onDataChange will be trigger everytime something happens to your mRef. That is ok. But the thing is you have set the adapter and the layout manager on that event and every time the recyclerview's adapter change when something happen to that mRef.
Here is how to do it properly.
Put the following code inside the onCreate method below add_num_call = findViewById(R.id.recycler_add_num_call); line.
add_num_call.setLayoutManager(new LinearLayoutManager(SettingActivity.this));
mAdapter = new SettingCallAdapter(SettingActivity.this , list_hospital);
mAdapter.notifyDataSetChanged();
add_num_call.setHasFixedSize(true);
Then inside onDataChange you can add the item to your adapter and notify the change like below.
for (DataSnapshot dataSnapshot1 : dataSnapshot.getChildren()){
Hospital mHospital = dataSnapshot1.getValue(Hospital.class);
list_hospital.add(mHospital);
}
mAdapter.notifyDataSetChanged();
As for your question, you can do this on your onActivityResult.
Hospital hospital= new Hospital();
hospital.setHos_name(name_contact);
hospital.setHos_tel(num_contact);
list_hospital.add(hospital);
mAdapter.notifyDataSetChanged();// or better to use ---> mAdapter.notifyItemInserted(list_hospita.size()-1);
Enjoy!
check whether number and name is empty or not
Related
Whenever I restart my app, all the information I saved inside an ArrayList during its runtime is deleted. In addition, sometimes when I go to another activity and then come back from that second activity. The information is deleted again. I'm not sure what's causing this. I want the information to be permanently saved unless deleted by the user. Usually, the error I'm receiving are IndexOutOfBounds exception when I need to call an item from my ArrayList.
Main Activity Code:
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private TextView preset;
private Button add;
private ListView exercises;
private ArrayList<String> exerciseName;
public ArrayList<Exercise> Exercises;
private MyAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Exercises = new ArrayList<Exercise>();
preset = findViewById(R.id.preset_title);
add = findViewById(R.id.add_exercise);
exercises = findViewById(R.id.exercises);
exerciseName = FileHelper.readData(this);
this.adapter = new MyAdapter(exerciseName, this, Exercises);
exercises.setAdapter(adapter);
add.setOnClickListener(this);
}
#Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.add_exercise:
final int CODE = 1;
Intent i = new Intent(this, add_activity.class);
startActivityForResult(i, CODE);
break;
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch(requestCode) {
case 1:
if(resultCode == RESULT_OK && data != null) {
Bundle passBack = data.getExtras();
Exercise exercise = passBack.getParcelable("exercise");
adapter.addData(exercise);
adapter.list.add(exercise.getName());
FileHelper.writeData(exerciseName, this);
adapter.notifyDataSetChanged();
}
case 2:
if (resultCode == RESULT_OK && data != null) {
Bundle passBack = data.getExtras();
Exercise exercise = passBack.getParcelable("exercise");
int position = passBack.getInt("position");
adapter.setData(exercise, position);
adapter.notifyDataSetChanged();
}
}
}
}
Custom Adapter Code (where my ArrayList data is stored):
public class MyAdapter extends ArrayAdapter<String> {
public ArrayList<String> list;
private Context context;
private TextView list_txt;
private ArrayList<Exercise> data;
public MyAdapter(ArrayList<String> records, Context context, ArrayList<Exercise> data) {
super(context, 0, records);
this.list = records;
this.data = data;
this.context = context;
}
public void addData(Exercise d){
data.add(d);
}
public void setData(Exercise d, int position) {
data.set(position, d);
}
#Override
public View getView(final int position, View convertView, final ViewGroup parent) {
if (convertView == null) {
convertView = LayoutInflater.from(getContext()).inflate(R.layout.listview_custom, parent, false);
}
Button list_but = (Button) convertView.findViewById(R.id.list_but);
TextView list_txt = (TextView) convertView.findViewById((R.id.list_txt));
Button edit = (Button) convertView.findViewById(R.id.list_but2);
Button start = (Button) convertView.findViewById(R.id.list_but3);
list_txt.setText(list.get(position));
edit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
final int CODE2 = 2;
Activity origin = (Activity)context;
Intent edit = new Intent(parent.getContext(), add_activity.class);
Bundle newBundle = new Bundle();
newBundle.putParcelable("exercise", data.get(position));
newBundle.putInt("position", position);
edit.putExtras(newBundle);
origin.startActivityForResult(edit, CODE2);
}
});
start.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent start = new Intent(parent.getContext(), timer_activity.class);
start.putExtra("exercise", data.get(position));
parent.getContext().startActivity(start);
}
});
list_but.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
AlertDialog.Builder alert = new AlertDialog.Builder(context);
alert.setTitle("Delete?");
alert.setMessage("Are you sure you want to delete this exercise?");
alert.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
list.remove(position);
try {
data.remove(position);
} catch(IndexOutOfBoundsException ex) {
}
notifyDataSetChanged();
}
});
alert.setNegativeButton("No", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
}
});
alert.create().show();
}
});
return convertView;
}
}
Every time You destroy activity You are losing all saved data in ListView. You have to save it before destroying and restore when You start an activity. You can do it with gson and SharedPreferences.
In Your MainActivity override onSaveInstanceState and inside this method save all Your exercises from Exercises list using gson.
Gson gson = new Gson();
String exercisesJSON = gson.toJson(Exercises);
SharedPreferences sharedPref = getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putString("KEY_BETTER_USE_CONST", exercisesJSON);
editor.commit();
And then in onCreate restore this data:
SharedPreferences sharedPref = getPreferences(Context.MODE_PRIVATE);
String exercisesJSON = sharedPref.getInt("KEY_BETTER_USE_CONST", "DEFAULT_VALUE_EMPTY");
//check if exercisesJSON is equal to "DEFAULT_VALUE_EMPTY" if yes, init array as empty, if not deserialize it using gson
Gson gson = new Gson();
Exercises[] exercises = gson.fromJson(exercisesJSON, Exercise[].class);
Haven't debugged this code but I think it should look something like this. I based on: Gson — Mapping of Arrays and Lists of Objects
sorry if the explanation is incomplete. I just learned about Android. and in my project this time, I made a filter feature using the radio button
I followed a totorial, but the tutorial uses static data, then I change it to dynamic using my data in the database. all works !! the data appears
but when I type something in the search bar that I make, suddenly my data disappears, I make 3 radio buttons to be selected by the user to be searched / filtered, namely type, price and facilities. the three radio buttons don't work, my data that appears are gone.
How to handle that problem?? if anyone can help me please help, thank you
this is the code
this fragment
public class FilterFragment extends Fragment implements RadioGroup.OnCheckedChangeListener, View.OnClickListener {
private static final String data_url = "http://000.000.00.000/kos/get_kos.php";
RecyclerView mRecyclerView;
ProgressDialog pd;
private Context context;
private RecyclerViewAdapter adapter;
private ArrayList<UserModel> arrayList;
private RadioGroup searchViaRadioGroup;
private EditText searchEditText;
private TextView searchViaLabel;
/* Filter Type to identify the type of Filter */
private FilterType filterType;
/* boolean variable for Filtering */
private boolean isSearchWithPrefix = false;
public FilterFragment() {
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
this.context = context;
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_filter, container, false);
pd = new ProgressDialog(getActivity());
mRecyclerView = (RecyclerView) view.findViewById(R.id.recycler_view);
arrayList = new ArrayList<>();
mRecyclerView.setLayoutManager(new GridLayoutManager(getActivity(), LinearLayoutManager.VERTICAL));
adapter = new RecyclerViewAdapter(getActivity(), arrayList);
mRecyclerView.setAdapter(adapter);
loadjson();
return view;
}
private void loadjson(){
pd.setMessage("Mengambil Data");
pd.setCancelable(false);
pd.show();
JsonArrayRequest arrayRequest = new JsonArrayRequest(Request.Method.POST, data_url, null, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
pd.cancel();
Log.d("volley", "response : " + response.toString());
for (int i=0; i < response.length(); i++)
try {
JSONObject data = response.getJSONObject(i);
UserModel md = new UserModel();
md.setJudul(data.getString("judul")); // memanggil nama array yang kita buat
md.setAlamat(data.getString("alamat"));
md.setHarga(data.getString("harga"));
md.setTipe_kos(data.getString("tipe_kos"));
md.setFasilitas(data.getString("fasilitas"));
arrayList.add(md);
} catch (JSONException e) {
e.printStackTrace();
}
adapter.notifyDataSetChanged();
}
}, new Response.ErrorListener(){
#Override
public void onErrorResponse(VolleyError error) {
pd.cancel();
Log.d("volley", "error : " + error.getMessage());
}
});
Controller.getInstance().addToRequestQueue(arrayRequest);
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
findViews(view);
implementEvents();
}
//Bind all Views
private void findViews(View view) {
filterType = FilterType.TIPE_KOS;
searchViaRadioGroup = (RadioGroup) view.findViewById(R.id.search_via_radio_group);
searchEditText = (EditText) view.findViewById(R.id.search_text);
searchViaLabel = (TextView) view.findViewById(R.id.search_via_label);
}
//Populate recycler view
private void implementEvents() {
searchViaRadioGroup.setOnCheckedChangeListener(this);
searchViaLabel.setOnClickListener(this);
searchEditText.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
#Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
//On text changed in Edit text start filtering the list
adapter.filter(filterType, charSequence.toString(), isSearchWithPrefix);
}
#Override
public void afterTextChanged(Editable editable) {
}
});
}
#Override
public void onCheckedChanged(RadioGroup radioGroup, int checkedId) {
int pos = radioGroup.indexOfChild(radioGroup.findViewById(checkedId));//get the checked position of radio button
switch (radioGroup.getId()) {
case R.id.search_via_radio_group:
switch (pos) {
case 0:
filterType = FilterType.TIPE_KOS;//Change filter type to Name if pos = 0
break;
case 1:
filterType = FilterType.NUMBER;//Change filter type to Number if pos = 1
break;
case 2:
filterType = FilterType.EMAIL;//Change filter type to Email if pos = 2
break;
}
}
}
#Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.search_via_label:
//show hide the radio group
if (searchViaRadioGroup.isShown()) {
searchViaLabel.setCompoundDrawablesWithIntrinsicBounds(0, 0, R.drawable.up_dropdown, 0);
searchViaRadioGroup.setVisibility(View.GONE);
} else {
searchViaLabel.setCompoundDrawablesWithIntrinsicBounds(0, 0, R.drawable.down_dropdown, 0);
searchViaRadioGroup.setVisibility(View.VISIBLE);
}
break;
}
}
}
this adapter
public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.RecyclerViewHolder> {
static class RecyclerViewHolder extends RecyclerView.ViewHolder {
private TextView judul, alamat, tipe_kos, fasilitas, harga;
RecyclerViewHolder(View view) {
super(view);
judul = (TextView) view.findViewById(R.id.judul);
alamat = (TextView) view.findViewById(R.id.alamat);
tipe_kos = (TextView) view.findViewById(R.id.tipe_kos);
fasilitas = (TextView) view.findViewById(R.id.fasilitas);
harga = (TextView) view.findViewById(R.id.harga);
}
}
private ArrayList<UserModel> arrayList;
private ArrayList<UserModel> filterArrayList;//duplicate list for filtering
private Context context;
public RecyclerViewAdapter(Context context, ArrayList<UserModel> arrayList) {
this.arrayList = arrayList;
this.context = context;
this.filterArrayList = new ArrayList<>();//initiate filter list
this.filterArrayList.addAll(arrayList);//add all items of array list to filter list
}
#Override
public RecyclerViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View v = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.custom_list_filter, viewGroup, false);
return new RecyclerViewHolder(v);
}
#Override
public void onBindViewHolder(final RecyclerViewHolder holder, final int i) {
final UserModel model = arrayList.get(i);
holder.judul.setText(model.getJudul());//menampilkan data
holder.alamat.setText(model.getAlamat());
holder.harga.setText(model.getHarga());
holder.tipe_kos.setText(model.getTipe_kos());
holder.fasilitas.setText(model.getFasilitas());
}
#Override
public int getItemCount() {
return (null != arrayList ? arrayList.size() : 0);
}
// Filter Class to filter data
public void filter(FilterType filterType, String charText, boolean isSearchWithPrefix) {
//If Filter type is TIPE_KOS and EMAIL then only do lowercase, else in case of NUMBER no need to do lowercase because of number format
if (filterType == FilterType.TIPE_KOS || filterType == FilterType.EMAIL)
charText = charText.toLowerCase(Locale.getDefault());
arrayList.clear();//Clear the main ArrayList
//If search query is null or length is 0 then add all filterList items back to arrayList
if (charText.length() == 0) {
arrayList.addAll(filterArrayList);
} else {
//Else if search query is not null do a loop to all filterList items
for (UserModel model : filterArrayList) {
//Now check the type of search filter
switch (filterType) {
case TIPE_KOS:
if (isSearchWithPrefix) {
//if STARTS WITH radio button is selected then it will match the exact TIPE_KOS which match with search query
if (model.getTipe_kos().toLowerCase(Locale.getDefault()).startsWith(charText))
arrayList.add(model);
} else {
//if CONTAINS radio button is selected then it will match the TIPE_KOS wherever it contains search query
if (model.getTipe_kos().toLowerCase(Locale.getDefault()).contains(charText))
arrayList.add(model);
}
break;
case EMAIL:
if (isSearchWithPrefix) {
//if STARTS WITH radio button is selected then it will match the exact EMAIL which match with search query
if (model.getFasilitas().toLowerCase(Locale.getDefault()).startsWith(charText))
arrayList.add(model);
} else {
//if CONTAINS radio button is selected then it will match the EMAIL wherever it contains search query
if (model.getFasilitas().toLowerCase(Locale.getDefault()).contains(charText))
arrayList.add(model);
}
break;
case NUMBER:
if (isSearchWithPrefix) {
//if STARTS WITH radio button is selected then it will match the exact NUMBER which match with search query
if (model.getHarga().startsWith(charText))
arrayList.add(model);
} else {
//if CONTAINS radio button is selected then it will match the NUMBER wherever it contains search query
if (model.getHarga().contains(charText))
arrayList.add(model);
}
break;
}
}
}
notifyDataSetChanged();
}
}
this FilterType
public enum FilterType {
TIPE_KOS, NUMBER, EMAIL;
}
and this user model
package com.example.asus.myapplication.fragment.filter;
public class UserModel {
private String judul, alamat, harga, tipe_kos, fasilitas;
public String getJudul() {
return judul;
}
public String getAlamat() {
return alamat;
}
public String getHarga() {
return harga;
}
public String getTipe_kos() {
return tipe_kos;
}
public String getFasilitas() {
return fasilitas;
}
public void setJudul(String mJudul) {
judul = mJudul;
}
public void setAlamat(String mAlamat) {
alamat = mAlamat;
}
public void setHarga(String mHarga) {
harga = mHarga;
}
public void setTipe_kos(String mTipe_kos) {
tipe_kos = mTipe_kos;
}
public void setFasilitas(String mFasilitas) { fasilitas= mFasilitas;
}
}
another one I do not understand at all for this filter API, I just pulled all the data in my database
My database is like this, which I circle, that's the data I want to filter later
I am new in android. I am using content provider for my app and want to delete an item from my sqlite database. it deletes the item from the database but the recyclerview does not show that it has been deleted except you go back and open the activity again before the deleted item disappears. I have looked through the code but I dont actually know what the problem is.
MainActivity
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_selecte_problem_drawal);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
toolbar.setTitleTextColor(Color.parseColor("#FFFFFF"));
mRecyclerView = (RecyclerView) findViewById(R.id.selected_problem_recycle_view); // Instantiate Recyclerview
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
mRecyclerView.setLayoutManager(linearLayoutManager);
mRecyclerView.setHasFixedSize(true);
selectedProblemsAdapter = new SelectedProblemsAdapter(this, null);
mRecyclerView.setAdapter(selectedProblemsAdapter);
getLoaderManager().initLoader(SELECTED_PROBLEMS_LOADER_ID, null,new CartLoader());
payForSelectedProblems = (Button)findViewById(R.id.payForSelectedProblems);
payForSelectedProblems.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (total > 0) {
Preferences.setDefaults("total", String.valueOf(total), getApplicationContext());
Intent intent = new Intent(SelectedProblems.this, SecondPayment.class);
startActivity(intent);
}else{
AlertDialog.Builder alert = new AlertDialog.Builder(SelectedProblems.this);
alert.setTitle("Alert");
alert.setMessage("Kindly Select a problem to continue...");
alert.setPositiveButton("OK",null);
alert.show();
}
}
});
}
public class CartLoader implements LoaderManager.LoaderCallbacks<Cursor> {
#Override
public Loader<Cursor> onCreateLoader(int i, Bundle bundle) {
return new CursorLoader(
SelectedProblems.this,
TranxavContract.CartEntries.CONTENT_URI,
SELECTED_PROBLEMS,
null,
null,
null
);
}
#Override
public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) {
selectedProblemsAdapter.update(cursor);
total = getSelectedProblemTotal(cursor);
problemSelectedTotal.setText(CurrencyFormatter.currencyFormat(String.valueOf(total)));
}
#Override
public void onLoaderReset(Loader<Cursor> loader){
selectedProblemsAdapter.update(null);
}
public double getSelectedProblemTotal(Cursor cursor){
while (cursor.moveToNext()){
total = total + Double.parseDouble(cursor.getString(SelectedProblems.PRICE));
}
return total;
}
}
Adapter
public SelectedProblemsAdapter(Context context, Cursor cursor) {
this.context = context;
this.cursor = cursor;
}
#NonNull
#Override
public SelectedProblemsViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
LayoutInflater layoutInflater = LayoutInflater.from(context);
View view = layoutInflater.inflate(R.layout.activity_selected_problems_content, null, false);
return new SelectedProblemsViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull SelectedProblemsViewHolder holder, final int position) {
if (this.cursor != null){
this.cursor.moveToPosition(position);
priceIndex = cursor.getColumnIndex(TranxavContract.CartEntries.PRICE);
problemsIndex = cursor.getColumnIndex(TranxavContract.CartEntries.PROBLEMS);
id = cursor.getString(idIndex);
problems = cursor.getString(problemsIndex);
price = cursor.getString(priceIndex);
formatted_price = CurrencyFormatter.currencyFormat(price);
holder.selectedProblemPrice.setText(formatted_price);
holder.selectedProblems.setText(problems);
holder.remove_problem_from_cart.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
context.getContentResolver().delete(
TranxavContract.CartEntries.CONTENT_URI,
TranxavContract.CartEntries.PROBLEMS + " = ?",
new String[] { problems }
);
Toast.makeText(context, problems + " Item Removed from Problem Selected" + "with postion " + position, Toast.LENGTH_SHORT).show();
notifyItemRemoved(position);
notifyDataSetChanged();
}
});
}
}
#Override
public int getItemCount() {
return (null != cursor ? cursor.getCount(): 0);
}
public void update(Cursor cursor) {
this.cursor = cursor;
notifyDataSetChanged();
}
class SelectedProblemsViewHolder extends RecyclerView.ViewHolder{
TextView selectedProblems, selectedProblemPrice, selectedProblemTotal;
Button remove_problem_from_cart;
public SelectedProblemsViewHolder(View itemView) {
super(itemView);
selectedProblems = itemView.findViewById(R.id.selected_problems);
selectedProblemPrice = itemView.findViewById(R.id.selected_problem_price);
selectedProblemTotal = itemView.findViewById(R.id.selectedProblemTotal);
remove_problem_from_cart = itemView.findViewById(R.id.remove_problem_from_cart);
}
}
Anybody who can help me.
For every delete, update your adapter like this
selectedProblemsAdapter.notifydatasetchanged();
Assuming all your deleting process is correct and you want to show animation all over your list in RecyclerView.
Instead of using
notifyItemRemoved(position)
you could implement
notifyItemRangeChanged(position, getItemCount());
notifyItemRangeChanged() notifies the RecyclerView Adapter that positions of element in adapter has been changed from position.
Here is a reference for you.
Hope it helps!
May be the problem is the list hasn't been reload after you deleted the record in db. You can try the method getLoaderManager().restartLoader(int id, Bundle args, LoaderCallbacks<D> callback) this should be restart the query and update it from the db. I hope so. Check more at here
After Deleting recall your display method
(If selectedProblemsAdapter.notifydatasetchanged(); this method is not work)
This is my firebase storage image and I want to display all images from url into gridview by taking the current user id
This is my main activity onstart() that leads to adapter class.
I want to show all the images under current user id like grid view.
How to display all user image posts in grid view from firebase above image.
#Override
protected void onStart() {
super.onStart();
FirebaseUser currentUser = mAuth.getCurrentUser();
uploads = new ArrayList<Blog>();
if (currentUser != null && !currentUser.isAnonymous()) {
mUserf.child("online").setValue("true");
mProgressbar.setMessage("Welcome.....");
mProgressbar.show();
mProgressbar.dismiss();
ConnectivityManager check = (ConnectivityManager)getSystemService(CONNECTIVITY_SERVICE);
NetworkInfo info = check.getActiveNetworkInfo(); //for checking whether app is connected to a network or not..
if(info!=null && info.isConnected()) {
//Toast.makeText(MainActivity.this, "network available", Toast.LENGTH_SHORT).show();
firebaseAuth.addAuthStateListener(authStateListener);
mProgressbar.setMessage("Fetching Blogs.....");
mProgressbar.show();
mProgressbar.dismiss();
list = new ArrayList<>();
adapter = new MyCustomAdapter(this,list,firebaseAuth,mdatabaseReference,likesdatabaseReference);
recyclerView = (RecyclerView) findViewById(R.id.blog_list);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
recyclerView.setAdapter(adapter);
alpha = FirebaseDatabase.getInstance().getReference().child("Blog").child(mAuth.getCurrentUser().getUid());
mchildEventListener = new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
mProgressbar.dismiss();
String j = dataSnapshot.getKey();
Log.v("GETKEYZZZ", j);
Blog friendlyMessage = dataSnapshot.getValue(Blog.class);
friendlyMessage.setPostkey(j);
list.add(friendlyMessage);
adapter.notifyDataSetChanged();
}
public void onChildChanged(DataSnapshot dataSnapshot, String s) {}
public void onChildRemoved(DataSnapshot dataSnapshot){}
public void onChildMoved(DataSnapshot dataSnapshot, String s) {}
public void onCancelled(DatabaseError databaseError) {}
};
mquery.addChildEventListener(mchildEventListener);
} else {
//Toast.makeText(MainActivity.this, "No network available", Toast.LENGTH_SHORT).show();
Toast.makeText(getApplicationContext(),"Please Check Your Internet Connection", Toast.LENGTH_LONG).show();
}
// mDatabseUsers.child("online").setValue("true");
} else {
Intent user1 = new Intent(MainActivity.this, LoginActivity.class);
startActivity(user1);
}
}
This is my adapter class where
public class MyCustomAdapter extends RecyclerView.Adapter<MyCustomAdapter.myviewholder> {
Context context;
ArrayList<Blog> list;
List <String> imageUrls;
//List<String> imageUrls ;
LayoutInflater inflator;
int lastPosition = 1;
boolean mprogressLike = true,mprogressview = true;
DatabaseReference likeDatabaseReference;
FirebaseAuth firebaseAuth;
DatabaseReference blogDatabaseReference;
public MyCustomAdapter(Context context, ArrayList<Blog> list,FirebaseAuth firebaseAuth,DatabaseReference blogDatabaseReference, DatabaseReference likeDatabaseReference) {
this.context=context;
this.list=list;
inflator=LayoutInflater.from(context);
this.likeDatabaseReference=likeDatabaseReference;
this.firebaseAuth=firebaseAuth;
this.blogDatabaseReference=blogDatabaseReference;
}
#Override
public myviewholder onCreateViewHolder(ViewGroup parent, int position) {
View v=inflator.inflate(R.layout.posts,parent,false);//this view will contain appearance of each layout i.e each row..
myviewholder holder=new myviewholder(v);// we are passing the view of each row to the myviewholder class
return holder;
}
#Override
public void onBindViewHolder(final myviewholder holder, int position) {//here we will inflate datas in the widgets i.e image and title..
//It is called for each row..so every row is inflated here..
final Blog p=list.get(position);
holder.title.setText(p.getTitle());
holder.username.setText(p.getUsername());
holder.viewno.setText(p.getTimestamp());
/*int count = 0;
for(HospitalModel.Images images: hospitalModelList.get(position).getImagesList()) {
count += images.size();
}*/
for(Blog model : list) {
imageUrls = new ArrayList<>();;
imageUrls.addAll(model.getUrl());
Log.v("IMURLSSS", String.valueOf(imageUrls));
Picasso.with(context).load(imageUrls.get(position)).into(holder.imageview);
Log.v("IMGGPOS", imageUrls.get(position));
}
Picasso.with(context).load(p.getImage()).into(holder.userdp);
}
#Override
public int getItemCount() {
return list.size();
}
public class myviewholder extends RecyclerView.ViewHolder implements View.OnClickListener {
// It contains the elements in each row that we will inflate in the recyclerView..
TextView title,desc,username,likeno,viewno;
ImageView imageview,userdp, over, comments, likes;
ImageButton likebtn,viewbtn;
public myviewholder(View itemView) {
super(itemView);
title = (TextView) itemView.findViewById(R.id.blog_desc);//here we link with the elements of each view i.e each row and
// desc = (TextView) itemView.findViewById(R.id.postdesc);//here we link with the elements of each view i.e each row and
username = (TextView) itemView.findViewById(R.id.blog_user_name);
viewno = (TextView) itemView.findViewById(R.id.blog_date);
likeno = (TextView) itemView.findViewById(R.id.blog_like_count);
userdp = (ImageView) itemView.findViewById(R.id.blog_user_image);
imageview = (ImageView) itemView.findViewById(R.id.blog_image);
comments = (ImageView) itemView.findViewById(R.id.blog_comment_icon);
//here we link with the elements of each view i.e each row and
// likebtn = (ImageButton)itemView.findViewById(R.id.likebtn);
// viewbtn = (ImageButton)itemView.findViewById(R.id.viewbtn);
comments.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mprogressview = true;
int pos = getAdapterPosition();
Blog b = list.get(pos);
Intent intent = new Intent(context,CommentBox.class);
Bundle bundle = new Bundle();
bundle.putString("post_key",b.getUid().toString());
intent.putExtras(bundle);
context.startActivity(intent);
}
});
over = (ImageView) itemView.findViewById(R.id.overflow);
over.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
showFilterPopup(v);
}
});
});
itemView.setOnClickListener(this);
}
}
To display all those url's, please use the following lines of code:
String uid = FirebaseAuth.getInstance().getCurrentUser().getUid();
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference urlRef = rootRef.child("Blog").child(uid).child("url");
ValueEventListener valueEventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot ds : dataSnapshot.getChildren()) {
String url = ds.getValue(String.class);
Log.d("TAG", url);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {}
};
urlRef.addListenerForSingleValueEvent(valueEventListener);
And here is a recommended way in which you can retrieve data from a Firebase Realtime database and display it in a RecyclerView using FirebaseRecyclerAdapter.
Edit:
String uid = FirebaseAuth.getInstance().getCurrentUser().getUid();
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference uidRef = rootRef.child("Blog").child(uid);
ValueEventListener valueEventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String uid = dataSnapshot.child("uid").getValue(String.class);
String title = dataSnapshot.child("title").getValue(String.class);
String timestamp = dataSnapshot.child("timestamp").getValue(String.class);
Log.d("TAG", uid + " / " + title + " / " + timestamp);
for(DataSnapshot ds : dataSnapshot.child("url").getChildren()) {
String url = ds.getValue(String.class);
Log.d("TAG", url);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {}
};
uidRef.addListenerForSingleValueEvent(valueEventListener);
How could I view the posts, only from friends?
in this example I would like to display in RecyclerView only the posts of my friends. In this case the user 15. (certainly is several friends, I put only one to exemplify)
Structure - database:
USERS
-user01 (current user)
-name: John
-age: 20
--friends
----user10
----user15
-POSTS
--idpost_98685754
---user_post: user15
---title_post: Title
---photo: link
-posts
--idpost_41254d4554s1
---user_post: user40
---title_post: Title
---photo: link
-posts
--idpost_121221sss1
---user_post: user15
---title_post: Title 2
---photo: link 2
-posts
--idpost_9865565555
---user_post: user15
---title_post: Title 3
---photo: link 3
I currently use only the simple order and limit functions explained in the documentation. This is the first time I need to do something like that.
EDIT:
CODE - FRAGMENT:
/*Firebase*/
mDb = FirebaseFirestore.getInstance();
mQuery = mDb.collection("Posts");
Query mQueryNew = mQuery.orderBy("timestamp", Query.Direction.DESCENDING);
/* Recycler */
mCardFeedList = (RecyclerView) view.findViewById(id.cardFeedUser_list);
mCardFeedList.setHasFixedSize(true);
mCardFeedList.setItemViewCacheSize(20);
mCardFeedList.setDrawingCacheEnabled(true);
mAdapter = new PostsAdapter(mQueryNew, this){
#Override
protected void onDataChanged() {
if (getItemCount() == 0) {
mCardFeedList.setVisibility(View.GONE);
} else {
mCardFeedList.setVisibility(View.VISIBLE);
}
}
};
llmanager = new LinearLayoutManager(getActivity());
mCardFeedList.setLayoutManager(llmanager);
mCardFeedList.setAdapter(mAdapter);
/*START*/
if (mAdapter != null) {
mAdapter.startListening();
}
ADAPTER:
public class PostsAdapter extends FirestoreAdapter<PostsAdapter.ViewHolder> {
public interface OnPostsListner{
void onPostSelected(DocumentSnapshot post);
void onLikeSelected(DocumentSnapshot like);
void onCurtidasSelected(DocumentSnapshot curtidas);
void onFotoSelected(DocumentSnapshot foto);
void onCommentsSelected(DocumentSnapshot coments);
}
private OnPostsListner mListner;
public PostsAdapter (Query query, OnPostsListner listner){
super(query);
mListner = listner;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from(parent.getContext());
return new ViewHolder(inflater.inflate(R.layout.card_feed_user_row, parent, false));
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
holder.bind(getSnapshot(position), mListner);
}
static class ViewHolder extends RecyclerView.ViewHolder {
private Boolean mIsliked = false;
#BindView(R.id.tvCardFeedUser_nome)
TextView nomeUser;
#BindView(R.id.tvCardFeedUser_horario)
TextView horaFeed;
#BindView(R.id.tvCardFeedUser_desc)
TextView descFeed;
#BindView(R.id.ivCardFeedUser_image)
ImageView imageFeed;
#BindView(R.id.secaoLike)
LinearLayout curtir;
#BindView(R.id.secaoComments)
LinearLayout comentarios;
#BindView(R.id.tv_card_feed_linear_curtidas)
LinearLayout linear_curtidas;
#BindView(R.id.idBtnLike)
TextView btnLike;
#BindView(R.id.tv_card_feed_numero_curtidas)
TextView curtidas;
#BindView(R.id.tv_card_feed_nome_curtida)
TextView nome_curtidas;
public ViewHolder(View itemView) {
super(itemView);
ButterKnife.bind(this, itemView);
}
public void bind(final DocumentSnapshot snapshot,
final OnPostsListner listener) {
final Posts ref = snapshot.toObject(Posts.class);
FirebaseFirestore db = FirebaseFirestore.getInstance();
FirebaseAuth mAuth = FirebaseAuth.getInstance();
final FirebaseUser mCurrentUser = mAuth.getCurrentUser();
nomeUser.setText(ref.getNome_user());
descFeed.setText(ref.getDesc());
//Foto
Picasso.with(itemView.getContext()).load(ref.getImage()).placeholder(R.drawable.bck_padrao).networkPolicy(NetworkPolicy.OFFLINE).into(imageFeed, new Callback() {
#Override
public void onSuccess() {
}
#Override
public void onError() {
Picasso.with(itemView.getContext()).load(ref.getImage()).placeholder(R.drawable.bck_padrao).into(imageFeed);
}
});
SimpleDateFormat formatter = new SimpleDateFormat("dd/M/yy HH:mm");
String novaData = formatter.format(ref.getTimestamp());
horaFeed.setText(novaData);
/*CLICKS*/
curtir.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (listener != null) {
listener.onLikeSelected(snapshot);
}
}
});
imageFeed.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (listener != null) {
listener.onFotoSelected(snapshot);
}
}
});
comentarios.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (listener != null) {
listener.onCommentsSelected(snapshot);
}
}
});
linear_curtidas.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (listener != null) {
listener.onCurtidasSelected(snapshot);
}
}
});
// Click listener
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (listener != null) {
listener.onPostSelected(snapshot);
}
}
});
}
}
}
To achieve this, you need to query your database twice using nested query. First of all you need to query the database to get all the friends id that correspond to a single user and then based on those ids to query the database for the second time to display only the post de correspond to those particular friends.
One thing to note is that this cannot be done in a single query.