Main Activity toolbar not showing after hiding when attaching fragment - android

I am attaching a fragment from a fragment that is attached to an activity and then inside the fragment i have set my custom toolbar with set setDisplayHomeUpEnabled to true. when am attaching the fragment i have set the Main activity toolbar to be hidden, the only problem is that it is not being unhidden when am returning to the parent fragment from the child fragment
package manu.apps.cartv6.Activities;
import androidx.annotation.NonNull;
import androidx.appcompat.app.ActionBarDrawerToggle;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.core.view.GravityCompat;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.google.android.material.navigation.NavigationView;
import com.google.android.material.snackbar.Snackbar;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import manu.apps.cartv6.Classes.CartCounterConverter;
import manu.apps.cartv6.Classes.Config;
import manu.apps.cartv6.Classes.Product;
import manu.apps.cartv6.Classes.UserSessionManager;
import manu.apps.cartv6.Fragments.UserProfileFragment;
import manu.apps.cartv6.Fragments.ViewProductsFragment;
import manu.apps.cartv6.Interfaces.AddRemoveCallbacks;
import manu.apps.cartv6.R;
import manu.apps.cartv6.Tests.CartFragment;
public class MainActivity extends AppCompatActivity implements View.OnClickListener, NavigationView.OnNavigationItemSelectedListener, AddRemoveCallbacks {
/** Lists*/
public static List<Product> cartList = new ArrayList<>();
/** Variables*/
// Counter for Cart
public static int cart_count = 0;
// Get Id for users
String getId;
// Time Interval for back button press
private static final int TIME_INTERVAL = 2000; // # milliseconds, desired time passed between two back presses.
// How long the back button has been pressed
private long backPressed;
//Getting Class Info
private static final String TAG = MainActivity.class.getSimpleName();
/** Views*/
// Toolbars
Toolbar toolbar;
// TextViews
TextView navHeaderUsername;
// ImageViews
ImageView navHeaderProfileImage;
/** Session Managing*/
UserSessionManager userSessionManager;
/** Navigation Drawer*/
//Declaring ActionBarDrawerToggle
private ActionBarDrawerToggle actionBarDrawerToggle;
//Declaring Navigation View
NavigationView navigationView;
//Declaring Drawer Layout
DrawerLayout drawerLayout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Creating a Session Manager for the Users
userSessionManager = new UserSessionManager(this);
userSessionManager.checkUserLogin();
//Finding Drawer Layout
drawerLayout = findViewById(R.id.drawer_layout);
//Finding Navigation View
navigationView = findViewById(R.id.navigation_view);
//Finding Toolbar
toolbar = findViewById(R.id.main_tool_bar);
//Toolbar Workings
setSupportActionBar(toolbar);
getSupportActionBar().setTitle("Home");
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
// Setting View Products Fragment
Fragment fragment = new ViewProductsFragment();
getSupportFragmentManager().beginTransaction().replace(R.id.frame_layout,fragment).commit();
//Setting ActionBarDrawerToggle to Open and Close
actionBarDrawerToggle = new ActionBarDrawerToggle(this,drawerLayout,R.string.open,R.string.close);
drawerLayout.addDrawerListener(actionBarDrawerToggle);
actionBarDrawerToggle.syncState();
// Setting Navigation Item Selected Listener for Items in Navigation View
navigationView.setNavigationItemSelectedListener(this);
/**
* app:headerLayout="#layout/layout_nav_header"
*
* Remove the above line in NavigationView because we are inflating programmatically
*
* */
View navView = navigationView.inflateHeaderView(R.layout.layout_nav_header);
//Finding Views in Navigation Header which is inside Navigation View
navHeaderUsername = navView.findViewById(R.id.nav_header_username);
navHeaderProfileImage = navView.findViewById(R.id.nav_header_profile_image);
// Parsing Username and Email
HashMap<String, String> user = userSessionManager.getUserDetails();
getId = user.get(userSessionManager.ID);
}
// Fetch User Details
private void fetchUserDetails(){
final ProgressDialog progressDialog = new ProgressDialog(this);
progressDialog.setMessage("Loading...");
//progressDialog.show();
StringRequest stringRequest = new StringRequest(Request.Method.POST, Config.FETCH_USER_DETAILS,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
progressDialog.dismiss();
Log.i(TAG, response.toString());
try {
JSONObject jsonObject = new JSONObject(response);
String success = jsonObject.getString("success");
JSONArray jsonArray = jsonObject.getJSONArray("fetch");
if (success.equals("1")) {
for (int i = 0; i < jsonArray.length();i++) {
JSONObject object = jsonArray.getJSONObject(i);
String username = object.getString("username").trim();
String email = object.getString("email").trim();
// Set Details for the Navigation Header
navHeaderUsername.setText(username);
//etProfileUsername.setText(username);
//etProfileEmail.setText(email);
}
}
} catch (JSONException e) {
e.printStackTrace();
progressDialog.dismiss();
Toast.makeText(MainActivity.this, "JSON Error fetching Details", Toast.LENGTH_SHORT).show();
Snackbar.make(getWindow().getDecorView().getRootView(),e.toString(),Snackbar.LENGTH_LONG).show();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
progressDialog.dismiss();
Toast.makeText(MainActivity.this, "Volley Error fetching Details", Toast.LENGTH_SHORT).show();
Snackbar.make(getWindow().getDecorView().getRootView(),error.toString(),Snackbar.LENGTH_LONG).show();
}
})
{
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String > params = new HashMap<>();
params.put("id", getId);
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
public static String numberFormatter(double d) {
DecimalFormat decimalFormat = new DecimalFormat("#,###.##");
return decimalFormat.format(d);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.user_toolbar_menu_items, menu);
MenuItem cartItem = menu.findItem(R.id.cart_action);
cartItem.setIcon(CartCounterConverter.convertLayoutToImage(MainActivity.this,cart_count,R.drawable.view_cart_icon));
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Check if Action Bar Drawer Toggle has been selected
if(actionBarDrawerToggle.onOptionsItemSelected(item)){
return true;
}
switch (item.getItemId()) {
case R.id.cart_action:
//startActivity(new Intent(MainActivity.this,CartActivity.class));
Fragment fragment = new CartFragment();
getSupportFragmentManager().beginTransaction().replace(R.id.frame_layout,fragment).commit();
getSupportActionBar().hide();
break;
case R.id.logout_action:
userSessionManager.logOutUser();
finish();
default:
break;
}
return super.onOptionsItemSelected(item);
}
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
Fragment fragment = null;
/*switch (item.getItemId()) {
case R.id.action_category_one:
Toast.makeText(this, "Under Development", Toast.LENGTH_SHORT).show();
break;
case R.id.action_profile:
fragment = new UserProfileFragment();
break;
}*/
int id = item.getItemId();
if (id == R.id.action_view_products) {
fragment = new ViewProductsFragment();
}
// else if (id == R.id.action_receipts) {
// }
else if (id == R.id.action_profile) {
//startActivity(new Intent(MainActivity.this,UserProfileActivity.class));
fragment = new UserProfileFragment();
}
if (fragment !=null) {
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction ft = fragmentManager.beginTransaction();
//R.id." " will be found in content_main.xml from the Frame Layout
ft.replace(R.id.frame_layout,fragment);
ft.commit();
}
drawerLayout.closeDrawer(GravityCompat.START);
return true;
}
#Override
public void onClick(View v) {
}
// When back button is pressed method
#Override
public void onBackPressed() {
//Check if navigation drawer is opened or closed
if (drawerLayout.isDrawerOpen(GravityCompat.START)){
drawerLayout.closeDrawer(GravityCompat.START);
}else {
if (backPressed + TIME_INTERVAL > System.currentTimeMillis()) {
super.onBackPressed();
return;
} else {
Toast.makeText(getBaseContext(), "Press back button again to exit", Toast.LENGTH_SHORT).show();
}
backPressed = System.currentTimeMillis();
}
}
#Override
protected void onResume() {
super.onResume();
fetchUserDetails();
}
// Remember to implement AddRemoveCallback Interface
#Override
public void onAddProduct() {
cart_count++;
invalidateOptionsMenu();
}
// Remember to implement AddRemoveCallback Interface
#Override
public void onRemoveProduct() {
cart_count--;
invalidateOptionsMenu();
}
}
My child fragment
package manu.apps.cartv6.Tests;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.widget.Toolbar;
import androidx.fragment.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import manu.apps.cartv6.Activities.MainActivity;
import manu.apps.cartv6.Fragments.ViewProductsFragment;
import manu.apps.cartv6.R;
/**
* A simple {#link Fragment} subclass.
*/
public class CartFragment extends Fragment {
Toolbar fragmentCartToolbar;
public CartFragment() {
// Required empty public constructor
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//((MainActivity) getActivity()).getSupportActionBar().hide();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
setHasOptionsMenu(true);
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_cart, container, false);
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
fragmentCartToolbar = view.findViewById(R.id.fragment_cart_tool_bar);
((MainActivity) getActivity()).setSupportActionBar(fragmentCartToolbar);
((MainActivity) getActivity()).getSupportActionBar().setTitle("Blank Fragment");
((MainActivity) getActivity()).getSupportActionBar().setDisplayHomeAsUpEnabled(true);
((MainActivity) getActivity()).getSupportActionBar().setDisplayShowHomeEnabled(true);
final Toolbar bar = (Toolbar) getActivity().findViewById(R.id.main_tool_bar);
fragmentCartToolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
((MainActivity) getActivity()).setSupportActionBar(bar);
//((MainActivity) getActivity()).getSupportActionBar().show();
Fragment fragment = new ViewProductsFragment();
getActivity().getSupportFragmentManager().beginTransaction().replace(R.id.frame_layout,fragment).commit();
}
});
}
}
The problem is that the moment i add setNavigationOnClickListener the Main Activity toolbar doesn't show again when i remove it, it shows perfectly
#Override
public void onResume() {
super.onResume();
((MainActivity)getActivity()).getSupportActionBar().hide();
((MainActivity) getActivity()).setSupportActionBar(fragmentCartToolbar);
((MainActivity) getActivity()).getSupportActionBar().setTitle("Blank Fragment");
((MainActivity) getActivity()).getSupportActionBar().setDisplayHomeAsUpEnabled(true);
//((MainActivity) getActivity()).getSupportActionBar().setDisplayShowHomeEnabled(true);
fragmentCartToolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Fragment fragment = new ViewProductsFragment();
getActivity().getSupportFragmentManager().beginTransaction().replace(R.id.frame_layout,fragment).commit();
}
});
}

Please try to add below in your parent fragment's onResume(), I guess it's ViewProductsFragment from the provided code.
This will allow you to hide the action bar from the fragment itself rather than the activity.
#Override
public void onResume() {
super.onResume();
((AppCompatActivity)getActivity()).getSupportActionBar().hide();
}

Related

onBackPressed() unfortunately app has stopped in android phone

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

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

change the items in a ListView from another fragment

I have two fragments, lets call them Fragment A and Fragment B, which are a part of a NavigationDrawer (this is the activity they a bound to). In Fragment A I have a button. When this button is pressed, I would like another item added to the ListView in Fragment B.
What is the best way to do this? Use Intents, SavedPreferences, making something public(?) or something else?
EDIT 5: 20/7/13 This is with srains latest code
This is the NavigationDrawer that I use to start the fragments:
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
public class Navigation_Drawer extends FragmentActivity {
public DrawerLayout mDrawerLayout; // Creates a DrawerLayout called_.
public ListView mDrawerList;
public ActionBarDrawerToggle mDrawerToggle;
private CharSequence mDrawerTitle;
private CharSequence mTitle;
private String[] mNoterActivities; // This creates a string array called _.
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
// Just setting up the navigation drawer
} // End of onCreate
// Removed the menu
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
selectItem(position);
}
}
private void selectItem(int position) {
FragmentManager fragmentManager = getSupportFragmentManager();
if (position == 0) {
Fragment qnfragment = new QuickNoteFragment();
((FragmentBase) qnfragment).setContext(this);
Bundle args = new Bundle(); // Creates a bundle called args
args.putInt(QuickNoteFragment.ARG_nOTERACTIVITY_NUMBER, position);
qnfragment.setArguments(args);
fragmentManager.beginTransaction()
.replace(R.id.content_frame, qnfragment).commit();
} else if (position == 3) {
Fragment pendViewPager = new PendViewPager(); // This is a ViewPager that includes HistoryFragment
((FragmentBase) pendViewPager).setContext(this);
Bundle args = new Bundle();
pendViewPager.setArguments(args);
fragmentManager.beginTransaction()
.replace(R.id.content_frame, pendViewPager).commit();
}
// Update title etc
}
#Override
protected void onPostCreate(Bundle savedInstanceState) { // Used for the NavDrawer toggle
super.onPostCreate(savedInstanceState);
// Sync the toggle state after onRestoreInstanceState has occurred.
mDrawerToggle.syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfig) { // Used for the NavDrawer toggle
super.onConfigurationChanged(newConfig);
// Pass any configuration change to the drawer toggles
mDrawerToggle.onConfigurationChanged(newConfig);
}
}
This is QuickNoteFragment:
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.v4.app.NotificationCompat;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class QuickNoteFragment extends FragmentBase implements OnClickListener {
public static final String ARG_nOTERACTIVITY_NUMBER = "noter_activity";
Button b_create;
// removed other defining stuff
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.quicknote, container, false);
int i = getArguments().getInt(ARG_nOTERACTIVITY_NUMBER);
String noter_activity = getResources().getStringArray(
R.array.noter_array)[i];
FragmentManager fm = getFragmentManager();
setRetainInstance(true);
b_create = (Button) rootView.findViewById(R.id.qn_b_create);
// Removed other stuff
getActivity().setTitle(noter_activity);
return rootView;
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.qn_b_create:
String data = "String data";
DataModel.getInstance().addItem(data);
break;
}
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
// TODO Auto-generated method stub
super.onCreateOptionsMenu(menu, inflater);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle item selection
}
}
public interface OnItemAddedHandler { // Srains code
public void onItemAdded(Object data);
}
}
This is HistoryFragment (Remember it is part of a ViewPager):
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.RiThBo.noter.QuickNoteFragment.OnItemAddedHandler;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;
public class HistoryFragment extends FragmentBase implements OnItemAddedHandler {
ListView lv;
List<Map<String, String>> planetsList = new ArrayList<Map<String, String>>();
SimpleAdapter simpleAdpt;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
View view = inflater.inflate(R.layout.history, container, false);
initList();
ListView lv = (ListView) view.findViewById(R.id.listView);
simpleAdpt = new SimpleAdapter(getActivity(), planetsList,
android.R.layout.simple_list_item_1, new String[] { "planet" },
new int[] { android.R.id.text1 });
lv.setAdapter(simpleAdpt);
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parentAdapter, View view,
int position, long id) {
// We know the View is a TextView so we can cast it
TextView clickedView = (TextView) view;
Toast.makeText(
getActivity(),
"Item with id [" + id + "] - Position [" + position
+ "] - Planet [" + clickedView.getText() + "]",
Toast.LENGTH_SHORT).show();
}
});
registerForContextMenu(lv);
return view;
}
private void initList() {
// We populate the planets
planetsList.add(createPlanet("planet", "Mercury"));
planetsList.add(createPlanet("planet", "Venus"));
planetsList.add(createPlanet("planet", "Mars"));
planetsList.add(createPlanet("planet", "Jupiter"));
planetsList.add(createPlanet("planet", "Saturn"));
planetsList.add(createPlanet("planet", "Uranus"));
planetsList.add(createPlanet("planet", "Neptune"));
}
private HashMap<String, String> createPlanet(String key, String name) {
HashMap<String, String> planet = new HashMap<String, String>();
planet.put(key, name);
return planet;
}
// We want to create a context Menu when the user long click on an item
#Override
public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
AdapterContextMenuInfo aInfo = (AdapterContextMenuInfo) menuInfo;
// We know that each row in the adapter is a Map
HashMap map = (HashMap) simpleAdpt.getItem(aInfo.position);
menu.setHeaderTitle("Options for " + map.get("planet"));
menu.add(1, 1, 1, "Details");
menu.add(1, 2, 2, "Delete");
}
#Override
public void onItemAdded(Object data) {
// to add item
String string = String.valueOf(data);
Toast.makeText(getContext(), "Data: " + string, Toast.LENGTH_SHORT).show();
planetsList.add(createPlanet("planet", string));
}
#Override
public void onStart() {
super.onStart();
DataModel.getInstance().setOnItemAddedHandler(this);
}
}
This is FragmentBase:
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
public class FragmentBase extends Fragment {
private FragmentActivity mActivity; // I changed it to FragmentActivity because Activity was not working, and my `NavDrawer` is a FragmentActivity.
public void setContext(FragmentActivity activity) {
mActivity = mActivity;
}
public FragmentActivity getContext() {
return mActivity;
}
}
This is DataModel:
import android.util.Log;
import com.xxx.xxx.QuickNoteFragment.OnItemAddedHandler;
public class DataModel {
private static DataModel instance;
private static OnItemAddedHandler mOnItemAddHandler;
public static DataModel getInstance() {
if (null == instance) {
instance = new DataModel();
}
return instance;
}
public void setOnItemAddedHandler(OnItemAddedHandler handler) {
mOnItemAddHandler = handler;
}
public void addItem(Object data) {
if (null != mOnItemAddHandler)
mOnItemAddHandler.onItemAdded(data);
else {
Log.i("is context null?", "yes!");
}
}
}
Thank you
I suggest you to use interface and MVC, that will make your code much more maintainable.
First you need an interface:
public interface OnItemAddedHandler {
public void onItemAdded(Object data);
}
Then, you will need a data model:
public class DataModel {
private static DataModel instance;
private static OnItemAddedHandler mOnItemAddHandler;
public static DataModel getInstance() {
if (null == instance) {
instance = new DataModel();
}
return instance;
}
public void setOnItemAddedHandler(OnItemAddedHandler handler) {
mOnItemAddHandler = handler;
}
public void addItem(Object data) {
if (null != mOnItemAddHandler)
mOnItemAddHandler.onItemAdded(data);
}
}
When you click the button, you can add data into the datamodel:
Object data = null;
DataModel.getInstance().addItem(data);
Then, the FragmentB implements the interface OnItemAddedHandler to add item
public class FragmentB implements OnItemAddedHandler {
#Override
public void onItemAdded(Object data) {
// to add item
}
}
also, When the FragmentB start, you should register itself to DataModel:
public class FragmentB implements OnItemAddedHandler {
#Override
public void onItemAdded(Object data) {
// to add item
}
#Override
protected void onStart() {
super.onStart();
DataModel.getInstance().setOnItemAddedHandler(this);
}
}
You also can add DataModel.getInstance().setOnItemAddedHandler(this); to the onCreate method of FragmentB
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
DataModel.getInstance().setOnItemAddedHandler(this);
// do other things
}
update
you can send string simply:
String data = "some string";
DataModel.getInstance().addItem(data);
then on FragementB
public class FragmentB implements OnItemAddedHandler {
#Override
public void onItemAdded(Object data) {
// get what you send into method DataModel.getInstance().addItem(data);
String string = String.valueOf(data);
}
}
update
OK. You have add DataModel.getInstance().setOnItemAddedHandler(this) in onCreateView method, so there is no need to add it in onStart() method. You can remove the whole onStart method.
onStart will be called on the fragment start, we do not need to call it in onCreateView. And on onItemAdded will be call when call the method DataModel.getInstance().addItem(data), we do not need to call it in onCreateView neither.
so, you can remove the code below from onCreateView method:
DataModel.getInstance().setOnItemAddedHandler(this);
// remove the methods below
// onItemAdded(getView());
// onStart();
You have another fragment where there is a button, you can add the codes below in the clickhandler function:
String data = "some string";
DataModel.getInstance().addItem(data);
update3
I think the HistoryFragment has been detached after you when to QuickNoteFragment
You can add code to HistoryFragment to check:
#Override
public void onDetach() {
super.onDetach();
Log.i("test", String.format("onDetach! %s", getActivity() == null));
}
update4
I think HistoryFragment and QuickNoteFragment should has an parent class, named FragmentBase:
public class FragmentBase extends Fragment {
private Activity mActivity;
public void setContext(Activity activity) {
mActivity = mActivity;
}
public Activity getContext() {
return mActivity;
}
}
HistoryFragment and QuickNoteFragment extends FragmentBase. Then when you switch between them, you can call setContext to set a Activity, like:
private void selectItem(int position) {
FragmentManager fragmentManager = getSupportFragmentManager();
if (position == 0) {
Fragment qnfragment = new QuickNoteFragment();
qnfragment.setContext(this);
// ...
} else if (position == 1) {
Fragment pagerFragment = new RemViewPager();
pagerFragment.setContext(this);
// ...
}
}
now, we can get a non-null activity in HistoryFragment by calling getContext, so we can change onItemAdded method to:
#Override
public void onItemAdded(Object data) {
// to add item
String string = String.valueOf(data);
Toast.makeText(getContext(), "Data: " + string, Toast.LENGTH_SHORT).show();
planetsList.add(createPlanet("planet", string));
}
I hope this would work.
Some good design principals:
An activity can know everything pubic about any Fragment it contains.
A Fragment should not know anything about the specific Activities that contain it.
A Fragment should NEVER know about other fragments that may or may not be contained in the Parent activity.
A suggested approach (informal design pattern) based on these principles.
Each fragment should declare an interface to be implemented by its parent activity:
public class MyFragment extends Fragment
{
public interface Parent
{
void onMyFragmentSomeAction();
}
private Parent mParent;
public onAttach(Activity activity)
{
mParent = (Parent) activity;
}
// This would actually be in a listener. Simplifying to save typing.
void onSomeButtonClick(View button)
{
mParent.onMyFragmentSomeAction();
}
}
And the activity should implement the appropriate interfaces for all of its contained fragments.
public class MyActivity extends Activity
implements MyFragment.Parent,
YourFragment.Parent,
HisFragment.Parent
{
[usual Activity code]
void onMyFragmentSomeAction()
{
if yourFragment is showing
{
yourFragment.reactToSomeAction();
}
if hisFragment is showing
{
hisFragment.observeThatSomeActionHappened();
}
[etc]
}
The broadcast approach is good, too, but it's pretty heavyweight and it requires the target Fragment to know what broadcasts will be sent by the source Fragment.
Use Broadcast. Send a boradcast from A, and B will receive and handle it.
Add a public method to B, for example, public void addListItem(), which will add data to listview in B. Fragment A try to find the instance of Fragment B using FragmentMananger.findFragmentByTag() and invoke this method.

How can I make a fragment replace actionbar menu behavior?

Before I start, yes I have read countless related questions. I still can't seem to track down the issue.
I have a SherlockFragmentActivity:
package com.kicklighterdesignstudio.floridaday;
import android.os.Bundle;
import android.support.v4.app.Fragment;
public class FragmentActivity extends BaseActivity {
public static final String TAG = "FragmentActivity";
public static final int SCHEDULE_FRAGMENT = 0;
public static final int MAP_FRAGMENT = 1;
public static final int FOOD_FRAGMENT = 2;
public static final int TWITTER_FRAGMENT = 3;
public static final int HASHTAG_FRAGMENT = 4;
private Fragment mContent;
public FragmentActivity() {
super(R.string.main_activity_title);
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.content_frame);
switchContent(SCHEDULE_FRAGMENT);
setBehindContentView(R.layout.menu_frame);
}
public void switchContent(int id) {
getFragment(id);
getSupportFragmentManager().beginTransaction().replace(R.id.content_frame, mContent)
.commit();
getSlidingMenu().showContent();
}
private void getFragment(int id) {
switch (id) {
case 0:
mContent = new ScheduleFragment();
break;
case 1:
mContent = new FoodFragment();
break;
case 2:
mContent = new MapFragment();
break;
case 3:
mContent = new TwitterFragment();
break;
case 4:
mContent = new HashtagFragment();
break;
}
}
}
It extends BaseActivity:
package com.kicklighterdesignstudio.floridaday;
import android.os.Bundle;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.app.ListFragment;
import com.actionbarsherlock.view.MenuItem;
import com.slidingmenu.lib.SlidingMenu;
import com.slidingmenu.lib.app.SlidingFragmentActivity;
public class BaseActivity extends SlidingFragmentActivity {
// private int mTitleRes;
protected ListFragment mFrag;
public BaseActivity(int titleRes) {
// mTitleRes = titleRes;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// setTitle(mTitleRes);
setTitle("");
// set the Behind View
setBehindContentView(R.layout.menu_frame);
if (savedInstanceState == null) {
FragmentTransaction t = this.getSupportFragmentManager().beginTransaction();
mFrag = new MenuFragment();
t.replace(R.id.menu_frame, mFrag);
t.commit();
} else {
mFrag = (ListFragment) this.getSupportFragmentManager().findFragmentById(
R.id.menu_frame);
}
// customize the SlidingMenu
SlidingMenu sm = getSlidingMenu();
sm.setShadowWidthRes(R.dimen.shadow_width);
sm.setShadowDrawable(R.drawable.shadow);
sm.setBehindOffsetRes(R.dimen.slidingmenu_offset);
sm.setFadeDegree(0.35f);
sm.setTouchModeAbove(SlidingMenu.TOUCHMODE_MARGIN);
sm.setBehindScrollScale(0.0f);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
toggle();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}
Right now, I'm only concerned with ScheduleFragment:
package com.kicklighterdesignstudio.floridaday;
import java.util.ArrayList;
import android.app.Activity;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import com.actionbarsherlock.app.SherlockFragment;
public class ScheduleFragment extends SherlockFragment implements OnItemClickListener {
public static final String TAG = "ScheduleFragment";
private ArrayList<ScheduleItem> schedule;
private FloridaDayApplication app;
public ScheduleFragment() {
// setRetainInstance(true);
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
app = (FloridaDayApplication) activity.getApplication();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.schedule_fragment, container, false);
}
#Override
public void onStart() {
super.onStart();
getSherlockActivity().getSupportActionBar().setTitle(R.string.schedule_fragment);
schedule = app.getSchedule();
ListView scheduleListView = (ListView) getActivity().findViewById(R.id.schedule_list);
ScheduleItemAdapter adapter = new ScheduleItemAdapter(getActivity(), schedule);
scheduleListView.setAdapter(adapter);
scheduleListView.setOnItemClickListener(this);
}
#Override
public void onItemClick(AdapterView<?> a, View v, int id, long position) {
Fragment newFragment = new ScheduleItemFragment(id);
FragmentTransaction transaction = getSherlockActivity().getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.content_frame, newFragment).addToBackStack(null).commit();
}
}
ScheduleFragment displays a list of schedule items. When clicked, a new fragment is displayed (ScheduleItemFragment) to show details of the item and a map to its location:
package com.kicklighterdesignstudio.floridaday;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.actionbarsherlock.app.SherlockFragment;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuInflater;
import com.actionbarsherlock.view.MenuItem;
import com.google.android.gms.common.GooglePlayServicesNotAvailableException;
import com.google.android.gms.maps.CameraUpdate;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapView;
import com.google.android.gms.maps.MapsInitializer;
import com.google.android.gms.maps.model.MarkerOptions;
#SuppressLint("ValidFragment")
public class ScheduleItemFragment extends SherlockFragment {
public static final String TAG = "ScheduleItemFragment";
private int scheduleItemId;
private FloridaDayApplication app;
private ScheduleItem scheduleItem;
private MapView mapView;
private GoogleMap map;
public ScheduleItemFragment(int id) {
scheduleItemId = id;
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
app = (FloridaDayApplication) activity.getApplication();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.schedule_item_fragment, container, false);
setHasOptionsMenu(true);
// Initialize MapView
mapView = (MapView) v.findViewById(R.id.map_view);
mapView.onCreate(savedInstanceState);
return v;
}
#Override
public void onStart() {
super.onStart();
scheduleItem = app.getSchedule().get(scheduleItemId);
getSherlockActivity().getSupportActionBar().setTitle(scheduleItem.getTitle());
// Map Stuff
map = mapView.getMap();
if (map != null) {
map.getUiSettings();
map.setMyLocationEnabled(true);
try {
MapsInitializer.initialize(getActivity());
} catch (GooglePlayServicesNotAvailableException e) {
e.printStackTrace();
}
// Add marker to the map
MarkerOptions options = new MarkerOptions().position(scheduleItem.getLocation().getPosition()).title(
scheduleItem.getLocation().getTitle());
map.addMarker(options);
// Adjust Camera Programmatically
CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngZoom(
scheduleItem.getLocation().getPosition(), 14);
map.animateCamera(cameraUpdate);
} else {
Log.i(TAG, "Map is null");
}
// Other Views
TextView title = (TextView) getSherlockActivity().findViewById(R.id.title);
TextView time = (TextView) getSherlockActivity().findViewById(R.id.time);
TextView description = (TextView) getSherlockActivity().findViewById(R.id.description);
title.setText(scheduleItem.getTitle());
time.setText(scheduleItem.getDateTimeString());
description.setText(scheduleItem.getDescription());
}
// TODO: Make this work
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
getFragmentManager().popBackStack();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
super.onCreateOptionsMenu(menu, inflater);
}
#Override
public void onDestroy() {
mapView.onDestroy();
super.onDestroy();
}
#Override
public void onLowMemory() {
mapView.onLowMemory();
super.onLowMemory();
}
#Override
public void onPause() {
mapView.onPause();
super.onPause();
}
#Override
public void onResume() {
mapView.onResume();
super.onResume();
}
#Override
public void onSaveInstanceState(Bundle outState) {
mapView.onSaveInstanceState(outState);
super.onSaveInstanceState(outState);
}
}
Thanks to BaseActivity, the icon in my ActionBar is clickable. It toggles the Sliding Menu. When viewing a ScheduleItemFragment, I would like the icon to return to the previous item in the backstack (which you can see I'm trying to do.) No matter what I try, the icon always toggles the Sliding Menu. Any thoughts on how to guarantee my Fragment gains control of the ActionBar menu clicks?
you need to call setHasOptionsMenu(true); in onCreate, not onCreateView
also I'm interested what happens when you debug, does onOptionsItemSelected still get called?
edit: add the following to your fragment
#Override
public void onCreate(Bundle savedInstanceState) {
setHasOptionsMenu(true);
super.onCreate(savedInstanceState);
}
edit1:
there may be a better way to do this but I'm not exactly sure how your fragments are setup out, create a public field in baseActivity public bool isItemFragmentOnTop
now onOptionsItemSelected in the case of the home button getting press do this
if (isItemFragmentOnTop){
getFragmentManager().popBackStack();
isItemFragmentOnTop = false;
} else {
toggle();
}
return true;
then in your fragment you can call ((BaseActivity)getActivity).isItemFragmentOnTop = true; to make the home button pop the back stack, you would want to do this when you display your fragment onItemClick in your list view.

Categories

Resources