Android Sqlite数据库修改后出错

时间:2015-08-18 11:06:58

标签: android sqlite

我正在使用sqlite数据库处理应用程序。我得到了项目源并运行它,没关系,但是当我使用sqlite浏览器修改数据库时,我在cat log中收到以下错误。

    08-18 15:57:57.910: E/CursorWindow(28926): Failed to read row 6, column 5 from a CursorWindow which has 7 rows, 5 columns.
08-18 15:57:57.925: E/AndroidRuntime(28926): FATAL EXCEPTION: AsyncTask #1
08-18 15:57:57.925: E/AndroidRuntime(28926): java.lang.RuntimeException: An error occured while executing doInBackground()
08-18 15:57:57.925: E/AndroidRuntime(28926):    at android.os.AsyncTask$3.done(AsyncTask.java:299)
08-18 15:57:57.925: E/AndroidRuntime(28926):    at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:352)
08-18 15:57:57.925: E/AndroidRuntime(28926):    at java.util.concurrent.FutureTask.setException(FutureTask.java:219)
08-18 15:57:57.925: E/AndroidRuntime(28926):    at java.util.concurrent.FutureTask.run(FutureTask.java:239)
08-18 15:57:57.925: E/AndroidRuntime(28926):    at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
08-18 15:57:57.925: E/AndroidRuntime(28926):    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
08-18 15:57:57.925: E/AndroidRuntime(28926):    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
08-18 15:57:57.925: E/AndroidRuntime(28926):    at java.lang.Thread.run(Thread.java:838)
08-18 15:57:57.925: E/AndroidRuntime(28926): Caused by: java.lang.IllegalStateException: Couldn't read row 6, col 5 from CursorWindow.  Make sure the Cursor is initialized correctly before accessing data from it.
08-18 15:57:57.925: E/AndroidRuntime(28926):    at android.database.CursorWindow.nativeGetString(Native Method)
08-18 15:57:57.925: E/AndroidRuntime(28926):    at android.database.CursorWindow.getString(CursorWindow.java:434)
08-18 15:57:57.925: E/AndroidRuntime(28926):    at android.database.AbstractWindowedCursor.getString(AbstractWindowedCursor.java:51)
08-18 15:57:57.925: E/AndroidRuntime(28926):    at company.profile.app.android.DataBaseHelperCompany.getAllDataProduct(DataBaseHelperCompany.java:204)
08-18 15:57:57.925: E/AndroidRuntime(28926):    at company.profile.app.android.Product.getAllProduct(Product.java:211)
08-18 15:57:57.925: E/AndroidRuntime(28926):    at company.profile.app.android.Product.access$0(Product.java:210)
08-18 15:57:57.925: E/AndroidRuntime(28926):    at company.profile.app.android.Product$CheckListData.doInBackground(Product.java:198)
08-18 15:57:57.925: E/AndroidRuntime(28926):    at company.profile.app.android.Product$CheckListData.doInBackground(Product.java:1)
08-18 15:57:57.925: E/AndroidRuntime(28926):    at android.os.AsyncTask$2.call(AsyncTask.java:287)
08-18 15:57:57.925: E/AndroidRuntime(28926):    at java.util.concurrent.FutureTask.run(FutureTask.java:234)
08-18 15:57:57.925: E/AndroidRuntime(28926):    ... 4 more
08-18 15:57:58.308: E/WindowManager(28926): Activity company.profile.app.android.Portfolio has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView{41fe6380 V.E..... R.....ID 0,0-407,175} that was originally added here
08-18 15:57:58.308: E/WindowManager(28926): android.view.WindowLeaked: Activity company.profile.app.android.Portfolio has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView{41fe6380 V.E..... R.....ID 0,0-407,175} that was originally added here
08-18 15:57:58.308: E/WindowManager(28926):     at android.view.ViewRootImpl.<init>(ViewRootImpl.java:424)
08-18 15:57:58.308: E/WindowManager(28926):     at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:218)
08-18 15:57:58.308: E/WindowManager(28926):     at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:69)
08-18 15:57:58.308: E/WindowManager(28926):     at android.app.Dialog.show(Dialog.java:281)
08-18 15:57:58.308: E/WindowManager(28926):     at android.app.ProgressDialog.show(ProgressDialog.java:116)
08-18 15:57:58.308: E/WindowManager(28926):     at android.app.ProgressDialog.show(ProgressDialog.java:99)
08-18 15:57:58.308: E/WindowManager(28926):     at company.profile.app.android.Product$CheckListData.onPreExecute(Product.java:190)
08-18 15:57:58.308: E/WindowManager(28926):     at android.os.AsyncTask.executeOnExecutor(AsyncTask.java:586)
08-18 15:57:58.308: E/WindowManager(28926):     at android.os.AsyncTask.execute(AsyncTask.java:534)
08-18 15:57:58.308: E/WindowManager(28926):     at company.profile.app.android.Product.onResume(Product.java:36)
08-18 15:57:58.308: E/WindowManager(28926):     at android.app.Instrumentation.callActivityOnResume(Instrumentation.java:1259)
08-18 15:57:58.308: E/WindowManager(28926):     at android.app.Activity.performResume(Activity.java:5200)
08-18 15:57:58.308: E/WindowManager(28926):     at android.app.ActivityThread.performResumeActivity(ActivityThread.java:2931)
08-18 15:57:58.308: E/WindowManager(28926):     at android.app.LocalActivityManager.moveToState(LocalActivityManager.java:178)
08-18 15:57:58.308: E/WindowManager(28926):     at android.app.LocalActivityManager.dispatchResume(LocalActivityManager.java:523)
08-18 15:57:58.308: E/WindowManager(28926):     at android.app.ActivityGroup.onResume(ActivityGroup.java:61)
08-18 15:57:58.308: E/WindowManager(28926):     at android.app.Instrumentation.callActivityOnResume(Instrumentation.java:1259)
08-18 15:57:58.308: E/WindowManager(28926):     at android.app.Activity.performResume(Activity.java:5200)
08-18 15:57:58.308: E/WindowManager(28926):     at android.app.ActivityThread.performResumeActivity(ActivityThread.java:2931)
08-18 15:57:58.308: E/WindowManager(28926):     at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:2973)
08-18 15:57:58.308: E/WindowManager(28926):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2408)
08-18 15:57:58.308: E/WindowManager(28926):     at android.app.ActivityThread.access$600(ActivityThread.java:165)
08-18 15:57:58.308: E/WindowManager(28926):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1373)
08-18 15:57:58.308: E/WindowManager(28926):     at android.os.Handler.dispatchMessage(Handler.java:107)
08-18 15:57:58.308: E/WindowManager(28926):     at android.os.Looper.loop(Looper.java:194)
08-18 15:57:58.308: E/WindowManager(28926):     at android.app.ActivityThread.main(ActivityThread.java:5370)
08-18 15:57:58.308: E/WindowManager(28926):     at java.lang.reflect.Method.invokeNative(Native Method)
08-18 15:57:58.308: E/WindowManager(28926):     at java.lang.reflect.Method.invoke(Method.java:525)
08-18 15:57:58.308: E/WindowManager(28926):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:833)
08-18 15:57:58.308: E/WindowManager(28926):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:600)
08-18 15:57:58.308: E/WindowManager(28926):     at dalvik.system.NativeStart.main(Native Method)

以下是我的数据库帮助文件。

package company.profile.app.android;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

public class DataBaseHelperCompany extends SQLiteOpenHelper{

    //The Android's default system path of your application database.
    private static String DB_PATH = "/data/data/company.profile.app.android/databases/";


    private final static String DB_NAME = "db_company";
    public final int DB_VERSION = 1;
    private SQLiteDatabase myDataBase; 

    private final Context myContext;

    private final String TABLE_NAME_PRODUCT = "tbl_product";
    private final String TABLE_ROW_ID_PRODUCT = "id";
    private final String TITLE_PRODUCT = "title_product";
    private final String CATEGORY_PRODUCT = "category_product";
    private final String DESC_PRODUCT = "desc_product";
    private final String IMAGE_PRODUCT = "image_product";

    private final String TABLE_NAME_SERVICE = "tbl_service";
    private final String TABLE_ROW_ID_SERVICE = "id";
    private final String TITLE_SERVICE = "title_service";
    private final String CATEGORY_SERVICE = "category_service";
    private final String DESC_SERVICE = "desc_service";
    private final String IMAGE_SERVICE = "image_service";

    boolean ada = false;
    /**
     * Constructor
     * Takes and keeps a reference of the passed context in order to access to the application assets and resources.
     * @param context
     */
    public DataBaseHelperCompany(Context context) {

        super(context, DB_NAME, null, 1);
        this.myContext = context;
    }   

  /**
     * Creates a empty database on the system and rewrites it with your own database.
     * */
    public void createDataBase() throws IOException{

        boolean dbExist = checkDataBase();
        SQLiteDatabase db_Read = null;

        if(dbExist){
            //Toast.makeText(myContext, "Create Database \n " +
            //      "Database", Toast.LENGTH_SHORT).show();
            //do nothing - database already exist
        }else{

            //By calling this method and empty database will be created into the default system path
               //of your application so we are gonna be able to overwrite that database with our database.
            db_Read = this.getReadableDatabase();
            db_Read.close();

            try {
                //Toast.makeText(myContext, "No Database \n" +
                //      "Call method Copy Database", Toast.LENGTH_SHORT).show();
                copyDataBase();
            } catch (IOException e) {
                throw new Error("Error copying database");
            }
        }

    }

    /**
     * Check if the database already exist to avoid re-copying the file each time you open the application.
     * @return true if it exists, false if it doesn't
     */
    private boolean checkDataBase(){

        SQLiteDatabase checkDB = null;

        try{
            String myPath = DB_PATH + DB_NAME;
            checkDB = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);
            //Toast.makeText(myContext, "Database", Toast.LENGTH_SHORT).show();
        }catch(SQLiteException e){
            //Toast.makeText(myContext, "No Database", Toast.LENGTH_SHORT).show();
            //database does't exist yet.
        }
        if(checkDB != null){
            checkDB.close();
        }

        return checkDB != null ? true : false;
    }

    /**
     * Copies your database from your local assets-folder to the just created empty database in the
     * system folder, from where it can be accessed and handled.
     * This is done by transfering bytestream.
     * */
    private void copyDataBase() throws IOException{
        //Toast.makeText(myContext, "Copy database", Toast.LENGTH_SHORT);

        //Open your local db as the input stream
        InputStream myInput = myContext.getAssets().open(DB_NAME);

        // Path to the just created empty db
        String outFileName = DB_PATH + DB_NAME;

        //Open the empty db as the output stream
        OutputStream myOutput = new FileOutputStream(outFileName);

        //transfer bytes from the inputfile to the outputfile
        byte[] buffer = new byte[1024];
        int length;
        while ((length = myInput.read(buffer))>0){
            myOutput.write(buffer, 0, length);
        }

        //Close the streams
        myOutput.flush();
        myOutput.close();
        myInput.close();

    }

    public void openDataBase() throws SQLException{
        //Toast.makeText(myContext, "Database Open", Toast.LENGTH_SHORT);

        //Open the database
        String myPath = DB_PATH + DB_NAME;
        myDataBase = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READWRITE);
    }

    @Override
    public synchronized void close() {

            if(myDataBase != null)
                myDataBase.close();

            super.close();

    }

    @Override
    public void onCreate(SQLiteDatabase db) {

    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

    }
        // Add your public helper methods to access and get content from the database.
       // You could return cursors by doing "return myDataBase.query(....)" so it'd be easy
       // to you to create adapters for your views.


    public ArrayList<ArrayList<Object>> getAllDataProduct()
    {
        // create an ArrayList that will hold all of the data collected from
        // the database.
        ArrayList<ArrayList<Object>> dataArrays = new ArrayList<ArrayList<Object>>();

        // this is a database call that creates a "cursor" object.
        // the cursor object store the information collected from the
        // database and is used to iterate through the data.
        Cursor cursor = null;
        try
        {
            // ask the database object to create the cursor.
            cursor = myDataBase.query(
                    TABLE_NAME_PRODUCT,
                    new String[]{TABLE_ROW_ID_PRODUCT, TITLE_PRODUCT, DESC_PRODUCT, IMAGE_PRODUCT, CATEGORY_PRODUCT},
                    null,null, null, null, null
            );

            // move the cursor's pointer to position zero.
            cursor.moveToLast();
            // if there is data after the current cursor position, add it
            // to the ArrayList.
            if (!cursor.isBeforeFirst())
            {
                do
                {
                    ArrayList<Object> dataList = new ArrayList<Object>();

                    dataList.add(cursor.getLong(0));
                    dataList.add(cursor.getString(1));
                    dataList.add(cursor.getString(2));
                    dataList.add(cursor.getString(3));
                    dataList.add(cursor.getString(4));
                    dataList.add(cursor.getString(5));
                    dataList.add(cursor.getString(6));
                    dataArrays.add(dataList);
                }
                // move the cursor's pointer up one position.
                while (cursor.moveToPrevious());
            }
            cursor.close();
        }
        catch (SQLException e)
        {
            Log.e("DB Error", e.toString());
            e.printStackTrace();
        }

        // return the ArrayList that holds the data collected from
        // the database.
        return dataArrays;
    }

    public ArrayList<ArrayList<Object>> getAllDataService()
    {
        // create an ArrayList that will hold all of the data collected from
        // the database.
        ArrayList<ArrayList<Object>> dataArrays = new ArrayList<ArrayList<Object>>();

        // this is a database call that creates a "cursor" object.
        // the cursor object store the information collected from the
        // database and is used to iterate through the data.
        Cursor cursor = null;
        try
        {
            // ask the database object to create the cursor.
            cursor = myDataBase.query(
                    TABLE_NAME_SERVICE,
                    new String[]{TABLE_ROW_ID_SERVICE, TITLE_SERVICE, DESC_SERVICE, IMAGE_SERVICE, CATEGORY_SERVICE},
                    null,null, null, null, null
            );

            // move the cursor's pointer to position zero.
            cursor.moveToLast();
            // if there is data after the current cursor position, add it
            // to the ArrayList.
            if (!cursor.isBeforeFirst())
            {
                do
                {
                    ArrayList<Object> dataList = new ArrayList<Object>();

                    dataList.add(cursor.getLong(0));
                    dataList.add(cursor.getString(1));
                    dataList.add(cursor.getString(2));
                    dataList.add(cursor.getString(3));
                    dataList.add(cursor.getString(4));
                    dataList.add(cursor.getString(5));
                    dataList.add(cursor.getString(6));
                    dataList.add(cursor.getString(7));
                    dataArrays.add(dataList);
                }
                // move the cursor's pointer up one position.
                while (cursor.moveToPrevious());
            }
            cursor.close();
        }
        catch (SQLException e)
        {
            Log.e("DB Error", e.toString());
            e.printStackTrace();
        }

        // return the ArrayList that holds the data collected from
        // the database.
        return dataArrays;
    }

Product.java

package company.profile.app.android;

import java.io.IOException;
import java.util.ArrayList;
import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.res.Configuration;
import android.database.SQLException;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.*;
import android.widget.AdapterView.OnItemClickListener;

public class Product extends Activity{
    ListView listProduct;
    ProductAdapter eaListProduct;
    static String[] title, desc, image, category;
    static int [] id;

    Button back;
    Dialog dialog;

    DataBaseHelperCompany myDbHelperCompany;
    ArrayList<ArrayList<Object>> data;

    @Override
    protected void onResume(){
        super.onResume();
        new CheckListData().execute();
        eaListProduct.notifyDataSetChanged();
        eaListProduct.notifyDataSetInvalidated();
        listProduct.invalidateViews();
    }

     public class ProductAdapter extends BaseAdapter {
          private LayoutInflater mInflater;

            public ProductAdapter(Context c) {
                mInflater = LayoutInflater.from(c);
            }

            public int getCount() {
                  return title.length;
            }

            public Object getItem(int position) {
                  return position;
            }

            public long getItemId(int position) {
                  return position;
            }

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

                 ViewHolder holder;
                  if (convertView == null) {
                    convertView = mInflater.inflate(R.layout.row_product, null);
                    holder = new ViewHolder();
                    holder.txtTitleProduct = (TextView) convertView.findViewById(R.id.txtTitleProduct);
                    holder.txtCatProduct = (TextView) convertView.findViewById(R.id.txtCatProduct);
                    holder.ImageProduct = (ImageView) convertView.findViewById(R.id.imgProduct);
                    convertView.setTag(holder);

                  } else{
                      holder = (ViewHolder) convertView.getTag();
                  }
                  holder.txtTitleProduct.setText(title[position]);
                  holder.txtCatProduct.setText(category[position]);

                  String uri = image[position];

                  int imageResource = getResources().getIdentifier(uri, null, getPackageName());
                  Drawable image = getResources().getDrawable(imageResource);
                  holder.ImageProduct.setImageDrawable(image);
                  holder.ImageProduct.setScaleType(ImageView.ScaleType.FIT_XY);

                  //holder.ImageProduct.setImageResource(R.drawable.product1);

                  return convertView;
            }

            public class ViewHolder {
                TextView txtTitleProduct;
                TextView txtCatProduct;
                ImageView ImageProduct;

            }
      }

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.product);
        listProduct = (ListView) findViewById(R.id.listProduct);

      //Check Database
        myDbHelperCompany= new DataBaseHelperCompany(this);
        try {
                myDbHelperCompany.createDataBase();
            }catch(IOException ioe){
                throw new Error("Unable to create database");
            }
        try{
                myDbHelperCompany.openDataBase();
            }catch(SQLException sqle){
                throw sqle;
            }

        eaListProduct = new ProductAdapter(this);

        listProduct.setFastScrollEnabled(true);  

        /*ColorDrawable divcolor = new ColorDrawable(Color.DKGRAY);
        listProduct.setDivider(divcolor);
        listProduct.setDividerHeight(4);
        */

        listProduct.setOnItemClickListener(new OnItemClickListener() {
            public void onItemClick(AdapterView<?> parent, View view,
                    int position, long idn) {
                 dialog = new Dialog(Product.this);
                 dialog.setContentView(R.layout.dialog_product);
                 dialog.setTitle("Item Descriptions");
                 dialog.setCancelable(true);

                 //set up text
                 TextView text_title = (TextView) dialog.findViewById(R.id.txt_title_product);
                 text_title.setText(title[position]);

               //set up text
                 TextView text_cat = (TextView) dialog.findViewById(R.id.txt_cat_product);
                 text_cat.setText(category[position]);

                 //set up text
                 TextView text_desc = (TextView) dialog.findViewById(R.id.txt_desc_product);
                 text_desc.setText(desc[position]);

                 //set up image view
                 ImageView img = (ImageView) dialog.findViewById(R.id.ImageProduct);
                 String uri = image[position];
                 int imageResource = getResources().getIdentifier(uri, null, getPackageName());
                 Drawable image = getResources().getDrawable(imageResource);
                 img.setImageDrawable(image);
                 img.setScaleType(ImageView.ScaleType.FIT_XY);

                 //set up button
                 Button button = (Button) dialog.findViewById(R.id.btnClose);
                 button.setOnClickListener(new OnClickListener() {
                     public void onClick(View v) {
                         dialog.dismiss();
                     }
                 });
                 //now that the dialog is set up, it's time to show it    
                 dialog.show();
            }
        });

        back = (Button) findViewById(R.id.btnBack);

        back.setOnClickListener(new View.OnClickListener() {

            public void onClick(View arg0) {
                // TODO Auto-generated method stub
                finish();
            }
        });
    }

    @Override
    public void onConfigurationChanged(final Configuration newConfig)
    {
        // Ignore orientation change to keep activity from restarting
        super.onConfigurationChanged(newConfig);
    }

    //this asyntask for display all data
    public class CheckListData extends AsyncTask<Void, Void, Void> {
        ProgressDialog dialog;

        @Override
         protected void onPreExecute() {
          // TODO Auto-generated method stub
             dialog= ProgressDialog.show(Product.this, "", 
                     "Read data..., please wait...", true);

         }

         @Override
         protected Void doInBackground(Void... params) {
          // TODO Auto-generated method stub
             getAllProduct();
          return null;
         }

        @Override
        protected void onPostExecute(Void result) {
            // TODO Auto-generated method stub
            listProduct.setAdapter(eaListProduct);
            dialog.dismiss();           
        }
    }

    private void getAllProduct(){
        data = myDbHelperCompany.getAllDataProduct();

        id = new int[data.size()];
        title = new String[data.size()];
        desc = new String[data.size()];
        image = new String[data.size()];
        category = new String[data.size()];

        for(int position = 0; position < data.size(); position++){
            ArrayList<Object> row = data.get(position);

            id[position] = Integer.parseInt(row.get(0).toString());
            title[position] = row.get(1).toString();
            desc[position] = row.get(2).toString();
            image[position] = row.get(3).toString();
            category[position] = row.get(4).toString();
        }
    }
}

1 个答案:

答案 0 :(得分:0)

更改您的DatabseHelper类,如:

if(cursor != null){
    if (cursor.moveToFirst()){
        do{
            ArrayList<Object> dataList = new ArrayList<Object>();

            dataList.add(cursor.getLong(0));
            dataList.add(cursor.getString(1));
            dataList.add(cursor.getString(2));
            dataList.add(cursor.getString(3));
            dataList.add(cursor.getString(4));
            dataList.add(cursor.getString(5)); 
            dataList.add(cursor.getString(6)); 
            dataArrays.add(dataList);
        }
        while (cursor.moveToNext());
    }
}
cursor.close;

修改

dataList.add移除最后两行getAllDataProduct()行,从getAllDataService()方法移除最后三行。