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, "");
}
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 don't understand why my recyclerview is only showing the last row of my database although I initialised it with 150 datas.
I searched a lot in the internet and even here on SO, but not one of the solutions is working. Can you help me to figure out why my recyclerView is only showing the last row of the database? Thanks in advance to all of you.
May be you can help me. Here is my code:
package com.example.frontaddress.matedesignc;
import android.database.Cursor;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.Toast;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class Customer_Activity extends AppCompatActivity {
private List<String> StateListArray =new ArrayList<String>();
private List<String> StateList =new ArrayList<String>();
private List<String> CityListArray ;
private List<String> CityList ;
private Spinner dropdown_state;
private Spinner dropdown_city;
private DBHandler DB = new DBHandler(this);
private static final String BUSINESSNAME = "bussiness_name";
private static final String MOBILE = "mobile";
private static final String ADDRESS = "address";
private static final String ID = "id";
private Toolbar toolbar;
private Customer_list_Adapter adapter;
private RecyclerView recyclerView_Customer;
//ProgressDialog pDialog = new ProgressDialog(this);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_customer_list);
toolbar = (Toolbar) findViewById(R.id.app_bar);
setSupportActionBar(toolbar);
getSupportActionBar().setHomeButtonEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
GetStateList(); }
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_sub, menu);
return true; }
public void CustomerDetails(String state,String city) throws IOException {
try {
List<customer_search_information> data = null;
data = new ArrayList<>();
customer_search_information current = new customer_search_information();
Cursor RST_CSTInfo = DB.getRows("customer", "id,bussiness_name,mobile,address", " state='" + state + "' AND city='" + city + "'");
while (!RST_CSTInfo.isAfterLast()) {
current.bussiness_name = RST_CSTInfo.getString(RST_CSTInfo.getColumnIndex(BUSINESSNAME));
current.state = state;
current.city = city;
current.address = RST_CSTInfo.getString(RST_CSTInfo.getColumnIndex(ADDRESS));
String Mob = RST_CSTInfo.getString(RST_CSTInfo.getColumnIndex(MOBILE));
current.mobile_no = Mob;
current.e_mail = "mail.isigntech#gmail.com";
current.id = RST_CSTInfo.getString(RST_CSTInfo.getColumnIndex(ID));
// displayExceptionMessage(current.id+current.bussiness_name+current.state+current.city+current.address+current.mobile+current.email);
data.add(current);
RST_CSTInfo.moveToNext();
}
recyclerView_Customer = (RecyclerView) findViewById(R.id.drawerListCustomer);
recyclerView_Customer.setHasFixedSize(true);
recyclerView_Customer.setHasFixedSize(true);
recyclerView_Customer.setLayoutManager(new LinearLayoutManager(this));
adapter = new Customer_list_Adapter(this, data);
recyclerView_Customer.setAdapter(adapter);
}catch (Exception e){ displayExceptionMessage(e.toString());}
}
private void GetStateList()
{ Cursor Customer= DB.getRows("customer","state", " 1 GROUP BY state");
while(!Customer.isAfterLast()){
String state=Customer.getString(Customer.getColumnIndex("state"));
StateList.add(state);
StateListArray.add(state);
Customer.moveToNext();
}
dropdown_state = (Spinner)findViewById(R.id.SpnSrch_State);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(Customer_Activity.this, android.R.layout.simple_spinner_dropdown_item, StateListArray);
dropdown_state.setAdapter(adapter);
dropdown_state.setPrompt("Choose State ");
dropdown_state.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) {
int item = dropdown_state.getSelectedItemPosition();
String state =StateListArray.get(item);
dropdown_city=(Spinner) findViewById(R.id.SpnSrch_State);
Cursor RstCity= DB.getRows("customer","city", "state='"+state+"' GROUP BY city");
CityListArray =new ArrayList<String>();
CityList =new ArrayList<String>();
while(!RstCity.isAfterLast()){
String city=RstCity.getString(RstCity.getColumnIndex("city"));
CityList.add(city);
CityListArray.add(city);
RstCity.moveToNext();
}
dropdown_city = (Spinner)findViewById(R.id.SpnSrch_City);
ArrayAdapter<String> cityadapter = new ArrayAdapter<String>(Customer_Activity.this, android.R.layout.simple_spinner_dropdown_item, CityListArray);
dropdown_city.setAdapter(cityadapter);
dropdown_city.setPrompt("Choose City ");
dropdown_city.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) {
int item = dropdown_state.getSelectedItemPosition();
String state =StateListArray.get(item);
item = dropdown_city.getSelectedItemPosition();
String city =CityListArray.get(item);
try {
CustomerDetails(state,city);
} catch (Exception e) {
displayExceptionMessage(e.toString());
e.printStackTrace();
}
}
#Override
public void onNothingSelected(AdapterView<?> parentView) {
displayExceptionMessage("Please Select State.");
}
});
}
#Override
public void onNothingSelected(AdapterView<?> parentView) {
displayExceptionMessage("Please Select City.");
}
});
}
public void displayExceptionMessage(String msg) {
//TextView Txterror=(TextView) findViewById(R.id.txterror);
Toast.makeText(this, msg, Toast.LENGTH_LONG).show();
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
if (id == android.R.id.home) {
// NavUtils.navigateUpFromSameTask(this);
}
return super.onOptionsItementer code hereSelected(item);
}
}
Here is my custom list adapter code:
package com.example.frontaddress.matedesignc;
import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.net.Uri;
import android.support.v4.app.ActivityCompat;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import java.util.Collections;
import java.util.List;
/**
* Created by frontaddress on 10/08/17.
*/
public class Customer_list_Adapter extends RecyclerView.Adapter<Customer_list_Adapter.CustomerViewHolder> {
private LayoutInflater inflater;
private Context contexts;
List<customer_search_information> Cst_data = Collections.emptyList();
public Customer_list_Adapter(Context context, List<customer_search_information> data) {
inflater = LayoutInflater.from(context);
this.Cst_data = data;
// Toast.makeText(contexts, data.size(), Toast.LENGTH_LONG).show();
this.contexts = context;
}
#Override
public CustomerViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = inflater.inflate(R.layout.content_search_staff, parent, false);
CustomerViewHolder holder = new CustomerViewHolder(view);
return holder;
}
#Override
public void onBindViewHolder(CustomerViewHolder holder, int position) {
try {
customer_search_information current = Cst_data.get(position);
Integer Pos=position;
holder.TxtBisinessName.setText(current.bussiness_name);
holder.TxtAddress.setText(current.address);
holder.Statecity.setText(current.state + "-" + current.city);
holder.Txt_Mobile.setText(current.mobile_no.toString());
holder.TxtEmail.setText(current.e_mail);
}catch (Exception e)
{
Toast.makeText(contexts,e.toString(),Toast.LENGTH_SHORT).show();
e.printStackTrace();
}
}
#Override
public int getItemCount() {
return Cst_data.size();
}
class CustomerViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
TextView TxtBisinessName;
TextView TxtAddress;
TextView Txt_Mobile;
TextView Statecity;
TextView TxtEmail;
ImageView ImgPhoneCall,ImgMailTo;
public CustomerViewHolder(View itemView) {
super(itemView);
TxtBisinessName = (TextView) itemView.findViewById(R.id.Txtbusiness_name);
Txt_Mobile = (TextView) itemView.findViewById(R.id.TxtMobile);
Statecity = (TextView) itemView.findViewById(R.id.Txtstatecity);
TxtAddress = (TextView) itemView.findViewById(R.id.Txtaddress);
TxtEmail=(TextView) itemView.findViewById(R.id.TxtEmail);
ImgPhoneCall = (ImageView) itemView.findViewById(R.id.ImgCallPhone);
ImgMailTo= (ImageView) itemView.findViewById(R.id.Imgmail);
ImgPhoneCall.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
customer_search_information current = Cst_data.get(getPosition());
String MOBILE = current.mobile_no;
try {
if (ActivityCompat.checkSelfPermission(contexts,Manifest.permission.CALL_PHONE) == PackageManager.PERMISSION_GRANTED)
{
Toast.makeText(contexts, "Call Permission Not Granted ", Toast.LENGTH_LONG).show();
return;
}
Intent callIntent = new Intent(Intent.ACTION_DIAL);
callIntent.setData(Uri.parse("tel:+91" + MOBILE));
callIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
contexts.startActivity(callIntent);
}
catch (Exception e){
Toast.makeText(contexts,e.toString(),Toast.LENGTH_SHORT).show();
e.printStackTrace();
}
}
});
/* TxtProfile.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
customer_search_information current = data.get(getPosition());
String SID = current.id;
Intent intent = new Intent(contexts, StudentProfileActivity.class);
intent.putExtra("id", SID);
contexts.startActivity(intent);
}
});*/
ImgMailTo.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
try {
// TODO Auto-generated method stub
customer_search_information current = Cst_data.get(getPosition());
String EMAIL = current.e_mail;
String BName = current.bussiness_name;
Intent emailIntent = new Intent(Intent.ACTION_SEND);
emailIntent.putExtra(Intent.EXTRA_EMAIL, EMAIL);
emailIntent.putExtra(Intent.EXTRA_SUBJECT, "");
emailIntent.setType("text/plain");
emailIntent.putExtra(android.content.Intent.EXTRA_TEXT, "Hi,"+BName);
final PackageManager pm = contexts.getPackageManager();
final List<ResolveInfo> matches = pm.queryIntentActivities(emailIntent, 0);
ResolveInfo best = null;
for (final ResolveInfo info : matches)
if (info.activityInfo.packageName.endsWith(".gm") || info.activityInfo.name.toLowerCase().contains("gmail"))
best = info;
if (best != null)
emailIntent.setClassName(best.activityInfo.packageName, best.activityInfo.name);
contexts.startActivity(emailIntent);
}
catch (Exception e){ }
}
});
}
#Override
public void onClick(View v) {
int ID=v.getId();
customer_search_information current=Cst_data.get(getPosition());
String SID=current.id;
// Toast.makeText(contexts,"Item Clicked Profile: "+ v.getId(), Toast.LENGTH_SHORT).show();
// Intent intent = new Intent(contexts, StudentProfileActivity.class);
// intent.putExtra("id", SID);
// contexts.startActivity(intent);
}
}
}
I think the problem is here , instead of
while(!RST_CSTInfo.isAfterLast()){
...
..
RST_CSTInfo.moveToNext();
}
try this ....
do(RST_CSTInfo.movetofirst()){
// your logic
}while(cursor.movetonext())
I had created a custom list view. Please tell me how to delete a entry from listview. I don't know where to write a code for delete button in my code. Please help me. Thanks..
Here is ListAdapater.java class:
package com.example.login;
import java.util.ArrayList;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
public class ListAdapater extends ArrayAdapter<String> {
customButtonListener customListner;
public interface customButtonListener {
public void onButtonClickListner(int position, String value);
}
public void setCustomButtonListner(customButtonListener listener) {
this.customListner = listener;
}
private Context context;
private ArrayList<String> data = new ArrayList<String>();
public ListAdapater(Context context, ArrayList<String> dataItem) {
super(context, R.layout.my_custom_list_layout, dataItem);
this.data = dataItem;
this.context = context;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
ViewHolder viewHolder;
if (convertView == null) {
LayoutInflater inflater = LayoutInflater.from(context);
convertView = inflater.inflate(R.layout.my_custom_list_layout, null);
viewHolder = new ViewHolder();
viewHolder.text = (TextView) convertView.findViewById(R.id.TextView);
viewHolder.button = (Button) convertView.findViewById(R.id.delete);
convertView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
final String temp = getItem(position);
viewHolder.text.setText(temp);
viewHolder.button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (customListner != null) {
customListner.onButtonClickListner(position, temp);
}
}
});
return convertView;
}
public class ViewHolder {
TextView text;
Button button;
}
}
Hompage.java class:
package com.example.login;
import com.example.login.ListAdapater.customButtonListener;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import android.app.Activity;
import android.database.Cursor;
import android.database.DataSetObserver;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.Toast;
public class Hompage extends Activity implements customButtonListener {
ListView listView;
ListAdapater adapter;
ArrayList<String> dataItems = new ArrayList<String>();
SQLiteDatabase db;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.home);
db = openOrCreateDatabase("login", MODE_PRIVATE, null);
// My code
String query1 = "SELECT * FROM USERS;";
int c = 0;
try {
Cursor c1 = db.rawQuery(query1, null);
if (c1.moveToFirst()) {
String[] temp2 = new String[c1.getCount()];
do {
String tempo = "Name" + ": " + c1.getString(1) + " " + c1.getString(2) + " \n" + "Gender" + ": "
+ c1.getString(4) + "\n " + "Hobbies" + ": " + c1.getString(8) + " \n" + "User Type" + ": "
+ c1.getString(9);
temp2[c] = tempo;
c++;
// String[] dataArray = temp2;
// List<String> datatemp = Arrays.asList(dataArray);
// dataItems.addAll(datatemp);
} while (c1.moveToNext());
String[] dataArray = temp2;
List<String> datatemp = Arrays.asList(dataArray);
dataItems.addAll(datatemp);
listView = (ListView) findViewById(R.id.listView);
adapter = new ListAdapater(Hompage.this, dataItems);
adapter.setCustomButtonListner(Hompage.this);
listView.setAdapter(adapter);
}
} catch (Exception e) {
}
}
#Override
public void onButtonClickListner(int position, String value) {
//EDITED CODE...
// TODO Auto-generated method stub
String query = "SELECT USER_TYPE FROM USERS WHERE userName = '" + temp + "'";
Cursor c2 = db.rawQuery(query, null);
if (c2.moveToFirst()) {
if (c2.getString(0).equals("Admin")) {
dataItems.remove(position);
adapter.notifyDataSetChanged();
Toast.makeText(getApplicationContext(), "Deleted", Toast.LENGTH_LONG).show();
return;
}
else{
Toast.makeText(getApplicationContext(), "Only Admin can delete", Toast.LENGTH_LONG).show();
}
}
}
}
Try like this
#Override
public void onButtonClickListner(int position, String value) {
// TODO Auto-generated method stub
dataItems.remove(position);
adapter.notifyDataSetChanged();
// call this method
deleteRowFromTable(your_table_name, your_column_name, value)
}
public void deleteRowFromTable(String tableName, String columnName, String keyValue) {
String whereClause = columnName + "=?";
String[] whereArgs = new String[]{String.valueOf(keyValue)};
yourDatabase.delete(tableName, whereClause, whereArgs);
}
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 can't seem to figure out what is going wrong with this, the code is pretty clean/ simple, but for some reason when I pull to refresh, it just shows me the loading icon infinity. Not only that, but I don't even receive any errors. The library I used for pull to refresh is this one.
I've spent several hours trying to figure this out, but the fact that it's not even giving me errors is making it very hard for me to track down.
And yes, I am sure the rest request is working.
import java.util.ArrayList;
import java.util.HashMap;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.GridView;
import android.widget.TextView;
import android.widget.Toast;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshBase.Mode;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener2;
import com.handmark.pulltorefresh.library.PullToRefreshGridView;
import com.loopj.android.http.JsonHttpResponseHandler;
import com.loopj.android.http.RequestParams;
public final class PullToRefresh extends Activity {
static final int MENU_SET_MODE = 0;
static final String KEY_FEED = "feed"; // parent node
static final String KEY_UID_FK = "uid_fk";
static final String KEY_FIRST_NAME = "first_name";
static final String KEY_LAST_NAME = "last_name";
public static final String KEY_NAME = "name";
static final String KEY_MESSAGE = "message";
static final String KEY_CREATED = "created";
static final String KEY_THUMB_URL = "thumb_img";
static final String KEY_DATA = "data";
static final String KEY_HOMETOWN = "hometown";
static final String KEY_BIO = "bio";
private ArrayList<HashMap<String, String>> feedList = new ArrayList<HashMap<String, String>>();
private PullToRefreshGridView mPullRefreshGridView;
private GridView mGridView;
private GridAdapter adapter;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_ptr_grid);
mPullRefreshGridView = (PullToRefreshGridView) findViewById(R.id.pull_refresh_grid);
mGridView = mPullRefreshGridView.getRefreshableView();
// Set a listener to be invoked when the list should be refreshed.
mPullRefreshGridView
.setOnRefreshListener(new OnRefreshListener2<GridView>() {
#Override
public void onPullDownToRefresh(
PullToRefreshBase<GridView> refreshView) {
Toast.makeText(PullToRefresh.this, "Pull Down!",
Toast.LENGTH_SHORT).show();
try {
new RestClientUsage().getPublicTimeline();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
#Override
public void onPullUpToRefresh(
PullToRefreshBase<GridView> refreshView) {
Toast.makeText(PullToRefresh.this, "Pull Up!",
Toast.LENGTH_SHORT).show();
try {
new RestClientUsage().getPublicTimeline();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
ArrayList<HashMap<String, String>> feedList = new ArrayList<HashMap<String, String>>();
TextView tv = new TextView(this);
tv.setGravity(Gravity.CENTER);
tv.setText("Empty View, Pull Down/Up to Add Items");
mPullRefreshGridView.setEmptyView(tv);
adapter = new GridAdapter(PullToRefresh.this, feedList);
mGridView.setAdapter(adapter);
}
class RestClientUsage {
public void getPublicTimeline() throws JSONException {
RequestParams params = new RequestParams();
params.put("loggedin_uid", TabHostFragmentActivity.loggedin_uid);
RestClient.post("http://localhost/basic/rest/request/format/json",
params, new JsonHttpResponseHandler() {
private JSONArray feed;
#Override
public void onSuccess(JSONObject json) {
try {
Log.i("JSON->TRAILS RESPONSE", json.toString(3));
// Getting Feed Array
feed = json.getJSONArray(KEY_FEED);
/*
* Log & Debug Code String feed_log =
* feed.toString(3); int feed_length =
* feed.length(); String string_length =
* Integer.toString(feed_length);
* Log.i("JSON PROFILE FEED RESPONSE", feed_log
* ); Log.i("JSON PROFILE FEED LENGTH",
* string_length);
*/
// looping through Feed of Updates
for (int i = 0; i < feed.length(); i++) {
JSONObject c = feed.getJSONObject(i);
String jFeedObj = c.toString(3);
Log.i("JSON FEED OBJ", jFeedObj);
// Storing each json item in variable
String uid = c.getString(KEY_UID_FK);
String first_name = c
.getString(KEY_FIRST_NAME);
String last_name = c
.getString(KEY_LAST_NAME);
String name = first_name + ' ' + last_name;
String http = "http://10.0.2.2/CI_REST_LOGIN/UPLOADS/thumbs/";
String base_url = c
.getString(KEY_THUMB_URL);
String thumb_url = http + base_url;
String message = c.getString(KEY_MESSAGE);
String created = c.getString(KEY_CREATED);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key =>
// value
map.put(KEY_UID_FK, uid);
map.put(KEY_NAME, name);
map.put(KEY_MESSAGE, message);
map.put(KEY_CREATED, created);
map.put(KEY_THUMB_URL, thumb_url);
Log.i("Trails - line 130", "Success");
// adding HashList to ArrayList
feedList.add(map);
}
adapter.notifyDataSetChanged();
// Call onRefreshComplete when the list has been
// refreshed.
mPullRefreshGridView.onRefreshComplete();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
menu.add(
0,
MENU_SET_MODE,
0,
mPullRefreshGridView.getMode() == Mode.BOTH ? "Change to MODE_PULL_DOWN"
: "Change to MODE_PULL_BOTH");
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
MenuItem setModeItem = menu.findItem(MENU_SET_MODE);
setModeItem
.setTitle(mPullRefreshGridView.getMode() == Mode.BOTH ? "Change to MODE_PULL_FROM_START"
: "Change to MODE_PULL_BOTH");
return super.onPrepareOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case MENU_SET_MODE:
mPullRefreshGridView
.setMode(mPullRefreshGridView.getMode() == Mode.BOTH ? Mode.PULL_FROM_START
: Mode.BOTH);
break;
}
return super.onOptionsItemSelected(item);
}
}
And here is the code for my GridView adapter:
import java.util.ArrayList;
import java.util.HashMap;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
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.ImageView;
import android.widget.TextView;
import com.loopj.android.image.SmartImageView;
public class GridAdapter extends BaseAdapter {
private Activity activity;
private ArrayList<HashMap<String, String>> data;
private static LayoutInflater inflater = null;
public ImageLoader imageLoader;
public GridAdapter(Activity a, ArrayList<HashMap<String, String>> d) {
activity = a;
data = d;
inflater = (LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
imageLoader = new ImageLoader(activity.getApplicationContext());
}
public int getCount() {
return data.size();
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
View vi = convertView;
if (convertView == null)
vi = inflater.inflate(R.layout.mobile, null);
TextView name = (TextView) vi.findViewById(R.id.grid_item_label); // title
SmartImageView thumb_image = (SmartImageView) vi
.findViewById(R.id.grid_item_image);
HashMap<String, String> update = new HashMap<String, String>();
update = data.get(position);
// Setting all values in listview
name.setText(update.get("name"));
thumb_image.setImageUrl(update.get("thumb_img"));
name.setOnClickListener(new myOnClickListener(position));
thumb_image.setOnClickListener(new myOnClickListener(position));
return vi;
}
public class myOnClickListener implements OnClickListener {
private int position;
private String clicked_uid;
public myOnClickListener(int position) {
this.position = position;
}
#Override
public void onClick(View v) { // TODO Auto-generated method stub
HashMap<String, String> update = new HashMap<String, String>();
update = data.get(position);
Log.i("Update Position:", update.toString());
clicked_uid = update.get("uid");
Log.d("Clicked UID:", clicked_uid + "");
Intent i = new Intent(activity.getApplicationContext(),
TabHostFragmentActivity.class);
i.putExtra("profile_uid", clicked_uid);
activity.startActivity(i);
}
}
}
You should POST to 10.0.2.2 instead of localhost in the call to RestClient.post in RestClientUsage.
I am not familiar withJsonHttpResponseHandler, but I would image there's an onFailure method (or something similar) that you may want to override. If there is, you may way to call mPullRefreshGridView.onRefreshComplete() in it.