In my application i can successfully upload file to parse.com. But when I tried to download it, it is giving null pointer exception.Here is my code to download file.
ParseObject downloadData = new ParseObject("DownloadData");
ParseFile downloadFile = (ParseFile) downloadData.get("File");
downloadFile.getDataInBackground(new GetDataCallback() {
#Override
public void done(byte[] bytes, ParseException e) {
if (e == null) {
String x= new String(bytes);
new AlertDialog.Builder(MainActivity2.this)
.setTitle("Downloaded File")
.setMessage(x)
.setPositiveButton("Ok", null)
.show();
} else {
new AlertDialog.Builder(MainActivity2.this)
.setTitle("Download File")
.setMessage("An Error Occurred")
.setPositiveButton("Ok", null)
.show();
}
}
});
the official documentation is confusing. Can anyone tell me a way to fix this.
You can not call get() on ParseObject created like this.
First you need to call parseQuery on your Parse Class and get this ParseObject from this query result.Now call get() on this ParseObject.
ParseQuery<ParseObject> query = ParseQuery.getQuery("DownloadData");
query.getInBackground("parse_object_id", new GetCallback<ParseObject>() {
public void done(ParseObject downloadData, ParseException e) {
if (e == null) {
// This object will contain your file
ParseFile downloadFile = (ParseFile) downloadData.get("File");
downloadFile.getDataInBackground(new GetDataCallback() {
#Override
public void done(byte[] bytes, ParseException e) {
if (e == null) {
String x= new String(bytes);
new AlertDialog.Builder(MainActivity2.this)
.setTitle("Downloaded File")
.setMessage(x)
.setPositiveButton("Ok", null)
.show();
} else {
new AlertDialog.Builder(MainActivity2.this)
.setTitle("Download File")
.setMessage("An Error Occurred")
.setPositiveButton("Ok", null)
.show();
}
}
});
} else {
// something went wrong
}
});
Related
I was trying to delete objects from Parse Class where requesterUsername is equals to current Username. I have more than 7 rows of data in Parse database but when I execute the method below objects.size() returns 0 which was not my expectation and it does not delete any rows from the database.
I am clueless here. Any help will be appreciated. Thanks in advance.
public void requestGride(View view){
if(requestActive == false) {
Log.i("MyApp", "Gride requested");
ParseObject request = new ParseObject("Requests");
request.put("requesterUsername", ParseUser.getCurrentUser().getUsername());
ParseACL parseACL = new ParseACL();
parseACL.setPublicWriteAccess(true);
request.setACL(parseACL);
request.saveInBackground(new SaveCallback() {
#Override
public void done(ParseException e) {
if (e == null) {
infoTextView.setText("Finding Gride..");
grideX.setText("Cancel GrideX");
requestActive = true;
}
}
});
}else{
infoTextView.setText("GrideX Cancelled");
grideX.setText("GrideX");
requestActive = false;
ParseQuery<ParseObject> query = new ParseQuery<ParseObject>("Requests");
query.whereEqualTo("requesterUsername",ParseUser.getCurrentUser().getUsername());
query.findInBackground(new FindCallback<ParseObject>() {
#Override
public void done(List<ParseObject> objects, ParseException e) {
if(e == null){
if(objects.size() > 0){
for (ParseObject adds : objects){
adds.deleteInBackground();
}
}
}
}
});
}
}
I can't figure out a solution to retrieve images from a Parse Table and display it in a Imageview in my Listview.
Here's what i have so far :
if (mSchedule.getCount() == 0) {
ParseQuery<ParseObject> query = ParseQuery.getQuery("sent_report");
query.selectKeys(Arrays.asList("Logo"));
query.selectKeys(Arrays.asList("Couleur"));
query.selectKeys(Arrays.asList("Date"));
query.selectKeys(Arrays.asList("Rog_pic"));
query.findInBackground(new FindCallback<ParseObject>() {
int i = 0;
Bitmap bmp;
public void done(List<ParseObject> names, ParseException e) {
if (e == null) {
for (ParseObject post : names) {
postTexts.add(post.getString("Logo"));
postTexts.add(post.getString("Couleur"));
postTexts.add(post.getString("Date"));
ParseFile image = (ParseFile) post.get("Rog_pic");
image.getDataInBackground(new GetDataCallback() {
public void done(byte[] data, ParseException e) {
if (e == null) {
bmp = BitmapFactory.decodeByteArray(data, 0, data.length);
} else {
Log.d("test", "There was a problem downloading the data.");
}
}
});
map = new HashMap<String, Object>();
map.put("nom", postTexts.get(i));
i++;
map.put("titre", postTexts.get(i));
i++;
map.put("description", postTexts.get(i));
i++;
map.put("img", bmp);
listItem.add(map);
mSchedule.notifyDataSetChanged();
}
} else {
Log.d("score", "Error: " + e.getMessage());
}
}
});
}
mSchedule is the SimpleAdapter. I tried a lot of things to make it work. I checked, and the ParseFile is not null, so why aren't the images displayed in the Imageview ?
Thanks in advance.
Please post the code for your adapter. Thats where the bug is. Are you sure you're performing a setImageBitmap(img) on your image view within the getView on your adapter? We need to see more adapter code to figure this out.
I'm downloading image to a folder on the SDCARD. Since the images and my folder is not immediately visible in the Gallery I'm trying to get the MediaScannerConnection to update and show the folder/images in the gallery.
Shows you how to do this in view code ?
private void downloadImage() {
if (future != null) {
//set the callback and start downloading
future.withResponse().setCallback(new FutureCallback<Response<InputStream>>() {
#Override
public void onCompleted(Exception e, Response<InputStream> result) {
boolean success = false;
if (e == null && result != null && result.getResult() != null) {
try {
//prepare the file name
String url = mSelectedImage.getUrl();
String fileName = url.substring(url.lastIndexOf('/') + 1, url.length());
//create a temporary directory within the cache folder
File dir = Utils.getAlbumStorageDir("wall-tx");
//create the file
File file = new File(dir, fileName);
if (!file.exists()) {
file.createNewFile();
}
//copy the image onto this file
Utils.copyInputStreamToFile(result.getResult(), file);
//animate the first elements
animateCompleteFirst(true);
//Broadcast the Media Scanner Intent to trigger it
success = true;
} catch (Exception ex) {
Log.e("walltx", ex.toString());
}
//animate after complete
animateComplete(success);
} else {
animateReset(true);
}
}
});
}
}
MediaScannerConnection.scanFile(this, new String[]{file.getPath()},
null, new MediaScannerConnection.OnScanCompletedListener() {
public void onScanCompleted(String path, Uri uri) {
// now visible in gallery
}
});
I have done Google drive integration and in integration i have created a file and write some text on the file and save it into the Login user's drive it is running fine but i want to to update the contents of the file i have created a save to drive, i have done allot of research but did not able to find the demo or any code, please any one guide me, i will post my code where i am creating file and saving to my drive
public class MainActivity extends Activity implements ConnectionCallbacks,OnConnectionFailedListener {
private GoogleApiClient mGoogleApiClient;
Button b ,editfile;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mGoogleApiClient = new GoogleApiClient.Builder(this).addApi(Drive.API)
.addScope(Drive.SCOPE_FILE)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.build();
b = (Button) findViewById(R.id.createfile);
editfile = (Button) findViewById(R.id.editfile);
b.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
// create new contents resource
/**
* A code to illustrate how to create a new FILE in the Drive.
*/
Drive.DriveApi.newContents(getGoogleApiClient())
.setResultCallback(contentsCallback);
}
});
}
#Override
protected void onStart() {
super.onStart();
mGoogleApiClient.connect();
}
/**
* Called when activity gets visible. A connection to Drive services need to
* be initiated as soon as the activity is visible. Registers
* {#code ConnectionCallbacks} and {#code OnConnectionFailedListener} on the
* activities itself.
*/
#Override
protected void onResume() {
super.onResume();
if (mGoogleApiClient == null) {
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addApi(Drive.API)
.addScope(Drive.SCOPE_FILE)
//.addScope(Drive.SCOPE_APPFOLDER) // required for App Folder sample
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.build();
}
mGoogleApiClient.connect();
}
#Override
public void onConnected(Bundle arg0) {
// TODO Auto-generated method stub
}
#Override
public void onConnectionSuspended(int arg0) {
// TODO Auto-generated method stub
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
if (connectionResult.hasResolution()) {
try {
connectionResult.startResolutionForResult(this, 1);
} catch (IntentSender.SendIntentException e) {
// Unable to resolve, message user appropriately
}
} else {
GooglePlayServicesUtil.getErrorDialog(
connectionResult.getErrorCode(), this, 0).show();
}
}
#Override
protected void onActivityResult(final int requestCode,
final int resultCode, final Intent data) {
switch (requestCode) {
case 1:
if (resultCode == RESULT_OK) {
mGoogleApiClient.connect();
}
break;
}
}
public GoogleApiClient getGoogleApiClient() {
return mGoogleApiClient;
}
/**
* A code to illustrate how to create a new FILE with some text on the file in the Google Drive.
*/
final private ResultCallback<ContentsResult> contentsCallback = new ResultCallback<ContentsResult>() {
#Override
public void onResult(ContentsResult result) {
if (!result.getStatus().isSuccess()) {
Toast.makeText(MainActivity.this,"Error while trying to create new file contents" ,Toast.LENGTH_LONG).show();
return;
}
Contents driveContents = result.getContents();
// write content to DriveContents
OutputStream outputStream = driveContents.getOutputStream();
Writer writer = new OutputStreamWriter(outputStream);
try {
writer.write(information_data());
writer.close();
} catch (IOException e) {
Log.e("IOExceptions=", e.toString());
}
MetadataChangeSet changeSet = new MetadataChangeSet.Builder()
.setTitle("testFile.txt")
.setMimeType("text/plain")
.setStarred(true)
.build();
// create a file on root folder
Drive.DriveApi.getRootFolder(getGoogleApiClient())
.createFile(getGoogleApiClient(), changeSet, result.getContents())
.setResultCallback(fileCallback);
}
};
final private ResultCallback<DriveFileResult> fileCallback = new ResultCallback<DriveFileResult>() {
#Override
public void onResult(DriveFileResult result) {
if (!result.getStatus().isSuccess()) {
Toast.makeText(MainActivity.this,"Error while trying to create the file" ,Toast.LENGTH_LONG).show();
return;
}
Toast.makeText(MainActivity.this,"Created a file: " + result.getDriveFile().getDriveId(),Toast.LENGTH_LONG).show();
Log.e("result.getDriveFile().getDriveId=", ""+result.getDriveFile().getDriveId());
Log.e("result.getStatus()=", ""+result.getStatus().toString());
//Opening the file contents Reading files
driveOpnefileContents(result.getDriveFile());
}
};
public void driveOpnefileContents(DriveFile driveFile) {
// TODO Auto-generated method stub
Log.e("driveOpnefileContents=", "driveOpnefileContents");
driveFile.openContents(getGoogleApiClient(), DriveFile.MODE_READ_ONLY, new DownloadProgressListener() {
#Override
public void onProgress(long bytesDownloaded, long bytesExpected) {
// Update progress dialog with the latest progress.
Log.e("onProgress=", "onProgress");
int progress = (int)(bytesDownloaded*100/bytesExpected);
Log.e("progress", String.format("Loading progress: %d percent=", progress));
}
})
.setResultCallback(contentsOpenedCallback);
}
ResultCallback<ContentsResult> contentsOpenedCallback = new ResultCallback<ContentsResult>() {
#Override
public void onResult(ContentsResult result) {
if (!result.getStatus().isSuccess()) {
// display an error saying file can't be opened
Toast.makeText(MainActivity.this,"display an error saying file can't be opened" ,Toast.LENGTH_LONG).show();
return;
}
// DriveContents object contains pointers
// to the actual byte stream
try {
Contents driveContents = result.getContents();
BufferedReader reader = new BufferedReader(new InputStreamReader(driveContents.getInputStream()));
StringBuilder builder = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
builder.append(line);
}
String contentsAsString = builder.toString();
Log.e("Reading File Contents As String=", ""+contentsAsString);
driveContents.close();
/*try {
ParcelFileDescriptor parcelFileDescriptor = driveContents.getParcelFileDescriptor();
FileInputStream fileInputStream = new FileInputStream(parcelFileDescriptor.getFileDescriptor());
// Read to the end of the file.
fileInputStream.read(new byte[fileInputStream.available()]);
// Append to the file.
FileOutputStream fileOutputStream = new FileOutputStream(parcelFileDescriptor.getFileDescriptor());
Writer writer = new OutputStreamWriter(fileOutputStream);
writer.write("editing the contents of the saved file");
writer.close();
driveContents.close();
} catch (IOException e) {
Log.e("IOExceptionAppend to the file.=", e.toString());
//java.io.IOException: write failed: EBADF (Bad file number)
}*/
Log.e("Append to the file.=", "Append to the file.");
} catch (IOException e) {
// TODO Auto-generated catch block
Log.e("IOExceptionAppend to the file2.=", e.toString());
}
}
};
public String information_data(){
String result = "";
try {
JSONObject jArrayFacebookData = new JSONObject();
JSONObject jObjectType = new JSONObject();
// put elements into the object as a key-value pair
jObjectType.put("info", "facebook_login");
jArrayFacebookData.put("Result", jObjectType);
// 2nd array for user information
JSONObject jObjectData = new JSONObject();
// Create Json Object using Facebook Data
jObjectData.put("facebook_user_id", "facebook_user_id");
jObjectData.put("first_name", "achin");
jObjectData.put("last_name", "verma");
jObjectData.put("email", "xvz");
jObjectData.put("username", "achin");
jObjectData.put("birthday", "28 april 90");
jObjectData.put("gender", "male");
jObjectData.put("location", "mohali");
jObjectData.put("display_photo", "link");
jArrayFacebookData.put("data", jObjectData);
//Log.e("jArrayFacebookData=", ""+jArrayFacebookData);
result = ""+jArrayFacebookData;
} catch (JSONException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
return result;
}
}
Here is a code snippet 'update' that does what you need (I think). It is using the 'await' call version that has to run off the UI thread or you may turn it into a callback version. You actually need only the portion that starts with
dFile.open(mGAC, DriveFile.MODE_WRITE_ONLY, null)
(after turning DriveId into DriveFile) and make sure you call 'commit' on it
/**
* update file in GOODrive
* #param dId file id
* #param titl new file name (optional)
* #param mime new file mime type (optional, null or MIME_FLDR indicates folder)
* #param buf new file contents (optional)
* #return success status
*/
static boolean update(DriveId dId, String titl, String mime, String desc, byte[] buf){
if (dId == null || !isConnected()) return false; //------------>>>
Boolean bOK = false;
Builder mdBd = new MetadataChangeSet.Builder();
if (titl != null) mdBd.setTitle(titl);
if (mime != null) mdBd.setMimeType(mime);
if (desc != null) mdBd.setDescription(desc);
MetadataChangeSet meta = mdBd.build();
if (mime == null || UT.MIME_FLDR.equals(mime)) {
DriveFolder dFldr = Drive.DriveApi.getFolder(mGAC, dId);
MetadataResult r1 = dFldr.updateMetadata(mGAC, meta).await();
bOK = (r1 != null) && r1.getStatus().isSuccess();
} else {
DriveFile dFile = Drive.DriveApi.getFile(mGAC, dId);
MetadataResult r1 = dFile.updateMetadata(mGAC, meta).await();
if ((r1 != null) && r1.getStatus().isSuccess() && buf != null) {
DriveContentsResult r2 = dFile.open(mGAC, DriveFile.MODE_WRITE_ONLY, null).await();
if (r2.getStatus().isSuccess()) {
Status r3 = bytes2Cont(r2.getDriveContents(), buf).commit(mGAC, meta).await();
bOK = (r3 != null && r3.isSuccess());
}
}
}
return bOK;
}
the metadata do not need to be updated in your case, so you may modify the code or just pass nulls. Your new content has to be delivered as a byte buffer (String turned to bytes, jpeg data buffer, ...).
The context of this method can be found here . Good Luck
I know, this answer was late, but google always update's his api, so I desided to add answer.
Here is kotlin code, which working by this time
fun updateDriveFile(fileCache: File, googleRecentFileModel: GoogleRecentFileModel): Deferred<Boolean> = CoroutineScope(Dispatchers.Default).async {
var result = false
val drive = DriveId.decodeFromString(googleRecentFileModel.stringDriveId).asDriveFile()
val openFileTask = driveResourceClient?.openFile(drive, DriveFile.MODE_WRITE_ONLY)
openFileTask?.continueWithTask { task ->
val contents = task.result
contents!!.outputStream.use {
val fileBytes = ByteArray(fileCache.length().toInt())
val fileIS = FileInputStream(fileCache)
fileIS.read(fileBytes)
fileIS.close()
it.write(fileBytes)
it.flush()
it.close()
result = true
}
driveResourceClient?.commitContents(contents, null)
}
result
}
After my app is destroyed, when I click an item in my listview, it's supposed to copy the data to the clipboard instead the data is returned null although I do infact count some items in the list.
Here's some code:
#Override
protected void onSaveInstanceState(final Bundle outState) {
super.onSaveInstanceState(outState);
outState.putStringArrayList("list", listFragment.getLocations());
}
public void populateList(final StorageManager topItem,
final StorageManager bottomItem) {
Thread thread = new Thread(new Runnable() {
#Override
public void run() {
locations = topItem.readFile();
times = bottomItem.readFile();
for (int index = 0; index < locations.size() && index < times.size(); index++) {
Map<String, UserLocation> data = new HashMap<String, UserLocation>();
data.put("Top", new UserLocation(index, locations.get(index)));
data.put("Bottom", new UserLocation(index, times.get(index)));
list.add(data);
}
Collections.reverse(list);
Collections.reverse(locations);
}
});
thread.run();
}
#Override
public void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
String dataToSend = TwoItemListFragment.locations.get(position);
if (null != mListener) {
mListener.onFragmentInteraction(TwoItemListFragment.list.get(position).hashCode());
}
try {
copyData(dataToSend);
} catch (NullPointerException e) {
Log.d(TAG, dataToSend + "");
}
}
*/
public void copyData(String data) {
Context context = getActivity().getApplicationContext();
String copied = getString(R.string.copied);
Toast copyToast = Toast.makeText(context, copied, Toast.LENGTH_SHORT);
try {
cl.setPrimaryClip(ClipData.newPlainText("copy", data));
copyToast.show();
} catch (NullPointerException e) {
Log.e(TAG, "Could not copy data: NullPointerException");
Log.d(TAG, String.valueOf(TwoItemListFragment.locations.size()));
Log.d(TAG, String.valueOf(TwoItemListFragment.locations.get(1)));
copyToast = Toast.makeText(context, getString(R.string.null_text), Toast.LENGTH_LONG);
copyToast.show();
}
}
Some Logcat data
07-25 02:30:42.172 13968-13968/com.DXC0.locationmanagertests.app E/com.DXC0.locationmanagertests.app.TwoItemListFragment﹕ Could not copy data: NullPointerException
07-25 02:30:42.172 13968-13968/com.DXC0.locationmanagertests.app D/com.DXC0.locationmanagertests.app.TwoItemListFragment﹕ 5
EDIT:
Just checked, the data I'm sending is NOT null, it does in fact exist; but for some reason, it returns null still. The problem seems to be this line
cl.setPrimaryClip(ClipData.newPlainText("copy", data));
The ClipboardManager "cl" was null for some reason, so in my try block, I reinitialised and it worked. The data was never null.
try {
cl = ((MainActivity) getActivity()).clipboardManager();
cl.setPrimaryClip(ClipData.newPlainText("copy", data));
copyToast.show();
} catch (NullPointerException e) {
e.printStackTrace();
Log.e(TAG, "Could not copy data: NullPointerException");
copyToast = Toast.makeText(context, getString(R.string.null_text), Toast.LENGTH_LONG);
copyToast.show();
}