问题
Kinda new to Java programming, And I am trying to create a native app for android. my problem is, that when I select some stuff from my SQLite DB - I want to add a button with an eventlistener next to the output.
if(view==btnViewAll)
{
Cursor c=db.rawQuery("SELECT * FROM catalogue", null);
if(c.getCount()==0)
{
showMessage("Error", "No records found");
return;
}
StringBuffer buffer=new StringBuffer();
while(c.moveToNext())
{
buffer.append("Product name: "+c.getString(1)+"\n");
buffer.append("Description: "+c.getString(2)+"\n");
buffer.append("Price: "+c.getString(3)+"\n");
buffer.append("Image: "+c.getString(4)+"\n\n");
}
showMessage("All Products", buffer.toString());
}//end of btnViewAll
and then my ShowMessage is this -
public void showMessage(String title, String message) {
Builder builder = new Builder(this);
builder.setCancelable(true);
builder.setTitle(title);
builder.setMessage(message);
builder.show();
}//end of Message!
This all pops up on my phone, with a list of the records in my DB - but I can't figure out, how to add a button for each row in there.
help is appreciated!
回答1:
Refering to your recent comment, what you need instead of displaying the full String is to create a custom list and populate it via your DB. Here are the steps required :
1) Create an Object User, with name/phone number
2) When parsing your DB, return a list
3) Create a CustomAdapter extending ArrayAdapter
4) Change your xml so that there's only a listView
5) In your activity, call an AsyncTask to fetch your DB (as you probably already do), then use the List to populate the ListView through the Adapter.
Further tips : create a layout row.xml
that'll be inflated in your Adapter, where you'll have the Widgets needed to display informations about your user (ie name/phone n°) + a button. And in the getView of the adapter, inflate your row.xml
, update the values with the data, and set the behaviour for the button there.
Here's a great tutorial where you'll find everything in details : http://www.vogella.com/tutorials/AndroidListView/article.html
Good luck with it !
来源:https://stackoverflow.com/questions/26891575/how-to-add-a-button-next-to-a-message-in-java-builder