I have 2 radiobuttons and 1 button. I want that when i click the normal button it checks which radio button is checked and executes a method based on that. The following is the code i have used but the app crashes when i click the button
#Override
public void onClick(View v) {
radioGroup = (RadioGroup) v.findViewById(R.id.radioPost);
rdpublic=(RadioButton) v.findViewById(R.id.radioPublic);
rdprivate=(RadioButton) v.findViewById(R.id.radioPrivate);
radioGroup.setOnCheckedChangeListener(new OnCheckedChangeListener()
{
public void onCheckedChanged(RadioGroup group, int checkedId)
{
if(rdpublic.isChecked())
{
new PostPublic().execute();
}
else if(rdprivate.isChecked())
{
new PostPrivate().execute;
}
}
});
}
Try this.....
normalBtn= (Button) findViewById(R.id.Btn);
rdpublic=(RadioButton) findViewById(R.id.radioPublic);
rdprivate=(RadioButton) findViewById(R.id.radioPrivate);
normalBtn.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
try {
if(rdpublic.isChecked())
{
new PostPublic().execute();
}
else if(rdprivate.isChecked())
{
new PostPrivate().execute;
}
}catch(Exception e)
{
e.printStackTrace();
}
}
});
Why are you using the button view to find the RadioButtons and Group? Instead of v.findViewById, you should just use findViewById.
your code assumes that your Buttons or RadioButtons are child Views of the passed View v. Which is actually wrong and that is why you are getting an NPE.
This is the full code.
package com.project.bsc.radianstores;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.app.ProgressDialog;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Spinner;
import android.widget.Toast;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
public class PostEnquiry extends Fragment implements OnClickListener {
public String[] sItemType;
public int position =0;
private EditText Message;
JSONParser jsonParser = new JSONParser();
private ProgressDialog pDialog;
private static final String POST_PRIVATE_URL = "http://192.168.1.102/webservice/privateenquiry.php";
private static final String POST_PUBLIC_URL = "http://192.168.1.102/webservice/publicenquiry.php";
private static final String TAG_SUCCESS = "success";
private static final String TAG_MESSAGE = "message";
private Button BtnSave;
private RadioGroup radioGroup;
private RadioButton rdpublic;
private RadioButton rdprivate;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.enquiry, container, false);
BtnSave = (Button) v.findViewById(R.id.sendEnquiry);
Message = (EditText)v.findViewById(R.id.MessageBox);
Spinner spItemType = (Spinner) v.findViewById(R.id.spinnerItemType);
sItemType = getResources().getStringArray(R.array.ItemType);
BtnSave.setOnClickListener(this);
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(getActivity(),android.R.layout.simple_spinner_item, sItemType);
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spItemType.setAdapter(dataAdapter);
//setting up listener for the spinner
spItemType.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
int index = arg0.getSelectedItemPosition();
position = index;
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
}
});
return v;
}
#Override
public void onClick(View v) {
radioGroup = (RadioGroup) v.findViewById(R.id.radioPost);
rdpublic=(RadioButton) v.findViewById(R.id.radioPublic);
rdprivate=(RadioButton) v.findViewById(R.id.radioPrivate);
radioGroup.setOnCheckedChangeListener(new OnCheckedChangeListener()
{
#Override
public void onCheckedChanged(RadioGroup group, int checkedId)
{
if(checkedId == rdpublic.getId()) {
new PostPublic().execute();
}
else if (checkedId == rdprivate.getId()) {
//new PostPrivate().execute();
}
}
});
}
class PostPublic extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(getActivity());
pDialog.setMessage("Posting Enquiry...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected String doInBackground(String... args) {
// TODO Auto-generated method stub
// Check for success tag
int success;
String strItemType = sItemType[position];;
String strMessage = Message.getText().toString();
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(getActivity());
String strUsername = sp.getString("Username", "");
try {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("Username", strUsername));
params.add(new BasicNameValuePair("Item_Type", strItemType));
params.add(new BasicNameValuePair("Message", strMessage));
Log.d("request!", "starting");
//Posting user data to script
JSONObject json = jsonParser.makeHttpRequest(
POST_PUBLIC_URL, "POST", params);
// full json response
Log.d("Enquiry Posting attempt", json.toString());
// json success element
success = json.getInt(TAG_SUCCESS);
if (success == 1) {
Log.d("Enquiry Posted Successful!", json.toString());
return json.getString(TAG_MESSAGE);
}else{
Log.d("Posting Failure!", json.getString(TAG_MESSAGE));
return json.getString(TAG_MESSAGE);
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(String file_url) {
// dismiss the dialog once product deleted
pDialog.dismiss();
if (file_url != null)
Toast.makeText(getActivity(), file_url, Toast.LENGTH_LONG).show();
}
}
}
Related
I am developing an Android eCommerce application in which there are two different buttons. The first one is an ADD TO CART button and the other one is a BUY NOW button.
When I click on the ADD TO CART button, it successfully places the item in the cart and after I click on the cart button, the app proceeds to the Cart Activity. I did the same for BUY NOW but the issue is how do I update my cart and move to Cart Activity on a single click?
ProductDescription.java:
package com.www.prashant;
import android.app.ProgressDialog;
import android.graphics.Paint;
import android.os.AsyncTask;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.daimajia.slider.library.SliderLayout;
import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.PropertyInfo;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;
import org.xmlpull.v1.XmlPullParserException;
import java.io.IOException;
public class ProductDescription extends Fragment {
View V;
int position;
ImageView product_image;
TextView product_desc;
public TextView price;
public TextView specialPrice;
TextView product_name;
ImageLoader image;
SliderLayout product_images;
Button sharbtn;
public TextView txt_qty;
public Button btn_plus;
public Button btn_buy;
ProgressDialog pdialog;
public int sum=0;
public int remove=0;
String cartMessage;
String cartMessage1;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
((MainActivity)getActivity()).getSupportActionBar().setDisplayHomeAsUpEnabled(true);
((MainActivity)getActivity()).actionBarDrawerToggle.setDrawerIndicatorEnabled(false);
Constants.lastDetails = true;
setHasOptionsMenu(true);
}
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.product_details, container, false);
//Set Navigation mode as Statndard
((MainActivity)getActivity()).getSupportActionBar().setNavigationMode(((MainActivity) getActivity()).getSupportActionBar().NAVIGATION_MODE_STANDARD);
V=v;
//get Product Position
position = Constants.product_position;
//Initialize ids
product_image=(ImageView) V.findViewById(R.id.product_image);
product_desc=(TextView) V.findViewById(R.id.textProductDescription);
price=(TextView) V.findViewById(R.id.text1);
specialPrice = (TextView) V.findViewById(R.id.textSpecialPrice);
product_name=(TextView) V.findViewById(R.id.textProductName);
//sharbtn=(Button)V.findViewById(R.id.sharbtn);
image=new ImageLoader(getActivity());
image.DisplayImage(Constants.Product_image.get(position), product_image);
product_name.setText(Constants.Product_name.get(position));
product_desc.setText(Constants.Product_desc.get(position));
// product_adesc.setText(Constants.Product_adesc.get(position));
if(Constants.Product_specialPrice.get(position) < Constants.Product_price.get(position)
&& Constants.Product_specialPrice.get(position)!=0){
price.setText(String.format("%.2f",Constants.Product_price.get(position)));
price.setPaintFlags(price.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG);
specialPrice.setText(String.format("%.2f",Constants.Product_specialPrice.get(position)));
}
else {
price.setText(String.format("%.2f",Constants.Product_price.get(position)));
specialPrice.setText(null);
}
btn_plus = (Button) V.findViewById(R.id.btn_plus);
btn_buy = (Button) V.findViewById(R.id.btn_buy);
// btn_minus = (ImageButton) V.findViewById(R.id.btn_minus);
txt_qty = (TextView) V.findViewById(R.id.txt_qty);
txt_qty.setText(String.valueOf(Constants.Product_qty.get(position)));
**/* Button Click Listener for Add Qty*/**
btn_plus.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Constants.Product_pos=position;
remove=0;
sum = Integer.parseInt(txt_qty.getText().toString())+1;
Constants.Product_qty.set(position, sum);
cartMessage1="Adding product to cart...";
cartMessage="Product was added successfully";
new updateCart().execute();
}
});
**/* Button Click Listener for Buy Qty*/**
btn_buy.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Constants.Product_pos=position;
remove=0;
sum = Integer.parseInt(txt_qty.getText().toString())+1;
Constants.Product_qty.set(position, sum);
cartMessage1="Adding product to cart...";
cartMessage="Product was added successfully";
new updateCart().execute();
}
});
product_image.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ImageFragment imageFrag=new ImageFragment();
getActivity().getSupportFragmentManager().beginTransaction().replace(R.id.main_content,imageFrag,null).addToBackStack(null).commit();
getActivity().setTitle("Images");
}
});
return v;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
// TODO Auto-generated method stub
//((MainActivity)getActivity()).resetActionBar(true, DrawerLayout.LOCK_MODE_LOCKED_OPEN);
super.onActivityCreated(savedInstanceState);
}
#Override
public void onDestroy() {
super.onDestroy();
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == android.R.id.home) {
((MainActivity)getActivity()).getSupportActionBar().setDisplayHomeAsUpEnabled(true);
((MainActivity)getActivity()).actionBarDrawerToggle.setDrawerIndicatorEnabled(true);
MainActivity.getInstance().CallFragment(Constants.position);
}
return true;
}
//Add product to cart task
public class updateCart extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
if (pdialog==null){
pdialog=new ProgressDialog(getActivity());
pdialog.setMessage(cartMessage1);
pdialog.setCanceledOnTouchOutside(false);
pdialog.setCancelable(false);
pdialog.show();
}
}
#Override
protected Void doInBackground(Void... arg0) {
// TODO Auto-generated method stub
// parse json data from server in background
parseJSONDataAddProductToCart();
return null;
}
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
if (pdialog.isShowing()){
pdialog.dismiss();
pdialog=null;
}
Toast.makeText(getActivity(), cartMessage, Toast.LENGTH_LONG).show();
//Update Notification Count in action bar icon
//Constants.cart_count += 1;
//txt_qty.setText(String.valueOf(sum));
MainActivity.getInstance().updateHotCount(Constants.ProductCart_Id.size());
txt_qty.setText(String.valueOf(Constants.Product_qty.get(position)));
// if internet connection and data available show data on list
// otherwise, show alert text
}
}
//Remove product from cart
public class removeCartProduct extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
if (pdialog==null){
pdialog=new ProgressDialog(getActivity());
pdialog.setMessage(cartMessage1);
pdialog.setCanceledOnTouchOutside(false);
pdialog.setCancelable(false);
pdialog.show();
}
}
#Override
protected Void doInBackground(Void... arg0) {
// TODO Auto-generated method stub
// parse json data from server in background
parseJSONDataAddProductToCart();
return null;
}
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
if (pdialog.isShowing()){
pdialog.dismiss();
pdialog=null;
}
Toast.makeText(getActivity(), cartMessage,Toast.LENGTH_LONG).show();
//Update Notification Count in action bar icon
//Constants.cart_count -= 1;
//txt_qty.setText(String.valueOf(sum));
MainActivity.getInstance().updateHotCount(Constants.ProductCart_Id.size());
txt_qty.setText(String.valueOf(Constants.Product_qty.get(position)));
// if internet connection and data available show data on list
// otherwise, show alert text
}
}
public void parseJSONDataAddProductToCart(){
try {
SoapObject item = new SoapObject(Constants.NAMESPACE, "shoppingCartProductEntity");
SoapObject request;
int qty;
if(remove==0){
request = new SoapObject(Constants.NAMESPACE, "shoppingCartProductAdd");
qty=1;
}else{
qty= Constants.Product_qty.get(Constants.Product_pos);
if(qty==0){
request = new SoapObject(Constants.NAMESPACE, "shoppingCartProductRemove");
}else{
request = new SoapObject(Constants.NAMESPACE, "shoppingCartProductUpdate");
}
}
// add paramaters and values
request.addProperty("sessionId", Constants.sessionId);
PropertyInfo pinfo = new PropertyInfo();
pinfo.setName("product_id");
pinfo.setValue(Constants.Product_ID.get(Constants.Product_pos));
pinfo.setType(String.class);
item.addProperty(pinfo);
pinfo = new PropertyInfo();
pinfo.setName("qty");
pinfo.setValue(qty);
pinfo.setType(Double.class);
item.addProperty(pinfo);
SoapObject EntityArray = new SoapObject(Constants.NAMESPACE, "shoppingCartProductEntityArray");
EntityArray.addProperty("products", item);
request.addProperty("quoteId", Constants.cartId);
request.addProperty("products",EntityArray);
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.dotNet = true;
envelope.setOutputSoapObject(request);
//Web method call
HttpTransportSE androidHttpTransport = new HttpTransportSE(Constants.URL);
androidHttpTransport.debug = true;
androidHttpTransport.call("", envelope);
//get the response
Object result = envelope.getResponse();
Constants.CartaddStatus=result.toString();
if(Constants.CartaddStatus == "true"){
if (Constants.ProductCart_Id.isEmpty()){
Constants.cartArrayPos=0;
}
if (!Constants.ProductCart_Id.contains(Constants.Product_ID.get(Constants.Product_pos))) {
Constants.ProductCart_Id.add(Constants.cartArrayPos,Constants.Product_ID.get(Constants.Product_pos));
Constants.ProductCart_Img.add(Constants.cartArrayPos,Constants.Product_image.get(Constants.Product_pos));
Constants.ProductCart_Price.add(Constants.cartArrayPos, Constants.Product_price.get(Constants.Product_pos));
Constants.cartArrayPos+=1;
}
if (qty==0){
Constants.ProductCart_Id.remove(Constants.Product_pos);
Constants.ProductCart_Img.remove(Constants.Product_pos);
Constants.ProductCart_Price.remove(Constants.Product_pos);
Constants.cartArrayPos-=1;
}
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (XmlPullParserException e) {
e.printStackTrace();
}
}
}
ActivityCart:
package com.www.prashant;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.app.AppCompatActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.GridView;
import android.widget.TextView;
import android.widget.Toast;
import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONObject;
import org.json.simple.parser.JSONParser;
/**
* Created by Prashant on 10/16/2016.
*/
public class ActivityCart extends Fragment {
int run;
ProgressDialog pdialog;
View v;
GridView list2;
CartImageLoadAdapter adapter;
public static ActivityCart sActivityCart;
public Double TotalPrice= 0.00;
TextView btn_place_order;
TextView btn_place;
Button btn_place_ord;
static String TotalProductCartPrice;
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.cart, container, false);
sActivityCart = this;
((MainActivity)getActivity()).getSupportActionBar().setDisplayShowTitleEnabled(true);
((MainActivity)getActivity()).getSupportActionBar().setNavigationMode(((MainActivity) getActivity()).getSupportActionBar().NAVIGATION_MODE_STANDARD);
list2=(GridView)v.findViewById(R.id.cartlist);
//list2.setBackgroundColor(Color.BLACK);
//list2.setVerticalSpacing(1);
// list2.setHorizontalSpacing(1);
clearData();
btn_place_order = (TextView) v.findViewById(R.id.btn_place_order);
// btn_place = (TextView) v.findViewById(R.id.btn_place);
btn_place_ord = (Button) v.findViewById(R.id.btn_place_ord);
btn_place_ord.setOnClickListener(listener);
return v;
}
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
Constants.lastDetails = false;
((AppCompatActivity) getActivity()).getSupportActionBar().setSubtitle(null);
((MainActivity)getActivity()).actionBarDrawerToggle.setDrawerIndicatorEnabled(true);
Constants.cartEntry=1;
new getDataTask().execute();
}
void clearData(){
Constants.Product_ID.clear();
Constants.Product_name.clear();
Constants.Product_price.clear();
Constants.Product_image.clear();
Constants.Product_qty.clear();
Constants.Product_specialPrice.clear();
Constants.Product_desc.clear();
//Constants.Product_adesc.clear();
}
#Override
public void onDestroy()
{
// Remove adapter refference from list
if (run==1) {
list2.setAdapter(null);
//Refresh cache directory downloaded images
adapter.imageLoader.clearCache();
adapter.notifyDataSetChanged();
}
super.onDestroy();
}
//Click Listner for place order button
public View.OnClickListener listener=new View.OnClickListener(){
#Override
public void onClick(View arg0) {
if(run == 1) {
// Call Login Function
if(Constants.Customer_FirstName.equals(""))
{
CartLogin CartLogin=new CartLogin();
getActivity().getSupportFragmentManager().beginTransaction().replace(R.id.main_content,CartLogin,null).addToBackStack(null).commit();
getActivity().setTitle("Login");
}
else {
// Call Shipping Information Function
ActivityCustomerAddress CustomerAddress=new ActivityCustomerAddress();
getActivity().getSupportFragmentManager().beginTransaction().replace(R.id.main_content,CustomerAddress,null).addToBackStack(null).commit();
getActivity().setTitle("Shipping");
}
}
else
Toast.makeText(getActivity(),"Cart is Empty",Toast.LENGTH_LONG).show();
}
};
// Image urls used in LazyImageLoadAdapter.java file
public class getDataTask extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
if (pdialog==null){
pdialog=new ProgressDialog(getActivity());
pdialog.setMessage("Loading...");
pdialog.setCanceledOnTouchOutside(getRetainInstance());
pdialog.setCancelable(false);
pdialog.show();
}
}
#Override
protected Void doInBackground(Void... arg0) {
// TODO Auto-generated method stub
// parse json data from server in background
if (!Constants.ProductCart_Id.isEmpty()){
parseJSONData();
run=1;
}else{
run=0;
}
//Get Product Prices
return null;
}
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
// Create custom adapter for listview
if (run==1) {
String[] images = new String[Constants.Product_image.size()];
images = Constants.Product_image.toArray(images);
adapter = new CartImageLoadAdapter(getActivity(), images);
//Set adapter to listview
list2.setAdapter(adapter);
if (pdialog.isShowing()) {
pdialog.dismiss();
pdialog = null;
}
}else{
if (pdialog.isShowing()) {
pdialog.dismiss();
pdialog = null;
}
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle("Cart is Empty").setMessage("Start Shopping now !!").create().show();
run=0;
}
// if internet connection and data available show data on list
// otherwise, show alert text
// btn_place_order.setText(String.format("Total: %.2f Place Order", TotalPrice));
btn_place_order.setText(String.format("%.2f ", TotalPrice));
TotalProductCartPrice= btn_place_order.getText().toString();
}
}
// method to parse json data from server
public void parseJSONData(){
HttpClient Client = new DefaultHttpClient();
// Create URL string
String URL = "http://prashant.com/customApi/cartDetails.php?cartId="+Constants.cartId;
//Log.i("httpget", URL);
JSONParser parser =new JSONParser();
try
{
String SetServerString = "";
// Create Request to server and get response
HttpGet httpget = new HttpGet(URL);
ResponseHandler<String> responseHandler = new BasicResponseHandler();
SetServerString = Client.execute(httpget, responseHandler);
Constants.Login=SetServerString;
JSONArray array=new JSONArray(SetServerString);
for (int i = 0; i < array.length(); i++) {
JSONObject obj=array.getJSONObject(i);
Constants.Product_ID.add(Long.parseLong(obj.getString("productId")));
Constants.Product_name.add(obj.getString("name"));
Double price= Double.valueOf(obj.getString("price"));
int Qty= Integer.parseInt(obj.getString("qty"));
Constants.Product_price.add(price*Qty);
Constants.Product_image.add(obj.getString("imageurl"));
Constants.Product_qty.add(Integer.valueOf(obj.getString("qty")));
Constants.Product_specialPrice.add((Double.valueOf(obj.getString("spprice")))*Qty);
// Total Sum of Cart Item price
TotalPrice += Double.valueOf(Double.valueOf(obj.getString("spprice"))*Qty);
}
// Show response on activity
}
catch(Exception ex)
{
}
}
public static ActivityCart getInstance() {
return sActivityCart;
}
public void SyncCart(){
// Call Shipping Information Function
ActivityCart SyncCart=new ActivityCart();
getActivity().getSupportFragmentManager().beginTransaction().replace(R.id.main_content,SyncCart,null).addToBackStack(null).commit();
getActivity().setTitle("Cart");
}
}
I'm getting this error:
10-06 09:09:25.466:
E/not work(1300):
pass exceptionandroid.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.
my Android project pass above error when i am try to disabled button.
if (success == 1) {
Log.i("enable", "working//////");
upload.setEnabled(true);
sendDeseaseDetails.setEnabled(false);
}else{
upload.setActivated(false);
sendDeseaseDetails.setEnabled(true);
}
above code run time pass this error. what is wrong........? please help me...........!
This is full code:
package viewActivity;
//import java.io.Externalizable;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;
import com.src.adms.R;
import controller.DBConnection;
//import android.R.string;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
//import android.text.Editable;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
#SuppressLint("SimpleDateFormat")
public class Send_deases_Detail extends Activity {
Spinner diseaseSpinner; // disease type
Spinner weatherSpinner; // get weather
Spinner districSpinner; // get district
Spinner soilConditionSpinner; // get soil condition
ImageButton upload; // upload images
Button clear; // clear field
Button sendDeseaseDetails; // button send disease details
int success = 0; // use, to know disease details send successfully
private Bundle extraslogin; // to get username and password
private String userName;
#SuppressWarnings("unused")
private String password;
private String userType;
private int deases_id;
private String diseaseType;
private String weather;
private String soilCondition;
private String district;
private EditText plantName;
private EditText region;
private EditText userDescription;
private static final String SEND_DESEASE_URL = "http://10.0.2.2:80/ADMS/andrioidConnection/send_deases_detail.php";
// private static final String SEND_DESEASE_URL
// ="http://admstest.netau.net/ADMS/andrioidConnection/send_deases_detail.php";
private static final String TAG_SUCCESS = "success";
private static final String TAG_MESSAGE = "message";
private static final String TAG_USER_TYPE = "usertype";
private static final String TAG_DEASES_ID = "deases_id";
DBConnection dbConnection = new DBConnection();
private ProgressDialog dialogBox;
// private Object EditText;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.deases_detail);
// get user name and password form LoIin
extraslogin = getIntent().getExtras();
userName = extraslogin.getString("user_name");
password = extraslogin.getString("pass_word");
plantName = (EditText) findViewById(R.id.editPlantName);
diseaseSpinner = (Spinner) findViewById(R.id.diseaseTypeSpinner);
weatherSpinner = (Spinner) findViewById(R.id.weather_Spinner);
districSpinner = (Spinner) findViewById(R.id.district_Spinner);
soilConditionSpinner = (Spinner) findViewById(R.id.soil_condition_Spinner);
// get id of image upload button
upload = (ImageButton) findViewById(R.id.imagebtUpload);
//upload.setEnabled(false); // default set false
// get date
// ...................................................................................
Calendar calendar = Calendar.getInstance();
SimpleDateFormat simpleDateFormat = new SimpleDateFormat(
"d/M/yy h:m:s a");
String stringDate = simpleDateFormat.format(calendar.getTime());
TextView textView = (TextView) findViewById(R.id.txtDate);
textView.setText(stringDate);
// this for disease type spinner
ArrayAdapter<CharSequence> diseasearrArrayAdapter = ArrayAdapter
.createFromResource(this, R.array.diseaseType_array,
android.R.layout.simple_list_item_1);
diseasearrArrayAdapter
.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
diseaseSpinner.setAdapter(diseasearrArrayAdapter);
diseaseSpinner.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view,
int position, long id) {
((TextView) parent.getChildAt(0)).setTextSize(15);
// get selected item
diseaseType = parent.getSelectedItem().toString();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
// this for weather type spinner
ArrayAdapter<CharSequence> weatherArrayAdapter = ArrayAdapter
.createFromResource(this, R.array.weather_array,
android.R.layout.simple_list_item_1);
weatherArrayAdapter
.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
weatherSpinner.setAdapter(weatherArrayAdapter);
weatherSpinner.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view,
int position, long id) {
((TextView) parent.getChildAt(0)).setTextSize(15);
// to get selected item
weather = parent.getSelectedItem().toString();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
// TODO Auto-generated method stub
}
});
// this for district spinner
ArrayAdapter<CharSequence> districArrayAdapter = ArrayAdapter
.createFromResource(this, R.array.district_array,
android.R.layout.simple_list_item_1);
districArrayAdapter
.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
districSpinner.setAdapter(districArrayAdapter);
districSpinner.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view,
int position, long id) {
((TextView) parent.getChildAt(0)).setTextSize(15);
// get selected item
district = parent.getSelectedItem().toString();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
// TODO Auto-generated method stub
}
});
// this for soil
// condition..........................................................................................................
ArrayAdapter<CharSequence> soilArrayAdapter = ArrayAdapter
.createFromResource(this, R.array.soil_array,
android.R.layout.simple_list_item_1);
soilArrayAdapter
.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
soilConditionSpinner.setAdapter(soilArrayAdapter);
soilConditionSpinner
.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent,
View view, int position, long id) {
((TextView) parent.getChildAt(0)).setTextSize(15);
// to get selected item
soilCondition = parent.getSelectedItem().toString();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
// TODO Auto-generated method stub
}
});
// ..............................................................................
region = (EditText) findViewById(R.id.editRegion);
userDescription = (EditText) findViewById(R.id.editDescription);
// give action to send disease details
// button........................................................
sendDeseaseDetails = (Button) findViewById(R.id.btSendDetails);
sendDeseaseDetails.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
new sendDetail().execute();
}
});
// ..............................................................................
// give action to cancel
// button...................................................................
clear = (Button) findViewById(R.id.btCancel);
clear.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
clear();
//Toast.makeText(getApplicationContext(), "clear field",Toast.LENGTH_SHORT).show();
}
private void clear() {
plantName.setText("");
region.setText("");
userDescription.setText("");
upload.setEnabled(false);
sendDeseaseDetails.setEnabled(true);
weatherSpinner.setSelection(0);
soilConditionSpinner.setSelection(0);
districSpinner.setSelection(0);
diseaseSpinner.setSelection(0);
configureImageUploadButton();
}
});
clear.performClick();
}
// configure Image Upload Button......................................
private void configureImageUploadButton() {
// upload.setEnabled(true);
upload.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getApplicationContext(), "click image button",
Toast.LENGTH_SHORT).show();
// pass data to image Take activity
Intent imageTakeActivity = new Intent(Send_deases_Detail.this,
ImageTakeActivity.class);
imageTakeActivity.putExtra("user_type", userType);
imageTakeActivity.putExtra("deases_id", deases_id);
success=0;
//enable();
// go to ImageTakeActivity
startActivity(imageTakeActivity);
finish();
}
});
}
// .................................................................................
protected void enable() {
if (success == 1) {
Log.i("enable", "working//////");
upload.setEnabled(true);
sendDeseaseDetails.setEnabled(false);
}else{
upload.setEnabled(false);
sendDeseaseDetails.setEnabled(true);
}
}
class sendDetail extends AsyncTask<String, String, String> {
// preprocessing part
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
dialogBox = new ProgressDialog(Send_deases_Detail.this);
dialogBox.setTitle("Processing...");
dialogBox.setMessage("Please wait...");
dialogBox.setIndeterminate(false);
dialogBox.setCancelable(true);
dialogBox.show();
}
// back ground run process
#Override
protected String doInBackground(String... args) {
String plant_name = plantName.getText().toString();
String region_name = region.getText().toString();
String user_discription = userDescription.getText().toString();
try {
// add first name, last name, Email & password to array list
ArrayList<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("user_name", userName));
// params.add(new BasicNameValuePair("pass_word", password));
params.add(new BasicNameValuePair("disease_type", diseaseType));
params.add(new BasicNameValuePair("weather", weather));
params.add(new BasicNameValuePair("soil_condition",
soilCondition));
params.add(new BasicNameValuePair("district", district));
params.add(new BasicNameValuePair("plant_name", plant_name));
params.add(new BasicNameValuePair("region _name", region_name));
params.add(new BasicNameValuePair("user_discription",
user_discription));
Log.d("request!", "starting");
// getting product details by making HTTP request
JSONObject json = dbConnection.createHttpRequest(
SEND_DESEASE_URL, "POST", params);
// check your register for json response
Log.d("Send detail attempt", json.toString());
// json success tag
success = json.getInt(TAG_SUCCESS);
deases_id = json.getInt(TAG_DEASES_ID);
userType = json.getString(TAG_USER_TYPE);
Log.d("deases_id", String.valueOf(deases_id));
if (success == 1) {
Log.d("Send Desease Detaiail Successful!", json.toString());
//configureImageUploadButton();//comment
Log.i("after!", "???pass configureImageUploadButton");
// configureImageUploadButton();
// finish();
// startActivity(i);
try {
enable(); // call to image button enable method
//finish();
} catch (Exception exception) {
Log.e("not work", "pass exception"+exception);
}
Log.i("work", "in back ground process......");
return json.getString(TAG_MESSAGE);
} else {
Log.d("Send detail fail!", json.getString(TAG_MESSAGE));
return json.getString(TAG_MESSAGE);
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
dialogBox.dismiss();
if (result != null) {
Toast.makeText(Send_deases_Detail.this, result,
Toast.LENGTH_LONG).show();
}
}
}
}
please help me
In android you need to perform any actions on views from the main UI thread. This post Running code in main thread from another thread will give you an idea of how to do so.
I have made a custom progress Dialog,I wan to close it in my postExecute method,I have tried as below,But i don't know how to dismiss it.I have tried as below,Can anyone Please tell me how can i dismiss that custom dialog
main
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.ProgressDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
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.EditText;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.epe.yehki.adapter.ProductAdapter;
import com.epe.yehki.backend.BackendAPIService;
import com.epe.yehki.uc.Header;
import com.epe.yehki.uc.Menu;
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 SearchActivity extends Activity {
public com.epe.yehki.uc.Menu searchMenu;
public Header searchHeader;
public EditText et_serach;
JSONObject jsonObj;
private ProgressDialog pDialog;
Intent in = null;
String searchUrl;
int flag;
public Header header;
public Menu menu;
public TextView title;
Bitmap bitmap;;
private ProductAdapter productContent;
// PRODUCTS....
// arrayLists......
public static ArrayList<String> productArray;
public static ArrayList<String> categoryArray;
ProgressBar progressBar;
//
// contacts JSONArray
JSONArray subcategories = null;
JSONArray products = null;
public String catid;
public String id;
public String pid;
String name;
ListView lv;
// Hashmap for ListView
ArrayList<HashMap<String, String>> subcategoryList;
ArrayList<HashMap<String, String>> productList;
// new
public String proname;
public String prodesc;
public String proimg;
public String proMinOrderQty;
public String proMinPrice;
public String proMaxPrice;
public String proTerms;
#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_search);
productList = new ArrayList<HashMap<String, String>>();
searchMenu = (com.epe.yehki.uc.Menu) findViewById(R.id.menusearch);
searchMenu.setSelectedTab(2);
searchHeader = (Header) findViewById(R.id.headersearch);
searchHeader.title.setText("Search");
et_serach = (EditText) findViewById(R.id.et_serach);
lv = (ListView) findViewById(R.id.serch_list);
productContent = new ProductAdapter(SearchActivity.this, productList);
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
if (Pref.getValue(SearchActivity.this, Const.PREF_CUSTOMER_ID, "") != null && !Pref.getValue(SearchActivity.this, Const.PREF_CUSTOMER_ID, "").equals(" ")
&& !Pref.getValue(SearchActivity.this, Const.PREF_CUSTOMER_ID, "").equals("0")) {
in = new Intent(getApplicationContext(), ProductDetailActivity.class);
proname = ((TextView) view.findViewById(R.id.product_label)).getText().toString();
// getting ProductId from the tag...
pid = productList.get(position).get(Const.TAG_PRODUCT_ID);
proimg = productList.get(position).get(Const.TAG_PRODUCT_IMG);
System.out.println(":::::::::::::::;;THE INTENT FOR THE PRODUCUT DETIALS ACTIVITY=================" + pid);
in.putExtra(Const.TAG_PRODUCT_ID, pid);
in.putExtra(Const.TAG_PRODUCT_IMG, proimg);
in.putExtra(Const.TAG_PRODUCT_NAME, proname);
startActivity(in);
} else {
in = new Intent(SearchActivity.this, LoginActivity.class);
startActivity(in);
}
}
});
et_serach.addTextChangedListener(new TextWatcher() {
public void afterTextChanged(Editable s) {
System.out.println(":::::::::::::::;after text changed called:::");
productList.clear();
}
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
public void onTextChanged(CharSequence s, int start, int before, int count) {
if (s.length() != 0) {
System.out.println(":::::::::::::::;on text changed called:::");
// CALL SEARCH API........!!!
productList.clear();
new GetSearchList().execute();
}
}
});
}
public void addProgressBar(Activity activity) {
final ViewGroup rootFrameLayout = (ViewGroup) activity.getWindow().peekDecorView();
final ViewGroup modal = new RelativeLayout(activity);
progressBar = new ProgressBar(activity);
LayoutParams layoutParams = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
((android.widget.RelativeLayout.LayoutParams) layoutParams).addRule(RelativeLayout.CENTER_IN_PARENT);
modal.addView(progressBar, layoutParams);
rootFrameLayout.addView(modal, new ViewGroup.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.FILL_PARENT));
rootFrameLayout.invalidate();
}
// SEARCH API()..!!!
private class GetSearchList extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
productList.clear();
addProgressBar(SearchActivity.this);// pDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
// Creating service handler class instance
BackendAPIService sh = new BackendAPIService();
searchUrl = Const.API_PRODUCT + "?product_name=" + et_serach.getText().toString().trim();
System.out.println(":::::::::::::::::::SUB URL:::::::::::::::::" + searchUrl);
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(searchUrl, BackendAPIService.GET);
Log.d("Response: ", "> " + jsonStr);
try {
if (jsonStr != null) {
jsonObj = new JSONObject(jsonStr);
if (jsonObj.getString(Const.TAG_STATUS).equals("success")) {
if (jsonObj.has(Const.TAG_PRODUCT_DETAIL)) {
System.out.println("::::::::::::::::true::::::::::::::::" + jsonObj.has(Const.TAG_PRODUCT_DETAIL));
products = jsonObj.getJSONArray(Const.TAG_PRODUCT_DETAIL);
if (products != null && products.length() != 0) {
// looping through All Contacts
for (int i = 0; i < products.length(); i++) {
JSONObject c = products.getJSONObject(i);
pid = c.getString(Const.TAG_PRODUCT_ID);
System.out.println("::::::::::::::::::PARSING PRODUCT ID:::::::::::::" + pid);
String proname = c.getString(Const.TAG_PRODUCT_NAME);
String prodesc = c.getString(Const.TAG_LISTING_DESCRIPTION);
String proimg = Const.API_HOST + "/" + c.getString(Const.TAG_PRODUCT_IMG);
System.out.println("::::::::::::::;products Length:::::::::::" + products.length());
System.out.println(":::::::::::::::My Image Url:::::::::::::" + proimg);
String proMinOrderQty = c.getString(Const.TAG_PRODUCT_MIN_ORDER_QTY);
c.getString(Const.TAG_PRODUCT_MIN_PRICE);
c.getString(Const.TAG_PRODUCT_MAX_PRICE);
c.getString(Const.TAG_PRODUCT_PAYMENT_TERMS);
// for company details..!!!
// new Working
HashMap<String, String> product = new HashMap<String, String>();
product.put(Const.TAG_PRODUCT_ID, pid);
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);
productList.add(product);
}
}
}
} else {
runOnUiThread(new Runnable() {
public void run() {
Utils.showCustomeAlertValidation(SearchActivity.this, "No Product found", "Yehki", "Ok");
}
});
}
} 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
productContent.notifyDataSetChanged();
lv.setAdapter(productContent);
}
}
}
Its easy try:
pDialog.dismiss();
STEP 1
Declare progress dialog above on create
private ProgressDialog pDialog;
STEP 2
Define preExecute method
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(context);
pDialog.setTitle("Please wait");
pDialog.setMessage("Processing...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
pDialog.setButton(DialogInterface.BUTTON_NEGATIVE, "Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
pDialog.show();
}
STEP 3
//Your back ground task as it is
STEP 4
ADD postExecute Method
protected void onPostExecute()
{
pDialog.dismiss();
}
You need to just call dismiss() method for ProgressDialog. Like
protected void onPostExecute(){
pDialog.dismiss();
}
You have the progressBar variable that holds a reference to the progress bar in your layout. To hide it, call
progressBar.setVisibility(View.GONE);
The RelativeLayout you're placing the ProgressBar in is unnecessary. Also consider including the ProgressBar statically in your layout and just setting its visibility to VISIBLE/GONE as necessary.
I have made an activity in that one ListView is ther,In that ListView each listItem is having an editText named "qty",which can be edited,one textView is there which displays "price",I need is when i edit the edittext and if the entered value is more than some limi the textView value will change,After that i have to pass them as a parameter to an api as below:
http://yehki.epagestore.in/app_api/updateCart.php?customer_id=41&product_id=30&quantity=90&product_id=23&quantity=90
from that i will get subtotal's of eact item and have to set them to each item in the list,can anyone please help me for it?My code is as below..Please help me save my life...thank you
main.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.ProgressDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Adapter;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import com.epe.yehki.adapter.CartAdapter;
import com.epe.yehki.backend.BackendAPIService;
import com.epe.yehki.util.Const;
import com.epe.yehki.util.Pref;
import com.example.yehki.R;
public class CartListActivity extends Activity {
private ProgressDialog pDialog;
Intent in = null;
ListView lv;
JSONObject jsonObj;
ArrayList<HashMap<String, String>> cartList;
Bitmap bitmap;;
private CartAdapter cartContent;
JSONArray carts = null;
ImageView back;
TextView tv_place_order, tv_home;
#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_cart_list);
lv = (ListView) findViewById(R.id.cart_list);
back = (ImageView) findViewById(R.id.iv_bak);
tv_place_order = (TextView) findViewById(R.id.tv_place_order);
tv_home = (TextView) findViewById(R.id.tv_home);
cartList = new ArrayList<HashMap<String, String>>();
back.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
finish();
}
});
// execute the cartList api()...........!!!!
new GetCartList().execute();
// listView ClickEvent
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
lv.removeViewAt(position);
cartContent.notifyDataSetChanged();
}
});
tv_home.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
in = new Intent(CartListActivity.this, HomeActivity.class);
startActivity(in);
}
});
tv_place_order.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
}
});
}
/*
* CART LIST PRODUCT LIST...............!!!!!!!!!
*/
private class GetCartList extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(CartListActivity.this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
// Creating service handler class instance
String cartUrl = Const.API_CART_LIST + "?customer_id=" + Pref.getValue(CartListActivity.this, Const.PREF_CUSTOMER_ID, "");
BackendAPIService sh = new BackendAPIService();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(cartUrl, BackendAPIService.GET);
Log.d("Response: ", "> " + jsonStr);
try {
if (jsonStr != null) {
jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
if (jsonObj.has(Const.TAG_PRO_LIST)) {
carts = jsonObj.getJSONArray(Const.TAG_PRO_LIST);
if (carts != null && carts.length() != 0) {
// looping through All Contacts
for (int i = 0; i < carts.length(); i++) {
JSONObject c = carts.getJSONObject(i);
String proId = c.getString(Const.TAG_PRODUCT_ID);
String proName = c.getString(Const.TAG_PRODUCT_NAME);
String wPrice = c.getString(Const.TAG_WHOLESALE_PRICE);
String rPrice = c.getString(Const.TAG_RETAIL_PRICE);
String qty = c.getString(Const.TAG_QUANTITY);
String proimg = Const.API_HOST + "/" + c.getString(Const.TAG_PRODUCT_IMG);
HashMap<String, String> cartProduct = new HashMap<String, String>();
cartProduct.put(Const.TAG_PRODUCT_ID, proId);
cartProduct.put(Const.TAG_PRODUCT_NAME, proName);
cartProduct.put(Const.TAG_PRODUCT_IMG, proimg);
cartProduct.put(Const.TAG_WHOLESALE_PRICE, wPrice);
cartProduct.put(Const.TAG_RETAIL_PRICE, rPrice);
cartProduct.put(Const.TAG_QUANTITY, qty);
cartList.add(cartProduct);
}
}
}
} 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
*
* */
cartContent = new CartAdapter(CartListActivity.this, cartList);
lv.setAdapter(cartContent);
}
}
}
In ListAdapter, getItem() should return an item using which you populate the Views
#Override
public HashMap<String, String> getItem(int paramInt) {
return cartArray.get(paramInt);
}
To get all values,
final CartAdapter adapter = (CardAdapter) lv.getAdapter();
for (int i = 0; i < adapter.getCount(); i++) {
final HashMap<String, String> item = adapter.getItem(i);
final String quantity = item.get(Const.TAG_QUANTITY); // value of EditText of one row
}
I have written a code to get all the videos related to a specific user in YouTube as follows:
import java.util.ArrayList;
import java.util.Collection;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.DefaultClientConnection;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;
import com.example.tstnetconnwithjson.tables.custome;
import com.example.tstnetconnwithjson.tables.videos;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
public class MainActivity extends Activity {
Button search; ;
TextView name ;
ListView listview ;
ArrayList<videos > videolist;
ArrayAdapter< videos > adapter ;
AlertDialog.Builder alert ;
ProgressDialog progressdialog ;
EditText name;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
videolist = new ArrayList<videos>();
adapter = new ArrayAdapter<videos>(this, android.R.layout.simple_list_item_1 , android.R.id.text1,videolist);
name=(EditText) findViewById(R.id.editText1);
alert = new Builder(this);
alert.setTitle("Warnning" ) ;
alert.setMessage("You want to connect to the internet ..? " );
alert.setNegativeButton("No ", null);
alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface arg0, int arg1) {
String username=name.getText().toString();
new connection().execute("https://gdata.youtube.com/feeds/api/videos?author="+username+"&v=2&alt=jsonc");
}
});
progressdialog = new ProgressDialog(this);
progressdialog.setMessage("Wait Loading .... ");
progressdialog.setCancelable(false);
search = (Button) findViewById(R.id.button1);
name = (TextView) findViewById(R.id.textView1);
listview = (ListView) findViewById(R.id.listView1);
listview.setAdapter(adapter);
search.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
alert.show();
}
});
}
class connection extends AsyncTask<String, Integer, String>{
#Override
protected void onPreExecute() {
progressdialog.show();
super.onPreExecute();
}
#Override
protected String doInBackground(String... arg0) {
String s = GetUrlBody(arg0[0]);
return s;
}
#Override
protected void onPostExecute(String result) {
try{
JSONObject jo =(JSONObject) new JSONTokener(result).nextValue();
JSONObject feed = jo.optJSONObject("data");
JSONArray entry = feed.optJSONArray("items");
for(int i = 0 ; i<entry.length() ; i++){
String title = entry.getJSONObject(i).getString("title");
String thumbURL = entry.getJSONObject(i).getJSONObject("thumbnail").getString("sqDefault");
Log.d("after get image", "ok")
String url;
try {
url = entry.getJSONObject(i).getJSONObject("player").getString("mobile");
} catch (JSONException ignore) {
url = entry.getJSONObject(i).getJSONObject("player").getString("default");
}
String description = entry.getJSONObject(i).getString("description");
Log.d("after get description", "ok");
videos videoobject=new videos();
videoobject.setDecscrption(description);
videoobject.setImageurl(thumbURL);
videoobject.setVediourl(url);
videoobject.setVideoname(title);
videolist.add(videoobject);
}
listview.setAdapter(new custome(MainActivity.this,videolist));
Log.d("AFTER set custome ", "before notify changes");
adapter.notifyDataSetChanged();
}catch(Exception exception) {
Log.d("exception ", "nock nock nock....");
Log.e("json ", exception.getMessage());
}
progressdialog.dismiss();
super.onPostExecute(result);
}
String GetUrlBody (String Url ){
HttpClient client = new DefaultHttpClient();
HttpGet gethttp = new HttpGet(Url);
try{
HttpResponse response = client.execute(gethttp);
if(response.getStatusLine().getStatusCode() == 200){
String save =
EntityUtils.toString(response.getEntity(), HTTP.UTF_8);
return save;
}else {
return "Not Found";
}
}catch(Exception exception){}
return null;
}
}
}
Where the custome class is extends from base adapter in order to have list view with image view set to video image and text view set to video title.
In log cat messages the result are existed but my list view returns empty.
Can any one tell me why?
here is the code for costume list view:
public class custome extends BaseAdapter {
ArrayList<videos> data=new ArrayList<videos>();
android.content.Context context1;
android.widget.TextView name;
ImageView picture;
public custome(Context context,ArrayList<videos>arrayList) {
// TODO Auto-generated constructor stub
context=context;
arrayList=data;
}
public int getCount() {
// TODO Auto-generated method stub
return data.size();
}
public Object getItem(int arg0) {
// TODO Auto-generated method stub
return data.get(arg0);
}
public long getItemId(int arg0) {
// TODO Auto-generated method stub
return arg0;
}
public View getView(int arg0, View arg1, ViewGroup arg2) {
View view=arg1;
if(view==null)
{
LayoutInflater layoutInflater=(LayoutInflater) _c.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view=layoutInflater.inflate(R.layout.listvideo,null);
}
name=(TextView) view.findViewById(R.id.textView1);
picture=(ImageView) view.findViewById(R.id.imageView1);
videos video = data.get(arg0);
name.setText(video.getVideoname());
URL url = null;
try {
url = new URL(video.getImageurl());
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Bitmap bitmap = null;
try {
bitmap = BitmapFactory.decodeStream(url.openConnection().getInputStream());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
picture.setImageBitmap(bitmap);
return view;
}
}
The problem is in your assigning code of custome constructor:
Use this constructor:
public custome(Context context,ArrayList<videos> arrayList) {
context=context;
//arrayList=data;<<< WRONG
data=arrayList;//<<<<<<< Correct way of assigning
}
You are overriding your adapter here:
listview.setAdapter(new custome(MainActivity.this,videolist));
Remove this line