android ListView中含有按钮事件实时更新ListView数据案例

1、布局文件Listview

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".WriteAndReadActivity">

    <android.support.constraint.Guideline
        android:id="@+id/guideline3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        app:layout_constraintGuide_percent="0.8" />

    <android.support.constraint.Guideline
        android:id="@+id/guideline5"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        app:layout_constraintGuide_percent="0.9" />

    <Button
        android:id="@+id/button5"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="8dp"
        android:layout_marginEnd="8dp"
        android:text="返回"
        app:layout_constraintBottom_toTopOf="@+id/guideline5"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="@+id/guideline5" />

    <ScrollView
        android:id="@+id/scrollView2"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:fillViewport="true"
        android:orientation="vertical"
        app:layout_constraintBottom_toTopOf="@+id/guideline3"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent">

        <LinearLayout
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:orientation="vertical">

            <ListView
                android:id="@+id/listView"
                android:layout_width="fill_parent"
                android:layout_height="fill_parent"
                android:layout_marginStart="8dp"
                android:layout_marginTop="8dp"
                android:layout_marginEnd="8dp" />
        </LinearLayout>
    </ScrollView>

</android.support.constraint.ConstraintLayout>

2、listview_item布局文件

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:padding="10dp"
    android:minHeight="100dp"
    >
    
      <TextView
        android:id="@+id/textView_list_item_id"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="1"
          android:gravity="center"
        android:text=""
         />
    <TextView
        android:id="@+id/textView_list_item_epc"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginRight="10dp"
        android:layout_weight="1"
        android:gravity="center"
        android:textSize="10sp"
        android:text=""
        />
    <TextView
        android:id="@+id/textView_list_item_sku"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:gravity="center"
        android:textSize="10sp"
        android:text=""
        />

    <TextView
        android:id="@+id/textView_list_item_filename"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:text="文件名"
        android:gravity="center"
        android:textSize="10sp"
         />

    <TextView
        android:id="@+id/textView_list_item_state"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:text="状态"
        android:gravity="center"
        android:textSize="10sp"
        />

    <Button
        android:id="@+id/textView_list_btn_read"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:text="读"
        android:layout_weight="1" />

    <Button
        android:id="@+id/textView_list_btn_write"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:text="写"
        android:layout_weight="1" />



</LinearLayout>

3、Activity

package com.example.uhftopdf;

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;

import com.example.uhftopdf.com.ReadWriteAdapter;
import com.example.uhftopdf.com.bean.CabinetInfo;
import com.example.uhftopdf.com.db.DatabaseAccess;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class WriteAndReadActivity extends AppCompatActivity {

    private static final String TAGNAME = "WriteAndReadActivity";
    private Button btn;
    private ListView lv;
    private DatabaseAccess dao;
    private ArrayList<Map<String, Object>> listMap;
    private List<CabinetInfo> cabinetInfos;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_write_and_read);

        btn = findViewById(R.id.button5);

        lv = findViewById(R.id.listView);

        dao = DatabaseAccess.getInstance(WriteAndReadActivity.this);
        cabinetInfos = dao.getAll();
        Log.e(TAGNAME,"----------11111-------epc=:"+cabinetInfos.size());
        show();

        lv.setOnItemClickListener(new ReadWriterItemClickListener());

        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(WriteAndReadActivity.this,MainActivity.class);
                startActivity(intent);
            }
        });

    }



    @Override
    protected void onDestroy() {
        super.onDestroy();
    }


    private void show() {
        ReadWriteAdapter adapter = new ReadWriteAdapter(this,cabinetInfos,R.layout.listview_item,dao);
        lv.setAdapter(adapter);
    }

    public class ReadWriterItemClickListener implements AdapterView.OnItemClickListener
    {

        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            ListView lView = (ListView)parent;
            CabinetInfo car = (CabinetInfo)lView.getItemAtPosition(position);
//            Toast.makeText(getApplicationContext(),p.getName(),0).show();
        }
    }




}

4、java bean

package com.example.uhftopdf.com.bean;

public class CabinetInfo {
    public static final String EPC = "epc";
    public static final String SKU = "sku";
    public static final String ID = "id";
    public static final String FILENAME = "filename";
    public static final String SAVEPATH = "savepath";
    public static final String STATE = "state";

    private String id;
    private String epc;
    private String sku;
    private String state;
    private String filename;
    private String savePath;

    public CabinetInfo() {
    }

    public CabinetInfo(String id,String filename,String epc, String sku,String savePath, String state ) {
        this.epc = epc;
        this.sku = sku;
        this.id = id;
        this.filename = filename;
        this.savePath = savePath;
        this.state = state;
    }

    public CabinetInfo(String epc, String sku, String state, String filename, String savePath) {
        this.epc = epc;
        this.sku = sku;
        this.filename = filename;
        this.savePath = savePath;
        this.state = state;
    }

    public String getEPC() {
        return epc;
    }

    public  String getSKU() {
        return sku;
    }

    public String getID() {
        return id;
    }

    public String getFILENAME() {
        return filename;
    }

    public  String getSavePath() {
        return savePath;
    }

    public void setSavePath(String savePath) {
        this.savePath = savePath;
    }

    public String getSTATE() {
        return state;
    }

    public String getEpc() {
        return epc;
    }

    public void setEpc(String epc) {
        this.epc = epc;
    }

    public String getSku() {
        return sku;
    }

    public void setSku(String sku) {
        this.sku = sku;
    }

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getFilename() {
        return filename;
    }

    public void setFilename(String filename) {
        this.filename = filename;
    }

    public void setState(String state) {
        this.state = state;
    }

    @Override
    public String toString() {
        return "CabinetInfo{" +
                "id=‘" + id + ‘\‘‘ +
                ", epc=‘" + epc + ‘\‘‘ +
                ", sku=‘" + sku + ‘\‘‘ +
                ", state=‘" + state + ‘\‘‘ +
                ", filename=‘" + filename + ‘\‘‘ +
                ", savePath=‘" + savePath + ‘\‘‘ +
                ‘}‘;
    }
}

5、MySqliteOpenHelper

package com.example.uhftopdf.com.db;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteDatabase.CursorFactory;

public class MySqliteOpenHelper extends SQLiteOpenHelper {
    public static final int DB_VERSION = 22;
    public static final String DB_NAME = "Store_CabinetInfo.db";
    public final static String TB_TAGINFO = "tb_taginfo";
    public final static String TB_EPC = "tb_epc";
    public MySqliteOpenHelper(Context context, String name, CursorFactory factory, int version) {
        super(context, name, factory, version);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        CREATE(db);
        CREATETableEPC(db);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    }

    public void CREATE(SQLiteDatabase db) {
        db.execSQL("CREATE  TABLE IF NOT EXISTS tb_taginfo(id integer primary key autoincrement,filename varchar(60),epc varchar(60),sku varchar(60),savepath varchar2(120),state varchar(5))");
    }

    public void CREATETableEPC(SQLiteDatabase db) {
        db.execSQL("CREATE  TABLE IF NOT EXISTS tb_epc(id integer primary key autoincrement,sku char(24),epc char(32),serNum int)");
    }
}

6、DatabaseAccess

package com.example.uhftopdf.com.db;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

import com.example.uhftopdf.com.bean.CabinetInfo;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class DatabaseAccess {
    private final List<String> TAGUID = new ArrayList<String>();
    private final List<String> SERVICEUID = new ArrayList<String>();
    private final List<String> SERVICESKU = new ArrayList<String>();
    private final StringBuffer DATA = new StringBuffer();
    private Map<String, Integer> map_sku = new HashMap();
    boolean su;
    private static MySqliteOpenHelper mSqliteOpenHelper;
    private SQLiteDatabase db;
    private static DatabaseAccess dbAccess;
    private static Context mcontext;

    public static synchronized DatabaseAccess getInstance(Context context) {
        if (dbAccess == null) {
            mcontext = context;
            dbAccess = new DatabaseAccess(context);
            mSqliteOpenHelper = new MySqliteOpenHelper(context, MySqliteOpenHelper.DB_NAME, null, MySqliteOpenHelper.DB_VERSION);
        }
        return dbAccess;
    }

    private DatabaseAccess(Context context) {
    }

    public synchronized void close() {
        if (db != null && db.isOpen()) {
            db.close();
        }
        if (mSqliteOpenHelper != null) {
            mSqliteOpenHelper.close();
        }
    }

    public void clearn() {
        map_sku.clear();
        SERVICESKU.clear();
        TAGUID.clear();
        SERVICEUID.clear();
        DATA.delete(0, DATA.length());
    }



    public synchronized long InsertInfoToDB( String epc, String sku, String state, String filename,String savePath) {
        db = mSqliteOpenHelper.getWritableDatabase();
        ContentValues values = new ContentValues();

        values.put(CabinetInfo.EPC, epc);
        values.put(CabinetInfo.SKU, sku);
        values.put(CabinetInfo.STATE, state);
        values.put(CabinetInfo.FILENAME, filename);
        values.put(CabinetInfo.SAVEPATH, savePath);
        long rows = db.insert(MySqliteOpenHelper.TB_TAGINFO, null, values);
        return rows;
    }


    public synchronized int upgradetoryInfoToDB( String epc, String state) {
        ContentValues values = new ContentValues();

        values.put(CabinetInfo.STATE, state);

        int rows = db.update(MySqliteOpenHelper.TB_TAGINFO, values, "EPC=?", new String[]{epc});
        return rows;
    }

    public String getCount(String epc) {
        String count = "";
        Cursor cursor = null;
        try {
            db = this.mSqliteOpenHelper.getWritableDatabase();

            cursor = db.rawQuery("select * from TB_TAGINFO  where  epc=?", new String[]{ epc});

            // cursor = db.query(MySqliteOpenHelper.TB_TAGINFO, new String[]{"inventoryNum", "sku"}, "inventoryNum=? and sku=?", new String[]{SetOdd_Numbers, sku}, null, null, null);
            for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()) {
                count = cursor.getString(cursor.getColumnIndex("epc"));
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (cursor != null) {
                cursor.close();
            }
        }
        return count;
    }


    public synchronized boolean AllDataIsRepeat(String epc) {
        su = false;
        Cursor cursor = null;
        try {
            db = this.mSqliteOpenHelper.getWritableDatabase();
            cursor = db.query(MySqliteOpenHelper.TB_TAGINFO, new String[]{"epc"}, "epc=?", new String[]{epc}, null, null, null);
            if (cursor != null && cursor.moveToNext()) {
                su = true;
            } else {
                su = false;
            }
        } catch (Exception e) {
            // TODO: handle exception
        } finally {
            if (cursor != null) {
                cursor.close();
            }
        }
        return su;
    }

    /**
     * 删除整个数据库
     *
     * @return
     */
    public synchronized int delAllFromTAGINFO() {
        db = mSqliteOpenHelper.getWritableDatabase();
        int num = db.delete(MySqliteOpenHelper.TB_TAGINFO, null, null);
        return num;
    }

    public synchronized int delFromTAGINFO(String epc) {
        db = mSqliteOpenHelper.getWritableDatabase();
        int num = db.delete(MySqliteOpenHelper.TB_TAGINFO, "epc=?", new String[]{epc});
        return num;
    }


    public synchronized List<CabinetInfo> getAll() {
        List<CabinetInfo> infoList = new ArrayList<>();

        db = mSqliteOpenHelper.getWritableDatabase();
        String sql = "select * from " + MySqliteOpenHelper.TB_TAGINFO ;
        Cursor cursor = db.rawQuery(sql, null);

        if (cursor != null && cursor.getCount() > 0) {
            while (cursor.moveToNext()) {
                String id = cursor.getString(0);
                String filename = cursor.getString(1);
                String epc = cursor.getString(2);
                String sku = cursor.getString(3);
                String savepath = cursor.getString(4);
                String state = cursor.getString(5);

                CabinetInfo info = new CabinetInfo(id,filename, epc, sku, savepath, state);
                infoList.add(info);
            }
        }
        if (cursor != null)
            cursor.close();
        return infoList;
    }

    public synchronized CabinetInfo getCabByEpc(String epc) {

        db = mSqliteOpenHelper.getWritableDatabase();
        String sql = "select * from " + MySqliteOpenHelper.TB_TAGINFO +" where epc=‘"+epc+"‘";
        Cursor cursor = db.rawQuery(sql, null);

        if (cursor != null && cursor.getCount() > 0) {
            while (cursor.moveToNext()) {
                String id = cursor.getString(0);
                String filename = cursor.getString(1);
                String tempEpc = cursor.getString(2);
                String sku = cursor.getString(3);
                String savepath = cursor.getString(4);
                String state = cursor.getString(5);

                CabinetInfo info = new CabinetInfo(id,filename, tempEpc, sku, savepath, state);
                return info;
            }
        }
        if (cursor != null)
            cursor.close();
        return null;
    }

    public synchronized CabinetInfo getCabBySku(String sku) {

        db = mSqliteOpenHelper.getWritableDatabase();
        String sql = "select * from " + MySqliteOpenHelper.TB_TAGINFO +" where sku=‘"+sku+"‘";
        Cursor cursor = db.rawQuery(sql, null);

        if (cursor != null && cursor.getCount() > 0) {
            while (cursor.moveToNext()) {
                String id = cursor.getString(0);
                String filename = cursor.getString(1);
                String tempEpc = cursor.getString(2);
                String strSku = cursor.getString(3);
                String savepath = cursor.getString(4);
                String state = cursor.getString(5);

                CabinetInfo info = new CabinetInfo(id,filename, tempEpc, strSku, savepath, state);
                return info;
            }
        }
        if (cursor != null)
            cursor.close();
        return null;
    }
}

7、ReadWriteAdapter

package com.example.uhftopdf.com;

import android.content.Context;
import android.graphics.Color;
import android.os.Environment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;

import com.android.hdhe.uhf.reader.UhfReader;
import com.android.hdhe.uhf.readerInterface.TagModel;
import com.example.uhftopdf.MainActivity;
import com.example.uhftopdf.R;
import com.example.uhftopdf.com.bean.CabinetInfo;
import com.example.uhftopdf.com.db.DatabaseAccess;
import com.example.uhftopdf.com.util.SoundUtil;
import com.example.uhftopdf.com.util.StringUtil;

import java.io.File;
import java.util.List;
import java.util.Map;

import cn.pda.serialport.Tools;

public class ReadWriteAdapter extends BaseAdapter {


    public static final String PWD = "00000000";
    public int membank = UhfReader.MEMBANK_EPC;
    private int addr = 2;// begin address
    private List<CabinetInfo> cabinetInfos;
    private int resource;
    private LayoutInflater inflater;
    private Context context;

    private UhfReader manager;
    private String readEpc;
    private int length = 8;
    private DatabaseAccess dao;

    public ReadWriteAdapter(Context context,List<CabinetInfo> cabinetInfos, int resource) {
        this.context = context;
        this.cabinetInfos = cabinetInfos;
        this.resource = resource;
        manager = UhfReader.getInstance();
        inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    }

    public ReadWriteAdapter(Context context,List<CabinetInfo> cabinetInfos, int resource,DatabaseAccess dao) {
        this.context = context;
        this.cabinetInfos = cabinetInfos;
        this.resource = resource;
        this.dao = dao;
        manager = UhfReader.getInstance();
        inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    }

    @Override
    public int getCount() {
        return cabinetInfos.size();
    }

    @Override
    public Object getItem(int position) {
        return cabinetInfos.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        if(convertView==null)
        {
            convertView = inflater.inflate(resource,null);
        }
        TextView idView = (TextView)convertView.findViewById(R.id.textView_list_item_id);
        TextView epcView = (TextView)convertView.findViewById(R.id.textView_list_item_epc);
        TextView filenameView = (TextView)convertView.findViewById(R.id.textView_list_item_filename);
        TextView skuView = (TextView)convertView.findViewById(R.id.textView_list_item_sku);
        TextView stateView = (TextView)convertView.findViewById(R.id.textView_list_item_state);
        Button readBtn = (Button)convertView.findViewById(R.id.textView_list_btn_read);
        Button writeBtn = (Button)convertView.findViewById(R.id.textView_list_btn_write);


        final CabinetInfo p = cabinetInfos.get(position);
        final int pos = position;
        idView.setText((position+1)+"");
        epcView.setText(p.getEPC());
        filenameView.setText(p.getFilename());
        skuView.setText(p.getSku());
        Log.d("Test", "----------------p.getSTATE()---------------"+p.getSTATE());
        if("0".equals(p.getSTATE())){
            stateView.setTextColor(Color.RED);
            stateView.setText("未写" );
        }else{
            stateView.setTextColor(Color.GREEN);
            stateView.setText( "已写");
        }

        //读操作
        readBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
//                Toast.makeText(context,"读",Toast.LENGTH_SHORT).show();
                read();
            }
        });

        //写操作
        writeBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
//                Toast.makeText(context,"写",Toast.LENGTH_SHORT).show();
                String epc = p.getEPC();
                Log.d("Test", "----------------epc---------------"+epc);
                write(p.getEPC(),pos);
            }
        });


        return convertView;
    }

    private void read(){
        byte[] accessPassword = Tools.HexString2Bytes(PWD);

        byte[] data = manager.readFrom6C(membank, addr, length, accessPassword);
        Log.e("Test","-----------------manager=:"+manager);
        Log.e("Test","----------11111-------data=:"+data);
        Log.e("Test","----------11111-------(data != null )=:"+(data != null ));
        Log.e("Test","----------11111-------(data.length > 1)=:"+( data.length > 1));
        Log.e("Test","----------11111-------(data != null && data.length > 1)=:"+(data != null && data.length > 1));
        if (data != null && data.length > 1) {
            readEpc = Tools.Bytes2HexString(data, data.length);
            Toast.makeText(context,readEpc,Toast.LENGTH_LONG).show();
        }else{
//            Toast.makeText(context,readEpc,Toast.LENGTH_LONG).show();
            Toast.makeText(context,"读取失败",Toast.LENGTH_LONG).show();
        }

    }

    private void write(String epc,int position){
        if(readEpc==null || "".equals(readEpc)){
            Toast.makeText(context,"请先扫描标签",Toast.LENGTH_LONG).show();
            return;
        }
        Log.d("Test", "----------------readEpc---------------"+readEpc);
        Log.e("Test","-----------------manager=:"+manager);
        manager.selectEPC(Tools.HexString2Bytes(readEpc));
        byte[] accessPassword = Tools.HexString2Bytes(PWD);
        if (accessPassword.length != 4) {
            Toast.makeText(context,"写入密码错误",Toast.LENGTH_LONG).show();
            return;
        }
        String writeData = epc;
        Log.d("Test", "----------------writeData---------------"+writeData);
        if (writeData.length() % 4 != 0) {
            Toast.makeText(context,"写入数据字节数错误",Toast.LENGTH_LONG).show();
            return;
        }
        byte[] dataBytes = Tools.HexString2Bytes(writeData);
        // dataLen = dataBytes/2 dataLen
        Log.d("Test", "----------------accessPassword---------------"+accessPassword);
        Log.d("Test", "----------------membank---------------"+membank);
        Log.d("Test", "----------------addr---------------"+addr);
        boolean writeFlag = manager.writeTo6C(accessPassword, membank,
                addr, dataBytes.length / 2, dataBytes);

        if (writeFlag) {

            CabinetInfo cab = cabinetInfos.get(position);
            dao.upgradetoryInfoToDB(writeData,"1");
            cab.setState("1");
            update(position, cab);
            Toast.makeText(context,"写入成功",Toast.LENGTH_LONG).show();
        } else {
            Toast.makeText(context,"写入失败",Toast.LENGTH_LONG).show();
        }
    }


    //实时更新ListView数据
    private void update(int position,CabinetInfo cabinetInfo){
        cabinetInfos.set(position,cabinetInfo);
        this.notifyDataSetChanged();
    }



}

 

android ListView中含有按钮事件实时更新ListView数据案例

上一篇:创建一个wx.App的子类


下一篇:Take advantage of Checkra1n to Jailbreak iDevice for App analysis