I have a SearchView in my application that searches through notes in my RecyclerView (I am using Room Database to store the notes).
But after using the SearchView my other functions no longer work unless I restart the application.
These are the functions that no longer work after using the SearchView such as Adding note, Editing existing note, Deleting note and Pinning/Unpinning note.
This code is inside onCreate fucntion of MainActivity:
searchView_home = findViewById(R.id.searchView_home);
searchView_home.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
filter(newText);
return true;
}
});
This code is outside of onCreate function of MainActivity:
private void filter(String newText) {
List<Notes> filteredList = new ArrayList<>();
for (Notes singleNote: notes){
if (singleNote.getTitle().toLowerCase().contains(newText.toLowerCase())
|| singleNote.getNotes().toLowerCase().contains(newText.toLowerCase())){
filteredList.add(singleNote);
}
}
notesListAdapter.filterList(filteredList);
}
This code is inside onBindViewHolder of my NotesListAdapter class:
public void filterList(List<Notes> filteredList){
list = filteredList;
notifyDataSetChanged();
}
And this is the Notes model class itself:
#Entity(tableName = "notes")
public class Notes implements Serializable {
#PrimaryKey(autoGenerate = true)
int ID = 0;
#ColumnInfo(name = "title")
String title ="";
#ColumnInfo(name = "notes")
String notes = "";
#ColumnInfo(name = "date")
String date = "";
#ColumnInfo(name = "pinned")
boolean pinned = false;
public int getID() {
return ID;
}
public void setID(int ID) {
this.ID = ID;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getNotes() {
return notes;
}
public void setNotes(String notes) {
this.notes = notes;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public boolean isPinned() {
return pinned;
}
public void setPinned(boolean pinned) {
this.pinned = pinned;
}
}
Related
So I have a simple notes app, it has a noteModel class which extends RealmObject. I added a boolean value "pinned" to it but when I set this value to true it stops returning any of the data saved to it. The title starts returning null in the adapter and I can't use it but when I set "pinned" back to false everything goes back to normal.
Here is the Model class
public class NoteModel extends RealmObject {
#PrimaryKey
private int noteID;
private String note;
private String title;
private long timeStamp;
private boolean archived;
private boolean pinned;
public NoteModel() {
}
public boolean isPinned() {
return pinned;
}
public void setPinned(boolean pinned) {
this.pinned = pinned;
}
public int getNoteID() {
return noteID;
}
public void setNoteID(int noteID) {
this.noteID = noteID;
}
public String getNote() {
return note;
}
public void setNote(String note) {
this.note = note;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public long getTimeStamp() {
return timeStamp;
}
public void setTimeStamp(long timeStamp) {
this.timeStamp = timeStamp;
}
public boolean isArchived() {
return archived;
}
public void setArchived(boolean archived) {
this.archived = archived;
}
}
Here is the adapter code:
switch (which) {
case 0:
if (noteModel.isPinned()) {
realm.beginTransaction();
noteModel.setPinned(false);
realm.commitTransaction();
Prevalent.allNotes.add(noteModel);
Prevalent.pinnedNotes.remove(pos);
} else {
realm.beginTransaction();
noteModel.setPinned(true);
realm.commitTransaction();
Prevalent.pinnedNotes.add(noteModel);
Prevalent.allNotes.remove(index);
}
notifyItemRemoved(index);
NotesFragment.pinNote();
break;
}
When it looses the data it just starts returning null for every get request apart from pinned
Dear Stack Community,
I have an API and I have made the API interface and Api client (using retrofit). When I hit the search for a word (I do see results being shown in my logs but my screen remains blank. I am posting my code below and also the screenshot of my screen and logs message. Please see and guide me on what I might be missing. Many thanks for your attention.
MY MainActivity.java is.
public class MainActivity extends AppCompatActivity {
private ListView listViewNews;
private NewsListAdapter mAdapter;
private static final String API_KEY = "6a6f7c77766442acb20c86157a152131";
TextView emptytextView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_all);
listViewNews = findViewById(R.id.list);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu, menu);
SearchView searchView = (SearchView) menu.findItem(R.id.action_search).getActionView();
SearchManager searchManager = (SearchManager) getSystemService(SEARCH_SERVICE);
searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));
searchView.setSubmitButtonEnabled(true);
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String s) {
String country = getCountry ();
String languauge = getLanguage();
ProductService productService = APICLIENT.getClient().create(ProductService.class);
Call<List<Newsclass>> call;
if (s.length() > 0) {
call = productService.getNewsSearch(s, languauge, "publishedAt", API_KEY);
} else {
call = productService.getNews(country, API_KEY);
}
call.enqueue(new Callback() {
#Override
public void onResponse(Call call, Response response) {
List<Newsclass> newsclass = (List<Newsclass>)response.body();
mAdapter = new NewsListAdapter(getApplicationContext(), newsclass);
listViewNews.setAdapter(mAdapter);
}
#Override
public void onFailure(Call call, Throwable t) {
Toast.makeText(getApplicationContext(), t.getMessage(), Toast.LENGTH_SHORT);
}
});
return false;
}
#Override
public boolean onQueryTextChange(String s) {
return false;
}
});
return true;
}
public static String getCountry(){
Locale locale = Locale.getDefault();
String country = locale.getCountry();
return country.toLowerCase();
}
public static String getLanguage(){
Locale locale = Locale.getDefault();
String country = locale.getLanguage();
return country.toLowerCase();
}
}
My ApiClient.java
public class APICLIENT {
private static Retrofit retrofit = null;
private static final String SPORTS_API = "https://newsapi.org/v2/";
public static Retrofit getClient() {
HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
OkHttpClient client = new OkHttpClient.Builder().addInterceptor(interceptor).build();
retrofit = new Retrofit.Builder().baseUrl(SPORTS_API).addConverterFactory(GsonConverterFactory.create()).client(client).build();
return retrofit;
}
}
My APIINTERFACE.java
public interface ProductService {
/*
#GET ("search/{keyword}")
Call<List<Newsclass>> search (#Path("keyword") String keyword);
*/
#GET("top-headlines")
Call<List<Newsclass>> getNews(#Query("country") String country , #Query("apiKey") String apiKey
);
#GET("everything")
Call<List<Newsclass>> getNewsSearch(
#Query("q") String keyword, #Query("language") String language, #Query("sortBy") String sortBy, #Query("apiKey") String apiKey);
}
My adapter.
public class NewsListAdapter extends ArrayAdapter<Newsclass> {
private Context context;
private List<Newsclass> newsclass;
public NewsListAdapter (Context context, List<Newsclass> newsclass) {
super(context, R.layout.list_item_news, newsclass);
this.context = context;
this.newsclass = newsclass;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater layoutInflater = LayoutInflater.from(context);
convertView = layoutInflater.inflate(R.layout.list_item_news, parent, false);
Newsclass newclasses = newsclass.get(position);
TextView textViewTitle = convertView.findViewById(R.id.title);
textViewTitle.setText(newclasses.getTitle());
TextView textViewDes = convertView.findViewById(R.id.description);
textViewDes.setText(newclasses.getDescription());
TextView textSource = convertView.findViewById(R.id.newsSource);
textSource.setText(newclasses.getSource());
TextView texttimeView = convertView.findViewById(R.id.date);
texttimeView.setText(newclasses.getPublishedAt());
ImageView photosView = convertView.findViewById(R.id.imageView);
Picasso.get().load(newclasses.getUrlToImage()).centerCrop().fit().into(photosView);
return convertView;
}
}
My custom class.
public class Newsclass implements Serializable {
#SerializedName("title")
private String title;
#SerializedName("source")
private String source;
#SerializedName("description")
private String description;
#SerializedName("urlToImage")
private String urlToImage;
#SerializedName("publishedAt")
private String publishedAt;
#SerializedName("url")
private String url;
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getSource() {
return source;
}
public void setSource(String source) {
this.source = source;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getUrlToImage() {
return urlToImage;
}
public void setUrlToImage(String urlToImage) {
this.urlToImage = urlToImage;
}
public String getPublishedAt() {
return publishedAt;
}
public void setPublishedAt(String publishedAt) {
this.publishedAt = publishedAt;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
}
and here are the screenshots
// shows no result on my screen but in logs I can see specific queries.
enter image description here
I am trying to insert realm lists to my realmdb in my first insert there is no problem but when I insert another realmList with a different class, my old values are deleted. So how can I insert a realmlist to DB? inserts are done separately.
RealmList<Product> insertedProduct = new RealmList<Product>();
RealmList<ProductSubCategory> insertedSubCategory = new RealmList<ProductSubCategory>();
RealmList<ProductMainCategory> insertedMainCategory = new RealmList<ProductMainCategory>();
... inserting to realm list firt time ...
insertRealmList(insertedProduct); //inserting to realmDB first time
insertRealmList(insertedSubCategory); //inserting to realmDB first time
insertRealmList(insertedMainCategory); //inserting to realmDB first time
first insert to realmDB
RealmList insert function
private void insertRealmList(final RealmList realmObject) {
mRealm = Realm.getDefaultInstance();
realmTask = mRealm.executeTransactionAsync(
new Realm.Transaction() {
#Override
public void execute(Realm realm) {
realm.copyToRealmOrUpdate(realmObject);
}
},
new Realm.Transaction.OnSuccess() {
#Override
public void onSuccess() {
Log.i(TAG, "onSuccess: successfully inserted data");
}
},
new Realm.Transaction.OnError() {
#Override
public void onError(Throwable error) {
Log.i(TAG, "onError: error while inserting " + "error: " + error);
}
}
);
}
... inserting to realm list second time...
insertRealmList(insertedLanguages); //insert realmDB second time
second insert to realmDB
PRODUCT MODEL
package Model;
import io.realm.RealmList;
import io.realm.RealmObject;
import io.realm.annotations.Ignore;
import io.realm.annotations.Index;
import io.realm.annotations.PrimaryKey;
public class Product extends RealmObject {
#PrimaryKey
#Index
private int ID;
#Index
private int PLU_NO;
private String PRODUCT_NAME;
private String MAIN_CATEGORY;
private String SUB_CATEGORY;
private String TYPE;
private String TUS;
private Double PRICE;
private String CALORIE;
private String COOKING_TIME;
private RealmList<String> PRODUCT_NAME_LANGUAGES;
private RealmList<String> PRODUCT_DESCRIPTION_LANGUAGES;
private String IMAGE_BASE_HORIZONTAL; //4/3
private String IMAGE_BASE_VERTICAL; //16/9
private String VIDEO_NAME; //video name
#Ignore
private int AMOUNT;
#Ignore
private int WINDOW_AMOUNT = 1;
public Product(int ID, int PLU_NO, String PRODUCT_NAME, String MAIN_CATEGORY, String SUB_CATEGORY, String TYPE, String TUS, Double PRICE, String CALORIE, String COOKING_TIME, RealmList<String> PRODUCT_NAME_LANGUAGES, RealmList<String> PRODUCT_DESCRIPTION_LANGUAGES, String IMAGE_BASE_HORIZONTAL, String IMAGE_BASE_VERTICAL, String VIDEO_NAME) {
this.ID = ID;
this.PLU_NO = PLU_NO;
this.PRODUCT_NAME = PRODUCT_NAME;
this.MAIN_CATEGORY = MAIN_CATEGORY;
this.SUB_CATEGORY = SUB_CATEGORY;
this.TYPE = TYPE;
this.TUS = TUS;
this.PRICE = PRICE;
this.CALORIE = CALORIE;
this.COOKING_TIME = COOKING_TIME;
this.PRODUCT_NAME_LANGUAGES = PRODUCT_NAME_LANGUAGES;
this.PRODUCT_DESCRIPTION_LANGUAGES = PRODUCT_DESCRIPTION_LANGUAGES;
this.IMAGE_BASE_HORIZONTAL = IMAGE_BASE_HORIZONTAL;
this.IMAGE_BASE_VERTICAL = IMAGE_BASE_VERTICAL;
this.VIDEO_NAME = VIDEO_NAME;
}
public Product() {
}
public int getID() {
return ID;
}
public void setID(int ID) {
this.ID = ID;
}
public int getPLU_NO() {
return PLU_NO;
}
public void setPLU_NO(int PLU_NO) {
this.PLU_NO = PLU_NO;
}
public String getPRODUCT_NAME() {
return PRODUCT_NAME;
}
public void setPRODUCT_NAME(String PRODUCT_NAME) {
this.PRODUCT_NAME = PRODUCT_NAME;
}
public String getMAIN_CATEGORY() {
return MAIN_CATEGORY;
}
public void setMAIN_CATEGORY(String MAIN_CATEGORY) {
this.MAIN_CATEGORY = MAIN_CATEGORY;
}
public String getSUB_CATEGORY() {
return SUB_CATEGORY;
}
public void setSUB_CATEGORY(String SUB_CATEGORY) {
this.SUB_CATEGORY = SUB_CATEGORY;
}
public String getTYPE() {
return TYPE;
}
public void setTYPE(String TYPE) {
this.TYPE = TYPE;
}
public String getTUS() {
return TUS;
}
public void setTUS(String TUS) {
this.TUS = TUS;
}
public Double getPRICE() {
return PRICE;
}
public void setPRICE(Double PRICE) {
this.PRICE = PRICE;
}
public String getCALORIE() {
return CALORIE;
}
public void setCALORIE(String CALORIE) {
this.CALORIE = CALORIE;
}
public String getCOOKING_TIME() {
return COOKING_TIME;
}
public void setCOOKING_TIME(String COOKING_TIME) {
this.COOKING_TIME = COOKING_TIME;
}
public RealmList<String> getPRODUCT_NAME_LANGUAGES() {
return PRODUCT_NAME_LANGUAGES;
}
public void setPRODUCT_NAME_LANGUAGES(RealmList<String> PRODUCT_NAME_LANGUAGES) {
this.PRODUCT_NAME_LANGUAGES = PRODUCT_NAME_LANGUAGES;
}
public RealmList<String> getPRODUCT_DESCRIPTION_LANGUAGES() {
return PRODUCT_DESCRIPTION_LANGUAGES;
}
public void setPRODUCT_DESCRIPTION_LANGUAGES(RealmList<String> PRODUCT_DESCRIPTION_LANGUAGES) {
this.PRODUCT_DESCRIPTION_LANGUAGES = PRODUCT_DESCRIPTION_LANGUAGES;
}
public String getIMAGE_BASE_HORIZONTAL() {
return IMAGE_BASE_HORIZONTAL;
}
public void setIMAGE_BASE_HORIZONTAL(String IMAGE_BASE_HORIZONTAL) {
this.IMAGE_BASE_HORIZONTAL = IMAGE_BASE_HORIZONTAL;
}
public String getIMAGE_BASE_VERTICAL() {
return IMAGE_BASE_VERTICAL;
}
public void setIMAGE_BASE_VERTICAL(String IMAGE_BASE_VERTICAL) {
this.IMAGE_BASE_VERTICAL = IMAGE_BASE_VERTICAL;
}
public String getVIDEO_NAME() {
return VIDEO_NAME;
}
public void setVIDEO_NAME(String VIDEO_NAME) {
this.VIDEO_NAME = VIDEO_NAME;
}
public int getAMOUNT() {
return AMOUNT;
}
public void setAMOUNT(int AMOUNT) {
this.AMOUNT = AMOUNT;
}
public int getWINDOW_AMOUNT() {
return WINDOW_AMOUNT;
}
public void setWINDOW_AMOUNT(int WINDOW_AMOUNT) {
this.WINDOW_AMOUNT = WINDOW_AMOUNT;
}
public void setDEFAULT_WINDOW_AMOUNT() {
this.WINDOW_AMOUNT = 1;
}
}
LANGUAGE MODEL
package Model;
import io.realm.RealmObject;
public class Language extends RealmObject {
#PrimaryKey
#Index
private int ID;
private String ICON;
private String NAME;
public Language(){
}
public Language(int ID, String ICON, String NAME) {
this.ID = ID;
this.ICON = ICON;
this.NAME = NAME;
}
public int getId() {
return ID;
}
public void setId(int id) {
this.ID = id;
}
public String getICON() {
return ICON;
}
public void setICON(String ICON) {
this.ICON = ICON;
}
public String getName() {
return NAME;
}
public void setName(String name) {
this.NAME = name;
}
}
Other two models are similar with product.
Please try the following method:
private <T extends RealmModel> void insertRealmList(final List<T> objects) {
try (Realm realmInstance = Realm.getDefaultInstance()) {
realmInstance.executeTransaction(realm -> {
for (T object : objects) {
realmInstance.insertOrUpdate(object);
}
});
}
}
Hope this helps!
I have 2 applications(different package names) which use one Firebase database. One app has to write access to the database and another have read access to the database.in my second application, i use recyclerview to retrieve data which is stored by 1st App.
for this I use below code:
FirebaseOptions options = new FirebaseOptions.Builder()
.setApplicationId("1:567....259c8f58311") // Required for Analytics.
.setApiKey("AIzaSyA9BRxl......hE03y5qD-c") // Required for Auth.
.setDatabaseUrl("https://mycity-3a561.firebaseio.com/") // Required for RTDB.
.build();
FirebaseApp.initializeApp(this /* Context */, options, "MyCity");
// Retrieve my other app.
FirebaseApp app = FirebaseApp.getInstance("MyCity");
// Get the database for the other app.
FirebaseDatabase secondaryDatabase = FirebaseDatabase.getInstance(app);
DatabaseReference data = secondaryDatabase.getInstance().getReference();
data.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot snapshot) {
for (DataSnapshot ds : snapshot.getChildren()) {
for (DataSnapshot dSnapshot : ds.getChildren()) {
WaterClass waterClass = dSnapshot.getValue(WaterClass.class);
Log.d("Show", waterClass.getName() == null ? "" : waterClass.getName());
list.add(waterClass);
}
adapter = new WaterAdapter(ShowWaterDetails.this, list);
recyclerView.setAdapter(adapter);
adapter.notifyDataSetChanged();
progressDialog.dismiss();
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
progressDialog.dismiss();
}
});
}
Adapter class
private class WaterAdapter extends RecyclerView.Adapter<WaterAdapter.ViewHolder> {
ShowWaterDetails showDetail;
List<WaterClass> listData;
public WaterAdapter(ShowWaterDetails showWaterDetails, List<WaterClass> list) {
this.showDetail = showWaterDetails;
this.listData = list;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.show_items, parent, false);
WaterAdapter.ViewHolder viewHolder = new WaterAdapter.ViewHolder(view);
return viewHolder;
}
#Override
public void onBindViewHolder(WaterAdapter.ViewHolder holder, int position) {
WaterClass AllDetails = listData.get(position);
holder.NameTextView.setText(AllDetails.getName());
holder.DetailTextView.setText(AllDetails.getDetail());
holder.DateTextView.setText(AllDetails.getDate());
holder.LocationTextView.setText(AllDetails.getLocation());
holder.TypeTextView.setText(AllDetails.getType());
Picasso.with(showDetail).load(AllDetails.getImgurl()).resize(120, 60).into(holder.ImageTextView);
}
#Override
public int getItemCount() {
return listData.size();
}
class ViewHolder extends RecyclerView.ViewHolder {
public TextView NameTextView;
public TextView DetailTextView;
public TextView DateTextView;
public TextView LocationTextView;
public TextView TypeTextView;
public ImageView ImageTextView;
public ViewHolder(View itemView) {
super(itemView);
NameTextView = itemView.findViewById(R.id.ShowNameTextView);
DetailTextView = itemView.findViewById(R.id.ShowDetailTextView);
DateTextView = itemView.findViewById(R.id.ShowDateTextView);
LocationTextView = itemView.findViewById(R.id.ShowLocationTextView);
TypeTextView = itemView.findViewById(R.id.ShowTypeTextView);
ImageTextView = itemView.findViewById(R.id.ShowImageView);
}
}
}
}
POJO Class
class WaterClass {
private String id;
private String email;
private String name;
private String type;
private String detail;
private String location;
private String date;
private String imgurl;
public WaterClass(){
}
public WaterClass(String id, String currentUserString, String imageUrl, String nameString, String typeString, String detailString, String locationString, String dateString) {
this.id = id;
this.email = currentUserString;
this.name =nameString;
this.type = typeString;
this.detail = detailString;
this.location = locationString;
this.date = dateString;
this.imgurl = imageUrl;
}
public String getImgurl() {
return imgurl;
}
public void setImgurl(String imgurl) {
this.imgurl = imgurl;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getDetail() {
return detail;
}
public void setDetail(String detail) {
this.detail = detail;
}
public String getLocation() {
return location;
}
public void setLocation(String location) {
this.location = location;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
}
:
there is no error but my recycler not showing anything
go to onStart() and start listening
#Override
protected void onStart() {
super.onStart();
adapter.startListening();
}
and in your onStop
#Override
protected void onStop() {
super.onStop();
adapter.stopListening();
}
The FirebaseRecyclerAdapter uses a snapshot listener to monitor changes to the Firestore query. To begin listening for data, call the startListening() method. You may want to call this in your onStart() method. Make sure you have finished any authentication necessary to read the data before calling startListening() or your query will fail.
Be sure that the names of constant in the POJO match exatly the names
of your database structure in your firebase console !!
ps: do not post your api-keys or app-ids in your questions, keep them secret, and consider using firebaserecycleradapter if you are using firebase-database , it will be more easy to setup and to show values.
Your POJO is ok !
Found Solution!!
just change this part of a code
FirebaseApp.initializeApp(this /* Context */, options, "MyCity");
// Retrieve my other app.
FirebaseApp app = FirebaseApp.getInstance("MyCity");
TO
FirebaseApp.initializeApp(this);
// Retrieve my other app.
FirebaseApp app = FirebaseApp.getInstance("[DEFAULT]");
i got data from api link (server) to display data in recyclview ,if i want to click on items then it will open next activity thats fine, but some items have no data , if i want to click geting class cast exception
in this above image, click on Adventure , then it will open next activity with related data , if i want click on Kids Activities then getting Class cast exception error because from server no data is available of Kids Activities ,
if i want click on Kids ACtivities then it wil open toast massage like no more data is available , how should i get it?
This is adapter class
public class SubCategoryChild_Adapter extends RecyclerView.Adapter {
private List<SubCategoryChild> subCategoryChildList;
private Context context;
public class MyViewHolder extends RecyclerView.ViewHolder {
public TextView
discountName,
subcategorychild_merchantName,
subcategoryChild_discountedPrice,
subcategoryChild_actualPrice,
subcategoryChild_distance,
staticUgx;
public ImageView SubcategoryChild_imageView;
public SubCategoryChild subCategoryChild;
public MyViewHolder(View view) {
super(view);
subcategoryChild_actualPrice = (TextView) view.findViewById(R.id.ScChild_actualPrice);
subcategoryChild_actualPrice.setPaintFlags(subcategoryChild_actualPrice.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG);
subcategoryChild_discountedPrice = (TextView) view.findViewById(R.id.ScChild_discountedPrice);
subcategorychild_merchantName = (TextView) view.findViewById(R.id.ScChild_merchantName);
staticUgx = (TextView) view.findViewById(R.id.ScChild_actualprice_ugx);
staticUgx.setPaintFlags(staticUgx.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG);
subcategoryChild_distance = (TextView) view.findViewById(R.id.ScChild_Near_Location_text);
discountName = (TextView) view.findViewById(R.id.ScChild_Discount_Text);
SubcategoryChild_imageView = (ImageView) view.findViewById(R.id.ScChild_imageView);
}
}
public SubCategoryChild_Adapter(Context context , List<SubCategoryChild> subCategoryChildList) {
this.subCategoryChildList = subCategoryChildList;
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
RecyclerView.ViewHolder itemView;
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.subcategorydeal_list, parent, false);
itemView = new MyViewHolder(view);
return itemView;
}
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder,int position){
final SubCategoryChild subCategoryChild = subCategoryChildList.get(position);
((MyViewHolder) holder).subcategorychild_merchantName.setText(subCategoryChild.getMerchantName());
((MyViewHolder) holder).discountName.setText(subCategoryChild.getName());
((MyViewHolder) holder).subcategoryChild_actualPrice.setText(subCategoryChild.getActualPrice());
((MyViewHolder) holder).subcategoryChild_discountedPrice.setText(subCategoryChild.getDiscountedPrice());
((MyViewHolder) holder).subcategoryChild_distance.setText(subCategoryChild.getDistance());
context = ((MyViewHolder) holder).SubcategoryChild_imageView.getContext();
Picasso.with(context).load(subCategoryChild.getLogo()).fit().into(((MyViewHolder)holder).SubcategoryChild_imageView);
((MyViewHolder) holder).subCategoryChild = subCategoryChild;
}
#Override
public int getItemCount() {
if(subCategoryChildList == null){
return 0;
}else {
return subCategoryChildList.size();
}
}
}
this is model class
public class SubCategoryChild {
#SerializedName("merchant_id")
#Expose
private String merchantId;
#SerializedName("merchant_name")
#Expose
private String merchantName;
#SerializedName("name")
#Expose
private String name;
#SerializedName("deal_sub_title")
#Expose
private String dealSubTitle;
#SerializedName("discounted_price")
#Expose
private String discountedPrice;
#SerializedName("actual_price")
#Expose
private String actualPrice;
#SerializedName("discounted_percentage")
#Expose
private String discountedPercentage;
#SerializedName("category_id")
#Expose
private String categoryId;
#SerializedName("sub_category_id")
#Expose
private String subCategoryId;
#SerializedName("city_id")
#Expose
private String cityId;
#SerializedName("logo")
#Expose
private String logo;
#SerializedName("website")
#Expose
private String website;
#SerializedName("email")
#Expose
private String email;
#SerializedName("phone")
#Expose
private String phone;
#SerializedName("mobile")
#Expose
private String mobile;
#SerializedName("description")
#Expose
private String description;
#SerializedName("Merchant_address")
#Expose
private String merchantAddress;
#SerializedName("latitude")
#Expose
private String latitude;
#SerializedName("longitude")
#Expose
private String longitude;
#SerializedName("distance")
#Expose
private String distance;
#SerializedName("deal_count")
#Expose
private Integer dealCount;
public String getMerchantId() {
return merchantId;
}
public void setMerchantId(String merchantId) {
this.merchantId = merchantId;
}
public String getMerchantName() {
return merchantName;
}
public void setMerchantName(String merchantName) {
this.merchantName = merchantName;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDealSubTitle() {
return dealSubTitle;
}
public void setDealSubTitle(String dealSubTitle) {
this.dealSubTitle = dealSubTitle;
}
public String getDiscountedPrice() {
return discountedPrice;
}
public void setDiscountedPrice(String discountedPrice) {
this.discountedPrice = discountedPrice;
}
public String getActualPrice() {
return actualPrice;
}
public void setActualPrice(String actualPrice) {
this.actualPrice = actualPrice;
}
public String getDiscountedPercentage() {
return discountedPercentage;
}
public void setDiscountedPercentage(String discountedPercentage) {
this.discountedPercentage = discountedPercentage;
}
public String getCategoryId() {
return categoryId;
}
public void setCategoryId(String categoryId) {
this.categoryId = categoryId;
}
public String getSubCategoryId() {
return subCategoryId;
}
public void setSubCategoryId(String subCategoryId) {
this.subCategoryId = subCategoryId;
}
public String getCityId() {
return cityId;
}
public void setCityId(String cityId) {
this.cityId = cityId;
}
public String getLogo() {
return logo;
}
public void setLogo(String logo) {
this.logo = logo;
}
public String getWebsite() {
return website;
}
public void setWebsite(String website) {
this.website = website;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getMobile() {
return mobile;
}
public void setMobile(String mobile) {
this.mobile = mobile;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getMerchantAddress() {
return merchantAddress;
}
public void setMerchantAddress(String merchantAddress) {
this.merchantAddress = merchantAddress;
}
public String getLatitude() {
return latitude;
}
public void setLatitude(String latitude) {
this.latitude = latitude;
}
public String getLongitude() {
return longitude;
}
public void setLongitude(String longitude) {
this.longitude = longitude;
}
public String getDistance() {
return distance;
}
public void setDistance(String distance) {
this.distance = distance;
}
public Integer getDealCount() {
return dealCount;
}
public void setDealCount(Integer dealCount) {
this.dealCount = dealCount;
}
}
this is activity class
public class SubCategoryChild_Activity extends AppCompatActivity {
RecyclerView subCategoryDeal_RecyclerView;
public Context context;
ProgressBar progress_bar;
SubCategoryChild_Adapter subCategoryChild_adapter;
List<SubCategoryChild> subCategoryChildList;
SubCategoryChild subCategoryChild;
public String catId,subCatId,ActionBar_Name;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sub_category_child_);
Bundle extras = getIntent().getExtras();
catId = extras.getString("cat_Id");
subCatId = extras.getString("Sub_CatId");
ActionBar_Name = extras.getString("actionBar_Name");
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDefaultDisplayHomeAsUpEnabled(true);
getSupportActionBar().setTitle(ActionBar_Name);
subCategoryDeal_RecyclerView = (RecyclerView) findViewById(R.id.subCategoryDeal_RecyclerView);
final ProgressBar progress_bar = (ProgressBar) findViewById(R.id.ScChild_progress_bar);
subCategoryDeal_RecyclerView.setLayoutManager(new LinearLayoutManager(this));
subCategoryDeal_RecyclerView.setHasFixedSize(true);
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(this);
subCategoryDeal_RecyclerView.setLayoutManager(layoutManager);
subCategoryDeal_RecyclerView.addItemDecoration(new DividerItemDecoration(this, DividerItemDecoration.VERTICAL_LIST));
subCategoryDeal_RecyclerView.setItemAnimator(new DefaultItemAnimator());
subCategoryChild_adapter = new SubCategoryChild_Adapter(context, subCategoryChildList);
subCategoryDeal_RecyclerView.setAdapter(subCategoryChild_adapter);
progress_bar.setVisibility(View.VISIBLE);
if(new SubCategoryChild_Response().getStatus() == null){
RestClient.get(this).diskCacheEnable(true).new NetworkTask<Void, SubCategoryChild_Response>(SubCategoryChild_Response.class, Http.GET) {
#Override
protected void onPostExecute(SubCategoryChild_Response subCategoryChild_response) {
super.onPostExecute(subCategoryChild_response);
progress_bar.setVisibility(View.GONE);
if (subCategoryChild_response != null && subCategoryChild_response.getSubCategoryChild() != null & subCategoryChild_response.getSubCategoryChild().size() > 0) {
subCategoryChildList = subCategoryChild_response.getSubCategoryChild();
subCategoryChild_adapter = new SubCategoryChild_Adapter(SubCategoryChild_Activity.this, subCategoryChildList);
subCategoryDeal_RecyclerView.setAdapter(subCategoryChild_adapter);
}
}
}.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, "https://api.bargaincry.com/apurl/deal/get_merchantBy_subcat/41187/" + catId + "/" + subCatId + "/latitude~longitude");
}else {
if(new SubCategoryChild_Response().getStatus().isEmpty())
Toast.makeText(SubCategoryChild_Activity.this,"error",Toast.LENGTH_LONG).show();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.navigation_,menu);
//getMenuInflater().inflate(R.menu.navigation_, menu);
// Associate searchable configuration with the SearchView
SearchManager searchManager = (SearchManager)getSystemService(Context.SEARCH_SERVICE);
SearchView searchView = (SearchView) menu.findItem(R.id.action_search).getActionView();
ComponentName cn = new ComponentName(this, SearchResultsActivity.class);
searchView.setSearchableInfo(searchManager.getSearchableInfo(cn));
//searchView.setSubmitButtonEnabled(true);
//searchView.setOnQueryTextListener(MainActivity.this);
searchView.setIconifiedByDefault(false);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
// app icon in action bar clicked; goto parent activity.
this.finish();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}
this is Response class
public class SubCategoryChild_Response {
#SerializedName("status")
#Expose
private String status;
#SerializedName("merchant")
#Expose
private List<SubCategoryChild> subCategoryChildList = null;
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public List<SubCategoryChild> getSubCategoryChild() {
return subCategoryChildList;
}
public void setSubCategoryChildList(List<SubCategoryChild> subCategoryChildList) {
this.subCategoryChildList = subCategoryChildList;
}
}
this is catLog here
FATAL EXCEPTION: main Process: app.com.BargainCryApp, PID: 28129
java.lang.ClassCastException: java.lang.String cannot be cast to
models.SubCategoryChild_Response at
app.com.BargainCryApp.SubCategoryChild_Activity$1.onPostExecute(SubCategoryChild_Activity.java:69)
at android.os.AsyncTask.finish(AsyncTask.java:665) at
android.os.AsyncTask.-wrap1(AsyncTask.java) at
android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:682)
at android.os.Handler.dispatchMessage(Handler.java:111) at
android.os.Looper.loop(Looper.java:207) at
android.app.ActivityThread.main(ActivityThread.java:5769) at
java.lang.reflect.Method.invoke(Native Method) at
com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:861)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:751)
Before casting object, check instanceOf
if (holder instanceof MyViewHolder) {
MyViewHolder mHolder = (MyViewHolder) holder;
mHolder.subcategorychild_merchantName.setText(subCategoryChild.getMerchantName());
//..........
}
For your question how to avoid ClassCastException, the answer is use 'instanceof'
operator and instanceof returns true then further perform your actions.
if (subCategoryChild_response != null &&
subCategoryChild_response.getSubCategoryChild() != null &&
subCategoryChild_response.getSubCategoryChild() instanceof 'Your Child Class should be here'
subCategoryChild_response.getSubCategoryChild().size() > 0)
Hope this helps you