Related
I want to send multiple selected checkbox travel id value to a server.
The code is working, but the value is not updating.
When the submit button is pressed, I want all the selected checkbox values to be sent to the server and the selected check box values are updated on the server.
package com.example.fiffa.fifaa;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.util.SparseBooleanArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;
import org.w3c.dom.Text;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class ViewSubmission extends AppCompatActivity{
final Context context = this;
ListView listView;
String travelid;
TextView txtvisit,txtsum,txtsystem;
Button submit,back;
String MyPREFERENCES = "loginInfo";
SharedPreferences sharedpreferences;
ProgressDialog pDialog;
String ss="";
String userid;
boolean[] present;
boolean[] absent;
String takenatt="";
double gtotal=0.0;
List<Submitconvencelistitem> rowItems;
ArrayList<Submitconvencelistitem> feedsList;
Submitconvenceadapter adapter;
int count;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view_submission);
submit = (Button) findViewById(R.id.submit);
back = (Button) findViewById(R.id.backviewsub);
txtvisit=(TextView)findViewById(R.id.txtvisit);
txtsum=(TextView)findViewById(R.id.txttotal);
//txtsystem=(TextView)findViewById(R.id.txtsystem);
listView = (ListView) findViewById(R.id.lstconveynce);
back.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent viewsub=new Intent(ViewSubmission.this,Submitconveyance.class);
startActivity(viewsub);
}
});
String viewdata = getIntent().getExtras().getString("response", "");
Log.e("viewdata", viewdata);
sharedpreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
//conveyncetravelid = sharedpreferences.getString("travelid", "");
//Log.e("econveyncetravelid", conveyncetravelid);
userid = sharedpreferences.getString("userId", "");
Log.e("userId", userid);
try {
//feedsList=getSubmit(false);
JSONArray js = new JSONArray(viewdata);
feedsList=new ArrayList<>();
for (int i = 0; i < js.length(); i++) {
JSONObject jObject = js.getJSONObject(i);
Submitconvencelistitem st=new Submitconvencelistitem();
String total_amount=jObject.getString("total_amount");
Log.e("total_amount",total_amount);
//String travelid = jObject.getString("travelid");
//Log.e("conveyncetravelid", travelid);
st.settravelid(jObject.optString("travelid"));
st.setsubdate(jObject.optString("startdate"));
st.setstartlocation(jObject.optString("startlocation"));
st.setendlocation(jObject.optString("endlocation"));
st.setccno(jObject.optString("cc_no"));
st.setcustomername(jObject.optString("custname"));
st.setcallstatus(jObject.optString("callstatus"));;
st.setmodeofconveynce(jObject.optString("travel_mode"));
st.setkmstravelled(jObject.optString("KM"));
st.setclaimamout(jObject.optString("total_amount"));
//st.setSelected(true);
feedsList.add(st);
/* gtotal += Double.parseDouble(feedsList.get(i).getclaimamout());
Log.e("Total", String.valueOf(gtotal));
txtsum.setText(Double.toString(gtotal));*/
//Toast.makeText(MainActivity.this,result.toString(),Toast.LENGTH_LONG).show();
/* Log.e("shams", viewdata.toString());
String startdate = js.getJSONObject(0).getString("startdate");
Log.e("startdate",startdate);
String startlocation = js.getJSONObject(0).getString("startlocation");
Log.e("startlocation",startlocation);
String endlocation = js.getJSONObject(0).getString("endlocation");
Log.e("endlocation",endlocation);
String cc_no = js.getJSONObject(0).getString("cc_no");
Log.e("cc_no",cc_no);
String custname = js.getJSONObject(0).getString("custname");
Log.e("custname",custname);
String callstatus = js.getJSONObject(0).getString("callstatus");
Log.e("callstatus",callstatus);
String travel_mode = js.getJSONObject(0).getString("travel_mode");
Log.e("travel_mode",travel_mode);
String KM = js.getJSONObject(0).getString("KM");
Log.e("KM",KM);
String total_amount = js.getJSONObject(0).getString("total_amount");
Log.e("total_amount",total_amount);
st.setsubdate(startdate);
st.setstartlocation(startlocation);
st.setendlocation(endlocation);
st.setccno(cc_no);
st.setcustomername(custname);
st.setcallstatus(callstatus);
st.setmodeofconveynce(travel_mode);
st.setkmstravelled(KM);
st.setclaimamout(total_amount);
st.setSelected(true);*//*
feedsList.add(st);*/
/* JSONObject post = js.getJSONObject(i);
Submitconvencelistitem st=new Submitconvencelistitem();
st.setsubdate(post.optString("startdate"));
st.setstartlocation(post.optString("startlocation"));
st.setendlocation(post.optString("endlocation"));
st.setccno(post.optString("cc_no"));
st.setcustomername(post.optString("custname"));
st.setcallstatus(post.optString("callstatus"));
st.setmodeofconveynce(post.optString("travel_mode"));
st.setkmstravelled(post.optString("KM"));
st.setclaimamout(post.optString(("total_amount")));
st.setSelected(true);
feedsList.add(st);*/
}
adapter = new Submitconvenceadapter(ViewSubmission.this, feedsList);
listView.setAdapter(adapter);
adapter.notifyDataSetChanged();
count=adapter.getCount();
txtvisit.setText(Integer.toString(count));
}
catch (JSONException e) {
e.printStackTrace();
}
submit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//final List<Submitconvencelistitem> selectedItems = adapter.getSelectedItems();
//Use this data for sending to your webserver
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(ViewSubmission.this);
alertDialogBuilder.setMessage("Submit the Selected Conveynce");
alertDialogBuilder.setPositiveButton("yes",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface arg0, int arg1) {
for (int strt=0;strt<present.length;strt++) {
if (present[strt]) {
travelid = feedsList.get(strt).gettravelid();
}
new Asyncupdate_travelforconv().execute();
}
//Toast.makeText(ViewSubmission.this,"Your conveyance has been submitted ",Toast.LENGTH_LONG).show();
}
});
alertDialogBuilder.setNegativeButton("No",new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Intent view=new Intent(ViewSubmission.this,Submitconveyance.class);
startActivity(view);
}
});
AlertDialog alertDialog = alertDialogBuilder.create();
alertDialog.show();
//new Asncselect_travelforconvsub().execute();
}
});
}
/* private ArrayList<Submitconvencelistitem> getSubmit(boolean isSelect){
ArrayList<Submitconvencelistitem> list = new ArrayList<>();
for(int i = 0; i < feedsList.size(); i++){
Submitconvencelistitem st = new Submitconvencelistitem();
st.setSelected(isSelect);
feedsList.add(st);
}
return list;
}
*/
/*Asynctask For Insertstart travel details*/
private class Asyncupdate_travelforconv extends AsyncTask<String, Integer, String> {
String SOAP_ACTION = "http://tempuri.org/IFIFA/update_travelforconv";
String NAMESPACE = "http://tempuri.org/";
String METHOD_NAME = "update_travelforconv";
String URL = "http://migadget.aforeserve.co.in/FIFA.svc?singleWsdl";
#Override
protected void onPreExecute() {
}
#Override
protected String doInBackground(String... strings) {
try {
SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
request.addProperty("travelid", travelid);
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
//envelope.setOutputSoapObject(request);
envelope.dotNet = true;
envelope.setOutputSoapObject(request);
HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);
try {
androidHttpTransport.call(SOAP_ACTION, envelope);
Object result = null;
result = (Object) envelope.getResponse();
Log.e("conveynce", String.valueOf(result));
System.out.println("APIresult:" + result.toString());
ss = result.toString();
Log.e("APIRESULT", ss);
} catch (Exception e) {
System.out.println("Error" + e);
}
return ss;
} catch (Exception ex) {
ex.printStackTrace();
return "";
}
}
#Override
protected void onPostExecute(String result) {
Log.e("APIResult", result);
Toast.makeText(getBaseContext(), "Data Updated", Toast.LENGTH_LONG).show();
}
}
/*Adapter class For Submit conveynce */
public class Submitconvenceadapter extends BaseAdapter {
ArrayList<Submitconvencelistitem> listData;
private LayoutInflater layoutInflater;
Context context;
List<Submitconvencelistitem> rowItems;
String MyPREFERENCES = "loginInfo";
String travelid;
SharedPreferences sharedpreferences;
public Submitconvenceadapter(Context ViewSubmission,ArrayList<Submitconvencelistitem> results)
{
listData = results;
context=ViewSubmission;
present=new boolean[listData.size()];
Arrays.fill(present, true);
}
#Override
public int getCount()
{
return listData.size();
}
#Override
public Object getItem(int position)
{
return listData.get(position);
}
#Override
public long getItemId(int position)
{
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent)
{
final ViewHolder holder;
LayoutInflater layoutInflater=(LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
convertView = layoutInflater.inflate(R.layout.list_item_submitconveynce, null);
holder = new ViewHolder();
//holder.checkbox=(CheckBox) convertView.findViewById(R.id.cb1);
holder.date = (TextView) convertView.findViewById(R.id.subdate);
holder.startlocation = (TextView) convertView.findViewById(R.id.startlocation);
holder.endlocation=(TextView)convertView.findViewById(R.id.endlocation);
holder.ccno = (TextView) convertView.findViewById(R.id.ccno);
holder.customername = (TextView) convertView.findViewById(R.id.tv_name);
holder.callstatus = (TextView)convertView.findViewById(R.id.tv_callstatus);
holder.modeofconveynce = (TextView)convertView.findViewById(R.id.tv_modconveynce);
holder.Kmtravelled = (TextView)convertView.findViewById(R.id.tv_km);
holder.claimamount = (TextView)convertView.findViewById(R.id.claim_amount);
holder.checkbox=(CheckBox)convertView.findViewById(R.id.chk1);
/*//holder.checkbox.setChecked(true);
holder.checkbox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
listData.get(position).setSelected(isChecked);
}
});*/
convertView.setTag(holder);
holder.checkbox.setChecked(present[position]);
}
else
{
holder = (ViewHolder) convertView.getTag();
holder.checkbox.setChecked(present[position]);
}
holder.checkbox.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (holder.checkbox.isChecked())
present[position] = true;
else
present[position] = false;
}
});
//travelid=listData.get(position).gettravelid();
//holder.travelid.setText(listData.get(position).gettravelid());
holder.date.setText(listData.get(position).getsubdate());
holder.startlocation.setText(listData.get(position).getstartlocation());
holder.endlocation.setText(listData.get(position).getendlocation());
holder.ccno.setText(listData.get(position).getccno());
holder.customername.setText(listData.get(position).getcustomername());
holder.callstatus.setText(listData.get(position).getcallstatus());
holder.modeofconveynce.setText(listData.get(position).getmodeofconveynce());
holder.Kmtravelled.setText(listData.get(position).getkmstravelled());
holder.claimamount.setText(listData.get(position).getclaimamout());
//holder.checkbox.setChecked(true);
return convertView;
}
public class ViewHolder {
CheckBox checkbox;
TextView date;
TextView startlocation;
TextView endlocation;
TextView ccno;
TextView customername;
TextView callstatus;
TextView modeofconveynce;
TextView Kmtravelled;
TextView claimamount;
TextView travelid;
}
/* public List<Submitconvencelistitem> getSelectedItems()
{
List<Submitconvencelistitem> selectedItems = new ArrayList<>();
for(Submitconvencelistitem item : listData)
{
selectedItems.add(item);
}
return selectedItems;
}*/
}
}
I am assuming that you are using php over your server.What you can do is send the comma separated travel id's over server like this:-
Put travel id's into an arraylist or array like this:-
ArrayList<String> selectedTravelId= new ArrayList<>();
selectedTravelId.add(travelId); // add travel ids
StringBuilder travelId = new StringBuilder();
for (int i = 0; i < selectedTravelId.size(); i++) {
travelId .append(selectedTravelId.get(i));
if (!(i == selectedTravelId.size() - 1)) {
travelId .append(",");
}
}// to create travelId string
travelId.toString();// to convert StringBuilder to String
After this execute your AsyncTask.
You will get a string like e.g. 1,2,134,142.Now send this travelId to sever.
At server side retrieve
Try explode:
$mytravelId = " 1,2,134,142";
$myArray = explode(',', $mytravelId );
print_r($myArray);
Output :
Array
(
[0] => 1
[1] => 2
[2] => 134
[3] => 142
)
I am working with GridView. I want to update GridView on some basis. But notifyDataSetChanged() method is not working.
I am selecting tables on basis of section name. When I select section name very first time than I got tables of that section. But when I go to sections fragment again and select diff. section than I get previously selected tables only. That means notifyDataSetChanged() is not working.
What I have tried is like below.
TableScreenActivity.java
import java.util.ArrayList;
import java.util.HashMap;
import android.app.Activity;
import android.app.Dialog;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.view.Display;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.Animation.AnimationListener;
import android.view.animation.AnimationUtils;
import android.view.animation.ScaleAnimation;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.RelativeLayout.LayoutParams;
import android.widget.TextView;
import com.malaka.R;
import com.malaka.db.DBAdapter;
import com.malaka.helper.ActionItem;
import com.malaka.helper.AssignGetterSetter;
import com.malaka.helper.Attributes;
import com.malaka.helper.CategoryAdapter;
import com.malaka.helper.DialogAdapter;
import com.malaka.helper.JoinTableAdapter;
import com.malaka.helper.ListSwipeDetector;
import com.malaka.helper.Logout;
import com.malaka.helper.PopupWindows;
import com.malaka.helper.QuickAction;
import com.malaka.helper.QuickActionLocation;
import com.malaka.helper.ReplaceFragment;
import com.malaka.helper.async.AddNewCustomerAsync;
import com.malaka.helper.async.CustomerPhotoAsync;
import com.malaka.helper.async.GetValetNoAsync;
import com.malaka.helper.async.ReAssignTableAsync;
import com.malaka.helper.async.SetTableStatusAsync;
import com.malaka.helper.async.TableStatusAsync;
import com.malaka.helper.async.UnAttendedAsync;
import com.malaka.helper.async.ValetAsync;
import com.malaka.utils.CommanUtils;
import com.malaka.utils.PreferenceUtils;
public class TableScreenActivity extends Fragment {
final static String TAG = "TableScreenActivity";
Button btnBarCode, btnFeedBack, btnLogOut;
GridView gridView;
private TextView mDropdownTitle;
static DBAdapter dbAdapter;
TextView malaka, version;
ImageView refresh;
Animation rotation;
boolean isOpen = false;
RelativeLayout rl;
public static FragmentActivity activity;
LinearLayout mDropdownFoldOutNewCust;
TextView dropDownTextViewNewCust, alt0NewCust, alt1NewCust,
mDropdownTitleNewCust;
LinearLayout ll;
static Dialog dialogAddCust, joinDialog;
ListSwipeDetector detector;
static PreferenceUtils pref;
ArrayList<String> tableName, tableId, sectionId, tableDescriptionId,
tableDescription, custName, custId, custNo, parentId, isManager,
parentName;
ArrayList<String> isVale, isInquired;
ArrayList<Integer> tableColors;
Bundle bundle;
String name = "", no = "", custType = "", tableIds, tableDesc;
static String tableDescId;
static EditText edtName, edtNo;
int pos;
QuickAction quickAction;
QuickActionLocation quickActionLocation;
private static final int ID_TABLE = 1;
private static final int ID_TASK = 2;
private static final int ID_MANAGER = 3;
private static final int ID_RECIPE = 4;
private static final int ID_INSTRUCTION = 5;
private static final int ID_SEARCH = 6;
private static final int ID_HELP = 7;
private static final int ID_SETTING = 8;
private static final int ID_LOGOUT = 9;
private static final int ID_SECTIONS = 11;
private static final int ID_KP = 10;
private static final int ID_BANER = 20;
private static final int ID_CITY = 30;
static ArrayList<String> o_name, o_id, e_id, mTableIdList;
private CategoryAdapter categoryAdapter;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
System.out.println("TestTag: savedInstanceState " + savedInstanceState
+ " container: " + container);
System.out.println("TestTag: o_name " + o_name + " mTableIdList: "
+ mTableIdList);
View view = inflater.inflate(R.layout.table_screen, container, false);
init(view);
return view;
}
private void init(View view) {
System.out.println("TestTag: Time1: " + System.currentTimeMillis());
// getActivity().setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
activity = getActivity();
o_id = new ArrayList<String>();
o_name = new ArrayList<String>();
e_id = new ArrayList<String>();
mTableIdList = new ArrayList<String>();
TextView textView = (TextView) view.findViewById(R.id.txt_table_status);
textView.setVisibility(View.GONE);
refresh = (ImageView) view.findViewById(R.id.img_refresh_table);
rotation = AnimationUtils.loadAnimation(getActivity(),
R.anim.refresh_dialog);
pref = new PreferenceUtils(getActivity());
version = (TextView) view.findViewById(R.id.table_version);
version.setText(pref.getVersion());
if (!pref.getTableStatus()) {
TableStatusAsync Async = new TableStatusAsync(getActivity());
HashMap<String, String> map = new HashMap<String, String>();
Log.e(TAG,
"user id : " + pref.getUserId() + "location : "
+ pref.getLocation() + "SectionId: "
+ pref.getSectionId());
map.put("UserId", pref.getUserId());
map.put("SectionId", pref.getSectionId());
map.put("Location", pref.getLocation());
Async.execute(map);
}
dbAdapter = new DBAdapter(getActivity());
dbAdapter.open();
tableId = dbAdapter.getTableId();
tableName = dbAdapter.getTableName();
sectionId = dbAdapter.getTableSectionId();
tableDescriptionId = dbAdapter.getTableDescriptionId();
tableDescription = dbAdapter.getTableDescription();
custName = dbAdapter.getTableCustName();
custId = dbAdapter.getTableCustID();
custNo = dbAdapter.getTableCustNo();
parentId = dbAdapter.getTableParentId();
parentName = dbAdapter.getTableParentName();
isVale = dbAdapter.getTableIsValeStatus();
isManager = dbAdapter.getTableIsManagerStatus();
isInquired = dbAdapter.getTableIsInquiredStatus();
dbAdapter.close();
Log.d(TAG, "Table length ==" + tableId.size());
tableColors = new ArrayList<Integer>();
for (int i = 0; i < tableDescriptionId.size(); i++) {
tableColors.add(Attributes.getColors(tableDescriptionId.get(i),
getActivity()));
}
ll = (LinearLayout) view.findViewById(R.id.table_ll);
rl = (RelativeLayout) view.findViewById(R.id.ll);
if (pref.getUserRole()) {
rl.setVisibility(View.VISIBLE);
} else {
rl.setVisibility(View.GONE);
}
rl.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
quickActionLocation.show(arg0);
}
});
detector = new ListSwipeDetector();
malaka = (TextView) view.findViewById(R.id.txt_malaka_title_table);
malaka.setText(pref.getLocation());
gridView = (GridView) view.findViewById(R.id.gridView_table);
if (tableId.size() <= 0) {
gridView.setVisibility(View.GONE);
textView.setVisibility(View.VISIBLE);
} else {
gridView.setVisibility(View.VISIBLE);
textView.setVisibility(View.GONE);
}
dbAdapter = new DBAdapter(getActivity());
// CategoryAdapter categoryAdapter = new CategoryAdapter(getActivity(),
// 0,
// tableName, tableColors, isInquired, custName,
// tableDescriptionId, parentId, parentName, isManager);
// gridView.setAdapter(categoryAdapter);
// categoryAdapter.notifyDataSetChanged();
//tableName.clear();
//tableName = dbAdapter.getTableName();
categoryAdapter = new CategoryAdapter(getActivity(), 0, tableName,
tableColors, isInquired, custName, tableDescriptionId,
parentId, parentName, isManager);
gridView.setAdapter(categoryAdapter);
categoryAdapter.notifyDataSetChanged();
mDropdownTitle = ((TextView) view
.findViewById(R.id.dropdown_textview_table));
mDropdownTitle.setText(pref.getUserNameToGetManagerPage()
.substring(0, 1).toUpperCase()
+ pref.getUserNameToGetManagerPage().substring(1).toLowerCase()
+ " ");
final TextView dropDownTextView = (TextView) view
.findViewById(R.id.dropdown_textview_table);
dropDownTextView.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (PopupWindows.mWindow.isShowing()) {
closeDropdown();
} else {
openDropdown();
}
quickAction.show(v);
}
});
gridView.setOnTouchListener(detector);
gridView.setOnItemLongClickListener(new OnItemLongClickListener() {
....
....
}
gridView.setOnItemClickListener(new OnItemClickListener() {
....
....
}
}// init() method closes
#Override
public void onAttach(Activity activity) {
Log.d(TAG, "TestTag::: onAttach()");
super.onAttach(activity);
}
#Override
public void onCreate(Bundle savedInstanceState) {
Log.d(TAG, "TestTag::: onCreate() savedInstanceState: "
+ savedInstanceState);
super.onCreate(savedInstanceState);
}
#Override
public void onStart() {
Log.d(TAG, "TestTag::: onStart()");
super.onStart();
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
Log.d(TAG, "TestTag::: onActivityCreated(): savedInstanceState "
+ savedInstanceState);
super.onActivityCreated(savedInstanceState);
}
#Override
public void onResume() {
Log.d(TAG, "TestTag::: onResume()");
super.onResume();
}
#Override
public void onPause() {
Log.d(TAG, "TestTag::: onPause()");
super.onPause();
}
#Override
public void onDestroyView() {
Log.d(TAG, "TestTag::: onDestroyView()");
super.onDestroyView();
}
#Override
public void onDestroy() {
Log.d(TAG, "TestTag::: onDestroy()");
super.onDestroy();
}
#Override
public void onStop() {
Log.d(TAG, "TestTag::: onStop()");
super.onStop();
}
#Override
public void onDetach() {
Log.d(TAG, "TestTag::: onDetach()");
super.onDetach();
}
}
Please, Help. I got stuck in. Thanks advance.
EDIT
TableStatusAsync.java
package com.malaka.helper.async;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;
import android.os.AsyncTask;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import com.malaka.helper.AsyncAttributes;
import com.malaka.helper.ReplaceFragment;
import com.malaka.helper.TableStatusXmlParser;
import com.malaka.ui.TableScreenActivity;
import com.malaka.utils.CommanUtils;
import com.malaka.utils.NetworkUtils;
import com.malaka.utils.PreferenceUtils;
public class TableStatusAsync extends
AsyncTask<Map<String, String>, Void, Void> {
final static String TAG = "TableStatusAsync";
FragmentActivity context;
String xml;
PreferenceUtils pref;
int response;
boolean isConnected;
public TableStatusAsync(FragmentActivity context) {
this.context = context;
pref = new PreferenceUtils(context);
}
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
CommanUtils.getDialogShow(context, "Please Wait...");
}
#Override
protected Void doInBackground(Map<String, String>... params) {
if (NetworkUtils.isConnectedToInternet(context)) {
isConnected = true;
HashMap<String, String> map = (HashMap<String, String>) params[0];
SoapObject request = new SoapObject(
AsyncAttributes.TableStatusNAMESPACE,
AsyncAttributes.TableStatusMETHOD_NAME);
Iterator<String> iterator = map.keySet().iterator();
// PropertyInfo pi1 = new PropertyInfo();
// pi1.setName("UserId");
// pi1.setValue(map.get("UserId"));
// pi1.setType(String.class);
//
// PropertyInfo pi2 = new PropertyInfo();
// pi2.setName("SectionId");
// pi2.setValue(map.get("SectionId"));
// pi2.setType(String.class);
//
// PropertyInfo pi3 = new PropertyInfo();
// pi3.setName("Location");
// pi3.setValue(map.get("Location"));
// pi3.setType(String.class);
//
// request.addProperty(pi1);
// request.addProperty(pi2);
// request.addProperty(pi3);
Log.e(TAG,
"user id : " + map.get("UserId") + "\nsection id : "
+ map.get("SectionId") + "\nlocation : "
+ map.get("Location"));
while (iterator.hasNext()) {
String key = iterator.next();
request.addProperty(key, map.get(key));
Log.d(TAG, "user id key: " + key + " value: " + map.get(key));
}
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
SoapEnvelope.VER11);
envelope.dotNet = true;
envelope.setOutputSoapObject(request);
HttpTransportSE androidHttpTransport = new HttpTransportSE(
AsyncAttributes.TableStatusURL);
try {
androidHttpTransport.call(
AsyncAttributes.TableStatusSOAP_ACTION, envelope);
SoapObject result = (SoapObject) envelope.bodyIn;
if (result
.toString()
.equals("GetTableStatusResponse{GetTableStatusResult=No Table available; }")) {
String xmltemp = String.valueOf(result).split("=")[1];
xml = xmltemp.split(";")[0];
} else {
String xmltemp = "<NewDataSet>\n"
+ String.valueOf(result).split("<NewDataSet>")[1];
xml = xmltemp.split("</NewDataSet>")[0] + "</NewDataSet>";
}
} catch (Exception e) {
e.printStackTrace();
}
if (xml == null) {
response = 1;
Log.d(TAG, "xml null");
} else if (xml.equals("No Table available")) {
response = 2;
} else {
response = 2;
Log.d(TAG, "Task 1 result " + xml);
TableStatusXmlParser.getTableStatusXmlParseData(xml, context);
}
} else {
isConnected = false;
}
return null;
}
protected void onPostExecute(Void result) {
super.onPostExecute(result);
CommanUtils.getDialogDismiss();
if (!isConnected) {
CommanUtils.showAlertDialog("Internet Is Required", context);
} else if (response == 1) {
CommanUtils.getToast("Server Error", context);
}
if (response == 2) {
pref.setTableStatus(true);
ReplaceFragment.getReplaceFragment(context,
new TableScreenActivity(), "");
}
}
}
EDIT - 2
CategoryAdapter.java
package com.malaka.helper;
import java.util.ArrayList;
import java.util.List;
import android.content.Context;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.view.Display;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.malaka.R;
import com.malaka.utils.PreferenceUtils;
public class CategoryAdapter extends ArrayAdapter<String> {
ArrayList<String> table, custName, isInquired, isManager, sectionId,
parentId, parentname;
ArrayList<Integer> tableColors;
FragmentActivity context;
ArrayList<Boolean> status;
View view;
PreferenceUtils pref;
int posision;
final static String TAG = "CategoryAdapter";
public CategoryAdapter(FragmentActivity context, int textViewResourceId,
List<String> objects, List<Integer> colors,
List<String> isInquired, List<String> custName,
List<String> sectionId, List<String> parentId,
List<String> parentname, List<String> ismanager) {
super(context, textViewResourceId, objects);
// TODO Auto-generated constructor stub
table = (ArrayList<String>) objects;
this.parentId = (ArrayList<String>) parentId;
this.parentname = (ArrayList<String>) parentname;
pref = new PreferenceUtils(context);
this.custName = (ArrayList<String>) custName;
tableColors = (ArrayList<Integer>) colors;
this.isManager = (ArrayList<String>) ismanager;
this.isInquired = (ArrayList<String>) isInquired;
this.sectionId = (ArrayList<String>) sectionId;
status = new ArrayList<Boolean>();
Log.i(TAG, "\nisInquired == " + isInquired);
this.context = context;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
view = convertView;
ViewHolder holder = new ViewHolder();
if (convertView == null) {
Display display = context.getWindowManager().getDefaultDisplay();
int height = display.getHeight() / 8;
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.table_screen_row, null);
holder.textView = (TextView) convertView
.findViewById(R.id.txt_category_seat);
holder.txtName = (TextView) convertView
.findViewById(R.id.txt_customer_name);
holder.imageViewManager = (ImageView) convertView
.findViewById(R.id.imageView_table_manager);
holder.textViewValet = (TextView) convertView
.findViewById(R.id.text_table_valley);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT, height);
holder.rl = (RelativeLayout) convertView
.findViewById(R.id.category_seat);
holder.rl.setLayoutParams(params);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
// if(isVale.get(position).equals("0")){
// holder.textViewValet.setText("");
// }else{
// if(parentId.get(position).equals("0")){
// holder.textViewValet.setText(isVale.get(position));
// }
// }
Log.d(TAG, "custName == " + custName.get(position) + "\nlength == "
+ custName.get(position).length());
if (custName.get(position).length() > 9) {
if (parentId.get(position).equals("0")) {
holder.txtName.setText(custName.get(position).substring(0, 8)
+ "...");
holder.textView.setText(table.get(position));
} else {
// we have to use parent table Name when Parent id is not 0
holder.txtName.setText(parentname.get(position));
holder.textView.setText("");
}
} else {
if (parentId.get(position).equals("0")) {
holder.txtName.setText(custName.get(position));
holder.textView.setText(table.get(position));
} else {
holder.txtName.setText(parentname.get(position));
holder.textView.setText("");
}
}
if (isManager.get(position).equals("true")) {
holder.imageViewManager
.setBackgroundResource(R.drawable.manager_icon);
} else {
holder.imageViewManager.setBackgroundResource(0);
}
holder.rl.setBackgroundColor(tableColors.get(position));
return convertView;
}
private class ViewHolder {
TextView textView, txtName;
ImageView imageViewManager;
TextView textViewValet;
RelativeLayout rl;
}
}
At last I got the solution.
I have done like below...
I was maintaining a FLAG called getTableStatus to get the tables of particular section. If the value of getTableStatus is FALSE than only TableStatusAsync is called. At first selection of section, tables are coming from web service and those tables are being inserted in DB.
On second time, selecting of SECTION, tables are coming from DB not from web service. And tables are coming from DB are of previously selected SECTION. So, there is nothing to do with notifyDataSetChanged().
I have just change the FLAG value to FALSE by calling pref.setTableStatus(false); on selection of SECTION. Now, TableStatusAsync is called every time when you change your selection of SECTION.
Modified Code...
TableScreenSectionwiseActivity.java
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
pref.setSectionId(view.getTag().toString());
pref.setTableStatus(false);
pref.setTableServiceStatus(false);
Fragment fragment = new TableScreenActivity();
ReplaceFragment.getReplaceFragment(getActivity(), fragment, "");
}
I am using list view with each and every row has its own timer.I want to delete the position of a list view when timer is completed its time interval.I had implemented as below but position is always catching wrongly and last item is deleting every time.Please see my code below,inside onfinish() of timer i am trying to remove the position but it is not getting deleted properly, help me.
ProductListAdapter.java
package com.devpoint.adapter;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import org.w3c.dom.Document;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.CountDownTimer;
import android.os.Handler;
import android.text.Html;
import android.text.format.DateUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.Animation.AnimationListener;
import android.view.animation.AnimationUtils;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.RatingBar;
import android.widget.TableLayout;
import android.widget.TextView;
import com.devpoint.PlacesandMaps.GMapV2Direction;
import com.devpoint.PlacesandMaps.PlacesMapActivity;
import com.devpoint.common.GetAllGooglePlaces;
import com.devpoint.model.ListDetails;
import com.devpoint.rprtgnet.LoadActivity;
import com.devpoint.rprtgnet.MapFragmentActivity;
import com.devpoint.rprtgnet.R;
import com.devpoint.sharedpreferences.SharedPreference;
import com.devpoint.tabsswipe.ListOnGoing;
import com.devpoint.tabsswipe.SwipeViewPagerAdapter;
import com.devpoint.user.PostLogcatErrors;
import com.devpoint.volley.AppController;
import com.google.android.gms.maps.GoogleMap;
import com.squareup.picasso.Picasso;
import android.view.animation.Transformation;
#SuppressLint({ "InflateParams", "ShowToast" })
public class ProductListAdapter extends ArrayAdapter<ListDetails> {
private Activity context;
List<ListDetails> products;
SharedPreference sharedPreference;
public static com.android.volley.toolbox.ImageLoader imageLoader;
LayoutInflater inflater;
//ViewHolder holder;
protected String Day = "";
public static View alertLayout;
private static GMapV2Direction gmapdirection;
public static GoogleMap gmap;
protected Document doc;
static final int ANIMATION_DURATION = 200;
//TextView timer;
//String Pagename;
private HashMap<TextView,CountDownTimer> counters;
static class TestViewHolder
{
public TextView tvCounter;
}
public ProductListAdapter(Context context, List<ListDetails> products) {
super(context, R.layout.adapter_offer_list_item, products);
this.context = (Activity) context;
this.products = products;
sharedPreference = new SharedPreference();
imageLoader = AppController.getInstance().getImageLoader();
this.counters = new HashMap<TextView, CountDownTimer>();
inflater = (LayoutInflater) context
.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
}
private class ViewHolder {
TextView productNameTxt;
//TextView Ratingsno;
TextView productPriceTxt;
//TextView timedist;
TableLayout distancesection;
TextView categoryname;
ImageView favoriteImg;
RatingBar rb;
ImageView OfferImage;
//ImageView MapImage;
ImageView listimage;
public TextView distance;
public ImageView indicator;
TextView timer;
TextView move;
//TextView Postedon;
}
#Override
public int getCount() {
return products.size();
}
#Override
public ListDetails getItem(int position) {
return products.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int po, View convertView, final ViewGroup parent) {
try {
ViewHolder holder = null;
Day = "";
final ListDetails product = products.get(po);
//final int abc = po;
/*LayoutInflater li = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);*/
if (convertView == null) {
holder = new ViewHolder();
convertView = inflater.inflate(R.layout.offerlist_new, parent,
false);
final View v= convertView;
// convertView.requestLayout();
holder.productNameTxt = (TextView) convertView
.findViewById(R.id.name);
holder.productPriceTxt = (TextView) convertView
.findViewById(R.id.listview_description);
holder.distance = (TextView) convertView
.findViewById(R.id.listview_distane);
/*holder.timedist = (TextView) convertView
.findViewById(R.id.timedist);*/
/*holder.Ratingsno = (TextView) convertView
.findViewById(R.id.Ratingsno);*/
/*holder.Postedon = (TextView) convertView
.findViewById(R.id.Postedon);*/
holder.favoriteImg = (ImageView) convertView
.findViewById(R.id.fav_checkbox);
holder.rb = (RatingBar) convertView
.findViewById(R.id.ratingbar);
holder.timer = (TextView) convertView.findViewById(R.id.time);
holder.categoryname = (TextView) convertView
.findViewById(R.id.Categoryname);
holder.listimage = (ImageView) convertView
.findViewById(R.id.list_image);
/*holder.distancesection = (TableLayout) convertView
.findViewById(R.id.distancesection);*/
/*holder.MapImage = (ImageView) convertView
.findViewById(R.id.imgmap);*/
holder.move = (TextView) convertView
.findViewById(R.id.listview_description3);
holder.move.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
try {
removeListItem(v,po) ;
} catch (Exception e) {
e.printStackTrace();
PostLogcatErrors ple = new PostLogcatErrors();
ple.PostLogcatErorrs(e);
}
}
});
String text = "<font color=#222222>" + product.getShopName()
+ "</font>"
+ "<small><font color=#0091EA> ( </font></small>"
+ " <small><font color=#0091EA>" + product.getAreaName()
+ "</font></small>"
+ "<small><font color=#0091EA> ) </font></small>";
holder.productNameTxt.setText(Html.fromHtml(text));
// holder.productNameTxt.setText(product.getShopName() + " " + "( "
// + Html.fromHtml("<font color='#0091EA'>" + product.getAreaName()
// + "</font>") + " )");
holder.productPriceTxt.setText(product.getDeal() + "");
holder.rb.setRating(Float.valueOf(product.getRatingAvg()));
//holder.Ratingsno.setText(product.getTotalRatings() + " Ratings");
//holder.timedist.setText(product.getTime());
holder.distance.setText(String.valueOf(product.getDistance())
+ " Km");
holder.categoryname.setText(product.getCategoryName());
//holder.listimage.setImageUrl(product.getListImage(), imageLoader);
Picasso.with(context).load(product.getListImage()).into(holder.listimage);
if (checkFavoriteItem(product)) {
holder.favoriteImg.setImageResource(R.drawable.checked);
holder.favoriteImg.setTag(context
.getString(R.string.red_favcolor));
} else {
holder.favoriteImg.setImageResource(R.drawable.unchecked);
holder.favoriteImg.setTag(context
.getString(R.string.grey_favcolor));
}
/*holder.Postedon.setText("Posted On" + " "
+ product.getPostedDate());*/
final TextView tv = holder.timer;
CountDownTimer cdt = counters.get(tv);
if(cdt!=null)
{
cdt.cancel();
cdt=null;
}
cdt = new CountDownTimer(Long.parseLong(product.getOfferEndTime()), 1000)
{
#Override
public void onTick(long millisUntilFinished)
{
int minutes = 0;
int seconds = 0;
String sDate = "";
if(millisUntilFinished > DateUtils.MINUTE_IN_MILLIS)
{
minutes = (int) (millisUntilFinished / DateUtils.MINUTE_IN_MILLIS);
}
millisUntilFinished -= (minutes*DateUtils.MINUTE_IN_MILLIS);
if(millisUntilFinished > DateUtils.SECOND_IN_MILLIS)
{
seconds = (int) (millisUntilFinished / DateUtils.SECOND_IN_MILLIS);
}
sDate += " "+"00"+":"+String.format("%02d",minutes)+":"+String.format("%02d",seconds);
tv.setText(sDate.trim());
}
#Override
public void onFinish() {
tv.setText("Finished");
final int abc = po;
final Animation animation = AnimationUtils.loadAnimation(
context, android.R.anim.slide_in_left);
v.startAnimation(animation);
Handler handle = new Handler();
handle.postDelayed(new Runnable() {
public void run() {
products.remove(abc);
ListOnGoing.productListAdapter = new ProductListAdapter(
LoadActivity.activity, products);
ListOnGoing.swipelisview
.setAdapter(ListOnGoing.productListAdapter);
ListOnGoing.productListAdapter.notifyDataSetChanged();
}
}, 1000);
}
};
counters.put(tv, cdt);
cdt.start();
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
return convertView;
} catch (Exception e) {
e.printStackTrace();
PostLogcatErrors ple = new PostLogcatErrors();
ple.PostLogcatErorrs(e);
}
return convertView;
}
/* Checks whether a particular product exists in SharedPreferences */
public boolean checkFavoriteItem(ListDetails checkProduct) {
boolean check = false;
List<ListDetails> favorites = sharedPreference.getFavorites(context);
if (favorites != null) {
for (ListDetails product : favorites) {
/*
* if (product.equals(checkProduct)) { check = true; break; }
*/
if (product.getOfferID().equals(checkProduct.getOfferID())) {
check = true;
break;
}
}
}
return check;
}
public void cancelAllTimers()
{
Set<Entry<TextView, CountDownTimer>> s = counters.entrySet();
Iterator it = s.iterator();
while(it.hasNext())
{
try
{
Map.Entry pairs = (Map.Entry)it.next();
CountDownTimer cdt = (CountDownTimer)pairs.getValue();
cdt.cancel();
cdt = null;
}
catch(Exception e){}
}
it=null;
s=null;
counters.clear();
}
}
If abc is declared as a field of your class (e. g. private int abc), you are assigning po to abc each time getView gets called. Later, when you call
products.remove(abc);
You are removing an element with index of the last assigned value of abc, which most probably is index of the last element.
Replace the above line with
products.remove(po);
or change
abc = po;
to
final int abc = po;
Also try doing a similar thing with the following line:
holder = null;
I have created a custom Adapter for list which different items and each item has a button to invite. The item should flip horizontally when the respective invite button is clicked and that is working fine. The problem is that when I click invite button of first item then invite button of 4th item is also clicked. I am attaching the code hee
package rovoltlabs.coffeechat.adapters;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import rovoltlabs.coffeechat.R;
import rovoltlabs.coffeechat.animation.AnimationFactory;
import rovoltlabs.coffeechat.animation.AnimationFactory.FlipDirection;
import rovoltlabs.coffeechat.volley.utils.Const;
import rovoltslabs.coffeechat.app.AppController;
import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ViewAnimator;
import com.android.volley.Request.Method;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.VolleyLog;
import com.android.volley.toolbox.StringRequest;
public class MyCustomAdapter extends BaseAdapter implements OnClickListener {
Context contexts;
List<String> name = new ArrayList<String>();
List<String> ids = new ArrayList<String>();
List<String> slots = new ArrayList<String>();
List<String> heading = new ArrayList<String>();
List<String> showtime = new ArrayList<String>();
List<Bitmap> img = new ArrayList<Bitmap>();
List<ViewHolder> myview = new ArrayList<ViewHolder>();
private String tag_json_obj = "jobj_req";
private LayoutInflater mLayoutInflater;
View row;
ViewHolder holder;
public MyCustomAdapter(Context context, List<String> name,
List<Bitmap> img, List<String> heading, List<String> slots,
List<String> id) {
super();
this.contexts = context;
this.name = name;
this.img = img;
this.heading = heading;
this.slots = slots;
this.ids = id;
mLayoutInflater = ((Activity) contexts).getLayoutInflater();
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return name.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return null;
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
#Override
public View getView(int position, View view, ViewGroup parent) {
// TODO Auto-generated method stub
// check to see if the reused view is null or not, if is not null then
// reuse it
if (view == null) {
holder = new ViewHolder();
view = mLayoutInflater.inflate(R.layout.item, null);
holder.name = (TextView) view.findViewById(R.id.Name);
holder.fname = (TextView) view.findViewById(R.id.flipName);
holder.msg = (EditText) view.findViewById(R.id.fsend);
holder.heading = (TextView) view.findViewById(R.id.ddheading);
holder.distance = (TextView) view.findViewById(R.id.Distance);
holder.image = (ImageView) view.findViewById(R.id.imagecoffee);
holder.invite = (Button) view.findViewById(R.id.inviteButton);
holder.send = (Button) view.findViewById(R.id.fsendButton);
holder.time = (TextView) view.findViewById(R.id.timefree);
holder.viewAnimator = (ViewAnimator) view
.findViewById(R.id.viewFlipper);
myview.add(holder);
holder.v = view;
} else {
holder = (ViewHolder) view.getTag();
}
view.setTag(holder);
holder.invite.setOnClickListener(this);
holder.send.setOnClickListener(this);
holder.name.setText(name.get(position).split("\n")[0]);
holder.fname.setText(name.get(position).split("\n")[0]);
holder.heading.setText(heading.get(position));
String temp = "";
int sl = Integer.parseInt(slots.get(position));
if (sl % 2 == 0) {
temp = "" + ((sl / 2) - 1) + ":30 - " + ((sl / 2)) + ":00";
} else {
temp = "" + ((sl / 2)) + ":00-" + ((sl / 2)) + ":30";
}
holder.time.setText(temp);
holder.distance.setText(name.get(position).split("\n")[1] + " m");
holder.image.setImageBitmap(img.get(position));
holder.invite.setTag(position);
holder.send.setTag(position);
return view;
}
private static class ViewHolder {
protected TextView name;
protected TextView heading;
protected TextView distance, time;
protected ImageView image;
protected Button invite, send;
protected View v;
protected ViewAnimator viewAnimator;
protected TextView fname;
protected EditText msg;
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (v.getId() == R.id.inviteButton) {
AnimationFactory.flipTransition(
myview.get((Integer) v.getTag()).viewAnimator,
FlipDirection.LEFT_RIGHT);
} else if (v.getId() == R.id.fsend) {
SharedPreferences pref = contexts.getApplicationContext()
.getSharedPreferences("MyPref", 0);
String slotsss = "{\"slots\":[" + slots.get((Integer) v.getTag())
+ "]}";
final Map<String, String> params = new HashMap<String, String>();
params.put("slot", slotsss);
Log.e("invite slots", slotsss);
params.put("to", ids.get((Integer) v.getTag()));
params.put("from", pref.getString("id", "N/A"));
params.put("message", myview.get((Integer) v.getTag()).msg
.getText().toString());
StringRequest jsonObjReq = new StringRequest(Method.POST,
Const.URL_INVITE, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d("Slots Response: ", response.toString());
Toast.makeText(contexts, "invited" + response,
Toast.LENGTH_SHORT).show();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d("invite Error:",
"Error: " + error.getMessage());
}
}) {
/**
* Passing some request headers
* */
#Override
protected Map<String, String> getParams() {
return params;
}
};
// Adding request to request queue
AppController.getInstance().addToRequestQueue(jsonObjReq,
tag_json_obj);
}
}
}
The View objects are recycling and you're using the same ViewHolder object (and other UI components) for both positions. The view being clicked has had its tag updated to the position desired, but the animation object is the same as another position due to the recycling.
I have a list view inside a fragment like this:
The contacts section shows the user contacts and the groups section shows user groups. both of them are using fragments. I have been able to implement the custom listview for them. Code for contactadaptor used to populate the listview in contact section is given below:
package com.project.iandwe.Adaptor;
import android.content.Context;
import android.content.res.Resources;
import android.database.Cursor;
import android.net.Uri;
import android.util.Log;
import android.util.SparseBooleanArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.*;
import com.project.iandwe.Data.ContactData;
import com.project.iandwe.R;
import java.util.ArrayList;
/**
* Created by NathanDrake on 6/4/2014.
*/
public class ContactSelectAdaptor extends BaseAdapter implements CompoundButton.OnCheckedChangeListener {
ArrayList<ContactData> listViewRows;
Context context;
public SparseBooleanArray checkboxState;
public ContactSelectAdaptor(Context context){
//Resources resources = context.getResources();
this.context =context;
UserDatabaseAdapter userDatabaseAdapter = new UserDatabaseAdapter(context);
Cursor cursor = userDatabaseAdapter.getUserContacts();
listViewRows = new ArrayList<ContactData>();
checkboxState = new SparseBooleanArray();
while (cursor.moveToNext()){
// ContactData listViewRow = new ListViewRow();
String contact_id = cursor.getString(0);
String first_name = cursor.getString(1);
String last_name = cursor.getString(2);
String email = cursor.getString(3);
String icon = cursor.getString(4);
// Log.d("ContactSelectAdaptor"," " + contact_id + " " + first_name + " " + last_name+ " " + email);
if (last_name == null){
last_name = " ";
}
listViewRows.add(new ContactData(contact_id,first_name,last_name,email,icon));
}
cursor.close();
}
#Override
public int getCount() {
return listViewRows.size();
}
#Override
public Object getItem(int position) {
return listViewRows.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
ViewClass viewClass = null;
if (row==null) {
LayoutInflater layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = layoutInflater.inflate(R.layout.listview_contact_select, parent, false);
viewClass = new ViewClass(row);
row.setTag(viewClass);
}
else {
viewClass = (ViewClass) row.getTag();
}
/* ImageView imageView = (ImageView) view.findViewById(R.id.imageViewProfile);
TextView textViewName = (TextView) view.findViewById(R.id.textViewDisplayName);
TextView textViewEmail = (TextView) view.findViewById(R.id.textViewEmailAddress);
CheckBox checkBox = (CheckBox) view.findViewById(R.id.checkBoxSelected);
*/
ContactData contactData = listViewRows.get(position);
Uri uri = contactData.getIcon();
if (uri!=null){ viewClass.imageView.setImageURI(uri); }
else { viewClass.imageView.setImageResource(R.drawable.ic_contacts); }
viewClass.textViewName.setText(contactData.getFirst_name());
viewClass.textViewEmail.setText(contactData.getEmail());
viewClass.checkBox.setTag(position);
viewClass.checkBox.setChecked(checkboxState.get(position,false));
viewClass.checkBox.setOnCheckedChangeListener(this);
return row;
}
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
checkboxState.put((Integer) buttonView.getTag(), isChecked);
}
class ViewClass {
ImageView imageView;
TextView textViewName;
TextView textViewEmail;
CheckBox checkBox;
ViewClass (View view){
imageView = (ImageView) view.findViewById(R.id.imageViewProfile);
textViewName = (TextView) view.findViewById(R.id.textViewDisplayName);
textViewEmail = (TextView) view.findViewById(R.id.textViewEmailAddress);
checkBox = (CheckBox) view.findViewById(R.id.checkBoxSelected);
}
}
}
This is how i try to pick up the contacts that have been selected by the user:
package com.project.iandwe.Menu;
import android.database.Cursor;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import android.widget.TextView;
import com.project.iandwe.Adaptor.ContactSelectAdaptor;
import com.project.iandwe.Adaptor.UserDatabaseAdapter;
import com.project.iandwe.R;
import java.util.ArrayList;
/**
* Created by NathanDrake on 5/4/2014.
*/
public class ContactsFragments extends Fragment {
TextView textView;
ListView listView;
String eventId;
public ContactsFragments(){}
public ContactsFragments (String eventID){
this.eventId=eventID;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_contact,container, false );
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
UserDatabaseAdapter userDatabaseAdapter = new UserDatabaseAdapter(getActivity());
//textView = (TextView) getActivity().findViewById(R.id.textViewSample);
// textView.setText(userDatabaseAdapter.getUserContacts());
listView = (ListView) getActivity().findViewById(R.id.listViewContacts);
ContactSelectAdaptor contactSelectAdaptor = new ContactSelectAdaptor(getActivity());
listView.setAdapter(contactSelectAdaptor);
listView.setVisibility(View.VISIBLE);
/* Checking who all customers have been invited to the events
* http://stackoverflow.com/questions/18162931/get-selected-item-using-checkbox-in-listview */
Cursor cursor = userDatabaseAdapter.getUserContacts();
cursor.moveToFirst();
for (int i=0; i<contactSelectAdaptor.checkboxState.size();i++){
if (contactSelectAdaptor.checkboxState.get(i)==true){
String contact_id = cursor.getString(0);
String first_name = cursor.getString(1);
String last_name = cursor.getString(2);
String email = cursor.getString(3);
//String icon = cursor.getString(4);
long id = userDatabaseAdapter.insertUserInvite(eventId,contact_id,email,first_name,last_name,0,0,0,0);
if (id<0){
Log.e("UserEventContactInsert","Failure");
}
}
cursor.moveToNext();
}
cursor.close();
}
}
AS i am new to android, i am not sure if the above code to check for user selection of checkboxes should be done in which section of the fragment? I would actually like to populate this data if the user has selected the Done menu presented on the top right corner but then i am finding it difficult to spend the sparse boolean array from fragment to activity. Is there a way this can be accomplished?
Adding code for the main activity which has the "Done" menu button:
package com.project.iandwe;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.view.ViewPager;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.Toast;
import com.project.iandwe.Adaptor.FragmentContactAdaptor;
import com.project.iandwe.Adaptor.UserDatabaseAdapter;
/**
* Created by NathanDrake on 5/21/2014.
*/
public class AddContacts extends FragmentActivity {
ViewPager viewPager = null;
String name;
String eventId,description,date, time, location;
protected void onCreate( Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.add_contacts);
viewPager = (ViewPager) findViewById(R.id.pager_contacts);
FragmentManager fragmentManager = getSupportFragmentManager();
viewPager.setAdapter(new FragmentContactAdaptor(fragmentManager));
//viewPager.setCurrentItem(1);
Intent intent = getIntent();
eventId = intent.getExtras().getString("eventId");
name = intent.getExtras().getString("name");
description = intent.getExtras().getString("description");
date = intent.getExtras().getString("date");
time = intent.getExtras().getString("time");
location = intent.getExtras().getString("location");
}
public boolean onCreateOptionsMenu(Menu menu){
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.add_event_finish,menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_finish:
//UserDatabaseAdapter userDatabaseAdapter = new UserDatabaseAdapter(this);
//long id = userDatabaseAdapter.insertUserEvent(name,description,date,time,location);
//if (id>0 ) {
Toast.makeText(this,"Event successfully Created",Toast.LENGTH_LONG).show();
Intent intent = new Intent(this, HomePage.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
finish();
// }
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}
In the menu done handler try to get your adapter in this way:
ContactsFragments fragment = (ContactsFragments) getSupportFragmentManager()
.findFragmentByTag("ContactsFragments");
ListView listView = fragment.listView;
ContactSelectAdaptor adapter = (ContactSelectAdaptor)listView.getAdaptor();
If you have the adaptor then your sparseb boolean array is visible.