How to refresh viewpager after delete operation - java

In my app ,i used view pager to show my image gallery .
after deleteing any image from my gallery , view pager should get updated.
My Activity
public class FullScreenViewActivityForSelfImage extends Activity{
#SuppressWarnings("unused")
private Utils utils;
private FullScreenImageAdapterForSelfImage adapter;
private static ViewPager viewPager;
DatabaseHelper db;
ArrayList<Image> aryimages;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_fullscreen_view);
db=new DatabaseHelper(this);
viewPager = (ViewPager) findViewById(R.id.pager);
aryimages= db.getimages();
Intent i = getIntent();
int position = i.getIntExtra("position", 0);
adapter = new FullScreenImageAdapterForSelfImage(FullScreenViewActivityForSelfImage.this,
aryimages,this);
viewPager.setAdapter(adapter);
// displaying selected image first
viewPager.setCurrentItem(position);
}
public static ViewPager getAdapter() {
return viewPager;
}
}
My Adapter Class
public class FullScreenImageAdapterForSelfImage extends PagerAdapter
{
private Activity _activity;
private ArrayList<Image> _imagePaths;
ArrayList<Image> aryimages;
public ImageListAdapter ImageListAdapter;
private LayoutInflater inflater;
private Context context;
int columnWidth,width,cellWidth,padding,height;
DatabaseHelper db;
int i;
String id,name;
// constructor
public FullScreenImageAdapterForSelfImage(Activity activity,
ArrayList<Image> aryimages,Context context) {
this._activity = activity;
this._imagePaths = aryimages;
this.context = context;
db= new DatabaseHelper(_activity);
Display display = activity.getWindowManager().getDefaultDisplay();
Point size = new Point();
display.getSize(size);
width = size.x;
height = size.y;
}
My Adapter where delete service is called
btndel.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(v.getContext());
alertDialog.setTitle("Confirm Delete...");
alertDialog.setMessage("You are about to delete all images of this product continue");
alertDialog.setPositiveButton("YES",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int which) {
// Write your code here to execute after dialog
name = _imagePaths.get(position).Image_name.toString();
String imei=db.SelectImeiNo();
id=db.getidbyname(name);
System.out.println("selected imei = "+imei);
System.out.println("selected id = "+id);
dialog.cancel();
WebServiceTask wst = new WebServiceTask(WebServiceTask.POST_TASK, context , "Deleting Image...");
wst.execute(new String[] { Service_url });
}
});
In Adapter i tried to refresh
public void handleResponse(String response) {
System.out.println("handle REsponse...got result..."+response);
if(response.equalsIgnoreCase("0"))
{
System.out.println("!!!!!!!!!!Server Busy try again latter!!!!!!!!!!!!!!!!");
Toast.makeText(context.getApplicationContext(), "Server Busy try again latter", Toast.LENGTH_LONG).show();
}
else if(response.equalsIgnoreCase("1"))
{
System.out.println("!!!!!!!!!!!!Image deleted!!!!!!!!!!!!!!!!!!!");
Toast.makeText(context.getApplicationContext(), "Image deleted", Toast.LENGTH_LONG).show();
db.deleteImageSelected(id);
_imagePaths.remove(i);
ImageListAdapter.notifyDataSetChanged();
}
}
Image Adapter
public class ImageListAdapter extends BaseAdapter {
//private Context context;
private ArrayList<Image> Img;
private LayoutInflater inflater = null;
public ImageListAdapter(Context context, ArrayList<Image> Image) {
// this.context = context;
this.Img = Image;
inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
return Img.size();
}
#Override
public Object getItem(int position) {
return position;
}
#Override
public long getItemId(int position) {
return position;
}
#SuppressLint("InflateParams")
#SuppressWarnings("unused")
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = null;
if (convertView == null) {
view = inflater.inflate(R.layout.imageshow, null);
} else {
view = convertView;
}
ImageView iv= (ImageView) view.findViewById(R.id.imageshowView1);
TextView name= (TextView) view.findViewById(R.id.Imageshownametv);
TextView id= (TextView) view.findViewById(R.id.Imageshowidtv);
TextView desc= (TextView) view.findViewById(R.id.Imageshowimagedesc);
id.setText(Img.get(position).Image_id);
byte[] I= Img.get(position).image;
System.out.println("Byte array of the image "+I);
Bitmap bp=BitmapFactory.decodeByteArray(I, 0, I.length);
iv.setImageBitmap(bp);
return view;
}
}
But it is not done
so please help me..

Related

Removing objects from listView in custom adapter

So I have an activity with a listview inside of it and when I click a delete button I want to remove the object from the list. I already know how to find which object I want to remove and remove it from the list that populates my array adapter but I am not sure what i need to do to call the .notifyDataSetChanged() routine which Is what I believe I need to do. Any help would be much appreciated.
My activity code
public class MealActivity2 extends AppCompatActivity {
private ListView lv;
public static ArrayList<Model> modelArrayList;
private CustomAdapter customAdapter;
private Button btnnext;
private String[] fruitlist = new String[]{"Apples", "Oranges", "Potatoes", "Tomatoes","Grapes"};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_meal2);
Integer numFoodItems = ((Globals) getApplication()).getLength();
lv = (ListView) findViewById(R.id.lv);
btnnext = (Button) findViewById(R.id.next);
modelArrayList = getModel(numFoodItems);
customAdapter = new CustomAdapter(this);
lv.setAdapter(customAdapter);
btnnext.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MealActivity2.this,NextActivity.class);
startActivity(intent);
}
});
}
// this builds the array list of model opbjects that will be used by the adapter to populate
// the list view dynamically
private ArrayList<Model> getModel(Integer length){
ArrayList<Model> list = new ArrayList<>();
for(int i = 0; i < length; i++){
FoodDetailsPost food = ((Globals) getApplication()).getFoodList().get(i);
Model model = new Model();
model.setNumber(((Globals) getApplication()).getServing(i));
model.setFruit(food.getDescription());
list.add(model);
}
return list;
}
}
and here is my custom adapter code if you look near the end at the last comment that is where i need to notify my activity that I have changed the contents of the list and should update the displaying items
public class CustomAdapter extends BaseAdapter {
private Context context;
private adapterGlobalAccess g = new adapterGlobalAccess();
private CustomAdapter customAdapter;
public CustomAdapter(Context context) {
this.context = context;
}
#Override
public int getViewTypeCount() {
return getCount();
}
#Override
public int getItemViewType(int position) {
return position;
}
#Override
public int getCount() {
return MealActivity2.modelArrayList.size();
}
#Override
public Object getItem(int position) {
return MealActivity2.modelArrayList.get(position);
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
final ViewHolder holder;
if (convertView == null) {
holder = new ViewHolder(); LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.lv_item, null, true);
holder.tvFruit = (TextView) convertView.findViewById(R.id.animal);
holder.tvnumber = (TextView) convertView.findViewById(R.id.number);
holder.btn_edit = (Button) convertView.findViewById(R.id.plus);
holder.btn_minus = (Button) convertView.findViewById(R.id.minus);
convertView.setTag(holder);
}else {
// the getTag returns the viewHolder object set as a tag to the view
holder = (ViewHolder)convertView.getTag();
}
holder.tvFruit.setText(MealActivity2.modelArrayList.get(position).getFruit());
holder.tvnumber.setText(String.valueOf(MealActivity2.modelArrayList.get(position).getNumber()));
holder.btn_edit.setTag(R.integer.btn_plus_view, convertView);
holder.btn_edit.setTag(R.integer.btn_plus_pos, position);
holder.btn_edit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
View tempview = (View) holder.btn_edit.getTag(R.integer.btn_plus_view);
TextView tv = (TextView) tempview.findViewById(R.id.number);
Integer pos = (Integer) holder.btn_edit.getTag(R.integer.btn_plus_pos);
Double number = Double.parseDouble(tv.getText().toString()) + 1;
tv.setText(String.valueOf(number));
MealActivity2.modelArrayList.get(pos).setNumber(number);
g.setServing(pos, number);
}
});
holder.btn_minus.setTag(R.integer.btn_minus_view, convertView);
holder.btn_minus.setTag(R.integer.btn_minus_pos, position);
holder.btn_minus.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
View tempview = (View) holder.btn_minus.getTag(R.integer.btn_minus_view);
TextView tv = (TextView) tempview.findViewById(R.id.number);
Integer pos = (Integer) holder.btn_minus.getTag(R.integer.btn_minus_pos);
((Globals) context.getApplicationContext()).remove(pos);
MealActivity2.modelArrayList.remove(pos);
// i need to do .notifyDataSetChanged() here but im not sure how
}
});
return convertView;
}
You can just use a interface to solve the problem
CustomAdapter
public class CustomAdapter extends BaseAdapter {
...
private CustomAdapterListener listener;
interface CustomAdapterListener{
void itemClick();
}
public CustomAdapter(Context context, CustomAdapterListener listener) {
this.context = context;
this.listener = listener;
}
MainActivity2
public class MealActivity2 extends AppCompatActivity implements CustomAdapterListener {
...
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_meal2);
...
customAdapter = new CustomAdapter(this, this);
}
#Override
public void itemClick() {
// you can do .notifyDataSetChanged() here
}
after that you can use listener to callback to Activity and do anything you want
CustomAdapter
#Override
public void onClick(View v) {
listener.itemClick();
// i need to do .notifyDataSetChanged() here but im not sure how
}

Handle click events of both Recyclerview and CardView in same time

I have requirement to create nested recyclerView like
RecyclerView Contains-> CardView contains-> RecyclerView.
If I click on card I'm getting child position only but I also need parent card position. How can I handle click events of both Recyclerview and CardView at same time?
MainActivity.java:
public class MainActivity extends Activity {
LinearLayout linView;
private RecyclerView main_view;
RootAdapter adapter2;
private RelativeLayout mRelativeLayout;
private Context mContext;
private Activity mActivity;
int pos = 0;
int main_pos;
private static RecyclerView.Adapter adapter;
private static RecyclerView.Adapter adapterCo;
private RecyclerView.LayoutManager layoutManager;
private static ArrayList<DataModelMain> dataMain;
private static ArrayList<DataModel_CO> dataCo;
static View.OnClickListener myOnClickListener;
static View.OnClickListener onClickListener;
private static ArrayList<Integer> removedItems;
TestMain mainData = new TestMain();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
prof = (ImageView) findViewById(R.id.profile);
main_view = (RecyclerView) findViewById(R.id.recycler_main);
mRelativeLayout = (RelativeLayout) findViewById(R.id.partners);
cont = (TextView) findViewById(R.id.mobile);
iconType = (ImageView) findViewById(R.id.icon_type);
linView = (LinearLayout) findViewById(R.id.layout_view);
// Get the application context
mContext = getApplicationContext();
// Get the activity
mActivity = MainActivity.this;
myOnClickListener = new MyOnClickListener(this);
onClickListener = new OnClickListener(this);
main_view.setHasFixedSize(true);
layoutManager = new LinearLayoutManager(
this,
LinearLayoutManager.VERTICAL,
false
) {
};
main_view.setLayoutManager(layoutManager);
main_view.setItemAnimator(new DefaultItemAnimator());
dataMain = new ArrayList<DataModelMain>();
getMainData();
setMainView();
}
}
private void getMainData() {
for (int i = 0; i < mainData.passengers.length; i++) {
dataMain.add(new DataModelMain(
mainData.type[i],
mainData.passengers[i],
mainData.p_name[i],
mainData.p_contact[i],
mainData.p_flight[i],
mainData.p_pnr[i],
mainData.air[i],
mainData.p_time[i]
));
}
adapter2 = new RootAdapter(this, dataMain);
main_view.setAdapter(adapter2);
}
private class MyOnClickListener implements View.OnClickListener {
private final Context context;
private MyOnClickListener(Context context) {
this.context = context;
}
#Override
public void onClick(View v) {
showIcons(v);
}
private void showIcons(View v) {
pos = main_view.getChildPosition(v);
setMainView();
}
}
private class OnClickListener implements View.OnClickListener {
private final Context context1;
private OnClickListener(Context context0) {
this.context1 = context0;
}
#Override
public void onClick(View v) {
showIcons(v);
}
private void showIcons(View v) {
pos = main_view.getChildPosition(v);
Log.e("CLICKED","pos: "+pos);
}
}
private class RootAdapter extends RecyclerView.Adapter<RootAdapter.RootViewHolder> {
private final LayoutInflater inflater;
String[] _items = new String[]{"GROUP 1", "GROUP 2", "GROUP 3", "GROUP 4"};
private ArrayList<DataModelMain> dataSet;
public RootAdapter(Context context,ArrayList<DataModelMain> data) {
inflater = LayoutInflater.from(context);
this.dataSet = data;
}
#Override
public RootViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View view = inflater.inflate(R.layout.card_main, viewGroup, false);
RootViewHolder rvi = new RootViewHolder(view);
view.setOnClickListener(MainActivity.onClickListener);
return rvi;
}
#Override
public void onBindViewHolder(RootViewHolder rootViewHolder, int i) {
rootViewHolder.recyclerViewChild.setLayoutManager(new LinearLayoutManager(inflater.getContext()));
rootViewHolder.recyclerViewChild.setAdapter(new ChildAdapter(inflater,dataSet));
}
#Override
public int getItemCount() {
return _items.length;
}
class RootViewHolder extends RecyclerView.ViewHolder {
RecyclerView recyclerViewChild;
public RootViewHolder(View itemView) {
super(itemView);
recyclerViewChild = (RecyclerView) itemView.findViewById(R.id.recycler_partners);
}
}
}
private class ChildAdapter extends RecyclerView.Adapter<ChildAdapter.ChildViewHolder> {
private LayoutInflater _inflater;
private ArrayList<DataModelMain> dataSet;
public ChildAdapter(LayoutInflater inflater,ArrayList<DataModelMain> data) {
_inflater = inflater;
this.dataSet = data;
}
#Override
public ChildViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View view = _inflater.inflate(R.layout.card_partner, viewGroup, false);
ChildViewHolder rvi = new ChildViewHolder(view);
view.setOnClickListener(MainActivity.myOnClickListener);
return rvi;
}
#Override
public void onBindViewHolder(ChildViewHolder holder, int listPosition) {
TextView name = holder.tvName;
TextView cont = holder.tvCont;
TextView flight = holder.tvFlight;
TextView pnr = holder.tvPNR;
TextView time = holder.tvTime;
ImageView type = holder.im_type;
ImageView pic = holder.im_pic;
ImageView logo = holder.im_logo;
CardView cardView = holder.card;
name.setText(dataSet.get(listPosition).getName());
cont.setText(dataSet.get(listPosition).getContact());
flight.setText(dataSet.get(listPosition).getFlight());
pnr.setText(dataSet.get(listPosition).getPnr());
time.setText(dataSet.get(listPosition).getTime());
type.setImageResource(dataSet.get(listPosition).getType());
pic.setImageResource(dataSet.get(listPosition).getImage());
logo.setImageResource(dataSet.get(listPosition).getLogo());
switch (dataSet.get(listPosition).getType()){
case R.mipmap.gov:
cardView.setCardBackgroundColor(Color.parseColor("#FAFAD2"));
break;
case R.mipmap.vip:
cardView.setCardBackgroundColor(Color.parseColor("#CDFFCD"));
break;
case R.mipmap.jail:
cardView.setCardBackgroundColor(Color.parseColor("#FFE4E1"));
break;
case R.mipmap.ban:
cardView.setCardBackgroundColor(Color.parseColor("#DCDCDC"));
break;
}
}
#Override
public int getItemCount() {
return dataSet.size();
}
public class ChildViewHolder extends RecyclerView.ViewHolder {
ImageView im_type,im_pic,im_logo;
TextView tvName,tvCont,tvFlight,tvPNR,tvTime;
CardView card;
public ChildViewHolder(View itemView) {
super(itemView);
this.card = (CardView) itemView.findViewById(R.id.card_view);
this.im_type = (ImageView) itemView.findViewById(R.id.p_type);
this.im_pic = (ImageView) itemView.findViewById(R.id.p_profile);
this.im_logo = (ImageView) itemView.findViewById(R.id.p_air_lines);
this.tvName = (TextView) itemView.findViewById(R.id.p_name);
this.tvCont = (TextView) itemView.findViewById(R.id.p_mob);
this.tvFlight = (TextView) itemView.findViewById(R.id.p_flight);
this.tvPNR = (TextView) itemView.findViewById(R.id.p_pnr);
this.tvTime = (TextView) itemView.findViewById(R.id.p_timer);
}
}
}
}
How about making the root/parent cardView clickable??
Give an id to the cardView item of the parent recyclerView. Place it in your ViewHolderClass and then assign a onCLickListener to the cardView in BindViewHolder like this:
rootViewHolder.rootCardView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// keep an track of the selected position of the cardView and store it in a global/local variable
}
});
you can track the adapter position of the selected cardView using
rootViewHolder.getAdapterPosition()
Note: rootViewHolder is written as per your ViewHolder class
I hope this helps !!

Custom Adapter starts before ArrayList is ready

I'm making a list of links and for that I have made a custom adapter, but the list is not ready when the adapter starts so I get the following error:
java.lang.RuntimeException: Unable to start activity ComponentInfo{}: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.Object android.content.Context.getSystemService(java.lang.String)' on a null object reference
this is because when the adapter is started the list is empty, and just moments after the list is filled but it's too late here is my code:
UPDATE: the code has been changed so now I du not get the error but it doesn't run getView in the adapter:
public class Controller extends Activity {
private String TAG = Controller.class.getSimpleName();
private String http;
CustomAdapter adapter;
public Controller con = null;
private ListView lv;
private static String url;
ArrayList<Selfservice> linkList = new ArrayList<Selfservice>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_view);
con = this;
http = this.getString(R.string.http);
url = this.getString(R.string.path1);
new GetLinks().execute();
lv = (ListView)findViewById(R.id.list);
//Resources res = getResources();
//adapter = new CustomAdapter(con, linkList, res);
//lv.setAdapter(adapter);
}
private class GetLinks extends AsyncTask<Void, Void, List<Selfservice>> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected List<Selfservice> doInBackground(Void... arg0) {
Document doc;
Elements links;
List<Selfservice> returnList = null;
try {
doc = Jsoup.connect(url).timeout(0).get();
links = doc.getElementsByClass("processlink");
returnList = ParseHTML(links);
} catch (IOException e) {
e.printStackTrace();
}
return returnList;
}
#Override
protected void onPostExecute(final List<Selfservice> result) {
super.onPostExecute(result);
runOnUiThread(new Runnable() {
#Override
public void run() {
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
//setSupportActionBar(toolbar);
//getSupportActionBar().setDisplayShowTitleEnabled(false);
toolbar.setTitle("");
toolbar.setSubtitle("");
Resources res = getResources();
Log.e(TAG, linkList.toString());
linkList = (ArrayList<Selfservice>) result;
adapter = new CustomAdapter(con, result, res);
adapter.notifyDataSetChanged();
lv.setAdapter(adapter);
}
});
}
}
and my adapter:
public class CustomAdapter extends BaseAdapter implements OnClickListener {
private String TAG = CustomAdapter.class.getSimpleName();
Context context;
List<Selfservice> data;
private Activity activity;
public Resources res;
Selfservice self = null;
private static LayoutInflater inflater;
int layoutResourceId = 0;
public CustomAdapter(Activity act, List<Selfservice> dataList, Resources resources) {
res = resources;
activity = act;
data = dataList;
}
private class Holder {
TextView title;
TextView link;
}
#Override
public int getCount() {
return data.size();
}
#Override
public Object getItem(int pos) {
return pos;
}
#Override
public long getItemId(int pos) {
return pos;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View rowView = convertView;
Holder holder;
if(rowView == null){
rowView = inflater.inflate(R.layout.list_item, null);
holder = new Holder();
holder.title = (TextView) rowView.findViewById(R.id.title);
holder.link = (TextView) rowView.findViewById(R.id.link);
rowView.setTag(holder);
}else{
holder = (Holder)rowView.getTag();
}
if(data.size()<=0){
holder.title.setText("did not work");
}else{
self = null;
self = (Selfservice) data.get(position);
holder.title.setText(self.getTitle());
holder.link.setText(self.getLink());
Log.i(TAG, "adapter");
rowView.setOnClickListener(new OnItemClickListener(position));
}
return rowView;
}
#Override
public void onClick(View v){
Log.v("CustomAdapter", "row clicked");
}
private class OnItemClickListener implements OnClickListener{
private int mPos;
OnItemClickListener(int position){
mPos = position;
}
#Override
public void onClick(View arg0){
Controller con = (Controller)activity;
con.onItemClick(mPos);
}
}
}
So How do I get the adapter to wait to the list is full?
firstly use ArrayAdapter<Selfservice> instead of BaseAdapter
use constructor
public CustomAdapter(Context context, int resource, List<Selfservice> objects) {
super(context, resource, objects);
data = objects;
}
then override only two methods
public int getCount()
public View getView(int position, View convertView, ViewGroup parent)
then return list.size() in getCount()
in getView() method
if (convertView == null) {
LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = inflater.inflate(R.layout.list_item, null);
}
in doInBackground() method in the try block
instead of linkList = ParseHTML(links);
do linkList.addAll(ParseHTML(links));
and in onPostExcecute() method
adapter.notifyDatasetChanged(); in the ui thread
You can create the adapter in the onPostExecute;
Change the Async Task to this:
private class GetLinks extends AsyncTask<Void, Void, List<Selfservice>> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... arg0) {
Document doc;
Elements links;
List<Selfservice> returnList
try {
doc = Jsoup.connect(url).timeout(10000).get();
links = doc.getElementsByClass("processlink");
returnList = ParseHTML(links);
} catch (IOException e) {
e.printStackTrace();
}
return returnList;
}
#Override
protected void onPostExecute(List<Selfservice> result) {
super.onPostExecute(result);
runOnUiThread(new Runnable() {
#Override
public void run() {
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
//setSupportActionBar(toolbar);
//getSupportActionBar().setDisplayShowTitleEnabled(false);
toolbar.setTitle("");
toolbar.setSubtitle("");
linkList = result
adapter = new CustomAdapter(con, result, res);
lv.setAdapter(adapter);
}
});
}
This way you will only create the adapter when your list is ready.
Edit:
You are not creating the variable context inside your adapter. Change your constructor to this:
public CustomAdapter(Context context, Activity act, List<Selfservice> dataList, Resources resources) {
res = resources;
activity = act;
data = dataList;
this.context = context;
}
And you will stop seeing the NullPointerExecption

list view adapter setting null object on custom dialog

hi friends i had tried to implement list view in the custom dialog and passing data dynamically by using JSON and searched everywhere but don't got any solution i had tried everything from past 3 days and also i don't see any wrong in my code too i had set adapter correctly i am getting this error
Attempt to invoke virtual method 'void android.widget.ListView.setAdapter(android.widget.ListAdapter)' on a null object reference
public class Cat_comment_adap extends BaseAdapter {
String cid;
ImageLoader imageLoader = AppController.getInstance().getImageLoader();
int idddget;
private LayoutInflater inflater;
private List<CurrentList> catlist;
private PopupWindow commentWindow;
ArrayList<CurrentList> commentlist = new ArrayList<CurrentList>();
Activity activity;
public Cat_comment_adap(Activity activity, List<CurrentList> catlist) {
this.activity = activity;
this.catlist = catlist;
}
#Override
public int getCount() {
return catlist.size();
}
#Override
public Object getItem(int i) {
return catlist.get(i);
}
#Override
public long getItemId(int i) {
return i;
}
#Override
public View getView(int i, View view, ViewGroup viewGroup) {
inflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(R.layout.cat_row, viewGroup, false);
NetworkImageView singleimg = (NetworkImageView) view.findViewById(R.id.singleimg);
final ImageView agree = (ImageView) view.findViewById(R.id.agree);
ImageView commentbox = (ImageView) view.findViewById(R.id.commentbox);
commentbox.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
onShowpopup(view);
Toast.makeText(activity, "Comments Button clicked", Toast.LENGTH_SHORT).show();
}
});
final CurrentList catertlist = catlist.get(i);
singleimg.setImageUrl(catertlist.getCatimg(), imageLoader);
idddget = catertlist.getCcids();
SharedPreferences eveid = activity.getSharedPreferences("loginPrefs", Context.MODE_PRIVATE);
cid = eveid.getString("userid", "");
agree.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String url = "http://sampletemplates.net/majority/api.php?action=addVote&question_id=" + idddget + "&user_id=" + cid + "&vote=1&source=android";
Log.d("Vote", "http://sampletemplates.net/majority/api.php?action=addVote&question_id=" + idddget + "&user_id=" + cid + "&vote=1&source=android");
JsonObjectRequest voting = new JsonObjectRequest(Request.Method.POST, url, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
String votings = response.getString("status");
if (votings.equals("success")) {
agree.setImageResource(R.drawable.agreed);
Toast.makeText(activity, "Voted Successfully", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(activity, "Already Voted", Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
AppController.getInstance().addToRequestQueue(voting);
}
});
return view;
}
public void onShowpopup(View v) {
LayoutInflater layoutInflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View popupview = layoutInflater.inflate(R.layout.current_comment_dialog, null);
ListView commentsListView = (ListView) v.findViewById(R.id.commentsListView);
// commentAdapter = new comment_adapter(activity, commentlist);
WindowManager wm = (WindowManager) activity.getSystemService(Context.WINDOW_SERVICE);
Display display = wm.getDefaultDisplay();
Point size = new Point();
display.getSize(size);
int width = size.x;
int height = size.y;
commentWindow = new PopupWindow(popupview, width - 50, height - 400, true);
commentWindow.setBackgroundDrawable(activity.getResources().getDrawable(R.drawable.comment_bg));
commentWindow.setFocusable(true);
commentWindow.setOutsideTouchable(true);
commentWindow.showAtLocation(v, Gravity.BOTTOM, 0, 100);
commentsListView.setAdapter(new comment_adapter(activity,commentlist));
commentAdapter.notifyDataSetChanged();
}
Adapter class
public class comment_adapter extends BaseAdapter {
private Activity activity;
private LayoutInflater inflater;
private List<CurrentList> commentlist;
public comment_adapter(Activity activity, List<CurrentList> commentlist){
this.activity = activity;
this.commentlist = commentlist;
}
#Override
public int getCount() {
return commentlist.size();
}
#Override
public Object getItem(int i) {
return commentlist.get(i);
}
#Override
public long getItemId(int i) {
return i;
}
#Override
public View getView(int i, View view, ViewGroup viewGroup) {
if (inflater == null)
inflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (view == null)
view = inflater.inflate(R.layout.comment_row, viewGroup, false);
TextView user_name = (TextView) view.findViewById(R.id.user_name);
TextView posttime = (TextView) view.findViewById(R.id.posttime);
TextView comtsdetails = (TextView) view.findViewById(R.id.comtsdetails);
CurrentList listofcomments = commentlist.get(i);
user_name.setText(listofcomments.getEvtusername());
posttime.setText(listofcomments.getTimetaken());
comtsdetails.setText(listofcomments.getEvcomment());
return view;
}
}
here in this class Cat_comment_adap in the method onShowpopup change
View popupview = layoutInflater.inflate(R.layout.current_comment_dialog, null);
ListView commentsListView = (ListView) v.findViewById(R.id.commentsListView);
to
View popupview = layoutInflater.inflate(R.layout.current_comment_dialog, null);
ListView commentsListView = (ListView) popupview.findViewById(R.id.commentsListView);
because your inflating listview from this layout so u have to give the name of inflated layout object there not the parameter of the method
public void onClick(View view) {
onShowpopup(view);
Toast.makeText(activity, "Comments Button clicked", Toast.LENGTH_SHORT).show();
}
Here passed view is not R.layout.cat_row as you think but it's a button that was clicked.
So just use onShowpopup(self.view) and it will work :)
or change to onClick(View clickedButton)

Android : custom adapter showing data multiple times

I am building a test application with kinvey as a backend.I download the kinvey entities from the backend and add them to my adapter.The adapter behaves wrongly the first data entity is accessed three times.
The code for adapter is below
public class ImageAdapter extends BaseAdapter {
private static final String TAG = ImageAdapter.class.getSimpleName();
private static ImageFetcher mImageFetcher;
private ArrayList<ImageEntity> mImageEntities;
private Context mContext;
private LayoutInflater mLayoutInflater;
public ImageAdapter(Context context, ArrayList<ImageEntity> imageEntities) {
mContext = context;
mImageEntities = imageEntities;
mLayoutInflater = LayoutInflater.from(context);
mImageFetcher = new ImageFetcher(context);
}
#Override
public int getCount() {
return mImageEntities.size();
}
#Override
public Object getItem(int position) {
return mImageEntities.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder viewHolder = null;
if (convertView != null) {
viewHolder = (ViewHolder) convertView.getTag();
} else {
convertView = mLayoutInflater.inflate(R.layout.grid_item_layout, parent, false);
viewHolder = new ViewHolder(convertView);
convertView.setTag(viewHolder);
}
ImageEntity imageEntity = mImageEntities.get(position);
Log.d(TAG, imageEntity.getId());
viewHolder.textView.setText(imageEntity.getId());
viewHolder.imageView.setImageDrawable(mContext.getResources().getDrawable(R.drawable.ic_launcher));
mImageFetcher.loadImage(viewHolder.imageView, imageEntity.getId());
return convertView;
}
static class ViewHolder {
ImageView imageView;
TextView textView;
public ViewHolder(View v) {
imageView = (ImageView) v.findViewById(R.id.id_simple_image);
textView = (TextView) v.findViewById(R.id.textview);
}
}
}
The code for the Activity is
public class ImageActivity extends ActionBarActivity {
private static final int CAPTURE_IMAGE_REQUEST_CODE = 11;
private static final int MEDiA_TYPE_IMAGE = 1;
private static final int PICK_IMAGE = 2;
private static final String TAG = ImageActivity.class.getSimpleName();
private Client mKinveyClient;
private EntitySource mEntitySource;
private Uri mFileUri;
private GridView mGridView;
private ImageAdapter mImageAdapter;
private ArrayList<ImageEntity> mImageEntities;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_image);
mEntitySource = EntitySource.getEntitySource(this);
mKinveyClient = TestApplication.getClientInstance();
mGridView = (GridView) findViewById(R.id.gridview);
mImageEntities = new ArrayList<>();
if (!mKinveyClient.user().isUserLoggedIn()) {
Intent intent = new Intent(this, LoginActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
}
mImageAdapter = new ImageAdapter(this, mImageEntities);
mGridView.setAdapter(mImageAdapter);
}
private void updateData() {
AsyncAppData<ImageEntity> events = mKinveyClient.appData("events", ImageEntity.class);
events.get(new KinveyListCallback<ImageEntity>() {
#Override
public void onSuccess(ImageEntity[] imageEntities) {
mImageEntities.addAll(Arrays.asList(imageEntities));
for (ImageEntity imageEntity : imageEntities) {
System.out.println(imageEntity.getId());
}
mImageAdapter.notifyDataSetChanged();
}
#Override
public void onFailure(Throwable throwable) {
Log.d(TAG, "Fail " + throwable.getMessage());
}
});
}
Log: shows three entities are downloaded but in adapter the first entity is accessed three times.Please help
12-22 18:43:39.742: V/Kinvey - Client(16995): adding new instance of AppData, new collection name
12-22 18:43:40.628: I/System.out(16995): 5497cdc4b76664a0030358a2
12-22 18:43:40.628: I/System.out(16995): 5497cedfe21a6f05030016b8
12-22 18:43:40.629: I/System.out(16995): 5498062bc0f22386510111b6
12-22 18:43:40.635: D/ImageAdapter(16995): 5497cdc4b76664a0030358a2
12-22 18:43:40.640: D/ImageAdapter(16995): 5497cdc4b76664a0030358a2
12-22 18:43:40.641: D/ImageAdapter(16995): 5497cdc4b76664a0030358a2
12-22 18:43:40.643: D/ImageAdapter(16995): 5497cedfe21a6f05030016b8
You are adding to the array every time you get results back in updateData. You need to reset the collection each time, so call clear first:
mImageEntities.clear();
mImageEntities.addAll(Arrays.asList(imageEntities));

Categories