BaseAdapter中的超级方法无法在RealmBaseAdapter中初始化

时间:2017-08-17 07:47:40

标签: android realm adapter delete-row

我正在使用Realm数据库从Mobile中的JSON保存数据。我正在使用自定义适配器而不是RealmAdapter。我能够保存数据并从Realm数据库中检索数据但是当我删除项目时按位置我收到一个错误,表示对象不再有效。

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());
            }
        });


    }

收藏夹

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();
    }
}

登录

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)
  

如何解决这个问题?

1 个答案:

答案 0 :(得分:0)

如果删除任何线程上的给定RealmObject,那么当Realm更新(并调用RealmChangeListeners)时,该对象将不再有效,并且将不再可用于以前具有的任何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;

但是,无论出于何种原因,您都将RealmResults的内容复制到ArrayList

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;

这是超级糟糕的,因为不仅结果集不再更新,而且它还能够存储和保留无效对象。

因此,

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();
}

并且应该是

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);
       ...

     ...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);

OR

array[i].onclick

编辑:同样,完全删除评论代码

function setContentBox() {
  for (var i = 0; i < jArrayText.length; i++)
    document.getElementById(textWord[i]).onclick = function() {
      var x = document.getElementById(textWord[i] + "commentB");
      if (x.style.display === 'none') {
        x.style.display = 'block';
      } else {
        x.style.display = 'none';
      }
    };
}

$(document).ready(function(){
  setContentBox();
});