I hired someone to code my app. It loads a instrumental downloaded from the internet to my app. To download the instrumental it is fast but when loading the instrumental it takes a really long time at least a minute or more. I looked over the code to see where it would be slowing it down but i can't seem to figure it out. Any help is appreciated.
Code:
//File loading task
class SaveInputStreamTask extends AsyncTask<String, Integer, String> {
private Context context;
ProgressDialog mProgressDialog;
public SaveInputStreamTask(Context context) {
this.context = context;
}
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
// mProgressDialog = new ProgressDialog(context);
//mProgressDialog.setMessage("Beat Will Take A Minute To Load When Mixing So Start Recording");
mProgressDialog = ProgressDialog.show(context, getResources().getString(R.string.app_name), "Beat Will Take Up To A Minute To Load. In The Meantime How's Your Day?");
mProgressDialog.show();
}
#Override
protected String doInBackground(String... sUrl) {
try
{
File file = new File(instrument_file_name);
long totalFilesize = file.length();
long readSize = 0;
FileInputStream fis = new FileInputStream(file);
saveInputStream(fis);
return "SUCCESS";
}
catch(Exception ex)
{
ex.printStackTrace();
}
return null;
}
#Override
protected void onProgressUpdate(Integer... progress) {
super.onProgressUpdate(progress);
// if we get here, length is known, now set indeterminate to false
mProgressDialog.setIndeterminate(false);
mProgressDialog.setMax(100);
mProgressDialog.setProgress(progress[0]);
}
#Override
protected void onPostExecute(String result) {
mProgressDialog.dismiss();
if(result == null){
Toast.makeText(context, "Loading Beat failed. Please try again", Toast.LENGTH_SHORT).show();
RecordRap.this.finish();
}
else
{
}
}
public void saveInputStream(InputStream is) throws IOException
{
int n = 0;
DataInputStream in1;
in1 = new DataInputStream(is);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
try
{
while ((n = in1.read()) != -1)
{
bos.write(n);
}
}
catch (IOException e)
{
e.printStackTrace();
}
ByteBuffer bb = ByteBuffer.wrap(bos.toByteArray());
bb.order(ByteOrder.LITTLE_ENDIAN);
ShortBuffer sb = bb.asShortBuffer();
for (int i = 0; i < sb.capacity(); i++) {
beatsShortList.add(sb.get(i));
}
}
}
So thanks to #Stephen C the problem was while ((n = in1.read()) != -1) so i added a buffer and changed the code to the following and the problem is fixed now loading only takes a few seconds. Thanks to Stephen C for the help and as Ratul Sharker.
Updated code:
byte[] buffer = new byte[0xFFFF];
while ((n = in1.read(buffer)) != -1)
{
bos.write(buffer, 0, n);
}
for (int i = 0; i < sb.capacity(); i++) {
beatsShortList.add(sb.get(i));
}
This is the culprit what are you looking for :)
Related
Please help me to add update code to my app to be update from my server thank you
nothing worked from net , i need complete guide
You can't install your app without users permission and root access but you can download your applications new version from server then ask users for install. Here is an example:
{
PackageManager manager = context.getPackageManager();
try {
PackageInfo info = manager.getPackageInfo(context.getPackageName(), 0);
version = info.versionName;
if (newversion.replace(".", "") < version.replace(".", "")) {
new DownloadFileFromURL().execute("http://exampl.com/Content/files/example.apk");
}
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
}
}
private class DownloadFileFromURL extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
dialog = onCreateDialog();
}
#Override
protected String doInBackground(String... f_url) {
int count;
try {
File file = new File(Environment.getExternalStorageDirectory() + "/example.apk");
if (file.exists()) {
file.delete();
}
URL url = new URL(f_url[0]);
URLConnection conection = url.openConnection();
conection.connect();
int lenghtOfFile = conection.getContentLength();
pDialog.setMax(lenghtOfFile / 1024);
InputStream input = new BufferedInputStream(url.openStream(), 8192);
OutputStream output = new FileOutputStream(Environment.getExternalStorageDirectory() + "/example.apk");
byte data[] = new byte[1024];
long total = 0;
while ((count = input.read(data)) != -1) {
total += count;
publishProgress(total / 1024 + "");
output.write(data, 0, count);
}
output.flush();
output.close();
input.close();
} catch (Exception ignored) {
}
return null;
}
protected void onProgressUpdate(String... progress) {
pDialog.setProgress(Integer.parseInt(progress[0]));
}
#Override
protected void onPostExecute(String file_url) {
dialog.dismiss();
File file = new File(Environment.getExternalStorageDirectory() + "/example.apk");
if (file.exists()) {
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent);
} else {
//finish() or whatever you want
}
}
}
I found an excellent UnZip class with progress bar support for Android. However the progress bar does not update when clicking extract in my app. The Unzipping works fine.
Can someone please tell me what I am doing wrong?
public class UnZip1 extends AsyncTask<Void, Integer, Integer> {
{
}
private String _zipFile;
private String _location;
private ProgressDialog mProgressDialog;
private int per = 0;
private Context _conti;
private ProgressBar bar1;
public UnZip1(Context conti,String zipFile, String location) {
_conti = conti;
_zipFile = zipFile;
_location = location;
bar1 = (ProgressBar)findViewById(R.id.pb1);
_dirChecker("");
}
public void streamCopy(InputStream in, OutputStream out) throws IOException {
byte[] buffer = new byte[32 * 1024]; // play with sizes..
int readCount;
while ((readCount = in.read(buffer)) != -1) {
out.write(buffer, 0, readCount);
}
}
protected Integer doInBackground(Void... params) {
try {
ZipFile zip = new ZipFile(_zipFile);
FileInputStream fin = new FileInputStream(_zipFile);
ZipInputStream zin = new ZipInputStream(fin);
ZipEntry ze = null;
while ((ze = zin.getNextEntry()) != null) {
Log.v("Decompress", "Unzipping " + ze.getName());
if(ze.isDirectory()) {
_dirChecker(ze.getName());
} else {
// Here I am doing the update of my progress bar
Log.v("Decompress", "more " + ze.getName());
per++;
publishProgress(per);
FileOutputStream fout = new FileOutputStream(_location + ze.getName());
streamCopy(zin, fout);
zin.closeEntry();
fout.close();
} }
zin.close();
} catch(Exception e) {
Log.e("Decompress", "unzip", e);
}
return null;
}
protected void onProgressUpdate(Integer... progress) {
bar1.setProgress(per);
}
protected void onPostExecute(Integer... result) {
Log.i("UnZip" ,"Completed. Total size: "+result);
}
private void _dirChecker(String dir) {
File f = new File(_location + dir);
if(!f.isDirectory()) {
f.mkdirs();
}
}
}
}
You have to use the ProgressDialog with STYLE_HORIZONTAL
if you want to see the actual progress.
You can add the initialization in your preExecute():
#Override
protected void onPreExecute()
{
super.onPreExecute();
mProgressDialog = new ProgressDialog(MainActivity.this);
mProgressDialog.setOnCancelListener(new DialogInterface.OnCancelListener()
{
public void onCancel(DialogInterface dialog)
{
}
});
mProgressDialog.setCancelable(true);
mProgressDialog.setMessage("Progress");
mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
mProgressDialog.setProgress(1);
mProgressDialog.show();
}
MainActivity is the name of my activity class.
Then set the progress on the onProgressUpdate function.
protected void onProgressUpdate(Integer... progress)
{
mProgressDialog.setProgress(progress[0]);
}
Can you try this :
#Override
protected void onProgressUpdate(Integer... progress) {
// TODO Auto-generated method stub
super.onProgressUpdate(values);
bar1.setProgress(progress[0])
}
I'm using Apache's FTPClient to upload files to my server (images from the gallery if it matters)
I'm having a small and pretty insignificant problem, but I would still like to solve it.
The problem is that the bar is filled and reaches 100% before the upload actually completes, causing the dialog to show 100% for an extra 2-3 seconds on small files (and could be a lot more on files weighing several MBs).
I'm guessing it's because of the conversion from long to int, but that's just a guess.
Here's the code:
#Override
protected void onPreExecute() {
super.onPreExecute();
dialog = new ProgressDialog(UploadActivity.this);
dialog.setOnCancelListener(new OnCancelListener() {
#Override
public void onCancel(DialogInterface dialog) {
uploadImage.cancel(true);
}
});
dialog.setMessage("Uploading...\nPlease Wait.");
dialog.setIndeterminate(false);
dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
dialog.setProgress(0);
dialog.setCancelable(false);
dialog.setMax((int)(file.length()/1024));
dialog.setProgressNumberFormat ("%1dKB/%2dKB");
dialog.show();
}
#Override
protected String doInBackground(Void... params) {
CopyStreamAdapter streamListener = new CopyStreamAdapter() {
#Override // THIS PART IS RESPONSIBLE FOR UPDATING THE PROGRESS
public void bytesTransferred(long totalBytesTransferred, int bytesTransferred, long streamSize) {
int percent = (int) (totalBytesTransferred * 100 / file.length());
publishProgress(percent);
}
};
String name = null;
ftp.setCopyStreamListener(streamListener);
FileInputStream fis = null;
try {
String extension = "";
String fileName = file.getName();
int i = fileName.lastIndexOf('.');
int p = Math.max(fileName.lastIndexOf('/'), fileName.lastIndexOf('\\'));
if (i > p) {
extension = fileName.substring(i + 1);
}
SimpleDateFormat sdf = new SimpleDateFormat("ddMMyy-hhmmss-SSS");
name = String.format("File-%s.%s", sdf.format(new Date()), extension);
ftp.connect(FTP_SERVER);
ftp.enterLocalPassiveMode();
ftp.login(ftpUser, ftpPassword);
ftp.setFileType(FTP.BINARY_FILE_TYPE);
fis = new FileInputStream(file);
if (!ftp.storeFile(name, fis)) {
showToast("Failed uploading");
return null;
}
ftp.logout();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (fis != null) {
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return name;
}
#Override
protected void onProgressUpdate(Integer... values) {
dialog.setProgress(values[0]);
}
Thanks!
all is it possible to create a progress dialog to show the upload progress under a thread i use this code to upload a file called index.html to ftp.
please help me thanx in advance..
new Thread(new Runnable() {
public void run() {
Looper.prepare();
FTPClient client = new FTPClient();
try {
boolean result = false;
FileInputStream fis = null;
client.connect(server);
client.enterLocalPassiveMode();
client.login(user, pass);
client.makeDirectory("/public_html/"+str);
client.setFileType(FTP.BINARY_FILE_TYPE);
client.setFileTransferMode(FTP.BINARY_FILE_TYPE );
client.changeWorkingDirectory(str);
String path1 = Environment.getExternalStorageDirectory() + "/index.htm";
File f = new File(path1);
String testname = "/public_html/"+str+"/"+f.getName();
fis = new
FileInputStream(f);
result = client.storeFile(testname, fis);
if (result == true){
Log.v("upload","upload successfull");
}
else{
Log.v("upload", "upload failed");
}
client.logout();
client.disconnect();
}
catch (Exception e) {
Context context = getApplicationContext();
CharSequence text = "failed!!";
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
}
}
}).start();
Why not use an asynctask? With it you could spawn a dialog in the onPreExecute method than in the onProgressUpdate method update the progress of the background task...There are other ways of doing it but i believe this to be the cleanest and easiest
private class DownloadFilesTask extends AsyncTask<URL, Integer, Long> {
protected Long doInBackground(URL... urls) {
int count = urls.length;
long totalSize = 0;
for (int i = 0; i < count; i++) {
totalSize += Downloader.downloadFile(urls[i]);
publishProgress((int) ((i / (float) count) * 100));
// Escape early if cancel() is called
if (isCancelled()) break;
}
return totalSize;
}
protected void onProgressUpdate(Integer... progress) {
setProgressPercent(progress[0]);
}
protected void onPostExecute(Long result) {
showDialog("Downloaded " + result + " bytes");
}
}
The android dev reference should help clear things up http://developer.android.com/reference/android/os/AsyncTask.html
I'm apologise for my english.
I use the following piece of code to download a file from ftp host to Tablet. When I use Wi-Fi everything works well. But when I try to download a file using the mobile Internet, the download stops, but not always, sometimes finishes normally. I've found that stop is always going on "retrieveFile" or "logout", the program comes to these commands and no going further, and simply stands, the icon of data transfer does not blink, stops occur randomly. I tried to use different mobile operators, but there is no difference. What could be the reason?
And another question, but It is not so important, I've not found how to get the file size, and used my decision, maybe there is another way to get the file size ?
private void downloadFile(final String url, final String Message, final String Message2, final Uri uri) {
final ProgressDialog progressDialog = new ProgressDialog(this);
new AsyncTask() {
private Exception m_error = null;
#Override
protected void onPreExecute() {
progressDialog.setMessage(Message);
progressDialog.setCancelable(true);
progressDialog.setMax(100);
progressDialog
.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
progressDialog.show();
}
#Override
protected File doInBackground(String... params) {
FileOutputStream fos = null;
File file = null;
FTPClient client = null;
try{
client = new FTPClient();
client.connect(ftp_host,Integer.parseInt(ftp_port));
client.login(ftp_user, ftp_password);
client.enterLocalPassiveMode();
client.setFileType(FTP.BINARY_FILE_TYPE);
String stat = "";
if (url.equals("MobiTrade.apk")){
client.changeWorkingDirectory("/var/srv/home/user/mobitrade/update/");}
file = new File(Environment.getExternalStorageDirectory(),
"/MobiTrade/update/MobiTrade.apk");}
stat = client.getStatus("/var/srv/home/user/mobitrade/update/MobiTrade.apk");
else {
client.changeWorkingDirectory("/var/srv/home/user/mobitrade/"+number+"/out/");
file = new File(Environment.getExternalStorageDirectory(),
"/MobiTrade/in/"+url);
if (url.equals("message.csv")) file.delete();
stat = client.getStatus("/var/srv/home/user/mobitrade/"+number+"/out/"+url);
}
final Integer FileSize;
if (stat.length() >= 64) {
stat = stat.substring(49,64);
stat = stat.trim();
FileSize = Integer.parseInt(stat);
}
else {
FileSize = 0;
}
fos = new FileOutputStream(file);
CountingOutputStream cos = new CountingOutputStream(fos){
protected void beforeWrite(int n){
super.beforeWrite(n);
publishProgress(getCount(), FileSize);
}
};
if (url.equals("MobiTrade.apk")){
client.retrieveFile("/var/srv/home/user/mobitrade/update/MobiTrade.apk", cos);
}
else {
client.retrieveFile("/var/srv/home/user/mobitrade/"+number+"/out/"+url, cos);
}
if (url.equals("message.csv")){
client.deleteFile("/var/srv/home/user/mobitrade/"+number+"/out/"+url);
}
client.logout();
}
catch (Exception e){
e.printStackTrace();
}
finally{
try{
if (fos != null) fos.close();
if (client.isConnected()) {
client.disconnect();
}
}
catch (IOException e){
e.printStackTrace();
}
}
return file;
}
protected void onProgressUpdate(Integer... values) {
progressDialog
.setProgress((int) ((values[0] / (float) values[1]) * 100));
};
#Override
protected void onPostExecute(File result) {
if (m_error != null) {
m_error.printStackTrace();
return;
}
progressDialog.hide();
if (url.equals("settings.csv"))
ProcessSettings(url);
else if (url.equals("MobiTrade.apk"))
ProcessUpdate();
else
ProcessData(url, Message2, uri);
}
}.execute(url);
}
Any help would be appreciable.