RealmRecyclerViewAdapter不起作用

时间:2017-08-28 11:22:26

标签: java android android-recyclerview realm recycler-adapter

我正在开发Android应用程序,并将使用Realm(这是我的第一个应用程序与Realm)。但是我的recyclerviewadapter有问题。

我得到致命的异常

E/AndroidRuntime: FATAL EXCEPTION: main
                                                 Process: com.udacity.stockhawk, PID: 9880
                                                 java.lang.RuntimeException: Unable to start activity ComponentInfo{com.udacity.stockhawk/com.udacity.stockhawk.ui.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'io.realm.RealmList com.udacity.stockhawk.data.Parent.getStockList()' on a null object reference
                                                     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2521)
                                                     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2595)
                                                     at android.app.ActivityThread.access$800(ActivityThread.java:178)
                                                     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1470)
                                                     at android.os.Handler.dispatchMessage(Handler.java:111)
                                                     at android.os.Looper.loop(Looper.java:194)
                                                     at android.app.ActivityThread.main(ActivityThread.java:5631)
                                                     at java.lang.reflect.Method.invoke(Native Method)
                                                     at java.lang.reflect.Method.invoke(Method.java:372)
                                                     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:959)
                                                     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:754)
                                                  Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'io.realm.RealmList com.udacity.stockhawk.data.Parent.getStockList()' on a null object reference
                                                     at com.udacity.stockhawk.ui.MainActivity.onCreate(MainActivity.java:66)
                                                     at android.app.Activity.performCreate(Activity.java:6092)
                                                     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1112)
                                                     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2468)
                                                     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2595) 
                                                     at android.app.ActivityThread.access$800(ActivityThread.java:178) 
                                                     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1470) 
                                                     at android.os.Handler.dispatchMessage(Handler.java:111) 
                                                     at android.os.Looper.loop(Looper.java:194) 
                                                     at android.app.ActivityThread.main(ActivityThread.java:5631) 
                                                     at java.lang.reflect.Method.invoke(Native Method) 
                                                     at java.lang.reflect.Method.invoke(Method.java:372) 
                                                     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:959) 
                                                     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:754) 

我的适配器是:

class StockAdapter extends RealmRecyclerViewAdapter<Stock, StockAdapter.StockViewHolder> {
    private final Context context;
    private final DecimalFormat dollarFormatWithPlus;
    private final DecimalFormat dollarFormat;
    private final DecimalFormat percentageFormat;
    private final StockAdapterOnClickHandler clickHandler;

    StockAdapter(Context context, StockAdapterOnClickHandler clickHandler,
                 OrderedRealmCollection<Stock> data) {
        super(context, data, true);
        this.context = context;
        this.clickHandler = clickHandler;

        dollarFormat = (DecimalFormat) NumberFormat.getCurrencyInstance(Locale.US);
        dollarFormatWithPlus = (DecimalFormat) NumberFormat.getCurrencyInstance(Locale.US);
        dollarFormatWithPlus.setPositivePrefix("+$");
        percentageFormat = (DecimalFormat) NumberFormat.getPercentInstance(Locale.getDefault());
        percentageFormat.setMaximumFractionDigits(2);
        percentageFormat.setMinimumFractionDigits(2);
        percentageFormat.setPositivePrefix("+");
    }

    @Override
    public StockViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {

        View item = LayoutInflater.from(context).inflate(R.layout.list_item_quote, parent, false);

        return new StockViewHolder(item);
    }

    @Override
    public void onBindViewHolder(StockViewHolder holder, int position) {
        final Stock stock = getItem(position);

        holder.symbol.setText(stock.getDataset_code());
        double currentPrice = stock.getQuoteHistory().first().getValue();
        double oldPrice = stock.getQuoteHistory().get(1).getValue();
        holder.price.setText(dollarFormat.format(currentPrice));
        double rawAbsoluteChange = currentPrice - oldPrice;
        double percentageChange = (rawAbsoluteChange/oldPrice) * 100.0;

        if (rawAbsoluteChange > 0) {
            holder.change.setBackgroundResource(R.drawable.percent_change_pill_green);
        } else {
            holder.change.setBackgroundResource(R.drawable.percent_change_pill_red);
        }

        String change = dollarFormatWithPlus.format(rawAbsoluteChange);
        String percentage = percentageFormat.format(percentageChange / 100);

        if (Utils.getDisplayMode(context)
                .equals(context.getString(R.string.pref_display_mode_absolute_key))) {
            holder.change.setText(change);
        } else {
            holder.change.setText(percentage);
        }


    }

    interface StockAdapterOnClickHandler {
        void onClick(String symbol);
    }

    class StockViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {

        @BindView(R.id.symbol)
        TextView symbol;

        @BindView(R.id.price)
        TextView price;

        @BindView(R.id.change)
        TextView change;

        StockViewHolder(View itemView) {
            super(itemView);
            ButterKnife.bind(this, itemView);
            itemView.setOnClickListener(this);
        }

        @Override
        public void onClick(View v) {
            int adapterPosition = getAdapterPosition();
            clickHandler.onClick(getItem(adapterPosition).getDataset_code());
        }
    }
}

我对创建代码的活动是:

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);
        ButterKnife.bind(this);
        realm = Realm.getDefaultInstance();
        adapter = new StockAdapter(this, this, realm.where(Parent.class).findFirst().getStockList());
        stockRecyclerView.setAdapter(adapter);
        stockRecyclerView.setLayoutManager(new LinearLayoutManager(this));

        swipeRefreshLayout.setOnRefreshListener(this);
        swipeRefreshLayout.setRefreshing(true);
        onRefresh();

        QuoteSyncJob.initialize(this);

        new ItemTouchHelper(new ItemTouchHelper.SimpleCallback(0, ItemTouchHelper.RIGHT) {
            @Override
            public boolean onMove(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, RecyclerView.ViewHolder target) {
                return false;
            }

            @Override
            public void onSwiped(RecyclerView.ViewHolder viewHolder, int direction) {
                String symbol = adapter.getItem(viewHolder.getAdapterPosition()).getDataset_code();
                Utils.removeStock(realm, symbol);
            }

        }).attachToRecyclerView(stockRecyclerView);
    }

我需要做些什么来解决这个问题? 项目中的其他课程正在运作。 我使用此https://github.com/realm/realm-android-adapters作为示例

P.S。:这是关于Udacity Nanodegree的项目3。

1 个答案:

答案 0 :(得分:0)

您是否对您的Realm对象进行了任何更改?如果您添加,删除或修改了任何内容(例如归档类型或名称),则必须清除整个数据库并再次创建所有对象。

您可以使用以下方式执行此操作:

Realm.deleteAll()