Printing integer values in a textview and thread sleep time - android

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

Related

how to record android click event background

I want to record the android click event when I use other apps. For each click, I record its timestamp. So, this app should run background. I use the "getevent" to catch the click event. I am not very familiar with Android operation. My code
has a bug. Its output is not very good, there are many "null"s in the output, and the record is not exactly right.(My app needs root permission)
1.MainActivity.java
package kingofne.seu.edu.ndktest;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
private EditText editText = null;
private TextView textView = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editText = (EditText) findViewById(R.id.editText);
textView = (TextView) findViewById(R.id.textView);
Button btn_start = (Button) findViewById(R.id.btn_start);
if (btn_start != null) {
btn_start.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent();
intent.setClass(getApplicationContext(), MyService.class);
int param = 1;
if (editText != null) {
param = Integer.valueOf(String.valueOf(editText.getText()));
}
intent.putExtra("param", param);
startService(intent);
Toast.makeText(getApplicationContext(), "start", Toast.LENGTH_SHORT).show();
textView.setText(String.valueOf(System.currentTimeMillis()));
}
});
}
Button btn_stop = (Button) findViewById(R.id.btn_stop);
if (btn_stop != null) {
btn_stop.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent();
intent.setClass(getApplicationContext(), MyService.class);
stopService(intent);
Toast.makeText(getApplicationContext(), "stop", Toast.LENGTH_SHORT).show();
}
});
}
}
}
2.MyService.java
package kingofne.seu.edu.ndktest;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.text.SimpleDateFormat;
import java.util.Date;
public class MyService extends Service {
private boolean isRunning = false;
private int param = 1;
private Thread captureThread = null;
private volatile boolean doCapture = false;
public MyService() {
}
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
if (isRunning) {
return START_NOT_STICKY;
}
param = intent.getIntExtra("param", 1);
this.captureThread = new Thread(new Producer());
captureThread.setDaemon(true);
this.doCapture = true;
captureThread.start();
isRunning = true;
return START_NOT_STICKY;
}
#Override
public void onDestroy() {
super.onDestroy();
// stop the thread
this.doCapture = false;
// destroy the thread
this.captureThread = null;
}
private class Producer implements Runnable {
public void run() {
Log.d("ps", "going to run");
Date now = new Date();
SimpleDateFormat sDateFormat = new SimpleDateFormat(
"yyyy-MM-dd-HH-mm-ss");
String str2 = sDateFormat.format(now);
// String location = str2;
//String cmdLine = "getevent -t -l /dev/input/event" + String.valueOf(param) + " > /sdcard/guo" + ".txt";
String cmdLine = "cat /dev/input/event" + String.valueOf(param) + " > /sdcard/guo.txt";
CMDExecute cmd = new CMDExecute();
try {
// cmd.run_su("getevent -t > /sdcard/Yang_"+location+".txt");
cmd.run_su(cmdLine);
} catch (IOException e) {
// TODO Auto-generated catch block
Log.d("ps", "error");
e.printStackTrace();
}
}
};
class CMDExecute {
public synchronized String run(String[] cmd, String workdirectory)
throws IOException {
String result = "";
try {
ProcessBuilder builder = new ProcessBuilder(cmd);
BufferedReader in = null;
// 设置一个路径
if (workdirectory != null) {
builder.directory(new File(workdirectory));
builder.redirectErrorStream(true);
Process process = builder.start();
process.waitFor();
in = new BufferedReader(new InputStreamReader(process
.getInputStream()));
char[] re = new char[1024];
int readNum;
while ((readNum = in.read(re, 0, 1024)) != -1) {
// re[readNum] = '\0';
result = result + new String(re, 0, readNum);
}
}
if (in != null) {
in.close();
}
} catch (Exception ex) {
ex.printStackTrace();
}
return result;
}
public synchronized String run_su(String cmd)
throws IOException {
String result = "";
Process p=null;
try {
p = Runtime.getRuntime().exec("su");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
DataOutputStream os = new DataOutputStream(p.getOutputStream());
BufferedReader is = new BufferedReader(new InputStreamReader(p.getInputStream()));
try {
String istmp;
os.writeBytes(cmd+"\n");
//os.writeBytes("exit\n");
os.flush();
os.writeBytes("exit\n");
os.flush();
p.waitFor();
is.close();
os.close();
p.destroy();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
} return result;
}
}
}

android java.lang.NullPointerException - I think I've instantiated every object

I've searched for hours on this null pointer exception but with to no avail. From what I've read there seems to be some object that has not yet been instantiated. I've revised my code over and over but I can't find where I've gone wrong. If I comment out the for loop containing the compTurn(); in onCreate(); then it gets to the main screen but obviously doesn't perform the function I need it too.
Thank you in advance :)
package com.hunsdale.cognitive;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.Random;
import android.app.Activity;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.TextView;
public class Main extends Activity {
// Initialise ArrayLists
static ArrayList<Integer> Computer;
static ArrayList<Integer> Player;
// Initialise Computer's Arraylist Iterator
static Iterator<Integer> CompIt;
// Initialise computer's pick and user's pick for arraylist
static int compPick, userPick, level;
// Initialise counter for score
static int counter;
// Initialise random number generator and boolean(for next level
// advance)
static Random rand;
// Initialise sounds for buttons
static MediaPlayer Mblue, Mgreen, Mred, Morange, Mturn;
// Initialise buttons
static ImageView blue, green, red, orange, turnSwitch;
// Initialise string to show their score to the user
TextView score;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// set content = main.xml
setContentView(R.layout.main);
// Instantiate buttons
blue = (ImageView) findViewById(R.id.blue_button);
blue.setOnClickListener(onClickListener);
green = (ImageView) findViewById(R.id.green_btn);
green.setOnClickListener(onClickListener);
red = (ImageView) findViewById(R.id.red_btn);
red.setOnClickListener(onClickListener);
orange = (ImageView) findViewById(R.id.orange_btn);
orange.setOnClickListener(onClickListener);
// Instantiate button sounds
Mblue = MediaPlayer.create(Main.this, R.raw.bubble);
Mgreen = MediaPlayer.create(Main.this, R.raw.release);
Mred = MediaPlayer.create(Main.this, R.raw.texture_scratch);
Morange = MediaPlayer.create(Main.this, R.raw.whistle_scratch);
// Instantiate score display
score = (TextView) findViewById(R.id.score);
// Instantiate ArrayLists
Computer = new ArrayList<Integer>();
compPick = 0;
userPick = 0;
for (int i = 0; i <= 20; i++) {
compTurn();
}
}
public static void compTurn() {
if (Player.equals(Computer)) {
level++;
Mblue.reset();
Mgreen.reset();
Mred.reset();
Morange.reset();
Player = new ArrayList<Integer>();
counter = 0;
// the buttons cannot be clicked
blue.setEnabled(false);
green.setEnabled(false);
red.setEnabled(false);
orange.setEnabled(false);
compPick = rand.nextInt(4);
Computer.add(compPick);
for (Iterator<Integer> CompIt = Computer.iterator(); CompIt.hasNext();) {
Integer i = CompIt.next();
if (i == 0) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
blue.setImageResource(R.drawable.btn_blue_hghlight);
Mblue.start();
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
blue.setImageResource(R.drawable.cst_btn_blue);
Mblue.reset();
} else if (i == 1) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
green.setImageResource(R.drawable.btn_green_highlight);
Mgreen.start();
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
green.setImageResource(R.drawable.cst_btn_green);
Mgreen.reset();
} else if (i == 2) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
red.setImageResource(R.drawable.btn_red_highlight);
Mred.start();
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
red.setImageResource(R.drawable.cst_btn_red);
Mred.reset();
} else if (i == 3) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
orange.setImageResource(R.drawable.btn_orange_highlight);
Morange.start();
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
orange.setImageResource(R.drawable.big_btn_orange2);
Morange.reset();
}
}
} else if (counter < Computer.size()) {
enableUserTurn(true);
counter++;
}
}
public static void enableUserTurn(boolean buttonsEnabled) {
// enable buttons to be clicked
blue.setEnabled(buttonsEnabled);
green.setEnabled(buttonsEnabled);
red.setEnabled(buttonsEnabled);
orange.setEnabled(buttonsEnabled);
}
private OnClickListener onClickListener = new OnClickListener() {
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.blue_button:
Mblue.start();
Player.add(counter, 0);
if (Player.indexOf(counter) == (Computer.indexOf(counter))) {
compTurn();
} else {
score.setText("Fail");
}
break;
case R.id.green_btn:
Mgreen.start();
Player.add(counter, 1);
if (Player.indexOf(counter) == (Computer.indexOf(counter))) {
compTurn();
} else {
score.setText("Fail");
}
break;
case R.id.red_btn:
Mred.start();
Player.add(counter, 2);
if (Player.indexOf(counter) == (Computer.indexOf(counter))) {
compTurn();
} else {
score.setText("Fail");
}
break;
case R.id.orange_btn:
Morange.start();
Player.add(counter, 3);
Morange.reset();
if (Player.indexOf(counter) == (Computer.indexOf(counter))) {
compTurn();
} else {
score.setText("Fail");
}
break;
}
}
};
}
The culprit is this:
if (Player.equals(Computer))
You missed creating object Player and it is null. If you change it to
if (Computer.equals(Player))
it should work.
You are trying to use Player before it's initialized.
Do this:
// Instantiate ArrayLists
Computer = new ArrayList<Integer>();
Player = new ArrayList<Integer>();
compPick = 0;
userPick = 0;
for (int i = 0; i <= 20; i++) {
compTurn();
}
...

asynctaskrunner error in android application

while using asynctask runner in android application i got some struck here in running asynctaskrunner in while loop after every 5 seconds to show gps coordinates in a text view .
package com.example.gpsproject;
import android.content.Context;
import android.location.Location;
import android.os.AsyncTask;
import android.widget.TextView;
public class AsyncTaskRunner extends AsyncTask<Void,Void,Void> {
private final Context mContext;
TextView latitude,longitude;
public AsyncTaskRunner(Context c,TextView lat,TextView lon) {
// TODO Auto-generated constructor stub
mContext = c;
latitude = lat;
longitude = lon;
}
Location a = new Location("zfcdha");
String lonii,latii;
private void sleep(int i) {
// TODO Auto-generated method stub
}
protected void onPostExecute() {
}
#Override
protected void onPreExecute() {
}
protected Void doInBackground(Void... params) {
try {
GPSTracker mytracker = new GPSTracker(mContext);
while(true){
latii = "" + a.getLatitude();
lonii = "" + a.getLongitude();
latitude.setText(latii);
longitude.setText(lonii);
sleep(5000);
}
} catch (Exception e) {
e.printStackTrace();
;
}
;
return null;
}
}
onPostExecute(Result) runs on UI Thread
onPreExecute() runs on UI Thread
doInBackground(Void... params) runs on its own thread
you should never change the UI in another thread,we prefer using message.
you should update UI in main thread,not in background thread. you can use Handler to send a message to set the value.or you can use runOnUiThread method,like below :
protected Void doInBackground(Void... params) {
try {
GPSTracker mytracker = new GPSTracker(mContext);
while(true){
latii = "" + a.getLatitude();
lonii = "" + a.getLongitude();
currentActivity.this.runOnUiThread(new Runnable() {
public void run()
{
latitude.setText(latii);
longitude.setText(lonii);
}
});
sleep(5000);
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}

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.

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