Why is sharedPreference not saving here? - java

I am trying to set some strings in the sharedPreferences but when I restart the app , the preference is coming empty and so "null" is returned in getString method .
public class settingsView extends Fragment {
DataSnapshot citiesSnap;
Spinner theaterSpinner, citySpinner;
String selectedCity, selectedTheater;
String[] cities = {"Bagalkot", "Belgaum", "Bellary", "Bijapur", "Chitradurga", "Davanagere", "Dharwad", "Gadag", "Hassan", "Hosapete", "Hospet", "Hubli", "Mysore", "Shimoga", "Tumkur"};
List<String>theaters ;
public settingsView() {
Log.d("testing" , "settingsview constructor called");
citiesSnap = null;
theaterSpinner = null;
citySpinner = null;
selectedCity = null;
selectedTheater = null;
theaters = null ;
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
Log.d("testing", "Called onActivityCreated");
citySpinner = (Spinner) getActivity().findViewById(R.id.citySpinner);
theaterSpinner = (Spinner) getActivity().findViewById(R.id.theaterSpinner);
final SharedPreferences mSettings = this.getActivity().getPreferences(Context.MODE_PRIVATE);
selectedCity = mSettings.getString("selectedCity", "null" );
selectedTheater = mSettings.getString("selectedTheater", "null");
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity().getApplicationContext(), android.R.layout.simple_selectable_list_item, cities);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
citySpinner.setAdapter(adapter);
updateTheatersSpinner(selectedCity);
if(theaters!=null)
theaterSpinner.setSelection(theaters.indexOf(selectedTheater));
FirebaseDatabase.getInstance().getReference("movies/karnataka").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
citiesSnap = dataSnapshot;
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
citySpinner.setOnItemSelectedListener(new Spinner.OnItemSelectedListener() {
#Override
public void onItemSelected(Spinner parent, View view, int position, long id) {
updateTheatersSpinner(citySpinner.getSelectedItem().toString());
mSettings.edit().putString("selectedCity" , citySpinner.getSelectedItem().toString()).commit();
}
});
theaterSpinner.setOnItemSelectedListener(new Spinner.OnItemSelectedListener() {
#Override
public void onItemSelected(Spinner parent, View view, int position, long id) {
mSettings.edit().putString("selectedTheater" , theaterSpinner.getSelectedItem().toString()).commit() ;
}
});
}
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.settingsview, container, false);
return view;
}
#Override
public void onSaveInstanceState(#NonNull Bundle outState) {
Log.d("testing" , "On save instancestate") ;
super.onSaveInstanceState(outState);
SharedPreferences preferences = this.getActivity().getPreferences(Context.MODE_PRIVATE);
preferences.edit().putString("selectedCity", selectedCity).putString("selectedTheater", theaterSpinner.getSelectedItem().toString()).commit();
}
public void updateTheatersSpinner(String city) {
if (citiesSnap != null) {
ArrayList<String> theaterlist = new ArrayList<>();
for (DataSnapshot snapshot : citiesSnap.child(city).getChildren()) {
theaterlist.add(snapshot.getKey());
}
this.theaters = theaterlist ;
Log.d("firebasedata", "theaterlist : " + theaterlist.toString());
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity().getApplicationContext(), android.R.layout.simple_selectable_list_item, theaterlist);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
this.theaterSpinner.setAdapter(adapter);
}
}
}

You have the class fields selectedCity and selectedTheater which you never update so they are always null, but then in onSaveInstanceState you save those fields, so when your activity closes, it writes null to both fields in the SharedPreferences. You should update those fields when the spnner changes.
citySpinner.setOnItemSelectedListener(new Spinner.OnItemSelectedListener() {
#Override
public void onItemSelected(Spinner parent, View view, int position, long id) {
selectedCity = citySpinner.getSelectedItem().toString(); // <--
updateTheatersSpinner(selectedCity);
mSettings.edit().putString("selectedCity", selectedCity).commit();
}
});
theaterSpinner.setOnItemSelectedListener(new Spinner.OnItemSelectedListener() {
#Override
public void onItemSelected(Spinner parent, View view, int position, long id) {
selectedTheater = theaterSpinner.getSelectedItem().toString(); // <--
mSettings.edit().putString("selectedTheater", selectedTheater).commit();
}
});
Then, in onSaveInstanceState
#Override
public void onSaveInstanceState(#NonNull Bundle outState) {
Log.d("testing" , "On save instancestate") ;
super.onSaveInstanceState(outState);
SharedPreferences preferences = this.getActivity().getPreferences(Context.MODE_PRIVATE);
preferences.edit()
.putString("selectedCity", selectedCity)
.putString("selectedTheater", selectedTheater)
.commit();
}

Related

SearchBar with TabLayout and Viewpager. SearchBar (EditText) doesn't filter through users, nor events

My SearchFragment is the host Fragment for two other Fragments: SearchUsersFragment and SearchEventsFragment. The way I have it organized is the TabLayout and Viewpager are in the SearchFragment, and the RecyclerView, Adapters, and ArrayList are in the two child Fragments.
What I would like to do is implement a SearchBar (EditText), which I have already done in the SearchFragment and use that SearchBar to filter through the users (in SearchUsersFragment) and events (in SearchEventsFragment).
The problem: is I have written two methods in each child Fragment searchusers(); and readUsers();. The method searchUsers(); I made public so that I can add it to the SearchFragment in onTextChangedListener, but still the users whose names begin with the letters that I type into the SearchBar aren't coming up.
Can someone please tell me how to fix this? I have been working on this for 3 days and can't get the users or events to come up that start with the letters someone types in the SearchBar.
SearchFragment
public class SearchFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_search, container, false);
final TabLayout tabLayout = v.findViewById(R.id.tab_layout);
final ViewPager viewPager = v.findViewById(R.id.viewpager);
tabLayout.addTab(tabLayout.newTab().setIcon(R.drawable.icon_people_black));
tabLayout.addTab(tabLayout.newTab().setIcon(R.drawable.icon_event_available_black));
ViewPagerAdapter viewPagerAdapter = new ViewPagerAdapter(getChildFragmentManager());
viewPagerAdapter.addFragment(new SearchUsersFragment(), "");
viewPagerAdapter.addFragment(new SearchEventsFragment(), "");
viewPager.setAdapter(viewPagerAdapter);
viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
tabLayout.addOnTabSelectedListener(new TabLayout.ViewPagerOnTabSelectedListener(viewPager));
EditText searchBar = v.findViewById(R.id.search_bar);
searchBar.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) {
FragmentManager fragmentManager = getChildFragmentManager();
SearchUsersFragment searchUsersFragment = (SearchUsersFragment) fragmentManager.findFragmentById(R.id.fragment_search_users);
if (searchUsersFragment != null) {
searchUsersFragment.searchUsers(s.toString().toLowerCase());
}
}
#Override
public void afterTextChanged(Editable s) {
}
});
return v;
}
static class ViewPagerAdapter extends FragmentPagerAdapter {
private ArrayList<Fragment> mFragments;
private ArrayList<String> mTitles;
ViewPagerAdapter(#NonNull FragmentManager fm) {
super(fm);
this.mFragments = new ArrayList<>();
this.mTitles = new ArrayList<>();
}
#NonNull
#Override
public Fragment getItem(int position) {
return mFragments.get(position);
}
#Override
public int getCount() {
return mFragments.size();
}
void addFragment(Fragment fragment, String title) {
mFragments.add(fragment);
mTitles.add(title);
}
#Nullable
#Override
public CharSequence getPageTitle(int position) {
return mTitles.get(position);
}
}
}
SearchUsersFragment
public class SearchUsersFragment extends Fragment {
RecyclerView mRecyclerView;
UserAdapter mUserAdapter;
List<User> mUserList;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_search_users, container, false);
mRecyclerView = view.findViewById(R.id.recycler_view);
mRecyclerView.setHasFixedSize(true);
mRecyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
mUserList = new ArrayList<>();
mUserAdapter = new UserAdapter(getContext(), mUserList, true);
mRecyclerView.setAdapter(mUserAdapter);
readUsers();
return view;
}
public void searchUsers(String s) {
Query query = FirebaseDatabase.getInstance().getReference("Users").orderByChild("username").startAt(s).endAt(s + "\uf8ff");
query.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
mUserList.clear();
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
User user = snapshot.getValue(User.class);
if (user != null) {
mUserList.add(user);
}
}
mUserAdapter.notifyDataSetChanged();
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
private void readUsers() {
final FirebaseUser firebaseUser = FirebaseAuth.getInstance().getCurrentUser();
DatabaseReference reference = FirebaseDatabase.getInstance().getReference("Users");
reference.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
mUserList.clear();
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
User user = snapshot.getValue(User.class);
if (firebaseUser != null && user != null && !user.getId().equals(firebaseUser.getUid())) {
mUserList.add(user);
}
}
mUserAdapter.notifyDataSetChanged();
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
}
SearchEventsFragment
public class SearchEventsFragment extends Fragment {
RecyclerView mRecyclerView;
SearchEventsAdapter mSearchEventsAdapter;
List<Post> mPostList;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_search_events, container, false);
mRecyclerView = view.findViewById(R.id.recycler_view);
mRecyclerView.setHasFixedSize(true);
mRecyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
mPostList = new ArrayList<>();
mSearchEventsAdapter = new SearchEventsAdapter(getContext(), mPostList);
mRecyclerView.setAdapter(mSearchEventsAdapter);
readEvents();
return view;
}
private void readEvents() {
DatabaseReference reference = FirebaseDatabase.getInstance().getReference("Posts");
reference.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
mPostList.clear();
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
Post post = snapshot.getValue(Post.class);
if (post != null) {
mPostList.add(post);
}
}
mSearchEventsAdapter.notifyDataSetChanged();
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
}
I have used a searchView here for filtering 3 fragments together
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
mAdapter.getFilter().filter(newText);
fAdapter.getFilter().filter(newText);
rAdapter.getFilter().filter(newText);
return false;
}
});
And then in my adapters I have done implements Filterable and
#Override
public Filter getFilter() {
return myFilter;
}
private Filter myFilter = new Filter() {
#Override
protected FilterResults performFiltering(CharSequence constraint) {
ArrayList<String> filterList = new ArrayList<>();
if (constraint == null || constraint.length() == 0) {
filterList.addAll(MainActivity.Db.getWholeData());
} else {
String toFilter = constraint.toString().toLowerCase().trim();
for (String item : MainActivity.Db.getWholeData()) {
if (item.toLowerCase().contains(toFilter)) {
filterList.add(item);
}
}
}
clickPurposeFav = filterList;
FilterResults filterResults = new FilterResults();
filterResults.values = filterList;
return filterResults;
}
#Override
protected void publishResults(CharSequence constraint, FilterResults results) {
MainActivity.arrList.clear();
MainActivity.arrList.addAll((List) results.values);
}
};

Remove Duplicate Item name in ArrayList

Please help me. I want to show the username only once from firebase. Although the user have multiple record in the firebase, I just want to view the name of user who make order. The user can make multiple order, but I just want to show their name once.
I tried many ways but can't succeed. Someone who know about this? Thank you very much.
public void onCreate(Bundle savedInstanceState) {
UID = this.getArguments().getString("UID");
mDatabase = FirebaseDatabase.getInstance().getReference();
mStorage = FirebaseStorage.getInstance();
mItems = new ArrayList<>();
wordDulicate = new ArrayList<>();
tempList = new ArrayList<>();
if(UID != null){
mItemsKey = new ArrayList<>();
mOrderedItemRef = mDatabase.child("OrderedItem");
Log.d(TAG, " mOrderedItemRef:" + mOrderedItemRef);
mOrderedItemVEL = mOrderedItemRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
mItems.clear();
mItemsKey.clear();
wordDulicate.clear();
Log.d(TAG, "onDataChange");
for (DataSnapshot d : dataSnapshot.getChildren()) {
OrderedItem orderedItem = d.getValue(OrderedItem.class);
Log.d(TAG, "orderedItem:" + orderedItem.getUserName());
mItems.add(orderedItem);
mItemsKey.add(d.getKey());
}
updateUI();
}
#Override
public void onCancelled (DatabaseError databaseError){
Log.d(TAG, "get item databaseError: "+databaseError);
}
});
}
else{
Log.d(TAG, "UID: "+UID);
}
super.onCreate(savedInstanceState);
}
#Override
public void onDestroy(){
super.onDestroy();
// if (mItemRef != null) mItemRef.removeEventListener(mItemVEL);
}
#Override
public void onDetach(){
super.onDetach();
// if (mItemRef != null) mItemRef.removeEventListener(mItemVEL);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_admin_list_user_order, container, false);
mItemRecyclerView = (RecyclerView) view.findViewById(R.id.admin_order_recycler_view);
DividerItemDecoration dividerItemDecoration = new DividerItemDecoration(mItemRecyclerView.getContext(), new LinearLayoutManager(getActivity()).getOrientation());
mItemRecyclerView.addItemDecoration(dividerItemDecoration);
mItemRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
return view;
}
private void updateUI(){
Log.d(TAG, "Enter updateUI(); mItems: " + mItems);
mAdapter = new ItemAdapter(mItems);
mItemRecyclerView.setAdapter(mAdapter);
}
private class ItemHolder extends RecyclerView.ViewHolder{
OrderedItem mItems;
TextView mNameTextView;
ItemHolder(final View itemView){
super(itemView);
mNameTextView = (TextView) itemView.findViewById(R.id.textview_username);
/* if (UID != null) {
itemView.setOnClickListener(new View.OnClickListener() {
#SuppressLint("LongLogTag")
#Override
public void onClick(View view) {
Log.d(TAG, "UID != null");
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder
.setMessage("Delete This Item?")
.setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
deleteItem(mItems);
}
}).setNegativeButton(R.string.no, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// User cancelled the dialog
}
});
AlertDialog dialog = builder.create();
dialog.show();
}
});
}*/
}
void bindData(OrderedItem s){
mItems = s;
mNameTextView.setText(s.getUserName());
}
}
private class ItemAdapter extends RecyclerView.Adapter<ItemHolder>{
private ArrayList<OrderedItem> mItems;
ItemAdapter(ArrayList<OrderedItem> Items){
mItems = Items;
}
#Override
public ItemHolder onCreateViewHolder(ViewGroup parent, int viewType) {
LayoutInflater layoutInflater = LayoutInflater.from(getActivity());
View view = layoutInflater.inflate(R.layout.admin_listed_user_order,parent,false);
return new ItemHolder(view);
}
#Override
public void onBindViewHolder(ItemHolder holder, int position) {
OrderedItem s = mItems.get(position);
holder.bindData(s);
}
#Override
public int getItemCount() {
return mItems.size();
}
}
}
Since you rely on a key and a value, why not use a map instead? Maps have a key and a value, and you can check whether or not an item with a key is present by getting the key, instead of having to iterate through the list and find duplicates.
First you need to initialize it:
Map<String, ArrayList<OrderedItem>> items = new HashMap<>();
The value is an ArrayList to keep any existing data
then put the items:
for (DataSnapshot d : dataSnapshot.getChildren()) {
OrderedItem orderedItem = d.getValue(OrderedItem.class);
Log.d(TAG, "orderedItem:" + orderedItem.getUserName());
items.putIfAbsent(d.getKey(), new ArrayList<>());//create a list if it doesn't exist
items.get(d.geyKey()).add(orderedItem);//add the item
}
and clearing with a map is the same as with lists

Issue with PagerAdapter

I try to load the database from firebase database and get this exception. It is about the notifyDataSetChanged. I has tried to put in in getCount() in SlideShowAapter but it has not worked.
Exceptions:
java.lang.IllegalStateException: The application's PagerAdapter changed the adapter's contents without calling PagerAdapter#notifyDataSetChanged!
Expected adapter item count: 0, found: 1 Pager id: com.example.dave.lomoapp:id/slideShow Pager class: class android.support.v4.view.ViewPager
Problematic adapter: class com.example.davenguyen.lomoapp.SlideShowAdapter
at android.support.v4.view.ViewPager.populate(ViewPager.java:1135)
at android.support.v4.view.ViewPager.setCurrentItemInternal(ViewPager.java:662)
at android.support.v4.view.ViewPager.setCurrentItemInternal(ViewPager.java:624)
at android.support.v4.view.ViewPager.setCurrentItem(ViewPager.java:616)
at com.example.davenguyen.lomoapp.HomeFragment$1.run(HomeFragment.java:71)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:7331)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)
This my SlideShowAdapter
public class SlideShowAdapter extends PagerAdapter {
private boolean doNotifyDataSetChangedOnce = false;
private ArrayList<Genre> genresList;
private LayoutInflater inflater;
private Context context;
public SlideShowAdapter(Context context, ArrayList<Genre> images) {
this.context = context;
this.genresList =images;
inflater = LayoutInflater.from(context);
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
container.removeView((View) object);
}
#Override
public int getCount()
{
if (doNotifyDataSetChangedOnce) {
doNotifyDataSetChangedOnce = false;
notifyDataSetChanged();
}
return genresList.size();
}
#Override
public Object instantiateItem(ViewGroup view, int position) {
View myImageLayout = inflater.inflate(R.layout.slide, view, false);
ImageView myImage = (ImageView) myImageLayout
.findViewById(R.id.slideShowImg);
Picasso.with(context).load(genresList.get(position).getImage()).into(myImage);
view.addView(myImageLayout, 0);
view.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
}
});
return myImageLayout;
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view.equals(object);
}
}
This a fragment that has my custom adapter
public class HomeFragment extends Fragment {
private static ViewPager mPager;
private static int currentPage = 0;
private ArrayList<Genre> genreList = new ArrayList<Genre>();
DatabaseReference mref;
public HomeFragment() {
// Required empty public constructor
}
#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);
return v;
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
loadImage();
mPager = (ViewPager) view.findViewById(R.id.slideShow);
mPager.setAdapter(new SlideShowAdapter(getActivity(), genreList));
CircleIndicator indicator = (CircleIndicator) view.findViewById(R.id.indicator);
indicator.setViewPager(mPager);
// Auto start of viewpager
final Handler handler = new Handler();
final Runnable Update = new Runnable() {
public void run() {
if (currentPage == genreList.size()) {
currentPage = 0;
}
mPager.setCurrentItem(currentPage++, true);
}
};
Timer swipeTimer = new Timer();
swipeTimer.schedule(new TimerTask() {
#Override
public void run() {
handler.post(Update);
}
}, 2500, 2500);
}
private void loadImage() {
// Get a reference to our genres
mref = FirebaseDatabase.getInstance().getReference().child("genres");
// Attach a listener to read the data at our genres reference
mref.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
genreList.add (dataSnapshot.getValue(Genre.class));
}
#Override
public void onCancelled(DatabaseError databaseError) {
Log.i("READ_FAIELD","The read failed: " + databaseError.getCode());
}
});
}
}
Thanks in advance
My guess is that the problem is that flag doNotifyDataSetChangedOnce in your adapter. Try to remove that if and call adapter.notifyDataSetChanged() after your image is loaded (in onDataChange).
If this solves the crash but the viewPager is not updated, you might need to add this code in your adapter:
public int getItemPosition(Object object) {
return POSITION_NONE;
}
Write this way :
SlideShowAdapter adapter=new SlideShowAdapter(getActivity(), genreList);
mPager.setAdapter(adapter);
adapter.notifyDataSetChanged();
Instead of
mPager.setAdapter(new SlideShowAdapter(getActivity(), genreList));
Try changing in instantiateItem with this:
View myImageLayout = inflater.inflate(R.layout.slide, view, false);
ImageView myImage = (ImageView) myImageLayout
.findViewById(R.id.slideShowImg);
Picasso.with(context).load(genresList.get(position).getImage()).into(myImage);
.
myImageLayout.addView(myImage, 0);
myImageLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
}
});
return myImageLayout;
And remove :
if (doNotifyDataSetChangedOnce) {
doNotifyDataSetChangedOnce = false;
notifyDataSetChanged();
}

getListView() not working showing null pointer exception

I have a ListFragment OnItemClick is not working; it's basically not getting called. I have been unable to find any errors in my code. Is this somehow a problem with getListView?
I've explored Google and StackOverflow but did not find a solution. Here's my code:
public class FragmentSongs extends ListFragment implements OnFragmentCreatedListener,OnItemClickListener {
static ListView lv;
private static final String TAG = FragmentSongs.class.getSimpleName();
MediaMetadataRetriever metaRetriver1;
Vector<ForPLaylist> gtuMcaBean= new Vector<ForPLaylist>();
Forplaylistadapter adaptor;
String artist="";
static int i=0,f=0,k=0;;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
trial t=new trial();
t.onCreate();
ViewGroup root = (ViewGroup) inflater.inflate(R.layout.playlist, container,false);
metaRetriver1 = new MediaMetadataRetriever();
lv=(ListView) root.findViewById(android.R.id.list);
//data calculation here
lv.setAdapter(adaptor);
// lv = getListView();//showing error here if i call it
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,int position, long id) {
int songIndex=position;
Intent in = new Intent(getActivity(), AndroidBuildingMusicPlayerActivity.class);
in.putExtra("songIndex",songIndex);
startActivityForResult(in, 100);
closefragment();
}
});
return root;
}
OnFragmentCreatedListener listener;
private void closefragment() {
getActivity().getFragmentManager().popBackStack();
}
#Override
public void onFragmentCreated(ArrayList<String> msg) {
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
int songIndex=position;
Intent in = new Intent(null, AndroidBuildingMusicPlayerActivity.class);
in.putExtra("songIndex",songIndex);
startActivityForResult( in,100);
finish();
}
private void finish() {
getActivity().getSupportFragmentManager().beginTransaction().remove(this).commit();
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
Log.d(TAG, "onActivityCreated");
if(savedInstanceState != null) {
Log.d(TAG, "saved variable number: " + savedInstanceState.getInt("number"));
}
super.onActivityCreated(savedInstanceState);
// lv=getListView();
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
// lv = getListView();
}
}
try move your getListView();to onActivityCreated and make sure you call super.onActivityCreated(savedInstanceState) first
I think you should check the code in onItemClick of ListFragment (not the code of onItemClick inside onCreateView method):
Intent in = new Intent(null, AndroidBuildingMusicPlayerActivity.class);
Just change it to:
Intent in = new Intent(getActivity(), AndroidBuildingMusicPlayerActivity.class);

Null class variables implementing interface

I haven't found similar questions, so I'm writing a new one.
I'm developing a little Android app and I have some problems with an interface. The app consists of 3 fragments and a ViewPager. Clicking a button, I show a custom dialog (made my extending the AlertDialog.Builder class). To retrieve data back from the target fragment, I made an interface that I implement in the fragment.
Everything seems to work, but when I try to access fragment class variables inside the overridden methods, they are null! Class variables are initialized in onCreateView fragment method.
Thanks
import android.content.DialogInterface;
public interface BandDialogInterface{
public void onActionCreate(DialogInterface dialog, String name, MyColor color);
public void onActionEdit(DialogInterface dialog, int id, String name, MyColor color);
}
It's a bit messy because I was trying something:
public class EditBandDialog extends AlertDialog.Builder {
private final Band band;
private Spinner listColor;
private EditText inputName;
private DatabaseHelper dbHelper;
private BandDialogInterface bandDialogInterface;
public EditBandDialog(Context context, final Band band){
super(context);
this.band = band;
try{
bandDialogInterface = ((MercenAppActivity)context).getBandsFragment();
Log.d("CONTEXT", ((MercenAppActivity)context).getBandsFragment().toString());
}catch (Exception e){
e.printStackTrace();
}
View dialogView = ((Activity)context).getLayoutInflater().inflate(R.layout.dialog_edit_band, null);
setView(dialogView);
setCancelable(false);
dbHelper = new DatabaseHelper(context);
listColor = (Spinner)dialogView.findViewById(R.id.dialog_edit_band_color);
inputName = (EditText)dialogView.findViewById(R.id.dialog_edit_band_name);
BandColorAdapter adapter = new BandColorAdapter(context);
listColor.setAdapter(adapter);
if(isNewBand()) {
setTitle(R.string.title_new_band);
setPositiveButton("Crea", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
//bandAdapter.insert(new Band(-1, inputName.getText().toString(), ((MyColor) listColor.getSelectedItem())));
//Toast.makeText(getContext(), R.string.toast_band_added, Toast.LENGTH_SHORT).show();
bandDialogInterface.onActionCreate(dialog, inputName.getText().toString(), (MyColor)listColor.getSelectedItem());
}
});
}else{
setTitle(R.string.title_edit_band);
inputName.setText(band.getName());
int pos = 0;
while(((MyColor)listColor.getAdapter().getItem(pos)).getColor() != band.getColor())
pos++;
listColor.setSelection(pos);
setPositiveButton("Modifica", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
//dbHelper.updateBand(dbHelper.getWritableDatabase(), band.getId(), inputName.getText().toString(), ((MyColor) listColor.getSelectedItem()).getColor());
//bandAdapter.update(new Band(band.getId(), inputName.getText().toString(), ((MyColor) listColor.getSelectedItem())));
//Toast.makeText(getContext(), R.string.toast_band_edited, Toast.LENGTH_SHORT).show();
bandDialogInterface.onActionEdit(dialog, band.getId(), inputName.getText().toString(), (MyColor)listColor.getSelectedItem());
}
});
}
setNegativeButton("Annulla", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
}
private boolean isNewBand(){
return band == null;
}
}
class MyColor{
int color;
public MyColor(int color){
this.color = color;
}
public static MyColor fromString(String s){
return new MyColor(Color.parseColor(s));
}
public int getColor(){
return color;
}
}
class BandColorAdapter extends ArrayAdapter<MyColor> implements SpinnerAdapter {
private static final MyColor[] colors = {MyColor.fromString("#D60000"), //ROSSO
MyColor.fromString("#0080FF"), //AZZURRO
MyColor.fromString("#00AD37"), //VERDE
MyColor.fromString("#FFF700"), //GIALLO
MyColor.fromString("#FF8400"), //ARANCIO
MyColor.fromString("#10009C")}; //BLU
public BandColorAdapter(Context context) {
super(context, R.layout.row_band_color, colors);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = LayoutInflater.from(getContext()).inflate(R.layout.row_band_color, parent, false);
}
View bandColor = convertView.findViewById(R.id.band_color_item);
bandColor.setBackgroundColor(getItem(position).getColor());
return convertView;
}
#Override
public View getDropDownView(int position, View convertView, ViewGroup parent) {
if (convertView == null)
{
convertView = LayoutInflater.from(getContext()).inflate(R.layout.row_band_color, parent, false);
}
View bandColor = convertView.findViewById(R.id.band_color_item);
bandColor.setBackgroundColor(getItem(position).getColor());
return convertView;
}
}
And this is the class where I implement the interface:
public class BandsFragment extends Fragment implements BandDialogInterface{
private static final String TAG = "BandsFragment";
private static final boolean D = true;
private DatabaseHelper dbHelper;
private BandAdapter bandAdapter;
private String s;
public BandsFragment(){
}
#Override
public void onActionCreate(DialogInterface dialog, String name, MyColor color) {
//Toast.makeText(getActivity(), "CREATE", Toast.LENGTH_SHORT).show();
//bandAdapter.insert(new Band(0, name, color));
Log.d("CREATE", s);
}
#Override
public void onActionEdit(DialogInterface dialog, int id, String name, MyColor color) {
Toast.makeText(getActivity(), "EDITED", Toast.LENGTH_SHORT).show();
}
/**
* Returns a new instance of this fragment for the given section
* number.
*/
public static BandsFragment newInstance() {
BandsFragment fragment = new BandsFragment();
return fragment;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_bands, container, false);
if (D) Log.d(TAG, "--- onCreateView ---");
dbHelper = new DatabaseHelper(getActivity());
ListView listBands = (ListView)rootView.findViewById(R.id.list_bands);
TextView noBands = (TextView)rootView.findViewById(R.id.no_bands);
bandAdapter = new BandAdapter(getActivity(), noBands);
listBands.setAdapter(bandAdapter);
// if(dbList.size() == 0){
// noBands.setVisibility(View.VISIBLE);
// }else{
// noBands.setVisibility(View.GONE);
// }
listBands.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//TODO something
}
});
registerForContextMenu(listBands);
return rootView;
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
if (D) Log.d(TAG, "--- onAttach ---");
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (D) Log.d(TAG, "--- onCreate ---");
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
if (D) Log.d(TAG, "--- onViewCreated ---");
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
if (D) Log.d(TAG, "--- onActivityCreated ---");
}
#Override
public void onStart() {
super.onStart();
if (D) Log.d(TAG, "--- onStart ---");
}
#Override
public void onResume() {
super.onResume();
if (D) Log.d(TAG, "--- onResume ---");
}
#Override
public void onPause() {
super.onPause();
if (D) Log.d(TAG, "--- onPause ---");
}
#Override
public void onStop() {
super.onStop();
if (D) Log.d(TAG, "--- onStop ---");
}
#Override
public void onDestroyView() {
super.onDestroyView();
if (D) Log.d(TAG, "--- onDestroyView ---");
}
#Override
public void onDestroy() {
super.onDestroy();
if (D) Log.d(TAG, "--- onDestroy ---");
}
#Override
public void onDetach() {
super.onDetach();
if (D) Log.d(TAG, "--- onDetach ---");
}
#Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo)menuInfo;
menu.setHeaderTitle(bandAdapter.getItem(info.position).getName());
getActivity().getMenuInflater().inflate(R.menu.context_band, menu);
MenuItem.OnMenuItemClickListener l = new MenuItem.OnMenuItemClickListener() {
#Override
public boolean onMenuItemClick(MenuItem item) {
onContextItemSelected(item);
return true;
}
};
for(int i = 0; i < menu.size(); ++i){
menu.getItem(i).setOnMenuItemClickListener(l);
}
}
#Override
public boolean onContextItemSelected(MenuItem item) {
AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo)item.getMenuInfo();
switch (item.getItemId()){
case R.id.context_band_edit:
new EditBandDialog(getActivity(), bandAdapter.getItem(info.position)).show();
//Log.d("D",bandAdapter.getItem(info.position).getName());
break;
case R.id.context_band_delete:
/*dbHelper.deleteBand(dbHelper.getWritableDatabase(), bandAdapter.getItem(info.position).getId());
bandAdapter.remove(bandAdapter.getItem(info.position));
bandAdapter.notifyDataSetChanged();*/
bandAdapter.delete(bandAdapter.getItem(info.position));
Toast.makeText(getActivity(), R.string.toast_band_deleted, Toast.LENGTH_SHORT).show();
break;
}
return true;
}
}
class BandAdapter extends ArrayAdapter<Band> implements SpinnerAdapter{
private DatabaseHelper dbHelper;
private TextView noBands;
public BandAdapter(Context context, TextView noBands) {
super(context, R.layout.row_band);
this.noBands = noBands;
dbHelper = new DatabaseHelper(context);
updateAdapter();
}
private void updateAdapter(){
clear();
addAll(dbHelper.getAllBands());
if(noBands != null) {
if (isEmpty()) {
noBands.setVisibility(View.VISIBLE);
} else {
noBands.setVisibility(View.GONE);
}
}
notifyDataSetChanged();
}
public void insert(Band band){
//dbHelper.insertBand(dbHelper.getWritableDatabase(), band.getName(), band.getColor());
Toast.makeText(getContext(), "ADDED", Toast.LENGTH_SHORT).show();
updateAdapter();
}
public void update(Band band){
dbHelper.updateBand(dbHelper.getWritableDatabase(), band.getId(), band.getName(), band.getColor());
updateAdapter();
}
public void delete(Band band){
dbHelper.deleteBand(dbHelper.getWritableDatabase(), band.getId());
updateAdapter();
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// Get the data item for this position
Band band = getItem(position);
// Check if an existing view is being reused, otherwise inflate the view
if (convertView == null) {
convertView = LayoutInflater.from(getContext()).inflate(R.layout.row_band, parent, false);
}
// Lookup view for data population
TextView bandName = (TextView) convertView.findViewById(R.id.band_name);
View bandColor = (View) convertView.findViewById(R.id.band_color);
bandColor.setBackgroundColor(band.getColor());
// Populate the data into the template view using the data object
bandName.setText(band.getName());
// Return the completed view to render on screen
return convertView;
}
#Override
public View getDropDownView(int position, View convertView, ViewGroup parent) {
if (convertView == null)
{
convertView = LayoutInflater.from(getContext()).inflate(R.layout.row_band, parent, false);
}
Band band = getItem(position);
TextView bandName = (TextView) convertView.findViewById(R.id.band_name);
View bandColor = (View) convertView.findViewById(R.id.band_color);
bandColor.setBackgroundColor(band.getColor());
// Populate the data into the template view using the data object
bandName.setText(band.getName());
return convertView;
}
}

Categories

Resources