0

我有一个活动,它显示用户信息并使用图像编辑用户信息。当我第一次尝试更改图像时,活动恢复。如果我第二次更改图像,活动不会恢复,它会给出一个 staledata 异常,下面是代码和日志。

日志:

01-03 17:44:23.539: E/AndroidRuntime(30754): FATAL EXCEPTION: main
01-03 17:44:23.539: E/AndroidRuntime(30754): java.lang.RuntimeException: Unable to resume activity {com.globalnest.event/com.globalnest.event.LeadDetails}: android.database.StaleDataException: Attempted to access a cursor after it has been closed.
01-03 17:44:23.539: E/AndroidRuntime(30754):    at android.app.ActivityThread.performResumeActivity(ActivityThread.java:2471)
01-03 17:44:23.539: E/AndroidRuntime(30754):    at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:2499)
01-03 17:44:23.539: E/AndroidRuntime(30754):    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1184)
01-03 17:44:23.539: E/AndroidRuntime(30754):    at android.os.Handler.dispatchMessage(Handler.java:99)
01-03 17:44:23.539: E/AndroidRuntime(30754):    at android.os.Looper.loop(Looper.java:137)
01-03 17:44:23.539: E/AndroidRuntime(30754):    at android.app.ActivityThread.main(ActivityThread.java:4448)
01-03 17:44:23.539: E/AndroidRuntime(30754):    at java.lang.reflect.Method.invokeNative(Native Method)
01-03 17:44:23.539: E/AndroidRuntime(30754):    at java.lang.reflect.Method.invoke(Method.java:511)
01-03 17:44:23.539: E/AndroidRuntime(30754):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:823)
01-03 17:44:23.539: E/AndroidRuntime(30754):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:590)
01-03 17:44:23.539: E/AndroidRuntime(30754):    at dalvik.system.NativeStart.main(Native Method)
01-03 17:44:23.539: E/AndroidRuntime(30754): Caused by: android.database.StaleDataException: Attempted to access a cursor after it has been closed.
01-03 17:44:23.539: E/AndroidRuntime(30754):    at android.database.BulkCursorToCursorAdaptor.throwIfCursorIsClosed(BulkCursorToCursorAdaptor.java:75)
01-03 17:44:23.539: E/AndroidRuntime(30754):    at android.database.BulkCursorToCursorAdaptor.requery(BulkCursorToCursorAdaptor.java:144)
01-03 17:44:23.539: E/AndroidRuntime(30754):    at android.database.CursorWrapper.requery(CursorWrapper.java:186)
01-03 17:44:23.539: E/AndroidRuntime(30754):    at android.app.Activity.performRestart(Activity.java:4505)
01-03 17:44:23.539: E/AndroidRuntime(30754):    at android.app.Activity.performResume(Activity.java:4531)
01-03 17:44:23.539: E/AndroidRuntime(30754):    at android.app.ActivityThread.performResumeActivity(ActivityThread.java:2461)
01-03 17:44:23.539: E/AndroidRuntime(30754):    ... 10 more

源代码:

            setcur=db.rawQuery("select * from LeadDetails where QR_ID='"+ATID+"' and EventID='"+EventID+"' and UserID='"+dbUserID+"'", null);
            this.startManagingCursor(setcur);
            if(setcur!=null&&setcur.getCount()!=0){ 


                setcur.moveToFirst();

                LeadID=setcur.getString(setcur.getColumnIndex("_id"));
                fname.setText(setcur.getString(setcur.getColumnIndex("FirstName")));
                lname.setText(setcur.getString(setcur.getColumnIndex("LastName")));
                company.setText(setcur.getString(setcur.getColumnIndex("Company")));
                pno.setText(setcur.getString((setcur.getColumnIndex("PhoneNumber"))));
                email.setText(setcur.getString(setcur.getColumnIndex("EmailID")));
                city.setText(setcur.getString(setcur.getColumnIndex("City")));
                state.setText(setcur.getString(setcur.getColumnIndex("State")));
                notes.setText(setcur.getString(setcur.getColumnIndex("Notes")));

                String fwldateandtime=setcur.getString(setcur.getColumnIndex("FollowUpDate"));
                System.out.println("the date is "+fwldateandtime);

                if(fwldateandtime.equals("null")||fwldateandtime.equals(" ") ||fwldateandtime.equals("") ){
                    fwldate.setText("");

                    fwltime.setText("");

                }else{

                    String[] temp = fwldateandtime.split(" ");
                    System.out.println("the temp is "+temp);

                    SimpleDateFormat f1 = new SimpleDateFormat("hh:mm a");
                    SimpleDateFormat f2 = new SimpleDateFormat("hh:mm:ss");
                    SimpleDateFormat f4 = new SimpleDateFormat("yyyy-MM-dd");
                    SimpleDateFormat f3 = new SimpleDateFormat("yyyy-MM-dd"); 

                    String time="",date="";

                    try {

                        Date d1 = f4.parse(temp[0]);
                        date = f3.format(d1);

                        if(temp[1].equals("00:00:00")){
                            time="";
                        }else{
                            Date d = f2.parse(temp[1]);
                            time = f1.format(d); 
                            System.out.println("The time is "+time+" the object is "+d+"the date is to be"+date+"the temp"+temp[0]);

                        }

                        fwltime.setText(time);
                        fwldate.setText(date);
                    } catch (ParseException e) {
                // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
            fwltime.setText(time);
            fwldate.setText(date);

        }

        String values = email.getText().toString();
        System.out.println("the values is "+values);

        if(values.equals("")||values.equals("null")){
            email.setEnabled(true);
        }else{
            email.setEnabled(false);
        }


        title.setText(setcur.getString(setcur.getColumnIndex("Title")));

        ImageView iv=(ImageView) findViewById(R.id.leadimage);
        String imgloc=setcur.getString(setcur.getColumnIndex("ImageURL"));
        ftypes=NullChecker(setcur.getString(setcur.getColumnIndex("FollowUPTypes")));
        types="";
        System.out.println("the followuptypes are"+ftypes);
        SetImage();


        String rate=setcur.getString(setcur.getColumnIndex("Rating"));

        float f;
        if(rate.equals("null")){
             f = Float.valueOf("0").floatValue();
        }else
            f = Float.valueOf(rate).floatValue();


        System.out.println("the values for rating is "+f);
        rating.setRating(f);
        String sa1=setcur.getString(setcur.getColumnIndex("SurveyQ1Answer"));
        String sa=setcur.getString(setcur.getColumnIndex("SurveyQ2Answer"));
        String sa3=setcur.getString(setcur.getColumnIndex("SurveyQ3Answer"));
        }else{
            email.setEnabled(true);
        }

        //c.close();
            setcur1 = db.rawQuery("select * from EventDetails where EventID='"+EventID+"'", null);
        this.startManagingCursor(setcur1);
        setcur1.moveToFirst();
        TextView ename=(TextView) findViewById(R.id.textView1);
        ename.setText(setcur1.getString(setcur1.getColumnIndex("EventName")));
        //c1.close();

        //db.close();
    }

/// 设置图像方法

public void SetImage(){

            String Imagedata=null;
             StringBuilder stringBuilder = new StringBuilder();
             FileInputStream fin;
                try {

                    InputStream isr = openFileInput(ATID+dbUserID);

                    InputStreamReader inputStreamReader = new InputStreamReader(isr);

                     BufferedReader inRd = new BufferedReader(inputStreamReader);

                     String receiveString = "";


                    while ( (receiveString = inRd.readLine()) != null ) {

                        stringBuilder.append(receiveString);
                     }
                    System.out.println("the base64 value is "+stringBuilder);



                    byte[] decodedString = Base64.decode(stringBuilder.toString(), Base64.DEFAULT);
                    Bitmap decodedByte = BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length);                 
                    LeadImage.setImageBitmap(decodedByte);

                } catch (FileNotFoundException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                if(stringBuilder.toString()==null||stringBuilder.toString().equals("null")||stringBuilder.toString().equals("")){ 
                    LeadImage.setImageResource(R.drawable.durga);
                } 

        }

// ALert show 当用户点击图片时显示警报

 public void AlertShow(){

          final String [] items         = new String [] {"Take from camera", "Select from gallery"};                
            ArrayAdapter<String> adapter    = new ArrayAdapter<String> (this, android.R.layout.select_dialog_item,items);
            AlertDialog.Builder builder     = new AlertDialog.Builder(this);

            builder.setTitle("Select Image");
            builder.setAdapter( adapter, new DialogInterface.OnClickListener() {
                public void onClick( DialogInterface dialog, int item ) { //pick from camera
                    if (item == 0) {
                        Intent intent    = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

                        mImageCaptureUri = Uri.fromFile(new File(Environment.getExternalStorageDirectory(),
                                           "tmp_avatar_" + String.valueOf(System.currentTimeMillis()) + ".jpg"));

                        System.out.println("the values are "+mImageCaptureUri);
                        intent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, mImageCaptureUri);


                        try {
                            intent.putExtra("return-data", true);

                            startActivityForResult(intent, PICK_FROM_CAMERA);
                        } catch (ActivityNotFoundException e) {
                            e.printStackTrace();
                        }
                    } else { 
                        Intent intent = new Intent();

                        intent.setType("image/*");
                        intent.setAction(Intent.ACTION_GET_CONTENT);

                        startActivityForResult(Intent.createChooser(intent, "Complete action using"), PICK_FROM_FILE);
                    }
                }
            });

            final AlertDialog dialog = builder.create();
            dialog.show();
     }

// 之后的结果

 @Override
        protected void onActivityResult(int requestCode, int resultCode, Intent data) {
            if (resultCode != RESULT_OK) return;

            switch (requestCode) {
                case PICK_FROM_CAMERA:
                    doCrop();

                    break;

                case PICK_FROM_FILE:  
                    mImageCaptureUri = data.getData();

                    doCrop();

                    break;          

                case CROP_FROM_CAMERA:          
                    Bundle extras = data.getExtras();

                    if (extras != null) {               
                        Bitmap photo = extras.getParcelable("data");

                        LeadImage.setImageBitmap(photo);


                        ByteArrayOutputStream blob = new ByteArrayOutputStream();
                        photo.compress(CompressFormat.JPEG, 100 , blob);
                        byte[] bitmapdata = blob.toByteArray();

                        encodedImage = Base64.encodeToString(bitmapdata, Base64.DEFAULT);

                        FileOutputStream fos;
                        try {
                            fos = openFileOutput(ATID+dbUserID, Context.MODE_PRIVATE);
                            fos.write(encodedImage.getBytes());
                            fos.close();
                            System.out.println("the file name is "+ATID);

                        } catch (FileNotFoundException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        } catch (IOException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }



                    }

                    File f = new File(mImageCaptureUri.getPath());            
                    System.out.println("the path is "+f.getAbsolutePath());
                    f.delete();

                    int id=getLastImageId();
                    removeImage(id);

                    break;

            }
        }

//裁剪方法

 private void doCrop() {
            final ArrayList<CropOption> cropOptions = new ArrayList<CropOption>();

            Intent intent = new Intent("com.android.camera.action.CROP");
            intent.setType("image/*");

            List<ResolveInfo> list = getPackageManager().queryIntentActivities( intent, 0 );

            int size = list.size();

            if (size == 0) {            
                Toast.makeText(this, "Can not find image crop app", Toast.LENGTH_SHORT).show();

                return;
            } else {

                intent.setData(mImageCaptureUri); 

                intent.putExtra("outputX", 90);
                intent.putExtra("outputY", 90);
                intent.putExtra("aspectX", 1);
                intent.putExtra("aspectY", 1);
                intent.putExtra("scale", true);
                intent.putExtra("return-data", true);

                if (size == 1) {
                    Intent i        = new Intent(intent);
                    ResolveInfo res = list.get(0);

                    i.setComponent( new ComponentName(res.activityInfo.packageName, res.activityInfo.name));

                    startActivityForResult(i, CROP_FROM_CAMERA);
                } else {
                    for (ResolveInfo res : list) {
                        final CropOption co = new CropOption();

                        co.title    = getPackageManager().getApplicationLabel(res.activityInfo.applicationInfo);
                        co.icon     = getPackageManager().getApplicationIcon(res.activityInfo.applicationInfo);
                        co.appIntent= new Intent(intent);

                        co.appIntent.setComponent( new ComponentName(res.activityInfo.packageName, res.activityInfo.name));

                        cropOptions.add(co);
                    }

                    CropOptionAdapter adapter = new CropOptionAdapter(getApplicationContext(), cropOptions);

                    AlertDialog.Builder builder = new AlertDialog.Builder(this);
                    builder.setTitle("Choose Crop App");
                    builder.setAdapter( adapter, new DialogInterface.OnClickListener() {
                        public void onClick( DialogInterface dialog, int item ) {
                            startActivityForResult( cropOptions.get(item).appIntent, CROP_FROM_CAMERA);
                        }
                    });

                    builder.setOnCancelListener( new DialogInterface.OnCancelListener() {
                        @Override
                        public void onCancel( DialogInterface dialog ) {

                            if (mImageCaptureUri != null ) {

                                int id=getLastImageId();
                                removeImage(id);

                                getContentResolver().delete(mImageCaptureUri, null, null );
                                mImageCaptureUri = null;
                            }
                        }
                    } );

                    AlertDialog alert = builder.create();

                    alert.show();
                }
            }
        }
4

0 回答 0