从未在数据库'/ data

时间:2015-10-17 05:24:27

标签: android

我在启动应用程序时一次又一次地出现 close()从未明确调用的错误。我不明白我在数据库中的位置错误。

这是我的代码

 @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        mLayout = (MainLayout) this.getLayoutInflater().inflate(R.layout.all_post, null);
        setContentView(mLayout);
        dbhelper = new MyDbHelper(this);
        imgLeftmenu = (ImageView) findViewById(R.id.imgLeftMenu);
        imgSearch = (ImageView) findViewById(R.id.imgSearch);
        imgAdd = (ImageView) findViewById(R.id.imgAdd);
        listView = (ListView) findViewById(R.id.listview_AllPost);
        populateList();

        new GetgetDoenLoaddata().execute();
        SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
        str_Authentication_Token = sharedPreferences.getString("strAuthentication_Token", "");
        str_UserId = sharedPreferences.getString("strUserId", "");
        Log.e("Prefs", "str_Authentication_Token = " + str_Authentication_Token + "Prefs str_UserId = " + str_UserId);

        SQLiteDatabase db = dbhelper.getWritableDatabase();
        String query = "select * from SyncTime where WebServiceEntity ='" + "AllPost_ActivityList" + "'";
        Cursor cursor = db.rawQuery(query, null);
        while (cursor.moveToNext()) {
            strSyncTime = cursor.getString(cursor.getColumnIndex("SyncTime"));
            strSyncTime1 = strSyncTime.replaceAll(" ", "%20");
            Log.e("strSyncTime ", " = " + strSyncTime1);
        }
        cursor.close();

        Intent intent = getIntent();
        String newAudioFile = intent.getStringExtra("newAudioFile");
        Log.e("newAudioFile ", " = " + newAudioFile);

        imgAdd.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent i = new Intent(AllPosts_Page.this, AddPost.class);
                startActivity(i);
            }
        });

        imgSearch.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
            }
        });
    }

    private void populateList() {
        descArray.clear();

        List<All_Post> allDesc = dbhelper.getAllDescriptions();
        for (All_Post all_Post : allDesc) {
            descArray.add(all_Post);
        }

        if (adapter == null) {
            adapter = new MyListAdapter(this, R.layout.all_post_row, descArray);
            listView.setAdapter(adapter);
            Log.e("Single Entry ", " !!!! ");
        } else if (adapter != null) {
            adapter.notifyDataSetChanged();
            Log.e("Double Entry ", " !!!! ");
            adapter = new MyListAdapter(this, R.layout.all_post_row, descArray);
            listView.setAdapter(adapter);
        }

    }

    @Override
    protected void onResume() {
        super.onResume();
        populateList();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (dbhelper != null) {
            dbhelper.close();
        }
    }

    public void getDoenLoaddata() {
        dbhelper = new MyDbHelper(this);
        SQLiteDatabase db1 = dbhelper.getWritableDatabase();

        Cursor cursor = db1.rawQuery("select * from ActivityObjectList", null);

        if (cursor.moveToFirst()) {
            do {
                imageName = cursor.getString(cursor.getColumnIndex("imageaudioPath"));
                String strDownLoadStatus = cursor.getString(cursor.getColumnIndex("DownLoad_Status"));

                if (strDownLoadStatus.equalsIgnoreCase("0")) {
                    if (imageName.endsWith(mp3_Pattern)) {
                        str_DownLoadUrl = namespace + "/DownloadFile/FileName/" + imageName;
                        DownLoadAudioFile(str_DownLoadUrl, imageName);
                        strDownLoadStatus = "1";
                        dbhelper.update_DownLoadStatus(imageName, strDownLoadStatus);
                    }
                    if (imageName.endsWith(png_Pattern) || imageName.endsWith(jpg_pattern) || imageName.endsWith(bmp_pattern) || imageName.endsWith(gif_pattern) || imageName.endsWith(jpeg_pattern)) {
                        str_DownLoadUrl = namespace + "/DownloadFile/FileName/" + imageName;
                        download_PngFile(str_DownLoadUrl, imageName);
                        strDownLoadStatus = "1";
                        dbhelper.update_DownLoadStatus(imageName, strDownLoadStatus);
                    }
                }
            }
            while (cursor.moveToNext());
        }
        cursor.close();
        //db1.close();
    }

    private void initiatePopupWindow() {
        try {
            Log.e("string_ActivityId ", " = " + string_ActivityId);
            dbhelper = new MyDbHelper(this);
            SQLiteDatabase db = dbhelper.getReadableDatabase();
            Cursor cursor1 = db.rawQuery("select * from ALL_Post where ActivityId " + "= ? ", new String[]{string_ActivityId});

            if (cursor1.moveToFirst()) {

                struserId1 = cursor1.getString(cursor1.getColumnIndex("UserId"));
                strobjectId1 = cursor1.getString(cursor1.getColumnIndex("VesselId"));
                Log.e("initiatePopupWindow  ", "onCameraclick strobjectId1 = " + strobjectId1);
                Log.e("initiatePopupWindow ", "onCameraclickt struserId1 = " + struserId1);

            }
            cursor1.close();
            db.close();

            LayoutInflater inflater = (LayoutInflater) AllPosts_Page.this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            View layout = inflater.inflate(R.layout.camera_popup, (ViewGroup) findViewById(R.id.popup_element));
            pwindo = new PopupWindow(layout, 600, 380, true);
            pwindo.showAtLocation(layout, Gravity.BOTTOM, 0, 0);
            pwindo.setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT));

            btnCamera = (Button) layout.findViewById(R.id.button_Camera);
            btnCamera.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
                    startActivityForResult(cameraIntent, CAMERA_REQUEST);
                }
            });

            btnGallery = (Button) layout.findViewById(R.id.button_Gallery);
            btnGallery.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {

                    Intent galleryIntent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                    startActivityForResult(galleryIntent, RESULT_LOAD_IMG);
                }
            });

            cancelPopUp = (Button) layout.findViewById(R.id.btnCancelCamera);
            cancelPopUp.setOnClickListener(cancel_button_click_listener);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    class MyListAdapter extends ArrayAdapter<All_Post> {
        Context context;
        int layoutResourceId;

        /**/
        ArrayList<All_Post> data = new ArrayList<All_Post>();

        public MyListAdapter(Context context, int layoutResourceId, ArrayList<All_Post> data) {
            super(context, layoutResourceId, data);
            this.layoutResourceId = layoutResourceId;
            this.context = context;
            this.data = data;
        }

        @Override
        public int getCount() {
            return data.size();
        }

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

        @Override
        public View getView(final int position, View convertView, ViewGroup parent) {
            View row = convertView;
            final Holder holder;
            if (row == null) {
                LayoutInflater vi;
                vi = LayoutInflater.from(getContext());
                row = vi.inflate(R.layout.all_post_row, null);
                holder = new Holder();

                holder.text_ActivityId = (TextView) row.findViewById(R.id.textActivityId);
                holder.text_InspectorName = (TextView) row.findViewById(R.id.textInspectorName);
                holder.text_SpChar = (TextView) row.findViewById(R.id.textSpChar);
                holder.text_Notation = (TextView) row.findViewById(R.id.textNotation);
                holder.txtViewDate = (TextView) row.findViewById(R.id.txt_Date);
                holder.txtInitialLetter = (TextView) row.findViewById(R.id.txt_InitialLetter);
                holder.txtRemark = (TextView) row.findViewById(R.id.textRemark);

                holder.imgBtn_FollowUp = (ImageView) row.findViewById(R.id.imgButton_FoloowUp);
                holder.imgBtn_RateEquipMent = (ImageView) row.findViewById(R.id.imgButtonRateEquipment);
                holder.imgBtn_Camera = (ImageView) row.findViewById(R.id.imgButton_Camera);
                holder.imgBtn_Audio = (ImageView) row.findViewById(R.id.imgButton_RecordAudio);

                holder.horizontalScrollView = (HorizontalScrollView) row.findViewById(R.id.hlist);
                holder.lLinearLayout = (LinearLayout) row.findViewById(R.id.innerlay);

                row.setTag(holder);
            } else {
                holder = (Holder) row.getTag();
            }

            final All_Post all_Post = data.get(position);
            holder.text_ActivityId.setText(all_Post.getStrActivityId());
            holder.text_InspectorName.setText(all_Post.getStringInspectorname());
            String typenameRGN = all_Post.getStrShortName();
            Log.e("typenameRGN ", " = " + typenameRGN);
            holder.txtInitialLetter.setText(typenameRGN);

            if (holder.txtInitialLetter.getText().toString().equals("R")) {
                holder.txtInitialLetter.setBackgroundResource(R.drawable.red_circle_shape);

            }
            if (holder.txtInitialLetter.getText().toString().equals("G")) {

                holder.txtInitialLetter.setBackgroundResource(R.drawable.green_circle_shape);
            }
            if (holder.txtInitialLetter.getText().toString().equals("N")) {

                holder.txtInitialLetter.setBackgroundResource(R.drawable.blue_circle_shape);
            }


            holder.txtRemark.setText(all_Post.getStrRemark());
            holder.text_Notation.setText(all_Post.getStrNotationNo());
            String strtextNotation = holder.text_Notation.getText().toString().trim();
            Log.e("strtextNotation ", " = " + strtextNotation);

            holder.txtViewDate.setText(all_Post.getActiondate());

            strListItem_ActivityId = all_Post.getStrActivityId();
            Log.e("strListItem_ActivityId ", " = " + strListItem_ActivityId);


            dbhelper = new MyDbHelper(AllPosts_Page.this);
            SQLiteDatabase db = dbhelper.getReadableDatabase();
            Cursor cursor = db.rawQuery("select * from ActivityObjectList where activityId " + "= ? ", new String[]{strListItem_ActivityId});
            imageArray.clear();
            if (cursor.moveToFirst()) {
                do {
                    String imagePath = cursor.getString(cursor.getColumnIndex("imageaudioPath"));
                    imageArray.add(imagePath);
                }
                while (cursor.moveToNext());
            }
            cursor.close();
            //db.close();

            //OnClickListener for camera button in the List
            holder.imgBtn_Camera.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    string_ActivityId = all_Post.getStrActivityId();
                    initiatePopupWindow();
                }
            });


            final String actid = all_Post.getStrActivityId();
            dbhelper = new MyDbHelper(context);
            db = dbhelper.getReadableDatabase();
            Cursor cursor1 = db.rawQuery("select * from ALL_Post where activityId ='" + actid + "'", null);
            if (cursor1.moveToFirst()) {
                do {

                    String strStarFlag = cursor1.getString(cursor1.getColumnIndex("StarFlag"));
                    Log.e("strStarFlag ", " is = " + strStarFlag);

                    if (strStarFlag.equals("0")) {
                        holder.imgBtn_RateEquipMent.setImageResource(R.drawable.stargrey_new);
                    } else if (strStarFlag.equals("1")) {
                        holder.imgBtn_RateEquipMent.setImageResource(R.drawable.yellow_star);
                    }
                }
                while (cursor1.moveToNext());

            }
            cursor1.close();
            db.close();
            return row;
        }

    }

    private class GetgetDoenLoaddata extends AsyncTask<Void, Void, Void> {

        @Override
        protected Void doInBackground(Void... arg0) {
            getDoenLoaddata();
            return null;
        }
    }
}

这是我的logcat

  

E / SQLiteDatabase:从未在数据库上显式调用close()   '/data/data/com.example.tazeen.classnkk/databases/ClassNKK'           android.database.sqlite.DatabaseObjectNotClosedException:应用程序没有关闭光标或数据库对象   在这里开了                   在android.database.sqlite.SQLiteDatabase。(SQLiteDatabase.java:1943)                   在android.database.sqlite.SQLiteDatabase.openDatabase(SQLiteDatabase.java:1007)                   在android.database.sqlite.SQLiteDatabase.openDatabase(SQLiteDatabase.java:986)                   在android.database.sqlite.SQLiteDatabase.openOrCreateDatabase(SQLiteDatabase.java:1051)                   在android.app.ContextImpl.openOrCreateDatabase(ContextImpl.java:770)                   在android.content.ContextWrapper.openOrCreateDatabase(ContextWrapper.java:221)                   在android.database.sqlite.SQLiteOpenHelper.getWritableDatabase(SQLiteOpenHelper.java:157)                   在android.database.sqlite.SQLiteOpenHelper.getReadableDatabase(SQLiteOpenHelper.java:231)                   at com.example.tazeen.classnkk.AllPosts_Page $ MyListAdapter.getView(AllPosts_Page.java:1225)                   在android.widget.AbsListView.obtainView(AbsListView.java:2033)                   在android.widget.ListView.makeAndAddView(ListView.java:1772)                   在android.widget.ListView.fillDown(ListView.java:672)                   在android.widget.ListView.fillGap(ListView.java:636)                   在android.widget.AbsListView.trackMotionScroll(AbsListView.java:4546)                   在android.widget.AbsListView $ FlingRunnable.run(AbsListView.java:3813)                   在android.os.Handler.handleCallback(Handler.java:605)                   在android.os.Handler.dispatchMessage(Handler.java:92)                   在android.os.Looper.loop(Looper.java:137)                   在android.app.ActivityThread.main(ActivityThread.java:4340)                   at java.lang.reflect.Method.invokeNative(Native Method)                   在java.lang.reflect.Method.invoke(Method.java:511)                   在com.android.internal.os.ZygoteInit $ MethodAndArgsCaller.run(ZygoteInit.java:784)                   在com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)                   at dalvik.system.NativeStart.main(Native Method)       10-17 10:31:47.927 1242-1251 /? E / System:终结器抛出的未捕获异常       10-17 10:31:47.927 1242-1251 /? E / System:java.lang.IllegalStateException:没有数据库锁!                   在android.database.sqlite.SQLiteDatabase.verifyLockOwner(SQLiteDatabase.java:2090)                   在android.database.sqlite.SQLiteDatabase $ 1.entryRemoved(SQLiteDatabase.java:2182)                   在android.database.sqlite.SQLiteDatabase $ 1.entryRemoved(SQLiteDatabase.java:2178)                   在android.util.LruCache.trimToSize(LruCache.java:197)                   在android.util.LruCache.evictAll(LruCache.java:285)                   在android.database.sqlite.SQLiteDatabase.deallocCachedSqlStatements(SQLiteDatabase.java:2143)                   在android.database.sqlite.SQLiteDatabase.closeClosable(SQLiteDatabase.java:1126)                   在android.database.sqlite.SQLiteDatabase.finalize(SQLiteDatabase.java:1914)                   在java.lang.Daemons $ FinalizerDaemon.doFinalize(Daemons.java:182)                   在java.lang.Daemons $ FinalizerDaemon.run(Daemons.java:168)                   在java.lang.Thread.run(Thread.java:856)

2 个答案:

答案 0 :(得分:1)

所以在看到你的代码之后,我将建议一种不同的方法,即我说的第一个方法,你应该在每次通话后close()

我在您的代码中看到了许多问题,以下是一些建议:

  • 你为什么多次dbhelper = new MyDbHelper(this);?您只应在onCreate
  • 中执行此操作一次
  • 您也可以在SQLiteDatabase db中创建一个成员变量db= dbhelper.getWritableDatabase();并执行onCreate
  • db.close()方法之外,删除对onDestroy()的所有其他来电。
  • 删除对dbhelper.getReadableDatabase();dbhelper.getWritableDatabase();的所有来电,因为您已经拥有db方法中的实例onCreate,您可以在活动的任何位置使用该实例

基本上我想说的是你只需在writable中获取onCreate数据库实例一次,然后在onDestroy中关闭它。

答案 1 :(得分:1)

你的logcat会抛出什么:

  

android.database.sqlite.DatabaseObjectNotClosedException:应用程序   没有关闭在这里打开的游标或数据库对象   android.database.sqlite.SQLiteDatabase。

无需评论db.close()。启用此功能:
Android error - close() was never explicitly called on database

https://developer.android.com/reference/android/database/sqlite/SQLiteOpenHelper.html