I have a ListView fragment that has the option to save specific table values. You can click a button to toggle the table to only show saved values. When the toggle is active instead of saving you have the option to delete values. I have noticed however that while the delete will delete the value permanently so long as the app is open, If i close the app and reopen it, the value will reappear. Also if I delete the app and reinstall this same value reappears. I'm not sure how this value is getting added in and why it refuses to go. Debugging shows me saving the correct values in SharedPreferences but that does not stay.
EDIT: After some more testing it appears that the first item saved in the specific SharedPreferences remains permanently saved. It cannot be removed and all other values saved will not remain there.
Fragment:
package layout;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.preference.PreferenceManager;
import android.support.design.widget.FloatingActionButton;
import android.support.v4.widget.SwipeRefreshLayout;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.SearchView;
import android.widget.TextView;
import android.os.StrictMode;
import com.tble.brgo.HTMLPull;
import com.tble.brgo.InfoArticle;
import com.tble.brgo.R;
import android.widget.AdapterView.OnItemClickListener;
import java.io.IOException;
import java.lang.reflect.Array;
import java.util.ArrayList;
import android.text.TextUtils;
import java.util.HashSet;
import java.util.Set;
/**
* A simple {#link Fragment} subclass.
* Use the {#link Websites#newInstance} factory method to
* create an instance of this fragment.
*/
public class Websites extends Fragment implements SearchView.OnQueryTextListener, displayInterface {
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private SearchView mSearchView;
private ListView mListView;
public Boolean toggle = false;
public ArrayList<InfoArticle> mData = new ArrayList<InfoArticle>();
public StandardCellAdapter mAdapter;
public ArrayList<InfoArticle> fDataSet = new ArrayList<InfoArticle>();
public Websites webTable;
public Websites() {
// Required empty public constructor
}
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* #return A new instance of fragment Websites.
*/
// TODO: Rename and change types and number of parameters
public static Websites newInstance() {
Websites fragment = new Websites();
Bundle args = new Bundle();
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
toggle = false;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_websites, container, false);
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
.permitAll().build();
StrictMode.setThreadPolicy(policy);
ArrayList<InfoArticle> data = new ArrayList<InfoArticle>();
webTable = this;
try {
data = getData();
} catch (IOException e) {
e.printStackTrace();
}
mListView = (ListView) view.findViewById(R.id.WebsiteTable);
final StandardCellAdapter adapter = new StandardCellAdapter(getActivity(), data, 1,this);
fDataSet = data;
mData = data;
mListView.setAdapter(adapter);
mAdapter = adapter;
mSearchView = (SearchView) view.findViewById(R.id.searchView);
mListView.setTextFilterEnabled(true);
FloatingActionButton myFab = (FloatingActionButton) view.findViewById(R.id.dataToggle);
myFab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
toggleView();
}
});
setupSearchView();
final SwipeRefreshLayout swipeLayout = (SwipeRefreshLayout) view.findViewById(R.id.webRefresh);
swipeLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
try {
mData = getData();
mAdapter = new StandardCellAdapter(getContext(), mData, 1,webTable);
mListView.setAdapter(mAdapter);
} catch (IOException e) {
e.printStackTrace();
}
swipeLayout.setRefreshing(false);
}
});
return view;
}
private void setupSearchView() {
mSearchView.setOnQueryTextListener(this);
mSearchView.setIconifiedByDefault(true);
}
private ArrayList<InfoArticle> getData() throws IOException {
SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(getContext());
int school = sharedPref.getInt("School", 14273);
HTMLPull Connection = new HTMLPull();
Connection.getStaff(school);
Connection.Results.remove(0);
return Connection.Results;
}
#Override
public boolean onQueryTextChange(String newText) {
if (TextUtils.isEmpty(newText)) {
mListView.clearTextFilter();
} else {
mListView.setFilterText(newText);
}
return true;
}
public ArrayList<InfoArticle> toData(ArrayList<String> t, ArrayList<String> d) {
ArrayList<InfoArticle> temp = new ArrayList<InfoArticle>();
if (t.size() == 0) {
temp.add(new InfoArticle("Slide to Save Teachers", "google.com"));
} else {
for (int i = 0; i < t.size(); i++) {
temp.add(new InfoArticle(t.get(i), d.get(i)));
}
}
return temp;
}
#Override
public boolean onQueryTextSubmit(String query) {
return false;
}
private void toggleView(){
if (!toggle) {
SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(getContext());
HashSet<String> defv = new HashSet<String>();
ArrayList<String> teachers = new ArrayList<String>(sharedPref.getStringSet("teachPref", defv));
ArrayList<String> links = new ArrayList<String>(sharedPref.getStringSet("linkPref", defv));
mAdapter = new StandardCellAdapter(getContext(), toData(teachers, links),2,this);
mListView.setAdapter(mAdapter);
toggle = true;
} else {
mAdapter = new StandardCellAdapter(getContext(), mData, 1,this);
mListView.setAdapter(mAdapter);
toggle = false;
}
}
/**public void displayWebpage(int position){
if (toggle == true) {
WebsiteDisplay fullView = WebsiteDisplay.newInstance(mAdapter.getItem(position).description);
FragmentTransaction transfer = getActivity().getSupportFragmentManager().beginTransaction();
transfer.replace(R.id.fragmentcontainer, fullView).addToBackStack("tag").commit();
} else {
if (!mSearchView.isIconified()) {
for (InfoArticle a : fDataSet) {
if (a.title.equals(((InfoArticle) mListView.getAdapter().getItem(position)).title)) {
WebsiteDisplay fullView = WebsiteDisplay.newInstance(a.description);
FragmentTransaction transfer = getActivity().getSupportFragmentManager().beginTransaction();
transfer.replace(R.id.fragmentcontainer, fullView).addToBackStack("tag").commit();
}
}
} else {
WebsiteDisplay fullView = WebsiteDisplay.newInstance(fDataSet.get(position).description);
FragmentTransaction transfer = getActivity().getSupportFragmentManager().beginTransaction();
transfer.replace(R.id.fragmentcontainer, fullView).addToBackStack("tag").commit();
}
}
}*/
public void displayWebpage(String Link){
WebsiteDisplay fullView = WebsiteDisplay.newInstance(Link);
FragmentTransaction transfer = getActivity().getSupportFragmentManager().beginTransaction();
transfer.replace(R.id.fragmentcontainer, fullView).addToBackStack("tag").commit();
}
}
CellAdapter:
package layout;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.media.Image;
import android.nfc.Tag;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.widget.RecyclerView;
import android.widget.ArrayAdapter;
import android.content.Context;
import android.view.View;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Set;
import android.preference.PreferenceManager;
import android.widget.ImageView;
import android.widget.TextView;
import android.view.LayoutInflater;
import android.view.ViewGroup;
import com.chauthai.swipereveallayout.SwipeRevealLayout;
import com.tble.brgo.InfoArticle;
import com.tble.brgo.R;
import android.graphics.Typeface;
import android.widget.Filterable;
import android.widget.Filter;
import org.w3c.dom.Text;
/**
* Created by Praveen on 8/21/16.
*/
public class StandardCellAdapter extends ArrayAdapter<InfoArticle> implements Filterable {
public ArrayList<InfoArticle> orig;
public ArrayList<InfoArticle> Teachers;
public SwipeRevealLayout swipeV;
public TextView deleteButton;
public TextView saveButton;
public int tableType;
public displayInterface activity;
public Context ct;
public StandardCellAdapter(Context context, ArrayList<InfoArticle> titles, int tableType, displayInterface inter) {
super(context, 0, titles);
this.Teachers = titles;
this.tableType = tableType;
saveButton = new TextView(context);
deleteButton = new TextView(context);
activity = inter;
ct = context;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// Get the data item for this position
String title = getItem(position).title;
String desc = getItem(position).description;
Holder TagHolder = null;
TextView Ctitle;
// Check if an existing view is being reused, otherwise inflate the view
if (convertView == null) {
if (tableType == 0) {
convertView = LayoutInflater.from(getContext()).inflate(R.layout.nclayout, parent, false);
Ctitle = (TextView) convertView.findViewById(R.id.cellTitle);
}
else if(tableType == 1){
convertView = LayoutInflater.from(getContext()).inflate(R.layout.sclayout, parent, false);
Ctitle = (TextView) convertView.findViewById(R.id.cellTitle);
TagHolder = new Holder();
swipeV = (SwipeRevealLayout)convertView.findViewById(R.id.scSwipe);
saveButton = (TextView)convertView.findViewById(R.id.saveButton);
TagHolder.Save = saveButton;
TagHolder.Cell = Ctitle;
convertView.setTag(TagHolder);
}
else{
convertView = LayoutInflater.from(getContext()).inflate(R.layout.tclayout, parent, false);
Ctitle = (TextView) convertView.findViewById(R.id.cellTitle);
TagHolder = new Holder();
swipeV = (SwipeRevealLayout)convertView.findViewById(R.id.tcSwipe);
deleteButton = (TextView) convertView.findViewById(R.id.deleteButton);
TagHolder.Delete = deleteButton;
TagHolder.Cell = Ctitle;
convertView.setTag(TagHolder);
}
}
else {
TagHolder = (Holder) convertView.getTag();
Ctitle = (TextView) convertView.findViewById(R.id.cellTitle);
}
if(tableType == 1) {
TagHolder.Save.setTag(position);
TagHolder.Save.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
saveTeacher((int)v.getTag());
}
});
TagHolder.Cell.setTag(position);
TagHolder.Cell.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
activity.displayWebpage(getItem((int)v.getTag()).description);
}
});
}
else if(tableType == 2) {
TagHolder.Delete.setTag(position);
deleteButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
deleteTeacher((int)v.getTag());
if(Teachers.size() == 0)
Teachers.add(new InfoArticle("Slide to Save Teachers", "google.com"));
notifyDataSetChanged();
}
});
TagHolder.Cell.setTag(position);
TagHolder.Cell.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
activity.displayWebpage(getItem((int)v.getTag()).description);
}
});
}
Typeface customFont = Typeface.SERIF;
Ctitle.setTypeface(customFont);
Ctitle.setText(title);
return convertView;
}
public Filter getFilter() {
return new Filter() {
#Override
protected FilterResults performFiltering(CharSequence constraint) {
final FilterResults oReturn = new FilterResults();
final ArrayList<InfoArticle> results = new ArrayList<InfoArticle>();
if (orig == null)
orig = Teachers;
if (constraint != null) {
if (orig != null && orig.size() > 0) {
for (final InfoArticle g : orig) {
if (g.title.toLowerCase()
.contains(constraint.toString().toLowerCase())) {
results.add(g);
}
}
}
oReturn.values = results;
}
return oReturn;
}
#SuppressWarnings("unchecked")
#Override
protected void publishResults(CharSequence constraint,
FilterResults results) {
Teachers = (ArrayList<InfoArticle>)results.values;
notifyDataSetChanged();
}
};
}
#Override
public void notifyDataSetChanged() {
super.notifyDataSetChanged();
}
public ArrayList<InfoArticle> toIA(ArrayList<String> data){
ArrayList<InfoArticle> converted = new ArrayList<InfoArticle>();
for(String a: data)
{
converted.add(new InfoArticle(a,""));
}
return converted;
}
#Override
public int getCount() {
return Teachers.size();
}
#Override
public InfoArticle getItem(int position) {
return Teachers.get(position);
}
public void saveTeacher(int position){
SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(getContext());
SharedPreferences.Editor editor = sharedPref.edit();
Set<String> teach = sharedPref.getStringSet("teachPref", new HashSet<String>());
teach.add(Teachers.get(position).title);
Set<String> link = sharedPref.getStringSet("linkPref", new HashSet<String>());
link.add(Teachers.get(position).description);
editor.putStringSet("teachPref", teach);
editor.putStringSet("linkPref", link);
editor.apply();
new AlertDialog.Builder(getContext())
.setTitle("Teacher Saved")
.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// continue with delete
}
}).setIcon(android.R.drawable.ic_dialog_alert)
.show();
swipeV.close(true);
}
private void deleteTeacher(int position){
SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(getContext());
SharedPreferences.Editor editor = sharedPref.edit();
Set<String> teach = sharedPref.getStringSet("teachPref", new HashSet<String>());
Set<String> link = sharedPref.getStringSet("linkPref", new HashSet<String>());
teach.remove(Teachers.get(position).title);
link.remove(Teachers.get(position).description);
editor.putStringSet("teachPref", teach);
editor.putStringSet("linkPref", link);
editor.apply();
HashSet<String> defv = new HashSet<String>();
Teachers.remove(position);
new AlertDialog.Builder(getContext())
.setTitle("Teacher Deleted")
.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// continue with delete
}
}).setIcon(android.R.drawable.ic_dialog_alert)
.show();
swipeV.close(false);
}
class Holder{
TextView Delete;
TextView Save;
TextView Cell;
}
}
Related
I am trying to create a form that has a recyclerView for address and above the RecyclerView there is a Button which onClick able to add more address fields inside this RecyclerView but not able to do that instead when the button has clicked the app crashed.
Here is the Log output I got
Process: com.fitness.client, PID: 101621
java.lang.NullPointerException: Attempt to invoke virtual method 'boolean androidx.recyclerview.widget.RecyclerView$ViewHolder.shouldIgnore()' on a null object reference
at androidx.recyclerview.widget.RecyclerView$LayoutManager.removeAndRecycleAllViews(RecyclerView.java:10079)
at androidx.recyclerview.widget.RecyclerView.removeAndRecycleViews(RecyclerView.java:1174)
at androidx.recyclerview.widget.RecyclerView.setAdapterInternal(RecyclerView.java:1197)
at androidx.recyclerview.widget.RecyclerView.setAdapter(RecyclerView.java:1156)
at com.fitness.client.ui.main.fragments.listing.ListingFragment$1.onClick(ListingFragment.java:144)
at android.view.View.performClick(View.java:6608)
at android.view.View.performClickInternal(View.java:6585)
at android.view.View.access$3100(View.java:785)
at android.view.View$PerformClick.run(View.java:25921)
at android.os.Handler.handleCallback(Handler.java:873)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:201)
And here is the code of my fragment
AND btw the BUTTON name is "address"
package com.fitness.client.ui.main.fragments.listing;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.InputType;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.LinearLayout;
import androidx.annotation.NonNull;
import com.fitness.client.BR;
import com.fitness.client.R;
import com.fitness.client.api.RetroFitFactory;
import com.fitness.client.api.product.ProductDetailResponse;
import com.fitness.client.api.user.UserProfileResponse;
import com.fitness.client.api.user.UserService;
import com.fitness.client.base.classes.BaseFragment;
import com.fitness.client.base.classes.BaseRecyclerViewAdapter;
import com.fitness.client.base.classes.BaseViewHolder;
import com.fitness.client.databinding.ItemOfferingBinding;
import com.fitness.client.databinding.ItemProductListingBinding;
import com.fitness.client.objects.Product;
import com.fitness.client.ui.main.fragments.listing.adapter.AddressAdapter;
import com.fitness.client.ui.main.fragments.listing.adapter.DescriptionAdapter;
import com.fitness.client.ui.main.fragments.listing.adapter.EmailAdapter;
import com.fitness.client.ui.main.fragments.listing.adapter.FacilitesAdapter;
import com.fitness.client.ui.main.fragments.listing.adapter.PhoneAdapter;
import com.fitness.client.ui.main.fragments.listing.adapter.TagAdapter;
import com.fitness.client.ui.main.fragments.listing.adapter.TermsAdapter;
import com.fitness.client.ui.main.fragments.listing.adapter.TimingAdapter;
import com.fitness.client.ui.offering.OfferingActivity;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
public class ListingFragment extends BaseFragment<ItemProductListingBinding, ListingViewModel, ListingNavigator> implements ListingNavigator {
public String TAG = "ListingFragment";
private AddressAdapter addressAdapter;
private EmailAdapter emailAdapter;
private FacilitesAdapter facilitesAdapter;
private PhoneAdapter phoneAdapter;
private DescriptionAdapter descriptionAdapter;
private TermsAdapter termsAdapter;
private TagAdapter tagAdapter;
private TimingAdapter timingAdapter;
private OfferingAdapter offeringAdapter;
private LinearLayout addressLayout;
private LinearLayout.LayoutParams layoutParams;
private int ids = 0;
private int hint = 0;
public static ListingFragment getInstance(Context context) {
return (ListingFragment) ListingFragment.instantiate(context, ListingFragment.class.getName());
}
#Override
public int getBindingVariable() {
return BR.listing_view_model;
}
#Override
public int getLayoutId() {
return R.layout.item_product_listing;
}
#Override
public void init(View view, Bundle savedInstances) {
addressAdapter = new AddressAdapter(new ArrayList<>());
emailAdapter = new EmailAdapter(new ArrayList<>());
facilitesAdapter = new FacilitesAdapter(new ArrayList<>());
phoneAdapter = new PhoneAdapter(new ArrayList<>());
descriptionAdapter = new DescriptionAdapter(new ArrayList<>());
termsAdapter = new TermsAdapter(new ArrayList<>());
tagAdapter = new TagAdapter(new ArrayList<>());
timingAdapter = new TimingAdapter(new ArrayList<>());
offeringAdapter = new OfferingAdapter(new ArrayList<>());
getViewDataBinding().addressList.setAdapter(addressAdapter);
getViewDataBinding().emailList.setAdapter(emailAdapter);
getViewDataBinding().facilitiesList.setAdapter(facilitesAdapter);
getViewDataBinding().phoneList.setAdapter(phoneAdapter);
getViewDataBinding().descriptionList.setAdapter(descriptionAdapter);
getViewDataBinding().termsAndConditionsList.setAdapter(termsAdapter);
getViewDataBinding().tagList.setAdapter(tagAdapter);
getViewDataBinding().timingList.setAdapter(timingAdapter);
getViewDataBinding().offeringList.setAdapter(offeringAdapter);
getViewModel().requestData();
// LayoutInflater inflater = (LayoutInflater)
// Objects.requireNonNull(getContext()).getSystemService(Context.LAYOUT_INFLATER_SERVICE);
LayoutInflater inflater = LayoutInflater.from(getContext());
View view1 = inflater != null ? inflater.inflate(R.layout.item_edit_box, null) : null;
// addressLayout =getViewDataBinding().layoutmain;
if (view != null) {
addressLayout = view1 != null ? view1.findViewById(R.id.createLayout) : null;
}
Log.e("Listing Fragment", String.format("Recyler View LAYOUT %s", addressLayout));
// addressLayout = view.findViewById(R.id.createLayout);
layoutParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
layoutParams.setMargins(5, 5, 5, 5);
final int[] i = {0};
getViewDataBinding().address.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
i[0] = i[0] + 1;
// TextView more = new TextView(getContext());
// more.setText(String.format("Address %s", i[0]));
// more.setTextAlignment(View.TEXT_ALIGNMENT_VIEW_START);
// more.setVisibility(View.VISIBLE);
ids++;
hint++;
EditText newEdit = new EditText(getContext());
newEdit.setHint(String.format("Address %s", hint));
newEdit.setId(ids);
newEdit.setMinLines(4);
Log.e("New Edittext: ", String.valueOf(ids));
newEdit.setInputType(InputType.TYPE_CLASS_TEXT);
// addressLayout.addView(more);
addressLayout.addView(newEdit,layoutParams);
getViewDataBinding().addressList.addView(addressLayout);
AddressAdapter addressAdapter1 = new AddressAdapter(new ArrayList<>());
// getViewDataBinding().addressList.addView(addressLayout);
getViewDataBinding().addressList.setAdapter(addressAdapter1);
addressAdapter1.notifyDataSetChanged();
// getViewDataBinding().moreAddress.setAdapter(addressAdapter);
// addressAdapter.notifyDataSetChanged();
// ListingFragment fragment = (ListingFragment) getFragmentManager().findFragmentByTag(TAG);
// if (fragment != null) {
// fragment.addressAdapter.getAdapter().newAddeddata();
// }
// getViewDataBinding().
// getViewDataBinding().moreAddress.setAdapter(addressAdapter);
// addressAdapter.notifyDataSetChanged();
// RecyclerView recyclerView = new RecyclerView(getContext());
// recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
// recyclerView.setHasFixedSize(true);
// recyclerView.setAdapter(addressAdapter);
}
});
}
#Override
public void updateProductList(List<Product> products) {
if (products != null && products.size() > 0) {
for (Product product : products) {
getViewModel().requestProductDetails(product.getId());
}
} else {
showToast("No products found");
}
}
#Override
public void setUpProductDetails(ProductDetailResponse data) {
offeringAdapter.addData(data.getData().getOffer_package());
}
#Override
public void setProfileInformation(UserProfileResponse body) {
getViewDataBinding().name.setText(body.getData().getName());
timingAdapter.addData(body.getData().getTiming_info());
termsAdapter.addData(Collections.singletonList(body.getData().getMerchant_info().getTermscondition()));
Log.e("Listing Fragment", "Terms: " + Collections.singletonList(body.getData().getMerchant_info().getTermscondition()));
tagAdapter.addData(Collections.singletonList(body.getData().getMerchant_info().getBusiness_tags()));
descriptionAdapter.addData(Collections.singletonList(body.getData().getMerchant_info().getDescription()));
addressAdapter.addData(body.getData().getAddress());
if (body.getData().getFacilities_info().getFacilities() != null)
facilitesAdapter.addData(Arrays.asList(body.getData().getFacilities_info().getFacilities().split(",")));
List<String> emailList = Arrays.asList(body.getData().getContact_info().getAlter_email_1(),
body.getData().getContact_info().getAlter_email_2(),
body.getData().getContact_info().getAlter_email_3(),
body.getData().getContact_info().getAlter_email_4());
// emailAdapter.addData(emailList);
emailAdapter.addData(emailList);
Log.e("Listing Fragment", "Email: " + emailList);
// phoneAdapter.addData(body.getData().getContact_info());
List<String> phoneList = Arrays.asList(body.getData().getContact_info().getAlter_mobile_1(),
body.getData().getContact_info().getAlter_mobile_2(),
body.getData().getContact_info().getAlter_mobile_3(),
body.getData().getContact_info().getAlter_mobile_4());
Log.e("Listing Fragment", "Phone Number: " + phoneList);
phoneAdapter.addData(phoneList);
// phoneAdapter.addData(Arrays.asList(body.getData().getContact_info().getAlter_mobile_1(),
// );
getViewDataBinding().update.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
showLoading("Loading", "Please wait while update your profile");
RetroFitFactory.getRetrofitCallFor(UserService.class)
.updateUserProfile();
}
});
}
class OfferingAdapter extends BaseRecyclerViewAdapter<OfferingAdapter.OfferingHolder, ProductDetailResponse.Offer_packageEntity> {
public OfferingAdapter(List<ProductDetailResponse.Offer_packageEntity> data) {
super(data);
}
#NonNull
#Override
public OfferingHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
return new OfferingHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.item_offering, parent, false));
}
class OfferingHolder extends BaseViewHolder<ProductDetailResponse.Offer_packageEntity, ItemOfferingBinding> {
public OfferingHolder(View itemView) {
super(itemView);
}
#Override
protected void bindObject(ProductDetailResponse.Offer_packageEntity object) {
getViewDataBinding().setOffering(object);
getViewDataBinding().viewSch.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(getContext(), OfferingActivity.class);
intent.putParcelableArrayListExtra("data", object.getDays_timing());
startActivity(intent);
}
});
/* adapter.clear();
ProductDetailResponse.Days_timingEntity placeHolder = new ProductDetailResponse.Days_timingEntity();
placeHolder.setDay("Day");
placeHolder.setWeek("Week");
adapter.addData(Collections.singletonList(placeHolder));
adapter.addData(object.getDays_timing());*/
}
}
}
}
Create functions in your adapter, named addItem and removeItem
watch this video for a more detailed explanation
: https://www.youtube.com/watch?v=enTvZm9LOGc&t=247s
Everything works, but after I check the log it shows:
"E/RecyclerView: No adapter attached; skipping layout ".
My home fragment code:
package com.apps.mathar;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.apps.adapter.AdapterRecent;
import com.apps.item.ItemSong;
import com.apps.utils.Constant;
import com.apps.utils.DBHelper;
import com.apps.utils.JsonUtils;
import com.apps.utils.RecyclerItemClickListener;
import com.apps.utils.ZProgressHUD;
import com.google.android.gms.ads.AdListener;
import com.squareup.picasso.Callback;
import com.squareup.picasso.Picasso;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
public class FragmentHome extends Fragment {
DBHelper dbHelper;
RecyclerView recyclerView;
ArrayList<ItemSong> arrayList;
ArrayList<ItemSong> arrayList_recent;
AdapterRecent adapterRecent;
ZProgressHUD progressHUD;
LinearLayoutManager linearLayoutManager;
public ViewPager viewpager;
ImagePagerAdapter adapter;
TextView textView_empty;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
View rootView = inflater.inflate(R.layout.fragment_home, container, false);
setHasOptionsMenu(true);
dbHelper = new DBHelper(getActivity());
progressHUD = ZProgressHUD.getInstance(getActivity());
progressHUD.setMessage(getActivity().getResources().getString(R.string.loading));
progressHUD.setSpinnerType(ZProgressHUD.FADED_ROUND_SPINNER);
textView_empty = (TextView)rootView.findViewById(R.id.textView_recent_empty);
adapter = new ImagePagerAdapter();
viewpager = (ViewPager)rootView.findViewById(R.id.viewPager_home);
viewpager.setPadding(80,20,80,20);
viewpager.setClipToPadding(false);
viewpager.setPageMargin(40);
viewpager.setClipChildren(false);
// viewpager.setPageTransformer(true,new BackgroundToForegroundTransformer());
arrayList = new ArrayList<ItemSong>();
arrayList_recent = new ArrayList<ItemSong>();
recyclerView = (RecyclerView)rootView.findViewById(R.id.recyclerView_home_recent);
linearLayoutManager = new LinearLayoutManager(getActivity(),LinearLayoutManager.HORIZONTAL,false);
recyclerView.setLayoutManager(linearLayoutManager);
recyclerView.setItemAnimator(new DefaultItemAnimator());
recyclerView.setHasFixedSize(true);
if (JsonUtils.isNetworkAvailable(getActivity())) {
new LoadLatestNews().execute(Constant.URL_LATEST);
} else {
Toast.makeText(getActivity(), getResources().getString(R.string.internet_not_conn), Toast.LENGTH_SHORT).show();
}
recyclerView.addOnItemTouchListener(new RecyclerItemClickListener(getActivity(), new RecyclerItemClickListener.OnItemClickListener() {
#Override
public void onItemClick(View view, int position) {
if(JsonUtils.isNetworkAvailable(getActivity())) {
Constant.isOnline = true;
Constant.arrayList_play.clear();
Constant.arrayList_play.addAll(arrayList_recent);
Constant.playPos = position;
((MainActivity)getActivity()).changeText(arrayList_recent.get(position).getMp3Name(),arrayList_recent.get(position).getCategoryName(),position+1,arrayList_recent.size(),arrayList_recent.get(position).getDuration(),arrayList_recent.get(position).getImageBig(),"home");
Constant.context = getActivity();
if(position == 0) {
Intent intent = new Intent(getActivity(), PlayerService.class);
intent.setAction(PlayerService.ACTION_FIRST_PLAY);
getActivity().startService(intent);
}
} else {
Toast.makeText(getActivity(), getResources().getString(R.string.internet_not_conn), Toast.LENGTH_SHORT).show();
}
}
}));
return rootView;
}
private class LoadLatestNews extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
progressHUD.show();
arrayList.clear();
super.onPreExecute();
}
#Override
protected String doInBackground(String... strings) {
try {
String json = JsonUtils.getJSONString(strings[0]);
JSONObject mainJson = new JSONObject(json);
JSONArray jsonArray = mainJson.getJSONArray(Constant.TAG_ROOT);
JSONObject objJson = null;
for (int i = 0; i < jsonArray.length(); i++) {
objJson = jsonArray.getJSONObject(i);
String id = objJson.getString(Constant.TAG_ID);
String cid = objJson.getString(Constant.TAG_CAT_ID);
String cname = objJson.getString(Constant.TAG_CAT_NAME);
String artist = objJson.getString(Constant.TAG_ARTIST);
String name = objJson.getString(Constant.TAG_SONG_NAME);
String url = objJson.getString(Constant.TAG_MP3_URL);
String desc = objJson.getString(Constant.TAG_DESC);
String duration = objJson.getString(Constant.TAG_DURATION);
String image = objJson.getString(Constant.TAG_THUMB_B).replace(" ","%20");
String image_small = objJson.getString(Constant.TAG_THUMB_S).replace(" ","%20");
ItemSong objItem = new ItemSong(id,cid,cname,artist,url,image,image_small,name,duration,desc);
arrayList.add(objItem);
}
return "1";
} catch (JSONException e) {
e.printStackTrace();
return "0";
} catch (Exception ee) {
ee.printStackTrace();
return "0";
}
}
#Override
protected void onPostExecute(String s) {
if(s.equals("1")) {
progressHUD.dismissWithSuccess(getResources().getString(R.string.success));
// setLatestVariables(0);
if(Constant.isAppFirst) {
if(arrayList.size()>0) {
Constant.isAppFirst = false;
Constant.arrayList_play.addAll(arrayList);
((MainActivity)getActivity()).changeText(arrayList.get(0).getMp3Name(),arrayList.get(0).getCategoryName(),1,arrayList.size(),arrayList.get(0).getDuration(),arrayList.get(0).getImageBig(),"home");
Constant.context = getActivity();
}
}
viewpager.setAdapter(adapter);
loadRecent();
// adapterPagerTrending = new AdapterPagerTrending(getActivity(),Constant.arrayList_trending);
// viewPager_trending.setAdapter(adapterPagerTrending);
// adapterTopStories = new AdapterTopStories(getActivity(),Constant.arrayList_topstories);
// listView_topstories.setAdapter(adapterTopStories);
// setListViewHeightBasedOnChildren(listView_topstories);
} else {
progressHUD.dismissWithFailure(getResources().getString(R.string.error));
Toast.makeText(getActivity(), getResources().getString(R.string.server_no_conn), Toast.LENGTH_SHORT).show();
}
super.onPostExecute(s);
}
}
private void loadRecent() {
arrayList_recent = dbHelper.loadDataRecent();
adapterRecent = new AdapterRecent(getActivity(),arrayList_recent);
recyclerView.setAdapter(adapterRecent);
if(arrayList_recent.size() == 0) {
recyclerView.setVisibility(View.GONE);
textView_empty.setVisibility(View.VISIBLE);
} else {
recyclerView.setVisibility(View.VISIBLE);
textView_empty.setVisibility(View.GONE);
}
}
private class ImagePagerAdapter extends PagerAdapter {
private LayoutInflater inflater;
public ImagePagerAdapter() {
// TODO Auto-generated constructor stub
inflater = (LayoutInflater) getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
return arrayList.size();
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view.equals(object);
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
View imageLayout = inflater.inflate(R.layout.viewpager_home, container, false);
assert imageLayout != null;
ImageView imageView = (ImageView) imageLayout.findViewById(R.id.imageView_pager_home);
final ProgressBar spinner = (ProgressBar) imageLayout.findViewById(R.id.loading_home);
TextView title = (TextView) imageLayout.findViewById(R.id.textView_pager_home_title);
TextView cat = (TextView) imageLayout.findViewById(R.id.textView_pager_home_cat);
RelativeLayout rl = (RelativeLayout)imageLayout.findViewById(R.id.rl_homepager);
title.setText(arrayList.get(position).getMp3Name());
cat.setText(arrayList.get(position).getCategoryName());
Picasso.with(getActivity())
.load(arrayList.get(position).getImageBig())
.placeholder(R.mipmap.app_icon)
.into(imageView, new Callback() {
#Override
public void onSuccess() {
spinner.setVisibility(View.GONE);
}
#Override
public void onError() {
spinner.setVisibility(View.GONE);
}
});
rl.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(JsonUtils.isNetworkAvailable(getActivity())) {
//showInter();
playIntent();
} else {
Toast.makeText(getActivity(), getResources().getString(R.string.internet_not_conn), Toast.LENGTH_SHORT).show();
}
}
});
container.addView(imageLayout, 0);
return imageLayout;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
container.removeView((View) object);
}
}
/* private void showInter() {
Constant.adCount = Constant.adCount + 1;
if(Constant.adCount % Constant.adDisplay == 0) {
((MainActivity)getActivity()).mInterstitial.setAdListener(new AdListener() {
#Override
public void onAdClosed() {
playIntent();
super.onAdClosed();
}
});
if(((MainActivity)getActivity()).mInterstitial.isLoaded()) {
((MainActivity)getActivity()).mInterstitial.show();
((MainActivity)getActivity()).loadInter();
} else {
playIntent();
}
} else {
playIntent();
}
}
*/
private void playIntent() {
Constant.isOnline = true;
int pos = viewpager.getCurrentItem();
Constant.arrayList_play.clear();
Constant.arrayList_play.addAll(arrayList);
Constant.playPos = pos;
((MainActivity)getActivity()).changeText(arrayList.get(pos).getMp3Name(),arrayList.get(pos).getCategoryName(),pos+1,arrayList.size(),arrayList.get(pos).getDuration(),arrayList.get(pos).getImageBig(),"home");
Constant.context = getActivity();
if(pos == 0) {
Intent intent = new Intent(getActivity(), PlayerService.class);
intent.setAction(PlayerService.ACTION_FIRST_PLAY);
getActivity().startService(intent);
}
}
}
I saw another question similar to this, that said to attach the adapter before running other threads but I don't believe I have any other threads running in this activity.
You start a new thread in this line:
new LoadLatestNews().execute(Constant.URL_LATEST);
and it is executed before control reaches:
recyclerView.setAdapter(adapterRecent);
This however should not be the problem you have since AsyncTask publishes to the UIThread.
Instead you should set an empty adapter in onCreateView and update it with adapterRecent.notifyDataSetChanged(); once you have loaded your data.
I am working on a android project where I have 2 Custom spinner
State
City
i am using below code to to populate the spinner with Custom list view.
xml code:
<com.infantstudio.CatholicMithrulu.Spinner.SearchableSpinnerState
android:id="#+id/spinner2"
android:layout_width="100dp"
android:layout_height="wrap_content"
android:entries="#array/state"
app:hintTextState="Select"/>
SearchableListDialogState.class
package com.infantstudio.CatholicMithrulu.Spinner;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.DialogFragment;
import android.app.SearchManager;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.SearchView;
import com.infantstudio.CatholicMithrulu.R;
import java.io.Serializable;
import java.util.List;
public class SearchableListDialogState extends DialogFragment implements
SearchView.OnQueryTextListener, SearchView.OnCloseListener {
private static final String ITEMS = "items";
private ArrayAdapter listAdapter;
private ListView _listViewItems;
private SearchableListDialogState.SearchableItem _searchableItem;
private OnSearchTextChanged _onSearchTextChanged;
private SearchView _searchView;
private String _strTitle;
private String _strPositiveButtonText;
private DialogInterface.OnClickListener _onClickListener;
public SearchableListDialogState() {
}
public static SearchableListDialogState newInstance(List items) {
SearchableListDialogState multiSelectExpandableFragment = new
SearchableListDialogState();
Bundle args = new Bundle();
args.putSerializable(ITEMS, (Serializable) items);
multiSelectExpandableFragment.setArguments(args);
return multiSelectExpandableFragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
getDialog().getWindow().setSoftInputMode(WindowManager.LayoutParams
.SOFT_INPUT_STATE_HIDDEN);
return super.onCreateView(inflater, container, savedInstanceState);
}
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
// Getting the layout inflater to inflate the view in an alert dialog.
LayoutInflater inflater = LayoutInflater.from(getActivity());
// Crash on orientation change #7
// Change Start
// Description: As the instance was re initializing to null on rotating the device,
// getting the instance from the saved instance
if (null != savedInstanceState) {
_searchableItem = (SearchableItem) savedInstanceState.getSerializable("item");
}
// Change End
View rootView = inflater.inflate(R.layout.searchable_list_dialog, null);
setData(rootView);
AlertDialog.Builder alertDialog = new AlertDialog.Builder(getActivity());
alertDialog.setView(rootView);
String strPositiveButton = _strPositiveButtonText == null ? "CLOSE" : _strPositiveButtonText;
alertDialog.setPositiveButton(strPositiveButton, _onClickListener);
String strTitle = _strTitle == null ? "Select Item" : _strTitle;
alertDialog.setTitle(strTitle);
final AlertDialog dialog = alertDialog.create();
dialog.getWindow().setSoftInputMode(WindowManager.LayoutParams
.SOFT_INPUT_STATE_HIDDEN);
return dialog;
}
// Crash on orientation change #7
// Change Start
// Description: Saving the instance of searchable item instance.
#Override
public void onSaveInstanceState(Bundle outState) {
outState.putSerializable("item", _searchableItem);
super.onSaveInstanceState(outState);
}
// Change End
public void setTitle(String strTitle) {
_strTitle = strTitle;
}
public void setPositiveButton(String strPositiveButtonText) {
_strPositiveButtonText = strPositiveButtonText;
}
public void setPositiveButton(String strPositiveButtonText, DialogInterface.OnClickListener onClickListener) {
_strPositiveButtonText = strPositiveButtonText;
_onClickListener = onClickListener;
}
public void setOnSearchableItemClickListener(SearchableItem searchableItem) {
this._searchableItem = searchableItem;
}
public void setOnSearchTextChangedListener(OnSearchTextChanged onSearchTextChanged) {
this._onSearchTextChanged = onSearchTextChanged;
}
private void setData(View rootView) {
SearchManager searchManager = (SearchManager) getActivity().getSystemService(Context
.SEARCH_SERVICE);
_searchView = (SearchView) rootView.findViewById(R.id.search);
_searchView.setSearchableInfo(searchManager.getSearchableInfo(getActivity().getComponentName
()));
_searchView.setIconifiedByDefault(false);
_searchView.setOnQueryTextListener(this);
_searchView.setOnCloseListener(this);
_searchView.clearFocus();
InputMethodManager mgr = (InputMethodManager) getActivity().getSystemService(Context
.INPUT_METHOD_SERVICE);
mgr.hideSoftInputFromWindow(_searchView.getWindowToken(), 0);
List items = (List) getArguments().getSerializable(ITEMS);
_listViewItems = (ListView) rootView.findViewById(R.id.listItems);
//create the adapter by passing your ArrayList data
listAdapter = new ArrayAdapter(getActivity(), android.R.layout.simple_list_item_1,items);
//attach the adapter to the list
_listViewItems.setAdapter(listAdapter);
_listViewItems.setTextFilterEnabled(true);
_listViewItems.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
_searchableItem.onSearchableItemClicked(listAdapter.getItem(position), position);
getDialog().dismiss();
}
});
}
#Override
public boolean onClose() {
return false;
}
#Override
public boolean onQueryTextSubmit(String s) {
_searchView.clearFocus();
return true;
}
#Override
public boolean onQueryTextChange(String s) {
// listAdapter.filterData(s);
if (TextUtils.isEmpty(s)) {
// _listViewItems.clearTextFilter();
((ArrayAdapter) _listViewItems.getAdapter()).getFilter().filter(null);
} else {
((ArrayAdapter) _listViewItems.getAdapter()).getFilter().filter(s);
}
if (null != _onSearchTextChanged) {
_onSearchTextChanged.onSearchTextChanged(s);
}
return true;
}
public interface SearchableItem<T> extends Serializable {
void onSearchableItemClicked(T item, int position);
}
public interface OnSearchTextChanged {
void onSearchTextChanged(String strText);
}
}
SearchableSpinnerState.class
package com.infantstudio.CatholicMithrulu.Spinner;
import android.app.Activity;
import android.content.Context;
import android.content.ContextWrapper;
import android.content.res.TypedArray;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.SpinnerAdapter;
import android.widget.Toast;
import com.infantstudio.CatholicMithrulu.Adddata;
import com.infantstudio.CatholicMithrulu.R;
import java.util.ArrayList;
import java.util.List;
public class SearchableSpinnerState extends Spinner implements View.OnTouchListener,
SearchableListDialogState.SearchableItem {
String selectedItem;
//this string above will store the value of selected item.
public static final int NO_ITEM_SELECTED = -1;
private Context _context;
private List _items;
private SearchableListDialogState _searchableListDialog;
private boolean _isDirty;
private ArrayAdapter _arrayAdapter;
private String _strHintText;
private boolean _isFromInit;
public SearchableSpinnerState(Context context) {
super(context);
this._context = context;
init();
}
public SearchableSpinnerState(Context context, AttributeSet attrs) {
super(context, attrs);
this._context = context;
TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.SearchableSpinnerState);
final int N = a.getIndexCount();
for (int i = 0; i < N; ++i) {
int attr = a.getIndex(i);
if (attr == R.styleable.SearchableSpinnerState_hintTextState) {
_strHintText = a.getString(attr);
}
}
a.recycle();
init();
}
public SearchableSpinnerState(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
this._context = context;
init();
}
private void init() {
_items = new ArrayList();
System.out.println("items"+_items);
_searchableListDialog = SearchableListDialogState.newInstance
(_items);
_searchableListDialog.setOnSearchableItemClickListener(this);
setOnTouchListener(this);
_arrayAdapter = (ArrayAdapter) getAdapter();
if (!TextUtils.isEmpty(_strHintText)) {
ArrayAdapter arrayAdapter = new ArrayAdapter(_context, android.R.layout
.simple_list_item_1, new String[]{_strHintText});
_isFromInit = true;
setAdapter(arrayAdapter);
}
}
#Override
public boolean onTouch(View v, MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_UP) {
if (null != _arrayAdapter) {
// Refresh content #6
// Change Start
// Description: The items were only set initially, not reloading the data in the
// spinner every time it is loaded with items in the adapter.
_items.clear();
for (int i = 0; i < _arrayAdapter.getCount(); i++) {
_items.add(_arrayAdapter.getItem(i));
}
// Change end.
_searchableListDialog.show(scanForActivity(_context).getFragmentManager(), "TAG");
}
}
return true;
}
#Override
public void setAdapter(SpinnerAdapter adapter) {
if (!_isFromInit) {
_arrayAdapter = (ArrayAdapter) adapter;
if (!TextUtils.isEmpty(_strHintText) && !_isDirty) {
ArrayAdapter arrayAdapter = new ArrayAdapter(_context, android.R.layout
.simple_list_item_1, new String[]{_strHintText});
super.setAdapter(arrayAdapter);
} else {
super.setAdapter(adapter);
}
} else {
_isFromInit = false;
super.setAdapter(adapter);
}
}
//The method just below is executed when an item in the searchlist is tapped.This is where we store the value int string called selectedItem.
#Override
public void onSearchableItemClicked(Object item, int position) {
setSelection(_items.indexOf(item));
if (!_isDirty) {
_isDirty = true;
setAdapter(_arrayAdapter);
setSelection(_items.indexOf(item));
}
selectedItem= item.toString().trim();
Adddata.setValueSt(selectedItem);
// Toast.makeText(getContext(),"You selected "+selectedItem, Toast.LENGTH_LONG).show();
}
private Activity scanForActivity(Context cont) {
if (cont == null)
return null;
else if (cont instanceof Activity)
return (Activity) cont;
else if (cont instanceof ContextWrapper)
return scanForActivity(((ContextWrapper) cont).getBaseContext());
return null;
}
#Override
public int getSelectedItemPosition() {
if (!TextUtils.isEmpty(_strHintText) && !_isDirty) {
return NO_ITEM_SELECTED;
} else {
return super.getSelectedItemPosition();
}
}
#Override
public Object getSelectedItem() {
if (!TextUtils.isEmpty(_strHintText) && !_isDirty) {
return null;
} else {
return super.getSelectedItem();
}
}
}
The above code is working fine, but I need to change the array at run time . Array is declared in the xml file like this
android:entries="#array/state"
How can I modify this array at run time? Any help would be valuable.
--Thanks!
Create ArrayList and insert the entries that you are getting from API or add it.
List < String > list = new ArrayList < > ();
list.add("Male");
list.add("Female");
list.add("Others");
ArrayAdapter < String > dataAdapter = new ArrayAdapter < String > (this, android.R.layout.simple_spinner_item, list);
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinnerGender.setAdapter(dataAdapter);
or
List<String> list= new ArrayList<>();
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, list);
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinnerGender.setAdapter(dataAdapter);
onResposeSucessofAPI(List<String> list){
this.list = list;
dataAdapter.notifyDataSetChanged();
}
Create a arrayList of Strings
ArrayList<String> area = new ArrayList<>();
add values in area arrayList
area.add("value1");
area.add("value2");
Now set adapter
yourSpinner.setAdapter(new ArrayAdapter<String>(context
, android.R.layout.simple_list_item_1, area));
Anything declared in Resources, cannot be changed at Runtime
You must do it by java code
I am having problem with fragments.I am developing an app like 360 security and i am having problem implementing fragments ,getting "Binary XML file line #1: Error inflating class fragment".
Here is my xml file.I have tried every solution please help me.
Thanks in advance.
<fragment xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/item_list"
android:name="sabby.completesecurity.MainListFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".ItemListActivity"
tools:layout="#android:layout/list_content" />
This is my activity file:
package sabby.completesecurity;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.FrameLayout;
import android.widget.ImageView;
import sabby.completesecurity.R;
public class MainActivityCache extends FragmentActivity implements sabby.completesecurity.MainCallbacks {
private boolean mIsDualPane;
private boolean mIsArtShowed = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_cache);
mIsDualPane = findViewById(R.id.item_detail_container) != null;
//Show an art when no fragment is showed, we make sure no detail fragment is present.
if (mIsDualPane && getFragmentManager().findFragmentByTag(sabby.completesecurity.DetailFragment.FRAGMENT_TAG) == null) {
ImageView imageView = new ImageView(this);
imageView.setImageResource(R.mipmap.ic_launcher);
imageView.setScaleType(ImageView.ScaleType.FIT_CENTER);
((FrameLayout) findViewById(R.id.item_detail_container)).addView(imageView);
mIsArtShowed = true;
}
}
#Override
public void onItemSelected(String packageName) {
if (mIsDualPane) {
//Hide art when a fragment is showed.
if (mIsArtShowed) {
((FrameLayout) findViewById(R.id.item_detail_container)).removeAllViews();
mIsArtShowed = false;
}
getFragmentManager()
.beginTransaction()
.replace(R.id.item_detail_container, DetailFragment.getInstance(packageName), DetailFragment.FRAGMENT_TAG)
.commit();
} else {
Intent intent = new Intent(this, DetailActivity.class);
intent.putExtra(DetailFragment.EXTRA_PACKAGE_NAME, packageName);
startActivity(intent);
}
}
#Override
protected void onStart() {
super.onStart();
registerReceiver(receiver, getIntentFilter());
}
#Override
protected void onStop() {
super.onStop();
unregisterReceiver(receiver);
}
private void showAboutDialog() {
new AlertDialog.Builder(this)
.setTitle("About")
.setView(getLayoutInflater().inflate(R.layout.about_dialog_message, null))
.setNegativeButton(android.R.string.ok, null)
.show();
}
/**
* Used to update the list if a package is added or removed.
*/
private IntentFilter getIntentFilter() {
IntentFilter filter = new IntentFilter();
filter.addDataScheme("package");
filter.addAction(Intent.ACTION_PACKAGE_CHANGED);
filter.addAction(Intent.ACTION_PACKAGE_REPLACED);
filter.addAction(Intent.ACTION_PACKAGE_FULLY_REMOVED);
filter.addAction(Intent.ACTION_PACKAGE_ADDED);
return filter;
}
enter code here
BroadcastReceiver receiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
MainListFragment mainListFragment = (MainListFragment) getFragmentManager().findFragmentById(R.id.item_list);
if (mainListFragment != null)
mainListFragment.loadList();
}
};
}
MainListFragment.java
package sabby.completesecurity;
import android.app.ActionBar;
import android.app.Activity;
import android.app.ListFragment;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.content.pm.IPackageStatsObserver;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageStats;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.RemoteException;
import android.text.format.Formatter;
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.BaseAdapter;
import android.widget.ImageView;
import android.widget.SectionIndexer;
import android.widget.Spinner;
import android.widget.TextView;
import sabby.completesecurity.utils.Utils;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
public class MainListFragment extends ListFragment implements AdapterView.OnItemClickListener, AdapterView.OnItemSelectedListener {
private static final int SORT_NAME = 0;
private static final int SORT_PKG = 1;
private static final int SORT_DOMAIN = 2;
private static final int SORT_INSTALLATION = 3;
private static final int SORT_SIZE = 4;
private static final String INSTANCE_STATE_SORT_BY = "sort_by";
private Adapter mAdapter;
private List<Item> mItemList = new ArrayList<Item>();
private int mOnSizeFinishedItemCount;
private PackageManager mPackageManager;
private ProgressDialog mProgressDialog;
private LayoutInflater mLayoutInflater;
private MainCallbacks mCallbacks;
private Context mContext;
private Async mAsyncLoader;
private Spinner mSpinner;
private boolean mSpinnerListenerAuthorized;
private SimpleDateFormat mSimpleDateFormat;
private int mSortBy = 0;
class Item {
ApplicationInfo applicationInfo;
String label;
Long date;
Long size = -1L;
}
private int mColorGrey1;
private int mColorGrey2;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
mProgressDialog = new ProgressDialog(mContext);
mProgressDialog.setTitle(R.string.loading_apps);
mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
mProgressDialog.setCancelable(false);
//Used to prevent message not showing later
mProgressDialog.setMessage("");
mPackageManager = mContext.getPackageManager();
mSimpleDateFormat = new SimpleDateFormat("dd/MM/yyyy hh:mm:ss");
mColorGrey1 = getResources().getColor(R.color.grey_1);
mColorGrey2 = getResources().getColor(R.color.grey_2);
ActionBar actionBar = getActivity().getActionBar();
actionBar.setDisplayShowCustomEnabled(true);
mSpinner = new Spinner(actionBar.getThemedContext());
SpinnerAdapter spinnerAdapter = new SpinnerAdapter(actionBar.getThemedContext(),
R.array.sort_spinner_items, android.R.layout.simple_list_item_1);
mSpinner.setAdapter(spinnerAdapter);
mSpinnerListenerAuthorized = false;
mSpinner.setOnItemSelectedListener(this);
ActionBar.LayoutParams layoutParams = new ActionBar.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.MATCH_PARENT);
actionBar.setCustomView(mSpinner, layoutParams);
if (savedInstanceState != null)
setSortBy(savedInstanceState.getInt(INSTANCE_STATE_SORT_BY, -1), false);
}
#Override
public void onStart() {
super.onStart();
mSpinner.setSelection(mSortBy);
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt(INSTANCE_STATE_SORT_BY, mSortBy);
}
private void onTaskEnded(List<Item> list) {
RetainedFragment retainedFragment = (RetainedFragment) getFragmentManager().findFragmentByTag(RetainedFragment.FRAGMENT_TAG);
retainedFragment.setList(list);
mItemList = list;
mAdapter.notifyDataSetChanged();
if (getListView().getAdapter() == null)
setListAdapter(mAdapter);
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
getListView().setOnItemClickListener(this);
getListView().setFastScrollEnabled(true);
mAdapter = new Adapter();
RetainedFragment retainedFragment = (RetainedFragment) getFragmentManager()
.findFragmentByTag(RetainedFragment.FRAGMENT_TAG);
if (retainedFragment == null) {
retainedFragment = new RetainedFragment();
getFragmentManager()
.beginTransaction()
.add(retainedFragment, RetainedFragment.FRAGMENT_TAG)
.commit();
}
if (retainedFragment.getList() != null) {
onTaskEnded(retainedFragment.getList());
mOnSizeFinishedItemCount = mItemList.size();
//Notify spinner that size sort is available
SpinnerAdapter adapter = (SpinnerAdapter) mSpinner.getAdapter();
adapter.notifyDataSetChanged();
} else
loadList();
}
public void loadList() {
mAsyncLoader = new Async();
mAsyncLoader.execute();
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
mCallbacks = (MainCallbacks) activity;
mContext = activity;
mLayoutInflater = activity.getLayoutInflater();
}
#Override
public void onDetach() {
super.onDetach();
if (mAsyncLoader != null)
mAsyncLoader.cancel(true);
mCallbacks = null;
mContext = null;
mLayoutInflater = null;
}
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
if (mCallbacks != null)
mCallbacks.onItemSelected(mItemList.get(i).applicationInfo.packageName);
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.fragment_main_list, menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_refresh:
loadList();
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
if (mSpinnerListenerAuthorized)
setSortBy(i, true);
mSpinnerListenerAuthorized = true;
}
/**
* Sort main list if provided value is valid.
* #param sort Must be one of SORT_*
* #param checkViews Set if views have to be updated, eg. when restoring state, views aren't
* created yet, so value must be false
*/
public void setSortBy(int sort, boolean checkViews) {
if (sort >= SORT_NAME && sort <= SORT_SIZE) {
mSortBy = sort;
if (checkViews) {
checkFastScroll();
sortApplicationList(mItemList, mSortBy);
mAdapter.notifyDataSetChanged();
}
}
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
private void checkFastScroll() {
getListView().setFastScrollEnabled(mSortBy == SORT_NAME);
}
public void sortApplicationList(List<Item> list, final int sortBy) {
Collections.sort(list, new Comparator<Item>() {
#Override
public int compare(Item item1, Item item2) {
switch (sortBy) {
case SORT_NAME:
return item1.label.compareTo(item2.label);
case SORT_PKG:
return item1.applicationInfo.packageName.compareTo(item2.applicationInfo.packageName);
case SORT_DOMAIN:
boolean isSystem1 = (item1.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
boolean isSystem2 = (item2.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
return Utils.compareBooleans(isSystem1, isSystem2);
case SORT_INSTALLATION:
//Sort in decreasing order
return -item1.date.compareTo(item2.date);
case SORT_SIZE:
return -item1.size.compareTo(item2.size);
default:
return 0;
}
}
});
}
/**
* This method is called by each item when it has finished retrieving its size
* When all items have finished, we set size sort available in spinner, and invalidate
* main list to display sizes in UI.
*/
private void onItemFinishedSizeProcess() {
mOnSizeFinishedItemCount ++;
if (mOnSizeFinishedItemCount == mItemList.size()) {
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
SpinnerAdapter adapter = (SpinnerAdapter) mSpinner.getAdapter();
adapter.notifyDataSetChanged();
mAdapter.notifyDataSetChanged();
}
});
}
}
class Adapter extends BaseAdapter implements SectionIndexer {
class ViewHolder {
ImageView icon;
TextView label;
TextView packageName;
TextView version;
TextView isSystemApp;
TextView date;
TextView size;
IconAsyncTask iconLoader;
}
String sections = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
#Override
public int getCount() {
return mItemList.size();
}
#Override
public Object getItem(int i) {
return mItemList.get(i);
}
#Override
public long getItemId(int i) {
return i;
}
#Override
public View getView(int i, View view, ViewGroup viewGroup) {
ViewHolder holder;
if (view == null) {
view = mLayoutInflater.inflate(R.layout.main_list_item, null);
holder = new ViewHolder();
holder.icon = (ImageView) view.findViewById(R.id.icon);
holder.label = (TextView) view.findViewById(R.id.label);
holder.packageName = (TextView) view.findViewById(R.id.packageName);
holder.version = (TextView) view.findViewById(R.id.version);
holder.isSystemApp = (TextView) view.findViewById(R.id.isSystem);
holder.date = (TextView) view.findViewById(R.id.date);
holder.size = (TextView) view.findViewById(R.id.size);
view.setTag(holder);
} else {
holder = (ViewHolder) view.getTag();
holder.iconLoader.cancel(true);
}
view.setBackgroundColor(i % 2 == 0 ? mColorGrey2 : mColorGrey1);
Item item = mItemList.get(i);
ApplicationInfo info = item.applicationInfo;
try {
PackageInfo packageInfo = mPackageManager.getPackageInfo(info.packageName, 0);
holder.version.setText(packageInfo.versionName);
Date date = new Date(packageInfo.firstInstallTime);
holder.date.setText(mSimpleDateFormat.format(date));
} catch (PackageManager.NameNotFoundException e) {
//Do nothing
}
holder.iconLoader = new IconAsyncTask(holder.icon, info);
holder.iconLoader.execute();
holder.label.setText(info.loadLabel(mPackageManager));
holder.packageName.setText(info.packageName);
boolean isSystemApp = (info.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
holder.isSystemApp.setText(isSystemApp ? getString(R.string.system) : getString(R.string.user));
if (item.size != -1L)
holder.size.setText(Formatter.formatFileSize(getActivity(), item.size));
return view;
}
#Override
public int getPositionForSection(int section) {
for (int i = 0; i < this.getCount(); i++) {
String item = mItemList.get(i).label;
if (item.charAt(0) == sections.charAt(section))
return i;
}
return 0;
}
#Override
public int getSectionForPosition(int i) {
return 0;
}
#Override
public Object[] getSections() {
String[] sectionsArr = new String[sections.length()];
for (int i = 0; i < sections.length(); i++)
sectionsArr[i] = "" + sections.charAt(i);
return sectionsArr;
}
class IconAsyncTask extends AsyncTask<Void, Integer, Drawable> {
ImageView imageView;
ApplicationInfo info;
IconAsyncTask(ImageView imageView, ApplicationInfo info) {
this.imageView = imageView;
this.info = info;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
imageView.setVisibility(View.INVISIBLE);
}
#Override
protected Drawable doInBackground(Void... voids) {
if (!isCancelled())
return info.loadIcon(mPackageManager);
return null;
}
#Override
protected void onPostExecute(Drawable drawable) {
super.onPostExecute(drawable);
imageView.setImageDrawable(drawable);
imageView.setVisibility(View.VISIBLE);
}
}
}
class SpinnerAdapter extends BaseAdapter {
private Context mContext;
private int mLayoutResId;
private String[] mItems;
public SpinnerAdapter(Context themedContext, int arrayResId, int layoutResId) {
mContext = themedContext;
mItems = themedContext.getResources().getStringArray(arrayResId);
mLayoutResId = layoutResId;
}
#Override
public int getCount() {
return mItems.length;
}
#Override
public Object getItem(int i) {
return null;
}
#Override
public long getItemId(int i) {
return 0;
}
//It make no sense to implement recycled view system because there is only 5 items in list
#Override
public View getView(int i, View view, ViewGroup viewGroup) {
view = View.inflate(mContext, mLayoutResId, null);
if (view instanceof TextView)
((TextView) view).setText(mItems[i]);
return view;
}
/**
* Set sort_by_size item disabled if all items haven't retrieved them size.
*/
#Override
public boolean isEnabled(int position) {
return position != SORT_SIZE || mItemList != null && mOnSizeFinishedItemCount == mItemList.size();
}
}
class Async extends AsyncTask<Void, Async.Progress, List<Item>> {
class Progress {
String label;
int totalSize;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
mProgressDialog.show();
}
#Override
protected List<Item> doInBackground(Void... voids) {
List<ApplicationInfo> applicationInfos = mPackageManager.getInstalledApplications(PackageManager.GET_META_DATA);
Progress progress = new Progress();
progress.totalSize = applicationInfos.size();
List<Item> itemList = new ArrayList<Item>(applicationInfos.size());
mOnSizeFinishedItemCount = 0;
for (ApplicationInfo applicationInfo : applicationInfos) {
if (isCancelled())
break;
Item item = new Item();
item.applicationInfo = applicationInfo;
String label = applicationInfo.loadLabel(mPackageManager).toString();
item.label = label;
try {
item.date = mPackageManager.getPackageInfo(applicationInfo.packageName, 0).firstInstallTime;
} catch (PackageManager.NameNotFoundException e) {
item.date = 0L;
}
itemList.add(item);
getItemSize(item);
progress.label = label;
publishProgress(progress);
}
sortApplicationList(itemList, mSortBy);
return itemList;
}
private void getItemSize(final Item item) {
try {
Method getPackageSizeInfo = mPackageManager.getClass().getMethod(
"getPackageSizeInfo", String.class, IPackageStatsObserver.class);
getPackageSizeInfo.invoke(mPackageManager, item.applicationInfo.packageName, new IPackageStatsObserver.Stub() {
#Override
public void onGetStatsCompleted(final PackageStats pStats, boolean succeeded)
throws RemoteException {
if (succeeded)
item.size = pStats.codeSize + pStats.cacheSize + pStats.dataSize
+ pStats.externalCodeSize + pStats.externalCacheSize + pStats.externalDataSize
+ pStats.externalMediaSize + pStats.externalObbSize;
else
item.size = -1L;
onItemFinishedSizeProcess();
}
});
} catch (NoSuchMethodException e) {
e.printStackTrace();
onItemFinishedSizeProcess();
} catch (IllegalAccessException e) {
e.printStackTrace();
onItemFinishedSizeProcess();
} catch (InvocationTargetException e) {
e.printStackTrace();
onItemFinishedSizeProcess();
}
}
#Override
protected void onProgressUpdate(Progress... values) {
super.onProgressUpdate(values);
Progress progress = values[0];
mProgressDialog.setMessage(progress.label);
if (mProgressDialog.getMax() == 100)
mProgressDialog.setMax(progress.totalSize);
mProgressDialog.incrementProgressBy(1);
}
#Override
protected void onPostExecute(List<Item> list) {
super.onPostExecute(list);
mProgressDialog.hide();
onTaskEnded(list);
}
#Override
protected void onCancelled(List<Item> list) {
super.onCancelled(list);
mProgressDialog.hide();
}
}
}
In the xml that you have posted,replace the TAG <Fragment> with <LinearLayout> or <RelativeLayout> and inside this you simply show what you want to display in you UI
Make sure you extend Fragment class in you fragment activity
Could you post the code for your fragment? The problem could be with your import statements. You have 'import android.support.v4.app.FragmentActivity'. Do you have 'import android.support.v4.app.Fragment' in your fragment file?
I have a Fragment called User Management where I collect data from a server and display it in a ListView. It's also refreshable via SwipeRefreshLayout.
What happens is, if I get data on 1-4 users, it displays the data correctly. However, if I get data on more than 4 users, it displays the first 4 correctly, and instead of the fifth, it's the first one again, instead of the 6th, it's the second one and so on and so on.
I've tried everything I could think of, the adapter is getting the data correctly, the ListView is getting the adapter correctly, but for some reason, it peaks at 4 users displayed, and simply repeats them after that (the funny thing is, if I add a user and then refresh, it simply repeats the next user one more time in the list, so it's definitely aware of the change in user number)
Can you help me finding the problem?
The java class:
package com.softwarenation.jetfuel.fragments.userManagement;
import android.app.AlertDialog;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.ListFragment;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.widget.SwipeRefreshLayout;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.VolleyError;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.softwarenation.jetfuel.R;
import com.softwarenation.jetfuel.activities.MainActivity;
import com.softwarenation.jetfuel.fragments.Stations;
import com.softwarenation.jetfuel.managers.JetfuelManager;
import com.softwarenation.jetfuel.managers.StatusManager;
import com.softwarenation.jetfuel.managers.UserManager;
import com.softwarenation.jetfuel.utility.Global;
import com.softwarenation.jetfuel.utility.GlobalConnection;
import com.softwarenation.jetfuel.utility.users.User_pictures;
import com.softwarenation.jetfuel.utility.users.Users_mana;
import org.nicktate.projectile.Method;
import org.nicktate.projectile.Projectile;
import org.nicktate.projectile.StringListener;
import java.io.InputStream;
import java.util.ArrayList;
public class UserManagement extends Fragment {
private SwipeRefreshLayout swipeRefreshLayout;
//private View refreshView;
private Global font = new Global();
private ListView listView;
private ArrayList<User_pictures> pictureses = new ArrayList<User_pictures>();
private static boolean isfirst = false;
private PullToRefreshListView pullToRefreshView;
/**---------------------------------------------------------------------------------------------*/
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
/**---------------------------------------------------------------------------------------------*/
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_usermanagemnet, container, false);
listView = (ListView)rootView.findViewById(R.id.list);
swipeRefreshLayout = (SwipeRefreshLayout)rootView.findViewById(R.id.swipe);
// refreshView = (View) rootView.findViewById(R.id.swipe);
//First time, we get the data from a server, then only display that data until the user calls for a refresh
if(!StatusManager.getInstance().getUsermStatus()){
UsersTask usersTask = new UsersTask();
usersTask.execute();
}else{
setContent();
}
Button addUser = (Button)rootView.findViewById(R.id.addUser_button);
addUser.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Fragment fragment = new AddUser();
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction().replace(R.id.content_frame, fragment).commit();
}
});
// Set a listener to be invoked when the list should be refreshed.
swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
Log.e("start","onRefresh");
new GetDataTask().execute();
}
}
);
/* pullToRefreshView = (PullToRefreshListView)rootView.findViewById(R.id.pull_to_refresh_listview);
pullToRefreshView.bringToFront();
pullToRefreshView.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener<ListView>() {
#Override
public void onRefresh(PullToRefreshBase<ListView> refreshView) {
// Do work to refresh the list here.
new GetDataTask().execute();
}
});*/
return rootView;
}
public void setOnRefreshListener (SwipeRefreshLayout.OnRefreshListener listener){
swipeRefreshLayout.setOnRefreshListener(listener);
}
public boolean isRefreshing(){
return swipeRefreshLayout.isRefreshing();
}
public void setRefreshing(boolean refreshing){
swipeRefreshLayout.setRefreshing(refreshing);
}
public SwipeRefreshLayout getSwipeRefreshLayout(){
return swipeRefreshLayout;
}
//on refresh, get new data from the server
private class GetDataTask extends AsyncTask<Void, Void, String[]> {
#Override
protected String[] doInBackground(Void... voids) {Log.e("start","GetDataTask");
UsersTask usersTask = new UsersTask();
usersTask.execute();
return new String[0];
}
#Override
protected void onPostExecute(String[] result) {
// Call onRefreshComplete when the list has been refreshed.
// pullToRefreshView.onRefreshComplete();
super.onPostExecute(result);
MainActivity.setBackDisabled(false);
Log.e("GetDataTask","completed");
}
}
private class SampleItem {
public String id;
public String title;
public String username;
public String groupName;
public int userPicture;
public int editPicture;
public int dPicture;
public String activated;
public SampleItem(String id, String title, String username, String groupName, int userPicture, int editPicture, int dPicture, String activated ) {
this.id = id;
this.title = title;
this.username = username;
this.groupName = groupName;
this.userPicture = userPicture;
this.editPicture = editPicture;
this.dPicture = dPicture;
this.activated = activated;
}
}
static class ViewHolder {
private String checkBox;
private RelativeLayout relativeLayout;
private LinearLayout linearLayout;
private RelativeLayout relativeLayout2;
public void setCheckBox(String checkBox) {
this.checkBox = checkBox;
}
public void setLinearLayout(LinearLayout linearLayout) {
this.linearLayout = linearLayout;
}
public void setRelativeLayout(RelativeLayout relativeLayout) {
this.relativeLayout = relativeLayout;
}
public void setRelativeLayout2(RelativeLayout relativeLayout2) {
this.relativeLayout2 = relativeLayout2;
}
public LinearLayout getLinearLayout() {
return linearLayout;
}
public RelativeLayout getRelativeLayout() {
return relativeLayout;
}
public RelativeLayout getRelativeLayout2() {
return relativeLayout2;
}
public RelativeLayout getCheckBox() {
return relativeLayout;
}
}
public class SampleAdapter extends ArrayAdapter<SampleItem> {
final ViewHolder holder = new ViewHolder();
public SampleAdapter(Context context) {
super(context, 0);
}
public View getView(final int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = LayoutInflater.from(getContext()).inflate(R.layout.row_usermana, null);
ImageView userPicture = (ImageView)convertView.findViewById(R.id.userpicture);
userPicture.setImageDrawable(getResources().getDrawable(getItem(position).userPicture));
TextView title = (TextView)convertView.findViewById(R.id.user_name);
font.setFont(title, 3, getActivity());
title.setText(getItem(position).title);
TextView username = (TextView)convertView.findViewById(R.id.username);
font.setFont(username, 2, getActivity());
username.setText(getItem(position).username);
TextView groupname = (TextView)convertView.findViewById(R.id.groupName);
font.setFont(groupname, 2, getActivity());
groupname.setText(getItem(position).groupName);
ImageView useredit = (ImageView)convertView.findViewById(R.id.editbutton);
useredit.setImageDrawable(getResources().getDrawable(getItem(position).editPicture));
useredit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Bundle bundle = new Bundle();
bundle.putString("user_id", getItem(position).id);
Fragment fragment = new EditProfile();
fragment.setArguments(bundle);
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction().replace(R.id.content_frame, fragment).commit();
}
});
/**---------------*/
ImageView userdelate = (ImageView)convertView.findViewById(R.id.deletebutton);
userdelate.setImageDrawable(getResources().getDrawable(getItem(position).dPicture));
holder.setLinearLayout((LinearLayout)convertView.findViewById(R.id.lin_show_profile));
//LinearLayout show = (LinearLayout)convertView.findViewById(R.id.lin_show_profile);
holder.getLinearLayout().setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Bundle bundle = new Bundle();
bundle.putString("user_id", getItem(position).id);
Fragment fragment = new ShowProfile();
fragment.setArguments(bundle);
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction().replace(R.id.content_frame, fragment).commit();
}
});
//
holder.setRelativeLayout((RelativeLayout)convertView.findViewById(R.id.delate_user));
//RelativeLayout delete_user = (RelativeLayout)convertView.findViewById(R.id.delate_user);
holder.getRelativeLayout().setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
DialogStop("Are you sure?", getItem(position).username, getActivity(), getItem(position).id);
}
});
//
//holder.setCheckBox(getItem(position).activated);
//
/**---------------*/
//Red or Blue background
// RelativeLayout settings = (RelativeLayout)convertView.findViewById(R.id.settingsbutton);
holder.setRelativeLayout2((RelativeLayout) convertView.findViewById(R.id.settingsbutton));
//if(getItem(position).activated.equals("false")) {
if (getItem(position).activated.equals("false")) {
holder.getLinearLayout().setBackground(getResources().getDrawable(R.drawable.discrepancy_background_red));
holder.getRelativeLayout().setBackground(getResources().getDrawable(R.drawable.discrepancy_background_red));
holder.getRelativeLayout2().setBackground(getResources().getDrawable(R.drawable.discrepancy_background_red));
}
//holder.setCheckBox(getItem(position).activated);
convertView.setTag(holder);
} else {
convertView.getTag();
}
return convertView;
}
}
public void DialogStop(String title, String message,Context context, final String id){
new AlertDialog.Builder(context)
.setTitle(title)
.setMessage(message)
.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
//dialog.cancel();
DeleteTask deleteTask = new DeleteTask();
deleteTask.execute(id);
}
})
.setNegativeButton(android.R.string.no, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
})
.setIcon(android.R.drawable.ic_dialog_alert)
.show();
}
private class DeleteTask extends AsyncTask<String, String, String>{
#Override
protected String doInBackground(String... params) {
String response = null;
try {
response = new GlobalConnection().DELETE( getString(R.string.apicdeleteuser) + params[0].toString() );
Log.v("response", response + "");
} catch (Exception e) {
e.printStackTrace();
}
return response;
}
#Override
protected void onPostExecute(String response) {
Log.v("response", response + "");
}
}
private class UsersTask extends AsyncTask<String, Void, ArrayList<Users_mana>> {
#Override
protected ArrayList<Users_mana> doInBackground(String... strings) {
//Users_mana users = null;
String response = null;
ArrayList<Users_mana> users_manas = null;
try{Log.e("start","GET via GlobalConnection()");
response = new GlobalConnection().GET( getString(R.string.apiusers));
users_manas = new Gson().fromJson(response, new TypeToken<ArrayList<Users_mana>>(){}.getType());
Log.e("start","setUsers_mana");
UserManager.getInstance().setUsers_mana(users_manas);
}catch (Exception e){
Log.e("response error", e.getMessage().toString());
}
return users_manas;
}
#Override
protected void onPostExecute(ArrayList<Users_mana> response) {
if(!response.isEmpty()) {Log.e("start","setContent()");
setContent();
StatusManager.getInstance().setUsermStatus(true);
Log.e("UsermStatus:",String.valueOf(StatusManager.getInstance().getUsermStatus()));
}
super.onPostExecute(response);
}
}
private void setContent(){
SampleAdapter adapter = new SampleAdapter(getActivity());
adapter.notifyDataSetChanged();
try {
if (!UserManager.getInstance().getUsers_mana().isEmpty()) {
for (int i = 0; i < UserManager.getInstance().getUsers_mana().size(); i++) {
Log.e("adding to adapter:",UserManager.getInstance().getUsers_mana().get(i).firstName + " " + UserManager.getInstance().getUsers_mana().get(i).lastName + "" + UserManager.getInstance().getUsers_mana().get(i).id + "" + UserManager.getInstance().getUsers_mana().get(i).username + "group:" + UserManager.getInstance().getUsers_mana().get(i).group);
adapter.add(new SampleItem(
UserManager.getInstance().getUsers_mana().get(i).id
, UserManager.getInstance().getUsers_mana().get(i).firstName + " " + UserManager.getInstance().getUsers_mana().get(i).lastName
, UserManager.getInstance().getUsers_mana().get(i).username
, UserManager.getInstance().getUsers_mana().get(i).group
, R.drawable.users_test
, R.drawable.settings
, R.drawable.delete
, UserManager.getInstance().getUsers_mana().get(i).activated
));
}
listView.setAdapter(adapter);Log.e("setting","ListView");
}
}catch (Exception e){
Log.e("error setContent", e.getMessage().toString());
}
}
/*
private class PicturesTask extends AsyncTask<String, String ,String>{
#Override
protected String doInBackground(String... urls) {
//String urldisplay = urls[0];
Bitmap mIcon11 = null;
try {
for(int i = 0; i < urls.length; i++) {
if(UserManager.getInstance().getUsers_mana().get(i).photo != null) {
InputStream in = new java.net.URL(getString(R.string.jetfuel_url ) + UserManager.getInstance().getUsers_mana().get(i).username).openStream();
mIcon11 = BitmapFactory.decodeStream(in);
pictureses.add(new User_pictures(mIcon11, UserManager.getInstance().getUsers_mana().get(i).username, UserManager.getInstance().getUsers_mana().get(i).id));
UserManager.getInstance().setUserPictureses(pictureses);
}
}
} catch (Exception e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String s) {
if(!UserManager.getInstance().getUserPictureses().isEmpty()) {
for (int i = 0; i < UserManager.getInstance().getUserPictureses().size(); i++) {
Log.v("pictures", UserManager.getInstance().getUserPictureses().get(i).picture + "");
}
}
super.onPostExecute(s);
}
}
*/
/**---------------------------------------------------------------------------------------------*/
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.main, menu);
//menu.removeItem(R.id.Station);
super.onCreateOptionsMenu(menu, inflater);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.Station:
Fragment fragment = new Stations();
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction().replace(R.id.content_frame, fragment).commit();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
/**---------------------------------------------------------------------------------------------*/
}
The xml view:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<LinearLayout
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/blue">
<Button
android:id="#+id/addUser_button"
android:layout_width="fill_parent"
android:layout_height="50dp"
android:text="#string/add_user"
android:background="#drawable/button_yellow_background"
android:textStyle="bold"
android:textSize="20sp"
android:textColor="#color/blue"/>
<android.support.v4.widget.SwipeRefreshLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/swipe">
<ListView
android:id="#+id/list"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="#color/blue"
/>
</android.support.v4.widget.SwipeRefreshLayout>
</LinearLayout>
</RelativeLayout>
Thank you!
There is a huge problem in your SampleAdapter.getView() method.
When you scroll down the View disappearing at the top of the screen is reused to be injected at the bottom. This reused View is the convertView you get as getView parameter.
As you code is, the reused view is injected with the exact same data (because if (convertView == null) { is always false when you scroll).
Images and texts are not updated.
When you scroll down, the element disappearing at the top just appears at the bottom, and so does others...
You should be doing something like:
public View getView(final int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
convertView = LayoutInflater.from(getContext()).inflate(R.layout.row_usermana, null);
// The ViewHolder constructor should handle the mapping of its views
holder = new ViewHolder(convertView);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
// Here you should only use holder as in:
holder.userpicture.setImageDrawable(getResources().getDrawable(getItem(position).userPicture));
...
}
This method looks strange, and is perhaps suspect. I don't see getUsers_mana() defined anywhere in this sample code, so I don't know if it is the problem or not. For one, you should call that 'UserManager.getInstance().getUsers_mana()' and then 'get(i)' once each and store the results in variables.
private void setContent(){
SampleAdapter adapter = new SampleAdapter(getActivity());
adapter.notifyDataSetChanged();
try {
if (!UserManager.getInstance().getUsers_mana().isEmpty()) {
for (int i = 0; i < UserManager.getInstance().getUsers_mana().size(); i++) {
Log.e("adding to adapter:",UserManager.getInstance().getUsers_mana().get(i).firstName + " " + UserManager.getInstance().getUsers_mana().get(i).lastName + "" + UserManager.getInstance().getUsers_mana().get(i).id + "" + UserManager.getInstance().getUsers_mana().get(i).username + "group:" + UserManager.getInstance().getUsers_mana().get(i).group);
adapter.add(new SampleItem(
UserManager.getInstance().getUsers_mana().get(i).id
, UserManager.getInstance().getUsers_mana().get(i).firstName + " " + UserManager.getInstance().getUsers_mana().get(i).lastName
, UserManager.getInstance().getUsers_mana().get(i).username
, UserManager.getInstance().getUsers_mana().get(i).group
, R.drawable.users_test
, R.drawable.settings
, R.drawable.delete
, UserManager.getInstance().getUsers_mana().get(i).activated
));
}
listView.setAdapter(adapter);Log.e("setting","ListView");
}
}catch (Exception e){
Log.e("error setContent", e.getMessage().toString());
}
}
It is because you are not doing anything in the
else {
convertView.getTag();
}
Check here
Why we should re-assign values for a recycled convertView in getView()
You have to reassign values to the convertView with the data of the 5th roq, 6th row etc. otherwise it still contains the old data
Remove the initialization of holder on the top and just put this line of code in the beginning of getView function.
ViewHolder holder = null;
You need to re initialize holder if its null and you need to update it with latest data if its not null.
See this sample it might help you
https://github.com/erikwt/PullToRefresh-ListView