Action Bar not Displaying - android

I'm trying to put an up button on my action bar, but my app isn't displaying the action bar for the fragment. My main activity's fragment has an action bar, just not the fragment it launches, so when I call getActivity().getActionBar().setDisplayHomeAsUpEnabled(true), the app throws a nullPointerException. (Stack trace for this below at NPE Stack Trace 1).
I've tried using getActionBar.show() and setting the theme to Theme.Holo.Light, as suggested here. getActionBar.show(), but that crashes the app with a nullPointerException. When I try to use Theme.Holo.Light, it tells me I have to use an appcompat theme ("You need to use a Theme.AppCompat theme (or descendant) with this activity.")
I've looked around for how to fix that error, but none of the AppCompat themes people suggest solve the problem of there being no action bar on this fragment. Any suggestions people have are appreciated. Code below.
The fragment that won't display an action bar:
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentManager;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.NavUtils;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import java.util.Date;
import java.util.UUID;
public class CrimeFragment extends Fragment {
public static final String EXTRA_CRIME_ID = "com.bignerdranch.android.criminalintent,crime_id";
private static final String DIALOG_DATE = "date";
private static final int REQUEST_DATE = 0;
private Crime mCrime;
private EditText mTitleField;
private Button mDateButton;
private CheckBox mSolvedCheckBox;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
UUID crimeId = (UUID)getArguments().getSerializable(EXTRA_CRIME_ID);
mCrime = CrimeLab.get(getActivity()).getCrime(crimeId);
}
#TargetApi(11)
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup parent, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_crime, parent, false);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
if (NavUtils.getParentActivityName(getActivity()) != null) {
//getActivity().getActionBar().setDisplayHomeAsUpEnabled(true);
}
}
mTitleField = (EditText)v.findViewById(R.id.crime_title);
mTitleField.setText(mCrime.getTitle());
mTitleField.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
//This space intentionally left blank
}
#Override
public void onTextChanged(CharSequence c, int start, int before, int count) {
mCrime.setTitle(c.toString());
}
#Override
public void afterTextChanged(Editable s) {
//This space intentionally left blank
}
});
mDateButton = (Button)v.findViewById(R.id.crime_date);
updateDate();
mDateButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
FragmentManager fm = getActivity().getFragmentManager();
DatePickerFragment dialog = DatePickerFragment.newInstance(mCrime.getDate());
dialog.setTargetFragment(CrimeFragment.this, REQUEST_DATE);
dialog.show(fm, DIALOG_DATE);
}
});
mSolvedCheckBox = (CheckBox)v.findViewById(R.id.crime_solved);
mSolvedCheckBox.setChecked(mCrime.isSolved());
mSolvedCheckBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
mCrime.setSolved(isChecked);
}
});
return v;
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode != Activity.RESULT_OK) return;
if (requestCode == REQUEST_DATE) {
Date date = (Date)data.getSerializableExtra(DatePickerFragment.EXTRA_DATE);
mCrime.setDate(date);
updateDate();
}
}
public static CrimeFragment newInstance(UUID crimeId) {
Bundle args = new Bundle();
args.putSerializable(EXTRA_CRIME_ID, crimeId);
CrimeFragment fragment = new CrimeFragment();
fragment.setArguments(args);
return fragment;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch(item.getItemId()) {
case R.id.home:
if (NavUtils.getParentActivityName(getActivity()) != null) {
NavUtils.navigateUpFromSameTask(getActivity());
}
return true;
default:
return super.onOptionsItemSelected(item);
}
}
private void updateDate() {
mDateButton.setText(mCrime.getDate().toString());
}
}
Fragment XML:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#string/crime_title_label"
style="?android:listSeparatorTextViewStyle"
/>
<EditText
android:id="#+id/crime_title"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="#string/crime_title_hint"
/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#string/crime_details_label"
style="?android:listSeparatorTextViewStyle"
/>
<Button
android:id="#+id/crime_date"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="16dp"
android:layout_marginRight="16dp"
/>
<CheckBox
android:id="#+id/crime_solved"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="16dp"
android:layout_marginRight="16dp"
android:text="#string/crime_solved_label"
/>
Activity hosting fragment:
import android.app.Fragment;
import android.app.FragmentManager;
import android.os.Bundle;
import android.support.v13.app.FragmentStatePagerAdapter;
import android.support.v4.app.FragmentActivity;
import android.support.v4.view.ViewPager;
import java.util.ArrayList;
import java.util.UUID;
public class CrimePagerActivity extends FragmentActivity {
private ViewPager mViewPager;
private ArrayList<Crime> mCrimes;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mViewPager = new ViewPager(this);
mViewPager.setId(R.id.viewpager);
setContentView(mViewPager);
mCrimes = CrimeLab.get(this).getCrimes();
FragmentManager fm = getFragmentManager();
mViewPager.setAdapter(new FragmentStatePagerAdapter(fm) {
#Override
public int getCount() {
return mCrimes.size();
}
#Override
public Fragment getItem(int pos) {
Crime crime = mCrimes.get(pos);
return CrimeFragment.newInstance(crime.getId());
}
});
UUID crimeId = (UUID)getIntent().getSerializableExtra(CrimeFragment.EXTRA_CRIME_ID);
for (int i = 0; i < mCrimes.size(); i++) {
if (mCrimes.get(i).getId().equals(crimeId)) {
mViewPager.setCurrentItem(i);
break;
}
}
mViewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
public void onPageScrollStateChanged(int state) {}
public void onPageScrolled(int pos, float posOffset, int posOffsetPixels) {}
public void onPageSelected(int pos) {
Crime crime = mCrimes.get(pos);
if (crime.getTitle() != null) {
setTitle(crime.getTitle());
}
}
});
}
}
Manifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.bignerdranch.android.criminalintent" >
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name=".CrimeListActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".CrimePagerActivity"
android:label="#string/app_name" >
<meta-data android:name="android.support.PARENT_ACTIVITY"
android:value=".CrimeListActivity"/>
</activity>
</application>
res/styles:
<resources>
<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
<!-- Customize your theme here. -->
</style>
NPE Stack Trace 1:
Process: com.bignerdranch.android.criminalintent, PID: 24448
java.lang.NullPointerException
at com.bignerdranch.android.criminalintent.CrimeFragment.onCreateView(CrimeFragment.java:57)
at android.app.Fragment.performCreateView(Fragment.java:1700)
at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:890)
at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:1062)
at android.app.BackStackRecord.run(BackStackRecord.java:684)
at android.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1453)
at android.app.FragmentManagerImpl.executePendingTransactions(FragmentManager.java:479)
at android.support.v13.app.FragmentStatePagerAdapter.finishUpdate(FragmentStatePagerAdapter.java:167)
at android.support.v4.view.ViewPager.populate(ViewPager.java:1073)
at android.support.v4.view.ViewPager.populate(ViewPager.java:919)
at android.support.v4.view.ViewPager.onMeasure(ViewPager.java:1441)
at android.view.View.measure(View.java:17495)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5363)
at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
at android.view.View.measure(View.java:17495)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5363)
at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1410)
at android.widget.LinearLayout.measureVertical(LinearLayout.java:695)
at android.widget.LinearLayout.onMeasure(LinearLayout.java:588)
at android.view.View.measure(View.java:17495)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5363)
at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
at com.android.internal.policy.impl.PhoneWindow$DecorView.onMeasure(PhoneWindow.java:2548)
at android.view.View.measure(View.java:17495)
at android.view.ViewRootImpl.performMeasure(ViewRootImpl.java:2285)
at android.view.ViewRootImpl.measureHierarchy(ViewRootImpl.java:1396)
at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1595)
at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1254)
at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:6632)
at android.view.Choreographer$CallbackRecord.run(Choreographer.java:814)
at android.view.Choreographer.doCallbacks(Choreographer.java:614)
at android.view.Choreographer.doFrame(Choreographer.java:584)
at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:800)
at android.os.Handler.handleCallback(Handler.java:733)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:146)
at android.app.ActivityThread.main(ActivityThread.java:5487)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1283)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1099)
at dalvik.system.NativeStart.main(Native Method)

CrimePagerActivity probably wants to extend ActionBarActivity rather than FragmentActivity.

when I call
getActivity().getActionBar().setDisplayHomeAsUpEnabled(true), the app
throws a nullPointerException.
When you are calling this function and saying yourself that you have ActionBar in your Fragment and not in your Activity then how can you run this command.
I've tried using getActionBar.show() and setting the theme to Theme.Holo.Light, as suggested here. getActionBar.show()
That example is outdated and there's no more Holo Theme or ActionBar. There's Toolbar now.

Related

Trying to get callbacks from DialogFragment to a fragment but the app is crashing

My app's MainActivity has a ViewPager which has three children(swipe views). When swiped to last child, the ActionBar gets two menu items. On clicking one item, a Dialog pops up to add a name of an item into a Database. On clicking second menu item, another Dialog pops up that prompts user to enter the name of the item that is to be removed from the Database. These Dialogs are getting constructed by separate Dialog Fragments. Basically what I want is to get the callback event from the Dialog that the positive or negative button has been clicked and wanna perform some action in the fragment which is as I mentioned is the last child of my ViewPager. I've seen the Android documentation as well as a Youtube video to learn how to implement the interface, yet my app's crashing.
Here's the code for my DialogFragment which shows a Dialog that prompts the user to enter input and save it to the Database.
package com.example.android.mybusiness;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.DialogFragment;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
public class AddCigaretteNameDialog extends DialogFragment {
EditText userInput;
String cigaretteName;
DbHelper dbHelper;
public AddCigaretteNameDialogListener listener;
public interface AddCigaretteNameDialogListener {
void onDialogPositiveClick(String name);
}
#NonNull
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
dbHelper = new DbHelper(getContext());
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
// SET THE TITLE FOR THE DIALOG.
builder.setTitle(R.string.add_title);
// GET THE LAYOUT INFLATOR
LayoutInflater inflater = getActivity().getLayoutInflater();
// INFLATE THE LAYOUT AND PUT IT INTO A VARIABLE.
// PASS NULL AS PARENT VIEW, BECAUSE IT'S GOING IN THE DIALOG
View view = inflater.inflate(R.layout.edit_text_for_dialogs, null);
// GET THE EDIT_TEXT FROM THE 'VIEW' VARIABLE.
userInput = view.findViewById(R.id.cigarette_name_user_input);
// SET THE LAYOUT FOR THE DIALOG
builder.setView(view);
// SET ACTION BUTTONS
builder.setPositiveButton(R.string.save, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
// GET THE USER INPUT FROM THE EDIT_TEXT ABOVE AND PUT IT INTO A VARIABLE.
cigaretteName = userInput.getText().toString();
// PUT THE USER INPUT IN THE DATABASE.
Boolean result = dbHelper.insertCigaretteName(cigaretteName);
if (result) {
// SHOW SUCCESS MESSAGE THAT CIGARETTE NAME HAS BEEN INSERTED.
Toast.makeText(getContext(), cigaretteName + " has been added successfully!", Toast.LENGTH_SHORT).show();
listener.onDialogPositiveClick(cigaretteName);
} else {Toast.makeText(getContext(), "Something is wrong", Toast.LENGTH_SHORT).show();}
}
})
.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
dismiss();
}
});
// RETURN THE DIALOG.
return builder.create();
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
// VERIFY THAT THE HOST ACTIVITY IMPLEMENTS THE CALLBACK INTERFACE
try {
listener = (AddCigaretteNameDialogListener) getTargetFragment();
} catch (ClassCastException e){
// THE ACTIVITY DOESN'T IMPLEMENT INTERFACE, THROW AN EXCEPTION.
throw new ClassCastException(getActivity().toString() + " must implement listener");
}
}
}
And here's the fragment which is the last child of the view pager.
package com.example.android.mybusiness;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.Toast;
/**
* A simple {#link Fragment} subclass.
*/
public class Purchase extends Fragment implements AddCigaretteNameDialog.AddCigaretteNameDialogListener {
Spinner spinner;
DbHelper dbHelper;
ArrayAdapter<String> arrayAdapter;
// FRAGMENT'S CONSTRUCTOR.
public Purchase() { }
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// KIND OF REQUIREMENT FOR OPTION MENUS.
setHasOptionsMenu(true);
// INSTANTIATING THE OBJECT TO RUN A FUNCTION, WHICH GETS THE CIGARETTES NAME.
dbHelper = new DbHelper(getContext());
// Inflate the layout for this fragment
// AND PUT IT INTO A VARIABLE SO WIDGETS CAN BE ACCESSED.
View view = inflater.inflate(R.layout.fragment_purchase, container, false);
// FIND THE spinner.
spinner = view.findViewById(R.id.spinner);
// CREATING THIS ADAPTER TO POPULATE THE SPINNER WIDGET.
arrayAdapter = new ArrayAdapter<String>(getContext(), android.R.layout.simple_list_item_1, dbHelper.getAllCigaretteNames());
// SETTING THE ADAPTER TO THE SPINNER, WHICH WILL PROVIDE THE CONTENT TO BE SELECTED BY ME.
spinner.setAdapter(arrayAdapter);
return view;
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.menu, menu);
super.onCreateOptionsMenu(menu, inflater);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.add_cigarette:
AddCigaretteNameDialog addCigaretteNameDialog = new AddCigaretteNameDialog();
addCigaretteNameDialog.show(getFragmentManager(), "add_cigarette_name");
return true;
case R.id.remove_cigarette:
RemoveCigaretteNameDailog RemoveCigaretteNameDailog = new RemoveCigaretteNameDailog();
RemoveCigaretteNameDailog.show(getFragmentManager(), "add_cigarette_name");
; return true;
default:
return super.onOptionsItemSelected(item);
}
}
#Override
public void onDialogPositiveClick(String name) {
arrayAdapter.add(name);
}
}
Here's the crash log:
12-07 13:13:59.278 25327-25327/com.example.android.mybusiness
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.android.mybusiness, PID: 25327
java.lang.NullPointerException: Attempt to invoke interface method 'void
com.example.android.mybusiness.AddCigaretteNameDialog$AddCigaretteNameDialogListener.onDialogPositiveClick(java.lang.String)'
on a null object reference
at com.example.android.mybusiness.AddCigaretteNameDialog$2.onClick(AddCigaretteNameDialog.java:58)
at com.android.internal.app.AlertController$ButtonHandler.handleMessage(AlertController.java:162)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5296)
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:912)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:707)
Line 58 is
listener.onDialogPositiveClick(cigaretteName);
Thanks in advance!
If you use custom dialog class with custom view this would solve your problem. I am posting a code below which shows a custom dialog with views. first of all create a layout file for your dialog design by name dlg_add_cigarette_name inside layout folder
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:background="#drawable/dialog_background_inset"
android:layout_height="wrap_content">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:layout_marginLeft="16dp"
android:text="Cigrate Name:"
android:id="#+id/tv_label_total"
/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/layout_total_update"
android:orientation="horizontal"
android:layout_below="#+id/tv_label_total"
android:weightSum="2"
>
<EditText
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1.5"
android:layout_marginLeft="16dp"
android:layout_marginRight="10dp"
android:id="#+id/et_cgrate_name"
android:inputType="text"
/>
</LinearLayout>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/layout_total_update"
android:layout_alignParentRight="true"
android:background="#android:color/transparent"
android:layout_marginRight="70dp"
android:text="OK"
android:layout_marginBottom="20dp"
android:layout_marginTop="20dp"
android:id="#+id/button_ok"
android:textColor="#color/colorPrimaryDark"
/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/layout_total_update"
android:layout_toLeftOf="#+id/button_ok"
android:layout_marginRight="30dp"
android:text="Cancel"
android:layout_marginBottom="20dp"
android:layout_marginTop="20dp"
android:background="#android:color/transparent"
android:id="#+id/button_cancel"
android:textColor="#color/colorPrimaryDark"
/>
Now inside drawable folder create a new file by name dialog_background_insetand update the file by following code
<?xml version="1.0" encoding="utf-8"?>
<inset
xmlns:android="http://schemas.android.com/apk/res/android"
android:drawable="#color/white"
android:insetRight="15dp"
android:insetLeft="15dp">
</inset>
and now in your AddCigaretteNameDialog file update the class by following code
import android.annotation.SuppressLint;
import android.app.Dialog;
import android.content.Context;
import android.content.res.Resources;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.FragmentManager;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.drinkwater.reminder.watertracker.R;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
public class AddCigaretteNameDialog extends DialogFragment {
private static final float DIM_AMOUNT = 0.4f;
#BindView(R.id.tv_label_total)
TextView tvLabelTotal;
#BindView(R.id.et_cgrate_name)
EditText etCgrateName;
#BindView(R.id.layout_total_update)
LinearLayout layoutTotalUpdate;
#BindView(R.id.button_ok)
Button buttonOk;
#BindView(R.id.button_cancel)
Button buttonCancel;
#OnClick(R.id.button_cancel)
public void onClick(){
dismiss();
}
#OnClick(R.id.button_ok)
public void onClickOkay(){
unitCallBack.addCigarette(cigaretteName);
}
private Unbinder mUnbinder;
private AddCigaretteName unitCallBack;
private String cigaretteName;
public AddCigaretteNameDialog() {
}
public static AddCigaretteNameDialog newInstance(String title) {
AddCigaretteNameDialog frag = new AddCigaretteNameDialog();
Bundle args = new Bundle();
args.putString("title", title);
frag.setArguments(args);
return frag;
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
if (unitCallBack == null && context instanceof AddCigaretteName) {
unitCallBack = (AddCigaretteName) context;
}
}
#Override
public void onDetach() {
super.onDetach();
unitCallBack = null;
}
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
final Dialog dialog = super.onCreateDialog(savedInstanceState);
final Window window = dialog.getWindow();
if (window != null) {
window.requestFeature(Window.FEATURE_NO_TITLE);
window.setBackgroundDrawableResource(android.R.color.transparent);
WindowManager.LayoutParams windowLayoutParams = window.getAttributes();
windowLayoutParams.dimAmount = DIM_AMOUNT;
}
dialog.setCancelable(false);
dialog.setCanceledOnTouchOutside(false);
return dialog;
}
#SuppressLint("NewApi")
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.test, container, false);
mUnbinder = ButterKnife.bind(this, view);
etCgrateName.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
cigaretteName=s.toString();
}
#Override
public void afterTextChanged(Editable s) {
}
});
return view;
}
#Override
public void onResume() {
super.onResume();
final int width = getScreenWidth();
int height = getScreenHeight() / 2;
changeWindowSizes(width, ViewGroup.LayoutParams.WRAP_CONTENT);
}
private void changeWindowSizes(int width, int height) {
final Window window = getDialog().getWindow();
if (window != null) {
window.setLayout(width, height);
}
}
#Override
public void onDestroyView() {
super.onDestroyView();
mUnbinder.unbind();
}
#Override
public int getTheme() {
return R.style.CustomDialog;
}
public interface AddCigaretteName {
void addCigarette(String name);
}
public static int getScreenWidth() {
return Resources.getSystem().getDisplayMetrics().widthPixels;
}
public static int getScreenHeight() {
return Resources.getSystem().getDisplayMetrics().heightPixels;
}
}
create a custom theme inside styles file
<style name="CustomDialog" parent="Theme.AppCompat.Light.Dialog">
<item name="android:windowAnimationStyle">#style/CustomDialogAnimation</item>
</style>
<style name="CustomDialogAnimation">
<item name="android:windowEnterAnimation">#anim/translate_left_side</item>
<item name="android:windowExitAnimation">#anim/translate_right_side</item>
</style>
create a package anim inside resfolder and create two files translate_left_sideand translate_right_side
translate_right_side
<?xml version="1.0" encoding="utf-8"?>
<translate xmlns:android="http://schemas.android.com/apk/res/android"
android:fromXDelta="0%" android:toXDelta="100%"
android:fromYDelta="0%" android:toYDelta="0%"
android:duration="600"/>
translate_left_side
<?xml version="1.0" encoding="utf-8"?>
<translate xmlns:android="http://schemas.android.com/apk/res/android"
android:duration="600"
android:fromXDelta="100%"
android:toXDelta="0%"/>
Your AddCigrateDialog is ready to appear.Now its time to call this dialog from button click.Inside Purchase make an object of AddCigaretteDialog class globally
AddCigaretteNameDialog addCigaretteNameDialog;
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.add_cigarette:
addCigaretteNameDialog= new AddCigaretteNameDialog();
addCigaretteNameDialog= AddCigaretteNameDialog.newInstance("AddCigrateNameDialog");
addCigaretteNameDialog.show(manager,"show");
return true;
case R.id.remove_cigarette:
RemoveCigaretteNameDailog RemoveCigaretteNameDailog = new RemoveCigaretteNameDailog();
RemoveCigaretteNameDailog.show(getFragmentManager(), "add_cigarette_name");
; return true;
default:
return super.onOptionsItemSelected(item);
}
}
And yes don't forget to implement the interface of AddCigaretteDialog inside Purchase dialog
As I am using ButterKnife dependency add the following lines inside your app's gradle file
inal BUTTER_KNIFE_VERSION = "8.8.1"
implementation "com.jakewharton:butterknife:$BUTTER_KNIFE_VERSION"
annotationProcessor "com.jakewharton:butterknife-compiler:$BUTTER_KNIFE_VERSION"

Android Horizontal Scroll View for showing youtube vidoes

am creating android application which will displays youtube videos on horizontal(Landscape) list view similar to application in screen-shot. And when i click on one of the video then it should play, which is what currently happening, am able to load all the youtube videos along with there thumbnails in simple list view(Vertical) in android, but i couldn't found out a way so far, using which I can show all videos in the youtube playlist in the manner as shown in the following screen shot layout view.
If any one knows how I could show my video list in horizontal(Landscape) layout as depicted in the attached screen-shot, it would be great help for me.
Please visit link to see the screenshot: https://sc-cdn.scaleengine.net/i/954e89ab4d5fef83bb19009107d71c60.png
Thank You.
Here Sample code
Sorry for the Logs, as am running it on device.
MainActivity
package in.wptrafficanalyzer.viewpagerdemo;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.view.ViewPager;
import android.view.Menu;
public class MainActivity extends FragmentActivity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
/** Getting a reference to the ViewPager defined the layout file */
ViewPager pager = (ViewPager) findViewById(R.id.pager);
/** Getting fragment manager */
FragmentManager fm = getSupportFragmentManager();
/** Instantiating FragmentPagerAdapter */
MyFragmentPagerAdapter pagerAdapter = new MyFragmentPagerAdapter(fm);
/** Setting the pagerAdapter to the pager object */
pager.setAdapter(pagerAdapter);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
MyFragment.java
package in.wptrafficanalyzer.viewpagerdemo;
import com.google.android.youtube.player.YouTubeInitializationResult;
import com.google.android.youtube.player.YouTubePlayer;
import com.google.android.youtube.player.YouTubePlayer.ErrorReason;
import com.google.android.youtube.player.YouTubePlayer.PlaybackEventListener;
import com.google.android.youtube.player.YouTubePlayer.PlayerStateChangeListener;
import com.google.android.youtube.player.YouTubePlayer.Provider;
import com.google.android.youtube.player.YouTubePlayerView;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class MyFragment extends Fragment implements YouTubePlayer.OnInitializedListener{
int mCurrentPage;
public static final String API_KEY = "AIzaSyBaoObw6vr4uCJnCXXXXXXXX";
//http://youtu.be/<VIDEO_ID>
public static final String VIDEO_ID = "dKLftgvYsVU";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
/** Getting the arguments to the Bundle object */
Bundle data = getArguments();
/** Getting integer data of the key current_page from the bundle */
mCurrentPage = data.getInt("current_page", 0);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.myfragment_layout, container,false);
YouTubePlayerView tv = (YouTubePlayerView ) v.findViewById(R.id.youtube_player);
tv.initialize(API_KEY, this);
return v;
}
#Override
public void onInitializationFailure(Provider provider, YouTubeInitializationResult result) {
//Toast.makeText(this, "Failured to Initialize!", Toast.LENGTH_LONG).show();
}
#Override
public void onInitializationSuccess(Provider provider, YouTubePlayer player, boolean wasRestored) {
/** add listeners to YouTubePlayer instance **/
player.setPlayerStateChangeListener(playerStateChangeListener);
player.setPlaybackEventListener(playbackEventListener);
/** Start buffering **/
if (!wasRestored) {
player.cueVideo(VIDEO_ID);
}
}
private PlaybackEventListener playbackEventListener = new PlaybackEventListener() {
#Override
public void onBuffering(boolean arg0) {
}
#Override
public void onPaused() {
}
#Override
public void onPlaying() {
}
#Override
public void onSeekTo(int arg0) {
}
#Override
public void onStopped() {
}
};
private PlayerStateChangeListener playerStateChangeListener = new PlayerStateChangeListener() {
#Override
public void onAdStarted() {
}
#Override
public void onError(ErrorReason arg0) {
}
#Override
public void onLoaded(String arg0) {
}
#Override
public void onLoading() {
}
#Override
public void onVideoEnded() {
}
#Override
public void onVideoStarted() {
}
};
}
MyFragmentPagerAdapter.java
package in.wptrafficanalyzer.viewpagerdemo;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
public class MyFragmentPagerAdapter extends FragmentPagerAdapter{
final int PAGE_COUNT = 5;
/** Constructor of the class */
public MyFragmentPagerAdapter(FragmentManager fm) {
super(fm);
}
/** This method will be invoked when a page is requested to create */
#Override
public Fragment getItem(int arg0) {
MyFragment myFragment = new MyFragment();
Bundle data = new Bundle();
data.putInt("current_page", arg0+1);
myFragment.setArguments(data);
return myFragment;
}
/** Returns the number of pages */
#Override
public int getCount() {
return PAGE_COUNT;
}
#Override
public CharSequence getPageTitle(int position) {
return "Page #" + ( position + 1 );
}
}
activity_main.xml
<RelativeLayout 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.support.v4.view.ViewPager
android:id="#+id/pager"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<android.support.v4.view.PagerTabStrip
android:id="#+id/pager_tab_strip"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="top"
android:background="#33b5e5"
android:textColor="#fff"
android:paddingTop="4dp"
android:paddingBottom="4dp" />
</android.support.v4.view.ViewPager>
</RelativeLayout>
myfragment_layout.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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:orientation="vertical" >
<com.google.android.youtube.player.YouTubePlayerView
android:id="#+id/youtube_player"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#fff"
android:padding="5dp"
/>
</LinearLayout>
AndroidManifest.xml
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="in.wptrafficanalyzer.viewpagerdemo"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="4"
android:targetSdkVersion="17" />
<application
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name=".MainActivity"
android:label="#string/title_activity_main" >
<intent-filter
android:label="#string/app_name"
>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
</manifest>
You are doing it wrong. Your my Fragment Xml should look like this:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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:orientation="vertical" >
<android.support.v4.view.ViewPager
android:id="#+id/pager"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<com.google.android.youtube.player.YouTubePlayerView
android:id="#+id/youtube_player"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#fff"
android:padding="5dp"
/>
</android.support.v4.view.ViewPager>
</LinearLayout>
Now code accordingly and Post your logcat for crash issue resolution.

android oncreateview throwing inflateException using viewpager

I'm trying to put a google maps fragment in another fragment, and that fragment is part of a viewpager. The initial part of it works, the map fragment gets put on my phone's screen.
The activity uses a viewpager that has 3 fragments, the fragment with the map fragment in it is the first one you see, but when i swipe to the last fragment and then go back to the middle fragment, the app crashes and i get an inflateException in the OnCreateView method of my first fragment (the one with the map).
I have no idea how to fix this, and nothing i tried makes it work. Any help with this would be greatly appreciated.
The fragment with the mapfragment in it.
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/tV_welkomtekst"
android:textSize="25dp"
android:layout_gravity="center"/>
<TextView
android:text="#string/sportdropdown_tekst"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="25dp"/>
<Spinner
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="#+id/spinSporten"></Spinner>
<fragment
android:layout_width="match_parent"
android:layout_height="300sp"
android:id="#+id/map"
android:name="com.google.android.gms.maps.MapFragment"
/>
<Button
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="#string/tekst_startWorkout"/>
The activity that holds the fragments.
package desomer_michael_2app.desomer_michael_eindopdracht_app;
import android.content.Intent;
import android.support.v4.app.FragmentActivity;
import android.support.v4.view.ViewPager;
import android.support.v7.app.ActionBarActivity;
import android.app.Fragment;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
public class SportActivity extends FragmentActivity implements SportStatsFragment.OnSportStatsFragmentInteractionListener, SportStartFragment.OnSportStartFragmentInteractionListener, SportBadgesFragment.OnSportBadgesFragmentInteractionListener{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sport);
ViewPager viewPager = (ViewPager) findViewById(R.id.pager);
viewPager.setAdapter(new ViewPagerAdapter(getSupportFragmentManager()));
/*
if (savedInstanceState == null) {
getFragmentManager().beginTransaction()
.add(R.id.container, new SportStartFragment())
.commit();
}
*/
}
protected void onSaveInstanceState(Bundle outState){
super.onSaveInstanceState(outState);
//getSupportFragmentManager().putFragment(outState, "sportStartFragment", );
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_sport, menu);
return true;
}
public void uitloggen(){
//Intent i = new Intent("android.intent.action.MAIN");
//startActivity(i);
finish();
}
#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();
switch(id){
case R.id.log_out:
uitloggen();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}
The viewpager
package desomer_michael_2app.desomer_michael_eindopdracht_app;
import android.support.v4.app.FragmentManager;
import android.content.Context;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentPagerAdapter;
/**
* Created by Michaël Desomer on 25/04/2015.
*/
public class ViewPagerAdapter extends FragmentPagerAdapter{
final int PAGE_COUNT = 3;
private String tabtitles[] = new String[]{"Start","Stats","Badges"};
Context context;
public ViewPagerAdapter(FragmentManager fm){
super(fm);
}
#Override
public Fragment getItem(int i) {
switch(i){
case 0:
SportStartFragment sportStartFragment = new SportStartFragment();
return sportStartFragment;
case 1:
SportStatsFragment sportStatsFragment = new SportStatsFragment();
return sportStatsFragment;
case 2:
SportBadgesFragment sportBadgesFragment = new SportBadgesFragment();
return sportBadgesFragment;
default:
return null;
}
//return null;
}
#Override
public CharSequence getPageTitle(int position){
return tabtitles[position];
}
#Override
public int getCount() {
return PAGE_COUNT;
}
}
My android manifest
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<meta-data
android:name="com.google.android.gms.version"
android:value="#integer/google_play_services_version" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name=".LoginRegistreerActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".SportActivity"
android:label="#string/title_activity_sport" >
<intent-filter>
<action android:name="create_sportactivity" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
<meta-data
android:name="com.google.android.gms.version"
android:value="#integer/google_play_services_version" />
<meta-data
android:name="com.google.android.geo.API_KEY"
android:value=""/>
</application>
The error message
05-02 15:57:01.360 19662-19662/desomer_michael_2app.desomer_michael_eindopdracht_app E/AndroidRuntime﹕ FATAL EXCEPTION: main
android.view.InflateException: Binary XML file line #30: Error inflating class fragment
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:719)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:761)
at android.view.LayoutInflater.inflate(LayoutInflater.java:498)
at android.view.LayoutInflater.inflate(LayoutInflater.java:398)
at desomer_michael_2app.desomer_michael_eindopdracht_app.SportStartFragment.onCreateView(SportStartFragment.java:57)
at android.support.v4.app.Fragment.performCreateView(Fragment.java:1786)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:947)
at android.support.v4.app.FragmentManagerImpl.attachFragment(FragmentManager.java:1302)
at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:729)
at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1489)
at android.support.v4.app.FragmentManagerImpl.executePendingTransactions(FragmentManager.java:486)
at android.support.v4.app.FragmentPagerAdapter.finishUpdate(FragmentPagerAdapter.java:141)
at android.support.v4.view.ViewPager.populate(ViewPager.java:1073)
at android.support.v4.view.ViewPager.populate(ViewPager.java:919)
at android.support.v4.view.ViewPager$3.run(ViewPager.java:249)
at android.view.Choreographer$CallbackRecord.run(Choreographer.java:791)
at android.view.Choreographer.doCallbacks(Choreographer.java:591)
at android.view.Choreographer.doFrame(Choreographer.java:560)
at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:777)
at android.os.Handler.handleCallback(Handler.java:730)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:176)
at android.app.ActivityThread.main(ActivityThread.java:5419)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:525)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1046)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:862)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.IllegalArgumentException: Binary XML file line #30: Duplicate id 0x7f09006d, tag null, or parent id 0xffffffff with another fragment for com.google.android.gms.maps.MapFragment
at desomer_michael_2app.desomer_michael_eindopdracht_app.SportStartFragment.onCreateView(SportStartFragment.java:57)
(there were quite bit more, but i couldn't get them all in the code format)
The SportStatsFragment
package desomer_michael_2app.desomer_michael_eindopdracht_app;
import android.app.Activity;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
/**
* A simple {#link Fragment} subclass.
* Activities that contain this fragment must implement the
* {#link SportStatsFragment.OnSportStatsFragmentInteractionListener} interface
* to handle interaction events.
*/
public class SportStatsFragment extends Fragment {
private OnSportStatsFragmentInteractionListener mListener;
public SportStatsFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_sport_stats, container, false);
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
mListener = (OnSportStatsFragmentInteractionListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement OnFragmentInteractionListener");
}
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
/**
* This interface must be implemented by activities that contain this
* fragment to allow an interaction in this fragment to be communicated
* to the activity and potentially other fragments contained in that
* activity.
* <p/>
* See the Android Training lesson <a href=
* "http://developer.android.com/training/basics/fragments/communicating.html"
* >Communicating with Other Fragments</a> for more information.
*/
public interface OnSportStatsFragmentInteractionListener {
// TODO: Update argument type and name
}
}
 
           
The problem is that you are using the same map again and again (Duplicate id 0x7f09006d) without destroying.
The case is destroy fragment
#Override
public void onDestroyView()
{
super.onDestroyView();
Fragment fragment = (getFragmentManager().findFragmentById(R.id.map));
FragmentTransaction ft= getActivity().getSupportFragmentManager().beginTransaction();
ft.remove(fragment);
ft.commit();
}
package com.panorma.views.fragments.contact;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.util.Log;
import android.view.InflateException;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.google.android.gms.maps.CameraUpdate;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapsInitializer;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLndg;
import com.google.android.gms.maps.model.MarkerOptions;
import com.panorma.R;
/**
* Created by aateek on 3/10/2016.
*/
// In this case, the fragment displays simple text based on the page
public class MapViewPagerFragment extends Fragment {
private static View rootView;
private final double LATITUDE = *********;
private final double LONGITUDE = ********;
GoogleMap googleMap;
private SupportMapFragment mapFrag;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
if (rootView != null) {
ViewGroup parent = (ViewGroup) rootView.getParent();
if (parent != null)
parent.removeView(rootView);
}
try {
rootView = inflater.inflate(R.layout.fragment_contacts, container, false);
} catch (InflateException e) {
/* map is already there, just return view as it is */
Log.d("InflateException", "onCreateView: ");
}
initMap();
return rootView;
}
private void initMap() {
LatLng location = new LatLng(LATITUDE, LONGITUDE);
FragmentManager fm = getChildFragmentManager();
mapFrag = (SupportMapFragment) fm.findFragmentById(
R.id.map);
if (mapFrag != null) {
googleMap = mapFrag.getMap();
}
if (googleMap != null) {
googleMap.getUiSettings().setMyLocationButtonEnabled(false);
googleMap.addMarker(new MarkerOptions().position(location));
MapsInitializer.initialize(this.getActivity());
// Updates the location and zoom of the MapView
CameraUpdate initalUpdate = CameraUpdateFactory.newLatLngZoom(
location, 17.0f);
googleMap.animateCamera(initalUpdate);
}
}
}

Up caret shows navigation drawer

Nothing much more to say. I'm using a single activity and I go into a Fragment which calls setDisplayHomeAsUpEnabled(Boolean.TRUE) and setHasOptionsMenu(Boolean.TRUE). The menu has two items and the interactions with them are right. I have set breakpoints on all onOptionsItemSelected of the app (which includes the Activity, the Fragment, and the drawer toggle) but when I debug, the menu opens and no breakpoint is triggered.
The Activity and Fragment code in case they help:
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/navigation_drawer"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:animateLayoutChanges="true">
<include
android:id="#+id/toolbar_actionbar"
layout="#layout/toolbar_default"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<FrameLayout
android:id="#+id/content_fragment_container"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
<fragment
android:id="#+id/navigation_drawer_fragment"
android:name="org.jorge.lolin1.ui.fragment.NavigationDrawerFragment"
android:layout_width="#dimen/navigation_drawer_width"
android:layout_height="match_parent"
android:layout_gravity="start"
layout="#layout/fragment_navigation_drawer" />
The Fragment code:
import android.app.Activity;
import android.content.Context;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.app.ActionBar;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.ScrollView;
import android.widget.TextView;
import com.melnykov.fab.FloatingActionButton;
import com.squareup.picasso.Picasso;
import org.jorge.lolin1.LoLin1Application;
import org.jorge.lolin1.R;
import org.jorge.lolin1.datamodel.FeedArticle;
import org.jorge.lolin1.ui.activity.MainActivity;
import org.jorge.lolin1.ui.util.StickyParallaxNotifyingScrollView;
import org.jorge.lolin1.util.PicassoUtils;
public class ArticleReaderFragment extends Fragment {
private Context mContext;
private int mDefaultImageId;
private String TAG;
private FeedArticle mArticle;
public static final String ARTICLE_KEY = "ARTICLE";
private MainActivity mActivity;
private Drawable mActionBarBackgroundDrawable;
private final Drawable.Callback mDrawableCallback = new Drawable.Callback() {
#Override
public void invalidateDrawable(Drawable who) {
final ActionBar actionBar = mActivity.getSupportActionBar();
if (actionBar != null)
actionBar.setBackgroundDrawable(who);
}
#Override
public void scheduleDrawable(Drawable who, Runnable what, long when) {
}
#Override
public void unscheduleDrawable(Drawable who, Runnable what) {
}
};
private ActionBar mActionBar;
private float mOriginalElevation;
private FloatingActionButton mMarkAsReadFab;
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
mContext = LoLin1Application.getInstance().getContext();
Bundle args = getArguments();
if (args == null)
throw new IllegalStateException("ArticleReader created without arguments");
mArticle = args.getParcelable(ARTICLE_KEY);
TAG = mArticle.getUrl();
mActivity = (MainActivity) activity;
mDefaultImageId = getArguments().getInt(FeedListFragment.ERROR_RES_ID_KEY);
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
super.onCreateOptionsMenu(menu, inflater);
inflater.inflate(R.menu.actionbar_article_reader, menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.homeAsUp:
mActivity.onBackPressed();
return Boolean.TRUE;
case R.id.action_browse_to:
mArticle.requestBrowseToAction(mContext);
return Boolean.TRUE;
case R.id.action_share:
mArticle.requestShareAction(mContext);
return Boolean.TRUE;
default:
return super.onOptionsItemSelected(item);
}
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN_MR1) {
mActionBarBackgroundDrawable.setCallback(mDrawableCallback);
}
}
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
setHasOptionsMenu(Boolean.TRUE);
final View ret = inflater.inflate(R.layout.fragment_article_reader, container, Boolean.FALSE);
View mHeaderView = ret.findViewById(R.id.image);
PicassoUtils.loadInto(mContext, mArticle.getImageUrl(), mDefaultImageId, (android.widget.ImageView) mHeaderView, TAG);
final String title = mArticle.getTitle();
mHeaderView.setContentDescription(title);
((TextView) ret.findViewById(R.id.title)).setText(title);
((TextView) ret.findViewById(android.R.id.text1)).setText(mArticle.getPreviewText());
mActionBar = mActivity.getSupportActionBar();
mActionBar.setDisplayHomeAsUpEnabled(Boolean.TRUE);
mActionBarBackgroundDrawable = new ColorDrawable(mContext.getResources().getColor(R.color.toolbar_background));
mActionBar.setBackgroundDrawable(mActionBarBackgroundDrawable);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
mOriginalElevation = mActionBar.getElevation();
mActionBar.setElevation(0); //So that the shadow of the ActionBar doesn't show over the article title
}
mActionBar.setTitle(mActivity.getString(R.string.section_title_article_reader));
StickyParallaxNotifyingScrollView scrollView = (StickyParallaxNotifyingScrollView) ret.findViewById(R.id.scroll_view);
scrollView.setOnScrollChangedListener(mOnScrollChangedListener);
scrollView.smoothScrollTo(0, 0);
if (!mArticle.isRead()) {
mMarkAsReadFab = (FloatingActionButton) ret.findViewById(R.id.fab_button_mark_as_read);
mMarkAsReadFab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mArticle.markAsRead();
mMarkAsReadFab.hide();
}
});
mMarkAsReadFab.show();
}
return ret;
}
private StickyParallaxNotifyingScrollView.OnScrollChangedListener mOnScrollChangedListener = new StickyParallaxNotifyingScrollView.OnScrollChangedListener() {
public void onScrollChanged(ScrollView who, int l, int t, int oldl, int oldt) {
if (mMarkAsReadFab != null)
if (!who.canScrollVertically(1)) {
mMarkAsReadFab.show();
} else if (t < oldt) {
mMarkAsReadFab.show();
} else if (t > oldt) {
mMarkAsReadFab.hide();
}
}
};
#Override
public void onDestroy() {
super.onDestroy();
Picasso.with(mContext).cancelTag(TAG);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
mActionBar.setElevation(mOriginalElevation);
}
}
#Override
public Animation onCreateAnimation(int transit, boolean enter, int nextAnim) {
if (enter) {
return AnimationUtils.loadAnimation(mContext, R.anim.move_in_from_bottom);
} else {
return AnimationUtils.loadAnimation(mContext, R.anim.move_out_to_bottom);
}
}
}
I have opted for making an activity only for that fragment which doesn't include the nav drawer. But obviously this doesn't answer the question, it just gets a relatively similar behavior.

Android Bar Activity with Fragments

I have a question regarding the structure of an Android Bar Activity including Fragments. I have a MainMenuActivity integrating the Bar Elements, creating the fragments, etc.
I want to enable a button to do something (within the fragment).
I'd like to start a timer in a fragment, but the application crashes before opening the fragment.
Here is the error I get:
07-10 09:14:08.010: E/AndroidRuntime(8615): at android.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1447)
07-10 09:14:08.010: E/AndroidRuntime(8615): at android.app.FragmentManagerImpl$1.run(FragmentManager.java:443)
07-10 09:14:08.010: E/AndroidRuntime(8615): at android.os.Handler.handleCallback(Handler.java:733)
07-10 09:14:08.010: E/AndroidRuntime(8615): at android.os.Handler.dispatchMessage(Handler.java:95)
07-10 09:14:08.010: E/AndroidRuntime(8615): at android.os.Looper.loop(Looper.java:157)
07-10 09:14:08.010: E/AndroidRuntime(8615): at android.app.ActivityThread.main(ActivityThread.java:5356)
07-10 09:14:08.010: E/AndroidRuntime(8615): at java.lang.reflect.Method.invokeNative(Native Method)
07-10 09:14:08.010: E/AndroidRuntime(8615): at java.lang.reflect.Method.invoke(Method.java:515)
07-10 09:14:08.010: E/AndroidRuntime(8615): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1265)
07-10 09:14:08.010: E/AndroidRuntime(8615): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1081)
07-10 09:14:08.010: E/AndroidRuntime(8615): at dalvik.system.NativeStart.main(Native Method)
Then here is the MainMenuActivity.java file:
package com.example.client;
import org.slf4j.LoggerFactory;
import android.annotation.SuppressLint;
import android.app.ActionBar;
import android.app.ActionBar.Tab;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Fragment;
import android.app.FragmentTransaction;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.location.Location;
import android.os.Bundle;
import android.os.IBinder;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.example.uadclient.R;
public class MainMenuActivity extends Activity {
Logger LOG = LoggerFactory.getLogger(MainMenuActivity.class);
private static final String TAB_KEY_INDEX = "tab_key";
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// ActionBar
ActionBar actionbar = getActionBar();
actionbar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
// create new tabs and and set up the titles of the tabs
ActionBar.Tab mFindTab = actionbar.newTab().setText(
getString(R.string.ui_tabname_find));
ActionBar.Tab mChatTab = actionbar.newTab().setText(
getString(R.string.ui_tabname_chat));
ActionBar.Tab mMeetTab = actionbar.newTab().setText(
getString(R.string.ui_tabname_meet));
ActionBar.Tab mPartyTab = actionbar.newTab().setText(
getString(R.string.ui_tabname_party));
// create the fragments
Fragment mFindFragment = new FindFragment();
Fragment mChatFragment = new ChatFragment();
Fragment mMeetFragment = new MeetFragment();
Fragment mPartyFragment = new PartyFragment();
// bind the fragments to the tabs - set up tabListeners for each tab
mFindTab.setTabListener(new MyTabsListener(mFindFragment,
getApplicationContext()));
mChatTab.setTabListener(new MyTabsListener(mChatFragment,
getApplicationContext()));
mMeetTab.setTabListener(new MyTabsListener(mMeetFragment,
getApplicationContext()));
mPartyTab.setTabListener(new MyTabsListener(mPartyFragment,
getApplicationContext()));
// add the tabs to the action bar
actionbar.addTab(mFindTab);
actionbar.addTab(mChatTab);
actionbar.addTab(mMeetTab);
actionbar.addTab(mPartyTab);
// restore to navigation
if (savedInstanceState != null) {
Toast.makeText(getApplicationContext(),
"tab is " + savedInstanceState.getInt(TAB_KEY_INDEX, 0),
Toast.LENGTH_SHORT).show();
actionbar.setSelectedNavigationItem(savedInstanceState.getInt(
TAB_KEY_INDEX, 0));
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main, menu);
return true;
}
protected void onDestroy(){
super.onDestroy();
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
}
return false;
}
// onSaveInstanceState() is used to "remember" the current state when a
// configuration change occurs such screen orientation change. This
// is not meant for "long term persistence". We store the tab navigation
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
Toast.makeText(
this,
"onSaveInstanceState: tab is"
+ getActionBar().getSelectedNavigationIndex(),
Toast.LENGTH_SHORT).show();
outState.putInt(TAB_KEY_INDEX, getActionBar()
.getSelectedNavigationIndex());
}
}
// TabListenr class for managing user interaction with the ActionBar tabs. The
// application context is passed in pass it in constructor, needed for the
// toast.
class MyTabsListener implements ActionBar.TabListener {
public Fragment fragment;
public Context context;
public MyTabsListener(Fragment fragment, Context context) {
this.fragment = fragment;
this.context = context;
}
#Override
public void onTabReselected(Tab tab, FragmentTransaction ft) {
Toast.makeText(context, "Reselected!", Toast.LENGTH_SHORT).show();
}
#Override
public void onTabSelected(Tab tab, FragmentTransaction ft) {
Toast.makeText(context, "Selected!", Toast.LENGTH_SHORT).show();
ft.replace(R.id.fragment_container, fragment);
}
#Override
public void onTabUnselected(Tab tab, FragmentTransaction ft) {
Toast.makeText(context, "Unselected!", Toast.LENGTH_SHORT).show();
ft.remove(fragment);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
}
#SuppressLint("CutPasteId")
public void onClick(View v) {
switch(v.getId()) {
case R.id.checkBox1:
{
try {
EditText inputIP = (EditText) findViewById(R.id.editText1);
String ip = inputIP.getText().toString();
EditText inputhost = (EditText) findViewById(R.id.editText2);
int host = Integer.parseInt(inputhost.getText().toString());
if (inputIP.getText().length() > &&((inputhost.getText().length()> 0))) {
send(ip, host );
}
else {
inputIP.setError("Cannot be empty");
inputhost.setError("Cannot be empty");
}
} catch (TException e) {
// LOG.error("Sending failed: ", e);
}
break;
}
//Show Coordinates
case R.id.button1:
{
LocationProviderService locService = null;
Location currentLoc = locService.getLastGPSProviderPosition();
GeographicPointReference gpr = new GeographicPointReference();
BoundingBox bb = new BoundingBox();
gpr.setLatitude(currentLoc.getLatitude());
gpr.setLongitude(currentLoc.getLongitude());
bb.setUpperright(gpr);
bb.setLowerleft(gpr);
TextView tv = new TextView(locService);
tv.setText(" "+bb.setLowerleft(gpr)+" ");
setContentView(tv);
}
return;
}
}
private void setContentView(TextView tv) {
// TODO Auto-generated method stub
}
private EditText findViewById(int edittext1) {
// TODO Auto-generated method stub
return null;
}}
The Fragment, which contains the timer is ChatFragment.java
package com.example.client;
import android.annotation.SuppressLint;
import android.app.Fragment;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.example.uadclient.R;
public class ChatFragment extends Fragment {
private MalibuCountDownTimer countDownTimer;
private long timeElapsed;
private boolean timerHasStarted = false;
private TextView text;
private TextView timeElapsedView;
private final long startTime = 50000;
private final long interval = 1000;
private Button buttonTimer;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
LinearLayout rr = (LinearLayout) inflater.inflate(R.layout.chatfragment,
container, false);
text = (TextView) rr.findViewById(R.id.timer);
timeElapsedView = (TextView) rr.findViewById(R.id.timeElapsed);
countDownTimer = new MalibuCountDownTimer(startTime, interval);
text.setText(text.getText() + String.valueOf(startTime));
buttonTimer = (Button) rr.findViewById(R.id.button1);
buttonTimer.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Fragment fragment = new FindFragment();
android.app.FragmentTransaction ft = getFragmentManager()
.beginTransaction();
switch (v.getId()) {
case R.id.button1:
{
if (!timerHasStarted)
{
countDownTimer.start();
timerHasStarted = true;
buttonTimer.setText("Start");
}
else
{
countDownTimer.cancel();
timerHasStarted = false;
buttonTimer.setText("RESET");
}
}}
// ft.commit();
}
});
return rr;
}
}
and the chatfragment.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="0.30"
android:orientation="vertical" >
<Button
android:id="#+id/button"
android:text="Start"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
<TableLayout
android:padding="10dip"
android:layout_gravity="center"
android:layout_width="fill_parent"
android:layout_height="wrap_content">
<TableRow>
<TextView
android:id="#+id/timer"
android:text="Time: "
android:paddingRight="10dip"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView
android:id="#+id/timeElapsed"
android:text="Time elapsed: "
android:paddingRight="10dip"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</TableRow>
</TableLayout>
</LinearLayout>
</LinearLayout>
you should use
getFragmentManager().executePendingTransactions(); to confirm all the other transactions are completely executed before you perform a new transaction for a fragment.
For more information regarding the same you can view the issue here

Categories

Resources