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
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.
I am using a recycler view. I've set an OnLongClickListener() on it using a custom interface. everything works fine but when I long-press the row the app crashes with Java.lang.IndexOutOfBoundsException. while debugging I found that my array list's data is being deleted while I long-press but the recycler view is just not getting updated.
here's my code.
MainActivity.java
package com.raunak.alarmdemo4;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Switch;
import android.widget.Toast;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.raunak.alarmdemo4.Activities.AddAlarm;
import com.raunak.alarmdemo4.Adapters.AlarmAdapter;
import com.raunak.alarmdemo4.HelperClasses.AlarmsDBhelperClass;
import com.raunak.alarmdemo4.Interfaces.AlarmRecyclerViewInterface;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity implements AlarmRecyclerViewInterface {
FloatingActionButton mAlarmAddButton;
RecyclerView mRecyclerView;
SQLiteDatabase db;
AlarmsDBhelperClass mAlarmsDBhelperClass;
ArrayList<String> nameArrayList,modeArrayList,repeatArrayList,hoursArrayList,minArrayList;
Switch mSwitch;
AlarmAdapter alarmAdapter = new AlarmAdapter(hoursArrayList,minArrayList,modeArrayList,repeatArrayList,nameArrayList,this);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
//Initializing RecyclerView & DatabaseHelperClass and the FAB button
mAlarmsDBhelperClass = new AlarmsDBhelperClass(getApplicationContext());
mAlarmAddButton = findViewById(R.id.btnAlarmADD);
mRecyclerView = findViewById(R.id.alarmList);
mSwitch = findViewById(R.id.switchONOFF);
//Initializing ArrayList
nameArrayList = new ArrayList<>();
modeArrayList = new ArrayList<>();
repeatArrayList = new ArrayList<>();
hoursArrayList = new ArrayList<>();
minArrayList = new ArrayList<>();
DividerItemDecoration itemDecoration = new DividerItemDecoration(this,DividerItemDecoration.VERTICAL);
mRecyclerView.addItemDecoration(itemDecoration);
//Getting a writable reference of the Database.
db = mAlarmsDBhelperClass.getWritableDatabase();
//getAlarm(db);
getAlarm(db);
mAlarmAddButton.setImageResource(R.drawable.addalarm);
mAlarmAddButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent mIntent = new Intent(getApplicationContext(), AddAlarm.class);
startActivity(mIntent);
}
});
/* mSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
if(b){
Toast.makeText(getApplicationContext(),"Checked !",Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(getApplicationContext(),"Unchecked !",Toast.LENGTH_SHORT).show();
}
}
});*/
AlarmAdapter alarmAdapter = new AlarmAdapter(hoursArrayList,minArrayList,modeArrayList,repeatArrayList,nameArrayList,this);
mRecyclerView.setLayoutManager(new LinearLayoutManager(getApplicationContext()));
mRecyclerView.setAdapter(alarmAdapter);
mRecyclerView.setHasFixedSize(true);
}
public void getAlarm(SQLiteDatabase db) {
Cursor cursor = db.rawQuery("SELECT * FROM alarms", new String[]{});
cursor.moveToFirst();
if (cursor != null) {
do {
nameArrayList.add(cursor.getString(2));
modeArrayList.add(cursor.getString(3));
repeatArrayList.add(cursor.getString(4));
hoursArrayList.add(Integer.toString(cursor.getInt(5)));
minArrayList.add(Integer.toString(cursor.getInt(6)));
} while (cursor.moveToNext());
}
cursor.close();
}
#Override
public void onItemClick(int position) {
Toast.makeText(this, "Alarm Clicked !", Toast.LENGTH_SHORT).show();
}
#Override
public void onLongItemClick(int position) {
hoursArrayList.remove(position);
Log.d("d",""+position);
alarmAdapter.notifyItemRemoved(position);
Toast.makeText(this, ""+hoursArrayList.size(), Toast.LENGTH_SHORT).show();
}
}
my Recyclerview adapter.
package com.raunak.alarmdemo4.Adapters;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.raunak.alarmdemo4.Interfaces.AlarmRecyclerViewInterface;
import com.raunak.alarmdemo4.R;
import java.util.ArrayList;
public class AlarmAdapter extends RecyclerView.Adapter<AlarmAdapter.AlarmView> {
//Variables for the main recycler view
private ArrayList<String> hoursArrayList;
private ArrayList<String> minArrayList;
private ArrayList<String> modeArrayList;
private ArrayList<String> repeatArrayList;
private ArrayList<String> nameArrayList;
private AlarmRecyclerViewInterface mInterface;
public AlarmAdapter(ArrayList<String> hours,ArrayList<String> mins,ArrayList<String> mode,ArrayList<String> repeat,ArrayList<String> name,AlarmRecyclerViewInterface mInterface){
this.hoursArrayList = hours;
this.minArrayList = mins;
this.modeArrayList = mode;
this.nameArrayList = name;
this.repeatArrayList = repeat;
this.mInterface = mInterface;
}
#NonNull
#Override
public AlarmView onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
LayoutInflater layoutInflater = LayoutInflater.from(parent.getContext());
View view = layoutInflater.inflate(R.layout.alarm_profile,parent,false);
return new AlarmView(view);
}
#Override
public void onBindViewHolder(#NonNull AlarmView holder, int position) {
if(Integer.parseInt(hoursArrayList.get(position)) < 10 ){
holder.hours.setText("0"+hoursArrayList.get(position));
}else {
holder.hours.setText(hoursArrayList.get(position));
}
if (Integer.parseInt(minArrayList.get(position)) < 10){
holder.mins.setText("0"+minArrayList.get(position));
}else {
holder.mins.setText(minArrayList.get(position));
}
holder.repeat.setText(repeatArrayList.get(position));
holder.mode.setText(modeArrayList.get(position));
holder.name.setText(nameArrayList.get(position));
}
#Override
public int getItemCount() {
return nameArrayList.size();
}
/*ItemTouchHelper.SimpleCallback itemTouchHelperCallback = new ItemTouchHelper.SimpleCallback(0,ItemTouchHelper.RIGHT) {
#Override
public boolean onMove(#NonNull RecyclerView recyclerView, #NonNull RecyclerView.ViewHolder viewHolder, #NonNull RecyclerView.ViewHolder target) {
return false;
}
#Override
public void onSwiped(#NonNull RecyclerView.ViewHolder viewHolder, int direction) {
nameArrayList.remove(viewHolder.getAdapterPosition());
modeArrayList.remove(viewHolder.getAdapterPosition());
repeatArrayList.remove(viewHolder.getAdapterPosition());
hoursArrayList.remove(viewHolder.getAdapterPosition());
minArrayList.remove(viewHolder.getAdapterPosition());
}
};*/
public class AlarmView extends RecyclerView.ViewHolder{
TextView hours,mins,repeat,name,mode;
public AlarmView(#NonNull View itemView) {
super(itemView);
hours = itemView.findViewById(R.id.txtHOUR);
mins = itemView.findViewById(R.id.txtMins);
repeat = itemView.findViewById(R.id.txtRepeatDays);
name = itemView.findViewById(R.id.txtName);
mode = itemView.findViewById(R.id.txtMode);
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Log.d("d",""+getAdapterPosition());
mInterface.onItemClick(getAdapterPosition());
}
});
itemView.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View view) {
Log.d("d",""+getAdapterPosition());
mInterface.onLongItemClick(getAdapterPosition());
return true;
}
});
}
}
}
my CustomInterface
package com.raunak.alarmdemo4.Interfaces;
public interface AlarmRecyclerViewInterface {
void onItemClick(int position);
void onLongItemClick(int position);
}
Thanks for help!
You should remove the element also from nameArrayList and inside your Adapter:
#Override
public int getItemCount() {
return nameArrayList.size(); //This return a number that is higher than the number of elements
}
.
//When you call this, you remove the element from the list in the Main Activity, but not in your Adapter
hoursArrayList.remove(position);
.
itemView.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View view) {
int pos = getAdapterPosition();
Log.d("d",""+ pos);
hoursArrayList.remove(pos); //I think you'd add
nameArrayList.remove(pos); //these two lines
mInterface.onLongItemClick(pos);
return true;
}
});
.
#Override
public int getItemCount() {
return hoursArrayList.size(); //Or just the first line and modify this
}
And you should modify your MainActiivty fields:
FloatingActionButton mAlarmAddButton;
RecyclerView mRecyclerView;
SQLiteDatabase db;
AlarmsDBhelperClass mAlarmsDBhelperClass;
ArrayList<String> nameArrayList,modeArrayList,repeatArrayList,hoursArrayList,minArrayList;
Switch mSwitch;
AlarmAdapter alarmAdapter = new AlarmAdapter(hoursArrayList,minArrayList,modeArrayList,repeatArrayList,nameArrayList,this);
//This line has nosense, if you re-declare another alarmAdapter in the onCreate
Your are declaring and assigning different adapter in onCreate. Remove the declaration from there and just initialize it there.
AlarmAdapter alarmAdapter = new AlarmAdapter(hoursArrayList,minArrayList,modeArrayList,repeatArrayList,nameArrayList,this);
And you need to improve your code for efficiency, create a model class instead of declaring arrrayList of every param.
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 :)
I have a class that extends from a RecyclerView.Adapter, in that class I have two buttons, one to update and one to delete, the problem is that I want to use those buttons to call a method that is in another class that extends Fragments but not I know how to make the instance to my method, I also want to pass a parameter.
This is my class that extends from a RecyclerView.Adapter:
package com.example.enriq.examen_tareas_segundo_plano_enrique_espinosa.adapter;
import android.app.Activity;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.TextView;
import android.widget.Toast;
import com.example.enriq.examen_tareas_segundo_plano_enrique_espinosa.R;
import com.example.enriq.examen_tareas_segundo_plano_enrique_espinosa.tareasFragmento;
import java.util.ArrayList;
/**
* Created Enrique Espinosa.
*/
public class TareasAdapter extends RecyclerView.Adapter<TareasAdapter.UsuarioHolder>{
private Activity activity;
private ArrayList<Tareas> tareas;
public TareasAdapter(Activity activity, ArrayList<Tareas> tareas) {
this.activity = activity;
this.tareas = tareas;
}
public class UsuarioHolder extends RecyclerView.ViewHolder {
public TextView txtId;
public TextView txtNombreUsuario;
public TextView txtNota;
public TextView txtEstudiante;
public int pasId;
Button btnEliminar = (Button)itemView.findViewById(R.id.btnEliminar);
Button btnActualizar = (Button)itemView.findViewById(R.id.btnActualizar);
public UsuarioHolder(View itemView) {
super(itemView);
txtId = (TextView) itemView.findViewById(R.id.txt_id);
txtNombreUsuario = (TextView) itemView.findViewById(R.id.txt_nombre_usuario);
txtNota = (TextView) itemView.findViewById(R.id.txt_nota);
txtEstudiante = (TextView) itemView.findViewById(R.id.txtEstudiante);
}
}
#Override
public UsuarioHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = activity.getLayoutInflater().inflate(R.layout.plantilla_usuariosegundo, parent, false);
UsuarioHolder holder = new UsuarioHolder(view);
return holder;
}
#Override
public void onBindViewHolder(final UsuarioHolder holder, int position) {
holder.txtId.setText(tareas.get(position).getId());
holder.txtNombreUsuario.setText("Tarea: "+ tareas.get(position).getNombreTarea());
holder.txtNota.setText("Nota: "+ tareas.get(position).getNota());
holder.txtEstudiante.setText("Estudiante: "+ tareas.get(position).getEstudiante());
}
#Override
public int getItemCount() {
return tareas.size();
}
}
And this is my class that extends form a Fragment:
package com.example.enriq.examen_tareas_segundo_plano_enrique_espinosa;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.v4.app.Fragment;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.GridLayoutManager;
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.Toast;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonArrayRequest;
import com.android.volley.toolbox.Volley;
import com.example.enriq.examen_tareas_segundo_plano_enrique_espinosa.adapter.Tareas;
import com.example.enriq.examen_tareas_segundo_plano_enrique_espinosa.adapter.TareasAdapter;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
/**
* Created by Enriq on 26/04/2018.
*/
public class tareasFragmento extends Fragment {
private String url = "http://192.168.1.128:8080/WebServiceExamenFinal/webapi/tareas";
private ArrayList<Tareas> estudiantes = new ArrayList<>();
//Si no funciona esto se puede borrar
AlertDialog alertDialog;
private List<Tareas> tareasList;
private TareasAdapter tareasAdapter;
private int assiId;
public tareasFragmento() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.activity_tareas, container, false);
RecyclerView recyclerView = (RecyclerView) view.findViewById(R.id.recycler_list);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new GridLayoutManager(getContext(), 2,
GridLayoutManager.VERTICAL, false));
final TareasAdapter adapter = new TareasAdapter(getActivity(), estudiantes);
recyclerView.setAdapter(adapter);
RequestQueue queue = Volley.newRequestQueue(getContext());
final ProgressDialog dialog = new ProgressDialog(getContext());
dialog.setMessage("Por favor espere...");
dialog.show();
try {
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(Request.Method.GET, url,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
deserializarJSONArray(response);
adapter.notifyDataSetChanged();
if (dialog.isShowing()) dialog.dismiss();
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getActivity(),
"Error al realizar la peticiĆ³n\n" + error.getMessage(),
Toast.LENGTH_LONG).show();
if (dialog.isShowing()) dialog.dismiss();
}
});
queue.add(jsonArrayRequest);
}catch (Exception e) {
Toast.makeText(getActivity(),"El error es: "+e,Toast.LENGTH_LONG).show();
}
return view;
}
public void deserializarJSONArray(JSONArray jsonArray) {
for (int i = 0; i < jsonArray.length(); i++) {
try {
JSONObject item = jsonArray.getJSONObject(i);
Tareas tareas = new Tareas();
tareas.setId(item.getString("id"));
tareas.setNombreTarea(item.getString("nombreUsuario"));
tareas.setEstudiante(item.getString("estudiante"));
tareas.setNota(item.getString("nota"));
estudiantes.add(tareas);
} catch (JSONException e) {
Toast.makeText(getActivity(), "Error al procesar la respuesta de la peticiĆ³n: " + e,
Toast.LENGTH_SHORT).show();
}
}
}
public void delete(int id){
Toast.makeText(getActivity(),"Este es el id recibido: "+id,Toast.LENGTH_LONG).show();
}
public int getAssiId(){
Toast.makeText(getActivity(),"Estas en el get de tareas fragmento",Toast.LENGTH_LONG).show();
return assiId;
}
}
I tried doing something similar to this:
tareasFragmento tarea = new tareasFragmento();
tarea.eliminar(id);
But it returns this error:
Attemp to invoque a virtual method 'android.content.res.Resources
android.content.Context.getResources()' a null object refrences
I've updated your adapter.
public class TareasAdapter extends RecyclerView.Adapter<TareasAdapter.UsuarioHolder> {
private Activity activity;
private ArrayList<Tareas> tareas;
private OnClickButton callback;
public TareasAdapter(Activity activity, ArrayList<Tareas> tareas) {
this.activity = activity;
this.tareas = tareas;
}
public void setCallback(OnClickButton callback) {
this.callback = callback;
}
public class UsuarioHolder extends RecyclerView.ViewHolder {
public TextView txtId;
public TextView txtNombreUsuario;
public TextView txtNota;
public TextView txtEstudiante;
public int pasId;
Button btnEliminar;
Button btnActualizar;
public UsuarioHolder(View itemView) {
super(itemView);
txtId = (TextView) itemView.findViewById(R.id.txt_id);
txtNombreUsuario = (TextView) itemView.findViewById(R.id.txt_nombre_usuario);
txtNota = (TextView) itemView.findViewById(R.id.txt_nota);
txtEstudiante = (TextView) itemView.findViewById(R.id.txtEstudiante);
btnEliminar = (Button) itemView.findViewById(R.id.btnEliminar);
btnActualizar = (Button) itemView.findViewById(R.id.btnActualizar);
}
}
#Override
public UsuarioHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = activity.getLayoutInflater().inflate(R.layout.plantilla_usuariosegundo, parent, false);
UsuarioHolder holder = new UsuarioHolder(view);
holder.btnActualizar.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
callback.onClickUpdate();
}
});
holder.btnEliminar.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
callback.onClickDelete();
}
});
return holder;
}
#Override
public void onBindViewHolder(final UsuarioHolder holder, int position) {
holder.txtId.setText(tareas.get(position).getId());
holder.txtNombreUsuario.setText("Tarea: " + tareas.get(position).getNombreTarea());
holder.txtNota.setText("Nota: " + tareas.get(position).getNota());
holder.txtEstudiante.setText("Estudiante: " + tareas.get(position).getEstudiante());
}
#Override
public int getItemCount() {
return tareas.size();
}
public interface OnClickButton {
void onClickUpdate();
void onClickDelete();
}
}
EDIT:
Now make the fragment that uses this adapter implement the interface OnClickButton. you'll then be able to manipulate the click events in the activity which is the right place to manipulate/communicate with fragments.
Finally after initializing the adapter call:
adapter.setCallback(this);
I am working o a project where i have RecyclerView with list of items.And when i click on a item it should get the details of the item and start another activity and fill the Texview of the activity with the details.
I have implemented several methods for implementing onclicklistener on Recyclerview but nothing worked
The below one is the latest one i used.It dosent work too.
Thank you...
My InterFace :
public interface ItemClickListener
{
void onItemClick(View view,int position);
}
My Adapterclass :
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.TextView;
import android.widget.Toast;
import java.util.Collections;
import java.util.List;
/**
* Created by mrudu on 01-05-2016.
*/
public class mainrow_adapter extends RecyclerView.Adapter<mainrow_adapter.View_Holder>
{
List<Person_details> list = Collections.emptyList();
Context context;
public mainrow_adapter(List<Person_details> list, Context context) {
this.list = list;
this.context = context;
}
#Override
public mainrow_adapter.View_Holder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.main_rowlayout,parent,false);
View_Holder holder = new View_Holder(view);
return holder;
}
#Override
public void onBindViewHolder(mainrow_adapter.View_Holder holder, int position)
{
Person_details person_details = new Person_details();
holder.nametext.setText(list.get(position).getName());
holder.amounttext.setText(list.get(position).getAmount());
holder.setClickListener(new ItemClickListener() {
#Override
public void onItemClick(View view, int position) {
Person_details selectedPerson = list.get(position);
String name = selectedPerson.getName();
Toast.makeText(context,name,Toast.LENGTH_SHORT).show();
}
});
}
#Override
public int getItemCount() {
return list.size();
}
public class View_Holder extends RecyclerView.ViewHolder implements View.OnClickListener
{
TextView nametext,amounttext;
private ItemClickListener clickListener;
public View_Holder(View itemView) {
super(itemView);
nametext = (TextView)itemView.findViewById(R.id.Name);
amounttext = (TextView)itemView.findViewById(R.id.Amount);
}
public void setClickListener(ItemClickListener itemClickListener)
{
clickListener = itemClickListener;
}
#Override
public void onClick(View view)
{
clickListener.onItemClick(view,getAdapterPosition());
}
}
}
Main activity :
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
public class MainList extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_mainlist);
final Intent adnew = new Intent(this,Add_Person.class);
RecyclerView recyclerView = (RecyclerView)findViewById(R.id.recyclerview);
List<Person_details> list = filldata();
mainrow_adapter adapter = new mainrow_adapter(list,getApplication());
recyclerView.setAdapter(adapter);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
RecyclerView.ItemAnimator animator = new DefaultItemAnimator();
animator.setAddDuration(1000);
animator.setRemoveDuration(1000);
recyclerView.setItemAnimator(animator);
FloatingActionButton floatingActionButton = (FloatingActionButton)findViewById(R.id.addnewfab);
floatingActionButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(MainList.this, "Add new Log", Toast.LENGTH_SHORT).show();
startActivity(adnew);
}
});
}
public List<Person_details> filldata()
{
List<Person_details> data = new ArrayList<>();
data.add(new Person_details("Mrudhu","9959461221","Glp","2500"));
data.add(new Person_details("Ram","9959461221","Glp","2820"));
data.add(new Person_details("Syam","9959461221","Glp","8000"));
data.add(new Person_details("Shekar","9959461221","Glp","320"));
data.add(new Person_details("Sharif","9959461221","Glp","836"));
data.add(new Person_details("Rahul","9959461221","Glp","126"));
data.add(new Person_details("Rohith","9959461221","Glp","50"));
data.add(new Person_details("Manikanta","9959461221","Glp","55"));
data.add(new Person_details("Ramesh","9959461221","Glp","198"));
data.add(new Person_details("Ram","9959461221","Glp","162"));
return data;
}
}
You are not registering click listener. Register it in View_Holder constructor
itemView.setOnClickListener(this);
public View_Holder(View itemView) {
super(itemView);
nametext = (TextView)itemView.findViewById(R.id.Name);
amounttext = (TextView)itemView.findViewById(R.id.Amount);
itemView.setOnClickListener(this);
}