Downloading list of audio from URL - java

So I'm implementing audio Playlist app that imports audios from Parse.com, and when I retrieve them by streaming them directly from their URls, it took maybe one minute to play after clicking play button.
So I don't want to use streaming from URL methods to play my audio from server because it makes it so slow. Instead I want to download list of audios from server (Parse.com) at once and then playing them by retrieving from sdcard.
I have the class that downloads single audio from single URL .. I want to edit the code to make it downloads more than one audio at once.
here is the class I have to download audio from URL.
class DownloadMusicfromInternet extends AsyncTask<String, String, String> {
private Context mContext;
private MediaPlayer mPlayer;
public DownloadMusicfromInternet(Context context) {
mContext = context;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
// Download Music File from Internet
#Override
protected String doInBackground(String... f_url) {
int count;
try {
URL url = new URL(f_url[0]);
URLConnection conection = url.openConnection();
conection.connect();
// Get Music file length
int lenghtOfFile = conection.getContentLength();
// input stream to read file - with 8k buffer
InputStream input = new BufferedInputStream(url.openStream(), 10 * 1024);
// Output stream to write file in SD card
OutputStream output = new
Also if you could help me in how to set a name for the audios, I don't want to write static name because I'm downloading more than one audio at a time .
FileOutputStream(Environment.getExternalStorageDirectory().getPath() + "/"+"how to put unique name for each audio here ?"+".mp3");
byte data[] = new byte[1024];
long total = 0;
while ((count = input.read(data)) != -1) {
total += count;
publishProgress("" + (int) ((total * 100) / lenghtOfFile));
// Write data to file
output.write(data, 0, count);
}
// Flush output
output.flush();
// Close streams
output.close();
input.close();
} catch (Exception e) {
Log.e("Error: ", e.getMessage());
}
return null;
}
// While Downloading Music File
// Once Music File is downloaded
#Override
protected void onPostExecute(String file_url) {
// Play the music
playMusic();
}
// Play Music
protected void playMusic() {
// Read Mp3 file present under SD card
Uri myUri1 = Uri.parse("file:///sdcard/"+"the same unique name that was set previously ! "+".mp3");
mPlayer = new MediaPlayer();
mPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
try {
mPlayer.setDataSource(mContext.getApplicationContext(), myUri1);
mPlayer.prepare();
// Start playing the Music file
mPlayer.start();
mPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
public void onCompletion(MediaPlayer mp) {
// TODO Auto-generated method stub
// Once Music is completed playing, enable the button
// btnPlayMusic.setEnabled(true);
Toast.makeText(mContext.getApplicationContext(), "Music completed playing", Toast.LENGTH_LONG).show();
}
});
} catch (IllegalArgumentException e) {
Toast.makeText(mContext.getApplicationContext(), "You might not set the URI correctly!", Toast.LENGTH_LONG).show();
} catch (SecurityException e) {
Toast.makeText(mContext.getApplicationContext(), "URI cannot be accessed, permissed needed", Toast.LENGTH_LONG).show();
} catch (IllegalStateException e) {
Toast.makeText(mContext.getApplicationContext(), "Media Player is not in correct state", Toast.LENGTH_LONG).show();
} catch (IOException e) {
Toast.makeText(mContext.getApplicationContext(), "IO Error occured", Toast.LENGTH_LONG).show();
}
}
}
and this is my adapter, and here is where my problem occurs and crashes my app. I don't know how to call ( DownloadMusicfromInternet ) more than once from the following adapter .
public class mAdapter extends ParseQueryAdapter<ParseObject> {
public mAdapter (Context context) {
super(context, new ParseQueryAdapter.QueryFactory<ParseObject>() {
public ParseQuery create() {
ParseQuery query = new ParseQuery("MusicPlaylist");
return query;
}
});
}
#Override
public View getItemView(final ParseObject object, View v, ViewGroup parent) {
if (v == null) {
v = View.inflate(getContext(), R.layout.list_music, null);
}
super.getItemView(object, v, parent);
//Audio retrieving
final ImageButton btn = (ImageButton) v.findViewById(R.id.play_btn);
final ParseFile fileObject = object.getParseFile("music");
**// here I put a loop because I want it to download a list of audios at once and I think here is the problem**
if (fileObject != null) {
for (int i = 10; i >= j; j++) {
new DownloadMusicfromInternet().execute(fileObject.getUrl());
}
fileObject.getDataInBackground(new GetDataCallback() {
#Override
public void done(byte[] bytes, com.parse.ParseException e) {
btn.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
}//end on click
}//end listener
);
}//end done
});//end get data
}//end if
return v;
}//end getItem View
}//end mAdapter
Any help would be appreciated ..

Related

not able to move images to another folder in gallery, using asynctask

I created an image gallery app.
My requirment: I want to select multiple images, click on button cut and come back to activity which displays all folders (ImageGallery.java). Now, I want to select a folder and paste all the selected images in that folder, on selecting the folder.
What is happening? I am able to select images using my app and come back to activity which displays all folders but not able to move them using my app.
I put the code for moving images in a background thread using task. I select images from one folder, come back to the activity which displays all the folders (ImageGallery.java) and select the folder to which the images are to be moved. But when I try to move images, selected images do not move to other folder being selected, on selecting a folder. I guess the code inside AsyncTask isn't even getting executed.
How do I fix it ?
PhotosActivity.java (Activity used to select images):
int int_position;
private GridView gridView;
GridViewAdapter adapter;
ArrayList<Model_images> al_menu = new ArrayList<>();
private ArrayList<Integer> mSelected = new ArrayList<>();
boolean boolean_folder;
gridView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(final AdapterView<?> parent, View view, final int position, long id) {
if (mSelected.contains(position)) {
mSelected.remove(position);
view.setBackgroundColor(Color.TRANSPARENT);// remove item from list
// update view (v) state here
// eg: remove highlight
} else {
mSelected.add(position);
view.setBackgroundColor(Color.LTGRAY);// add item to list
// update view (v) state here
// eg: add highlight
}
buttoncut.setVisibility(View.VISIBLE);
button2.setVisibility(View.VISIBLE);
button3.setVisibility(View.VISIBLE);
button4.setVisibility(View.VISIBLE);
button5.setVisibility(View.VISIBLE);
buttoncut.setOnClickListener(
new View.OnClickListener() {
public void onClick(View view) {
buttoncut.setVisibility(View.GONE);
button2.setVisibility(View.GONE);
button3.setVisibility(View.GONE);
button4.setVisibility(View.GONE);
button5.setVisibility(View.GONE);
Intent moveIntent = new Intent(PhotosActivity.this, ImageGallery.class);
moveIntent.putIntegerArrayListExtra("selected_images", mSelected);
startActivity(moveIntent);
}
});
ImageGallery.java:
public static ArrayList<Model_images> al_images = new ArrayList<>();
ArrayList<Integer> selectedImages = new ArrayList<>();
boolean boolean_folder;
Adapter_PhotosFolder obj_adapter;
GridView gv_folder;
private static final int REQUEST_PERMISSIONS = 100;
int int_position;
selectedImages = getIntent().getIntegerArrayListExtra("selected_images");
if (selectedImages != null) {
Toast.makeText(ImageGallery.this, "This code gets executed", Toast.LENGTH_SHORT)
.show();
new LongOperation().execute();
}
private class LongOperation extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
for (int image : selectedImages) {
File sourceImage = new File(al_images.get(int_position).getAl_imagepath().get(image)); //returns the image File from model class to be moved.
File destinationImage = new File(al_images.get(int_position).getStr_folder(), ".jpeg");
try {
copyOrMoveFile(sourceImage, destinationImage, true);
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
//Method to move the file
private void copyOrMoveFile(File file, File dir, boolean isCopy) throws IOException {
File newFile = new File(dir, file.getName());
FileChannel outChannel = null;
FileChannel inputChannel = null;
try {
outChannel = new FileOutputStream(newFile).getChannel();
inputChannel = new FileInputStream(file).getChannel();
inputChannel.transferTo(0, inputChannel.size(), outChannel);
inputChannel.close();
if (!isCopy)
file.delete();
} finally {
if (inputChannel != null) inputChannel.close();
if (outChannel != null) outChannel.close();
}
}
}
You have to use Intent.ACTION_MEDIA_SCANNER_SCAN_FILE for updating media store.
Inside AsyncTask -> onPostExecute method fetch latest images from MediaStore
private class LongOperation extends AsyncTask<String, Void, File> {
#Override
protected File doInBackground(String... params) {
for (String imagePath : selectedImages) {
File sourceImage = new File(imagePath); //returns the image File from model class to
// be// moved.
File destinationImage = new File(al_images.get(int_position).getDirectoryPath() +
File.separator + sourceImage.getName());
try {
moveFile(sourceImage, destinationImage, true);
return destinationImage;
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
#Override
protected void onPreExecute() {
}
#Override
protected void onPostExecute(File file) {
super.onPostExecute(file);
getBaseContext().sendBroadcast(new Intent(
Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.fromFile(file)));
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
fn_imagespath(); // Call method to fetch latest images.
}
}, 1000); // additional delay time of 1 sec to update media scanner
}
}
Just a better method to move file
private void moveFile(File file_Source, File file_Destination, boolean isCopy) throws IOException {
FileChannel source = null;
FileChannel destination = null;
if (!file_Destination.exists()) {
file_Destination.createNewFile();
}
try {
source = new FileInputStream(file_Source).getChannel();
destination = new FileOutputStream(file_Destination).getChannel();
long count = 0;
long size = source.size();
while ((count += destination.transferFrom(source, count, size - count)) < size) ;
if (!isCopy) {
file_Source.delete();
}
} finally {
if (source != null) {
source.close();
}
if (destination != null) {
destination.close();
}
}
}
Not much changes in code added MediaScannerConnection. Give it a try .
private class LongOperation extends AsyncTask<String, Void, Integer> {
#Override
protected Integer doInBackground(String... params) {
int movedCount=0;
for (int i=0;i<selectedImages.size();i++) {
File sourceImage = new File(al_images.get(int_position).getAl_imagepath().get(i));
File destinationImage = new File(al_images.get(int_position).getStr_folder(), ".jpeg");
try {
boolean isMoved= copyOrMoveFile(sourceImage, destinationImage, true);
if(isMoved) {
movedCount++;
callMediaScanner(ImageGallery.this, destinationImage.getAbsolutePath());
}
} catch (IOException e) {
e.printStackTrace();
}
}
return movedCount;
}
#Override
protected void onPostExecute(Integer val) {
super.onPostExecute(val);
// Here you have to modify return type of doInBackground as per your convineance
if(val.intValue()==selectedImages.size()){
Log.e("Moved","Allfile moved");
}else{
Log.e("Moved","Some file missing");
}
}
public boolean copyOrMoveFile(File localFile, File destinationFile, boolean isCopy) {
FileChannel outputChannel = null;
FileChannel inputChannel = null;
try {
outputChannel = new FileOutputStream(destinationFile).getChannel();
inputChannel = new FileInputStream(localFile).getChannel();
inputChannel.transferTo(0, inputChannel.size(), outputChannel);
inputChannel.close();
if (!isCopy)
localFile.delete();
} catch (Exception e) {
e.printStackTrace();
return false;
} finally {
try {
if (inputChannel != null) inputChannel.close();
if (outputChannel != null) outputChannel.close();
} catch (Exception e) {
e.printStackTrace();
}
}
return true;
}
}
public void callMediaScanner(Context context, String path) {
MediaScannerConnection.scanFile(context,
new String[] { path }, null,null);
}

Playing music from Parse.com android

so I'm implementing like music playlist app, my audios are uploaded to Parse.com as mp3 , I want to retrieve those audios ..
final Button btn = (Button) v.findViewById(R.id.button);
final ParseFile fileObject = object.getParseFile("music");
if (fileObject != null) {
fileObject.getDataInBackground(new GetDataCallback() {
#Override
public void done(byte[] bytes, com.parse.ParseException e) {
final String audioFileURL = fileObject.getUrl();
mediaPlayer = new MediaPlayer();
mediaPlayer.reset();
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
btn.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
try {
mediaPlayer.setDataSource(audioFileURL);
mediaPlayer.prepare();
mediaPlayer.start();
} catch (IllegalArgumentException e1) {
e1.printStackTrace();
}//end catch
catch (IOException e1) {
e1.printStackTrace();
}
}//end on click
}//end listener
);
}//end done
});//end get data
}//end if
this is how I retrieve music from Parse.com but this is taking so much time specially that I have a list of audios .. I want a way to download group of the audios in the background .. so when I click the button, the music play so fast .. any help would be greatly appreciated.
I have no time right now to understand why your code doesn't work, but you can take my sample app on github (committed just now), you should solve your problem...if not, let me know. Please, take note of the README.md
https://github.com/fullwipe/ParseAudioFileExample
Hope it helps...
Edit This is the essential part of my repository. Record and save:
String outputFile = Environment.getExternalStorageDirectory().
getAbsolutePath() + "/rumor.mp3";
myRecorder = new MediaRecorder();
myRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
myRecorder.setOutputFormat(MediaRecorder.OutputFormat.DEFAULT);
myRecorder.setAudioEncoder(MediaRecorder.OutputFormat.AMR_NB);
myRecorder.setOutputFile(outputFile);
Then, start recording...
try {
myRecorder.prepare();
myRecorder.start();
} catch (IllegalStateException e) {
// start:it is called before prepare()
// prepare: it is called after start() or before setOutputFormat()
e.printStackTrace();
} catch (IOException e) {
// prepare() fails
e.printStackTrace();
}
When you stop recording, save it on Parse.com in this way:
FileInputStream fileInputStream = null;
File fileObj = new File(outputFile);
byte[] data = new byte[(int) fileObj.length()];
try {
//convert file into array of bytes
fileInputStream = new FileInputStream(fileObj);
fileInputStream.read(data);
fileInputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
ParseFile parseAudioFile = new ParseFile("audiofile.mp3", data);
parseAudioFile.saveInBackground();
ParseObject parseObject = new ParseObject("AudioFileClass");
parseObject.put("audiofile", parseAudioFile);
parseObject.saveInBackground(new SaveCallback() {
public void done(ParseException e) {
if (e == null) {
Toast.makeText(getApplicationContext(),"Audio file saved successfully", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getApplicationContext(),"Error: audio file not saved", Toast.LENGTH_SHORT).show();
}
}
});
Retrieve and play from Parse.com is very simple, I have used a ParseQueryAdapter. This is the part where you get the mp3 file and play it:
ParseFile descr = object.getParseFile("audiofile");
if (descr != null) {
String audioFileURL = descr.getUrl();
MediaPlayer mediaPlayer = new MediaPlayer();
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
try {
mediaPlayer.setDataSource(audioFileURL);
mediaPlayer.prepare();
mediaPlayer.start();
}
...
...

Load sliding layer after camera bitmap/image save

Im Still fresh so go easy.
This is my OnClickListener for my camera
buttonClick = (Button) findViewById(R.id.btnCapture);
buttonClick.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
preview.mCamera.takePicture(shutterCallback, rawCallback, jpegCallback);
camera.takePicture(shutterCallback, rawCallback, jpegCallback);
}
}
);}
And this is the code to save to sd card
private class SaveImageTask extends AsyncTask<byte[], Void, Void> {
#Override
protected Void doInBackground(byte[]... data) {
FileOutputStream outStream = null;
// Write to SD Card
try {
File sdCard = Environment.getExternalStorageDirectory();
File dir = new File(sdCard.getAbsolutePath() + "/camtest");
dir.mkdirs();
String fileName = String.format("%d.jpg", System.currentTimeMillis());
File outFile = new File(dir, fileName);
outStream = new FileOutputStream(outFile);
outStream.write(data[0]);
outStream.flush();
outStream.close();
Log.d(TAG, "onPictureTaken - wrote bytes: " + data.length + " to " + outFile.getAbsolutePath());
refreshGallery(outFile);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
}
return null;
}
}
and then i call my sliding layer up
public void buttonClicked(View v){
switch (v.getId()) {
case R.id.btnCapture:
if (!mSlidingLayer.isOpened()) {
mSlidingLayer.openLayer(true);
}
break;
case R.id.buttonClose:
if (mSlidingLayer.isOpened()) {
mSlidingLayer.closeLayer(true);
}
break;
}
}
How do i implement my OnClickListener from my camera with the buttonClicked from my sliding layer in one instance.
I tried combining the two but that gave me the RuntimeException: Canvas: trying to use a recycled bitmap error because the sliding layer was coming into effect before the Save Image Task could complete.
Any help would be great.
Kind regards Sean.
Trigger the code to slide your layer in the onPostExecute() method of your AsyncTask. This method will be called when the task has completed, and will be called on the main thread so you can safely manipulate UI classes.

Android Update the file content of created file on Google Drive

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
}

How to download multiple images and have one progressBar using AsynTask (Android)

I want my program to download many images (around 500) from the internet and store them in my external storage. Currently when I download a single image, it shows a progressBar and downloads the image properly. However when I am trying to replicate w/ two images, it gives the Toast for "Download complete" for both images being downloaded, however no progressBar for either image is shown and only the first image is properly downloaded.
Here is the code for my onCreate method for activity.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//Remove Title bar
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
//force portrait orientation. (No landscape orientation).
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
setContentView(R.layout.activity_quran);
//Instantiate ProgressDialog (Used for downloading quran pages).
myProgressDialog = new ProgressDialog(QuranActivity.this);
myProgressDialog.setMessage("Downloading Quran");
myProgressDialog.setIndeterminate(true);
myProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
myProgressDialog.setCancelable(true);
//execute when the downloader must be fired.
final DownloadTask downloadTask = new DownloadTask(QuranActivity.this);
DownloadTask second = new DownloadTask(getApplicationContext());
myHTTPURL = "https://ia601608.us.archive.org/BookReader/BookReaderImages.php?zip=/10/items/05Quran15LineWhitePageWithVioletBorderWww.Momeen.blogspot.com/05%20Quran%2015%20Line%20[White%20page%20with%20Violet%20border]%20-%20www.Momeen.blogspot.com_jp2.zip&file=05%20Quran%2015%20Line%20[White%20page%20with%20Violet%20border]%20-%20www.Momeen.blogspot.com_jp2/05%20Quran%2015%20Line%20[White%20page%20with%20Violet%20border]%20-%20www.Momeen.blogspot.com_0001.jp2&scale=1&rotate=0";
myHTTPURL2 = "https://ia601608.us.archive.org/BookReader/BookReaderImages.php?zip=/10/items/05Quran15LineWhitePageWithVioletBorderWww.Momeen.blogspot.com/05%20Quran%2015%20Line%20[White%20page%20with%20Violet%20border]%20-%20www.Momeen.blogspot.com_jp2.zip&file=05%20Quran%2015%20Line%20[White%20page%20with%20Violet%20border]%20-%20www.Momeen.blogspot.com_jp2/05%20Quran%2015%20Line%20[White%20page%20with%20Violet%20border]%20-%20www.Momeen.blogspot.com_0002.jp2&scale=1&rotate=0";
//First check if the file has already been created. (Only need to download 1ce, or
//in the case where the user deleted the files, we reinstall them again).
if (isExternalStorageWritable()) {
File makeDirectory = getQuranStorageDir(QuranActivity.this, "Quran_Pages");
for (int i = 0; i < 2; i++) {
Bundle myBundle = new Bundle();
myBundle.putInt("i", i);
if (i == 0) {
downloadTask.execute(myHTTPURL);
try {
downloadTask.get();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
myProgressDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
#Override
public void onCancel(DialogInterface dialog) {
downloadTask.cancel(true);
}
});
} else {
/*if (downloadTask.getStatus() == AsyncTask.Status.FINISHED) {
downloadTask.execute(myHTTPURL2);
} else if (downloadTask.getStatus() == AsyncTask.Status.RUNNING) {
try {
downloadTask.execute(myHTTPURL2).wait(10000);
} catch (InterruptedException e) {
e.printStackTrace();
}
} */
second.execute(myHTTPURL2);
try {
second.get();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
// downloadTask.execute(myHTTPURL2);
}
}
}
and this is the code for my AsynTask Class.
#TargetApi(Build.VERSION_CODES.FROYO)
private class DownloadTask extends AsyncTask {
private Context context;
private PowerManager.WakeLock myWakeLock;
public DownloadTask(Context context) {
this.context = context;
}
#Override
protected String doInBackground(String... sUrl) {
InputStream input = null;
OutputStream output = null;
HttpURLConnection connection = null;
try {
URL url = new URL(sUrl[0]);
connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setRequestMethod("GET");
connection.connect();
if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) {
return "Server returned HTTP " + connection.getResponseCode()
+ " " + connection.getResponseMessage();
}
//Display download percentage.
int fileLength = connection.getContentLength();
//create folder to place the downloaded file in.
// File Path:E:\Android\data\com.syedabdullah.syed.quran_memorization_application
// \files\Quran Memorization Application\Quran_Pictures
//So first create a root folder Quran Memorization Application then inside that
//folder we create another folder named Quran Pictures.
/* File rootFolder = new File(getExternalFilesDir("Quran Memorization Application"),
"Quran_Pages"); */
//Here we insert inside the Quran_Pictures folder the quran_pages.
//String myFileName = "quran_01.jpg";
Bundle y = new Bundle();
int retrievePos = y.getInt("i");
String quranFilePageName = "_" + retrievePos + ".jpg";
// String fileName = "justwork.jpg";
File sup = new File(getExternalFilesDir("Quran Memorization Application"), "Quran_Pages");
File myFile = new File(sup, quranFilePageName);
myFile.createNewFile();
//downlaod the file.
input = connection.getInputStream();
output = new FileOutputStream(myFile);
byte data[] = new byte[4096];
long total = 0;
int count;
while ((count = input.read(data)) != -1) {
//allow cancel with back button.
if (isCancelled()) {
input.close();
return null;
}
total += count;
//publish the progress.
if (fileLength > 0) {
publishProgress((int) (total * 100 / fileLength));
}
output.write(data, 0, count);
}
Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
intent.setData(Uri.fromFile(myFile));
QuranActivity.this.sendBroadcast(intent);
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (output != null) {
output.close();
}
if (input != null) {
input.close();
}
} catch (IOException e) {
e.printStackTrace();
}
if (connection != null) {
connection.disconnect();
}
}
return null;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
//Take CPU lock to prevent CPU from going off if the user presses the power button.
//during download.
PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
myWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, getClass().getName());
myWakeLock.acquire();
myProgressDialog.show();
}
#Override
protected void onProgressUpdate(Integer... progress) {
super.onProgressUpdate(progress);
//If we get here length is known, so setIndertimante to false.
myProgressDialog.setIndeterminate(false);
myProgressDialog.setMax(100);
myProgressDialog.setProgress(progress[0]);
}
#Override
protected void onPostExecute(String result) {
myWakeLock.release();
myProgressDialog.dismiss();
if (result != null) {
Toast.makeText(context, "Download error: " + result, Toast.LENGTH_LONG).show();
} else {
Toast.makeText(context, "Download Complete", Toast.LENGTH_SHORT).show();
}
}
} }
I was hoping to have a for loop that would create hundreds of downloadTasks and download all the images I need, and then I would call the get method. However in order for that to work, I first need too know why when I try for 2 images only the first one gets downloaded and why no progressbar shows up. Also if possible if I could get a hint as to how I can make my progressBar update for all the images and not be designed for just 1. Thanks in advance. (Note all URLs are currect.)
Thank you so much! figured out that my loops were suppose to go inside doInBackground. Also to anyone else having a similar issue. To download multiple files and display a decent progressBar, here is a very great tutorial: http://theopentutorials.com/tutorials/android/dialog/android-download-multiple-files-showing-progress-bar/

Categories

Resources