i am recently start using this pdf bignerd ranch for making app…gladly it says very good
recently i stuck with creation of Action Bar…in the net says need to use Tool Bar instead of Action Bar, which are now deprecated…i used my way…each time i run the app was crashed…it says recently error as like " java.lang.NullPointerException: Attempt to invoke virtual method ‘void android.support.v7.app.ActionBar.setHomeButtonEnabled(boolean)’ on a null object reference " in the CrimeFragment.java file…pls help me what is iam wrong…is this way i want to using…if not pls correct me…i am pasting the code what i used upto now
activity_fragment.xml
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/fragmentContainer"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true">
<android.support.v7.widget.Toolbar
android:id="@+id/mr_toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:minHeight="?attr/actionBarSize"
android:background="?attr/colorPrimary"
android:elevation="4dp"
app:contentInsetLeft="0dp"
app:contentInsetStart="0dp"
/>
</FrameLayout>
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/Theme.AppCompat.Light.NoActionBar">
<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>
CrimeListActivity.java
public class CrimeListActivity extends SingleFragmentActivity { @Override protected Fragment createFragment() { return new CrimeListFragment(); } }
SingleFragmentActivity.java
package com.mr.crimetest; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v7.app.AppCompatActivity; public abstract class SingleFragmentActivity extends AppCompatActivity //public abstract class SingleFragmentActivity extends FragmentActivity { protected abstract Fragment createFragment(); @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_fragment); FragmentManager fm = getSupportFragmentManager(); Fragment fragment = fm.findFragmentById(R.id.fragmentContainer); if(fragment == null) { fragment = createFragment(); fm.beginTransaction().add(R.id.fragmentContainer,fragment).commit(); } } // onCreate() }
CrimeListFragment.java
package com.mr.crimetest; import android.content.Intent; import android.os.Bundle; import android.support.v4.app.ListFragment; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; 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.CheckBox; import android.widget.ListView; import android.widget.TextView; import java.util.ArrayList; public class CrimeListFragment extends ListFragment { private ArrayList mCrimes; private static final String TAG = "CrimeListFragment"; public static final String EXTRA_TO_CRIMEFRAGMENT_ITEM_ID="com.mr.crimetest.itemid"; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Toolbar mractionbar = (Toolbar)getActivity().findViewById(R.id.mr_toolbar); ((AppCompatActivity)getActivity()).setSupportActionBar(mractionbar); setHasOptionsMenu(true); getActivity().setTitle(R.string.crimes_title); mCrimes = CrimeLab.get(getActivity()).getCrimes(); CrimeAdapter adapter = new CrimeAdapter(mCrimes); setListAdapter(adapter); } // onCreate() @Override public void onListItemClick(ListView l, View v, int position, long id) { Crime c=((CrimeAdapter)getListAdapter()).getItem(position); Intent i=new Intent(getActivity(),CrimePagerActivity.class); i.putExtra(EXTRA_TO_CRIMEFRAGMENT_ITEM_ID,c.getId()); startActivity(i); } // onListItemClick() @Override public void onResume() { super.onResume(); ((CrimeAdapter)getListAdapter()).notifyDataSetChanged(); } //onResume() private class CrimeAdapter extends ArrayAdapter { public CrimeAdapter(ArrayList crimes) { super(getActivity(),0,crimes); // this constructor is same as seen on pdf 204 } @Override public View getView(int position, View convertview, ViewGroup parent) { // if we werent given a view, inflate one if(convertview==null) { convertview=getActivity().getLayoutInflater().inflate(R.layout.list_item_crime,null); } // configure the view for this Crime Crime c= getItem(position); TextView titletextview=(TextView)convertview.findViewById(R.id.crime_list_item_titleTextView); titletextview.setText(c.getTitle()); TextView datetextview=(TextView)convertview.findViewById(R.id.crime_list_item_dateTextView); datetextview.setText(c.getDate().toString()); CheckBox solvedcheckbox=(CheckBox)convertview.findViewById(R.id.crime_list_item_solvedCheckBox); solvedcheckbox.setChecked(c.isSolved()); return convertview; } // getView() } // CrimeAdapter @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { super.onCreateOptionsMenu(menu,inflater); // this call not a mandatory but we used as a traditional as we used earlier inflater.inflate(R.menu.fragment_crime_list,menu); } //onCreateOptionsMenu() @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.menu_item_new_crime: Crime crime=new Crime(); CrimeLab.get(getActivity()).addCrime(crime); Intent i= new Intent(getActivity(),CrimePagerActivity.class); i.putExtra(CrimeListFragment.EXTRA_TO_CRIMEFRAGMENT_ITEM_ID,crime.getId()); startActivityForResult(i,0); return true; default: return super.onOptionsItemSelected(item); } // switch() } // onOptionsItemSelected() } // CrimeListFragment
CrimePagerActivity.java
package com.mr.crimetest; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentStatePagerAdapter; import android.support.v4.view.ViewPager; import android.support.v7.app.AppCompatActivity; import java.util.ArrayList; import java.util.UUID; //public class CrimePagerActivity extends FragmentActivity public class CrimePagerActivity extends AppCompatActivity { private ViewPager mviewpager; private ArrayList mCrimes; // public static final String TAG="CrimePagerActivity"; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); mviewpager=new ViewPager(this); // here "this" means Context mviewpager.setId(R.id.viewPager); setContentView(mviewpager); mCrimes=CrimeLab.get(this).getCrimes(); FragmentManager fm=getSupportFragmentManager(); mviewpager.setAdapter(new FragmentStatePagerAdapter(fm) { @Override public Fragment getItem(int position) { Crime crime=mCrimes.get(position); //ArrayList method is taken...It fetches the Crime instance for the given position in the dataset return CrimeFragment.newInstance(crime.getId()); } @Override public int getCount() { return mCrimes.size(); } }); //FragementStatePagerAdapter() mviewpager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() { @Override public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) { } @Override public void onPageSelected(int position) { Crime crime=mCrimes.get(position); //ArrayList method is using if(crime.getTitle()!=null) setTitle(crime.getTitle()); // this is Activity method is using } @Override public void onPageScrollStateChanged(int state) { } }); // addOnPageChangeListener() UUID crimeid = (UUID)getIntent().getSerializableExtra(CrimeListFragment.EXTRA_TO_CRIMEFRAGMENT_ITEM_ID); for(int i=0; i<mCrimes.size();i++) { if(mCrimes.get(i).getId().equals(crimeid)) { mviewpager.setCurrentItem(i); //Log.d(TAG,mCrimes.get(i).toString()); // show output when clicking Crime 83 D/CrimePagerActivity: Crime # 83 break; } } }// onCreate() } // CrimePagerActivity
CrimeFragment.java
package com.mr.crimetest; import android.annotation.TargetApi; import android.app.Activity; import android.content.Intent; import android.os.Build; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.NavUtils; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; 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 { private Crime mCrime; private EditText mTitileField; private Button mDateButton; private CheckBox mSolvedCheckBox; public static final String TAG="CrimeFragment"; private static final String DIALOG_DATE="date"; private static final int REQUEST_DATE=0; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Toolbar mractionbar = (Toolbar)getActivity().findViewById(R.id.mr_toolbar); ((AppCompatActivity)getActivity()).setSupportActionBar(mractionbar); ((AppCompatActivity)getContext()).getSupportActionBar().setHomeButtonEnabled(true); setHasOptionsMenu(true); mCrime = new Crime(); UUID crimeid=(UUID)getArguments().getSerializable(CrimeListFragment.EXTRA_TO_CRIMEFRAGMENT_ITEM_ID); / mCrime=CrimeLab.get(getActivity()).getCrime(crimeid); Log.d(TAG, "Crime Id = "+crimeid+" "+mCrime.getTitle()); } @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) { ((AppCompatActivity)getActivity()).getSupportActionBar().setDisplayHomeAsUpEnabled(true); } } mTitileField = (EditText)v.findViewById(R.id.crime_title); mTitileField.setText(mCrime.getTitle()); mTitileField.addTextChangedListener(new TextWatcher() { @Override public void beforeTextChanged(CharSequence c, int start, int count, int after) { // this space is intentionally left blank } @Override public void onTextChanged(CharSequence c, int start, int before, int count) { mCrime.setTitle(c.toString()); } @Override public void afterTextChanged(Editable c) { // this space intentionally left blank } }); // mTitleField mDateButton = (Button) v.findViewById(R.id.crime_date); updateDate(); mDateButton.setOnClickListener(new View.OnClickListener() { public void onClick(View view) { FragmentManager fm= getActivity().getSupportFragmentManager(); DatePickerFragment dialog = DatePickerFragment.newInstance(mCrime.getDate()); dialog.setTargetFragment(CrimeFragment.this,REQUEST_DATE); dialog.show(fm,DIALOG_DATE); } }); // setOnClickListener() mSolvedCheckBox = (CheckBox) v.findViewById(R.id.crime_solved); mSolvedCheckBox.setChecked(mCrime.isSolved()); mSolvedCheckBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { //@Override // this is not required for methods defined in interfaces public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { mCrime.setSolved(isChecked); } }); // mSolvedCheckBox return v; } // onCreateView() @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(); } } // onActivityResult() public static CrimeFragment newInstance(UUID crimeid) { Bundle args =new Bundle(); args.putSerializable(CrimeListFragment.EXTRA_TO_CRIMEFRAGMENT_ITEM_ID,crimeid); // create argument bundle CrimeFragment fragment =new CrimeFragment(); // creating fragment instance fragment.setArguments(args); return fragment; } // newInstance() private void updateDate() { mDateButton.setText(mCrime.getDate().toString()); //mDateButton is global instance so dont worry } // updateDate() @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case android.R.id.home: if(NavUtils.getParentActivityName(getActivity())!=null) NavUtils.navigateUpFromSameTask(getActivity()); return true; default: return super.onOptionsItemSelected(item); } // switch() } // onOptionsItemSelected() public void onPause() { super.onPause(); CrimeLab.get(getActivity()).savecrimes(); } } // CrimeFragment
styles.xml
<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
<item name="colorPrimary">@color/colorPrimary</item>
<item name="colorPrimaryDark">@color/colorPrimaryDark</item>
<item name="colorAccent">@color/colorAccent</item>
</style>