whoami whoami - 6 months ago 18
Android Question

Seperating text in one TextView by a line in Android

I have a

TextView
that will display all the stuff from database. Since I don't know how to generate number of
TextView
s according to Database, I wonder if there is any way to set a visible line after one item String. Example,

List of items
book1 love yourself
total of 3
book2 love you
total of 2


As you can see, if I display it all in one
TextView
, its hard to determine the separate books, so I am wondering if there is anything i can do to separate them.

Answer

If you put books name from database in a ArrayList like this

public ArrayList<String> getAllBooks(){
    ArrayList<String> alArrayList  = new ArrayList<String>();
    Database db = getWritableDatabase();
    Cursor cursor = db.query("BOOKS", null, null, null, null, null, null );
    if (cursor!=null && cursor.moveToFirst()) {
        do{

        String book = cursor.getString(cursor.getColumnIndex("book_name"));
        alArrayList.add(book);

        }while(cursor.moveToNext());
        db.close();
    }

    return alArrayList;
}

Then you can use this ArrayList to create you desire output

    public void setBooks(){
        ArrayList<String> bookNames = new YourDatabseName(this, version).getAllBooks(); 

        LinearLayout layout = (LinearLayout) findViewById(R.id.bookslayout);      
        LayoutParams textViewLayoutParams = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);

        TextView heading = new TextView(this);
        heading.setText("List of items");
        heading.setLayoutParams(textViewLayoutParams);
        layout.addView(textView);

        if(bookNames.size()>0){
            for(int i = 0; i<=bookNames.size();i++){

                TextView book= new TextView(this);
                book.setText("Book "+ (i+1) +" "+bookNames.get(i).toString());
                book.setLayoutParams(textViewLayoutParams);
                layout.addView(textView);

            }
        }

        TextView footer= new TextView(this);
        footer.setText("Total of "+bookNames.size());
        footer.setLayoutParams(textViewLayoutParams);
        layout.addView(textView);
    }

Now your need a LinearLayout inside your activitys layout like this

<LinearLayout
android:id="@+id/bookslayout"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
</LinearLayout>