How to make a Dynamic Listview generated with Barcodescan data?

Asked

Viewed 709 times

0

I’m a beginner in Java/Android, and I want to make a listview is created from the "Scans" made using Zxing.

In case I have the screen with the button to scan and in it is displayed the answer of the scan, I want to put the answers of more than one scan in a listview as a stack, one on top of the other, how do this?

This is Mainactivity (Zxing example pattern).

public class MainActivity extends Activity {
    public static final int REQUEST_CODE = 0;
    private TextView txResult;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        txResult = (TextView) findViewById(R.id.txResult);


    }

    public void callZXing(View view){
        Intent it = new Intent(MainActivity.this, com.google.zxing.client.android.CaptureActivity.class);
        startActivityForResult(it, REQUEST_CODE);
    }


    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data){
        if(REQUEST_CODE == requestCode && RESULT_OK == resultCode){
            txResult.setText("RESULTADO: "+data.getStringExtra("SCAN_RESULT")+" ("+data.getStringExtra("SCAN_FORMAT")+")");
        }
    }
}

Thank you to all who can help.

  • Someone could show you the way to do it?

  • so I didn’t understand the part of R.layout.my_text_view,this Textview you put inside another xml file?

1 answer

1


I will recommend using Recyclerview instead of Listview because Recyclerview supports everything that a Listview does more efficiently.

I would also like to recommend reading below so you can understand the code: http://developer.android.com/intl/pt-br/training/material/lists-cards.html

First, you need to import the lib from Recyclerview, go to your build.Radle:

dependencies
    {
        ...
        compile 'com.android.support:recyclerview-v7:23.1.1'
    }

In your activity_main.xml you will need to add a Recyclerview:

...
<!-- A RecyclerView with some commonly used attributes -->
<android.support.v7.widget.RecyclerView
android:id="@+id/my_recycler_view"
android:scrollbars="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
...

In your Mainactivity.java you will need to start Recyclerview and your Adapter:

public class MainActivity extends Activity {
private RecyclerView mRecyclerView;
private RecyclerView.Adapter mAdapter;
private RecyclerView.LayoutManager mLayoutManager;

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

    ...
    mRecyclerView = (RecyclerView) findViewById(R.id.my_recycler_view);

    // use this setting to improve performance if you know that changes
    // in content do not change the layout size of the RecyclerView
    mRecyclerView.setHasFixedSize(true);

    // use a linear layout manager
    mLayoutManager = new LinearLayoutManager(this);
    mRecyclerView.setLayoutManager(mLayoutManager);

    // specify an adapter (see also next example)
    List<String> mData = new ArrayList<String>();
    mAdapter = new MyAdapter( mData );
    mRecyclerView.setAdapter( mAdapter );
    ...
}
...
}

Your Adapter will need to have a function to add new obtained data, in case the public void addData( String newData ):

public class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder> {
private List<String> mDataset;

// Provide a reference to the views for each data item
// Complex data items may need more than one view per item, and
// you provide access to all the views for a data item in a view holder
public static class ViewHolder extends RecyclerView.ViewHolder {
    // each data item is just a string in this case
    public TextView mTextView;
    public ViewHolder(TextView v) {
        super(v);
        mTextView = v;
    }
}

// Provide a suitable constructor (depends on the kind of dataset)
public MyAdapter(List<String> myDataset) {
    mDataset = myDataset;
}

// Create new views (invoked by the layout manager)
@Override
public MyAdapter.ViewHolder onCreateViewHolder(ViewGroup parent,
                                               int viewType) {
    // create a new view
    View v = LayoutInflater.from(parent.getContext())
                           .inflate(R.layout.my_text_view, parent, false);
    // set the view's size, margins, paddings and layout parameters
    ...
    ViewHolder vh = new ViewHolder((TextView)v);
    return vh;
}

// Replace the contents of a view (invoked by the layout manager)
@Override
public void onBindViewHolder(ViewHolder holder, int position) {
    // - get element from your dataset at this position
    // - replace the contents of the view with that element
    holder.mTextView.setText( mDataset.get( position) );

}

// Return the size of your dataset (invoked by the layout manager)
@Override
public int getItemCount() {
    return mDataset.size();
}

public void addData( String newData ){
    mDataset.add( newData );
}

}

Remember to create the layout of your list items, inside the res/layouts folder create a file called my_text_view with only one Textview with the desired layout.

Recyclerview and its Adapter are now correctly configured and you should pass the new scans obtained to Adapter and warn that a new element has been inserted. To send the scanned value you will use the function we created in Adapter, and to warn that a new element has been inserted just call the notifyDataSetChanged( ) function of Adapter. Soon, your onActivityResult would look like this:

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data){
    if(REQUEST_CODE == requestCode && RESULT_OK == resultCode){
        mAdapter.addData("RESULTADO: "+data.getStringExtra("SCAN_RESULT")+" ("+data.getStringExtra("SCAN_FORMAT")+")");
        mAdapter.notifyDataSetChanged( );
    }
}
  • Excellent explanation Matheus, thank you for your attention. However, after inserting everything as you quoted, in this part: @Override public Myadapter.Viewholder onCreateViewHolder (Viewgroup Parent, int viewType){ View v = Layoutinflater.from(Parent.getcontext()). inflate(R.layout.my_text_view,parent, false);&#xA;&#xA; ViewHolder vh = new ViewHolder(v);&#xA; return vh;&#xA;&#xA; }&#xA;&#xA;O "v" entre (), fica destacado com a seguinte mensagem: &#xA;&#xA;ViewHolder (android.widget.TextView) in ViewHolder cannot be applied to (android.view.View) , what could it be? Thanks in advance.

  • To solve this you need to cast View v: Viewholder vh = new Viewholder( (Textview) v);

  • It worked, now there’s another detail I forgot to mention above. &#xA;&#xA;No meu onActivityResult, o addData não está sendo reconhecido: &#xA;&#xA;mAdapter.addData("RESULTADO: "+data.getStringExtra("SCAN_RESULT")+" ("+data.getStringExtra("SCAN_FORMAT")+")"); &#xA;&#xA;E ele está no MyAdapter:&#xA; public void addData(String newData){ mDataset.add( newData ); } What could also be?

  • This happened to be a Recyclerview.Adapter object in Private recyclerview.Adapter mAdapter;. Change this to private Myadapter mAdapter;. As its class Myadapter extende Recyclerview.Adapter it has all its methods, but the inverse is not valid, the function addData is a function of Myadapter.

  • Thank you, I did as you explained. I compiled it, now the home screen continues the way it was, I scan it and it keeps showing only that scanned item, when I scan another one it takes the place of the first one, it’s not setting up the list, could help me again?

  • Well, I took a look at the code and was unable to identify the error. What I suggest is to put some breakpoints in getItemCount( ) and onBindViewHolder( ) to see if your mData has the correct data, getItemCount returns the number of elements in mData and onBindViewHolder is called once for each mData element. If everything is correct I would need to look at your code and I think it’s best to create another question or look for a previously asked question in stackoverflow or some tutorial in Google that can point you to the error.

Show 1 more comment

Browser other questions tagged

You are not signed in. Login or sign up in order to post.