Use getVIew() to find fragment container Id in non static method - java

I am trying to use the following code
public int id=GeneralPreferenceFragment.getView().getParent().getId();
inside SettingAvtivity/MainActivity .
but it shows following error
Non-static method 'getView()' can not be referenced from a static Context
please help me resolving this issue
following is the method used
public void method1(View view)
{
Button bt1=(Button)findViewById(R.id.button);
bt1.setOnClickListener(new
View.OnClickListener() {
#Override
public void onClick(View view) {
// ViewGroup vg = (ViewGroup) mCurrentFragment.getView().getParent();
Toast.makeText(SettingsActivity.this,"Sound",Toast.LENGTH_SHORT).show();
DataSyncPreferenceFragment fragment;
GeneralPreferenceFragment fragment1;
GeneralPreferenceFragment frag1;
fragment= new DataSyncPreferenceFragment();
fragment1=new GeneralPreferenceFragment();
GeneralPreferenceFragment prefFragment = new GeneralPreferenceFragment();
int id = prefFragment.getView().getParent().getId();
FragmentManager fm=getFragmentManager();
FragmentTransaction ft=fm.beginTransaction();
ft.replace(R.id.layout_1id,fragment);
ft.remove(fragment1);
ft.add(R.id.layout_1id,fragment);
ft.addToBackStack(null);
ft.commit();
}
});
}
if i use an instance of General preferenceFragment then it shows
Cannot resolve getId();
code for header that links fragment-pref_header.xml
<preference-headers xmlns:android="http://schemas.android.com/apk/res/android">
<!-- These settings headers are only used on tablets. -->
<header
android:fragment="com.example.amit.check1.SettingsActivity$GeneralPreferenceFragment"
android:icon="#drawable/ic_info_black_24dp"
android:title="#string/pref_header_general"
android:id="#+id/id3"/>
<header
android:fragment="com.example.amit.check1.SettingsActivity$NotificationPreferenceFragment"
android:icon="#drawable/ic_notifications_black_24dp"
android:title="#string/pref_header_notifications" />
<header android:fragment="com.example.amit.check1.SettingsActivity$DataSyncPreferenceFragment"
android:icon="#drawable/ic_sync_black_24dp"
android:title="#string/pref_header_data_sync" />
</preference-headers>
SettingActivity.java
package com.example.amit.check1;
import android.annotation.TargetApi;
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.media.Ringtone;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.preference.ListPreference;
import android.preference.Preference;
import android.support.annotation.IdRes;
import android.support.v7.app.ActionBar;
import android.preference.PreferenceFragment;
import android.preference.PreferenceManager;
import android.preference.RingtonePreference;
import android.telecom.Call;
import android.text.TextUtils;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.Toast;
import java.util.List;
public class SettingsActivity extends AppCompatPreferenceActivity {
//private int mcontainerid;
private static Preference.OnPreferenceChangeListener sBindPreferenceSummaryToValueListener = new Preference.OnPreferenceChangeListener() {
#Override
public boolean onPreferenceChange(Preference preference, Object value) {
String stringValue = value.toString();
if (preference instanceof ListPreference) {
ListPreference listPreference = (ListPreference) preference;
int index = listPreference.findIndexOfValue(stringValue);
preference.setSummary(
index >= 0
? listPreference.getEntries()[index]
: null);
}
else if (preference instanceof RingtonePreference) {
if (TextUtils.isEmpty(stringValue)) {
preference.setSummary(R.string.pref_ringtone_silent);
} else {
Ringtone ringtone = RingtoneManager.getRingtone(
preference.getContext(), Uri.parse(stringValue));
if (ringtone == null) {
// Clear the summary if there was a lookup error.
preference.setSummary(null);
} else {
// Set the summary to reflect the new ringtone display
// name.
String name = ringtone.getTitle(preference.getContext());
preference.setSummary(name);
}
}
} else {
// For all other preferences, set the summary to the value's
// simple string representation.
preference.setSummary(stringValue);
}
return true;
}
};
private static boolean isXLargeTablet(Context context) {
return (context.getResources().getConfiguration().screenLayout
& Configuration.SCREENLAYOUT_SIZE_MASK) >= Configuration.SCREENLAYOUT_SIZE_XLARGE;
}
private static void bindPreferenceSummaryToValue(Preference preference) {
preference.setOnPreferenceChangeListener(sBindPreferenceSummaryToValueListener);
sBindPreferenceSummaryToValueListener.onPreferenceChange(preference,
PreferenceManager
.getDefaultSharedPreferences(preference.getContext())
.getString(preference.getKey(), ""));
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// int id=GeneralPreferenceFragment.getView().getParent().getId();
setupActionBar();
}
private void setupActionBar() {
ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
actionBar.setDisplayHomeAsUpEnabled(true);
}
}
#Override
public boolean onIsMultiPane() {
return isXLargeTablet(this);
}
#Override
#TargetApi(Build.VERSION_CODES.HONEYCOMB)
public void onBuildHeaders(List<Header> target) {
loadHeadersFromResource(R.xml.pref_headers, target);
}
protected boolean isValidFragment(String fragmentName) {
return PreferenceFragment.class.getName().equals(fragmentName)
|| GeneralPreferenceFragment.class.getName().equals(fragmentName)
|| DataSyncPreferenceFragment.class.getName().equals(fragmentName)
|| NotificationPreferenceFragment.class.getName().equals(fragmentName);
}
#TargetApi(Build.VERSION_CODES.HONEYCOMB)
public static class GeneralPreferenceFragment extends PreferenceFragment {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.pref_general);
Preference preference = findPreference("launchFragment");
preference.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
#Override
public boolean onPreferenceClick(Preference preference) {
// launch fragment
// addPreferencesFromResource(R.xml.pref_notification);
// Toast.makeText(getActivity(),"hellp",Toast.LENGTH_SHORT).show();
return false;
}
});
setHasOptionsMenu(true);
bindPreferenceSummaryToValue(findPreference("example_text"));
bindPreferenceSummaryToValue(findPreference("example_list"));
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == android.R.id.home) {
startActivity(new Intent(getActivity(), SettingsActivity.class));
return true;
}
return super.onOptionsItemSelected(item);
}
}
#TargetApi(Build.VERSION_CODES.HONEYCOMB)
public static class NotificationPreferenceFragment extends PreferenceFragment {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.pref_notification);
setHasOptionsMenu(true);
bindPreferenceSummaryToValue(findPreference("notifications_new_message_ringtone"));
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == android.R.id.home) {
startActivity(new Intent(getActivity(), SettingsActivity.class));
return true;
}
return super.onOptionsItemSelected(item);
}
}
#TargetApi(Build.VERSION_CODES.HONEYCOMB)
public static class DataSyncPreferenceFragment extends PreferenceFragment {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.pref_data_sync);
setHasOptionsMenu(true);
bindPreferenceSummaryToValue(findPreference("sync_frequency"));
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == android.R.id.home) {
startActivity(new Intent(getActivity(), SettingsActivity.class));
return true;
}
return super.onOptionsItemSelected(item);
}
}
public void method1(View view)
{
Button bt1=(Button)findViewById(R.id.button);
bt1.setOnClickListener(new
View.OnClickListener() {
#Override
public void onClick(View view) {
// ViewGroup vg = (ViewGroup) mCurrentFragment.getView().getParent();
Toast.makeText(SettingsActivity.this,"Sound",Toast.LENGTH_SHORT).show();
DataSyncPreferenceFragment fragment;
GeneralPreferenceFragment fragment1;
GeneralPreferenceFragment frag1;
fragment= new DataSyncPreferenceFragment();
fragment1=new GeneralPreferenceFragment();
GeneralPreferenceFragment prefFragment = new GeneralPreferenceFragment();
// int id = prefFragment.getView().getId();
//String st=Integer.toString(id);
//Toast.makeText(SettingsActivity.this,st,Toast.LENGTH_SHORT).show();
// int id = frag1.getView().getParent().getId();
//ViewGroup vg = (ViewGroup) findViewById(id);
FragmentManager fm=getFragmentManager();
FragmentTransaction ft=fm.beginTransaction();
//ft.add(1234,fragment,"f1");
//int id=fragment.getId();
//String s1=Integer.toString(id);
// Toast.makeText(SettingsActivity.this,s1,Toast.LENGTH_SHORT).show();
// ft.add(R.id.layout_1id,fragment);
//ft.add() will add fragment in previous fragment to
// the previous fragment
// ft.replace(R.id.layout_1id,fragment);
// ft.hide(fragment1);
//ft.hide() is used to hide an fragment;
// ft.detach(fragment1);
//detach method removes the fragment from UI.but it can be reused with the help
//of attach method.
//Toast.makeText(SettingsActivity.this,"removed frag1",Toast.LENGTH_SHORT).show();
//ft.show(fragment);
ft.remove(fragment1);
//remove method removes the fragment from UI;you can reuse fragment again,for reusing
//again you would have to use add method
ft.add(R.id.layout_1id,fragment);
ft.addToBackStack(null);
ft.commit();
}
});
}
}

You need to call method getView() from instance of you class GeneralPreferenceFragment. I.e:
GeneralPreferenceFragment prefFragment = new GeneralPreferenceFragment();
// ... some business logic
public int id = prefFragment.getView().getParent().getId();

Related

What should the container be when FragmentPagerAdapter is used

So in NameList where it says "fragmentTransaction.add(android.R.id.content, fragment2, "login").commit();" I need to find the container of NameList when I try R.id.container a blank white screen appears. What should I put instead of android.R.id.content in this case?
NameList.java
package com.drdc1.medic;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.content.Context;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
/**
* A simple {#link Fragment} subclass.
*/
public class NameList extends Fragment implements DataObserver {
private SoldierListAdapter adapter;
private HomeActivity homeActivity;
private ArrayList<Soldier> soldiers = new ArrayList<>();
public NameList() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_name_list, container, false);
homeActivity = (HomeActivity) getActivity();
homeActivity.registerFragment(this);
final ListView listView = (ListView) rootView.findViewById(R.id.soldierList);
addListHeader(listView);
DataManager dbManager = ((AppContext) getActivity().getApplication()).getDataManager();
soldiers = dbManager.getActiveSoldier();
adapter = new SoldierListAdapter(getContext(), soldiers);
listView.setAdapter(adapter);
TextView nameHeader = (TextView) rootView.findViewById(R.id.name_header);
nameHeader.setOnClickListener(new ClickToSort());
TextView hrHeader = (TextView) rootView.findViewById(R.id.hr_header);
hrHeader.setOnClickListener(new ClickToSort());
TextView brHeader = (TextView) rootView.findViewById(R.id.br_header);
brHeader.setOnClickListener(new ClickToSort());
TextView skinTmpHeader = (TextView) rootView.findViewById(R.id.skin_tmp_header);
skinTmpHeader.setOnClickListener(new ClickToSort());
TextView core_tmp_header = (TextView) rootView.findViewById(R.id.core_tmp_header);
core_tmp_header.setOnClickListener(new ClickToSort());
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//TODO When item clicked, write code here
String idsol = null;
if (((Soldier) listView.getAdapter().getItem(position)) != null) {
idsol = ((Soldier) listView.getAdapter().getItem(position)).getId();
}
android.support.v4.app.FragmentTransaction fragmentTransaction =
getFragmentManager().beginTransaction();
Bundle bundle = new Bundle();
if (idsol != null){
bundle.putString("id", idsol); // Put anything what you want
}
IndividualSoldierTab fragment2 = new IndividualSoldierTab();
fragment2.setArguments(bundle);
fragmentTransaction.add(android.R.id.content, fragment2, "login").commit();
// getFragmentManager()
// .beginTransaction()
// .replace(R.id.container, fragment2)
// .commit();
}
});
return rootView;
}
#Override
public void onPause() {
super.onPause();
homeActivity.registerFragment(this);
}
#Override
public void onResume() {
super.onResume();
homeActivity.registerFragment(this);
}
#Override
public void onDestroyView() {
homeActivity.unregisterFragment(this);
super.onDestroyView();
}
#Override
public void update(Map data) {
Boolean soldierInTheList = false;
for (Soldier s : soldiers) {
if (data.get("ID").equals(s.getId())) {
s.setPhysioData(data);
soldierInTheList = true;
}
}
if (!soldierInTheList) {
Soldier newSol = new Soldier((String) data.get("name"), (String) data.get("ID"));
newSol.setPhysioData(data);
soldiers.add(newSol);
}
adapter.notifyDataSetChanged();
}
private void addListHeader(ListView lv) {
View headerView =
LayoutInflater.from(getContext()).inflate(R.layout.list_header, lv, false);
lv.addHeaderView(headerView);
}
private class SoldierListAdapter extends ArrayAdapter<Soldier> {
private final ArrayList<Soldier> soldiers;
private String sortedBy = "";
// the soldier list is only sorted by 1 attribute at a time. don't overthink about stable sorting
public SoldierListAdapter(Context context, ArrayList<Soldier> soldiers) {
super(context, R.layout.list_item, soldiers);
this.soldiers = soldiers;
}
public String getSortedBy() {
return sortedBy;
}
/***
* When the user click the header when soldiers are already sorted, reverse the order
*/
public void reverse() {
Collections.reverse(soldiers);
}
/***
* #param x "Sort by x" Sortby is an enum
*/
public void sort(SortBy x) {
switch (x) {
case NAME:
this.sort(new OrderByName());
sortedBy = "NAME";
break;
case HR:
this.sort(new OrderByHR());
sortedBy = "HR";
break;
case BR:
this.sort(new OrderByBR());
sortedBy = "BR";
break;
case SKINTMP:
this.sort(new OrderBySkinTmp());
sortedBy = "SKINTMP";
break;
case CORETMP:
this.sort(new OrderByCoreTmp());
sortedBy = "CORETMP";
break;
default:
}
}
#NonNull
#Override
public View getView(int position, View v, ViewGroup parent) {
// Get the data item for this position
Soldier soldier = getItem(position);
// Check if an existing view is being reused, otherwise inflate the view
if (v == null) {
v = LayoutInflater.from(getContext())
.inflate(R.layout.list_item, parent, false);
}
TextView name = (TextView) v.findViewById(R.id.name);
// name.setOnClickListener(new setFragmentTransition());
name.setText(soldier.getName());
ImageView overall = (ImageView) v.findViewById(R.id.overal_status);
switch (soldier.getOverallStatus()) {
case "RED":
overall.setImageResource(R.drawable.red);
break;
case "GREEN":
overall.setImageResource(R.drawable.green);
break;
case "YELLOW":
overall.setImageResource(R.drawable.yellow);
break;
default:
break;
}
if (soldier.getBodyOrientation() != null && !soldier.getBodyOrientation().isEmpty()) {
ImageView bodyPos = (ImageView) v.findViewById(R.id.body_position);
bodyPos.setImageResource(R.drawable.body);
switch (soldier.getBodyOrientation()) {
case "UP":
break;
case "DOWN":
bodyPos.setRotation(180);
break;
case "LEFT":
bodyPos.setRotation(270);
break;
case "RIGHT":
bodyPos.setRotation(90);
break;
default:
break;
}
}
String currentHR = soldier.getHeartRate();
String lastHR = soldier.getLastHeartRate();
if (!currentHR.equals("")) {
TextView heartRate = (TextView) v.findViewById(R.id.hr_text);
ImageView arrow = (ImageView) v.findViewById(R.id.hr_img);
if (!lastHR.equals("")) {
if (Integer.parseInt(currentHR) > Integer.parseInt(lastHR)) {
arrow.setImageResource(R.drawable.up_arrow);
heartRate.setTextColor(Color.RED);
} else if (Integer.parseInt(currentHR) < Integer.parseInt(lastHR)) {
arrow.setImageResource(R.drawable.down_arrow);
heartRate.setTextColor(Color.YELLOW);
} else {
arrow.setImageResource(0);
heartRate.setTextColor(Color.BLACK);
}
}
heartRate.setText(currentHR);
}
//TODO replace image for down_arrow color not right
String currentBR = soldier.getBreathingRate();
String lastBR = soldier.getLastBreathingRate();
if (!currentBR.equals("")) {
TextView breathingRate = (TextView) v.findViewById(R.id.br_text);
ImageView arrow = (ImageView) v.findViewById(R.id.br_img);
if (!lastBR.equals("")) {
if (Integer.parseInt(currentBR) > Integer.parseInt(lastBR)) {
arrow.setImageResource(R.drawable.up_arrow);
breathingRate.setTextColor(Color.RED);
} else if (Integer.parseInt(currentBR) < Integer.parseInt(lastBR)) {
arrow.setImageResource(R.drawable.down_arrow);
breathingRate.setTextColor(Color.YELLOW);
} else {
arrow.setImageResource(0);
breathingRate.setTextColor(Color.BLACK);
}
}
breathingRate.setText(currentBR);
}
String currentCoreTmp = soldier.getCoreTmp();
String lastCoreTmp = soldier.getLastCoreTmp();
if (!currentCoreTmp.equals("")) {
TextView coreTmp = (TextView) v.findViewById(R.id.core_tmp_text);
ImageView arrow = (ImageView) v.findViewById(R.id.core_tmp_img);
if (!lastCoreTmp.equals("")) {
if (Integer.parseInt(currentCoreTmp) > Integer.parseInt(lastCoreTmp)) {
arrow.setImageResource(R.drawable.up_arrow);
coreTmp.setTextColor(Color.RED);
} else if (Integer.parseInt(currentCoreTmp) < Integer.parseInt(lastCoreTmp)) {
arrow.setImageResource(R.drawable.down_arrow);
coreTmp.setTextColor(Color.YELLOW);
} else {
arrow.setImageResource(0);
coreTmp.setTextColor(Color.BLACK);
}
}
coreTmp.setText(currentCoreTmp);
}
String currentSkinTmp = soldier.getSkinTmp();
String lastSkinTmp = soldier.getLastSkinTmp();
if (!currentSkinTmp.equals("")) {
TextView skinTmp = (TextView) v.findViewById(R.id.skin_tmp_text);
ImageView arrow = (ImageView) v.findViewById(R.id.skin_tmp_img);
if (!lastSkinTmp.equals("")) {
if (Integer.parseInt(currentSkinTmp) > Integer.parseInt(lastSkinTmp)) {
arrow.setImageResource(R.drawable.up_arrow);
skinTmp.setTextColor(Color.RED);
} else if (Integer.parseInt(currentSkinTmp) < Integer.parseInt(lastSkinTmp)) {
arrow.setImageResource(R.drawable.down_arrow);
skinTmp.setTextColor(Color.YELLOW);
} else {
arrow.setImageResource(0);
skinTmp.setTextColor(Color.BLACK);
}
}
skinTmp.setText(currentSkinTmp);
}
//TextView tvHome = (TextView) v.findViewById(R.id.tvHome);
// Populate the data into the template view using the data object
// Return the completed view to render on screen
return v;
}
}
private class ClickToSort implements View.OnClickListener {
#Override
public void onClick(View v) {
String sortBy = (String) ((TextView) v).getText();
switch (sortBy.toLowerCase()) {
case "name":
if (adapter.getSortedBy().equals("NAME")) {
adapter.reverse();
} else {
adapter.sort(SortBy.NAME);
}
break;
case "hr":
if (adapter.getSortedBy().equals("HR")) {
adapter.reverse();
} else {
adapter.sort(SortBy.HR);
}
break;
case "br":
if (adapter.getSortedBy().equals("BR")) {
adapter.reverse();
} else {
adapter.sort(SortBy.BR);
}
break;
case "skintmp":
if (adapter.getSortedBy().equals("SKINTMP")) {
adapter.reverse();
} else {
adapter.sort(SortBy.SKINTMP);
}
break;
case "coretmp":
if (adapter.getSortedBy().equals("CORETMP")) {
adapter.reverse();
} else {
adapter.sort(SortBy.CORETMP);
}
break;
default:
}
adapter.notifyDataSetChanged();
}
}
/************************************************************************
* Comparator classes to support different ordering of soldiers
*************************************************************************/
private enum SortBy {
NAME, HR, BR, SKINTMP, CORETMP
}
private static class OrderByName implements Comparator<Soldier> {
#Override
public int compare(Soldier s1, Soldier s2) {
return s1.getName().compareTo(s2.getName());
}
}
private static class OrderByHR implements Comparator<Soldier> {
#Override
public int compare(Soldier s1, Soldier s2) {
return Integer.parseInt(s1.getHeartRate().equals("") ? "0" : s1.getHeartRate())
- Integer.parseInt(s2.getHeartRate().equals("") ? "0" : s2.getHeartRate());
}
}
private static class OrderByBR implements Comparator<Soldier> {
#Override
public int compare(Soldier s1, Soldier s2) {
return Integer.valueOf(s1.getBreathingRate().equals("") ? "0" : s1.getBreathingRate())
.compareTo(Integer.valueOf(
s2.getBreathingRate().equals("") ? "0" : s2.getBreathingRate()));
}
}
private static class OrderBySkinTmp implements Comparator<Soldier> {
#Override
public int compare(Soldier s1, Soldier s2) {
return Integer.valueOf(s1.getSkinTmp().equals("") ? "0" : s1.getSkinTmp())
.compareTo(Integer.valueOf(s2.getSkinTmp().equals("") ? "0" : s2.getSkinTmp()));
}
}
private static class OrderByCoreTmp implements Comparator<Soldier> {
#Override
public int compare(Soldier s1, Soldier s2) {
return Integer.valueOf(s1.getCoreTmp().equals("") ? "0" : s1.getCoreTmp())
.compareTo(Integer.valueOf(s2.getCoreTmp().equals("") ? "0" : s2.getCoreTmp()));
}
}
}
HomeActivity.java
package com.drdc1.medic;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.RequiresApi;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
// This is the home page of the tab application.
public class HomeActivity extends AppCompatActivity implements FragmentDataManager {
private SectionsPagerAdapter mSectionsPagerAdapter;
private DataReceiver dataReceiver;
private ArrayList<DataObserver> fragmentlist;
static private HashMap data; //one data shared by all fragments
/**
* The {#link ViewPager} that will host the section contents.
*/
private ViewPager mViewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
startBackgroundServices();
setContentView(R.layout.activity_home);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
// Create the adapter that will return a fragment for each of the three
// primary sections of the activity.
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
//register intent filter for LocalBroadbast Manager
IntentFilter PDAMESSAGE = new IntentFilter("PDAMessage");
dataReceiver = new DataReceiver();
LocalBroadcastManager.getInstance(this).registerReceiver(dataReceiver, PDAMESSAGE);
data = new HashMap();
fragmentlist = new ArrayList<>();
// Set up the ViewPager with the sections adapter.
mViewPager = (ViewPager) findViewById(R.id.container);
mViewPager.setAdapter(mSectionsPagerAdapter);
mViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset,
int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
}
#Override
public void onPageScrollStateChanged(int state) {
}
});
TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(mViewPager);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
}
#Override
public void registerFragment(DataObserver o) {
if (!fragmentlist.contains(o))
fragmentlist.add(o);
}
#Override
public void unregisterFragment(DataObserver o) {
if (fragmentlist.contains(o)) {
int observerIndex = fragmentlist.indexOf(o);
fragmentlist.remove(observerIndex);
}
}
#RequiresApi(api = Build.VERSION_CODES.M)
#Override
public void notifyObserver(Map data) {
for (DataObserver observer : fragmentlist) {
observer.update(data);
}
}
class DataReceiver extends BroadcastReceiver {
#RequiresApi(api = Build.VERSION_CODES.M)
#Override
public void onReceive(Context context, Intent intent) {
data.put("bodypos", intent.getStringExtra("bodypos"));
data.put("overall", intent.getStringExtra("overall"));
data.put("coreTemp", intent.getStringExtra("coreTmp"));
data.put("skinTemp", intent.getStringExtra("skinTmp"));
data.put("br", intent.getStringExtra("br"));
data.put("hr", intent.getStringExtra("hr"));
data.put("ID",intent.getStringExtra("ID"));
data.put("name",intent.getStringExtra("name"));
notifyObserver(data);
}
}
/**
* 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";
public PlaceholderFragment() {
}
/**
* 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;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_home, container, false);
TextView textView = (TextView) rootView.findViewById(R.id.section_label);
textView.setText(
getString(R.string.section_format, getArguments().getInt(ARG_SECTION_NUMBER)));
return rootView;
}
}
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
SquadStatus tab1 = new SquadStatus();
return tab1;
case 1:
NameList tab2 = new NameList();
return tab2;
case 2:
IndividualSoldierTab tab3 = new IndividualSoldierTab();
return tab3;
case 3:
TreatmentScreenTab tab4 = new TreatmentScreenTab();
return tab4;
default:
return null;
}
}
#Override
public int getCount() {
// Show 4 total pages.
return 4;
}
#Override
public CharSequence getPageTitle(int position) {
switch (position) {
case 0:
return "Squad Status";
case 1:
return "Name List";
case 2:
return "Individual Soldier";
case 3:
return "Treatment Screen";
}
return null;
}
}
private void startBackgroundServices() {
Intent Serviceintent = new Intent();
Serviceintent.setClass(this, BackgroundServer.class);
startService(Serviceintent);
Intent sleepAlgo = new Intent();
sleepAlgo.setClass(this, BackgroundSleepAlgo.class);
startService(sleepAlgo);
Intent wellnessAlgo = new Intent();
wellnessAlgo.setClass(this, BackgroundWellnessAlgo.class);
startService(wellnessAlgo);
}
public void callHelp(View v) {
Intent callhelp = new Intent(HomeActivity.this, HelpActivity.class);
startActivity(callhelp);
}
}
What should the container?
You can simply use a FrameLayout as the container layout and add fragments dynamically.

Android fragments must be static

I've got this error, but I don't know how to resolve this error.
Error: Fragments should be static such that they can be re-instantiated by the system, and anonymous classes are not static [ValidFragment]
Please help me if you know how to solve
This is the MainActivity.java
import android.annotation.TargetApi;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.res.ColorStateList;
import android.content.res.Configuration;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.NavigationView;
import android.support.design.widget.Snackbar;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v4.view.GravityCompat;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GoogleApiAvailability;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity {
private DrawerLayout mDrawerLayout;
private String keyPref = "test";
private SharedPreferences pref;
private static SharedPreferences.Editor editor;
private static ViewPager view;
private FoodListFragment makanan = new FoodListFragment() {
#Override
public void doRefresh() {
updateData();
}
};
private FoodListFragment minuman = new FoodListFragment() {
#Override
public void doRefresh() {
updateData();
}
};
private FoodListFragment snack = new FoodListFragment() {
#Override
public void doRefresh() {
updateData();
}
};
private Adapter adapter = new Adapter(getSupportFragmentManager());
private static final int PLAY_SERVICES_RESOLUTION_REQUEST = 4343;
private BroadcastReceiver mRegistrationBroadcastReceiver;
private static ProgressDialog loading;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
pref = getApplicationContext().getSharedPreferences(keyPref, MODE_PRIVATE);
editor = pref.edit();
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
final ActionBar ab = getSupportActionBar();
ab.setHomeAsUpIndicator(R.drawable.ic_menu);
ab.setDisplayHomeAsUpEnabled(true);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
if (navigationView != null) {
setupDrawerContent(navigationView);
}
ViewPager viewPager = (ViewPager) findViewById(R.id.viewpager);
if (viewPager != null) {
setupViewPager(viewPager);
}
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setBackgroundTintList(ColorStateList.valueOf(Color.rgb(183,28,28)));
fab.setOnClickListener(new View.OnClickListener() {
#TargetApi(Build.VERSION_CODES.LOLLIPOP)
#Override
public void onClick(View view) {
Intent intent = new Intent(getApplicationContext(), CartActivity.class);
MainActivity.this.startActivity(intent);
}
});
TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(viewPager);
DBHelper db = new DBHelper(this);
mRegistrationBroadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
//mRegistrationProgressBar.setVisibility(ProgressBar.GONE);
SharedPreferences sharedPreferences =
PreferenceManager.getDefaultSharedPreferences(context);
boolean sentToken = sharedPreferences
.getBoolean(QuickstartPreferences.SENT_TOKEN_TO_SERVER, false);
}
};
loading = new ProgressDialog(this);
loading.setMessage("Loading");
loading.setTitle("Menu");
updateData();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
return true;
}
#Override
protected void onPause() {
super.onPause();
LocalBroadcastManager.getInstance(this).unregisterReceiver(mRegistrationBroadcastReceiver);
}
#Override
protected void onResume() {
super.onResume();
LocalBroadcastManager.getInstance(this).registerReceiver(mRegistrationBroadcastReceiver,
new IntentFilter(QuickstartPreferences.REGISTRATION_COMPLETE));
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
mDrawerLayout.openDrawer(GravityCompat.START);
return true;
}
return super.onOptionsItemSelected(item);
}
public void updateData() {
ServerHelper server = new ServerHelper() {
#Override
public void onStart() {
loading.show();
}
#Override
public void onFinish() {
loading.dismiss();
}
#Override
public void onSuccess(int statusCode, String response) {
try {
editor.putString("response", response);
editor.commit();
makanan.clearFood();
minuman.clearFood();
snack.clearFood();
JSONArray foods = new JSONArray(response);
for (int i = 0; i <= foods.length()-1; i++) {
JSONObject object = foods.getJSONObject(i);
JSONObject subs = object.getJSONObject("SubCategory");
FoodCategory addFood = new FoodCategory(subs.getString("name"), subs.getString("photo"));
if (subs.getString("categories_id").contains("1")) {
makanan.addFood(addFood);
} else if (subs.getString("categories_id").contains("2")) {
minuman.addFood(addFood);
} else if (subs.getString("categories_id").contains("3")) {
snack.addFood(addFood);
}
}
makanan.doneRefresh();
minuman.doneRefresh();
snack.doneRefresh();
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(view.getContext(),"Terjadi masalah koneksi, silahkan coba kembali", Toast.LENGTH_LONG).show();
}
loading.dismiss();
}
#Override
public void onFailure(int statusCode, String response) {
if (view != null) {
Snackbar.make(view, "Terjadi Masalah Koneksi", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
} else {
Toast.makeText(MainActivity.this,"Terjadi Masalah Koneksi", Toast.LENGTH_LONG).show();
}
makanan.doneRefresh();
minuman.doneRefresh();
snack.doneRefresh();
loading.dismiss();
}
};
server.getAllSubs();
}
private void setupViewPager(ViewPager viewPager) {
makanan.setRetainInstance(true);
minuman.setRetainInstance(true);
snack.setRetainInstance(true);
adapter.addFragment(makanan, "Makanan");
adapter.addFragment(minuman, "Minuman");
adapter.addFragment(snack, "Snack");
viewPager.setAdapter(adapter);
updateData();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
}
private void setupDrawerContent(final NavigationView navigationView) {
View header = navigationView.getHeaderView(0);
TextView username = (TextView) header.findViewById(R.id.main_username);
DBHelper db = new DBHelper(this);
username.setText(db.getUsers().getName());
navigationView.setNavigationItemSelectedListener(
new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
switch (menuItem.getItemId()) {
case R.id.nav_home: {
menuItem.setChecked(true);
break;
}
case R.id.nav_order: {
navigationView.getMenu().getItem(0).setChecked(true);
Intent order = new Intent(MainActivity.this, OrderActivity.class);
startActivity(order);
break;
}
case R.id.nav_cart: {
navigationView.getMenu().getItem(0).setChecked(true);
Intent cart = new Intent(MainActivity.this, CartActivity.class);
startActivity(cart);
break;
}
case R.id.nav_logout: {
AlertDialog.Builder dialog = new AlertDialog.Builder(MainActivity.this);
dialog.setMessage("Anda yakin ingin logout akun anda ?");
dialog.setNegativeButton("Batal",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface arg0, int arg1) {
}
});
dialog.setPositiveButton("Keluar",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface arg0, int arg1) {
DBHelper logout = new DBHelper(MainActivity.this);
logout.clearSPConfig();
LocalBroadcastManager.getInstance(MainActivity.this).unregisterReceiver(mRegistrationBroadcastReceiver);
Intent goLogin = new Intent(MainActivity.this, LoginMainActivity.class);
startActivity(goLogin);
}
});
AlertDialog alertDialog = dialog.create();
alertDialog.show();
}
}
mDrawerLayout.closeDrawers();
return true;
}
});
}
public static class Adapter extends FragmentPagerAdapter {
private final List<Fragment> mFragments = new ArrayList<>();
private final List<String> mFragmentTitles = new ArrayList<>();
public Adapter(FragmentManager fm) {
super(fm);
}
public void addFragment(Fragment fragment, String title) {
mFragments.add(fragment);
mFragmentTitles.add(title);
}
#Override
public Fragment getItem(int position) {
return mFragments.get(position);
}
#Override
public int getCount() {
return mFragments.size();
}
#Override
public CharSequence getPageTitle(int position) {
return mFragmentTitles.get(position);
}
}
}
and this is the fragment class FoodListFragment.java
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.annotation.UiThread;
import android.support.design.widget.Snackbar;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.InflateException;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
public abstract class FoodListFragment extends Fragment {
private ArrayList<FoodCategory> foodList = new ArrayList<FoodCategory>();
private RecyclerView rv;
private RecyclerViewAdapter adapter;
private SwipeRefreshLayout swipeLayout;
private View view;
FoodListFragment() {
}
public void addFoods(ArrayList<FoodCategory> food) {
foodList = food;
if (adapter != null) {
adapter.notifyDataSetChanged();
}
}
public void addFood(FoodCategory food) {
foodList.add(food);
if (adapter != null) {
adapter.notifyDataSetChanged();
}
}
public void clearFood() {
foodList.clear();
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// final RecyclerView rv = (RecyclerView) inflater.inflate(R.layout.fragment_food_list, container, false);
view = inflater.inflate(R.layout.fragment_food_list, null);
swipeLayout = (SwipeRefreshLayout) view.findViewById(R.id.swipe_container);
swipeLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
doRefresh();
}
});
swipeLayout.setColorSchemeColors(Color.RED, Color.GRAY);
RecyclerView rv = (RecyclerView) view.findViewById(R.id.recyclerview);
setupRecyclerView(rv);
return view;
}
private void setupRecyclerView(final RecyclerView recyclerView) {
//recyclerView.setLayoutManager(new LinearLayoutManager(recyclerView.getContext()));
recyclerView.setLayoutManager(new GridLayoutManager(recyclerView.getContext(), 2));
recyclerView.setHasFixedSize(true);
setRetainInstance(true);
adapter = new RecyclerViewAdapter(getActivity(),foodList);
recyclerView.setAdapter(adapter);
}
public void doneRefresh(){
if (swipeLayout != null) {
swipeLayout.setRefreshing(false);
}
}
public abstract void doRefresh();
}
You are declaring your Fragment as abstract class. Abstract class can't be instantiated. It can be used only as a base class. The way you are trying to use it (anonymous class) is not possible in Android framework. A Fragment class must be a subclass of Fragment (or an existing subclass of it) and concrete.
Remove abstract keyword
public class FoodListFragment extends Fragment {
Things your are trying to achieve with
public abstract void doRefresh();
should be done using an interface.

Navigation drawer fragment class not showing up

My navigation drawer only show the first fragment class and 1 other class.I have 8 fragment class for menu in my drawer. When I click the other fragment class, it will be blank.
Here is the NavigationDrawerFragment.java :
import android.app.Activity;
import android.app.Fragment;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.graphics.BitmapShader;
import android.graphics.Canvas;
import android.graphics.ColorFilter;
import android.graphics.Paint;
import android.graphics.PixelFormat;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.Shader;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import java.util.ArrayList;
import java.util.List;
/**
* Fragment used for managing interactions for and presentation of a navigation drawer.
* See the <a href="https://developer.android.com/design/patterns/navigation-drawer.html#Interaction">
* design guidelines</a> for a complete explanation of the behaviors implemented here.
*/
public class NavigationDrawerFragment extends Fragment implements NavigationDrawerCallbacks {
/**
* Remember the position of the selected item.
*/
private static final String STATE_SELECTED_POSITION = "selected_navigation_drawer_position";
/**
* Per the design guidelines, you should show the drawer on launch until the user manually
* expands it. This shared preference tracks this.
*/
private static final String PREF_USER_LEARNED_DRAWER = "navigation_drawer_learned";
/**
* A pointer to the current callbacks instance (the Activity).
*/
private NavigationDrawerCallbacks mCallbacks;
/**
* Helper component that ties the action bar to the navigation drawer.
*/
private ActionBarDrawerToggle mActionBarDrawerToggle;
private DrawerLayout mDrawerLayout;
public RecyclerView mDrawerList;
private View mFragmentContainerView;
private int mCurrentSelectedPosition = 0;
private boolean mFromSavedInstanceState;
private boolean mUserLearnedDrawer;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Read in the flag indicating whether or not the user has demonstrated awareness of the
// drawer. See PREF_USER_LEARNED_DRAWER for details.
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(getActivity());
mUserLearnedDrawer = sp.getBoolean(PREF_USER_LEARNED_DRAWER, false);
if (savedInstanceState != null) {
mCurrentSelectedPosition = savedInstanceState.getInt(STATE_SELECTED_POSITION);
mFromSavedInstanceState = true;
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_navigation_drawer, container, false);
mDrawerList = (RecyclerView) view.findViewById(R.id.drawerList);
LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
mDrawerList.setLayoutManager(layoutManager);
mDrawerList.setHasFixedSize(true);
final List<NavigationItem> navigationItems = getMenu();
NavigationDrawerAdapter adapter = new NavigationDrawerAdapter(navigationItems);
adapter.setNavigationDrawerCallbacks(this);
mDrawerList.setAdapter(adapter);
selectItem(mCurrentSelectedPosition);
return view;
}
public boolean isDrawerOpen() {
return mDrawerLayout != null && mDrawerLayout.isDrawerOpen(mFragmentContainerView);
}
public ActionBarDrawerToggle getActionBarDrawerToggle() {
return mActionBarDrawerToggle;
}
public DrawerLayout getDrawerLayout() {
return mDrawerLayout;
}
#Override
public void onNavigationDrawerItemSelected(int position) {
selectItem(position);
}
public List<NavigationItem> getMenu() {
List<NavigationItem> items = new ArrayList<NavigationItem>();
items.add(new NavigationItem(getString(R.string.Home), getResources().getDrawable(R.drawable.ico_home)));
items.add(new NavigationItem(getString(R.string.Map), getResources().getDrawable(R.drawable.ico_map)));
items.add(new NavigationItem(getString(R.string.Departments), getResources().getDrawable(R.drawable.ico_dpt)));
items.add(new NavigationItem(getString(R.string.Units), getResources().getDrawable(R.drawable.ico_unit)));
items.add(new NavigationItem(getString(R.string.Gallery), getResources().getDrawable(R.drawable.ico_gallery)));
items.add(new NavigationItem(getString(R.string.AboutPSIS), getResources().getDrawable(R.drawable.ico_about)));
items.add(new NavigationItem(getString(R.string.Help), getResources().getDrawable(R.drawable.ico_help)));
items.add(new NavigationItem(getString(R.string.Credits), getResources().getDrawable(R.drawable.ico_credit)));
return items;
}
/**
* Users of this fragment must call this method to set up the navigation drawer interactions.
*
* #param fragmentId The android:id of this fragment in its activity's layout.
* #param drawerLayout The DrawerLayout containing this fragment's UI.
* #param toolbar The Toolbar of the activity.
*/
public void setup(int fragmentId, DrawerLayout drawerLayout, Toolbar toolbar) {
mFragmentContainerView = (View) getActivity().findViewById(fragmentId).getParent();
mDrawerLayout = drawerLayout;
mDrawerLayout.setStatusBarBackgroundColor(getResources().getColor(R.color.myPrimaryDarkColor));
mActionBarDrawerToggle = new ActionBarDrawerToggle(getActivity(), mDrawerLayout, toolbar, R.string.drawer_open, R.string.drawer_close) {
#Override
public void onDrawerClosed(View drawerView) {
super.onDrawerClosed(drawerView);
if (!isAdded()) return;
getActivity().invalidateOptionsMenu(); // calls onPrepareOptionsMenu()
}
#Override
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
if (!isAdded()) return;
if (!mUserLearnedDrawer) {
mUserLearnedDrawer = true;
SharedPreferences sp = PreferenceManager
.getDefaultSharedPreferences(getActivity());
sp.edit().putBoolean(PREF_USER_LEARNED_DRAWER, true).apply();
}
getActivity().invalidateOptionsMenu(); // calls onPrepareOptionsMenu()
}
};
// If the user hasn't 'learned' about the drawer, open it to introduce them to the drawer,
// per the navigation drawer design guidelines.
if (!mUserLearnedDrawer && !mFromSavedInstanceState) {
mDrawerLayout.openDrawer(mFragmentContainerView);
}
// Defer code dependent on restoration of previous instance state.
mDrawerLayout.post(new Runnable() {
#Override
public void run() {
mActionBarDrawerToggle.syncState();
}
});
mDrawerLayout.setDrawerListener(mActionBarDrawerToggle);
}
private void selectItem(int position) {
mCurrentSelectedPosition = position;
if (mDrawerLayout != null) {
mDrawerLayout.closeDrawer(mFragmentContainerView);
}
if (mCallbacks != null) {
mCallbacks.onNavigationDrawerItemSelected(position);
}
((NavigationDrawerAdapter) mDrawerList.getAdapter()).selectPosition(position);
}
public void openDrawer() {
mDrawerLayout.openDrawer(mFragmentContainerView);
}
public void closeDrawer() {
mDrawerLayout.closeDrawer(mFragmentContainerView);
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
mCallbacks = (NavigationDrawerCallbacks) activity;
} catch (ClassCastException e) {
throw new ClassCastException("Activity must implement NavigationDrawerCallbacks.");
}
}
#Override
public void onDetach() {
super.onDetach();
mCallbacks = null;
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt(STATE_SELECTED_POSITION, mCurrentSelectedPosition);
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
// Forward the new configuration the drawer toggle component.
mActionBarDrawerToggle.onConfigurationChanged(newConfig);
}
/*
public void setUserData(String user, String email, Bitmap avatar) {
ImageView avatarContainer = (ImageView) mFragmentContainerView.findViewById(R.id.imgAvatar);
((TextView) mFragmentContainerView.findViewById(R.id.txtUserEmail)).setText(email);
((TextView) mFragmentContainerView.findViewById(R.id.txtUsername)).setText(user);
avatarContainer.setImageDrawable(new RoundImage(avatar));
}
*/
public View getGoogleDrawer() {
return mFragmentContainerView.findViewById(R.id.googleDrawer);
}
public static class RoundImage extends Drawable {
private final Bitmap mBitmap;
private final Paint mPaint;
private final RectF mRectF;
private final int mBitmapWidth;
private final int mBitmapHeight;
public RoundImage(Bitmap bitmap) {
mBitmap = bitmap;
mRectF = new RectF();
mPaint = new Paint();
mPaint.setAntiAlias(true);
mPaint.setDither(true);
final BitmapShader shader = new BitmapShader(bitmap, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP);
mPaint.setShader(shader);
mBitmapWidth = mBitmap.getWidth();
mBitmapHeight = mBitmap.getHeight();
}
#Override
public void draw(Canvas canvas) {
canvas.drawOval(mRectF, mPaint);
}
#Override
protected void onBoundsChange(Rect bounds) {
super.onBoundsChange(bounds);
mRectF.set(bounds);
}
#Override
public void setAlpha(int alpha) {
if (mPaint.getAlpha() != alpha) {
mPaint.setAlpha(alpha);
invalidateSelf();
}
}
#Override
public void setColorFilter(ColorFilter cf) {
mPaint.setColorFilter(cf);
}
#Override
public int getOpacity() {
return PixelFormat.TRANSLUCENT;
}
#Override
public int getIntrinsicWidth() {
return mBitmapWidth;
}
#Override
public int getIntrinsicHeight() {
return mBitmapHeight;
}
public void setAntiAlias(boolean aa) {
mPaint.setAntiAlias(aa);
invalidateSelf();
}
#Override
public void setFilterBitmap(boolean filter) {
mPaint.setFilterBitmap(filter);
invalidateSelf();
}
#Override
public void setDither(boolean dither) {
mPaint.setDither(dither);
invalidateSelf();
}
public Bitmap getBitmap() {
return mBitmap;
}
}
}
this class handle the drawer click :
package com.example.tropo;
import android.app.Fragment;
import android.os.Bundle;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
public class MainActivity extends ActionBarActivity
implements NavigationDrawerCallbacks {
/**
* Fragment managing the behaviors, interactions and presentation of the navigation drawer.
*/
private NavigationDrawerFragment mNavigationDrawerFragment;
private Toolbar mToolbar;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mToolbar = (Toolbar) findViewById(R.id.toolbar_actionbar);
setSupportActionBar(mToolbar);
mNavigationDrawerFragment = (NavigationDrawerFragment)
getFragmentManager().findFragmentById(R.id.fragment_drawer);
// Set up the drawer.
mNavigationDrawerFragment.setup(R.id.fragment_drawer, (DrawerLayout) findViewById(R.id.drawer), mToolbar);
}
#Override
public void onNavigationDrawerItemSelected(int position) {
Fragment fragment;
switch (position) {
case 0: //Home
fragment = getFragmentManager().findFragmentByTag(D_Home.TAG);
if (fragment == null) {
fragment = new D_Home();
}
getFragmentManager().beginTransaction().replace(R.id.container, fragment, D_Home.TAG).commit();
break;
case 1: //Map
fragment = getFragmentManager().findFragmentByTag(D_Map.TAG);
if (fragment == null) {
fragment = new D_Map();
}
getFragmentManager().beginTransaction().replace(R.id.container, fragment, D_Map.TAG).commit();
break;
case 2: //Departments
fragment = getFragmentManager().findFragmentByTag(D_Departments.TAG);
if (fragment == null) {
fragment = new D_Departments();
}
getFragmentManager().beginTransaction().replace(R.id.container, fragment, D_Departments.TAG).commit();
break;
case 3: //Units
fragment = getFragmentManager().findFragmentByTag(D_Units.TAG);
if (fragment == null) {
fragment = new D_Units();
}
getFragmentManager().beginTransaction().replace(R.id.container, fragment, D_Units.TAG).commit();
break;
case 4: //Gallery
fragment = getFragmentManager().findFragmentByTag(D_Gallery.TAG);
if (fragment == null) {
fragment = new D_Gallery();
}
getFragmentManager().beginTransaction().replace(R.id.container, fragment, D_Gallery.TAG).commit();
break;
case 5: //About PSIS
fragment = getFragmentManager().findFragmentByTag(D_About.TAG);
if (fragment == null) {
fragment = new D_About();
}
getFragmentManager().beginTransaction().replace(R.id.container, fragment, D_About.TAG).commit();
break;
case 6: //Help
fragment = getFragmentManager().findFragmentByTag(D_Help.TAG);
if (fragment == null) {
fragment = new D_Help();
}
getFragmentManager().beginTransaction().replace(R.id.container, fragment, D_Help.TAG).commit();
break;
case 7: //Credit
fragment = getFragmentManager().findFragmentByTag(D_Credit.TAG);
if (fragment == null) {
fragment = new D_Credit();
}
getFragmentManager().beginTransaction().replace(R.id.container, fragment, D_Credit.TAG).commit();
break;
}
}
#Override
public void onBackPressed() {
if (mNavigationDrawerFragment.isDrawerOpen())
mNavigationDrawerFragment.closeDrawer();
else
super.onBackPressed();
}
#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);
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();
return super.onOptionsItemSelected(item);
}
public void onActivityCreated(Bundle savedInstanceState) {
}
}

Method OnItemClickListener from JSONParser override OnItemLongClickListener from another activity

I'm trying to create the favorites list from Json Objects which I received by URL.
When I got Json array, I defined methods OnItemLongClickListener and OnItemClickListener that get different things:
The OnItemClickListener method has to open another activity with description of product
The OnItemLongClickListener method has to add product to favorite list
The Problem that method OnItemClickListener which I defined in MainActivity is override method OnItemLongClickListener which I defined in FragmentActivty and the method OnItemLongClickListener doesn't work at all then I tried to define both methods in FragmentActivity but after that both methods don't work at all.
Is there any way to determine this problem?
Main Activity:
package com.boom.kayakapp.activities;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.StrictMode;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.ActionBarActivity;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.VolleyLog;
import com.android.volley.toolbox.JsonArrayRequest;
import com.boom.kayakapp.R;
import com.boom.kayakapp.adapters.AirlinesAdapter;
import com.boom.kayakapp.controllers.AppController;
import com.boom.kayakapp.fragment.AirlinesFragment;
import com.boom.kayakapp.fragment.FavoriteFragment;
import com.boom.kayakapp.model.Airlines;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends ActionBarActivity {
private Fragment contentFragment;
AirlinesFragment airlinesFragment;
FavoriteFragment favoriteFragment;
// JSON Node names
public static final String TAG_NAME = "name";
public static final String TAG_PHONE = "phone";
public static final String TAG_SITE = "site";
public static final String TAG_LOGO = "logoURL";
public static final String TAG_CODE = "code";
// Log tag
private static final String TAG = MainActivity.class.getSimpleName();
// Airlines json url
private static final String url = "https://www.kayak.com/h/mobileapis/directory/airlines";
public ProgressDialog pDialog;
public List<Airlines> airlinesList = new ArrayList<Airlines>();
public ListView listView;
public AirlinesAdapter adapter;
#Override
protected void onCreate (Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list);
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
listView = (ListView) findViewById(R.id.list);
adapter = new AirlinesAdapter(this, airlinesList);
listView.setAdapter(adapter);
pDialog = new ProgressDialog(this);
// Showing progress dialog before making http request
pDialog.setMessage("Loading...");
pDialog.show();
// Listview on item click listener
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// getting values from selected ListItem
String name = ((TextView) view.findViewById(R.id.name))
.getText().toString();
String phone = ((TextView) view.findViewById(R.id.phone))
.getText().toString();
String site = ((TextView) view.findViewById(R.id.site))
.getText().toString();
String logoURL = String.valueOf(((ImageView) view.findViewById(R.id.logoURL)));
// Starting single contact activity
Intent in = new Intent(getApplicationContext(),
SingleContactActivity.class);
in.putExtra(TAG_NAME, name);
in.putExtra(TAG_PHONE, phone);
in.putExtra(TAG_SITE, site);
in.putExtra(TAG_LOGO, logoURL);
startActivity(in);
}
});
// changing action bar color
getSupportActionBar().setBackgroundDrawable(
new ColorDrawable(Color.parseColor("#1b1b1b")));
// Creating volley request obj
JsonArrayRequest airlinesReq = new JsonArrayRequest(url,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d(TAG, response.toString());
hidePDialog();
// Parsing json
for (int i = 0; i < response.length(); i++) {
try {
JSONObject obj = response.getJSONObject(i);
Airlines airlines = new Airlines();
airlines.setName(obj.getString("name"));
airlines.setLogoURL(obj.getString("logoURL"));
airlines.setPhone(obj.getString("phone"));
airlines.setCode(obj.getInt("code"));
airlines.setSite(obj.getString("site"));
// adding airlines to movies array
airlinesList.add(airlines);
} catch (JSONException e) {
e.printStackTrace();
}
}
// notifying list adapter about data changes
// so that it renders the list view with updated data
adapter.notifyDataSetChanged();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
hidePDialog();
}
});
// Adding request to request queue
AppController.getInstance().addToRequestQueue(airlinesReq);
FragmentManager fragmentManager = getSupportFragmentManager();
/*
* This is called when orientation is changed.
*/
if (savedInstanceState != null) {
if (savedInstanceState.containsKey("content")) {
String content = savedInstanceState.getString("content");
if (content.equals(FavoriteFragment.ARG_ITEM_ID)) {
if (fragmentManager.findFragmentByTag(FavoriteFragment.ARG_ITEM_ID) != null) {
setFragmentTitle(R.string.favorites);
contentFragment = fragmentManager
.findFragmentByTag(FavoriteFragment.ARG_ITEM_ID);
}
}
}
if (fragmentManager.findFragmentByTag(AirlinesFragment.ARG_ITEM_ID) != null) {
airlinesFragment = (AirlinesFragment) fragmentManager
.findFragmentByTag(AirlinesFragment.ARG_ITEM_ID);
contentFragment = airlinesFragment;
}
} else {
airlinesFragment = new AirlinesFragment();
// setFragmentTitle(R.string.app_name);
switchContent(airlinesFragment, AirlinesFragment.ARG_ITEM_ID);
}
}
#Override
public void onDestroy () {
super.onDestroy();
hidePDialog();
}
private void hidePDialog() {
if (pDialog != null) {
pDialog.dismiss();
pDialog = null;
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
protected void onSaveInstanceState(Bundle outState) {
if (contentFragment instanceof FavoriteFragment) {
outState.putString("content", FavoriteFragment.ARG_ITEM_ID);
} else {
outState.putString("content", AirlinesFragment.ARG_ITEM_ID);
}
super.onSaveInstanceState(outState);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_favorites:
setFragmentTitle(R.string.favorites);
favoriteFragment = new FavoriteFragment();
switchContent(favoriteFragment, FavoriteFragment.ARG_ITEM_ID);
return true;
}
return super.onOptionsItemSelected(item);
}
public void switchContent(Fragment fragment, String tag) {
FragmentManager fragmentManager = getSupportFragmentManager();
while (fragmentManager.popBackStackImmediate()) ;
if (fragment != null) {
FragmentTransaction transaction = fragmentManager
.beginTransaction();
transaction.replace(R.id.content_frame, fragment, tag);
//Only FavoriteFragment is added to the back stack.
if (!(fragment instanceof AirlinesFragment)) {
transaction.addToBackStack(tag);
}
transaction.commit();
contentFragment = fragment;
}
}
protected void setFragmentTitle(int resourseId) {
setTitle(resourseId);
getSupportActionBar().setTitle(resourseId);
}
/*
* We call super.onBackPressed(); when the stack entry count is > 0. if it
* is instanceof ProductListFragment or if the stack entry count is == 0, then
* we finish the activity.
* In other words, from ProductListFragment on back press it quits the app.
*/
#Override
public void onBackPressed() {
FragmentManager fm = getSupportFragmentManager();
if (fm.getBackStackEntryCount() > 0) {
super.onBackPressed();
} else if (contentFragment instanceof AirlinesFragment
|| fm.getBackStackEntryCount() == 0) {
finish();
}
}
}
FragmentActivity:
package com.boom.kayakapp.fragment;
import android.app.Activity;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.Toast;
import com.boom.kayakapp.R;
import com.boom.kayakapp.adapters.AirlinesAdapter;
import com.boom.kayakapp.model.Airlines;
import com.boom.kayakapp.util.SharedPreference;
import java.util.ArrayList;
import java.util.List;
public class AirlinesFragment extends Fragment implements OnItemClickListener, OnItemLongClickListener{
public static final String ARG_ITEM_ID = "airlines_list";
Activity activity;
ListView airlinesListView;
List<Airlines> airlines;
AirlinesAdapter airlinesAdapter;
public AirlinesFragment() {
airlines = new ArrayList<>();
}
SharedPreference sharedPreference;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
activity = getActivity();
sharedPreference = new SharedPreference();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.activity_list, container,
false);
findViewsById(view);
airlinesAdapter = new AirlinesAdapter(activity, airlines);
airlinesListView.setAdapter(airlinesAdapter);
airlinesListView.setOnItemClickListener(this);
airlinesListView.setOnItemLongClickListener(this);
return view;
}
private void findViewsById(View view) {
airlinesListView = (ListView) view.findViewById(R.id.list);
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
Airlines airlines = (Airlines) parent.getItemAtPosition(position);
Toast.makeText(activity, airlines.toString(), Toast.LENGTH_LONG).show();
}
#Override
public boolean onItemLongClick(AdapterView<?> arg0, View view,
int position, long arg3) {
ImageView button = (ImageView) view.findViewById(R.id.favorite_button);
String tag = button.getTag().toString();
if (tag.equalsIgnoreCase("grey")) {
sharedPreference.addFavorite(activity, airlines.get(position));
Toast.makeText(activity,
activity.getResources().getString(R.string.add_favr),
Toast.LENGTH_SHORT).show();
button.setTag("red");
button.setImageResource(R.drawable.heart_red);
} else {
sharedPreference.removeFavorite(activity, airlines.get(position));
button.setTag("grey");
button.setImageResource(R.drawable.heart_grey);
Toast.makeText(activity,
activity.getResources().getString(R.string.remove_favr),
Toast.LENGTH_SHORT).show();
}
return true;
}
#Override
public void onResume() {
getActivity().setTitle(R.string.app_name);
super.onResume();
}
}
In my way I deleted definition both Methods from FavoriteFragment and defined it in MainActivity:
Json Array
listView = (ListView) findViewById(R.id.list);
adapterAirlines = new AirlinesAdapter(this, airlinesList);
listView.setAdapter(adapterAirlines);
pDialog = new ProgressDialog(this);
// Showing progress dialog before making http request
pDialog.setMessage("Loading...");
pDialog.show();
// Listview OnItemClickListener
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// getting values from selected ListItem
String name = ((TextView) view.findViewById(R.id.name))
.getText().toString();
String phone = ((TextView) view.findViewById(R.id.phone))
.getText().toString();
String site = ((TextView) view.findViewById(R.id.site))
.getText().toString();
String logoURL = String.valueOf(((ImageView) view.findViewById(R.id.logoURL)));
// Starting single contact activity
Intent in = new Intent(getApplicationContext(),
SingleContactActivity.class);
in.putExtra(TAG_NAME, name);
in.putExtra(TAG_PHONE, phone);
in.putExtra(TAG_SITE, site);
in.putExtra(TAG_LOGO, logoURL);
startActivity(in);
}
});
listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view,
int position, long id) {
ImageView button = (ImageView) view.findViewById(R.id.favorite_button);
String tag = button.getTag().toString();
if (tag.equalsIgnoreCase("grey")) {
sharedPreference.addFavorite(MainActivity.this, airlinesList.get(position));
Toast.makeText(MainActivity.this,
MainActivity.this.getResources().getString(R.string.add_favr),
Toast.LENGTH_SHORT).show();
button.setTag("red");
button.setImageResource(R.drawable.heart_red);
} else {
sharedPreference.removeFavorite(MainActivity.this, airlinesList.get(position));
button.setTag("grey");
button.setImageResource(R.drawable.heart_grey);
Toast.makeText(MainActivity.this,
MainActivity.this.getResources().getString(R.string.remove_favr),
Toast.LENGTH_SHORT).show();
}
return true;
}
});
now it works

The method onOptionsItemSelected(MenuItem) is undefined for the type FragmentPagerAdapter

The application was working just great and all of a sudden it gave me this error stating the onOptionsItemSelected(MenuItem) method is undefined. I couldn't understand what they exactly mean and what solution I should refer to.
This is the code:
package com.noura.luba;
import java.util.List;
import java.util.Stack;
import android.app.ActionBar;
import android.app.ActionBar.Tab;
import android.app.ActionBar.TabListener;
import android.app.Dialog;
import android.content.Intent;
import android.content.pm.ResolveInfo;
import android.net.Uri;
import android.os.Bundle;
import android.os.Parcelable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
public class Degree_Programs extends FragmentActivity implements TabListener{
AppSectionsPagerAdapter mAppSectionsPagerAdapter;
ViewPager mViewPager;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.degree_programs);
mAppSectionsPagerAdapter = new AppSectionsPagerAdapter(getSupportFragmentManager());
final ActionBar actionBar = getActionBar();
actionBar.setHomeButtonEnabled(false);
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mAppSectionsPagerAdapter);
mViewPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
#Override
public void onPageSelected(int position) {
actionBar.setSelectedNavigationItem(position);
}
});
for (int i = 0; i < mAppSectionsPagerAdapter.getCount(); i++) {
if (i==0){
actionBar.addTab(
actionBar.newTab()
.setText("Study Cycle")
.setTabListener(this));
}
if (i==1){
actionBar.addTab(
actionBar.newTab()
.setText("LMD")
.setTabListener(this));
}
if (i==2){
actionBar.addTab(
actionBar.newTab()
.setText("Business Administration")
.setTabListener(this));
}
if (i==3){
actionBar.addTab(
actionBar.newTab()
.setText("Economics")
.setTabListener(this));
}
}
}
public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
}
public void onTabSelected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
mViewPager.setCurrentItem(tab.getPosition());
}
public void onTabReselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
}
public class AppSectionsPagerAdapter extends FragmentPagerAdapter {
public AppSectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
public Fragment getItem(int i) {
switch (i) {
case 0:
return new LaunchpadSectionFragment();
default:
Fragment fragment = new DummySectionFragment();
Bundle args = new Bundle();
args.putInt(DummySectionFragment.ARG_SECTION_NUMBER, i + 1);
fragment.setArguments(args);
return fragment;
}
}
public int getCount() {
return 4;
}
public String getPageTitle(int position) {
return "";
}
public class LaunchpadSectionFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_section_launchpad, container, false);
rootView.findViewById(R.id.demo_collection_button)
.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(getActivity(), CollectionDemoActivity.class);
startActivity(intent);
}
});
rootView.findViewById(R.id.demo_external_activity)
.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent externalActivityIntent = new Intent(Intent.ACTION_PICK);
externalActivityIntent.setType("image/*");
externalActivityIntent.addFlags(
Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
startActivity(externalActivityIntent);
}
});
return rootView;
}
}
public class DummySectionFragment extends Fragment {
public static final String ARG_SECTION_NUMBER = "section_number";
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_section_dummy, container, false);
Bundle args = getArguments();
TextView dst = (TextView) rootView.findViewById(android.R.id.text1);
dst.setText(getString(R.string.dummy_section_text, args.getInt(ARG_SECTION_NUMBER)));
return rootView;
}
}
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.information:
final Dialog dialog =new Dialog(Degree_Programs.this);
dialog.setContentView(R.layout.information);
return true;
case R.id.logOut:
Intent intent = new Intent(getApplicationContext(),
MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
| Intent.FLAG_ACTIVITY_SINGLE_TOP);
startActivity(intent);
return true;
case R.id.email:
Intent i = new Intent(Intent.ACTION_SEND);
i.setType("*/*");
i.putExtra(Intent.EXTRA_SUBJECT, "Crash report");
i.putExtra(Intent.EXTRA_TEXT, "Some crash report details");
startActivity(createEmailOnlyChooserIntent(i, "Send via email"));
return true;
default:
return super.onOptionsItemSelected(item);
}
}
public Intent createEmailOnlyChooserIntent(Intent source,
CharSequence chooserTitle) {
Stack<Intent> intents = new Stack<Intent>();
Intent i = new Intent(Intent.ACTION_SENDTO, Uri.fromParts("mailto",
"***#gmail.com", null));
List<ResolveInfo> activities = getPackageManager()
.queryIntentActivities(i, 0);
for (ResolveInfo ri : activities) {
Intent target = new Intent(source);
target.setPackage(ri.activityInfo.packageName);
intents.add(target);
}
if (!intents.isEmpty()) {
Intent chooserIntent = Intent.createChooser(intents.remove(0),
chooserTitle);
chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS,
intents.toArray(new Parcelable[intents.size()]));
return chooserIntent;
} else {
return Intent.createChooser(source, chooserTitle);
}
}
}
#Override
public void onTabReselected(Tab arg0, android.app.FragmentTransaction arg1) {
// TODO Auto-generated method stub
}
#Override
public void onTabSelected(Tab arg0, android.app.FragmentTransaction arg1) {
// TODO Auto-generated method stub
}
#Override
public void onTabUnselected(Tab arg0, android.app.FragmentTransaction arg1) {
// TODO Auto-generated method stub
}}
There should be an #Override annotation over the onOptionsItemSelected(MenuItem) method:
#Override
public boolean onOptionsItemSelected(MenuItem item) {

Categories

Resources