So when I delete a row in the SQLITE Database and the actual activity is closing, I see the CardView which is delete.
I really tried to google but nothing changed, so maybe you could help me out guys.
This is the SQLITE Delete function:
public void deleteEntry(String ID){
SQLiteDatabase db = this.getWritableDatabase();
String query = "DELETE FROM " + DB_NAME + " WHERE ID = '" + ID + "'";
Log.d("QUERY",query);
db.execSQL(query);
db.close();
}
MyAdapter.java
package simplylabs.com.simplynote;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.GestureDetector;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.TimeZone;
import static android.content.ContentValues.TAG;
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.MyViewHolder>
{
public MyAdapter(List<ListItem> listItems, Context context) {
this.listItems = listItems;
this.context = context;
}
private List<ListItem> listItems;
private Context context;
#Override
public MyAdapter.MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext())
.inflate(R.layout.row_design,parent,false);
return new MyViewHolder(v);
}
#Override
public void onBindViewHolder(MyAdapter.MyViewHolder holder, int position)
{
final ListItem list = listItems.get(position);
holder.insert_NOTIZENNAME.setText(list.getNOTIZENNAME());
holder.insert_NOTIZ.setText(list.getNOTIZ());
holder.insert_TIME.setText(list.getTIME());
if(list.getPRIORITAET().equals("Sehr wichtig")){
holder.prioColor.setBackgroundResource(R.color.rot);
}
if(list.getPRIORITAET().equals("Wichtig")){
holder.prioColor.setBackgroundResource(R.color.orange);
}
if(list.getPRIORITAET().equals("Nicht wichtig")){
holder.prioColor.setBackgroundResource(R.color.gruen);
}
}
#Override
public int getItemCount() {
return listItems.size();
}
public class MyViewHolder extends RecyclerView.ViewHolder{
TextView insert_NOTIZENNAME;
TextView insert_NOTIZ;
TextView insert_TIME;
View prioColor;
public MyViewHolder(View itemView) {
super(itemView);
insert_NOTIZENNAME = itemView.findViewById(R.id.showNOTIZENNAME);
insert_NOTIZ = itemView.findViewById(R.id.show_NOTIZ);
insert_TIME = itemView.findViewById(R.id.show_DATUM);
prioColor = itemView.findViewById(R.id.view_prioritaet);
}
}
}
This is when I click on the menu Item:
#Override
public boolean onOptionsItemSelected(MenuItem item) {
DBHandler dbHandler = new DBHandler(this);
final Bundle extras = getIntent().getExtras();
switch(item.getItemId()){
case R.id.notiz_loeschen:
dbHandler.deleteEntry(extras.getString("ID"));
Toast.makeText(this, extras.getString("ID"), Toast.LENGTH_SHORT).show();
finish();
break;
case R.id.notiz_aendern:
break;
}
return super.onOptionsItemSelected(item);
}
MainActivity.java
recyclerView = rootView.findViewById(R.id.recyclerview_alle_notizen);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
recyclerView.setItemAnimator(new DefaultItemAnimator());
adapter = new MyAdapter(listItems,getActivity());
adapter.notifyDataSetChanged();
recyclerView.setAdapter(adapter);
recyclerView.addOnItemTouchListener(
new RecyclerItemClickListener(getActivity(), new RecyclerItemClickListener.OnItemClickListener() {
#Override public void onItemClick(View view, int position) {
if (data.moveToPosition(position))
{
Intent i = new Intent(getActivity(),NotizAnzeigen.class);
i.putExtra("NotizName",data.getString(1));
i.putExtra("Notiz",data.getString(2));
startActivity(i);
}
}
})
);
Could you please help me out please?
I've changed this, it is still only remove the cardview when i move to the last tab ...
package simplylabs.com.simplynote;
import android.content.Intent;
import android.support.v4.app.Fragment;
import android.database.Cursor;
import android.os.Bundle;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import java.util.ArrayList;
import java.util.List;
public class AlleNotizen extends Fragment {
RecyclerView recyclerView;
RecyclerView.Adapter adapter;
private List<ListItem> listItems;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.alle_notizen, container, false);
recyclerView = rootView.findViewById(R.id.recyclerview_alle_notizen);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
recyclerView.setItemAnimator(new DefaultItemAnimator());
return rootView;
}
#Override
public void onResume() {
listItems = new ArrayList<>();
ListItem listItem = new ListItem();
final DBHandler db = new DBHandler(getActivity());
final Cursor data = db.getData();
while(data.moveToNext()){
ListItem li = new ListItem(data.getString(0), data.getString(1),data.getString(2),data.getString(4),data.getString(3));
listItems.add(li);
}
adapter = new MyAdapter(listItems,getActivity());
adapter.notifyDataSetChanged();
recyclerView.setAdapter(adapter);
recyclerView.addOnItemTouchListener(
new RecyclerItemClickListener(getActivity(), new RecyclerItemClickListener.OnItemClickListener() {
#Override public void onItemClick(View view, int position) {
if (data.moveToPosition(position))
{
Intent i = new Intent(getActivity(),NotizAnzeigen.class);
i.putExtra("NotizName",data.getString(1));
i.putExtra("Notiz",data.getString(2));
startActivity(i);
}
}
})
);
super.onResume();
}
}
As you are deleting data from your local storage you need to notify the adapter that data set has changed.To do that you could try this.
After deleting data from SQLite you need to read data again and store
it in a list/arraylist variable.
create a function inside your adapter like this,
public void loadWithNewData(List<items> newCollectedData) {
this.listItems.clear();
this.listItems = newCollectedData;
this.notifyDataSetChanged();
}
And then call that function with adapter variable like this.
adapter.loadWithNewData(newDataCollectedFromDatabase);
hope it will help.
You are deleting the row from the database, but you are not updating your listItems array. You should update listItems and then call adapter.notifyDataSetChanged();
Related
My RecyclerView gets the same value as the other once I edited/updated a specifc item. Here is the example of what I am getting instead of update one specific item only. example
package com.example.crudrecycler;
import android.content.Context;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.text.Layout;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import org.w3c.dom.Text;
import java.lang.reflect.Array;
import java.util.ArrayList;
public class CustomAdapter extends RecyclerView.Adapter<CustomAdapter.ModelViewHolder> {
Context c;
ArrayList<StudentModel> studentArrayList= new ArrayList<>();
SQLiteDatabase sqlDB;
public CustomAdapter(Context c, int onedata, ArrayList<StudentModel> studentArrayList, SQLiteDatabase sqlDB) {
this.c = c;
this.studentArrayList = studentArrayList;
this.sqlDB = sqlDB;
}
#NonNull
#Override
public CustomAdapter.ModelViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from(c);
View view = inflater.inflate(R.layout.onedata, null);
return new ModelViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull CustomAdapter.ModelViewHolder holder, int position) {
final StudentModel model = studentArrayList.get(position);
holder.txtName.setText(model.getName());
holder.txtAddress.setText(model.getAddress());
holder.btn_Edit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Bundle bundle = new Bundle();
bundle.putInt("id", model.getId());
bundle.putString("name", model.getName());
bundle.putString("address", model.getAddress());
Intent intent = new Intent(c, MainActivity.class);
intent.putExtra("userdata", bundle);
c.startActivity(intent);
notifyDataSetChanged();
}
});
}
#Override
public int getItemCount() {
return studentArrayList.size();
}
public class ModelViewHolder extends RecyclerView.ViewHolder {
TextView txtName, txtAddress;
Button btn_Edit;
public ModelViewHolder(#NonNull View itemView) {
super(itemView);
txtName = (TextView)itemView.findViewById(R.id.txtName);
txtAddress = (TextView)itemView.findViewById(R.id.txtAddress);
btn_Edit = (Button)itemView.findViewById(R.id.btn_Edit);
}
}
}
I think the problem here is that I am setting my intent to my MainActivity.class and once I click edit/update on my MainActivity it also updates other items inside the RecyclerView, but still I don't know how to fix where and which is the problem here since I am just new and exploring things inside android studio.
i have implemented recyclerview and it works fine , i used a call back in BikeAdapter to be able to click every single row of this recycler view but when, i put these lines in OnCreateView the recycler view recycler throw null callback error , and when i delete mAdapter.setCallback(this); the recyclerview became empty
recyclerView.setAdapter(mAdapter); fillData();
mAdapter = new BikesAdapter(getActivity(), (ArrayList<Bike>) bikes);
mAdapter.setCallback(this);
and when i put these lines inside the filldata() OnResponse method : mAdapter.setCallback(this) is not recognized
mAdapter.setCallback(this);
if i want to display my recycler view without problems i have to delete mAdapter.setCallback(this);
mAdapter = new BikesAdapter(getActivity(), (ArrayList) bikes);
recyclerView.setAdapter(mAdapter);
inside the fillData to get the response at the right time
//my adapter code
package com.example.miniprojetandroid.adapters;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.example.miniprojetandroid.R;
import com.example.miniprojetandroid.models.Bike;
public class BikesAdapter extends RecyclerView.Adapter<BikesAdapter.BikesViewHolder> {
private final ArrayList<Bike> bikes;
private Context mContext;
private Callback mCallback;
public BikesAdapter(Context mContext, ArrayList<Bike> bikes) {
this.mContext = mContext ;
this.bikes = bikes;
}
#NonNull
#Override
public BikesAdapter.BikesViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View mItemView = LayoutInflater.from(mContext).inflate(R.layout.bike_list_item, parent, false);
return new BikesViewHolder(mItemView, this);
}
#Override
public void onBindViewHolder(#NonNull BikesAdapter.BikesViewHolder holder, int position) {
final Bike singleItem = bikes.get(position);
holder.BikeName.setText(singleItem.getModel());
holder.BikeImage.setBackgroundResource(singleItem.getImage());
holder.bikeView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mCallback.onItemClicked(singleItem);
}
});
holder.BikeImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(mContext,singleItem.getModel(),Toast.LENGTH_SHORT).show();
}
});
}
#Override
public int getItemCount() {
return bikes.size();
}
public class BikesViewHolder extends RecyclerView.ViewHolder {
public final TextView BikeName;
public final ImageView BikeImage;
public final Button bikeView;
final BikesAdapter mAdapter;
public BikesViewHolder(#NonNull View itemView, BikesAdapter mAdapter) {
super(itemView);
this.BikeName = itemView.findViewById(R.id.bikeName);
this.BikeImage = itemView.findViewById(R.id.bikeImage);
this.bikeView = itemView.findViewById(R.id.btn_view);
this.mAdapter = mAdapter;
}
}
public void setCallback(Callback callback) {
mCallback = callback;
}
public interface Callback {
void onItemClicked(Bike bike);
}
}
//my fragment that contains the recyclerview
package com.example.miniprojetandroid.ui.fragments;
import android.os.Bundle;
import androidx.fragment.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.example.miniprojetandroid.R;
import java.util.ArrayList;
import java.util.List;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.example.miniprojetandroid.Retrofit.BikeService;
import com.example.miniprojetandroid.Retrofit.RetrofitClient;
import com.example.miniprojetandroid.Retrofit.UserService;
import com.example.miniprojetandroid.adapters.BikesAdapter;
import com.example.miniprojetandroid.models.Bike;
import com.example.miniprojetandroid.models.User;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
public class FragmentOne extends Fragment implements BikesAdapter.Callback{
private BikeService apiService;
private RecyclerView recyclerView;
private List<Bike> bikes = new ArrayList<Bike>();
private BikesAdapter mAdapter;
List<Bike> result = new ArrayList<Bike>();
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_one, container,false);
recyclerView = rootView.findViewById(R.id.recycler_bikes);
recyclerView.setHasFixedSize(true);
recyclerView.setNestedScrollingEnabled(true);
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity(),
LinearLayoutManager.VERTICAL, false));
apiService = RetrofitClient.getClient().create(BikeService.class);
fillData();
mAdapter.setCallback(this);
return rootView;
}
public void fillData(){
Call<List<Bike>> call = apiService.getBikes();
call.enqueue(new Callback<List<Bike>>() {
#Override
public void onResponse(Call<List<Bike>> call, Response<List<Bike>> response) {
if(response.isSuccessful()){
bikes.addAll(response.body());
for(Bike bike: bikes){
bike.setImage(R.drawable.ruebike);
}
Log.e("Bike LIST", bikes.toString());
mAdapter = new BikesAdapter(getActivity(), (ArrayList<Bike>) bikes);
recyclerView.setAdapter(mAdapter);
//listView.setAdapter(new UserAdapter(MainActivity.this, R.layout.list_user, list));
}
}
#Override
public void onFailure(Call<List<Bike>> call, Throwable t) {
Log.e("ERROR: ", t.getMessage());
}
});
/*bikes.add(new Bike(1,"ECO", "RTT" , "44", R.drawable.ruebike ));
bikes.add(new Bike(2,"AAA", "RTT" , "33", R.drawable.ruebike ));
bikes.add(new Bike(3,"BBB", "RUE" , "11", R.drawable.ruebike ));
bikes.add(new Bike(4,"EEE", "SPORT" , "25", R.drawable.ruebike ));
bikes.add(new Bike(5,"CCC", "SPORT" , "77", R.drawable.ruebike ));
Log.e("USERS LIST", bikes.toString());*/
}
#Override
public void onItemClicked(Bike bike) {
Bundle bundle = new Bundle();
bundle.putInt("bike_id",bike.getId());
bundle.putString("model", bike.getModel());
bundle.putString("type", bike.getType());
bundle.putString("price", bike.getPrice());
bundle.putInt("image", bike.getImage());
DetailsFragment f = new DetailsFragment();
f.setArguments(bundle);
getActivity().getSupportFragmentManager()
.beginTransaction()
.replace(R.id.fragmentsContainer, f )
.commit();
}
}
What i am trying to do is two things:
1/ make my fragment recyclerview works with filldata with the call back method(for idea Log.e show that this method works fine)
2/ to make sure that when i click an item of the recycler view , i pass the selected bike to a thired fragmend (DetailsFragment)
Errors: the recycler view is empty when i delete the callback and it throw null exception when i use it
help me pls
the method fillData is not executing immediately because it contain network operation so it work on background thread , so when you call setCallback , the mAdapter will not be initialized yet , so i suggest to initialize mAdapter and call setAdapter inside onCreate instead of onResponse method, and you can pass the array to the constructor as null ,and inside onResponse you can pass the bikes arrayList by setter method and inside this method (the setter method) after assigning the list add "notifyDataSetChanged();"
so your adapter will look like :
package com.example.miniprojetandroid.adapters;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.example.miniprojetandroid.R;
import com.example.miniprojetandroid.models.Bike;
public class BikesAdapter extends RecyclerView.Adapter<BikesAdapter.BikesViewHolder> {
private final ArrayList<Bike> bikes;
private Context mContext;
private Callback mCallback;
public BikesAdapter(Context mContext, ArrayList<Bike> bikes) {
this.mContext = mContext ;
this.bikes = bikes;
}
public setBikesList(ArrayList<Bike> bikes){
this.bikes=bikes;
notifyDataSetChanged();
}
#NonNull
#Override
public BikesAdapter.BikesViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View mItemView = LayoutInflater.from(mContext).inflate(R.layout.bike_list_item, parent, false);
return new BikesViewHolder(mItemView, this);
}
#Override
public void onBindViewHolder(#NonNull BikesAdapter.BikesViewHolder holder, int position) {
final Bike singleItem = bikes.get(position);
holder.BikeName.setText(singleItem.getModel());
holder.BikeImage.setBackgroundResource(singleItem.getImage());
holder.bikeView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mCallback.onItemClicked(singleItem);
}
});
holder.BikeImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(mContext,singleItem.getModel(),Toast.LENGTH_SHORT).show();
}
});
}
#Override
public int getItemCount() {
return bikes.size();
}
public class BikesViewHolder extends RecyclerView.ViewHolder {
public final TextView BikeName;
public final ImageView BikeImage;
public final Button bikeView;
final BikesAdapter mAdapter;
public BikesViewHolder(#NonNull View itemView, BikesAdapter mAdapter) {
super(itemView);
this.BikeName = itemView.findViewById(R.id.bikeName);
this.BikeImage = itemView.findViewById(R.id.bikeImage);
this.bikeView = itemView.findViewById(R.id.btn_view);
this.mAdapter = mAdapter;
}
}
public void setCallback(Callback callback) {
mCallback = callback;
}
public interface Callback {
void onItemClicked(Bike bike);
}
}
and your fragment :
package com.example.miniprojetandroid.ui.fragments;
import android.os.Bundle;
import androidx.fragment.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.example.miniprojetandroid.R;
import java.util.ArrayList;
import java.util.List;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.example.miniprojetandroid.Retrofit.BikeService;
import com.example.miniprojetandroid.Retrofit.RetrofitClient;
import com.example.miniprojetandroid.Retrofit.UserService;
import com.example.miniprojetandroid.adapters.BikesAdapter;
import com.example.miniprojetandroid.models.Bike;
import com.example.miniprojetandroid.models.User;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
public class FragmentOne extends Fragment implements BikesAdapter.Callback{
private BikeService apiService;
private RecyclerView recyclerView;
private List<Bike> bikes = new ArrayList<Bike>();
private BikesAdapter mAdapter;
List<Bike> result = new ArrayList<Bike>();
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_one, container,false);
recyclerView = rootView.findViewById(R.id.recycler_bikes);
recyclerView.setHasFixedSize(true);
recyclerView.setNestedScrollingEnabled(true);
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity(),
LinearLayoutManager.VERTICAL, false));
apiService = RetrofitClient.getClient().create(BikeService.class);
fillData();
mAdapter = new BikesAdapter(getActivity(),null);
mAdapter.setCallback(this);
recyclerView.setAdapter(mAdapter);
return rootView;
}
public void fillData(){
Call<List<Bike>> call = apiService.getBikes();
call.enqueue(new Callback<List<Bike>>() {
#Override
public void onResponse(Call<List<Bike>> call, Response<List<Bike>> response) {
if(response.isSuccessful()){
bikes.addAll(response.body());
for(Bike bike: bikes){
bike.setImage(R.drawable.ruebike);
}
Log.e("Bike LIST", bikes.toString());
mAdapter.setBikesList(bikes);
//listView.setAdapter(new UserAdapter(MainActivity.this, R.layout.list_user, list));
}
}
#Override
public void onFailure(Call<List<Bike>> call, Throwable t) {
Log.e("ERROR: ", t.getMessage());
}
});
/*bikes.add(new Bike(1,"ECO", "RTT" , "44", R.drawable.ruebike ));
bikes.add(new Bike(2,"AAA", "RTT" , "33", R.drawable.ruebike ));
bikes.add(new Bike(3,"BBB", "RUE" , "11", R.drawable.ruebike ));
bikes.add(new Bike(4,"EEE", "SPORT" , "25", R.drawable.ruebike ));
bikes.add(new Bike(5,"CCC", "SPORT" , "77", R.drawable.ruebike ));
Log.e("USERS LIST", bikes.toString());*/
}
#Override
public void onItemClicked(Bike bike) {
Bundle bundle = new Bundle();
bundle.putInt("bike_id",bike.getId());
bundle.putString("model", bike.getModel());
bundle.putString("type", bike.getType());
bundle.putString("price", bike.getPrice());
bundle.putInt("image", bike.getImage());
DetailsFragment f = new DetailsFragment();
f.setArguments(bundle);
getActivity().getSupportFragmentManager()
.beginTransaction()
.replace(R.id.fragmentsContainer, f )
.commit();
}
}
I have a recyclerview with a couple of items. When someone clicks on an item in the Main Fragment, it is stored on sharedpreferences and then all clicked items are supposed to be displayed on another fragment. My issue is when someone clicks on an item, only the first clicked item is displayed on the other fragment(Details Fragment) instead of a list of items.
These are the methods of saving, retrieving and removing items on my SessionManager.class
public void saveitems(Context context,List<SingleItem> items){
Gson gson = new Gson();
String cartitems = gson.toJson(items);
editor.putString(KEY_ITEMS,cartitems);
editor.commit();
}
public void grandtotal (String total){
editor.putString(KEY_TOTAL,total);
editor.commit();
}
public void savetocart(Context context, SingleItem singleitems){
List<SingleItem> itemList = getItems(context);
if (itemList == null) {
itemList = new ArrayList<>();
itemList.add(singleitems);
saveitems(context, itemList);
}
}
public ArrayList<SingleItem> getItems(Context context){
List<SingleItem> items;
if (pref.contains(KEY_ITEMS)){
String cartitems = pref.getString(KEY_ITEMS,null);
Gson gson = new Gson();
SingleItem[] singleItems = gson.fromJson(cartitems,SingleItem[].class);
items = Arrays.asList(singleItems);
items = new ArrayList<>(items);
}
else
return null;
return (ArrayList<SingleItem>) items;
}
public void removeitem(Context context, SingleItem singleItem){
ArrayList<SingleItem> items = getItems(context);
if (items != null){
items.remove(singleItem);
saveitems(context,items);
}
}
This is how i am storing the items that have been clicked. Take a look at (RecyclerItems):
package com.carlton.shop;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import es.dmoral.toasty.Toasty;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
import ss.com.bannerslider.banners.RemoteBanner;
import ss.com.bannerslider.views.BannerSlider;
/**
* A simple {#link Fragment} subclass.
*/
public class MainFragment extends Fragment {
private BannerSlider bannerSlider;
private RecyclerView Categories;
public RecyclerView RecyclerItems;
private ShopItemAdapter adapter;
private List<ShopItem> item;
SessionManager sessionManager;
private List<SingleItem> items;
private SingleItemAdapter adapters;
private LinearLayout Layoutcategories, Layoutitems;
private TextView CatName;
private Button Up;
public MainFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(final LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_main, container, false);
bannerSlider = (BannerSlider) view.findViewById(R.id.banner_slider1);
Categories = (RecyclerView) view.findViewById(R.id.recyclercategories);
Layoutcategories = (LinearLayout) view.findViewById(R.id.LayoutCategories);
Layoutitems = (LinearLayout) view.findViewById(R.id.LayoutItems);
RecyclerItems = (RecyclerView) view.findViewById(R.id.recycleritems);
CatName = (TextView) view.findViewById(R.id.tvcategoryname);
Up = (Button) view.findViewById(R.id.btnup);
sessionManager = new SessionManager(getContext());
Categories.setHasFixedSize(true);
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getContext());
Categories.setLayoutManager(layoutManager);
RecyclerItems.setHasFixedSize(true);
RecyclerView.LayoutManager layoutmanager = new LinearLayoutManager(getContext());
RecyclerItems.setLayoutManager(layoutmanager);
Categories.addOnItemTouchListener(new RecyclerItemClickListener(getContext(), new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, final int position, long id) {
Layoutcategories.setVisibility(View.GONE);
Layoutitems.setVisibility(View.VISIBLE);
sessionManager.createcategorysession(item.get(position).getCategory());
HashMap<String, String> cat = sessionManager.getcategoryitems();
CatName.setText(cat.get(SessionManager.KEY_CATEGORY));
Up.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Layoutitems.setVisibility(View.GONE);
Layoutcategories.setVisibility(View.VISIBLE);
}
});
items = new ArrayList<>(item.get(position).getItems());
adapters = new SingleItemAdapter(getContext(),items);
RecyclerItems.setAdapter(adapters);
RecyclerItems.addOnItemTouchListener(new RecyclerItemClickListener(getContext(), new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
sessionManager.savetocart(getContext(), items.get(position));
Toasty.success(getContext(),"Added to cart",Toast.LENGTH_SHORT,true).show();
}
}));
}
}));
Banner();
getdata();
return view;
}
private void Banner() {
bannerSlider.addBanner(new RemoteBanner("http://supa.swagshop.co.ke/Images/moto.png"));
bannerSlider.addBanner(new RemoteBanner("http://supa.swagshop.co.ke/Images/moto.png"));
bannerSlider.addBanner(new RemoteBanner("http://supa.swagshop.co.ke/Images/moto.png"));
bannerSlider.addBanner(new RemoteBanner("http://supa.swagshop.co.ke/Images/moto.png"));
}
private void getdata() {
final ProgressDialog progressDialog = new ProgressDialog(getContext());
progressDialog.setMessage("Loading Items...");
progressDialog.show();
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(Constants.BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
InterfaceRequest request = retrofit.create(InterfaceRequest.class);
Call<JSONResponse> call =request.getJSON();
call.enqueue(new Callback<JSONResponse>() {
#Override
public void onResponse(Call<JSONResponse> call, Response<JSONResponse> response) {
if (response.isSuccessful()){
JSONResponse jsonResponse = response.body();
item = new ArrayList<>(jsonResponse.getItem());
adapter = new ShopItemAdapter(getContext(),item);
Categories.setAdapter(adapter);
} else {
Toasty.warning(getContext(),"Oops! Items could not be loaded",Toast.LENGTH_SHORT,true).show();
}
progressDialog.dismiss();
}
#Override
public void onFailure(Call<JSONResponse> call, Throwable t) {
Toasty.error(getContext(),t.getLocalizedMessage(),Toast.LENGTH_SHORT,true).show();
Log.d(Constants.TAG,t.getMessage());
progressDialog.dismiss();
}
});
}
}
This is how i'm retrieving the items on DetailsFragment;
package com.carlton.shop;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.RectF;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.helper.ItemTouchHelper;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.CheckBox;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
import es.dmoral.toasty.Toasty;
import static com.helpshift.util.HelpshiftContext.getApplicationContext;
/**
* A simple {#link Fragment} subclass.
*/
public class Details extends Fragment {
private RecyclerView RecyclerDetails;
private TextView CartPrice;
private CheckBox CheckCart;
private List<SingleItem> list;
private CartAdapter adapter;
private boolean add = false;
private Paint p = new Paint();
private SessionManager sessionManager;
public Details() {
// 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_details, container, false);
RecyclerDetails = (RecyclerView) view.findViewById(R.id.recyclercart);
CartPrice = (TextView) view.findViewById(R.id.tvcart);
CheckCart = (CheckBox) view.findViewById(R.id.chkcart);
sessionManager = new SessionManager(getContext());
RecyclerDetails.setHasFixedSize(true);
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getContext());
RecyclerDetails.setLayoutManager(layoutManager);
list = sessionManager.getItems(getContext());
RecyclerDetails.addOnItemTouchListener(new RecyclerItemClickListener(getContext(), new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
}
}));
if(list != null){
Toasty.info(getContext(),"Swipe to go to Next", Toast.LENGTH_LONG,true).show();
adapter = new CartAdapter(getContext(),list);
RecyclerDetails.setAdapter(adapter);
}
//initswipe();
return view;
}
}
In your session manager something's not right with the savetocart() method.
The first time it called, getItems() will return null as expected, therefore the if statement in the next line will resolve to true and an item will be added. But after that itemList will not be null, therefore the if statement will always resolve to false and no items are added to the list.
That method should look like this
public void savetocart(Context context, SingleItem singleitems){
List<SingleItem> itemList = getItems(context);
if (itemList == null) {
itemList = new ArrayList<>();
}
itemList.add(singleitems);
saveitems(context, itemList);
}
Hi i am new to android project so i am trying to use recycler view. but it is not working. i keep getting errors # this line " RecyclerAdapter adapter = new RecyclerAdapter(this, getData());" it says RecyclerAdapter (android.content.context, List) in RecyclerAdapter cannot be applied to my package class please help
statement.java
import android.content.Context;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import java.util.ArrayList;
import java.util.List;
import nnnnn.R;
import nnnnnn.RecyclerAdapter;
import nnnnnnnnnnnnn.Landscape;
public class Statements extends Fragment {
Toolbar toolbar;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.statements,container,false);
toolbar = (Toolbar) v.findViewById(R.id.toolbar);
toolbar.setTitle("Statements");
toolbar.inflateMenu(R.menu.menu_main);
setUpRecyclerView();
return v;}
private void setUpRecyclerView() {
RecyclerView recyclerView = (RecyclerView) findViewById(R.id.recyclerView);
RecyclerAdapter adapter = new RecyclerAdapter(this.getActivity(),Landscape.getData());
recyclerView.setAdapter(adapter);
final LinearLayoutManager mLinearLayoutManagerVertical = new LinearLayoutManager(this.getActivity()); // (Context context, int spanCount)
mLinearLayoutManagerVertical.setOrientation(LinearLayoutManager.VERTICAL);
recyclerView.setLayoutManager(mLinearLayoutManagerVertical);
recyclerView.setItemAnimator(new DefaultItemAnimator()); // Even if we dont use it then also our items shows default animation. #Check Docs
}
}
RecyclerAdapter code is below
RecyclerAdapter
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import java.util.List;
import xx.xx.xx.xx.xx.R;
import xx.xx.xx.xx.model.Landscape;
public class RecyclerAdapter extends RecyclerView.Adapter<RecyclerAdapter.MyViewHolder> {
private static final String TAG = RecyclerAdapter.class.getSimpleName();
private List<Landscape> mDataList;
private LayoutInflater inflater;
public RecyclerAdapter(Context context, List<Landscape> data) {
this.mDataList = data;
this.inflater = LayoutInflater.from(context);
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
Log.i(TAG, "onCreateViewHolder");
View view = inflater.inflate(R.layout.statementlist, parent, false);
MyViewHolder holder = new MyViewHolder(view);
return holder;
}
#Override
public void onBindViewHolder(MyViewHolder holder, int position) {
Log.i(TAG, "onBindViewHolder" + position);
Landscape current = mDataList.get(position);
holder.setData(current, position);
holder.setListeners();
}
#Override
public int getItemCount() {
return mDataList.size();
}
public void removeItem(int position) {
mDataList.remove(position);
notifyItemRemoved(position);
// notifyItemRangeChanged(position, mDataList.size());
// notifyDataSetChanged();
}
public void addItem(int position, Landscape landscape) {
mDataList.add(position, landscape);
notifyItemInserted(position);
// notifyItemRangeChanged(position, mDataList.size());
// notifyDataSetChanged();
}
class MyViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
TextView title;
ImageView imgThumb, imgDelete, imgAdd;
int position;
Landscape current;
public MyViewHolder(View itemView) {
super(itemView);
title = (TextView) itemView.findViewById(R.id.tvTitle);
imgThumb = (ImageView) itemView.findViewById(R.id.img_row);
imgDelete = (ImageView) itemView.findViewById(R.id.img_row_delete);
imgAdd = (ImageView) itemView.findViewById(R.id.img_row_add);
}
public void setData(Landscape current, int position) {
this.title.setText(current.getTitle());
imgThumb.setImageResource(current.getImageID());
this.position = position;
this.current = current;
}
public void setListeners() {
imgDelete.setOnClickListener(MyViewHolder.this);
imgAdd.setOnClickListener(MyViewHolder.this);
imgThumb.setOnClickListener(MyViewHolder.this);
}
#Override
public void onClick(View v) {
// Log.i("onClick before operation", position + " " + mDataList.size());
switch (v.getId()) {
case R.id.img_row_delete:
removeItem(position);
break;
case R.id.img_row_add:
addItem(position, current);
break;
}
// Log.i("onClick after operation", mDataList.size() + " \n\n" + mDataList.toString());
}
}
}
You're passing in "this" for the first argument to RecyclerAdapter. "this" being a Fragment class. The Fragment class does not extend from Context, so it cannot be used as such.
Try "this.getActivity()". This may result in null, so ideally put this within the Fragment subclass's "onActivityCreated" method (instead of the "onCreateView" method)
You need to override OnActivitycreated in order to call getActivity. Call setUpRecyclerView in OnActivitycreated and add getActivity. before findViewById and it will work
I need dividers in RecyclerView like an Image,I cant understand how I can do this.Dividers must look like textview or image,I need to make different ViewHolder or what?Im google it and don't find any example look like I need.
Its must look like this
http://www.picshare.ru/view/7210663/
My Adapter:
package com.example.myapplication;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import java.util.List;
import java.util.Objects;
import butterknife.Bind;
/**
* Created by Рост on 20.03.2016.
*/
public class UserAdapter extends RecyclerView.Adapter<UserAdapter.MyViewHolder> {
private List<User> UserList;
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
RecyclerView.ViewHolder viewHolder = null;
LayoutInflater inflater = LayoutInflater.from(parent.getContext());
View viewUser = inflater.inflate(R.layout.row_item_layout,parent,false);
viewHolder = new MyViewHolder(viewUser);
return (MyViewHolder) viewHolder;
}
#Override
public void onBindViewHolder(MyViewHolder holder, int position) {
holder.UserTitle.setText(UserList.get(position).getTitle());
holder.UserDescription.setText(UserList.get(position).getDescription());
holder.UserIcon.setImageResource(R.drawable.emilypic);
}
public UserAdapter(List<User> UserList){
this.UserList = UserList;
}
#Override
public int getItemCount() {
return UserList.size();
}
public class MyViewHolder extends RecyclerView.ViewHolder {
public ImageView UserIcon;
public TextView UserTitle;
public TextView UserDescription;
public Button UserFollowButton;
public MyViewHolder(View itemView) {
super(itemView);
UserIcon = (ImageView) itemView.findViewById(R.id.item_icon);
UserTitle = (TextView) itemView.findViewById(R.id.item_title);
UserDescription = (TextView) itemView.findViewById(R.id.item_description);
UserFollowButton = (Button) itemView.findViewById(R.id.item_follow_button);
}
}
}
Fragment with data:
package com.example.myapplication;
import android.annotation.TargetApi;
import android.content.Context;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.app.Fragment;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import java.util.ArrayList;
import java.util.List;
import butterknife.Bind;
public class Fragment_Username_Search extends Fragment {
private List<User> userList = new ArrayList<>();
private RecyclerView recyclerView;
private UserAdapter userAdapter;
#TargetApi(Build.VERSION_CODES.M)
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
private void prepareUserData() {
User user = new User(R.drawable.emilypic,"Marry Young","marbear",R.id.item_follow_button);
userList.add(user);
user = new User(R.drawable.emilypic,"Marry Young","marbear",R.id.item_follow_button);
userList.add(user);
user = new User(R.drawable.emilypic,"Sammy Lee","sambam",R.id.item_follow_button);
userList.add(user);
user = new User(R.drawable.emilypic,"Lilly Martinson","lilmartini",R.id.item_follow_button);
userList.add(user);
userAdapter.notifyDataSetChanged();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment__username__search, container, false);
RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getActivity());
recyclerView = (RecyclerView) view.findViewById(R.id.RecyclerView);
userAdapter = new UserAdapter(userList);
recyclerView.setLayoutManager(mLayoutManager);
recyclerView.setItemAnimator(new DefaultItemAnimator());
recyclerView.setAdapter(userAdapter);
prepareUserData();
return view;
}
}