I am using Realm Database to Save the Data From the JSON within the Mobile.I am using Custom Adapter rather than the RealmAdapter.I am able to save the Data and Retrieve the Data from the Realm Database but when i delete the item by position i got an error, that says the Object is no longer valid to operate on.
ToDoRealmAdapter
public class ToDoRealmAdapter extends RealmBaseAdapter<RealmDatabasePopularDestination> {
Context mContext;
RealmResults<RealmDatabasePopularDestination> clas_realm_bookmark = null;
String TAG = "HomeTab_adapter";
public ToDoRealmAdapter(#NonNull Context context, RealmResults<RealmDatabasePopularDestination> clas_realm_bookmark) {
super(context, clas_realm_bookmark);
this.context = mContext;
this.clas_realm_bookmark = clas_realm_bookmark;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
final Holder viewHolder;
if (convertView == null) {
// inflate the layout
LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
// LayoutInflater inflater = LayoutInflater.from(parent.getContext());
convertView = inflater.inflate(R.layout.bookmark_grid_list_item, parent, false);
// well set up the ViewHolder
// viewHolder = new ClassScheduleStudentAdapter.Holder();
viewHolder = new Holder();
// viewHolder.popular_destintion_id = (TextView) convertView.findViewById(R.id.student_profile_subject);
viewHolder.title = (TextView) convertView.findViewById(R.id.festivalName);
viewHolder.imageLogo = (ImageView) convertView.findViewById(R.id.event_festival_main_image);
viewHolder.location = (TextView) convertView.findViewById(R.id.eventAddress);
viewHolder.monthEvent = (TextView) convertView.findViewById(R.id.textDateBookmark);
viewHolder.textViewIcon = (ImageView) convertView.findViewById(R.id.imageLocationBookmark);
// Log.d(TAG, "## postion:" + position + " getTeacherName" + class_destination.get(position).getId());
convertView.setTag(viewHolder);
} else {
// we've just avoided calling findViewById() on resource everytime
// just use the viewHolder
// viewHolder = (ClassScheduleStudentAdapter.Holder) convertView.getTag();
viewHolder = (Holder) convertView.getTag();
}
viewHolder.title.setText(clas_realm_bookmark.get(position).getTitle());
viewHolder.location.setText(clas_realm_bookmark.get(position).getLocation());
if (clas_realm_bookmark.get(position).getType().equals("popular_destination")) {
viewHolder.monthEvent.setVisibility(View.INVISIBLE);
viewHolder.textViewIcon.setImageResource(R.mipmap.fav_icon_popular);
} else {
viewHolder.monthEvent.setText(clas_realm_bookmark.get(position).getDateEvent());
viewHolder.textViewIcon.setImageResource(R.mipmap.events_festival_icon);
}
System.out.println("Display" + clas_realm_bookmark.get(position).getDateEvent());
Picasso picasso = Picasso.with(mContext);
// picasso.setIndicatorsEnabled(true);
picasso.load(clas_realm_bookmark.get(position).getImage()).memoryPolicy(MemoryPolicy.NO_STORE).networkPolicy(NetworkPolicy.OFFLINE).error(R.drawable.close).into(viewHolder.imageLogo, new Callback() {
#Override
public void onSuccess() {
}
#Override
public void onError() {
//Try again online if cache failed
Picasso.with(mContext)
.load(clas_realm_bookmark.get(position).getImage())
.error(R.drawable.close)
.into(viewHolder.imageLogo, new Callback() {
#Override
public void onSuccess() {
}
#Override
public void onError() {
Log.v("Picasso", "Could not fetch image");
}
});
}
});
//Picasso.with(mContext).load(clas_realm_bookmark.get(position).getImage()).error(R.drawable.close).into(viewHolder.imageLogo);
return convertView;
}
class Holder {
TextView title;
ImageView imageLogo;
TextView location;
TextView monthEvent;
ImageView textViewIcon;
}
}
PopularDestinationGridDetail
public void savetoDatabase() {
realm.executeTransactionAsync(new Realm.Transaction() {
#Override
public void execute(Realm bgRealm) {
//
count = (int) bgRealm.where(RealmDatabasePopularDestination.class).equalTo("Id", id).equalTo("Type", type).count();//mofidy Query here
if (count > 0) {
} else {
RealmDatabasePopularDestination realmDatabasePopularDestination = bgRealm.createObject(RealmDatabasePopularDestination.class);
realmDatabasePopularDestination.setId(id);
realmDatabasePopularDestination.setTitle(title);
realmDatabasePopularDestination.setLatitude(latitude);
realmDatabasePopularDestination.setLongitude(longitude);
realmDatabasePopularDestination.setImage(image);
realmDatabasePopularDestination.setType(type);
realmDatabasePopularDestination.setLocation(location);
realmDatabasePopularDestination.setDescription(description);
Log.v("Success", realmDatabasePopularDestination.getTitle());
}
}
}, new Realm.Transaction.OnSuccess() {
#Override
public void onSuccess() {
if (count > 0) {
Toast.makeText(PopularDestinationGridDetail.this, "Already added", LENGTH_LONG).show();
} else {
Toast.makeText(PopularDestinationGridDetail.this, "Added to Favorites", LENGTH_LONG).show();
}
Log.v("Success", title);
}
}, new Realm.Transaction.OnError() {
#Override
public void onError(Throwable error) {
Log.e("failed", error.getMessage());
}
});
}
Favourites
public class Favourites extends Fragment {
Realm realm;
GridView gridViewBookmark;
RealmResults<RealmDatabasePopularDestination> destination_bookmark_realm =null;
RealmResults<RealmDatabasePopularDestination> realmDatabasePopularDestinations;
FavouriteAdapter favouriteAdapter;
ToDoRealmAdapter toDoRealmAdapter;
RealmChangeListener<RealmResults<RealmDatabasePopularDestination>> realmChangeListener = new RealmChangeListener<RealmResults<RealmDatabasePopularDestination>>() {
#Override
public void onChange(RealmResults<RealmDatabasePopularDestination> databasePopularDestinations) {
toDoRealmAdapter.notifyDataSetChanged();
}
};
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
Realm.init(getContext());
realm = Realm.getDefaultInstance();
View view = inflater.inflate(R.layout.bookmark_layout_gridview, container, false);
gridViewBookmark = (GridView) view.findViewById(R.id.gridviewBookmark);
getData();
getGridItemClick();
return view;
}
RealmResults<RealmDatabasePopularDestination> result;
public void getData() {
result = realm.where(RealmDatabasePopularDestination.class).findAll();
result.load();
// System.out.println("Result" + result.get(0).getTitle());
for (int i = 0; i < result.size(); i++) {
//if(result.get(i).getType().equals("popular_destination")) {
destination_bookmark_realm.add(result.get(i));
//}else{
// destination_bookmark_realm.add(result.get(i));
//}
}
// favouriteAdapter = new FavouriteAdapter(getContext(), destination_bookmark_realm);
// gridViewBookmark.setAdapter(favouriteAdapter);
toDoRealmAdapter = new ToDoRealmAdapter(getContext(), destination_bookmark_realm);
gridViewBookmark.setAdapter(toDoRealmAdapter);
destination_bookmark_realm.addChangeListener((RealmChangeListener<RealmResults<RealmDatabasePopularDestination>>) realmChangeListener);
System.out.println("Result is" + result);
}
String type;
public void getType(final int pos) {
realm.executeTransactionAsync(new Realm.Transaction() {
#Override
public void execute(Realm bgRealm) {
//
RealmResults<RealmDatabasePopularDestination> results = bgRealm.where(RealmDatabasePopularDestination.class).findAll();//mofidy Query here
type = results.get(pos).getType();
System.out.println("LOg2" + type);
}
}, new Realm.Transaction.OnSuccess() {
#Override
public void onSuccess() {
}
}, new Realm.Transaction.OnError() {
#Override
public void onError(Throwable error) {
Log.e("failed", error.getMessage());
}
});
}
public void getGridItemClick() {
gridViewBookmark.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
getType(position);
System.out.println("LOg" + type);
if (type == null) {
return;
}
if (type.equals("popular_destination")) {
System.out.println("LOg4" + type);
Intent Bookmark_Popular_Des_grid_intent = new Intent(getContext(), PopularDestinationGridDetail.class);
Bundle popular_destination_bundle = new Bundle();
popular_destination_bundle.putString("Popular_Destination_ID", String.valueOf(destination_bookmark_realm.get(position).getId()));
popular_destination_bundle.putString("Fav_Flag", "1");
Bookmark_Popular_Des_grid_intent.putExtras(popular_destination_bundle);
startActivity(Bookmark_Popular_Des_grid_intent);
} else {
System.out.println("LOg5" + type);
Intent Bookmark_Event_fes_grid_intent = new Intent(getContext(), EventAndFestivalGridDetail.class);
Bundle event_festival_bundle = new Bundle();
event_festival_bundle.putString("Event_Festival_ID", String.valueOf(destination_bookmark_realm.get(position).getId()));
event_festival_bundle.putString("Fav_Flag", "2");
Bookmark_Event_fes_grid_intent.putExtras(event_festival_bundle);
startActivity(Bookmark_Event_fes_grid_intent);
}
}
});
}
#Override
public void onDestroy() {
super.onDestroy();
result.removeAllChangeListeners();
realm.close();
}
}
log
e: FATAL EXCEPTION: main
Process: org.municipality.mobile.patanheritage, PID: 31896
java.lang.NoSuchFieldError: No field handlerController of type Lio/realm/HandlerController; in class Lio/realm/BaseRealm; or its superclasses (declaration of 'io.realm.BaseRealm' appears in /data/app/org.municipality.mobile.patanheritage-2/base.apk)
at io.realm.RealmBaseAdapter.addListener(RealmBaseAdapter.java:67)
at io.realm.RealmBaseAdapter.<init>(RealmBaseAdapter.java:60)
at org.municipality.mobile.patanheritage.adapter.ToDoRealmAdapter.<init>(ToDoRealmAdapter.java:36)
at org.municipality.mobile.patanheritage.activity.PopularDestinationGridDetail.onCreate(PopularDestinationGridDetail.java:121)
at android.app.Activity.performCreate(Activity.java:6662)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1118)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2599)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2707)
at android.app.ActivityThread.-wrap12(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1460)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
How can this issue be solved??
If you delete a given RealmObject on any thread, then when Realm becomes updated (and RealmChangeListeners are called), then that object will no longer be valid, and will no longer be available in any RealmResults<T> that previously had it.
However you for whatever reason copy the contents of the RealmResults to an ArrayList
ArrayList<T> arrayList = new ArrayList<>();
arrayList.addAll(realmResults); // <-- DON'T DO THIS AT HOME
which is super-duper horrible, because not only will the result set no longer update, but it will also be able to store and retain invalid objects.
Therefore,
public class FavouriteAdapter extends BaseAdapter {
Context mContext;
ArrayList<RealmDatabasePopularDestination> clas_realm_bookmark = null; // <-- BAD
String TAG = "HomeTab_adapter";
public FavouriteAdapter(Context mContext,
ArrayList<RealmDatabasePopularDestination> clas_realm_bookmark) { // <-- BAD
super();
this.mContext = mContext;
and should be either
public class FavouriteAdapter extends BaseAdapter {
Context mContext;
List<RealmDatabasePopularDestination> clas_realm_bookmark = null;
String TAG = "HomeTab_adapter";
public FavouriteAdapter(Context mContext, List<RealmDatabasePopularDestination> clas_realm_bookmark) {
super();
this.mContext = mContext;
with
RealmResults<...> results;
FavouriteAdapter adapter;
RealmChangeListener<RealmResults<...>> realmChangeListener = (element) -> {
adapter.notifyDataSetChanged();
};
public void onCreate(Bundle b) {
....
results = realm.where(RealmDatabasePopularDestination.class).findAll();
FavouriteAdapter adapter = new FavouriteAdapter(this, results);
results.addChangeListener(realmChangeListener);
}
public void onDestroy() {
....
results.removeAllChangeListeners();
realm.close();
}
OR
public class FavouriteAdapter extends RealmBaseAdapter<RealmDatabasePopularDestination> {
Context mContext;
//ArrayList<RealmDatabasePopularDestination> clas_realm_bookmark = null;
String TAG = "HomeTab_adapter";
public FavouriteAdapter(Context mContext, RealmResults<RealmDatabasePopularDestination> results) {
super(results);
...
EDIT: also, remove the commented code entirely
...executeTransactionAsync(realm -> {
if (count > 0) {
// RealmResults<RealmDatabasePopularDestination> result = bgRealm.where(RealmDatabasePopularDestination.class).equalTo("Id", pop_dest_id).equalTo("Type", "popular_destination").findAll();
// result.deleteAllFromRealm();
// results = realm.where(RealmDatabasePopularDestination.class).equalTo("Id", pop_dest_id).equalTo("Type", "popular_destination").findAll();
// adapter = new FavouriteAdapter(getApplicationContext(), results);
// results.addChangeListener(realmChangeListener);
Related
I have two ArrayLists from which I am trying to insert data into separate static ArrayList in another class and display in RecyclerView, but the recycler is not getting populated though the same was being done with a dummy ArrayList.Please help me with this problem.
My Class where I am inserting data from phoneContactNos and phoneContactName in two separate ArrayList: Common.selectedContactNos and Common.selectedContactName.
public void displayMatchedContacts()
{
try {
for (int i = 1; i < phoneContactNos.size(); i++) {
if (phoneContactNos.contains(registeredContactNos.get(i))) {
if (registeredContactNos.get(i) != null) {
try {
indexOfRegNumber = phoneContactNos.indexOf(registeredContactNos.get(i));
//Common.indexPosition_contacts=indexOfRegNumber;
Toast.makeText(this, "index" + String.valueOf(indexOfRegNumber), Toast.LENGTH_LONG).show();
if ((phoneContactNos.get(indexOfRegNumber) != null) &&(phoneContactName.get(indexOfRegNumber) != null)) {
//String regName="";
//String regContact="";
Common.selectedContactNos.add(phoneContactNos.get(indexOfRegNumber));
//Toast.makeText(this,selectedContactNos.get(i).toString(),Toast.LENGTH_SHORT).show();
//Toast.makeText(this,phoneContactNos.get(indexOfRegNumber).toString(),Toast.LENGTH_SHORT).show();
Common.selectedContactName.add(phoneContactName.get(indexOfRegNumber));
//Toast.makeText(this,selectedContactName.get(i).toString(),Toast.LENGTH_SHORT).show();
//Toast.makeText(this, phoneContactName.get(indexOfRegNumber).toString(), Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, "null index no", Toast.LENGTH_SHORT).show();
}
} catch (Exception e) {
Log.i("Contacts display error", e.getLocalizedMessage());
e.printStackTrace();
}
}
}
}
}catch (Exception e)
{
Log.i("Contacts error in loop", e.getLocalizedMessage());
e.printStackTrace();
}
}
My Common class
public final class Common {
public static ArrayList<String> selectedContactNos=new ArrayList<>();
public static ArrayList<String> selectedContactName=new ArrayList<>();
public static String fcmId="";
public static int position;
public static String contacts_list="";
public static int indexPosition_contacts;
}
My RecyclerView populating code
public void populateList() {
Log.i("Populate List","Entered");
LinearLayoutManager mLinearLayoutManager = new LinearLayoutManager(this);
recyclerView_contacts.setLayoutManager(mLinearLayoutManager);
displayRecyclerAdapter = new DisplayRecyclerAdapter(this);
recyclerView_contacts.setAdapter(displayRecyclerAdapter);
}
My Adapter Class
public class DisplayRecyclerAdapter extends RecyclerView.Adapter<DisplayRecyclerAdapter.displayViewHolder> {
private LayoutInflater mInflater;
private Context context;
Fragment fragment;
FragmentTransaction ft;
FrameLayout container;
public DisplayContacts displayContacts;
public DisplayRecyclerAdapter(Context context) {
this.mInflater = LayoutInflater.from(context);
this.context = context;
ft = ((AppCompatActivity) context).getSupportFragmentManager().beginTransaction();
//displayContacts = new DisplayContacts();
}
#Override
public displayViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = mInflater.inflate(R.layout.contacts_row, parent, false);
displayViewHolder holder = new displayViewHolder(view);
return holder;
}
#Override
public void onBindViewHolder(displayViewHolder holder, int position) {
holder.setData(position);
//Common.position = position;
holder.setListeners();
//for(int i=0;i<((DisplayContacts)context).selectedContactName.size();i++)
for(int i=0;i<Common.selectedContactName.size();i++)
{
//String contactName=((DisplayContacts)context).selectedContactName.get(i);
String contactName=Common.selectedContactName.get(i);
//String contactNumber=((DisplayContacts)context).selectedContactNos.get(i);
String contactNumber=Common.selectedContactNos.get(i);
Toast.makeText(context,contactName+","+contactNumber,Toast.LENGTH_SHORT).show();
}
}
class displayViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
int position;
//ImageView productSearchImg;
TextView name_contactList;
Button call_contact;
public displayViewHolder(View itemView) {
super(itemView);
name_contactList = (TextView) itemView.findViewById(R.id.contactlist_name);
call_contact = (Button) itemView.findViewById(R.id.contactlist_call);
}
public void setData(int position) {
this.position = position;
//String displayContacts=((DisplayContacts) context).selectedContactName.get(position);
String displayContacts=Common.selectedContactName.get(position);
Toast.makeText(context,"name to display"+ displayContacts,Toast.LENGTH_SHORT).show();
//name_contactList.setText(((DisplayContacts) context).selectedContactName.get(position));
//name_contactList.setText(displayContacts);
name_contactList.setText("dummy text");
}
#Override
public void onClick(View v) {
//sendPushNotification();
startAudioCall();
}
public void setListeners() {
call_contact.setOnClickListener(displayViewHolder.this);
}
}
public void startAudioCall() {
Intent i = new Intent(context, AudioCallActivity.class).setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(i);
}
#Override
public int getItemCount() {
return ((DisplayContacts) context).selectedContactName.size();
}
}
can be one of two things:
1.you are not attaching the adapter with data,hence empty
2.or you are updating your data but not calling notifyDataSetChanged()
try to pass the list data in your Adapter class while you are creating it,then attach it to the recyelerview.
//to give a vary basic example
List dataList;
RvAdapter(Context c,List data){
this.dataList=data;
}
onBidViewHolder(Viewholder holder,int position){
holder.tvName.setText(dataList.get(position).getName());
.......
}
//in your activity/fragment
RvAdapter adapter=new RavAdapter(context,dataList);
recylerview.setAdapter(adapter);
//if you change your data
adapter.notifyDataSetChanged()
I am able to Save the JSON Data to the Realm Database. I have used as the documentation of the Realm, but I am not able to set the data to the GridView. I am using Custom Adapter not the Realm Adapter. The Data are Logged but they are not Displayed to the GridView. How can this the Data be Retrieved and Displayed to the GridView?
PopularDestinationGridDetail this is where JSON data is parsed and saved to database
Realm.init(this);
realm = Realm.getDefaultInstance();
LinearAddTOFavourite.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
savetoDatabase();
}
});
public void savetoDatabase() {
realm.executeTransactionAsync(new Realm.Transaction() {
#Override
public void execute(Realm bgRealm) {
RealmDatabasePopularDestination realmDatabasePopularDestination = bgRealm.createObject(RealmDatabasePopularDestination.class);
realmDatabasePopularDestination.setTitle(title);
realmDatabasePopularDestination.setTitle(latitude);
realmDatabasePopularDestination.setTitle(longitude);
realmDatabasePopularDestination.setImage(image);
// Toast.makeText(this, realmDatabasePopularDestination.setLatitude(realmDatabasePopularDestination1.getLatitude()))
}
}, new Realm.Transaction.OnSuccess() {
#Override
public void onSuccess() {
Log.v("Success",title);
}
}, new Realm.Transaction.OnError() {
#Override
public void onError(Throwable error) {
Log.e("failed", error.getMessage());
}
});
}
Favourites
public class Favourites extends Fragment {
Realm realm;
GridView gridViewBookmark;
ArrayList<RealmDatabasePopularDestination> destination_bookmark_realm = new ArrayList<>();
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
Realm.init(getContext());
realm = Realm.getDefaultInstance();
RealmDatabasePopularDestination realmDatabasePopularDestination = new RealmDatabasePopularDestination();
View view = inflater.inflate(R.layout.bookmark_layout_gridview, container, false);
gridViewBookmark = (GridView) view.findViewById(R.id.gridviewBookmark);
destination_bookmark_realm.add(realmDatabasePopularDestination);
getData();
return view;
}
public void getData() {
FavouriteAdapter favouriteAdapter = new FavouriteAdapter(getContext(), destination_bookmark_realm);
gridViewBookmark.setAdapter(favouriteAdapter);
RealmResults<RealmDatabasePopularDestination> result = realm.where(RealmDatabasePopularDestination.class).equalTo("Title","niyash temple").findAll();
result.load();
System.out.println("Result is" + result);
// String output = "";
// for (RealmDatabasePopularDestination realmDatabasePopularDestination : result) {
//
//
// output += realmDatabasePopularDestination.toString();
//
// }
//
// System.out.println("output" + output);
// System.out.println("Total size=" + result.size());
}
}
getter and setter
public class RealmDatabasePopularDestination extends RealmObject {
String Title;
String Latitude;
String Longitude;
String image;
public String getTitle() {
return Title;
}
public void setTitle(String title) {
Title = title;
}
public String getLatitude() {
return Latitude;
}
public void setLatitude(String latitude) {
Latitude = latitude;
}
public String getLongitude() {
return Longitude;
}
public void setLongitude(String longitude) {
Longitude = longitude;
}
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
}
FavouriteAdapter
public class FavouriteAdapter extends BaseAdapter {
Context mContext;
ArrayList<RealmDatabasePopularDestination> clas_realm_bookmark = null;
String TAG = "HomeTab_adapter";
public FavouriteAdapter(Context mContext, ArrayList<RealmDatabasePopularDestination> clas_realm_bookmark) {
super();
this.mContext = mContext;
this.clas_realm_bookmark = clas_realm_bookmark;
}
#Override
public int getCount() {
return clas_realm_bookmark.size();
}
#Override
public Object getItem(int position) {
return clas_realm_bookmark.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
final FavouriteAdapter.Holder viewHolder;
if (convertView == null) {
// inflate the layout
LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
// LayoutInflater inflater = LayoutInflater.from(parent.getContext());
convertView = inflater.inflate(R.layout.bookmark_grid_list_item, parent, false);
// well set up the ViewHolder
// viewHolder = new ClassScheduleStudentAdapter.Holder();
viewHolder = new FavouriteAdapter.Holder();
// viewHolder.popular_destintion_id = (TextView) convertView.findViewById(R.id.student_profile_subject);
viewHolder.title = (TextView) convertView.findViewById(R.id.festivalName);
viewHolder.imageLogo = (ImageView) convertView.findViewById(R.id.event_festival_main_image);
// Log.d(TAG, "## postion:" + position + " getTeacherName" + class_destination.get(position).getId());
convertView.setTag(viewHolder);
} else {
// we've just avoided calling findViewById() on resource everytime
// just use the viewHolder
// viewHolder = (ClassScheduleStudentAdapter.Holder) convertView.getTag();
viewHolder = (Holder) convertView.getTag();
}
viewHolder.title.setText(clas_realm_bookmark.get(position).getTitle());
Picasso.with(mContext).load(clas_realm_bookmark.get(position).getImage()).error(R.drawable.close).into(viewHolder.imageLogo);
return convertView;
}
class Holder {
TextView title;
ImageView imageLogo;
}
}
I am not getting any error but they are not set on the ListView.This is the first time using realm, so don't get where I am doing wrong.
Instead of
public class FavouriteAdapter extends BaseAdapter {
Context mContext;
ArrayList<RealmDatabasePopularDestination> clas_realm_bookmark = null;
You should be using RealmBaseAdapter from realm-android-adapters as specified in the documentation.
you are setting adapter to list view before extracting data from database.
RealmResults<RealmDatabasePopularDestination> result = realm.where(RealmDatabasePopularDestination.class).equalTo("Title","niyash temple").findAll();
result.load();
FavouriteAdapter favouriteAdapter = new FavouriteAdapter(getContext(), destination_bookmark_realm);
gridViewBookmark.setAdapter(favouriteAdapter);
use above code and.
destination_bookmark_realm it should be load with the result you got from databse
I am getting some job information from the internet, and preparing to display using Listview. While I use RxJava to deal with multiple thread, and the list item cannot display.List item cannot display getting data using RxJava
And I use some test data, it can displayUse an array as data
public class MainActivity extends AppCompatActivity {
private Toolbar mToolbar;
private ActionBar mActionbar;
private ListView mSeminarList;
private SeminarListAdapter mSeminarListAdapter;
private ArrayList<SeminarListItem> mSeminarData;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initToolbar();
initSlideMenu();
initListView();
}
private void initToolbar() {
mToolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(mToolbar);
mActionbar = getSupportActionBar();
mActionbar.setTitle("爱实习 爱工作");
mToolbar.setNavigationIcon(R.mipmap.ic_menu_white_36dp);
}
private void initSlideMenu() {
PrimaryDrawerItem priItemHome = new PrimaryDrawerItem()
.withName("首页");
SecondaryDrawerItem subItemSeminar = new SecondaryDrawerItem()
.withName("宣讲信息");
SecondaryDrawerItem subItemIntern = new SecondaryDrawerItem()
.withName("实习信息");
SecondaryDrawerItem subItemJob = new SecondaryDrawerItem()
.withName("工作信息");
Drawer result = new DrawerBuilder()
.withActivity(this)
.withToolbar(mToolbar)
.addDrawerItems(
priItemHome, new DividerDrawerItem(),
subItemSeminar, subItemIntern, subItemJob
)
.build();
}
private void initListView() {
mSeminarList = (ListView) findViewById(R.id.listview_seminar);
mSeminarData = new ArrayList<SeminarListItem>();
// getListData();
getListDataTest();
}
private void getListData() {
Observable.create(new Observable.OnSubscribe<Elements>() {
public void call(Subscriber<? super Elements> subscriber) {
try {
String url = "http://xjh.haitou.cc/sh/uni-132";
Connection conn = Jsoup.connect(url);
conn.header("User-Agent", "Mozilla/5.0 (X11; Linux x86_64; rv:32.0) Gecko/20100101 Firefox/32.0");
Document doc = conn.get();
Elements elements = doc.select("tbody tr");
subscriber.onNext(elements);
subscriber.onCompleted();
} catch (Exception e) {
Log.d("Exception", e.toString());
}
}
}).subscribeOn(Schedulers.io())
.subscribe(new Observer<Elements>() {
#Override
public void onCompleted() {
Log.d("onCompleted", "test");
if (mSeminarListAdapter == null) {
mSeminarListAdapter = new SeminarListAdapter(getApplicationContext(), R.layout.list_item, mSeminarData);
}
mSeminarList.setAdapter(mSeminarListAdapter);
mSeminarListAdapter.notifyDataSetChanged();
}
#Override
public void onError(Throwable e) {
}
#Override
public synchronized void onNext(Elements elements) {
for (Element element : elements) {
String company = element.getElementsByClass("company").text();
String link = element.select("a").attr("abs:href").toString();
String time = element.getElementsByClass("hold-ymd").text();
String address = element.getElementsByClass("text-ellipsis").text();
SeminarListItem item = new SeminarListItem();
item.setCompanyName(company);
item.setTime("举办时间: " + time);
item.setPlace("举办地点: " + address);
item.setInfoUrl(link);
mSeminarData.add(item);
Log.d("test company name", company);
}
}
});
}
private void getListDataTest() {
for (int i=0; i<10; i++) {
SeminarListItem item = new SeminarListItem();
item.setCompanyName("company" + i);
item.setPlace("place" + i);
item.setTime("time" + i);
mSeminarData.add(item);
}
if (mSeminarListAdapter == null) {
mSeminarListAdapter = new SeminarListAdapter(MainActivity.this, R.layout.list_item, mSeminarData);
}
mSeminarList.setAdapter(mSeminarListAdapter);
mSeminarListAdapter.notifyDataSetChanged();
}
}
Following is the my custom adapter.
public class SeminarListAdapter extends ArrayAdapter<SeminarListItem> {
Context mContext;
int mResId;
ArrayList<SeminarListItem> mSeminarListData;
public SeminarListAdapter(Context context, int resource, ArrayList<SeminarListItem> object) {
super(context, resource, object);
this.mContext = context;
this.mResId = resource;
this.mSeminarListData = object;
}
public void setSeminarListData(ArrayList<SeminarListItem> data) {
this.mSeminarListData = data;
notifyDataSetChanged();
}
#Override
public int getCount() {
if (mSeminarListData == null) {
return 0;
} else {
return mSeminarListData.size();
}
}
#Override
public SeminarListItem getItem(int position) {
if (mSeminarListData == null) {
return null;
} else {
return mSeminarListData.get(position);
}
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
LayoutInflater inflater = ((Activity)mContext).getLayoutInflater();
convertView = inflater.inflate(mResId, parent, false);
holder = new ViewHolder();
holder.companyName = (TextView) convertView.findViewById(R.id.textview_company_name);
holder.time = (TextView) convertView.findViewById(R.id.textview_time);
holder.place = (TextView) convertView.findViewById(R.id.textview_place);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
SeminarListItem item = mSeminarListData.get(position);
holder.companyName.setText(item.getCompanyName());
holder.time.setText(item.getTime());
holder.place.setText(item.getPlace());
return convertView;
}
class ViewHolder {
public TextView companyName;
public TextView time;
public TextView place;
}
}
While I call fuction getListDataTest(), it display successfully, and if I call fuction getListData(), it will fail. I have debugged, and found that function getView() in adapter will not be called.
I doubt that, if I get the argument "context" using MainActivity at a new thread, it will differ from the "context" got from the UI main thread.
You need to do your listview operations, i.e. notifyDataSetChanged, on the mainthread. The simplest way to do this is to use rxandroid and add
.observeOn(AndroidSchedulers.mainThread())
before subscribing to the observable.
MyFragment
#Override
public View onCreateView(LayoutInflater inflater, final ViewGroup container,
Bundle savedInstanceState) {
setHasOptionsMenu(true);
// Inflate the layout for this fragment
final View layoutSearch = inflater.inflate(R.layout.fragment_search, container, false);
mswipeRefreshLayout=(SwipeRefreshLayout) layoutSearch.findViewById(R.id.searchMoviesRefresh);
mswipeRefreshLayout.setOnRefreshListener(this);
textVolleyError = (TextView) layoutSearch.findViewById(R.id.textVolleyError);
listMovieHits = (RecyclerView) layoutSearch.findViewById(R.id.search_movies);
listMovieHits.setLayoutManager(new LinearLayoutManager(getActivity()));
search=(SearchView) layoutSearch.findViewById(R.id.searchView1);
search.setQueryHint("Start typing to search...");
buttonBarcode = (ImageButton) layoutSearch.findViewById(R.id.imageButton2);
buttonAudio = (ImageButton) layoutSearch.findViewById(R.id.imageButton1);
search.setOnQueryTextFocusChangeListener(new View.OnFocusChangeListener() {
#Override
public void onFocusChange(View v, boolean hasFocus) {
}
});search.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
L.t(getActivity(), newText);
if (newText.length() > 3) {
listMovieHits.setVisibility(layoutSearch.getVisibility());
searchForMovies m = (searchForMovies) new searchForMovies().execute(newText);
} else {
listMovieHits.setVisibility(layoutSearch.INVISIBLE);
}
return false;
}
});
listMovieHits.setAdapter(mAdapterBoxOffice);
if (savedInstanceState != null) {
mlistMovies = savedInstanceState.getParcelableArrayList(STATE_MOVIES);
} else {
L.t(getActivity(), "executing task from the fragment");
/*new TaskLoadSearchMovies(this).execute();*/
}
/* mAdapterBoxOffice.setMovieList(filteredProductResults);
mAdapterBoxOffice.SetOnclickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
container.getContext().startActivity(new Intent(container.getContext(), Details_Activity.class));
}
});*/
return layoutSearch;
}
public void filterProductArray(String newText){
String sName;
filteredProductResults.clear();
for (int i=0; i<mlistMovies.size(); i++)
{
sName=mlistMovies.get(i).getTitle().toLowerCase();
if (sName.contains(newText.toLowerCase()))
{
filteredProductResults.add(mlistMovies.get(i));
}
}
}
class searchForMovies extends AsyncTask<String, Void, String>
{
Parser parser;
JSONArray listMovies;
String url=new String();
String textSearch;
ProgressDialog progressDialog;
#Override
protected void onPreExecute(){
super.onPreExecute();
listMovies=new JSONArray();
parser =new Parser();
progressDialog=new ProgressDialog(getActivity());
progressDialog.setCancelable(false);
progressDialog.setMessage("Searching....");
progressDialog.getWindow().setGravity(Gravity.CENTER);
progressDialog.show();
}
#Override
protected String doInBackground(String... params) {
url="http://api.rottentomatoes.com/api/public/v1.0/movies.json?apikey={MyID}="+params+"limit=30";
String returnMovieResult= getMovieList();
this.textSearch=params[0];
return returnMovieResult;
}
private String getMovieList() {
Movie tempMovie=new Movie();
String mathFound="N";
try{
JSONObject response = Requestor.sendRequestBoxOfficeMovies(requestQueue, url);
ArrayList<Movie> listMovies = Parser.parseMoviesJSON(response);
L.m(String.valueOf(listMovies));
}catch (Exception e){
e.printStackTrace();
return "error";
}
return ("Exception");
}
protected void onPostExecute(String result){
super.onPostExecute(result);
if(result.equalsIgnoreCase("Exception Caught"))
{
Toast.makeText(getActivity(), "Unable to connect to server,please try later", Toast.LENGTH_LONG).show();
progressDialog.dismiss();
}
else
{
//calling this method to filter the search results from productResults and move them to
//filteredProductResults
filterProductArray(textSearch);
listMovieHits.setAdapter(mAdapterBoxOffice);
mAdapterBoxOffice.setFilteredMovies(mlistMovies);
progressDialog.dismiss();
}
}
}
AdapterClass
public class AdapterBoxOffice extends RecyclerView.Adapter<AdapterBoxOffice.ViewHolderBoxOffice> {
private LayoutInflater layoutInflater;
private ArrayList<Movie> mlistMovies = new ArrayList<>();
private VolleySingleton volleySingleton;
private ImageLoader imageLoader;
private DateFormat dateFormat = new SimpleDateFormat("yyy-MM-dd");
private int previousPosition=0;
AdapterView.OnItemClickListener mOnItemClickListener;
public AdapterBoxOffice(Context context) {
layoutInflater = LayoutInflater.from(context);
volleySingleton = VolleySingleton.getsInstance();
imageLoader = volleySingleton.getImageLoader();
}
public void setMovieList(ArrayList<Movie> listMovies) {
this.mlistMovies = listMovies;
notifyDataSetChanged();
}
public void setFilteredMovies(ArrayList<Movie> filteredProductResults){
this.mlistMovies=filteredProductResults;
}
#Override
public ViewHolderBoxOffice onCreateViewHolder(ViewGroup parent, int viewType) {
View view = layoutInflater.inflate(R.layout.custom_movie_box_office, parent, false);
ViewHolderBoxOffice viewHolder = new ViewHolderBoxOffice(view);
return viewHolder;
}
#Override
public void onBindViewHolder(final ViewHolderBoxOffice holder, int position) {
Movie currentMovie = mlistMovies.get(position);
holder.movieTitle.setText(currentMovie.getTitle());
Date movieReleaseDate = currentMovie.getReleaseDateTheater();
if (movieReleaseDate != null) {
String formmattedDate = dateFormat.format(movieReleaseDate);
holder.movieReleaseDate.setText(formmattedDate);
} else {
holder.movieReleaseDate.setText(Constants.NA);
}
int audienceScore=currentMovie.getAudienceScore();
if (audienceScore==-1){
holder.movieAudienceScore.setRating(0.0F);
holder.movieAudienceScore.setAlpha(0.5F);
}
else
{
holder.movieAudienceScore.setRating(currentMovie.getAudienceScore() / 20.0F);
holder.movieAudienceScore.setAlpha(1.0F);
}
if(position>previousPosition)
{
comeagain.materialdesign.anim.AnimationUtils.animate(holder, true);
}else {
comeagain.materialdesign.anim.AnimationUtils.animate(holder, false);
}
previousPosition=position;
String urlThumbnail = currentMovie.getUrlThumbnail();
loadImages(urlThumbnail, holder);
}
private void loadImages(String urlThumbnail, final ViewHolderBoxOffice holder) {
if (urlThumbnail != null) {
imageLoader.get(urlThumbnail, new ImageLoader.ImageListener() {
#Override
public void onResponse(ImageLoader.ImageContainer response, boolean isImmediate) {
holder.movieThumbnail.setImageBitmap(response.getBitmap());
}
#Override
public void onErrorResponse(VolleyError error) {
}
});
}
}
#Override
public int getItemCount() {
return mlistMovies.size();
}
class ViewHolderBoxOffice extends RecyclerView.ViewHolder implements View.OnClickListener {
private ImageView movieThumbnail;
private TextView movieTitle;
private TextView movieReleaseDate;
private RatingBar movieAudienceScore;
public ViewHolderBoxOffice(View itemView) {
super(itemView);
movieThumbnail = (ImageView) itemView.findViewById(R.id.movieThumbnail);
movieTitle = (TextView) itemView.findViewById(R.id.movieTitle);
movieReleaseDate = (TextView) itemView.findViewById(R.id.movieReleaseDate);
movieAudienceScore = (RatingBar) itemView.findViewById(R.id.movieAudienceScore);
}
}
LogCat
01-23 22:00:18.141 19563-19563/comeagain.materialdesign E/AndroidRuntime: FATAL EXCEPTION: main
Process: comeagain.materialdesign, PID: 19563
java.lang.NullPointerException: Attempt to invoke virtual method 'void comeagain.materialdesign.adapters.AdapterBoxOffice.setFilteredMovies(java.util.ArrayList)' on a null object reference
at comeagain.materialdesign.fragments.FragmentSearch$searchForMovies.onPostExecute(FragmentSearch.java:270)
at comeagain.materialdesign.fragments.FragmentSearch$searchForMovies.onPostExecute(FragmentSearch.java:209)
at android.os.AsyncTask.finish(AsyncTask.java:651)
at android.os.AsyncTask.-wrap1(AsyncTask.java)
at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:668)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
I want to implement search query in Json Api, the problem is that the I am getting a null exception . I do not know why the filteredArray is returning null, I really do not know where is the problem, Please help me solve this issue.
when I conduct onRefresh, my recyclerView adds on another copy to my current recyclerView instead of refreshing it, by looking at my code below does anyone know what the problem is?I have tried everything but nothing seems to work?
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
//send our volley JSON Request
//Initialize VolleySingleton
mVolleySingleton = VolleySingleton.getInstance();
//intitalize Volley Singleton request key
mRequestQueue = mVolleySingleton.getRequestQueue();
//2 types of requests an Array request and an Object Request
JSONArrayRequest();
}
private void JSONArrayRequest() {
JsonArrayRequest request = new JsonArrayRequest(Request.Method.GET, URL_API, (String) null, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
listblogs=parseJSONResponse(response);
mAdapterDashBoard.setBloglist(listblogs);
System.out.println("it worked!!!");
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
ToastTest.t(getActivity(), error.toString());
}
});
mRequestQueue.add(request);
}
private ArrayList<Blogs> parseJSONResponse(JSONArray response) {
if (!response.equals("")) {
ArrayList<Blogs> blogsArrayList = new ArrayList<>();
try {
StringBuilder data = new StringBuilder();
for (int i = 0; i < response.length(); i++) {
JSONObject currentQuestions = response.getJSONObject(i);
String text = currentQuestions.getString("text");
String points = currentQuestions.getString("points");
String ID=currentQuestions.getString("id");
String courseId = currentQuestions.getString("courseId");
String studentId = currentQuestions.getString("studentId");
data.append(text + "\n" + points + "\n" + courseId + "\n");
System.out.println(data);
Blogs blogs = new Blogs();
blogs.setId(ID);
blogs.setMstudentId(studentId);
blogs.setMtext(text);
blogs.setPoints(points);
listblogs.add(blogs);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
return listblogs;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view=inflater.inflate(R.layout.fragment_dashboard,container,false);
mRecyclerView=(RecyclerView)view.findViewById(R.id.fragment_dashboard);
mRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
mAdapterDashBoard=new AdapterDashBoard(getActivity());
mRecyclerView.setAdapter(mAdapterDashBoard);
mPullToRefreshView = (PullToRefreshView)view.findViewById(R.id.pull_to_refresh);
mPullToRefreshView.setOnRefreshListener(new PullToRefreshView.OnRefreshListener() {
#Override
public void onRefresh() {
mPullToRefreshView.postDelayed(new Runnable() {
#Override
public void run() {
mPullToRefreshView.setRefreshing(false);
JSONArrayRequest();
}
}, REFRESH_DELAY);
}
});
return view;
}
}
public class AdapterDashBoard extends RecyclerView.Adapter<AdapterDashBoard.ViewDashboard>{
private LayoutInflater mLayoutInflater;
private ArrayList<Blogs> listblogs=new ArrayList<>();
public AdapterDashBoard(Context context){
mLayoutInflater=LayoutInflater.from(context);
}
public void setBloglist(ArrayList<Blogs> listBlogs){
this.listblogs=listBlogs;
notifyItemRangeChanged(0,listBlogs.size());
}
#Override
public ViewDashboard onCreateViewHolder(ViewGroup parent, int viewType) {
View view= mLayoutInflater.inflate(R.layout.customizejson,parent,false);
ViewDashboard viewholder=new ViewDashboard(view);
return viewholder;
}
#Override
public void onBindViewHolder(ViewDashboard holder, int position) {
Blogs currentBlog=listblogs.get(position);
holder.questionText.setText(currentBlog.getMtext().toString());
holder.points.setText(currentBlog.getPoints().toString());
holder.id.setText(currentBlog.getId().toString());
}
#Override
public int getItemCount() {
return listblogs.size();
}
static class ViewDashboard extends RecyclerView.ViewHolder{
private ImageView thumbnail;
private TextView questionText;
private TextView points;
private TextView id;
public ViewDashboard (View itemView){
super(itemView);
//thumbnail=(ImageView)itemView.findViewById(R.id.thumbnail);
questionText=(TextView)itemView.findViewById(R.id.questionText);
points=(TextView)itemView.findViewById(R.id.points);
id=(TextView)itemView.findViewById(R.id.ID);
}
}
}
You need to clear your listblogs list before adding new items. This is why you get duplicated values.
Also you're already adding new items to listblogs in parseJSONResponse() method, so there is no need for listblogs=parseJSONResponse(response); in onResponse() method, while its the same list.
Change your onResponse() method to:
#Override
public void onResponse(JSONArray response) {
listblogs.clear(); // here you clear the old data
parseJSONResponse(response);
mAdapterDashBoard.setBloglist(listblogs);
System.out.println("it worked!!!");
}