NullException on my dynamic slider - android

I would like to ask how will I be able to handle the NullException every time that I reach the last object in my int[] array.
Here is my InformationTab
package com.example.aldrinjohn.milktracktest;
import android.app.Activity;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
/**
* Created by Aldrin John on 3/20/2017.
*/
public class InformationTab extends Fragment{
ViewPager viewPager;
CustomSwipeAdapter adapter;
Button btnTrivia,btnBenefitB,btnBenefitM,btnPump,btnStoring,btnInfo;
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.informationtab, container, false);
viewPager = (ViewPager)rootView.findViewById(R.id.view_pager);
btnTrivia = (Button)rootView.findViewById(R.id.trivia);
btnTrivia.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
GlobalVariables.buttonClick = "trivia";
adapter = new CustomSwipeAdapter(getActivity());
viewPager.setAdapter(adapter);
}
});
btnBenefitB = (Button)rootView.findViewById(R.id.benefit_babies);
btnBenefitB.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
GlobalVariables.buttonClick = "benefitb";
adapter = new CustomSwipeAdapter(getActivity());
viewPager.setAdapter(adapter);
}
});
btnBenefitM = (Button)rootView.findViewById(R.id.benefit_mother);
btnBenefitM.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
GlobalVariables.buttonClick = "benefitm";
adapter = new CustomSwipeAdapter(getActivity());
viewPager.setAdapter(adapter);
}
});
btnPump = (Button)rootView.findViewById(R.id.pump);
btnPump.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
GlobalVariables.buttonClick = "pump";
adapter = new CustomSwipeAdapter(getActivity());
viewPager.setAdapter(adapter);
}
});
btnStoring = (Button)rootView.findViewById(R.id.storing);
btnStoring.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
GlobalVariables.buttonClick = "storing";
adapter = new CustomSwipeAdapter(getActivity());
viewPager.setAdapter(adapter);
}
});
btnInfo = (Button)rootView.findViewById(R.id.tips);
btnInfo.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
GlobalVariables.buttonClick = "tips";
adapter = new CustomSwipeAdapter(getActivity());
viewPager.setAdapter(adapter);
}
});
return rootView;
}
}
and this is my
package com.example.aldrinjohn.milktracktest;
import android.content.Context;
import android.provider.ContactsContract;
import android.support.v4.view.PagerAdapter;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import com.google.android.gms.ads.formats.NativeAd;
import com.google.android.gms.tagmanager.Container;
/**
* Created by Aldrin John on 3/26/2017.
*/
public class CustomSwipeAdapter extends PagerAdapter{
private int[] trivia = {R.drawable.c1,R.drawable.c2,R.drawable.c3,R.drawable.c4, R.drawable.c5,R.drawable.c6};
private int[] benefitBaby = {R.drawable.c7,R.drawable.c8,R.drawable.c9};
private int[] benefitMother = {R.drawable.c91,R.drawable.c92};
private int[] info = {R.drawable.a1,R.drawable.a2,R.drawable.a3,R.drawable.a4,R.drawable.a5,R.drawable.a6,R.drawable.a7,
R.drawable.a8,R.drawable.a9,R.drawable.a91,R.drawable.a92};
private int[] storing = {R.drawable.b1,R.drawable.b2,R.drawable.b3,R.drawable.b4};
private int[] pump = {R.drawable.a21,R.drawable.a22,R.drawable.a23,R.drawable.a24,R.drawable.a25,R.drawable.a31,R.drawable.a32,
R.drawable.a33,R.drawable.a34,R.drawable.a35,R.drawable.pic1,R.drawable.pic2,R.drawable.pic3,R.drawable.pic4,R.drawable.pic5};
private Context ctx;
private LayoutInflater layoutInflater;
public CustomSwipeAdapter(Context ctx)
{
this.ctx = ctx;
}
#Override
public int getCount() {
return pump.length;
}
#Override
public boolean isViewFromObject(View view, Object object) {
return (view==(LinearLayout)object);
}
#Override
public Object instantiateItem(ViewGroup container, int position){
layoutInflater = (LayoutInflater)ctx.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
final View item_view = layoutInflater.inflate(R.layout.swipe_layout,container,false);
ImageView imgTrivia = (ImageView)item_view.findViewById(R.id.image_view);
if(GlobalVariables.buttonClick.equals("trivia"))
{
imgTrivia.setImageResource(trivia[position]);
}
else if (GlobalVariables.buttonClick.equals("benefitb"))
{
imgTrivia.setImageResource(benefitBaby[position]);
}
else if (GlobalVariables.buttonClick.equals("benefitm"))
{
imgTrivia.setImageResource(benefitMother[position]);
}
else if (GlobalVariables.buttonClick.equals("storing"))
{
imgTrivia.setImageResource(storing[position]);
}
else if (GlobalVariables.buttonClick.equals("tips"))
{
imgTrivia.setImageResource(info[position]);
}
else if (GlobalVariables.buttonClick.equals("pump"))
{
imgTrivia.setImageResource(pump[position]);
}
container.addView(item_view);
return item_view;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object){
container.removeView((LinearLayout)object);
}
}

SOLVED! I just used a global variable class that contains the number of slides that is clicked. and return it to getCount function.

Related

How to take reference of itemClick on recyclerview

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 :)

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!!

How to retain the values of radio buttons from listview in android on orientation change

I have different layouts for landscape and portrait mode. When I select the values from radio buttons in radio group and change the orientation , new layout is displayed and all values are vanished. Please Help.
package com.hp.opiniondesknew;
import android.content.Context;
import android.os.Bundle;
import android.os.Parcelable;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.os.ParcelableCompat;
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.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
/**
* Created by HP on 15-12-2016.
*/
public class FragmentFeedback extends Fragment {
private ArrayList<Questions> questionsArrayList;
HashMap<Questions, String> mapAns=new HashMap<Questions, String>();
private MyAdapter myAdapter;
private ListView listFeedbackQuestions;
private Button btSubmitFeedback;
private String selectedAns;
ArrayList<String> rbAnswersArray = new ArrayList<>();
int yesCount=0,noCount=0;
Questions questionPojo;
public FragmentFeedback() {
// setRetainInstance(true);
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view=inflater.inflate(R.layout.feedback_layout,container,false);
listFeedbackQuestions= (ListView)view.findViewById(R.id.opinion_desk_feedback_lv_questions);
btSubmitFeedback=(Button)view.findViewById(R.id.opinion_desk_feedback_bt_submit);
questionsArrayList= new ArrayList<Questions>();
addlistview();
initializeBtnSubmit(btSubmitFeedback);
return view;
}
private void initializeBtnSubmit( Button btSubmitFeedback) {
btSubmitFeedback.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//---------
try
{
for(Map.Entry m:mapAns.entrySet()){
// System.out.println(m.getKey"()+" "+m.getValue());
Log.e("key value",m.getKey()+""+m.getValue());
}
if(mapAns.size()==0 || mapAns.size()< questionsArrayList.size())
{
Toast.makeText(getContext(),"Ans all q",Toast.LENGTH_SHORT).show();
}
else
{
int countYes = Collections.frequency(mapAns.values(), "yes");
{
Log.e("yescount",countYes+"");
}
int countNo = Collections.frequency(mapAns.values(), "no");
{
Log.e("noCount",countNo+"");
Log.e("mapsize",mapAns.size()+"");
}
if(countYes>countNo)
{
Fragment someFragment = new FragmentTestimonial();
FragmentTransaction transaction = getFragmentManager().beginTransaction();
transaction.replace(R.id.content_frame, someFragment ); // give your fragment container id in first parameter
// transaction.addToBackStack(null); // if written, this transaction will be added to backstack
transaction.commit();
Log.e("noCount",countNo+"");
Log.e("yescount",countYes+"");
// Log.e("yes is greater",rbAnswersArray.size()+"");
}
else
{
Fragment someFragment = new FragmentSuggestions();
FragmentTransaction transaction = getFragmentManager().beginTransaction();
transaction.replace(R.id.content_frame, someFragment ); // give your fragment container id in first parameter
// transaction.addToBackStack(null); // if written, this transaction will be added to backstack
transaction.commit();
Log.e("noCount",countNo+"");
Log.e("yescount",countYes+"");
}
mapAns.clear();
}
}catch (Exception e){e.printStackTrace();}
//-----
}
});
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
getActivity().setTitle("Feedback");
}
public void addlistview()
{
try
{
for (int i=0;i<5;i++) {
Questions questions = new Questions();
// questions.setQuestion(i+"");
questions.setQuestion("Did you like the performance of the service?");
questions.setQuestionNo(i);
questionsArrayList.add(questions);
myAdapter = new MyAdapter(getContext(), questionsArrayList);
listFeedbackQuestions.setAdapter(myAdapter);
if(selectedState != null) {
listFeedbackQuestions.onRestoreInstanceState(selectedState);
}
// Log.e("pojo",questions.toString());
}
}
catch (Exception e){e.printStackTrace();}
}
public class MyAdapter extends BaseAdapter {
Context context;
ArrayList<Questions> questionsArrayList;
LayoutInflater inflator;
public MyAdapter(Context context, ArrayList<Questions> questionsArrayList) {
this.context = context;
this.questionsArrayList = questionsArrayList;
inflator= LayoutInflater.from(context);
}
#Override
public int getCount() {
return questionsArrayList.size();
}
#Override
public Object getItem(int position) {
return questionsArrayList.get(position);
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
// Questions questionsPojo= new Questions();
Holder holder= new Holder();
if(convertView==null)
{
convertView=inflator.inflate(R.layout.feedback_question_row,parent,false);
holder.tvQuestion=(TextView) convertView.findViewById(R.id.opinion_desk_feedback_tv_question);
holder.rGroupButtons=(RadioGroup)convertView.findViewById(R.id.opinion_desk_rg_yes_no);
holder.rbYes=(RadioButton) convertView.findViewById(R.id.opinion_desk_feedback_rb_yes);
holder.rbNo=(RadioButton)convertView.findViewById(R.id.opinion_desk_feedback_rb_no);
convertView.setTag(holder);
}
else
{
holder=(Holder)convertView.getTag();
}
questionPojo=questionsArrayList.get(position);
holder.tvQuestion.setText(questionsArrayList.get(position).getQuestion());
final Holder finalHolder = holder;
holder.rGroupButtons.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
if (finalHolder.rbYes.isChecked())
{
Log.e("no",position+"");
finalHolder.selectedAnswer="yes";
questionsArrayList.get(position).setAnswer(finalHolder.selectedAnswer);
selectedAns= questionsArrayList.get(position).getAnswer();
rbAnswersArray.add(selectedAns);
yesCount++;
}
else
{
Log.e("no",position+"");
finalHolder.selectedAnswer="no";
questionsArrayList.get(position).setAnswer(finalHolder.selectedAnswer);
selectedAns=questionsArrayList.get(position).getAnswer();
noCount++;
}
mapAns.put(questionsArrayList.get(position),selectedAns);
rbAnswersArray.add(selectedAns);
//
}
});
return convertView;
}
}
public class Holder
{
TextView tvQuestion;
RadioGroup rGroupButtons;
RadioButton rbYes,rbNo, rbSelectedAnswer;
String selectedAnswer, ansNo;
}
#Override
public void onDestroyOptionsMenu() {
super.onDestroyOptionsMenu();
}
// #Override
// public void onSaveInstanceState(Bundle outState) {
// super.onSaveInstanceState(outState);
// }
}
I am using listview and custom adapter for the listview. I am launching the fragment feedback from navigation activity. OnSavedInstanceState is not working, applictaion is crashing in onRestore method.I might be doing something wrong.
You have to use Bundle savedInstanceState to retrive your values.
You can save them in the onSaveInstanceState method.
Here a link to the documentation https://developer.android.com/guide/components/activities/activity-lifecycle.html

Cannot get data from sharedpreference?

Here is my doubt I have one activity inside that one fragment need to populate listview in activity from fragment data . But when I press back button from activity listview data is missing my doubt is how to store data permanently I have read about shared preferences here we can store and retrieve data permanently but when I use it i doesn't store the listview value permanently it's still missing the value as am new for android am confused with this so far what I have tried is:
Here is my Fragment:
package first.service.precision.servicefirst;
import android.app.Activity;
import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
/**
* Created by 4264 on 16-12-2015.
*/
public class NewCompetitors extends Fragment {
CompetitorsData competitorsData;
CompetitorsView competitorsView = new CompetitorsView();
EditText editText_name,editText_website,editText_strength,editText_weakness;
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.new_competitors_fragment, container, false);
editText_name = (EditText) rootView.findViewById(R.id.competitors_name);
editText_website = (EditText) rootView.findViewById(R.id.competitors_website);
editText_strength = (EditText) rootView.findViewById(R.id.competitors_strength);
editText_weakness = (EditText) rootView.findViewById(R.id.competitors_weakness);
Button btn_save = (Button) rootView.findViewById(R.id.btn_save);
btn_save.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
editTextcompetitor();
sendData(competitorsView);
getActivity().getFragmentManager().popBackStack();
}
});
return rootView;
}
public void editTextcompetitor(){
competitorsView.setCompetitor_name(editText_name.getText().toString());
competitorsView.setCompetitor_website(editText_website.getText().toString());
competitorsView.setCompetitor_strength(editText_strength.getText().toString());
competitorsView.setCompetitor_weakness(editText_weakness.getText().toString());
}
public void sendData(CompetitorsView competitorsView){
competitorsData.dataToCompetitorActivity(competitorsView);
}
#SuppressWarnings("deprecation")
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
competitorsData = (CompetitorsData) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()+ "");
}
}
public interface CompetitorsData{
void dataToCompetitorActivity(CompetitorsView competitorsView);
}
}
Here is my Activity where i populate listview:
package first.service.precision.servicefirst;
import android.app.FragmentTransaction;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.ListView;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;
public class Competitors extends Main2Activity implements NewCompetitors.CompetitorsData{
ListView lv;
SharedPreferences sharedPreferences;
List<CompetitorsView> competitorsViews;
CompetitorsListAdapter competitorsListAdapter;
Context context;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_competitors);
LayoutInflater inflater = (LayoutInflater) this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View contentView = inflater.inflate(R.layout.activity_competitors, null, false);
mDrawerLayout.addView(contentView, 0);
lv=(ListView)findViewById(R.id.list_competitors);
competitorsViews=new ArrayList<CompetitorsView>();
competitorsListAdapter=new CompetitorsListAdapter(this,R.id.list_competitors,competitorsViews);
lv.setAdapter(competitorsListAdapter);
Button btn_competitors=(Button)findViewById(R.id.btn_new_competitors);
SharedPreferences sharedPreferences= PreferenceManager.getDefaultSharedPreferences(this.getApplicationContext());
SharedPreferences.Editor edit=sharedPreferences.edit();
Gson gson=new Gson();
String yog=sharedPreferences.getString("go","");
Type type=new TypeToken<List<NewCompetitors>>(){}.getType();
List<CompetitorsView>competitorsViews=gson.fromJson(yog,type);
edit.commit();
btn_competitors.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
NewCompetitors fragment = new NewCompetitors();
FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.add(R.id.competitors_frame, fragment);
ft.addToBackStack(null);
ft.commit();
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_competitors, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
protected void onDestroy() {
super.onDestroy();
Gson gson = new Gson();
String jsonCurProduct = gson.toJson(competitorsViews);
SharedPreferences sharedPref = getApplicationContext().getSharedPreferences("yog", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putString("go", jsonCurProduct);
editor.commit();
}
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
//ArrayList<CompetitorsView>cc=savedInstanceState.getParcelableArrayList("yog");
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
}
#Override
public void dataToCompetitorActivity(CompetitorsView competitorsView)
{
competitorsViews.add(competitorsView);
competitorsListAdapter.notifyDataSetChanged();
}
#Override
protected void onRestart() {
super.onRestart();
}
}
Here is my customlistadapter:
package first.service.precision.servicefirst;
import android.content.Context;
import android.graphics.Color;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import java.util.List;
/**
* Created by 4264 on 16-12-2015.
*/
public class CompetitorsListAdapter extends ArrayAdapter<CompetitorsView> {
private List<CompetitorsView> listData;
private LayoutInflater layoutInflater;
public CompetitorsListAdapter(Context context, int resource, List<CompetitorsView> listdata) {
super(context, resource, listdata);
this.listData = listdata;
layoutInflater = LayoutInflater.from(context);
}
#Override
public void add(CompetitorsView object) {
super.add(object);
}
#Override
public int getCount() {
return listData.size();
}
#Override
public CompetitorsView getItem(int position) {
return listData.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
View mview = convertView;
if (mview == null) {
convertView = layoutInflater.inflate(R.layout.list_competitors, null);
// TextView req = (TextView) convertView.findViewById(R.id.txt);
//req.setText("Select Lead Information");
holder = new ViewHolder();
holder.competitors_name = (TextView) convertView.findViewById(R.id.company_grp);
holder.competitors_website = (TextView) convertView.findViewById(R.id.company_name);
holder.competitors_strength = (TextView) convertView.findViewById(R.id.addrsline);
holder.competitors_weakness = (TextView) convertView.findViewById(R.id.stateid);
// add.lv.setVisibility(View.INVISIBLE);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
// add.lv.setVisibility(View.VISIBLE);
holder.competitors_name.setText("Competitors Name: " + listData.get(position).getCompetitor_name());
holder.competitors_website.setText("Website: " + listData.get(position).getCompetitor_website());
holder.competitors_strength.setText("Competitors Strength: " + listData.get(position).getCompetitor_strength());
holder.competitors_weakness.setText("Competitors Weakness:" + listData.get(position).getCompetitor_weakness());
convertView.setBackgroundColor(Color.parseColor("#ffffff"));
return convertView;
}
static class ViewHolder {
public TextView competitors_name;
public TextView competitors_website;
public TextView competitors_strength;
public TextView competitors_weakness;
}
}
it's working but it's not storing the value!

Categories

Resources