Issue with checkbox checked - java

i am use this for setting checkbox in listview i have follow all step as per given tutorial, but there are some critical issue with output, is that when i am select first checkbox and scroll down it will change selected item and automatically appear 3rd.
so i think there are something wrong with getview. so please help me out this ....
here is my code ::
package com.AppFavorits;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import android.app.ListActivity;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.CompoundButton;
import android.widget.ListView;
import android.widget.RatingBar;
public class Favorites extends ListActivity {
protected static final String TAG = "Favorites";
CommentsDataSource datasource;
ListView lstFavrowlistv;
ArrayList alAppName;
float[] rate;
boolean[] bSelected;
ArrayList<Comment> alPackagenm;
Drawable[] alIcon;
ViewHolder holder;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
protected void onResume() {
super.onResume();
datasource = new CommentsDataSource(this);
datasource.open();
alAppName = datasource.getAllComments();
alPackagenm = datasource.getAllPackage();
Log.i(TAG, "values >>>" + alAppName);
Log.i(TAG, "values >>>" + alPackagenm);
int inc = 0;
alIcon = new Drawable[200];
for (int i = 0; i < alPackagenm.size(); i++) {
Log.i(TAG, "Appname >>>" + GetAllApp.lstpinfo.get(i).pname);
for (int j = 0; j < GetAllApp.lstpinfo.size(); j++) {
if (alPackagenm
.get(i)
.toString()
.equalsIgnoreCase(
GetAllApp.lstpinfo.get(j).pname.toString())) {
alIcon[inc] = GetAllApp.lstpinfo.get(j).icon;
Log.i("TAG", "sqlPackagename"
+ alPackagenm.get(i).toString());
Log.i("TAG", "from getAllapp"
+ GetAllApp.lstpinfo.get(j).pname.toString());
inc++;
}
}
}
ArrayList<RowModel> list = new ArrayList<RowModel>();
ArrayList<Model> Mlist = new ArrayList<Model>();
rate = new float[alAppName.size()];
bSelected = new boolean[alAppName.size()];
Iterator itr = alAppName.iterator();
String strVal = null;
while (itr.hasNext()) {
strVal += itr.next().toString() + ",";
}
int lastIndex = strVal.lastIndexOf(",");
strVal = strVal.substring(0, lastIndex);
System.out.println("Output String is : " + strVal);
String strAr[] = strVal.split(",");
for (int i = 0; i < strAr.length; i++) {
System.out.println("strAr[" + i + "] " + strAr[i]);
}
for (String s : strAr) {
list.add(new RowModel(s));
}
for (String s : strAr) {
Mlist.add(new Model(s));
}
setListAdapter(new RatingAdapter(list, Mlist));
datasource.close();
}
class RowModel {
String label;
float rating = 0.0f;
RowModel(String label) {
this.label = label;
}
public String toString() {
if (rating >= 3.0) {
return (label.toUpperCase());
}
return (label);
}
}
private RowModel getModel(int position) {
return (((RatingAdapter) getListAdapter()).getItem(position));
}
class RatingAdapter extends ArrayAdapter<RowModel> {
private ArrayList<Model> mlist;
RatingAdapter(ArrayList<RowModel> list, ArrayList<Model> mlist) {
super(Favorites.this, R.layout.outbox_list_item,
R.id.txvxFavrowiconappname, list);
this.mlist = mlist;
}
public View getView(final int position, View convertView,
ViewGroup parent) {
View row = super.getView(position, convertView, parent);
holder = (ViewHolder) row.getTag();
if (holder == null) {
holder = new ViewHolder(row);
row.setTag(holder);
RatingBar.OnRatingBarChangeListener l = new RatingBar.OnRatingBarChangeListener() {
public void onRatingChanged(RatingBar ratingBar,
float rating, boolean fromTouch) {
Integer myPosition = (Integer) ratingBar.getTag();
RowModel model = getModel(myPosition);
model.rating = rating;
rate[position] = rating;
}
};
holder.chkbxFavrowsel
.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(
CompoundButton buttonView, boolean isChecked) {
Model element = (Model) holder.chkbxFavrowsel
.getTag();
element.setSelected(buttonView.isChecked());
bSelected[position] = isChecked;
}
});
holder.chkbxFavrowsel.setTag(mlist.get(position));
holder.ratingBar1.setOnRatingBarChangeListener(l);
} else {
row = convertView;
((ViewHolder) row.getTag()).chkbxFavrowsel.setTag(mlist
.get(position));
}
RowModel model = getModel(position);
ViewHolder holder = (ViewHolder) row.getTag();
holder.ratingBar1.setTag(new Integer(position));
holder.ratingBar1.setRating(model.rating);
holder.imgvFavrowiconappicon.setImageDrawable(alIcon[position]);
holder.txvxFavrowiconappname.setText(alAppName.get(position)
.toString());
holder.chkbxFavrowsel.setChecked(mlist.get(position).isSelected());
return (row);
}
}
}

I really don't understand your code exactly what you are trying to do. I haven't seen before this you are checking holder == null where as it should be convertView == null. If you have a scrolling issue you can check my blog post
holder = (ViewHolder) row.getTag();
if (holder == null) {
holder = new ViewHolder(row);
row.setTag(holder);
...
}
else {
row = convertView;
((ViewHolder) row.getTag()).chkbxFavrowsel.setTag(mlist
.get(position));
}

Use Below Code to your MainActivity.java file.
public class ListViewActivity extends Activity {
ListView mLstView1;
Button mBtn1;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mLstView1 = (ListView) findViewById(R.id.mLstView1);
String[] lv_items = { "Dipak", "Rahul", "Hiren", "Nandlal", "Keyur",
"Kapil", "Dipak", "Rahul", "Hiren", "Nandlal", "Keyur",
"Kapil" };
;
mLstView1.setAdapter(new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_multiple_choice, lv_items));
mLstView1.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
mBtn1 = (Button) findViewById(R.id.mBtn1);
mBtn1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
// Using a List to hold the IDs, but could use an array.
List<Integer> checkedIDs = new ArrayList<Integer>();
// Get all of the items that have been clicked - either on or
// off
final SparseBooleanArray checkedItems = mLstView1
.getCheckedItemPositions();
for (int i = 0; i < checkedItems.size(); i++) {
// And this tells us the item status at the above position
final boolean isChecked = checkedItems.valueAt(i);
if (isChecked) {
// This tells us the item position we are looking at
final int position = checkedItems.keyAt(i);
// Put the value of the id in our list
checkedIDs.add(position);
System.out.println("Position is:- " + position);
}
}
}
});
}
}

Related

I deleted some items in an adapter and after my setOnClick crash

I'm trying to show a listView after i deleted some items. But, after i deleted some items, OnItemClick crash (java.lang.IllegalStateException: The content of the adapter has changed but ListView did not receive a notification). I want to show a new list after i deleted, like a filter. I already try to use adapter.remove(position) and list.remove(position) like the example down.
My OnItemClick
//listView.invalidateViews();
//listView.refreshDrawableState();
//pullToRefresh.setRefreshing(false);
Collections.sort(lista, new Viagem());
adapter.notifyDataSetChanged();
System.out.println(position);
Viagem vg = (Viagem) parent.getItemAtPosition(position);
Bundle bundle = new Bundle();
bundle.putString("usuario", usuario);
bundle.putString("usuarioViagem", vg.getUsuario());
bundle.putString("data", vg.getData());
bundle.putString("hora", vg.getHora());
Intent intent = new Intent(getApplicationContext(), MostraInfoViagemActivity.class);
intent.putExtras(bundle);
startActivity(intent);
}
});
How i deleted some items.
public void delete(){
jaEntrou = false;
ArrayList <Integer> apagar = new ArrayList<>();
Viagem aux;
List<String> listaUsuarios;
for(int i = 0 ; i < lista.size(); i++){
jaEntrou = false;
aux = lista.get(i);
listaUsuarios = aux.getUsuarios();
for(int j = 0; j < listaUsuarios.size(); j++){
if(listaUsuarios.get(j).equals(usuario)){
jaEntrou = true;
}
}
if(!jaEntrou){
apagar.add(i);
}
}
for(int i = apagar.size() - 1; i >= 0; i--){
int index = apagar.get(i);
lista.remove(index);
//adapter.removeItem(apagar.get(i));
//adapter.notifyDataSetChanged();
}
adapter.notifyDataSetChanged();
listView.invalidateViews();
listView.refreshDrawableState();
lista = fb.getLista();
Intent intent = new Intent(getApplicationContext(), OnlyDelay.class);
startActivity(intent);
}
My Custom List
package com.example.caronassuldeminas;
import android.app.Activity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
import java.util.List;
public class Custom_List extends BaseAdapter {
private List<Viagem> viagens;
private Activity act;
private Object orig;
public Custom_List(List<Viagem> viagens, Activity act){
this.viagens = viagens;
this.act = act;
}
#Override
public int getCount() {
return viagens.size();
}
#Override
public Object getItem(int position) {
return viagens.get(position);
}
#Override
public long getItemId(int position) {
return 0;
}
public void removeItem(int position){
viagens.remove(position);
}
public void attLista(List<Viagem> viagens){
this.viagens = viagens;
}
public Viagem getViagem(int position){
return viagens.get(position);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = act.getLayoutInflater().inflate(R.layout.list_item, parent, false);
TextView cidadePartida = (TextView) view.findViewById(R.id.textView8);
TextView cidadeChegada = (TextView) view.findViewById(R.id.textView9);
TextView dia = (TextView) view.findViewById(R.id.textView10);
TextView hora = (TextView) view.findViewById(R.id.textView11);
cidadePartida.setText(viagens.get(position).getCidadePartida());
cidadeChegada.setText(viagens.get(position).getCidadeChegada());
dia.setText("Dia: " + viagens.get(position).getData());
hora.setText("Hora: " + padronizaHora(viagens.get(position).getHora()) + "h");
return view;
}
public String padronizaHora(String data){
if(data.length() == 5)
return data;
int pos = 0;
String resu = "";
for(int i = 0; i < data.length(); i++){
if(data.charAt(i) == ':'){
pos = i;
break;
}
}
if(pos < 2){
resu += "0";
}
resu += data.substring(0, pos);
resu += ":";
if(data.charAt(data.length()-1) == '0'){
resu += "0";
}
resu += data.substring(pos + 1);
return resu;
}
}
Usually, when I add or remove items from the ArrayList that drives the ListView and Adapter, I recreate the adapter and re-assign it to the ListView rather than call notifyDatasetChanged. This also seems to prevent any crashes, which most likely are caused by the adapter trying to reference ArrayList elements that are no longer there.
adapter = new TripSelectAdapter(this, thisContext, tripItems);
mTripList.setAdapter(adapter);

Recycler view list items are showing duplicate few items at the bottom of listview

I have one recycle list view .In this I have one button .on click list view item button shows.On button click I hit one api to perform action .After performing action ,at the bottom of list automatically one item get repeat. when ever I perform api hit action same time items add at the bottom of list .Like as I perform api hit action 4 times then every time one-one item get add at the bottom of list . Please provide me solution to resolve this.
Below I'm providing code of my adapter class :-
import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Build;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.NetworkResponse;
import com.android.volley.Request;
import com.android.volley.VolleyError;
import com.dockedinDoctor.app.R;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import pojo.AvailableTimeSlots;
import pojo.GetBlockedTimings;
import pojo.GetDoctorScheduleDetail;
import utils.Common;
import utils.ItemClickListener;
import utils.NetworkManager;
import utils.NetworkResponseListenerJSONObject;
import utils.SessionManager;
import utils.ShowMessage;
import static utils.Common.createProgressDialog;
public class MyScheduleAdapter extends RecyclerView.Adapter<MyScheduleAdapter.ViewHolder> {
private static final String TAG = "MyScheduleTwoAdapter";
private ArrayList<GetDoctorScheduleDetail> getDoctorScheduleDetails;
private ArrayList<GetBlockedTimings> getBlockedTimingses = new ArrayList<>();
private ArrayList<AvailableTimeSlots> availableTimeSlotses = new ArrayList<>();
Context context;
private LayoutInflater inflater = null;
private int mSelectedItemPosition = -1;
Activity parentActivity;
ProgressDialog pd;
int fk_time_id;
int fk_schedule_id;
int fkscheduleid;
int getFk_schedule_id;
int block_time_slot_id;
int time_slot_id;
String DateofSlot;
String BlockDateOfSlot;
int blockid;
SessionManager manager = new SessionManager();
int Doc_Id;
ArrayList<Integer> compare= new ArrayList<Integer>();
ArrayList<Integer> compare_fk= new ArrayList<Integer>();
public MyScheduleAdapter(Context context, ArrayList<GetDoctorScheduleDetail> getDoctorScheduleDetails) {
this.context = context;
this.getDoctorScheduleDetails = getDoctorScheduleDetails;
inflater = LayoutInflater.from(context);
// setHasStableIds(true);
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = inflater.inflate(R.layout.row_item_get_doctor_schedule, parent, false);
MyScheduleAdapter.ViewHolder holder = new MyScheduleAdapter.ViewHolder(view);
return holder;
}
#Override
public void onBindViewHolder(final ViewHolder holder, int position) {
final GetDoctorScheduleDetail pojo = getDoctorScheduleDetails.get(position);
fkscheduleid = pojo.getScheduleId();
DateofSlot = pojo.getDateOfSlot();
try {
Doc_Id = manager.getPreferencesInt(context, "DocId");
Log.e(TAG, "DOCID" + Doc_Id);
holder.bindDataWithViewHolder(pojo, position);
//getting data from availavle timeslots
holder.tv_time_of_slot.setText(pojo.getAvailableTimeSlots().get(position).getTimeOfSlot());
time_slot_id = pojo.getAvailableTimeSlots().get(position).getTimeSlotId();
//want to ge
block_time_slot_id = pojo.getGetBlockedTimings().get(position).getFkTimeId();
BlockDateOfSlot = pojo.getGetBlockedTimings().get(position).getBlockDateOfSlot();
blockid = pojo.getGetBlockedTimings().get(position).getBlockId();
Log.e(TAG, "values_blockk" + time_slot_id +" "+ block_time_slot_id);
compare.add(time_slot_id);//compare is an arraylist using to save Availablearray-->timeslot id
compare_fk.add(block_time_slot_id);//compare_fk is an arraylist using to save getblocktimeid-->fktime id
Log.e(TAG, "compare" + compare);
Log.e(TAG, "compare_fk" + compare_fk);
/*erlier I was using this*/
/*ArrayList<Integer> x = compare;
ArrayList<Integer> y = compare_fk;
for (int i = 0; i < x.size(); i++) {
Integer xval = y.get(i);
for (int j = 0; j < y.size(); j++) {
if (xval.equals(x.get(j))) {
Toast.makeText(context,"same_list"+y.get(j),Toast.LENGTH_SHORT).show();
holder.tv_time_of_slot.setTextColor(Color.RED);
}
}
}*/
int array1Size = compare.size();
int array2Size = compare_fk.size();
if (compare.size() > compare_fk.size()) {
int k = 0;
for (int i = 0; i < compare_fk.size(); i++) {
if (((Integer)compare.get(i)).equals((Integer)compare_fk.get(i))) {
System.out.println((Integer)compare_fk.get(i));
Log.e("values_adapter", String.valueOf(((Integer)compare_fk.get(i))));
}
k = i;
}
}
else {
int k = 0;
for (int i = 0; i < compare.size(); i++) {
if (((Integer)compare.get(i)).equals((Integer) compare_fk.get(i))) {
System.out.println((Integer) compare.get(i));
Log.e("values_adapter11",String.valueOf(((Integer)compare.get(i))));
}
k = i;
}
}
if (time_slot_id == block_time_slot_id)
{
holder.tv_time_of_slot.setTextColor(Color.RED);
}
if (!(pojo.getGetBlockedTimings().get(position).getBlockDateOfSlot().equals("")))
{
holder.tv_d.setText(pojo.getGetBlockedTimings().get(position).getBlockDateOfSlot());
holder.tv_b.setText(pojo.getGetBlockedTimings().get(position).getBlockId());
}
} catch (Exception e) {
e.printStackTrace();
e.getMessage();
}
// //iterate on the general list
// for (int i = 0; i < availableTimeSlotses.size(); i++) {
// int timeSlotId = availableTimeSlotses.get(i).getTimeSlotId();
// if (getFk_time_id == timeSlotId) {
//
// holder.tv_time_of_slot.setText(pojo.getDateOfSlot());
// }
// }
// block api
holder.btn_block.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final Dialog lDialog = new Dialog(context);
lDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
lDialog.setCancelable(false);
lDialog.getWindow().setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT));
lDialog.getWindow().setDimAmount(.7f);
lDialog.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_BLUR_BEHIND);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP_MR1) {
lDialog.getWindow().setElevation(4);
}
lDialog.setContentView(R.layout.popup_no_yes);
TextView tv_titiel = (TextView) lDialog.findViewById(R.id.tv_titiel);
TextView textMsg = (TextView) lDialog.findViewById(R.id.popup_msgs);
Button btnno = (Button) lDialog.findViewById(R.id.popup_no_btn);
Button btnyes = (Button) lDialog.findViewById(R.id.popup_yes_btn);
btnno.setTransformationMethod(null);
btnyes.setTransformationMethod(null);
tv_titiel.setText("Schedule");
textMsg.setText("Are you sure you want to block this slot?");
btnno.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
lDialog.dismiss();
}
});
btnyes.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
LocalBroadcastManager.getInstance(context).sendBroadcast(new Intent("notification_fragment"));
slotBlockingApi(fkscheduleid, time_slot_id);
lDialog.dismiss();
}
});
lDialog.show();
}
});
}
#Override
public int getItemCount() {
return getDoctorScheduleDetails.size();
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public int getItemViewType(int position) {
return position;
}
public void slotBlockingApi(int _fk_schedule_id, int _fk_time_id) {
isOnline();
pd = createProgressDialog(context);
pd.show();
final String requestBody = "'{\"fkScheduledId\":\"" + _fk_schedule_id +
"\",\"fkTimeId\":\"" + _fk_time_id +
"\",\"DoctorId\":\"" + Doc_Id +
"\"}'";
Log.e(TAG, "requset body of slotBlockingApi : " + requestBody);
NetworkManager.getInstance(context).makeNetworkRequestForJSON(
Request.Method.POST,
Common.BASE_URL + "/PostDoctorCheckForAppointmentBeforeSlotBlocking",
null,
requestBody,
null,
new NetworkResponseListenerJSONObject() {
#Override
public void onDataReceived(Object data) {
pd.dismiss();
Log.e(TAG, "response of slotBlockingApi : " + data.toString());
try {
JSONObject jsonObject = new JSONObject(data.toString());
JSONObject ResponseJsonObject1 = jsonObject.getJSONObject("Response");
int ResponseCode = ResponseJsonObject1.getInt("ResponseCode");
String ResponseText = ResponseJsonObject1.getString("ResponseText");
// JSONObject jsonObjectDetail = jsonObject.getJSONObject("Detail");
// Log.e(TAG, "jsonObjectDetail : " + jsonObjectDetail);
// int doc_id = jsonObjectDetail.getInt("DocId");
// if (ResponseText == "No Appointment" || ResponseText.equals("No Appointment") || ResponseText.equalsIgnoreCase("No Appointment")) {
if (ResponseText == "No Appointment" || ResponseText.equals("No Appointment") || ResponseText.equalsIgnoreCase("No Appointment")) {
// if (ResponseText =="No Appointment" || ResponseText.equals("No Appointment")) {
pd = createProgressDialog(context);
pd.show();
final String requestBody = "'{\"utcTimeOffset\":\"" + "330" +
"\",\"BlockedScheduledDate\":\"" + DateofSlot +
"\",\"fkScheduledId\":\"" + fkscheduleid +
"\",\"fkTimeId\":\"" + time_slot_id +
"\"}'";
Log.e(TAG, "requset body of slotBlocking: " + requestBody);
NetworkManager.getInstance(context).makeNetworkRequestForJSON(
Request.Method.POST,
Common.BASE_URL + "/PostDoctorBlockTimeSlot",
null,
requestBody,
null,
new NetworkResponseListenerJSONObject() {
#Override
public void onDataReceived(Object data) {
pd.dismiss();
new ShowMessage(context, "Block Slot","Time slot blocked Successfully");
Log.e(TAG, "response of slotBlocking: " + data.toString());
}
#Override
public void onDataFailed(VolleyError error) {
pd.dismiss();
String json = null;
NetworkResponse response = error.networkResponse;
if (response != null && response.data != null) {
switch (response.statusCode) {
case 302:
Toast.makeText(context, "No Internet Connection Found.", Toast.LENGTH_SHORT).show();
break;
}
//Additional cases
}
}
});
} else {
final Dialog lDialog = new Dialog(context);
lDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
lDialog.setCancelable(false);
lDialog.getWindow().setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT));
lDialog.getWindow().setDimAmount(.7f);
lDialog.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_BLUR_BEHIND);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP_MR1) {
lDialog.getWindow().setElevation(4);
}
lDialog.setContentView(R.layout.custom_popup);
TextView textTitle = (TextView) lDialog.findViewById(R.id.popup_title);
TextView textMsg = (TextView) lDialog.findViewById(R.id.popup_msg);
Button okButton = (Button) lDialog.findViewById(R.id.popup_ok_btn);
okButton.setTransformationMethod(null);
textTitle.setText("Schedule");
textMsg.setText("An appointment has been booked on this slot.");
okButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
lDialog.dismiss();
}
});
lDialog.show();
}
// else if (ResponseCode == 0 || ResponseCode == 2) {
// new ShowMessage(context, ResponseText);
// }
} catch (JSONException e) {
e.printStackTrace();
}
}
#Override
public void onDataFailed(VolleyError error) {
pd.dismiss();
String json = null;
NetworkResponse response = error.networkResponse;
if (response != null && response.data != null) {
switch (response.statusCode) {
case 302:
Toast.makeText(context, "No Internet Connection Found.", Toast.LENGTH_SHORT).show();
break;
}
//Additional cases
}
}
});
}
public boolean isOnline() {
ConnectivityManager conMgr = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = conMgr.getActiveNetworkInfo();
if (netInfo == null || !netInfo.isConnected() || !netInfo.isAvailable()) {
new ShowMessage(context, "Network error","Internet not available, Cross check your internet connectivity and try again");
}
return true;
}
/**
* VIEW HOLDER CLASS DEFINE HERE
*/
public class ViewHolder extends RecyclerView.ViewHolder {
#BindView(R.id.ll_row_item_get_doctor_schedule)
LinearLayout ll_row_item_get_doctor_schedule;
#BindView(R.id.tv_time_of_slot)
TextView tv_time_of_slot;
#BindView(R.id.btn_block)
Button btn_block;
#BindView(R.id.btn_unblock)
Button btn_unblock;
#BindView(R.id.tv_d)
TextView tv_d;
#BindView(R.id.tv_b)
TextView tv_b;
GetDoctorScheduleDetail doctorScheduleDetail = null;
ItemClickListener clickListener;
private ViewHolder(View itemView) {
super(itemView);
ButterKnife.bind(this, itemView);
ll_row_item_get_doctor_schedule.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Handling for background selection state changed
int previousSelectState = mSelectedItemPosition;
mSelectedItemPosition = getAdapterPosition();
//notify previous selected item
notifyItemChanged(previousSelectState);
//notify new selected Item
notifyItemChanged(mSelectedItemPosition);
//Your other handling in onclick
}
});
}
public void setClickListener(ItemClickListener itemClickListener) {
this.clickListener = itemClickListener;
}
#OnClick
public void onClickMethod(View v) {
clickListener.onClick(v, getPosition(), false);
}
public void bindDataWithViewHolder(GetDoctorScheduleDetail schedulePojo, int currentPosition) {
this.doctorScheduleDetail = schedulePojo;
//Handle selection state in object View.
if (currentPosition == mSelectedItemPosition) {
btn_block.setVisibility(View.VISIBLE);
} else {
btn_block.setVisibility(View.GONE);
}
//other View binding logics like setting text , loading image etc.
}
}
}

cannot find symbol method onActivityResult(int,int,Intent)

Im following the tutorial of In-app Billing from the following link:
Android Studio Google Play In-app Billing Tutorial.
Im implementing this logic in a Contact Adapter class which extends Base Adapter. In tutorial it is implemented in a class which extends Activity.
Error comes on onActivityResult(). I read several questions on this and I understand this method should be written in class which extends Activity but in my case the scenario is different.
Is there any way to solve this without writing onActivityResult method in MainActivity class.. and if not what should I do?
Heres ContactAdapter.java
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.TextView;
import android.widget.Toast;
import com.neirx.myco.smsproject.util.IabHelper;
import com.neirx.myco.smsproject.util.IabResult;
import com.neirx.myco.smsproject.util.Inventory;
import com.neirx.myco.smsproject.util.Purchase;
import java.util.List;
public class ContactAdapter extends BaseAdapter {
private static final java.lang.String CLASS_NAME = "<ContactAdapter> ";
Context context;
List<Contact> objects;
LayoutInflater lInflater;
MainActivity activity;
static final String ITEM_SKU = "android.test.purchased";
IabHelper mHelper;
int count = 0;
int get_limit;
private int limit_counter = 0;
private int max_limit = 2;
boolean testbool = true;
public ContactAdapter(Context context, List<Contact> contact) {
this.context = context;
objects = contact;
lInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
activity = (MainActivity) context;
}
#Override
public int getCount() {
int selectedCount = 0;
int nonSelectedCount = 0;
int size = 0;
for(Contact contact : objects){
if(contact.isChecked()) selectedCount++;
else nonSelectedCount++;
}
if(activity.isShowSelected()) size += selectedCount;
if(activity.isShowNonSelected()) size += nonSelectedCount;
return size;
}
#Override
public Object getItem(int position) {
return objects.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
public void buyClick() {
mHelper.launchPurchaseFlow(activity, ITEM_SKU, 10001, mPurchaseFinishedListener, "mypurchasetoken");
}
#Override
protected void onActivityResult(int requestCode, int resultCode,Intent data)
{
if (!mHelper.handleActivityResult(requestCode,resultCode, data)) {
super.onActivityResult(requestCode, resultCode, data);
}
}
IabHelper.OnIabPurchaseFinishedListener mPurchaseFinishedListener = new IabHelper.OnIabPurchaseFinishedListener() {
public void onIabPurchaseFinished(IabResult result,Purchase purchase)
{
if (result.isFailure()) {
// Handle error
Log.d("----FAILURE 1---", "FAIL 1");
return;
}
else if (purchase.getSku().equals(ITEM_SKU)) {
consumeItem();
//buyButton.setEnabled(false);
}
}
};
public void consumeItem() {
mHelper.queryInventoryAsync(mReceivedInventoryListener);
}
IabHelper.QueryInventoryFinishedListener mReceivedInventoryListener = new IabHelper.QueryInventoryFinishedListener() {
public void onQueryInventoryFinished(IabResult result,Inventory inventory) {
if (result.isFailure()) {
// Handle failure
Log.d("----FAILURE 2---", "FAIL 2");
} else {
mHelper.consumeAsync(inventory.getPurchase(ITEM_SKU),mConsumeFinishedListener);
}
}
};
IabHelper.OnConsumeFinishedListener mConsumeFinishedListener = new IabHelper.OnConsumeFinishedListener() {
public void onConsumeFinished(Purchase purchase,IabResult result) {
if (result.isSuccess()) {
//clickButton.setEnabled(true);
Log.d("----Success ----", "Success");
} else {
// handle error
Log.d("----FAILURE 3---", "FAIL 3");
}
}
};
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = convertView;
String base64EncodedPublicKey = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAxW650UixX2dLFECVdOpTh5OpBTqHwsznQAKd/cVcqKhrXROy4+Gj6B7M6wbkhTaloNSzTOf+nw9t1LZZ19Vlr6kcwmtxP+V/HOFwjf/NB69StOONogXtGKDyRrxtVaPM5es3yGy/aP/LXWfTLFQYJvur4AePonuRXz33iufBq5ITDQJ0+0D/o/mGtadJv0ZMsP9LV/qrMqruoqpSdaIiw5TGXdzYlJTuoP3GwS9kRyZKDeG/70KZ28W/ZclVWAdnZ7aCeDURYDV3a4pmGp5/cIvKwbex6Y7KbQYENX5ObSgNoFHLdyPTdkYaeuU9O6pet2TjGUCKr8n4M5KUMZVm8QIDAQAB";
mHelper = new IabHelper(context, base64EncodedPublicKey);
mHelper.startSetup(new IabHelper.OnIabSetupFinishedListener() {
public void onIabSetupFinished(IabResult result)
{
if (!result.isSuccess()) {
Log.d("---MY TAG---", "In-app Billing setup failed: " +
result);
} else {
Log.d("---MY TAG---", "In-app Billing is set up OK");
}
}
});
SharedPreferences limit_pref = context.getSharedPreferences(Statical.PREF_LIMIT, Context.MODE_PRIVATE);
get_limit = limit_pref.getInt("LIMIT_KEY",0);
//Log.d("----- STORED VALUE-----", "Value is: "+get_limit);
Log.d("----- Max VALUE-----", "Value is: "+max_limit);
if (view == null) {
view = lInflater.inflate(R.layout.view_contact, parent, false);//create view file
}
if (position == 0) {
count = 0;
}
if (!activity.isShowSelected()) {
while (objects.get(position + count).isChecked()) {
count++;
}
}
if (!activity.isShowNonSelected()) {
while (!objects.get(position + count).isChecked()) {
count++;
}
}
final Contact contact = objects.get(position + count);
String contactFirstName = contact.getFirstName();
String contactSecondName = contact.getSecondName();
String contactMiddleName = contact.getMiddleName();
String[] contactNumbers = contact.getNumbers();
TextView tvName = (TextView) view.findViewById(R.id.tvName);
TextView tvNumber = (TextView) view.findViewById(R.id.tvNumber);
final CheckBox checkBox = (CheckBox) view.findViewById(R.id.checkBox);
if(get_limit == max_limit)
{
//checkBox.setChecked(contact.isChecked());
//testbool = false;
limit_counter = get_limit;
}
else if (get_limit == 1)
{
limit_counter = 1;
}
String fullName;
switch (MainActivity.sortMode) {
case Contact.COMPARE_SECOND_NAME:
fullName = getFullName(contactSecondName, contactFirstName);
break;
case Contact.COMPARE_MIDDLE_NAME:
fullName = getFullName(contactMiddleName, contactFirstName, contactSecondName);
break;
default:
fullName = getFullName(contactFirstName, contactSecondName);
break;
}
tvName.setText(fullName);
StringBuilder sbNumber = new StringBuilder();
for (int i = 0; i < contactNumbers.length; i++) {
sbNumber.append(contactNumbers[i]);
if (i < contactNumbers.length - 1) {
sbNumber.append(", ");
}
}
tvNumber.setText(sbNumber);
if (testbool) {
//Log.d("Check Boolean Tag 2 ", "testbool: "+testbool);
checkBox.setChecked(contact.isChecked());
}
checkBox.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
SharedPreferences selected = context.getSharedPreferences(Statical.CONTACTS_SELECTED, Context.MODE_PRIVATE);
SharedPreferences.Editor editSelected = selected.edit();
SharedPreferences limit_pref = context.getSharedPreferences(Statical.PREF_LIMIT, Context.MODE_PRIVATE);
SharedPreferences.Editor edit_limit_pref = limit_pref.edit();
int k = 0;
if(limit_counter == max_limit)
{
checkBox.setChecked(false);
//Toast.makeText(context,"Limit reached !! ", Toast.LENGTH_SHORT).show();
Log.d("-------LIMIT REACH-----", "value: "+limit_counter);
edit_limit_pref.putInt("LIMIT_KEY",limit_counter);
showAlertDialog();
}
if (contact.isChecked() && limit_counter <= max_limit && limit_counter >= 0) {
limit_counter = limit_counter - 1;
editSelected.putBoolean(contact.getContactId(), false);
edit_limit_pref.putInt("LIMIT_KEY",limit_counter);
contact.setChecked(false);
Log.d("-------UN CHECKED-----", "Un Checked value: "+limit_counter);
k = -1;
}
else if(!contact.isChecked() && limit_counter < max_limit){
limit_counter = limit_counter + 1;
editSelected.putBoolean(contact.getContactId(), true);
edit_limit_pref.putInt("LIMIT_KEY",limit_counter);
contact.setChecked(true);
Log.d("------- CHECKED -----", "Checked value: "+limit_counter);
k = 1;
}
editSelected.apply();
edit_limit_pref.apply();
activity.updateCount(k);
}
});
return view;
}
public void showAlertDialog()
{
Log.d("-------VALUE-----", "value: "+limit_counter);
AlertDialog.Builder alertDialog = new AlertDialog.Builder(context);
alertDialog.setTitle("Limit Reached!");
alertDialog.setMessage("Buy Pro Version");
alertDialog.setIcon(R.drawable.action_bar_logo);
alertDialog.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
buyClick();
Log.d("-------OK PRESSED -----", "value: " + limit_counter);
dialog.cancel();
}
});
alertDialog.setNegativeButton("Later", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Log.d("----LATER PRESSED -----", "value: " + limit_counter);
dialog.cancel();
}
});
alertDialog.show();
}
private String getFullName(String first, String second, String third) {
StringBuilder sbName = new StringBuilder();
if (!first.isEmpty()) {
sbName.append(first).append(" ");
}
if (!second.isEmpty()) {
sbName.append(second).append(" ");
}
if (!third.isEmpty()) {
sbName.append(third);
}
return sbName.toString();
}
private String getFullName(String first, String second) {
StringBuilder sbName = new StringBuilder();
if (!first.isEmpty()) {
sbName.append(first).append(" ");
}
if (!second.isEmpty()) {
sbName.append(second);
}
return sbName.toString();
}
}
I recommend you to create an activity just to process this payment and then you can back to your normal flow.

Android BaseAdapter only shows correct information once

I'm trying to put together an adapter that will display the number of occurrences in a list. There are two ListViews in a tab host with each being in its own tab. As long as you do not click on the tab that shows the occurrences it will keep up with the data input just fine. The first time you go to view the listview, all of the groups are displayed with the correct amount of occurrences for each; however, from then on it does not want to update properly. At times it will not update at all, re-insert an existing group but still keep the old one.
For example, if I were to put in 10, 20, and 30 the first time I go to view the groups listview I would see:
10 -- 1
20 -- 1
30 -- 1
...but if I were to put in another 10 it would still display the same thing with no update.
When I put something else in like 45 I get:
10 -- 1
20 -- 1
30 -- 1
10 -- 2
I can keep adding other numbers and it will just keep adding in 10 -- 1's or sometimes even more 20's or 30's. If I use debugAll() in the log window it will show that it attempts all of the numbers that I put in, and it will return the correct number of occurences, just the display won't keep up and is displaying more of what is already there.
I have tried putting in several log statements and they show that the information in the adapter is right, just the display is wrong.
import android.content.Context;
import android.net.Uri;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
import java.net.URI;
import java.util.ArrayList;
import java.util.LinkedHashMap;
public class HashAdapter extends BaseAdapter {
private LinkedHashMap<String, String> mData = new LinkedHashMap<String, String>();
private final ArrayList keyArray = new ArrayList();
private final Context _context;
public HashAdapter (Context context) {
_context = context;
}
#Override
public int getCount() {
return keyArray.size();
}
#Override
public String getItem(int position) {
return mData.get(keyArray.get(position));
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
final View listView;
final LayoutInflater inflater = (LayoutInflater) _context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null) { // FIXME
listView = inflater.inflate(R.layout.list_item, null);
TextView textView = (TextView) listView.findViewById(R.id.listItem);
String tile = keyArray.get(position) + " -- " + getItem(position);
textView.setText(tile);
Log.i("getView Text Is", tile);
} else {
listView = convertView;
}
return listView;
}
public void addNewValue (String key) {
if (mData.containsKey(key)) {
int retrieve = Integer.parseInt(mData.get(key));
mData.put(key, String.valueOf(++retrieve));
} else { // HASH MAP CREATING A NEW KEY WITH VALUE OF 1
mData.put(key, "1");
keyArray.add(0, key);
}
this.notifyDataSetChanged();
Log.i("Array List ", keyArray.toString());
}
public void modifyExistingValue (String oldValue, String newValue) {
if (!oldValue.equals(newValue)) {
int newInt = Integer.parseInt(mData.get(oldValue));
if (newInt > 1) {
mData.put(oldValue, String.valueOf(--newInt));
String secondInt = mData.get(newValue);
if (secondInt != null) {
int newNewInt = Integer.parseInt(secondInt);
mData.put(newValue, String.valueOf(++newNewInt));
} else {
mData.put(newValue, "1");
}
} else {
mData.remove(oldValue);
keyArray.remove(oldValue);
mData.put(newValue, "1");
Log.i("Old Value ", oldValue + " Is Gone From HashMap");
}
keyArray.add(0, newValue);
}
this.notifyDataSetChanged();
Log.i("Array List ", keyArray.toString());
}
public void removeOccurrence (String oldValue) {
String oldOccurrences = mData.get(oldValue);
if (!oldOccurrences.equals("1")) { // IF THERE ARE ENOUGH REMAINING TO STILL EXIST
int newInt = Integer.parseInt(oldOccurrences);
mData.put(oldValue, String.valueOf(--newInt));
} else { // NOT ENOUGH LEFT...REMOVE IT
mData.remove(oldValue);
keyArray.remove(oldValue);
Log.i("Old Value", oldValue + " Is Gone From HashMap");
}
this.notifyDataSetChanged();
Log.i("Array List ", keyArray.toString());
}
public void clear () {
mData.clear();
keyArray.clear();
this.notifyDataSetChanged();
Log.i("Array List ", keyArray.toString());
}
public void debugValue (String key) {
Log.i("AdapterDebug Value", key + " has " + mData.get(key));
}
public void debugAll () {
int size = keyArray.size();
for (int i = 0; i < size; i++) {
String retrieve = (String) keyArray.get(i);
Log.i("AdapterDebug All", "Attempted " + retrieve + " and retrieved " + mData.get(retrieve));
}
}
}
EDIT:
I figured some one might find the fully working version useful so I'll put this here.
It will keep track of re occurring values. Build off of it, use it as is, I don't care.
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.LinkedHashMap;
/*
* ARRAY ADAPTER FOR KEEPING TRACK OF REOCCURRING VALUES AND DISPLAYING ON A LISTVIEW
* CREATED BY : COREY WILLIAMS
* 8/13/2014
*
* BeerWare (http://en.wikipedia.org/wiki/Beerware)
* */
class HashAdapter extends BaseAdapter {
private LinkedHashMap<String, String> mData = new LinkedHashMap<String, String>();
private ArrayList keyArray = new ArrayList();
private final Context _context;
public HashAdapter (Context context) {
_context = context;
}
#Override
public int getCount() {
return keyArray.size();
}
#Override
public String getItem(int position) {
return mData.get(keyArray.get(position));
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
final View listView;
final LayoutInflater inflater = (LayoutInflater) _context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
listView = inflater.inflate(R.layout.list_item, null);
TextView textView = (TextView) listView.findViewById(R.id.listItem);
String tile = keyArray.get(position) + " -- " + getItem(position);
textView.setText(tile);
} else {
listView = convertView;
TextView textView = (TextView) listView.findViewById(R.id.listItem);
String tile = keyArray.get(position) + " -- " + getItem(position);
textView.setText(tile);
}
return listView;
}
public void addNewValue (String key) {
if (mData.containsKey(key)) {
int retrieve = Integer.parseInt(mData.get(key));
mData.put(key, String.valueOf(++retrieve));
} else { // HASH MAP CREATING A NEW KEY WITH VALUE OF 1
mData.put(key, "1");
keyArray.add(0, key);
}
this.notifyDataSetChanged();
}
public void modifyExistingValue (String oldValue, String newValue) {
if (!oldValue.equals(newValue)) {
int oldAmmount = Integer.parseInt(mData.get(oldValue)); // GET HOW MANY ARE LEFT OF WHAT YOU SELECTED
boolean alreadyHasNewValue = mData.containsKey(newValue);
if (oldAmmount > 1) { // IF THERE IS SOME LEFT
mData.put(oldValue, String.valueOf(--oldAmmount));
if (alreadyHasNewValue) {
String secondInt = mData.get(newValue);
int newNewInt = Integer.parseInt(secondInt);
mData.put(newValue, String.valueOf(++newNewInt));
} else {
mData.put(newValue, "1");
}
} else {
mData.remove(oldValue);
keyArray.remove(oldValue);
if (alreadyHasNewValue) {
String secondInt = mData.get(newValue);
int newNewInt = Integer.parseInt(secondInt);
mData.put(newValue, String.valueOf(++newNewInt));
} else {
mData.put(newValue, "1");
}
}
if (!keyArray.contains(newValue)) {
keyArray.add(0, newValue);
}
}
this.notifyDataSetChanged();
}
public void removeOccurrence (String oldValue) {
String oldOccurrences = mData.get(oldValue);
if (!oldOccurrences.equals("1")) { // IF THERE ARE ENOUGH REMAINING TO STILL EXIST
int newInt = Integer.parseInt(oldOccurrences);
mData.put(oldValue, String.valueOf(--newInt));
} else { // NOT ENOUGH LEFT...REMOVE IT
mData.remove(oldValue);
keyArray.remove(oldValue);
}
this.notifyDataSetChanged();
}
public void clear () {
mData.clear();
keyArray.clear();
this.notifyDataSetChanged();
}
public ArrayList getKeys () {
return keyArray;
}
public void restoreKeys (ArrayList<String> restore) {
keyArray = restore;
this.notifyDataSetChanged();
}
public LinkedHashMap<String, String> getValues () {
return mData;
}
public void restoreValues (LinkedHashMap<String, String> restore) {
mData = restore;
this.notifyDataSetChanged();
}
}
In the "getView" method you must update the content placeholders (TextView(s) in your code) even if "convertView" is not null.
It's because of view recycling system of ListView.
So the updated code could be like this:
#Override
public View getView(int position, View convertView, ViewGroup parent) {
final View listView;
final LayoutInflater inflater = (LayoutInflater) _context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
listView = inflater.inflate(R.layout.list_item, null);
} else {
listView = convertView;
}
TextView textView = (TextView) listView.findViewById(R.id.listItem);
String tile = keyArray.get(position) + " -- " + getItem(position);
textView.setText(tile);
Log.i("getView Text Is", tile);
return listView;
}

NullPointer cause in CustomListview

I am developing an application in which i have Implement CustomListview with one icon, raitingbar,checkbox. now everything is display fine but when i have insert one button it getting me nullpointer error.i know that nullpointer error cause in situation of not initialize the control... but i have tried so far and not understand what is the proble over here....
i have take one viewHold for declare all Row item..
package com.AppFavorits;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.RatingBar;
import android.widget.TextView;
class ViewHolder {
public ImageView imgvFavrowiconappicon;
public TextView txvxFavrowiconappname;
public RatingBar ratingBar1;
public CheckBox chkbxFavrowsel;
public Button btnFavrowOpen;
ViewHolder(View base) {
this.ratingBar1=(RatingBar)base.findViewById(R.id.ratingBar1);
this.ratingBar1.setFocusable(false);
this.txvxFavrowiconappname=(TextView)base.findViewById(R.id.txvxFavrowiconappname);
this.imgvFavrowiconappicon=(ImageView)base.findViewById(R.id.imgvFavrowiconappicon);
this.chkbxFavrowsel = (CheckBox)base.findViewById(R.id.chkbxFavrowsel);
this.btnFavrowOpen= (Button)base.findViewWithTag(R.id.btnFavrowOpen);
this.chkbxFavrowsel.setFocusable(false);
}
}
CustomAdapter
class RatingAdapter extends ArrayAdapter<RowModel> implements OnClickListener {
private ArrayList<Model> mlist;
boolean[] checkBoxState;
RatingAdapter(ArrayList<RowModel> list, ArrayList<Model> mlist) {
super(Favorites.this, R.layout.rowfavorites,
R.id.txvxFavrowiconappname, list);
checkBoxState = new boolean[list.size()];
this.mlist = mlist;
}
public View getView(final int position, View convertView,
ViewGroup parent) {
View row = super.getView(position, convertView, parent);
holder = (ViewHolder) row.getTag();
if (convertView == null) {
holder = new ViewHolder(row);
row.setTag(holder);
} else {
row = convertView;
((ViewHolder) row.getTag()).chkbxFavrowsel.setTag(mlist
.get(position));
}
RatingBar.OnRatingBarChangeListener l = new RatingBar.OnRatingBarChangeListener() {
public void onRatingChanged(RatingBar ratingBar, float rating,
boolean fromTouch) {
Integer myPosition = (Integer) ratingBar.getTag();
RowModel model = getModel(myPosition);
model.rating = rating;
flFavRate[position] = rating;
// stored listitem rating in array
datasource.open();
datasource.UpdateRating(String.valueOf(rating), String.valueOf(position+1));
datasource.close();
}
};
holder.ratingBar1.setOnRatingBarChangeListener(l);
holder.chkbxFavrowsel
.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
Model element = (Model) holder.chkbxFavrowsel
.getTag();
element.setSelected(buttonView.isChecked());
bSelected[position] = isChecked;
element.setsizeInc(sizeincrement);
// if (holder.chkbxFavrowsel.isChecked() ==
// isChecked) {
boolean bAlreadyfav = false;
String prefixlink = "https://play.google.com/store/apps/details?id=";
ShrdDatasource.open();
ArrayList<Comment> alDSPackagenm = ShrdDatasource.getAllPackage();
ArrayList<Comment> alDSRating = ShrdDatasource.getAllRating();
ArrayList<Comment> alDSID = ShrdDatasource.getID();
Log.i(TAG, "First Package cmp"+ alDSPackagenm);
ShrdDatasource.close();
int i = 0 ;
if (alDSPackagenm != null) {
for (i = 0; i < alDSPackagenm.size(); i++) {
if(alDSPackagenm.get(i).toString().equalsIgnoreCase(prefixlink + alPackagenm.get(position).toString() + "1x2optrue") || alDSPackagenm.get(i).toString().equalsIgnoreCase(prefixlink + alPackagenm.get(position).toString() + "1x2opfalse"))
{
bAlreadyfav = true;
break;
}
}
}
GolbPosition = position;
if (bAlreadyfav == true) {
Log.i(TAG, "Share positionis "+i);
Log.i(TAG, "Current positionis "+position);
Log.i(TAG,"ShrdDatasource Rating" + alDSRating.get(i).toString());
Log.i(TAG,"Favorite Rating" + String.valueOf(flFavRate[GolbPosition]));
if(alDSRating.get(i).toString().equalsIgnoreCase(String.valueOf(flFavRate[GolbPosition])))
{
Toast.makeText(getBaseContext(), " App already in Share list ",
Toast.LENGTH_LONG).show();
}
else
{
//alid
/*GolbPosition = position;
new GETFavTask().execute();*/
//UpdateRating
ShrdDatasource.open();
ShrdDatasource.UpdateRating(String.valueOf(flFavRate[GolbPosition]), alDSID.get(i).toString());
ShrdDatasource.close();
//Update Query fire
}
} else {
//Log.i(TAG, "First Package cmp"+ alDSPackagenm.get(position).toString());
Log.i(TAG, "Second Package cmp"+ alPackagenm.get(position).toString());
GolbPosition = position;
new GETFavTask().execute();
// add item in Database when user get select
}
}
});
RowModel model = getModel(position);
ViewHolder holder = (ViewHolder) row.getTag();
holder.ratingBar1.setTag(new Integer(position));
//holder.btnFavrowOpen.setTag(mlist.get(position));
holder.ratingBar1.setRating(model.rating);
holder.imgvFavrowiconappicon.setImageDrawable(drblAlIcon[position]);
holder.txvxFavrowiconappname.setText(alAppName.get(position)
.toString());
holder.chkbxFavrowsel.setChecked(mlist.get(position).isSelected());
holder.chkbxFavrowsel.setTag(mlist.get(position));
holder.btnFavrowOpen.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// OpenApp(alPackagenm.get(position).toString());
}
});
try
{
if (alAppRating.get(position) == null | alAppRating.get(position).toString().equalsIgnoreCase("null")) {
holder.ratingBar1.setRating(0.0f);
} else {
holder.ratingBar1.setRating(Float.parseFloat(alAppRating
.get(position).toString()));
}
}catch (Exception e) {
e.printStackTrace();
}
//holder.ratingBar1.setRating(Float.parseFloat(alAppRating.get(position).toString()));
return (row);
}
Here you can see the button holder.btnFavrowOpen with onclicklistner i got null pointer at that line very much tied what happen here.... if i am remove button code in adapter it getting work fine...but when i write button code again it getting Error of null pointer
use
base.findViewById
and not
base.findViewWithTag

Categories