mardi 26 mai 2015

viewing a listview with checkboxes from the database using CostumeAdapter

This code should show a listview with checkboxes using database.I've been trying since three weeks,but I don't know how to implement the code to set up a listview which must be optimized such that when checkboxes are checked that should not repeat on regular intervals and checked items shouldn't change their position while scrolling.Here is my code,

package com.example.pop;

import android.app.Activity;
import android.content.Context;
import android.database.Cursor;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;



public class MainActivity extends Activity {

DBAdapter myDb;            
ListView myList;
MyCustomAdapter dataAdapter=null ;

@Override
public void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    openDB();
    display();
    insett();

}

private void insert() {

String pap = "1";
String pap1 = "2";
String pap2 = "3";
String pap3 = "4";
String pap4= "5";
String pap5 = "6";
String pap6 = "7";
String pap7 = "8";
String pap8 = "9";
String pap9 = "10";
String pap10 = "11";
String pap11 = "12";
String pap12 = "13";
String pap13= "14";
String pap14 = "15";
String pap15 = "16";
String pap16 = "17";
String pap17 = "18";
String pap18 = "19";
String pap19 = "20";
String pap20 = "21";
String pap21 = "22";
String pap22 = "23";

    // ODO Auto-generated method stub
    myDb.insertRow(pap,false);
    myDb.insertRow(pap1,true);
    myDb.insertRow(pap2,true);
    myDb.insertRow(pap3,false);
    myDb.insertRow(pap4,false);
    myDb.insertRow(pap5,false);
    myDb.insertRow(pap6,false);
    myDb.insertRow(pap7,true);
    myDb.insertRow(pap8,false);
    myDb.insertRow(pap9,false);
    myDb.insertRow(pap10,false);
    myDb.insertRow(pap11,false);
    myDb.insertRow(pap12,false);
    myDb.insertRow(pap13,false);
    myDb.insertRow(pap14,false);
    myDb.insertRow(pap15,false);
    myDb.insertRow(pap16,false);
    myDb.insertRow(pap17,false);
    myDb.insertRow(pap18,false);
    myDb.insertRow(pap19,false);
    myDb.insertRow(pap20,false);
    myDb.insertRow(pap21,false);
    myDb.insertRow(pap22,true);
     Toast.makeText(this, "insett(); method called...", Toast.LENGTH_LONG).show();

}




@Override
protected void onDestroy() {
super.onDestroy();  
closeDB();
}
private void openDB() {
myDb = new DBAdapter(this, null);
myDb.open();
}
private void closeDB() {
myDb.close();
}

// Display ListView with CheckBoxes
private void display() {

    final Cursor cursor = myDb.getAllRows();
    dataAdapter = new MyCustomAdapter(getBaseContext(),cursor);
    myList = (ListView) findViewById(R.id.listView1);
    ListAdapter myCursorAdapter = null;
    myList.setAdapter(myCursorAdapter);

 }


// MyCustomAdapter for ListView Optimization
private class MyCustomAdapter extends DBAdapter  {

   private LayoutInflater mInflater;
   private Cursor cursor;


  public MyCustomAdapter(Context context, Cursor cursor) {
   super(context,cursor);
   this.mInflater = LayoutInflater.from(context);
   this.cursor = cursor;
  }


  private class ViewHolder
   {
       TextView name; 
       CheckBox box;
   }

  public View getView(int position, View convertView, ViewGroup parent) {

   ViewHolder holder = null;

   if (convertView == null) {
   convertView = this.mInflater.inflate(R.layout.item_layoutt, null);
                holder = new ViewHolder();
                holder.name =   (TextView)convertView.findViewById(R.id.textsv);
                holder.box =  (CheckBox)convertView.findViewById(R.id.textcb);
                convertView.setTag(holder);
   } 
   else {
     holder = (ViewHolder) convertView.getTag();
   }
    this.cursor.moveToPosition(position);
              holder.name.setText(this.cursor.getString(this.cursor.getColumnIndex("name")));          
            Boolean bi= Boolean.valueOf(this.cursor.getString(this.cursor.getColumnIndex("ischecked")));
            holder.box.setChecked(bi);
            return convertView;
  }
}
}

DBAdapter.java

 package com.example.pop;


import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;


//TO USE:
//Change the package (at top) to match your project.
//Search for "TODO", and make the appropriate changes.
public class DBAdapter {

/////////////////////////////////////////////////////////////////////
//  Constants & Data
/////////////////////////////////////////////////////////////////////
// For logging:
private static final String TAG = "DBAdapter";

// DB Fields
public static final String KEY_ROWID = "_id";
public static final int COL_ROWID = 0;
/*
 * CHANGE 1:
 */
// TODO: Setup your fields here:
public static final String KEY_NAME = "name";
public static final String KEY_CHECK = "ischecked";

// TODO: Setup your field numbers here (0 = KEY_ROWID, 1=...)
public static final int COL_NAME = 1;



public static final String[] ALL_KEYS = new String[] {KEY_ROWID, KEY_NAME};

// DB info: it's name, and the table we are using (just one).
public static final String DATABASE_NAME = "MyDb";
public static final String DATABASE_TABLE = "mainTable";
// Track DB version if a new version of your app changes the format.
public static final int DATABASE_VERSION = 2;   

private static final String DATABASE_CREATE_SQL = 
        "create table " + DATABASE_TABLE 
        + " (" + KEY_ROWID + " integer primary key autoincrement, "

        /*
         * CHANGE 2:
         */
        // TODO: Place your fields here!
        // + KEY_{...} + " {type} not null"
        //  - Key is the column name you created above.
        //  - {type} is one of: text, integer, real, blob
        //      (http://ift.tt/1aUsJJH)
        //  - "not null" means it is a required field (must be given a   value).
        // NOTE: All must be comma separated (end of line!) Last one must   have NO comma!!
        + KEY_NAME + " text not null "


        // Rest  of creation:
        + ");";

// Context of application who uses us.
private final Context context;

private DatabaseHelper myDBHelper;
private SQLiteDatabase db;

/////////////////////////////////////////////////////////////////////
//  Public methods:
/////////////////////////////////////////////////////////////////////

public DBAdapter(Context ctx, Cursor c) {
    super();
    this.context = ctx;
    myDBHelper = new DatabaseHelper(context);

}

public View getView(int position, View convertView, ViewGroup parent) {
    // TODO Auto-generated method stub
    return parent;
}


// Open the database connection.
public DBAdapter open() {
    db = myDBHelper.getWritableDatabase();
    return this;
}

// Close the database connection.
public void close() {
    myDBHelper.close();
}

// Add a new set of values to the database.
public long insertRow(String name,boolean b) {
    /*
     * CHANGE 3:
     */     
    // TODO: Update data in the row with new fields.
    // TODO: Also change the function's arguments to be what you need!
    // Create row's data:
    ContentValues initialValues = new ContentValues();
    initialValues.put(KEY_NAME, name);
    initialValues.put(KEY_CHECK, b);


    // Insert it into the database.
    return db.insert(DATABASE_TABLE, null, initialValues);
}

// Delete a row from the database, by rowId (primary key)
public boolean deleteRow(long l) {
    String where = KEY_ROWID + "=" + l;
    return db.delete(DATABASE_TABLE, where, null) != 0;
}

public void deleteAll() {
    Cursor c = getAllRows();
    long rowId = c.getColumnIndexOrThrow(KEY_ROWID);
    if (c.moveToFirst()) {
        do {
            deleteRow(c.getLong((int) rowId));              
        } while (c.moveToNext());
    }
    c.close();
}

// Return all data in the database.
public Cursor getAllRows() {
    String where = null;
    Cursor c =  db.query(true, DATABASE_TABLE, ALL_KEYS, 
                        where, null, null, null, null, null);
    if (c != null) {
        c.moveToFirst();
    }
    return c;
}

// Get a specific row (by rowId)
public Cursor getRow(String string) {
    String where = KEY_ROWID + "=" + string;
    Cursor c =  db.query(true, DATABASE_TABLE, ALL_KEYS, 
                    where, null, null, null, null, null);
    if (c != null) {
        c.moveToFirst();
    }
    return c;
}

// Change an existing row to be equal to new data.
public boolean updateRow(String kite, String name) {
    String where = KEY_ROWID + "=" + kite;

    /*
     * CHANGE 4:
     */
    // TODO: Update data in the row with new fields.
    // TODO: Also change the function's arguments to be what you need!
    // Create row's data:
    ContentValues newValues = new ContentValues();
    newValues.put(KEY_NAME, name);


    // Insert it into the database.
    return db.update(DATABASE_TABLE, newValues, where, null) != 0;
}



/////////////////////////////////////////////////////////////////////
//  Private Helper Classes:
/////////////////////////////////////////////////////////////////////

/**
 * Private class which handles database creation and upgrading.
 * Used to handle low-level database access.
 */
private static class DatabaseHelper extends SQLiteOpenHelper
{
    DatabaseHelper(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase _db) {
        _db.execSQL(DATABASE_CREATE_SQL);           
    }

    @Override
    public void onUpgrade(SQLiteDatabase _db, int oldVersion, int newVersion)      {
        Log.w(TAG, "Upgrading application's database from version " +   oldVersion
                + " to " + newVersion + ", which will destroy all old data!");

        // Destroy old database:
        _db.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE);

        // Recreate new database:
        onCreate(_db);
    }
}

}

activity_main.xml

<RelativeLayout xmlns:android="http://ift.tt/nIICcg"
xmlns:tools="http://ift.tt/LrGmb4"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.example.adapterx.MainActivity" >

<ListView
    android:id="@+id/listView1"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_alignParentBottom="true"
    android:layout_below="@+id/textView1" >

</ListView>

<Button
    android:id="@+id/textView1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignLeft="@+id/listView1"
    android:layout_alignParentTop="true"
    android:layout_alignRight="@+id/listView1"
    android:text="Get"
   />

</RelativeLayout>

item_layoutt.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://ift.tt/nIICcg"
android:layout_width="fill_parent"
android:layout_height="match_parent"
android:orientation="horizontal" >

<CheckBox
    android:id="@+id/textcb"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" />

<TextView
    android:id="@+id/textsv"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:padding="10dp"
    android:text="TextView" />

</LinearLayout>

This code inserts items into database ,but cannot show it into the screen. I'm unable to detect errors in this code. Please Help Me!




Aucun commentaire:

Enregistrer un commentaire