Android Studio

时间:2015-08-13 09:45:00

标签: java android database listview

当我尝试使用游标创建包含来自数据库的数据的ListView时,我遇到了一些问题。 但是当我运行活动时,错误报告会给出错误消息:

  

java.lang.IllegalStateException:无法从CursorWindow读取第0行col -1。在从中访问数据之前,请确保Cursor已正确初始化。

我不知道发生了什么,我在StackOverFlow上搜索答案我找到了一些答案,我必须分配Cursor的值,但它仍然没有解决我的错误。 拜托,有人可以帮助我轻松理解单词。 谢谢。

NB。我的CategorySetting.java代码(Activity包含ListView

public class CategorySetting extends Activity {
    private SQLiteDatabase db;
    private CustomCursorAdapter customAdapter ;
    private static Button BtnIAddCateg;
    private static Button BtnICancelCateg;
    private static final String TAG = CategorySetting.class.getSimpleName();
    DatabaseHelper dBHelper = new DatabaseHelper (this);
    private ListView list;
    private ArrayList<String> arrCategId = new ArrayList<String>();
    private ArrayList<String> arrCategName = new ArrayList<String>();
    private ArrayList<String> arrCategNote = new ArrayList<String>();
    private ArrayList<String> arrCategCurr = new ArrayList<String>();


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_category_setting);
        onButtonClickButtonListener();
        //ListView list = getListView();
        //showListView();
        displayData();
    }

    public void showListView(){
        list = (ListView)findViewById(android.R.id.list);
        list.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
                Log.d(TAG, "clicked on item: " + arg2);
                String label = arg0.getItemAtPosition(arg2).toString();
                Toast.makeText(CategorySetting.this, "You Selected " + label, Toast.LENGTH_LONG).show();
                //click to update data
                Intent i = new Intent(getApplicationContext(), AddCategory.class);
                //i.putExtra("CategId", arrCategId.get(arg2));
                i.putExtra("CategName", arrCategName.get(arg2));
                i.putExtra("CategNote", arrCategNote.get(arg2));
                i.putExtra("CategCurr", arrCategCurr.get(arg2));
                i.putExtra("update", true);
                startActivity(i);


            }
        });

        new Handler().post(new Runnable() {
            @Override
            public void run() {
                customAdapter = new CustomCursorAdapter(CategorySetting.this, dBHelper.getAllData());
                list.setAdapter(customAdapter);
            }
        });
    }

    private void displayData() {
        db = dBHelper.getReadableDatabase();
        Cursor mCursor = db.rawQuery("SELECT * FROM " + dBHelper.TABLE_Categ_NAME, null);

        arrCategId.clear();
        arrCategName.clear();
        arrCategNote.clear();
        arrCategCurr.clear();
        if (mCursor.moveToFirst()) {
            do {
                arrCategId.add(mCursor.getString(mCursor.getColumnIndex(dBHelper.COL1)));// error disini make sure cursor is bla bla
                arrCategName.add(mCursor.getString(mCursor.getColumnIndex(dBHelper.COL2)));
                arrCategNote.add(mCursor.getString(mCursor.getColumnIndex(dBHelper.COL3)));
                arrCategCurr.add(mCursor.getString(mCursor.getColumnIndex(dBHelper.COL4)));

            } while (mCursor.moveToNext());
        }
        DisplayAdapter disadpt = new DisplayAdapter(CategorySetting.this, arrCategId, arrCategName, arrCategId, arrCategCurr);
        list.setAdapter(disadpt);
        mCursor.close();
    }
        //ListView view = getListView();
        //iew.addHeaderView(getLayoutInflater().inflate(R.layout.row, null));
        //db = dBHelper.getWritableDatabase();
        //this.muat_ulang();



    /*public void reload(){
        try {
            DatabaseHelper dbHelper = new DatabaseHelper(this.getApplicationContext());
            db = dbHelper.getWritableDatabase();
            Cursor c = db.rawQuery("SELECT CategName FROM " + tableName, null);
            if (c != null ) {
                if  (c.moveToFirst()) {
                    do {
                        String categName = c.getString(c.getColumnIndex("CategName"));
                    }while (c.moveToNext());
                }
            }
        } catch (SQLiteException se ) {
            Log.e(getClass().getSimpleName(), "Could not create or Open the database");
        } finally {
            if (db != null)
                db.execSQL("DELETE FROM " + tableName);
            db.close();
        }

    }*/



    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_category_setting, menu);
        return true;
    }

    public void onButtonClickButtonListener(){

        BtnIAddCateg = (Button)findViewById(R.id.btnAddNewCateg);
        BtnIAddCateg.setOnClickListener(
                new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Intent intentAddCateg = new Intent ("com.example.ever_ncn.cashflow.AddCategory");
                        startActivity(intentAddCateg);
                    }
                }
        );

        BtnICancelCateg = (Button)findViewById(R.id.btnCancelCateg);
        BtnICancelCateg.setOnClickListener(
                new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Intent intent = new Intent(
                                CategorySetting.this,
                                MainActivity.class
                        );
                        startActivity(intent);
                    }
                }
        );
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
}

DatabaseHelper.java

public class DatabaseHelper extends SQLiteOpenHelper {

    public static final String MyVillageSoftware = "MyVillageSoftware";
    public static final String DATABASE_NAME = "Cashflow.db";
    public static final String TABLE_Categ_NAME = "category_table";
    public static final String TABLE_Trans_NAME = "transaction_table";
    public static final String COL1 = "CategId";
    public static final String COL2 = "CategName";
    public static final String COL3 = "Note";
    public static final String COL4 = "Currency";
    public static final String COL5 = "_id";
    //TOL for transaction Coloumn
    public static final String TOL1 = "TransId";
    public static final String TOL2 = "TransName";
    public static final String TOL3 = "Amount";
    public static final String TOL4 = "TransNote";
    public static final String TOL5 = "TransDate";
    public static final String TOL6 = "CategId";
    public static final String TOL7 = "_id";
    private static final String TAG = DatabaseHelper.class.getSimpleName();



    public DatabaseHelper(Context context) {
        super(context, DATABASE_NAME, null, 9);

    }

    @Override
    public void onCreate(SQLiteDatabase db) {

        db.execSQL("Create table " + TABLE_Categ_NAME +
                " (CategID Integer PRIMARY KEY AUTOINCREMENT, " +
                "CategName Text," +
                " Note Text," +
                " Currency Text," +
                " _id Text)");

        db.execSQL("Create table " + TABLE_Trans_NAME +
                " (TransID Integer PRIMARY KEY AUTOINCREMENT, " +
                "TransName Text," +
                " Amount Integer," +
                " TransNote Text," +
                " TransDate long," +
                " CategId Text, " +
                " _id Text)");
    }

    public boolean insertCategData(String categname, String note, String currency, String id){
        SQLiteDatabase db = this.getWritableDatabase();
        ContentValues contentValues = new ContentValues();
        contentValues.put(COL2, categname);
        contentValues.put(COL3, note);
        contentValues.put(COL4, currency);
        contentValues.put(COL5, id);
        long result = db.insert(TABLE_Categ_NAME, null, contentValues);
         if (result == -1)
             return false;
         else
             return true;

    }

    public boolean insertTransData (String transname, Integer amount, String transnote, long transdate, String categ, String id){
        SQLiteDatabase db = this.getWritableDatabase();
        ContentValues contentValues = new ContentValues();
        //contentValues.put(TOL1, transname);
        contentValues.put(TOL2, transname);
        contentValues.put(TOL3, amount);
        contentValues.put(TOL4, transnote);
        contentValues.put(TOL5, transdate);
        contentValues.put(TOL6, categ);
        contentValues.put(TOL7, id);
        long result = db.insert(TABLE_Trans_NAME, null, contentValues);
        if (result == -1)
            return false;
        else
            return true;

    }


    public List<String> getAllCategory() {
        List<String> AllCategoryList = new ArrayList<String>();

            String selectQuery = "SELECT * FROM " + TABLE_Categ_NAME;
            SQLiteDatabase db = this.getReadableDatabase();
            Cursor cursor = db.rawQuery(selectQuery, null);

            /*db = SQLiteDatabase.openDatabase(DATABASE_NAME, Context.MODE_PRIVATE, null);
            Cursor allrows = db.rawQuery("SELECT * FROM " + TABLE_Categ_NAME, null);
            System.out.println("COUNT : " + allrows.getCount());*/

            if (cursor.moveToFirst()) {
                do {

                    String ID = cursor.getString(0);
                    String Categ = cursor.getString(1);
                    String Note = cursor.getString(2);
                    String Curr = cursor.getString(3);
                    AllCategoryList.add(Categ);

                } while (cursor.moveToNext());
            }
            cursor.close();
            db.close();
            return AllCategoryList;
        }
    public Cursor getAllData() {
        SQLiteDatabase db = this.getReadableDatabase();

        String buildSQL = "SELECT * FROM " + TABLE_Categ_NAME;

        Log.d(TAG, "getAllData SQL: " + buildSQL);

        return db.rawQuery(buildSQL, null);
    }



    /*public ArrayList<String>getAllCategory(){
        ArrayList<String> AllCategoryList = new ArrayList<String>();
        SQLiteDatabase db = this.getReadableDatabase();
        String selectCateg="Select * FROM " +TABLE_Categ_NAME;
        Cursor cursor = db.rawQuery(selectCateg, null);
        if(cursor.getCount()>0){
            while (cursor.moveToNext()){
                String categname1=cursor.getString(cursor.getColumnIndex(COL2));
                AllCategoryList.add(COL2);

            }return AllCategoryList;
        }

        return AllCategoryList;

    }*/


    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        db.execSQL("DROP TABLE IF EXISTS " + TABLE_Categ_NAME);
        db.execSQL("DROP TABLE IF EXISTS " + TABLE_Trans_NAME);
        onCreate(db);

    }
}

这个DisplayAdapter.java

public class DisplayAdapter extends BaseAdapter {

    private Context mContext;
    private ArrayList<String> categArrId;
    private ArrayList<String> categArrName;
    private ArrayList<String> categArrNote;
    private ArrayList<String> categArrCurr;

    public DisplayAdapter(Context c, ArrayList<String> categId,ArrayList<String> categName, ArrayList<String> categNote, ArrayList<String> categCurr) {
        this.mContext = c;

        this.categArrId = categId;
        this.categArrName = categName;
        this.categArrNote = categNote;
        this.categArrCurr = categCurr;
    }

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

    public Object getItem(int position) {
        // TODO Auto-generated method stub
        return null;
    }

    public long getItemId(int position) {
        // TODO Auto-generated method stub
        return 0;
    }

    public View getView(int pos, View child, ViewGroup parent) {
        Holder mHolder;
        LayoutInflater layoutInflater;
        if (child == null) {
            layoutInflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            child = layoutInflater.inflate(R.layout.categsetlist, null);
            mHolder = new Holder();
            mHolder.txt_id = (TextView) child.findViewById(R.id.txt_id);
            mHolder.txt_name = (TextView) child.findViewById(R.id.txt_categnamelist);
            mHolder.txt_note = (TextView) child.findViewById(R.id.txt_categnotelist);
            mHolder.txt_curr = (TextView) child.findViewById(R.id.txt_categcurrlist);
            child.setTag(mHolder);
        } else {
            mHolder = (Holder) child.getTag();
        }

        mHolder.txt_name.setText(categArrName.get(pos));
        return child;
    }

    public class Holder {
        TextView txt_id;
        TextView txt_name;
        TextView txt_note;
        TextView txt_curr;
    }
}

1 个答案:

答案 0 :(得分:0)

好吧,看看你的代码,我发现:
DatabaseHelper.COL1 CategId onCreate CategID mCursor.getColumnIndex(dBHelper.COL1)作为列名称时,documentClient.createDocument( getTodoCollection().getSelfLink(), document, null, false) - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath static NSString *CellIdentifier = @"Cell"; UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; // if (cell == nil){ cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier]; // } if (indexPath.row==0) { UILabel *lbl_label = [[UILabel alloc] initWithFrame:CGRectMake(15, 7, 200, 25)]; lbl_label.text = @"PRICE"; [lbl_label setFont:NORMAL_LABEL(16)]; [lbl_label setTextColor:UIColorFromRGB(0x565A5C,1.0)]; UILabel *lbl_price = [[UILabel alloc] initWithFrame:CGRectMake(100, 7, 200, 25)]; lbl_price.text = @"$ 50"; [lbl_price setFont:NORMAL_LABEL(16)]; [lbl_price setTextColor:[UIColor grayColor]]; [lbl_price setTextColor:UIColorFromRGB(0x82898D,1.0)]; lbl_price.textAlignment = NSTextAlignmentRight; [cell addSubview:lbl_price]; [cell addSubview:lbl_label]; } else if (indexPath.row==1) { UILabel *lbl_label = [[UILabel alloc] initWithFrame:CGRectMake(15, 7, 200, 25)]; lbl_label.text = @"CUISINE"; [lbl_label setFont:NORMAL_LABEL(16)]; [lbl_label setTextColor:UIColorFromRGB(0x565A5C,1.0)]; UILabel *lbl_price = [[UILabel alloc] initWithFrame:CGRectMake(100, 7, 200, 25)]; lbl_price.text = @"Sushi, Japanese, Arabian"; [lbl_price setFont:NORMAL_LABEL(16)]; [lbl_price setTextColor:[UIColor grayColor]]; [lbl_price setTextColor:UIColorFromRGB(0x82898D,1.0)]; lbl_price.textAlignment = NSTextAlignmentRight; [cell addSubview:lbl_price]; [cell addSubview:lbl_label]; } else if (indexPath.row==2) { UILabel *lbl_label = [[UILabel alloc] initWithFrame:CGRectMake(15, 7, 200, 25)]; lbl_label.text = @"GOOD FOR"; [lbl_label setFont:NORMAL_LABEL(16)]; [lbl_label setTextColor:UIColorFromRGB(0x565A5C,1.0)]; UILabel *lbl_price = [[UILabel alloc] initWithFrame:CGRectMake(100,7, 200, 25)]; lbl_price.text = @"Alcohol, Brunch"; [lbl_price setFont:NORMAL_LABEL(16)]; [lbl_price setTextColor:[UIColor grayColor]]; [lbl_price setTextColor:UIColorFromRGB(0x82898D,1.0)]; lbl_price.textAlignment = NSTextAlignmentRight; [cell addSubview:lbl_price]; [cell addSubview:lbl_label]; cell.selectionStyle = UITableViewCellSelectionStyleNone; return cell; - &GT;因此找不到order by

的光标列