Can't start Activity from Recycler Adapter - android

I tried to find solution, but my weak programming skills didn't help me to solve problem.
import android.content.Context;
import android.content.Intent;
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 com.squareup.picasso.Picasso;
import java.util.ArrayList;
import java.util.List;
public class GridAdapter extends RecyclerView.Adapter<GridAdapter.ViewHolder> {
List<HeroItem> mItems;
Context mContext;
MyOnItemClickListener listener;
public GridAdapter(Context context) {
super();
this.mContext = context;
mItems = new ArrayList<HeroItem>();
HeroItem species = new HeroItem();
//species.setName("Amur Leopard");
species.setThumbnail(R.drawable.test1);
mItems.add(species);
species = new HeroItem();
//species.setName("Black Rhino");
species.setThumbnail(R.drawable.test2);
mItems.add(species);
species = new HeroItem();
//species.setName("Orangutan");
species.setThumbnail(R.drawable.test3);
mItems.add(species);
species = new HeroItem();
//species.setName("Sea Lions");
species.setThumbnail(R.drawable.test4);
mItems.add(species);
species = new HeroItem();
//species.setName("Indian Elephant");
species.setThumbnail(R.drawable.test5);
mItems.add(species);
species = new HeroItem();
// species.setName("Giant Panda");
species.setThumbnail(R.drawable.test6);
mItems.add(species);
species = new HeroItem();
//species.setName("Snow Leopard");
species.setThumbnail(R.drawable.test1);
mItems.add(species);
species = new HeroItem();
//species.setName("Dolphin");
species.setThumbnail(R.drawable.test1);
mItems.add(species);
}
#Override
public GridAdapter.ViewHolder onCreateViewHolder(ViewGroup viewGroup, final int i) {
View v = LayoutInflater.from(viewGroup.getContext())
.inflate(R.layout.grid_item, viewGroup, false);
return new ViewHolder(v);
}
#Override
public void onBindViewHolder(ViewHolder viewHolder, final int position) {
HeroItem nature = mItems.get(position);
//viewHolder.tvspecies.setText(nature.getName());
//viewHolder.imgThumbnail.setImageResource(nature.getThumbnail());
Picasso.with(mContext)
.load(nature.getThumbnail())
.into(viewHolder.imgThumbnail);
viewHolder.setListener(new MyOnItemClickListener() {
#Override
public void MyOnClickListener(int position) {
//Log.d("Click","Position: " + position);
switch (position) {
case 0:
Intent intent = new Intent(mContext, Wolverine.class);
mContext.startActivity(intent);
break;
}
}
});
}
#Override
public int getItemCount() {
return mItems.size();
}
class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
public ImageView imgThumbnail;
//public TextView tvspecies;
public ViewHolder(View itemView) {
super(itemView);
imgThumbnail = (ImageView) itemView.findViewById(R.id.photoView);
//tvspecies = (TextView)itemView.findViewById(R.id.tv_species);
itemView.setOnClickListener(this);
}
#Override
public void onClick(View v) {
listener.MyOnClickListener(getAdapterPosition());
}
public void setListener(MyOnItemClickListener onItemClick) {
listener = onItemClick;
}
}
public interface MyOnItemClickListener {
void MyOnClickListener(int position);
}
}
So, I wrote my own listener that needs position of the item, as you can see. I have no problems with showing position in logs Log.d("Click","Position: " + position); , but I still can't to start new Activity.
And here is code of my fragment Activity that uses adapter
import android.graphics.Point;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.DisplayMetrics;
import android.view.Display;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
public class TabHero extends Fragment {
RecyclerView mRecyclerView;
RecyclerView.LayoutManager mLayoutManager;
RecyclerView.Adapter mAdapter;
int widthRecycler,widthScreen,padding;
public static TabHero newInstance() {
Bundle args = new Bundle();
TabHero fragment = new TabHero();
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.tab_hero, container, false);
// Calling the RecyclerView
mRecyclerView = (RecyclerView) v.findViewById(R.id.recycler_view);
mRecyclerView.setHasFixedSize(true);
// The number of Columns
mLayoutManager = new GridLayoutManager(getActivity(), 2);
mRecyclerView.setLayoutManager(mLayoutManager);
mAdapter = new GridAdapter(getContext());
mRecyclerView.setAdapter(mAdapter);
return v;
}
}
What I do wrong?

itemViewHolder.CategoryItem.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i=new Intent(context, SubcatogaryActivity.class);
i.putExtra("id",Integer.toString(received_dataList.get(position).getId()));
context.startActivity(i);
}
});

Related

How to get data from one RecyclerView and show it in another Activity's RecyclerView

I have an Android nested recycler view in which I am able to show the data now I want to show that data in another activity recycler view. How can I do that?
This is my nested list view:-
This is where I want to show data in list:-
Here's my code: my Main Activity:-
package com.saikari.vid.activities;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import com.saikari.vid.R;
import com.saikari.vid.adapters.VerticalRVAdapter;
import com.saikari.vid.models.HorizontalModel;
import com.saikari.vid.models.VerticalModel;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
public class MainActivity extends AppCompatActivity {
private DatabaseReference dbCategories;
VerticalRVAdapter adapter;
RecyclerView verticalRecyclerView;
ArrayList<VerticalModel> mListData = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
verticalRecyclerView = findViewById(R.id.recycler_view);
verticalRecyclerView.setHasFixedSize(true);
setData();
}
private void setData() {
for (int i = 0; i<10; i++){
VerticalModel verticalModel = new VerticalModel();
verticalModel.setCat_title("Title: "+i);
ArrayList<HorizontalModel> arrayListHorizontal = new ArrayList<>();
for (int j = 0; j<10; j++){
HorizontalModel horizontalModel = new HorizontalModel();
horizontalModel.setVid_url("https://picsum.photos/seed/picsum/200/300");
horizontalModel.setVid_title("Name: "+j);
arrayListHorizontal.add(horizontalModel);
}
verticalModel.setVidArrayList(arrayListHorizontal);
mListData.add(verticalModel);
}
adapter.notifyDataSetChanged();
}
}
Vertical RecyclerView adapter class:-
public class VerticalRVAdapter extends RecyclerView.Adapter<VerticalRVAdapter.VerticalRVViewHolder> {
Context context;
ArrayList<VerticalModel> arrayList;
public VerticalRVAdapter(Context context, ArrayList<VerticalModel> arrayList){
this.arrayList = arrayList;
this.context = context;
}
#NonNull
#Override
public VerticalRVViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_vertical,parent,false);
return new VerticalRVViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull VerticalRVViewHolder holder, int position) {
final VerticalModel verticalModel = arrayList.get(position);
String title = verticalModel.getCat_title();
final ArrayList<HorizontalModel> singleItem = verticalModel.getVidArrayList();
holder.titleText.setText(title);
HorizontalRVAdapter horizontalRecyclerViewAdapter= new HorizontalRVAdapter(context,singleItem);
holder.recyclerView.setHasFixedSize(true);
holder.recyclerView.setLayoutManager(new LinearLayoutManager(context,LinearLayoutManager.HORIZONTAL,false));
holder.recyclerView.setAdapter(horizontalRecyclerViewAdapter);
holder.buttonMore.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(context, verticalModel.getCat_title(), Toast.LENGTH_SHORT).show();
Intent i = new Intent(context, VideoListActivity.class);
i.putExtra("catTitle", verticalModel.getCat_title());
context.startActivity(i);
}
});
}
#Override
public int getItemCount() {
return arrayList.size();
}
public class VerticalRVViewHolder extends RecyclerView.ViewHolder{
RecyclerView recyclerView;
TextView titleText;
TextView buttonMore;
public VerticalRVViewHolder(#NonNull View itemView) {
super(itemView);
recyclerView = itemView.findViewById(R.id.recycler_view1);
titleText = itemView.findViewById(R.id.titleText);
buttonMore = itemView.findViewById(R.id.btn_more);
}
}
}
Horizontal Recycler View Adapter class:-
public class HorizontalRVAdapter extends RecyclerView.Adapter<HorizontalRVAdapter.HorizontalRVViewHolder> {
Context context;
ArrayList<HorizontalModel> arrayList;
public HorizontalRVAdapter(Context context, ArrayList<HorizontalModel> arrayList) {
this.context = context;
this.arrayList = arrayList;
}
#NonNull
#Override
public HorizontalRVViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_horizontal,parent,false);
return new HorizontalRVViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull final HorizontalRVViewHolder holder, int position) {
final HorizontalModel horizontalModel = arrayList.get(position);
holder.textViewTitle.setText(horizontalModel.getVid_title());
com.bumptech.glide.Glide.with(context).load(horizontalModel.getVid_url()).into(holder.imageViewThumb);
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(context, horizontalModel.getVid_url(), Toast.LENGTH_SHORT).show();
Intent i = new Intent(context, YoutubePlayActivity.class);
i.putExtra("videoID", horizontalModel.getVid_url());
context.startActivity(i);
}
});
}
#Override
public int getItemCount() {
return arrayList.size();
}
public class HorizontalRVViewHolder extends RecyclerView.ViewHolder{
TextView textViewTitle;
ImageView imageViewThumb;
public HorizontalRVViewHolder(#NonNull View itemView) {
super(itemView);
textViewTitle = itemView.findViewById(R.id.textTitleHorizontal);
imageViewThumb = itemView.findViewById(R.id.ivThumb);
}
}
}
Data in list activity class (this is the activity where I need to show data):-
public class VideoListActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_video_list);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setTitle(getIntent().getStringExtra("catTitle"));
}
}
Implement Parcelable on HorizontalModel class. If you need help with that check here.
In VerticalRVAdapter inside onBindViewHolder method
holder.buttonMore.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(context, verticalModel.getCat_title(), Toast.LENGTH_SHORT).show();
Intent i = new Intent(context, VideoListActivity.class);
i.putExtra("catTitle", verticalModel.getCat_title());
// Put horizontal models in extra bundle
i.putParcelableArrayListExtra("horizontal_models", singleItem);
context.startActivity(i);
}
});
You can now get the bundled HorizontalModel list in VideoListActivity inside onCreate as
ArrayList<HorizontalModel> horizontalModels = getIntent().getParcelableArrayListExtra("horizontal_models");
You can use this list to populate the vertical list that you want to show.

RecyclerView Adapter List<E> get 0

I am new in android development. I am getting a problem, I have create simple application in which I have RecyclerView in MainActivity. I try to Drag and Drop position. But when I move from MainActivity to CompleteList_activity and come to again MainActivity and try to Drag and drop i got ArrayOutOfBound error because List value get 0 in
public void positionchange(int fromPosition, int toPosition) method.
MainActivity :
package com.example.marmeto.todolist;
import android.content.Intent;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.helper.ItemTouchHelper;
import android.view.View;
import android.widget.ImageButton;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
public class MainActivity extends AppCompatActivity implements View.OnClickListener{
DBHelper db;
ImageButton btn_addtodolist,btn_completelist;
List<Model> todolist = new ArrayList<>();
List<Model> adapterList = new ArrayList<>();
private RecyclerView recyclerView;
private RecyclerView.LayoutManager layoutManager;
private ToDoList_Adapter adapter;
public static final int NEW_WORD_ACTIVITY_REQUEST_CODE = 1;
Model mToDOItemList = new Model();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
db = new DBHelper(this);
recyclerView = (RecyclerView)findViewById(R.id.recyclerview);
recyclerView.setHasFixedSize(true);
layoutManager = new LinearLayoutManager(getApplicationContext());
recyclerView.setLayoutManager(layoutManager);
btn_addtodolist = (ImageButton) findViewById(R.id.btn_addtodolist);
btn_completelist = (ImageButton)findViewById(R.id.btn_completedlist);
btn_addtodolist.setOnClickListener(this);
btn_completelist.setOnClickListener(this);
getValue();
}
void getValue(){
todolist.clear();
todolist = db.getUserDetail();
Collections.sort(todolist, new Comparator<Model>() {
#Override public int compare(Model p1, Model p2) {
return p1.getPosition()- p2.getPosition(); // Ascending
}
});
adapter = new ToDoList_Adapter(todolist,getApplicationContext());
ItemTouchHelper.SimpleCallback callback=new SwipItem(adapter);
ItemTouchHelper helper=new ItemTouchHelper(callback);
helper.attachToRecyclerView(recyclerView);
recyclerView.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
#Override
protected void onResume() {
super.onResume();
}
#Override
protected void onPause() {
super.onPause();
}
#Override
public void onClick(View v) {
if (v.getId() == R.id.btn_addtodolist) {
Intent intent = new Intent(getApplicationContext(), AddToDoList_Activity.class);
startActivity(intent);
} else {
Intent intent = new Intent(getApplicationContext(),CompletedActivity.class);
startActivity(intent);
}
}
}
AdapterClass:
package com.example.marmeto.todolist;
import android.content.Context;
import android.support.annotation.NonNull;
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.Button;
import android.widget.TextView;
import android.widget.Toast;
import java.util.Collections;import java.util.List;
public class ToDoList_Adapter extends RecyclerView.Adapter<ToDoList_Adapter.ViewHolder> {
List<Model> items;
private Context context;
public ToDoList_Adapter(List<Model> items, Context context) {
this.items = items;
this.context = context;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext())
.inflate(R.layout.todolist_adapter, parent, false);
ViewHolder viewHolder = new ViewHolder(v);
return viewHolder;
}
#Override
public void onBindViewHolder(ViewHolder holder, final int position) {
final Model itemlist = items.get(position);
holder.todoText.setText(itemlist.getPosition()+" "+itemlist.getTitle());
}
#Override
public int getItemCount() {
return items.size();
}
public void positionchange(int fromPosition, int toPosition)
{
try {
Collections.swap(items,fromPosition,toPosition);
DBHelper db = new DBHelper(context);
db.updateList(items);
}catch (Exception e)
{
e.printStackTrace();
}
this.notifyItemMoved(fromPosition,toPosition);
}
public void deletePlanet(int pos)
{
//GET ID
try {
Model p = items.get(pos);
int id = p.getId();
//DELETE FROM DB
DBHelper db = new DBHelper(context);
if (db.delete(id)) {
items.remove(pos);
db.updateList(items);
} else {
Toast.makeText(context, "Unable To Delete", Toast.LENGTH_SHORT).show();
}
this.notifyItemRemoved(pos);
}catch (Exception e){
e.printStackTrace();
}
}
class ViewHolder extends RecyclerView.ViewHolder {
public TextView todoText;
public Button btn_done;
public ViewHolder(final View itemView) {
super(itemView);
todoText = (TextView)itemView.findViewById(R.id.todoItem_text);
btn_done = (Button)itemView.findViewById(R.id.btn_done);
btn_done.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
DBHelper db = new DBHelper(context);
try {
Model p = items.get(getAdapterPosition());
db.updateData(p.getId());
items.remove(getAdapterPosition());
db.updateList(items);
}catch (Exception e){
e.printStackTrace();
}
notifyItemRemoved(getAdapterPosition());
}
});
}
}
}
Thanks in advance to help.
You call your getValue() and so you populate your data into onCreate. But when you pass to a new Activity and then you go back to the previous activity onCreate method is not called again.
Try calling your getValue() into your onResume method
Look at there Activity lifecycle

Swipe left or right in RecyclerView

I try to add a swipe left or right to my RecyclerView List, but I don't know what I'm doing wrong. I've tried a lot of working solutions but they don't work for me.
This is my Fragment:
import android.app.Fragment;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.LinearSnapHelper;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;
import java.util.ArrayList;
import de.christian_heinisch.studenttodo.adapters.ToDoListRecyclerViewAdapter;
import de.christian_heinisch.studenttodo.database.ToDo;
import de.christian_heinisch.studenttodo.database.ToDoDataSource;
/**
* A simple {#link Fragment} subclass.
*/
public class ToDoFragment_RV extends Fragment {
View rootview;
private ToDoDataSource dataSource_todo;
private RecyclerView mRecyclerView;
private RecyclerView new_mRecyclerView;
private RecyclerView.Adapter mAdapter;
private RecyclerView.LayoutManager mLayoutManager;
private RecyclerView.LayoutManager new_mLayoutManager;
private static String LOG_TAG = "RecyclerViewActivity";
public ToDoFragment_RV() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
rootview = inflater.inflate(R.layout.fragment_to_do_rv, container, false);
mRecyclerView = (RecyclerView) rootview.findViewById(R.id.rv);
mRecyclerView.setHasFixedSize(true);
LinearSnapHelper snapHelper = new LinearSnapHelper();
snapHelper.attachToRecyclerView(mRecyclerView);
mLayoutManager = new LinearLayoutManager(getContext());
mRecyclerView.setLayoutManager(mLayoutManager);
mAdapter = new ToDoListRecyclerViewAdapter(getContext(), getDataSet());
mRecyclerView.setAdapter(mAdapter);
mRecyclerView.setOnFlingListener(snapHelper);
RecyclerView.ItemDecoration itemDecoration =
new DividerItemDecoration(getContext(), LinearLayoutManager.VERTICAL);
mRecyclerView.addItemDecoration(itemDecoration);
new_mRecyclerView = (RecyclerView) rootview.findViewById(R.id.rv_checked);
new_mRecyclerView.setHasFixedSize(true);
new_mLayoutManager = new LinearLayoutManager(getContext());
new_mRecyclerView.setLayoutManager(new_mLayoutManager);
mAdapter = new ToDoListRecyclerViewAdapter(getContext(), getDataSet_checked());
new_mRecyclerView.setAdapter(mAdapter);
RecyclerView.ItemDecoration newitemDecoration =
new DividerItemDecoration(getContext(), LinearLayoutManager.VERTICAL);
new_mRecyclerView.addItemDecoration(newitemDecoration);
// setHasOptionsMenu(true);
FloatingActionButton fab = (FloatingActionButton) rootview.findViewById(R.id.fbToDoAdd);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
((StartActivity)getContext()).DialogAddToDO();
}
});
return rootview;
}
private ArrayList<ToDo> getDataSet() {
dataSource_todo = new ToDoDataSource(getContext());
dataSource_todo.open();
ArrayList<ToDo> arrayOfToDo = null;
arrayOfToDo = dataSource_todo.getToDoForList("false");
dataSource_todo.close();
return arrayOfToDo;
}
private ArrayList<ToDo> getDataSet_checked() {
dataSource_todo = new ToDoDataSource(getContext());
dataSource_todo.open();
ArrayList<ToDo> arrayOfToDo = null;
arrayOfToDo = dataSource_todo.getToDoForList("true");
dataSource_todo.close();
return arrayOfToDo;
}
}
This is my RecyclerView Adapter
import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.text.format.DateFormat;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Locale;
import de.christian_heinisch.studenttodo.R;
import de.christian_heinisch.studenttodo.StartActivity;
import de.christian_heinisch.studenttodo.ToDoFragment_RV;
import de.christian_heinisch.studenttodo.database.ToDo;
import de.christian_heinisch.studenttodo.database.ToDoDataSource;
/**
* Created by chris on 16.06.2017.
*/
public class ToDoListRecyclerViewAdapter extends RecyclerView
.Adapter<ToDoListRecyclerViewAdapter
.DataObjectHolder> {
private ArrayList<ToDo> mDataset;
private static MyClickListener myClickListener;
private Context mContext;
ToDoDataSource dataSource = new ToDoDataSource(mContext);
public static class DataObjectHolder extends RecyclerView.ViewHolder
implements View
.OnClickListener {
TextView label;
TextView dateTime;
CheckBox checked;
public DataObjectHolder(View itemView) {
super(itemView);
label = (TextView) itemView.findViewById(R.id.textView_item_todolist_content);
dateTime = (TextView) itemView.findViewById(R.id.textView_item_todolist_Date);
checked = (CheckBox) itemView.findViewById(R.id.cbToDo);
//itemView.setOnClickListener(this);
}
#Override
public void onClick(View v) {
myClickListener.onItemClick(getPosition(), v);
}
}
public void setOnItemClickListener(MyClickListener myClickListener) {
this.myClickListener = myClickListener;
}
public ToDoListRecyclerViewAdapter(Context context, ArrayList<ToDo> myDataset) {
mDataset = myDataset;
mContext = context;
}
#Override
public DataObjectHolder onCreateViewHolder(ViewGroup parent,
int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.item_todolist, parent, false);
DataObjectHolder dataObjectHolder = new DataObjectHolder(view);
return dataObjectHolder;
}
#Override
public void onBindViewHolder(final DataObjectHolder holder, final int position) {
holder.label.setText(mDataset.get(position).getToDo());
holder.dateTime.setText(getDate(mDataset.get(position).isDate()));
if(mDataset.get(position).isChecked().equalsIgnoreCase("true")){
holder.checked.toggle();
}
holder.itemView.setOnTouchListener(new View.OnTouchListener() {
float _xSwipe1;
float _xSwipe2;
#Override
public boolean onTouch(View v, MotionEvent event)
{
switch (event.getAction())
{
case MotionEvent.ACTION_DOWN:
_xSwipe1 = event.getX();
break;
case MotionEvent.ACTION_UP:
_xSwipe2 = event.getX();
float deltaX = _xSwipe2 - _xSwipe1;
if (deltaX < 0)
{
Log.e("SWIPE", "Right to Left swipe");
}
else if (deltaX >0)
{
Log.e("SWIPE", "Left to right swipe");
}
break;
}
return false;
}
});
// Set onClicklistener
holder.label.setOnLongClickListener(new View.OnLongClickListener() {
public boolean onLongClick(View view) {
System.out.println("Position " + position);
edit(mDataset.get(position).getId());
//notifyDataSetChanged();
return false;
}
});
holder.dateTime.setOnLongClickListener(new View.OnLongClickListener() {
public boolean onLongClick(View view) {
edit(mDataset.get(position).getId());
return false;
}
});
holder.checked.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dataSource = new ToDoDataSource(mContext);
dataSource.open();
// TODO Auto-generated method stub
if(holder.checked.isChecked()){
System.out.println("Checked");
dataSource.updateToDo(mDataset.get(position).getId(), mDataset.get(position).getToDo(), "true", mDataset.get(position).isDate());
}else{
System.out.println("un-Checked");
dataSource.updateToDo(mDataset.get(position).getId(), mDataset.get(position).getToDo(), "false", mDataset.get(position).isDate());
}
dataSource.close();
}
});
}
public void addItem(ToDo dataObj, int index) {
mDataset.add(dataObj);
notifyItemInserted(index);
}
public void deleteItem(int index) {
mDataset.remove(index);
notifyItemRemoved(index);
}
#Override
public int getItemCount() {
return mDataset.size();
}
public interface MyClickListener {
public void onItemClick(int position, View v);
}
private String getDate(long time) {
Calendar cal = Calendar.getInstance(Locale.GERMAN);
cal.setTimeInMillis(time);
String date = DateFormat.format("dd.MM.yyyy", cal).toString();
return date;
}
private void edit(long l){
((StartActivity)mContext).DialogEditToDO(l);
}
}
Return true on case MotionEvent.ACTION_DOWN may resolve your issue.

Save, Share & Favourite Imageview in recyclerview

this codes contains a share button, download button, and a favourate button.
till now its working properly with favourate button, if i remove onClick method from ViewHolder.
I want to implement share/save button onClick share/download the Image in the ImageView in recyclerview.
Please ignore gramatical mistakes
This is my cardFragment Class.
import android.content.ContentResolver;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
public class CardFragment extends Fragment {
ArrayList<WonderModel> listitems = new ArrayList<>();
RecyclerView MyRecyclerView;
String Wonders[] = {"Chichen Itza","Christ the Redeemer","Great Wall of China","Machu Picchu","Petra","Taj Mahal","Colosseum"};
int Images[] = {R.drawable.chichen_itza,R.drawable.christ_the_redeemer,R.drawable.great_wall_of_china,R.drawable.machu_picchu,R.drawable.petra,R.drawable.taj_mahal,R.drawable.colosseum};
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
initializeList();
getActivity().setTitle("7 Wonders of the Modern World");
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_card, container, false);
MyRecyclerView = (RecyclerView) view.findViewById(R.id.cardView);
MyRecyclerView.setHasFixedSize(true);
LinearLayoutManager MyLayoutManager = new LinearLayoutManager(getActivity());
MyLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
if (listitems.size() > 0 & MyRecyclerView != null) {
MyRecyclerView.setAdapter(new MyAdapter(listitems));
}
MyRecyclerView.setLayoutManager(MyLayoutManager);
return view;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
}
public class MyAdapter extends RecyclerView.Adapter<MyViewHolder> {
private ArrayList<WonderModel> list;
public MyAdapter(ArrayList<WonderModel> Data) {
list = Data;
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent,int viewType) {
// create a new view
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.recycle_items, parent, false);
MyViewHolder holder = new MyViewHolder(view);
return holder;
}
#Override
public void onBindViewHolder(final MyViewHolder holder, int position) {
holder.titleTextView.setText(list.get(position).getCardName());
holder.coverImageView.setImageResource(list.get(position).getImageResourceId());
holder.coverImageView.setTag(list.get(position).getImageResourceId());
holder.likeImageView.setTag(R.drawable.ic_like);
}
#Override
public int getItemCount() {
return list.size();
}
}
public class MyViewHolder extends RecyclerView.ViewHolder {
public TextView titleTextView;
public ImageView coverImageView;
public ImageView likeImageView;
public ImageView shareImageView;
public MyViewHolder(View v) {
super(v);
titleTextView = (TextView) v.findViewById(R.id.titleTextView);
coverImageView = (ImageView) v.findViewById(R.id.coverImageView);
likeImageView = (ImageView) v.findViewById(R.id.likeImageView);
shareImageView = (ImageView) v.findViewById(R.id.shareImageView);
likeImageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int id = (int)likeImageView.getTag();
if( id == R.drawable.ic_like){
likeImageView.setTag(R.drawable.ic_liked);
likeImageView.setImageResource(R.drawable.ic_liked);
Toast.makeText(getActivity(),titleTextView.getText()+" added to favourites",Toast.LENGTH_SHORT).show();
}else{
likeImageView.setTag(R.drawable.ic_like);
likeImageView.setImageResource(R.drawable.ic_like);
Toast.makeText(getActivity(),titleTextView.getText()+" removed from favourites",Toast.LENGTH_SHORT).show();
}
}
});
shareImageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Uri imageUri = Uri.parse(ContentResolver.SCHEME_ANDROID_RESOURCE +
"://" + getResources().getResourcePackageName(coverImageView.getId())
+ '/' + "drawable" + '/' + getResources().getResourceEntryName((int)coverImageView.getTag()));
Intent shareIntent = new Intent();
shareIntent.setAction(Intent.ACTION_SEND);
shareIntent.putExtra(Intent.EXTRA_STREAM,imageUri);
shareIntent.setType("image/jpeg");
startActivity(Intent.createChooser(shareIntent, getResources().getText(R.string.send_to)));
}
});
}
}
public void initializeList() {
listitems.clear();
for(int i =0;i<7;i++){
WonderModel item = new WonderModel();
item.setCardName(Wonders[i]);
item.setImageResourceId(Images[i]);
item.setIsfav(0);
item.setIsturned(0);
listitems.add(item);
}
}
}
Here is MainActivity.Java
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v7.app.AppCompatActivity;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
FragmentManager fm = getSupportFragmentManager();
Fragment fragment = fm.findFragmentById(R.id.fragmentContainer);
if (fragment == null) {
fragment = new CardFragment();
;
fm.beginTransaction()
.add(R.id.fragmentContainer, fragment)
.commit();
}
}
}
Create your ViewHolder Constructor Like this
public MyViewHolder(View v,Activity activity) {
super(v);
this.activity = activity
/////Remaining code
Now you able to get the activity context in your viewholder class.
Hope it will helps you!!

recycler view GridLayoutManager first row is one less than others

hi i have a recyclerview with GridLayoutManager that have 3 cols but in the first row just shows 2 items like this :
where i was wrong in this codes :
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.GridLayoutManager;
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 com.github.florent37.materialviewpager.MaterialViewPagerHelper;
import com.github.florent37.materialviewpager.adapter.RecyclerViewMaterialAdapter;
import java.util.ArrayList;
import java.util.List;
public class Main_Recycle6 extends Fragment {
private RecyclerView recyclerView;
private Main_Recycle_Adapter2 movieRecyclerviewAdapter;
private List<Main> movies;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
return inflater.inflate(R.layout.main_grid4, container, false);
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
movies = new ArrayList<>();
recyclerView = (RecyclerView) getView().findViewById(R.id.Recycle1);
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
// recyclerView.setNestedScrollingEnabled(false);
RecyclerView.LayoutManager layoutManager;
layoutManager = new GridLayoutManager(getActivity(), 3);
recyclerView.setLayoutManager(layoutManager);
movies = getData();
movieRecyclerviewAdapter = new Main_Recycle_Adapter2 (getActivity(), movies);
recyclerView.setAdapter(movieRecyclerviewAdapter);
RecyclerViewMaterialAdapter movieRecyclerviewAdapterMaterial = new RecyclerViewMaterialAdapter(movieRecyclerviewAdapter);
// 4. set adapter
recyclerView.setAdapter(movieRecyclerviewAdapterMaterial);
//5. Register the recyclerview to MaterialViewPager
MaterialViewPagerHelper.registerRecyclerView(getActivity(), recyclerView, null);
}
public static Main_Recycle newInstance() {
return new Main_Recycle();
}
private List<Main> getData() {
List<Main> movies = new ArrayList<>();
String names[] = { "آزمون 1",
"آزمون 2",
.....
};
String logos[] = {"i1",
"i2",
.....
};
for (int i = 0; i < names.length; i++) {
Main newMovie = new Main(names[i], logos[i]);
movies.add(newMovie);
}
return movies;
}
adapter :
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import java.util.Collections;
import java.util.List;
public class Main_Recycle_Adapter2 extends RecyclerView.Adapter<Main_Recycle_Adapter2.MovieViewHolder> {
List<Main> movies = Collections.emptyList();
LayoutInflater layoutInflater;
Context context;
public Main_Recycle_Adapter2(Context context, List<Main> movies){
this.context = context;
layoutInflater = LayoutInflater.from(context);
this.movies = movies;
}
//;;;;;;;;;;;;;;
#Override
public int getItemCount() {
return movies.size();
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public MovieViewHolder onCreateViewHolder(ViewGroup parent, int viewType )
{
View row;
row = layoutInflater.inflate(R.layout.gridview_custom_layout, parent, false);
MovieViewHolder holder = new MovieViewHolder(row);
return holder;
}
#Override
public void onBindViewHolder(MovieViewHolder holder, int position) {
Main thisMovie = movies.get(position);
holder.tozih.setText(thisMovie.getName());
holder.tablooo.setImageResource(context.getResources().getIdentifier(thisMovie.getLogo(), "drawable", context.getPackageName()));
}
public class MovieViewHolder extends RecyclerView.ViewHolder {
private TextView tozih;
private ImageView tablooo;
public MovieViewHolder(View itemView) {
super(itemView);
tozih = (TextView) itemView.findViewById(R.id.gridview_text);
tablooo = (ImageView) itemView.findViewById(R.id.gridview_image);
}
}
}
here is the grid code
the recyclerview is in a fragment and the fragment is in another activity
RecyclerView.LayoutManager layoutManager;
layoutManager = new GridLayoutManager(getActivity(), 3);
recyclerView.setLayoutManager(layoutManager);
thanks in advance

Categories

Resources