Android - 无法从匿名调用方法

时间:2015-10-31 11:14:39

标签: java android parse-platform

我正面临着一个星期无法解决的问题。所以,我想要做的是将图像保存到内部存储器中,获取其URI并将其保存到SQLite DB中。我的问题是我无法从匿名调用方法"完成"获取URI。我无法重写它,因为我使用Parse API将ParseFile转换为Image。代码如下:

public class DataFetch extends IntentService {

public final String LOG_TAG = DataFetch.class.getSimpleName();
private TestUri mImageUri;

public DataFetch() {
    super("UriTest");
}

@Override
protected void onHandleIntent(Intent intent) {
    //Set up background task here
    try {
        // Locate the class table named "Test_Images" in Parse.com
        ParseQuery<ParseObject> queryTest = new ParseQuery<ParseObject>(
                "Test_Images");
        List<ParseObject> testData = queryTest.find();

        //Insert the new test information into the database
        Vector<ContentValues> cVVector = new Vector<ContentValues>(testData.size());

        for(ParseObject object : testData) {
            // Create a ContentValues object to hold data which would be added to DB.
            final ContentValues testDataValues = new ContentValues();
            ParseFile image = (ParseFile)object.get("image");
            final String imageName = object.getString("name");

            //Log.i("data_fetch","before inner class: "+mImageUri.getUri());
            if(image != null){
                mImageUri = new TestUri();
                image.getDataInBackground(new GetDataCallback() {
                    public void done(byte[] data, ParseException e) {
                        if (e == null) {
                            Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);
                            Log.d(LOG_TAG,"Bitmap straight after creation: "+bitmap);
                            if(bitmap != null){
                                //Set image of the event in place
                                mImageUri.setUri(saveImageToInternalStorage(bitmap, imageName));
                                Log.i("data_fetch", "inner class: " + mImageUri.getUri());
                                Log.d(LOG_TAG, "Bitmap straight after processing: " + bitmap + " and its length is " + data.length);
                            }
                            else {
                                Log.d(LOG_TAG, "file null?");
                                mImageUri.setUri("nothing_here");
                            }
                        }
                        else
                            Log.d(LOG_TAG, "ParseFile ParseException: " + e.toString());
                    }
                });
            }
            else {
                Log.d(LOG_TAG, "ParseFile is null");
            }
            Log.i("data_fetch","after inner class: "+mImageUri.getUri());

            // Insert the name and id of the data.
            testDataValues.put(DataTestContract.TestFieldEntry.COL_NAME, imageName);
            Log.i("data_fetch", "name: " + object.getString("name"));
            testDataValues.put(DataTestContract.TestFieldEntry.COL_CAT, object.getString("Id"));
            Log.i("data_fetch", "id: " + object.getString("Id"));
            // Insert image URI into ContentValues object.
            testDataValues.put(DataTestContract.TestFieldEntry.COL_URI, mImageUri.getUri());
            Log.i("data_fetch","image uri: "+mImageUri.getUri());
            cVVector.add(testDataValues);
        }
        //Add test data to database
        int inserted = 0;
        int deleted = 0;
        // add to database
        if (cVVector.size() > 0) {
            ContentValues[] cvArray = new ContentValues[cVVector.size()];
            cVVector.toArray(cvArray);
            for(int i=0;i<cvArray.length;++i){
                Log.i("data_fetch","data passed to cvArray: "+cVVector.get(i));
                Log.i("data_fetch", "data to be inserted: " + cvArray[i]);
            }
            getApplicationContext().getContentResolver().bulkInsert(DataTestContract.TestFieldEntry.CONTENT_URI, cvArray);
            //Delete old data from DB

        }

        Log.d(LOG_TAG, "Sync Complete. " + cVVector.size() + " Inserted. Deleted:"+deleted);

    } catch (ParseException e) {
        Log.e("Error", e.getMessage());
        e.printStackTrace();
    }
}

private String saveImageToInternalStorage(Bitmap image, String name) {
    ContextWrapper cw = new ContextWrapper(getApplicationContext());
    // path to /data/data/yourapp/app_data/imageDir
    File directory = cw.getDir("imageDir", Context.MODE_PRIVATE);
    // Create imageDir
    name.trim();
    File mypath=new File(directory, name+".jpg");

    FileOutputStream fos = null;
    try {

        fos = new FileOutputStream(mypath);

        // Use the compress method on the BitMap object to write image to the OutputStream
        image.compress(Bitmap.CompressFormat.PNG, 100, fos);
        fos.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
    return mypath.getAbsolutePath();
}

public static class AlarmReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        Intent sendIntent = new Intent(context, DataFetch.class);
        context.startService(sendIntent);
    }
}

}

提前感谢您的帮助!

1 个答案:

答案 0 :(得分:0)

这是实现它的一种方法。

var resizeImageKey = require('cloud/resize-image-key');
var ImageMetadata = Parse.Object.extend("ImageMetadata");

var NORMAL_WIDTH = 612;
var SMALL_WIDTH = 110;

// Resize image into various sizes before saving
Parse.Cloud.beforeSave("Image", function(req, res) {
  var original = req.object.get('sizeOriginal');

  Parse.Promise.as().then(function() {
    // Create an image metadata object on creation
    if (req.object.isNew()) {
      var im = new ImageMetadata;
      im.set("views", 0);
      return im.save();    
    }
  }).then(function(im) {
    // Set the metadata object relationship
    if (im) {
      req.object.set("imageMetadata", im);
    }

    if (!original) {
      return Parse.Promise.error("No original sized image file set.");
    }

    if (!req.object.dirty("sizeOriginal")) {
      // The original isn't being modified.
      return Parse.Promise.as();
    }

    // Don't set blank titles
    if (req.object.get("title").length === 0) {
      req.object.unset("title");
    }

    // Resize to a normal "show" page image size  
    return resizeImageKey({
      object: req.object,
      fromKey: "sizeOriginal",
      toKey: "sizeNormal",
      width: NORMAL_WIDTH
    })
  }).then(function() {
    // Resize to a smaller size for thumbnails
    return resizeImageKey({
      object: req.object,
      fromKey: "sizeOriginal",
      toKey: "sizeSmall",
      width: SMALL_WIDTH,
      crop: true
    });
  }).then(function(result) {
    res.success();
  }, function(error) {
    res.error(error);
  });
});

// Does all the work to update metadata about an image upon a view
Parse.Cloud.define("viewImage", function(request, response) {
  // Use the master key to prevent clients from tampering with view count
  Parse.Cloud.useMasterKey();
  var object = new ImageMetadata;
  object.id = request.params.metadataId;

  object.increment("views");
  object.save().then(function() {
    response.success();
  }, function(error) {
    response.error(error);
  });
});