Intent And Context crashing app without start - android

I need a lot of help to make the Android APP main page stop giving problem
MainActivity.java
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.pm.ActivityInfo;
import android.content.res.Resources;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.annotation.NonNull;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import com.android.vending.billing.IabBroadcastReceiver;
import com.android.vending.billing.IabHelper;
import com.android.vending.billing.IabResult;
import com.android.vending.billing.Inventory;
import com.android.vending.billing.Purchase;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdView;
import com.google.firebase.messaging.FirebaseMessaging;
import com.mikepenz.fontawesome_typeface_library.FontAwesome;
import com.mikepenz.materialdrawer.Drawer;
import com.mikepenz.materialdrawer.DrawerBuilder;
import com.mikepenz.materialdrawer.model.DividerDrawerItem;
import com.mikepenz.materialdrawer.model.PrimaryDrawerItem;
import com.mikepenz.materialdrawer.model.SecondaryDrawerItem;
import com.mikepenz.materialdrawer.model.SectionDrawerItem;
import com.mikepenz.materialdrawer.model.interfaces.IDrawerItem;
import com.riipo.helpers.AdvertHelper;
import com.riipo.helpers.BillingHelper;
import java.util.ArrayList;
import java.util.List;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import com.riipo.helpers.LocaleHelper;
import static com.riipo.gt.Configurations.PUBLIC_KEY;
import static com.riipo.gt.Configurations.TEST_DEVICES;
/**
* This is the first Activity shown.
* <p>
* Handles the generation of the side navigation drawer, shows the main fragment and shows ads if enabled
*/
public class MainActivity extends AppCompatActivity implements IabBroadcastReceiver.IabBroadcastListener {
#BindView(R.id.toESButton)
Button mtoESButton;
#BindView(R.id.toENButton)
Button mToENButton;
Toolbar toolbar;
Drawer drawer;
Context context;
AppCompatActivity activity;
//ad related
AdView ad;
LinearLayout BackgroundLayout;
AdvertHelper advertHelper;
int ad_counter = 0;
//Analytics
//AnalyticsHelper analyticsHelper;
//billing
BillingHelper billingHelper;
//navigation drawer item identification numbers
final int NAV_HOME = 0, NAV_BOOKMARKED = 1, NAV_MORE = 3, NAV_INFO = 4, NAV_PREMIUM = 5, NAVSETTINGS = 6, NAV_NEWS = 7, NAV_PROFILE = 8, NAV_LOGOUT = 9, NAV_CATEGORIES = 100, NAV_POLICY = 10, NAV_TERMS = 11;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButterKnife.bind(this);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButterKnife.bind(this);
}
#Override
protected void attachBaseContext(Context base) {
super.attachBaseContext(LocaleHelper.onAttach(base));
}
#OnClick(R.id.toESButton)
public void onChangeToTRClicked() {
updateViews("es");
}
#OnClick(R.id.toENButton)
public void onChangeToENClicked() {
updateViews("en");
}
private void updateViews(String languageCode) {
Context context = LocaleHelper.setLocale(this, languageCode);
Resources resources = context.getResources();
mtoESButton.setText(resources.getString(R.string.main_activity_to_es_button));
mToENButton.setText(resources.getString(R.string.main_activity_to_en_button));
// Configuration configuration = getResources().getConfiguration();
// configuration.setLayoutDirection(new Locale("fa"));
// configuration.setLocale(new Locale("fa"));
// getResources().updateConfiguration(configuration, getResources().getDisplayMetrics());
setContentView(R.layout.activity_main);
activity = this;
this.context = this;
//portrait only
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
//enable/disable Firebase topic subscription
SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(this);
if (sharedPref.getBoolean("pref_enable_push_notifications", true))
FirebaseMessaging.getInstance().subscribeToTopic(Configurations.FIREBASE_PUSH_NOTIFICATION_TOPIC);
else
FirebaseMessaging.getInstance().unsubscribeFromTopic(Configurations.FIREBASE_PUSH_NOTIFICATION_TOPIC);
//set toolbar
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
toolbar.setTitle(getResources().getString(R.string.app_name));
//Generate the side navigation drawer
drawer = new DrawerBuilder()
.withActivity(this)
.withToolbar(toolbar)
.withRootView(R.id.drawer_container)
//.withDisplayBelowStatusBar(true)
.withActionBarDrawerToggle(true)
.withActionBarDrawerToggleAnimated(true)
.addDrawerItems(getDrawerItems(null))
.withOnDrawerItemClickListener(new Drawer.OnDrawerItemClickListener() {
#Override
public boolean onItemClick(View view, int position, IDrawerItem drawerItem) {
//On click: open the required activity or fragment
Intent intent;
switch ((int) drawerItem.getIdentifier()) {
case NAV_HOME:
Fragment feed = new SearchFragment();
Bundle bdl = new Bundle(1);
feed.setArguments(bdl);
changeFragment(feed);
break;
case NAV_MORE:
changeFragment(new CategoryFragment());
break;
case NAV_BOOKMARKED:
changeFragment(new BookmarkFragment());
break;
case NAV_INFO:
changeFragment(new InfoFragment());
break;
case NAV_PREMIUM:
intent = new Intent(context, PremiumActivity.class);
startActivity(intent);
break;
case NAVSETTINGS:
intent = new Intent(context, SettingsActivity.class);
startActivity(intent);
break;
case NAV_NEWS:
Fragment news = new NewsFragment();
Bundle bd2 = new Bundle(1);
bd2.putInt(NewsFragment.MODE_KEY, NewsFragment.RECENT);
news.setArguments(bd2);
changeFragment(news);
break;
case NAV_PROFILE:
if (User.isUserLoggedInElseTry(activity)) {
intent = new Intent(context, ProfileActivity.class);
startActivity(intent);
}
break;
case NAV_LOGOUT:
User.logout(context);
break;
case NAV_POLICY:
intent = new Intent(context, PolicyActivity.class);
startActivity(intent);
break;
case NAV_TERMS:
intent = new Intent(context, TermsActivity.class);
startActivity(intent);
break;
default:
//opens the categories displayed in drawer
if (drawerItem.getIdentifier() > NAV_CATEGORIES) {
Bundle b = new Bundle();
b.putInt("Category_id", (int) (drawerItem.getIdentifier() - NAV_CATEGORIES));
Fragment f = new PlacesInCategoryFragment();
f.setArguments(b);
changeFragment(f);
}
}
drawer.closeDrawer();
return true;
}
})
.build();
//initialise analytics
//analyticsHelper = new AnalyticsHelper(this);
//analyticsHelper.initialiseAnalytics(getResources().getString(R.string.google_analytics_id));
//add Google Analytics view
//analyticsHelper.AnalyticsView();
//initialise billing
billingHelper = new BillingHelper(this,
new BillingHelper.RefreshListener() {
#Override
public void onRefresh(boolean isPremium, Inventory inventory) {
if (isPremium) {
//destroy banner ad
if (ad != null)
ad.destroy();
if (BackgroundLayout != null)
BackgroundLayout.removeView(ad);
//remove upgrade 'Go premium' from drawer
drawer.removeItem(NAV_PREMIUM);
//remove purchase
invalidateOptionsMenu();
}
}
},
new IabHelper.OnIabPurchaseFinishedListener() {
public void onIabPurchaseFinished(IabResult result, Purchase purchase) {
System.out.println("Purchase successful " + result);
}
},
new IabHelper.OnConsumeFinishedListener() {
public void onConsumeFinished(Purchase purchase, IabResult result) {
}
}, PUBLIC_KEY);
// Important: Dynamically register for broadcast messages about updated purchases.
// We register the receiver here instead of as a <receiver> in the Manifest
// because we always call getPurchases() at startup, so therefore we can ignore
// any broadcasts sent while the app isn't running.
// Note: registering this listener in an Activity is a bad idea, but is done here
// because this is a SAMPLE. Regardless, the receiver must be registered after
// IabHelper is setup, but before first call to getPurchases().
billingHelper.mBroadcastReceiver = new IabBroadcastReceiver(MainActivity.this);
IntentFilter broadcastFilter = new IntentFilter(IabBroadcastReceiver.ACTION);
registerReceiver(billingHelper.mBroadcastReceiver, broadcastFilter);
//Admob Banner and Interstitial Advert
BackgroundLayout = (LinearLayout) findViewById(R.id.background_layout);
ad = (AdView) findViewById(R.id.adView);
if (!BillingHelper.isPremium(context)) {
advertHelper = new AdvertHelper(this, getResources().getString(R.string.interstitial_ad), null);
advertHelper.initialiseInterstitialAd(TEST_DEVICES);
AdRequest.Builder builder = new AdRequest.Builder().addTestDevice(AdRequest.DEVICE_ID_EMULATOR);
for (int i = 0; i < TEST_DEVICES.length; i++) {
builder.addTestDevice(TEST_DEVICES[i]);
}
final AdRequest adRequest = builder.build();
if (getResources().getString(R.string.banner_ad).length() > 1) {
ad.loadAd(adRequest);
} else {
if (ad != null)
ad.destroy();
if (BackgroundLayout != null)
BackgroundLayout.removeView(ad);
}
} else {
//destroy banner ad
if (ad != null)
ad.destroy();
if (BackgroundLayout != null)
BackgroundLayout.removeView(ad);
}
//load categories for side menu
Category.loadCategories(context, "", new Category.onCategoriesDownloadedListener() {
#Override
public void onCategoriesDownloaded(List<Category> categories) {
refreshNavDrawer(categories);
}
});
//load showauthorname
Preference.load(context, "showauthorname", new Preference.onPreferenceDownloadedListener() {
#Override
public void onPreferenceDownloaded(String value) {
//just load it. It is now cached
}
});
//load showfeatureimage
Preference.load(context, "showfeatureimage", new Preference.onPreferenceDownloadedListener() {
#Override
public void onPreferenceDownloaded(String value) {
//just load it. It is now cached
}
});
}
/**
* Removes all items from drawer and creates them again to refresh.
*
* #param categories - List of Categories
*/
public void refreshNavDrawer(List<Category> categories) {
drawer.removeAllItems();
drawer.addItems(getDrawerItems(categories));
}
/**
* Generates a list of Drawer items
*
* #param categories
* #return
*/
public IDrawerItem[] getDrawerItems(List<Category> categories) {
List<IDrawerItem> drawerItems = new ArrayList<>();
//TODO: You can change the order of the items in the Side Navigation Bar from here
//Add Home, Top Stories and Bookmarks
drawerItems.add(new PrimaryDrawerItem().withIdentifier(NAV_HOME).withName(R.string.nav_all_places).withIcon(FontAwesome.Icon.faw_map_marker));
if (Configurations.ENABLE_NEWS)
drawerItems.add(new SecondaryDrawerItem().withIdentifier(NAV_NEWS).withName(R.string.nav_news).withIcon(FontAwesome.Icon.faw_newspaper_o));
drawerItems.add(new SecondaryDrawerItem().withIdentifier(NAV_BOOKMARKED).withName(R.string.nav_bookmarks).withIcon(FontAwesome.Icon.faw_bookmark_o));
//Topics
if (Configurations.DISPLAY_CATEGORIES_IN_NAVIGATION_DRAWER) {
//Add categories and more...
drawerItems.add(new SectionDrawerItem().withName(R.string.nav_categories));
if (categories != null) {
for (int i = 0; i < categories.size(); i++) {
if (i < Configurations.CATEGORIES_TO_SHOW_IN_NAVIGATION_DRAWER) {
SecondaryDrawerItem temp = new SecondaryDrawerItem().withIdentifier(NAV_CATEGORIES + categories.get(i).id).withName(categories.get(i).name);
drawerItems.add(temp);
if (Configurations.SHOW_CATEGORIES_ICONS) {
if (categories.get(i).icon.length() > 3) {
String iconName = categories.get(i).icon.substring(3, categories.get(i).icon.length());
String iconNameUnderscore = iconName.replaceAll("-", "_");
String icon = "faw_" + iconNameUnderscore;
temp.withIcon(FontAwesome.Icon.valueOf(icon));
}
}
}
}
}
if (Configurations.SHOW_CATEGORIES_ICONS)
drawerItems.add(new SecondaryDrawerItem().withIdentifier(NAV_MORE).withName(R.string.nav_categories_more).withIcon(FontAwesome.Icon.faw_ellipsis_h));
else
drawerItems.add(new SecondaryDrawerItem().withIdentifier(NAV_MORE).withName(R.string.nav_categories_more));
drawerItems.add(new DividerDrawerItem());
} else {
//add just a categories button
drawerItems.add(new SecondaryDrawerItem().withIdentifier(NAV_MORE).withName(R.string.nav_categories).withIcon(FontAwesome.Icon.faw_bars));
}
//add final 4 items
if (Configurations.ENABLE_USER_SYSTEM)
drawerItems.add(new SecondaryDrawerItem().withIdentifier(NAV_PROFILE).withName(R.string.profile_title).withIcon(FontAwesome.Icon.faw_user));
drawerItems.add(new SecondaryDrawerItem().withIdentifier(NAV_INFO).withName(R.string.nav_info).withIcon(FontAwesome.Icon.faw_question));
if (Configurations.PUBLIC_KEY.length() > 0) {
if (!BillingHelper.isPremium(context))
drawerItems.add(new SecondaryDrawerItem().withIdentifier(NAV_PREMIUM).withName(R.string.nav_go_premium).withIcon(FontAwesome.Icon.faw_money));
}
drawerItems.add(new SecondaryDrawerItem().withIdentifier(NAVSETTINGS).withName(R.string.nav_settings).withIcon(FontAwesome.Icon.faw_cog));
if (Configurations.ENABLE_USER_SYSTEM){
if(User.isUserLoggedIn(activity))
drawerItems.add(new SecondaryDrawerItem().withIdentifier(NAV_LOGOUT).withName(R.string.nav_logout).withIcon(FontAwesome.Icon.faw_sign_out));
}
drawerItems.add(new SecondaryDrawerItem().withIdentifier(NAV_TERMS).withName(R.string.terms).withIcon(FontAwesome.Icon.faw_file_o));
drawerItems.add(new SecondaryDrawerItem().withIdentifier(NAV_POLICY).withName(R.string.privacy).withIcon(FontAwesome.Icon.faw_info));
return drawerItems.toArray(new IDrawerItem[0]);
}
/**
* Open interstitial Ad every couple of times. The number of clicks can be set from strings.xml
* Doesn't display ads in premium mode.
*
* #return
*/
public boolean loadInterstitial() {
if (!billingHelper.isPremium(context)) {
ad_counter++;
if (ad_counter >= getResources().getInteger(R.integer.ad_shows_after_X_clicks)) {
advertHelper.openInterstitialAd(new AdvertHelper.InterstitialListener() {
#Override
public void onClosed() {
}
#Override
public void onNotLoaded() {
}
});
ad_counter = 0;
return true;
}
}
return false;
}
/**
* Change main fragment
*
* #param fragment
*/
public void changeFragment(Fragment fragment) {
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.mainFragment, fragment);
transaction.commit();
activity.invalidateOptionsMenu();
}
/**
* On back pressed, always go to home fragment before closing
*/
#Override
public void onBackPressed() {
//if stack has items left
if (getSupportFragmentManager().getBackStackEntryCount() == 0) {
//get current fragment
Fragment fragment = getSupportFragmentManager().findFragmentById(R.id.mainFragment);
//only close if in CategoryFragment else go to CategoryFragment
if (fragment instanceof SearchFragment) {
finish();
} else {
changeFragment(new SearchFragment());
}
} else {
super.onBackPressed();
}
}
/**
* Broadcast receiver for billing
*/
#Override
public void receivedBroadcast() {
billingHelper.receivedBroadcast();
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
//back from billing
if (billingHelper.onActivityResult(requestCode, resultCode, data)) {
}
List<Fragment> fragments = getSupportFragmentManager().getFragments();
if (fragments != null) {
for (Fragment fragment : fragments) {
if (fragment != null) {
fragment.onActivityResult(requestCode, resultCode, data);
}
}
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grants) {
List<Fragment> fragments = getSupportFragmentManager().getFragments();
if (fragments != null) {
for (Fragment fragment : fragments) {
if (fragment != null) {
fragment.onRequestPermissionsResult(requestCode, permissions, grants);
}
}
}
}
#Override
public void onStart() {
super.onStart();
//analytics
//analyticsHelper.onStart();
}
#Override
public void onPause() {
if (advertHelper != null)
advertHelper.onPause();
super.onPause();
}
#Override
public void onResume() {
super.onResume();
if (advertHelper != null)
advertHelper.onResume();
if (billingHelper != null)
billingHelper.refreshInventory();
}
#Override
public void onDestroy() {
if (advertHelper != null)
advertHelper.onDestroy();
super.onDestroy();
if (billingHelper.mBroadcastReceiver != null) {
unregisterReceiver(billingHelper.mBroadcastReceiver);
}
if (billingHelper != null)
billingHelper.onDestroy();
}
#Override
protected void onStop() {
super.onStop();
//analytics
// analyticsHelper.onStop();
}
}
this is a code xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true">
<!-- Toolbar is the actual app bar with text and the action items -->
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
android:minHeight="?attr/actionBarSize"
app:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar" />
<LinearLayout
android:id="#+id/drawer_container"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="#id/toolbar"
android:orientation="vertical">
<LinearLayout
android:id="#+id/background_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<fragment
android:id="#+id/mainFragment"
class="com.riipo.gt.SearchFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1" />
<com.google.android.gms.ads.AdView xmlns:ads="http://schemas.android.com/apk/res-auto"
android:id="#+id/adView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="0"
android:gravity="center_horizontal"
ads:adSize="SMART_BANNER"
ads:adUnitId="#string/banner_ad" />
</LinearLayout>
</LinearLayout>
</RelativeLayout>
I'm trying to turn the tourism app into multi language plus it's being more complicated than I imagined
With this error, even if I can generate the build the program hangs as soon as it enters the main page, I am not able to put the translations

Related

whenever i run the app on emulator it says unfortunately the app has stopped working and the log reads the below lines

The MainActivity file
package com.example.intel.dualboot;
import android.annotation.TargetApi;
import android.app.AlertDialog;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Configuration;
import android.os.Build;
import android.preference.PreferenceManager;
import android.support.v4.widget.DrawerLayout;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.ActionBar;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.SpannableString;
import android.text.method.LinkMovementMethod;
import android.text.util.Linkify;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity implements StatusAsyncTask.StatusAsyncTaskListener, SwipeRefreshLayout.OnRefreshListener, MainActivityListener {
private static final String TAG = "db::MainActivity";
/* public static final int ACT_INSTALL_ROM = 1;
public static final int ACT_CHANGE_PAGE = 2;
public static final int ACT_SELECT_ICON = 3;
public static final int ACT_UNINSTALL_ROM = 4;
public static final String INTENT_EXTRA_SHOW_ROM_LIST = "show_rom_list";*/
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if(Build.VERSION.SDK_INT == 20) {
showDeprecatedLAlert();
return;
}
setContentView(R.layout.activity_main);
// This activity is using different background color, which would cause overdraw
// of the whole area, so disable the default background
getWindow().setBackgroundDrawable(null);
Utils.installHttpCache(this);
PreferenceManager.setDefaultValues(this, R.xml.settings, false);
m_srLayout = (InSwipeRefreshLayout)findViewById(R.id.refresh_layout);
m_srLayout.setOnRefreshListener(this);
m_curFragment = -1;
m_fragmentTitles = getResources().getStringArray(R.array.main_fragment_titles);
m_drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
m_drawerList = (ListView) findViewById(R.id.left_drawer);
String[] fragmentClsNames = new String[MainFragment.MAIN_FRAG_CNT];
for(int i = 0; i < fragmentClsNames.length; ++i)
fragmentClsNames[i] = MainFragment.getFragmentClass(i).getName();
m_fragments = new MainFragment[MainFragment.MAIN_FRAG_CNT];
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction t = fragmentManager.beginTransaction();
for(int i = 0; i < m_fragments.length; ++i) {
m_fragments[i] = (MainFragment)fragmentManager.findFragmentByTag(fragmentClsNames[i]);
if(m_fragments[i] == null) {
m_fragments[i] = MainFragment.newFragment(i);
t.add(R.id.content_frame, m_fragments[i], fragmentClsNames[i]);
}
t.hide(m_fragments[i]);
}
t.commit();
// Set the adapter for the list view
m_drawerList.setAdapter(new ArrayAdapter<String>(this,
R.layout.drawer_list, m_fragmentTitles));
// Set the list's click listener
m_drawerList.setOnItemClickListener(new DrawerItemClickListener());
m_drawerTitle = getText(R.string.app_name);
m_drawerToggle = new ActionBarDrawerToggle(
this, m_drawerLayout, R.string.drawer_open, R.string.drawer_close) {
public void onDrawerClosed(View view) {
getSupportActionBar().setTitle(m_title);
}
public void onDrawerOpened(View drawerView) {
getSupportActionBar().setTitle(m_drawerTitle);
}
};
m_drawerLayout.setDrawerListener(m_drawerToggle);
final ActionBar bar = getSupportActionBar();
if(bar != null) {
bar.setDisplayHomeAsUpEnabled(true);
bar.setHomeButtonEnabled(true);
}
/* if (getIntent().hasExtra(INTENT_EXTRA_SHOW_ROM_LIST) &&
getIntent().getBooleanExtra(INTENT_EXTRA_SHOW_ROM_LIST, false)) {
getIntent().removeExtra(INTENT_EXTRA_SHOW_ROM_LIST);
selectItem(1);
} else if(savedInstanceState != null) {
selectItem(savedInstanceState.getInt("curFragment", 0));
} else {
selectItem(0);
}*/
}
/*#Override
protected void onNewIntent(Intent i) {
super.onNewIntent(i);
if (i.hasExtra(INTENT_EXTRA_SHOW_ROM_LIST) &&
i.getBooleanExtra(INTENT_EXTRA_SHOW_ROM_LIST, false)) {
selectItem(1);
}
}*/
#Override
protected void onStop() {
super.onStop();
Utils.flushHttpCache();
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt("curFragment", m_curFragment);
}
#Override
public boolean onCreateOptionsMenu (Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
m_refreshItem = menu.findItem(R.id.action_refresh);
if(!StatusAsyncTask.instance().isComplete())
m_refreshItem.setEnabled(false);
return true;
}
private class DrawerItemClickListener implements ListView.OnItemClickListener {
#Override
public void onItemClick(AdapterView parent, View view, int position, long id) {
selectItem(position);
}
}
/** Swaps fragments in the main content view */
private void selectItem(int position) {
if(position < 0 || position >= m_fragments.length) {
Log.e(TAG, "Invalid fragment index " + position);
return;
}
// Insert the fragment by replacing any existing fragment
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction t = fragmentManager.beginTransaction();
if(m_curFragment != -1)
t.hide(m_fragments[m_curFragment]);
t.show(m_fragments[position]);
t.commit();
m_curFragment = position;
// Highlight the selected item, update the title, and close the drawer
m_drawerList.setItemChecked(position, true);
setTitle(m_fragmentTitles[position]);
m_drawerLayout.closeDrawer(m_drawerList);
}
#Override
public void setTitle(CharSequence title) {
m_title = title;
getSupportActionBar().setTitle(m_title);
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
if(m_drawerToggle != null)
m_drawerToggle.syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
if(m_drawerToggle != null)
m_drawerToggle.onConfigurationChanged(newConfig);
}
#Override
public boolean onOptionsItemSelected(MenuItem it) {
if (m_drawerToggle.onOptionsItemSelected(it))
return true;
switch(it.getItemId()) {
case R.id.action_refresh:
refresh(false);
return true;
case R.id.action_reboot:
{
AlertDialog.Builder b = new AlertDialog.Builder(this);
b.setTitle("Reboot")
.setCancelable(true)
.setNegativeButton("Cancel", null)
.setItems(R.array.reboot_options, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
switch (i) {
case 0: Utils.reboot(""); break;
case 1: Utils.reboot("recovery"); break;
case 2: Utils.reboot("bootloader"); break;
}
}
})
.create().show();
return true;
}
default:
return false;
}
}
public void startRefresh(boolean notifyRefreshLayout) {
if(notifyRefreshLayout)
m_srLayout.setRefreshing(true);
if(m_refreshItem != null)
m_refreshItem.setEnabled(false);
for(int i = 0; i < m_fragments.length; ++i)
m_fragments[i].startRefresh();
StatusAsyncTask.instance().setListener(this);
StatusAsyncTask.instance().execute();
}
#Override
public void refresh(boolean b) {
refresh(true);
}
#Override
public void setRefreshComplete() {
m_srLayout.setRefreshing(false);
if(m_refreshItem != null)
m_refreshItem.setEnabled(true);
for(int i = 0; i < m_fragments.length; ++i)
m_fragments[i].setRefreshComplete();
}
#Override
public void onFragmentViewCreated() {
if(++m_fragmentViewsCreated == m_fragments.length) {
// postDelayed because SwipeRefresher view ignores
// setRefreshing call otherwise
m_srLayout.postDelayed(new Runnable() {
#Override
public void run() {
Intent i = getIntent();
if(i == null || !i.getBooleanExtra("force_refresh", false)) {
startRefresh(true);
} else {
i.removeExtra("force_refresh");
refresh(false);
}
}
}, 1);
}
}
#Override
public void onFragmentViewDestroyed() {
--m_fragmentViewsCreated;
}
#Override
public void addScrollUpListener(InSwipeRefreshLayout.ScrollUpListener l) {
m_srLayout.addScrollUpListener(l);
}
#Override
public void onStatusTaskFinished(StatusAsyncTask.Result res) {
for(int i = 0; i < m_fragments.length; ++i)
m_fragments[i].onStatusTaskFinished(res);
}
#Override
public void onRefresh() {
refresh(false);
}
#TargetApi(20)
private void showDeprecatedLAlert() {
SpannableString msg = new SpannableString("Android Developer preview has bugs");
Linkify.addLinks(msg, Linkify.ALL);
AlertDialog.Builder b = new AlertDialog.Builder(this);
b.setTitle("Unsupported Android version")
.setCancelable(false)
.setMessage(msg)
.setNegativeButton("Exit Application", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
finish();
}
});
AlertDialog d = b.create();
d.show();
TextView msgView = (TextView)d.findViewById(android.R.id.message);
msgView.setMovementMethod(LinkMovementMethod.getInstance());
}
private DrawerLayout m_drawerLayout;
private ListView m_drawerList;
private String[] m_fragmentTitles;
private MainFragment[] m_fragments;
private int m_curFragment;
private CharSequence m_title;
private ActionBarDrawerToggle m_drawerToggle;
private CharSequence m_drawerTitle;
private MenuItem m_refreshItem;
private int m_fragmentViewsCreated;
private InSwipeRefreshLayout m_srLayout;
}
I am getting this error
E/AndroidRuntime: FATAL EXCEPTION: main
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.intel.dualboot/com.example.intel.dualboot.MainActivity}: java.lang.ClassCastException: minor_activities.Status cannot be cast to com.example.intel.dualboot.MainFragment
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2306)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2358)
at android.app.ActivityThread.access$600(ActivityThread.java:156)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1340)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:153)
at android.app.ActivityThread.main(ActivityThread.java:5297)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:833)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:600)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.ClassCastException: minor_activities.Status cannot be cast to com.example.intel.dualboot.MainFragment
at com.example.intel.dualboot.MainFragment.newFragment(MainFragment.java:28)
at com.example.intel.dualboot.MainActivity.onCreate(MainActivity.java:77)
at android.app.Activity.performCreate(Activity.java:5122)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1081)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2270)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2358)
at android.app.ActivityThread.access$600(ActivityThread.java:156)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1340)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:153)
at android.app.ActivityThread.main(ActivityThread.java:5297)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
activity_main.xml file
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/drawer_layout">
<com.example.intel.dualboot.InSwipeRefreshLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/refresh_layout"
android:layout_alignParentTop="true"
android:layout_alignParentStart="true">
<FrameLayout android:id="#+id/content_frame"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</com.example.intel.dualboot.InSwipeRefreshLayout>
<ListView android:id="#+id/left_drawer"
android:layout_width="#dimen/lviewdimen"
android:layout_height="match_parent"
android:layout_gravity="start"
android:choiceMode="singleChoice"
android:divider="#android:color/transparent"
android:dividerHeight="0dp"
android:background="#111" />
</android.support.v4.widget.DrawerLayout>
here is your error...
android.support.v4.widget.SwipeRefreshLayout cannot be cast to com.example.intel.dualboot.InSwipeRefreshLayout
You have initialize SwipeToRefresh in XML as "android.support.v4.widget.SwipeRefreshLayout" But you are trying to create object of that view as "com.example.intel.dualboot.InSwipeRefreshLayout". So you got an error because of wrong casting of class. Change "android.support.v4.widget.SwipeRefreshLayout" to "com.example.intel.dualboot.InSwipeRefreshLayout" in xml to solve your problem.

whenever i run the app on emulator it says unfortunately the app has stopped working and the log reads as below

MainActivity.java
package com.example.intel.dualboot;
import android.annotation.TargetApi;
import android.app.AlertDialog;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Configuration;
import android.os.Build;
import android.preference.PreferenceManager;
import android.support.v4.widget.DrawerLayout;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.ActionBar;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.SpannableString;
import android.text.method.LinkMovementMethod;
import android.text.util.Linkify;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity implements StatusAsyncTask.StatusAsyncTaskListener, SwipeRefreshLayout.OnRefreshListener, MainActivityListener {
private static final String TAG = "db::MainActivity";
/* public static final int ACT_INSTALL_ROM = 1;
public static final int ACT_CHANGE_PAGE = 2;
public static final int ACT_SELECT_ICON = 3;
public static final int ACT_UNINSTALL_ROM = 4;
public static final String INTENT_EXTRA_SHOW_ROM_LIST = "show_rom_list";*/
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if(Build.VERSION.SDK_INT == 20) {
showDeprecatedLAlert();
return;
}
setContentView(R.layout.activity_main);
// This activity is using different background color, which would cause overdraw
// of the whole area, so disable the default background
getWindow().setBackgroundDrawable(null);
Utils.installHttpCache(this);
PreferenceManager.setDefaultValues(this, R.xml.settings, false);
m_srLayout = (InSwipeRefreshLayout)findViewById(R.id.refresh_layout);
m_srLayout.setOnRefreshListener(this);
m_curFragment = -1;
m_fragmentTitles = getResources().getStringArray(R.array.main_fragment_titles);
m_drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
m_drawerList = (ListView) findViewById(R.id.left_drawer);
String[] fragmentClsNames = new String[MainFragment.MAIN_FRAG_CNT];
for(int i = 0; i < fragmentClsNames.length; ++i)
fragmentClsNames[i] = MainFragment.getFragmentClass(i).getName();
m_fragments = new MainFragment[MainFragment.MAIN_FRAG_CNT];
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction t = fragmentManager.beginTransaction();
for(int i = 0; i < m_fragments.length; ++i) {
m_fragments[i] = (MainFragment)fragmentManager.findFragmentByTag(fragmentClsNames[i]);
if(m_fragments[i] == null) {
m_fragments[i] = MainFragment.newFragment(i);
t.add(R.id.content_frame, m_fragments[i], fragmentClsNames[i]);
}
t.hide(m_fragments[i]);
}
t.commit();
// Set the adapter for the list view
m_drawerList.setAdapter(new ArrayAdapter<String>(this,
R.layout.drawer_list, m_fragmentTitles));
// Set the list's click listener
m_drawerList.setOnItemClickListener(new DrawerItemClickListener());
m_drawerTitle = getText(R.string.app_name);
m_drawerToggle = new ActionBarDrawerToggle(
this, m_drawerLayout, R.string.drawer_open, R.string.drawer_close) {
public void onDrawerClosed(View view) {
getSupportActionBar().setTitle(m_title);
}
public void onDrawerOpened(View drawerView) {
getSupportActionBar().setTitle(m_drawerTitle);
}
};
m_drawerLayout.setDrawerListener(m_drawerToggle);
final ActionBar bar = getSupportActionBar();
if(bar != null) {
bar.setDisplayHomeAsUpEnabled(true);
bar.setHomeButtonEnabled(true);
}
/* if (getIntent().hasExtra(INTENT_EXTRA_SHOW_ROM_LIST) &&
getIntent().getBooleanExtra(INTENT_EXTRA_SHOW_ROM_LIST, false)) {
getIntent().removeExtra(INTENT_EXTRA_SHOW_ROM_LIST);
selectItem(1);
} else if(savedInstanceState != null) {
selectItem(savedInstanceState.getInt("curFragment", 0));
} else {
selectItem(0);
}*/
}
/*#Override
protected void onNewIntent(Intent i) {
super.onNewIntent(i);
if (i.hasExtra(INTENT_EXTRA_SHOW_ROM_LIST) &&
i.getBooleanExtra(INTENT_EXTRA_SHOW_ROM_LIST, false)) {
selectItem(1);
}
}*/
#Override
protected void onStop() {
super.onStop();
Utils.flushHttpCache();
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt("curFragment", m_curFragment);
}
#Override
public boolean onCreateOptionsMenu (Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
m_refreshItem = menu.findItem(R.id.action_refresh);
if(!StatusAsyncTask.instance().isComplete())
m_refreshItem.setEnabled(false);
return true;
}
private class DrawerItemClickListener implements ListView.OnItemClickListener {
#Override
public void onItemClick(AdapterView parent, View view, int position, long id) {
selectItem(position);
}
}
/** Swaps fragments in the main content view */
private void selectItem(int position) {
if(position < 0 || position >= m_fragments.length) {
Log.e(TAG, "Invalid fragment index " + position);
return;
}
// Insert the fragment by replacing any existing fragment
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction t = fragmentManager.beginTransaction();
if(m_curFragment != -1)
t.hide(m_fragments[m_curFragment]);
t.show(m_fragments[position]);
t.commit();
m_curFragment = position;
// Highlight the selected item, update the title, and close the drawer
m_drawerList.setItemChecked(position, true);
setTitle(m_fragmentTitles[position]);
m_drawerLayout.closeDrawer(m_drawerList);
}
#Override
public void setTitle(CharSequence title) {
m_title = title;
getSupportActionBar().setTitle(m_title);
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
if(m_drawerToggle != null)
m_drawerToggle.syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
if(m_drawerToggle != null)
m_drawerToggle.onConfigurationChanged(newConfig);
}
#Override
public boolean onOptionsItemSelected(MenuItem it) {
if (m_drawerToggle.onOptionsItemSelected(it))
return true;
switch(it.getItemId()) {
case R.id.action_refresh:
refresh(false);
return true;
case R.id.action_reboot:
{
AlertDialog.Builder b = new AlertDialog.Builder(this);
b.setTitle("Reboot")
.setCancelable(true)
.setNegativeButton("Cancel", null)
.setItems(R.array.reboot_options, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
switch (i) {
case 0: Utils.reboot(""); break;
case 1: Utils.reboot("recovery"); break;
case 2: Utils.reboot("bootloader"); break;
}
}
})
.create().show();
return true;
}
default:
return false;
}
}
public void startRefresh(boolean notifyRefreshLayout) {
if(notifyRefreshLayout)
m_srLayout.setRefreshing(true);
if(m_refreshItem != null)
m_refreshItem.setEnabled(false);
for(int i = 0; i < m_fragments.length; ++i)
m_fragments[i].startRefresh();
StatusAsyncTask.instance().setListener(this);
StatusAsyncTask.instance().execute();
}
#Override
public void refresh(boolean b) {
refresh(true);
}
#Override
public void setRefreshComplete() {
m_srLayout.setRefreshing(false);
if(m_refreshItem != null)
m_refreshItem.setEnabled(true);
for(int i = 0; i < m_fragments.length; ++i)
m_fragments[i].setRefreshComplete();
}
#Override
public void onFragmentViewCreated() {
if(++m_fragmentViewsCreated == m_fragments.length) {
// postDelayed because SwipeRefresher view ignores
// setRefreshing call otherwise
m_srLayout.postDelayed(new Runnable() {
#Override
public void run() {
Intent i = getIntent();
if(i == null || !i.getBooleanExtra("force_refresh", false)) {
startRefresh(true);
} else {
i.removeExtra("force_refresh");
refresh(false);
}
}
}, 1);
}
}
#Override
public void onFragmentViewDestroyed() {
--m_fragmentViewsCreated;
}
#Override
public void addScrollUpListener(InSwipeRefreshLayout.ScrollUpListener l) {
m_srLayout.addScrollUpListener(l);
}
#Override
public void onStatusTaskFinished(StatusAsyncTask.Result res) {
for(int i = 0; i < m_fragments.length; ++i)
m_fragments[i].onStatusTaskFinished(res);
}
#Override
public void onRefresh() {
refresh(false);
}
#TargetApi(20)
private void showDeprecatedLAlert() {
SpannableString msg = new SpannableString("Android Developer preview has bugs");
Linkify.addLinks(msg, Linkify.ALL);
AlertDialog.Builder b = new AlertDialog.Builder(this);
b.setTitle("Unsupported Android version")
.setCancelable(false)
.setMessage(msg)
.setNegativeButton("Exit Application", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
finish();
}
});
AlertDialog d = b.create();
d.show();
TextView msgView = (TextView)d.findViewById(android.R.id.message);
msgView.setMovementMethod(LinkMovementMethod.getInstance());
}
private DrawerLayout m_drawerLayout;
private ListView m_drawerList;
private String[] m_fragmentTitles;
private MainFragment[] m_fragments;
private int m_curFragment;
private CharSequence m_title;
private ActionBarDrawerToggle m_drawerToggle;
private CharSequence m_drawerTitle;
private MenuItem m_refreshItem;
private int m_fragmentViewsCreated;
private InSwipeRefreshLayout m_srLayout;
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/drawer_layout">
<com.example.intel.dualboot.InSwipeRefreshLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/refresh_layout"
android:layout_alignParentTop="true"
android:layout_alignParentStart="true">
<FrameLayout android:id="#+id/content_frame"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</com.example.intel.dualboot.InSwipeRefreshLayout>
<ListView android:id="#+id/left_drawer"
android:layout_width="#dimen/lviewdimen"
android:layout_height="match_parent"
android:layout_gravity="start"
android:choiceMode="singleChoice"
android:divider="#android:color/transparent"
android:dividerHeight="0dp"
android:background="#111" />
</android.support.v4.widget.DrawerLayout>
Stack Trace
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.intel.dualboot, PID: 23319
java.lang.RuntimeException: Unable to start activity
ComponentInfo{com.example.intel.dualboot/com.example.intel.dualboot.MainActivity}:
java.lang.NullPointerException: Attempt to write to field
'android.app.FragmentManagerImpl
android.app.Fragment.mFragmentManager' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2330)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2392)
at android.app.ActivityThread.access$800(ActivityThread.java:154)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1308)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5273)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:908)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:703)
Caused by: java.lang.NullPointerException: Attempt to write to field
'android.app.FragmentManagerImpl
android.app.Fragment.mFragmentManager' on a null object reference
at android.app.BackStackRecord.doAddOp(BackStackRecord.java:469)
at android.app.BackStackRecord.add(BackStackRecord.java:464)
at com.example.intel.dualboot.MainActivity.onCreate(MainActivity.java:78)
at android.app.Activity.performCreate(Activity.java:6041)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1109)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2283)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2392) 
at android.app.ActivityThread.access$800(ActivityThread.java:154) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1308) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:135) 
at android.app.ActivityThread.main(ActivityThread.java:5273) 
at java.lang.reflect.Method.invoke(Native Method) 
at java.lang.reflect.Method.invoke(Method.java:372)
replace
com.exmaple.intel.dualboot.InSwipeRefreshLayout
with
android.support.v4.widget.SwipeRefreshLayout
in your xml file,
as the com.exmaple.intel.dualboot.InSwipeRefreshLayout class is not defined
com.exmaple.intel.dualboot.InSwipeRefreshLayout
Check this path if it is correct in your xml.It seems the path of "InSwipeRefreshLayout" is not corect
in your xml
<?xml version="1.0" encoding="utf-8"?><android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/drawer_layout">
<com.exmaple.intel.dualboot.InSwipeRefreshLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/refresh_layout"
android:layout_alignParentTop="true"
android:layout_alignParentStart="true">
<FrameLayout android:id="#+id/content_frame"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</com.exmaple.intel.dualboot.InSwipeRefreshLayout>
<ListView android:id="#+id/left_drawer"
android:layout_width="#dimen/lviewdimen"
android:layout_height="match_parent"
android:layout_gravity="start"
android:choiceMode="singleChoice"
android:divider="#android:color/transparent"
android:dividerHeight="0dp"
android:background="#111" />
</android.support.v4.widget.DrawerLayout>
the com.exmaple.intel.dualboot.InSwipeRefreshLayout has that spelling of "exmaple", it should be example.
The posted layout working fine for me.Please check the package name properly com.example.intel.dualboot.InSwipeRefreshLayout whether exist or not and clean and build the project.

onBackPressed add double tap exit?

i have this code onBackPressed in my MainActivity.java
#Override
public void onBackPressed() {
if (getFragmentManager().getBackStackEntryCount() > 0) {
getFragmentManager().popBackStack();
} else {
super.onBackPressed();
}
}
and I have HomeFragment.java
what I want is when im in the HomeFragment.java..
I want to add a double tap back to exit my application..
How can I do that?
here is my MainActivity.java
package com.example.administrator.mosbeau;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Handler;
import android.provider.Settings;
import android.support.v7.app.ActionBarActivity;
import android.app.Fragment;
import android.app.FragmentManager;
import android.os.Bundle;
import android.util.Base64;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.support.v4.widget.DrawerLayout;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.SearchView;
import android.widget.TextView;
import android.widget.Toast;
import org.json.JSONArray;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import android.content.pm.Signature;
import com.facebook.appevents.AppEventsLogger;
#SuppressWarnings("deprecation")
public class MainActivity extends ActionBarActivity
implements NavigationDrawerFragment.NavigationDrawerCallbacks {
/**
* Fragment managing the behaviors, interactions and presentation of the navigation drawer.
*/
private NavigationDrawerFragment mNavigationDrawerFragment;
/**
* Used to store the last screen title. For use in {#link #//restoreActionBar()}.
*/
private CharSequence mTitle;
UserLocalStore userLocalStore;
String customersid, countrycode, carttotal, stateid;
SearchView searchView;
RelativeLayout notifCount;
TextView tv;
public static final int CONNECTION_TIMEOUT = 1000 * 15;
public static final String SERVER_ADDRESS = "http://shop.mosbeau.com.ph/android/";
String myJSONcarttotal;
JSONArray jsonarraycarttotal;
private static final int TIME_DELAY = 2000;
private static long back_pressed;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Connectivity connectivity=new Connectivity();
if(connectivity.isConnected(MainActivity.this)) {
// Add code to print out the key hash
/*try {
PackageInfo info = getPackageManager().getPackageInfo(
"com.administrator.mosbeau",
PackageManager.GET_SIGNATURES);
for (Signature signature : info.signatures) {
MessageDigest md = MessageDigest.getInstance("SHA");
md.update(signature.toByteArray());
Log.d("KeyHash:", Base64.encodeToString(md.digest(), Base64.DEFAULT));
}
} catch (PackageManager.NameNotFoundException e) {
} catch (NoSuchAlgorithmException e) {
}*/
}else{
nointernet();
}
userLocalStore = new UserLocalStore(this);
mNavigationDrawerFragment = (NavigationDrawerFragment)
getSupportFragmentManager().findFragmentById(R.id.navigation_drawer);
mTitle = getTitle();
// Set up the drawer.
mNavigationDrawerFragment.setUp(
R.id.navigation_drawer,
(DrawerLayout) findViewById(R.id.drawer_layout));
}
public void onStart() {
super.onStart();
if(authenticate() == true){
displayUserDetails();
}else{
Intent myIntent = new Intent(MainActivity.this, IndexActivity.class);
startActivity(myIntent);
}
}
private boolean authenticate() {
if (userLocalStore.getLoggedInUser() == null) {
Intent myIntent = new Intent(MainActivity.this, IndexActivity.class);
startActivity(myIntent);
return false;
}
return true;
}
private void displayUserDetails(){
User user = userLocalStore.getLoggedInUser();
customersid = user.customers_id;
countrycode = user.customers_countryid;
stateid = user.customers_stateid;
if(customersid==""){
Intent myIntent = new Intent(MainActivity.this, IndexActivity.class);
startActivity(myIntent);
}
}
#Override
public void onNavigationDrawerItemSelected(int position,String id,String name,String image2) {
// update the main content by replacing fragments
FragmentManager fragmentManager = getFragmentManager();
// NEW STUFF
if(position == 0){
fragmentManager.beginTransaction()
.replace(R.id.container, HomeFragment.newInstance())
.commit();
}
else if (position == 1){
fragmentManager.beginTransaction()
.replace(R.id.container, CategoryFragment.newInstance(id,name,countrycode,image2,customersid,stateid))
.commit();
}
else if (position == 2){
fragmentManager.beginTransaction()
.replace(R.id.container, AccountFragment.newInstance(customersid))
.commit();
}
else if (position == 3){
fragmentManager.beginTransaction()
.replace(R.id.container, ReferFragment.newInstance(customersid))
.commit();
}
else if (position == 4){
fragmentManager.beginTransaction()
.replace(R.id.container, AboutFragment.newInstance(customersid))
.commit();
}
else if (position == 5){
fragmentManager.beginTransaction()
.replace(R.id.container, PolicyFragment.newInstance(customersid))
.commit();
}
else if (position == 6){
fragmentManager.beginTransaction()
.replace(R.id.container, TermsFragment.newInstance(customersid))
.commit();
}
else if (position == 7){
fragmentManager.beginTransaction()
.replace(R.id.container, ContactusFragment.newInstance(customersid))
.commit();
}
else if (position == 8){
userLocalStore.clearUserData();
userLocalStore.setUserLoggedIn(false);
Intent myIntent = new Intent(this, IndexActivity.class);
startActivity(myIntent);
}
else if (position == 101){
fragmentManager.beginTransaction()
.replace(R.id.container, CartFragment.newInstance(customersid,countrycode,stateid,"a"))
.commit();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
if (!mNavigationDrawerFragment.isDrawerOpen()) {
// Only show items in the action bar relevant to this screen
// if the drawer is not showing. Otherwise, let the drawer
// decide what to show in the action bar.
getMenuInflater().inflate(R.menu.main, menu);
//restoreActionBar();
// HERE RETURNS NULL
searchView = (SearchView) menu.findItem(R.id.action_search).getActionView();
int searchImgId = getResources().getIdentifier("android:id/search_button", null, null);
ImageView v = (ImageView) searchView.findViewById(searchImgId);
v.setImageResource(R.drawable.action_searchm);
if (searchView != null) {
final Menu menu_block = menu;
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
// collapse the view ?
//menu_block.findItem(R.id.action_search).collapseActionView();
SearchFragment searchFragment = SearchFragment.newInstance(query,countrycode,customersid,stateid);
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.container, searchFragment)
.addToBackStack(null)
.commit();
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
// search goes here !!
// listAdapter.getFilter().filter(query);
return false;
}
});
//Log.i("sales module", "SearchView QWE");
}else{
//Log.i("sales module", "SearchView is null");
}
return true;
}
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
/*if (id == R.id.action_settings) {
return true;
}*/
return super.onOptionsItemSelected(item);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
/**
* The fragment argument representing the section number for this
* fragment.
*/
private static final String ARG_SECTION_NUMBER = "section_number";
/**
* Returns a new instance of this fragment for the given section
* number.
*/
public static PlaceholderFragment newInstance(int sectionNumber) {
PlaceholderFragment fragment = new PlaceholderFragment();
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, sectionNumber);
fragment.setArguments(args);
return fragment;
}
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
return rootView;
}
}
/*#Override
public void onBackPressed() {
if (getFragmentManager().getBackStackEntryCount() > 0) {
getFragmentManager().popBackStack();
} else {
super.onBackPressed();
}
}*/
boolean doubleBackToExitPressedOnce = false;
#Override
public void onBackPressed() {
if (getFragmentManager().getBackStackEntryCount() > 0) {
getFragmentManager().popBackStack();
} else {
Fragment fragment = getFragmentManager().findFragmentById(R.id.textHomeBack);
if (fragment instanceof HomeFragment) {
if (doubleBackToExitPressedOnce) {
super.onBackPressed();
return;
}
this.doubleBackToExitPressedOnce = true;
Toast.makeText(this, "Please click BACK again to exit", Toast.LENGTH_SHORT).show();
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
doubleBackToExitPressedOnce = false;
}
}, 2000);
}
else {
super.onBackPressed();
}
}
}
public void nointernet(){
AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this);
dialogBuilder.setMessage("There seems to be a problem with your connection.");
dialogBuilder.setNegativeButton("Edit Settings", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
//Stop the activity
startActivity(new Intent(Settings.ACTION_WIFI_SETTINGS));
}
});
dialogBuilder.setPositiveButton("Reload", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
//Stop the activity
Intent intent = getIntent();
finish();
startActivity(intent);
}
});
AlertDialog dialog = dialogBuilder.show();
TextView messageText = (TextView)dialog.findViewById(android.R.id.message);
messageText.setGravity(Gravity.CENTER);
dialog.setCanceledOnTouchOutside(false);
dialog.setCancelable(false);
dialog.show();
}
}
and here is my homelayout.xml
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:fillViewport="false"
android:background="#fffff1f1">
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="match_parent"
android:background="#fffff1f1"
android:padding="10dp"
android:orientation="horizontal"
android:gravity="center_horizontal">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/textHomeBack"
android:visibility="invisible"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/textCountryId"
android:visibility="invisible"/>
<FrameLayout
android:id="#+id/framelayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:minHeight="200dp">
<ImageView
android:id="#+id/imageView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:adjustViewBounds="true"
android:gravity="center"
android:layout_gravity="center"/>
<ProgressBar
android:id="#+id/loading"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:visibility="gone"
android:layout_gravity="center" />
</FrameLayout>
<FrameLayout
android:id="#+id/framelayout2"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="#+id/framelayout"
android:layout_marginTop="10dp"
android:layout_marginBottom="10dp"
android:minHeight="130dp">
<HorizontalScrollView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scrollbars="horizontal"
android:id="#+id/horizontalScrollView"
android:fillViewport="false">
<LinearLayout
android:id="#+id/linear"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal"/>
</HorizontalScrollView>
<ProgressBar
android:id="#+id/loading2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:visibility="gone"
android:layout_gravity="center" />
</FrameLayout>
<FrameLayout
android:id="#+id/framelayout3"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="#+id/framelayout2"
android:minHeight="200dp">
<ImageView
android:id="#+id/imageView3"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:adjustViewBounds="true"
android:gravity="center"
android:layout_gravity="center" />
<ProgressBar
android:id="#+id/loading3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:visibility="gone"
android:layout_gravity="center" />
</FrameLayout>
</RelativeLayout>
</ScrollView>
please help me.
Try it like this :
boolean doubleBackToExitPressedOnce = false;
#Override
public void onBackPressed() {
if (getFragmentManager().getBackStackEntryCount() > 0) {
getFragmentManager().popBackStack();
} else {
Fragment fragment = getFragmentManager().findFragmentById(R.id.fragment_container);
if (fragment instanceof HomeFragment) {
if (doubleBackToExitPressedOnce) {
super.onBackPressed();
return;
}
this.doubleBackToExitPressedOnce = true;
Toast.makeText(this, "Please click BACK again to exit", Toast.LENGTH_SHORT).show();
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
doubleBackToExitPressedOnce = false;
}
}, 2000);
}
else {
super.onBackPressed();
}
}
}
Try this code..
long back_pressed=0;
#Override
public void onBackPressed()
{
if (back_pressed + 2000 > System.currentTimeMillis())
super.onBackPressed();
else
{
Snackbar snackbar=Snackbar.make(view, "Double Tap to Exit!", Snackbar.LENGTH_SHORT);
View view=snackbar.getView();
view.setBackgroundColor(getResources().getColor(R.color.white));
snackbar.show();
back_pressed = System.currentTimeMillis();
}
}
This code must help you to do things.
Define
private static final int TIME_INTERVAL = 2000; // # milliseconds, desired time passed between two back presses.
private long mBackPressed;
While adding fragments to your container, add them with backstack.
private void setFragment(Fragment fragment, int position) {
mTextViewAppTitle.setText(navTitles[position]);
getSupportFragmentManager()
.beginTransaction()
.add(R.id.main_content, fragment)
.addToBackStack(navTitles[position])
.commit();
}
Then in onBackPressed event
#Override
public void onBackPressed() {
if (getSupportFragmentManager().getBackStackEntryCount() != 0) {
super.onBackPressed();
return;
}
if (mBackPressed + TIME_INTERVAL > System.currentTimeMillis()) {
super.onBackPressed();
return;
} else {
Utils.showToast(this, "Tap back button in order to Exit");
}
mBackPressed = System.currentTimeMillis();
}
I have not get double tap to exit any way and I don't know this is right way or not but you can solve your problem following way
#Override
public void onBackPressed() {
// TODO Auto-generated method stub
if (count == 0)
count = 1;
else
count = 2;
android.os.Handler h = new android.os.Handler();
h.postDelayed(new Runnable() {
#Override
public void run() {
if (count == 2) {
// Just Put Your Code for Exit
Log.d("DoubleTap", "Exit");
}
count= 0;
}
}, 500);//You can set double tap interval currently set half second
// super.onBackPressed();
}
Note : - Declare count as a global int variable;
ex. int count = 0;

How to Reload TabContent on Click of tab in FragmentTabHost?

I am developing an android Application ,In which i am using FragmentTabHost, I am maintaining a container for each tab, But i am getting problem to reload Tabcontent when i reclick on tabs.
import android.content.Context;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTabHost;
import android.support.v4.app.FragmentTransaction;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TabHost;
import android.widget.TabHost.OnTabChangeListener;
import android.widget.TabHost.TabSpec;
import android.widget.TabWidget;
import android.widget.TextView;
import com.eDeftsoft.FragmentsContainer.AboutContainerFragment;
import com.eDeftsoft.FragmentsContainer.BaseContainerFragment;
import com.eDeftsoft.FragmentsContainer.CityContainerFragment;
import com.eDeftsoft.FragmentsContainer.HomeContainerFragment;
import com.eDeftsoft.FragmentsContainer.PhotosContainerFragment;
import com.eDeftsoft.Utility.CommonDialogues;
public class HomeScreen extends FragmentActivity {
private static final String TAB_1_TAG = "Home";
private static final String TAB_2_TAG = "Photos";
private static final String TAB_3_TAG = "City";
private static final String TAB_4_TAG = "About";
private FragmentTabHost mTabHost;
TabWidget tbwidget;
HomeContainerFragment homeFragment;
PhotosContainerFragment photosFragment;
CityContainerFragment cityFragment;
AboutContainerFragment aboutFragment;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.home_screen);
initView();
homeFragment = new HomeContainerFragment();
photosFragment = new PhotosContainerFragment();
cityFragment = new CityContainerFragment();
aboutFragment = new AboutContainerFragment();
}
private void initView() {
mTabHost = (FragmentTabHost) findViewById(android.R.id.tabhost);
mTabHost.setup(this, getSupportFragmentManager(), R.id.realtabcontent);
mTabHost.addTab(setMyCustomIndicator(this, TAB_1_TAG, "Home"),
HomeContainerFragment.class, null);
mTabHost.addTab(setMyCustomIndicator(this, TAB_2_TAG, "Photos"),
PhotosContainerFragment.class, null);
mTabHost.addTab(setMyCustomIndicator(this, TAB_3_TAG, "City"),
CityContainerFragment.class, null);
mTabHost.addTab(setMyCustomIndicator(this, TAB_4_TAG, "About"),
AboutContainerFragment.class, null);
setTabHostColors();
mTabHost.setCurrentTabByTag("TAB_1_TAG");
mTabHost.setCurrentTab(0);
mTabHost.getTabWidget().setShowDividers(LinearLayout.SHOW_DIVIDER_NONE);
mTabHost.getTabWidget().setStripEnabled(false);
tbwidget = mTabHost.getTabWidget();
/*I had Also used This But getting error when i reclick on sametabs*/
// mTabHost.setOnTabChangedListener(new OnTabChangeListener() {
//
// #Override
// public void onTabChanged(String tabId) {
// // TODO Auto-generated method stub
// if (tabId.equals(TAB_1_TAG)) {
// pushFragments(TAB_1_TAG, homeFragment);
// } else if (tabId.equals(TAB_2_TAG)) {
// pushFragments(TAB_1_TAG, photosFragment);
//
// } else if (tabId.equals(TAB_3_TAG)) {
// pushFragments(TAB_1_TAG, cityFragment);
// } else {
// pushFragments(TAB_1_TAG, aboutFragment);
// }
//
// }
// });
}
/*
* insert the fragment into the FrameLayout
*/
// public void pushFragments(String tag, Fragment class1) {
//
// FragmentManager manager = getSupportFragmentManager();
// FragmentTransaction ft = manager.beginTransaction();
//
// ft.replace(R.id.realtabcontent, class1);
// ft.commit();
// }
public TabSpec setMyCustomIndicator(Context con, String tag,
String labeltext) {
TabHost.TabSpec spec = mTabHost.newTabSpec(tag);
View tabIndicator = LayoutInflater.from(this).inflate(
R.layout.tab_indicator, null, false);
((TextView) tabIndicator.findViewById(R.id.title)).setText(labeltext);
// ((ImageView) tabIndicator.findViewById(R.id.icon))
// .setImageResource(resid);
return spec.setIndicator(tabIndicator);
}
#Override
public void onBackPressed() {
boolean isPopFragment = false;
String currentTabTag = mTabHost.getCurrentTabTag();
FragmentManager fm = getSupportFragmentManager();
if (currentTabTag.equals(TAB_1_TAG)) {
for (int entry = 0; entry < fm.getBackStackEntryCount(); entry++) {
String ide = fm.getBackStackEntryAt(entry).getName();
Log.i("TAG" + TAB_1_TAG, "Found fragment: " + ide);
}
isPopFragment = ((BaseContainerFragment) getSupportFragmentManager()
.findFragmentByTag(TAB_1_TAG)).popFragment();
}
else if (currentTabTag.equals(TAB_2_TAG)) {
for (int entry = 0; entry < fm.getBackStackEntryCount(); entry++) {
String ide = fm.getBackStackEntryAt(entry).getName();
Log.i("TAG" + TAB_2_TAG, "Found fragment: " + ide);
}
isPopFragment = ((BaseContainerFragment) getSupportFragmentManager()
.findFragmentByTag(TAB_2_TAG)).popFragment();
}
else if (currentTabTag.equals(TAB_3_TAG)) {
for (int entry = 0; entry < fm.getBackStackEntryCount(); entry++) {
String ide = fm.getBackStackEntryAt(entry).getName();
Log.i("TAG" + TAB_3_TAG, "Found fragment: " + ide);
}
isPopFragment = ((BaseContainerFragment) getSupportFragmentManager()
.findFragmentByTag(TAB_3_TAG)).popFragment();
}
else if (currentTabTag.equals(TAB_4_TAG)) {
for (int entry = 0; entry < fm.getBackStackEntryCount(); entry++) {
String ide = fm.getBackStackEntryAt(entry).getName();
Log.i("TAG" + TAB_4_TAG, "Found fragment: " + ide);
}
isPopFragment = ((BaseContainerFragment) getSupportFragmentManager()
.findFragmentByTag(TAB_4_TAG)).popFragment();
}
if (!isPopFragment) {
CommonDialogues.showAlertDialog(HomeScreen.this,
"Application Will Exit", "Do you Want to Exit");
}
}
private void setTabHostColors() {
for (int i = 0; i < mTabHost.getTabWidget().getChildCount(); i++) {
mTabHost.getTabWidget().getChildAt(i)
.setBackgroundColor(Color.TRANSPARENT);
final TextView tv = (TextView) mTabHost.getTabWidget()
.getChildAt(i).findViewById(android.R.id.title);
if (tv == null)
continue;
else
tv.setTextSize(12);
}
}
#Override
public void onDestroy() {
super.onDestroy();
mTabHost = null;
}
}
When i go in inner fragments of tab1 , like from fragmentA -> Fragment B and From FragmentB -> fragmentC (and finally i am at fragmentC) , When i select Tab1 again i want to reload tabs and FragmentA should Apper.
Any help will be appreciated. I had gone through some of tutorials and coderepository but couldn`t found solution to my problem.
How Can i reload The content Of First tab when first tab is clicked again.
I had asked a question
When i go in inner fragments of tab1 , like from fragmentA -> Fragment B and From FragmentB -> fragmentC (and finally i am at fragmentC) , When i select Tab1 again i want to reload tabs and FragmentA should Apper.
I searched a lot and come to the conclusion , We can implement OnTabChangeListner and when any tab is clicked again we can reset it.(I was having need to reload tab when it is clicked 2nd time)
<!--Layout for Tabs -->
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<TabHost
android:id="#android:id/tabhost"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:baselineAligned="false"
android:orientation="vertical" >
<FrameLayout
android:id="#android:id/tabcontent"
android:layout_width="fill_parent"
android:layout_height="0dp"
android:layout_weight="1" />
<!-- android:background="#drawable/footer" -->
<FrameLayout
android:id="#+id/tabframeLayout"
android:layout_width="fill_parent"
android:layout_height="#dimen/tabframe_height"
android:layout_marginTop="1dp"
android:background="#FBFAFA" >
<TabWidget
android:id="#android:id/tabs"
android:layout_width="fill_parent"
android:layout_height="#dimen/tab_height"
android:background="#F2F0F0" >
</TabWidget>
</FrameLayout>
</LinearLayout>
</TabHost>
</RelativeLayout>
import java.util.ArrayList;
import java.util.HashMap;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.Typeface;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TabHost;
import android.widget.TabHost.OnTabChangeListener;
import android.widget.TextView;
import com.abc.Fragments.FragmentA;
import com.abc.Fragments.FragmentA1;
import com.abc.Fragments.FragmentA2;
import com.abc.Fragments.FragmentA3;
import com.abc.Utility.CommonDialogues;
public class MyHomeScreen extends FragmentActivity implements
OnTabChangeListener {
private TabHost tabHost;
private String currentSelectedTab;
private HashMap<String, ArrayList<Fragment>> hMapTabs;
final int TEXT_ID = 100;
final String arrTabLabel[] = { "FragmentA", "FragmentA1", "FragmentA2",
"FragmentA3" };
final static int arrIcons[] = { R.drawable.homee, R.drawable.photoi,
R.drawable.cityi, R.drawable.abouti };
private MyTabView arrTabs[] = new MyTabView[4];
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.my_home_screen);
hMapTabs = new HashMap<String, ArrayList<Fragment>>();
hMapTabs.put(AppConstant.TAB_1_TAG, new ArrayList<Fragment>());
hMapTabs.put(AppConstant.TAB_2_TAG, new ArrayList<Fragment>());
hMapTabs.put(AppConstant.TAB_3_TAG, new ArrayList<Fragment>());
hMapTabs.put(AppConstant.TAB_4_TAG, new ArrayList<Fragment>());
tabHost = (TabHost) findViewById(android.R.id.tabhost);
tabHost.setOnTabChangedListener(this);
tabHost.setup();
TabHost.TabSpec spec = tabHost.newTabSpec(AppConstant.TAB_1_TAG);
tabHost.setCurrentTab(0);
arrTabs[0] = new MyTabView(this, 0, arrTabLabel[0]);
spec.setContent(new TabHost.TabContentFactory() {
public View createTabContent(String tag) {
return findViewById(android.R.id.tabcontent);
}
});
spec.setIndicator(arrTabs[0]);
tabHost.addTab(spec);
spec = tabHost.newTabSpec(AppConstant.TAB_2_TAG);
arrTabs[1] = new MyTabView(this, 1, arrTabLabel[1]);
spec.setContent(new TabHost.TabContentFactory() {
public View createTabContent(String tag) {
return findViewById(android.R.id.tabcontent);
}
});
spec.setIndicator(arrTabs[1]);
tabHost.addTab(spec);
spec = tabHost.newTabSpec(AppConstant.TAB_3_TAG);
arrTabs[2] = new MyTabView(this, 2, arrTabLabel[2]);
spec.setContent(new TabHost.TabContentFactory() {
public View createTabContent(String tag) {
return findViewById(android.R.id.tabcontent);
}
});
spec.setIndicator(arrTabs[2]);
tabHost.addTab(spec);
spec = tabHost.newTabSpec(AppConstant.TAB_4_TAG);
arrTabs[3] = new MyTabView(this, 3, arrTabLabel[3]);
spec.setContent(new TabHost.TabContentFactory() {
public View createTabContent(String tag) {
return findViewById(android.R.id.tabcontent);
}
});
spec.setIndicator(arrTabs[3]);
tabHost.addTab(spec);
// set background for Selected Tab
TextView tv = (TextView) tabHost.getCurrentTabView().findViewById(
TEXT_ID);
// tv.setTextColor(Color.parseColor("#2882C6"));
View iv = (View) tabHost.getCurrentTabView();
// iv.setBackgroundResource(R.color.green);
// Listner for Tab 1//
tabHost.getTabWidget().getChildAt(0)
.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (hMapTabs.size() > 0) {
if (tabHost.getTabWidget().getChildAt(0)
.isSelected()) {
if (hMapTabs.get(AppConstant.TAB_1_TAG).size() > 1) {
resetFragment();
}
}
tabHost.getTabWidget().setCurrentTab(0);
tabHost.setCurrentTab(0);
}
}
});
/* Listner for Tab 2 */
tabHost.getTabWidget().getChildAt(1)
.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
if (hMapTabs.size() > 0) {
if (tabHost.getTabWidget().getChildAt(1)
.isSelected()) {
if (hMapTabs.get(AppConstant.TAB_2_TAG).size() > 1) {
resetFragment();
}
}
tabHost.getTabWidget().setCurrentTab(1);
tabHost.setCurrentTab(1);
}
}
});
/* Listner for Tab 3 */
tabHost.getTabWidget().getChildAt(2)
.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
if (hMapTabs.size() > 0) {
if (tabHost.getTabWidget().getChildAt(2)
.isSelected()) {
if (hMapTabs.get(AppConstant.TAB_3_TAG).size() > 1) {
resetFragment();
}
}
tabHost.getTabWidget().setCurrentTab(2);
tabHost.setCurrentTab(2);
}
}
});
/* Listner for Tab 4 */
tabHost.getTabWidget().getChildAt(3)
.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
if (hMapTabs.size() > 0) {
if (tabHost.getTabWidget().getChildAt(3)
.isSelected()) {
if (hMapTabs.get(AppConstant.TAB_4_TAG).size() > 1) {
resetFragment();
}
}
tabHost.getTabWidget().setCurrentTab(3);
tabHost.setCurrentTab(3);
}
}
});
}
/* Method for adding fragment */
public void addFragments(String tabName, Fragment fragment,
boolean animate, boolean add) {
if (add) {
hMapTabs.get(tabName).add(fragment);
}
FragmentManager manager = getSupportFragmentManager();
FragmentTransaction ft = manager.beginTransaction();
if (animate) {
ft.setCustomAnimations(R.animator.slide_in_right,
R.animator.slide_out_left);
}
ft.replace(android.R.id.tabcontent, fragment);
ft.commit();
}
/* Method for remove fragment */
public void removeFragment() {
Fragment fragment = hMapTabs.get(currentSelectedTab).get(
hMapTabs.get(currentSelectedTab).size() - 2);
hMapTabs.get(currentSelectedTab).remove(
hMapTabs.get(currentSelectedTab).size() - 1);
FragmentManager manager = getSupportFragmentManager();
FragmentTransaction ft = manager.beginTransaction();
ft.setCustomAnimations(R.animator.slide_in_left,
R.animator.slide_out_right);
ft.replace(android.R.id.tabcontent, fragment);
ft.commit();
}
// reset frgment used when clicked on same tab
private void resetFragment() {
Fragment fragment = hMapTabs.get(currentSelectedTab).get(0);
hMapTabs.get(currentSelectedTab).clear();
hMapTabs.get(currentSelectedTab).add(fragment);
FragmentManager manager = getSupportFragmentManager();
FragmentTransaction ft = manager.beginTransaction();
ft.setCustomAnimations(R.animator.slide_in_left,
R.animator.slide_out_right);
ft.replace(android.R.id.tabcontent, fragment);
ft.commit();
}
#Override
public void onBackPressed() {
if (hMapTabs.get(currentSelectedTab).size() <= 1) {
// super.onBackPressed();
CommonDialogues.showAlertDialog(MyHomeScreen.this,
"Application Will Exit", "Do you Want to Exit");
} else {
removeFragment();
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (hMapTabs.get(currentSelectedTab).size() == 0) {
return;
}
hMapTabs.get(currentSelectedTab)
.get(hMapTabs.get(currentSelectedTab).size() - 1)
.onActivityResult(requestCode, resultCode, data);
}
#Override
public void onTabChanged(String tabName) {
// TODO Auto-generated method stub
currentSelectedTab = tabName;
// make iteration for unselected tab and make normal background
for (int i = 0; i < tabHost.getTabWidget().getChildCount(); i++) {
TextView tv = (TextView) tabHost.getTabWidget().getChildAt(i)
.findViewById(TEXT_ID);
tv.setTextColor(Color.parseColor("#BDBDBD"));
View iv = (View) tabHost.getTabWidget().getChildAt(i);
iv.setBackgroundColor(0x00000000);
}
TextView tv = (TextView) tabHost.getCurrentTabView().findViewById(
TEXT_ID); // for Selected Tab
tv.setTextColor(Color.parseColor("#2882C6"));
View iv = (View) tabHost.getCurrentTabView();
if (hMapTabs.get(tabName).size() == 0) {
if (tabName.equals(AppConstant.TAB_1_TAG)) {
addFragments(tabName, new FragmentA(), false, true);
} else if (tabName.equals(AppConstant.TAB_2_TAG)) {
addFragments(tabName, new FragmentA1(), false, true);
} else if (tabName.equals(AppConstant.TAB_3_TAG)) {
addFragments(tabName, new FragmentA2(), false, true);
} else if (tabName.equals(AppConstant.TAB_4_TAG)) {
addFragments(tabName, new FragmentA3(), false, true);
}
} else {
addFragments(
tabName,
hMapTabs.get(tabName).get(hMapTabs.get(tabName).size() - 1),
false, false);
}
switch (tabHost.getCurrentTab()) {
case 0:
// we can also set background color of tabview
// iv.setBackgroundResource(R.color.green);
break;
case 1:
// iv.setBackgroundResource(R.color.red);
break;
case 2:
// iv.setBackgroundResource(R.color.yellow);
break;
case 3:
// iv.setBackgroundResource(R.color.twitter);
break;
}
}
private class MyTabView extends LinearLayout {
int nIdx = -1;
TextView tv;
public MyTabView(Context c, int drawableIdx, String label) {
super(c);
ImageView iv = new ImageView(c);
nIdx = drawableIdx;
// used for forground icons//
iv.setImageResource(arrIcons[nIdx]);
tv = new TextView(c);
tv.setText(label);
tv.setGravity(Gravity.BOTTOM);
tv.setTextSize(14.0f);
tv.setTypeface(null, Typeface.BOLD);
tv.setId(TEXT_ID);
LinearLayout.LayoutParams param = new LinearLayout.LayoutParams(
LayoutParams.WRAP_CONTENT, LayoutParams.FILL_PARENT, 0.9f);
LinearLayout.LayoutParams layout = new LinearLayout.LayoutParams(
LayoutParams.WRAP_CONTENT, LayoutParams.FILL_PARENT, 0.3f);
layout.setMargins(0, 3, 0, 0);
iv.setLayoutParams(layout);
layout.setMargins(0, 3, 0, 2);
tv.setLayoutParams(param);
tv.setTextColor(Color.parseColor("#BDBDBD"));
setOrientation(LinearLayout.VERTICAL);
setGravity(Gravity.CENTER_VERTICAL | Gravity.CENTER_HORIZONTAL);
addView(iv);
addView(tv);
}
}
}
<!--Layout for FragmenA -->
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#00ff00"
android:gravity="center"
android:orientation="vertical" >
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:text="TAB 1 FIRST SCREEN"
android:textColor="#color/dark_blue"
android:textSize="30sp"
android:textStyle="bold" />
<Button
android:id="#+id/btnNext"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="10dip"
android:text="Go to Next Screen" />
<EditText
android:id="#+id/editText1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:inputType="textPersonName" >
</EditText>
</LinearLayout>
code for fragment A ...it is extend By Basefragment
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.Toast;
public class FirstScreen extends BaseFragment implements OnClickListener {
private Button btnNext;
#Override
public void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
Toast.makeText(getActivity(), "I am in onCreate", Toast.LENGTH_LONG).show();
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.tab1_firstscreen,
container, false);
btnNext = (Button) view.findViewById(R.id.btnNext);
btnNext.setOnClickListener(this);
System.out.println("replace");
return view;
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
fragmentTabActivity.addFragments(Const.TAB_FIRST,
new SecondScreen(), true, true);
}
}
Code for BaseFragment is
extend this class with all sub fragment which you are going to add on (While adding fragment use myhomescreenActivity(This object) and call add Function in MyHomeScreen ):
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
public class BaseFragment extends Fragment {
protected MyHomeScreen myhomescreenActivity;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
myhomescreenActivity = (MyHomeScreen) this.getActivity();
}
public boolean onBackPressed() {
return false;
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
}
}
This is the link of repository on Github for further understanding.......
https://github.com/thankimanish/TabUsingFragment
1.You can try moving your code inside the onCreate method to the onResume method so that every time fragment comes to front the code inside the onResume gets executed and reloads the frament.
2.You can also try overriding the onHiddenChanged method of the fragment and reload the fragment as soon as fragment becomes visible

How do I use fragments properly

I'm trying to learn how to use Fragments in android. I create the separate classes and layouts. I'm having trouble understanding how I'm supposed to link them all. What exactly goes in my Main class? Could someone please demonstrate exactly how to use fragments in a very basic way?
please read this first as, i think, i has the very basics. Below is an example:
MainActivity:
public class MainActivity extends Activity implements OnClickListener{
private final String TAG = "MainActivity";
private int btn00Clicks = 0;
private int btn01Clicks = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.mainactivity);
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Fragment mSelectedFragment = null;
switch (v.getId()) {
case R.id.btn00:
Bundle mBundle00 = new Bundle();
String clicks00 = Integer.toString(btn00Clicks);
mBundle00.putString("btn00_clicks", clicks00);
mSelectedFragment = new Fragment00();
mSelectedFragment.setArguments(mBundle00);
if (mSelectedFragment != null) {
FragmentManager mFragmentManager = getFragmentManager();
mFragmentManager.beginTransaction()
.replace(R.id.fragment00ID, mSelectedFragment).commit();
}
btn00Clicks++;
break;
case R.id.btn01:
Bundle mBundle01 = new Bundle();
String clicks01 = Integer.toString(btn01Clicks);
mBundle01.putString("btn01_clicks", clicks01);
mSelectedFragment = new Fragment01();
mSelectedFragment.setArguments(mBundle01);
if (mSelectedFragment != null) {
FragmentManager mFragmentManager = getFragmentManager();
mFragmentManager.beginTransaction()
.replace(R.id.fragment00ID, mSelectedFragment).commit();
}
btn01Clicks++;
}
}
}
Fragment00.java:
public class Fragment00 extends Fragment {
private final String TAG = "Fragment00";
TextView mTv;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
View view = inflater.inflate(R.layout.fragment00, null);
return view;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onActivityCreated(savedInstanceState);
mTv = (TextView) getView().findViewById(R.id.fragment00Tv00);
if (getArguments() != null) {
String str = getArguments().getString("btn00_clicks").toString();
mTv.setText("the Button was clicked "+str+ " time(s)");
Log.i(TAG, "onActivityCreated(): "+str);
}else {
Log.i(TAG, "onActivityCreated(): getArguments() is NULL");
}
}
#Override
public void onAttach(Activity activity) {
// TODO Auto-generated method stub
super.onAttach(activity);
}
#Override
public void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
}
}
Fragment01.java:
public class Fragment01 extends Fragment {
private static final String TAG = "Fragment01";
TextView mTv;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
return inflater.inflate(R.layout.fragment01, null);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onActivityCreated(savedInstanceState);
mTv = (TextView) getView().findViewById(R.id.fragment01Tv00);
if (getArguments() != null) {
String str = getArguments().getString("btn01_clicks").toString();
mTv.setText("the Button was clicked "+str+ " time(s)");
Log.i(TAG, "onActivityCreated(): "+str);
}else {
Log.i(TAG, "onActivityCreated(): getArguments() is NULL");
}
}
}
MainActivity_layout:
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/container"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
tools:context="com.example.fragments01.MainActivity"
tools:ignore="MergeRootFrame">
<RelativeLayout
android:id="#+id/mainRelativeLayout00"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_gravity="top|center_vertical">
<Button
android:id="#+id/btn00"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="fragment_one"
android:onClick="onClick"></Button>
<Button
android:id="#+id/btn01"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/btn00"
android:text="Fragment two"
android:onClick="onClick"></Button>
<fragment
android:name="com.example.fragments01.Fragment00"
android:id="#+id/fragment00ID"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_below="#+id/btn01">
</fragment>
</RelativeLayout>
Fragment00_layout.xml
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/container"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
tools:context="com.example.fragments01.Fragment00"
tools:ignore="MergeRootFrame"
android:background="#00ffff">
<RelativeLayout
android:id="#+id/fragment00RelativeLayout00"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_gravity="top|center_vertical">
<TextView
android:id="#+id/fragment00Tv00"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
</TextView>
</RelativeLayout>
Fragment01_layout.xml:
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/container"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
tools:context="com.example.fragments01.Fragment01"
tools:ignore="MergeRootFrame"
android:background="#ffff00">
<RelativeLayout
android:id="#+id/fragment01RelativeLayout00"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_gravity="top|center_vertical">
<TextView
android:id="#+id/fragment01Tv00"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Fragment two">
</TextView>
<Button
android:id="#+id/fragment01Btn00"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Button of fragment two"
android:layout_below="#+id/fragment01Tv00">
</Button>
</RelativeLayout>
In your main class you produce one or more fragments... While you produce each fragment it's pretty similar to Activity,but has its own lifecircle(google it).
here's example on fragment:
public class DummySectionFragment3 extends Fragment
{
public DummySectionFragment3() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState)
{
View rootView = inflater.inflate(R.layout.exercise_layout,
container, false);
return rootView;
}
}
in OnCreateView() method you do what you usually do with activity.
My Main class contains SectionsPagerAdapter that switches between the fragments(A pager like in API samples)
create 2 or 3 fragments and just try it...
I didn't find any good example on it,so I just tried the above.
http://www.c-sharpcorner.com/UploadFile/2fd686/fragments/
Here's one good link with tabs and fragments.
You can also define your fragments in your xml.
Same as what LetsAmrIt posted, just another example:
Main Activity:
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.Comparator;
import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.content.Context;
import android.content.Intent;
import android.content.res.Configuration;
import android.graphics.PixelFormat;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
public class MainActivity extends Activity implements MyListFragment.MovieSelectedListener
{
Movie movie;
ListView movieList;
#SuppressWarnings("deprecation")
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
getWindow().setFormat(PixelFormat.RGBA_8888);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_DITHER);
setContentView(R.layout.activity_main);
try
{
FileInputStream fis = openFileInput("movies");
if (fis != null)
{
ObjectInputStream in = new ObjectInputStream(fis);
movie = (Movie) in.readObject();
in.close();
Toast.makeText(this, "Movies loaded.", Toast.LENGTH_SHORT).show();
}
}
catch (Exception e)
{
Toast.makeText(this, "No movies to load.", Toast.LENGTH_SHORT).show();
}
if (movie == null)
{
movie = new Movie();
movie.addMovie("Harry Potter", "12 January", "Thriller", 4, "Some people", "Bad", "Someone", "Walmer Park");
}
loadFragments();
}
public void loadFragments()
{
if ((getResources().getConfiguration().screenLayout &Configuration.SCREENLAYOUT_SIZE_MASK) == Configuration.SCREENLAYOUT_SIZE_LARGE)
{
Log.d("Screen Size: ", "LARGE");
// obtain the fragment manager
FragmentManager fragmentManager = getFragmentManager();
// determine if the fragment has already been loaded (may have happened)
Fragment listfrag = fragmentManager.findFragmentById(R.id.fragment_container);
// place fragment into container if not already there
if (listfrag == null) {
// start a transaction that will handle the swapping in/out
FragmentTransaction fragmentTransaction = fragmentManager
.beginTransaction();
// multiple additions to the transaction can be done so that they
// changes will be done simultaneously
MyListFragment fragment1 = new MyListFragment();
fragmentTransaction.add(R.id.fragment_container, fragment1);
ViewFragment fragment2 = new ViewFragment();
fragmentTransaction.add(R.id.details_container, fragment2);
Bundle args = new Bundle();
args.putSerializable("Movie", movie);
fragment1.setArguments(args);
// commit the changes, i.e. do it!
fragmentTransaction.commit();
}
}
else if ((getResources().getConfiguration().screenLayout & Configuration.SCREENLAYOUT_SIZE_MASK) == Configuration.SCREENLAYOUT_SIZE_NORMAL) {
Log.d("Screen Size: ", "NORMAL");
// obtain the fragment manager
FragmentManager fragmentManager = getFragmentManager();
// determine if the fragment has already been loaded (may have happened)
Fragment listfrag = fragmentManager.findFragmentById(R.id.fragment_container);
// place fragment into container if not already there
if (listfrag == null) {
// start a transaction that will handle the swapping in/out
FragmentTransaction fragmentTransaction = fragmentManager
.beginTransaction();
// multiple additions to the transaction can be done so that they
// changes will be done simultaneously
MyListFragment fragment = new MyListFragment();
fragmentTransaction.add(R.id.fragment_container, fragment);
Bundle args = new Bundle();
args.putSerializable("Movie", movie);
fragment.setArguments(args);
// commit the changes, i.e. do it!
fragmentTransaction.commit();
}
}
else if ((getResources().getConfiguration().screenLayout & Configuration.SCREENLAYOUT_SIZE_MASK) == Configuration.SCREENLAYOUT_SIZE_SMALL) {
Log.d("Screen Size: ", "SMALL");
}
else if ((getResources().getConfiguration().screenLayout & Configuration.SCREENLAYOUT_SIZE_MASK) == Configuration.SCREENLAYOUT_SIZE_XLARGE) {
Log.d("Screen Size: ", "XLARGE");
Log.d("Screen Size: ", "LARGE");
// obtain the fragment manager
FragmentManager fragmentManager = getFragmentManager();
// determine if the fragment has already been loaded (may have happened)
Fragment listfrag = fragmentManager.findFragmentById(R.id.fragment_container);
// place fragment into container if not already there
if (listfrag == null) {
// start a transaction that will handle the swapping in/out
FragmentTransaction fragmentTransaction = fragmentManager
.beginTransaction();
// multiple additions to the transaction can be done so that they
// changes will be done simultaneously
MyListFragment fragment1 = new MyListFragment();
fragmentTransaction.add(R.id.fragment_container, fragment1);
ViewFragment fragment2 = new ViewFragment();
fragmentTransaction.add(R.id.details_container, fragment2);
Bundle args = new Bundle();
args.putSerializable("Movie", movie);
fragment1.setArguments(args);
// commit the changes, i.e. do it!
fragmentTransaction.commit();
}
}
else {
Log.d("Screen Size: ","UNKNOWN_CATEGORY_SCREEN_SIZE");
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu items for use in the action bar
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main, menu);
return true;
}
public void pushFragment(Movie curMovie) {
// obtain the fragment manager
FragmentManager fragmentManager = getFragmentManager();
// start a transaction that will handle the swapping in/out
FragmentTransaction fragmentTransaction = fragmentManager
.beginTransaction();
// add new fragment, BUT remember previous one, so that BACK button
// returns to it
ViewFragment fragment = new ViewFragment();
fragmentTransaction.replace(R.id.fragment_container, fragment);
fragmentTransaction.addToBackStack("view");
Bundle args = new Bundle();
args.putSerializable("curMovie", curMovie);
fragment.setArguments(args);
// commit the changes, i.e. do it!
fragmentTransaction.commit();
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
MyListFragment fragment = (MyListFragment) getFragmentManager().findFragmentById(R.id.fragment_container);
switch(item.getItemId())
{
case R.id.action_about:
About();
return true;
case R.id.action_add:
addMovie();
return true;
case R.id.sort_Title:
fragment.sortTitle();
return true;
case R.id.sort_Date:
fragment.sortDateViewed();
return true;
case R.id.sort_Rating:
fragment.sortRating();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
if (requestCode == 1)
{
if (resultCode == RESULT_OK)
{
String title = data.getStringExtra("titleText");
String genre = data.getStringExtra("genreText");
String actors = data.getStringExtra("actorsText");
int rating = data.getIntExtra("ratingValue", 0);
String date = data.getStringExtra("dateWatched");
String watchedWith = data.getStringExtra("watchedWithText");
String watchedAt = data.getStringExtra("watchedAtText");
String comment = data.getStringExtra("commentText");
movie.addMovie(title, date, genre, rating, actors, comment, watchedWith, watchedAt);
write();
}
}
super.onActivityResult(requestCode, resultCode, data);
}
public void write()
{
try
{
FileOutputStream fos = openFileOutput("movies", Context.MODE_PRIVATE);
ObjectOutputStream out = new ObjectOutputStream(fos);
out.writeObject(movie);
fos.close();
Toast.makeText(this, "Movies saved.", Toast.LENGTH_SHORT).show();
}
catch (Exception e)
{
Toast.makeText(this, "Movies could not be saved.", Toast.LENGTH_SHORT).show();
}
}
public void addMovie()
{
Intent intentAdd = new Intent(MainActivity.this, AddMovie.class);
startActivityForResult(intentAdd, 1);
}
public void About()
{
Intent intentAbout = new Intent(this, About.class);
startActivity(intentAbout);
}
public void addDetails(Movie curMovie)
{
// obtain the fragment manager
FragmentManager fragmentManager = getFragmentManager();
// start a transaction that will handle the swapping in/out
FragmentTransaction fragmentTransaction = fragmentManager
.beginTransaction();
ViewFragment fragment = new ViewFragment();
// REPLACE the existing fragment with another one
fragmentTransaction.replace(R.id.details_container, fragment);
Bundle args = new Bundle();
args.putSerializable("curMovie", curMovie);
fragment.setArguments(args);
// commit the changes, i.e. do it!
fragmentTransaction.commit();
}
#Override
public void onMovieSelected(String movieName) {
// TODO Auto-generated method stub
if ((getResources().getConfiguration().screenLayout &Configuration.SCREENLAYOUT_SIZE_MASK) == Configuration.SCREENLAYOUT_SIZE_LARGE)
{
Log.d("Screen Size: ", "LARGE");
Movie current = movie.getMovie(movieName);
Context context = getApplicationContext();
CharSequence text = current.MovieTitle;
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
addDetails(current);
}
else if ((getResources().getConfiguration().screenLayout & Configuration.SCREENLAYOUT_SIZE_MASK) == Configuration.SCREENLAYOUT_SIZE_NORMAL) {
Log.d("Screen Size: ", "NORMAL");
Movie current = movie.getMovie(movieName);
Context context = getApplicationContext();
CharSequence text = current.MovieTitle;
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
pushFragment(current);
}
else if ((getResources().getConfiguration().screenLayout & Configuration.SCREENLAYOUT_SIZE_MASK) == Configuration.SCREENLAYOUT_SIZE_SMALL) {
Log.d("Screen Size: ", "SMALL");
}
else if ((getResources().getConfiguration().screenLayout & Configuration.SCREENLAYOUT_SIZE_MASK) == Configuration.SCREENLAYOUT_SIZE_XLARGE) {
Log.d("Screen Size: ", "XLARGE");
}
else {
Log.d("Screen Size: ","UNKNOWN_CATEGORY_SCREEN_SIZE");
}
}
#Override
public void onDeleteSelected(String movie, MovieAdapter adapter) {
// TODO Auto-generated method stub
this.movie.deleteMovie(movie);
adapter.notifyDataSetChanged();
write();
}
}
Movie Adapter:
import java.util.List;
import android.content.Context;
import android.view.*;
import android.widget.ArrayAdapter;
import android.widget.RatingBar;
import android.widget.TextView;
public class MovieAdapter extends ArrayAdapter<Movie> {
private Context context;
private List<Movie> movies;
public MovieAdapter(Context context, List<Movie> movies)
{
super(context, R.layout.movie_layout, movies);
this.context = context;
this.movies = movies;
}
#Override
public View getView(int position, View convertView, ViewGroup parent)
{
View movieView = convertView;
if(movieView == null)
{
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
movieView = inflater.inflate(R.layout.movie_layout, parent, false);
}
movieView.setTag(movies.get(position));
TextView txtTitle = (TextView) movieView.findViewById(R.id.txtTitle);
TextView txtDate = (TextView) movieView.findViewById(R.id.txtDate);
RatingBar ratingBar = (RatingBar) movieView.findViewById(R.id.ratingBar);
txtTitle.setText(movies.get(position).MovieTitle);
txtDate.setText("Date Viewed: "+movies.get(position).dateViewed);
ratingBar.setIsIndicator(true);
ratingBar.setNumStars(movies.get(position).rating);
ratingBar.setRating(movies.get(position).rating);
return movieView;
}
}
List Fragment:
import java.util.Comparator;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Fragment;
import android.content.DialogInterface;
import android.util.Log;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.TextView;
public class MyListFragment extends Fragment{
Movie movie;
MovieAdapter adapter;
MovieSelectedListener callBack;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
View view = inflater.inflate(R.layout.list_fragment, container, false);
ListView movieList = (ListView)view.findViewById(R.id.movieList);
movieList.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// TODO Auto-generated method stub
TextView movie = (TextView)view.findViewById(R.id.txtTitle);
String title = movie.getText().toString();
callBack.onMovieSelected(title);
}
});
if (getArguments() != null)
movie = (Movie)getArguments().getSerializable("Movie");
Log.v("PASSED","Got here");
adapter = new MovieAdapter(getActivity(), movie.movies);
movieList.setAdapter(adapter);
movieList.setLongClickable(true);
movieList.setOnItemLongClickListener(new OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, final View view,
int position, long id) {
// TODO Auto-generated method stub
AlertDialog.Builder dialog = new AlertDialog.Builder(getActivity());
dialog.setMessage("Are you sure you want to delete this movie?");
dialog.setTitle("Alert Message");
dialog.setCancelable(false);
dialog.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
TextView movie = (TextView)view.findViewById(R.id.txtTitle);
String title = movie.getText().toString();
callBack.onDeleteSelected(title, adapter);
}
});
dialog.setNegativeButton("No",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
}
});
dialog.show();
return false;
}
});
return view;
}
public interface MovieSelectedListener
{
public void onMovieSelected(String movie);
public void onDeleteSelected(String movie, MovieAdapter adapter);
}
#Override
public void onAttach(Activity activity)
{
super.onAttach(activity);;
try
{
callBack = (MovieSelectedListener) activity;
}
catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement MovieSelectedListener");
}
}
public void sortTitle()
{
adapter.sort(new Comparator<Movie>() {
public int compare(Movie lhs, Movie rhs) {
return lhs.MovieTitle.compareTo(rhs.MovieTitle);
}
});
adapter.notifyDataSetChanged();
}
public void sortDateViewed()
{
adapter.sort(new Comparator<Movie>() {
public int compare(Movie lhs, Movie rhs) {
return lhs.dateViewed.compareTo(rhs.dateViewed);
}
});
adapter.notifyDataSetChanged();
}
public void sortRating()
{
adapter.sort(new Comparator<Movie>() {
public int compare(Movie lhs, Movie rhs) {
return ((Integer)lhs.rating).compareTo(rhs.rating);
}
});
adapter.notifyDataSetChanged();
}
}
View Fragment
import android.app.Fragment;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RatingBar;
import android.widget.TextView;
public class ViewFragment extends Fragment {
Movie curMovie = new Movie("Empty", "Empty", "Empty", 5, "Empty", "Empty", "Empty", "Empty");
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
View view = inflater.inflate(R.layout.view_fragment, container, false);
if (getArguments() != null)
curMovie = (Movie)getArguments().getSerializable("curMovie");
TextView titleTxt = (TextView)view.findViewById(R.id.titleTxt);
titleTxt.setText(curMovie.MovieTitle);
TextView genreTxt = (TextView)view.findViewById(R.id.genreTxt);
genreTxt.setText(curMovie.genre);
TextView actorsTxt = (TextView)view.findViewById(R.id.actorsTxt);
actorsTxt.setText(curMovie.actors);
RatingBar ratingRes = (RatingBar)view.findViewById(R.id.ratingRes);
ratingRes.setIsIndicator(true);
ratingRes.setNumStars(curMovie.rating);
ratingRes.setRating(curMovie.rating);
TextView dateWatchedTxt = (TextView)view.findViewById(R.id.dateWatchedTxt);
dateWatchedTxt.setText(curMovie.dateViewed);
TextView watchedWithTxt = (TextView)view.findViewById(R.id.watchedWithTxt);
watchedWithTxt.setText(curMovie.viewedWith);
TextView watchedAtTxt = (TextView)view.findViewById(R.id.watchedAtTxt);
watchedAtTxt.setText(curMovie.viewedWhere);
TextView commentTxt = (TextView)view.findViewById(R.id.commentTxt);
commentTxt.setText(curMovie.comments);
// Inflate the layout for this fragment
return view;
}
}
Movie:
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
public class Movie implements Serializable
{
String MovieTitle, dateViewed, actors, genre, comments, viewedWith, viewedWhere;
int rating;
public Movie(String MovieTitle, String dateViewed, String genre, int rating, String actors, String comments, String viewedWith, String viewedWhere)
{
this.MovieTitle = MovieTitle;
this.dateViewed = dateViewed;
this.genre = genre;
this.rating = rating;
this.actors = actors;
this.comments = comments;
this.viewedWith = viewedWith;
this.viewedWhere = viewedWhere;
}
final List<Movie> movies = new ArrayList<Movie>();
public Movie(){
}
public void addMovie(String MovieTitle, String dateViewed, String genre, int rating, String actors, String comments, String viewedWith, String viewedWhere)
{
movies.add(new Movie(MovieTitle, dateViewed, genre, rating, actors, comments, viewedWith, viewedWhere));
}
public void deleteMovie(String movieTitle)
{
Movie toDelete = getMovie(movieTitle);
movies.remove(toDelete);
}
public Movie getMovie(String movie)
{
for(Movie mov:movies)
{
if(mov.MovieTitle.equals(movie))
{
return mov;
}
}
return null;
}
}
Add Movie:
import java.io.FileOutputStream;
import java.io.ObjectOutputStream;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.EditText;
import android.widget.RatingBar;
import android.widget.Toast;
public class AddMovie extends Activity
{
EditText title2;
EditText genre2;
EditText actors2;
RatingBar rating2;
EditText date2;
EditText watchedWith2;
EditText watchedAt2;
EditText comment2;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_movie);
//savedInstance
title2 = (EditText)findViewById(R.id.title);
genre2 = (EditText)findViewById(R.id.genre);
actors2 = (EditText)findViewById(R.id.actors);
rating2 = (RatingBar)findViewById(R.id.rating);
date2 = (EditText)findViewById(R.id.dateWatched);
watchedWith2 = (EditText)findViewById(R.id.watchedWith);
watchedAt2 = (EditText)findViewById(R.id.watchedAt);
comment2 = (EditText)findViewById(R.id.comment);
if ((savedInstanceState != null) && (savedInstanceState.containsKey("TITLE_STATE_KEY")))
{
title2.setText(savedInstanceState.getString("TITLE_STATE_KEY"));
actors2.setText(savedInstanceState.getString("ACTORS_STATE_KEY"));
genre2.setText(savedInstanceState.getString("GENRE_STATE_KEY"));
comment2.setText(savedInstanceState.getString("GC_STATE_KEY"));
watchedWith2.setText(savedInstanceState.getString("WITH_STATE_KEY"));
watchedAt2.setText(savedInstanceState.getString("LOCATION_STATE_KEY"));
date2.setText(savedInstanceState.getString("DATE_STATE_KEY"));
rating2.setRating(savedInstanceState.getFloat("RATING_STATE_KEY"));
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.add_movie, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
switch(item.getItemId())
{
case R.id.action_settings:
return true;
case R.id.action_done:
done();
default:
return super.onOptionsItemSelected(item);
}
}
public void done()
{
EditText title = (EditText)findViewById(R.id.title);
String titleText = title.getText().toString();
EditText genre = (EditText)findViewById(R.id.genre);
String genreText = genre.getText().toString();
EditText actors = (EditText)findViewById(R.id.actors);
String actorsText = actors.getText().toString();
RatingBar rating = (RatingBar)findViewById(R.id.rating);
int ratingValue = Math.round(rating.getRating());
EditText date = (EditText)findViewById(R.id.dateWatched);
String dateWatched = date.getText().toString();
EditText watchedWith = (EditText)findViewById(R.id.watchedWith);
String watchedWithText = watchedWith.getText().toString();
EditText watchedAt = (EditText)findViewById(R.id.watchedAt);
String watchedAtText = watchedAt.getText().toString();
EditText comment = (EditText)findViewById(R.id.comment);
String commentText = comment.getText().toString();
Intent intent = new Intent(AddMovie.this, MainActivity.class);
intent.putExtra("titleText", titleText);
intent.putExtra("genreText", genreText);
intent.putExtra("actorsText", actorsText);
intent.putExtra("ratingValue", ratingValue);
intent.putExtra("dateWatched", dateWatched);
intent.putExtra("watchedWithText", watchedWithText);
intent.putExtra("watchedAtText", watchedAtText);
intent.putExtra("commentText", commentText);
setResult(RESULT_OK, intent);
finish();
}
#Override
public void onSaveInstanceState(Bundle saveInstanceState)
{
saveInstanceState.putString("TITLE_STATE_KEY", title2.getText().toString());
saveInstanceState.putString("GENRE_STATE_KEY", genre2.getText().toString());
saveInstanceState.putString("GC_STATE_KEY", comment2.getText().toString());
saveInstanceState.putString("DATE_STATE_KEY", date2.getText().toString());
saveInstanceState.putString("ACTORS_STATE_KEY", actors2.getText().toString());
saveInstanceState.putString("WITH_STATE_KEY", watchedWith2.getText().toString());
saveInstanceState.putString("LOCATION_STATE_KEY", watchedAt2.getText().toString());
saveInstanceState.putFloat("RATING_STATE_KEY", rating2.getRating());
super.onSaveInstanceState(saveInstanceState);
}
}
The basic is like this:
Create one Activity and 2 Fragments.
If something happens in FragmantA something should change in fragmentB right. So the Activity links Fragment A and B together. What do you need for that: an Interface.
So create an Interface with a method which takes the right properties (don't forget the datatype). Now you can implement the interface in your activity.
After this you should initialize the interface in FragmentA in the onActivityCreated method. Perform the changes and send the data to the interfacemethod in the Activity. Create a reference to FragmentB using the FragmentManager. Now you can send the data/changes to FragmentB.
I hope you understand this ;). cheers
I made a sample project that doesn't use ViewPager and all the weird stuff, just the link between Activity and Fragment here on Stack Overflow and the same thing on Code Review to demonstrate it, click either links to see the project.
I used this link to get started
http://www.techotopia.com/index.php/Using_Fragments_in_Android_-_A_Worked_Example
This guy uses 2 different types of listeners and takes in the user input on the first fragment. The 2nd fragment outputs the data!
Goodluck!

Categories

Resources