2013-05-06 8 views
0

Я создал базу данных, и ее содержимое показано в таблице таблицы. При вставке в базу данных данные показаны в таблице. До этого он работает отлично. Но проблема в том, что , когда я нажимаю на строку, ее содержимое не отображается в тосте (скорее, если я хочу показать на другой странице). Только последняя строка получает щелчок, кроме того, столбец, индекс установлен последним. заранее спасибо.Показать данные всей строки таблицы из базы данных

это моя страница XML

<?xml version="1.0" encoding="utf-8"?> 

    <TableLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent" 
    android:background="@drawable/gradientb" 
    android:id="@+id/tableLayout1" 
    android:shrinkColumns="*" 
    android:stretchColumns="*" > 


<ImageView 
    android:id="@+id/imageView1" 
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:scaleType="fitXY" 
    android:src="@drawable/deliverylistbar" /> 

<TableRow 
    android:id="@+id/tableRow1" 
    android:layout_width="match_parent" 
    android:layout_height="wrap_content" 
    android:gravity="center_horizontal" > 
</TableRow> 

<TableRow 
    android:id="@+id/tableRow2" 
    android:layout_width="match_parent" 
    android:layout_height="wrap_content" > 
<TextView 
     android:id="@+id/TextView0" 
     android:gravity="center|left" 
     android:text="Id" 
     android:textColor="@android:color/black" 
     android:textSize="20dp" 
     android:textStyle="bold" 
     android:typeface="serif" > 

    </TextView> 
    <TextView 
     android:id="@+id/TextView1" 
     android:gravity="center|left" 
     android:text="Items" 
     android:textColor="@android:color/black" 
     android:textSize="20dp" 
     android:textStyle="bold" 
     android:typeface="serif" > 

    </TextView> 

    <TextView 
     android:id="@+id/TextView2" 
     android:gravity="center|left" 
     android:text="Location" 
     android:textColor="@android:color/black" 
     android:textSize="18dp" 
     android:textStyle="bold" 
     android:typeface="serif" > 

    </TextView> 

    <TextView 
     android:id="@+id/TextView3" 
     android:gravity="center|left" 
     android:text="PickBy" 
     android:textColor="@android:color/black" 
     android:textSize="18dp" 
     android:textStyle="bold" 
     android:typeface="serif" > 

    </TextView> 

    <TextView 
     android:id="@+id/TextView4" 
     android:gravity="center|left" 
     android:text="Status" 
     android:textColor="@android:color/black" 
     android:textSize="18dp" 
     android:textStyle="bold" 
     android:typeface="serif" > 

    </TextView> 
    </TableRow> 
</TableLayout> 

теперь страница SampleTableActivitys.java дается здесь ....

public class SampleTableActivity extends Activity { 
    /** Called when the activity is first created. */ 


SQLiteDatabase database; 
private static String DBNAME = "sample.db";  
private static String TABLE = "test"; 

TableLayout tableLayout; 
TableRow row; 
TextView firstCol; 
TextView secondCol; 
TextView thirdCol; 
TextView fourthCol; 
TextView fifthCol; 


@Override 
public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.main); 
    tableLayout=(TableLayout)findViewById(R.id.tableLayout1); 

    createDB(); 
    insertValues(); 
    displayDB(); 
    row.setClickable(true); 
    row.setOnClickListener(new View.OnClickListener() { 
     public void onClick(View view) { 

     Toast.makeText(getApplicationContext(), " "+row.getTag(), 
      Toast.LENGTH_LONG).show(); 
      view.setBackgroundColor(Color.WHITE); 
     } 
     }); 
} 

столбцы создаются с помощью этого ...

private void displayDB() { 

database=openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null); 
if(database!=null) 
{ 
    Cursor cursor=database.rawQuery("SELECT * FROM "+ TABLE, null); 

    Integer index0=cursor.getColumnIndex("ID"); 
    Integer index1 = cursor.getColumnIndex("ITEMS");  
     Integer index2 = cursor.getColumnIndex("LOCATION"); 
     Integer index3 = cursor.getColumnIndex("NAME"); 
     Integer index4 = cursor.getColumnIndex("STATUS"); 
     if(cursor.getCount()>0) 
     { 
      cursor.moveToFirst(); 
      do 
      { 
       row=new TableRow(this); 
       row.setId(100); 
       row.setTag(cursor.getString(index0)); 
       row.setTag(cursor.getString(index1)); 
       row.setTag(cursor.getString(index2)); 
       row.setTag(cursor.getString(index3)); 
       row.setTag(cursor.getString(index4)); 
       row.setLayoutParams(new LayoutParams(
         LayoutParams.FILL_PARENT, 
         LayoutParams.WRAP_CONTENT)); 

       /*Setting up the first coloumn parameters*/ 
       firstCol=new TextView(this); 
       firstCol.setText(cursor.getString(index0)); 
       firstCol.setTextSize(16); 
       firstCol.setTextColor(Color.DKGRAY); 
       firstCol.setLayoutParams(new LayoutParams(
         LayoutParams.FILL_PARENT, 
         LayoutParams.WRAP_CONTENT)); 
       row.addView(firstCol); //adding coloumn to row 

       /*Setting up the second coloumn parameters*/    
       secondCol=new TextView(this); 
       secondCol.setText(cursor.getString(index1)); 
       secondCol.setTextColor(Color.DKGRAY); 
       secondCol.setTextSize(16); 
       secondCol.setLayoutParams(new LayoutParams(
         LayoutParams.FILL_PARENT, 
         LayoutParams.WRAP_CONTENT)); 
       row.addView(secondCol); //adding coloumn to row 

       /*Setting up the third coloumn parameters*/ 
       thirdCol=new TextView(this); 
       thirdCol.setText(cursor.getString(index2)); 
       thirdCol.setTextColor(Color.DKGRAY); 
       thirdCol.setTextSize(16); 
       thirdCol.setLayoutParams(new LayoutParams(
         LayoutParams.WRAP_CONTENT, 
         LayoutParams.WRAP_CONTENT)); 
       row.addView(thirdCol); //adding coloumn to row 
       fourthCol=new TextView(this); 
       fourthCol.setText(cursor.getString(index3)); 
       fourthCol.setTextSize(16); 
       fourthCol.setTextColor(Color.DKGRAY); 
       fourthCol.setLayoutParams(new LayoutParams(
         LayoutParams.FILL_PARENT, 
         LayoutParams.WRAP_CONTENT)); 
       row.addView(fourthCol); 

       fifthCol=new TextView(this); 
       fifthCol.setText(cursor.getString(index4)); 
       fifthCol.setTextSize(16); 
       fifthCol.setTextColor(Color.BLACK); 
       fifthCol.setLayoutParams(new LayoutParams(
         LayoutParams.FILL_PARENT, 
         LayoutParams.WRAP_CONTENT)); 
       row.addView(fifthCol); 
       /*Adding the row to the tablelayout*/ 
       tableLayout.addView(row,new TableLayout.LayoutParams(
         LayoutParams.FILL_PARENT, 
         LayoutParams.WRAP_CONTENT)); 

      }while(cursor.moveToNext()); 
      database.close(); 
     } 
     else 
     { 
      Toast.makeText(getBaseContext(), "NOT AVAILABLE", Toast.LENGTH_LONG).show(); 
     } 
    } 
} 

база данных создана здесь ....

private void createDB() { 
    // TODO Auto-generated method stub 
    try 
    { 
     database=openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null); 
     database.execSQL("CREATE TABLE IF NOT EXISTS "+ TABLE +" (ID INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, ITEMS TEXT, LOCATION TEXT, NAME TEXT, STATUS TEXT);"); 
     database.close(); 
    } 
    catch(Exception e) 
    { 
     Log.e("Database Creation", "Error "+e.toString()); 
    } 
} 

ответ

1

Две вещи я мог заметить:

  1. В displayDB(), вы назначаете одинаковый идентификатор каждой строки. Назначьте уникальные идентификаторы каждому из них. можно присвоить уникальный идентификатор, используя что-то вроде этого внутри цикла:

    row.setId(increment+10); 
    increment++; 
    

    Вы можете инициализировать increment до 100 или любого другого значения, вне цикла.

Edit: Полный код

private void displayDB() { 

database=openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null); 
if(database!=null) 
{ 
    Cursor cursor=database.rawQuery("SELECT * FROM "+ TABLE, null); 
    **int increment =100;** 
    Integer index0=cursor.getColumnIndex("ID"); 
    Integer index1 = cursor.getColumnIndex("ITEMS");  
     Integer index2 = cursor.getColumnIndex("LOCATION"); 
     Integer index3 = cursor.getColumnIndex("NAME"); 
     Integer index4 = cursor.getColumnIndex("STATUS"); 
     if(cursor.getCount()>0) 
     { 
      cursor.moveToFirst(); 
      do 
      { 
       row=new TableRow(this); 

       **row.setId(increment + 10); 
      increment++;** 

      row.setTag(cursor.getString(index0)); 
       row.setTag(cursor.getString(index1)); 
       row.setTag(cursor.getString(index2)); 
       row.setTag(cursor.getString(index3)); 
       row.setTag(cursor.getString(index4)); 
       row.setLayoutParams(new LayoutParams(
         LayoutParams.FILL_PARENT, 
         LayoutParams.WRAP_CONTENT)); 

       /*Setting up the first coloumn parameters*/ 
       firstCol=new TextView(this); 
       firstCol.setText(cursor.getString(index0)); 
       firstCol.setTextSize(16); 
       firstCol.setTextColor(Color.DKGRAY); 
       firstCol.setLayoutParams(new LayoutParams(
         LayoutParams.FILL_PARENT, 
         LayoutParams.WRAP_CONTENT)); 
       row.addView(firstCol); //adding coloumn to row 

       /*Setting up the second coloumn parameters*/    
       secondCol=new TextView(this); 
       secondCol.setText(cursor.getString(index1)); 
       secondCol.setTextColor(Color.DKGRAY); 
       secondCol.setTextSize(16); 
       secondCol.setLayoutParams(new LayoutParams(
         LayoutParams.FILL_PARENT, 
         LayoutParams.WRAP_CONTENT)); 
       row.addView(secondCol); //adding coloumn to row 

       /*Setting up the third coloumn parameters*/ 
       thirdCol=new TextView(this); 
       thirdCol.setText(cursor.getString(index2)); 
       thirdCol.setTextColor(Color.DKGRAY); 
       thirdCol.setTextSize(16); 
       thirdCol.setLayoutParams(new LayoutParams(
         LayoutParams.WRAP_CONTENT, 
         LayoutParams.WRAP_CONTENT)); 
       row.addView(thirdCol); //adding coloumn to row 
       fourthCol=new TextView(this); 
       fourthCol.setText(cursor.getString(index3)); 
       fourthCol.setTextSize(16); 
       fourthCol.setTextColor(Color.DKGRAY); 
       fourthCol.setLayoutParams(new LayoutParams(
         LayoutParams.FILL_PARENT, 
         LayoutParams.WRAP_CONTENT)); 
       row.addView(fourthCol); 

       fifthCol=new TextView(this); 
       fifthCol.setText(cursor.getString(index4)); 
       fifthCol.setTextSize(16); 
       fifthCol.setTextColor(Color.BLACK); 
       fifthCol.setLayoutParams(new LayoutParams(
         LayoutParams.FILL_PARENT, 
         LayoutParams.WRAP_CONTENT)); 
       row.addView(fifthCol); 
       /*Adding the row to the tablelayout*/ 
       tableLayout.addView(row,new TableLayout.LayoutParams(
         LayoutParams.FILL_PARENT, 
         LayoutParams.WRAP_CONTENT)); 

      }while(cursor.moveToNext()); 
      database.close(); 
     } 
     else 
     { 
      Toast.makeText(getBaseContext(), "NOT AVAILABLE", Toast.LENGTH_LONG).show(); 
     } 
    } 
} 
  1. В OnCreate(), вы настраиваете onClickListener для строки после вызова displayDB(), так что только последняя строка была слушателем прилагается к нему. Прикрепите OnClick() к каждой строке, которую вы создаете, и это можно сделать в цикле, в котором вы создаете строки.
+0

спасибо большое ... я могу уловить ур вторую точку, и я реализовал it.its, работающий отлично, то есть теперь я могу щелкнуть каждую строку. Но все же одно и то же значение отображается для каждого щелчка.i can not get ur first point.how должен я назначать уникальные идентификаторы для каждой строки. Возможно, это будет хорошо. Это будет полезно. Спасибо заранее. –

+0

Может ли плз изменить код, указанный мной? я был бы очень благодарен –

+0

Проверьте обновленный ответ, добавили образец кода! –

Смежные вопросы