Json parsing using Listview in Android using Ayntask - android

Hi there I want to get data from a table through API using following query
select * from Order as O where username=O.username;
my Asyntask code is :
protected String doInBackground(Void... params) {
String data = "";
//login doesnt exist
final String url = Data.server + "/Order.aspx";
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(url);
List<NameValuePair> param = new ArrayList<NameValuePair>();
param.add(new BasicNameValuePair("username", mEmail));
UrlEncodedFormEntity uefa = null;
try {
uefa = new UrlEncodedFormEntity(param);
post.setEntity(uefa);
HttpResponse response;
response = client.execute(post);
HttpEntity entity = response.getEntity();
data = EntityUtils.toString(entity);
} catch (IOException e) {
// TODO Auto-generated catch block
data = e.toString();
e.printStackTrace();
}
return data;
}
#Override
protected void onPostExecute(String success) {
mAuthTask = null;
showProgress(false);
if (success.contains("[{") && (success.length() > 5)) {
//start the profile activity if json is returned
LocalRegistryreg(success);
try {
JSONArray jarr = new JSONArray(res);
ArrayAdapter<jarr> adapter = new ArrayAdapter<jarr>(this,
android.R.layout.simple_list_item_1, items);
scourseslist.setAdapter(adapter);
for (int i = 0; i < jarr.length(); ++i) {
// Extract values from JSON row:
JSONObject jsonObject = jarr.getJSONObject(i);
String PID = jsonObject.has("PID ") ? jsonObject.getString("PID ") : "";
String PTitle = jsonObject.has("PTitle ") ? jsonObject.getString("PTitle ") : "";
String Quantity = jsonObject.has("Quantity ") ? jsonObject.getString("Quantity ") : "";
String Price = jsonObject.has("Price ") ? jsonObject.getString("Price ") : "";
}
} catch (JSONException e) {
e.printStackTrace();
}
finish();
//Utility.shoAlert(success,LoginActivity.this);
} else {
Utility.shoAlert(success, Order.this);
}
}
im storing return json in a string variable String data;and my data look like this
and the data is multi row. i want to show up all my data row using listview. i treied but i got error. so kindly provide a piece of code to show my data in listview?

You need to define a class to hold the data:
public class Order {
private String pID;
private String pTitle;
private String quantity;
private String price;
public Order(String pID, String pTitle, String quantity, String price) {
this.pID = pID;
this.pTitle = pTitle;
this.quantity = quantity;
this.price = price;
}
public String getpID() {
return pID;
}
public void setpID(String pID) {
this.pID = pID;
}
public String getpTitle() {
return pTitle;
}
public void setpTitle(String pTitle) {
this.pTitle = pTitle;
}
public String getQuantity() {
return quantity;
}
public void setQuantity(String quantity) {
this.quantity = quantity;
}
public String getPrice() {
return price;
}
public void setPrice(String price) {
this.price = price;
}
}
you need to create a custom adapter class:
public class OrderAdapter extends BaseAdapter {
private Activity activity;
private ArrayList<Order> orderList = new ArrayList<Order>();
private static LayoutInflater inflater = null;
public OrderAdapter(Activity activity, ArrayList<Order> orderList,
Resources res) {
this.activity = activity;
this.orderList = orderList;
// Layout inflator to call external xml layout ()
inflater = (LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
return orderList.size();
}
#Override
public Order getItem(int arg0) {
// TODO Auto-generated method stub
return orderList.get(arg0);
}
#Override
public long getItemId(int arg0) {
// TODO Auto-generated method stub
return 0;
}
public static class ViewHolder {
public TextView text1;
public TextView text2;
public TextView text3;
public TextView text4;
public TextView text5;
}
/****** Depends upon data size called for each row , Create each ListView row *****/
public View getView(int position, View convertView, ViewGroup parent) {
View view = convertView;
ViewHolder holder;
if (convertView == null) {
view = inflater.inflate(R.layout.tabitem, null);
holder = new ViewHolder();
holder.text1 = (TextView) view.findViewById(R.id.text1);
holder.text1 = (TextView) view.findViewById(R.id.text2);
holder.text2 = (TextView) view.findViewById(R.id.text3);
holder.text4 = (TextView) view.findViewById(R.id.text4);
view.setTag(holder);
} else {
holder = (ViewHolder) view.getTag();
}
Order order = (Order) orderList.get(position);
/************ Set Model values in Holder elements ***********/
holder.text1.setText(order.getpID());
holder.text2.setText(order.getPrice());
holder.text3.setText(order.getpTitle());
holder.text4.setText(order.getQuantity());
return view;
}
}
create a custom row layout with name tabitem:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TextView
android:id="#+id/text1"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
</TextView>
<TextView
android:id="#+id/text2"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
</TextView>
<TextView
android:id="#+id/text3"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
</TextView>
<TextView
android:id="#+id/text4"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
</TextView>
</LinearLayout>
Define ListView to show data:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ListView
android:id="#+id/list"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="1"/>
</RelativeLayout>
Than you need to create instance of the class and set the data in your on onPostExecute method.
Order order = new Order(PID, PTitle,Quantity, Price);
List<Order> orderList = new ArrayList<Order>();
and than pass that list of order data to activity, and activity can than apply adapter to show the data:
ListView list= (ListView) findViewById(R.id.list); // List defined in XML
OrderAdapter orderAdapter = OrderAdapter(activity, orderList);
list.setAdapter(orderAdapter );

I don't want to make it harder for you, but it could save you a lot of work and provide more flexibility in the future: Retrofit

Related

Choose a specific row of a recyclerview for sharing intent

Is there a way to choose a specific row of my RecyclerView (maybe by getting the index of the row) and then use it to create an intent.
I tried some things by getting the specific row information but that was not even close. My recycler is populated with data from a database.
To choose a specific row of my recycler, you can add setOnItemClickListener code like this one to your onCreate function:
listView_search.setOnItemClickListener(
new AdapterView.OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> parent, View v, int position, long id){
//Here I'm getting store_id and store_name
TextView store_search_id =(TextView) v.findViewById(R.id.store_search_id);
TextView store_search_name =(TextView) v.findViewById(R.id.store_search_name);
String store_name = store_search_name.getText().toString();
String store_id = store_search_id.getText().toString();
//Then I'm sending theses variables to a shared Intent
Intent myIntent = new Intent(getApplicationContext(), StoresShowActivity.class);
myIntent.putExtra("STORE_ID", store_id);
myIntent.putExtra("STORE_NAME", store_name);
startActivity(myIntent);
}
}
);
You may also want to follow these steps:
A. Add a layout for the Recycle view:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/activity_stores_search"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="ksa.ikp.activities.StoresSearchActivity">
<SearchView
android:id="#+id/SearchView_store"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:iconifiedByDefault="false">
<requestFocus />
</SearchView>
<ListView
android:id="#+id/listView_search"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_below="#+id/SearchView_store" />
</RelativeLayout >
B. Add a layout for the recycleview item
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="horizontal"
android:padding="10dp">
<TextView
android:id="#+id/store_search_id"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:visibility="invisible" />
<TextView
android:id="#+id/store_search_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView
android:id="#+id/store_search_category"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
C. Use adapter like this one and you can modify it based on your need
public class StoresSearchAdapter extends BaseAdapter {
// Declare Variables
Context mContext;
LayoutInflater inflater;
private List<Store> myList = null;
private ArrayList<Store> myArrayList;
public StoresSearchAdapter(Context context, List<Store> myList) {
mContext = context;
this.myList = myList;
inflater = LayoutInflater.from(mContext);
this.myArrayList = new ArrayList<Store>();
this.myArrayList.addAll(myList);
}
public class ViewHolder {
TextView store_search_id;
TextView store_search_name;
TextView store_search_category;
}
#Override
public int getCount() {
return myList.size();
}
#Override
public Store getItem(int position) {
return myList.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
public View getView(final int position, View view, ViewGroup parent) {
final ViewHolder holder;
if (view == null) {
holder = new ViewHolder();
view = inflater.inflate(R.layout.activity_stores_search_item, null);
// Locate the TextViews in activity_stores_search_item.xml
holder.store_search_id = (TextView) view.findViewById(R.id.store_search_id);
holder.store_search_name = (TextView) view.findViewById(R.id.store_search_name);
holder.store_search_category = (TextView) view.findViewById(R.id.store_search_category);
view.setTag(holder);
} else {
holder = (ViewHolder) view.getTag();
}
// Set the results into TextViews
holder.store_search_id.setText(myList.get(position).getStr_id()+"");
holder.store_search_name.setText(myList.get(position).getStr_name());
String s = SplashActivity.db.getNameById(myList.get(position).getStr_cat_id()+"",SplashActivity.db.TABLE_CATEGORY,SplashActivity.db.COLUMN_CAT_NAME,SplashActivity.db.COLUMN_CAT_ID);
s = " in ("+ s + ")";
holder.store_search_category.setText(s);
return view;
}
// Filter Class
public void filter(String s) {
s = s.toLowerCase(Locale.getDefault());
myList.clear();
if (s.length() == 0) {
myList.addAll(myArrayList);
} else {
myList.addAll(SplashActivity.db.getAllStoresFiltered(s));
}
notifyDataSetChanged();
}
}
Finally your final output will be something like this one:
screenshot
This is my recyclerbackgroundtask
public class RecycleBackgroundTask extends AsyncTask{
Context ctx;
Activity activity;
RecyclerView recyclerView;
RecyclerView.Adapter adapter;
RecyclerView.LayoutManager layoutManager;
ArrayList<Post> arrayList = new ArrayList<>();
public RecycleBackgroundTask(Context ctx){
this.ctx = ctx;
activity = (Activity)ctx;
}
String json_string = "http://192.168.2.110/app/post.php";
#Override
public void onPreExecute() {
recyclerView = (RecyclerView)activity.findViewById(R.id.recyclerView);
layoutManager = new LinearLayoutManager(ctx);
recyclerView.setLayoutManager(layoutManager);
recyclerView.setHasFixedSize(true);
adapter = new RecyclerAdapter(arrayList);
recyclerView.setAdapter(adapter);
}
#Override
public Void doInBackground(Void... params) {
try {
URL url = new URL(json_string);
HttpURLConnection httpURLConnection = (HttpURLConnection)url.openConnection();
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
StringBuilder stringBuilder = new StringBuilder();
String line;
while ((line=bufferedReader.readLine())!=null) {
stringBuilder.append(line+"\n");
}
httpURLConnection.disconnect();
String json_string = stringBuilder.toString().trim();
JSONObject jsonObject = new JSONObject(json_string);
JSONArray jsonArray = jsonObject.getJSONArray("server_response");
int count = 0;
while(count<jsonArray.length()){
JSONObject JO = jsonArray.getJSONObject(count);
count++;
Post post = new Post(JO.getString("headline"),JO.getString("source"),JO.getString("url"));
publishProgress(post);
}
Log.d("JSON STRING",json_string);
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
#Override
public void onProgressUpdate(Post... values) {
arrayList.add(values[0]);
adapter.notifyDataSetChanged();
}
And my RecyclerAdapter
public class RecyclerAdapter extends RecyclerView.Adapter {
private static final int TYPE_HEAD = 0;
private static final int TYPE_LIST = 1;
ArrayList<Post> arrayList = new ArrayList<>();
public RecyclerAdapter (ArrayList<Post> arrayList){
this.arrayList = arrayList;
}
#Override
public RecyclerViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
if(viewType == TYPE_HEAD){
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.row_recycler,parent,false); // instead of row_recycler ,header_layout.
RecyclerViewHolder recyclerViewHolder = new RecyclerViewHolder(view,viewType);
return recyclerViewHolder;
}
if(viewType == TYPE_LIST){
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.row_recycler,parent,false);
RecyclerViewHolder recyclerViewHolder = new RecyclerViewHolder(view,viewType);
return recyclerViewHolder;
}
return null;
}
#Override
public void onBindViewHolder(RecyclerViewHolder holder, int position) {
if(holder.viewType == TYPE_LIST) {
Post post = arrayList.get(position-1);
holder.Headline.setText(post.getHeadline());
holder.Source.setText(post.getSource());
//holder.Url.setText(post.getUrl());
}
}
#Override
public int getItemCount() {
return arrayList.size()+1;
}
public static class RecyclerViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
TextView Headline,Source;//,Url;
int viewType;
public RecyclerViewHolder(View view,int viewType){
super(view);
if(viewType == TYPE_LIST) {
Headline = (TextView) view.findViewById(R.id.headline);
Source = (TextView) view.findViewById(R.id.source);
Headline.setOnClickListener(this);
Source.setOnClickListener(this);
// Url = (TextView) view.findViewById(R.id.url);
this.viewType = TYPE_LIST;
}else if (viewType == TYPE_HEAD){
this.viewType = TYPE_HEAD;
}
}
#Override
public void onClick(View v) {
Toast.makeText(v.getContext(), "ITEM PRESSED = " + String.valueOf(getAdapterPosition()), Toast.LENGTH_SHORT).show();
}
}
#Override
public int getItemViewType(int position){
if(position==0)
return TYPE_HEAD;
return TYPE_LIST;
}
public void setFilter(ArrayList<Post> newList){
arrayList = new ArrayList<>();
arrayList.addAll(newList);
notifyDataSetChanged();
}
}
Maybe that helps. i already set up a simple onclicklistener with a toast btw

customAdapter not working properly with asynchronous image download

Hey guys i am trying to create a custom listview with text and images where images are coming from a url. i am trying to display them asynchronously with my list items. but as i scroll down the list, the image in list items changes and wrong images are displayed in listitems. Below is my code snippet:
CustomList.java,
it is implimenting my base adapter
public class CustomList extends BaseAdapter {
//private ArrayList listData;
private LayoutInflater layoutInflater;
private ArrayList<ListItem> listData;
public CustomList(Context context,ArrayList<ListItem> listData)
{
//Toast.makeText(History.this,"hey",Toast.LENGTH_LONG).show();
this.listData = listData;
layoutInflater = LayoutInflater.from(context);
}
#Override
public int getCount() {
Log.e("mysize",String.valueOf(listData.size()));
return listData.size();
}
#Override
public Object getItem(int position) {
return listData.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView,ViewGroup parent)
{
ViewHolder holder;
if(convertView == null)
{
convertView = layoutInflater.inflate(R.layout.history_row,null);
holder = new ViewHolder();
holder.so = (TextView)convertView.findViewById(R.id.SO);
holder.name = (TextView)convertView.findViewById(R.id.Name);
holder.process = (ImageView)convertView.findViewById(R.id.Process);
holder.cloth = (ImageView)convertView.findViewById(R.id.Cloth);
convertView.setTag(holder);
}
else
{
holder = (ViewHolder) convertView.getTag();
}
ListItem data = (ListItem)listData.get(position);
holder.so.setText(data.getSo());
if(data.getProcess().equals("0"))
{
holder.process.setImageResource(R.drawable.tick);
}
else
holder.process.setImageResource(android.R.drawable.ic_delete);
if(holder.cloth !=null)
{
holder.name.setText(data.getName());
Log.e("urlsss",data.getUrl()+ data.getName());
new ImageDownload(holder.cloth).execute(data.getUrl());
}
return convertView;
}
static class ViewHolder
{
TextView so;
TextView name;
ImageView process;
ImageView cloth;
}
}
ImageDownload.class for downloading images
public class ImageDownload extends AsyncTask<String,Void,Bitmap> {
private final WeakReference<ImageView> imageViewReference;
public ImageDownload(ImageView imageView)
{
imageViewReference = new WeakReference<ImageView>(imageView);
}
protected Bitmap doInBackground(String... params)
{
RequestHandler rh = new RequestHandler();
return rh.downloadBitmap(params[0]);
}
#Override
protected void onPostExecute(Bitmap bitmap) {
if (isCancelled()) {
bitmap = null;
}
if (imageViewReference != null) {
ImageView imageView = imageViewReference.get();
if (imageView != null) {
if (bitmap != null) {
imageView.setImageBitmap(bitmap);
} else {
Drawable placeholder = imageView.getContext().getResources().getDrawable(android.R.drawable.star_on);
imageView.setImageDrawable(placeholder);
}
}
}
}
}
ListItem.java that is producing my data for each row in listView
public class ListItem {
private String so,name,process,imgUrl;
public void setSo(String so)
{
this.so = so;
}
public void setName(String name)
{
this.name = name;
}
public void setProcess(String process)
{
this.process = process;
}
public void setUrl(String url)
{
this.imgUrl = url;
}
public String getSo()
{
return so;
}
public String getName()
{
return name;
}
public String getProcess()
{
return process;
}
public String getUrl()
{
return imgUrl; }
}
This is my main activity where custom-adapter is called
public class History extends AppCompatActivity {
//url to fetch data from
public static final String URL_HISTORY = "http://192.168.1.233/vendor/history.php";
//Json tags
public static final String TAG_JSON_ARRAY="result";
public static final String TAG_SO = "SO";
public static final String TAG_NAME = "CustomerName";
public static final String TAG_DESC = "ClothDescription";
public static final String TAG_DATE = "DeliveryDate";
public static final String TAG_PRODUCT_TYPE = "ProductType";
public static final String TAG_PRODUCT_DESC = "ProductDescription";
public static final String TAG_IMAGE_URL = "ImageUrl";
public static final String TAG_PROCESS = "Process";
HashMap<String,String> data = new HashMap<>();
ArrayList<ListItem> detail_list;
ListView listView;
//key to put in hashmap
public static final String VENDOR_NAME = "Username";
//to store fetched data
String[] so;
String[] customerName;
String[] clothesDesc;
String[] delivDate;
String[] prodType;
String[] prodDesc;
String[] imgUrl;
String[] process;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_history);
listView =(ListView)findViewById(R.id.listView);
detail_list = new ArrayList<ListItem>();
//to get vendorname
SharedPreferences sharedPref = getSharedPreferences("vendorInfo", Context.MODE_PRIVATE);
String vendor_name =sharedPref.getString("username", "");
data.put(VENDOR_NAME, vendor_name);
fetchHistory();
}
public void fetchHistory()
{
class FetchHistory extends AsyncTask<Void,Void,String>
{
ProgressDialog loading;
protected void onPreExecute()
{
super.onPreExecute();
loading = ProgressDialog.show(History.this,"Fetching...","Wait",false,false);
}
protected String doInBackground(Void...params)
{
RequestHandler rh = new RequestHandler();
String result = rh.sendPostRequest(URL_HISTORY, data);
return result;
}
protected void onPostExecute(String s)
{
super.onPostExecute(s);
loading.dismiss();
Log.e("myjson",s);
showHistory(s);
}
}
FetchHistory fh = new FetchHistory();
fh.execute();
}
public void showHistory(String json)
{
try {
JSONObject jsonObject = new JSONObject(json);
JSONArray result = jsonObject.getJSONArray(TAG_JSON_ARRAY);
int length = result.length();
so = new String[length];
customerName = new String[length];
clothesDesc = new String[length];
delivDate = new String[length];
prodType = new String[length];
prodDesc = new String[length];
imgUrl = new String[length];
process = new String[length];
for (int i = 0; i < result.length(); i++) {
JSONObject c = result.getJSONObject(i);
so[i] = c.getString(TAG_SO);
customerName[i] = c.getString(TAG_NAME);
clothesDesc[i] = c.getString(TAG_DESC);
delivDate[i] = c.getString(TAG_DATE);
prodType[i] = c.getString(TAG_PRODUCT_TYPE);
prodDesc[i] = c.getString(TAG_PRODUCT_DESC);
imgUrl[i] = c.getString(TAG_IMAGE_URL);
process[i] = c.getString(TAG_PROCESS);
}
}
catch(JSONException e)
{
Log.e("myexception",e.toString());
}
for(int i =0;i<customerName.length;i++)
{
//storing all value in hashmap
ListItem values = new ListItem();
values.setSo(so[i]);
values.setName(customerName[i]);
values.setUrl(imgUrl[i]);
Log.e("myurl", imgUrl[i]);
values.setProcess(process[i]);
detail_list.add(values);
}
Toast.makeText(this,"hey",Toast.LENGTH_LONG).show();
Log.e("hey", "hey00");
CustomList customList = new CustomList(this,detail_list);
listView.setAdapter(customList);
Toast.makeText(this,"you",Toast.LENGTH_LONG).show();
Log.e("you", "you00");
}
}
My layout file for each row is
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:id="#+id/linear">
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="0dp"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:id="#+id/SO"
android:layout_marginRight="10dp"
android:layout_weight="2" />
<TextView
android:layout_width="0dp"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:id="#+id/Name"
android:layout_marginRight="10dp"
android:layout_weight="2" />
<ImageView
android:layout_width="0dp"
android:layout_height="wrap_content"
android:id="#+id/Process"
android:layout_weight="1" />
</LinearLayout>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<ImageView
android:layout_width="0dp"
android:layout_height="wrap_content"
android:id="#+id/Cloth"
android:layout_weight="1"
android:scaleType="fitXY" />
</LinearLayout>
</LinearLayout>
This is a common mistake. Your listView recycles views, so instead of creating views for the 100 items in your listView, it just creates enough to fill up the screen.
As you scroll down, that ImageView that was used for position #1, is now the same ImageView being used for position #11, and #21, and so on...
The fix require tracking what positions are currently being displayed to the user, and only setting images for those positions, and clearing the associated imageview (or cancelling the pending download) when it falls off the screen.
You can figure out when your imageView gets reassigned because it will be called in getView again, and from there you can figure out if it has a pending download you need to cancel.
Consider using one of the existing solutions or just checking out how others have done it for a full example. https://github.com/nostra13/Android-Universal-Image-Loader

how to Listview Refresh after Delete an item on Button Click event in android?

I want to delete an item from Listview, and at a time Refresh Listview after deleting an item. How to possible?
I am using get all item using JSON Parsing from database and delete an selected an item on click of button. delete successfully from database but Listview not refresh at a time. how to do?
I am using Json Parsing. not local database.
In This case, How to refresh Listview when Deleting Item?
please Guide me.
Thanks in Advance.
My Code is,
Detail.java File
public class Detail extends Activity {
ListView lstDetail = null;
/** String */
String urlGetDetailData = null;
/** Declare another variable for Listview */
Adapter1 adapter1 = null;
ArrayList<Detail> myList = new ArrayList<Detail>();
/** Hashmap for ListView */
ArrayList<HashMap<String, String>> dataList = null;
/** JSON Node names */
public static final String TAG_MEMBER_ID = "mem_id";
public static final String TAG_ID = "id";
public static final String TAG_USER_ID = "userid";
public static final String TAG_STATUS = "Status";
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
onCreateActivity(R.layout.detail);
initializeWidgets();
}
private void initializeWidgets() {
/** ListView */
lstDetail = (ListView) findViewById(R.id.lstDetail);
urlGetDetailData = "http://example.com/getdata.php?id="
+ strId;
new GetDetailData().execute();
myList.remove(position);
Adapter1.this.notifyDataSetChanged();
}
/**
* Async task class to get json by making HTTP call
* */
private class GetDetailData extends AsyncTask<Void, Void, Void> {
JSONObject jsonobject;
JSONArray jsonarray;
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... arg0) {
dataList = new ArrayList<HashMap<String, String>>();
// Retrieve JSON Objects from the given URL address
jsonobject = JSONFunctions.getJSONfromURL(urlGetDetailData);
try {
// Locate the array name in JSON
jsonarray = jsonobject.getJSONArray("data");
for (int i = 0; i < jsonarray.length(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
jsonobject = jsonarray.getJSONObject(i);
// Retrive JSON Objects
map.put("mem_id", String.valueOf(jsonobject
.getString(TAG_MEMBER_ID)));
map.put("id",
jsonobject.getString(TAG_ID));
map.put("userid", jsonobject.getString(TAG_USER_ID));
map.put("Status", jsonobject.getString(TAG_STATUS));
dataList.add(map);
}
} catch (JSONException e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
if (dataList.size() != 0) {
lstDetail.setVisibility(View.VISIBLE);
Adapter1 = new Adapter1(Detail.this,
dataList);
lstDetail.setAdapter(Adapter1);
} else {
lstDetail.setVisibility(View.GONE);
}
}
}
}
And Adapter Class is,
Adapter1.java File
public class Adapter1 extends BaseAdapter {
public ArrayList<HashMap<String, String>> arrData = null;
Context context = null;
LayoutInflater layoutInflater = null;
HashMap<String, String> getDetailData = new HashMap<String, String>();
/** String */
String strMemberId = null, urlDelete = null;
/** Constructor */
public Adapter1(Context context,
ArrayList<HashMap<String, String>> arrData) {
layoutInflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
this.context = context;
this.arrData = arrData;
}
#Override
public int getCount() {
return arrData.size();
}
#Override
public Object getItem(int position) {
return arrData.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
ViewHolder viewHolder = null;
if (convertView == null) {
convertView = layoutInflater.inflate(
R.layout.list_item, null);
viewHolder = new ViewHolder();
getData = arrData.get(position);
/** Initialize Widgets */
viewHolder.imgCancel = (ImageView) convertView
.findViewById(R.id.imgCancel);
viewHolder.imgCancel
.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
strMemberId = arrData.get(
position).get(
Detail.TAG_MEMBER_ID);
urlDelete = "http://example.com/delete.php?mem_id="
+ strMemberId;
new DeleteComments().execute();
}
});
/** TextView */
viewHolder.txtMemberId = (TextView) convertView
.findViewById(R.id.txtMemberId);
viewHolder.txtId = (TextView) convertView
.findViewById(R.id.txtId);
viewHolder.txtDesc = (TextView) convertView
.findViewById(R.id.txtDesc);
/** Set Value */
viewHolder.txtMemberId.setText(getDetailData
.get(Detail.TAG_MEMBER_ID));
viewHolder.txtId.setText(getDetailData
.get(Detail.TAG_ID));
viewHolder.txtDesc.setText(getDetailData
.get(Detail.TAG_STATUS));
convertView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
return convertView;
}
/** ViewHolder Class */
#SuppressLint("NewApi")
public static class ViewHolder {
ImageView imgCancel = null;
TextView txtMemberId = null, txtId = null,txtDesc = null;
}
public class DeleteComments extends AsyncTask<Void, Void, Void> {
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... arg0) {
ServiceHandler sh = new ServiceHandler();
String jsonStr = sh.makeServiceCall(urlDelete,
ServiceHandler.GET);
Log.d("Response : delete join comments", ">" + jsonStr);
return null;
}
protected void onPostExecute(Void result) {
super.onPostExecute(result);
};
}
}
detail.xml File is,
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/re/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content" >
<ListView
android:id="#+id/lstDetail"
android:layout_width="fill_parent"
android:layout_height="wrap_content" >
</ListView>
</RelativeLayout>
list_item.xml file is,
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/re/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content" >
<LinearLayout
android:id="#+id/contentLayout"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center_vertical"
android:orientation="vertical" >
<TextView
android:id="#+id/txtId"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="111" />
<TextView
android:id="#+id/txtDesc"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
</LinearLayout>
<ImageView
android:id="#+id/imgCancel"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_centerVertical="true"
android:src="#drawable/cancel" />
<TextView
android:id="#+id/txtMemberId"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/txtUserEventId"
android:layout_alignBottom="#+id/txtUserEventId"
android:layout_alignParentLeft="true"
android:text="222" />
</RelativeLayout>
in your custom adapter call this.notifyDataSetChanged(); where you are performing delete functionality and deleting that element from arrayList which is set to that adapter
You are writing delete action, in that function only call adapter.notifyDataSetChanged again.So it refr
on delete action fetch the data once again and then again call adapter.notifyDataSetChanged it will work
First of all Put you adapter code in Details.java class
then change this,
public class DeleteComments extends AsyncTask<Void, Void, Void> {
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... arg0) {
ServiceHandler sh = new ServiceHandler();
String jsonStr = sh.makeServiceCall(urlDelete,
ServiceHandler.GET);
Log.d("Response : delete join comments", ">" + jsonStr);
return null;
}
protected void onPostExecute(Void result) {
super.onPostExecute(result);
Adapter1.remove(Adapter1.getItem(position));
};
}
hope it will help you
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
ViewHolder viewHolder = null;
if (convertView == null) {
convertView = layoutInflater.inflate(
R.layout.list_item, null);
viewHolder = new ViewHolder();
getData = arrData.get(position);
/** Initialize Widgets */
viewHolder.imgCancel = (ImageView) convertView
.findViewById(R.id.imgCancel);
viewHolder.imgCancel
.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
strMemberId = arrData.get(
position).get(
Detail.TAG_MEMBER_ID);
urlDelete = "http://example.com/delete.php?mem_id="
+ strMemberId;
new DeleteComments().execute();
}
});
/** TextView */
viewHolder.txtMemberId = (TextView) convertView
.findViewById(R.id.txtMemberId);
viewHolder.txtId = (TextView) convertView
.findViewById(R.id.txtId);
viewHolder.txtDesc = (TextView) convertView
.findViewById(R.id.txtDesc);
/** Set Value */
viewHolder.txtMemberId.setText(getDetailData
.get(Detail.TAG_MEMBER_ID));
viewHolder.txtId.setText(getDetailData
.get(Detail.TAG_ID));
viewHolder.txtDesc.setText(getDetailData
.get(Detail.TAG_STATUS));
convertView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
bDelete.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View view)
{
arrData.remove(position);
notifyDataSetChanged():
}
});
return convertView;
}
Why make it that complicated?
Just call remove(Obj); in OnClickListener of your customized adapter Adapter1's. And notifyDataSetChanged will be called in removed method too.

Can not understand how to get the value from setters and getters class

I am parsing json data and displaying in custom ListView using BaseAdapter. I have no problem in parsing the data. Also don't have any problem setting the data to ModelClass.java (setters and getters class) only question is how to get the data from ModelClass.java. Please help.
This is my MainActivity.java
public class MainActivity extends ActionBarActivity {
// url to make request(to get the latest 20 feeds).
private static String url = "http;.....";
// JSON Node names
private static final String TAG_BODY = "body";
private static final String TAG_CREATED_AT = "created_at";
private static final String TAG_DATE_TIME = "date_time";
private static final String TAG_DEPARTEMENT = "department";
private static final String TAG_ID = "id";
private static final String TAG_INCLUDE = "include";
private static final String TAG_MEDI_TYPE = "mediaType";
private static final String TAG_PRIORITY = "priority";
private static final String TAG_TITLE = "title";
private static final String TAG_UPDATED_AT = "updated_at";
private static final String TAG_USER_ID = "user_id";
ProgressDialog progressDialog;
ListView listViewFeeds;
// String mTitle, mBody;
List<ModelClass> model = new ArrayList<ModelClass>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
/* To display the feed */
listViewFeeds = (ListView) findViewById(R.id.listViewFeeds);
listViewFeeds.setAdapter(new NewAdapter(this));
Feeds feeds = new Feeds();
feeds.execute();
}
public class Feeds extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
progressDialog = new ProgressDialog(MainActivity.this);
progressDialog.setTitle("Loading ...");
progressDialog.show();
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... arg0) {
HttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
httpGet.setHeader("Accept", "application/json");
try {
HttpResponse httpResponse = httpClient.execute(httpGet);
StatusLine statusLine = httpResponse.getStatusLine();
int statusCode = statusLine.getStatusCode();
if (statusCode != 200) {
return null;
}
HttpEntity httpEntity = httpResponse.getEntity();
InputStream inputStream = httpEntity.getContent();
BufferedReader bufferedReader = new BufferedReader(
new InputStreamReader(inputStream));
StringBuilder stringBuilder = new StringBuilder();
String line;
while ((line = bufferedReader.readLine()) != null) {
stringBuilder.append(line);
}
String jsonData = stringBuilder.toString();
// Displaying json data in logcat.
Log.d("Latest 20 feeds", jsonData);
JSONArray array = new JSONArray(jsonData);
for (int i = 0; i < array.length(); i++) {
JSONObject object = array.getJSONObject(i);
String mTitle = object.getString("title");
String mBody = object.getString("body");
System.out.println("Titlte: " + mTitle);
System.out.println("Body: " + mBody);
// Setting the data to ModelClass
ModelClass mc = new ModelClass(mTitle, mBody);
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
progressDialog.dismiss();
super.onPostExecute(result);
}
}
}
class NewAdapter extends BaseAdapter {
ArrayList<ModelClass> list;
Context context;
NewAdapter(Context c) {
context = c;
}
#Override
public int getCount() {
return 0;
// return list.size();
}
#Override
public Object getItem(int position) {
return list.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View row = inflater.inflate(R.layout.single_row_feed_view, parent,
false);
TextView title = (TextView) row.findViewById(R.id.textViewTitleFeeds);
TextView body = (TextView) row.findViewById(R.id.textViewBody);
ModelClass temp = list.get(position);
title.setText(temp.title);
body.setText(temp.body);
return row;
}
}
This is my ModelClass.java
public class ModelClass {
String title;
String body;
ModelClass(String title, String body) {
this.title = title;
this.body = body;
}
}
activity_main.xml file
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<ListView
android:id="#+id/listViewFeeds"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
</ListView>
</LinearLayout>
single_row_feed_view.xml file(row appears in ListView)
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TextView
android:id="#+id/textViewTitleFeeds"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="#+id/viewColor"
android:ellipsize="end"
android:maxLines="2"
android:text="TextView"
android:textSize="12dp" />
<TextView
android:id="#+id/textViewBody"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="#+id/textViewTitleFeeds"
android:layout_marginTop="3dp"
android:ellipsize="end"
android:maxLines="2"
android:text="TextView"
android:textSize="8dp" />
</RelativeLayout>
Its a bit hard to work out the exact question because you are asking how to get the value from setters and getters class but your ModelClass has no getters or setters.
You can put getters into your ModelClass, but you may not technically need them if its in the same package.
You should look at this tutorial. It helped me a lot.
http://www.vogella.com/tutorials/AndroidListView/article.html
Is this what you're asking for?
//Inside your Model class:
public String getTitle(){
return this.title;
}
public String setTitle(String givenTitle){
this.title = givenTitle;
}
public String getBody(){
return this.body;
}
public String setTitle(String givenBody){
this.body = givenBody;
}
As others have mentioned you need to put getters and setters in your model class. In terms of putting the values in a list and formatting the list item, then you need a custom list adapter. Then create a list of the items you want to put in the list adapter.. then show the list. Below is an example.
enter code here
public class ExampleListAdapter extends ArrayAdapter<ExampleModel> {
private Context context;
private ArrayList<ExampleModel> items;
public ExampleListAdapter(Context context, ArrayList<ExampleModel> items) {
super(context, R.id.result_list_item_direction_icon, items);
this.context = context;
this.items = items;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = null;
View rowView = convertView;
//Get rowView from inflater
inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
rowView = inflater.inflate(R.id.yourcustom_layout, parent, false);
// Get reference ids from the rowView
//example
TextView item = (TextView) rowView.findViewById(R.id.itemID);
// Set the values for items in custom list view
item.setText(items.get(position).yourGetter());
return rowView;
}
}
then in the in the class you want to use it…
enter code here
ArrayList<t> yourList = new ArrayList<t>();
yourList = getValuesFromDBOROtherSource;//make sure the return value is list!
yourCustomAdapter = new ExampleListAdapter(getActivity(), yourList);
setListAdapter(yourCustomAdapter);

How to get the check box selected position

How to get the selected position in checkbox itemId.
I have two item Veg and non-veg item. I want the result for veg Items only. I show the screen in veg items .But it is not working for veg list checked items.
Response
|1|Amaretto cookies|True
is itemId
food item
True/False.
Based on True or False I need to check the check boxes and retrieve the checked items
Veg items:
|21|1|Amaretto cookies|True|2|Amish White Bread|True|6|Caesar Salad|True|10|Guacamole|True|13|Macaroni and Cheese|True|16|Pancakes|True|17|Pasta|True|18|Ribollita|True|20|Pizza|True|21|Seven Layer Taco Dip|True|22|Shrimp Bisque|True|23|Spicy Bean Salsa|True|24|Sopapilla Cheesecake|True|25|Sopapilla Cheesecake Pie|True|26|Vegetarian Tortilla Stew|True|561|food|True|563|asdf|True|574|veg|True|579|a|True|593|hjg|True|619|hhy|True|
Non- Veg items:
|12|3|Barbeque|False|4|Buffalo Chicken Wings|False|5|Burgers|False|7|Classic Lasagna|False|8|Chicken Chow Mein|False|9|Fried Chicken|False|11|Japanese sushi|False|12|Mezze|False|14|Mutton Pepper Gravy|False|15|Paella Valenciana|False|19|Phad Thai Recipe|False|578|Pizza|False|
Url:
String user_url="http://mobileapps.iwedplanner.com/mobileapps/iwedplanner/mobile/version21/mmealitems.aspx?uname="+LoginForm.str1+"&occasion="+occasionval;
Code:
httpclass obj = new httpclass();
result = obj.server_conn(user_url);
System.out.println(result);
if (result != null)
{
token = new StringTokenizer2(result, "");
}
value = new ArrayList<String>();
while (token.hasMoreTokens())
{
value.add(token.nextToken());
}
value.add(Integer.toString(value.size()));
Integer k=null;
table=new Hashtable<Integer,ArrayList<String>>();
itemId = new ArrayList<String>();
stritem = new ArrayList<String>();
vegitems = new ArrayList<String>();
nonvegitems = new ArrayList<String>();
int id=0,c=0,n=value.size();
for(int j=0; j<n; j++)
{
z = value.get(j);
String[] mystring = z.split("<br>");
int arraysize = mystring.length;
for(int a=0; a<arraysize-1;a++)
{
str2.add(mystring[0]);
str3.add(mystring[1]);
}
}
for(int g=0; g<str2.size();g++)
{
String name = str2.get(g);
token2 = new StringTokenizer2(name, "|", false);
while (token2.hasMoreTokens())
{
vegitems.add(token2.nextToken());
}
}
for(int x=1;x<vegitems.size();x++)
{
itemId.add(vegitems.get(x));
x=x+1;
stritem.add(vegitems.get(x));
x=x+1;
status.add(vegitems.get(x));
}
setListAdapter(new IconicAdapter(this));
selection = (TextView) findViewById(R.id.selection);
getListView().setTextFilterEnabled(true);
save.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
tru = new StringBuffer();
fals = new StringBuffer();
for (int i = 0; i<status.size();i++)
{
if (status.get(i).equals("True"))
tru.append(itemId.get(i)+",");
else
fals.append(itemId.get(i)+",");
}
boolean netvalue = false;
ConnectivityManager cm = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo info = cm.getActiveNetworkInfo();
if (info != null && info.isAvailable()) {
String user_url="http://mobileapps.iwedplanner.com/mobileapps/iwedplanner/mobile/version21/minsertmealchoiceNew.aspx?uname="+username+"&occasion="+occasionval+
"&choice="+tru+fals+"&ownchoice=&category=";
httpclass obj = new httpclass();
result = obj.server_conn(user_url);
StringTokenizer st = new StringTokenizer(result, "|");
result = st.nextToken();
if ((result.equals("Engagement 1&")) || (result.equals("Wedding 1&")) || (result.equals("Reception 1&")))
{
#SuppressWarnings("rawtypes")
class IconicAdapter extends ArrayAdapter
{
Activity context;
#SuppressWarnings("unchecked")
IconicAdapter(Activity context)
{
super(context, R.layout.rsvp_mealsse, stritem);
this.context = context;
}
#Override
public View getView(int position, View convertView, ViewGroup parent)
{
LayoutInflater inflater = context.getLayoutInflater();
View row = inflater.inflate(R.layout.rsvp_mealsse,null);//viewappointlist, null);
TextView index = (TextView) row.findViewById(R.id.index);
index.setText(String.valueOf(position+1)+".");
TextView label = (TextView) row.findViewById(R.id.title);
label.setText(stritem.get(position));
CheckBox check=(CheckBox)row.findViewById(R.id.check);
check.setId(Integer.parseInt(itemId.get(position)));
if(status.get(position).equals("True"))
check.setChecked(true);
else
check.setChecked(false);
check.setOnCheckedChangeListener(new OnCheckedChangeListener()
{
#Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
// TODO Auto-generated method stub
int ind=itemId.indexOf(String.valueOf(buttonView.getId()));
status.set(ind, String.valueOf(isChecked));
}
});
return (row);
}
}
Snap :
This is what it should look like.False items are checked in the snap
Above shows the full code of my project.
These are my requirements:
It is all about event planner for Food. The invited guests can select and save the interested food items such as pizza, Caesar salad, Ameretocokies etc from the items list and mail to the inviter so that the inviter can view the saved items and arrange for the selected items.
I picked the solution from Romain Guy's solution #
https://groups.google.com/forum/?fromgroups#!topic/android-developers/No0LrgJ6q2M
I have used a ViewHolder pattern for smooth scrolling and performance. I have used a SparseBooleanArray to get checked items.
I assume you want the items whose corresponding check boxes are checked.
Also check this to understand listview re-cycles views
How ListView's recycling mechanism works
public class dsds extends Activity
{
ListView lv;
String result = null;
StringTokenizer2 token = null,token2=null;;
ArrayList<String> value,value2 = null;
ArrayList<String> str = null;
ArrayList<String> str2 = null;
ArrayList<String> newstatus=null;
Hashtable<Integer, String> checkstatus=null;
ArrayList<String>stateId=null;
StringBuffer tru,fals;
private SparseBooleanArray mCheckStates;
String z;
ArrayList<Holder> ha = new ArrayList<Holder>();
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.text);
str2 = new ArrayList<String>();
stateId = new ArrayList<String>();
newstatus=new ArrayList<String>();
lv = (ListView) findViewById(R.id.listView1);
Button b= (Button) findViewById(R.id.button1);
new TheTask().execute();
b.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v) {
StringBuilder result = new StringBuilder();
for(int i=0;i<str2.size();i++)
{
if(mCheckStates.get(i)==true)
{
result.append(str2.get(i));
result.append("\n");
}
}
Toast.makeText(dsds.this, result, 1000).show();
}
});
}
class TheTask extends AsyncTask<Void,Void,Void>
{
#Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
HttpClient httpclient = new DefaultHttpClient();
httpclient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
HttpGet request = new HttpGet("http://mobileapps.iwedplanner.com/mobileapps/iwedplanner/mobile/version21/mmealitems.aspx?uname=abcdefg&occasion=Engagement");
try
{
HttpResponse response = httpclient.execute(request);
HttpEntity resEntity = response.getEntity();
String _response=EntityUtils.toString(resEntity);
if (_response != null)
{
//alertbox("",result);
String[] mystring = _response.split("<br>"); // splt by break
token = new StringTokenizer2(mystring[0], "|", false);// split by |
token2 = new StringTokenizer2(mystring[1], "|", false);
}
/////// for veg
value = new ArrayList<String>();
while (token.hasMoreTokens())
{
value.add(token.nextToken());
}
for(int i=1;i<value.size()-1;i=i+3)
{
// Log.i("....Veg ids.......",""+value.get(i));
stateId.add(value.get(i));
}
for(int i=2;i<value.size()-1;i=i+3)
{
str2.add(value.get(i));
// Log.i("....Veg ids.......",""+value.get(i));
}
for(int i=3;i<=value.size()-1;i=i+3)
{
newstatus.add(value.get(i));
// Log.i("....Veg ids.......",""+value.get(i));
}
// add all to list of Holder
for(int h=0;h<str2.size();h++)
{
Holder holder = new Holder();
holder.setTitle(str2.get(h));
holder.setId(stateId.get(h));
if(newstatus.get(h).equals("False"))
{
holder.setCheck(true);
}
else
{
holder.setCheck(false);
}
ha.add(holder);
}
}catch(Exception e)
{
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
lv.setAdapter(new IconicAdapter(dsds.this));
}
}
#SuppressWarnings("rawtypes")
class IconicAdapter extends ArrayAdapter implements CompoundButton.OnCheckedChangeListener
{
Activity context;
LayoutInflater mInflater;
#SuppressWarnings("unchecked")
IconicAdapter(Activity context)
{
super(context, R.layout.list_item, str2);
mCheckStates = new SparseBooleanArray(str2.size());
mInflater = LayoutInflater.from(context);
}
#Override
public View getView(int position, View convertView, ViewGroup parent)
{
ViewHolder holder;
if(convertView==null)
{
convertView=mInflater.inflate(R.layout.list_item,parent,false);
holder = new ViewHolder();
holder.tv1 = (TextView) convertView.findViewById(R.id.textView1);
holder.tv2 = (TextView) convertView.findViewById(R.id.textView2);
holder.cb = (CheckBox) convertView.findViewById(R.id.checkBox1);
convertView.setTag(holder);
}
else
{
holder = (ViewHolder) convertView.getTag();
}
Holder hol = ha.get(position);
holder.tv1.setText(hol.getId().toString());
holder.tv2.setText(hol.getTitle().toString());
if(hol.isCheck()==true)
{
holder.cb.setChecked(mCheckStates.get(position, true));
holder.cb.setTag(position);
}
else
{
holder.cb.setChecked(mCheckStates.get(position, false));
holder.cb.setTag(position);
}
holder.cb.setOnCheckedChangeListener(this);
return convertView;
}
public boolean isChecked(int position) {
return mCheckStates.get(position, false);
}
public void setChecked(int position, boolean isChecked) {
mCheckStates.put(position, isChecked);
}
public void toggle(int position) {
setChecked(position, !isChecked(position));
}
#Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
mCheckStates.put((Integer) buttonView.getTag(), isChecked);
}
}
static class ViewHolder
{
TextView tv1,tv2;
CheckBox cb;
}
}
Holder class
public class Holder {
String title;
String id;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
boolean check;
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public boolean isCheck() {
return check;
}
public void setCheck(boolean check) {
this.check = check;
}
}
text.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:text="Button" />
<ListView
android:id="#+id/listView1"
android:layout_above="#id/button1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true" >
</ListView>
</RelativeLayout>
list_tiem.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginLeft="33dp"
android:layout_marginTop="40dp"
android:text="TextView" />
<TextView
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/textView1"
android:layout_centerHorizontal="true"
android:text="TextView" />
<CheckBox
android:id="#+id/checkBox1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/textView2"
android:layout_alignBottom="#+id/textView2"
android:layout_alignParentRight="true"
android:text="CheckBox" />
</RelativeLayout>
Snap
Now 1 and 2 are checked and when you click the button at the bottom you see the selected text. I checked 1 and 2 manually. However it depends on the response ie True or False. Right now all veg items are true.
Note: The list displays only veg items
If you are using list-view and you want to check list-view item then you can use below code.
int len = mListView.getCount();
SparseBooleanArray checked = mListView.getCheckedItemPositions();
for (int i = 0; i < len; i++)
if (checked.get(i)){
..... // Your code whatever you want to do with selected item..
}
else{
....
}

Categories

Resources