Suppose I have a scrolling RecyclerView (where images scrolling Horizontally) after clicking any of images it will appear below the recyclerView.
Main Activity:
package com.aariyan.testm;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;`enter code here`
import com.daimajia.slider.library.Animations.DescriptionAnimation;
import com.daimajia.slider.library.Indicators.PagerIndicator;
import com.daimajia.slider.library.SliderLayout;`enter code here`
import com.daimajia.slider.library.SliderTypes.BaseSliderView;
import com.daimajia.slider.library.SliderTypes.TextSliderView;
import com.daimajia.slider.library.Tricks.ViewPagerEx;
import java.util.ArrayList;
import java.util.HashMap;
public class MainActivity extends AppCompatActivity {
//implements BaseSliderView.OnSliderClickListener, ViewPagerEx.OnPageChangeListener
private SliderLayout mDemoSlider;
private ImageView imageView;
private String selectDrinkCategory;
private String drinks = "drinks";
//String i = "0";
int j;
RecyclerViewAdapter recyclerViewAdapter;
private int[] images = {R.drawable.a,
R.drawable.bb,
R.drawable.c,
R.drawable.d,
R.drawable.e,
R.drawable.d_2_1,
R.drawable.d_2_2,
R.drawable.d_2_3,
R.drawable.d_2_4
};
private ArrayList<Integer> inputImages = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//get Intent
Intent intent = getIntent();
if (getIntent() != null) {
selectDrinkCategory = intent.getStringExtra("drinks");
}
initUI();
initBitmapImages();
initRecyclerView();
Toast.makeText(this, "J: "+j, Toast.LENGTH_SHORT).show();
}
private void initRecyclerView() {
LinearLayoutManager manager = new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false);
RecyclerView recyclerView = findViewById(R.id.recyclerView);
recyclerView.setLayoutManager(manager);
RecyclerViewAdapter adapter = new RecyclerViewAdapter(inputImages, this);
Toast.makeText(this, " Main Value j : " + adapter.index, Toast.LENGTH_SHORT).show();
imageView.setImageResource(images[j]);
recyclerView.setAdapter(adapter);
}
private void initBitmapImages() {
for (int i = 0; i < images.length; i++) {
// inputImages.add(String.valueOf(images[i]));
inputImages.add(images[i]);
}
}
private void initUI() {
//mDemoSlider = (SliderLayout) findViewById(R.id.slider);
imageView = findViewById(R.id.viewSingleImages);
//imageView.setImageResource((images[0]));
}
#Override
protected void onStop() {
// To prevent a memory leak on rotation, make sure to call stopAutoCycle() on the slider before activity or fragment is destroyed
super.onStop();
}
}
RecyclerView:
I have a scrolling RecyclerView (where images scrolling Horizontally) after clicking any of images it will appear below the
package com.aariyan.testm;
import android.content.Context;
import android.content.Intent;
import android.support.annotation.NonNull;
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.Toast;
import com.bumptech.glide.Glide;
import java.util.ArrayList;
public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.ViewHolder> {
private ArrayList<Integer> totalImages = new ArrayList<>();
private Context context;
//MainActivity mainActivity;
int index = 0;
public RecyclerViewAdapter(ArrayList<Integer> totalImages, Context context) {
this.totalImages = totalImages;
this.context = context;
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.images, viewGroup, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull final ViewHolder viewHolder, final int i) {
//index = 0;
Glide.with(context).asBitmap().load(totalImages.get(i)).into(viewHolder.singleImages);
viewHolder.setItemClickListener(new ItemClickListener() {
#Override
public void onClick(View view, int position, boolean isClicked) {
Toast.makeText(context, "TotalImages : "+totalImages.get(i), Toast.LENGTH_SHORT).show();
index = totalImages.get(i);
}
});
// viewHolder.singleImages.setOnClickListener(new View.OnClickListener() {
// #Override
// public void onClick(View v) {
// Toast.makeText(context, "" + viewHolder.getAdapterPosition(), Toast.LENGTH_SHORT).show();
// //viewHolder.imageView.setImageResource(totalImages.get(viewHolder.getAdapterPosition()));
// //index = viewHolder.getAdapterPosition();
// index = i;
// Toast.makeText(context, "Index : " + index, Toast.LENGTH_SHORT).show();
// }
// });
}
#Override
public int getItemCount() {
return totalImages.size();
}
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
public ImageView singleImages;
private ItemClickListener itemClickListener;
public ViewHolder(#NonNull View itemView) {
super(itemView);
singleImages = itemView.findViewById(R.id.imagesViewOnScroll);
itemView.setOnClickListener(this);
}
public void setItemClickListener (ItemClickListener itemClickListener) {
this.itemClickListener = itemClickListener;
}
#Override
public void onClick(View v) {
itemClickListener.onClick(v,getAdapterPosition(),false);
}
}
}
activity_main.xml : just have a recyclerView and image View
and images.xml : only a image view to set on RecyclerView
for get clicked item of recyckerview you have to use interface.
here is code sample:
first of all make one interface like below :
public interface ImageClickListener {
void onImageClick(String path);
}
now in your activity, make adapter's object like this
RecyclerViewAdapter adapter = new RecyclerViewAdapter(inputImages, this, new ImageClickListener() {
#Override
public void onImageClick(String path) {
Glide.with(context).load(path).into(imageView);
}
});
now create your adapter and make a constructor like this
public RecyclerViewAdapter(ArrayList<Integer> totalImages, Context context, ImageClickListener imageClickListener) {
this.totalImages = totalImages;
this.context = context;
this.imageClickListener = imageClickListener;
}
now you have an instance of interface in which you have one method, named onImageClick() in which you will pass the path of clicked image.
now on click of image do code like this:
viewHolder.singleImages.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
imageClickListener.onImageClick(totalImages.get(viewHolder.getAdapterPosition()));
}
});
now your method of interface will call & it will execute activity's image view to set the given path.
Enjoy codding :)
Related
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.
this cod show all array list i want to show first row in array list and then click button show row number two and click again show row number three and then can do that
public void onClick(View v) {
babyViewModel.getLetterRecourceID();
this cod show all array list i want to show first row in array list and then click button show row number two and click again show row number three and then can do that
the cod in activity_englishletters the first code
activity_englishletters
package com.example.learnn;
import androidx.appcompat.app.AppCompatActivity;
import androidx.databinding.DataBindingUtil;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProviders;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import com.example.learnn.databinding.ActivityEnglishcolorsBinding;
import com.example.learnn.databinding.ActivityEnglishlettersBinding;
import com.example.learnn.ui.BabyListAdapter;
import com.example.learnn.ui.BabyModel;
import com.example.learnn.ui.BabyViewModel;
import java.util.ArrayList;
public class EnglishlettersActivity extends AppCompatActivity {
BabyViewModel babyViewModel;
ImageView imagee,next;
RecyclerView recycler;
private int index = 0;
ArrayList arrayList,letterList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ActivityEnglishlettersBinding binding = DataBindingUtil.setContentView(this, R.layout.activity_englishletters);
imagee = (ImageView)findViewById(R.id.imagee);
recycler = (RecyclerView)findViewById(R.id.recycler);
final BabyListAdapter adapter = new BabyListAdapter();
recycler.setAdapter(adapter);
recycler.setLayoutManager(new LinearLayoutManager(this));
babyViewModel = ViewModelProviders.of(this).get(BabyViewModel.class);
babyViewModel.letterRecourceIDMutableLiveData.observe(this, new Observer<ArrayList<BabyModel>>() {
#Override
public void onChanged(ArrayList<BabyModel> babyModels) {
adapter.setList(babyModels);
}
});
binding.next.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
babyViewModel.getLetterRecourceID();
index = index+1;
if (index < letterList.size()) {
imagee.setBackgroundResource( (int) letterList.get( index ) );
return;
}
if (index == letterList.size()) {
imagee.setBackgroundResource( (int) letterList.get( 0 ) );
index = 0;
}
}
});
}
}
viewModel
package com.example.learnn.ui;
import com.example.learnn.R;
import java.util.ArrayList;
import androidx.lifecycle.MutableLiveData;
import androidx.lifecycle.ViewModel;
public class BabyViewModel extends ViewModel {
ArrayList arrayList;
public MutableLiveData<ArrayList<BabyModel>> letterRecourceIDMutableLiveData = new MutableLiveData<>();
public void getLetterRecourceID(){
letterRecourceIDMutableLiveData.setValue(getDataFromDatabase());
}
private ArrayList<BabyModel> getDataFromDatabase(){
ArrayList<BabyModel> arrayList = new ArrayList<>();
arrayList.add(new BabyModel(R.drawable.a));
arrayList.add(new BabyModel(R.drawable.b));
arrayList.add(new BabyModel(R.drawable.c));
arrayList.add(new BabyModel(R.drawable.d));
arrayList.add(new BabyModel(R.drawable.e));
return arrayList;
}
}
adapter
package com.example.learnn.ui;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import com.example.learnn.R;
import java.util.ArrayList;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
public class BabyListAdapter extends RecyclerView.Adapter<BabyListAdapter.BabyViewHolder> {
private ArrayList<BabyModel> letterList = new ArrayList<>();
#NonNull
#Override
public BabyViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
return new BabyViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.litter_list_item, parent, false));
}
#Override
public void onBindViewHolder(#NonNull BabyViewHolder holder, int position) {
holder.image.setImageResource(letterList.get(position).getLetterRecourceID());
}
#Override
public int getItemCount() {
return letterList.size();
}
public void setList(ArrayList<BabyModel> letterList) {
this.letterList = letterList;
notifyDataSetChanged();
}
public class BabyViewHolder extends RecyclerView.ViewHolder {
ImageView image;
public BabyViewHolder(#NonNull View itemView) {
super(itemView);
image = itemView.findViewById(R.id.imagee);
}
}
}
So, as a starter you will have a global index
int index=0;
then on the button click:
babyViewModel.letterRecourceIDMutableLiveData.observe(this, new Observer<ArrayList<BabyModel>>() {
#Override
public void onChanged(ArrayList<BabyModel> babyModels) {
List<BabyModel> list = babyModels.subList(0, index);
adapter.setList(list);
index++;
}
});
This is my recyclerview class where I have electrician, plumber, welder etc as my recyclerview items. I want whenever user click on any of these items the respective data that is retrieved from firebase should be shown in the next activity.
package com.example.hp.dc_project;
import android.content.Context;
import android.content.Intent;
import android.support.v7.widget.CardView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import java.util.List;
/** * Created by HP on 20-07-2018. */
public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.MyViewHolder> {
private Context mContext;
private List<category> mdata;
public RecyclerViewAdapter(Context context, List<category> mdata) {
this.mContext = context;
this.mdata = mdata;
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
LayoutInflater mInflater = LayoutInflater.from(mContext);
View view = mInflater.inflate(R.layout.cardview_category,parent,false);
return new MyViewHolder(view);
}
#Override
public void onBindViewHolder(MyViewHolder holder, int position) {
holder.tv.setText(mdata.get(position).getName());
holder.iv.setImageResource(mdata.get(position).getThumnail());
holder.cardView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(mContext.getApplicationContext(),available_worker.class);
mContext.startActivity(i);
}
});
}
#Override
public int getItemCount() {
return mdata.size();
}
public static class MyViewHolder extends RecyclerView.ViewHolder {
TextView tv;
ImageView iv;
CardView cardView;
public MyViewHolder(View itemView) {
super(itemView);
tv = (TextView)itemView.findViewById(R.id.tv_category);
iv = (ImageView)itemView.findViewById(R.id.iv_category);
cardView = (CardView)itemView.findViewById(R.id.cardview);
}
}
}
This is the activity class where I want to display the listview containing the data that is retrieved from firebase after clicking on the recyclerview items:
package com.example.hp.dc_project;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
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 java.util.ArrayList;
public class available_worker extends AppCompatActivity {
private ListView lv;
private FirebaseDatabase database;
private ArrayList<String>list;
private ArrayAdapter<String>adapter;
private Electrician elec;
// adapter = new ArrayAdapter<Electrician>(this,R.layout.list_of_work
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_available_worker);
lv = (ListView)findViewById(R.id.listView_workeravailable);
elec = new Electrician();
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?>parent, View view, int position, long id) {
Intent i = new Intent(available_worker.this,WorkerProfile.class);
startActivity(i);
}
});
list = new ArrayList<>();
adapter = new ArrayAdapter<String>(this, R.layout.list_of_worker,R.id.employeeadd);
database = FirebaseDatabase.getInstance();
DatabaseReference rootref = database.getReference();
DatabaseReference electricianref = rootref.child("Employee").child("Electrician");
electricianref.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot ds : dataSnapshot.getChildren()) {
String fName = ds.child("Fname").getValue(String.class);
String lName = ds.child("Lname").getValue(String.class);
String address = ds.child("Address").getValue(String.class);
list.add(fName);
list.add(lName);
list.add(address);
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
}
In on click get your worker id and put in extra , in the next activity put value event listner and get the respective data but you have one thing is that you have to have the id or something which can uniquely identify the reference of firebase.
holder.cardView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(mContext.getApplicationContext(),available_worker.class);
i.putExtra("uid",workerid);
mContext.startActivity(i);
}
});
in the next activity
String s = getIntent().getStringExtra("uid");
firebaseref.child(s).addvalueEventListner(////) {//pupulate your list view}
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
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