I looked through a lot of information, but have not found the right solution.
My code:
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.safety.Whitelist;
import org.jsoup.select.Elements;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Typeface;
import android.os.AsyncTask;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseExpandableListAdapter;
import android.widget.Button;
import android.widget.ExpandableListView;
import android.widget.TextView;
import android.widget.Toast;
public class ExpandableListAdapter extends BaseExpandableListAdapter {
MyPointsDB db;
ArrayList<String> arr_book_title = new ArrayList<String>();
ArrayList<String> arr_book_href = new ArrayList<String>();
String selGroupParam;
String selItemParam;
public static String PACKAGE_NAME;
File directory;
String directory_string;
private Context _context;
private List<String> _listDataHeader; // header titles
private List<String> _paramDataHeader;
// child data in format of header title, child title
private HashMap<String, List<String>> _listDataChild;
private List<String> _paramDataChild;
AlertDialog dialog;
public ExpandableListAdapter(Context context, List<String> listDataHeader, List<String> paramDataHeader, HashMap<String, List<String>> listChildData, List<String> paramChildData) {
this._context = context;
this._listDataHeader = listDataHeader;
this._paramDataHeader = paramDataHeader;
this._listDataChild = listChildData;
this._paramDataChild = paramChildData;
//PACKAGE_NAME = _context.getPackageName();
this.db = new MyPointsDB(_context);
}
#Override
public Object getChild(int groupPosition, int childPosititon) {
return this._listDataChild.get(this._listDataHeader.get(groupPosition)).get(childPosititon);
}
#Override
public long getChildId(int groupPosition, int childPosition) {
return childPosition;
}
public String getChildParam(int groupPosition, int childPosition) {
return _paramDataChild.get(childPosition).toString();
}
#Override
public View getChildView(int groupPosition, final int childPosition, boolean isLastChild, View convertView, ViewGroup parent) {
final String childText = (String) getChild(groupPosition, childPosition);
if (convertView == null) {
LayoutInflater infalInflater = (LayoutInflater) this._context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = infalInflater.inflate(R.layout.list_item, null);
}
TextView txtListChild = (TextView) convertView.findViewById(R.id.lblListItem);
txtListChild.setTag(_paramDataChild.get(childPosition).toString());
txtListChild.setText(childText);
Button btnItem = (Button) convertView.findViewById(R.id.iconShowParamItem);
btnItem.setTag(_paramDataChild.get(childPosition).toString());
btnItem.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
selItemParam = view.getTag().toString().trim();
final CharSequence[] items = {_context.getString(R.string.operation_del_book)};
AlertDialog.Builder builder = new AlertDialog.Builder(_context);
builder.setItems(items, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
String[] separated = selItemParam.split(";");
String url_base = separated[1];
// Delete book
if (items[item] == _context.getString(R.string.operation_del_book)) {
new AlertDialog.Builder(_context)
.setTitle(R.string.alert_del_book_caption)
.setMessage(R.string.alert_del_book_message)
.setPositiveButton(R.string.button_ok, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
String[] separated = selItemParam.split(";");
String _id = separated[0];
db.deleteBOOKid(_id);
//Toast.makeText(_context, selItemParam, Toast.LENGTH_LONG).show();
//refreshList();
//Toast.makeText(_context, _context.getString(R.string.operation_del_book), Toast.LENGTH_SHORT).show();
}
})
.setNegativeButton(R.string.button_cancel,
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
}
}).show();
}
}
});
AlertDialog alert = builder.create();
alert.show();
}
});
return convertView;
}
#Override
public int getChildrenCount(int groupPosition) {
return this._listDataChild.get(this._listDataHeader.get(groupPosition)).size();
}
#Override
public Object getGroup(int groupPosition) {
return this._listDataHeader.get(groupPosition);
}
#Override
public int getGroupCount() {
return this._listDataHeader.size();
}
#Override
public long getGroupId(int groupPosition) {
return groupPosition;
}
#Override
public View getGroupView(int groupPosition, boolean isExpanded, View convertView, ViewGroup parent) {
String headerTitle = (String) getGroup(groupPosition);
if (convertView == null) {
LayoutInflater infalInflater = (LayoutInflater) this._context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = infalInflater.inflate(R.layout.list_group, null);
}
TextView lblListHeader = (TextView) convertView.findViewById(R.id.lblListHeader);
lblListHeader.setTypeface(null, Typeface.BOLD);
lblListHeader.setText(headerTitle);
Button btnGroup = (Button) convertView.findViewById(R.id.iconShowParamGroup);
btnGroup.setTag(_paramDataHeader.get(groupPosition).toString());
btnGroup.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
//Toast.makeText(_context, "btnGroup", Toast.LENGTH_SHORT).show();
selGroupParam = view.getTag().toString().trim();
final CharSequence[] items = {_context.getString(R.string.operation_add_book), _context.getString(R.string.operation_del_autor)};
AlertDialog.Builder builder = new AlertDialog.Builder(_context);
builder.setItems(items, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
//Toast.makeText(_context, items[item], Toast.LENGTH_SHORT).show();
String[] separated = selGroupParam.split(";");
String url_base = separated[1];
// Add book
if (items[item] == _context.getString(R.string.operation_add_book)) {
new selectBookInAutor().execute(url_base);
}
// Delete book
if (items[item] == _context.getString(R.string.operation_del_autor)) {
new AlertDialog.Builder(_context)
.setTitle(R.string.alert_del_autor_caption)
.setMessage(R.string.alert_del_autor_message)
.setPositiveButton(R.string.button_ok, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
String[] separated = selGroupParam.split(";");
String _id = separated[0];
db.deleteAUTORid(_id);
notifyDataSetChanged();
}
})
.setNegativeButton(R.string.button_cancel,
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
}
}).show();
}
}
});
AlertDialog alert = builder.create();
alert.show();
}
});
return convertView;
}
#Override
public boolean hasStableIds() {
return false;
}
#Override
public boolean isChildSelectable(int groupPosition, int childPosition) {
return true;
}
private class selectBookInAutor extends AsyncTask<String, Void, String> {
ProgressDialog mProgressDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
arr_book_title.clear();
arr_book_href.clear();
mProgressDialog = new ProgressDialog(_context);
mProgressDialog.setMessage("Loading...");
mProgressDialog.setIndeterminate(false);
mProgressDialog.show();
}
#Override
protected String doInBackground(String... params) {
Document doc = null;
StringBuilder sb = new StringBuilder();
try {
doc = Jsoup.connect(params[0]).userAgent("Mozilla").get();
//Elements links = doc.select("dl>dl>dt>li>a");
Elements links = doc.select("li>a");
for (Element link : links) {
sb.append(link.text());
arr_book_title.add(link.text());
arr_book_href.add(Jsoup.clean(link.attr("abs:href"), Whitelist.basic()));
}
} catch (IOException e) {
e.printStackTrace();
}
return sb.toString();
}
#Override
protected void onPostExecute(String result) {
if(!result.equals("")){
//Toast.makeText(_context, result, Toast.LENGTH_LONG).show();
final CharSequence[] items = arr_book_title.toArray(new CharSequence[arr_book_title.size()]);
final ArrayList seletedItems = new ArrayList();
AlertDialog.Builder builder = new AlertDialog.Builder(_context);
builder.setTitle("Select The Difficulty Level");
builder.setMultiChoiceItems(items, null, new DialogInterface.OnMultiChoiceClickListener() {
#Override
public void onClick(DialogInterface dialog, int indexSelected, boolean isChecked) {
if (isChecked) {
seletedItems.add(indexSelected);
}else if(seletedItems.contains(indexSelected)){
seletedItems.remove(Integer.valueOf(indexSelected));
}
}
}).setPositiveButton(R.string.button_ok, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
//Toast.makeText(_context, seletedItems.toString(), Toast.LENGTH_SHORT).show();
for (Object s : seletedItems){
String[] separated = selGroupParam.split(";");
String _idautor = separated[0].toString();
long id_book = db.insertBOOK(_idautor, arr_book_href.get(Integer.valueOf(s.toString())).toString(), "", arr_book_title.get(Integer.valueOf(s.toString())).toString());
new saveBookInAutor().execute(arr_book_href.get(Integer.valueOf(s.toString())).toString(), _idautor, String.valueOf(id_book));
}
//refreshList();
}
}).setNegativeButton(R.string.button_cancel, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
}
}).create().show();
}else{
Toast.makeText(_context, "Error get book autor", Toast.LENGTH_SHORT).show();
}
mProgressDialog.dismiss();
}
}
private class saveBookInAutor extends AsyncTask<String, Void, String> {
ProgressDialog mProgressDialog2;
String _idautor = "", _idbook = "";
#Override
protected void onPreExecute() {
super.onPreExecute();
mProgressDialog2 = new ProgressDialog(_context);
mProgressDialog2.setMessage("Save page...");
mProgressDialog2.setIndeterminate(false);
mProgressDialog2.show();
}
#Override
protected String doInBackground(String... params) {
Document doc = null;
String _html = "";
_idautor = params[1];
_idbook = params[2];
try {
doc = Jsoup.connect(params[0]).userAgent("Mozilla").get();
_html = doc.select("dd").outerHtml();
} catch (IOException e) {
e.printStackTrace();
}
return Jsoup.clean(_html, Whitelist.basic());
}
#Override
protected void onPostExecute(String result) {
if(!result.equals("")){
Toast.makeText(_context, "Save file", Toast.LENGTH_SHORT).show();
String html = "<html lang='ru'><head><meta http-equiv='Content-Type' content='text/html; charset=UTF-8'/></head><body>"+result+"</body></html>";
//String html = result;
savePageToFile(_idautor + "_" + String.valueOf(_idbook), html);
}else{
Toast.makeText(_context, "Error save page", Toast.LENGTH_SHORT).show();
}
mProgressDialog2.dismiss();
}
}
public void refreshList() {
Intent intent = new Intent(_context, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
_context.startActivity(intent);
}
public void savePageToFile(String filename, String html) {
try {
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(_context.openFileOutput(filename, Context.MODE_PRIVATE));
outputStreamWriter.write(html);
outputStreamWriter.close();
}
catch (IOException e) {
//Log.e("Exception", "File write failed: " + e.toString());
}
}
public String readPageFile(String filename) {
String ret = "";
try {
InputStream inputStream = _context.openFileInput(filename);
if ( inputStream != null ) {
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String receiveString = "";
StringBuilder stringBuilder = new StringBuilder();
while ( (receiveString = bufferedReader.readLine()) != null ) {
stringBuilder.append(receiveString);
}
inputStream.close();
ret = stringBuilder.toString();
}
}
catch (FileNotFoundException e) {
//Log.e("login activity", "File not found: " + e.toString());
} catch (IOException e) {
//Log.e("login activity", "Can not read file: " + e.toString());
}
return ret;
}
}
Problem is Delete book. After removal of the book from the database I want to update the screen ExpandableListView. This error occurs when you call the notifyDataSetChanged(). The element does not disappears from the screen.
I found a crutch to solve the problem:
Intent intent = new Intent(_context, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
_context.startActivity(intent);
But this is not entirely correct.
I ask your help.
You delete the item from the database, but it is still present in the lists that you have. You have to update the _listDataHeader list after you delete the item, and then notifyDataSetChanged. Also you should remove the child which corresponds to this item. Since you have many lists, update them also when an item is deleted.
.setPositiveButton(R.string.button_ok, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
String[] separated = selItemParam.split(";");
String _id = separated[0];
db.deleteBOOKid(_id);
//update lists here, and remove the header, child items and anything related..
// _listDataHeader.remove(groupPosition) // groupPosition should be final
// etc. etc.
notifyDataSetChanged();
} })
To ensure that data is consistent, when you delete something.. delete other related items too.. for example:
if _paramDataChild and _paramDataHeader are related to the item being deleted, you may want to update them too.. so that they don't have values which relate to the deleted item. (this depends on your scenario, i am just giving an example)
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 new in android and badly need to do animation in ExpandableLIstView in onGroupExpand and onGroupCollapse.
Please help me.
Given below is my code -
My MainActivity is
package comsam.myexpandablelistviedjsonapp;
import android.app.ProgressDialog;
import android.net.ParseException;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.view.animation.PathInterpolatorCompat;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.animation.AccelerateInterpolator;
import android.view.animation.Animation;
import android.view.animation.Interpolator;
import android.view.animation.TranslateAnimation;
import android.widget.ExpandableListView;
import android.widget.ImageView;
import android.widget.Toast;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
private ExpandListAdapter ExpAdapter;
private ExpandableListView ExpandList;
private Interpolator easeInOutQuart = PathInterpolatorCompat.create(0.77f, 0f, 0.175f, 1f);
private int lastExpandedPosition = -1;
ArrayList<Parent> list = new ArrayList<Parent>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final ImageView animatedButton = (ImageView) findViewById(R.id.parent_img);
ExpandList = (ExpandableListView)findViewById(R.id.exp_list);
new JSONAsyncTask().execute("http://local.agdits.com.bd/hrdemo/expandable.php");
ExpAdapter = new ExpandListAdapter(MainActivity.this, list);
ExpandList.setAdapter(ExpAdapter);
//to show which list has been clicked for Expand
ExpandList.setOnGroupExpandListener(new ExpandableListView.OnGroupExpandListener() {
#Override
public void onGroupExpand(final int groupPosition) {
if (lastExpandedPosition != -1 && groupPosition != lastExpandedPosition) {
ExpandList.collapseGroup(lastExpandedPosition);
// setupLayoutAnimationClose(groupPosition);
// new AnimUtils().collapse(ExpandList);
}
lastExpandedPosition = groupPosition;
}
});
//to show which list has been clicked for Collapse
ExpandList.setOnGroupCollapseListener(new ExpandableListView.OnGroupCollapseListener() {
#Override
public void onGroupCollapse(int parentPosition) {
Toast.makeText(getBaseContext(), ExpAdapter.getGroupName(parentPosition) + " is collapse ", Toast.LENGTH_LONG).show();
}
});
//to show which Child has been clicked
ExpandList.setOnChildClickListener(new ExpandableListView.OnChildClickListener() {
#Override
public boolean onChildClick(ExpandableListView parent, View v, int parentPosition, int childPosition, long id) {
Toast.makeText(getBaseContext(), ExpAdapter.getChildName(parentPosition, childPosition) + " from category " + ExpAdapter.getGroupName(parentPosition) + " is selected", Toast.LENGTH_LONG).show();
return false;
}
});
}
private void expand1() {
System.out.println("I am here expand");
}
private void collapse() {
System.out.println("I am here collapse");
}
class JSONAsyncTask extends AsyncTask<String, Void, Boolean> {
ProgressDialog dialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
dialog = new ProgressDialog(MainActivity.this);
dialog.setMessage("Loading, please wait");
dialog.setTitle("Connecting server");
dialog.show();
dialog.setCancelable(false);
}
#Override
protected Boolean doInBackground(String... urls) {
try {
//------------------>>
HttpGet httppost = new HttpGet(urls[0]);
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response = httpclient.execute(httppost);
// StatusLine stat = response.getStatusLine();
int status = response.getStatusLine().getStatusCode();
if (status == 200) {
HttpEntity entity = response.getEntity();
String data = EntityUtils.toString(entity);
//System.out.println(data);
ArrayList<Child> ch_list;
JSONArray jsonArray1 = new JSONArray(data);
for (int i = 0; i < jsonArray1.length(); i++) {
JSONObject object = jsonArray1.getJSONObject(i);
// System.out.println(object.getString("_id"));
Parent parent = new Parent();
parent.setParentName(object.getString("CategoryName"));
parent.setParentImage(object.getString("CatImage"));
//System.out.println(object.getString("CategoryName"));
//Make Child List Array
ch_list = new ArrayList<Child>();
JSONArray childArray = object.getJSONArray("child");
//System.out.println(childArray.length());
for (int j = 0; j < childArray.length(); j++) {
JSONObject childobject = childArray.getJSONObject(j);
Child child = new Child();
child.setName(childobject.getString("name"));
child.setImage(childobject.getString("image"));
ch_list.add(child);
}
// System.out.println(childArray);
//Child List to Parent Items
parent.setItems(ch_list);
list.add(parent);
}
return true;
}
//------------------>>
} catch (ParseException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return false;
}
protected void onPostExecute(Boolean result) {
dialog.cancel();
ExpAdapter.notifyDataSetChanged();
if(result == false) {
Toast.makeText(getApplicationContext(), "Unable to fetch data from server", Toast.LENGTH_LONG).show();
}
}
}
#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_main, menu);
return true;
}
#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;
}
return super.onOptionsItemSelected(item);
}
}
My ExpandListAdapter class is
package comsam.myexpandablelistviedjsonapp;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseExpandableListAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import java.io.InputStream;
import java.util.ArrayList;
/**
* Created by tanvinn on 10/27/2015.
*/
public class ExpandListAdapter extends BaseExpandableListAdapter{
private Context context;
private ArrayList<Parent> parents;
public MainActivity activity;
public ImageLoader imageLoader;
public int lastExpandedGroupPosition=-1;
public ExpandListAdapter(Context context, ArrayList<Parent> parents) {
this.context = context;
this.parents = parents;
// Create ImageLoader object to download and show image in list
// Call ImageLoader constructor to initialize FileCache
imageLoader = new ImageLoader(activity);
}
#Override
public Object getChild(int parentPosition, int childPosition) {
ArrayList<Child> chList = parents.get(parentPosition).getItems();
return chList.get(childPosition);
}
#Override
public long getChildId(int parentPosition, int childPosition) {
return childPosition;
}
#Override
public View getChildView(int parentPosition, int childPosition,
boolean isLastChild, View convertView, ViewGroup parent) {
Child child = (Child) getChild(parentPosition, childPosition);
if (convertView == null) {
LayoutInflater infalInflater = (LayoutInflater) context
.getSystemService(context.LAYOUT_INFLATER_SERVICE);
convertView = infalInflater.inflate(R.layout.child_layout, null);
}
TextView tv = (TextView) convertView.findViewById(R.id.child_txt);
ImageView imageView = (ImageView)convertView.findViewById(R.id.child_img);
imageView.setImageResource(R.drawable.geofence1);
tv.setText(child.getName().toString());
//new DownloadImageTask(imageView).execute(child.getImage().toString());
imageLoader.DisplayImage(child.getImage().toString(), imageView);
return convertView;
}
#Override
public int getChildrenCount(int parentPosition) {
ArrayList<Child> chList = parents.get(parentPosition).getItems();
return chList.size();
}
#Override
public Object getGroup(int parentPosition) {
return parents.get(parentPosition);
}
#Override
public int getGroupCount() {
return parents.size();
}
#Override
public long getGroupId(int parentPosition) {
return parentPosition;
}
#Override
public View getGroupView(int parentPosition, boolean isExpanded,
View convertView, ViewGroup parent) {
Parent parent1 = (Parent) getGroup(parentPosition);
if (convertView == null) {
LayoutInflater inf = (LayoutInflater) context
.getSystemService(context.LAYOUT_INFLATER_SERVICE);
convertView = inf.inflate(R.layout.parent_layout, null);
}
TextView tv = (TextView) convertView.findViewById(R.id.parent_txt);
ImageView imageView = (ImageView)convertView.findViewById(R.id.parent_img);
imageView.setImageResource(R.drawable.geofence1);
tv.setText(parent1.getParentName());
// new DownloadImageTask(imageView).execute(parent1.getParentImage().toString());
imageLoader.DisplayImage(parent1.getParentImage().toString(), imageView);
return convertView;
}
#Override
public boolean hasStableIds() {
return false;
}
#Override
public boolean isChildSelectable(int parentPosition, int childPosition) {
return true;
}
public Object getGroupName(int parentPosition) {
Parent parent1 = (Parent) getGroup(parentPosition);
String parentName = parent1.getParentName();
return parentName;
}
public Object getChildName(int parentPosition, int childPosition) {
Child child = (Child) getChild(parentPosition, childPosition);
String childName = child.getName();
return childName;
}
private class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {
ImageView bmImage;
public DownloadImageTask(ImageView bmImage) {
this.bmImage = bmImage;
}
protected Bitmap doInBackground(String... urls) {
String urldisplay = urls[0];
Bitmap mIcon11 = null;
try {
InputStream in = new java.net.URL(urldisplay).openStream();
mIcon11 = BitmapFactory.decodeStream(in);
} catch (Exception e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return mIcon11;
}
protected void onPostExecute(Bitmap result) {
bmImage.setImageBitmap(result);
}
}
}
Thanks in advance.
You can try with this AnimatedExpandableListView
listView = (AnimatedExpandableListView) findViewById(R.id.listView);
listView.setAdapter(YOUR_ADAPTER);
// In order to show animations, we need to use a custom click handler
// for our ExpandableListView.
listView.setOnGroupClickListener(new OnGroupClickListener() {
#Override
public boolean onGroupClick(ExpandableListView parent, View v, int groupPosition, long id) {
// We call collapseGroupWithAnimation(int) and
// expandGroupWithAnimation(int) to animate group
// expansion/collapse.
if (listView.isGroupExpanded(groupPosition)) {
listView.collapseGroupWithAnimation(groupPosition);
} else {
listView.expandGroupWithAnimation(groupPosition);
}
return true;
}
});
Android ExpandableListView using animation
Animation for expandableListView
The following in item_animation_fall_down.xml (Place this xml file in res/anim folder)
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android"android:duration="500">
<translate android:interpolator="#android:anim/accelerate_decelerate_interpolator"
android:fromYDelta="50%p" android:toYDelta="0" />
<alpha android:fromAlpha="0" android:toAlpha="1"
android:interpolator="#android:anim/accelerate_decelerate_interpolator" />
</set>
The following in getGroupView(....) {} block
convertView.setAnimation(AnimationUtils.loadAnimation(_context,R.anim.item_animation_fall_down));
The following in Activity class
expListView.setAnimation(AnimationUtils.loadAnimation(this,R.anim.item_animation_from_right));
The following in activity_home.xml ( to the root element)
android:fillAfter="true" android:fillEnabled="true"
I've seen many examples of setOnLongClickListener in a ListView, but I'm using an AndroidHive's ExpandableListView, so it doesn't seem to recognized (error: setOnLongClickListener cannot be resolved to a type). How would I go about making it so that I can use setOnLongClickListener?
ExpandableListView expListView;
...
expListView.setOnLongClickListener(new OnLongClickListener() {
#Override
public boolean onLongChildClick(View v) {
return true;
}
});
MainActivity.java (listener located in first method):
package com.example.groceryrunnerv4;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.graphics.Paint;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.ExpandableListView;
import android.widget.PopupMenu;
import android.widget.TextView;
import android.widget.ExpandableListView.OnChildClickListener;
import android.widget.ExpandableListView.OnGroupClickListener;
import android.widget.ExpandableListView.OnGroupCollapseListener;
import android.widget.ExpandableListView.OnGroupExpandListener;
import android.widget.Toast;
public class MainActivity extends Activity {
ExpandableListAdapter listAdapter;
ExpandableListView expListView;
List<String> listDataHeader;
HashMap<String, List<String>> listDataChild;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// get the listview
expListView = (ExpandableListView) findViewById(R.id.lvExp);
// preparing list data
prepareListData();
listAdapter = new ExpandableListAdapter(this, listDataHeader, listDataChild);
// setting list adapter
expListView.setAdapter(listAdapter);
// Listview on child click listener
expListView.setOnChildClickListener(new OnChildClickListener() {
#Override
public boolean onChildClick(ExpandableListView parent, View v,
int groupPosition, int childPosition, long id) {
//((TextView) v).setPaintFlags(((TextView) v).getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG);
//listDataChild.get(listDataHeader.get(groupPosition)).get(childPosition) .setPaintFlags(CHILD.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG);
return false;
}
});
expListView.setOnLongClickListener(new OnLongClickListener() {
#Override
public boolean onLongChildClick(View v) {
return true;
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
// Adds food group data
private void prepareListData() {
listDataHeader = new ArrayList<String>();
listDataChild = new HashMap<String, List<String>>();
// Adding child data groups
listDataHeader.add("Produce");
listDataHeader.add("Grains");
listDataHeader.add("Meat & Seafood");
listDataHeader.add("Frozen");
listDataHeader.add("Canned");
listDataHeader.add("Bakery");
listDataHeader.add("Beverages");
listDataHeader.add("Other");
// Adding child data items
List<String> Produce = new ArrayList<String>();
Produce.add("Chaquita Bananas");
Produce.add("Apples (8)");
Produce.add("Kiwi");
Produce.add("Romaine Lettuce (3)");
List<String> Grains = new ArrayList<String>();
Grains.add("Whole Grain Bread");
Grains.add("Whole Wheat English Muffins");
Grains.add("Pasta");
Grains.add("Oatmeal");
List<String> MeatSeafood = new ArrayList<String>();
MeatSeafood.add("My dead friends");
List<String> Frozen = new ArrayList<String>();
Frozen.add("Edamame");
Frozen.add("Bean Burgers");
List<String> Canned = new ArrayList<String>();
Canned.add("Amy's Lentils");
Canned.add("Jam");
Canned.add("Peanu Butter");
List<String> Bakery = new ArrayList<String>();
Canned.add("Fresh Bread");
List<String> Beverages = new ArrayList<String>();
Canned.add("Water");
listDataChild.put(listDataHeader.get(0), Produce);
listDataChild.put(listDataHeader.get(1), Grains);
listDataChild.put(listDataHeader.get(2), MeatSeafood);
listDataChild.put(listDataHeader.get(3), Frozen);
listDataChild.put(listDataHeader.get(4), Canned);
listDataChild.put(listDataHeader.get(5), Bakery);
listDataChild.put(listDataHeader.get(6), Beverages);
}
// Method for activity events
public void onButtonClick(View v) {
final int id = v.getId();
switch (id) {
case R.id.CreateLG:
createLGPopup(v);
break;
case R.id.EditButton:
createEditButtonPopup(v);
break;
case R.id.SaveButton:
Toast.makeText(getApplicationContext(), "List saved.",
Toast.LENGTH_SHORT).show();
break;
case R.id.ListButton:
// chooseListDialog()
}
}
// findViewById(R.id.GetStarted).setVisibility(View.INVISIBLE);
// TextView text = (TextView) findViewById(R.id.GetStarted);
// text.setText(choice);
// CreateLG Button's Popup Menu
public void createLGPopup(View v) {
PopupMenu LGMenu = new PopupMenu(this, v);
LGMenu.getMenuInflater().inflate(R.menu.createlg_menu, LGMenu.getMenu());
LGMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
#Override
public boolean onMenuItemClick(MenuItem item) {
String choice = new String((String) item.getTitle());
if (choice.equals("Create List")) {
createListDialog();
}
else if (choice.equals("Create Group")) {
createGroupDialog();
}
return false;
}
});
LGMenu.show();
}
// Create Edit Button's Popup Menu
public void createEditButtonPopup(View v) {
PopupMenu EditMenu = new PopupMenu(this, v);
EditMenu.getMenuInflater().inflate(R.menu.editlist_menu, EditMenu.getMenu());
EditMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
#Override
public boolean onMenuItemClick(MenuItem item) {
String choice = new String((String) item.getTitle());
if (choice.equals("Edit List Name")) {
editListDialog();
}
else if (choice.equals("Clear All Items")) {
Toast.makeText(getApplicationContext(), "All list items deleted.",
Toast.LENGTH_SHORT).show();
}
else if (choice.equals("Delete List")) {
TextView text = (TextView) findViewById(R.id.ListName);
text.setText("Grocery Runner");
Toast.makeText(getApplicationContext(), "\"" + text.getText().toString() + "\" list edited.",
Toast.LENGTH_SHORT).show();
}
return false;
}
});
EditMenu.show();
}
// Create List Dialog
public AlertDialog.Builder dialogBuilder;
private void createListDialog() {
dialogBuilder = new AlertDialog.Builder(this);
final EditText textInput = new EditText(this);
dialogBuilder.setTitle("Create new list");
dialogBuilder.setMessage("Name your list: ");
dialogBuilder.setView(textInput);
dialogBuilder.setPositiveButton("Create", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
TextView text = (TextView) findViewById(R.id.ListName);
text.setText(textInput.getText().toString());
Toast.makeText(getApplicationContext(), "\"" + textInput.getText().toString() + "\" list created.",
Toast.LENGTH_SHORT).show();
//add list to ListsButton
}
});
dialogBuilder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(getApplicationContext(), "Cancelled.",
Toast.LENGTH_SHORT).show();
}
});
// Output
AlertDialog dialogue = dialogBuilder.create();
dialogue.show();
}
// Create Group Dialog
private void createGroupDialog() {
dialogBuilder = new AlertDialog.Builder(this);
final EditText textInput = new EditText(this);
dialogBuilder.setTitle("Create new group");
dialogBuilder.setMessage("Name your group: ");
dialogBuilder.setView(textInput);
dialogBuilder.setPositiveButton("Create", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
createGroup(textInput.getText().toString());
Toast.makeText(getApplicationContext(), "\"" + textInput.getText().toString() + "\" group created.",
Toast.LENGTH_SHORT).show();
}
});
dialogBuilder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(getApplicationContext(), "Cancelled.",
Toast.LENGTH_SHORT).show();
}
});
// Output
AlertDialog dialogue = dialogBuilder.create();
dialogue.show();
}
public void createGroup(String inputGroup){
listDataHeader = new ArrayList<String>();
listDataChild = new HashMap<String, List<String>>();
// Adding child data group
listDataHeader.add(inputGroup);
// Adding child data items
List<String> group = new ArrayList<String>();
Integer groupIndex = listDataHeader.indexOf(inputGroup);
listDataChild.put(listDataHeader.get(groupIndex), group);
}
// Create List Dialog
private void editListDialog() {
dialogBuilder = new AlertDialog.Builder(this);
final EditText textInput = new EditText(this);
dialogBuilder.setTitle("Edit list name");
dialogBuilder.setMessage("Name your list: ");
dialogBuilder.setView(textInput);
dialogBuilder.setPositiveButton("Create", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
TextView text = (TextView) findViewById(R.id.ListName);
text.setText(textInput.getText().toString());
Toast.makeText(getApplicationContext(), "\"" + textInput.getText().toString() + "\" list edited.",
Toast.LENGTH_SHORT).show();
}
});
dialogBuilder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(getApplicationContext(), "Cancelled.",
Toast.LENGTH_SHORT).show();
}
});
// Output
AlertDialog dialogue = dialogBuilder.create();
dialogue.show();
}
}
ExpandableListAdapter.java:
package com.example.groceryrunnerv4;
import java.util.HashMap;
import java.util.List;
import android.content.Context;
import android.graphics.Typeface;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseExpandableListAdapter;
import android.widget.TextView;
public class ExpandableListAdapter extends BaseExpandableListAdapter {
private Context _context;
private List<String> _listDataHeader; // header titles
// child data in format of header title, child title
private HashMap<String, List<String>> _listDataChild;
public ExpandableListAdapter(Context context, List<String> listDataHeader,
HashMap<String, List<String>> listChildData) {
this._context = context;
this._listDataHeader = listDataHeader;
this._listDataChild = listChildData;
}
#Override
public Object getChild(int groupPosition, int childPosititon) {
return this._listDataChild.get(this._listDataHeader.get(groupPosition))
.get(childPosititon);
}
#Override
public long getChildId(int groupPosition, int childPosition) {
return childPosition;
}
#Override
public View getChildView(int groupPosition, final int childPosition,
boolean isLastChild, View convertView, ViewGroup parent) {
final String childText = (String) getChild(groupPosition, childPosition);
if (convertView == null) {
LayoutInflater infalInflater = (LayoutInflater) this._context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = infalInflater.inflate(R.layout.list_item, null);
}
TextView txtListChild = (TextView) convertView
.findViewById(R.id.lblListItem);
txtListChild.setText(childText);
return convertView;
}
#Override
public int getChildrenCount(int groupPosition) {
return this._listDataChild.get(this._listDataHeader.get(groupPosition))
.size();
}
#Override
public Object getGroup(int groupPosition) {
return this._listDataHeader.get(groupPosition);
}
#Override
public int getGroupCount() {
return this._listDataHeader.size();
}
#Override
public long getGroupId(int groupPosition) {
return groupPosition;
}
#Override
public View getGroupView(int groupPosition, boolean isExpanded,
View convertView, ViewGroup parent) {
String headerTitle = (String) getGroup(groupPosition);
if (convertView == null) {
LayoutInflater infalInflater = (LayoutInflater) this._context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = infalInflater.inflate(R.layout.list_group, null);
}
TextView lblListHeader = (TextView) convertView
.findViewById(R.id.lblListHeader);
lblListHeader.setTypeface(null, Typeface.BOLD);
lblListHeader.setText(headerTitle);
return convertView;
}
#Override
public boolean hasStableIds() {
return false;
}
#Override
public boolean isChildSelectable(int groupPosition, int childPosition) {
return true;
}
}
getExpandableListView().setOnItemLongClickListener(new OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
if (ExpandableListView.getPackedPositionType(id) == ExpandableListView.PACKED_POSITION_TYPE_CHILD) {
int groupPosition = ExpandableListView.getPackedPositionGroup(id);
int childPosition = ExpandableListView.getPackedPositionChild(id);
// You now have everything that you would as if this was an OnChildClickListener()
// Add your logic here.
// Return true as we are handling the event.
return true;
}
return false;
}
});
from Android: long click on the child views of a ExpandableListView?
I want to create a custom listview in which every single row has a textview and an imageview(which i'll use to check/uncheck the list items) as shown in the following figure:
I want to delete multiple items from the list. How to achieve this ?? Can you please provide any tutorial or reference or link to learn this ??
This is how i created my custom listview with ease:
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.Context;
import android.content.DialogInterface;
import android.content.pm.ActivityInfo;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
public class DeleteData extends Activity {
Cursor cursor;
ListView lv_delete_data;
static ArrayList<Integer> listOfItemsToDelete;
SQLiteDatabase database;
private Category[] categories;
ArrayList<Category> categoryList;
private ArrayAdapter<Category> listAdapter;
ImageView iv_delete;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_delete_data);
this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
manage_reload_list();
listOfItemsToDelete = new ArrayList<Integer>();
iv_delete = (ImageView) findViewById(R.id.imageViewDeleteDataDelete);
iv_delete.setClickable(true);
iv_delete.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (listOfItemsToDelete.isEmpty()) {
Toast.makeText(getBaseContext(), "No items selected.",
Toast.LENGTH_SHORT).show();
}
else {
showDialog(
"Warning",
"Are you sure you want to delete these categories ? This will erase all records attached with it.");
}
}
});
lv_delete_data = (ListView) findViewById(R.id.listViewDeleteData);
lv_delete_data.setAdapter(listAdapter);
lv_delete_data.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
// TODO Auto-generated method stub
ImageView imageView = (ImageView) arg1
.findViewById(R.id.imageViewSingleRowDeleteData);
Category category = (Category) imageView.getTag();
if (category.getChecked() == false) {
imageView.setImageResource(R.drawable.set_check);
listOfItemsToDelete.add(category.getId());
category.setChecked(true);
} else {
imageView.setImageResource(R.drawable.set_basecircle);
listOfItemsToDelete.remove((Integer) category.getId());
category.setChecked(false);
}
}
});
}
private void showDialog(final String title, String message) {
AlertDialog.Builder adb = new Builder(DeleteData.this);
adb.setTitle(title);
adb.setMessage(message);
adb.setIcon(R.drawable.ic_launcher);
String btn = "Ok";
if (title.equals("Warning")) {
btn = "Yes";
adb.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
}
adb.setPositiveButton(btn, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface arg0, int arg1) {
if (title.equals("Warning")) {
for (int i : listOfItemsToDelete) {
// -------first delete from category table-----
database.delete("category_fields", "cat_id=?",
new String[] { i + "" });
// --------now fetch rec_id where cat_id =
// i-----------------
cursor = database.query("records_data",
new String[] { "rec_id" }, "cat_id=?",
new String[] { i + "" }, null, null, null);
if (cursor.getCount() == 0)
cursor.close();
else {
ArrayList<Integer> al_tmp_rec_id = new ArrayList<Integer>();
while (cursor.moveToNext())
al_tmp_rec_id.add(cursor.getInt(0));
cursor.close();
for (int i1 : al_tmp_rec_id) {
database.delete("records_fields_data",
"rec_id=?", new String[] { i1 + "" });
database.delete("record_tag_relation",
"rec_id=?", new String[] { i1 + "" });
}
// ---------delete from records_data-------
database.delete("records_data", "cat_id=?",
new String[] { i + "" });
cursor.close();
}
}
showDialog("Success",
"Categories, with their records, deleted successfully.");
} else {
database.close();
listOfItemsToDelete.clear();
manage_reload_list();
lv_delete_data.setAdapter(listAdapter);
}
}
});
AlertDialog ad = adb.create();
ad.show();
}
protected void manage_reload_list() {
loadDatabase();
categoryList = new ArrayList<Category>();
// ------first fetch all categories name list-------
cursor = database.query("category", new String[] { "cat_id",
"cat_description" }, null, null, null, null, null);
if (cursor.getCount() == 0) {
Toast.makeText(getBaseContext(), "No categories found.",
Toast.LENGTH_SHORT).show();
cursor.close();
} else {
while (cursor.moveToNext()) {
categories = new Category[] { new Category(cursor.getInt(0),
cursor.getString(1)) };
categoryList.addAll(Arrays.asList(categories));
}
cursor.close();
}
listAdapter = new CategoryArrayAdapter(this, categoryList);
}
static class Category {
String cat_name = "";
int cat_id = 0;
Boolean checked = false;
Category(int cat_id, String name) {
this.cat_name = name;
this.cat_id = cat_id;
}
public int getId() {
return cat_id;
}
public String getCatName() {
return cat_name;
}
public Boolean getChecked() {
return checked;
}
public void setChecked(Boolean checked) {
this.checked = checked;
}
public boolean isChecked() {
return checked;
}
public void toggleChecked() {
checked = !checked;
}
}
static class CategoryViewHolder {
ImageView imageViewCheck;
TextView textViewCategoryName;
public CategoryViewHolder(ImageView iv_check, TextView tv_category_name) {
imageViewCheck = iv_check;
textViewCategoryName = tv_category_name;
}
public ImageView getImageViewCheck() {
return imageViewCheck;
}
public TextView getTextViewCategoryName() {
return textViewCategoryName;
}
}
static class CategoryArrayAdapter extends ArrayAdapter<Category> {
LayoutInflater inflater;
public CategoryArrayAdapter(Context context, List<Category> categoryList) {
super(context, R.layout.single_row_delete_data,
R.id.textViewSingleRowDeleteData, categoryList);
inflater = LayoutInflater.from(context);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
Category category = (Category) this.getItem(position);
final ImageView imageViewCheck;
final TextView textViewCN;
if (convertView == null) {
convertView = inflater.inflate(R.layout.single_row_delete_data,
null);
imageViewCheck = (ImageView) convertView
.findViewById(R.id.imageViewSingleRowDeleteData);
textViewCN = (TextView) convertView
.findViewById(R.id.textViewSingleRowDeleteData);
convertView.setTag(new CategoryViewHolder(imageViewCheck,
textViewCN));
}
else {
CategoryViewHolder viewHolder = (CategoryViewHolder) convertView
.getTag();
imageViewCheck = viewHolder.getImageViewCheck();
textViewCN = viewHolder.getTextViewCategoryName();
}
imageViewCheck.setFocusable(false);
imageViewCheck.setFocusableInTouchMode(false);
imageViewCheck.setClickable(true);
imageViewCheck.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
ImageView iv = (ImageView) v;
Category category = (Category) iv.getTag();
if (category.getChecked() == false) {
imageViewCheck.setImageResource(R.drawable.set_check);
listOfItemsToDelete.add(category.getId());
category.setChecked(true);
} else {
imageViewCheck
.setImageResource(R.drawable.set_basecircle);
listOfItemsToDelete.remove((Integer) category.getId());
category.setChecked(false);
}
}
});
imageViewCheck.setTag(category);
if (category.getChecked() == true)
imageViewCheck.setImageResource(R.drawable.set_check);
else
imageViewCheck.setImageResource(R.drawable.set_basecircle);
textViewCN.setText(category.getCatName());
return convertView;
}
}
private void loadDatabase() {
database = openOrCreateDatabase("WalletAppDatabase.db",
SQLiteDatabase.OPEN_READWRITE, null);
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
finish();
return true;
}
return super.onKeyDown(keyCode, event);
}
}
Anyone who have doubts in this can ask me...
Fisrt of all make a custom adapter and row layout for your listview. Follow this link (click) for that.Then add check-box to each row.You can customize check-box to achieve like the image you have posted.To do that, check this link (click)
After creating your custom listview, you have to get the checked listview row id on checkbox click in custom adapter(inside getview method).When the user click a checkbox you have to get the clicked row id and store into an array list.Lets say, your selected id-array list is "ArrayId" and your listview items array list is "Yourarray". here is the code,
checkbox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView,boolean isChecked) {
if(isChecked)
{
ArrayId.add(Yourlist.get(position));//add item position to arraylist if checked
}
else
{
ArrayId.remove(Yourlist.get(position));//remove item position from arraylist if unchecked
}
}
}
Then you loop through each id stored in arraylist and delete the entry.Check the code below,
for(int i=0;i<ArrayId.size();i++)
{
Yourlist.remove(ArrayId[i]);
}
Now the items from your listview items array-"Yourlist" will be removed.Then invalidate the listview with updated "Yourlist" array.
Is this ok to do?
#Override
protected void onPostExecute(final ChannelPair p) {
HiddenChannelsListAdapter adapter = new HiddenChannelsListAdapter(p.ctx, p.channelList);
p.lv.setAdapter(adapter);
p.lv.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
Log.i("CLICKED ON LV ITEM", "YEA");
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
}
Its not actually triggering the event I think. At least no item is Selected?
UPDATE
So I removed the stuff from the asyncTask and added it to a new Thread, so now its all in the same file. But still, I cannot get the clicks from the items
package com.example.tvrplayer;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.preference.DialogPreference;
import android.util.AttributeSet;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
public class ChannelsDialogPreference extends DialogPreference {
public static Context ctx;
// Activity activity;
public ChannelsDialogPreference(Context context, AttributeSet attrs) {
super(context, attrs);
this.ctx = context;
}
#Override
protected View onCreateDialogView() {
// Set loading spinner
// Start looking for channels
// When complete, show channels
LayoutInflater inflater = ((SettingsActivity) ctx).getLayoutInflater();
final View vw = inflater.inflate(R.layout.channel_content_view, null);
// Do this in a new Thread
Thread thread = new Thread()
{
#Override
public void run() {
try {
final JSONArray channels;
String username = null;
String linkid = null;
final String apiurl = "http://192.168.2.136:8080";
final String channelID = null;
final DatabaseHandler db = new DatabaseHandler(ctx);
List<User> users = db.getAllUsers();
for (User cn : users) {
linkid = cn.getLinkID();
username = cn.getUserName();
}
db.close();
final ArrayList< HashMap < String, String > > channelList = new ArrayList < HashMap < String, String > > ();
try {
if ( channelID != null ) {
channels = Json.getJson(apiurl + "/rest/channel/"+ linkid +"/"+ username + "/" + channelID, "GET");
Log.i("CHANNELS", channels.toString());
for (int i=0; i < channels.length(); i++) {
JSONObject json_data = channels.getJSONObject(i);
String name = json_data.getString("Name");
String channelid = json_data.getString("ChannelID");
HashMap<String, String> channelObject = new HashMap<String, String>();
// if ( json_data.getString("ParentPath") == "" ) {
channelObject.put("id", channelid);
channelObject.put("name", name);
channelList.add(channelObject);
// }
}
} else {
channels = Json.getJson(apiurl + "/rest/channel/"+ linkid +"/"+ username, "GET");
Log.i("CHANNELS", channels.toString());
for (int i=0; i < channels.length(); i++) {
JSONObject json_data = channels.getJSONObject(i);
String name = json_data.getString("Name");
String channelid = json_data.getString("ChannelID");
HashMap<String, String> channelObject = new HashMap<String, String>();
Log.i("CHANNEL LEN", ""+ json_data.getString("ParentID").length());
if ( json_data.getString("ParentID").length() < 32 ) {
channelObject.put("id", channelid);
channelObject.put("name", name);
channelList.add(channelObject);
}
}
}
((Activity)ctx).runOnUiThread(new Runnable() {
public void run() {
HiddenChannelsListAdapter adapter = new HiddenChannelsListAdapter(ctx, channelList);
ListView lv = (ListView) vw.findViewById(R.id.list);
lv.setAdapter(adapter);
lv.setOnItemClickListener(new android.widget.AdapterView.OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3)
{
Log.i("CLICKED ON LV ITEM", "YEA");
}
});
}
});
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (Exception e) {
e.printStackTrace();
}
}
};
thread.start();
return vw;
}
#Override
protected void onDialogClosed(boolean positiveResult) {
super.onDialogClosed(positiveResult);
persistBoolean(positiveResult);
}
#Override
public void onClick (DialogInterface dialog, int which)
{
super.onClick(dialog, which);
//
Log.v("which", Integer.toString(which));
//
if(which == -1) { //Clear all
// new ChannelHandler().execute(apiurl, username, linkid, vw, ctx, channelID);
}
}
}
This part is where the clicks are bound:
((Activity)ctx).runOnUiThread(new Runnable() {
public void run() {
HiddenChannelsListAdapter adapter = new HiddenChannelsListAdapter(ctx, channelList);
ListView lv = (ListView) vw.findViewById(R.id.list);
lv.setAdapter(adapter);
lv.setOnItemClickListener(new android.widget.AdapterView.OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3)
{
Log.i("CLICKED ON LV ITEM", "YEA");
}
});
}
});
This causes a change on UIthread which should not be called from the background thread. Remeber never to update or notifychange() a listView from the backgound thread