This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 7 years ago.
import android.app.Activity;
import android.media.MediaPlayer;
import android.media.MediaRecorder;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ListAdapter;
import android.widget.TextView;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import umd.frenchpronunciationapp.dummy.DummyContent;
/**
* A fragment representing a list of Items.
* <p/>
* Large screen devices (such as tablets) are supported by replacing the ListView
* with a GridView.
* <p/>
* Activities containing this fragment MUST implement the {#link OnFragmentInteractionListener}
* interface.
*/
public class FragmentList1 extends Fragment implements AbsListView.OnItemClickListener{
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
TextView text1;
private Button button1 = (Button) getView().findViewById(R.id.male);
private Button button2 = (Button) getView().findViewById(R.id.female);
ArrayList <String> phrases = new ArrayList<String> ();
private OnFragmentInteractionListener mListener;
/**
* The fragment's ListView/GridView.
*/
private AbsListView mListView;
/**
* The Adapter which will be used to populate the ListView/GridView with
* Views.
*/
private ListAdapter mAdapter;
// TODO: Rename and change types of parameters
public static FragmentList1 newInstance(String param1, String param2) {
FragmentList1 fragment = new FragmentList1();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
/**
* Mandatory empty constructor for the fragment manager to instantiate the
* fragment (e.g. upon screen orientation changes).
*/
public FragmentList1() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
// TODO: Change Adapter to display your content
mAdapter = new ArrayAdapter<DummyContent.DummyItem>(getActivity(),
android.R.layout.simple_list_item_1, android.R.id.text1, DummyContent.ITEMS);
addListenerOnButtonMale();
addListenerOnButtonFemale();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_item, container, false);
// Set the adapter
mListView = (AbsListView) view.findViewById(android.R.id.list);
((AdapterView<ListAdapter>) mListView).setAdapter(mAdapter);
// Set OnItemClickListener so we can be notified on item clicks
mListView.setOnItemClickListener(this);
return view;
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
mListener = (OnFragmentInteractionListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement OnFragmentInteractionListener");
}
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
public void readInPhrases () throws IOException
{
String str;
InputStream myStream = getResources().openRawResource(R.raw.phrases);
BufferedReader reader = new BufferedReader(new InputStreamReader(myStream));
while ((str = reader.readLine()) != null)
{
phrases.add(str);
}
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id)
{
if (null != mListener) {
// Notify the active callbacks interface (the activity, if the
// fragment is attached to one) that an item has been selected.
mListener.onFragmentInteraction(DummyContent.ITEMS.get(position).id);
}
text1 = (TextView) getView ().findViewById (R.id.phrase);
try {
readInPhrases();
}
catch (IOException ex)
{
// catches overidden error ioexecption
}
MediaPlayer mp1 = MediaPlayer.create (getActivity().getApplicationContext(), (R.raw.g1));
MediaPlayer mp2 = MediaPlayer.create (getActivity().getApplicationContext(), (R.raw.g2));
MediaPlayer mp3 = MediaPlayer.create (getActivity().getApplicationContext(), (R.raw.g3));
MediaPlayer mp4 = MediaPlayer.create (getActivity().getApplicationContext(), (R.raw.g4));
MediaPlayer mp5 = MediaPlayer.create (getActivity().getApplicationContext(), (R.raw.g5));
MediaPlayer mp6 = MediaPlayer.create (getActivity().getApplicationContext(), (R.raw.g6));
MediaPlayer mp7 = MediaPlayer.create (getActivity().getApplicationContext(), (R.raw.g7));
MediaPlayer mp8 = MediaPlayer.create (getActivity().getApplicationContext(), (R.raw.g8));
MediaPlayer mp9 = MediaPlayer.create (getActivity().getApplicationContext(), (R.raw.g9));
MediaPlayer mp10 = MediaPlayer.create (getActivity().getApplicationContext(), (R.raw.g10));
MediaPlayer mp11 = MediaPlayer.create (getActivity().getApplicationContext(), (R.raw.g11));
MediaPlayer mp12 = MediaPlayer.create (getActivity().getApplicationContext(), (R.raw.g12));
switch (position){
default:
case 0:
text1.setText (phrases.get(0));
// to incorperate male voice, do this and have male and female buttons
// and a variable that holds true or false if button was pressed
//if (male == true)
mp1.start();
//else
//mp... .start ();
break;
case 1:
text1.setText (phrases.get (1));
mp2.start ();
break;
case 2:
text1.setText (phrases.get (2));
mp3.start ();
break;
case 3:
text1.setText (phrases.get (3));
mp4.start ();
break;
case 4:
text1.setText (phrases.get (4));
mp5.start ();
break;
case 5:
text1.setText (phrases.get (5));
mp6.start ();
break;
case 6:
text1.setText (phrases.get (6));
mp7.start ();
break;
case 7:
text1.setText (phrases.get (7));
mp8.start ();
break;
case 8:
text1.setText (phrases.get (8));
mp9.start ();
break;
case 9:
text1.setText (phrases.get (9));
mp10.start ();
break;
case 10:
text1.setText (phrases.get (10));
mp11.start ();
break;
case 11:
text1.setText (phrases.get (11));
mp12.start ();
break;
}
}
public void addListenerOnButtonMale ()
{
//male.setBackgroundResource((R.drawable.malelogo));
button1.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Perform action on click
}
});
}
public void addListenerOnButtonFemale ()
{
//female.setBackgroundResource((R.drawable.femalelogo));
button2.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
MediaPlayer mp1 = MediaPlayer.create(getActivity().getApplicationContext(), (R.raw.g1));
mp1.start();
}
});
}
/**
* The default content for this Fragment has a TextView that is shown when
* the list is empty. If you would like to change the text, call this method
* to supply the text it should use.
*/
public void setEmptyText(CharSequence emptyText) {
View emptyView = mListView.getEmptyView();
if (emptyView instanceof TextView) {
((TextView) emptyView).setText(emptyText);
}
}
/**
* 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 OnFragmentInteractionListener {
// TODO: Update argument type and name
public void onFragmentInteraction(String id);
}
}
The addition of the addListenerOnButtonMale(); in the onCreate() method causes my app to crash. I looked around for answers that would help with the NullPointerException but they all stated that i needed to declare the button before the method was called and this still doesn't help with anything.
Your onCreate():
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
// TODO: Change Adapter to display your content
mAdapter = new ArrayAdapter<DummyContent.DummyItem>(getActivity(),
android.R.layout.simple_list_item_1, android.R.id.text1, DummyContent.ITEMS);
addListenerOnButtonMale();
addListenerOnButtonFemale();
}
Your addListenerOnButtonMale():
public void addListenerOnButtonMale ()
{
//male.setBackgroundResource((R.drawable.malelogo));
button1.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Perform action on click
}
});
}
Check your onCreate()... you have not initialised the button1.. Thats why you are getting NullPoitnerException.
Remove the addListenerOnButtonMale(); and addListenerOnButtonFemale(); from your onCreate();
Modify your onCreateView() as below:
First initialise by finding the reference and then, call your methods:
public void onCreateView(){
View view = inflater.inflate(R.layout.fragment_item, container, false);
// Set the adapter
mListView = (AbsListView) view.findViewById(android.R.id.list);
((AdapterView<ListAdapter>) mListView).setAdapter(mAdapter);
// Set OnItemClickListener so we can be notified on item clicks
mListView.setOnItemClickListener(this);
button1 = (Button) view.findViewById(R.id.*button1*);// place id of your button1.
button2 = (Button) view.findViewById(R.id.*button2*);// place id of your button2.
addListenerOnButtonMale();
addListenerOnButtonFemale();
return view;
}
Related
Problem: I have a viewPager with 3 fragments, the first one has a videoView. When I change to the second fragment, the video stops and when I change to the third, the same. But when I change from the third fragment to the second one, the video starts playing in the background.
I want the video to play only in the first fragment. How can i solve this problem? Thanks
Here is my code:
Activity Adapter:
import android.net.Uri;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.os.Bundle;
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 ActivitySwipe extends AppCompatActivity implements
HomeFragment.OnFragmentInteractionListener ,
CamaraFragment.OnFragmentInteractionListener
, SearchFragment.OnFragmentInteractionListener{
/**
* The {#link android.support.v4.view.PagerAdapter} that will provide
* fragments for each of the sections. We use a
* {#link FragmentPagerAdapter} derivative, which will keep every
* loaded fragment in memory. If this becomes too memory intensive, it
* may be best to switch to a
* {#link android.support.v4.app.FragmentStatePagerAdapter}.
*/
private SectionsPagerAdapter mSectionsPagerAdapter;
/**
* The {#link ViewPager} that will host the section contents.
*/
private ViewPager mViewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_swipe);
/* 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());
final HomeFragment homeFragment = new HomeFragment();
// Set up the ViewPager with the sections adapter.
mViewPager = (ViewPager) findViewById(R.id.container);
mViewPager.setAdapter(mSectionsPagerAdapter);
/* 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();
}
});*/
mViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
public void onPageScrollStateChanged(int state) {}
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
public void onPageSelected(int position) {
// Check if this is the page you want.
}
});
}
#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_activity_swipe, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onFragmentInteraction(Uri uri) {
}
/**
* 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 Fragment newInstance(int sectionNumber) {
Fragment fragment = null;
switch (sectionNumber){
case 1 : fragment=new HomeFragment();
break;
case 2 : fragment=new CamaraFragment();
break;
case 3 : fragment=new SearchFragment();
break;
}
return fragment;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_activity_swipe, 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;
}
}
/**
* A {#link FragmentPagerAdapter} that returns a fragment corresponding to
* one of the sections/tabs/pages.
*/
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
// getItem is called to instantiate the fragment for the given page.
// Return a PlaceholderFragment (defined as a static inner class below).
return PlaceholderFragment.newInstance(position + 1);
}
#Override
public int getCount() {
// Show 3 total pages.
return 3;
}
}
}
Here is my 1st fragment:
import android.content.Context;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.VideoView;
/**
* A simple {#link Fragment} subclass.
* Activities that contain this fragment must implement the
* {#link HomeFragment.OnFragmentInteractionListener} interface
* to handle interaction events.
* Use the {#link HomeFragment#newInstance} factory method to
* create an instance of this fragment.
*/
public class HomeFragment extends Fragment{
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
VideoView videoview;
MediaPlayer mediap;
int position;
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
private OnFragmentInteractionListener mListener;
public HomeFragment() {
// Required empty public constructor
}
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* #param param1 Parameter 1.
* #param param2 Parameter 2.
* #return A new instance of fragment HomeFragment.
*/
// TODO: Rename and change types and number of parameters
public static HomeFragment newInstance(String param1, String param2) {
HomeFragment fragment = new HomeFragment();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setUserVisibleHint(false);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View v= inflater.inflate(R.layout.fragment_home, container, false);
videoview = (VideoView) v.findViewById(R.id.video1);
videoview.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared( MediaPlayer mp) {
mp.setLooping(true);
mediap=mp;
}
});
Uri uri = Uri.parse("android.resource://" + getActivity().getPackageName() + "/" + R.raw.vid5);
videoview.setVideoURI(uri);
videoview.requestFocus();
videoview.start();
return v;
}
// TODO: Rename method, update argument and hook method into UI event
public void onButtonPressed(Uri uri) {
if (mListener != null) {
mListener.onFragmentInteraction(uri);
}
}
#Override
public void setUserVisibleHint(boolean isVisibleToUser) {
super.setUserVisibleHint(isVisibleToUser);
if (isVisibleToUser) {
resume();
}
else {
pause();
}
}
#Override
public void setMenuVisibility(final boolean visible) {
super.setMenuVisibility(visible);
if (visible&&isResumed()) {
resume();
}else{
pause();
}
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnFragmentInteractionListener) {
mListener = (OnFragmentInteractionListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement OnFragmentInteractionListener");
}
}
public void pause(){
//NOT videoview.pause(); Needn't save Stop position
if (mediap != null){
mediap.pause();
}
}
public void resume(){
//NOT videoview.resume();
if (mediap != null){
mediap.start(); //Video will begin where it stopped
}
}
#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 OnFragmentInteractionListener {
// TODO: Update argument type and name
void onFragmentInteraction(Uri uri);
}
}
And my 2nd fragment:
import android.content.Context;
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 CamaraFragment.OnFragmentInteractionListener} interface
* to handle interaction events.
* Use the {#link CamaraFragment#newInstance} factory method to
* create an instance of this fragment.
*/
public class CamaraFragment extends Fragment {
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
private OnFragmentInteractionListener mListener;
public CamaraFragment() {
// Required empty public constructor
}
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* #param param1 Parameter 1.
* #param param2 Parameter 2.
* #return A new instance of fragment CamaraFragment.
*/
// TODO: Rename and change types and number of parameters
public static CamaraFragment newInstance(String param1, String param2) {
CamaraFragment fragment = new CamaraFragment();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_camara, container, false);
}
// TODO: Rename method, update argument and hook method into UI event
public void onButtonPressed(Uri uri) {
if (mListener != null) {
mListener.onFragmentInteraction(uri);
}
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnFragmentInteractionListener) {
mListener = (OnFragmentInteractionListener) context;
} else {
throw new RuntimeException(context.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 OnFragmentInteractionListener {
// TODO: Update argument type and name
void onFragmentInteraction(Uri uri);
}
}
When you use an FragmentPagerAdapter, it pre-loads your fragments to left and right of your fragment in focus. So when you scroll from position 0 to 1 to 2, the fragment in position 0 is removed. When you then scroll back to position 1, the fragment in position 0 is re-loaded, which triggers creating the view. If you look at your HomeFragment, you trigger playing video when in OnCreateView().
To resolve this, you need to change how you trigger playing the video from when the Fragment is created to instead be activated when it scrolls into view. You are already halfway there with your empty OnPageChangeListener. You should check the position in onPageSelected() and start the video there instead of in the Fragment's OnCreateView
You have to override setUserVisibleHint method in a fragment where you play video.
public void setUserVisibleHint
#Override
public void setUserVisibleHint(boolean isVisibleToUser)
{
super.setUserVisibleHint(isVisibleToUser);
if (this.isVisible())
{
if (!isVisibleToUser)
{
//pause or stop video
} else {
//play your video
}
}
}
I'm new to this fragment coding in Android stuff so I hope this is a simple one for most to answer.
I have a TextView object, 'next', that, when clicked, does not seem to be responding. I want to do a few things when the TextView text is clicked. First, check the String value in the eventName spinner, then Toast the eventID value and finally start a new fragment for the next part of user interaction.
I have not yet implemented the new fragment or a call to the fragment. I assume the way to call the new fragment is with the following code:
NextFragment nextFrag= new NextFragment();
getActivity().getSupportFragmentManager().beginTransaction()
.replace(R.id.Layout_container, nextFrag,"findThisFragment")
.addToBackStack(null)
.commit();
My questions are:
Why is the Toast not being displayed? It seems as though the OnCickListener or the OnClick method isn't triggering the Toast.
Is the code above all that I need to do to call a new fragment and make it active in the current Activity or is there something else that I need to add in the Activity code?
Fragment code:
import android.content.Context;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
/**
* A simple {#link Fragment} subclass.
* Activities that contain this fragment must implement the
* {#link FindEventFragment.OnFragmentInteractionListener} interface
* to handle interaction events.
* Use the {#link FindEventFragment#newInstance} factory method to
* create an instance of this fragment.
*/
public class FindEventFragment extends Fragment{
public static final String TAG = "FindEventFragment";
private VolleyHelper mInstance;
private ArrayList<String> eventList = new ArrayList<String>();
private JSONArray result;
private Spinner eventNameSpinner;
private TextView eventDate;
private String eventID;
private TextView next;
//TextView errorText;
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
private OnFragmentInteractionListener mListener;
public FindEventFragment() {
// Required empty public constructor
}
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* #param param1 Parameter 1.
* #param param2 Parameter 2.
* #return A new instance of fragment FindEventFragment.
*/
// TODO: Rename and change types and number of parameters
public static FindEventFragment newInstance(String param1, String param2) {
FindEventFragment fragment = new FindEventFragment();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}
public void onStart() {
super.onStart();
// Instantiate the RequestQueue from VolleyHelper
mInstance = VolleyHelper.getInstance(getActivity().getApplicationContext());
// API
connectApi();
}
#Override
public void onStop () {
super.onStop();
if (mInstance.getRequestQueue() != null) {
mInstance.getRequestQueue().cancelAll(TAG);
}
}
private void connectApi() {
String url = "http://gblakes.ddns.net/get_events.php";
StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
new Response.Listener<String>() {
#Override
public void onResponse(String ServerResponse) {
JSONObject j = null;
try {
result = new JSONArray(ServerResponse);
eventDetails(result);
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError volleyError) {
Toast.makeText(getActivity().getApplicationContext(), "Oops, something went wrong", Toast.LENGTH_LONG).show();
}
});
if (mInstance != null) {
// Add a request to your RequestQueue.
mInstance.addToRequestQueue(stringRequest);
// Start the queue
mInstance.getRequestQueue().start();
}
}
private void eventDetails(JSONArray j) {
eventList.add("Choose an event");
for (int i = 0; i < j.length(); i++) {
try {
JSONObject json = j.getJSONObject(i);
// eventList.add(json.getString("EventName") + json.getString("EventDate"));
eventList.add(json.getString("EventName"));
} catch (JSONException e) {
//e.printStackTrace();
Log.d(TAG, e.toString());
}
}
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_spinner_item, eventList);
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
eventNameSpinner.setAdapter(dataAdapter);
eventNameSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View v, int position, long id) {
//Setting the value to textview for a selected item
eventDate.setText(getEventDate(position));
eventID = (getEventID(position));
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
eventDate.setText("test me");
}
});
next.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Make sure the user has made a valid selection
//errorText.setError("");
if (eventNameSpinner.equals("Choose an event")){
//errorText.setError("");
Toast.makeText(getActivity().getApplicationContext(),"Choose an event first",Toast.LENGTH_LONG);
//errorText.setText("Choose an event first");
} else {
//if an event is selected then open the next fragment
Toast.makeText(getActivity().getApplicationContext(),eventID.toString(),Toast.LENGTH_LONG);
}
}
});
}
private String getEventID(int position) {
String eventID = "";
try {
//Getting object of given index
JSONObject json = result.getJSONObject(position);
//Fetching name from that object
eventID = json.getString("EventID");
} catch (JSONException e) {
e.printStackTrace();
}
//Returning the name
return eventID;
}
private String getEventDate(int position){
String eventDate="";
try {
JSONObject json = result.getJSONObject(position);
eventDate = json.getString("EventDate");
} catch (JSONException e) {
e.printStackTrace();
}
return eventDate;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View v = inflater.inflate(R.layout.fragment_find_event,container,false);
eventNameSpinner = (Spinner) v.findViewById(R.id.spinEventPicker);
//eventNameSpinner = new Spinner(getActivity().getApplicationContext());
eventDate = (TextView) v.findViewById(R.id.textEventDate);
next = (TextView) v.findViewById(R.id.link_judgeToEvent);
eventDate.setText("test me");
// errorText = (TextView)eventNameSpinner.getSelectedView();
return v;
}
// TODO: Rename method, update argument and hook method into UI event
public void onButtonPressed(Uri uri) {
if (mListener != null) {
mListener.onFragmentInteraction(eventID);
}
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnFragmentInteractionListener) {
mListener = (OnFragmentInteractionListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement OnFragmentInteractionListener");
}
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
void onFragmentInteraction(String eventID);
}
}
and the fragment's XML
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:id="#+id/textEventName">
<Spinner
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/spinEventPicker"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:gravity="center"
android:layout_alignParentStart="true" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Large Text"
android:id="#+id/textEventDate"
android:layout_marginTop="49dp"
android:layout_below="#+id/spinEventPicker"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
<TextView
android:id="#+id/link_judgeToEvent"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="24dp"
android:layout_below="#+id/textEventDate"
android:gravity="center"
android:text="Next"
android:textAlignment="center"
android:textSize="16dip" />
</RelativeLayout>
Toast will display if you call show(), So you have to change the following line of code like this
Toast.makeText(getActivity().getApplicationContext(),"Choose an event first",Toast.LENGTH_LONG).show();
You can use the following code sample code to launch the fragment from another fragment
Fragment2 fragment2 = new Fragment2();
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.fragment1, fragment2);
fragmentTransaction.commit();
I'm trying to use the ZXing library for make a Bar Code scan in a Fragment.
I have successful imported the library but when I choose from the APP this Fragment the APP crash with the following traceback:
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
at com.fastnetserv.barcodeapp.Barcode.onResume(Barcode.java:86)
at android.support.v4.app.Fragment.performResume(Fragment.java:2020)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1107)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1252)
at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:742)
at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1617)
at android.support.v4.app.FragmentManagerImpl$1.run(FragmentManager.java:517)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5254)
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:903)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
And here the Fragment code
package com.fastnetserv.barcodeapp;
import com.google.zxing.integration.android.IntentIntegrator;
import com.google.zxing.integration.android.IntentResult;
import android.content.Context;
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;
import android.app.Activity;
import android.content.Intent;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
/**
* A simple {#link Fragment} subclass.
* Activities that contain this fragment must implement the
* {#link Barcode.OnFragmentInteractionListener} interface
* to handle interaction events.
* Use the {#link Barcode#newInstance} factory method to
* create an instance of this fragment.
*/
public class Barcode extends Fragment implements OnClickListener {
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
private OnFragmentInteractionListener mListener;
public Barcode() {
// Required empty public constructor
}
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* #param param1 Parameter 1.
* #param param2 Parameter 2.
* #return A new instance of fragment Barcode.
*/
// TODO: Rename and change types and number of parameters
public static Barcode newInstance(String param1, String param2) {
Barcode fragment = new Barcode();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}
private Button scanBtn;
private TextView formatTxt, contentTxt;
#Override
public void onResume() {
super.onResume();
//instantiate button, text, content
scanBtn = (Button) getActivity().findViewById(R.id.scan_button);
formatTxt = (TextView) getActivity().findViewById(R.id.scan_format);
contentTxt = (TextView) getActivity().findViewById(R.id.scan_content);
scanBtn.setOnClickListener(this);
}
// TODO: Rename method, update argument and hook method into UI event
public void onButtonPressed(Uri uri) {
if (mListener != null) {
mListener.onFragmentInteraction(uri);
}
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
try {
mListener = (OnFragmentInteractionListener) context;
} catch (ClassCastException e) {
throw new ClassCastException(context.toString()
+ " must implement OnFragmentInteractionListener");
}
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
//retrieve scan result
IntentResult scanningResult = IntentIntegrator.parseActivityResult(requestCode, resultCode, intent);
if (scanningResult != null) {
//we have a result
String scanContent = scanningResult.getContents();
String scanFormat = scanningResult.getFormatName();
formatTxt.setText("FORMAT: " + scanFormat);
contentTxt.setText("CONTENT: " + scanContent);
}else{
Toast toast = Toast.makeText(getActivity(),
"No scan data received!", Toast.LENGTH_SHORT);
toast.show();
}
}
#Override
public void onClick(View v) {
//respond to clicks
if(v.getId()==R.id.scan_button){
//scan
IntentIntegrator scanIntegrator = new IntentIntegrator(getActivity());
scanIntegrator.initiateScan();
}
}
}
What I've missing or what I'm doing wrong?
You haven't defined any view for your fragment, so it is unable to find that relevant id thus resulting in Null Pointer Exception. Override onCreateView() method in your fragment and provide a view in that and then write your findViewById code in this method like this
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.layout, container, false);
btn_name= (Button) view.findViewById(R.id.your_button_id);
return view;
}
You can't instantiate view using getActivity() in Fragment.
You have to do like below and remove instantiation from onResume():
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.your_fragment_layout, container, false);
scanBtn = (Button) view.findViewById(R.id.scan_button);
formatTxt = (TextView) view.findViewById(R.id.scan_format);
contentTxt = (TextView) view.findViewById(R.id.scan_content);
scanBtn.setOnClickListener(this);
return view;
}
please help me.
just want to know how can i refresh listview after i click imagebutton in my item.
here is my button onclick inside adapter..
buttonHeart.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
if (arg0 != null) {
FragmentOne_DbAdapter database=new FragmentOne_DbAdapter(context);
database.open();
if(favorite.matches("0")) {
database.updateItemFavorite(_id,"1");
buttonHeart.setImageResource(R.drawable.heartred);
//Toast.makeText(arg0.getContext(),favorite,Toast.LENGTH_LONG).show();
}else if(favorite.matches("1")){
database.updateItemFavorite(_id, "0");
buttonHeart.setImageResource(R.drawable.heart);
//Toast.makeText(arg0.getContext(),favorite,Toast.LENGTH_LONG).show();
}
}
}
});
here is my complete adapter..
package com.magicstarme.virtualsongbook;
import android.content.Context;
import android.database.Cursor;
import android.media.Image;
import android.support.v4.widget.CursorAdapter;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ToggleButton;
import java.util.ArrayList;
/**
* Created by Joe on 6/29/2016.
*/
public class FragmentOne_Adapter extends CursorAdapter {
public FragmentOne_Adapter(Context context, Cursor c, int flags) {
super(context, c, flags);
// TODO Auto-generated constructor stub
}
#Override
public void bindView(View view, final Context context, Cursor cursor) {
// TODO Auto-generated method stub
TextView txtTitle = (TextView) view.findViewById(R.id.title);
TextView txtArtist = (TextView) view.findViewById(R.id.artist);
TextView txtVolume = (TextView) view.findViewById(R.id.volume);
TextView txtNumber = (TextView) view.findViewById(R.id.number);
final ImageButton buttonHeart = (ImageButton) view.findViewById(R.id.heart);
final int _id = cursor.getInt(cursor.getColumnIndexOrThrow("_id"));
String title = cursor.getString(cursor.getColumnIndexOrThrow("title"));
String artist = cursor.getString(cursor.getColumnIndexOrThrow("artist"));
String volume = cursor.getString(cursor.getColumnIndexOrThrow("volume"));
final String favorite = cursor.getString(cursor.getColumnIndexOrThrow("favorite"));
String number = cursor.getString(cursor.getColumnIndexOrThrow("number"));
// Populate fields with extracted properties
txtTitle.setText(title);
txtArtist.setText(artist);
txtVolume.setText(volume);
txtNumber.setText(number);
if(favorite.matches("0")) {
buttonHeart.setImageResource(R.drawable.heart);
}else if(favorite.matches("1")){
buttonHeart.setImageResource(R.drawable.heartred);
}
buttonHeart.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
if (arg0 != null) {
FragmentOne_DbAdapter database=new FragmentOne_DbAdapter(context);
database.open();
if(favorite.matches("0")) {
database.updateItemFavorite(_id,"1");
buttonHeart.setImageResource(R.drawable.heartred);
//Toast.makeText(arg0.getContext(),favorite,Toast.LENGTH_LONG).show();
}else if(favorite.matches("1")){
database.updateItemFavorite(_id, "0");
buttonHeart.setImageResource(R.drawable.heart);
//Toast.makeText(arg0.getContext(),favorite,Toast.LENGTH_LONG).show();
}
}
}
});
}
#Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
// TODO Auto-generated method stub
return LayoutInflater.from(context).inflate(R.layout.fragment_fragment_one_slview, parent, false);
}
}
and here is my fragment..
package com.magicstarme.virtualsongbook;
import android.content.Context;
import android.database.Cursor;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.app.ActionBar;
import android.support.v7.app.ActionBarActivity;
import android.text.Editable;
import android.text.TextWatcher;
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.AdapterView;
import android.widget.EditText;
import android.widget.FilterQueryProvider;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.SearchView;
import android.widget.SimpleCursorAdapter;
import android.widget.TabHost;
import android.widget.Toast;
import android.widget.ToggleButton;
import java.util.ArrayList;
/**
* A simple {#link Fragment} subclass.
* Activities that contain this fragment must implement the
* {#link FragmentOne.OnFragmentInteractionListener} interface
* to handle interaction events.
* Use the {#link FragmentOne#newInstance} factory method to
* create an instance of this fragment.
*/
public class FragmentOne extends Fragment {
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
private OnFragmentInteractionListener mListener;
public FragmentOne() {
// Required empty public constructor
}
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* #param param1 Parameter 1.
* #param param2 Parameter 2.
* #return A new instance of fragment FragmentOne.
*/
// TODO: Rename and change types and number of parameters
public static FragmentOne newInstance(String param1, String param2) {
FragmentOne fragment = new FragmentOne();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}
private FragmentOne_DbAdapter dbHelper;
private SimpleCursorAdapter dataAdapter;
private FragmentOne_Adapter FragmentOneAdapter;
ListView listView;
EditText player1ESearch;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootView = inflater.inflate(R.layout.fragment_fragment_one, container, false);
TabHost host = (TabHost) rootView.findViewById(R.id.tabHost);
host.setup();
//Tab 1
TabHost.TabSpec spec = host.newTabSpec("SONG LIST");
spec.setContent(R.id.tab1);
spec.setIndicator("SONG LIST");
host.addTab(spec);
player1ESearch = (EditText) rootView.findViewById(R.id.player1Search);
listView = (ListView) rootView.findViewById(R.id.slPlayer1ListView);
dbHelper = new FragmentOne_DbAdapter(getActivity());
dbHelper.open();
//Clean all data
//dbHelper.deleteAllPlayer1();
//Add some data
dbHelper.insertPlayer1Songlist();
//Generate ListView from SQLite Database
displayPlayer1ListView();
ImageButton dplayer1ESearch=(ImageButton) rootView.findViewById(R.id.delete);
dplayer1ESearch.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
player1ESearch.setText("");
}
});
//Tab 2
spec = host.newTabSpec("NEW SONGS");
spec.setContent(R.id.tab2);
spec.setIndicator("NEW SONGS");
host.addTab(spec);
//Tab 3
spec = host.newTabSpec("FAVORITES");
spec.setContent(R.id.tab3);
spec.setIndicator("FAVORITES");
host.addTab(spec);
return rootView;
}
private void displayPlayer1ListView() {
Cursor cursor = dbHelper.fetchAllPlayer1();
FragmentOneAdapter = new FragmentOne_Adapter(getActivity(), cursor, 0);
listView.setAdapter(FragmentOneAdapter);
player1ESearch.addTextChangedListener(new TextWatcher() {
public void afterTextChanged(Editable s) {
}
public void beforeTextChanged(CharSequence s, int start,
int count, int after) {
}
public void onTextChanged(CharSequence s, int start,
int before, int count) {
FragmentOneAdapter.getFilter().filter(s.toString());
}
});
FragmentOneAdapter.setFilterQueryProvider(new FilterQueryProvider() {
public Cursor runQuery(CharSequence constraint) {
return dbHelper.fetchPlayer1ByTitle(constraint.toString());
}
});
}
// TODO: Rename method, update argument and hook method into UI event
public void onButtonPressed(Uri uri) {
if (mListener != null) {
mListener.onFragmentInteraction(uri);
}
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnFragmentInteractionListener) {
mListener = (OnFragmentInteractionListener) context;
} else {
throw new RuntimeException(context.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 OnFragmentInteractionListener {
// TODO: Update argument type and name
void onFragmentInteraction(Uri uri);
}
}
Simple call notifyDataSetChanged(); when you click in button for refresh your ListView
buttonHeart.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
...
notifyDataSetChanged();
}
});
Basically your list view is connected with adapter. You need to notify this adapter to redraw the list view. Can you give more information where exactly your button click listener code is (in which class). If it is inside your adapter class (like I suppose) you can do something like this in your click listener code (some where inside the method public void onClick(View arg0) ) :
YourAdapterClassName.this.notifyDataSetChanged();
Update your adapter constructor to accept the Fragment as a parameter.
Something like :
public CustomAdapter(Context context, int id, HomeFragment fragment) {
this.fragment = fragment;
}
then you call methods using the fragment variable.
fragment.doSomething();
and in this method you can refresh the list using notifyDataSetChanged();
I am beginner at android developing and i am making very simple app that has a content inside and you can edit the font type and size of the content using settings fragment .
a problem is facing me which when i set my fonts settings it saved well. i close the app and get back to the content activity and it works very well but when i get back to the settings fragment it returns the font type JUST . to its default value.the font size stays at user determinded value .
This is settings fragment code
package com.example.ali.azkarv10;
import android.content.Context;
import android.content.SharedPreferences;
import android.graphics.Typeface;
import android.net.Uri;
import android.os.Bundle;
import android.preference.SwitchPreference;
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.CompoundButton;
import android.widget.SeekBar;
import android.widget.Spinner;
import android.widget.Switch;
import android.widget.TextView;
import android.widget.Toast;
/**
* A simple {#link Fragment} subclass.
* Activities that contain this fragment must implement the
* {#link SettingsFragment.OnFragmentInteractionListener} interface
* to handle interaction events.
* Use the {#link SettingsFragment#newInstance} factory method to
* create an instance of this fragment.
*/
public class SettingsFragment extends Fragment {
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
// TODO: Rename and change types of parameters
private static final String fonts[]={"fonts/blacksugar.ttf","fonts/baghdad.ttf","fonts/bdavat.ttf","fonts/fsmetal.ttf","fonts/kufi.ttf","fonts/tachkili.ttf","fonts/yassin.ttf"};
private String mParam1;
private String mParam2;
SharedPreferences sharedPreferences;
SharedPreferences.Editor edit;
Switch switchWidget;
TextView textView;
SeekBar seekBar;
TextView tester;
Spinner spinner;
SpinnerAdapter spinnerAdapter;
private OnFragmentInteractionListener mListener;
public SettingsFragment() {
// Required empty public constructor
}
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* #param param1 Parameter 1.
* #param param2 Parameter 2.
* #return A new instance of fragment SettingsFragment.
*/
// TODO: Rename and change types and number of parameters
public static SettingsFragment newInstance(String param1, String param2) {
SettingsFragment fragment = new SettingsFragment();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
sharedPreferences=getActivity().getSharedPreferences("data",Context.MODE_PRIVATE);
edit=sharedPreferences.edit();
View v= inflater.inflate(R.layout.fragment_settings, container, false);
switchWidget=(Switch)v.findViewById(R.id.switch1);
switchWidget.setChecked(sharedPreferences.getBoolean("buzzer",false));
switchWidget.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if(isChecked){
edit.putBoolean("buzzer",true);
// Toast.makeText(getActivity(),"true",Toast.LENGTH_LONG).show();
edit.commit();
}else {
edit.putBoolean("buzzer",false).commit();
//Toast.makeText(getActivity(),"false",Toast.LENGTH_LONG).show();
}
}
});
tester=(TextView)v.findViewById(R.id.textSizeTester);
seekBar=(SeekBar)v.findViewById(R.id.seekBar);
seekBar.setProgress(sharedPreferences.getInt("fontSize",20)-10);
tester.setTextSize(seekBar.getProgress()+10);
seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
int progress_Value;
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
progress_Value=progress;
edit.putInt("fontSize",10+progress).commit();
tester.setTextSize(((float)10+progress));
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
edit.putInt("fontSize",10+progress_Value).commit();
tester.setTextSize(((float)10+progress_Value));
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
edit.putInt("fontSize",10+progress_Value).commit();
tester.setTextSize(((float)10+progress_Value));
}
});
Typeface typeface=Typeface.createFromAsset(getActivity().getAssets(),"fonts/blacksugar.ttf");
textView=(TextView)v.findViewById(R.id.textsets);
textView.setTypeface(typeface);
spinner=(Spinner)v.findViewById(R.id.spinner);
spinnerAdapter=new SpinnerAdapter(getActivity(),fonts);
spinner.setAdapter(spinnerAdapter);
tester.setTypeface(Typeface.createFromAsset(getActivity().getAssets(),sharedPreferences.getString("fontType","fonts/fsmetal.ttf")));
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
switch(position){
case 0:edit.putString("fontType",fonts[0]).commit();
tester.setTypeface(Typeface.createFromAsset(getActivity().getAssets(),sharedPreferences.getString("fontType","")));
break;
case 1:edit.putString("fontType",fonts[1]).commit();
tester.setTypeface(Typeface.createFromAsset(getActivity().getAssets(),sharedPreferences.getString("fontType","")));
break;
case 2:edit.putString("fontType",fonts[2]).commit();
tester.setTypeface(Typeface.createFromAsset(getActivity().getAssets(),sharedPreferences.getString("fontType","")));
break;
case 3:edit.putString("fontType",fonts[3]).commit();
tester.setTypeface(Typeface.createFromAsset(getActivity().getAssets(),sharedPreferences.getString("fontType","")));
break;
case 4:edit.putString("fontType",fonts[4]).commit();
tester.setTypeface(Typeface.createFromAsset(getActivity().getAssets(),sharedPreferences.getString("fontType","")));
break;
case 5:edit.putString("fontType",fonts[5]).commit();
tester.setTypeface(Typeface.createFromAsset(getActivity().getAssets(),sharedPreferences.getString("fontType","")));
break;
case 6:edit.putString("fontType",fonts[6]).commit();
tester.setTypeface(Typeface.createFromAsset(getActivity().getAssets(),sharedPreferences.getString("fontType","")));
break;
}
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
// textView.setText(sharedPreferences.getString("fontType",""));
return v;
}
// TODO: Rename method, update argument and hook method into UI event
public void onButtonPressed(Uri uri) {
if (mListener != null) {
mListener.onFragmentInteraction(uri);
}
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnFragmentInteractionListener) {
mListener = (OnFragmentInteractionListener) context;
} else {
throw new RuntimeException(context.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 OnFragmentInteractionListener {
// TODO: Update argument type and name
void onFragmentInteraction(Uri uri);
}
}
please help
onItemSelectedListener is called the first time with position = 0.
So you are overriding the preference with "fonts/blacksugar.ttf" when SettingsFragment is created.
You should get "fontType" preference and select it in the Spinner:
Spinner spinner = (Spinner) v.findViewById(R.id.spinner);
ArrayAdapter<String> spinnerAdapter = new ArrayAdapter<>(getActivity(), R.layout.spinner_layout, fonts);
spinner.setAdapter(spinnerAdapter);
spinner.setSelection(spinnerAdapter.getPosition(sharedPreferences.getString("fontType","fonts/blacksugar.ttf")));
spinner.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
edit.putString("fontType",fonts[position]).commit();
tester.setTypeface(Typeface.createFromAsset(getActivity().getAssets(),sharedPreferences.getString("fontType","")));
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
Typeface typeface=Typeface.createFromAsset(getActivity().getAssets(),"fonts/blacksugar.ttf");
textView=(TextView)v.findViewById(R.id.textsets);
textView.setTypeface(typeface);
I think your problem could be here. You are setting the typeface of the textview yourself and not reading from the file.
Also,
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
switch(position){
case 0:edit.putString("fontType",fonts[0]).commit();
tester.setTypeface(Typeface.createFromAsset(getActivity().getAssets(),sharedPreferences.getString("fontType","")));
break;
case 1:edit.putString("fontType",fonts[1]).commit();
tester.setTypeface(Typeface.createFromAsset(getActivity().getAssets(),sharedPreferences.getString("fontType","")));
break;
case 2:edit.putString("fontType",fonts[2]).commit();
tester.setTypeface(Typeface.createFromAsset(getActivity().getAssets(),sharedPreferences.getString("fontType","")));
break;
case 3:edit.putString("fontType",fonts[3]).commit();
tester.setTypeface(Typeface.createFromAsset(getActivity().getAssets(),sharedPreferences.getString("fontType","")));
break;
case 4:edit.putString("fontType",fonts[4]).commit();
tester.setTypeface(Typeface.createFromAsset(getActivity().getAssets(),sharedPreferences.getString("fontType","")));
break;
case 5:edit.putString("fontType",fonts[5]).commit();
tester.setTypeface(Typeface.createFromAsset(getActivity().getAssets(),sharedPreferences.getString("fontType","")));
break;
case 6:edit.putString("fontType",fonts[6]).commit();
tester.setTypeface(Typeface.createFromAsset(getActivity().getAssets(),sharedPreferences.getString("fontType","")));
break;
}
}
The switch statement is redundant. Just do,
edit.putString("fontType",fonts[position]).commit();