onProgressUpdate() not called during downloading file from dropbox - android

I have been stucking from last 2 days.. In my case the onProgressUpdate() is not called.. So it is not updating the progress bar.. can any one please have a look and suggest.. Thanks. here is my code
package com.example.downloadupload;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Environment;
import android.util.Log;
import com.dropbox.client2.DropboxAPI;
import com.dropbox.client2.ProgressListener;
import com.dropbox.client2.android.AndroidAuthSession;
import com.dropbox.client2.exception.DropboxException;
public class DownloadFile extends AsyncTask<Void, Long, Boolean> {
DropboxAPI<AndroidAuthSession> dDBApi;
Context dContext;
private final ProgressDialog uDialog;
private long dFileLen;
long bytess;
public DownloadFile(Context context,
DropboxAPI<AndroidAuthSession> mDBApi) {
dDBApi=mDBApi;
dContext=context.getApplicationContext();
uDialog = new ProgressDialog(context);
uDialog.setMax(100);
uDialog.setMessage("Downloading Image");
uDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
uDialog.show();
}
#Override
protected Boolean doInBackground(Void... params) {
String path1= Environment.getExternalStorageDirectory()+"/log.txt";
BufferedOutputStream out=null;
try {
File file = new File(path1);
out = new BufferedOutputStream(new FileOutputStream(file));
dDBApi.getFile("/log.txt", null,out,new ProgressListener() {
/* #Override
public long progressInterval() {
// Update the progress bar every half-second or so
return 500;
}*/
#Override
public void onProgress(long bytes, long total) {
// TODO Auto-generated method stub
bytess=bytes;
publishProgress(bytes);
}
});
} catch (DropboxException e) {
Log.e("DbExampleLog", "Something went wrong while downloading.");
} catch (FileNotFoundException e) {
Log.e("DbExampleLog", "File not found.");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
if (out != null) {
try {
out.close();
} catch (IOException e) {}
}
}
return null;
}
#Override
protected void onProgressUpdate(Long... progress) {
// TODO Auto-generated method stub
super.onProgressUpdate(progress);
int percent = (int)(100.0*(double)progress[0]/bytess + 0.5);
uDialog.setProgress(percent);
System.out.println("Hi progressing");
}
#Override
protected void onPostExecute(Boolean result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
uDialog.dismiss();
System.out.println("calling post execute");
}
}

Instead of this
int percent = (int)(100.0*(double)progress[0]/bytess + 0.5);
Use this
int percent = (int)(100.0*(double)progress[0]/TotalsizeOfFile + 0.5);
And you can uncomment
#Override
public long progressInterval()
{
// Update the progress bar every half-second or so
return 500;
}
It's working for me.

I think the mistake is this
bytess=bytes;
publishProgress(bytes);
and then,
int percent = (int)(100.0*(double)progress[0]/bytess + 0.5);
here, progress[0] = bytess -> everytime, hence progress might not be getting updated.

Make onProgress() something like this
public void onProgress(long bytes, long total) {
// TODO Auto-generated method stub
long[2] bytess = {bytes, total};
publishProgress(bytess);
}
and calculate percentage
int percent = (int)(100.0*(double)progress[0]/progress[1]+ 0.5);

Related

My activity changes orientation on screen lock

I have set orientation of my activity to landscape and it remains in that state except one case.and the case is screen lock .when my activity is running and i lock my screen it changes orientation from landscape to portrait for little bit of time and causes my app to restart and which I don't want.any solution...?
package com.example.hello;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import android.app.Activity;
import android.app.KeyguardManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.media.MediaPlayer;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.os.PowerManager;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.MediaController;
import android.widget.Spinner;
import android.widget.Toast;
import android.widget.VideoView;
public class MainActivity extends Activity{
VideoView vv;
public ArrayList<String> list = new ArrayList<String>();
int n,positio = 0;
String file = null;
Spinner spin;
MediaPlayer mp;
Intent intent;
File fl;
boolean isPlaying = true;
boolean screenOn = false;
PowerManager pm;
#Override
public void onCreate(Bundle savedInstance){
super.onCreate(savedInstance);
Log.d("zaid iqbal", "in onCreate");
requestFullScreen();
setContentView(R.layout.activity_main);
vv = (VideoView)findViewById(R.id.video);
spin = (Spinner)findViewById(R.id.spinner);
MediaController mc = new MediaController(this);
pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
vv.setMediaController(mc);
setupSpin();
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
//Log.d("zaid iqbal", "in onPause");
isPlaying = vv.isPlaying();
screenOn = pm.isScreenOn();
if (screenOn && isPlaying) {
// Screen is still on, so do your thing here
n++;
positio = vv.getCurrentPosition();
vv.pause();
//Toast.makeText(this, file, Toast.LENGTH_LONG).show();
intent = new Intent(this,playBack.class);
intent.putExtra("file", file);
intent.putExtra("position", positio);
intent.putExtra("n", n);
startService(intent);
}
if(!isPlaying){
positio = vv.getCurrentPosition();
}
super.onPause();
}
#Override
protected void onResume() {
// TODO Auto-generated method stub
//Log.d("zaid iqbal", "in onResume");
if(!isPlaying){
vv.setVideoPath(file);
vv.seekTo(positio);
}else{
async aa = new async();
aa.execute();
}
super.onResume();
}
#Override
public void onBackPressed() {
// TODO Auto-generated method stub
}
public void requestFullScreen(){
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN
,WindowManager.LayoutParams.FLAG_FULLSCREEN);
}
public void setupSpin(){
File root = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/Video/");
listFiles(root);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item,list);
spin.setAdapter(adapter);
spin.setOnItemSelectedListener(new OnItemSelectedListener(){
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1,
int position, long id) {
// TODO Auto-generated method stub
//Log.d("zaid iqbal","in onclick of spin");
if(n == 0){
file = Environment.getExternalStorageDirectory().getAbsolutePath() + "/Video/" + list.get(position);
Log.d("zaid", file);
//Toast.makeText(MainActivity.this, "original" + file, Toast.LENGTH_SHORT).show();
vv.setVideoPath(file);
vv.start();
}
//n = 0;
/*File fl = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/Video/","settings.txt");
try {
BufferedReader reader = new BufferedReader(new FileReader(fl));
file = reader.readLine();
position = Integer.parseInt(reader.readLine());
reader.close();
BufferedWriter writer = new BufferedWriter(new FileWriter(fl));
writer.write(file);
writer.write(position);
writer.write(n);
position = Integer.parseInt(reader.readLine());
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}*/
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
}
public void listFiles(File f){
try{
File[] files = f.listFiles();
for(File file : files){
if(file.isFile()){
String filenameArray[] = file.toString().split("\\.");
String extension = filenameArray[filenameArray.length-1];
//if(extension == "mp4" || extension == "3gp")
list.add(file.getName());
}
}
}catch(Exception e){
e.printStackTrace();
}
}
class async extends AsyncTask<String,Long,Long>{
#Override
protected Long doInBackground(String... params) {
// TODO Auto-generated method stub
if(intent != null){
stopService(intent);
//Reading file
}
return null;
}
#Override
protected void onPostExecute(Long result) {
// TODO Auto-generated method stub
fl = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/Video/","settings.txt");
try {
//Log.d("zaid iqbal", "getted file");
BufferedReader reader = new BufferedReader(new FileReader(fl));
file = reader.readLine();
//Toast.makeText(MainActivity.this, "getted file" + file, Toast.LENGTH_SHORT).show();
positio = Integer.parseInt(reader.readLine());
n = Integer.parseInt(reader.readLine());
reader.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if(n != 0){
n=0;
try {
BufferedWriter writer = new BufferedWriter(new FileWriter(fl));
writer.write(file + "\n" + positio + "\n" + n);
writer.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
vv.setVideoPath(file);
vv.seekTo(positio);
vv.start();
}
super.onPostExecute(result);
}
}
}
First, I would read up on Android activity lifecycle. Personally I think this is the way begin to address the issue -
http://developer.android.com/training/basics/activity-lifecycle/index.html
Another option to investigate -
android:configChanges="orientation|keyboardHidden|screenSize"
how to stop activity recreation on screen orientation?
Try this in your Activity Tag of Manifest file :
<activity android:name=".MyActivity"
android:configChanges="orientation|keyboardHidden"
android:label="#string/app_name">
Here Orientation refers to Configuration changes which you want to handle by your own.
To declare that your activity handles a configuration change, edit the appropriate <activity> element in your manifest file to include the android:configChanges attribute with a value that represents the configuration you want to handle.
Use onSaveInstanceState() and onRestoreInstanceState() if you want to restore your previous state of an activity.
Refer this also
You may try to call setRequestedOrientation() in you activity so the orientation is forced.

Android, How to make a basic Handler Static

I am new to Android programming and only have a very basic knowledge of it. I am trying to understand basic multithreading.
I have followed a tutorial for creating a basic thread and displaying a progressDialog which simply adds 500 records to a database when the button is clicked.
public void btnAddClick(View v) {
// Create progress dialog to show status
dialog = ProgressDialog.show(MainActivity.this, "Loading", "Updating database...");
h = new Handler(){
#Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
dialog.dismiss();
}
};
// Create a new thread
new Thread() {
#Override
public void run() {
// TODO Auto-generated method stub
super.run();
// Time consuming task here
try {
Thread.sleep(1);
UpdateDB();
h.sendEmptyMessage(0);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
.start();
//UpdateDB();
}
With this code i get a warning within the IDE: This Handler class should be static or leaks might occur.
I Have 2 more buttons View and Clear, i use the same code for each of them and just UpdateDB(); Becomes ViewDB(); and ClearDB();
The code compiles and the AddClick works perfectly, but if i try and use ViewClick or ClearClick then my application crashes, on View sometimes the dialog displays for a few seconds then my application is crashing.
Is that caused by a resource leak? and can somebody please show me an example of how to make the Handler static so i avoid issues while using it.
The Full source code for the activity is here:
import android.app.Activity;
import android.app.ProgressDialog;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.Menu;
import android.view.View;
import android.widget.TextView;
public class MainActivity extends Activity {
protected ProgressDialog dialog;
protected Handler h;
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
DBAdapter myDb;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
checkDataBase();
}
#Override
protected void onDestroy() {
super.onDestroy();
closeDB();
}
private void openDB() {
myDb = new DBAdapter(this);
myDb.open();
}
private void closeDB() {
myDb.close();
}
private void displayText(String message) {
TextView textView = (TextView) findViewById(R.id.textDisplay);
textView.setText(message);
}
public void btnAddClick(View v) {
// Create progress dialog to show status
dialog = ProgressDialog.show(MainActivity.this, "Please Wait", "Updating database...");
h = new Handler(){
#Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
dialog.dismiss();
}
};
// Create a new thread
new Thread() {
#Override
public void run() {
// TODO Auto-generated method stub
super.run();
// Time consuming task here
try {
Thread.sleep(1);
UpdateDB();
h.sendEmptyMessage(0);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
.start();
//UpdateDB();
}
public void btnClearClick(View v) {
// Create progress dialog to show status
dialog = ProgressDialog.show(MainActivity.this, "Please Wait", "Deleting database...");
h = new Handler(){
#Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
dialog.dismiss();
}
};
// Create a new thread
new Thread() {
#Override
public void run() {
// TODO Auto-generated method stub
super.run();
// Time consuming task here
try {
Thread.sleep(1);
ClearDB();
h.sendEmptyMessage(0);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
.start();
}
public void btnViewClick(View v) {
// Create progress dialog to show status
dialog = ProgressDialog.show(MainActivity.this, "Please Wait", "Displaying records...");
h = new Handler(){
#Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
dialog.dismiss();
}
};
// Create a new thread
new Thread() {
#Override
public void run() {
// TODO Auto-generated method stub
super.run();
// Time consuming task here
try {
Thread.sleep(1);
ViewDB();
h.sendEmptyMessage(0);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
.start();
}
// Display full database inside TextView
private void displayRecordSet(Cursor cursor) {
String message = "";
// populate the message from the cursor
// Reset cursor to start, checking to see if there's data:
if (cursor.moveToFirst()) {
do {
// Process the data:
int id = cursor.getInt(DBAdapter.COL_ROWID);
String make = cursor.getString(DBAdapter.COL_MAKE);
String model = cursor.getString(DBAdapter.COL_MODEL);
String year = cursor.getString(DBAdapter.COL_YEAR);
String tyreSize = cursor.getString(DBAdapter.COL_TYRESIZE);
String front = cursor.getString(DBAdapter.COL_FRONT);
String rear = cursor.getString(DBAdapter.COL_REAR);
// Append data to the message:
message += "id=" + id
+", make=" + make
+", model=" + model
+", year=" + year
+", tyreSize=" + tyreSize
+", front=" + front
+", rear=" + rear
+"\n";
} while(cursor.moveToNext());
}
// Close the cursor to avoid a resource leak.
cursor.close();
displayText(message);
}
// Checks database file exists during OnCreate();
private boolean checkDataBase() {
SQLiteDatabase checkDB = null;
try {
String DB_FULL_PATH = "/data/data/com.digitak.mytyrepressure/databases/myDb";
checkDB = SQLiteDatabase.openDatabase(DB_FULL_PATH , null,
SQLiteDatabase.OPEN_READONLY);
checkDB.close();
} catch (SQLiteException e) {
// database doesn't exist yet.
System.out.println("Database Doesnt Exist...Creating");
openDB();
}
return checkDB != null ? true : false;
}
// Adds 500 Records to the database for testing purposes
public void UpdateDB() {
int x = 0;
while (x < 500) {
myDb.insertRow("Ford", "KA", "1996-2003", "155/70R13", "31", "26");
x++;
}
}
public void ViewDB() {
Cursor cursor = myDb.getAllRows();
displayRecordSet(cursor);
}
public void ClearDB() {
myDb.deleteAll();
}
}
Thank you for your time.
Probably it didn't happen because of leak but why it happened it would be easier to say if we see catlog..
Side note.. WTH is Thread.sleep(1) for???
Side note 2: You shouldn't use threads here at all.. If you need to do task in background in general there is AsyncTask class. Specifically for DB transaction, there are even better content provider and Loader concepts..
Hope I help a bit so you can go in the right direction.
Add this argument when creating Handler: Looper.getMainLooper()
Handler handler = new Handler(Looper.getMainLooper()){...
}
This should remove the warning

Don't know if it is safe to implement Asynctask like that

I made a code on android and i would like to receive some opinions from stackoverflow people.
It is about a code which i used the AsyncTask class... But i don't know if it is coded good or not ...
Here it is the code:
package com.example.basicmaponline;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.HashMap;
import java.util.concurrent.ExecutionException;
import android.app.Activity;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import com.mlab.android.basicoverlays.PostgreSQL;
import com.mlab.android.basicoverlays.SQLloja;
public class Intro extends Activity{
//SQLlistLoja listaLoja;
HashMap<String, SQLloja> listaLoja;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.intro);
//Intent openMainActivity = new Intent("com.example.basicmaponline.MAINACTIVITY"); //isto vem do ficheiro AndroidManifest.xml o "com.example....."
//startActivity(openMainActivity);
try {
listaLoja = new loadDatabase().execute().get();
} catch (InterruptedException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (ExecutionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if(listaLoja !=null){
for(SQLloja loja : listaLoja.values()){
Log.d("ASYNC25", loja.getNome() );
}
}
else{
Log.d("ASYNC25", "NAO GUARDOU!" );
}
Thread timer = new Thread(){
public void run(){
try{
sleep(3000);
}catch (InterruptedException e) {
// TODO: handle exception
e.printStackTrace();
}finally{
Intent openMenu = new Intent("com.example.basicmaponline.MENU"); //isto vem do ficheiro AndroidManifest.xml o "com.example....."
openMenu.putExtra("listaLoja",listaLoja);
startActivity(openMenu);
}
}
};
timer.start();
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
//ourSong.release(); //release the music and we are done with you
finish();
}
//#SuppressWarnings("rawtypes")
public class loadDatabase extends AsyncTask<Void, Void, HashMap<String,SQLloja>>{
#Override
protected HashMap<String,SQLloja> doInBackground(Void... params) {
// TODO Auto-generated method stub
HashMap<String,SQLloja>listaLojas = new HashMap<String, SQLloja>();
try{
PostgreSQL pSQL = new PostgreSQL(host,db, username, password);
String sql = pSQL.getLojasCidadao();
Statement st = pSQL.getConnection().createStatement();
ResultSet rs = st.executeQuery(sql);
Log.d("ASYNC2","Entrei na thread ASYNCTASK");
while(rs.next()){
int lcId = Integer.parseInt(rs.getString(1));
String lcNome=rs.getString(2);
String lcCP = rs.getString(3);
int lcDistrito = Integer.parseInt(rs.getString(4));
int lcConselho = Integer.parseInt(rs.getString(5));
double lcAltitude = Double.parseDouble(rs.getString(6));
double lcLongitude = Double.parseDouble(rs.getString(7));
String lcTelefone = rs.getString(8);
boolean lcEstado = Boolean.parseBoolean(rs.getString(9));
String lcRua = rs.getString(10);
SQLloja loja = new SQLloja(lcId,lcNome,lcCP,lcDistrito,lcConselho,lcAltitude,lcLongitude,lcTelefone,lcEstado,lcRua);
listaLojas.put(loja.getNome(),loja.clone());
String informacoesLoja = "Rua : "+lcRua+"\nC.P. : "+lcCP+"\nTel. : "+lcTelefone;
Log.d("ASYNC",lcNome+" Altitude = "+lcAltitude+" Longitude = "+lcLongitude+" Rua = "+lcRua);
}
//listaLoja = new SQLlistLoja(listaLojas);
rs.close();
st.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
if(listaLojas!=null){
Log.d("ASYNC","entrei no if da listaLojas");
for(SQLloja loja : listaLojas.values()){
Log.d("ASYNC", loja.getNome() );
}
}
else Log.d("ASYNC","listaLoja nula ! PQP !");
return listaLojas;
}
#Override
protected void onPostExecute(HashMap<String,SQLloja> listaLojas){
listaLoja = listaLojas;
for(SQLloja loja : listaLoja.values()){
Log.d("ASYNC24", loja.getNome() );
}
}
}
}
I'm not sure but, i think that the return value from AsyncTask isn't made by the right way although its working on my android application.
Some opinions will be welcomed.
Thank you ! :)
When you use the AsyncTask its good create a class instance to implement the methods, and then when you want to use, create a variable asynctask with the method .start(); if i'm no mistaken.
And its good too create a ProgressDialog.

Printing integer values in a textview and thread sleep time

How do I print integer values in a textview and also when I increasing the sleep time in the thread its not working correctly in android.
package com.example.chaljayar;
import java.util.concurrent.Delayed;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.widget.TextView;
public class MainActivity extends Activity implements Runnable
{
TextView Tv;
int num = 0, i = 0;
String con = "";
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Tv = (TextView)findViewById(R.id.Text);
Thread test = new Thread(this);
test.start();
}
#Override
public void run()
{
// TODO Auto-generated method stub
while(i <= 100)
{
try{
con += Integer.toString(i);
Tv.setText(con);
Thread.sleep(1000);
} catch (Exception e)
{
// TODO: handle exception
e.printStackTrace();
}
i++;
}
}
}
Try this To Thread alone and the other out of (try/catch) :
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
If you want any thing about print int values in textview show this link please :
Integer value in TextView

Why is this app running slow?

Why does this app stop answering then I press play? It sometimes show a "the application is not responding" but it works if I wait.
It works nice on my emulator, but not on my phone (or any other phone I tried).
All it does is streaming sound.
package comunicera.se;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import android.app.ListActivity;
import android.content.Context;
import android.media.MediaPlayer;
import android.net.ConnectivityManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Html;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ProgressBar;
import android.widget.TextView;
public class Godnattsaga extends ListActivity {
/** Called when the activity is first created. */
ListView list;
TextView spelandesSagqa;
//private ProgressDialog mProgressDialog;
ProgressBar myProgressBar;
int myProgress = 0;
MediaPlayer mp = new MediaPlayer();
String BASEURL = "http://godnattsaga.nu/sagor";
public static long glCurrentSaga = 0;
public static String giCode = null;
int giAntalSagor = 0;
int possWhenPaused = 0;
ProgressBar myBufferProgressBar;
TextView buffrarText;
int progress;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
try
{
new Thread(buffer).start();
String lsSagor = getFileFromUrl(BASEURL+"/gratisSagor.txt");
final String[] laList = lsSagor.split("~");
giAntalSagor = laList.length;
//String saga = laList[0].replaceAll("#", "\n");
String[] laSaga = laList[0].split("#");
final String[] guiLaList = new String[giAntalSagor];
for (int i = 0; i < giAntalSagor; i++)
{
guiLaList[i] = laList[i].replaceAll("#", "\n");
}
changeSpelandesSaga(laSaga[0]);
setList (guiLaList);
ListView list = getListView();
list.setTextFilterEnabled(true);
list.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
String liCode = kop(id);
glCurrentSaga = id;
String[] laSaga = laList[(int) glCurrentSaga].split("#");
changeSpelandesSaga(laSaga[0]);
}
});
final Button button = (Button) findViewById(R.id.SpelaPause);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
selectDownloadOrPLay(laList);
}
});
glCurrentSaga = 0;
changeSpelandesSaga(laSaga[0]);
}
catch (Exception e)
{
changeSpelandesSaga("Check your connection, are you in flightmode?");
}
}
public void selectDownloadOrPLay(String[] laList) {
String[] laSaga = laList[(int) glCurrentSaga].split("#");
String url = BASEURL+"/gratis/"+laSaga[0].replaceAll(" ", "_")+".mp3";
if (mp.isPlaying())
{
mp.pause();
possWhenPaused=mp.getCurrentPosition();
}
else if (possWhenPaused != 0)
{
mp.start();
}
else
{
startSaga (url);
}
}
private String kop(long id)
{
mp.pause();
return "gratis";
}
public void setList (String[] laList)
{
/*
*
final String[] lAList = new String[3];
lAList[0] = "Saga 1 \n";
lAList[1] = "Saga 2 \n";
lAList[2] = "Saga 3";
setList (lAList);
*
*/
setContentView(R.layout.main);
ArrayAdapter<String> appointmentList = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, laList);
list=(ListView)findViewById(android.R.id.list);
list.setAdapter(appointmentList);
}
public void changeSpelandesSaga(String sagaRubrik)
{
possWhenPaused = 0;
TextView t = new TextView(this);
t=(TextView)findViewById(R.id.spelandesSaga);
t.setText(Html.fromHtml("<b>"+sagaRubrik+"</b>"));
}
private void startSaga(String url)
{
try {
mp.reset();
mp.setDataSource(url);
mp.prepare();
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
mp.start();
myProgressBar=(ProgressBar)findViewById(R.id.mProgressDialog);
new Thread(myThread).start();
}
private Runnable myThread = new Runnable(){
#Override
public void run() {
// TODO Auto-generated method stub
while (myProgress<100){
try{
myHandle.sendMessage(myHandle.obtainMessage());
Thread.sleep(1000);
}
catch(Throwable t){
}
}
}
Handler myHandle = new Handler(){
double poss = 0.0;
double sagaleng = 0.0;
#Override
public void handleMessage(Message msg) {
// TODO Auto-generated method stub
poss = mp.getCurrentPosition();
sagaleng = mp.getDuration();
progress = (int) ((int)poss / sagaleng * 100);
myProgress = progress;
myProgressBar.setProgress(progress);
}
};
};
public static String getFileFromUrl(String url)
{
InputStream content = null;
try
{
HttpGet httpGet = new HttpGet(url);
HttpClient httpclient = new DefaultHttpClient();
// Execute HTTP Get Request
HttpResponse response = httpclient.execute(httpGet);
content = response.getEntity().getContent();
}
catch (Exception e)
{
showNoConnection ();
return null;
}
BufferedReader rd = new BufferedReader(new InputStreamReader(content), 4096);
String line;
StringBuilder sb = new StringBuilder();
try {
while ((line = rd.readLine()) != null) {
sb.append(line);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
rd.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return sb.toString();
}
public boolean isOnline() {
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
boolean connected = cm.getActiveNetworkInfo().isConnectedOrConnecting();
return connected;
}
private static void showNoConnection()
{
}
private Runnable buffer = new Runnable(){
#Override
public void run() {
// TODO Auto-generated method stub
while (myProgress<100){
try{
myHandle.sendMessage(myHandle.obtainMessage());
Thread.sleep(1000);
}
catch(Throwable t)
{
}
}
}
Handler myHandle = new Handler(){
#Override
public void handleMessage(Message msg) {
// TODO Auto-generated method stub
//SpelaPause.setImageURI("pauseicon");
myBufferProgressBar = (ProgressBar)findViewById(R.id.mBuffrar);
TextView bufferText = (TextView)findViewById(R.id.buffrarText);
if (mp.isPlaying() && progress == 0)
{
myBufferProgressBar.setVisibility(View.VISIBLE);
bufferText.setVisibility(View.VISIBLE);
}
else
{
myBufferProgressBar.setVisibility(View.INVISIBLE);
bufferText.setVisibility(View.INVISIBLE);
}
}
};
};
}
If your application uses internet, it is possible, that the phone has worse connection than your comp. For example, if they both run on the SAME WiFi, at the same point, phones are connected MUCH worse than PC. Slower connection - you have to wait...
Read http://developer.android.com/guide/practices/design/responsiveness.html and http://developer.android.com/guide/practices/design/performance.html - VERY useful. For example, you will know the name of your problem - bad responsiveness (not performance) - for better further searches. :-)
All long-lasting tasks should be run in separate thread, not in UI thread. You call getFileFromUrl(..) from onCreate(..) method. This cause hangings.
I recommend you not to do any time consuming task in onCreate(..) method. In general an activity won't be shown till onCreate(..) is finished.
You are using getFileFromUrl in your onCreate method. Your method just performs the download action, which in case could last some time. You should always move long running tasks into it's own thread and notify the UI thread only.
Consider never running big logic in the UI thread, the UI thread should only be responsible for UI stuff.
To download a file in an async manner try to use the AsyncTask: http://developer.android.com/reference/android/os/AsyncTask.html
This code works, without responsiveness problems. But the buffering takes to long time so I need another solution.
I'm posting some code if someone else have the same problem
package comunicera.se;
import java.io.IOException;
import android.app.Activity;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
public class GodnattsagaTest1 extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final Button button = (Button) findViewById(R.id.SpelaPause);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
selectDownloadOrPLay();
}
});
}
public void selectDownloadOrPLay() {
Toast.makeText(getApplicationContext(), "Before ... ", Toast.LENGTH_SHORT).show();
Saga.startSaga ();
Toast.makeText(getApplicationContext(), "after ... ", Toast.LENGTH_SHORT).show();
}
}
class Saga
{
static MediaPlayer mp = new MediaPlayer();
static void startSaga()
{
new Thread(spelaSaga).start();
}
private static Runnable spelaSaga = new Runnable(){
#Override
public void run() {
// TODO Auto-generated method stub
try {
mp.reset();
mp.setDataSource("http://godnattsaga.nu/sagor/gratis/Fisken.mp3");
mp.prepare();
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
mp.start();
}
};
}
I believe it has something to do with the progress bar you use. I use one and it slows my app. Not sure if the progress bar must slow the app or there is another way to avoid this though.

Categories

Resources