I have made a custom adapter for seting to a listView in android,I am paring some jsondata and want to set in into a list view,I have tried as belo but its not workig,My code as below,pls help me .
myactivity.java
package com.epe.yehki.ui;
import java.util.ArrayList;
import java.util.HashMap;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;
import com.epe.yehki.adapter.CategoryAdapter;
import com.epe.yehki.adapter.ProductAdapter;
import com.epe.yehki.backend.ServiceHandler;
import com.epe.yehki.uc.Header;
import com.epe.yehki.util.Const;
import com.example.yehki.R;
public class ProSubCategoryActivity extends Activity {
int flag;
public Header header;
public TextView title;
Bitmap bitmap;;
private ProductAdapter productContent;
private CategoryAdapter categoryContent;
// PRODUCTS....
// arrayLists......
public static ArrayList<String> productArray;
public static ArrayList<String> categoryArray;
//
// contacts JSONArray
JSONArray subcategories = null;
JSONArray products = null;
public String catid;
public String id;
String name;
ListView lv;
JSONObject jsonObj;
// Hashmap for ListView
ArrayList<HashMap<String, String>> subcategoryList;
ArrayList<HashMap<String, String>> productList;
private ProgressDialog pDialog;
Intent in = null;
// new
public String proname;
public String prodesc;
public String proimg;
public String proMinOrderQty;
public String proMinPrice;
public String proMaxPrice;
public String proTerms;
public String proId;
// new
// URL to get contacts JSON
private static String url = "http://yehki.epagestore.in/app_api/categories.php";
private static String mainurl = "http://yehki.epagestore.in/";
public String suburl = "";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sub);
this.header = (Header) findViewById(R.id.headersubcat);
title = (TextView) findViewById(R.id.title);
// getting intent data
categoryArray = new ArrayList<String>();
productArray = new ArrayList<String>();
in = getIntent();
lv = (ListView) findViewById(R.id.list);
categoryContent = new CategoryAdapter(this, categoryArray);
// Get JSON values from previous intent
try {
catid = in.getStringExtra(Const.TAG_CAT_ID);
name = in.getStringExtra(Const.TAG_CAT_NAME);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("::::::::::::::MY CATEGORY ID::::::::::::::IN SUB "
+ catid);
subcategoryList = new ArrayList<HashMap<String, String>>();
productList = new ArrayList<HashMap<String, String>>();
suburl = "http://yehki.epagestore.in/app_api/categories.php?"
+ Const.TAG_CAT_ID + "=" + catid;
System.out.println("::::::::::::::::MY SUBCATEGORY URL::::::::::::"
+ suburl);
title.setText(name);
// Displaying all values on the screen
new GetSubCategories().execute();
// Listview on item click listener
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// getting values from selected ListItem
if (flag == 0) {
String catname = ((TextView) view.findViewById(R.id.name))
.getText().toString();
in = new Intent(getApplicationContext(),
SubCategoryTwoActivity.class);
in.putExtra(Const.TAG_CAT_NAME, catname);
in.putExtra(Const.TAG_CAT_ID, catid);
startActivity(in);
} else {
in = new Intent(getApplicationContext(),
ProductDetailActivity.class);
proname = ((TextView) view.findViewById(R.id.product_label))
.getText().toString();
proId = ((TextView) view.findViewById(R.id.pro_id))
.getText().toString();
System.out
.println(":::::::::::::::;;THE INTENT FOR THE PRODUCUT DETIALS ACTIVITY================="
+ proname
+ " proDuct Id::::::::::::>>>>>>>>>"
+ proId);
in.putExtra(Const.TAG_PRODUCT_ID, proId);
in.putExtra(Const.TAG_PRODUCT_NAME, proname);
in.putExtra(Const.TAG_PRODUCT_IMG, proimg);
in.putExtra(Const.TAG_PRODUCT_MIN_ORDER_QTY, proMinOrderQty);
in.putExtra(Const.TAG_PRODUCT_MIN_PRICE, proMinPrice);
in.putExtra(Const.TAG_PRODUCT_MAX_PRICE, proMaxPrice);
in.putExtra(Const.TAG_PRODUCT_DESCRIPTION, prodesc);
in.putExtra(Const.TAG_PRODUCT_PAYMENT_TERMS, proTerms);
/*
* in.putExtra(TAG_CAT_NAME, p); in.putExtra(TAG_CAT_ID,
* catid);
*/
startActivity(in);
}
}
});
}
private class GetSubCategories extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(ProSubCategoryActivity.this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
// Creating service handler class instance
ServiceHandler sh = new ServiceHandler();
System.out.println(":::::::::::::::::::SUB URL:::::::::::::::::"
+ suburl);
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(suburl, ServiceHandler.GET);
Log.d("Response: ", "> " + jsonStr);
try {
if (jsonStr != null) {
jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
if (jsonObj.has(Const.TAG_CAT_LlIS)) {
System.out
.println("::::::::::::::::true::::::::::::::::"
+ jsonObj.has(Const.TAG_CAT_LlIS));
subcategories = jsonObj
.getJSONArray(Const.TAG_CAT_LlIS);
if (subcategories != null
&& subcategories.length() != 0) {
// looping through All Contacts
flag = 0;
System.out
.println(":::::::::::FLAG IN SUB:::::::::::"
+ subcategories.length());
for (int i = 0; i < subcategories.length(); i++) {
JSONObject c = subcategories.getJSONObject(i);
id = c.getString(Const.TAG_CAT_ID);
String name = c.getString(Const.TAG_CAT_NAME);
// tmp hashmap for single category
/*
* HashMap<String, String> subcategory = new
* HashMap<String, String>();
*
* // adding each child node to HashMap key =>
* // value subcategory.put(Const.TAG_CAT_ID,
* id); subcategory.put(Const.TAG_CAT_NAME,
* name);
*
* // adding contact to contact list
* subcategoryList.add(subcategory);
*/
// new adde 3=04=2014
// categoryArray.add(id);
categoryArray.add(name);
System.out
.println("::::::::::My category:::::::"
+ categoryArray.get(i)
.toString().trim());
}
}
} else if (jsonObj.has(Const.TAG_PRODUCT_LlST)) {
flag = 1;
System.out
.println("::::::::::::::::true::::::::::::::::"
+ jsonObj.has(Const.TAG_PRODUCT_LlST));
products = jsonObj.getJSONArray(Const.TAG_PRODUCT_LlST);
if (products != null && products.length() != 0) {
// looping through All Contacts
System.out
.println(":::::::::::FLAG IN SUB:::::::::::"
+ flag);
for (int i = 0; i < products.length(); i++) {
JSONObject c = products.getJSONObject(i);
id = c.getString(Const.TAG_PRODUCT_ID);
String proname = c
.getString(Const.TAG_PRODUCT_NAME);
String prodesc = c
.getString(Const.TAG_PRODUCT_DESCRIPTION);
String proimg = Const.API_HOST + "/"
+ c.getString(Const.TAG_PRODUCT_IMG);
System.out
.println(":::::::::::::::My Image Url:::::::::::::"
+ proimg);
String proMinOrderQty = c
.getString(Const.TAG_PRODUCT_MIN_ORDER_QTY);
String proMinPrice = c
.getString(Const.TAG_PRODUCT_MIN_PRICE);
String proMaxPrice = c
.getString(Const.TAG_PRODUCT_MAX_PRICE);
String proTerms = c
.getString(Const.TAG_PRODUCT_PAYMENT_TERMS);
System.out
.println(":::::::::::::My prododuct name+++++++:::::::::::::"
+ proname);
System.out
.println(":::::::::::::My prododuct image+++++++:::::::::::::"
+ proimg);
System.out
.println(":::::::::::::My prododuct min order qty+++++++:::::::::::::"
+ proMinOrderQty);
// tmp hashmap for single category
HashMap<String, String> product = new HashMap<String, String>();
// adding each child node to HashMap key =>
// value
product.put(Const.TAG_PRODUCT_ID, id);
product.put(Const.TAG_PRODUCT_NAME, proname);
product.put(Const.TAG_PRODUCT_IMG, proimg);
product.put(Const.TAG_PRODUCT_MIN_ORDER_QTY,
proMinOrderQty);
product.put(Const.TAG_PRODUCT_DESCRIPTION,
prodesc);
// adding contact to contact list
productList.add(product);
}
}
}
} else {
Log.e("ServiceHandler",
"Couldn't get any data from the url");
}
} catch (JSONException e) {
e.printStackTrace();
System.out
.println("::::::::::::::::::got an error::::::::::::");
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// Dismiss the progress dialog
if (pDialog.isShowing())
pDialog.dismiss();
/**
* Updating parsed JSON data into ListView
*
* */
if (flag == 0) {
lv.setAdapter(categoryContent);
} else {
Toast.makeText(ProSubCategoryActivity.this, "Please wait", 1)
.show();
/*
* ListAdapter adapter = new SimpleAdapter(
* ProSubCategoryActivity.this, productList,
* R.layout.activity_single_produt, new String[] {
* Const.TAG_PRODUCT_ID, Const.TAG_PRODUCT_NAME,
* Const.TAG_PRODUCT_IMG, Const.TAG_PRODUCT_MIN_ORDER_QTY,
* Const.TAG_PRODUCT_DESCRIPTION }, new int[] {
* R.id.product_label, R.id.iv_product_img, R.id.min_qty,
* R.id.pro_desc, R.id.pro_id }); setListAdapter(adapter);
*/
}
}
}
}
Adapter.java
package com.epe.yehki.adapter;
import java.util.ArrayList;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
import com.example.yehki.R;
public class CategoryAdapter extends BaseAdapter {
private ArrayList<String> categoryArray;
private Context mContext;
public CategoryAdapter(Context paramContext,
ArrayList<String> paramArrayList) {
this.mContext = paramContext;
this.categoryArray = paramArrayList;
}
public int getCount() {
return this.categoryArray.size();
}
public void setAllItems(ArrayList<String> paramArrayList) {
this.categoryArray.addAll(paramArrayList);
}
public Object getItem(int paramInt) {
return Integer.valueOf(paramInt);
}
public long getItemId(int paramInt) {
return paramInt;
}
public View getView(int paramInt, View paramView, ViewGroup paramViewGroup) {
LayoutInflater localLayoutInflater = (LayoutInflater) this.mContext
.getSystemService("layout_inflater");
Viewholder localViewholder = null;
if (paramView == null) {
paramView = localLayoutInflater.inflate(R.layout.list_item,
paramViewGroup, false);
localViewholder = new Viewholder();
localViewholder.categoryName = ((TextView) paramView
.findViewById(R.id.name));
paramView.setTag(localViewholder);
} else {
localViewholder = new Viewholder();
localViewholder = (Viewholder) paramView.getTag();
}
localViewholder.categoryName.setText(categoryArray.get(paramInt)
.indexOf(0));
return paramView;
}
static class Viewholder {
private TextView categoryName;
}
}
I changed your code , try this now
public class CategoryAdapter extends BaseAdapter {
private ArrayList<String> categoryArray;
private Context mContext;
private Viewholder localViewholder = null;
public CategoryAdapter(Context paramContext,
ArrayList<String> paramArrayList) {
this.mContext = paramContext;
this.categoryArray = paramArrayList;
}
public int getCount() {
return this.categoryArray.size();
}
public void setAllItems(ArrayList<String> paramArrayList) {
this.categoryArray.addAll(paramArrayList);
}
public Object getItem(int paramInt) {
return Integer.valueOf(paramInt);
}
public long getItemId(int paramInt) {
return paramInt;
}
public View getView(int paramInt, View paramView, ViewGroup paramViewGroup) {
LayoutInflater localLayoutInflater = (LayoutInflater) this.mContext
.getSystemService("layout_inflater");
if (paramView == null) {
localViewholder = new Viewholder();
paramView = localLayoutInflater.inflate(R.layout.list_item,
paramViewGroup, false);
localViewholder = new Viewholder();
localViewholder.categoryName = ((TextView) paramView
.findViewById(R.id.name));
paramView.setTag(localViewholder);
} else {
localViewholder = (Viewholder) paramView.getTag();
}
localViewholder.categoryName.setText(categoryArray.get(paramInt)
.indexOf(0));
return paramView;
}
static class Viewholder {
private TextView categoryName;
}
}
Related
I want to count row wise total for each item according to its quantity.my problem is that i want to start increment in each row from 1 but if i do increment in first row for e.g. from 1 to 5 then in next row its start from 6 but I want it will start from 1.how I resolve this problem?
Code is:
OrderScreenActivity.java
package com.example.veer.quickpos.activity;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.example.veer.quickpos.R;
import com.example.veer.quickpos.adapter.ListAdapter;
import com.example.veer.quickpos.adapter.ListItemAdapter;
import com.example.veer.quickpos.utility.Utils;
import com.example.veer.quickpos.utils.app.Constants;
import org.json.JSONArray;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
/**
* Created by Veer on 12/07/2016.
*/
public class OrderScreenActivity extends BaseActivity {
public static String CmpId, GroupID, GroupName, UnderGroupId, ParentGroupName,ItemID,ItemName,CategoryID,SellingPrice;
public static ArrayList<String> CmpIdList, GroupIDList, GroupNameList, UnderGroupIdList, ParentGroupNameList;
public static LinearLayout ll;
public EditText edtitem;
public ListView lstitem;
public ListView listItemqty;
public static String item;
ListAdapter adapter;
public int total;
ListItemAdapter adapter2;
public static ArrayList<String> nameList,priceLIst,ItemIDList,ItemNameList,CategoryIDList,SellingPriceList,qtyList;
ProgressDialog pDialog;
/**
* ATTENTION: This was auto-generated to implement the App Indexing API.
* See https://g.co/AppIndexing/AndroidStudio for more information.
*/
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_order);
lstitem = (ListView)findViewById(R.id.lstitem);
edtitem = (EditText)findViewById(R.id.edtitem);
listItemqty = (ListView)findViewById(R.id.listviewItem);
makeJsonStringRequest();
}
public void makeJsonStringRequest() {
String URL = Utils.BASE_URL + Utils.GET_GROUP + Utils.AUTH_KEY;
Log.e("URL =>", URL);
StringRequest stringRequest = new StringRequest(Request.Method.GET, URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
Log.i("Response", response);
JSONArray mResponse = new JSONArray(response);
CmpIdList = new ArrayList<String>();
GroupIDList = new ArrayList<String>();
GroupNameList = new ArrayList<String>();
UnderGroupIdList = new ArrayList<String>();
ParentGroupNameList = new ArrayList<String>();
if (mResponse.length() != 0) {
for (int i = 0; i < mResponse.length(); i++) {
JSONObject obj = mResponse.optJSONObject(i);
CmpId = obj.optString("CmpId");
GroupID = obj.optString("GroupID");
GroupName = obj.optString("GroupName");
UnderGroupId = obj.optString("UnderGroupId");
ParentGroupName = obj.optString("ParentGroupName");
Log.d("CmpId", "" + CmpId);
Log.d("GroupID", "" + GroupID);
Log.d("GroupName", "" + GroupName);
Log.d("UnderGroupId", "" + UnderGroupId);
Log.d("ParentGroupName", "" + ParentGroupName);
CmpIdList.add(CmpId);
GroupIDList.add(GroupID);
GroupNameList.add(GroupName);
UnderGroupIdList.add(UnderGroupId);
ParentGroupNameList.add(ParentGroupName);
/*GetGodowns getGodowns = new GetGodowns();
getGodowns.setGoDownId(_id);
getGodowns.setName(_name);
getGodowns.setDate(CurrentDate);
getGodowns.setSyncData(_Sync);
listGetGodowns.add(getGodowns);*/
}
for (int i = 0; i < CmpIdList.size(); i++) {
ll = (LinearLayout) findViewById(R.id.llgroup);
ll.setOrientation(LinearLayout.HORIZONTAL);
Button txv = new Button(OrderScreenActivity.this);
txv.setWidth(290);
txv.setHeight(180);
txv.setTextColor(getResources().getColor(R.color.darksky));
txv.setText(GroupNameList.get(i));
ll.addView(txv);
txv.setTextSize(15);
txv.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d("in onclick:","");
item = edtitem.getText().toString();
Log.d("value of edittext text:",""+item);
makeJsonStringRequestItem(item);
}
});
Log.d("Id of textview :", "" + txv.getId());
}
//myDbHelper.InsertGoDown(listGetGodowns);
// bindSpinnerData();
hideProgress();
// myDbHelper.InsertGoDown(listGetGodowns);
// bindSpinnerData();
// hideProgress();
}
hideProgress();
Log.e(Constants.TAG, "GetTill response => " + mResponse.toString(4));
} catch (Exception e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
hideProgress();
Toast.makeText(OrderScreenActivity.this, "Error in fetching data, PLease try again", Toast.LENGTH_LONG).show();
Log.v("Error String Request", "" + error.toString());
}
}) {
#Override
protected Map<String, String> getParams() {
return new HashMap<>();
}
};
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
showProgress();
}
public void makeJsonStringRequestItem(String Item) {
Log.d("item group id in item api:",""+GroupID);
String URL = Utils.BASE_URL + Utils.GET_ITEMS + Utils.AUTH_KEY +"&ItemName="+ Item +"&GroupId=0";
Log.e("URL =>", URL);
StringRequest stringRequest = new StringRequest(Request.Method.GET, URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
Log.i("Response", response);
JSONArray mResponse = new JSONArray(response);
CmpIdList = new ArrayList<String>();
ItemIDList = new ArrayList<String>();
ItemNameList = new ArrayList<String>();
CategoryIDList = new ArrayList<String>();
SellingPriceList = new ArrayList<String>();
if (mResponse.length() != 0) {
for (int i = 0; i < mResponse.length(); i++) {
JSONObject obj = mResponse.optJSONObject(i);
CmpId = obj.optString("CmpId");
ItemID = obj.optString("ItemID");
ItemName = obj.optString("ItemName");
CategoryID = obj.optString("CategoryID");
SellingPrice = obj.optString("SellingPrice");
Log.d("CmpId", "" + CmpId);
Log.d("ItemID", "" + ItemID);
Log.d("ItemName", "" + ItemName);
Log.d("CategoryID", "" + CategoryID);
Log.d("SellingPrice", "" + SellingPrice);
CmpIdList.add(CmpId);
ItemIDList.add(ItemID);
ItemNameList.add(ItemName);
CategoryIDList.add(CategoryID);
SellingPriceList.add(SellingPrice);
/*GetGodowns getGodowns = new GetGodowns();
getGodowns.setGoDownId(_id);
getGodowns.setName(_name);
getGodowns.setDate(CurrentDate);
getGodowns.setSyncData(_Sync);
listGetGodowns.add(getGodowns);*/
}
Log.d("Itemnamelist value:",ItemNameList.toString());
Log.d("SellingPriceList value:",SellingPriceList.toString());
adapter = new ListAdapter(OrderScreenActivity.this,ItemNameList,SellingPriceList);
lstitem.setAdapter(adapter);
adapter2 = new ListItemAdapter(OrderScreenActivity.this,ItemNameList,SellingPriceList);
listItemqty.setAdapter(adapter2);
for (int i = 0; i < CmpIdList.size(); i++) {
ll = (LinearLayout) findViewById(R.id.llgroup);
ll.setOrientation(LinearLayout.HORIZONTAL);
Button txv = new Button(OrderScreenActivity.this);
txv.setWidth(290);
txv.setHeight(180);
txv.setTextColor(getResources().getColor(R.color.darksky));
txv.setText(GroupNameList.get(i));
ll.addView(txv);
txv.setTextSize(15);
txv.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
Log.d("Id of textview :", "" + txv.getId());
txv.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
}
//myDbHelper.InsertGoDown(listGetGodowns);
// bindSpinnerData();
hideProgress();
// myDbHelper.InsertGoDown(listGetGodowns);
// bindSpinnerData();
// hideProgress();
}
hideProgress();
Log.e(Constants.TAG, "Getgroup item response => " + mResponse.toString(4));
} catch (Exception e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
hideProgress();
Toast.makeText(OrderScreenActivity.this, "Error in fetching data, PLease try again", Toast.LENGTH_LONG).show();
Log.v("Error String Request", "" + error.toString());
}
}) {
#Override
protected Map<String, String> getParams() {
return new HashMap<>();
}
};
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
showProgress();
}
private void showProgress() {
pDialog = new ProgressDialog(OrderScreenActivity.this);
pDialog.setMessage("Wait a moment");
pDialog.setCancelable(false);
pDialog.show();
}
private void hideProgress() {
if (null != pDialog) {
pDialog.dismiss();
}
}
}
ListItemAdapter
package com.example.veer.quickpos.adapter;
import android.app.Activity;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import com.example.veer.quickpos.R;
import java.util.ArrayList;
public class ListItemAdapter extends BaseAdapter {
Activity context;
public ArrayList<String> NameList;
public ArrayList<String> PriceList;
public ArrayList<String> totalList;
public int flag;
public static int qty;
public static ArrayList<String> qtyList;
public int total,grandtotal;
public ListItemAdapter(Activity a, ArrayList<String> nameList,ArrayList<String> plist) {
this.context = a;
this.NameList = nameList;
this.PriceList = plist;
}
/*private view holder class*/
class ViewHolder {
public TextView txtname,txtprice,txttotal;
public TextView txtqty;
public Button btnplus, btnminus;
}
public View getView(final int position, View convertView, ViewGroup parent) {
final ViewHolder holder;
final LayoutInflater mInflater = (LayoutInflater)
context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
convertView = mInflater.inflate(R.layout.activity_item_qty, null);
holder = new ViewHolder();
holder.btnplus = (Button) convertView.findViewById(R.id.btnplus);
holder.btnplus.setTag(position);
holder.btnminus = (Button) convertView.findViewById(R.id.btnminus);
holder.txtname = (TextView) convertView.findViewById(R.id.item);
holder.txtqty = (TextView) convertView.findViewById(R.id.itemqty);
holder.txtqty.setTag(R.id.itemqty,position);
holder.txtprice = (TextView) convertView.findViewById(R.id.txtprice);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
qtyList = new ArrayList<String>();
Log.d("Total row:",""+getCount());
Log.d("current position:",""+position);
Log.d("Item name at position:", "" + position + NameList.get(position));
holder.txtname.setText(NameList.get(position));
holder.txtprice.setText(PriceList.get(position));
holder.txtqty.setText(String.valueOf(flag));
// qty = Integer.parseInt(holder.txtqty.getText().toString());
// qtyList.add(String.valueOf(qty));
qty=1;
Log.d("value of qty before button plus click:",""+qty);
Log.d("value of flag before button plus click:",""+flag);
// final int pos=(Integer)convertView.getTag();
holder.btnplus.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int total = 0;
flag = qty;
Log.d("value of flag in button plus :",""+flag);
int itempos = holder.txtqty.getId();
holder.txtqty.setText(String.valueOf(flag));
Log.d("value of textqty in button plus :",""+holder.txtqty.getText().toString());
int pos=(Integer)v.getTag();
total = total + (Integer.parseInt(PriceList.get(pos))* (Integer.parseInt(holder.txtqty.getText().toString())));
Log.d("value of total in button plus :",""+total);
flag++;
}
});
holder.btnminus.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(qty>0) {
qty = qty - 1;
Log.d("Value of qty in minus button:", "" + qty);
holder.txtqty.setText(String.valueOf(qty));
total = total + (Integer.parseInt(PriceList.get(position)) * (qty));
Log.d("total is:", "" + total);
}
}
});
return convertView;
}
#Override
public int getCount() {
return NameList.size();
}
#Override
public Object getItem(int position) {
return position;
}
#Override
public long getItemId(int position) {
return position;
}
}
In adapter I did code for counter in btnplus click event.I want to set qty 1 in each row in textview txtqty and in each row increment start from 1 and according to quantity I will get total but if in first row i set qty 5 with increment from plus button in next it start from 6 but I want it start from 1 same as first row how I resolve it?
I am also getting ArrayListIndexOutofBound when I am pressing list item when the orientation is changed.As far my knowledge of android I have written Parcelable code correctly.But I think my issues are with the recycler view setup.I am confused with two declaration of my adapter.Help me
MainActivity.class
package com.reader.ashishyadav271.hackernewsmaterial;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteStatement;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Parcelable;
import android.os.PersistableBundle;
import android.support.v4.util.LruCache;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ListView;
import android.widget.Toast;
import com.wang.avi.AVLoadingIndicatorView;
import org.json.JSONArray;
import org.json.JSONObject;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class MainActivity extends AppCompatActivity implements MyCustomAdapter.ClickListener {
private static final String STATE_LIST = "state_list";
Map<Integer, String> articleURLs = new HashMap<>();
Map<Integer, String> articleTitles = new HashMap<>();
Map<Integer, String> articleDates =new HashMap<>();
Map<Integer, String> articleAuthors =new HashMap<>();
ArrayList<Integer> articleIds=new ArrayList<>();
SQLiteDatabase articlesDB;
ArrayList<Information> data=new ArrayList<>();
ArrayList<String> titles=new ArrayList<>();
ArrayList<String> urls=new ArrayList<>();
ArrayList<String> authors=new ArrayList<>();
ArrayList<String> dateAndTimes=new ArrayList<>();
MyCustomAdapter adapter;
RecyclerView recyclerView;
AVLoadingIndicatorView av;
List<DownloadTask> tasks;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
av= (AVLoadingIndicatorView) findViewById(R.id.avloadingIndicatorView);
av.setVisibility(View.INVISIBLE);
tasks = new ArrayList<>();
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
recyclerView= (RecyclerView) findViewById(R.id.recyclerView);
recyclerView.setLayoutManager(new LinearLayoutManager(getApplicationContext()));
recyclerView.addItemDecoration(new SimpleDividerItemDecoration(
getApplicationContext()
));
articlesDB = this.openOrCreateDatabase("Articles", MODE_PRIVATE, null);
articlesDB.execSQL("CREATE TABLE IF NOT EXISTS article (id INTEGER PRIMARY KEY," +
" articleId INTEGER," +
" url VARCHAR," +
" title VARCHAR," +
" author VARCHAR," +
" date VARCHAR)");
if(savedInstanceState != null) {
data=savedInstanceState.getParcelableArrayList(STATE_LIST);
adapter=new MyCustomAdapter(getApplicationContext(),data);
adapter.setClickListener(this);
recyclerView.setAdapter(adapter);
}else{
if (isOnline()) {
requestData("https://hacker-news.firebaseio.com/v0/topstories.json?print=pretty");
} else {
updateDisplay();
Toast.makeText(this, "Network isn't available", Toast.LENGTH_LONG).show();
}
}
//adapter=new MyCustomAdapter(getApplicationContext(),getData());
//adapter.setClickListener(this);
//recyclerView.setAdapter(adapter);
}
protected boolean isOnline() {
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
if (netInfo != null && netInfo.isConnectedOrConnecting()) {
return true;
} else {
return false;
}
}
private void requestData(String uri) {
DownloadTask task = new DownloadTask();
task.execute(uri);
}
#Override
public void itemClicked(View view, int position) {
Intent i = new Intent(getApplicationContext(), Main2Activity.class);
i.putExtra("articleUrl", urls.get(position));
startActivity(i);
}
protected void updateDisplay() {
adapter=new MyCustomAdapter(getApplicationContext(),getData());
adapter.setClickListener(this);
recyclerView.setAdapter(adapter);;
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putParcelableArrayList(STATE_LIST, data);
}
public class DownloadTask extends AsyncTask<String, Void, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
if (tasks.size() == 0) {
av.setVisibility(View.VISIBLE);
}
tasks.add(this);
}
#Override
protected String doInBackground(String... urls) {
String result = "";
URL url;
HttpURLConnection urlConnection;
try {
url = new URL(urls[0]);
urlConnection = (HttpURLConnection) url.openConnection();
InputStream in = urlConnection.getInputStream();
InputStreamReader reader = new InputStreamReader(in);
int data = reader.read();
while (data != -1) {
char current = (char) data;
result += current;
data = reader.read();
}
JSONArray jsonArray = new JSONArray(result);
articlesDB.execSQL("DELETE FROM article");
for (int i = 0; i < 15; i++) {
String articleId = jsonArray.getString(i);
url = new URL("https://hacker-news.firebaseio.com/v0/item/" + articleId + ".json?print=pretty");
urlConnection = (HttpURLConnection) url.openConnection();
in = urlConnection.getInputStream();
reader = new InputStreamReader(in);
data = reader.read();
String articleInfo = "";
while (data != -1 ) {
char current = (char) data;
articleInfo += current;
data = reader.read();
}
JSONObject jsonObject = new JSONObject(articleInfo);
String articleTitle = jsonObject.getString("title");
String articleURL = jsonObject.getString("url");
String articleDate=jsonObject.getString("time");
String articleAuthor=jsonObject.getString("by");
long unixSeconds = Long.valueOf(articleDate);
Date date = new Date(unixSeconds*1000L); // *1000 is to convert seconds to milliseconds
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss"); // the format of your date
String formattedarticleDate = sdf.format(date);
articleIds.add(Integer.valueOf(articleId));
articleTitles.put(Integer.valueOf(articleId), articleTitle);
articleURLs.put(Integer.valueOf(articleId), articleURL);
articleDates.put(Integer.valueOf(articleId), formattedarticleDate);
articleAuthors.put(Integer.valueOf(articleId), articleAuthor);
String sql = "INSERT INTO article (articleId, url, title, author, date) VALUES (? , ? , ? , ?, ?)";
SQLiteStatement statement = articlesDB.compileStatement(sql);
statement.bindString(1, articleId);
statement.bindString(2, articleURL);
statement.bindString(3, articleTitle);
statement.bindString(4, articleAuthor);
statement.bindString(5, formattedarticleDate);
statement.execute();
}
}catch (Exception e) {
e.printStackTrace();
}
return result;
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
tasks.remove(this);
if (tasks.size() == 0) {
av.setVisibility(View.INVISIBLE);
}
updateDisplay();
}
}
private List<Information> getData() {
/*List<Information> data=new ArrayList<>();
for(int i=0;i<20;i++){
titles.add(i,"Wikileaks Asssange wins UN ruling on arbitrary detention");
url.add(i,"https://www.google.co.in/search?q=best+custom+list+row");
date.add(i,"3 hrs");
author.add(i,"aburan28");
}
for(int i=0;i<20;i++){
Information current=new Information();
current.title=titles.get(i);
current.url=url.get(i);
current.author=author.get(i);
current.date=date.get(i);
data.add(current);
}
return data;*/
Cursor c = articlesDB.rawQuery("SELECT * FROM article", null);
try {
int urlIndex = c.getColumnIndex("url");
int titleIndex = c.getColumnIndex("title");
int authorIndex = c.getColumnIndex("author");
int dateIndex = c.getColumnIndex("date");
c.moveToFirst();
titles.clear();
//urls.clear();
authors.clear();
dateAndTimes.clear();
int i=0;
while (c != null) {
titles.add(c.getString(titleIndex));
urls.add(c.getString(urlIndex));
authors.add(c.getString(authorIndex));
dateAndTimes.add(c.getString(dateIndex));
Information current=new Information();
current.title=titles.get(i);
current.url=urls.get(i);
current.author=authors.get(i);
current.date = dateAndTimes.get(i);
data.add(current);
i++;
c.moveToNext();
}
}catch (Exception e) {
e.printStackTrace();
}finally {
c.close();
}
return data;
}
#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) {
startActivity(new Intent(getApplicationContext(),SettingsActivity.class));
return true;
}
if (id == R.id.action_about) {
startActivity(new Intent(getApplicationContext(),About.class));
return true;
}
return super.onOptionsItemSelected(item);
}
}
Information.class
package com.reader.ashishyadav271.hackernewsmaterial;
import android.os.Parcel;
import android.os.Parcelable;
public class Information implements Parcelable {
public String title;
public String author;
public String date;
public String url;
public Information(){
}
protected Information(Parcel in) {
title = in.readString();
author = in.readString();
date = in.readString();
url = in.readString();
}
public static final Creator<Information> CREATOR = new Creator<Information>() {
#Override
public Information createFromParcel(Parcel in) {
return new Information(in);
}
#Override
public Information[] newArray(int size) {
return new Information[size];
}
};
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(title);
dest.writeString(author);
dest.writeString(date);
dest.writeString(url);
}
}
Log Cat Error
02-06 14:52:58.106 8369-8369/com.reader.ashishyadav271.hackernewsmaterial E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.reader.ashishyadav271.hackernewsmaterial, PID: 8369
java.lang.IndexOutOfBoundsException: Invalid index 0, size is 0
at java.util.ArrayList.throwIndexOutOfBoundsException(ArrayList.java:255)
at java.util.ArrayList.get(ArrayList.java:308)
at com.reader.ashishyadav271.hackernewsmaterial.MainActivity.itemClicked(MainActivity.java:137)
at com.reader.ashishyadav271.hackernewsmaterial.MyCustomAdapter$MyViewHolder.onClick(MyCustomAdapter.java:77)
at android.view.View.performClick(View.java:4471)
at android.view.View$PerformClick.run(View.java:18778)
at android.os.Handler.handleCallback(Handler.java:808)
at android.os.Handler.dispatchMessage(Handler.java:103)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:5345)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:828)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:644)
at dalvik.system.NativeStart.main(Native Method)
Now I get it after years.I would have simply used.
FLAG_ACTIVITY_CLEAR_TOPĀ - If set, and the activity being launched is already running in the current task, then instead of launching a new instance of that activity, all of the other activities on top of it will be closed and this Intent will be delivered to the (now on top) old activity as a new Intent.
I used a listview to display the check boxes in my activity. I also put a check to see atleast one check box is checked otherwise it will toast a message asking the user to please select atleast one value. Below are my two classes. Problem which i am having is that when i press the submit button without selecting a check box then i get a message to select atleast one checkbox. But when i select and deselect the check box and then submit it then it goes to the next activity with value of the check box which i dont want. It should not go to the other activity till i select one checkbox. Please help me with this problem.
ConnectAdapter.java
package com.arcadian.adapter;
import java.util.ArrayList;
import android.content.Context;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.Toast;
import android.widget.CompoundButton.OnCheckedChangeListener;
import com.arcadian.genconian.R;
public class ConnectAdapter extends ArrayAdapter<ConnectModel> {
public ArrayList<ConnectModel> stateList;
Context cntx;
public static ConnectModel connect;
CheckBox cb;
public ConnectAdapter(Context context, int textViewResourceId,
ArrayList<ConnectModel> stateList) {
super(context, textViewResourceId, stateList);
this.cntx = context;
this.stateList = new ArrayList<ConnectModel>();
this.stateList.addAll(stateList);
}
public class ViewHolder {
CheckBox connect_CB;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
Log.v("ConvertView", String.valueOf(position));
if (convertView == null) {
LayoutInflater vi = (LayoutInflater) cntx
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = vi.inflate(R.layout.list_connect_row, null);
holder = new ViewHolder();
holder.connect_CB = (CheckBox) convertView
.findViewById(R.id.connect_CB);
convertView.setTag(holder);
holder.connect_CB
.setOnCheckedChangeListener(new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton v,
boolean isChecked) {
// TODO Auto-generated method stub
cb = (CheckBox) v;
if (v.isChecked()) {
connect = (ConnectModel) cb.getTag();
/*
* Toast.makeText( cntx.getApplicationContext(),
* "Checkbox: " + cb.getText() + " -> " +
* cb.isChecked(), Toast.LENGTH_LONG).show();
*/
connect.setSelected(cb.isChecked());
}
// else{
// Toast.makeText(getContext(), "Select aleast one.", Toast.LENGTH_LONG).show();
// String select = null;
// }
}
});
}
else {
holder = (ViewHolder) convertView.getTag();
}
ConnectModel state = stateList.get(position);
holder.connect_CB.setText(state.getName());
holder.connect_CB.setChecked(state.isSelected());
holder.connect_CB.setTag(state);
return convertView;
}
}
**ConnectActivity.java**
package com.arcadian.genconian;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;
import com.arcadian.adapter.ConnectAdapter;
import com.arcadian.adapter.ConnectModel;
import com.arcadian.utils.CommonActivity;
import com.arcadian.utils.Constants;
import com.arcadian.utils.JSONParser;
public class ConnectActivity extends CommonActivity implements OnClickListener {
ConnectAdapter dataAdapter = null;
ArrayList<ConnectModel> stateList;
private ProgressDialog pDialog;
String to_connect;
String response;
private StringBuffer responseText;
int success;
String email, type;
private String status;
String select;
ConnectModel _ConnectModel;
ConnectModel selstate;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_connect);
// Generate list View from ArrayList
displayListView();
responseText = new StringBuffer();
Button submit_BT = (Button) findViewById(R.id.submit_BT);
submit_BT.setOnClickListener(this);
Intent i = getIntent();
email = i.getStringExtra("user_email");
type = i.getStringExtra("type");
}
private void displayListView() {
// Array list of countries
stateList = new ArrayList<ConnectModel>();
_ConnectModel = new ConnectModel("All", false);
stateList.add(_ConnectModel);
_ConnectModel = new ConnectModel("Stream", false);
stateList.add(_ConnectModel);
_ConnectModel = new ConnectModel("Industry", false);
stateList.add(_ConnectModel);
_ConnectModel = new ConnectModel("Field", false);
stateList.add(_ConnectModel);
_ConnectModel = new ConnectModel("Batchmates", false);
stateList.add(_ConnectModel);
// create an ArrayAdaptar from the String Array
dataAdapter = new ConnectAdapter(this, android.R.layout.simple_list_item_multiple_choice,
stateList);
ListView to_connect_LV = (ListView) findViewById(R.id.to_connect_LV);
// Assign adapter to ListView
to_connect_LV.setAdapter(dataAdapter);
}
#Override
public void onClick(View v) {
int id = v.getId();
// openRequest.setCallback(statusCallback);
// session.openForRead(openRequest);
// loginProgress.setVisibility(View.VISIBLE);
switch (id) {
case R.id.submit_BT:
ArrayList<ConnectModel> stateList = dataAdapter.stateList;
response = "";
for (int i = 0; i < stateList.size(); i++) {
ConnectModel state = stateList.get(i);
selstate = ConnectAdapter.connect;
if(selstate!=null)
if (selstate.equals(state)) {
select = "abc";
if ((stateList.size() - 1) >= i) {
responseText.append(state.getName() + ",");
String text = state.getName();
response = responseText.toString();
loge("response", "response text is" + responseText);
}
else {
responseText.append(state.getName());
}
}
}
if (select == null) {
Toast.makeText(getApplicationContext(), "Select at least one.",
Toast.LENGTH_SHORT).show();
} else {
new Connect().execute();
}
/*
* if(response.length()>1) {
* if(response.substring(response.length()-1).equals(",") ) {
* response
* =response.replace(response.substring(response.length()-1), "" );
*
* }
*
* }
*
* if (response.length() <= 1) { response =
* "batch,stream,field,industry"; }
*/
break;
default:
break;
}
}
public class Connect extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(ConnectActivity.this);
pDialog.setMessage("Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected String doInBackground(String... params) {
to_connect = responseText.toString();
String connect_url = Constants.REMOTE_URL + "/GenconianApi/reg2";
log("to", "connect url is:" + connect_url);
try {
JSONParser jsonParser = new JSONParser();
List<NameValuePair> Params = new ArrayList<NameValuePair>();
String res;
Intent email_Intent = getIntent();
email = email_Intent.getStringExtra("user_email");
type = email_Intent.getStringExtra("type");
loge("email in", "connectactivity is:" + email);
int len = response.length();
StringBuilder builder = new StringBuilder();
for (int i = 0; i < len - 1; i++) {
builder.append(Character.toLowerCase(response.charAt(i)));
}
Params.add(new BasicNameValuePair("email", email));
Params.add(new BasicNameValuePair("connected", builder
.toString()));
Log.e("responce", builder.toString());
JSONObject json = jsonParser.makeHttpRequest(connect_url,
"POST", Params);
loge("in reg2", json.toString());
JSONObject obj = json.getJSONObject("Status");
loge("obj is", obj.toString());
status = obj.getString("status");
loge("user", "status is:" + status);
success = Integer.parseInt(status);
loge("chk", "rslt code is:" + success);
if (success == 1) {
Intent k = new Intent(ConnectActivity.this,
FindFriends.class);
loge("chk", "inside success:" + success);
k.putExtra("user_email", email);
k.putExtra("type", type);
overridePendingTransition(R.anim.slide_in, R.anim.slide_out);
startActivity(k);
loge("email", "" + email);
return json.getString(Constants.TAG_MESSAGE);
} else {
Log.e("Login Failure!",
json.getString(Constants.TAG_MESSAGE));
return json.getString(Constants.TAG_MESSAGE);
}
}
catch (JSONException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
pDialog.dismiss();
}
}
#Override
public void onBackPressed() {
// TODO Auto-generated method stub
super.onBackPressed();
Intent i = new Intent(ConnectActivity.this, More.class);
i.putExtra("user-email", email);
i.putExtra("type", type);
startActivity(i);
}
}
You can put all the checkboxes in a Collection of checkboxes.
Upon clicking submit button, loop through all checkboxes to see anyone of them is checked at that moment
Collection<CheckBox> boxes=new Vector<CheckBox>();
...
public void onClick(View v){
boolean anyoneChecked=false;
for(CheckBox b: boxes){
if(b.isChecked()){
anyoneChecked=true;
}
}
if(!anyoneChecked){
return;
}
// go to next activity
}
I have made an activity in that i have a listView and ,I have Implemeted a custom adapter for that ListView ,I have implemeted ListItem's textView's Clickevnet,In That I want to call my activity's AsyncTAk inside that customAdapter,CAn anybuddy tell me how can i do that? my code is as below:
main.java
package com.epe.yehki.ui;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Locale;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;
import com.epe.yehki.adapter.BuyingRequestAdapter;
import com.epe.yehki.backend.BackendAPIService;
import com.epe.yehki.uc.Header;
import com.epe.yehki.util.Const;
import com.epe.yehki.util.Pref;
import com.epe.yehki.util.Utils;
import com.example.yehki.R;
public class BuyingreqActivity extends Activity implements OnClickListener {
Button viewReq, postReq;
EditText productName;
TextView productCategory;
TextView expTime;
TextView productDesc;
TextView estOrderQty;
ImageView proImg;
Button send;
ImageView iv_fav_menu;
private int flag = 1;
ScrollView scr_post;
RelativeLayout scr_view;
RelativeLayout quote_view;
private ProgressDialog pDialog;
String viewURL, postURL;
JSONObject jsonObj;
JSONArray requestes = null;
JSONArray quotes = null;
ArrayList<HashMap<String, String>> reqList;
ArrayList<HashMap<String, String>> queList;
private BuyingRequestAdapter buyingRequestContent;
RelativeLayout rl_botm;
ListView lv;
Header header;
Calendar dateandtime;
private static final int PICK_FROM_CAMERA = 100;
private static final int PICK_FROM_GALLERY = 200;
private Uri picUri;
int la, lo;
final int CAMERA_CAPTURE = 1;
private static String fileName;
Intent in = null;
ListView quoteList;
private String imagePath;
private Uri imageUri;
String buyer_request_id, reqID;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_buying_request);
InitializeView();
productCategory.setOnClickListener(this);
send.setOnClickListener(this);
expTime.setOnClickListener(this);
proImg.setOnClickListener(this);
dateandtime = Calendar.getInstance(Locale.US);
header.back.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
finish();
}
});
reqList = new ArrayList<HashMap<String, String>>();
queList = new ArrayList<HashMap<String, String>>();
viewReq.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
flag = 2;
reqList.clear();
iv_fav_menu.setBackgroundResource(R.drawable.tab_two_fav);
new GetBuyingReqList().execute();
scr_view.setVisibility(View.VISIBLE);
quote_view.setVisibility(View.GONE);
rl_botm.setVisibility(View.GONE);
scr_post.setVisibility(View.GONE);
}
});
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// TODO Auto-generated method stub
in = new Intent(getApplicationContext(), BuyingRequestDetailActivity.class);
// getting ProductId from the tag...
reqID = reqList.get(position).get(Const.TAG_BUYING_REQUEST_ID);
System.out.println(":::::::::::::::;;THE INTENT FOR THE resuest DETIALS ACTIVITY=================" + reqID);
in.putExtra(Const.TAG_BUYING_REQUEST_ID, reqID);
startActivity(in);
}
});
postReq.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
flag = 1;
iv_fav_menu.setBackgroundResource(R.drawable.tab_one_fav);
quote_view.setVisibility(View.GONE);
scr_post.setVisibility(View.VISIBLE);
rl_botm.setVisibility(View.VISIBLE);
scr_view.setVisibility(View.GONE);
}
});
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.tv_pro_cat:
break;
case R.id.tv_pro_exp_tym:
DatePickerDailog dp = new DatePickerDailog(BuyingreqActivity.this, dateandtime, new DatePickerDailog.DatePickerListner() {
#Override
public void OnDoneButton(Dialog datedialog, Calendar c) {
datedialog.dismiss();
dateandtime.set(Calendar.YEAR, c.get(Calendar.YEAR));
dateandtime.set(Calendar.MONTH, c.get(Calendar.MONTH));
dateandtime.set(Calendar.DAY_OF_MONTH, c.get(Calendar.DAY_OF_MONTH));
expTime.setText(new SimpleDateFormat("yyyy-MM-dd").format(c.getTime()));
}
#Override
public void OnCancelButton(Dialog datedialog) {
// TODO Auto-generated method stub
datedialog.dismiss();
}
});
dp.show();
break;
case R.id.btn_send:
new postBuyingReqList().execute();
break;
case R.id.iv_img:
showCustomeAlert2(BuyingreqActivity.this, "Yehki", "From Camera", "From Gallery");
break;
}
}
#SuppressWarnings("deprecation")
private void showCustomeAlert2(Context context, String title, String rightButton, String leftButton) {
final Dialog dialog = new Dialog(BuyingreqActivity.this);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.getWindow().setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT));
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
dialog.getWindow().setLayout(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
dialog.setContentView(R.layout.popup_alert);
dialog.setCancelable(false);
final ImageView btn_lft = (ImageView) dialog.findViewById(R.id.iv_left);
final ImageView btn_rgt = (ImageView) dialog.findViewById(R.id.iv_right);
final Button cancel = (Button) dialog.findViewById(R.id.btn_cancle);
final TextView btn_left = (TextView) dialog.findViewById(R.id.btnLeft);
final TextView btn_right = (TextView) dialog.findViewById(R.id.btnRight);
btn_left.setText(leftButton);
btn_right.setText(rightButton);
cancel.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
dialog.dismiss();
}
});
btn_rgt.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
try {
System.out.println("=========== perform click ==============");
String mediaStorageDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).getPath();
fileName = "user_" + Pref.getValue(BuyingreqActivity.this, Const.PREF_USER_ID, 0) + "_" + System.currentTimeMillis() + ".png";
imageUri = Uri.fromFile(new File(Const.DIR_USER + "/" + fileName));
System.out.println(" PATH ::: " + imageUri);
Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
startActivityForResult(cameraIntent, CAMERA_CAPTURE);
} catch (ActivityNotFoundException anfe) {
String errorMessage = "Whoops - your device doesn't support capturing images!";
}
dialog.dismiss();
}
});
btn_lft.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent();
// call android default gallery
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
// ******** code for crop image
intent.putExtra("crop", "true");
intent.putExtra("aspectX", 0);
intent.putExtra("aspectY", 0);
intent.putExtra("outputX", 200);
intent.putExtra("outputY", 200);
try {
intent.putExtra("return-data", true);
startActivityForResult(Intent.createChooser(intent, "Complete action using"), PICK_FROM_GALLERY);
} catch (ActivityNotFoundException e) {
e.printStackTrace();
}
dialog.dismiss();
}
});
dialog.show();
}
void InitializeView() {
iv_fav_menu = (ImageView) findViewById(R.id.iv_fav_menu);
viewReq = (Button) findViewById(R.id.btn_view);
postReq = (Button) findViewById(R.id.btn_post);
scr_post = (ScrollView) findViewById(R.id.scr_post);
scr_view = (RelativeLayout) findViewById(R.id.scr_view);
quote_view = (RelativeLayout) findViewById(R.id.quote_view);
lv = (ListView) findViewById(R.id.req_list);
rl_botm = (RelativeLayout) findViewById(R.id.rl_botm);
header = (Header) findViewById(R.id.headerBuying);
header.title.setText("Post Buying Request");
proImg = (ImageView) findViewById(R.id.iv_img);
quoteList = (ListView) findViewById(R.id.quote_list);
productName = (EditText) findViewById(R.id.et_pro_name);
productCategory = (TextView) findViewById(R.id.tv_pro_cat);
expTime = (TextView) findViewById(R.id.tv_pro_exp_tym);
productDesc = (EditText) findViewById(R.id.et_pro_desc);
estOrderQty = (TextView) findViewById(R.id.et_est_qty);
send = (Button) findViewById(R.id.btn_send);
}
/*
* getting buying request list...!!!
*/
private class GetBuyingReqList extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(BuyingreqActivity.this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
String query = "?customer_id=" + Pref.getValue(BuyingreqActivity.this, Const.PREF_CUSTOMER_ID, "");
query = query.replace(" ", "%20");
viewURL = Const.API_BUYING_REQUEST_LIST + query;
BackendAPIService sh = new BackendAPIService();
System.out.println(":::::::::::::::::::ADDRESS URL:::::::::::::::::" + viewURL);
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(viewURL, BackendAPIService.GET);
Log.d("Response: ", "> " + jsonStr);
try {
if (jsonStr != null) {
jsonObj = new JSONObject(jsonStr);
if (jsonObj.has(Const.TAG_BUYING_REQUEST)) {
System.out.println("::::::::::::::::true::::::::::::::::" + jsonObj.has(Const.TAG_ADDRESS_LIST));
requestes = jsonObj.getJSONArray(Const.TAG_BUYING_REQUEST);
if (requestes != null && requestes.length() != 0) {
// looping through All Contacts
System.out.println(":::::::::::FLAG IN SUB:::::::::::" + flag);
for (int i = 0; i < requestes.length(); i++) {
JSONObject c = requestes.getJSONObject(i);
buyer_request_id = c.getString(Const.TAG_BUYING_REQUEST_ID);
System.out.println(":::::::::::::::MY buying request:::::::::::::" + buyer_request_id);
String subject = c.getString(Const.TAG_PRODUCT_NAME);
String date_modified = c.getString(Const.TAG_DATE_MODIFIED);
String expired_date = c.getString(Const.TAG_EXPIRY_DATE);
String quote_count = c.getString(Const.TAG_QUOTE_COUNT);
String buying_request_status = c.getString(Const.TAG_BUYING_REQUEST_STATUS);
HashMap<String, String> request = new HashMap<String, String>();
request.put(Const.TAG_BUYING_REQUEST_ID, buyer_request_id);
request.put(Const.TAG_PRODUCT_NAME, subject);
request.put(Const.TAG_DATE_MODIFIED, date_modified);
request.put(Const.TAG_EXPIRY_DATE, expired_date);
request.put(Const.TAG_QUOTE_COUNT, quote_count);
request.put(Const.TAG_BUYING_REQUEST_STATUS, buying_request_status);
reqList.add(request);
System.out.println("::::::::::::::::Is filled:::::::::::" + reqList.size());
}
}
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
} catch (JSONException e) {
e.printStackTrace();
System.out.println("::::::::::::::::::got an error::::::::::::");
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// Dismiss the progress dialog
if (pDialog.isShowing())
pDialog.dismiss();
/**
* Updating parsed JSON data into ListView
*
* */
buyingRequestContent = new BuyingRequestAdapter(BuyingreqActivity.this, reqList);
lv.setAdapter(buyingRequestContent);
}
}
/*
* getting qoute List...!!!
*/
public class GetQuoteList extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(BuyingreqActivity.this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
String query = "?customer_id=" + Pref.getValue(BuyingreqActivity.this, Const.PREF_CUSTOMER_ID, "") + "&buyer_request_id=" + reqID;
query = query.replace(" ", "%20");
viewURL = Const.API_QUOTE_RECIEVED + query;
BackendAPIService sh = new BackendAPIService();
System.out.println(":::::::::::::::::::ADDRESS URL:::::::::::::::::" + viewURL);
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(viewURL, BackendAPIService.GET);
Log.d("Response: ", "> " + jsonStr);
try {
if (jsonStr != null) {
jsonObj = new JSONObject(jsonStr);
if (jsonObj.has(Const.TAG_BUYING_REQUEST)) {
System.out.println("::::::::::::::::true::::::::::::::::" + jsonObj.has(Const.TAG_ADDRESS_LIST));
requestes = jsonObj.getJSONArray(Const.TAG_BUYING_REQUEST);
if (requestes != null && requestes.length() != 0) {
// looping through All Contacts
System.out.println(":::::::::::FLAG IN SUB:::::::::::" + flag);
for (int i = 0; i < requestes.length(); i++) {
JSONObject c = requestes.getJSONObject(i);
buyer_request_id = c.getString(Const.TAG_BUYING_REQUEST_ID);
System.out.println(":::::::::::::::MY buying request:::::::::::::" + buyer_request_id);
String product_name = c.getString(Const.TAG_PRODUCT_NAME);
String quote_id = c.getString(Const.TAG_QUOTE_ID);
String supplier_name = c.getString(Const.TAG_SUPPLIER_NAME);
String status = c.getString(Const.TAG_STATUS);
HashMap<String, String> quote = new HashMap<String, String>();
quote.put(Const.TAG_BUYING_REQUEST_ID, buyer_request_id);
quote.put(Const.TAG_PRODUCT_NAME, product_name);
quote.put(Const.TAG_QUOTE_ID, quote_id);
quote.put(Const.TAG_EXPIRY_DATE, supplier_name);
quote.put(Const.TAG_QUOTE_COUNT, status);
reqList.add(quote);
System.out.println("::::::::::::::::Is filled:::::::::::" + reqList.size());
}
}
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
} catch (JSONException e) {
e.printStackTrace();
System.out.println("::::::::::::::::::got an error::::::::::::");
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// Dismiss the progress dialog
if (pDialog.isShowing())
pDialog.dismiss();
/**
* Updating parsed JSON data into ListView
*
* */
buyingRequestContent = new BuyingRequestAdapter(BuyingreqActivity.this, reqList);
lv.setAdapter(buyingRequestContent);
}
}
/*
* post Buying Request api()...!!!
*/
private class postBuyingReqList extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(BuyingreqActivity.this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
postURL = Const.API_BUYING_REQUEST + "?customer_id=" + Pref.getValue(BuyingreqActivity.this, Const.PREF_CUSTOMER_ID, "") + "&product_name=" + productName.getText().toString().trim()
+ "&category_id=1&expire_time=" + expTime.getText().toString() + "&detail_desc=" + productDesc.getText().toString().trim() + "&esti_ordr_qty="
+ estOrderQty.getText().toString().trim() + "&esti_ordr_qty_unit=1&filename=abc.jpg&image=abc.png";
// Creating service handler class instance
postURL = postURL.replace(" ", "%20");
BackendAPIService sh = new BackendAPIService();
System.out.println(":::::::::::::::::::post buying request URL:::::::::::::::::" + postURL);
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(postURL, BackendAPIService.POST);
Log.d("Response: ", "> " + jsonStr);
try {
if (jsonStr != null) {
jsonObj = new JSONObject(jsonStr);
if (jsonObj.get("status").equals("success")) {
flag = 0;
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
} catch (JSONException e) {
e.printStackTrace();
System.out.println("::::::::::::::::::got an error::::::::::::");
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
Intent i;
// Dismiss the progress dialog
if (pDialog.isShowing())
pDialog.dismiss();
if (flag == 0) {
Utils.showCustomeAlertValidation(BuyingreqActivity.this, "Request Posted", "Yehki", "OK");
clearViews();
} else {
Toast.makeText(BuyingreqActivity.this, "Buying Request has not been posted", 0).show();
}
/**
* Updating parsed JSON data into ListView
*
* */
}
}
void clearViews() {
productName.setText("");
productDesc.setText("");
estOrderQty.setText("");
expTime.setText("Expiration Time");
proImg.setImageResource(R.drawable.noimage);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == CAMERA_CAPTURE) { // for camera
try {
System.out.println("============= FILENAME :: " + fileName);
if (new File(Const.DIR_USER + "/" + fileName).exists()) {
performCrop();
}
} catch (Exception e) {
e.printStackTrace();
}
} else if (requestCode == 2) { // for crop image
try {
if (data != null) {
Bundle extras = data.getExtras();
Bitmap thePic = extras.getParcelable("data");
Utils.createDirectoryAndSaveFile(thePic, Const.DIR_USER + "/" + fileName);
// pro_pic.setImageBitmap(thePic);
#SuppressWarnings("deprecation")
Drawable dra = (Drawable) new BitmapDrawable(thePic);
proImg.setImageDrawable(dra);
proImg.setScaleType(ScaleType.FIT_XY);
}
} catch (Exception e) {
e.printStackTrace();
}
} else if (requestCode == PICK_FROM_GALLERY && resultCode == RESULT_OK) {
if (data != null) {
/*
* fileName = Const.DIR_USER + "/" + "user_" +
* Pref.getValue(ProfileActivity.this, Const.PREF_USER_ID, 0) +
* "_" + System.currentTimeMillis() + ".png";
*/
fileName = "user_" + Pref.getValue(BuyingreqActivity.this, Const.PREF_USER_ID, 0) + "_" + System.currentTimeMillis() + ".png";
Bundle extras2 = data.getExtras();
Bitmap photo = extras2.getParcelable("data");
Utils.createDirectoryAndSaveFile(photo, Const.DIR_USER + "/" + fileName);
ImageView picView = (ImageView) findViewById(R.id.iv_img);
picView.setImageBitmap(photo);
}
}
}
private void performCrop() {
try {
System.out.println("============= AFTER FILENAME :: " + fileName);
Intent cropIntent = new Intent("com.android.camera.action.CROP");
imageUri = Uri.fromFile(new File(Const.DIR_USER + "/" + fileName));
cropIntent.setDataAndType(imageUri, "image/*");
cropIntent.putExtra("crop", "true");
cropIntent.putExtra("aspectX", 1);
cropIntent.putExtra("aspectY", 1);
cropIntent.putExtra("outputX", 200);// 256
cropIntent.putExtra("outputY", 200);
cropIntent.putExtra("return-data", true);
startActivityForResult(cropIntent, 2);
}
catch (ActivityNotFoundException anfe) {
String errorMessage = "Whoops - your device doesn't support the crop action!";
Toast toast = Toast.makeText(this, errorMessage, Toast.LENGTH_SHORT);
toast.show();
}
}
}
adapter.java
package com.epe.yehki.adapter;
import java.util.ArrayList;
import java.util.HashMap;
import android.content.Context;
import android.graphics.Color;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
import com.epe.yehki.ui.BuyingreqActivity;
import com.epe.yehki.ui.BuyingreqActivity.GetQuoteList;
import com.epe.yehki.util.Const;
import com.example.yehki.R;
public class BuyingRequestAdapter extends BaseAdapter {
public ArrayList<HashMap<String, String>> BuyingRequestArray;
private Context mContext;
public BuyingRequestAdapter(Context paramContext, ArrayList<HashMap<String, String>> productList) {
this.mContext = paramContext;
this.BuyingRequestArray = productList;
}
public int getCount() {
return this.BuyingRequestArray.size();
}
public Object getItem(int paramInt) {
return Integer.valueOf(paramInt);
}
public long getItemId(int paramInt) {
return paramInt;
}
#SuppressWarnings("static-access")
public View getView(int paramInt, View paramView, ViewGroup paramViewGroup) {
LayoutInflater localLayoutInflater = (LayoutInflater) this.mContext.getSystemService("layout_inflater");
Viewholder localViewholder = null;
if (paramView == null) {
paramView = localLayoutInflater.inflate(R.layout.raw_buying_req, paramViewGroup, false);
localViewholder = new Viewholder();
localViewholder.sub = ((TextView) paramView.findViewById(R.id.sub));
localViewholder.expDate = ((TextView) paramView.findViewById(R.id.exp_date));
localViewholder.quote = ((TextView) paramView.findViewById(R.id.quote));
localViewholder.status = ((TextView) paramView.findViewById(R.id.status));
localViewholder.lastUpdate = ((TextView) paramView.findViewById(R.id.last_updated));
paramView.setTag(localViewholder);
} else {
localViewholder = new Viewholder();
localViewholder = (Viewholder) paramView.getTag();
}
System.out.println(":::::::::::::::values:::::::::::::::" + BuyingRequestArray.get(paramInt).get(Const.TAG_PRODUCT_NAME));
localViewholder.sub.setText(BuyingRequestArray.get(paramInt).get(Const.TAG_PRODUCT_NAME));
localViewholder.expDate.setText(BuyingRequestArray.get(paramInt).get(Const.TAG_EXPIRY_DATE));
localViewholder.lastUpdate.setText(BuyingRequestArray.get(paramInt).get(Const.TAG_DATE_MODIFIED));
localViewholder.quote.setText(BuyingRequestArray.get(paramInt).get(Const.TAG_QUOTE_COUNT));
localViewholder.quote.setTextColor(Color.parseColor("#0000ff"));
localViewholder.status.setText(BuyingRequestArray.get(paramInt).get(Const.TAG_BUYING_REQUEST_STATUS));
localViewholder.quote.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
/*
* HERE I WANT TO CALL "GETqUOTElIST" ASYNCTASK OF MY ACTIVITY/////!!!!!!!
*/
}
});
return paramView;
}
static class Viewholder {
TextView sub;
TextView lastUpdate;
TextView expDate;
TextView quote;
TextView status;
}
}
This might not be the correct approach of coding ,where in you have all the asyncs in one activity.
But to achieve what you want you can use the context that you pass in the adapter like this:
((YourActivityYouArePassing)mContext).someMethod();
the activity's context must be the same as the one you are using for type casting, and someMethod() should be a method declared inside the activity with public keyword.
in someMethod() you could then call your async task like:
public void someMethod() {
new AsyncClass().execute();
}
EDIT:
The onClick will look like this in the adapter
localViewholder.quote.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
/*
* HERE I WANT TO CALL "GETqUOTElIST" ASYNCTASK OF MY ACTIVITY/////!!!!!!!
*/
((YourActivityYouArePassing)mContext).someMethod();
}
});
Hope that helps!!
You can call async task on text click inside Custom adapter
localViewholder.quote.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
new GetBuyingReqList.execute();
}
});
and make GetBuyingReqList class private to public
put below code where u want
GetBuyingReqList getBuyingReqList = new GetBuyingReqList ();
getBuyingReqList .execute();
Possible duplicate How to Call AsyncTask from Adapter class?
found these answers
move your adapter class inside your activity class and make adapter class as inner class.so you have access for calling Asynctask in adapter
Remove AsyncTask Inner class from activity class and Make AsyncTask as a separate class (put it in your package). After that you can call like this "new Asynctask().execute();" from any where
what i did... i sent an instance of the activity to the adapter while initializing, then i called a method at the activity by activity.method() and this method calls the AsyncTask
I am writing an Android application that essentially parses XML data using Fwix's API. The parsing part is working fine. Here's my class, Parser:
package com.magadistudio_student_connect_2011.com;
import java.net.URL;
import java.util.ArrayList;
import org.xmlpull.v1.XmlPullParser;
import android.content.res.XmlResourceParser;
import android.util.Xml;
public class Parser {
//Feed Parsing Method
public ArrayList<Bakery> parse(String url) {
//Array of Episode Objects
ArrayList<Bakery> bakeries = null;
try {
//Encode the URL into a URL Object
URL bakery_feed_url = new URL(url);
//Open a Connection to the feed
XmlPullParser parser = Xml.newPullParser();
try {
parser.setInput(bakery_feed_url.openConnection().getInputStream(), null);
}
finally {
}
int event_type = parser.getEventType();
Bakery current_bakery = null;
boolean done = false;
//Parse the feed, start reading throughout the feed from top to bottom
while (event_type != XmlResourceParser.END_DOCUMENT && !done) {
String tag_name = null;
switch (event_type) {
//Found the start of the feed
case XmlResourceParser.START_DOCUMENT:
bakeries = new ArrayList<Bakery>();
break;
//Found a start tag
case XmlResourceParser.START_TAG:
//apply the data to our Episode object based on the tag name
tag_name = parser.getName();
if (tag_name.equalsIgnoreCase("place")) {
current_bakery = new Bakery();
}
else if(current_bakery != null) {
if (tag_name.equalsIgnoreCase("phone_number")){
current_bakery.setPhone(parser.nextText());
}else if(tag_name.equalsIgnoreCase("city")){
current_bakery.setCity(parser.nextText());
}else if(tag_name.equalsIgnoreCase("province")){
current_bakery.setState(parser.nextText());
}else if(tag_name.equalsIgnoreCase("address")){
current_bakery.setAddress(parser.nextText());
}else if(tag_name.equalsIgnoreCase("lat")){
current_bakery.setLatitude(parser.nextText());
//lat = Integer.parseInt(parser.getAttributeValue(null,"lat"));
}else if(tag_name.equalsIgnoreCase("postal_code")){
current_bakery.setZip(parser.nextText());
}else if(tag_name.equalsIgnoreCase("lng")){
current_bakery.setLongitude(parser.nextText());
//lon = Integer.parseInt(parser.getAttributeValue(null,"lng"));
}else if(tag_name.equalsIgnoreCase("name")){
current_bakery.setPlace_name(parser.nextText());
}
}
break;
//An end tag has been reached
case XmlResourceParser.END_TAG:
tag_name = parser.getName();
//End of an Episode Item
if (tag_name.equalsIgnoreCase("place") && current_bakery != null) {
bakeries.add(current_bakery);
//Reached the end of all bakeries, no more data to collect
}
else if (tag_name.equalsIgnoreCase("places")){
done = true;
}
break;
}
event_type = parser.next();
}
}
catch (Exception e) {
throw new RuntimeException(e);
}
//Return the Episode Array
return bakeries;
}
}
And here is my overlay class, Overlay:
package com.magadistudio_student_connect_2011.com;
import java.util.ArrayList;
import android.app.AlertDialog;
import android.content.Context;
import android.graphics.drawable.Drawable;
import android.widget.Toast;
import com.google.android.maps.ItemizedOverlay;
import com.google.android.maps.OverlayItem;
public class StudentItemizedOverlay extends ItemizedOverlay<OverlayItem> {
private ArrayList<OverlayItem> mOverlays = new ArrayList<OverlayItem>();
private Context mContext;
public StudentItemizedOverlay(Drawable defaultMarker) {
super(boundCenterBottom(defaultMarker));
// TODO Auto-generated constructor stub
}
public void addOverlay(OverlayItem overlay) {
mOverlays.add(overlay);
populate();
}
#Override
protected OverlayItem createItem(int i) {
return mOverlays.get(i);
}
#Override
public int size() {
// TODO Auto-generated method stub
return mOverlays.size();
}
public StudentItemizedOverlay(Drawable defaultMarker, Context context){
super(boundCenterBottom(defaultMarker));
mContext = context;
}
#Override
protected boolean onTap(int index) {
OverlayItem item = mOverlays.get(index);
// Toast.makeText(StudentItemizedOverlay.this, "Hello", Toast.LENGTH_LONG).show();
AlertDialog.Builder dialog = new AlertDialog.Builder(mContext);
dialog.setTitle(item.getTitle());
dialog.setMessage(item.getSnippet());
dialog.show();
return true;
}
}
And here is class BakeryActivity:
package com.magadistudio_student_connect_2011.com;
import java.util.ArrayList;
import android.app.Activity;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.Toast;
public class BakeryActivity extends Activity implements OnItemClickListener {
//RSS Feed URL
private final String CGR_FEED_URL = "http://www.codinggreenrobots.com/episodes/rss.xml";
//xml new feed
private final String SCHOOLS_URL = "http://www.fizber.com/xml_data/xml_school_data.xml?state=wa&city=spokane";
private final String BAKERY_RSS = "apigoeshere";
//XML Widgets
private ListView listview_bakery;
private ProgressBar progress_bar;
//Arrays of Episode Data
private ArrayList<String> bakery_name;
private ArrayList<String> bakery_address;
private ArrayList<String> bakery_phone;
private ArrayList<String> bakery_latitude;
private ArrayList<String> bakery_longitude;
private ArrayList<String> bakery_state;
private ArrayList<String> bakery_zip;
private ArrayList<String> bakery_city;
/*private ArrayList<String> school_latitude;
private ArrayList<String> school_longitude;
*/
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.bakery_view);
//XML Widgets by ID
listview_bakery = (ListView) findViewById(R.id.listview_bakeries);
listview_bakery.setOnItemClickListener(this);
/* ColorDrawable sage = new ColorDrawable(this.getResources().getColor(R.drawable.colors));
listview_bakery.setDivider(sage);
listview_bakery.setDividerHeight(1);*/
progress_bar = (ProgressBar) findViewById(R.id.progress_bar_bakery);
//Make Progress Bar Invisible
progress_bar.setVisibility(ProgressBar.INVISIBLE);
//Initialize Arrays
bakery_name = new ArrayList<String>();
bakery_address = new ArrayList<String>();
bakery_phone = new ArrayList<String>();
bakery_latitude = new ArrayList<String>();
bakery_longitude = new ArrayList<String>();
bakery_state = new ArrayList<String>();
bakery_zip = new ArrayList<String>();
bakery_city = new ArrayList<String>();
//school_latitude = new ArrayList<String>();
//school_longitude = new ArrayList<String>();
downloadBakeries(BAKERY_RSS);
}
private void downloadBakeries(String Url) {
//Make Progress Bar Visible While Downloading Feed
progress_bar.setVisibility(ProgressBar.VISIBLE);
Log.d("CGRParser", "Downloading Feed");
//Start an ASync Thread to take care of Downloading Feed
new DownloadBakeries().execute(Url);
}
private class DownloadBakeries extends AsyncTask<String, Integer, ArrayList<Bakery>> {
#Override
protected ArrayList<Bakery> doInBackground(String... url) {
//Download and Parse Feed
Parser parser = new Parser();
ArrayList<Bakery> bakeries = new ArrayList<Bakery>();
bakeries = parser.parse(url[0]);
return bakeries;
}
#Override
protected void onPostExecute(ArrayList<Bakery> result) {
//Feed has been Downloaded and Parsed, Display Data to User
Log.d("CGRParser", "Feed Download Complete");
//Toast.makeText(BakeryActivity.this, "onPost", Toast.LENGTH_SHORT).show();
displayBakeries(result);
}
}
private void displayBakeries(ArrayList<Bakery> bakeries) {
//Create String Arrays to seperate titles and dates
Log.d("CGRParser", "Displaying Episode Titles To User");
ArrayList<String> bakery_name = new ArrayList<String>();
ArrayList<String> bakery_address = new ArrayList<String>();
ArrayList<String> bakery_phone = new ArrayList<String>();
ArrayList<String> bakery_latitude = new ArrayList<String>();
ArrayList<String> bakery_longitude = new ArrayList<String>();
ArrayList<String> bakery_state = new ArrayList<String>();
ArrayList<String> bakery_zip = new ArrayList<String>();
ArrayList<String> bakery_city = new ArrayList<String>();
//ArrayList<String> school_longitude = new ArrayList<String>();
for (Bakery bakery : bakeries) {
//Log.d("CGRParser", "Episode Title: " + episode.getTitle());
bakery_phone.add(bakery.getPhone());
bakery_name.add(bakery.getPlace_name());
bakery_address.add(bakery.getAddress());
bakery_latitude.add(bakery.getLatitude());
bakery_longitude.add(bakery.getLongitude());
bakery_state.add(bakery.getState());
bakery_zip.add(bakery.getZip());
bakery_city.add(bakery.getCity());
//school_longitude.add(episode.getLongitude());
}
//Toast.makeText(BakeryActivity.this, "DisplayBakeries", Toast.LENGTH_SHORT).show();
this.bakery_phone = bakery_phone;
this.bakery_name = bakery_name;
this.bakery_address = bakery_address;
this.bakery_latitude = bakery_latitude;
this.bakery_longitude = bakery_longitude;
this.bakery_state = bakery_state;
this.bakery_zip = bakery_zip;
this.bakery_city = bakery_city;
//int myNum = 0; try { myNum = Integer.parseInt(bakery_latitude.getText().toString()); } catch(NumberFormatException nfe) { System.out.println("Could not parse " + nfe); }
//Create a ListAdapter to Display the Titles in the ListView
ListAdapter adapter = new ArrayAdapter<String>(this, R.layout.bakery_row, R.id.title, bakery_name);
listview_bakery.setAdapter(adapter);
//Set Progress Bar Invisible since we are done with it
progress_bar.setVisibility(ProgressBar.INVISIBLE);
}
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
startActivity(new Intent(BakeryActivity.this, Map.class));
//Display the Title and Date to the user when they click on an episode
Toast.makeText(this, "Name:" + bakery_name.get(position) + "\nphone: " + bakery_phone.get(position)+
"\nState: "+ bakery_state.get(position) + "\nAddress: "+ bakery_address.get(position)
+ "\nZip: "+ bakery_zip.get(position)+ "\nLat: " +bakery_latitude.get(position)+ "\nlon: "+ bakery_longitude.get(position), Toast.LENGTH_LONG).show();
}
}
I am able to do the XML parsing work fine, but THE PROBLEM is I can't figure out how to get the "lat" and "lng" that I have parsed (and put then into an ArrayList of Strings) and convert them into integers so I can show markers of the respective latitude and longitude location on the map.
OK, so Android's Google Maps native location API uses integers with 6 digits following the decimal point. Therefore, you want to remove the "." from the strings of integers you parsed out. Then, simply do a parseInt to attain the coordinates. With that, drop them into GeoPoints and add them to the overlay. It should be no problem.
Unless I'm missing something here, which is possible.