how to work on BUY NOW button in android? - android

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");
}
}

Related

onBackPressed() unfortunately app has stopped in android phone

I am developing an eCommerce application where most of the java class file using Async Task for fetching data from server and I am using fragment in all java class . My problem is that when I click OnBackPressed it shows error in Async Task line because it takes some time interval again to fetch data from server..
MainActivity.java
package com.prashant;
import android.app.SearchManager;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.view.MenuItemCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.SearchView;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.os.Handler;
import android.widget.GridView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity implements android.support.v7.app.ActionBar.OnNavigationListener {
TextView txtView;
private static MainActivity sMainActivity;
ProgressBar prgLoading;
RelativeLayout drawerPane;
DrawerLayout drawerLayout;
GridView lvNav;
TextView Customer_name;
TextView Customer_email;
TextView Customer_mob;
List<NavItem> listNavItems;
List<Fragment> listFragment;
private Boolean exit = false;
ActionBarDrawerToggle actionBarDrawerToggle;
public int hot_number = Constants.ProductCart_Id.size();
private TextView ui_hot = null;
private boolean mNaviFirstHit = true;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sMainActivity = this;
// Styling Action Bar
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setBackgroundDrawable(new ColorDrawable(Color.rgb(7,112,200)));
drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
//Getting Session Information Of Customer
String MyPREFERENCES = "CustomerData";
SharedPreferences sharedpreferences =getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
Constants.Customer_FirstName= sharedpreferences.getString("Customer_FirstName","");
Constants.Customer_LastName=sharedpreferences.getString("Customer_LastName", "");
Constants.Customer_MobileNo=sharedpreferences.getString("Customer_MobileNo", "");
Constants.Customer_Id=sharedpreferences.getInt("Customer_Id", 0);
Constants.Customer_Email=sharedpreferences.getString("Customer_Email", "");
Customer_email.setText(Constants.Customer_Email);
//Asigning FRagment names of sidebar
listNavItems = new ArrayList<NavItem>();
listNavItems.add(new NavItem("Home", null, R.drawable.pras));
for(int i=0;i<Constants.Category_name.size();i++){
listNavItems.add(new NavItem(Constants.Category_name.get(i),null,R.drawable.teju));
}
NavListAdapter navListAdapter = new NavListAdapter(getApplicationContext(), R.layout.item_nav_list, listNavItems);
lvNav.setAdapter(navListAdapter);
listFragment = new ArrayList<Fragment>();
listFragment.add(new MyHome());
for(int i=0;i<Constants.Category_name.size();i++){
listFragment.add(new ProductsListFragment());
}
listFragment.add(new MyHome());
listFragment.add(new ActivityCart());
listFragment.add(new LoginFragment());
listFragment.add(new MyAbout());
//Asigning FRagment names of sidebar
//Saving fragment data as constants for my home categories
Constants.listNavItems=listNavItems;
Constants.listFragment=listFragment;
//Saving fragment data as constants for my home categories
//Load first fragment as default:
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction().replace(R.id.main_content, listFragment.get(0)).commit();
setTitle(listNavItems.get(0).getTitle());
lvNav.setItemChecked(0, true);
drawerLayout.closeDrawer(drawerPane);
// create listener for drawer layout
actionBarDrawerToggle = new ActionBarDrawerToggle(this, drawerLayout, R.string.drawer_open , R.string.drawer_close)
{
#Override
public void onDrawerOpened(View drawerView)
{
invalidateOptionsMenu();
super.onDrawerOpened(drawerView);
}
#Override
public void onDrawerClosed(View drawerView)
{
invalidateOptionsMenu();
super.onDrawerClosed(drawerView);
}
};
drawerLayout.setDrawerListener(actionBarDrawerToggle);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
final Menu mMenu = menu;
MenuInflater mif = getMenuInflater();
mif.inflate(R.menu.actionbar_icon_menu, menu);
// Cart Icon in Action Bar
final View menu_hotlist = menu.findItem(R.id.cart_icon).getActionView();
ui_hot = (TextView) menu_hotlist.findViewById(R.id.hotlist_Cart_hot);
updateHotCount(hot_number);
menu_hotlist.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Constants.lastDetails = false;
FragmentManager fragmentManager = getSupportFragmentManager();
ActivityCart cart = new ActivityCart();
fragmentManager.beginTransaction().replace(R.id.main_content, cart).commit();
setTitle("Cart");
drawerLayout.closeDrawer(drawerPane);
}
});
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item){
if(actionBarDrawerToggle.onOptionsItemSelected(item))
return true;
// Take appropriate action for each action item click
switch (item.getItemId()) {
case R.id.cart_icon:
// search action
FragmentManager fragmentManager = getSupportFragmentManager();
ActivityCart cart = new ActivityCart();
fragmentManager.beginTransaction().replace(R.id.main_content, cart).commit();
setTitle("Cart");
drawerLayout.closeDrawer(drawerPane);
return true;
case R.id.action_search:
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
actionBarDrawerToggle.syncState();
}
#Override
public void onBackPressed() {
if (getFragmentManager().getBackStackEntryCount() >0) {
getFragmentManager().popBackStack();
} else {
super.onBackPressed();
}
}
#Override
public boolean onNavigationItemSelected(int itemPosition, long itemId) {
if (mNaviFirstHit) {
mNaviFirstHit = false;
return true;
}
else {
if(itemPosition == 0)
Constants.isCallParent = true;
else
Constants.isCallParent = false;
Constants.SubCatposition = itemPosition;
ProductsListFragment productsListFragment = new ProductsListFragment();
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction().replace(R.id.main_content, productsListFragment).commit();
//lvNav.setItemChecked(position, true);
drawerLayout.closeDrawer(drawerPane);
//Toast.makeText(this, "Clicked at: " + itemPosition, Toast.LENGTH_LONG).show();
//mNaviFirstHit = true;
return true;
}
}
public void setLoginDetails(){
Customer_email.setText(Constants.Customer_Email);
Customer_name.setText("Welcome, " + Constants.Customer_FirstName);
Customer_name.setText(Constants.Customer_LastName);
}
}
ProductListFragment.java
package com.prashant;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.FragmentManager;
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 org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;
import org.xmlpull.v1.XmlPullParserException;
import java.io.IOException;
import java.util.ArrayList;
/**
* Created by prashant.
*/
public class ProductsListFragment extends Fragment {
ProgressDialog pdialog;
View v;
Button sort,filter;
//ListView list;
GridView list;
LazyImageLoadAdapter adapter;
private static ProductsListFragment sProductsListFragment;
// Title navigation Spinner data
private ArrayList<SpinnerNavItem> navSpinner;
// Navigation adapter
private TitleNavigationAdapter titleNavigationAdapter;
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//((AppCompatActivity) getActivity()).getSupportActionBar().setSubtitle(null);
//((MainActivity)getActivity()).actionBarDrawerToggle.setDrawerIndicatorEnabled(true);
// Action Bar
((MainActivity)getActivity()).getSupportActionBar().setDisplayShowTitleEnabled(false);
((MainActivity)getActivity()).getSupportActionBar().setNavigationMode(((MainActivity) getActivity()).getSupportActionBar().NAVIGATION_MODE_LIST);
}
#Override
public View onCreateView(LayoutInflater inflater,#Nullable ViewGroup container,#Nullable Bundle savedInstanceState) {
v = inflater.inflate(R.layout.productlistfragment, container, false);
sProductsListFragment = this;
list=(GridView)v.findViewById(R.id.list);
sort = (Button) v.findViewById(R.id.btn_sort);
sort.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(getActivity(),Pop.class));
}
});
//clearData();
return v;
}
#Override
public void onResume() {
super.onResume();
((AppCompatActivity) getActivity()).getSupportActionBar().setSubtitle(null);
((MainActivity)getActivity()).actionBarDrawerToggle.setDrawerIndicatorEnabled(true);
}
#Override
public void onPause() {
super.onPause();
((MainActivity)getActivity()).getSupportActionBar().setDisplayShowTitleEnabled(true);
}
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
Constants.cartEntry=0;
//check Product Description fragment is called or not
if (!Constants.lastDetails) {
clearData();
new getDataTask().execute();
}
else{
String[] images=new String[Constants.Product_image.size()];
images=Constants.Product_image.toArray(images);
adapter = new LazyImageLoadAdapter(getActivity(), images);
//Set adapter to listview
list.setAdapter(adapter);
Constants.lastDetails = false;
}
}
// clear arraylist variables before used
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();
}
#Override
public void onDestroy()
{
// Remove adapter refference from list
//list.setAdapter(null);
//Refresh cache directory downloaded images
//adapter.imageLoader.clearCache();
//adapter.notifyDataSetChanged();
super.onDestroy();
}
public View.OnClickListener listener=new View.OnClickListener(){
#Override
public void onClick(View arg0) {
//Refresh cache directory downloaded images
adapter.imageLoader.clearCache();
adapter.notifyDataSetChanged();
}
};
public void onItemClick(int mPosition)
{
/*
Intent intent = new Intent(getActivity(), ProductDescription.class);
intent.putExtra("descposition", mPosition);
startActivity(intent);*/
Constants.product_position = mPosition;
ProductDescription productDescription=new ProductDescription();
getActivity().getSupportFragmentManager().beginTransaction().replace(R.id.main_content, productDescription, null).addToBackStack("productDescription").commit();
//((AppCompatActivity) getActivity()).getSupportActionBar().setSubtitle(Constants.Product_name.get(mPosition));
getActivity().setTitle("Product Details");
}
// 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
parseJSONData();
return null;
}
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
// Create custom adapter for listview
String[] images=new String[Constants.Product_image.size()];
images=Constants.Product_image.toArray(images);
adapter = new LazyImageLoadAdapter(getActivity(), images);
//Set adapter to listview
list.setAdapter(adapter);
if (!Constants.isSubCategory) {
Constants.isSubCategory = true;
// Spinner title navigation data
navSpinner = new ArrayList<SpinnerNavItem>();
navSpinner.add(new SpinnerNavItem(Constants.Category_name.get(Constants.position - 1), R.drawable.icon));
for (int i = 0; i < Constants.SubCategory_ID.size(); i++) {
navSpinner.add(new SpinnerNavItem(Constants.SubCategory_name.get(i), R.drawable.icon));
}
// title drop down adapter
titleNavigationAdapter = new TitleNavigationAdapter(getActivity(), navSpinner);
// assigning the spinner navigation
((MainActivity) getActivity()).getSupportActionBar().setListNavigationCallbacks(titleNavigationAdapter, ((MainActivity) getActivity()));
}
if (pdialog.isShowing()){
pdialog.dismiss();
pdialog=null;
}
if (Constants.Product_ID.isEmpty()){
// Toast.makeText(getActivity(), "No products found!!Check your internet connection!!", Toast.LENGTH_LONG).show();
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle("No Product Found!!").setMessage("Slow Internet/Check Your Internet Settings").create().show();
}
/*for (int i = 0; i < Constants.Product_ID.size(); i++) {
Toast.makeText(getActivity(), "__" + Constants.Product_ID.get(i) + "__" + i, Toast.LENGTH_SHORT).show();
}*/
// if internet connection and data available show data on list
// otherwise, show alert text
}
}
// method to parse json data from server
public void parseJSONData(){
SoapObject request = new SoapObject(Constants.NAMESPACE, "catalogCategoryAssignedProducts");
String Catid;
// add paramaters and values
request.addProperty("sessionId", Constants.sessionId);
if ((!Constants.isSubCategory) || Constants.isCallParent) {
Constants.isCallParent = false;
request.addProperty("categoryId", String.valueOf(Constants.Category_ID.get(Constants.position - 1)));
Catid=String.valueOf(Constants.Category_ID.get(Constants.position - 1));
}
else {
request.addProperty("categoryId", String.valueOf(Constants.SubCategory_ID.get(Constants.SubCatposition - 1)));
Catid=String.valueOf(Constants.SubCategory_ID.get(Constants.SubCatposition - 1));
}
api_calls call=new api_calls();
call.getCategoryProducts(Catid);
if (!Constants.isSubCategory) {
Constants.SubCategory_ID.clear();
Constants.SubCategory_name.clear();
parseJSONDataSubCategory();
}
}
// method to parse json data from server
public void parseJSONDataSubCategory(){
try {
SoapObject request = new SoapObject(Constants.NAMESPACE, "catalogCategoryTree");
// add paramaters and values
request.addProperty("sessionId", Constants.sessionId);
request.addProperty("parentId", Constants.Category_ID.get(Constants.position-1));
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
SoapObject result2 = (SoapObject) envelope.getResponse();
SoapObject pii2 = (SoapObject) result2.getProperty(5);
for (int i = 0; i < pii2.getPropertyCount(); i++) {
//JSONObject object = data.getJSONObject(i);
SoapObject pii = (SoapObject)pii2.getProperty(i);
//JSONObject category = object.getJSONObject("Category");
Constants.SubCategory_ID.add(Long.parseLong(pii.getProperty(0).toString()));
Constants.SubCategory_name.add(pii.getProperty(2).toString());
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (XmlPullParserException e) {
e.printStackTrace();
}
}
// Making Sub Drawer for Sub Category
public static ProductsListFragment getInstance() {
return sProductsListFragment;
}
public void onBackPressed()
{
FragmentManager fm = getActivity().getSupportFragmentManager();
fm.popBackStack();
}
}
Logcat
02-11 12:39:57.838 12954-14579/? E/AndroidRuntime: FATAL EXCEPTION: AsyncTask #5
Process: com.softonetech.www.takenick, PID: 12954
java.lang.RuntimeException: An error occurred while executing doInBackground()
at android.os.AsyncTask$3.done(AsyncTask.java:309)
at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:354)
at java.util.concurrent.FutureTask.setException(FutureTask.java:223)
at java.util.concurrent.FutureTask.run(FutureTask.java:242)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:234)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588)
at java.lang.Thread.run(Thread.java:818)
Caused by: java.lang.ArrayIndexOutOfBoundsException: length=12; index=-1
at java.util.ArrayList.get(ArrayList.java:310)
at com.prashant.ProductsListFragment.parseJSONData(ProductsListFragment.java:250)
at com.prashant.ProductsListFragment$getDataTask.doInBackground(ProductsListFragment.java:185)
at com.prashant.ProductsListFragment$getDataTask.doInBackground(ProductsListFragment.java:167)
at android.os.AsyncTask$2.call(AsyncTask.java:295)
at java.util.concurrent.FutureTask.run(FutureTask.java:237)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:234) 
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113) 
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588) 
at java.lang.Thread.run(Thread.java:818) 
try cancelling your Async task execution during onBackPressed()
Declare:
Public getDataTask asyncFetchData;
asyncFetchData = new getDataTask();
asyncFetchData.execute();
Now in your Fragment:
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
getView().setFocusableInTouchMode(true);
getView().requestFocus();
getView().setOnKeyListener(new View.OnKeyListener() {
#Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
if (event.getAction() == KeyEvent.ACTION_DOWN) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
if (asyncFetchData!= null)
asyncFetchData.cancel(true);
Toast.makeText(getActivity(), "Back pressed...", Toast.LENGTH_SHORT).show();
return true;
}
}
return false;
}
});
}
Also in doInBackground notify the AsyncTask to cancel execution
#Override
protected Void doInBackground(Void... arg0) {
// TODO Auto-generated method stub
// parse json data from server in background
parseJSONData();
if (isCancelled()) break;
return null;
}

Using android radio button to execute method

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();
}
}
}

OnItemSelectedListener kept changing to adapter view

I want to create a spinner that retrieve data from database but OnItemSelectedListener won't work. It keeps suggesting to adapterview.OnclickListener but the coding need OnClickListenerOnly.
package com.example.win7.fyp;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.Settings;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
public class student_register extends Activity implements OnItemSelectedListener {
Toolbar toolbar;
private ProgressDialog progressDialog;
JsonParser jParser = new JsonParser();
private static String URL_TO_PASS = "http://arcafyp.xyz/chat/register_student.php";
SharedPreferences pref;
EditText username5, password5 ,advisorName5;
TextView advReg;
String username1;
String AndroidId;
private ArrayList<Category> categoriesList;
ProgressDialog pDialog;
private Spinner spinnerFood;
// Url to get all categories
private String URL_CATEGORIES = "http://ekinidris.site40.net/chat/advisorName.php";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_student_register);
pref = getApplicationContext().getSharedPreferences("MyPref", 0);// 0 - for private mode
username5 = (EditText)findViewById(R.id.register_matrixno);
password5 = (EditText) findViewById(R.id.register_ic);
advisorName5 = (EditText) findViewById(R.id.advName);
spinnerFood.setOnItemSelectedListener(this);
spinnerFood = (Spinner) findViewById(R.id.spinFood);
categoriesList = new ArrayList<Category>();
// Add new category click event
new GetCategories().execute();
}
private class GetCategories extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(student_register.this);
pDialog.setMessage("Fetching advisor name..");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
ServiceHandler jsonParser = new ServiceHandler();
String json = jsonParser.makeServiceCall(URL_CATEGORIES, ServiceHandler.GET);
Log.e("Response: ", "> " + json);
if (json != null) {
try {
JSONObject jsonObj = new JSONObject(json);
if (jsonObj != null) {
JSONArray categories = jsonObj
.getJSONArray("categories");
for (int i = 0; i < categories.length(); i++) {
JSONObject catObj = (JSONObject) categories.get(i);
Category cat = new Category(catObj.getInt("phone_id"),
catObj.getString("name"));
categoriesList.add(cat);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("JSON Data", "Didn't receive any data from server!");
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
if (pDialog.isShowing())
pDialog.dismiss();
//populateSpinner();
}
}
/**
* Adding spinner data
* */
private void populateSpinner() {
List<String> lables = new ArrayList<String>();
advisorName5.setText("");
for (int i = 0; i < categoriesList.size(); i++) {
lables.add(categoriesList.get(i).getName());
}
// Creating adapter for spinner
ArrayAdapter<String> spinnerAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, lables);
// Drop down layout style - list view with radio button
spinnerAdapter
.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// attaching data adapter to spinner
spinnerFood.setAdapter(spinnerAdapter);
}
#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_student_register, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.register_send) {
new registerUser().execute();
String newCategory = advisorName5.getText().toString();
return true;
}
return super.onOptionsItemSelected(item);
}
class registerUser extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
Intent i = getIntent();
String studentPhone_id = i.getStringExtra("phone_id").toString();
String studentUsername = username5.getText().toString();
progressDialog = new ProgressDialog(student_register.this);
progressDialog.setMessage("Processing Data" + studentPhone_id + studentUsername);
progressDialog.setIndeterminate(false);
progressDialog.setCancelable(true);
progressDialog.show();
}
#Override
protected String doInBackground(String... strings) {
String studentUsername = username5.getText().toString(); // matrix no
String studentPassword = password5.getText().toString(); //cgpa
String studentAdvName = advisorName5.getText().toString(); //advisor name
Intent i = getIntent();
String studentPhone_id = i.getStringExtra("phone_id").toString();
List<NameValuePair> param = new ArrayList<NameValuePair>();
param.add(new BasicNameValuePair("username",studentUsername));
param.add(new BasicNameValuePair("phone_id",studentPhone_id));
param.add(new BasicNameValuePair("password", studentPassword));
param.add(new BasicNameValuePair("advisorName", studentAdvName));
JSONObject json = jParser.makeHttpRequest("http://ekinidris.site40.net/chat/register_student.php","POST",param);
SharedPreferences.Editor editor = pref.edit();
Log.d("data", json.toString());
try {
int result = json.getInt("success");
if(result == 1) {
editor.putString("phone_id",studentPhone_id);
editor.commit();
Intent intent = new Intent(student_register.this, MainActivity.class);
intent.putExtra("phone_id", studentPhone_id);
intent.putExtra("username",studentUsername);
intent.putExtra("advisorName",studentAdvName);
startActivity(intent);
finish();
progressDialog.dismiss();
}else{
To be edited.....
put some action refreshing the page
}
}catch (JSONException e){
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
progressDialog.dismiss();
finish();
}
}
}
logcat
11-06 16:43:02.289 22071-22071/? E/AndroidRuntime﹕ FATAL EXCEPTION: main
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.win7.fyp/com.example.win7.fyp.student_register}: java.lang.ClassCastException: com.example.win7.fyp.student_register cannot be cast to android.view.View$OnClickListener
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1968)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1993)
at android.app.ActivityThread.access$600(ActivityThread.java:127)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1159)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4507)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:980)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:747)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.ClassCastException: com.example.win7.fyp.student_register cannot be cast to android.view.View$OnClickListener
at com.example.win7.fyp.student_register.onCreate(student_register.java:78)
at android.app.Activity.performCreate(Activity.java:4465)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1052)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1932)
            
follow this code-
spinner1.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
// TODO Auto-generated method stub
String msupplier=supplier.getSelectedItem().toString();
Log.e("Selected item : ",msupplier);
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
I used same answered by sud but with little modification which worked
spinner1.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view,
int pos, long id) {
// TODO Auto-generated method stub
// String msupplier=supplier.getSelectedItem().toString(); instead used below
Log.e("Selected item : ", (String) parent.getItemAtPosition(pos));
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
// TODO Auto-generated method stub
}
});

Data Getting from Webservice Showing in Listview, then Sort the Listview Custom Adapter Based on a item in List

In My Listview having 5 data,but Based On Km Distance Double Value ,sort the Full Listview in Ascending Order. All data fetching from Webservice. Showing Data In Listview Working But only Last Row Data Showing In Full List How to Resolve it Help me
package com.example;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import org.json.JSONArray;
import org.json.JSONObject;
import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.PropertyInfo;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapPrimitive;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.app.ActivityOptions;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.location.Location;
import android.media.Rating;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.Settings;
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.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.RatingBar;
import android.widget.TextView;
import android.widget.Toast;
public class Find_Stores_1_Distance_Based_Tabview1 extends Fragment implements OnClickListener {
ListView listPage;
Button Near_Me, Top_Service, Rating_Based, Add_ServiceCenter;
View rootView;
int[] images = {
R.drawable.shop1,R.drawable.shop2,R.drawable.shop1,
R.drawable.shop1,R.drawable.shop2,R.drawable.shop1,
R.drawable.shop1,R.drawable.shop2,R.drawable.shop1}
Rating rateme;
float ratingValue = 2.0f;
String ServiceModel = " Phone ";
// for WebService Fetch from web to Find stores ..
private static final String SOAP_ACTION = "************";
private static final String NAMESPACE = "************";
private static final String URL = "************";
private static final String METHOD_NAME = "************";
private String TAG2 = "************";
public static String Status_Response_FindStores_Landing = "";
// for WebService Fetch from web to Find stores ..
private static final String SOAP_ACTION1 = ""************"";
private static final String NAMESPACE1 = ""************"";
private static final String URL1 = ""************"";
private static final String METHOD_NAME1 = ""************"";
private String TAG3 = ""************"";
public static String Status_Res_FindStores_Showpage_Data = "";
public String Center_id,Brand_name, ServiceCenterName,Address1,EMailId,ContactNumber,Pincode,Cityname,Latitude1,Longitude1;
public String Center_id2,Brand_name2, ServiceCenterName2,Address2,EMailId2,ContactNumber2,Pincode2,Cityname2;
// flag for Internet connection status
Boolean isInternetPresent = false;
// Connection detector class
InternetConnectionDetector cd1;
// Progress Bar
ProgressBar pg;
private ProgressDialog progress;
String[] SERVICE_CENTERNAME,Full_ADDRESS,CENTER_ID;
String[] KM_DISTANCE_StringArray;
TextView CenterIDText;
public String CategoryStringItem,BrandStringItem,CityStringItem;
public TextView NotfoundText1;
public Button ReloadButton1;
public String centerId_Service,LatitudeSingle_Service,LangitudeSingle_Service;
public String Latittude_LogitutdeString;
double latitude_Current, longitude_current;
// public Float distance;
public double distance1;
GPSTracker gps;
boolean _areLecturesLoaded = false;
//For Creating Double array;
String[] LatitudeArray,LangitudeArray;
public static int StatusoutPutInteger1;
//For Ascending Order Sort
private boolean mAscendingOrder[] = {true, true, true};
private ItemsListAdapter mAdapter;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.find_stores_1_distancebased_tabview1,container, false);
// creating connection Detector class for checking Internet Status
cd1 = new InternetConnectionDetector(getActivity());
// create class object
gps = new GPSTracker(getActivity());
// call the views with this layout
listPage = (ListView) rootView.findViewById(R.id.listView123);
mAdapter = new ItemsListAdapter();
// ((ListView) rootView.findViewById(R.id.listView123)).setAdapter(mAdapter);
listPage.setAdapter(mAdapter);
// fillShoppingList();
return rootView;
}
public void onResume()
{
try {
super.onResume();
// get Internet status
isInternetPresent = cd1.isConnectingToInternet();
// check for Internet status
if (isInternetPresent)
{
// check if GPS enabled
if(gps.canGetLocation()){
latitude_Current = gps.getLatitude();
longitude_current = gps.getLongitude();
// for data Fetch from web
AsyncCallWSfor_PRODUCT task = new AsyncCallWSfor_PRODUCT();
// Call execute
task.execute();
}else{
// can't get location
// GPS or Network is not enabled
// Ask user to enable GPS/network in settings
gps.showSettingsAlert();
}
}
else
{
Toast.makeText(getActivity(),"Please Check Your Internet Connection ..!",Toast.LENGTH_SHORT).show();
}
} catch (Exception e)
{
e.printStackTrace();
Log.i("Exception in Tab1 Onresume","Error");
}
}
// for Product Web Sync
private class AsyncCallWSfor_PRODUCT extends AsyncTask<String, Void, Void> {
#Override
protected Void doInBackground(String... params)
{
Log.i(TAG2, "doInBackground");
try
{
getSignupdata1(CategoryStringItem,BrandStringItem,CityStringItem);
}
catch (Exception e)
{
// Toast.makeText(getActivity(),"error caught in do in background", Toast.LENGTH_SHORT).show();
Log.i(TAG2, "Error in Find Background");
e.printStackTrace();
}
return null;
// return null;
}
#Override
protected void onPostExecute(Void result)
{
//pg.setVisibility(View.INVISIBLE);
// To dismiss the dialog
progress.dismiss();
Log.i(TAG2, "onPostExecute");
try {
// Show items ascending
mAdapter.sortByPriceAsc();
listPage.setOnItemClickListener(new OnItemClickListener()
{
#Override public void onItemClick(AdapterView<?> arg0, View views,int position, long id)
{
try {
// get Internet status
isInternetPresent = cd1.isConnectingToInternet();
// check for Internet status
if (isInternetPresent)
// for Service Center Show page Data Fetch from web
AsyncCallWSfor_FETCHService_Center task = new AsyncCallWSfor_FETCHService_Center();
// Call execute
task.execute();
}
else
{
Toast.makeText(getActivity(),"Please Check Your Internet Connection..!",Toast.LENGTH_SHORT).show();
}
} catch (Exception e)
{
e.printStackTrace();
Log.i("Exception in Tab1 OnItemClick","Error");
}
}
});
}
} catch (Exception e) {
Log.i(TAG2, "Error in Product Insert");
//Toast.makeText(getActivity(), "Error in sucess",Toast.LENGTH_SHORT).show();
e.printStackTrace();
}
}
#Override
protected void onPreExecute()
{
progress.setTitle("Progress");
progress.setMessage("Please Wait Loading...");
progress.setProgressStyle(ProgressDialog.STYLE_SPINNER);
progress.setIndeterminate(true);
progress.show();
}
#Override
protected void onProgressUpdate(Void... values) {
Log.i(TAG2, "onProgressUpdate");
}
}
public void getSignupdata1(String Categoryitem,String Branditem, String CityLocation)
{
// Create request
SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
PropertyInfo pi3 = new PropertyInfo();
pi3.setName("Categ");
pi3.setValue(Categoryitem);// get the string that is to be sent to the webservice
pi3.setType(String.class);
request.addProperty(pi3);
PropertyInfo pi4 = new PropertyInfo();
pi4.setName("Band");
pi4.setValue(Branditem);// get the string that is to be sent to the webservice
pi4.setType(String.class);
request.addProperty(pi4);
PropertyInfo pi5= new PropertyInfo();
pi5.setName("City");
pi5.setValue(CityLocation);// get the string that is to be sent to the webservice
pi5.setType(String.class);
request.addProperty(pi5);
// Create envelope
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.dotNet = true;
// Set output SOAP object
envelope.setOutputSoapObject(request);
// Create HTTP call object
HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);
try {
// Invole web service
androidHttpTransport.call(SOAP_ACTION, envelope);
// Get the response
SoapPrimitive response = (SoapPrimitive) envelope.getResponse();
if ((response.toString()).contains("{"))
{
// JSONArray jr = new JSONArray(response);
SoapObject rep = (SoapObject) envelope.bodyIn;
JSONArray jr = new JSONArray(rep.getPropertyAsString(0));
for (int i = 0; i < jr.length(); i++)
{
JSONObject jb = (JSONObject) jr.get(i);
Center_id = jb.getString("CenterId");
Brand_name = jb.getString("Brand");
ServiceCenterName = jb.getString("Center");
Address1 = jb.getString("Add");
EMailId = jb.getString("mail");
ContactNumber = jb.getString("Contact");
Pincode = jb.getString("PinCode");
Cityname = jb.getString("City");
Latitude1=jb.getString("latitude");
Longitude1=jb.getString("longitude");
double latitude_Doublevalue = Double.parseDouble(Latitude1);
double longitude_Doublevalue = Double.parseDouble(Longitude1);
try
{
Location locationA = new Location("point A");
locationA.setLatitude(latitude_Current);
locationA.setLongitude(longitude_current);
Location locationB = new Location("point B");
locationB.setLatitude(latitude_Doublevalue);
locationB.setLongitude(longitude_Doublevalue);
// distance = locationA.distanceTo(locationB)/1000;//Distance in Kilometers
distance1 = locationA.distanceTo(locationB)/1000;
Log.i("Service_CenterNameStringOutput","Out "+ServiceCenterName);
Log.i("AddressStringOutput","Out "+Address1);
Log.i("DistanceStringOutput","Out "+distance1);
}
catch(Exception ex)
{
ex.printStackTrace();
Log.i(TAG2, "Error in Distance Calculate");
}
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
fillShoppingList(Address1,ServiceCenterName,distance1);
}
});
// Log.i("CenterIdssss", Center_id);
}
}
else
{
Status_Response_FindStores_Landing = response.toString();
}
} catch (Exception e) {
Log.i(TAG2, "Error in Signup1 catch");
e.printStackTrace();
}
}
//GPS Enabler
public void showSettingsAlert() {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(
getActivity());
alertDialog.setTitle("Settings");
alertDialog.setMessage("Enable Location Provider! Go to settings menu?");
alertDialog.setPositiveButton("Settings",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(
Settings.ACTION_LOCATION_SOURCE_SETTINGS);
getActivity().startActivity(intent);
}
});
alertDialog.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
alertDialog.show();
}
private void fillShoppingList(String address12, String serviceCenterName3, double distance12string )
{
SortAscendingClass item = new SortAscendingClass();
item.setAddressArray(address12);
item.setCmpy_NameArray(serviceCenterName3);
item.setDistancekmArray(distance12string);
mAdapter.addItem(item);
//mAdapter.sortByPriceAsc();
}
/** Adapter for the shopping list items */
private class ItemsListAdapter extends BaseAdapter {
private LayoutInflater vi;
private ArrayList<SortAscendingClass> shoppingList = new ArrayList<SortAscendingClass>();
public ItemsListAdapter()
{
vi = (LayoutInflater)getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
/** Add white line */
public void addItem(SortAscendingClass item) {
shoppingList.add(item);
notifyDataSetChanged();
}
/** Sort shopping list by price ascending */
public void sortByPriceAsc() {
Comparator<SortAscendingClass> comparator = new Comparator<SortAscendingClass>() {
#Override
public int compare(SortAscendingClass object1, SortAscendingClass object2) {
return Double.compare(object1.getDistancekmArray(), object2.getDistancekmArray());
}
};
Collections.sort(shoppingList, comparator);
notifyDataSetChanged();
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
if (convertView == null) {
holder = new ViewHolder();
convertView = vi.inflate(R.layout.findstores_service_center_tabview1_2_3_listview, null);
holder.myImage = (ImageView) convertView.findViewById(R.id.imageView1);
holder.ServcieCenterFullname = (TextView) convertView.findViewById(R.id.textView1);
holder.AddressName = (TextView) convertView.findViewById(R.id.textView2);
holder.ratingtext = (RatingBar)convertView.findViewById(R.id.ratingBarinTabs);
holder.myDistance = (TextView) convertView.findViewById(R.id.Distance);
holder.SErvice_Available = (TextView) convertView.findViewById(R.id.serviceCategory);
/*holder.CenterIDText=(TextView)convertView.findViewById(R.id.CenterId_xml);
holder.LatitudeText=(TextView)convertView.findViewById(R.id.latitude_xml);
holder.LangitudeText=(TextView)convertView.findViewById(R.id.langitude_xml);*/
convertView.setTag(holder);
}
else {
holder = (ViewHolder) convertView.getTag();
}
holder.myImage.setImageResource(images[position]);
holder.ServcieCenterFullname.setText(String.valueOf(shoppingList.get(position).getCmpy_NameArray()));
holder.AddressName.setText(String.valueOf(shoppingList.get(position).getAddressArray()));
holder.ratingtext.setRating(ratingValue); // to set rating value
holder.myDistance.setText(String.valueOf(shoppingList.get(position).getDistancekmArray()+" Km"));
holder.SErvice_Available.setText(ServiceModel);
return convertView;
}
#Override
public int getCount() {
return shoppingList.size();
}
#Override
public Object getItem(int position) {
return shoppingList.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
/** Helper class acting as a holder of the information for each row */
private class ViewHolder {
/*public TextView name;
public TextView price;
public TextView quantity;*/
public ImageView myImage;
public TextView ServcieCenterFullname;
public TextView AddressName ;
public RatingBar ratingtext ;
public TextView myDistance;
public TextView SErvice_Available;
public TextView CenterIDText;
public TextView LatitudeText;
public TextView LangitudeText;
}
}
}
You can use Collections and ArrayList also to sort out as per below.
Collections.sort(YourArrayList);
You can sort your adapter backing the ListView by that listview will automatically sort.
Use an ArrayAdapter, order the elements inside the array asociated whit the adapter by your integer and link the adapter to your listView.

How to solve empty costume list view issue?

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

Categories

Resources