在向sqLite

时间:2017-07-14 08:10:20

标签: java android sqlite android-recyclerview android-sqlite

每次SQLite获取新数据时,我都会尝试使用recyclerview刷新活动(实际上SQLite从TCP客户端信号中获取数据) 这是我的RecyclerView代码:

public static class ViewHolder extends RecyclerView.ViewHolder{
    public TextView data_txt;
    public TextView text_txt;
    public TextView ora_txt;
    public ImageView img;

    public ViewHolder(final View itemView) {
        super(itemView);

        data_txt = itemView.findViewById(R.id.Data);
        ora_txt = itemView.findViewById(R.id.Ora);
        text_txt = itemView.findViewById(R.id.Errore);
        img = itemView.findViewById(R.id.error_photo);
    }

}
private List<Adapter> mText;

public RecyclerViewAdapter(Context c,List<Adapter> testo) {
    this.c = c;
    mText = testo;

}


@Override
public RecyclerViewAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    View contactView = LayoutInflater.from(parent.getContext()).inflate(R.layout.recycler_blueprint, parent, false);
    return new ViewHolder(contactView);
}

@Override
public void onBindViewHolder(RecyclerViewAdapter.ViewHolder viewHolder, int position) {
    Adapter adapter = mText.get(position);

    TextView mData = viewHolder.data_txt;
    mData.setText(adapter.getDataText());

    TextView mOra = viewHolder.ora_txt;
    mOra.setText(adapter.getOraText());

    TextView mTesto = viewHolder.text_txt;
    mTesto.setText(adapter.getTesto());

    ImageView mImg = viewHolder.img;
    mImg.setImageBitmap(adapter.getImage());
}

@Override
public int getItemCount() {
    return mText.size();
}

public void removeItem(int position) {

    Adapter a = mText.get(position);
    int id=a.getId();

     DataBaseHandler myDB;
     myDB = DataBaseHandler.getInstance(c);
    myDB.openDB();
    if(myDB.delete(id))
    {
        mText.remove(position);
    }else
    {
        Toast.makeText(c,"Unable To Delete", Toast.LENGTH_SHORT).show();
    }
    myDB.closeDB();
    this.notifyDataSetChanged();
}

当我尝试使用RecyclerViewAdapter.notifyDataSetChanged();更新RecyclerView时TCP服务器获取因错误而崩溃的数据:

java.lang.NullPointerException: Attempt to invoke virtual method 'void com.example.sguidetti.selfmanegment.RecyclerViewAdapter.notifyDataSetChanged()' on a null object reference

编辑: 这是我在TCP服务器类中调用notifyDataSetChande()的代码:

    Vibrator vibrator;
    String date,ora;
    long[] pattern = {0, 1000, 500, 1000, 500, 1000};

    int lun;

    @Override
    public void run() {
        InputStream leggi;
        try {


            serverSocket = new ServerSocket(socketServerPORT);

            while (true) {
                myDB = DataBaseHandler.getInstance(activity);

                Socket socket = serverSocket.accept();
                leggi = socket.getInputStream();
                byte[] data = new byte[1000];
                lun = leggi.read(data, 0, data.length);
                letto = new String(data, "UTF-8");
                count++;
                MediaPlayer mPlay = MediaPlayer.create(activity, R.raw.gabsuono);
                mPlay.start();

                vibrator = (Vibrator) activity.getSystemService(VIBRATOR_SERVICE);
                vibrator.vibrate(pattern, -1);

                date = new SimpleDateFormat("dd-MM-yyyy").format(new Date());
                ora = new SimpleDateFormat("HH:mm:ss").format(new Date());



                myDB.insertDataServer(date, ora, letto);

                adapterView.notifyDataSetChanged();

                activity.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        prefs = activity.getSharedPreferences("MY_DATA", MODE_PRIVATE);
                        SharedPreferences.Editor edit = prefs.edit();
                        edit.putInt("counter", count);
                        edit.commit();
                        activity.msg.setText(String.valueOf(count));
                        activity.msg.setVisibility(View.VISIBLE);

                    }
                });
                leggi.close();


            }
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();

        }

这是我调用RecyclerView的活动:

DataBaseHandler myDB;
RecyclerView recyclerView;
RecyclerViewAdapter adapterView;
ImageButton home;
String IMGSTRING;
Adapter adapter;
List<Adapter> textList;
private Paint p = new Paint();


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_allert);
    Utils.darkenStatusBar(this, R.color.colorAccent);
    myDB = DataBaseHandler.getInstance(this);
    home = (ImageButton) findViewById(R.id.casa);
    recyclerView = (RecyclerView) findViewById(R.id.recyclerview);
    Bitmap img;
    img = BitmapFactory.decodeResource(getResources(), R.drawable.allert);
    Cursor data = myDB.fetchDataServer();
    textList = new ArrayList<>();
    int cont = 0;
    if (data.getCount() != 0) {
        while (data.moveToNext()) {


            IMGSTRING = data.getString(3).substring(0, 3);


            switch (IMGSTRING) {
                case "X00":
                    img = BitmapFactory.decodeResource(getResources(), R.drawable.allert);
                    break;
                case "E01":
                    img = BitmapFactory.decodeResource(getResources(), R.drawable.e01);
                    break;
                case "E02":
                    img = BitmapFactory.decodeResource(getResources(), R.drawable.e02);
                    break;
                case "E03":
                    img = BitmapFactory.decodeResource(getResources(), R.drawable.e03);
                    break;
                case "E90":
                    img = BitmapFactory.decodeResource(getResources(), R.drawable.e90);
                    break;
                case "E04":
                    img = BitmapFactory.decodeResource(getResources(), R.drawable.e04);
                    break;
                case "E05":
                    img = BitmapFactory.decodeResource(getResources(), R.drawable.e04);
                    break;
                case "E06":
                    img = BitmapFactory.decodeResource(getResources(), R.drawable.e04);
                    break;
            }


            adapter = new Adapter(data.getInt(0), data.getString(1), data.getString(2), data.getString(3).substring(3), img);   // 1 = time 2 = data 3 = text


            textList.add(cont, adapter);
            cont++;

        }
        RecyclerViewAdapter recycler = new RecyclerViewAdapter(this, textList);
        recyclerView.setAdapter(recycler);
        recyclerView.setLayoutManager((new LinearLayoutManager(this)));
    } else {
        Toast.makeText(allert.this, "NESSUN MESSAGGIO DA VISUALIZZARE!", Toast.LENGTH_LONG).show();
    }
    adapterView = new RecyclerViewAdapter(this, textList);
    recyclerView.setAdapter(adapterView);
    adapterView.notifyDataSetChanged();
    initSwipe();
    home.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            finish();
        }
    });
}

private void initSwipe() {
    ItemTouchHelper.SimpleCallback simpleItemTouchCallback = new ItemTouchHelper.SimpleCallback(0, ItemTouchHelper.LEFT) {

        @Override
        public boolean onMove(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, RecyclerView.ViewHolder target) {
            return false;
        }

        @Override
        public void onSwiped(RecyclerView.ViewHolder viewHolder, int direction) {
            int position = viewHolder.getAdapterPosition();
            adapterView.removeItem(position);


        }

        @Override
        public void onChildDraw(Canvas c, RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, float dX, float dY, int actionState, boolean isCurrentlyActive) {

            Bitmap icon;
            if (actionState == ItemTouchHelper.ACTION_STATE_SWIPE) {

                View itemView = viewHolder.itemView;
                float height = (float) itemView.getBottom() - (float) itemView.getTop();
                float width = height / 3;

                p.setColor(Color.parseColor("#D32F2F"));
                RectF background = new RectF((float) itemView.getRight() + dX, (float) itemView.getTop(), (float) itemView.getRight(), (float) itemView.getBottom() - 10);
                c.drawRect(background, p);
                icon = BitmapFactory.decodeResource(getResources(), R.drawable.ic_delete_white);
                RectF icon_dest = new RectF((float) itemView.getRight() - 2 * width, (float) itemView.getTop() + width, (float) itemView.getRight() - width, (float) itemView.getBottom() - width);
                c.drawBitmap(icon, null, icon_dest, p);

            }
            super.onChildDraw(c, recyclerView, viewHolder, dX, dY, actionState, isCurrentlyActive);
        }
    };
    ItemTouchHelper itemTouchHelper = new ItemTouchHelper(simpleItemTouchCallback);
    itemTouchHelper.attachToRecyclerView(recyclerView);
}

2 个答案:

答案 0 :(得分:0)

你可以在这里进行空检查吗?

@Override
public int getItemCount() {
    return mText != null ? mText.size() : 0;
}

我最好猜测的原因是当mText仍然为null时调用notifyDataSetChanged()。当调用notifyDataSetChanged()时,将首先调用getItemCount()以检查列表中的当前位置是否在“mText”列表的大小范围内,但是当mText为null时它将崩溃。

你可以在removeItem()方法上改进两件事:

  1. 不要调用this.notifyDataSetChanged(),而是调用this.notifyItemRemoved(position),因为onBindViewHolder()不会被调用n次(n = RecyclerView中当前可见的行数)
  2. 请勿将数据库代码与UI代码混合使用。您的RecyclerView.Adapter类应该只关注UI逻辑和UI状态对象(在本例中为mText)。换句话说,

    public void removeItem(int position) {
        mText.remove(position);
        this.notifyItemRemoved(position);
    }
    
  3. 在MainActivity类中,除了数据库代码外,还要调用removeItem()。

答案 1 :(得分:0)

您需要确保在调用notifyDataSetChanged()方法之前初始化适配器。另一种方法是在适配器类中添加一个方法,您可以在其中传递ArrayList并调用notifyDataSetChanged();