onBackPressed() unfortunately app has stopped in android phone - android

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

Related

how to work on BUY NOW button in 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");
}
}

First item displayed two times in the Listview Android

Hi I already posted the question before but again same question with details ,
I created a a NavigationDrawer in the app , Its working fine but the problem is that in FolderActivity the first Item as a title displayed two time in navigation drawer, I posted the code below please suggest me solution if any...!
navigation_drawer_class.java
package com.abc;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.R.*;
import android.app.ActionBar;
import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.AsyncTask;
import android.os.BaseBundle;
import android.os.Bundle;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.widget.DrawerLayout;
import android.util.Log;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.FrameLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
public class navigation_drawer_class extends Activity
{
private static final int Copy = 0;
int a =0;
public static FrameLayout frameLayout;
TextView mytextview;
public static ListView mDrawerList;
public DrawerLayout mDrawerLayout;
String Fullname;
protected String[] listArray = {"Home","Queue","Inbox","Create Ticket","Search","Clients","App settings"};
protected static int position;
private static boolean isLaunch = true;
JSONObject post_details_obj,post_obj;
public static String FIRST_NAME="first_name",LAST_NAME="last_name",PROFILE_IMAGE="image_name";
JSONArray staff_data_array;
private ActionBarDrawerToggle actionBarDrawerToggle;
Operation op=new Operation();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getActionBar().setHomeAsUpIndicator(R.drawable.crop3);//THIS ONE FOR THE DRAWER LOGO
frameLayout = (FrameLayout)findViewById(R.id.content_frame);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerList = (ListView) findViewById(R.id.left_drawer);
mDrawerList.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, listArray));
View header = (View)getLayoutInflater().inflate(R.layout.headerview_nav_drawer,null);
TextView headerValue = (TextView) header.findViewById(R.id.headerview_id);
headerValue.setText("");
new getname().execute();
mDrawerList.setOnItemClickListener(new OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id)
{
position -= mDrawerList.getHeaderViewsCount();//THIS ONE FOR THE FIRST ITEM AS TITLE
openActivity(position);
}
});
getActionBar().setDisplayHomeAsUpEnabled(true);
getActionBar().setHomeButtonEnabled(true);
actionBarDrawerToggle = new ActionBarDrawerToggle(
this, // host Activity
mDrawerLayout, // DrawerLayout object
R.drawable.ic_launcher, // nav drawer image to replace 'Up' caret
R.string.open_drawer, // "open drawer" description for accessibility
R.string.close_drawer) // "close drawer" description for accessibility
{
#Override
public void onDrawerClosed(View drawerView)
{
getActionBar().setTitle(listArray[position]);
invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
super.onDrawerClosed(drawerView);
}
#Override
public void onDrawerOpened(View drawerView)
{
getActionBar().setTitle(getString(R.string.app_name));
invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
super.onDrawerOpened(drawerView);
}
#Override
public void onDrawerSlide(View drawerView, float slideOffset)
{
super.onDrawerSlide(drawerView, slideOffset);
}
#Override
public void onDrawerStateChanged(int newState)
{
super.onDrawerStateChanged(newState);
}
};
mDrawerLayout.setDrawerListener(actionBarDrawerToggle);
if(isLaunch){
isLaunch = false;
openActivity(0);
}
}
protected void openActivity(int position) {
//mDrawerList.setItemChecked(position, true);
//setTitle(listArray[position]);
mDrawerLayout.closeDrawer(mDrawerList);
navigation_drawer_class.position = position; //Setting currently selected position in this field so that it will be available in our child activities.
switch (position) {
case 0:
startActivity(new Intent(this, Folders.class));
break;
case 1:
Intent i=new Intent(navigation_drawer_class.this,G.class);
startActivity(i);
break;
case 2:
Intent inbox=new Intent(navigation_drawer_class.this,E.class);
startActivity(inbox);
break;
case 3:
startActivity(new Intent(this, S.class));
break;
case 4:
startActivity(new Intent(this, A.class));
break;
case 5:
startActivity(new Intent(this, P.class));
break;
case 6:
startActivity(new Intent(this, V.class));
break;
default:
break;
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu)
{
// getMenuInflater().inflate(R.menu.main, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item)
{
// The action bar home/up action should open or close the drawer.
// ActionBarDrawerToggle will take care of this.
if (actionBarDrawerToggle.onOptionsItemSelected(item))
{
return true;
}
switch (item.getItemId())
{
default:
return super.onOptionsItemSelected(item);
}
}
#Override
public boolean onPrepareOptionsMenu(Menu menu)
{
//boolean drawerOpen = mDrawerLayout.isDrawerOpen(mDrawerList);
//menu.findItem(R.id.action_settings).setVisible(!drawerOpen);
return super.onPrepareOptionsMenu(menu);
}
/* We can override onBackPressed method to toggle navigation drawer*/
#Override
public void onBackPressed()
{
if(mDrawerLayout.isDrawerOpen(mDrawerList))
{
mDrawerLayout.closeDrawer(mDrawerList);
}
else
{
mDrawerLayout.openDrawer(mDrawerList);
}
}
private class getname extends AsyncTask<Void, Void, JSONArray>
{
Dialog dialog;
#Override
public void onPreExecute()
{
dialog = new Dialog(navigation_drawer_class.this,android.R.style.Theme_Translucent_NoTitleBar);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setContentView(R.layout.progressbar);
dialog.show();
}
#Override
protected JSONArray doInBackground(Void... params)
{
String STAFF_URL=op.getUrl(getApplicationContext(),"staff","get_staff_details","");
staff_data_array = JSONfunctions.getJSONfromURL(STAFF_URL+"&vis_encode=json",navigation_drawer_class.this);
return staff_data_array;
}
#Override
public void onPostExecute(JSONArray staff_data_array)
{
super.onPostExecute(staff_data_array);
String staff_data_result =staff_data_array.toString();
try {
post_obj = staff_data_array.getJSONObject(0);
String fname=post_obj.getString(FIRST_NAME);
String lname=post_obj.getString(LAST_NAME);
String image=post_obj.getString(PROFILE_IMAGE);
String fullname =fname;
if(fullname=="")
{
fullname="Admin";
}
Fullname="Welcome "+fullname;
View header = (View)getLayoutInflater().inflate(R.layout.headerview_nav_drawer,null);
TextView headerValue = (TextView) header.findViewById(R.id.headerview_id);
headerValue.setText(Fullname);
headerValue.setCompoundDrawablesWithIntrinsicBounds(R.drawable.default_img,0,0,0);
mDrawerList.addHeaderView(headerValue, null, false);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
dialog.dismiss();
}
}
}
Folders.java
package com.abc;
import java.util.ArrayList;
import android.R.*;
import java.util.HashMap;
import java.util.List;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.ActionBar;
import android.app.Dialog;
import android.app.SearchManager;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.StrictMode;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SearchView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
public class Folders extends navigation_drawer_class {
static final String NEW="A", OVERDUE ="B", ASSIGNED="C", TRASH="D", SPAM="E",NAME="name",COUNT="count";
ListView folders_list;
String[] folders;
String[] filter_id ={"2","3","4","5","6"};
List<String> folder_count;
JSONArray quick_view_array;
JSONObject quick_view_obj,count_obj;
String new_count, overdue_count,assigned_count,trash_count,spam_count;
List<HashMap<String, String>> menuItems;
Dialog dialog;
String URL;
Operation op=new Operation();
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
new getbrand().execute();
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
getLayoutInflater().inflate(R.layout.folders, frameLayout);
mDrawerList.setItemChecked(position, true);
setTitle(listArray[position]);
folders_list = (ListView)findViewById(R.id.folder_display_list);
folders_list.setAdapter(null);
View header = (View)getLayoutInflater().inflate(R.layout.headerview,null);
folders_list.addHeaderView(header, null, false);
if (Operation.isNetworkAvailable(this))
{
new folders().execute();
folders_list.setOnItemClickListener(new OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,long id)
{
position -= folders_list.getHeaderViewsCount();
String fid = filter_id[position];
String title=folders[position];
Intent i=new Intent(Folders.this,Tickets.class);
i.putExtra("filter_id","&vis_filter_id="+fid);
i.putExtra("title",title);
i.putExtra("set_queue","no");
startActivity(i);
}});
}
else
{
Operation.showToast(getApplicationContext(),R.string.no_network);
}
}
private class folders extends AsyncTask<Void, Void, JSONArray>
{
Dialog dialog;
#Override
public void onPreExecute()
{
dialog = new Dialog(Folders.this,android.R.style.Theme_Translucent_NoTitleBar);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setContentView(R.layout.progressbar);
dialog.show();
}
#Override
protected JSONArray doInBackground(Void... params) {
// TODO Auto-generated method stub
URL=op.getUrl(getApplicationContext(),"ticket","quick_view","");
quick_view_array = JSONfunctions.getJSONfromURL(URL+"&vis_encode=json",Folders.this);
return quick_view_array;
}
#Override
public void onPostExecute(JSONArray quick_view_array)
{
super.onPostExecute(quick_view_array);
try
{
quick_view_obj=quick_view_array.getJSONObject(0);
count_obj=quick_view_obj.getJSONObject("count");
folder_count= new ArrayList<String>();
//folder_count.add("");
folder_count.add(count_obj.getString(NEW));
folder_count.add(count_obj.getString(OVERDUE));
folder_count.add(count_obj.getString(ASSIGNED));
folder_count.add(count_obj.getString(TRASH));
folder_count.add(count_obj.getString(SPAM));
folders = getResources().getStringArray(R.array.folders);
menuItems=new ArrayList<HashMap<String, String>>();
for (int i = 0; i <filter_id.length; i++)
{
HashMap<String, String> map = new HashMap<String, String>();
map.put(NAME,folders[i]);
map.put(COUNT,folder_count.get(i));
menuItems.add(map);
}
SimpleAdapter list =new SimpleAdapter
(Folders.this,
menuItems,
R.layout.folders,
new String[] {NAME,COUNT},
new int[] {R.id.folder_name,R.id.folder_count}
)
{ };
folders_list.setAdapter(list);
dialog.dismiss();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// TODO Auto-generated method stub
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.home, menu);
SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
SearchView searchView = (SearchView) menu.findItem(R.id.action_search)
.getActionView();
searchView.setSearchableInfo(searchManager
.getSearchableInfo(getComponentName()));
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
String filter_id = null,Tickets_title = null;
int start_limit=0,page_no=1;
// TODO Auto-generated method stub
switch (item.getItemId())
{
case R.id.menu_inbox:
Intent inbox = new Intent(Folders.this,Test.class);
startActivity(inbox);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
#Override
public void onBackPressed()
{
moveTaskToBack(true);
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_HOME);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
this.finish();
}
private class getbrand extends AsyncTask<Void, Void, JSONArray>
{
Dialog dialog;
#Override
public void onPreExecute()
{
dialog = new Dialog(Folders.this,android.R.style.Theme_Translucent_NoTitleBar);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setContentView(R.layout.progressbar);
dialog.show();
}
#Override
protected JSONArray doInBackground(Void... params)
{
// TODO Auto-generated method stub
String access=op.getUrl(getApplicationContext(),"ticket","get_branding","");
JSONArray access_denied = JSONfunctions.getJSONfromURL(access+"&vis_encode=json",Folders.this);
return access_denied;
}
#Override
public void onPostExecute(JSONArray access_denied)
{
super.onPostExecute(access_denied);
String access_result =access_denied.toString();
ActionBar ab = getActionBar();
if(access_result.equals("[\"1\"]"))
{ ab.setTitle(R.string.app_name);
ab.setIcon(R.drawable.application_icon);
}
else
{
ab.setTitle(R.string.nobrand_app_name);
ab.setBackgroundDrawable(new ColorDrawable(Color.parseColor("#ffffff")));
ab.setHomeAsUpIndicator(R.drawable.crop1);
ab.setIcon(R.drawable.white3);
}
dialog.dismiss();
}
}
private class getname extends AsyncTask<Void, Void, JSONArray>
{
Dialog dialog;
#Override
public void onPreExecute()
{
dialog = new Dialog(Folders.this,android.R.style.Theme_Translucent_NoTitleBar);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setContentView(R.layout.progressbar);
dialog.show();
}
#Override
protected JSONArray doInBackground(Void... params)
{
String STAFF_URL=op.getUrl(getApplicationContext(),"staff","get_staff_details","");
staff_data_array = JSONfunctions.getJSONfromURL(STAFF_URL+"&vis_encode=json",Folders.this);
return staff_data_array;
}
#Override
public void onPostExecute(JSONArray staff_data_array)
{
super.onPostExecute(staff_data_array);
String staff_data_result =staff_data_array.toString();
try {
post_obj = staff_data_array.getJSONObject(0);
String fname=post_obj.getString(FIRST_NAME);
String lname=post_obj.getString(LAST_NAME);
String image=post_obj.getString(PROFILE_IMAGE);
String fullname =fname;
if(fullname=="")
{
fullname="Admin";
}
Fullname="Welcome "+fullname;
TextView tv = new TextView(getApplicationContext());
tv.setText(Fullname);
tv.setBackgroundColor(Color.GREEN);
tv.setCompoundDrawablesWithIntrinsicBounds(R.drawable.default_img,0,0,0);
mDrawerList.addHeaderView(tv, null, false);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
dialog.dismiss();
}
}
}

navigation drawer not working after asynctask

I am using navigation drawer with asynctask in one of the fragments. As soon as I click the element in navigation drawer to start that fragment, my navigation drawer stops working even after the asynctask is finished. I am able to click on navigation drawer and open it , but whenever I click on some other item in navigation drawer, it just closes without loading that fragment associated with that item in nav drawer.
main activity code:
package com.example.home;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import java.io.File;
import java.io.IOException;
import java.net.HttpCookie;
import java.net.URI;
import java.net.URISyntaxException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import org.apache.http.cookie.Cookie;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import com.example.fmapp.R;
import com.example.fmapp.StartActivity;
import com.example.fmapp.R.id;
import com.example.fmapp.R.layout;
import com.example.fmapp.R.menu;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Parcelable;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.annotation.SuppressLint;
import android.app.ActionBar;
import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentManager;
import android.content.ContentUris;
import android.content.Context;
import android.content.Intent;
import android.content.res.Configuration;
import android.database.Cursor;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.Spinner;
import android.widget.SpinnerAdapter;
#SuppressLint("NewApi")
public class Home extends Activity implements ActionBar.OnNavigationListener{
private DrawerLayout mDrawerLayout;
private ListView mDrawerList;
private ActionBarDrawerToggle mDrawerToggle;
private CharSequence mDrawerTitle;
private CharSequence mTitle;
private String[] mDrawerTitles;
static ProgressBar bar;
private String mCurrentPhotoPath;
private final static int FILECHOOSER_RESULTCODE=1;
//public AsyncHttpUpload uploadThread = null;
public ArrayAdapter<String> adapter = null;
#SuppressLint("NewApi")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
Log.i("start","started");
/*
if ((savedInstanceState != null) && (savedInstanceState.getString("currPath")) != null){
mCurrentPhotoPath = savedInstanceState.getString("currPath");
}
*/
bar = (ProgressBar) this.findViewById(R.id.progressBar);
ActionBar actionBar = getActionBar();
actionBar.setDisplayShowTitleEnabled(true);
if (UserInfo.userId == null){
//fetchUserData();
}
else{
//UserInfo.populateSpinner(adapter);
}
mTitle = mDrawerTitle = getTitle();
mDrawerTitles = getResources().getStringArray(R.array.planets_array);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerList = (ListView) findViewById(R.id.left_drawer);
// set a custom shadow that overlays the main content when the drawer opens
mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START);
// set up the drawer's list view with items and click listener
mDrawerList.setAdapter(new ArrayAdapter<String>(this,
R.layout.drawer_list_item, mDrawerTitles));
mDrawerList.setOnItemClickListener(new DrawerItemClickListener());
// enable ActionBar app icon to behave as action to toggle nav drawer
getActionBar().setDisplayHomeAsUpEnabled(true);
getActionBar().setHomeButtonEnabled(true);
// ActionBarDrawerToggle ties together the the proper interactions
// between the sliding drawer and the action bar app icon
mDrawerToggle = new ActionBarDrawerToggle(
this, /* host Activity */
mDrawerLayout, /* DrawerLayout object */
R.drawable.ic_drawer, /* nav drawer image to replace 'Up' caret */
R.string.drawer_open, /* "open drawer" description for accessibility */
R.string.drawer_close /* "close drawer" description for accessibility */
) {
public void onDrawerClosed(View view) {
getActionBar().setTitle(mTitle);
invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
}
public void onDrawerOpened(View drawerView) {
getActionBar().setTitle(mDrawerTitle);
invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
}
};
mDrawerLayout.setDrawerListener(mDrawerToggle);
if (savedInstanceState == null) {
selectItem(0);
}
}
#SuppressLint("NewApi")
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.home, menu);
//MenuItem item = menu.findItem(R.id.accounts_spinner);
return super.onCreateOptionsMenu(menu);
}
public boolean onOptionsItemSelected(MenuItem item) {
// Handle presses on the action bar items
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
switch (item.getItemId()) {
case R.id.action_logout:
logOut();
return true;
case R.id.action_change_pw:
Intent intent = new Intent(this, ChangePw.class);
this.startActivity(intent);
return true;
// case R.id.accounts_spinner:
// Log.i("spinner","spinner click");
// return true;
default:
return super.onOptionsItemSelected(item);
}
}
#SuppressLint("NewApi")
private void logOut() {
// TODO Auto-generated method stub
Log.i("logout","to logout");
//clear data
UserInfo.chosenAccount = null;
//clear client cookies
String cookieString = "";
Log.i("number of cookies",Integer.toString(StartActivity.cookieManager.getCookieStore().getCookies().size()));
if(StartActivity.cookieManager.getCookieStore().getCookies().size() != 0){
//HttpCookie cookie = (HttpCookie) StartActivity.cookieManager.getCookieStore().getCookies().toArray()[0];
//HttpCookie cookie = (HttpCookie) StartActivity.cookieManager.getCookieStore().getCookies().get(0);
int login_cookie_index = 0;
List<HttpCookie> cookieList = (List<HttpCookie>) StartActivity.cookieManager.getCookieStore().getCookies();
//TODO: search for ltsid cookie
for (int cookie_iter = 0; cookie_iter < cookieList.size(); cookie_iter++){
if((cookieList.get(cookie_iter).getName()).equals("ltsid")){
login_cookie_index = cookie_iter;
break;
}
}
HttpCookie cookie = cookieList.get(login_cookie_index);
cookieString = cookie.getValue();
StartActivity.cookieManager.getCookieStore().removeAll();
}
//clear server sessionId
JSONObject data = new JSONObject();
JSONObject name = new JSONObject();
JSONArray arg = new JSONArray();
try{
data.put("requestCommand", "LogOut");
name.put("name","sessionId");
name.put("type", "String");
name.put("value", cookieString);
arg.put(name);
data.put("args", arg);
String finaldata = data.toString();
new AsyncHttpLogout(this).execute(finaldata);
} catch (JSONException e2) {
e2.printStackTrace();
}
this.finish();
}
public boolean onKeyDown(int keyCode, KeyEvent event) {
if(event.getAction() == KeyEvent.ACTION_DOWN){
switch(keyCode)
{
case KeyEvent.KEYCODE_BACK:
finish();
return true;
} //TODO:can go forward
}
return super.onKeyDown(keyCode, event);
}
#SuppressLint("NewApi")
private void fetchUserData() {
int login_cookie_index = 0;
List<HttpCookie> cookieList = (List<HttpCookie>) StartActivity.cookieManager.getCookieStore().getCookies();
//TODO: search for ltsid cookie
for (int cookie_iter = 0; cookie_iter < cookieList.size(); cookie_iter++){
if((cookieList.get(cookie_iter).getName()).equals("ltsid")){
login_cookie_index = cookie_iter;
break;
}
}
HttpCookie cookie = cookieList.get(login_cookie_index);
JSONObject data = new JSONObject();
JSONObject sid = new JSONObject();
JSONArray arg = new JSONArray();
try {
data.put("requestCommand","FetchInfo");
sid.put("name","sessionId");
sid.put("type", "String");
sid.put("value", cookie.getValue());
arg.put(sid);
data.put("args", arg);
} catch (JSONException e2) {
e2.printStackTrace();
}
Log.i("fetch data",data.toString());
String finaldata = data.toString();
//View mySpinnerView = this.findViewById(R.id.accounts_spinner);
new AsyncGetAccountInfo(this,adapter).execute(finaldata);
}
#Override
public boolean onNavigationItemSelected(int position, long itemId) {
Log.i("arg0",Integer.toString(position));
//Log.i("arg1",Long.toString(itemId));
//UserInfo.chosenAccount = UserInfo.accountArray.get(position);
//TODO: fix default account
return false;
}
#Override
public void onSaveInstanceState(Bundle savedInstanceState) {
super.onSaveInstanceState(savedInstanceState);
// Save UI state changes to the savedInstanceState.
// This bundle will be passed to onCreate if the process is
// killed and restarted.
savedInstanceState.putString("currPath", mCurrentPhotoPath);
//savedInstanceState.
// etc.
}
/*
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
}
*/
private class DrawerItemClickListener implements ListView.OnItemClickListener {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
selectItem(position);
}
}
private void selectItem(int position) {
// update the main content by replacing fragments
if (position ==0){
Fragment fragment = new OrderForm();
Bundle args = new Bundle();
args.putInt(OrderForm.ARG_LIST_INDEX, position);
fragment.setArguments(args);
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction().replace(R.id.content_frame, fragment).commit();
// update selected item and title, then close the drawer
mDrawerList.setItemChecked(position, true);
setTitle(mDrawerTitles[position]);
mDrawerLayout.closeDrawer(mDrawerList);
}
else if (position ==1){
Fragment fragment = new ServicesGrid();
Bundle args = new Bundle();
args.putInt(ServicesGrid.ARG_LIST_INDEX, position);
fragment.setArguments(args);
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction().replace(R.id.content_frame, fragment).commit();
// update selected item and title, then close the drawer
mDrawerList.setItemChecked(position, true);
setTitle(mDrawerTitles[position]);
mDrawerLayout.closeDrawer(mDrawerList);
}
else if (position ==2){
Fragment fragment = new UserProfile();
Bundle args = new Bundle();
args.putInt(UserProfile.ARG_LIST_INDEX, position);
fragment.setArguments(args);
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction().replace(R.id.content_frame, fragment).commit();
// update selected item and title, then close the drawer
mDrawerList.setItemChecked(position, true);
setTitle(mDrawerTitles[position]);
mDrawerLayout.closeDrawer(mDrawerList);
}
else if (position ==3){
Fragment fragment = new OrderList();
Bundle args = new Bundle();
args.putInt(OrderList.ARG_LIST_INDEX, position);
fragment.setArguments(args);
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction().replace(R.id.content_frame, fragment).commit();
// update selected item and title, then close the drawer
mDrawerList.setItemChecked(position, true);
setTitle(mDrawerTitles[position]);
mDrawerLayout.closeDrawer(mDrawerList);
}
else if (position ==4){
}
else{
Fragment fragment = new PlanetFragment();
Bundle args = new Bundle();
args.putInt(PlanetFragment.ARG_PLANET_NUMBER, position);
fragment.setArguments(args);
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction().replace(R.id.content_frame, fragment).commit();
// update selected item and title, then close the drawer
mDrawerList.setItemChecked(position, true);
setTitle(mDrawerTitles[position]);
mDrawerLayout.closeDrawer(mDrawerList);
}
}
#Override
public void setTitle(CharSequence title) {
mTitle = title;
getActionBar().setTitle(mTitle);
}
/* Called whenever we call invalidateOptionsMenu() */
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
// If the nav drawer is open, hide action items related to the content view
//boolean drawerOpen = mDrawerLayout.isDrawerOpen(mDrawerList);
//menu.findItem(R.id.action_websearch).setVisible(!drawerOpen);
return super.onPrepareOptionsMenu(menu);
}
/**
* When using the ActionBarDrawerToggle, you must call it during
* onPostCreate() and onConfigurationChanged()...
*/
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
// Sync the toggle state after onRestoreInstanceState has occurred.
mDrawerToggle.syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
// Pass any configuration change to the drawer toggls
mDrawerToggle.onConfigurationChanged(newConfig);
}
public static class PlanetFragment extends Fragment {
public static final String ARG_PLANET_NUMBER = "planet_number";
public PlanetFragment() {
// Empty constructor required for fragment subclasses
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_planet, container, false);
int i = getArguments().getInt(ARG_PLANET_NUMBER);
String planet = getResources().getStringArray(R.array.planets_array)[i];
int imageId = getResources().getIdentifier(planet.toLowerCase(Locale.getDefault()),
"drawable", getActivity().getPackageName());
//((ImageView) rootView.findViewById(R.id.image)).setImageResource(imageId);
getActivity().setTitle(planet);
return rootView;
}
}
}
The problematic fragment is with position =3, the fragment's code:
package com.example.home;
import java.io.File;
import java.io.IOException;
import java.net.HttpCookie;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import com.example.fmapp.R;
import com.example.fmapp.StartActivity;
import android.app.Fragment;
import android.app.ListFragment;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ListView;
public class OrderList extends ListFragment {
public static final String ARG_LIST_INDEX = "planet_number";
public OrderList(){
}
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_orderlist, container, false);
int i = getArguments().getInt(ARG_LIST_INDEX);
fetchOrderInfo();
String planet = getResources().getStringArray(R.array.planets_array)[i];
int imageId = getResources().getIdentifier(planet.toLowerCase(Locale.getDefault()),
"drawable", getActivity().getPackageName());
//((ImageView) rootView.findViewById(R.id.image)).setImageResource(imageId);
getActivity().setTitle(planet);
return rootView;
}
public void fetchOrderInfo() {
// TODO Auto-generated method stub
int login_cookie_index = 0;
List<HttpCookie> cookieList = (List<HttpCookie>) StartActivity.cookieManager.getCookieStore().getCookies();
//TODO: search for ltsid cookie
for (int cookie_iter = 0; cookie_iter < cookieList.size(); cookie_iter++){
if((cookieList.get(cookie_iter).getName()).equals("ltsid")){
login_cookie_index = cookie_iter;
break;
}
}
HttpCookie cookie = cookieList.get(login_cookie_index);
JSONObject data = new JSONObject();
JSONObject sid = new JSONObject();
JSONArray arg = new JSONArray();
try {
data.put("requestCommand","GetRequestInfo");
sid.put("name","sessionId");
sid.put("type", "String");
sid.put("value", cookie.getValue());
arg.put(sid);
data.put("args", arg);
} catch (JSONException e2) {
e2.printStackTrace();
}
Log.i("fetch data",data.toString());
String finaldata = data.toString();
//View mySpinnerView = this.findViewById(R.id.accounts_spinner);
new AsyncFetchUserOrders(getActivity(),this).execute(finaldata);
return;
}
/*
public void onListItemClick(ListView l, View v, int position, long id) {
Log.i("list click","list item click");
}
*/
public void populateAdapter(ArrayList<OrderObj> arrayOrderObj) {
ArrayAdapter<OrderObj> OrderList = new OrderAdapter(getActivity(), arrayOrderObj);
setListAdapter(OrderList);
}
}
Note that if I comment out asynctask line, the nav drawer works fine.
Now the asynctask code:
package com.example.home;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;
import java.util.ArrayList;
import com.example.fmapp.GlobalVars;
import com.example.fmapp.JsonUtil;
import android.annotation.SuppressLint;
import android.app.ListFragment;
import android.content.Context;
import android.os.AsyncTask;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ProgressBar;
import android.widget.Toast;
public class AsyncFetchUserOrders extends AsyncTask<String,Boolean,Integer> {
protected static String USER_SERVER = GlobalVars.USER_SERVER;
private int errorCode = -1;
ProgressBar bar = Home.bar;
private Context mainContext;
private OrderList orderFragment;
//private Arra
private ArrayAdapter<String> adapter;
public ArrayList<OrderObj> arrayOrderObj = new ArrayList<OrderObj>();// TODO: populate this shit
private String toastMsg = null;
public AsyncFetchUserOrders(Context mainContext, OrderList orderFragment) {
this.mainContext = mainContext;
this.orderFragment = orderFragment;
}
protected void onPreExecute(){
bar.setVisibility(View.VISIBLE);
}
#SuppressLint("NewApi")
#Override
protected Integer doInBackground(String... params) {
URL url = null;
Log.i("req data",params[0]);
try {
url = new URL(USER_SERVER);
} catch (MalformedURLException e1) {
e1.printStackTrace();
}
HttpURLConnection urlConnection = null;
try {
urlConnection = (HttpURLConnection) url.openConnection();
} catch (IOException e1) {
e1.printStackTrace();
}
urlConnection.setReadTimeout( 10000 /*milliseconds*/ );
urlConnection.setConnectTimeout( 15000 /* milliseconds */ );
//urlConnection.setRequestProperty("X-Requested-With", "XMLHttpRequest");
urlConnection.setRequestProperty("Connection", "Keep-Alive");
try {
urlConnection.setDoOutput(true);
try {
urlConnection.setRequestMethod("POST");
} catch (ProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
urlConnection.connect();
OutputStream os = urlConnection.getOutputStream();
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
writer.write(params[0]);
writer.close();
os.close();
} catch (IOException e) {
e.printStackTrace();
}
//response:
try { //parse errorCode
if (urlConnection.getResponseCode() == HttpURLConnection.HTTP_OK) {
String response = urlConnection.getResponseMessage();
/*
InputStream responseStream = new BufferedInputStream(urlConnection.getInputStream());
BufferedReader responseStreamReader = new BufferedReader(new InputStreamReader(responseStream));
String line = "";
StringBuilder stringBuilder = new StringBuilder();
while ((line = responseStreamReader.readLine()) != null) {
stringBuilder.append(line);
Log.i("line",line);
}
responseStreamReader.close();
*/
BufferedReader in = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
String inputLine;
StringBuffer stringBuilder = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
stringBuilder.append(inputLine);
}
in.close();
String resp = stringBuilder.toString();
Log.i("resp",resp);
processResp(resp);
}
} catch (IOException e) {
e.printStackTrace();
}
}
finally {
urlConnection.disconnect();
}
return 1;
}
protected void onProgressUpdate(Integer... progress) {
}
protected void onPostExecute(Integer result) {
//Log.i("postexec","in post execute");
bar.setVisibility(View.GONE);
Toast toast = Toast.makeText(mainContext, toastMsg, Toast.LENGTH_SHORT);
toast.show();
if (JsonUtil.authSucess == false){
}
else{
// Imp TODO : get to new Activity
Log.i("ltid","populate spinner");
//IMP TODO :UserInfo.populateSpinner(adapter);
JsonUtil.authSucess = false;
/*
if (arrayOrderObj != null){
ArrayAdapter<OrderObj> OrderList = new OrderAdapter(mainContext, arrayOrderObj);
orderFragment.setListAdapter(OrderList);
}*/
}
//this.cancel(true);
}
/*
public void onStop() {
//super.onStop();
if(this!=null){
this.cancel(true);
}
}
*/
private void processResp(String resp) {
errorCode = JsonUtil.processRespForErrorCode(resp);
if (errorCode == 0){
JsonUtil.authSucess = true;
toastMsg = "Order info received";
//TODO: parse JSON and populate user orderinfo info
Log.i("orders", "to populate Order");
JsonUtil.populateOrderInfo(resp,arrayOrderObj);
//Log.i("fname",UserInfo.chosenAccount.firstName);
/*
ArrayAdapter<OrderObj> OrderList = new OrderAdapter(mainContext, arrayOrderObj);
orderFragment.setListAdapter(OrderList);
*/
//orderFragment.populateAdapter(arrayOrderObj);
}
else{
toastMsg = "Something wrong";
}
}
}
Once again, nothing fancy here. still cant figure out what is making the navigation drawer to just close and not start the fragment, if it is clicked on item to start another fragment.
Thanks.
I guess it will be the Home.bar covers your fragment? Maybe you should use ProgressBar.show() or ProgressBar.dismiss() to control the visibility of the progressbar

Regarding migrating searchview on appcompat

I am migrating search view Item provided in action bar using support library .Here I have done as mentioned in doc but still it is giving error while creating options menu.Please tell me where I have done wrong.Here is my code.
contacts_list_menu.xml
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:com.utteru.ui="http://schemas.android.com/apk/res-auto"
xmlns:yourapp="http://schemas.android.com/tools">
<!-- The search menu item. Honeycomb and above uses an ActionView or specifically a SearchView
which expands within the Action Bar directly. Note the initial collapsed state set using
collapseActionView in the showAsAction attribute. -->
<group
android:id="#+id/main_menu_group">
<item
android:id="#+id/menu_search"
android:actionViewClass="android.widget.SearchView"
android:icon="#drawable/ic_action_search"
yourapp:showAsAction="ifRoom|collapseActionView"
yourapp:actionViewClass="android.support.v7.widget.SearchView"
android:title="#string/menu_search" />
</group>
<group
android:id="#+id/refresh_group">
<item
android:id="#+id/refresh"
android:icon="#android:drawable/ic_popup_sync"
yourapp:showAsAction="ifRoom|collapseActionView"
yourapp:actionViewClass="android.support.v7.widget.SearchView"
android:title="#string/menu_search" />
</group>
</menu>
ContactsListFragment.java
import android.accounts.Account;
import android.app.SearchManager;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.res.AssetFileDescriptor;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.provider.ContactsContract.Contacts;
import android.provider.ContactsContract.Contacts.Photo;
import android.support.v4.BuildConfig;
import android.support.v4.app.ListFragment;
import android.support.v4.view.MenuItemCompat;
import android.support.v7.widget.SearchView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import java.io.FileDescriptor;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
public class ContactsListFragment extends ListFragment {
private static final String TAG = "ContactsAccessFragment";
private static final String STATE_PREVIOUSLY_SELECTED_KEY =
"com.Utteru.ui.SELECTED_ITEM";
ArrayList<AccessContactDto> allcontacts;
ArrayList<AccessContactDto> databasecontacts;
TextView textempty;
public Context mContext;
private AccessContactAdapter mAdapter;
private ImageLoader mImageLoader; // Handles loading the contact image in a background thread
// Stores the previously selected search item so that on a configuration change the same item
// can be reselected again
private int mPreviouslySelectedSearchItem = 0;
// Whether or not the search query has changed since the last time the loader was refreshed
private boolean mSearchQueryChanged;
// Whether or not this fragment is showing in a two-pane layout
private boolean mIsTwoPaneLayout;
// Whether or not this is a search result view of this fragment, only used on pre-honeycomb
// OS versions as search results are shown in-line via Action Bar search from honeycomb onward
private boolean mIsSearchResultView = false;
/**
* Fragments require an empty constructor.
*/
public ContactsListFragment() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mIsTwoPaneLayout = getResources().getBoolean(R.bool.has_two_panes);
getActivity().setTitle("");
if (savedInstanceState != null) {
// If we're restoring state after this fragment was recreated then
// retrieve previous search term and previously selected search
// result.
mPreviouslySelectedSearchItem =
savedInstanceState.getInt(STATE_PREVIOUSLY_SELECTED_KEY, 0);
}
mImageLoader = new ImageLoader(getActivity(), CommonUtility.getListPreferredItemHeight(getActivity())) {
#Override
protected Bitmap processBitmap(Object data) {
// This gets called in a background thread and passed the data from
// ImageLoader.loadImage().
return loadContactPhotoThumbnail((String) data, getImageSize());
}
};
// Set a placeholder loading image for the image loader
mImageLoader.setLoadingImage(R.drawable.ic_contact_picture_holo_light);
// Add a cache to the image loader
mImageLoader.addImageCache(getActivity().getSupportFragmentManager(), 0.1f);
mContext = getActivity().getBaseContext();
new loadData().execute();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the list fragment layout
View all_contacts_view = inflater.inflate(R.layout.contact_list_fragment, container, false);
textempty = (TextView)all_contacts_view.findViewById(android.R.id.empty);
textempty.setText("No contacts found");
return all_contacts_view;
}
#Override
public void onListItemClick(ListView l, View v, int position, long id) {
AccessContactDto cdto = (AccessContactDto) l.getItemAtPosition(position);
Log.e("number on click",""+cdto.getMobile_number());
cdto=UserService.getUserServiceInstance(mContext).getAccessConDataByNumber(cdto.getMobile_number());
if(cdto==null)
cdto = (AccessContactDto) l.getItemAtPosition(position);
else
Log.e("mumber not mull from db","number not null from db");
Intent detailsActivity = new Intent(mContext, ContactDetailActivity.class);
detailsActivity.putExtra("selected_con", cdto);
startActivity(detailsActivity);
getActivity().overridePendingTransition(R.anim.animation1, R.anim.animation2);
super.onListItemClick(l, v, position, id);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
// Let this fragment contribute menu items
setHasOptionsMenu(true);
// Set up ListView, assign adapter and set some listeners. The adapter was previously
// created in onCreate().
setListAdapter(mAdapter);
getListView().setOnScrollListener(new AbsListView.OnScrollListener() {
#Override
public void onScrollStateChanged(AbsListView absListView, int scrollState) {
// Pause image loader to ensure smoother scrolling when flinging
if (scrollState == AbsListView.OnScrollListener.SCROLL_STATE_FLING) {
mImageLoader.setPauseWork(true);
} else {
mImageLoader.setPauseWork(false);
}
}
#Override
public void onScroll(AbsListView absListView, int i, int i1, int i2) {
}
});
if (mIsTwoPaneLayout) {
getListView().setChoiceMode(ListView.CHOICE_MODE_SINGLE);
}
if (mPreviouslySelectedSearchItem == 0) {
}
}
#Override
public void onPause() {
super.onPause();
mImageLoader.setPauseWork(false);
}
#Override
public void onPrepareOptionsMenu(Menu menu) {
menu.clear();
getActivity().getMenuInflater().inflate(R.menu.contact_list_menu, menu);
MenuItem searchItem = menu.findItem(R.id.menu_search);
menu.setGroupVisible(R.id.main_menu_group, true);
if (mIsSearchResultView) {
searchItem.setVisible(false);
}
if (Utils.hasHoneycomb()) {
final SearchManager searchManager =
(SearchManager) getActivity().getSystemService(Context.SEARCH_SERVICE);
SearchView searchView = (SearchView) MenuItemCompat.getActionView(searchItem);
searchView.setSearchableInfo(
searchManager.getSearchableInfo(getActivity().getComponentName()));
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String queryText) {
return true;
}
#Override
public boolean onQueryTextChange(String newText) {
Log.e("on query text change ","on query text change");
if (newText != null && !newText.equals(""))
{
ArrayList<AccessContactDto> filterList = new ArrayList<AccessContactDto>();
for (AccessContactDto a : allcontacts) {
if (a.getDisplay_name().toLowerCase().startsWith(newText.toLowerCase())) {
filterList.add(a);
continue;
}
getListView().setAdapter(new AccessContactAdapter(filterList, getActivity(), mImageLoader));
}
return true;
}
else{
getListView().setAdapter(new AccessContactAdapter(allcontacts, getActivity(), mImageLoader));
return true;
}
}
});
}
super.onPrepareOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_search:
if (!Utils.hasHoneycomb()) {
getActivity().onSearchRequested();
}
break;
case R.id.refresh:
if (CommonUtility.isNetworkAvailable(getActivity())) {
final Account account = new Account(Constants.ACCOUNT_NAME, Constants.ACCOUNT_TYPE);
Bundle bundle = new Bundle();
bundle.putBoolean(ContentResolver.SYNC_EXTRAS_EXPEDITED, true);
bundle.putBoolean(ContentResolver.SYNC_EXTRAS_MANUAL, true);
ContentResolver.requestSync(account, ContactsContract.AUTHORITY, bundle);
mAdapter.notifyDataSetChanged();
// new CountDownTimer(5000, 1000) {
// #Override
// public void onTick(long millisUntilFinished) {
// }
//
// #Override
// public void onFinish() {
//
// }
// }.start();
} else {
Toast.makeText(getActivity(), "Internet Connection Required!!", Toast.LENGTH_SHORT).show();
}
break;
}
return super.onOptionsItemSelected(item);
}
private Bitmap loadContactPhotoThumbnail(String photoData, int imageSize) {
if (!isAdded() || getActivity() == null) {
return null;
}
AssetFileDescriptor afd = null;
try {
Uri thumbUri;
if (Utils.hasHoneycomb()) {
thumbUri = Uri.parse(photoData);
} else {
final Uri contactUri = Uri.withAppendedPath(Contacts.CONTENT_URI, photoData);
thumbUri = Uri.withAppendedPath(contactUri, Photo.CONTENT_DIRECTORY);
}
afd = getActivity().getContentResolver().openAssetFileDescriptor(thumbUri, "r");
FileDescriptor fileDescriptor = afd.getFileDescriptor();
if (fileDescriptor != null) {
return ImageLoader.decodeSampledBitmapFromDescriptor(
fileDescriptor, imageSize, imageSize);
}
} catch (FileNotFoundException e) {
if (BuildConfig.DEBUG) {
Log.d(TAG, "Contact photo thumbnail not found for contact " + photoData
+ ": " + e.toString());
}
} finally {
if (afd != null) {
try {
afd.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return null;
}
public ArrayList<AccessContactDto> readContactsNew() {
ArrayList<AccessContactDto> list = new ArrayList<AccessContactDto>();
AccessContactDto adto;
Cursor phones = mContext.getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,null,null, null);
while (phones.moveToNext())
{
String name=phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
String phoneNumber = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
String photouri= phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.PHOTO_URI));
String contact_id= phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone._ID));
Uri con_uri= Contacts.getLookupUri(phones.getLong(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone._ID)), phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.LOOKUP_KEY)));
adto = new AccessContactDto(contact_id, name, null, phoneNumber, null, photouri, con_uri.toString(),null,null,null);
list.add(adto);
}
phones.close();
return list;
}
public class loadData extends AsyncTask<Void, Void, Void>
{
#Override
protected void onPostExecute(Void aVoid) {
mAdapter = new AccessContactAdapter(allcontacts, getActivity(), mImageLoader);
if(getActivity()!=null)
getListView().setAdapter(mAdapter);
super.onPostExecute(aVoid);
}
#Override
protected Void doInBackground(Void... params) {
allcontacts = readContactsNew();
// databasecontacts = UserService.getUserServiceInstance(mContext).getAllAccessContacts();
// allcontacts.removeAll(databasecontacts);
// allcontacts.addAll(databasecontacts);
Collections.sort(allcontacts, new Comparator<AccessContactDto>() {
#Override
public int compare(AccessContactDto lhs, AccessContactDto rhs) {
return lhs.getDisplay_name().compareToIgnoreCase(rhs.getDisplay_name());
}
});
return null;
}
}
}
ContactsListActivity.java
import android.accounts.AccountManager;
import android.content.Intent;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.PagerTabStrip;
import android.support.v4.view.ViewPager;
import android.support.v7.app.ActionBarActivity;
import com.viewpagerindicator.IconPagerAdapter;
public class ContactsListActivity extends ActionBarActivity {
DemoCollectionPagerAdapter mDemoCollectionPagerAdapter;
ViewPager mViewPager;
private ContactDetailFragment mContactDetailFragment;
private boolean isTwoPaneLayout;
AccountManager mAccountManager;
Boolean checkAccount;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mDemoCollectionPagerAdapter = new DemoCollectionPagerAdapter(getSupportFragmentManager());
getSupportActionBar().setDisplayHomeAsUpEnabled(false);
getSupportActionBar().setBackgroundDrawable(new ColorDrawable(R.color.purple));
getSupportActionBar().setIcon(new ColorDrawable(getResources().getColor(android.R.color.transparent)));
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mDemoCollectionPagerAdapter);
isTwoPaneLayout = getResources().getBoolean(R.bool.has_two_panes);
PagerTabStrip pagerTabStrip = (PagerTabStrip) findViewById(R.id.pager_title_strip);
pagerTabStrip.setTextSpacing(0);
pagerTabStrip.setPadding(0, 0, 0, 10);
pagerTabStrip.setTextSize(1, 20);
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.remove("android:support:fragments");
}
#Override
public void onBackPressed() {
startActivity(new Intent(ContactsListActivity.this, MenuScreen.class).setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK|Intent.FLAG_ACTIVITY_NEW_TASK));
this.finish();
overridePendingTransition(R.anim.card_rotate_in, R.anim.card_rotate_out);
}
#Override
protected void onDestroy() {
if(CommonUtility.dialog!=null){
CommonUtility.dialog.dismiss();
}
super.onDestroy();
}
#Override
public boolean onSearchRequested() {
boolean isSearchResultView = false;
return !isSearchResultView && super.onSearchRequested();
}
public static class DemoCollectionPagerAdapter extends FragmentPagerAdapter implements IconPagerAdapter {
protected static final String[] CONTENT = new String[]{"All Contacts", "Access Contacts"};
protected final int[] ICONS = new int[]{
R.drawable.all_contact,
R.drawable.access_contacts
};
private int mCount = CONTENT.length;
public DemoCollectionPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int index) {
switch (index) {
case 0:
// All Contacts Fragment
return new ContactsListFragment();
case 1:
// Access Contacts Fragment
return new ContactsAccessFragment();
}
return null;
}
#Override
public CharSequence getPageTitle(int position) {
return DemoCollectionPagerAdapter.CONTENT[position % CONTENT.length];
}
#Override
public int getIconResId(int index) {
return ICONS[index % ICONS.length];
}
#Override
public int getCount() {
return mCount;
}
public void setCount(int count) {
if (count > 0 && count <= 10) {
mCount = count;
notifyDataSetChanged();
}
}
}
}
Error Log:
java.lang.NullPointerException
at com.hello.ContactsListFragment.onPrepareOptionsMenu(ContactsListFragment.java:236)
at android.support.v4.app.Fragment.performPrepareOptionsMenu(Fragment.java:1882)
at android.support.v4.app.FragmentManagerImpl.dispatchPrepareOptionsMenu(FragmentManager.java:2020)
at android.support.v4.app.FragmentActivity.onPreparePanel(FragmentActivity.java:459)
at android.support.v7.app.ActionBarActivity.superOnPreparePanel(ActionBarActivity.java:280)
at android.support.v7.app.ActionBarActivityDelegate$1.onPreparePanel(ActionBarActivityDelegate.java:84)
at android.support.v7.app.ActionBarActivityDelegateBase.preparePanel(ActionBarActivityDelegateBase.java:1006)
at android.support.v7.app.ActionBarActivityDelegateBase.doInvalidatePanelMenu(ActionBarActivityDelegateBase.java:1182)
at android.support.v7.app.ActionBarActivityDelegateBase.access$100(ActionBarActivityDelegateBase.java:79)
at android.support.v7.app.ActionBarActivityDelegateBase$1.run(ActionBarActivityDelegateBase.java:115)
at android.os.Handler.handleCallback(Handler.java:615)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:155)
at android.app.ActivityThread.main(ActivityThread.java:5520)
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:1029)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:796)
at dalvik.system.NativeStart.main(Native Method)

Loading in Android ListView stucked like forever

I'm new to android programming and I'm practicing in making a Facebook app. I got this ListView and which i will be using to display some information i got from facebook. But the problem is when the Listview starts to load the datas its stucked in the loading part and its taking forever but theres no error in the codes. here are the codes:
package com.example.forwardjunction;
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.Fragment;
import android.app.FragmentTransaction;
import android.app.ListFragment;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.res.Configuration;
import android.os.Bundle;
import android.util.Log;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.ScrollView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;
import com.facebook.HttpMethod;
import com.facebook.Request;
import com.facebook.Response;
import com.facebook.Session;
import com.facebook.SessionState;
import com.facebook.UiLifecycleHelper;
import com.facebook.model.GraphObject;
public class FragmentLayout extends Activity {
ProgressDialog mDialog;
static String postMessage;
static String from;
static String timeCreated;
static String postId;
static ArrayList<HashMap<String, String>> feedList;
private static final String TAG_MESSAGE = "message";
private static final String TAG_ID = "id";
private static final String TAG_NAME = "name";
static ListView list;
TextView author, feedMessage;
static UiLifecycleHelper uiHelper;
public FragmentLayout() {
// TODO Auto-generated constructor stub
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_layout);
author = (TextView) findViewById(R.id.author);
feedMessage = (TextView) findViewById(R.id.message);
feedList = new ArrayList<HashMap<String, String>>();
uiHelper = new UiLifecycleHelper(this, statusCallback);
// list = (ListView) findViewById(R.id.list);
}
public static class TitlesFragment extends ListFragment {
boolean mDualPane;
int mCurCheckPosition = 0;
// public View onCreateView(LayoutInflater inflater, ViewGroup container,
// Bundle savedInstanceState) {
//
// return null;
// }
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
ListView list = getListView();
feedList = new ArrayList<HashMap<String, String>>();
Request loadPageFeed = new Request(Session.getActiveSession(),
"163340583656/posts", null, HttpMethod.GET,
new Request.Callback() {
#Override
public void onCompleted(Response response) {
// TODO Auto-generated method stub
Log.i("FEED RESPONSE", response.toString());
try {
GraphObject graphObj = response.getGraphObject();
JSONObject json = graphObj.getInnerJSONObject();
JSONArray jArray = json.getJSONArray("data");
for (int i = 0; i < jArray.length(); i++) {
JSONObject currObj = jArray.getJSONObject(i);
postId = currObj.getString("id");
if (currObj.has("message")) {
postMessage = currObj.getString("message");
} else if (currObj.has("story")) {
postMessage = currObj.getString("story");
} else {
postMessage = "Forward Publication has posted something.";
}
JSONObject fromObj = currObj
.getJSONObject("from");
from = fromObj.getString("name");
timeCreated = currObj
.getString("created_time");
HashMap<String, String> feed = new HashMap<String, String>();
feed.put(TAG_ID, postId);
feed.put(TAG_MESSAGE, postMessage);
feed.put(TAG_NAME, from);
Log.i("passed", feed.toString());
feedList.add(feed);
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
loadPageFeed.executeAsync();
BaseAdapter adapter = new SimpleAdapter(getActivity(), feedList,
R.layout.feed_item, new String[] { TAG_MESSAGE, TAG_NAME,
TAG_ID }, new int[] { R.id.message, R.id.author,
R.id.id_tv });
list.setAdapter(adapter);
adapter.notifyDataSetChanged();
View detailsFrame = getActivity(). findViewById(R.id.details);
mDualPane = detailsFrame != null
&& detailsFrame.getVisibility() == View.VISIBLE;
if (savedInstanceState != null) {
// Restore last state for checked position.
mCurCheckPosition = savedInstanceState.getInt("curChoice", 0);
}
if (mDualPane) {
getListView().setChoiceMode(ListView.CHOICE_MODE_SINGLE);
showDetails(mCurCheckPosition);
} else {
getListView().setChoiceMode(ListView.CHOICE_MODE_SINGLE);
getListView().setItemChecked(mCurCheckPosition, true);
}
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt("curChoice", mCurCheckPosition);
}
#Override
public void onListItemClick(ListView l, View v, int position, long id) {
showDetails(position);
}
void showDetails(int index) {
mCurCheckPosition = index;
if (mDualPane) {
getListView().setItemChecked(index, true);
DetailsFragment details = (DetailsFragment) getFragmentManager()
.findFragmentById(R.id.details);
if (details == null || details.getShownIndex() != index) {
details = DetailsFragment.newInstance(index);
FragmentTransaction ft = getFragmentManager()
.beginTransaction();
ft.replace(R.id.details, details);
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
ft.commit();
}
} else {
Intent intent = new Intent();
intent.setClass(getActivity(), DetailsActivity.class);
intent.putExtra("index", index);
startActivity(intent);
}
}
}
public static class DetailsActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
finish();
return;
}
if (savedInstanceState == null) {
DetailsFragment details = new DetailsFragment();
details.setArguments(getIntent().getExtras());
getFragmentManager().beginTransaction()
.add(android.R.id.content, details).commit();
}
}
}
public static class DetailsFragment extends Fragment {
public static DetailsFragment newInstance(int index) {
DetailsFragment f = new DetailsFragment();
Bundle args = new Bundle();
args.putInt("index", index);
f.setArguments(args);
return f;
}
public int getShownIndex() {
return getArguments().getInt("index", 0);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
ScrollView scroller = new ScrollView(getActivity());
TextView text = new TextView(getActivity());
int padding = (int) TypedValue.applyDimension(
TypedValue.COMPLEX_UNIT_DIP, 4, getActivity()
.getResources().getDisplayMetrics());
text.setPadding(padding, padding, padding, padding);
scroller.addView(text);
// text.setText(Shakespeare.DIALOGUE[getShownIndex()]);
return scroller;
}
}
#Override
public void onResume() {
super.onResume();
uiHelper.onResume();
}
#Override
public void onPause() {
super.onPause();
uiHelper.onPause();
}
#Override
public void onDestroy() {
super.onDestroy();
uiHelper.onDestroy();
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
uiHelper.onActivityResult(requestCode, resultCode, data);
}
#Override
public void onSaveInstanceState(Bundle savedState) {
super.onSaveInstanceState(savedState);
uiHelper.onSaveInstanceState(savedState);
}
private Session.StatusCallback statusCallback = new Session.StatusCallback() {
#Override
public void call(Session session, SessionState state,
Exception exception) {
if (state.isOpened()) {
Log.d("FacebookSampleActivity", "Facebook session opened");
} else if (state.isClosed()) {
Log.d("FacebookSampleActivity", "Facebook session closed");
}
}
};
}
And heres the xml:
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<fragment
android:id="#+id/titles"
android:layout_width="match_parent"
android:layout_height="match_parent"
class="com.example.forwardjunction.FragmentLayout$TitlesFragment" />
</FrameLayout>
I hope you can help me. cheers
*edit> I think the problem is that the listview is empty, i dont really know where the problem is
because the UI thread is Blocked
Rather than using your thread class use Asynctask
class xyz extends Asynctask
{
}
then add to overrididen methods
do in background
on post execute
I m posting the sample code of mine
package com.example.urlconnectionclass;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Scanner;
import org.json.JSONArray;
import org.json.JSONObject;
import android.app.Activity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.Menu;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity {
ProgressDialog pDialog;
String urlString="http://api.androidhive.info/contacts/";
TextView tc;
String s;
JSONArray jr;
JSONObject jb,jb2;
ArrayList<HashMap<String, String>> contact;
String tagid="id";
String tagname="name",tagemail="email",taggender="gender",tagadd="address";
ListView lv;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lv=(ListView)findViewById(R.id.listView1);
contact = new ArrayList<HashMap<String,String>>();
new urlconn().execute();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public class urlconn extends AsyncTask<Void, Void, Void>
{
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
try {
URL url= new URL(urlString);
HttpURLConnection conn =(HttpURLConnection)url.openConnection();
conn.connect();
InputStream is= conn.getInputStream();
s=convertStreamToString(is);
jb = new JSONObject(s);
jr= jb.getJSONArray("contacts");
for(int i=0;i<=jr.length();i++)
{
jb2=jr.getJSONObject(i);
String id=jb2.getString(tagid);
String name=jb2.getString(tagname);
String email=jb2.getString(tagemail);
String address=jb2.getString(tagadd);
String gender=jb2.getString("gender");
HashMap<String, String> map = new HashMap<String, String>();
map.put(tagid, id);
map.put(tagname, name);
map.put(tagemail, email);
map.put("gender", gender);
map.put(tagadd, address);
contact.add(map);
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
String [] sr={tagid,tagname,tagemail,"gender",tagadd};
int [] in= {R.id.textView1,R.id.textView2,R.id.textView3,R.id.textView4,R.id.textView5};
SimpleAdapter sa= new SimpleAdapter(MainActivity.this, contact, R.layout.mapxml,sr, in);
lv.setAdapter(sa);
}
public String convertStreamToString(java.io.InputStream is) {
java.util.Scanner s = new java.util.Scanner(is).useDelimiter("\\A");
return s.hasNext() ? s.next() : "";
}
}
}

Categories

Resources