How to increase cart counter and then button click on that - android

this is my adapter class where i am having a add to cart button
public class ServiceSelectionOptionsListAdapter extends ArrayAdapter<ServiceSelectionOptionsDataModel> {
private Context context;
private int layoutResourceId;
ListView list;
static final String TAG = "LISTT";
HashMap<Integer, Integer> hashMap;
String response;
ProgressDialog pdilog;
SharedPreferences prefs;
String serverresponse1;
private List<ServiceSelectionOptionsDataModel> data;
String custid;
JSONArray _jsonarray;
JSONObject jsonObject;
String subsrvceopid;
String quantity = "1";
String cartcounter;
TextView counter;
public ServiceSelectionOptionsListAdapter(Context context, int layoutResourceId,
List<ServiceSelectionOptionsDataModel> data) {
super(context, R.layout.serviceselectionoptionslist, data);
this.layoutResourceId = layoutResourceId;
this.context = context;
this.data = data;
hashMap = new HashMap<Integer, Integer>();
prefs = context.getSharedPreferences(AppConstants.VERIFICATION,
Context.MODE_PRIVATE);
custid = prefs.getString(AppConstants.CUSTOMERID, "");
cartcounter = prefs.getString(AppConstants.CARTITEMCOUNTER, "");
}
#Override
public View getView(final int position, final View convertView, ViewGroup parent) {
View row = convertView;
final ViewHolder holder;
if (row == null) {
LayoutInflater inflater = ((Activity) context).getLayoutInflater();
row = inflater.inflate(layoutResourceId, parent, false);
holder = new ViewHolder();
holder.optionname = (TextView) row.findViewById(R.id.tvsubserviceoptionname);
holder.addtocart = (Button) row.findViewById(R.id.btnaddtocart);
row.setTag(holder);
} else {
holder = (ViewHolder) row.getTag();
}
final ServiceSelectionOptionsDataModel item = data.get(position);
holder.optionname.setText(item.getOptionname());
holder.addtocart.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Integer index = (Integer) view.getTag();
subsrvceopid = data.get(position).getId();
new addtocart().execute(custid, subsrvceopid, quantity);
new cartitemsdetails().execute(custid);
SharedPreferences.Editor editor = context.getSharedPreferences(AppConstants.VERIFICATION, context.MODE_PRIVATE).edit();
editor.putString(AppConstants.SUBSERVIEOPTIONID, subsrvceopid);
editor.commit();
notifyDataSetChanged();
}
});
return row;
}
static class ViewHolder {
TextView optionname;
// TextView charges;
Button addtocart;
TextView counter;
}
and this is my activity class where i m getting the size of the cart items list
class cartitemsdetails extends AsyncTask<String, Void, Void> {
#Override
protected void onPreExecute() {
pdilog = new ProgressDialog(ServiceSelectionOptionsListActivity.this);
pdilog.setMessage("Please Wait....");
pdilog.show();
super.onPreExecute();
}
#Override
protected Void doInBackground(String... params) {
String response = JSONFunctions.getJSONfromURL("http://cpanel.smartindiaservice.com/api/cartdetails?customerid=" + params[0]);
try {
jsonarray = new JSONArray(response);
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
size = jsonarray.length();
counter.setText(String.valueOf(size));
if (size == 0 )
{
viewcart.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(ServiceSelectionOptionsListActivity.this, NoItemsInTheCart.class);
startActivity(intent);
}
});
cart.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(ServiceSelectionOptionsListActivity.this, NoItemsInTheCart.class);
startActivity(intent);
}
});
}
if(size>0) {
viewcart.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(ServiceSelectionOptionsListActivity.this, MyCart.class);
startActivity(intent);
}
});
cart.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(ServiceSelectionOptionsListActivity.this, MyCart.class);
startActivity(intent);
}
});
}
pdilog.dismiss();
super.onPostExecute(aVoid);
}
}
class OptionsSelection extends AsyncTask<String, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Void doInBackground(String... params) {
response = JSONFunctions.getJSONfromURL("http://cpanel.smartindiaservice.com/api/subserviceoptions?subserviceid=" + params[0]);
try {
_jsonarray = new JSONArray(response);
for (int i = 0; i < _jsonarray.length(); i++) {
ServiceSelectionOptionsDataModel datamodel = new ServiceSelectionOptionsDataModel();
jsonObject = _jsonarray.getJSONObject(i);
optionname = jsonObject.getString("OptionName");
datamodel.setOptionname(optionname);
charge = jsonObject.getString("Charges");
datamodel.setCharge(charge);
subserviceoptionid = jsonObject.getString("SubServiceOptionID");
datamodel.setId(subserviceoptionid);
lstDataModel.add(datamodel);
}
} catch (Exception e) {
System.out.println(e);
}
return null;
}
#Override
protected void onPostExecute(Void result) {
ServiceSelectionOptionsListAdapter adapter = new ServiceSelectionOptionsListAdapter(ServiceSelectionOptionsListActivity.this, R.layout.serviceselectionoptionslist, lstDataModel);
options.setAdapter(adapter);
adapter.notifyDataSetChanged();
super.onPostExecute(result);
}
}

Related

how to reload activity on Item click of ListView in android

public class HomeFragment extends Fragment implements View.OnClickListener {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_sample, container, false);
new OrderData().execute();
return view;
}
class OrderData extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(String... params) {
try {
String Response = JSONfunctions.getJSONfromURL(Constant.OrderUL + "2");
JSONObject _jobjec = new JSONObject(Response);
OrderModel _orderModel = new OrderModel();
_orderModel.setJobID(_jobjec.getString("JobID"));
_orderModel.setCustomerName(_jobjec.getString("CustomerName"));
_orderModel.setCustomerAddressName(_jobjec.getString("CustomerAddressName"));
_orderModel.setCustomerPhoneNumber(_jobjec.getString("CustomerPhoneNumber"));
_orderModel.setCustomerHouseNumber(_jobjec.getString("CustomerHouseNumber"));
_orderModel.setCustomerArea(_jobjec.getString("CustomerArea"));
_orderModel.setCustomerLandmark(_jobjec.getString("CustomerLandmark"));
_orderModel.setCustomerCity(_jobjec.getString("CustomerCity"));
_orderModel.setServiceType(_jobjec.getString("ServiceType"));
_orderModel.setQuantity(_jobjec.getString("Quantity"));
_orderModel.setPayementMethod(_jobjec.getString("PayementMethod"));
_orderModel.setJobAmount(_jobjec.getString("JobAmount"));
_orderModel.setJobStatus(_jobjec.getString("JobStatus"));
// JobStatus =_jobjec.getString("JobStatus");
orderList.add(_orderModel);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
order_listview.setAdapter(_adapter);
_adapter = new ListViewAdapter(getActivity(), R.layout.listitem, orderList);
order_listview.setAdapter(_adapter);
}
}
this is my adapter:
public class ListViewAdapter extends ArrayAdapter<OrderModel> {
// Declare Variables
Context mcontext;
LayoutInflater inflater;
List<OrderModel> datamodel;
public ListViewAdapter(Context context, int resourceId,
List<OrderModel> worldpopulationlist) {
super(context, resourceId, worldpopulationlist);
this.mcontext = context;
this.datamodel = worldpopulationlist;
inflater = LayoutInflater.from(context);
}
private class ViewHolder {
TextView textView1;
TextView textView2;
TextView textView3;
TextView textView4;
TextView status;
}
#Override
public int getCount() {
return super.getCount();
}
public View getView(final int position, View view, ViewGroup parent) {
final ViewHolder holder;
if (view == null) {
holder = new ViewHolder();
view = inflater.inflate(R.layout.listitem, null);
//
holder.textView1 = (TextView) view.findViewById(R.id.textView1);
holder.textView2 = (TextView) view.findViewById(R.id.textView3);
holder.textView3 = (TextView) view.findViewById(R.id.textView2);
holder.textView4 = (TextView) view.findViewById(R.id.textView17);
holder.status = (TextView) view.findViewById(R.id.aceeptimageview);
view.setTag(holder);
} else {
holder = (ViewHolder) view.getTag();
}
// Capture position and set to the TextViews
holder.textView1.setText(datamodel.get(position).getJobID() + ":" + datamodel.get(position).getCustomerName());
holder.textView2.setText(datamodel.get(position).getCustomerPhoneNumber());
holder.textView3.setText(datamodel.get(position).getCustomerAddressName() + " " +
datamodel.get(position).getCustomerLandmark() + " " +
datamodel.get(position).getCustomerCity()
);
holder.textView4.setText(datamodel.get(position).getServiceType() + " " + datamodel.get(position).getJobAmount());
String Status = datamodel.get(position).getJobStatus();
if (Status.equals("Pending")) {
holder.status.setText("Accept");
holder.status.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
holder.status.setText("Started");
JSONObject _jobject = new JSONObject();
_jobject.put("JobID", datamodel.get(position).getJobID().toString());
_jobject.put("Status", "Accepted");
new StatsuBackground().execute(_jobject.toString());
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
if (Status.equals("Accepted")) {
holder.status.setText("Started");
holder.status.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(v.getContext(), "Started", Toast.LENGTH_LONG).show();
holder.status.setText("Closed");
try {
JSONObject _jobject = new JSONObject();
_jobject.put("JobID", datamodel.get(position).getJobID().toString());
_jobject.put("Status", "Started");
new StatsuBackground().execute(_jobject.toString());
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
if (Status.equals("Started")) {
holder.status.setText("Closed");
holder.status.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(v.getContext(), "Cloesd", Toast.LENGTH_LONG).show();
try {
JSONObject _jobject = new JSONObject();
_jobject.put("JobID", datamodel.get(position).getJobID().toString());
_jobject.put("Status", "Closed");
new StatsuBackground().execute(_jobject.toString());
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
return view;
}
class StatsuBackground extends AsyncTask<String, String, String> {
#Override
protected String doInBackground(String... params) {
String Response = PosttoServer.getJSONfromURL(Constant.StatusUrl, params[0]);
return null;
}
}
}
I have applied onItem Click function in adapter each item. What I want when I click on particular item is my activity should reload and hit again api so that I can get updated value from server. How should I apply this so that I can get updated? I even tried notfydatasetchange but its not working.
public class ListViewAdapter extends ArrayAdapter<OrderModel> {
// Declare Variables
Context mcontext;
LayoutInflater inflater;
List<OrderModel> datamodel;
public ListViewAdapter(Context context, int resourceId,
List<OrderModel> worldpopulationlist) {
super(context, resourceId, worldpopulationlist);
this.mcontext = context;
this.datamodel = worldpopulationlist;
inflater = LayoutInflater.from(context);
}
private class ViewHolder {
TextView textView1;
TextView textView2;
TextView textView3;
TextView textView4;
TextView status;
}
#Override
public int getCount() {
return super.getCount();
}
public View getView(final int position, View view, ViewGroup parent) {
final ViewHolder holder;
if (view == null) {
holder = new ViewHolder();
view = inflater.inflate(R.layout.listitem, null);
//
holder.textView1 = (TextView) view.findViewById(R.id.textView1);
holder.textView2 = (TextView) view.findViewById(R.id.textView3);
holder.textView3 = (TextView) view.findViewById(R.id.textView2);
holder.textView4 = (TextView) view.findViewById(R.id.textView17);
holder.status = (TextView) view.findViewById(R.id.aceeptimageview);
view.setTag(holder);
} else {
holder = (ViewHolder) view.getTag();
}
// Capture position and set to the TextViews
holder.textView1.setText(datamodel.get(position).getJobID() + ":" + datamodel.get(position).getCustomerName());
holder.textView2.setText(datamodel.get(position).getCustomerPhoneNumber());
holder.textView3.setText(datamodel.get(position).getCustomerAddressName() + " " +
datamodel.get(position).getCustomerLandmark() + " " +
datamodel.get(position).getCustomerCity()
);
holder.textView4.setText(datamodel.get(position).getServiceType() + " " + datamodel.get(position).getJobAmount());
String Status = datamodel.get(position).getJobStatus();
if (Status.equals("Pending")) {
holder.status.setText("Accept");
holder.status.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
holder.status.setText("Started");
JSONObject _jobject = new JSONObject();
_jobject.put("JobID", datamodel.get(position).getJobID().toString());
_jobject.put("Status", "Accepted");
new StatsuBackground().execute(_jobject.toString());
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
if (Status.equals("Accepted")) {
holder.status.setText("Started");
holder.status.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(v.getContext(), "Started", Toast.LENGTH_LONG).show();
holder.status.setText("Closed");
try {
JSONObject _jobject = new JSONObject();
_jobject.put("JobID", datamodel.get(position).getJobID().toString());
_jobject.put("Status", "Started");
new StatsuBackground().execute(_jobject.toString());
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
if (Status.equals("Started")) {
holder.status.setText("Closed");
holder.status.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(v.getContext(), "Cloesd", Toast.LENGTH_LONG).show();
try {
JSONObject _jobject = new JSONObject();
_jobject.put("JobID", datamodel.get(position).getJobID().toString());
_jobject.put("Status", "Closed");
new StatsuBackground().execute(_jobject.toString());
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
return view;
}
class StatsuBackground extends AsyncTask<String, String, String> {
#Override
protected String doInBackground(String... params) {
String Response = PosttoServer.getJSONfromURL(Constant.StatusUrl, params[0]);
return null;
}
#Override
protected void onPostExecute(String result) {
//check if success
finish();
startActivity(((Activity)context).getIntent())
}
}
}
Try this

Android - Creating Listview using Custom Adapter Programmatically

I'm in learning about add view programmatically. But, I'm in confusing now.
I have data, there are idpatient, idheader. Patient can have more than one ID header. When I input idpatient, it will add listview (with custom adapter) programmatically. The number of listview is same with the number of ID header.
I want to set in each listview with data patient group by ID header..
So far, I add search view when loop adding listview, but when I input one ID header to seacrh view, all of listview will view the same data according to ID header in search view..
I'm sorry for the long explanation. Can anybody help me to solve this problem?
Thanks in advance
This is My Adapter :
/**
* Created by RKI on 11/9/2016.
*/
public class AdapterHistory extends BaseAdapter implements Filterable, View.OnClickListener {
private Activity activity;
LayoutInflater inflater;
HistoryHeaderActivity main;
public int count = 0;
Context context;
public ModelHistory product;
ArrayList<ModelHistory> mStringFilterList;
ModelHistory tempValues = null;
ValueFilter valueFilter;
public Cart cart;
public AdapterHistory(HistoryHeaderActivity main, ArrayList<ModelHistory> arraylist) {
this.main = main;
this.main.historyModel = arraylist;
mStringFilterList = arraylist;
}
#Override
public int getCount() {
return main.historyModel.size();
}
#Override
public Object getItem(int position) {
return main.historyModel.get(position);
}
#Override
public long getItemId(int position) {
return 0;
}
public View getView(final int position, View convertView, ViewGroup parent) {
int pos = position;
final Cart carts = CartHelper.getCart();
View vi = convertView;
ViewHolderItem holder = new ViewHolderItem();
if (convertView == null) {
LayoutInflater inflater = (LayoutInflater) main.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
vi = inflater.inflate(R.layout.list_history, null);
holder.h_id = (TextView) vi.findViewById(R.id.id_header_);
holder.h_type = (TextView) vi.findViewById(R.id.servicetype_);
holder.h_qty = (TextView) vi.findViewById(R.id.qty_);
holder.h_ps_id = (TextView) vi.findViewById(R.id.patient_id);
holder.h_ps_name = (TextView) vi.findViewById(R.id.patient_);
holder.h_dokid = (TextView) vi.findViewById(R.id.doctor_id_);
holder.h_dokname = (TextView) vi.findViewById(R.id.doctor_);
holder.h_item = (TextView) vi.findViewById(R.id.item_);
holder.h_date = (TextView) vi.findViewById(R.id.date_);
holder.checkToCart = (CheckBox) vi.findViewById(R.id.checkBox);
holder.checkToCart.setTag(position);
holder.checkToCart.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
int getPosition = (Integer) buttonView.getTag(); // Here we get the position that we have set for the checkbox using setTag.
tempValues.setSelected(isChecked);
}
});
vi.setTag(holder);
vi.setTag(R.id.checkBox, holder.checkToCart);
} else {
holder = (ViewHolderItem) vi.getTag();
}
if (main.historyModel.size() <= 0) {
holder.h_date.setText("No Data");
} else {
/*** Get each Model object from Arraylist ****/
tempValues = null;
tempValues = (ModelHistory) main.historyModel.get(position);
holder.h_id.setText(tempValues.getH_id());
holder.h_type.setText(tempValues.getH_service());
holder.h_qty.setText(tempValues.getH_qty());
holder.h_ps_name.setText(tempValues.getH_p_name());
holder.h_ps_id.setText(tempValues.getH_p_id());
holder.h_dokid.setText(tempValues.getH_d_id());
holder.h_dokname.setText(tempValues.getH_d_name());
holder.h_item.setText(tempValues.getH_item());
holder.h_date.setText(tempValues.getH_date());
holder.checkToCart.setTag(position);
holder.checkToCart.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
main.historyModel.get(position).setSelected(buttonView.isChecked());
}
});
holder.checkToCart.setChecked(main.historyModel.get(position).isSelected());
for (pos = 1; pos <= 1; pos++) {
main.u_pname = tempValues.getH_p_name();
main.u_pid = tempValues.getH_p_id();
main.u_service = tempValues.getH_service();
main.up_iddetail = tempValues.getH_id();
}
}
return vi;
}
#Override
public void onClick(View v) {
}
public static class ViewHolderItem {
TextView h_id, h_type, h_ps_id, h_ps_name, h_dokid, h_dokname, h_item, h_qty, h_date;
CheckBox checkToCart;
}
private List<TransactionsItem> getCartItems(Cart cart) {
List<TransactionsItem> cartItems = new ArrayList<>();
Map<Saleable, Integer> itemMap = cart.getItemWithQuantity();
for (Map.Entry<Saleable, Integer> entry : itemMap.entrySet()) {
TransactionsItem cartItem = new TransactionsItem();
cartItem.setProduct((ModelInventory) entry.getKey());
cartItem.setQuantity(entry.getValue());
cartItems.add(cartItem);
}
return cartItems;
}
#Override
public Filter getFilter() {
if (valueFilter == null) {
valueFilter = new ValueFilter();
}
return valueFilter;
}
private class ValueFilter extends Filter {
#Override
protected FilterResults performFiltering(CharSequence constraint) {
FilterResults results = new FilterResults();
if (constraint != null && constraint.length() > 0) {
List<ModelHistory> filterList = new ArrayList<ModelHistory>();
for (int i = 0; i < mStringFilterList.size(); i++) {
if ((mStringFilterList.get(i).getH_id().toUpperCase())
.contains(constraint.toString().toUpperCase())) {
ModelHistory country = new ModelHistory(
mStringFilterList.get(i).getH_id(),
mStringFilterList.get(i).getH_p_id(),
mStringFilterList.get(i).getH_date(),
mStringFilterList.get(i).getH_p_name(),
mStringFilterList.get(i).getH_d_id(),
mStringFilterList.get(i).getH_d_name(),
mStringFilterList.get(i).getH_item(),
mStringFilterList.get(i).getH_qty(),
mStringFilterList.get(i).getH_service());
filterList.add(country);
}
}
results.count = filterList.size();
results.values = filterList;
} else {
results.count = mStringFilterList.size();
results.values = mStringFilterList;
}
return results;
}
#Override
protected void publishResults(CharSequence constraint,
FilterResults results) {
main.historyModel = (ArrayList<ModelHistory>) results.values;
notifyDataSetChanged();
}
}
}
This is My Activity :
import com.mobileproject.rki.mobile_his_receipt.view.adapter.AdapterHistory;
import org.w3c.dom.*;
import java.io.Serializable;
import java.util.*;
public class HistoryHeaderActivity extends AppCompatActivity implements SearchView.OnQueryTextListener {
static final String URL = "http://.../GetDataInv";
static final String KEY_TABLE = "Table"; // parent node
static final String KEY_REG_ID = "Sales_Aptk_ID", KEY_DATE = "Sales_Aptk_Date",
KEY_PATIENT_ID = "Sales_Aptk_Patient_ID", KEY_SERVICE_ID = "Sales_Aptk_Type",
KEY_PATIENT_NAME = "Sales_Aptk_Patient_Name",
KEY_DOCTOR_ID = "Sales_Aptk_Doctor_ID", KEY_DOCTOR_NAME = "Sales_Aptk_Doctor_Name",
KEY_ITEM_ID = "Sales_Aptk_Detail_Item_ID", KEY_DETAIL_UNIT = "Sales_Aptk_Detail_Unit",
KEY_ITEM_QTY = "Sales_Aptk_Detail_Qty";
static final String KEY_ID_HEADER = "Sales_Aptk_ID";
static final String KEY_TABLE_INV = "Table"; // parent node
static final String KEY_ITEM_ID_INV = "Item_ID", KEY_ITEM_NAME = "Item_Name",
KEY_MAX_STOCK = "Item_Max_Stock";
public static final int DIALOG_DOWNLOAD_DATA_PROGRESS = 0, DIALOG_NO_DATA = 1,
DIALOG_DOWNLOAD_FULL_PHOTO_PROGRESS = 2;
Element e;
final Context context = this;
public List<ModelInventory> invModels;
private ProgressDialog mProgressDialog;
public static String id, up_iddetail, up_user, u_pid, u_pname, u_service, xml;
public ArrayList<ModelInventory> invModel = new ArrayList<ModelInventory>();
public ArrayList<ModelHistory> historyModel = new ArrayList<ModelHistory>();
public ArrayList<ModelIDHeader> headerModel = new ArrayList<ModelIDHeader>();
public Cart cart;
private Menu menu;
AdapterHistory hstAdpt, idhstAdpt;
private ProgressDialog progressDialog;
public ModelInventory productInv;
int mPosition, invPosition;
EditText p_id;
ListView listHistory;
XMLParser parser;
LinearLayout lm;
LinearLayout.LayoutParams params;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_history_header);
lm = (LinearLayout) findViewById(R.id.linearMain);
params = new LinearLayout.LayoutParams(
LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
p_id = (EditText) findViewById(R.id.patientID);
listHistory = (ListView) findViewById(R.id.listhistory);
hstAdpt = new AdapterHistory(HistoryHeaderActivity.this, historyModel);
listHistory.setAdapter(hstAdpt);
listHistory.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
mPosition = position;
invPosition = position;
}
});
SharedPreferences login2 = getSharedPreferences("USERLOGIN", 0);
String doktername = login2.getString("userlogin", "0");
up_user = doktername;
p_id.addTextChangedListener(new TextWatcher() {
public void afterTextChanged(Editable s) {
}
public void beforeTextChanged(CharSequence s, int start,
int count, int after) {
}
public void onTextChanged(CharSequence s, int start,
int before, int count) {
onGetHistory();
}
});
}
/**
* Check Form Input
*
* #return
*/
private boolean isFormValid() {
String aTemp = p_id.getText().toString();
if (aTemp.isEmpty()) {
Toast.makeText(this, "Please Input Patient ID..", Toast.LENGTH_SHORT).show();
return false;
} else {
id = aTemp.toString();
}
return true;
}
protected void dismissDialogWait() {
if (progressDialog != null) {
if (progressDialog.isShowing()) {
progressDialog.dismiss();
}
}
}
public void onGetHistory() {
listHistory.setAdapter(null);
if (isFormValid()) {
GetDataHistoryTask syncTask = new GetDataHistoryTask();
syncTask.execute(new IntroductingMethod());
GetDataHeaderTask syncTaskHeader = new GetDataHeaderTask();
syncTaskHeader.execute(new IntroductingMethod());
}
}
private class GetDataHistoryTask extends AsyncTask<IntroductingMethod, String, String> {
#Override
protected String doInBackground(IntroductingMethod... params) {
IntroductingMethod REGService = params[0];
return REGService.getHistoryData(id);
}
#Override
protected void onPostExecute(String result) {
dismissDialogWait();
if (result != null) {
try {
ArrayList<HashMap<String, String>> menuItems = new ArrayList<HashMap<String, String>>();
if (Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
XMLParser parser = new XMLParser();
Document doc = parser.getDomElement(result); // getting DOM element
NodeList nl = doc.getElementsByTagName(KEY_TABLE);
// looping through all item nodes <item>
for (int i = 0; i < nl.getLength(); i++) {
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
Element e = (Element) nl.item(i);
ModelHistory add = new ModelHistory();
add.setH_id(parser.getValue(e, KEY_REG_ID));
add.setH_p_name(parser.getValue(e, KEY_PATIENT_NAME));
add.setH_p_id(parser.getValue(e, KEY_PATIENT_ID));
add.setH_service(parser.getValue(e, KEY_SERVICE_ID));
add.setH_date(parser.getValue(e, KEY_DATE));
add.setH_detail_unit(parser.getValue(e, KEY_DETAIL_UNIT));
add.setH_d_id(parser.getValue(e, KEY_DOCTOR_ID));
add.setH_d_name(parser.getValue(e, KEY_DOCTOR_NAME));
add.setH_item(parser.getValue(e, KEY_ITEM_ID));
add.setH_qty(parser.getValue(e, KEY_ITEM_QTY));
historyModel.add(add);
}
ShowAllContentHistory();
} catch (Exception e) {
Toast.makeText(HistoryHeaderActivity.this.getApplicationContext(),
"Koneksi gagal. Silahkan coba kembali.", Toast.LENGTH_LONG).show();
}
} else {
Toast.makeText(HistoryHeaderActivity.this.getApplicationContext(),
"Koneksi gagal. Silahkan coba kembali.", Toast.LENGTH_LONG).show();
}
}
}
private class GetDataHeaderTask extends AsyncTask<IntroductingMethod, String, String> {
#Override
protected String doInBackground(IntroductingMethod... params) {
IntroductingMethod REGService = params[0];
return REGService.getHistoryHeaderData(id);
}
#Override
protected void onPostExecute(String result) {
dismissDialogWait();
if (result != null) {
try {
ArrayList<HashMap<String, String>> menuItems = new ArrayList<HashMap<String, String>>();
if (Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
XMLParser parser = new XMLParser();
Document doc = parser.getDomElement(result); // getting DOM element
NodeList nl = doc.getElementsByTagName(KEY_TABLE);
// looping through all item nodes <item>
for (int i = 0; i < nl.getLength(); i++) {
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
Element e = (Element) nl.item(i);
ModelIDHeader add = new ModelIDHeader();
add.setIdSalesHeader(parser.getValue(e, KEY_ID_HEADER));
headerModel.add(add);
}
if(result.contains("<Sales_Aptk_Patient_ID>"+id+"</Sales_Aptk_Patient_ID>")){
Log.d("NilaiID ", id);
AddNewList();
}
else{
Log.d("Kenapayahh", id);
}
} catch (Exception e) {
Toast.makeText(HistoryHeaderActivity.this.getApplicationContext(),
"Koneksi gagal. Silahkan coba kembali.", Toast.LENGTH_LONG).show();
}
} else {
Toast.makeText(HistoryHeaderActivity.this.getApplicationContext(),
"Koneksi gagal. Silahkan coba kembali.", Toast.LENGTH_LONG).show();
}
}
}
public void AskUpdate(View v) {
if (hstAdpt.getCount() == 0) {
Toast.makeText(HistoryHeaderActivity.this.getApplicationContext(),
"Tidak ada rekaman pasien.", Toast.LENGTH_LONG).show();
} else {
SharedPreferences id_header = getSharedPreferences("IDSALESAPTK", 0);
SharedPreferences.Editor editorID = id_header.edit();
editorID.putString("idsalesaptk", up_iddetail);
editorID.commit();
SharedPreferences sendPref2 = getSharedPreferences("DATAPATIENTNAME", 0);
SharedPreferences.Editor editor2 = sendPref2.edit();
editor2.putString("datapatientname", u_pname);
editor2.commit();
editor2.clear();
SharedPreferences sendPref3 = getSharedPreferences("DATAPATIENTID", 0);
SharedPreferences.Editor editor3 = sendPref3.edit();
editor3.putString("datapatientid", u_pid);
editor3.commit();
editor3.clear();
SharedPreferences regID = getSharedPreferences("DATAREGID", 0);
String reg_ID = regID.getString("dataregid", "0");
SharedPreferences sendPref4 = getSharedPreferences("DATAREGID", 0);
SharedPreferences.Editor editor4 = sendPref4.edit();
editor4.putString("dataregid", reg_ID);
editor4.commit();
editor4.clear();
SharedPreferences sendPref1 = getSharedPreferences("DATASERVICE", 0);
SharedPreferences.Editor editor1 = sendPref1.edit();
editor1.putString("dataservice", u_service);
editor1.commit();
editor1.clear();
new LoadingDataAsync().execute();
}
}
public class LoadingDataAsync extends AsyncTask<String, Void, Void> {
#Override
protected Void doInBackground(String... params) {
updateDetail();
return null;
}
protected void onPostExecute(Void unused) {
dismissDialog(DIALOG_DOWNLOAD_DATA_PROGRESS);
removeDialog(DIALOG_DOWNLOAD_DATA_PROGRESS);
}
protected void onPreExecute() {
super.onPreExecute();
showDialog(DIALOG_DOWNLOAD_DATA_PROGRESS);
}
}
public void updateDetail() {
ArrayList<ModelHistory> candidateModelArrayList = new ArrayList<ModelHistory>();
for (ModelHistory model : historyModel) {
if (model.isSelected()) {
candidateModelArrayList.add(model);
}
}
ArrayList<HashMap<String, String>> menuItems = new ArrayList<HashMap<String, String>>();
if (Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
parser = new XMLParser();
xml = parser.getXmlFromUrl(URL);
Document doc = parser.getDomElement(xml);
NodeList nl = doc.getElementsByTagName(KEY_TABLE_INV);
for (int i = 0; i < nl.getLength(); i++) {
e = (Element) nl.item(i);
ModelInventory add = new ModelInventory();
add.setItem_ID(parser.getValue(e, KEY_ITEM_ID_INV));
add.setItem_Name(parser.getValue(e, KEY_ITEM_NAME));
add.setItem_Max_Stock(parser.getValue(e, KEY_MAX_STOCK));
invModel.add(add);
}
invModels = new ArrayList<ModelInventory>();
invModels = invModel;
ArrayAdapter<ModelInventory> adptInv = new ArrayAdapter<ModelInventory>(context, android.R.layout.simple_spinner_dropdown_item, invModels);
ArrayAdapter<ModelHistory> adptChkItem = new ArrayAdapter<ModelHistory>(context, android.R.layout.simple_spinner_dropdown_item, candidateModelArrayList);
if (adptInv.isEmpty()) {
Toast.makeText(HistoryHeaderActivity.this, "Empty Patient", Toast.LENGTH_SHORT).show();
}
cart = CartHelper.getCart();
for (mPosition = 0; mPosition < adptChkItem.getCount(); mPosition++) {
ModelHistory historyItem = (ModelHistory) adptChkItem.getItem(mPosition);
for (int j = mPosition; j < adptInv.getCount(); j++) {
ModelInventory inventoryItem = (ModelInventory) adptInv.getItem(j);
if (candidateModelArrayList.get(mPosition).getH_item().equals(inventoryItem.getItem_ID())) {
if (cart.getProducts().toString().contains(inventoryItem.getItem_Name())) {
} else {
productInv = (ModelInventory) (Serializable) adptInv.getItem(j);
int qty = Integer.parseInt(historyItem.getH_qty());
cart.add(productInv, qty);
}
} else {
}
}
}
Intent i = new Intent(getBaseContext(), CartActivity.class);
i.putExtra("PersonID", "try");
startActivity(i);
}
#Override
protected Dialog onCreateDialog(int id) {
}
#Override
public boolean onQueryTextSubmit(String query) {
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
hstAdpt.getFilter().filter(newText);
idhstAdpt.getFilter().filter(newText);
return false;
}
public void AddNewList(){
ArrayAdapter<ModelIDHeader> adptIDHeader = new ArrayAdapter<ModelIDHeader>(context, android.R.layout.simple_spinner_dropdown_item, headerModel);
for(int count =0; count< adptIDHeader.getCount(); count++){
idhstAdpt = new AdapterHistory(HistoryHeaderActivity.this, historyModel);
ModelIDHeader idHeader = (ModelIDHeader) adptIDHeader.getItem(count);
Button btn = new Button(this);
btn.setId(count);
btn.setText(idHeader.getIdSalesHeader());
lm.addView(btn);
SearchView search = new SearchView(this);
search.setQuery(idHeader.getIdSalesHeader(), false);
search.setOnQueryTextListener(this);
lm.addView(search);
ListView tv = new ListView(this);
tv.setId(count);
tv.setLayoutParams(params);
tv.setDividerHeight(2);
tv.setAdapter(idhstAdpt);
lm.addView(tv);
}
}
public void ShowAllContentHistory() {
listHistory = (ListView) findViewById(R.id.listhistory);
hstAdpt = new AdapterHistory(HistoryHeaderActivity.this, historyModel);
listHistory.setAdapter(hstAdpt);
listHistory.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.activity_history_actions, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_logout) {
new AlertDialog.Builder(this)
.setMessage("Are you sure you want to exit?")
.setCancelable(false)
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
ClearPrefs();
logout();
Intent intent = new Intent(HistoryHeaderActivity.this, LoginActivity.class);
startActivity(intent);
}
})
.setNegativeButton("No", null)
.show();
return true;
}
if (id == R.id.action_home) {
Intent intent = new Intent(HistoryHeaderActivity.this, MainActivity.class);
startActivity(intent);
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onBackPressed() {
Intent intent = new Intent(HistoryHeaderActivity.this, MainActivity.class);
startActivity(intent);
}
public void ClearPrefs() {
}
public void logout() {
SharedPreferences preferences5 = getSharedPreferences("IDLOGIN", Context.MODE_PRIVATE);
SharedPreferences.Editor editor5 = preferences5.edit();
editor5.clear();
editor5.commit();
}
}

display description of news in another activity

I need to display description of news in ShowNews activity and I used the intent
and put extra method to pass the description to the ShowNews Activity that contain a textview for setting Description. What is wrong in my code?
public class Downloader extends AsyncTask<Void,Void,Object> {
Context c;
String urlAddress ;
ListView lv;
ProgressDialog pd;
public Downloader(Context c,String urlAddress,ListView lv)
{
this.c = c;
this.urlAddress =urlAddress;
this.lv = lv;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
pd = new ProgressDialog(c);
pd.setTitle("Fetching Data");
pd.setMessage("Fetchinf Data...please wait ");
pd.show();
}
#Override
protected Object doInBackground(Void... voids) {
return this.downloadData();
}
#TargetApi(Build.VERSION_CODES.CUPCAKE)
#Override
protected void onPostExecute(Object data) {
super.onPostExecute(data);
pd.dismiss();
if (data.toString().startsWith("Error"))
{
Toast.makeText(c,data.toString(),Toast.LENGTH_LONG).show();
}
else {
// parsing
new ReadRss(c, (InputStream) data,lv).execute();
}
}
private Object downloadData()
{
Object connection = Connector.connect(urlAddress);
if (connection.toString().startsWith("Error"))
{
return connection.toString();
}
try {
HttpURLConnection con = (HttpURLConnection) connection;
int responsecode = con.getResponseCode();
if (responsecode == con.HTTP_OK) {
InputStream is = new BufferedInputStream(con.getInputStream());
return is;
}
return ErrorTracer.RESPONSE_ERROR+con.getResponseMessage();
} catch (IOException e) {
e.printStackTrace();
return ErrorTracer.IO_ERROR;
}
}
}
public class ReadRss extends AsyncTask<Void,Void,Boolean> {
Context c;
InputStream is;
ListView lv;
ProgressDialog pd;
CustomAdapter adapter ;
ArrayList<Site> sites = new ArrayList<>();
public ReadRss(Context c,InputStream is,ListView lv)
{
this.c = c;
this.is =is;
this.lv = lv;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
pd = new ProgressDialog(c);
pd.setTitle("parsing Data");
pd.setMessage("parsing Data...please wait ");
pd.show();
}
#Override
protected Boolean doInBackground(Void... voids) {
return this.parseRss();
}
#Override
protected void onPostExecute(Boolean isparsed) {
super.onPostExecute(isparsed);
pd.dismiss();
if (isparsed)
{
//bind
lv.setAdapter(new CustomAdapter(c,sites));
}
else {
Toast.makeText(c,"Unable to parse",Toast.LENGTH_LONG).show();
}
}
private Boolean parseRss()
{
try {
XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
XmlPullParser parser = factory.newPullParser();
parser.setInput(is,null);
int event = parser.getEventType();
String value = null;
sites.clear();
Site site = new Site();
do {
String name = parser.getName();
switch (event)
{
case XmlPullParser.START_TAG:
if (name.equals("item"))
{
site = new Site();
}
break;
case XmlPullParser.TEXT:
value = parser.getText();
break;
case XmlPullParser.END_TAG:
if (name.equals("title"))
{
site.setTitle(value);
}else if (name.equals("description"))
{
site.setDescription(value);
}else if (name.equals("pubDate"))
{
site.setData(value);
}else if (name.equals("link"))
{
site.setLink(value);
}
if (name.equals("item"))
{
sites.add(site);
}
break;
}
event = parser.next();
}while (event!=XmlPullParser.END_DOCUMENT);
return true;
} catch (XmlPullParserException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return false;
}
}
public class CustomAdapter extends BaseAdapter {
Context c;
ArrayList<Site> sites;
public CustomAdapter(Context c,ArrayList<Site> sites)
{
this.c = c;
this.sites = sites;
}
#Override
public int getCount() {
return sites.size();
}
#Override
public Object getItem(int i) {
return sites.get(i);
}
#Override
public long getItemId(int i) {
return i;
}
#Override
public View getView(int i, View view, ViewGroup viewGroup) {
if (view==null)
{
view = LayoutInflater.from(c).inflate(R.layout.row,viewGroup,false);
}
TextView titletxt = (TextView) view.findViewById(R.id.textView);
TextView desctxt = (TextView) view.findViewById(R.id.textView2);
TextView datetxt = (TextView) view.findViewById(R.id.textView3);
Site site = (Site) this.getItem(i);
titletxt.setText(site.getTitle());
desctxt.setText(site.getDescription());
datetxt.setText(site.getData());
return view;
}
}
public class MainActivity extends AppCompatActivity {
String ulrAddress = "http://www.alahlytv.net/Rss_Feeds.aspx";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
final ListView lv = (ListView) findViewById(R.id.lv);
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
Intent intent = new Intent(MainActivity.this,ShowNews.class);
Site site = new Site();
intent.putExtra("one",site.getDescription());
startActivity(intent);
}
});
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
new Downloader(MainActivity.this,ulrAddress,lv).execute();
}
});
public class ShowNews extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_show_news);
TextView textView = (TextView) findViewById(R.id.textView4);
Intent intent = getIntent();
Bundle bd = intent.getExtras();
if(bd != null)
{
String getName = (String) bd.get("one");
textView.setText(getName);
}
}
}
When you add any extra in your intent, don't try to get it from the Bundle. So change your reading passed data code to:
Intent intent = getIntent();
String getName = intent.getStringExtra("one", "default_value_if_null");
textView.setText(getName);
change your code like this
Intent intent = getIntent();
if(intent != null)
{
String getName = intent.getExtras().getString("one");
textView.setText(getName);
}

android ListActivity how to populate data with Json Volley Library

android ListActivity how to make Custom Adapter getter setter using ,call json Volley library populate data ListActivity ? could not populate data with Json how to implement ,Please Help me
my code
ItemFragment Class
public class ItemFragment extends ListActivity {
RequestParse requestParse;
MySharedPreferences prefs;
String UsrId;
Context context;
ArrayList<BizForumArticleInfo> list = new ArrayList<>();
private List<BizForumArticleInfo> CountryCodeNumber = new ArrayList<>();
MobileArrayAdapter adapter;
LinearLayoutManager mLayoutManager;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list_view_android_example);
requestParse = new RequestParse();
prefs = MySharedPreferences.getInstance(this, SESSION);
UsrId = prefs.getString("UsrID", "");
context = getApplicationContext();
setListAdapter(new MobileArrayAdapter(this,0, list));
getJson(60);
}
public void getJson(final int limit){
requestParse.postJson(ConfigApi.postArticleBiz(), new RequestParse.VolleyCallBackPost() {
#Override
public void onSuccess(String result) {
list = parseResponse(result);
}
#Override
public void onRequestError(String errorMessage) {
}
#Override
public Map OnParam(Map<String, String> params) {
params.put("sessionid", UsrId);
params.put("offset", "0");
params.put("limit", String.valueOf(limit));
params.put("viewtype", "all");
params.put("access_token","e3774d357aa7d4bd14e9763b5459ee9cf7ebe36161c142551836ee510d98814a:b349b76b334a94b2");
return params;
}
});
}
public static ArrayList<BizForumArticleInfo> parseResponse(String response) {
ArrayList<BizForumArticleInfo> bizList = new ArrayList<>();
try {
JSONObject json = new JSONObject(response);
JSONArray data = json.getJSONArray(DATA);
for (int i = 0; i < data.length(); i++) {
BizForumArticleInfo ls = new BizForumArticleInfo();
JSONObject item = data.getJSONObject(i);
String ArticleTitle = item.getString("ArticleTitle");
String Article = item.getString("Article");
M.i("===================",ArticleTitle);//working
ls.setArticleTitle(ArticleTitle);
ls.setArticleArticle(Article);
bizList.add(ls);
}
} catch (JSONException e) {
e.printStackTrace();
}
return bizList;
}
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
String selectedValue = (String) getListAdapter().getItem(position);
Toast.makeText(this, selectedValue, Toast.LENGTH_SHORT).show();
Intent intent = new Intent();
intent.putExtra("selectedValue", selectedValue);
setResult(RESULT_OK, intent);
finish();
//startActivity(new Intent(v.getContext(), MainActivity.class));
}
}
Adapter Class
public class MobileArrayAdapter extends ArrayAdapter<BizForumArticleInfo> {
private Activity activity;
private ArrayList<BizForumArticleInfo> lPerson;
private static LayoutInflater inflater = null;
public MobileArrayAdapter (Activity activity, int textViewResourceId,ArrayList<BizForumArticleInfo> _lPerson) {
super(activity, textViewResourceId, _lPerson);
try {
this.activity = activity;
this.lPerson = _lPerson;
inflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
} catch (Exception e) {
}
}
public int getCount() {
return lPerson.size();
}
public BizForumArticleInfo getItem(BizForumArticleInfo position) {
return position;
}
public long getItemId(int position) {
return position;
}
public static class ViewHolder {
public TextView display_name;
public TextView display_number;
}
public View getView(int position, View convertView, ViewGroup parent) {
View vi = convertView;
final ViewHolder holder;
try {
if (convertView == null) {
vi = inflater.inflate(R.layout.list_mobile, null);
holder = new ViewHolder();
holder.display_name = (TextView) vi.findViewById(R.id.label);
vi.setTag(holder);
} else {
holder = (ViewHolder) vi.getTag();
}
holder.display_name.setText(lPerson.get(position).getArticleTitle());
} catch (Exception e) {
}
return vi;
}
}

Custom ListView - Duplicate Entries

Main Activity
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
String[] answers = new String[]{"choice0","choice2","choice0","choice1","choice3","choice3"};
Question[] questions = new Question[6];
for(int i=0; i<6; i++){
questions[i] = new Question("Question"+(1+i),new String[]{"choice0","choice1","choice2","choice3"},answers[i]);
}
ListView listView = (ListView)findViewById(R.id.listQuestions);
QuestionAdapter questionAdapter = new QuestionAdapter(this, R.layout.list_item_row_qs, questions);
listView.setAdapter(questionAdapter);
}
}
Adapter
public class QuestionAdapter extends ArrayAdapter {
Context context;
Question[] questions;
View view;
public QuestionAdapter(Context context, int id, Question[] questions){
super(context, id, questions);
this.context = context;
this.questions = questions;
}
private class ViewHolder{
TextView chapName;
RadioButton rb0;
RadioButton rb1;
RadioButton rb2;
RadioButton rb3;
Button button;
RadioGroup rg;
TextView hiddenAnswer;
}
#Override
public View getView(int pos, View row, ViewGroup parent){
this.view = row;
ViewHolder viewHolder = null;
if(row == null) {
LayoutInflater inflater = ((Activity)context).getLayoutInflater();
row = inflater.inflate(R.layout.list_item_row_qs, null);
viewHolder = new ViewHolder();
viewHolder.chapName=(TextView) row.findViewById(R.id.question);
viewHolder.rb0 = (RadioButton) row.findViewById(R.id.choice0);
viewHolder.rb1 = (RadioButton) row.findViewById(R.id.choice1);
viewHolder.rb2 = (RadioButton) row.findViewById(R.id.choice2);
viewHolder.rb3 = (RadioButton) row.findViewById(R.id.choice3);
viewHolder.button = (Button) row.findViewById(R.id.check);
viewHolder.hiddenAnswer = (TextView) row.findViewById(R.id.answer);
row.setTag(viewHolder);
}
else {
viewHolder = (ViewHolder)row.getTag();
}
viewHolder.chapName.setText(questions[pos].getQuestionDescr());
viewHolder.rb0.setText(questions[pos].getChoice()[0]);
viewHolder.rb1.setText(questions[pos].getChoice()[1]);
viewHolder.rb2.setText(questions[pos].getChoice()[2]);
viewHolder.rb3.setText(questions[pos].getChoice()[3]);
viewHolder.hiddenAnswer.setText(questions[pos].getAnswer());
viewHolder.button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
View rowView = (ViewGroup) v.getParent();
RadioGroup group = (RadioGroup) rowView.findViewById(R.id.rg);
int selectedId = group.getCheckedRadioButtonId();
if (selectedId == -1) {
Toast.makeText(context, "Please choose the correct option", Toast.LENGTH_LONG).show();
} else {
RadioButton radioButton = (RadioButton) group.findViewById(selectedId);
String answer = String.valueOf(((TextView) rowView.findViewById(R.id.answer)).getText());
if (radioButton.getText().equals(answer)) {
Toast.makeText(context, "Correct Answer", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(context, "Wrong Answer", Toast.LENGTH_LONG).show();
}
}
}
});
return row;
}
}
Problem
First item in the list maps to 5th item. 2nd item to sixth item. I mean if I change radio button at the first item, Same radio button gets selected at the 5th list item also.
Any suggestions?
Is it because of recycling?
How do I resolve it?
I tried saving in Question object and retrieving it. I used pos to retrieve and set. But same problem still exist.
Adapter:
public class PersonAdapter extends BaseAdapter
{
private static final int MIN_RECORDS_NUMBER = 11;
private Context _con;
private List<Person> _data;
public PersonAdapter(Context context, List<Person> data)
{
_con = context;
_data = data;
}
#Override
public int getCount()
{
return _data.size();
}
#Override
public Person getItem(int position)
{
return _data.get(position);
}
#Override
public long getItemId(int position)
{
// TODO Auto-generated method stub
return 0;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent)
{
Holder h = null;
if (convertView == null)
{
h = new Holder();
convertView = LayoutInflater.from(_con).inflate(R.layout.item_layout, parent, false);
h._backgroundItem = (LinearLayout) convertView.findViewById(R.id.item_layout);
h._fName = (TextView) convertView.findViewById(R.id.f_name);
h._lName = (TextView) convertView.findViewById(R.id.l_name);
h._age = (TextView) convertView.findViewById(R.id.age);
h._editBtn = (Button) convertView.findViewById(R.id.edit_btn);
convertView.setTag(h);
}
else
{
h = (Holder) convertView.getTag();
}
final Person p = getItem(position);
h._fName.setText(p._fName);
h._lName.setText(p._lName);
h._age.setText(String.valueOf(p._age));
h._backgroundItem.setActivated(p._selected);
h._editBtn.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
((MainActivity)_con).onEditClick(p._url);
}
});
convertView.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
Person p = getItem(position);
Intent i = new Intent(_con,SecondActivity.class);
i.putExtra("DATA", p._fName);
_con.startActivity(i);
}
});
return convertView;
}
public void setData(List<Person> data)
{
_data = data;
notifyDataSetChanged();
}
private static class Holder
{
public LinearLayout _backgroundItem;
public TextView _fName;
public TextView _lName;
public TextView _age;
public Button _editBtn;
}
public interface IDialog
{
public void onEditClick(String url);
}
}
Activity
public class MainActivity extends Activity implements IDialog
{
private ListView _listView;
private PersonAdapter _adapter;
private Button _sortBtn;
private List<Person> _data;
private int _sort;
private int _selectedItemIndex;
private Bitmap _bit;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
_listView = (ListView) findViewById(R.id.list);
_sortBtn = (Button) findViewById(R.id.sort_list_btn);
_selectedItemIndex = -1;
_sort = 1;
_data = new ArrayList<Person>();
_data.add(new Person("http://i2.cdn.turner.com/cnnnext/dam/assets/160503230552-sanders-clinton-trump-triple-composite-mullery-medium-tease.jpg","abc", "defg", 1));
_data.add(new Person("http://i2.cdn.turner.com/cnnnext/dam/assets/160503230552-sanders-clinton-trump-triple-composite-mullery-medium-tease.jpg","aaa", "defg", 12));
_data.add(new Person("http://i2.cdn.turner.com/cnnnext/dam/assets/160503230552-sanders-clinton-trump-triple-composite-mullery-medium-tease.jpg","ccc", "defg", 13));
_data.add(new Person("http://i2.cdn.turner.com/cnnnext/dam/assets/160511120611-bud-america-medium-tease.jpg","bb", "defg", 14));
_data.add(new Person("http://i2.cdn.turner.com/cnnnext/dam/assets/160511120611-bud-america-medium-tease.jpg","aa", "defg", 144));
_data.add(new Person("http://i2.cdn.turner.com/cnnnext/dam/assets/160511120611-bud-america-medium-tease.jpg","fff", "defg", 199));
// _adapter = new PersonAdapter(this, _data);
// _listView.setAdapter(_adapter);
RedirectToMainActivityTask task = new RedirectToMainActivityTask();
task.execute();
_listView.setOnItemClickListener(new OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id)
{
if(position<_data.size())
{
if(_selectedItemIndex>-1)
{
_data.get(_selectedItemIndex)._selected = false;
}
_selectedItemIndex = position;
_data.get(position)._selected = true;
_adapter.setData(_data);
}
}
});
_sortBtn.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
if(_selectedItemIndex>-1)
{
_listView.clearChoices();
String fName = _adapter.getItem(_selectedItemIndex)._fName;
Comparator<Person> sortById = Person.getComperatorByFirstName(_sort);
Collections.sort(_data, sortById);
int newSelectedItemIndex = getSelectedItemIndexByFName(fName);
_selectedItemIndex = newSelectedItemIndex;
_adapter.setData(_data);
if(newSelectedItemIndex>-1)
{
_listView.setItemChecked(newSelectedItemIndex, true);
}
_sort = -_sort;
}
else
{
Comparator<Person> sortById = Person.getComperatorByFirstName(_sort);
Collections.sort(_data, sortById);
_adapter.setData(_data);
_sort = -_sort;
}
}
});
}
private int getSelectedItemIndexByFName(String name)
{
for(int index=0;index<_data.size();index++)
{
if(_data.get(index)._fName.equals(name))
{
return index;
}
}
return -1;
}
public static class Person
{
public String _url;
public String _fName;
public String _lName;
public int _age;
public boolean _selected;
public Person(String url,String fName, String lName, int age)
{
_url = url;
_fName = fName;
_lName = lName;
_age = age;
}
public static Comparator<Person> getComperatorByFirstName(final int ascendingFlag)
{
return new Comparator<Person>()
{
#Override
public int compare(Person patient1, Person patient2)
{
return patient1._fName.compareTo(patient2._fName) * ascendingFlag;
}
};
}
}
public Bitmap getBitmapFromURL(String src) {
try
{
URL url = new URL(src);
HttpURLConnection httpCon = (HttpURLConnection) url.openConnection();
httpCon.setInstanceFollowRedirects(true);
Bitmap image = BitmapFactory.decodeStream(httpCon.getInputStream());
return image;
}
catch (MalformedURLException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#Override
public void onEditClick(final String url)
{
new Thread(new Runnable()
{
#Override
public void run()
{
_bit = getBitmapFromURL(url);
runOnUiThread(new Runnable()
{
#Override
public void run()
{
Dialog dialog = new Dialog(MainActivity.this);
dialog.setContentView(R.layout.custom_image);
ImageView image = (ImageView) dialog.findViewById(R.id.image);
if(_bit!=null)
{
image.setImageBitmap(_bit);
}
dialog.setTitle("This is my custom dialog box");
dialog.setCancelable(true);
//there are a lot of settings, for dialog, check them all out!
dialog.show();
}
});
}
}).start();
}
private class RedirectToMainActivityTask extends AsyncTask<Void, Void, Void>
{
protected Void doInBackground(Void... params)
{
try
{
Thread.sleep( 2 * 1000 );
}
catch ( InterruptedException e )
{
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result)
{
Intent intent = new Intent( getApplicationContext(), SecondActivity.class );
intent.addFlags( Intent.FLAG_ACTIVITY_CLEAR_TOP );
startActivity( intent );
}
}
}
I am saving the state of the person view inside of person object

Categories

Resources