display image from android database - android

I have a local database that i want get res id from it(string saving) and show in application, also i have a recycler view and I want after click on items, display image.
public class AdapterApp extends RecyclerView.Adapter<AdapterApp.AdapterViewHolder>{
public static class AdapterViewHolder extends RecyclerView.ViewHolder{
public TextView txtDescription;
public ViewGroup layoutRoot;
public TextView txtTitle;
public ImageView imgDesc;
public AdapterViewHolder(View itemView) {
super(itemView);
txtTitle = (TextView) itemView.findViewById(R.id.txtTitle);
txtDescription = (TextView) itemView.findViewById(R.id.txtDesc);
layoutRoot = (ViewGroup) itemView.findViewById(R.id.layoutRoot);
imgDesc = (ImageView) itemView.findViewById(R.id.imgDesc);
}
}
private ArrayList<StructApp> names = new ArrayList<StructApp>();
public AdapterApp(ArrayList<StructApp> names){
this.names = names;
}
#Override
public AdapterViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View view = G.inflater.from(viewGroup.getContext()).inflate(R.layout.adapter_app,viewGroup,false);
return new AdapterViewHolder(view);
}
#Override
public void onBindViewHolder(final AdapterViewHolder adapterViewHolder, final int i) {
final StructApp name = names.get(i);
adapterViewHolder.txtTitle.setText(name.title);
adapterViewHolder.layoutRoot.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(G.currentActivity,ActivityDesc.class);
intent.putExtra("description",name.description);
G.currentActivity.startActivity(intent);
}
});
}
#Override
public int getItemCount() {
return names.size();
}
#Override
public void onAttachedToRecyclerView(RecyclerView recyclerView) {
super.onAttachedToRecyclerView(recyclerView);
}
}
database activity:
public class ActivityTitleEngineer extends ActivityEnhanced {
private RecyclerView recyclerView;
private AdapterApp adapter;
private ArrayList<StructApp> applications = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_reshte_math);
recyclerView = (RecyclerView) findViewById(R.id.recyclerView);
recyclerView.setHasFixedSize(true);
LinearLayoutManager manager = new LinearLayoutManager(G.context);
manager.setOrientation(LinearLayoutManager.VERTICAL);
recyclerView.setLayoutManager(manager);
adapter = new AdapterApp(G.reshte);
populateFromDatabase();
recyclerView.setAdapter(adapter);
}
public void populateFromDatabase() {
G.reshte.clear();
DataBaseConnection db = new DataBaseConnection(this, "database", 4);
final SQLiteDatabase database = db.getReadableDatabase();
Cursor cursor = database.rawQuery("SELECT * FROM Reshte ", null);
while (cursor.moveToNext()) {
StructApp application = new StructApp();
application.description = cursor.getString(cursor.getColumnIndex("description"));
application.title = cursor.getString(cursor.getColumnIndex("title"));
application.imgDesc = cursor.getString(cursor.getColumnIndex("img"));
G.reshte.add(application);
}
cursor.close();
}
}
activity of display image:
public class ActivityDesc extends AppCompatActivity {
private TextView txtDesc;
private ImageView imgDesc;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_reshte_desc);
txtDesc = (TextView) findViewById(R.id.txtDesc);
imgDesc = (ImageView) findViewById(R.id.imgDesc);
Bundle extras = getIntent().getExtras();
if(extras!= null){
String desc = extras.getString("description");
txtDesc.setText(desc);
}
}
}

Try this method :)
StorageReference islandRef = MainGameFragment.storageReference.child("Capture.PNG");
final long ONE_MEGABYTE = 1024 * 1024;
islandRef.getBytes(ONE_MEGABYTE).addOnSuccessListener(new OnSuccessListener<byte[]>() {
#Override
public void onSuccess(byte[] bytes) {
ByteArrayInputStream imageStream = new ByteArrayInputStream(bytes);
Bitmap bitmap = BitmapFactory.decodeStream(imageStream);
imageSettings.setImageBitmap(bitmap);
settingsText4.setText("Click to visit site for more information");
settingsText4.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String url = "site";
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse(url));
startActivity(i);
}
});
mProgress.setVisibility(View.GONE);
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception exception) {
}
});

Related

get key position in onBindViewHolder firebase database

I want to get key position in database.
getting error: getRef(position) : Cannot resolve method 'getRef(int)' on
final String post_key = getRef(position).getKey();
this is my code CustomPostAdapter
public class CustomPostAdapter extends RecyclerView.Adapter<CustomPostAdapter.ViewHolder>{
public List<Spacecraft> userList ;
public Context context ;
private boolean mProcessLike = false ;
private DatabaseReference mDatabaseLike ;
// public ImageView imagePostt ;
public CustomPostAdapter(Context context , List<Spacecraft> userList){
this.userList = userList ;
this.context = context;
}
#NonNull
#Override
public CustomPostAdapter.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.row_posts_item, parent,false);
return new CustomPostAdapter.ViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull final ViewHolder holder, int position) {
mDatabaseLike = FirebaseDatabase.getInstance().getReference().child("Likes");
mDatabaseLike.keepSynced(true);
final String post_key = getRef(position).getKey();
final String name = userList.get(position).getName();
final String image_post = userList.get(position).getImage_post();
final String descrip = userList.get(position).getDescrip();
final String hachatg = userList.get(position).getHachtag();
final String user = userList.get(position).getUser();
final String time = userList.get(position).getTime();
//Text Post
holder.nameText.setText(name);
holder.descripText.setText(descrip);
holder.hachtagText.setText(" " + hachatg);
holder.timeText.setText(" " + time);
//Imgae Post if null set Visibtly Gone to ImageView
if (TextUtils.isEmpty(image_post)){
holder.imagePostt.setVisibility(View.GONE);
}else {
//Image Post
Picasso.with(context).load(image_post).into(holder.imagePostt , new Callback() {
#Override
public void onSuccess() {
holder.imagePostt.setVisibility(View.VISIBLE);
}
#Override
public void onError() {
holder.imagePostt.setVisibility(View.GONE);
}
});
}
//Onclick items
holder.mView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(context , ContentActivity.class);
intent.putExtra("NAME_KEY", name);
intent.putExtra("HACHTAG_KEY", hachatg);
intent.putExtra("DESCRIP_KEY", descrip);
intent.putExtra("USER_KEY", user);
intent.putExtra("IMAGE_POST", image_post);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent);
}
});
//Button Like Onclice
holder.mLikeBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mProcessLike = true;
if (mProcessLike){
mDatabaseLike.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
//Chek if user already Like or not
if (dataSnapshot.child(post_key).hasChild(user)){
}else {
mDatabaseLike.child(post_key).child(user).setValue("RandomValue");
mProcessLike = false;
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
}
});
}
#Override
public int getItemCount() {
return userList.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
View mView;
public TextView nameText , hachtagText , descripText, urlText , timeText;
public ImageView imagePostt ;
public ImageButton mLikeBtn ;
public ViewHolder(View itemView) {
super(itemView);
mView = itemView;
nameText = (TextView)mView.findViewById(R.id.text_nameProblem);
hachtagText = (TextView)mView.findViewById(R.id.text_nameUser);
// urlText = (TextView)mView.findViewById(R.id.textUrl);
descripText = (TextView)mView.findViewById(R.id.text_Discription);
timeText = (TextView)mView.findViewById(R.id.timeText);
imagePostt = (ImageView)mView.findViewById(R.id.imagePost);
mLikeBtn = (ImageButton)mView.findViewById(R.id.btnLike);
}
}
}
You should be using FirebaseRecyclerAdapter which has the method getRef(). follow this link to learn how to use it
There are two ways in which you can solve this. The first one would be to store the key as a property in your user object and use:
final String key = userList.get(position).getKey();
And the second one would be to simply use FirebaseRecyclerAdapter instead and call:
mFirebaseRecyclerAdapter.getKey(position);
As explained here by #Puf.

FirebaseRecyclerAdapter with gridlayoutmanager

I have recyclerview recieving data from firebase and i want to make last item uploaded to be first item in the list.I'm using GridLayoutManager and want to display a pic with a text, all of this work fine but i want to make them in order like instagram, does any one know something like that ?
Here is my code
public class ItemsUser extends Fragment {
private View mMainView;
private RecyclerView mUsersList;
private String user_id;
private DatabaseReference mUserDatabase;
private FirebaseRecyclerAdapter<ItemRecycleview,UserRecycleView> firebaseRecyclerAdapter;
private DatabaseReference mDatabaseReference;
private FirebaseListAdapter<ItemRecycleview> firebaseListAdapter;
public ItemsUser() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
mMainView = inflater.inflate(R.layout.fragment_items_user, container, false);
mUsersList = (RecyclerView) mMainView.findViewById(R.id.recyclerView_profile);
mUsersList.setHasFixedSize(true);
mUsersList.setLayoutManager(new GridLayoutManager(getActivity(),3));
ProfileUser activity = (ProfileUser) getActivity();
user_id = activity.getMyData();
mDatabaseReference = FirebaseDatabase.getInstance().getReference();
mUserDatabase = FirebaseDatabase.getInstance().getReference().child("Users_photos").child(user_id);
mUserDatabase.keepSynced(true);
return mMainView;
}
#Override
public void onStart() {
super.onStart();
firebaseRecyclerAdapter = new FirebaseRecyclerAdapter<ItemRecycleview, UserRecycleView>(
ItemRecycleview.class,
R.layout.recycleview_item,
UserRecycleView.class,
mUserDatabase
) {
#Override
protected void populateViewHolder(UserRecycleView viewHolder, ItemRecycleview model, int position) {
viewHolder.setImageName(model.getImageName());
viewHolder.setImageURL(model.getImageURL(),getContext());
viewHolder.mView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String key = firebaseRecyclerAdapter.getRef(mUsersList.getChildLayoutPosition(v)).getKey();
Intent imageIntent = new Intent(getActivity(), ImageActivity.class);
imageIntent.putExtra("imageKey",key);
imageIntent.putExtra("user_id",user_id);
startActivity(imageIntent);
}
});
}
};
mUsersList.setAdapter(firebaseRecyclerAdapter);
}
public static class UserRecycleView extends RecyclerView.ViewHolder {
View mView;
public UserRecycleView(View itemView) {
super(itemView);
mView = itemView;
}
public void setImageName(String imageName){
TextView userNameView = (TextView) mView.findViewById(R.id.ImageNameTextView);
userNameView.setText(imageName);
}
public void setImageURL(final String imageURL,final Context ctx){
final ImageView userImageView = (ImageView) mView.findViewById(R.id.imageView);
Picasso.with(ctx).load(imageURL).networkPolicy(NetworkPolicy.OFFLINE).into(userImageView, new Callback() {
#Override
public void onSuccess() {
}
#Override
public void onError() {
Picasso.with(ctx).load(imageURL).into(userImageView);
}
});
}
}
}
and this is ItemRecyclerview:
public class ItemRecycleview {
public String imageName;
public String imageURL;
public ItemRecycleview(){
}
public ItemRecycleview(String imageName, String imageURL) {
this.imageName = imageName;
this.imageURL = imageURL;
}
public String getImageName() {
return imageName;
}
public void setImageName(String imageName) {
this.imageName = imageName;
}
public String getImageURL() {
return imageURL;
}
public void setImageURL(String imageURL) {
this.imageURL = imageURL;
}
}
hey guys i just found the answer :D
all you need to do is to add this method in firebaseRecyclerAdapter
here it's:
firebaseRecyclerAdapter = new FirebaseRecyclerAdapter<ItemRecycleview, UserRecycleView>(
ItemRecycleview.class,
R.layout.recycleview_item,
UserRecycleView.class,
mUserDatabase
) {
#Override
public ItemRecycleview getItem(int position) {
return super.getItem(getItemCount() - 1 - position);
}
#Override
protected void populateViewHolder(UserRecycleView viewHolder, ItemRecycleview model, int position) {
viewHolder.setImageName(model.getImageName());
viewHolder.setImageURL(model.getImageURL(),getContext());
viewHolder.mView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String key = firebaseRecyclerAdapter.getRef(mUsersList.getChildLayoutPosition(v)).getKey();
Intent imageIntent = new Intent(getActivity(), ImageActivity.class);
imageIntent.putExtra("imageKey",key);
imageIntent.putExtra("user_id",user_id);
startActivity(imageIntent);
}
});
}
};
and that will make it done
Have you tried using setReverseLayout() method to make first element last in the list
GridLayoutManager mLayoutManager = new GridLayoutManager(getActivity(),3);
mLayoutManager.setReverseLayout(true);
mLayoutManager.setStackFromEnd(true);
mUsersList.setLayoutManager(mLayoutManager);

Null pointer exception unable to solve?

Calling my async task class from my oncreate in OpensubcontentActivity, it is executing fine but while calling the same async task class from vivcontentAdapter in onBindViewHolder it is giving null pointer error in progressdialog.
OpensubcontentActivity
public class OpenSubContentActivity extends AppCompatActivity {
private RecyclerView recyclerView;
private vivcontentAdapter vivcontentAdapteradapter;
static String stack_info[] = new String[10];
static int top = -1;
static String ObjectId;
static List<Information> data_content = new ArrayList<>();
public static Map info_map = null;
Boolean file_flag;
File file;
Context context;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_open_sub_content);
setEveryThing();
Intent mIntent = getIntent();
context = this;
ObjectId = mIntent.getStringExtra("CabinetID");
new getData().execute();
}
public void setEveryThing() {
floatingActionMenu = (FloatingActionMenu) findViewById(R.id.floating_menu);
newfolder = (FloatingActionButton) findViewById(R.id.idtem__folder);
newdoc = (FloatingActionButton) findViewById(R.id.idtem_doc);
upload = (FloatingActionButton) findViewById(R.id.idtem_upload);
capture = (FloatingActionButton) findViewById(R.id.idtem_photo);
toolbar = (Toolbar) findViewById(R.id.toolBar);
toolbar.setTitleTextColor(0xFFFFFFFF);
setSupportActionBar(toolbar);
getSupportActionBar().setTitle(("Example"));
recyclerView = (RecyclerView) findViewById(R.id.list_file);
vivcontentAdapteradapter = new vivcontentAdapter(this, data_content);
recyclerView.setAdapter(vivcontentAdapteradapter);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
}
class getData extends AsyncTask<Void, Void, String> {
ProgressDialog pDialog;
#Override
protected void onPreExecute() {
pDialog = new ProgressDialog(OpenSubContentActivity.this);
pDialog.setMessage("Fetching Content...");
pDialog.show();
pDialog.setCanceledOnTouchOutside(false);
}
#Override
protected String doInBackground(Void... voids) {
info_map = new HashMap();
String title = "";
String results = "";
int count = 0;
if (ObjectId.startsWith("0c")) {
Log.d("first", "coming");
CmisObject object = MainActivity.session.getObject(MainActivity.session.createObjectId(ObjectId));
Folder folder = (Folder) object;
//Document document = (Document)object;
OperationContext operationContext = MainActivity.session.createOperationContext();
ItemIterable<CmisObject> childrenn = folder.getChildren(operationContext);
ItemIterable<CmisObject> page = childrenn.getPage();
Iterator<CmisObject> pageItems = page.iterator();
while (pageItems.hasNext()) {
CmisObject item = null;
item = pageItems.next();
//System.out.println(item.getId());
if (item != null && item.getName() != null) {
if (item.getId().startsWith("0b")) {
Information info = new Information();
info.title = item.getName();
info.iconId = icons[0];
info.folderId_open_Id = item.getId();
title = title + "\n" + item.getName();
info_map.put(count, info.folderId_open_Id);
data_content.add(info);
count++;
}
return results;
}
#Override
protected void onPostExecute(String s) {
pDialog.dismiss();
vivcontentAdapteradapter.notifyDataSetChanged();
}
}
}
}
}
}
vivcontentAdapter
In this activity i am calling async task class of opensubcontentactivity.But while calling from here in progress dialog it is giving error in asynctask class getData()
Using -
OpenSubContentActivity openSubContentActivity=new OpenSubContentActivity();
openSubContentActivity.new getData().execute();
vivcontentAdapter
public class vivcontentAdapter extends RecyclerView.Adapter<vivcontentAdapter.MyViewHolder> {
private final LayoutInflater inflater;
List<Information> data_content = Collections.emptyList();
Context context;
public vivcontentAdapter(Context context, List<Information> data) {
this.context = context;
inflater = LayoutInflater.from(context);
this.data_content = data;
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = inflater.inflate(R.layout.customrow, parent, false);
MyViewHolder holder = new MyViewHolder(view);
return holder;
}
#Override
public void onBindViewHolder(final vivcontentAdapter.MyViewHolder holder, final int position) {
Information current = data_content.get(position);
holder.title.setText(current.title);
holder.icon.setImageResource(current.iconId);
holder.keyicon.setImageResource(current.checkin_icon);
holder.title.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String store_objectID = (String) OpenSubContentActivity.info_map.get(position);
if (store_objectID.startsWith("0b")) {
OpenSubContentActivity.top++;
OpenSubContentActivity.stack_info[OpenSubContentActivity.top] = store_objectID; OpenSubContentActivity.ObjectId = store_objectID;
OpenSubContentActivity openSubContentActivity=new OpenSubContentActivity();
openSubContentActivity.new getData().execute();
} else {
OpenSubContentActivity.ObjectId = store_objectID;
OpenSubContentActivity openSubContentActivity=new OpenSubContentActivity();
openSubContentActivity.new getData().execute();
}
Toast.makeText(context, "Open", Toast.LENGTH_SHORT).show();
}
});
holder.txtOptionDigit.setOnClickListener(new View.OnClickListener() {
#SuppressLint("RestrictedApi")
#Override
public void onClick(View v) {
//Display option menu
});
}
#Override
public int getItemCount() {
return data_content.size();
}
class MyViewHolder extends RecyclerView.ViewHolder {
TextView title, txtOptionDigit;
ImageView icon, keyicon;
public MyViewHolder(View itemView) {
super(itemView);
title = (TextView) itemView.findViewById(R.id.textvw);
icon = (ImageView) itemView.findViewById(R.id.imageView);
keyicon = (ImageView) itemView.findViewById(R.id.key_icon);
txtOptionDigit = (TextView) itemView.findViewById(R.id.txtOptionDigit);
}
}
}
}
Error-
03-30 00:21:40.690 10385-10385/reva.irving E/SpannableStringBuilder: SPAN_EXCLUSIVE_EXCLUSIVE spans cannot have a zero length
03-30 00:21:40.690 10385-10385/reva.irving E/SpannableStringBuilder: SPAN_EXCLUSIVE_EXCLUSIVE spans cannot have a zero length
03-30 00:22:04.228 10385-10385/reva.irving E/AndroidRuntime: FATAL EXCEPTION: main
Process: reva.irving, PID: 10385
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.app.ProgressDialog.setMessage(java.lang.CharSequence)' on a null object reference
at reva.irving.OpenSubContentActivity$getData.onPreExecute(OpenSubContentActivity.java:103)
at android.os.AsyncTask.executeOnExecutor(AsyncTask.java:620)
at android.os.AsyncTask.execute(AsyncTask.java:567)
at reva.irving.OpenSubContentActivity.call(OpenSubContentActivity.java:84)
at reva.irving.vivcontentAdapter$1.onClick(vivcontentAdapter.java:59)
at android.view.View.performClick(View.java:5647)
at android.view.View$PerformClick.run(View.java:22462)
at android.os.Handler.handleCallback(Handler.java:754)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:163)
at android.app.ActivityThread.main(ActivityThread.java:6205)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:904)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:794)
To perform clicks in a Recycler view you need to change your adapter. Add an interface to act as the click listener and implement it in your activity, like so:
public class vivcontentAdapter extends RecyclerView.Adapter<vivcontentAdapter.MyViewHolder> {
private final LayoutInflater inflater;
List<Information> data_content = Collections.emptyList();
Context context;
private OnClickItem clickListener;
public vivcontentAdapter(Context context, List<Information> data) {
this.context = context;
inflater = LayoutInflater.from(context);
this.data_content = data;
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = inflater.inflate(R.layout.customrow, parent, false);
MyViewHolder holder = new MyViewHolder(view);
return holder;
}
#Override
public void onBindViewHolder(final vivcontentAdapter.MyViewHolder holder, final int position) {
Information current = data_content.get(position);
holder.title.setText(current.title);
holder.icon.setImageResource(current.iconId);
holder.keyicon.setImageResource(current.checkin_icon);
holder.txtOptionDigit.setOnClickListener(new View.OnClickListener() {
#SuppressLint("RestrictedApi")
#Override
public void onClick(View v) {
//Display option menu
});
}
#Override
public int getItemCount() {
return data_content.size();
}
public void setClickListener(OnClickItem listener){
this.listener = listener;
}
class MyViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
TextView title, txtOptionDigit;
ImageView icon, keyicon;
public MyViewHolder(View itemView) {
super(itemView);
title = (TextView) itemView.findViewById(R.id.textvw);
icon = (ImageView) itemView.findViewById(R.id.imageView);
keyicon = (ImageView) itemView.findViewById(R.id.key_icon);
txtOptionDigit = (TextView) itemView.findViewById(R.id.txtOptionDigit);
itemView.setOnClickListener(this);
}
#Override
public void onClick(View v) {
int pos = getAdapterPosition();
listener.onClickListItem(pos);
}
}
public interface OnClickItem{
void onClickListItem(int position);
}
}
Now in your activity you can catch the cliicks and run the async task:
public class OpenSubContentActivity extends AppCompatActivity implements vivcontentAdapter.OnClickItem{
private RecyclerView recyclerView;
private vivcontentAdapter vivcontentAdapteradapter;
static String stack_info[] = new String[10];
static int top = -1;
static String ObjectId;
static List<Information> data_content = new ArrayList<>();
public static Map info_map = null;
Boolean file_flag;
File file;
Context context;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_open_sub_content);
setEveryThing();
Intent mIntent = getIntent();
context=this;
ObjectId = mIntent.getStringExtra("CabinetID");
new getData().execute();
}
public void setEveryThing() {
floatingActionMenu = (FloatingActionMenu) findViewById(R.id.floating_menu);
newfolder = (FloatingActionButton) findViewById(R.id.idtem__folder);
newdoc = (FloatingActionButton) findViewById(R.id.idtem_doc);
upload = (FloatingActionButton) findViewById(R.id.idtem_upload);
capture = (FloatingActionButton) findViewById(R.id.idtem_photo);
toolbar = (Toolbar) findViewById(R.id.toolBar);
toolbar.setTitleTextColor(0xFFFFFFFF);
setSupportActionBar(toolbar);
getSupportActionBar().setTitle(("Example"));
recyclerView = (RecyclerView) findViewById(R.id.list_file);
vivcontentAdapteradapter = new vivcontentAdapter(this, data_content);
vivcontentAdapteradapter.setClickListener(this);
recyclerView.setAdapter(vivcontentAdapteradapter);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
}
#Override
public void onClickListItem(int position){
new getData().execute();
}
class getData extends AsyncTask<Void, Void, String> {
ProgressDialog pDialog;
#Override
protected void onPreExecute() {
pDialog = new ProgressDialog(OpenSubContentActivity.this);
pDialog.setMessage("Fetching Content...");
pDialog.show();
pDialog.setCanceledOnTouchOutside(false);
}
#Override
protected String doInBackground(Void... voids) {
info_map = new HashMap();
String title = "";
String results = "";
int count = 0;
if (ObjectId.startsWith("0c")) {
Log.d("first", "coming");
CmisObject object = MainActivity.session.getObject(MainActivity.session.createObjectId(ObjectId));
Folder folder = (Folder) object;
//Document document = (Document)object;
OperationContext operationContext = MainActivity.session.createOperationContext();
ItemIterable<CmisObject> childrenn = folder.getChildren(operationContext);
ItemIterable<CmisObject> page = childrenn.getPage();
Iterator<CmisObject> pageItems = page.iterator();
while (pageItems.hasNext()) {
CmisObject item = null;
item = pageItems.next();
//System.out.println(item.getId());
if (item != null && item.getName() != null) {
if (item.getId().startsWith("0b")) {
Information info = new Information();
info.title = item.getName();
info.iconId = icons[0];
info.folderId_open_Id = item.getId();
title = title + "\n" + item.getName();
info_map.put(count, info.folderId_open_Id);
data_content.add(info);
count++;
}
return results;
}
#Override
protected void onPostExecute(String s) {
pDialog.dismiss();
vivcontentAdapteradapter.notifyDataSetChanged();
}
}
}

recycle view won't recieve a bundle data

i'm trying to pass a bundle from a product detail activity to a cart with a recycle view but when i click on add to cart the cart is opened but remains empty i don't know what's wrong with the code
here is the first activity
public class product_details extends AppCompatActivity {
ImageView product_img, share;
TextView name, price;
public int img;
public int price1;
public String name1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_product_details);
product_img = (ImageView) findViewById(R.id.Product_Img);
name = (TextView) findViewById(R.id.product_name);
price = (TextView) findViewById(R.id.product_price);
share = (ImageView) findViewById(R.id.share);
img = getIntent().getIntExtra("img", 00);
Glide.with(this).load(img).into(product_img);
name1 = getIntent().getStringExtra("name");
name.setText(name1);
price1 = getIntent().getIntExtra("price", 0);
price.setText(String.valueOf(price1));
ImageView cart = (ImageView) findViewById(R.id.add_cart);
cart.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(v.getContext(), CartActivity.class);
Bundle extras = new Bundle();
extras.putString("price1", String.valueOf((price1)));
extras.putString("name1", name1);
extras.putString("img1",String.valueOf(img));
intent.putExtras(extras);
startActivity(intent);
}
my second activity class
public class CartRecycler {
int images_id;
String productname,productprice,productquantity;
public String getProductquantity() {
return productquantity;
}
public CartRecycler(int images_id , String productname , String productprice , String productquantity){
this.setImages_id(images_id);
this.setProductname(productname);
this.setProductprice(productprice);
this.setProductquantity(productquantity);
}
public CartRecycler(String productname, int images_id, String productprice) {
this.productname = productname;
this.images_id = images_id;
this.productprice = productprice;
}
public int getImages_id() {
return images_id;
}
public void setImages_id(int images_id) {
this.images_id = images_id;
}
public String getProductname() {
return productname;
}
public void setProductname(String productname) {
this.productname = productname;
}
public String getProductprice() {
return productprice;
}
public void setProductprice(String productprice) {
this.productprice = productprice;
}
public void setProductquantity(String productquantity) {
this.productquantity = productquantity;
}
}
cart adapter
public class CartAdapter extends RecyclerView.Adapter<CartAdapter.CartViewHolder> {
ArrayList<CartRecycler> adapterlist = new ArrayList<>();
CartActivity cartactivity;
Context cnx;
public CartAdapter(ArrayList<CartRecycler> adapterlist,Context cnx){
this.adapterlist =adapterlist;
this.cnx =cnx;
cartactivity = (CartActivity) cnx;
}
#Override
public CartViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.cart_cards,parent,false);
CartViewHolder cartviewholder = new CartViewHolder(v,cartactivity);
return cartviewholder;
}
#Override
public void onBindViewHolder(CartViewHolder holder, int position) {
holder.image.setImageResource(adapterlist.get(position).getImages_id());
holder.name.setText(adapterlist.get(position).getProductname());
holder.price.setText(adapterlist.get(position).getProductprice());
holder.quantity.setText(adapterlist.get(position).getProductquantity());
if(!cartactivity.edit_mode){
holder.checkornot.setVisibility(View.GONE);
}
else {
holder.checkornot.setVisibility(View.VISIBLE);
holder.checkornot.setChecked(false);
}
}
#Override
public int getItemCount() {
return adapterlist.size();
}
public static class CartViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
ImageView image;
TextView price,quantity,name;
CheckBox checkornot;
CartActivity cartactivity;
CardView cardv;
public CartViewHolder(View itemView, CartActivity cartactivity) {
super(itemView);
image = (ImageView) itemView.findViewById(R.id.cartimage);
name = (TextView) itemView.findViewById(R.id.pn);
price = (TextView) itemView.findViewById(R.id.p);
quantity = (TextView) itemView.findViewById(R.id.q);
checkornot = (CheckBox) itemView.findViewById(R.id.ckbox);
this.cartactivity= cartactivity;
cardv = (CardView) itemView.findViewById(R.id.cardd);
cardv.setOnLongClickListener((View.OnLongClickListener) cartactivity);
checkornot.setOnClickListener(this);
}
#Override
public void onClick(View view) {
cartactivity.prepareselection(view,getAdapterPosition());
}
}
public void updateadapter(ArrayList<CartRecycler> list){
for(CartRecycler cartRecycler:list){
adapterlist.remove(cartRecycler);
}
notifyDataSetChanged();
}
}
second activity
public class CartActivity extends AppCompatActivity implements View.OnLongClickListener{
Button l;
ImageView imv;
Toolbar t;
RecyclerView rv;
RecyclerView.LayoutManager layoutmanager;
RecyclerView.Adapter adapter;
ArrayList<CartRecycler> cartitems = new ArrayList<>();
ArrayList<CartRecycler> selected_items_list = new ArrayList<>();
int countt =0;
boolean edit_mode =false;
TextView counterr;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_cart);
t = (Toolbar) findViewById(R.id.toolb);
setSupportActionBar(t);
getSupportActionBar().setDisplayShowTitleEnabled(false);
l = (Button) findViewById(R.id.checkoutsummary);
l.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent n = new Intent(CartActivity.this,SummaryActivity.class);
startActivity(n);
}
});
rv = (RecyclerView) findViewById(R.id.mycartrecycler);
layoutmanager = new LinearLayoutManager(this);
rv.setLayoutManager(layoutmanager);
rv.setHasFixedSize(true);
Bundle extras = getIntent().getExtras();
if (extras != null) {
String price = extras.getString("price1");
String img1 = extras.getString("img1");
int imag1 = Integer.parseInt(img1);
String name = extras.getString("name1");
for (int i = 0; i < cartitems.size(); i++) {
CartRecycler cart = new CartRecycler(name, imag1, price);
cartitems.add(cart);
adapter.notifyDataSetChanged();
i++;
}
} else {
Intent intent = new Intent(this, test.class);
startActivity(intent);
}
adapter = new CartAdapter(cartitems,CartActivity.this);
rv.setAdapter(adapter);
counterr = (TextView) findViewById(R.id.selecteditemcounter);
counterr.setVisibility(View.GONE);
}
#Override
public boolean onLongClick(View view) {
t.getMenu().clear();
t.inflateMenu(R.menu.cart_edit_mode);
counterr.setVisibility(View.VISIBLE);
edit_mode = true;
adapter.notifyDataSetChanged();
return true;
}
public void prepareselection(View view,int position){
if(((CheckBox)view).isChecked()){
selected_items_list.add(cartitems.get(position));
countt = countt+1;
updatecounter(countt);
}
else {
selected_items_list.remove(cartitems.get(position));
countt = countt -1;
updatecounter(countt);
}
}
public void updatecounter(int counter){
if(counter==0){
counterr.setText("0 items selected");
}
else {
counterr.setText(counter+" item selected");
}
}
public boolean onOptionsItemSelected(MenuItem item){
if(item.getItemId()==R.id.item_delete){
CartAdapter cartAdapter = (CartAdapter) adapter;
cartAdapter.updateadapter(selected_items_list);
}
else if(item.getItemId()== android.R.id.home)
{
adapter.notifyDataSetChanged();
}
return true;
}
}
for (int i = 0; i < cartitems.size(); i++) This loop will not run until and unless size of cartitems is greater than 0 and hence all the code under it's scope will never get executed

RecyclerView notifyDatasetChanged not working

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

Categories

Resources