I am using Navigational drawer for showing ExpandableListview . Every thing is working perfect except one ... When no data network the drawer doesn't opens ( when clicked on the drawer icon nothing happens )
There is NO code explicitly to OPEN drawer when network is available .
MainActivity.java
public class MainActivity extends Activity implements OnQueryTextListener {
public int CURRENT_THEME;
/* Google Analytics*/
Button btn_trackEvent, btn_trackCrash;
EasyTracker easyTracker = null;
GoogleAnalytics googleAnalytics;
StandardExceptionParser exceptionParser;
/* END GOOGLE ANALYTICS */
/* shared preference */
SharedPreferences sharedExpListView;
SharedPreferences.Editor editorExpList;
/* end of shared preference */
private DrawerLayout mDrawerLayout;
//private ListView expListView;
ExpandableListAdapter listAdapter;
ExpandableListView expListView;
List<String> listDataHeader;
HashMap<String, List<String>> listDataChild,emptyChildren;
List<String> list_cat_name,list_cat_id,list_setting;
private HashMap<String, ArrayList<String>> emptyChild;
private ActionBarDrawerToggle mDrawerToggle;
// nav drawer title
private CharSequence mDrawerTitle;
// used to store app title
private CharSequence mTitle;
// slide menu items
private String[] navMenuTitles;
private TypedArray navMenuIcons;
private TextView mStatusView;
private ArrayList<NavDrawerItem> navDrawerItems;
private NavDrawerListAdapter adapter;
JSONArray cat = null;
// Hashmap for ListView
// ArrayList<HashMap<String, String>> catList;
int error_flag = 0; // 0 normal, 1 internet connvettion 2Server Error
private TextView main_error;
private TextView textView;
String FavCount = "0";
/* for push */
// Asyntask
AsyncTask<Void, Void, Void> mRegisterTask;
public static String name = "All";
public static String email = "newsfirst#gmail.com";
#Override
protected void onCreate(Bundle savedInstanceState) {
// Let's get rid of the app icon here
ActionBar actionBar = getActionBar();
actionBar.setIcon(null);
actionBar.setTitle("");
super.onCreate(savedInstanceState);
//overridePendingTransition(R.anim.slide_in, R.anim.slide_out);
//LayoutInflater inflator = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
//View view = inflator.inflate(R.layout.action_bar_custom, null);
setContentView(R.layout.activity_main);
// Google Analytics
googleAnalytics = GoogleAnalytics.getInstance(this);
googleAnalytics.setDryRun(true);
googleAnalytics.getLogger().setLogLevel(LogLevel.VERBOSE);
easyTracker = EasyTracker.getInstance(MainActivity.this);
easyTracker.set(Fields.SCREEN_NAME, "MainActivity");
easyTracker.send(MapBuilder.createAppView().build());
exceptionParser = new StandardExceptionParser(MainActivity.this, null);
// End Google Analytics
/* get polling webservice*/
StrictMode.ThreadPolicy policy1 = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy1);
/* shared preference */
sharedExpListView=this.getSharedPreferences("sharedExpListView", MODE_PRIVATE);
editorExpList=sharedExpListView.edit();
// mTitle = mDrawerTitle = getTitle();
// load slide menu items
navMenuTitles = getResources().getStringArray(R.array.nav_drawer_items);
// nav drawer icons from resources
navMenuIcons = getResources()
.obtainTypedArray(R.array.nav_drawer_icons);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
navDrawerItems = new ArrayList<NavDrawerItem>();
// Home
navDrawerItems.add(new NavDrawerItem(navMenuTitles[0], "", navMenuIcons
.getResourceId(0, -1), "0"));
FavCount = String.valueOf(All_link.getFavRowCount(MainActivity.this));
// initialize Expandable listview
expListView = (ExpandableListView) findViewById(R.id.list_slidermenu);
expListView.setGroupIndicator(null);
list_cat_name = new ArrayList<String>();
list_cat_id = new ArrayList<String>();
list_setting = new ArrayList<String>();
listDataHeader = new ArrayList<String>();
listDataChild = new HashMap<String, List<String>>();
emptyChild = new HashMap<String, ArrayList<String>>();
new GetCatList().execute();
mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,
R.drawable.ic_drawer, // nav menu toggle icon
0, // nav drawer open - description for
// accessibility
0 // nav drawer close - description for
// accessibility
) {
#Override
public void onDrawerClosed(View view) {
getActionBar().setTitle(mTitle);
// calling onPrepareOptionsMenu() to show action bar icons
invalidateOptionsMenu();
}
#Override
public void onDrawerOpened(View drawerView) {
getActionBar().setTitle(mDrawerTitle);
// calling onPrepareOptionsMenu() to hide action bar icons
//Toast.makeText(MainActivity.this, "Network Error", Toast.LENGTH_SHORT).show();
invalidateOptionsMenu();
}
};
mDrawerLayout.setDrawerListener(mDrawerToggle);
if (savedInstanceState == null) {
// on first time display view for first nav item
displayView(0, "0");
}
}
/**
* Slide menu item click listener
* */
private class SlideMenuClickListener implements
ListView.OnItemClickListener {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
Log.e("position", "karpo "+position);
TextView txt_id = (TextView) view.findViewById(R.id.txt_id);
String catid = txt_id.getText().toString();
TextView txt_title = (TextView) view.findViewById(R.id.title);
All_link.GLOBAL_TITLE = "";
All_link.GLOBAL_TITLE = txt_title.getText().toString();
// display view for selected nav drawer item
if (!catid.isEmpty())
displayView(position, catid);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Toast.makeText(this, "Selected Item: " + item.getTitle(),
// Toast.LENGTH_SHORT).show();
// toggle nav drawer on selecting action bar app icon/title
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
// Handle action bar actions click
switch (item.getItemId()) {
/*
* case R.id.action_search:
*
* return true;
*/
default:
return super.onOptionsItemSelected(item);
}
}
/* *
* Called when invalidateOptionsMenu() is triggered
*/
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
// if nav drawer is opened, hide the action items
// boolean drawerOpen = mDrawerLayout.isDrawerOpen(expListView);
// menu.findItem(R.id.action_search).setVisible(!drawerOpen);
return super.onPrepareOptionsMenu(menu);
}
/**
* Diplaying fragment view for selected nav drawer list item
* */
private void displayView(int position, String id) {
// update the main content by replacing fragments
Fragment fragment = null;
Log.e("POSITION", String.valueOf(id));
int position_id = Integer.parseInt(id);
switch (position_id) {
case 0:
// update selected item and title, then close the drawer
try{
fragment = new HomeFragment();
easyTracker.send(MapBuilder.createEvent("Menu Click", "Fragment", "HomeFragment", null).build());
}
catch(Exception e){
easyTracker.send(MapBuilder.createException(exceptionParser.getDescription(Thread.currentThread().getName(), e), false).build());
}
break;
default:
fragment = new CategoryFragment(id);
Log.e("category id","karcat "+id);
break;
}
// update selected item and title, then close the drawer
// expListView.setItemChecked(position, true);
// expListView.setSelection(position);
// //setTitle(navMenuTitles[position]);
// mDrawerLayout.closeDrawer(expListView);
if (fragment != null) {
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.frame_container, fragment).commit();
expListView.setItemChecked(position, true);
expListView.setSelection(position);
// setTitle(navMenuTitles[position]);
mDrawerLayout.closeDrawer(expListView);
} else {
// error in creating fragment
Log.e("MainActivity", "Error in creating fragment");
}
}
#Override
public void setTitle(CharSequence title) {
mTitle = title;
getActionBar().setTitle(mTitle);
}
#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);
}
/**
* Async task class to get json by making HTTP call
* */
private class GetCatList extends AsyncTask<String, Void, Void> {
#Override
protected void onPreExecute() {
//expListView.setVisibility(8);
super.onPreExecute();
// Adding group data
listDataHeader.add("Home");
listDataHeader.add("News Category");
listDataHeader.add("My Favourites");
listDataHeader.add("Manage Notifications");
listDataHeader.add("Send Your Story");
listDataHeader.add("News on WhatsApp");
listDataHeader.add("About NewsFirst");
listDataHeader.add("Contact NewsFirst");
listDataHeader.add("Share this App");
listDataHeader.add("Rate this App");
listDataHeader.add("Settings");
listDataChild.put(listDataHeader.get(0), new ArrayList<String>()); // No child
listDataChild.put(listDataHeader.get(2), new ArrayList<String>()); // No child
listDataChild.put(listDataHeader.get(3), new ArrayList<String>()); // No child
listDataChild.put(listDataHeader.get(4), new ArrayList<String>()); // No child
listDataChild.put(listDataHeader.get(5), new ArrayList<String>()); // No child
listDataChild.put(listDataHeader.get(6), new ArrayList<String>()); // No child
listDataChild.put(listDataHeader.get(7), new ArrayList<String>()); // No child
listDataChild.put(listDataHeader.get(8), new ArrayList<String>()); // No child
listDataChild.put(listDataHeader.get(9), new ArrayList<String>()); // No child
list_setting.add("FAQs");
list_setting.add("Privacy Policy");
list_setting.add("Terms & Conditions");
listDataChild.put(listDataHeader.get(10), list_setting); // With child
}
#Override
protected Void doInBackground(String... params) {
if (NetworkCheck.isNetworkAvailable(getApplicationContext()) == true) {
//navDrawerItems = new ArrayList<NavDrawerItem>();
// Creating service handler class instance
ServiceHandler sh = new ServiceHandler();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(All_link.CATEGORY_URL,
ServiceHandler.GET);
Log.d("Response: ", "> " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
cat = jsonObj.getJSONArray(All_link.TAG_NEWS);
String err = jsonObj.getString(All_link.TAG_ERROR);
Log.e("------>Error", String.valueOf(err));
if (err.equals("1")) {
} else {
// looping through All Contacts
for (int i = 0; i < cat.length(); i++) {
JSONObject c = cat.getJSONObject(i);
String cat_id = c.getString(All_link.TAG_CAT_ID);
String cat_name = c
.getString(All_link.TAG_CAT_NAME);
String image_icon = c.getString("image_icon");
list_cat_name.add(cat_name);
list_cat_id.add(cat_id);
}
// saving cat_name with cat id in shared preference
for (int i = 0; i <list_cat_name.size(); i++) {
editorExpList.putString(list_cat_name.get(i), list_cat_id.get(i));
editorExpList.commit();
}
// End saving cat_name with cat id in shared preference
listDataChild.put(listDataHeader.get(1), list_cat_name); // With child
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("ServiceHandler",
"Couldn't get any data from the url");
runOnUiThread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
Toast.makeText(MainActivity.this, "Network Error", Toast.LENGTH_SHORT).show();
}
});
}
} else {
Log.e("Network Error", "Internet Connection Error");
error_flag = 1;
// error = "Internet Connection Error";
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
if (error_flag == 1) {
expListView.setVisibility(8);
// main_error.setText("Internet Connection Error! Please check your network settings and try again");
// main_error.setVisibility(0);
} else {
/*
* navDrawerItems.add(new NavDrawerItem(navMenuTitles[1],
* navMenuIcons .getResourceId(0, -1),"1"));
*/
expListView.setVisibility(0);
// main_error.setText("");
// main_error.setVisibility(8);
// Recycle the typed array
navMenuIcons.recycle();
expListView
.setOnItemClickListener(new SlideMenuClickListener());
// setting the nav drawer list adapter
/*adapter = new NavDrawerListAdapter(getApplicationContext(),
navDrawerItems);*/
listAdapter=new ExpandableListAdapter(MainActivity.this, listDataHeader, listDataChild);
expListView.setAdapter(listAdapter);
expListView.setItemChecked(0, true);
expListView.setSelection(0);
}
}
}
}
Presumably, your Drawer consists of only the ExpandableListView expListView. If you check the AsyncTask's doInBackground() method, you'll see that error_flag is set to 1 if there's no network available. Then, in the onPostExecute() method:
if (error_flag == 1) {
expListView.setVisibility(8);
A value of 8 corresponds to View.GONE, so, essentially, if there is no network, there is no Drawer.
Related
I find a lot of tutorials on the Internet on how to implement a navigation drawer for Android Studio.
However, let's say I want to create a navigation drawer for any activity but with different items, is it possible to create some sort of baseactivity so I only need to write the NavDrawerItems and the DrawerItemClickListener ...
Can this BaseActivity be achieved or is it too far fetched? I searched alot on Google about this, but didn't find any tutorials concerning this particular question I got :( Most of the baseactivity tutorials I find are for navigation drawer with the same items.
Edit:
Code I have for now, but in my opinion it's a bit long to read:
Tutorials I used are:
https://trinitytuts.com/android-navigation-drawer-with-material-design-arrow/ http://thedeveloperworldisyours.com/android/put-image-navigation-drawer/
public class MainActivity extends Activity {
private Context context;
private RelativeLayout mDrawerRelativeLayout;
private DrawerLayout mDrawerLayout;
private ListView mDrawerList;
private ActionBarDrawerToggle mDrawerToggle;
private CharSequence mDrawerTitle;
private CharSequence mTitle;
private String[] mRequestsArray;
Toolbar toolbar;
TextView toolbarTitle;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
this.context = this;
mTitle = mDrawerTitle = getTitle();
mRequestsArray = new String[] { "Catalog", "Account", "Checkout", "Utilities"};
mDrawerRelativeLayout = (RelativeLayout) findViewById(R.id.left_drawer);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerList = (ListView) findViewById(R.id.list_view_drawer);
toolbar = (Toolbar) findViewById(R.id.toolbar);
toolbarTitle = (TextView) findViewById(R.id.titletool);
// 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, mRequestsArray));
mDrawerList.setOnItemClickListener(new DrawerItemClickListener());
// 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 */
toolbar, /* 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) {
toolbarTitle.setText(mTitle);
invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
}
public void onDrawerOpened(View drawerView) {
toolbarTitle.setText(mDrawerTitle);
invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
}
};
mDrawerLayout.setDrawerListener(mDrawerToggle);
if (savedInstanceState == null) {
setTitle(getTitle());
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main, menu);
return super.onCreateOptionsMenu(menu);
}
/* 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);
return super.onPrepareOptionsMenu(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 (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
return super.onOptionsItemSelected(item);
}
/* The click listener for ListView in the navigation drawer */
private class DrawerItemClickListener implements ListView.OnItemClickListener {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Fragment fragment = null;
switch (position) {
case 0:
fragment = new CatalogFragment();
break;
case 1:
fragment = new AccountFragment();
break;
case 2:
fragment = new CheckoutFragment();
break;
case 3:
fragment = new UtilitiesFragment();
break;
}
if (fragment != null) {
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.content_frame, fragment);
fragmentTransaction.commit();
}
selectItem(position);
mDrawerLayout.closeDrawer(mDrawerRelativeLayout);
}
}
private void selectItem(int position) {
// update selected item and title, then close the drawer
mDrawerList.setItemChecked(position, true);
setTitle(mRequestsArray[position]);
mDrawerLayout.closeDrawer(mDrawerRelativeLayout);
}
#Override
public void setTitle(CharSequence title) {
mTitle = title;
toolbarTitle.setText(mTitle);
}
/**
* 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);
}
}
In my opinion, it's possible. You can set it when preparing your list data, as the following sample
private static void prepareListData(final Context context) {
final Activity activity = ((Activity) context);
String activity_name = context.getClass().getSimpleName().replace("Activity", "");
sListDataHeader = new ArrayList<>();
sListDataChild = new HashMap<>();
// adding header data, except current activity
String[] mItemHeaders = activity.getResources().getStringArray(R.array.items_array_expandable_header);
// here...
for (String item : mItemHeaders) {
if (!item.toLowerCase().equals(activity_name.toLowerCase())) {
sListDataHeader.add(item);
}
}
String[] mItemMainChild = activity.getResources().getStringArray(R.array.items_array_expandable_main_child);
// Child data
List<String> listChild = Arrays.asList(mItemMainChild);
// Header, Child data
for (int i = 0; i < sListDataHeader.size() - 2; i++) {
sListDataChild.put(sListDataHeader.get(i), new ArrayList<String>());
}
sListDataChild.put(sListDataHeader.get(sListDataHeader.size() - 1), listChild);
}
Hope this help!
I was trying to use handler in onPageFinished method of onCreateView method of PlanetFragment class. But I am getting looper.prepare() error. Please help. And also please tell if there is some better method to use progressbar.
public class MainActivity extends Activity {
private DrawerLayout mDrawerLayout;
private ListView mDrawerList;
private ActionBarDrawerToggle mDrawerToggle;
private CharSequence mDrawerTitle;
private CharSequence mTitle;
private String[] mPlanetTitles;
static Handler progressBarHandler;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mTitle = mDrawerTitle = getTitle();
mPlanetTitles = 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, mPlanetTitles));
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);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main, menu);
return super.onCreateOptionsMenu(menu);
}
/* 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);
}
#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 (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
// Handle action buttons
switch (item.getItemId()) {
case R.id.action_websearch:
// create intent to perform web search for this planet
Intent intent = new Intent(Intent.ACTION_WEB_SEARCH);
intent.putExtra(SearchManager.QUERY, getActionBar().getTitle());
// catch event that there's no activity to handle intent
if (intent.resolveActivity(getPackageManager()) != null) {
startActivity(intent);
} else {
Toast.makeText(this, R.string.app_not_available,
Toast.LENGTH_LONG).show();
}
return true;
default:
return super.onOptionsItemSelected(item);
}
}
/* The click listner for ListView in the navigation drawer */
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
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(mPlanetTitles[position]);
mDrawerLayout.closeDrawer(mDrawerList);
}
#Override
public void setTitle(CharSequence title) {
mTitle = title;
getActionBar().setTitle(mTitle);
}
/**
* 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);
}
/**
* Fragment that appears in the "content_frame", shows a planet
*/
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());
final WebView webview = ((WebView) rootView
.findViewById(R.id.image));
final ProgressBar progressbar = ((ProgressBar) rootView
.findViewById(R.id.progressbar));
webview.getSettings().setJavaScriptEnabled(true);
final PlanetFragment activity = this;
webview.setWebViewClient(new WebViewClient() {
#Override
public void onPageStarted(WebView view, String url,
Bitmap favicon) {
view.setVisibility(View.GONE);// hide the webview that will
// display your dialog
new Thread(new Runnable() {
private int progressBarStatus = 0;
private int fileSize;
public void run() {
progressBarHandler = new Handler();
while (progressBarStatus < 100) {
// process some tasks
progressBarStatus = doWork();
// your computer is too fast, sleep 1 second
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
// Update the progress bar
progressBarHandler.post(new Runnable() {
public void run() {
progressbar
.setProgress(progressBarStatus);
}
});
}
// ok, file is downloaded,
if (progressBarStatus >= 100) {
// sleep 2 seconds, so that you can see the 100%
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
private int doWork() {
while (fileSize <= 1000000) {
fileSize++;
if (fileSize == 100000) {
return 10;
} else if (fileSize == 200000) {
return 20;
} else if (fileSize == 300000) {
return 30;
} else if (fileSize == 200000) {
return 40;
} else if (fileSize == 300000) {
return 50;
} else if (fileSize == 200000) {
return 60;
} else if (fileSize == 300000) {
return 70;
} else if (fileSize == 200000) {
return 80;
} else if (fileSize == 300000) {
return 90;
}
}
return 100;
}
}).start();
}
#Override
public void onPageFinished(WebView view, String url) {
progressBarHandler = new Handler();
webview.loadUrl("javascript:document.getElementsByClassName('header')[0].style.display=\"none\";");
webview.loadUrl("javascript:document.getElementsByClassName('icon-anon')[0].style.display=\"none\";");
webview.loadUrl("javascript:document.getElementsByClassName('search')[0].style.display=\"none\";");
webview.loadUrl("javascript:document.getElementsByClassName('wh_ad')[0].style.display=\"none\";");
webview.loadUrl("javascript:document.getElementsByClassName('cse_x')[0].style.display=\"none\";");
webview.loadUrl("javascript:document.getElementsByClassName('wh_search')[0].style.display=\"none\";");
webview.loadUrl("javascript:document.getElementsByClassName('wh_ad')[0].style.display=\"none\";");
webview.loadUrl("javascript:document.getElementsByClassName('wh_ad')[0].style.display=\"none\";");
webview.loadUrl("javascript:document.getElementsByClassName('footer_random_button')[0].style.display=\"none\";");
webview.loadUrl("javascript:document.getElementsByClassName('mw-mf-page-left')[0].style.display=\"none\";");
webview.loadUrl("javascript:document.getElementsByClassName('mw-mf-viewport')[0].style.display=\"none\";");
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
// Code here will run in UI thread
}
},1000);
webview.getSettings().setJavaScriptEnabled(false);
view.setVisibility(View.VISIBLE);
// you might need this
view.bringToFront();
}
});
webview.loadUrl(planet);
getActivity().setTitle(planet);
return rootView;
}
}
}
You have to create handler in Activity
just initialize the Handler in onCreate method of activity
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
progressBarHandler = new Handler();
// rest of your code
and remove the initialization in Fragment class as it is already initialized in Activity . Just Use progressBarHandler in Fragment Class and it will work fine.
This question already has an answer here:
Fragments starting twice
(1 answer)
Closed 8 years ago.
I'm trying to start a fragment from an activity, but everytime I start the app, the fragment is started twice. This is only happening when I run the app on a tablet device.
Does anyone know what can this issue be, and how can I solve it?
Here is my code:
public class TestSearch extends FragmentActivity {
private DrawerLayout mDrawerLayout;
private ListView mDrawerList;
// private ActionBarDrawerToggle mDrawerToggle;
private ArrayList<Device> devices;
private ArrayList<Recepie> recepies, mainRecepies;
private ArrayList<Recepie> searchResult;
private LinearLayout sideWrapper;
private EditText src;
ArrayList<Categories> cats;
boolean isTablet = false;
#SuppressWarnings("unchecked")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.test_search);
Log.v("--", "started");
if (Constants.isTablet(this)) {
isTablet = true;
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
} else {
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
}
devices = new ArrayList<Device>();
recepies = new ArrayList<Recepie>();
mainRecepies = new ArrayList<Recepie>();
devices = (ArrayList<Device>) getIntent().getSerializableExtra(
Constants.DEVICES_EXTRA);
recepies = getIntent().getParcelableArrayListExtra("all");
mainRecepies = getIntent().getParcelableArrayListExtra(
Constants.MAINRECEPIES);
// mTitle = mDrawerTitle = getTitle();
cats = new ArrayList<Categories>();
cats = (ArrayList<Categories>) getIntent().getSerializableExtra("cats");
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerList = (ListView) findViewById(R.id.left_drawer);
sideWrapper = (LinearLayout) findViewById(R.id.listwraper);
// 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
// View header = getLayoutInflater().inflate(R.layout.search_item,
// null);
src = (EditText) findViewById(R.id.search_est);
src.setOnKeyListener(new OnKeyListener() {
public boolean onKey(View v, int keyCode, KeyEvent event) {
// If the event is a key-down event on the "enter" button
if ((event.getAction() == KeyEvent.ACTION_DOWN)
&& (keyCode == KeyEvent.KEYCODE_ENTER)) {
Log.v("--", "Start search");
if (src.getText().length() > 0) {
searchResult = new ArrayList<Recepie>();
final ProgressDialog progress = ProgressDialog.show(
TestSearch.this,
getString(R.string.please_wait),
getString(R.string.getting_search_results),
true);
new AsyncTask<Void, Void, Void>() {
protected void onPreExecute() {
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(
src.getWindowToken(), 0);
};
#Override
protected Void doInBackground(Void... params) {
searchResult = getSearchResults(src.getText()
.toString());
return null;
}
protected void onPostExecute(Void result) {
// set screen to search fragment
Fragment fragment = new SideSearchFragment();
Bundle args = new Bundle();
args.putString("cat-title", src.getText()
.toString());
args.putSerializable("cats", cats);
args.putBoolean(Constants.SEARCH, true);
args.putParcelableArrayList(
Constants.SEARCH_RESULTS, searchResult);
fragment.setArguments(args);
progress.dismiss();
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction()
.add(R.id.content_frame, fragment)
.addToBackStack("search_results")
.commit();
// setTitle(mPlanetTitles[position]);
mDrawerLayout.closeDrawer(sideWrapper);
// clear search text and hide keyboard
src.setText("");
};
}.execute();
}
return true;
}
return false;
}
});
// mDrawerList.addHeaderView(header);
SideAdapter adapter = new SideAdapter(this, cats);
mDrawerList.setAdapter(adapter);
mDrawerList.setOnItemClickListener(new DrawerItemClickListener());
initActionBar();
// enable ActionBar app icon to behave as action to toggle nav drawer
getActionBar().setDisplayHomeAsUpEnabled(false);
getActionBar().setHomeButtonEnabled(true);
if (savedInstanceState == null) {
showMainFragment();
}
}
/* The click listner for ListView in the navigation drawer */
private class DrawerItemClickListener implements
ListView.OnItemClickListener {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
selectItem(position);
}
}
private void showFavoritesFragment() {
Fragment fragment = new FavoritesFragment();
Bundle args = new Bundle();
args.putSerializable("all", recepies);
args.putBoolean("search", true);
args.putSerializable("cats", cats);
fragment.setArguments(args);
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction().add(R.id.content_frame, fragment)
.addToBackStack("favorites").commit();
}
private void showMainFragment() {
Fragment fragment = new MainFragment();
Bundle args = new Bundle();
Log.v("--", "START MAIN FRAGMENT !!");
args.putParcelableArrayList("all", recepies);
args.putSerializable("cats", cats);
args.putParcelableArrayList(Constants.MAINRECEPIES, mainRecepies);
args.putBoolean("search", true);
fragment.setArguments(args);
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction().replace(R.id.content_frame, fragment)
.commit();
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
if (mDrawerLayout.isDrawerOpen(sideWrapper))
mDrawerLayout.closeDrawer(sideWrapper);
else
mDrawerLayout.openDrawer(sideWrapper);
return true;
case R.id.main_action_fav:
showFavoritesFragment();
return true;
case R.id.main_action_choose_cats:
Intent intent = new Intent(this, CircleListActivity.class);
intent.putExtra(Constants.DEVICES_EXTRA, devices);
intent.putExtra("cats", cats);
startActivity(intent);
// finish();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
private void initActionBar() {
getActionBar().setBackgroundDrawable(
new ColorDrawable(Color.parseColor("#e91a34")));
getActionBar().setCustomView(R.layout.actionbar_custom_view_home);
// actionBar.setcu
getActionBar().setDisplayShowTitleEnabled(false);
getActionBar().setDisplayShowCustomEnabled(true);
getActionBar().setDisplayUseLogoEnabled(false);
getActionBar().setDisplayShowHomeEnabled(true);
getActionBar().setHomeButtonEnabled(false);
getActionBar().setIcon(R.drawable.menu);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main, menu);
return true;
}
private void selectItem(int position) {
// update the main content by replacing fragments
Fragment fragment = new SearchFragment();
Bundle args = new Bundle();
args.putString("cat-title", cats.get(position).getTitle());
args.putInt(Constants.CATEGORY_ID, cats.get(position).getId());
args.putSerializable("cats", cats);
fragment.setArguments(args);
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction().add(R.id.content_frame, fragment)
.addToBackStack(null).commit();
// update selected item and title, then close the drawer
mDrawerList.setItemChecked(position, true);
mDrawerList.setSelection(position);
// setTitle(mPlanetTitles[position]);
mDrawerLayout.closeDrawer(sideWrapper);
}
#Override
public void setTitle(CharSequence title) {
// mTitle = title;
// getActionBar().setTitle(mTitle);
}
/**
* 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);
}
// This function gets the search results
public ArrayList<Recepie> getSearchResults(String keyword) {
ArrayList<Recepie> resultRecepie = new ArrayList<Recepie>();
JSONParser jParser = new JSONParser();
// get JSON data from URL
JSONObject jObj = jParser
.getJSONObjectFromUrl("http://oursson-recipes.outsourcingfarm.com/index.php/jsoner/getRecipe?query="
+ keyword);
try {
JSONArray withTechnics = jObj.getJSONArray("with_technics");
JSONArray withoutTechnics = jObj.getJSONArray("without_technics");
for (int i = 0; i < withTechnics.length(); i++) {
JSONObject with = withTechnics.getJSONObject(i);
boolean bool_tehcnics = true;
if (with.getInt("with_technics") == 1)
bool_tehcnics = false;
boolean my_devices = false;
if (with.getInt("mydevices") == 1)
my_devices = true;
JSONArray devices = with.getJSONArray("devices");
ArrayList<Integer> devicesIDs = new ArrayList<Integer>();
for (int k = 0; k < devices.length(); k++) {
devicesIDs.add(Integer.valueOf(devices.getString(k)));
}
resultRecepie.add(new Recepie(bool_tehcnics, my_devices, with
.getInt("id"), with.getInt("persons"), with
.getString("title"),
with.getString("preparation_time"), with
.getString("image_1"), devicesIDs));
}
for (int i = 0; i < withoutTechnics.length(); i++) {
JSONObject with = withoutTechnics.getJSONObject(i);
boolean bool_tehcnics = false;
if (with.getInt("with_technics") == 1)
bool_tehcnics = true;
boolean my_devices = false;
if (with.getInt("mydevices") == 1)
my_devices = true;
JSONArray devices = with.getJSONArray("devices");
ArrayList<Integer> devicesIDs = new ArrayList<Integer>();
for (int k = 0; k < devices.length(); k++) {
devicesIDs.add(Integer.valueOf(devices.getString(k)));
}
resultRecepie.add(new Recepie(bool_tehcnics, my_devices, with
.getInt("id"), with.getInt("persons"), with
.getString("title"),
with.getString("preparation_time"), with
.getString("image_1"), devicesIDs));
}
} catch (JSONException e) {
e.printStackTrace();
}
return resultRecepie;
}
}
I'm guessing that onCreate() is called twice, and the function showMainFragment(); is called twice.
When you're starting your Activity you're calling:
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
When calling this method, your Activity is possibly restarted, if the tablet is in portrait mode when the app starts up. This is stated in the documentation.
When you're Activity is restarted, onCreate is called once again and your Fragment is created once again.
On a side-note: It's not good practice to force your app into a specific orientation.
I have my navigation drawer activity as my MainActivity class and I already have Homepage.class activity previously made. Since Navigation Drawer uses Fragments, I am unable to call Homepage class through Drawer. Plz help me.
Here is my code for the Drawer-
public class MainActivity extends Activity {
private DrawerLayout mDrawerLayout;
private ListView mDrawerList;
private ActionBarDrawerToggle mDrawerToggle;
// nav drawer title
private CharSequence mDrawerTitle;
// used to store app title
private CharSequence mTitle;
// slide menu items
private String[] navMenuTitles;
private TypedArray navMenuIcons;
private ArrayList<NavDrawerItem> navDrawerItems;
private NavDrawerListAdapter adapter;
#SuppressLint("NewApi")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mTitle = mDrawerTitle = getTitle();
// load slide menu items
navMenuTitles = getResources().getStringArray(R.array.nav_drawer_items);
// nav drawer icons from resources
navMenuIcons = getResources()
.obtainTypedArray(R.array.nav_drawer_icons);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerList = (ListView) findViewById(R.id.list_slidermenu);
navDrawerItems = new ArrayList<NavDrawerItem>();
// adding nav drawer items to array
// Home
navDrawerItems.add(new NavDrawerItem(navMenuTitles[0], navMenuIcons.getResourceId(0, -1)));
// Find People
navDrawerItems.add(new NavDrawerItem(navMenuTitles[1], navMenuIcons.getResourceId(1, -1)));
// Photos
navDrawerItems.add(new NavDrawerItem(navMenuTitles[2], navMenuIcons.getResourceId(2, -1)));
// Communities, Will add a counter here
navDrawerItems.add(new NavDrawerItem(navMenuTitles[3], navMenuIcons.getResourceId(3, -1), true, "22"));
// Pages
navDrawerItems.add(new NavDrawerItem(navMenuTitles[4], navMenuIcons.getResourceId(4, -1)));
// What's hot, We will add a counter here
navDrawerItems.add(new NavDrawerItem(navMenuTitles[5], navMenuIcons.getResourceId(5, -1), true, "50+"));
// Recycle the typed array
navMenuIcons.recycle();
mDrawerList.setOnItemClickListener(new SlideMenuClickListener());
// setting the nav drawer list adapter
adapter = new NavDrawerListAdapter(getApplicationContext(),
navDrawerItems);
mDrawerList.setAdapter(adapter);
// enabling action bar app icon and behaving it as toggle button
getActionBar().setDisplayHomeAsUpEnabled(true);
getActionBar().setHomeButtonEnabled(true);
mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,
R.drawable.ic_drawer, //nav menu toggle icon
R.string.app_name, // nav drawer open - description for accessibility
R.string.app_name // nav drawer close - description for accessibility
) {
public void onDrawerClosed(View view) {
getActionBar().setTitle(mTitle);
// calling onPrepareOptionsMenu() to show action bar icons
invalidateOptionsMenu();
}
public void onDrawerOpened(View drawerView) {
getActionBar().setTitle(mDrawerTitle);
// calling onPrepareOptionsMenu() to hide action bar icons
invalidateOptionsMenu();
}
};
mDrawerLayout.setDrawerListener(mDrawerToggle);
if (savedInstanceState == null) {
// on first time display view for first nav item
displayView(0);
}
}
/**
* Slide menu item click listener
* */
private class SlideMenuClickListener implements
ListView.OnItemClickListener {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
// display view for selected nav drawer item
displayView(position);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// toggle nav drawer on selecting action bar app icon/title
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
// Handle action bar actions click
switch (item.getItemId()) {
case R.id.action_settings:
return true;
default:
return super.onOptionsItemSelected(item);
}
}
/* *
* Called when invalidateOptionsMenu() is triggered
*/
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
// if nav drawer is opened, hide the action items
boolean drawerOpen = mDrawerLayout.isDrawerOpen(mDrawerList);
menu.findItem(R.id.action_settings).setVisible(!drawerOpen);
return super.onPrepareOptionsMenu(menu);
}
/**
* Diplaying fragment view for selected nav drawer list item
* */
private void displayView(int position) {
// update the main content by replacing fragments
Fragment fragment = null;
switch (position) {
case 0:
fragment = new HomeFragment();
break;
case 1:
fragment = new FindPeopleFragment();
break;
case 2:
fragment = new PhotosFragment();
break;
case 3:
fragment = new CommunityFragment();
break;
case 4:
fragment = new PagesFragment();
break;
case 5:
fragment = new WhatsHotFragment();
break;
default:
break;
}
if (fragment != null) {
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.frame_container, fragment).commit();
// update selected item and title, then close the drawer
mDrawerList.setItemChecked(position, true);
mDrawerList.setSelection(position);
setTitle(navMenuTitles[position]);
mDrawerLayout.closeDrawer(mDrawerList);
} else {
// error in creating fragment
Log.e("MainActivity", "Error in creating fragment");
}
}
#Override
public void setTitle(CharSequence title) {
mTitle = title;
getActionBar().setTitle(mTitle);
}
/**
* 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);
}
}
One of my fragments -
public class HomeFragment extends Fragment {
public HomeFragment(){}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
Intent intent = new Intent();
intent.setClass(getActivity(), HomePage.class);
startActivity(intent);
View rootView = inflater.inflate(R.layout.activity_main, container, false);
return rootView;
}
HomePage Activity which I want to call when item on navigation drawer is clicked :
public class HomePage extends MainActivity {
private static final String TAG = MainActivity.class.getSimpleName();
private ListView listView;
private FeedListAdapter listAdapter;
private List<FeedItem> feedItems;
private String URL_FEED = "https://gist.githubusercontent.com/anonymous/e6c3336c57bf40c794ab/raw/022058ac0ceafd15bfed89a72e6b741dd84da130/blob.json";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_home);
listView = (ListView) findViewById(R.id.list);
feedItems = new ArrayList<FeedItem>();
listAdapter = new FeedListAdapter(this, feedItems);
listView.setAdapter(listAdapter);
// These two lines not needed,
// just to get the look of facebook (changing background color & hiding the icon)
getActionBar().setBackgroundDrawable(new ColorDrawable(Color.parseColor("#EF7B00")));
// getActionBar().setIcon(
// new ColorDrawable(getResources().getColor(android.R.color.transparent)));
// We first check for cached request
Cache cache = AppController.getInstance().getRequestQueue().getCache();
Entry entry = cache.get(URL_FEED);
if (entry != null) {
// fetch the data from cache
try {
String data = new String(entry.data, "UTF-8");
try {
parseJsonFeed(new JSONObject(data));
} catch (JSONException e) {
e.printStackTrace();
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
} else {
// making fresh volley request and getting json
JsonObjectRequest jsonReq = new JsonObjectRequest(Method.GET,
URL_FEED, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
VolleyLog.d(TAG, "Response: " + response.toString());
if (response != null) {
parseJsonFeed(response);
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
}
});
// Adding request to volley request queue
AppController.getInstance().addToRequestQueue(jsonReq);
}
}
/**
* Parsing json reponse and passing the data to feed view list adapter
* */
private void parseJsonFeed(JSONObject response) {
try {
JSONArray feedArray = response.getJSONArray("feed");
for (int i = 0; i < feedArray.length(); i++) {
JSONObject feedObj = (JSONObject) feedArray.get(i);
FeedItem item = new FeedItem();
item.setId(feedObj.getInt("id"));
item.setName(feedObj.getString("name"));
// Image might be null sometimes
String image = feedObj.isNull("image") ? null : feedObj
.getString("image");
item.setImge(image);
item.setStatus(feedObj.getString("status"));
item.setProfilePic(feedObj.getString("profilePic"));
item.setTimeStamp(feedObj.getString("timeStamp"));
// url might be null sometimes
String feedUrl = feedObj.isNull("url") ? null : feedObj
.getString("url");
item.setUrl(feedUrl);
feedItems.add(item);
}
// notify data changes to list adapater
listAdapter.notifyDataSetChanged();
} catch (JSONException e) {
e.printStackTrace();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
XML for the drawer:
<android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<!-- Framelayout to display Fragments -->
<FrameLayout
android:id="#+id/frame_container"
android:layout_width="match_parent"
android:layout_height="match_parent">
</FrameLayout>
<!-- Listview to display slider menu -->
<ListView
android:id="#+id/list_slidermenu"
android:layout_width="240dp"
android:layout_height="match_parent"
android:layout_gravity="start"
android:background="#color/list_background"
android:choiceMode="singleChoice"
android:divider="#color/list_divider"
android:dividerHeight="1dp"
android:listSelector="#drawable/list_selector" />
</android.support.v4.widget.DrawerLayout>
And Finally XML for the activity which I want to be called -
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ListView
android:id="#+id/list"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:divider="#null" />
</LinearLayout>
The API for starting an Activity does not change when using a navigation drawer. You still only need to call startActivity() to launch a different Activity.
In this case, your code will look something like this:
private void displayView(int position) {
// update the main content by replacing fragments
Fragment fragment = null;
switch (position) {
case 0: // Or whatever nav item position should start the Activity
startActivity(new Intent(this, HomePage.class));
return;
// The rest of your cases
}
Note that when after calling startActivity() for the homepage item, we return instead of break so that your displayView() doesn't try to replace the displayed Fragment.
Im new to the ActionBarCompat library.I want to develop an app which contains multiple fragments. Here is what i want to do
1.How to open a fragment when user select that from Navigation Drawer.
2.How to set a startup fragment which displays startup layout (example- In Google plus app,first its displays news feeds.when we select profile item from the side menu,then its hide the side menu/Navigation drawer and displays the profile layout)
Currently i have side menu and one fragment.
Here is the tutorial that i used to follow- wptrafficanalyzer
If you are going to use a slide out menu I recommend you use this slidemenu library I use it in my applications and it allows you to place whatever you want in the slide out menu, the menu is just a frame layout and you can put whatever you want in it (Listview, GridView, or even just a picture)
I am assuming by side menu you meant Navigation Drawer. You can find an answer in the below link.
Navigation Drawer with backword compatibility android
Do read
http://developer.android.com/design/patterns/navigation-drawer.html
Fragment is hosted by a Activity. So you need a container in the activity layout.
<android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<FrameLayout // container to which you add or replace fragments
android:id="#+id/content_frame"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
<ListView
android:layout_width="240dp"
android:layout_height="match_parent"
android:layout_gravity="start"
android:background="#111"
android:choiceMode="singleChoice"
android:divider="#android:color/transparent"
android:dividerHeight="0dp"/>
</android.support.v4.widget.DrawerLayout>
Initially you don't click any item. So initially add fragment1 to the container.
FragmentTransaction fragTran = getSupportFragmentManager()
.beginTransaction();
Fragment fragment1= new Fragment1();
fragTran.add(R.id.content_frame, fragment1);
fragTran.commit();
On click of listitem based on the position
FragmentTransaction fragTran = getSupportFragmentManager()
.beginTransaction();
Fragment fragment3= new Fragment3();
fragTran.replace(R.id.content_frame, fragment3);
fragTran.commit();
Hi check this code
public class MainActivity extends ActionBarActivity implements
OnItemClickListener {
DrawerLayout options_drawer;
FrameLayout main_frame;
ListView slider_list;
ActionBar action;
ActionBarDrawerToggle toggler;
BluetoothAdapter blue_adapter;
String options[] = { "Chat", "Device List", "Settings", "Emojis",
"Terms&Conditions" };
Fragment f;
private static final int REQUEST_ENABLE_BT = 3;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// supportRequestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
setContentView(R.layout.activity_main);
// setSupportProgressBarIndeterminateVisibility(true);
action = getSupportActionBar();
action.setHomeButtonEnabled(true);
action.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
options_drawer = (DrawerLayout) findViewById(R.id.drawer);
main_frame = (FrameLayout) findViewById(R.id.main_frame);
slider_list = (ListView) findViewById(R.id.slider_list);
blue_adapter = BluetoothAdapter.getDefaultAdapter();
if (blue_adapter == null) {
Toast.makeText(getApplicationContext(),
"NO BLUETOOTH DEVICE FOUND", Toast.LENGTH_LONG).show();
finish();
}
ArrayAdapter<String> al = new ArrayAdapter<String>(
getApplicationContext(), R.layout.option_text, options);
slider_list.setAdapter(al);
slider_list.setOnItemClickListener(this);
/*
* toggler=new ActionBarDrawerToggle(MainActivity.this,
* options_drawer,R.
* drawable.ic_launcher,R.string.app_name,R.string.app_name){
*
* #Override public void onDrawerOpened(View drawerView) { // TODO
* Auto-generated method stub super.onDrawerOpened(drawerView);
* options_drawer.openDrawer(slider_list); }
*
* };
*/
// options_drawer.setDrawerListener(toggler);
if (savedInstanceState == null) {
f = new chat_fragment();
fragmentTransition(f);
}
}
#Override
public void onStart() {
super.onStart();
// If BT is not on, request that it be enabled.
// setupChat() will then be called during onActivityResult
if (!blue_adapter.isEnabled()) {
Intent enableIntent = new Intent(
BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableIntent, REQUEST_ENABLE_BT);
// Otherwise, setup the chat session
}
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// TODO Auto-generated method stub
if (item.getItemId() == android.R.id.home) {
// If the drawer is open, close it; vice versa
if (options_drawer.isDrawerOpen(slider_list)) {
options_drawer.closeDrawer(slider_list);
} else {
options_drawer.openDrawer(slider_list);
}
}
return super.onOptionsItemSelected(item);
}
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position,
long arg3) {
// TODO Auto-generated method stub
options_drawer.closeDrawer(slider_list);
switch (position) {
case 0:
f = new chat_fragment();
fragmentTransition(f);
break;
case 1:
f = new device_list_fragment();
fragmentTransition(f);
break;
}
}
private void fragmentTransition(Fragment f2) {
// TODO Auto-generated method stub
FragmentTransaction fx = getSupportFragmentManager().beginTransaction();
fx.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
fx.replace(R.id.main_frame, f2).commit();
}
}
And XML file is
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/drawer"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity" >
<FrameLayout
android:id="#+id/main_frame"
android:layout_width="match_parent"
android:layout_height="match_parent" >
</FrameLayout>
<ListView
android:id="#+id/slider_list"
android:layout_width="fill_parent"
android:layout_height="match_parent"
android:layout_gravity="start"
android:background="#ffffff" >
</ListView>
try this link
http://www.androidhive.info/2013/11/android-sliding-menu-using-navigation-drawer/
android actionbarcompat is supported library for below android versions.In this you should do some modifications in code.I am giving some sample code with supported library
code:
public class SliderScreen extends ActionBarActivity {
private DrawerLayout mDrawerLayout;
private ListView mDrawerList;
private ActionBarDrawerToggle mDrawerToggle;
int checkboxValue=0;
// nav drawer title
private CharSequence mDrawerTitle;
private int selectedPosition=0;
private int currentpos=0;
// used to store app title
private CharSequence mTitle;
ProgressDialog progress_dialog;
// slide menu items
private String[] navMenuTitles;
private TypedArray navMenuIcons;
public static String letter = "";
private ArrayList<NavDrawerItem> navDrawerItems;
private NavDrawerListAdapter adapter;
ActionBarActivity activity;
MDatabase mdatabaseHelper;
String contact_id = "";
Cursor contactsCursor = null, databaseCursor = null,
messageDatabaseCursor = null,imageDatabaseCursor=null;
String contactCursorValue = "0";
int contactCursorRead = 0, messageCursorRead = 0,imageCursorRead=0;
int messageProgressValue = 0, contactProgressValue = 0,imageProgressValue=0;
AlertDialog d;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.slide_screen);
mTitle = mDrawerTitle = getTitle();
// activity=(ActionBarActivity) Context.getApplicationContext();
// load slide menu items
navMenuTitles = getResources().getStringArray(R.array.nav_drawer_items);
// nav drawer icons from resources
navMenuIcons = getResources()
.obtainTypedArray(R.array.nav_drawer_icons);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerList = (ListView) findViewById(R.id.list_slidermenu);
progress_dialog = new ProgressDialog(SliderScreen.this);
progress_dialog.setMessage("please wait ");
Builder build=new Builder(SliderScreen.this);
build.setTitle("");
build.setMessage("Do you want to signout ? ");
build.setPositiveButton("Yes",new OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
finish();
}
});
build.setNegativeButton("No",new OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
d.dismiss();
}
});
d=build.create();
// Database retrieval
mdatabaseHelper = new MDatabase(SliderScreen.this, null, null, 1);
mdatabaseHelper.getWritableDatabase();
navDrawerItems = new ArrayList<NavDrawerItem>();
// adding nav drawer items to array
// Home
navDrawerItems.add(new NavDrawerItem(navMenuTitles[0], navMenuIcons
.getResourceId(0, -1)));
// Find People
navDrawerItems.add(new NavDrawerItem(navMenuTitles[1], navMenuIcons
.getResourceId(1, -1), true, 0));
navDrawerItems.add(new NavDrawerItem(navMenuTitles[2], navMenuIcons
.getResourceId(2, -1), true, 0));
// Photos
navDrawerItems.add(new NavDrawerItem(navMenuTitles[3], navMenuIcons
.getResourceId(3, -1), true,0));
// Communities, Will add a counter here
navDrawerItems.add(new NavDrawerItem(navMenuTitles[4], navMenuIcons
.getResourceId(4, -1), true, getMusicFilesCount()));
// Pages
navDrawerItems.add(new NavDrawerItem(navMenuTitles[5], navMenuIcons
.getResourceId(5, -1)));
// What's hot, We will add a counter here
// Recycle the typed array
navMenuIcons.recycle();
mDrawerList.setOnItemClickListener(new SlideMenuClickListener());
// setting the nav drawer list adapter
adapter = new NavDrawerListAdapter(getApplicationContext(),
navDrawerItems);
mDrawerList.setAdapter(adapter);
// enabling action bar app icon and behaving it as toggle button
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,
R.drawable.listbulletes, // nav menu toggle icon
0, // nav drawer open - description for accessibility
0 // nav drawer close - description for accessibility
) {
public void onDrawerClosed(View view) {
getSupportActionBar().setTitle(mTitle);
if(currentpos!=selectedPosition)
{
currentpos=selectedPosition;
displayView(selectedPosition);
}
}
public void onDrawerOpened(View drawerView) {
getSupportActionBar().setTitle(mDrawerTitle);
// calling onPrepareOptionsMenu() to hide action bar icons
// ActivityCompat.invalidateOptionsMenu(getParent());
// invalidateOptionsMenu();
}
};
mDrawerLayout.setDrawerListener(mDrawerToggle);
if (savedInstanceState == null) {
// on first time display view for first nav item
displayView(1);
}
}
}
/**
* Slide menu item click listener
* */
private class SlideMenuClickListener implements
ListView.OnItemClickListener {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
if(currentpos!=position)
{
Fragment fragment=new DefaultFragment();
if (fragment != null) {
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.frame_container, fragment).commit();
// update selected item and title, then close the drawer
setTitle(" ");
} else {
// error in creating fragment
Log.e("MainActivity", "Error in creating fragment");
}
}
selectedPosition=position;
mDrawerLayout.closeDrawer(mDrawerList);
/*
// display view for selected nav drawer item
if(selectedPosition==position)
{
mDrawerLayout.closeDrawer(mDrawerList);
}
else
{
displayView(position);
selectedPosition=position;
}
*/}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// toggle nav drawer on selecting action bar app icon/title
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
// Handle action bar actions click
switch (item.getItemId()) {
case R.id.action_settings:
return true;
default:
return super.onOptionsItemSelected(item);
}
}
/* *
* Called when invalidateOptionsMenu() is triggered
*/
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
// if nav drawer is opened, hide the action items
boolean drawerOpen = mDrawerLayout.isDrawerOpen(mDrawerList);
menu.findItem(R.id.action_settings).setVisible(!drawerOpen);
return super.onPrepareOptionsMenu(menu);
}
/**
* Diplaying fragment view for selected nav drawer list item
* */
private void displayView(int position) {
// update the main content by replacing fragments
Fragment fragment = null;
switch (position) {
case 0:
fragment = new HomeFragment();
break;
case 1:
fragment = new ContactsFragment();
break;
case 2:
fragment = new MessagesFragment();
break;
case 3:
fragment = new ImageFragment();
break;
case 4:
fragment = new MusicFragment();
break;
case 5:
fragment = new SettingsFragment();
break;
default:
break;
}
if (fragment != null) {
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.frame_container, fragment).commit();
// update selected item and title, then close the drawer
mDrawerList.setItemChecked(position, true);
mDrawerList.setSelection(position);
setTitle(navMenuTitles[position]);
mDrawerLayout.closeDrawer(mDrawerList);
} else {
// error in creating fragment
Log.e("MainActivity", "Error in creating fragment");
}
}
private void showProgressDialog() {
progress_dialog.show();
}
#Override
public void setTitle(CharSequence title) {
mTitle = title;
getSupportActionBar().setTitle(mTitle);
}
/**
* 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);
}
}