ListView空白行

时间:2013-04-16 04:03:27

标签: java android listview

出于某种原因,我的ListView有空行,如图中所示。 我无法删除它们但是包含数据的行我可以删除它们。我使用SimpleCursorAdapter,ListAdapter和CursorAdapter从SQLitedatabase填充我的ListView。

Admin Activity

管理员班级

package com.fullfrontalgames.numberfighter;

import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ListActivity;
import android.content.Context;
import android.content.DialogInterface;
import android.database.Cursor;
import android.os.Bundle;
import android.support.v4.widget.CursorAdapter;
import android.support.v4.widget.SimpleCursorAdapter;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class Admin extends ListActivity {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.admin);

        DBAdapter db = new DBAdapter(this);
        db.open();

        ListView UsernameList = (ListView)findViewById(android.R.id.list);

        final Cursor playeraccounts = db.GetAllPlayers();
        db.changeCursor(playeraccounts);
        String[] from = new String[] {
            "USERNAME"
        };
        int[] to = new int[] {
            R.id.AdminTextView
        };

        ListAdapter cursorAdapter = new SimpleCursorAdapter(this, R.layout.admin, playeraccounts,
                from, to, 0);
        UsernameList.setAdapter(cursorAdapter);

        abstract class CustomCursorAdapter extends CursorAdapter {
            public CustomCursorAdapter(Context context, Cursor c, int flags) {
                super(context, playeraccounts, flags);
                inflater = LayoutInflater.from(context);

            }

            LayoutInflater inflater;

            @Override
            public View getView(int position, View convertView, ViewGroup parent) {
                ViewHolder holder;
                if (convertView == null) {
                    convertView = inflater.inflate(R.layout.admin, null);
                    holder = new ViewHolder();
                    holder.text1 = (TextView)convertView.findViewById(R.id.AdminTextView);
                    holder.button = (Button)convertView.findViewById(R.id.PlayerDelete);

                    convertView.setTag(holder);
                } else {
                    holder = (ViewHolder)convertView.getTag();

                    return convertView;
                }

                class ViewHolder {
                    TextView text1;

                }

                holder.text1.setText(position);
                holder.button.setText(position);
                return convertView;
            }
        }

    }

    public void onClickDelete(View view) {
        int id = 0;
        Button deletebutton = (Button)findViewById(R.id.PlayerDelete);
        // TODO Auto-generated method stub
        showDialog(id);

    }

    @Override
    public Dialog onCreateDialog(final int id) {
        final DBAdapter db = new DBAdapter(this);
        db.open();
        switch (id) {
            case 0:
                return new AlertDialog.Builder(this).setIcon(R.drawable.icon)
                        .setTitle("Would you like to delete this player?")
                        .setPositiveButton("Yes", new DialogInterface.OnClickListener() {

                            @Override
                            public void onClick(DialogInterface dialog, int whichButton) {
                                // TODO Auto-generated method stub
                                TextView playernames = (TextView)findViewById(R.id.AdminTextView);
                                String userName = playernames.getText().toString();
                                db.deleteEntry(userName);
                                Toast.makeText(getBaseContext(), "Player deleted",
                                        Toast.LENGTH_SHORT).show();
                            }
                        }).setNegativeButton("No", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int whichButton) {
                                Toast.makeText(getBaseContext(), "Canceled", Toast.LENGTH_SHORT)
                                        .show();
                            }
                        })

                        .create();

        }
        return null;

    }

}

DBAdapter类

    package com.fullfrontalgames.numberfighter;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;

public class DBAdapter {
    static final String DATABASE_NAME = "NFDB.db";
    static final int DATABASE_VERSION = 2;
    public static final int NAME_COLUMN = 1;
    // TODO: Create public field for each column in your table.
    // SQL Statement to create a new database.
    static final String DATABASE_CREATE = "create table NFDB ("
            + "ID integer primary key autoincrement, " + "USERNAME text,"
            + "PASSWORD text, EMAIL text, NUMBERINPUT text, "
            + "SCORE text, FRIENDS text); ";
    static final String CREATE_INDEX_KEYTYPE = "CREATE UNIQUE INDEX idx_keytype ON tableName(USERNAME)";
    // Variable to hold the database instance
    public SQLiteDatabase db;
    // Context of the application using the database.
    private final Context context;
    // Database open/upgrade helper
    private final DataBaseHelper DBHelper;

    public DBAdapter(Context _context) {
        context = _context;
        DBHelper = new DataBaseHelper(context, DATABASE_NAME, null,
                DATABASE_VERSION);
    }

    public DBAdapter open() throws SQLException {
        db = DBHelper.getWritableDatabase();

        return this;
    }

    public void close() {
        db.close();
    }

    public SQLiteDatabase getDatabaseInstance() {
        return db;
    }

    public void insertEntry(String userName, String password, String email) {
        ContentValues newValues = new ContentValues();
        // Assign values for each row.
        newValues.put("USERNAME", userName);
        newValues.put("PASSWORD", password);
        newValues.put("EMAIL", email);
        // Insert the row into your table
        db.insert("NFDB", null, newValues);
        // /Toast.makeText(context, "Reminder Is Successfully Saved",
        // Toast.LENGTH_LONG).show();
    }

    public int deleteEntry(String userName) {
        // String id=String.valueOf(ID);
        String where = "USERNAME=?";
        int numberOFEntriesDeleted = db.delete("NFDB", where,
                new String[] { userName });
        // Toast.makeText(context,
        // "Number fo Entry Deleted Successfully : "+numberOFEntriesDeleted,
        // Toast.LENGTH_LONG).show();
        return numberOFEntriesDeleted;
    }

    public String getSinlgeEntry(String userName) {
        Cursor cursor = db.query("NFDB", null, " USERNAME=?",
                new String[] { userName }, null, null, null);
        if (cursor.getCount() < 1) // UserName Not Exist
        {
            cursor.close();
            return "NOT EXIST";
        }
        cursor.moveToFirst();
        String password = cursor.getString(cursor.getColumnIndex("PASSWORD"));
        cursor.close();
        return password;

    }

    public void updateEntry(String userName, String password) {
        // Define the updated row content.
        ContentValues updatedValues = new ContentValues();
        // Assign values for each row.
        updatedValues.put("USERNAME", userName);
        updatedValues.put("PASSWORD", password);

        String where = "USERNAME = ?";
        db.update("NFDB", updatedValues, where, new String[] { userName });
    }

    public String getData() {
        String[] columns = new String[] { "ID", "USERNAME" };
        Cursor c = db
                .query("NFDB", columns, null, null, null, null, null, null);
        String result = "";
        int iRow = c.getColumnIndex("ID");
        int iName = c.getColumnIndex("USERNAME");

        for (c.moveToFirst(); !c.isAfterLast(); c.moveToNext()) {
            result = result + c.getString(iRow) + " " + c.getString(iName)
                    + "/n";
        }

        return result;
    }

    public String getUsername(String searchName) {
        Cursor c = db.query("NFDB", new String[] { "USERNAME" },
                "USERNAME = ?", new String[] { searchName }, null, null, null);
        if (c.moveToNext())
            return c.getString(0);
        else
            return "";
    }

    public void InsertScore(String Username, String Score) {
        ContentValues ScoreValues = new ContentValues();
        ScoreValues.put("USERNAME", Username);
        ScoreValues.put("SCORE", Score);
        db.insert("NFDB", null, ScoreValues);

    }

    public String GetGameScore(String Username, String Score) {
        Cursor cursor = db.query("NFDB", null, "USERNAME", new String[] {
                Username, Score }, null, null, null);
        cursor.moveToFirst();
        cursor.close();
        return Username;
    }

    public String GetAllScore() {
        String[] columns = new String[] { "ID", "USERNAME", "SCORE" };
        Cursor cursor = db.query("NFDB", columns, null, null, null, null, null);
        String result = "";
        int iRow = cursor.getColumnIndex("ID");
        int iUsername = cursor.getColumnIndex("USERNAME");
        int iScore = cursor.getColumnIndex("SCORE");

        for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()) {
            result = result + cursor.getString(iRow) + " "
                    + cursor.getString(iUsername) + " "
                    + cursor.getString(iScore) + "/n";
        }
        return result;
    }

    public void InsertNumber(String Number) {
        ContentValues NumberValues = new ContentValues();
        ;
        NumberValues.put("NUMBERINPUT", Number);
        db.insert("NFDB", null, NumberValues);
    }

    public String GetNumber(String Username, String Number) {
        Cursor cursor = db.query("NFDB", null, "USERNAME", new String[] {
                Username, Number }, null, null, null, null);
        cursor.moveToFirst();
        cursor.close();
        return Username;
    }

    public String GetAllNumbers() {
        String[] columns = new String[] { "ID", "USERNAME", "NUMBERINPUT" };
        Cursor cursor = db.query("NFDB", columns, null, null, null, null, null,
                null);
        String result = "";
        int iRow = cursor.getColumnIndex("ID");
        int iName = cursor.getColumnIndex("USERNAME");
        int iNumber = cursor.getColumnIndex("NUMBERINPUT");

        for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()) {
            result = result + cursor.getString(iRow) + " "
                    + cursor.getString(iName) + " " + cursor.getString(iNumber)
                    + "/n";
        }
        return result;

    }

    public void InsertFriends(String Friends) {
        ContentValues FriendValues = new ContentValues();
        FriendValues.put("FRIENDS", Friends);
        db.insert("NFDB", null, FriendValues);
    }

    public int DeleteFriends(String Friends) {
        String where = "FRIENDS=?";
        int numberOfEntriesDeleted = db.delete("NFDB", where,
                new String[] { Friends });
        return numberOfEntriesDeleted;
    }

    public String GetFriend(String Defender) {
        Cursor cursor = db.query("NFDB", null, "FRIENDS",
                new String[] { Defender }, null, null, null, null);
        cursor.moveToFirst();
        cursor.close();
        return Defender;

    }

    public int PlayFriend() {
        Cursor cursor = db.query("NFDB", null, "FRIENDS", null, null, null,
                null, null);
        cursor.moveToFirst();
        cursor.close();
        return 0;

    }

    public Cursor GetAllFriends() {

        return db.rawQuery("select rowid _id,FRIENDS FROM NFDB", null);

    }

    public int get(String string) {
        // TODO Auto-generated method stub
        return 0;
    }

    public Cursor GetAllPlayers() {

        return db.rawQuery("select rowid _id,* from NFDB", null);

    }

    public Cursor GetAllFriends2() {

        return db.rawQuery("select rowid _id,FRIENDS FROM NFDB", null);

    }

    public Cursor changeCursor(Cursor newcursor) {
        return newcursor;

    }

}

1 个答案:

答案 0 :(得分:0)

尝试使用下面的代码,它可以帮助你..

public class CustAdp extends ArrayAdapter<String> {

    Cursor cursor_subCat;

    public CustAdp(Context context, Cursor cursor_subcategory) {
        super(context, id);
        this.cursor_subCat = cursor_subcategory;
        cursor_subCat.moveToFirst();
    }

    public int getCount() {
        // TODO Auto-generated method stub
        return cursor_subCat.getCount();
    }

    public String getItem(int position) {
        // TODO Auto-generated method stub
        cursor_subCat.moveToPosition(position);
        return cursor_subCat.getString(cursor_subCat
                .getColumnIndex("Sub_CatName"));
    }

    public long getItemId(int position) {
        // TODO Auto-generated method stub
        cursor_subCat.moveToPosition(position);
        return cursor_subCat.getInt(cursor_subCat
                .getColumnIndex("Sub_IdAuto"));
    }

    @Override
    public void notifyDataSetChanged() {
        // TODO Auto-generated method stub
        super.notifyDataSetChanged();
        cursor_subCat.requery();
    }

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

        convertView = getLayoutInflater().inflate(R.layout.customsubcat,
                null);
        ImageView iv_subcat = (ImageView) convertView
                .findViewById(R.id.image_region1);
        TextView tv_subcat = (TextView) convertView
                .findViewById(R.id.txt_regionname1);
        Button btn_subcat = (Button) convertView
                .findViewById(R.id.button_delete_subcat);

        cursor_subCat.moveToPosition(position);
        try {
            byte[] subimage = cursor_subCat.getBlob(cursor_subCat
                    .getColumnIndex("Sub_CatImage"));
            Bitmap bm = BitmapFactory.decodeByteArray(subimage, 0,
                    subimage.length);
            iv_subcat.setImageBitmap(bm);
            tv_subcat.setText(cursor_subCat.getString(cursor_subCat
                    .getColumnIndex("Sub_CatName")));
            subcat_id = cursor_subCat.getLong(cursor_subCat
                    .getColumnIndex("Sub_IdAuto"));
            btn_subcat.setId((int) subcat_id);
            id = cursor_subCat.getInt(cursor_subCat
                    .getColumnIndex("Sub_MyReceipe"));
            convertView.setId(position);
        } catch (Exception e) {
            // TODO: handle exception
        }




        return convertView;

    }

    class ViewHolder {
        TextView tv_subcat;
        Button btn_subcat;
        ImageView iv_subcat;
    }
}

只需将光标传递给自定义适配器类。然后根据需要更改布局。