Null Pointer Exception in Android using List - android

I have following activities to load products from backend. Its a online food ordering with integration of paypal. I tried it in another app its working fine.
I am getting Error on onCreate Method.
There are three activities Item list , Product and product list adapter. I am getting error while loading view. When i commented the lines of adapter its not crashing but after adding the adapters its crashing . Its driving me crazy.
import com.flavorbaba.AppController;
import com.flavorbaba.Config;
import com.flavorbaba.Product;
import com.flavorbaba.ProductListAdapter;
import com.flavorbaba.ProductListAdapter.ProductListAdapterListener;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;
import com.android.volley.DefaultRetryPolicy;
import com.android.volley.Request.Method;
import com.android.volley.Response;
import com.android.volley.RetryPolicy;
import com.android.volley.VolleyError;
import com.android.volley.VolleyLog;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.StringRequest;
import com.paypal.android.sdk.payments.PayPalConfiguration;
import com.paypal.android.sdk.payments.PayPalItem;
import com.paypal.android.sdk.payments.PayPalPayment;
import com.paypal.android.sdk.payments.PayPalPaymentDetails;
import com.paypal.android.sdk.payments.PayPalService;
import com.paypal.android.sdk.payments.PaymentActivity;
import com.paypal.android.sdk.payments.PaymentConfirmation;
public class ItemsList extends Activity implements ProductListAdapterListener {
private static final String TAG = ItemsList.class.getSimpleName();
private ListView listView;
private Button btnCheckout;
// To store all the products
private List<Product> productsList;
// To store the products those are added to cart
private List<PayPalItem> productsInCart = new ArrayList<PayPalItem>();
private ProductListAdapter adapter;
// Progress dialog
private ProgressDialog pDialog;
private static final int REQUEST_CODE_PAYMENT = 1;
// PayPal configuration
private static PayPalConfiguration paypalConfig = new PayPalConfiguration()
.environment(Config.PAYPAL_ENVIRONMENT).clientId(
Config.PAYPAL_CLIENT_ID);
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.food_menu);
listView = (ListView) findViewById(R.id.list);
btnCheckout = (Button) findViewById(R.id.checkout);
productsList = new ArrayList<Product>();
adapter = new ProductListAdapter(ItemsList.this, productsList, this);
pDialog = new ProgressDialog(this);
pDialog.setCancelable(false);
// Starting PayPal service
Intent intent = new Intent(this, PayPalService.class);
intent.putExtra(PayPalService.EXTRA_PAYPAL_CONFIGURATION, paypalConfig);
startService(intent);
// Checkout button click listener
btnCheckout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Check for empty cart
if (productsInCart.size() > 0) {
launchPayPalPayment();
} else {
Toast.makeText(getApplicationContext(),
"Cart is empty! Please add few products to cart.",
Toast.LENGTH_SHORT).show();
}
}
});
// Fetching products from server
fetchProducts();
}
/**
* Fetching the products from our server
* */
private void fetchProducts() {
// Showing progress dialog before making request
pDialog.setMessage("Fetching products...");
showpDialog();
// Making json object request
JsonObjectRequest jsonObjReq = new JsonObjectRequest(Method.GET,
Config.URL_PRODUCTS, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d(TAG, response.toString());
try {
JSONArray products = response
.getJSONArray("products");
// looping through all product nodes and storing
// them in array list
for (int i = 0; i < products.length(); i++) {
JSONObject product = (JSONObject) products
.get(i);
String id = product.getString("p_id");
String name = product.getString("p_name");
String description = product
.getString("p_desc");
String image = product.getString("p_image");
BigDecimal price = new BigDecimal(product
.getString("p_price"));
String sku = product.getString("p_status");
Product p = new Product(id, name, description,
image, price, sku);
productsList.add(p);
}
listView.setAdapter(adapter);
// notifying adapter about data changes, so that the
// list renders with new data
adapter.notifyDataSetChanged();
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(),
"Error: " + e.getMessage(),
Toast.LENGTH_LONG).show();
}
// hiding the progress dialog
hidepDialog();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
Toast.makeText(getApplicationContext(),
error.getMessage(), Toast.LENGTH_SHORT).show();
// hide the progress dialog
hidepDialog();
}
});
// Adding request to request queue
AppController.getInstance().addToRequestQueue(jsonObjReq);
}
/**
* Verifying the mobile payment on the server to avoid fraudulent payment
* */
private void verifyPaymentOnServer(final String paymentId,
final String payment_client) {
// Showing progress dialog before making request
pDialog.setMessage("Verifying payment...");
showpDialog();
StringRequest verifyReq = new StringRequest(Method.POST,
Config.URL_VERIFY_PAYMENT, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d(TAG, "verify payment: " + response.toString());
try {
JSONObject res = new JSONObject(response);
boolean error = res.getBoolean("error");
String message = res.getString("message");
// user error boolean flag to check for errors
Toast.makeText(getApplicationContext(), message,
Toast.LENGTH_SHORT).show();
if (!error) {
// empty the cart
productsInCart.clear();
}
} catch (JSONException e) {
e.printStackTrace();
}
// hiding the progress dialog
hidepDialog();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, "Verify Error: " + error.getMessage());
Toast.makeText(getApplicationContext(),
error.getMessage(), Toast.LENGTH_SHORT).show();
// hiding the progress dialog
hidepDialog();
}
}) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("paymentId", paymentId);
params.put("paymentClientJson", payment_client);
return params;
}
};
// Setting timeout to volley request as verification request takes
// sometime
int socketTimeout = 60000;
RetryPolicy policy = new DefaultRetryPolicy(socketTimeout,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT);
verifyReq.setRetryPolicy(policy);
// Adding request to request queue
AppController.getInstance().addToRequestQueue(verifyReq);
}
/**
* Preparing final cart amount that needs to be sent to PayPal for payment
* */
private PayPalPayment prepareFinalCart() {
PayPalItem[] items = new PayPalItem[productsInCart.size()];
items = productsInCart.toArray(items);
// Total amount
BigDecimal subtotal = PayPalItem.getItemTotal(items);
// If you have shipping cost, add it here
BigDecimal shipping = new BigDecimal("0.0");
// If you have tax, add it here
BigDecimal tax = new BigDecimal("0.0");
PayPalPaymentDetails paymentDetails = new PayPalPaymentDetails(
shipping, subtotal, tax);
BigDecimal amount = subtotal.add(shipping).add(tax);
PayPalPayment payment = new PayPalPayment(
amount,
Config.DEFAULT_CURRENCY,
"Description about transaction. This will be displayed to the user.",
Config.PAYMENT_INTENT);
payment.items(items).paymentDetails(paymentDetails);
// Custom field like invoice_number etc.,
payment.custom("This is text that will be associated with the payment that the app can use.");
return payment;
}
/**
* Launching PalPay payment activity to complete the payment
* */
private void launchPayPalPayment() {
PayPalPayment thingsToBuy = prepareFinalCart();
Intent intent = new Intent(ItemsList.this, PaymentActivity.class);
intent.putExtra(PayPalService.EXTRA_PAYPAL_CONFIGURATION, paypalConfig);
intent.putExtra(PaymentActivity.EXTRA_PAYMENT, thingsToBuy);
startActivityForResult(intent, REQUEST_CODE_PAYMENT);
}
/**
* Receiving the PalPay payment response
* */
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_CODE_PAYMENT) {
if (resultCode == Activity.RESULT_OK) {
PaymentConfirmation confirm = data
.getParcelableExtra(PaymentActivity.EXTRA_RESULT_CONFIRMATION);
if (confirm != null) {
try {
Log.e(TAG, confirm.toJSONObject().toString(4));
Log.e(TAG, confirm.getPayment().toJSONObject()
.toString(4));
String paymentId = confirm.toJSONObject()
.getJSONObject("response").getString("id");
String payment_client = confirm.getPayment()
.toJSONObject().toString();
Log.e(TAG, "paymentId: " + paymentId
+ ", payment_json: " + payment_client);
// Now verify the payment on the server side
verifyPaymentOnServer(paymentId, payment_client);
} catch (JSONException e) {
Log.e(TAG, "an extremely unlikely failure occurred: ",
e);
}
}
} else if (resultCode == Activity.RESULT_CANCELED) {
Log.e(TAG, "The user canceled.");
} else if (resultCode == PaymentActivity.RESULT_EXTRAS_INVALID) {
Log.e(TAG,
"An invalid Payment or PayPalConfiguration was submitted.");
}
}
}
private void showpDialog() {
if (!pDialog.isShowing())
pDialog.show();
}
private void hidepDialog() {
if (pDialog.isShowing())
pDialog.dismiss();
}
#Override
public void onAddToCartPressed(Product product) {
PayPalItem item = new PayPalItem(product.getname(), 1,
product.getprice(), Config.DEFAULT_CURRENCY, product.getsku());
productsInCart.add(item);
Toast.makeText(getApplicationContext(),
item.getName() + " added to cart!", Toast.LENGTH_SHORT).show();
}
}
--------------------------------------------------------------------------
import java.math.BigDecimal;
public class Product {
private String id, name, description, image, sku;
private BigDecimal price;
public Product() {
}
public Product(String id, String name, String description, String image,
BigDecimal price, String sku) {
this.id = id;
this.name = name;
this.description = description;
this.image = image;
this.price = price;
this.sku = sku;
}
public String getid() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getname() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getdescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getimage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
public BigDecimal getprice() {
return price;
}
public String getsku() {
return sku;
}
}
---------------------------------------------------------------
package com.flavorbaba;
import com.flavorbaba.R;
import com.flavorbaba.AppController;
import java.util.List;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
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 com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.NetworkImageView;
public class ProductListAdapter extends BaseAdapter {
private Activity activity;
private LayoutInflater inflater;
private List<Product> products;
private ProductListAdapterListener listener;
ImageLoader imageLoader = AppController.getInstance().getImageLoader();
public ProductListAdapter(Activity activity, List<Product> feedItems,
ProductListAdapterListener listener) {
this.activity = activity;
this.products = feedItems;
this.listener = listener;
}
#Override
public int getCount() {
return products.size();
}
#Override
public Object getItem(int location) {
return products.get(location);
}
#Override
public long getItemId(int position) {
return position;
}
#SuppressLint("InflateParams")
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (inflater == null)
inflater = (LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null)
convertView = inflater.inflate(R.layout.list_item_product, null);
if (imageLoader == null)
imageLoader = AppController.getInstance().getImageLoader();
TextView name = (TextView) convertView.findViewById(R.id.productName);
TextView description = (TextView) convertView
.findViewById(R.id.productDescription);
TextView price = (TextView) convertView.findViewById(R.id.productPrice);
NetworkImageView image = (NetworkImageView) convertView
.findViewById(R.id.productImage);
Button btnAddToCart = (Button) convertView
.findViewById(R.id.btnAddToCart);
final Product product = products.get(position);
name.setText(product.getname());
description.setText(product.getdescription());
price.setText("Price: $" + product.getprice());
// user profile pic
image.setImageUrl(product.getimage(), imageLoader);
btnAddToCart.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
listener.onAddToCartPressed(product);
}
});
return convertView;
}
public interface ProductListAdapterListener {
public void onAddToCartPressed(Product product);
}
}

This is a lot ta code dude...
I Wonder why your Productlistadapter object needs two contexts and why you give the first context as Item activity.this but nevertheless
One big Problem here is that you are trying to make a network connection on the main thread...that's an error when you are in strict mode while debugging...

Related

How to get row wise increment in counter starting from one in each row listview

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?

how to set the view to last item in recyclerview

I am displaying a list of messages in my chat room and I'm using RecycleView to display. I want the view to be set to the recent message(last message, last item in the list) instead of the first item. I used smoothScrollToPosition but I don't want the list to be scrolled from first to last to view the recent message. I want it to be like whatsapp which when clicked on a chat would show the view of the last message. How can I achieve this?
package com.webapp.chat.activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.android.volley.DefaultRetryPolicy;
import com.android.volley.NetworkResponse;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.RetryPolicy;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import com.webapp.chat.R;
import com.webapp.chat.adapter.ChatRoomThreadAdapter;
import com.webapp.chat.app.Config;
import com.webapp.chat.app.EndPoints;
import com.webapp.chat.app.MyApplication;
import com.webapp.chat.gcm.NotificationUtils;
import com.webapp.chat.model.Message;
import com.webapp.chat.model.User;
public class ChatRoomActivity extends AppCompatActivity {
private String TAG = ChatRoomActivity.class.getSimpleName();
private String userChatRoomId;
private RecyclerView recyclerView;
private ChatRoomThreadAdapter mAdapter;
private ArrayList<Message> messageArrayList;
private BroadcastReceiver mRegistrationBroadcastReceiver;
private EditText inputMessage;
private Button btnSend;
private String selfUserId;
private String selfUserName;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_chat_room);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
inputMessage = (EditText) findViewById(R.id.message);
btnSend = (Button) findViewById(R.id.btn_send);
Intent intent = getIntent();
userChatRoomId = intent.getStringExtra("user_id");
String title = intent.getStringExtra("name");
getSupportActionBar().setTitle(title);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
if (userChatRoomId == null) {
Toast.makeText(getApplicationContext(), "User Chat room not found!", Toast.LENGTH_SHORT).show();
finish();
}
recyclerView = (RecyclerView) findViewById(R.id.recycler_view);
messageArrayList = new ArrayList<>();
// self user id is to identify the message owner
selfUserId = MyApplication.getInstance().getPrefManager().getUser().getId();
selfUserName = MyApplication.getInstance().getPrefManager().getUser().getName();
mAdapter = new ChatRoomThreadAdapter(this, messageArrayList, selfUserId);
LinearLayoutManager layoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutManager);
recyclerView.setItemAnimator(new DefaultItemAnimator());
recyclerView.setAdapter(mAdapter);
mRegistrationBroadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(Config.PUSH_NOTIFICATION)) {
// new push message is received
handlePushNotification(intent);
}
}
};
btnSend.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
sendMessage();
}
});
fetchChatThread();
}
#Override
protected void onResume() {
super.onResume();
// registering the receiver for new notification
LocalBroadcastManager.getInstance(this).registerReceiver(mRegistrationBroadcastReceiver,
new IntentFilter(Config.PUSH_NOTIFICATION));
NotificationUtils.clearNotifications();
}
#Override
protected void onPause() {
LocalBroadcastManager.getInstance(this).unregisterReceiver(mRegistrationBroadcastReceiver);
super.onPause();
}
/**
* Handling new push message, will add the message to
* recycler view and scroll it to bottom
* */
private void handlePushNotification(Intent intent) {
Message message = (Message) intent.getSerializableExtra("message");
String userChatRoomId = intent.getStringExtra("user_id");
if (message != null && userChatRoomId != null) {
messageArrayList.add(message);
mAdapter.notifyDataSetChanged();
if (mAdapter.getItemCount() > 1) {
recyclerView.getLayoutManager().smoothScrollToPosition(recyclerView, null, mAdapter.getItemCount() - 1);
}
}
}
/**
* Posting a new message in chat room
* will make an http call to our server. Our server again sends the message
* to all the devices as push notification
* */
private void sendMessage() {
final String message = this.inputMessage.getText().toString().trim();
if (TextUtils.isEmpty(message)) {
Toast.makeText(getApplicationContext(), "Enter a message", Toast.LENGTH_SHORT).show();
return;
}
/** Create chatroom with the other user after sending the message**/
String endPointInsert = EndPoints.CHAT_ROOM.replace("_ID_", selfUserId) + "/" + userChatRoomId;
Log.e(TAG, "endpointInsert: " + endPointInsert);
StringRequest strReque = new StringRequest(Request.Method.GET,
endPointInsert, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.e(TAG, "response: " + response);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
NetworkResponse networkResponse = error.networkResponse;
Log.e(TAG, "Volley error: " + error.getMessage() + ", code: " + networkResponse);
Toast.makeText(getApplicationContext(), "Volley error: " + error.getMessage(), Toast.LENGTH_SHORT).show();
}
});
Date date = new Date();
String createdAt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(date);
Log.e(TAG, "TIMESTAMP:" + createdAt);
User user = new User(selfUserId, selfUserName);
final Message msg = new Message();
msg.setId("");
msg.setMessage(message);
msg.setCreatedAt(createdAt);
msg.setUser(user);
messageArrayList.add(msg);
mAdapter.notifyDataSetChanged();
if (mAdapter.getItemCount() > 1) {
// scrolling to bottom of the recycler view
recyclerView.getLayoutManager().smoothScrollToPosition(recyclerView, null, mAdapter.getItemCount() - 1);
}
//Log.e(TAG,msg.getId());
String endPoint = EndPoints.USER_MESSAGE.replace("_ID_", userChatRoomId);
Log.e(TAG, "endpoint: " + endPoint);
this.inputMessage.setText("");
StringRequest strReq = new StringRequest(Request.Method.POST,
endPoint, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.e(TAG, "response: " + response);
try {
JSONObject obj = new JSONObject(response);
// check for error
if (obj.getBoolean("error") == false) {
JSONObject commentObj = obj.getJSONObject("message");
String commentId = commentObj.getString("message_id");
String commentText = commentObj.getString("message");
String createdAt = commentObj.getString("created_at");
JSONObject userObj = obj.getJSONObject("user");
String userId = commentObj.getString("from_user_id");
String userName = userObj.getString("name");
User user = new User(userId, userName);
Log.e(TAG, commentId);
msg.setId(commentId);
/*Message message = new Message();
message.setId(commentId);
message.setMessage(commentText);
message.setCreatedAt(createdAt);
message.setUser(user);*/
/*messageArrayList.add(msg);
mAdapter.notifyDataSetChanged();
if (mAdapter.getItemCount() > 1) {
// scrolling to bottom of the recycler view
recyclerView.getLayoutManager().smoothScrollToPosition(recyclerView, null, mAdapter.getItemCount() - 1);
}*/
} else {
Toast.makeText(getApplicationContext(), "" + obj.getString("message"), Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
Log.e(TAG, "json parsing error: " + e.getMessage());
Toast.makeText(getApplicationContext(), "json parse error: " + e.getMessage(), Toast.LENGTH_SHORT).show();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
NetworkResponse networkResponse = error.networkResponse;
Log.e(TAG, "Volley error: " + error.getMessage() + ", code: " + networkResponse);
Toast.makeText(getApplicationContext(), "Volley error: " + error.getMessage(), Toast.LENGTH_SHORT).show();
inputMessage.setText(message);
}
}) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("user_id", MyApplication.getInstance().getPrefManager().getUser().getId());
params.put("message", message);
Log.e(TAG, "Params: " + params.toString());
return params;
};
};
// disabling retry policy so that it won't make
// multiple http calls
int socketTimeout = 0;
RetryPolicy policy = new DefaultRetryPolicy(socketTimeout,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT);
strReq.setRetryPolicy(policy);
//Adding request to request queue
MyApplication.getInstance().addToRequestQueue(strReque);
MyApplication.getInstance().addToRequestQueue(strReq);
Log.i(TAG,msg.getId());
}
/**
* Fetching all the messages of a single chat room
* */
private void fetchChatThread() {
String endPointi = EndPoints.CHAT_USER_THREAD.replace("_ID_", userChatRoomId);
String endPoint = endPointi + "/" + selfUserId;
Log.e(TAG, "endPoint: " + endPoint);
StringRequest strReq = new StringRequest(Request.Method.GET,
endPoint, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.e(TAG, "response: " + response);
try {
JSONObject obj = new JSONObject(response);
// check for error
if (obj.getBoolean("error") == false) {
JSONArray commentsObj = obj.getJSONArray("messages");
for (int i = 0; i < commentsObj.length(); i++) {
JSONObject commentObj = (JSONObject) commentsObj.get(i);
String commentId = commentObj.getString("message_id");
String commentText = commentObj.getString("message");
String createdAt = commentObj.getString("created_at");
JSONObject userObj = commentObj.getJSONObject("user");
String userId = userObj.getString("user_id");
String userName = userObj.getString("username");
User user = new User(userId, userName);
Message message = new Message();
message.setId(commentId);
message.setMessage(commentText);
message.setCreatedAt(createdAt);
message.setUser(user);
messageArrayList.add(message);
}
mAdapter.notifyDataSetChanged();
if (mAdapter.getItemCount() > 1) {
recyclerView.getLayoutManager().smoothScrollToPosition(recyclerView, null, 1);
}
} else {
Toast.makeText(getApplicationContext(), "" + obj.getJSONObject("error").getString("message"), Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
Log.e(TAG, "json parsing error: " + e.getMessage());
Toast.makeText(getApplicationContext(), "json parse error: " + e.getMessage(), Toast.LENGTH_SHORT).show();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
NetworkResponse networkResponse = error.networkResponse;
Log.e(TAG, "Volley error: " + error.getMessage() + ", code: " + networkResponse);
Toast.makeText(getApplicationContext(), "Volley error: " + error.getMessage(), Toast.LENGTH_SHORT).show();
}
});
//Adding request to request queue
MyApplication.getInstance().addToRequestQueue(strReq);
}
}
package com.webapp.chat.adapter;
/**
* Created by COMP on 17-06-2016.
*/
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import com.webapp.chat.R;
import com.webapp.chat.model.Message;
public class ChatRoomThreadAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private static String TAG = ChatRoomThreadAdapter.class.getSimpleName();
private String userId;
private int SELF = 100;
private static String today;
private Context mContext;
private ArrayList<Message> messageArrayList;
public class ViewHolder extends RecyclerView.ViewHolder {
TextView message, timestamp;
public ViewHolder(View view) {
super(view);
message = (TextView) itemView.findViewById(R.id.message);
timestamp = (TextView) itemView.findViewById(R.id.timestamp);
}
}
public ChatRoomThreadAdapter(Context mContext, ArrayList<Message> messageArrayList, String userId) {
this.mContext = mContext;
this.messageArrayList = messageArrayList;
this.userId = userId;
Calendar calendar = Calendar.getInstance();
today = String.valueOf(calendar.get(Calendar.DAY_OF_MONTH));
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView;
// view type is to identify where to render the chat message
// left or right
if (viewType == SELF) {
// self message
itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.chat_item_self, parent, false);
} else {
// others message
itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.chat_item_other, parent, false);
}
return new ViewHolder(itemView);
}
#Override
public int getItemViewType(int position) {
Message message = messageArrayList.get(position);
if (message.getUser().getId().equals(userId)) {
return SELF;
}
return position;
}
#Override
public void onBindViewHolder(final RecyclerView.ViewHolder holder, int position) {
Message message = messageArrayList.get(position);
((ViewHolder) holder).message.setText(message.getMessage());
String timestamp = getTimeStamp(message.getCreatedAt());
if (message.getUser().getName() != null)
timestamp = message.getUser().getName() + ", " + timestamp;
((ViewHolder) holder).timestamp.setText(timestamp);
}
#Override
public int getItemCount() {
return messageArrayList.size();
}
public static String getTimeStamp(String dateStr) {
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String timestamp = "";
today = today.length() < 2 ? "0" + today : today;
try {
Date date = format.parse(dateStr);
SimpleDateFormat todayFormat = new SimpleDateFormat("dd");
String dateToday = todayFormat.format(date);
format = dateToday.equals(today) ? new SimpleDateFormat("hh:mm a") : new SimpleDateFormat("dd LLL, hh:mm a");
String date1 = format.format(date);
timestamp = date1.toString();
} catch (ParseException e) {
e.printStackTrace();
}
return timestamp;
}
}
Set setReverseLayout=true so that LayoutManager will layout items from end.
Something like this:
LinearLayoutManager layoutManager = new LinearLayoutManager(this);
layoutManager.setReverseLayout(true);
recyclerView.setLayoutManager(layoutManager);
EDIT: This will reverse the data order but not scroll the RecyclerView to the last item. For keeping data order same and simply scrolling the RecyclerView to the last item set setStackFromEnd=true
Sample:
LinearLayoutManager layoutManager = new LinearLayoutManager(this);
layoutManager.setStackFromEnd(true);
recyclerView.setLayoutManager(layoutManager);
Use RecyclerView LayoutManager to scroll item at position
recyclerView.getLayoutManager().scrollToPosition(messageList.size()-1);
And u are good to go
LinearLayoutManager manager = new LinearLayoutManager(ActivityMessage.this);
manager.setStackFromEnd(true);
manager.setReverseLayout(false);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(manager);

ArrayList shows only single item in RecyclerView

I'm trying to get all the user chats (created in my database) using an ArrayList and Recyclerview.Adapter but only first item from my ArrayList is being shown on my emulator screen.
Here's the corresponding code:
MainActivity:
package com.wipro.chat.activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.DefaultItemAnimator;
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.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.Toast;
import com.android.volley.NetworkResponse;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GoogleApiAvailability;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import com.wipro.chat.R;
import com.wipro.chat.adapter.ChatRoomsAdapter;
import com.wipro.chat.app.Config;
import com.wipro.chat.app.EndPoints;
import com.wipro.chat.app.MyApplication;
import com.wipro.chat.gcm.GcmIntentService;
import com.wipro.chat.gcm.NotificationUtils;
import com.wipro.chat.helper.SimpleDividerItemDecoration;
import com.wipro.chat.model.ChatRoom;
import com.wipro.chat.model.Message;
public class MainActivity extends AppCompatActivity {
private String TAG = MainActivity.class.getSimpleName();
private static final int PLAY_SERVICES_RESOLUTION_REQUEST = 9000;
private BroadcastReceiver mRegistrationBroadcastReceiver;
private ArrayList<ChatRoom> chatRoomArrayList;
private ChatRoomsAdapter mAdapter;
private RecyclerView recyclerView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
/**
* Check for login session. If not logged in launch
* login activity
* */
if (MyApplication.getInstance().getPrefManager().getUser() == null) {
launchLoginActivity();
}
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
recyclerView = (RecyclerView) findViewById(R.id.recycler_view);
/**
* Broadcast receiver calls in two scenarios
* 1. gcm registration is completed
* 2. when new push notification is received
* */
mRegistrationBroadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
// checking for type intent filter
if (intent.getAction().equals(Config.REGISTRATION_COMPLETE)) {
// gcm successfully registered
// now subscribe to `global` topic to receive app wide notifications
subscribeToGlobalTopic();
} else if (intent.getAction().equals(Config.SENT_TOKEN_TO_SERVER)) {
// gcm registration id is stored in our server's MySQL
Log.e(TAG, "GCM registration id is sent to our server");
} else if (intent.getAction().equals(Config.PUSH_NOTIFICATION)) {
// new push notification is received
handlePushNotification(intent);
}
}
};
chatRoomArrayList = new ArrayList<>();
mAdapter = new ChatRoomsAdapter(this, chatRoomArrayList);
LinearLayoutManager layoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutManager);
recyclerView.addItemDecoration(new SimpleDividerItemDecoration(
getApplicationContext()
));
recyclerView.setItemAnimator(new DefaultItemAnimator());
recyclerView.setAdapter(mAdapter);
recyclerView.addOnItemTouchListener(new ChatRoomsAdapter.RecyclerTouchListener(getApplicationContext(), recyclerView, new ChatRoomsAdapter.ClickListener() {
#Override
public void onClick(View view, int position) {
// when chat is clicked, launch full chat thread activity
ChatRoom userChatRoom = chatRoomArrayList.get(position);
Intent intent = new Intent(MainActivity.this, ChatRoomActivity.class);
intent.putExtra("user_id", userChatRoom.getId());
intent.putExtra("name", userChatRoom.getName());
startActivity(intent);
}
#Override
public void onLongClick(View view, int position) {
}
}));
/**
* Always check for google play services availability before
* proceeding further with GCM
* */
if (checkPlayServices()) {
registerGCM();
fetchChatRooms();
}
}
/**
* Handles new push notification
*/
private void handlePushNotification(Intent intent) {
/*int type = intent.getIntExtra("type", -1);
// if the push is of chat room message
// simply update the UI unread messages count
if (type == Config.PUSH_TYPE_CHATROOM) {
Message message = (Message) intent.getSerializableExtra("message");
String chatRoomId = intent.getStringExtra("chat_room_id");
if (message != null && chatRoomId != null) {
updateRow(chatRoomId, message);
}
} else if (type == Config.PUSH_TYPE_USER) {
// push belongs to user alone
// just showing the message in a toast
Message message = (Message) intent.getSerializableExtra("message");
Toast.makeText(getApplicationContext(), "New push: " + message.getMessage(), Toast.LENGTH_LONG).show();
}*/
Message message = (Message) intent.getSerializableExtra("message");
String userChatRoomId = intent.getStringExtra("user_id");
if (message != null && userChatRoomId != null) {
updateRow(userChatRoomId, message);
}
}
/**
* Updates the chat list unread count and the last message
*/
private void updateRow(String chatRoomId, Message message) {
for (ChatRoom cr : chatRoomArrayList) {
if (cr.getId().equals(chatRoomId)) {
int index = chatRoomArrayList.indexOf(cr);
cr.setLastMessage(message.getMessage());
cr.setUnreadCount(cr.getUnreadCount() + 1);
chatRoomArrayList.remove(index);
chatRoomArrayList.add(index, cr);
break;
}
}
mAdapter.notifyDataSetChanged();
}
/**
* fetching the chat rooms by making http call
*/
private void fetchChatRooms() {
StringRequest strReq = new StringRequest(Request.Method.GET,
EndPoints.CHAT_ROOMS, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.e(TAG, "response: " + response);
try {
JSONObject obj = new JSONObject(response);
// check for error flag
if (obj.getBoolean("error") == false) {
JSONArray chatRoomsArray = obj.getJSONArray("chat_rooms");
for (int i = 0; i < chatRoomsArray.length(); i++) {
JSONObject chatRoomsObj = (JSONObject) chatRoomsArray.get(i);
ChatRoom cr = new ChatRoom();
cr.setId(chatRoomsObj.getString("user_id"));
cr.setName(chatRoomsObj.getString("name"));
cr.setLastMessage("");
cr.setUnreadCount(0);
cr.setTimestamp(chatRoomsObj.getString("created_at"));
chatRoomArrayList.add(cr);
}
} else {
// error in fetching chat rooms
Toast.makeText(getApplicationContext(), "" + obj.getJSONObject("error").getString("message"), Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
Log.e(TAG, "json parsing error: " + e.getMessage());
Toast.makeText(getApplicationContext(), "Json parse error: " + e.getMessage(), Toast.LENGTH_LONG).show();
}
mAdapter.notifyDataSetChanged();
// subscribing to all chat room topics
//subscribeToAllTopics();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
NetworkResponse networkResponse = error.networkResponse;
Log.e(TAG, "Volley error: " + error.getMessage() + ", code: " + networkResponse);
Toast.makeText(getApplicationContext(), "Volley error: " + error.getMessage(), Toast.LENGTH_SHORT).show();
}
});
//Adding request to request queue
MyApplication.getInstance().addToRequestQueue(strReq);
}
// subscribing to global topic
private void subscribeToGlobalTopic() {
Intent intent = new Intent(this, GcmIntentService.class);
intent.putExtra(GcmIntentService.KEY, GcmIntentService.SUBSCRIBE);
intent.putExtra(GcmIntentService.TOPIC, Config.TOPIC_GLOBAL);
startService(intent);
}
// Subscribing to all chat room topics
// each topic name starts with `topic_` followed by the ID of the chat room
// Ex: topic_1, topic_2
/*private void subscribeToAllTopics() {
for (ChatRoom cr : chatRoomArrayList) {
Intent intent = new Intent(this, GcmIntentService.class);
intent.putExtra(GcmIntentService.KEY, GcmIntentService.SUBSCRIBE);
intent.putExtra(GcmIntentService.TOPIC, "topic_" + cr.getId());
startService(intent);
}
}*/
private void launchLoginActivity() {
Intent intent = new Intent(MainActivity.this, LoginActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
finish();
}
#Override
protected void onResume() {
super.onResume();
// register GCM registration complete receiver
LocalBroadcastManager.getInstance(this).registerReceiver(mRegistrationBroadcastReceiver,
new IntentFilter(Config.REGISTRATION_COMPLETE));
// register new push message receiver
// by doing this, the activity will be notified each time a new message arrives
LocalBroadcastManager.getInstance(this).registerReceiver(mRegistrationBroadcastReceiver,
new IntentFilter(Config.PUSH_NOTIFICATION));
// clearing the notification tray
NotificationUtils.clearNotifications();
}
#Override
protected void onPause() {
LocalBroadcastManager.getInstance(this).unregisterReceiver(mRegistrationBroadcastReceiver);
super.onPause();
}
// starting the service to register with GCM
private void registerGCM() {
Intent intent = new Intent(this, GcmIntentService.class);
intent.putExtra("key", "register");
startService(intent);
}
private boolean checkPlayServices() {
GoogleApiAvailability apiAvailability = GoogleApiAvailability.getInstance();
int resultCode = apiAvailability.isGooglePlayServicesAvailable(this);
if (resultCode != ConnectionResult.SUCCESS) {
if (apiAvailability.isUserResolvableError(resultCode)) {
apiAvailability.getErrorDialog(this, resultCode, PLAY_SERVICES_RESOLUTION_REQUEST)
.show();
} else {
Log.i(TAG, "This device is not supported. Google Play Services not installed!");
Toast.makeText(getApplicationContext(), "This device is not supported. Google Play Services not installed!", Toast.LENGTH_LONG).show();
finish();
}
return false;
}
return true;
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu_main, menu);
return true;
}
public boolean onOptionsItemSelected(MenuItem menuItem) {
switch (menuItem.getItemId()) {
case R.id.action_logout:
MyApplication.getInstance().logout();
break;
}
return super.onOptionsItemSelected(menuItem);
}
}
ChatRoomsAdapter:
package com.wipro.chat.adapter;
/**
* Created by COMP on 16-06-2016.
*/
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.GestureDetector;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import com.wipro.chat.R;
import com.wipro.chat.model.ChatRoom;
public class ChatRoomsAdapter extends RecyclerView.Adapter<ChatRoomsAdapter.ViewHolder> {
private Context mContext;
private ArrayList<ChatRoom> chatRoomArrayList;
private static String today;
public class ViewHolder extends RecyclerView.ViewHolder {
public TextView name, message, timestamp, count;
public ViewHolder(View view) {
super(view);
name = (TextView) view.findViewById(R.id.name);
message = (TextView) view.findViewById(R.id.message);
timestamp = (TextView) view.findViewById(R.id.timestamp);
count = (TextView) view.findViewById(R.id.count);
}
}
public ChatRoomsAdapter(Context mContext, ArrayList<ChatRoom> chatRoomArrayList) {
this.mContext = mContext;
this.chatRoomArrayList = chatRoomArrayList;
Calendar calendar = Calendar.getInstance();
today = String.valueOf(calendar.get(Calendar.DAY_OF_MONTH));
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.chat_rooms_list_row, parent, false);
return new ViewHolder(itemView);
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
ChatRoom chatRoom = chatRoomArrayList.get(position);
holder.name.setText(chatRoom.getName());
holder.message.setText(chatRoom.getLastMessage());
if (chatRoom.getUnreadCount() > 0) {
holder.count.setText(String.valueOf(chatRoom.getUnreadCount()));
holder.count.setVisibility(View.VISIBLE);
} else {
holder.count.setVisibility(View.GONE);
}
holder.timestamp.setText(getTimeStamp(chatRoom.getTimestamp()));
}
#Override
public int getItemCount() {
return chatRoomArrayList.size();
}
public static String getTimeStamp(String dateStr) {
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String timestamp = "";
today = today.length() < 2 ? "0" + today : today;
try {
Date date = format.parse(dateStr);
SimpleDateFormat todayFormat = new SimpleDateFormat("dd");
String dateToday = todayFormat.format(date);
format = dateToday.equals(today) ? new SimpleDateFormat("hh:mm a") : new SimpleDateFormat("dd LLL, hh:mm a");
String date1 = format.format(date);
timestamp = date1.toString();
} catch (ParseException e) {
e.printStackTrace();
}
return timestamp;
}
public interface ClickListener {
void onClick(View view, int position);
void onLongClick(View view, int position);
}
public static class RecyclerTouchListener implements RecyclerView.OnItemTouchListener {
private GestureDetector gestureDetector;
private ChatRoomsAdapter.ClickListener clickListener;
public RecyclerTouchListener(Context context, final RecyclerView recyclerView, final ChatRoomsAdapter.ClickListener clickListener) {
this.clickListener = clickListener;
gestureDetector = new GestureDetector(context, new GestureDetector.SimpleOnGestureListener() {
#Override
public boolean onSingleTapUp(MotionEvent e) {
return true;
}
#Override
public void onLongPress(MotionEvent e) {
View child = recyclerView.findChildViewUnder(e.getX(), e.getY());
if (child != null && clickListener != null) {
clickListener.onLongClick(child, recyclerView.getChildLayoutPosition(child));
}
}
});
}
#Override
public boolean onInterceptTouchEvent(RecyclerView rv, MotionEvent e) {
View child = rv.findChildViewUnder(e.getX(), e.getY());
if (child != null && clickListener != null && gestureDetector.onTouchEvent(e)) {
clickListener.onClick(child, rv.getChildLayoutPosition(child));
}
return false;
}
#Override
public void onTouchEvent(RecyclerView rv, MotionEvent e) {
}
#Override
public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) {
}
}
}
PHP code which is retrieving the chatroom is like:
/* * *
* fetching all chat rooms
*/
$app->get('/chat_rooms', function() {
$response = array();
$db = new DbHandler();
// fetching all user tasks
$result = $db->getAllChats();
$response["error"] = false;
$response["chat_rooms"] = array();
// pushing single chat room into array
while ($chat_room = $result->fetch_assoc()) {
$tmp = array();
$tmp["user_id"] = $chat_room["user_id"];
$tmp["name"] = $chat_room["name"];
$tmp["created_at"] = $chat_room["created_at"];
array_push($response["chat_rooms"], $tmp);
}
echoRespnse(200, $response);
});
public function getAllChats() {
$stmt = $this->conn->prepare("SELECT user_id, name, created_at FROM users");
$stmt->execute();
$tasks = $stmt->get_result();
$stmt->close();
return $tasks;
}
There are two user chats in my database, namely Messaging, Chat and I'm getting the both from database into ArrayList but it is only showing Messaging.
Adapter display:
Response from database:
Check recycler_view in your main layout. The height should be set to "wrap_content".

Nearby Places search gives a random result rather than a specific result

When I first run my app, on cicking on a particular Place Type, it generates every tpe of nearby place like: atm, malls, food,schools etc. within my specified mile radius.
Code for Places Activity:
package www.uneditedmap.com.locationandmap;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;
import android.widget.Toast;
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 java.util.List;
import www.uneditedmap.com.locationandmap.model.Places;
import www.uneditedmap.com.locationandmap.parsers.PlacesJSONParser;
public class PlacesActivity extends ListActivity {
TextView placeName;
TextView placeVicinity;
TextView placeStatus;
String locationType;
String myUrl;
ProgressDialog pDialog;
// List<FetchLocationTask> tasks;
List<Places> placesList;
String lat, lng;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.list_places);
// Initialize the TextView for vertical Scrolling
placeName = (TextView) findViewById(R.id.place_title);
placeVicinity = (TextView) findViewById(R.id.vicinity);
placeStatus = (TextView) findViewById(R.id.openNow);
// tasks = new ArrayList<>();
//locationFetcher();
Bundle extras = getIntent().getExtras();
if (extras != null) {
locationType = (extras.getString("TAG")).toString();
lat = extras.getString("lat").toString();
lng = extras.getString("lng").toString();
} else {
// set default value for now
locationType = "atm";
}
myUrl = "https://maps.googleapis.com/maps/api/place/nearbysearch/json?location="
+ lat + ","
+ lng
+ "&radius="
+ getString(R.string.radius)
+ "&types="
+ locationType
+ "&sensor=true&key="
+ getString(R.string.google_maps_key);
myUrl = myUrl.replaceAll(" ", "_");
//Log.d("generated URL: ", myUrl);
requestData(myUrl);
}
protected void updatePlaces() {
if (placesList.isEmpty()) {
Toast.makeText(getApplicationContext(), "No Result", Toast.LENGTH_LONG).show();
}
PlacesListAdapter adapter = new PlacesListAdapter(this, R.layout.item_vicinity, placesList);
setListAdapter(adapter);
}
#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_places, menu);
return true;
}
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
return super.onPrepareOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
if (id == R.id.action_refresh) {
//Toast.makeText(this, locationType, Toast.LENGTH_SHORT).show();
requestData(myUrl);
}
return false;
}
private void requestData(String uri) {
/*
Methods for Volley
Comment out this block and Uncomment AsyncTask to Use the AsyncTask block
The Volley Library uses less lines of code than the AsyncTask
*/
StringRequest request = new StringRequest(uri,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
placesList = PlacesJSONParser.parseFeed(response);
updatePlaces();
pDialog.dismiss();
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError ex) {
//Toast.makeText(PlacesActivity.this, ex.getMessage(), Toast.LENGTH_LONG).show();
Toast.makeText(PlacesActivity.this, "Please Check your network connection and" +
" refresh again", Toast.LENGTH_LONG).show();
pDialog.dismiss();
}
});
// add the request to queue
RequestQueue queue = Volley.newRequestQueue(this);
queue.add(request);
pDialog = new ProgressDialog(PlacesActivity.this);
pDialog.setMessage("Loading locations..");
pDialog.setCancelable(false);
pDialog.show();
//Methods using AsyncTask, Uncomment if using AsyncTask
// FetchLocationTask myTask = new FetchLocationTask();
// myTask.execute(uri);
}
/*
Replacing the AsyncTask with Volley.
To Use the AsyncTask, Comment out the Volley Method inside the RequestData() Method
and Uncomment AsyncTask with the corresponding methods
*/
/*private class FetchLocationTask extends AsyncTask<String, String, List<Places>> {
#Override
protected void onPreExecute() {
//updatePlaces();
pDialog = new ProgressDialog(PlacesActivity.this);
pDialog.setMessage("Loading locations..");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected List<Places> doInBackground(String... params) {
String content = HttpManager.getData(params[0]);
placesList = PlacesJSONParser.parseFeed(content);
Log.d("results : ", content);
return placesList;
}
#Override
protected void onPostExecute(List<Places> result) {
if (pDialog.isShowing())
pDialog.dismiss();
if (result == null) {
Toast.makeText(PlacesActivity.this, "Web service not available", Toast.LENGTH_LONG).show();
return;
}
placesList = result;
updatePlaces();
}
#Override
protected void onProgressUpdate(String... values) {
// updatePlaces(values[0]);
}
}*/
}
**Code for Restaurant.java**
package www.uneditedmap.com.locationandmap;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.widget.Toast;
public class Restaurant extends FragmentActivity {
MyLocation mLocation;
String lat, lng;
String[] keywords;
//String restaurants;
//private int defautltId, restaurantId;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_new_map);
// defautltId = R.drawable.ic_default;
// restaurantId = R.drawable.ic_restaurant;
keywords = getResources().getStringArray(R.array.keywords);
mLocation = new MyLocation(this);
//fetch location method
locationFetcher();
//keywords[0]
if (isOnline()) {
// Toast.makeText(getActivity().getBaseContext(), "You clicked "+ keywords[position]
// + " from " + lat + " , " + lng, Toast.LENGTH_SHORT).show();
Intent intent = new Intent(this, PlacesActivity.class)
.putExtra("TAG", keywords[0])
.putExtra("lat", lat)
.putExtra("lng", lng);
startActivity(intent);
} else {
Toast.makeText(this.getBaseContext(), "Network Isn't Available", Toast.LENGTH_LONG).show();
}
}
protected boolean isOnline() {
ConnectivityManager cm = (ConnectivityManager) this.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = cm.getActiveNetworkInfo();
if (networkInfo != null && networkInfo.isConnectedOrConnecting()) {
return true;
} else {
return false;
}
}
public void locationFetcher() {
if (mLocation.canGetLocation()) {
//mLocation.getLocation();
double latitude = mLocation.getLatitude();
double longitude = mLocation.getLongitude();
lat = String.valueOf(latitude);
lng = String.valueOf(longitude);
} else {
Toast.makeText(this, "LOCATION NOT ACQUIRED,TURN ON A PROVIDER", Toast.LENGTH_SHORT).show();
}
}
}
Code for the cardview where the restaurant.java is first added to the cardview stack:
package www.uneditedmap.com.locationandmap;
import android.content.Context;
import android.content.Intent;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
/**
* Created by null on 28/02/2015.
*/
public class GridAdapter extends RecyclerView.Adapter<GridAdapter.ViewHolder> {
public static String FAV = "New Activity";
List<EndangeredItem> mItems;
// LayoutInflater inflater;
private Context context;
public GridAdapter() {
super();
//inflater = LayoutInflater.from(viewGroup.getContext())
// this.context=context;
// this.mItems=mItems;
// inflater = LayoutInflater.from(context);
mItems = new ArrayList<EndangeredItem>();
EndangeredItem species = new EndangeredItem();
species.setName("Restaurant");
species.setThumbnail(R.drawable.restaurant);
mItems.add(species);
species = new EndangeredItem();
species.setName("Churches");
species.setThumbnail(R.drawable.church);
mItems.add(species);
species = new EndangeredItem();
species.setName("Laundry");
species.setThumbnail(R.drawable.laundry);
mItems.add(species);
species = new EndangeredItem();
species.setName("Schools");
species.setThumbnail(R.drawable.school);
mItems.add(species);
species = new EndangeredItem();
species.setName("Cinemas");
species.setThumbnail(R.drawable.cinema);
mItems.add(species);
species = new EndangeredItem();
species.setName("Hospitals");
species.setThumbnail(R.drawable.hospital);
mItems.add(species);
species = new EndangeredItem();
species.setName("Tech Centers");
species.setThumbnail(R.drawable.hubs);
mItems.add(species);
species = new EndangeredItem();
species.setName("Clubs");
species.setThumbnail(R.drawable.clubs);
mItems.add(species);
species = new EndangeredItem();
species.setName("Fashion House");
species.setThumbnail(R.drawable.fashion);
mItems.add(species);
species = new EndangeredItem();
species.setName("Banks");
species.setThumbnail(R.drawable.bank);
mItems.add(species);
species = new EndangeredItem();
species.setName("Atms");
species.setThumbnail(R.drawable.atm);
mItems.add(species);
species = new EndangeredItem();
species.setName("Sport Centers");
species.setThumbnail(R.drawable.sportcenters);
mItems.add(species);
species = new EndangeredItem();
species.setName("Supermarkets");
species.setThumbnail(R.drawable.supermarket);
mItems.add(species);
species = new EndangeredItem();
species.setName("Sitouts");
species.setThumbnail(R.drawable.sitouts);
mItems.add(species);
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View v = LayoutInflater.from(viewGroup.getContext())
.inflate(R.layout.grid_item, viewGroup, false);
ViewHolder viewHolder = new ViewHolder(v);
return viewHolder;
}
#Override
public void onBindViewHolder(ViewHolder viewHolder, int i) {
EndangeredItem nature = mItems.get(i);
viewHolder.tvspecies.setText(nature.getName());
viewHolder.imgThumbnail.setImageResource(nature.getThumbnail());
}
#Override
public int getItemCount() {
return mItems.size();
}
class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener, View.OnLongClickListener {
public ImageView imgThumbnail;
public TextView tvspecies;
public ViewHolder(View itemView) {
super(itemView);
context = itemView.getContext();
imgThumbnail = (ImageView) itemView.findViewById(R.id.img_thumbnail);
tvspecies = (TextView) itemView.findViewById(R.id.tv_species);
imgThumbnail.setOnClickListener(this);
//to enable user clicking long n the cardview image
imgThumbnail.setOnLongClickListener(this);
}
#Override
public void onClick(View view) {
Intent intent = null;
switch (getPosition()) {
case 0:
intent = new Intent(context, Restaurant.class);
break;
case 1:
intent = new Intent(context, TestIntent.class);
break;
case 2:
intent = new Intent(context, TestIntent.class);
break;
case 3:
intent = new Intent(context, TestIntent.class);
break;
case 4:
intent = new Intent(context, TestIntent.class);
break;
case 5:
intent = new Intent(context, TestIntent.class);
break;
case 6:
intent = new Intent(context, TestIntent.class);
break;
default:
intent = new Intent(context, MainActivity.class);
break;
}
context.startActivity(intent);
}
#Override
public boolean onLongClick(View view) {
// Intent intent;
// intent = new Intent(context, Favourites.class);
// intent.putExtra(FAV, R.id.img_thumbnail);
// context.startActivity(intent);
Toast.makeText(context, "added to favourites", Toast.LENGTH_SHORT).show();
return false;
}
}
}
My String Array:
<string-array name="keywords">
<item>Restaurants</item>
<item>Churches</item>
<item>Laundry</item>
<item>Schools</item>
<item>Cinemas</item>
<item>Hospitals</item>
<item>Tech Centers</item>
<item>Clubs</item>
<item>Fashion House</item>
<item>Banks</item>
<item>Atms</item>
<item>Sport Centers</item>
<item>Supermarkets</item>
<item>Sitouts</item>
</string-array>
Use this Google API to get food and bars around the location,
https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=ADD_LATITUDE,ADD_LONGITUDE&radius=5000&types=food,bar&sensor=true&key=YOUR_GOOGLE_MAP_BROWSER_KEY
Enable GooglePlacesAPI from Google Developers Console.
Generate Browser Key not Android Key, it will not work in this case.
Add this in your AndroidManifest.xml:
<meta-data
android:name="com.google.android.geo.API_KEY"
android:value="YOUR_API_KEY"/>
also add this permission:
<uses-permission android:name="android.permission.INTERNET" />
Response:
You will get JSON response when you enter URL in browser.
Use this as your URL String that searches for specific places.
String loginURL = "https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=19.9974,73.7876113&radius=2000&type=SBH&name=atm&key=API_KEY_HERE";
The problem is your Nearby Search request contains types=Restaurants, but that isn't a valid value for the types parameter. The valid values are in Table 1 of Place Types documentation. E.g. instead of Restaurants you want restaurant.
A secondary issue is that types is a deprecated parameter. You're only passing one type at a time, so you can easily switch to the fully supported type parameter. See the deprecation notice in the Place Search documentation.

Check box sending value to next activity even after deselcting it

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
}

Categories

Resources