如何将QR码扫描结果保存在列表视图中?

时间:2019-09-02 09:30:26

标签: java android listview qr-code

在条形码部分,我读取了条形码。我想将扫描结果保存到我创建的列表视图中。我试图通过查看许多项目来做到这一点,但失败了。你能帮助我吗?很抱歉,问题已经解决了一段时间。

public class BarcodeReaderFragment extends Fragment {

barcodeDetector.setProcessor(new Detector.Processor<Barcode>() {
    @Override
    public void release() {

    }

    @Override
    public void receiveDetections(Detector.Detections<Barcode> detections) {
        final SparseArray<Barcode> qrcode = detections.getDetectedItems();
        if (qrcode.size() != 0) {
            Intent my = new Intent(getActivity(),ResultActivity.class);
            my.putExtra("type", qrcode.valueAt(0));

            currentTime = Calendar.getInstance().getTime();
            df = new SimpleDateFormat("dd-MMM-yyyy");
            String formattedDate = df.format(currentTime);
            String d = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(Calendar.getInstance().getTime());
            System.out.println(formattedDate);

            //Add QR scan result to listview???
            //Add current time and date to listview???

            Gson gson = new Gson();
            String json = gson.toJson(qrcode.valueAt(0));
            SharedPreferences sp = getActivity().getSharedPreferences("list",Context.MODE_PRIVATE);
            addhistory(sp,json);
            startActivity(my);
            getActivity().finish();
            barcodeDetector.release();
        }
    }
});

public void addhistory(SharedPreferences sp,String json){
    int x = sp.getInt("index",0);
    SharedPreferences.Editor editor = sp.edit();
    editor.putString(String.valueOf(x),json);
    int  y;
    y = x+1;
    editor.putInt("index",y);
    editor.commit();

}

Item_Model

public class Item_Model implements Serializable {

    private String result, date_time;

    public Item_Model(String result, String date_time) {
        this.result = result;
        this.date_time = date_time;
    }

    public String getResult() {
        return result;
    }

    public String getDate_time() {
        return date_time;
    }

ListView_Adapter

public class ListView_Adapter extends BaseAdapter {

    private Context context;
    private ArrayList<Item_Model> item_modelArrayList;
    private SparseBooleanArray mSelectedItemsIds;

    public ListView_Adapter(Context context, ArrayList<Item_Model> item_modelArrayList) {
        this.context = context;
        this.item_modelArrayList = item_modelArrayList;
        mSelectedItemsIds = new SparseBooleanArray();
    }

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

    @Override
        public Item_Model getItem(int position) {
        return item_modelArrayList.get(position);
    }

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

    @Override
        public View getView(int position, View convertView, ViewGroup parent) {
        LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        ViewHolder holder;
        if (convertView == null) {
            convertView = inflater.inflate(R.layout.item_row, parent, false);
            holder = new ViewHolder();
            holder.Result = (TextView) convertView.findViewById(R.id.result);
            holder.Date_time = (TextView) convertView.findViewById(R.id.date_time);

            convertView.setTag(holder);
        } else
            holder = (ViewHolder) convertView.getTag();

        holder.Result.setText(item_modelArrayList.get(position).getResult());
    holder.Date_time.setText(item_modelArrayList.get(position).getDate_time());


        /** Change background color of the selected items in list view  **/
        convertView
            .setBackgroundColor(mSelectedItemsIds.get(position) ? 0x48FF9800
                    : Color.TRANSPARENT);

        return convertView;
    }

    private class ViewHolder {
        TextView Result, Date_time;
    }

ThreeFragment 在这一集中,我正在观看Listview。

private ActionMode mActionMode;

private static View view;
private static ListView_Adapter adapter;
private static ListView listView;
//Action Mode for toolbar

private static ArrayList<Item_Model> item_models;

public ThreeFragment() {
}

@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    view = inflater.inflate(R.layout.fragment_three, container, false);
    populateListView();
    implementListViewClickListeners();




    return view;
}





//I don't know how to fill this section with detector results?
//Populate ListView with dummy data
private void populateListView() {
    listView = (ListView) view.findViewById(R.id.list_view);
    item_models = new ArrayList<>();
    for (int i = 1; i <= 40; i++)
        item_models.add(new Item_Model("Result " + i, "Date-Time " + i));


    adapter = new ListView_Adapter(getActivity(), item_models);
    listView.setAdapter(adapter);
    adapter.notifyDataSetChanged();

}


//Implement item click and long click over listview
private void implementListViewClickListeners() {
    listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            //If ActionMode not null select item
            if (mActionMode != null)
                onListItemSelect(position);
        }
    });
    listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
        @Override
        public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
            //Select item on long click
            onListItemSelect(position);
            return true;
        }
    });
}

//List item select method
private void onListItemSelect(int position) {
    adapter.toggleSelection(position);//Toggle the selection

    boolean hasCheckedItems = adapter.getSelectedCount() > 0;//Check if any items are already selected or not

    if (hasCheckedItems && mActionMode == null)
        // there are some selected items, start the actionMode
        mActionMode = ((AppCompatActivity) getActivity()).startSupportActionMode(new Toolbar_ActionMode_Callback(getActivity(),adapter, item_models, true));
    else if (!hasCheckedItems && mActionMode != null)
        // there no selected items, finish the actionMode
        mActionMode.finish();

    if (mActionMode != null)
        //set action mode title on item selection
        mActionMode.setTitle(String.valueOf(adapter
                .getSelectedCount()) + " selected");


}

//Set action mode null after use
public void setNullToActionMode() {
    if (mActionMode != null)
        mActionMode = null;
}


//Delete selected rows
public void deleteRows() {
    SparseBooleanArray selected = adapter
            .getSelectedIds();//Get selected ids

    //Loop all selected ids
    for (int i = (selected.size() - 1); i >= 0; i--) {
        if (selected.valueAt(i)) {
            //If current id is selected remove the item via key
            item_models.remove(selected.keyAt(i));
            adapter.notifyDataSetChanged();//notify adapter

        }
    }
    Toast.makeText(getActivity(), selected.size() + " item deleted.", Toast.LENGTH_SHORT).show();//Show Toast
    mActionMode.finish();//Finish action mode after use

}

1 个答案:

答案 0 :(得分:0)

尝试执行以下步骤:

  1. 保持ResultActivity为登陆/父级活动。
  2. ThreeFragment添加到ResultActivity
  3. 创建一个BarcodeReaderActivity并在此活动中直接使用BarcodeDetector(为简单起见,删除BarcodeReaderFragment
  4. BarcodeReaderActivity的{​​{1}}开始startActivityForResult(),开始您喜欢的互动。
  5. 当您从ThreeFragment获取结果时,请使用BarcodeDetectorBarcodeReaderActivity活动将结果设置为setResult("xxxxxx")
  6. finish()中,您将在ThreeFragment中得到结果
  7. 获取结果后,将其放入onActivityResult()并将列表发送到listAdapter

更新

很抱歉,我无法更改整个项目的导航,这对我来说将花费太多时间。您应该在这里问一个确切的问题。我刚刚检查了您的项目,并提供了一些反馈。您必须自己为此编写代码。

  1. 使用数据库获取数据列表(QR扫描结果)
  2. 对于notifyDataSetChanged(),您可以通过以下代码找到片段的ViewPager
visibility/invisibility

建议:尝试逐步实施,如果出现任何问题,请先解决特定问题。