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

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();
}
...

Related

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

DatagramSocket.receive only receives the first two Datagrams

I am sending some data to an android application over UDP. Therefore i created the following UDPReceiver-Class:
package com.example.urowatch;
import java.net.*;
import java.nio.ByteBuffer;
import java.io.*;
public class UDPReceiver extends Thread
{
private DatagramSocket m_Socket;
private int m_BufferSize;
private Boolean m_End = false;
private int m_TotalLength;
private int m_Received;
private byte[] m_Buffer;
private byte[] m_Result;
private Boolean m_IsNewResult = false;
private float m_Progress;
private int m_ImageCount = 0;
private int m_FrameErrors = 0;
public UDPReceiver(String name, int port, int bufferSize) throws IOException
{
super(name);
m_Socket = new DatagramSocket(port);
m_BufferSize = bufferSize;
m_Socket.setBroadcast(true);
m_Socket.setReceiveBufferSize(m_BufferSize);
}
public void run()
{
while(!m_End)
{
try
{
byte[] buf = new byte[m_BufferSize];
DatagramPacket packet = new DatagramPacket(buf, buf.length);
m_Socket.receive(packet);
ProcessData(packet);
}
catch (IOException e)
{
if (!m_Socket.isClosed())
e.printStackTrace();
}
}
}
private void ProcessData(DatagramPacket packet)
{
if (packet.getLength() == 4)
{
ByteBuffer bb = ByteBuffer.wrap(packet.getData());
m_TotalLength = bb.getInt();
if (m_Received != 0)
m_FrameErrors++;
m_Received = 0;
m_Buffer = new byte[m_TotalLength];
}
else if (m_Buffer != null && m_Received != m_TotalLength)
{
int length = packet.getLength();
System.arraycopy(packet.getData(), 0, m_Buffer, m_Received, length);
m_Received += length;
m_Progress = 100 * (float)m_Received/(float)m_TotalLength;
if (m_Received == m_TotalLength)
{
m_Result = new byte[m_TotalLength];
System.arraycopy(m_Buffer, 0, m_Result, 0, m_TotalLength);
m_IsNewResult = true;
m_ImageCount++;
m_Received = 0;
}
}
}
public Boolean IsNewResult()
{
return m_IsNewResult;
}
public byte[] GetResult()
{
m_IsNewResult = false;
return m_Result;
}
public float GetProgress()
{
return m_Progress;
}
public float GetRatio()
{
return 100 * (float)m_ImageCount / (float)m_FrameErrors;
}
public void stopServer()
{
m_End = true;
if (m_Socket != null)
m_Socket.close();
}
}
And i am using this class like this:
package com.example.urowatch;
import java.io.IOException;
import java.text.DecimalFormat;
import android.os.*;
import android.app.Activity;
import android.app.AlertDialog;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import android.support.v4.app.NavUtils;
import android.annotation.TargetApi;
import android.content.Context;
import android.graphics.BitmapFactory;
import android.os.Build;
public class LiveActivity extends Activity {
private static ImageView m_ImageView1;
private static TextView m_TextView1;
private static DecimalFormat m_DF;
private static Context m_Context;
private UDPReceiver m_Receiver;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_live);
// Show the Up button in the action bar.
setupActionBar();
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
m_ImageView1 = (ImageView)findViewById(R.id.imageView1);
m_TextView1 = (TextView)findViewById(R.id.textView1);
m_Context = this;
m_DF = new DecimalFormat("00.00");
}
/**
* Set up the {#link android.app.ActionBar}, if the API is available.
*/
#TargetApi(Build.VERSION_CODES.HONEYCOMB)
private void setupActionBar() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
getActionBar().setDisplayHomeAsUpEnabled(true);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.live, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
// This ID represents the Home or Up button. In the case of this
// activity, the Up button is shown. Use NavUtils to allow users
// to navigate up one level in the application structure. For
// more details, see the Navigation pattern on Android Design:
//
// http://developer.android.com/design/patterns/navigation.html#up-vs-back
//
NavUtils.navigateUpFromSameTask(this);
return true;
}
return super.onOptionsItemSelected(item);
}
private static Handler MyHandler = new Handler()
{
#Override
public void handleMessage(Message msg)
{
if (msg.what == 100)
{
float[] infos = (float[])msg.obj;
m_TextView1.setText("Empfange Bild: " + m_DF.format(infos[0]) + "% (FrameErrors: " + m_DF.format(infos[1]) + "%)");
}
else if (msg.what == 101)
{
byte[] b = (byte[])msg.obj;
m_TextView1.setText("Empfange Bild: 100,00%");
m_ImageView1.setImageBitmap(BitmapFactory.decodeByteArray(b, 0, b.length));
}
else if (msg.what == 102)
{
AlertDialog.Builder b = new AlertDialog.Builder(m_Context);
b.setTitle("Fehler");
b.setMessage("Es ist folgende Exception aufgetreten:\n" + (Exception)msg.obj);
b.setNeutralButton("OK", null);
b.show();
}
}
};
#Override
public void onBackPressed() {
super.onBackPressed();
if (m_Receiver != null)
m_Receiver.stopServer();
finish();
}
#Override
public void onPause()
{
m_Receiver.stopServer();
super.onPause();
}
#Override
protected void onResume()
{
try {
m_Receiver = new UDPReceiver("UDPReceiver", 5678, 1024);
m_Receiver.start();
} catch (IOException e1)
{
// TODO Auto-generated catch block
e1.printStackTrace();
AlertDialog.Builder b = new AlertDialog.Builder(this);
b.setTitle("Fehler");
b.setMessage("Es ist folgende Exception aufgetreten:\n" + e1);
b.setNeutralButton("OK", null);
b.show();
}
// Thread thread = new Thread()
// {
// #Override
// public void run()
// {
// while(true)
// {
// try {
//sleep(250);
Toast.makeText(getBaseContext(), "Runing Thread", Toast.LENGTH_SHORT).show();
Update();
// } catch (InterruptedException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// MyHandler.sendMessage(MyHandler.obtainMessage(102, e));
// }
// }
// }
// };
// thread.start();
super.onResume();
}
public void buttonClick(View v)
{
Update();
}
private void Update()
{
if (m_Receiver != null)
{
if (m_Receiver.IsNewResult())
{
byte[] b = m_Receiver.GetResult();
MyHandler.sendMessage(MyHandler.obtainMessage(101, b));
}
else
{
float[] infos = new float[2];
infos[0] = m_Receiver.GetProgress();
infos[1] = m_Receiver.GetRatio();
MyHandler.sendMessage(MyHandler.obtainMessage(100, infos));
}
}
}
}
As you see i want to check the status of the UDPReceiver-Object (Is there a new complete byte[] ready?) by a thread. To update the GUI, the thread has to send a Message to MyHandler which will update the GUI.
In the moment i have to to click a button to raise the buttonClick-Event. Later on i want to do this in the commented thread-structure.
Now, here's my problem:
I start the Activity and everything works fine. Then i am starting to send ONE packet manually with my UDP-Sender (which works, i validated it with a C#-UDP-Receiver). The first packet get received fine. Then i send the second packet which get received, too. But from now on, my breakpoint at m_Socket.receive(packet); wont get hit anymore!
I have NO idea what this behaviour causes and it is very important for me to make this application work.
Please, if you have ANY Idea or just a guess, please let me know.

My application isn't working smoothly

I am trying to develop a application. It is a radio application. When i use a method to show meta data that time it is creating some problem.
1.Play Pause button are not working smoothly.
2.Taking more time to show layout.
here is the main activity code:
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Timer;
import java.util.TimerTask;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.widget.ImageButton;
import android.widget.TextView;
public class IRadioActivity extends Activity implements
MediaPlayer.OnCompletionListener, MediaPlayer.OnPreparedListener,
MediaPlayer.OnErrorListener, MediaPlayer.OnBufferingUpdateListener {
private String TAG = getClass().getSimpleName();
private MediaPlayer mp = null;
private ImageButton btnPlay;
String title;
String artist;
private static Context con;
Timer timer;
TextView StationName;
String Stationurl = "http://95.211.82.139:8048";
#Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.main);
IRadioActivity.con = this;
btnPlay = (ImageButton) findViewById(R.id.btnPlay);
mp = new MediaPlayer();
mp.setOnCompletionListener(this); // Important
btnPlay.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
// check for already playing
if (mp.isPlaying()) {
if (mp != null) {
mp.pause();
// Changing button image to play button
btnPlay.setImageResource(R.drawable.btn_play);
}
} else {
// Resume song
if (mp != null) {
mp.start();
// Changing button image to pause button
btnPlay.setImageResource(R.drawable.btn_pause);
}
}
}
});
playSong();
getMeta();
}
public void playSong() {
// Play song
try {
mp.reset();
mp.setDataSource(Stationurl);
mp.prepare();
mp.start();
// Displaying Song title
// Changing Button Image to pause image
btnPlay.setImageResource(R.drawable.btn_pause);
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public void onDestroy() {
super.onDestroy();
mp.release();
}
public void onCompletion(MediaPlayer mp) {
// TODO Auto-generated method stub
}
// ----------------
public boolean onError(MediaPlayer mp, int what, int extra) {
StringBuilder sb = new StringBuilder();
sb.append("Media Player Error: ");
switch (what) {
case MediaPlayer.MEDIA_ERROR_NOT_VALID_FOR_PROGRESSIVE_PLAYBACK:
sb.append("Not Valid for Progressive Playback");
break;
case MediaPlayer.MEDIA_ERROR_SERVER_DIED:
sb.append("Server Died");
break;
case MediaPlayer.MEDIA_ERROR_UNKNOWN:
sb.append("Unknown");
break;
default:
sb.append(" Non standard (");
sb.append(what);
sb.append(")");
}
sb.append(" (" + what + ") ");
sb.append(extra);
Log.e(TAG, sb.toString());
return true;
}
public void onBufferingUpdate(MediaPlayer mp, int percent) {
Log.d(TAG, "PlayerService onBufferingUpdate : " + percent + "%");
}
// .....top bar button....//
public void getMeta() {
Timer timer = new Timer();
timer.schedule(new TimerTask() {
public void run() {
URL url;
// Message msg = handler.obtainMessage();
try {
// url = new URL("http://relay5.slayradio.org:8000");
url = new URL(Stationurl);
final IcyStreamMeta icy = new IcyStreamMeta(url);
runOnUiThread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
// Typeface book = Typeface.createFromAsset(
// getAssets(), "fonts/Neutra2Text-Book.otf");
final TextView songTitle = (TextView) findViewById(R.id.songName);
final TextView artistName = (TextView) findViewById(R.id.artistName);
try {
artistName.setText(icy.getArtist().toString()
.trim());
artistName.setText(icy.getArtist().toString()
.trim());
songTitle.setText(icy.getTitle().toString()
.trim());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}, 0, 500);
}
#Override
public void onPrepared(MediaPlayer mp) {
// TODO Auto-generated method stub
}
}
Facing those problems when i use getMeta(); method.
Main Class for this method is:
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class IcyStreamMeta<Message> {
protected URL streamUrl;
private Map<String, String> metadata;
private boolean isError;
public IcyStreamMeta(URL streamUrl) {
setStreamUrl(streamUrl);
isError = false;
}
/**
* Get artist using stream's title
*
* #return String
* #throws IOException
*/
public String getArtist() throws IOException {
Map<String, String> data = getMetadata();
if (!data.containsKey("StreamTitle"))
return "";
String streamTitle = data.get("StreamTitle");
String title = streamTitle.substring(0, streamTitle.indexOf("-"));
return title.trim();
}
/**
* Get title using stream's title
*
* #return String
* #throws IOException
*/
public String getTitle() throws IOException {
Map<String, String> data = getMetadata();
if (!data.containsKey("StreamTitle"))
return "";
String streamTitle = data.get("StreamTitle");
String artist = streamTitle.substring(streamTitle.indexOf("-")+1);
return artist.trim();
}
public Map<String, String> getMetadata() throws IOException {
if (metadata == null) {
refreshMeta();
}
return metadata;
}
public void refreshMeta() throws IOException {
retreiveMetadata();
}
private void retreiveMetadata() throws IOException {
URLConnection con = streamUrl.openConnection();
con.setRequestProperty("Icy-MetaData", "1");
con.setRequestProperty("Connection", "close");
con.setRequestProperty("Accept", null);
con.connect();
int metaDataOffset = 0;
Map<String, List<String>> headers = con.getHeaderFields();
InputStream stream = con.getInputStream();
if (headers.containsKey("icy-metaint")) {
// Headers are sent via HTTP
metaDataOffset = Integer.parseInt(headers.get("icy-metaint").get(0));
} else {
// Headers are sent within a stream
StringBuilder strHeaders = new StringBuilder();
char c;
while ((c = (char)stream.read()) != -1) {
strHeaders.append(c);
if (strHeaders.length() > 5 && (strHeaders.substring((strHeaders.length() - 4), strHeaders.length()).equals("\r\n\r\n"))) {
// end of headers
break;
}
}
// Match headers to get metadata offset within a stream
Pattern p = Pattern.compile("\\r\\n(icy-metaint):\\s*(.*)\\r\\n");
Matcher m = p.matcher(strHeaders.toString());
if (m.find()) {
metaDataOffset = Integer.parseInt(m.group(2));
}
}
// In case no data was sent
if (metaDataOffset == 0) {
isError = true;
return;
}
// Read metadata
int b;
int count = 0;
int metaDataLength = 4080; // 4080 is the max length
boolean inData = false;
StringBuilder metaData = new StringBuilder();
// Stream position should be either at the beginning or right after headers
while ((b = stream.read()) != -1) {
count++;
// Length of the metadata
if (count == metaDataOffset + 1) {
metaDataLength = b * 16;
}
if (count > metaDataOffset + 1 && count < (metaDataOffset + metaDataLength)) {
inData = true;
} else {
inData = false;
}
if (inData) {
if (b != 0) {
metaData.append((char)b);
}
}
if (count > (metaDataOffset + metaDataLength)) {
break;
}
}
// Set the data
metadata = IcyStreamMeta.parseMetadata(metaData.toString());
// Close
stream.close();
}
public boolean isError() {
return isError;
}
public URL getStreamUrl() {
return streamUrl;
}
public void setStreamUrl(URL streamUrl) {
this.metadata = null;
this.streamUrl = streamUrl;
this.isError = false;
}
public static Map<String, String> parseMetadata(String metaString) {
Map<String, String> metadata = new HashMap();
String[] metaParts = metaString.split(";");
Pattern p = Pattern.compile("^([a-zA-Z]+)=\\'([^\\']*)\\'$");
Matcher m;
for (int i = 0; i < metaParts.length; i++) {
m = p.matcher(metaParts[i]);
if (m.find()) {
metadata.put((String)m.group(1), (String)m.group(2));
}
}
return metadata;
}
}
Use prepareAsync() and not prepare(). See the documentation here: http://developer.android.com/guide/topics/media/mediaplayer.html#preparingasync

Load record at scrolllistview

I need to prevent against lazy load in my custom list-view. so i found that scrollview onscroll listner are helpfull over there i have tryed it but not getting success to implement this functionality.
Code:
lviewAdapter = new ListViewAdapter(SaxParser2.this, Arr_ActivityName, Arr_AudioScript,Arr_RequestID,Arr_FolderPath,Arr_RequestTo);
lview.setOnScrollListener(SaxParser2.this);
#Override
public void onScroll(AbsListView arg0, int arg1, int arg2, int arg3) {
// TODO Auto-generated method stub
lview.setAdapter(lviewAdapter);
}
#Override
public void onScrollStateChanged(AbsListView arg0, int arg1) {
// TODO Auto-generated method stub
}
here is my BaseAdapter
package com.RecordingApp;
import it.sauronsoftware.ftp4j.FTPClient;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.io.Writer;
import java.net.HttpURLConnection;
import java.net.URL;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Typeface;
import android.graphics.drawable.AnimationDrawable;
import android.media.MediaPlayer;
import android.media.MediaRecorder;
import android.os.AsyncTask;
import android.os.CountDownTimer;
import android.os.Environment;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import com.Sharedpreferance.GMailSender;
public class ListViewAdapter extends BaseAdapter {
public static Activity context;
String title[];
String description[];
String RequestId[];
String Folderpath[];
String RequestTo[];
boolean b_Flag_Record_or_not = false;
boolean b_upload_or_not = false;
boolean start_or_not = false;
boolean start_play = false;
boolean upload_or_not = false;
boolean b_play_or_not = false;
boolean isplaying2 = false;
Thread welcomeThread,welcomeThread2;
int glob_position;
MediaPlayer mPlayer2;
int flag_stop_position;
AudioRecorder recorder;
AnimationDrawable frameAnimation, frameAnimation_play;
private static String mFileName = null;
private MediaRecorder mRecorder = null;
private MediaPlayer mPlayer = null;
Recording login = new Recording();
MediaPlayer MP_completeRequest = new MediaPlayer();
public ListViewAdapter(Activity context, String[] title,
String[] description, String[] req_id, String[] FolderPath,
String[] Arr_RequestTo) {
super();
this.context = context;
this.title = title;
this.description = description;
this.RequestId = req_id;
this.Folderpath = FolderPath;
this.RequestTo = Arr_RequestTo;
}
public int getCount() {
// TODO Auto-generated method stub
return title.length;
}
public Object getItem(int position) {
// TODO Auto-generated method stub
return null;
}
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
private class ViewHolder {
TextView txtViewTitle;
TextView txtViewDescription;
Button record, stop, play, upload;
}
public View getView(final int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
final ViewHolder holder;
LayoutInflater inflater = context.getLayoutInflater();
glob_position = position;
if (convertView == null) {
convertView = inflater.inflate(R.layout.listitem_row, null);
holder = new ViewHolder();
holder.txtViewTitle = (TextView) convertView
.findViewById(R.id.textView1);
holder.txtViewDescription = (TextView) convertView
.findViewById(R.id.textView2);
holder.record = (Button) convertView.findViewById(R.id.record);
holder.stop = (Button) convertView.findViewById(R.id.stop);
holder.play = (Button) convertView.findViewById(R.id.play1);
holder.upload = (Button) convertView
.findViewById(R.id.audio_upload);
holder.record.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if (isplaying2 == true) {
} else {
if (b_Flag_Record_or_not == true) {
} else {
try {
holder.record.setBackgroundResource(R.drawable.record_green);
b_Flag_Record_or_not = true;
b_play_or_not = true;
flag_stop_position = position;
AuthHandler dataHandler = new AuthHandler();
AuthDataset dataset = dataHandler
.getParsednewJobdtl_DataSet();
// Login l = new Login();
String str_useid = RequestTo[position];
recorder = new AudioRecorder(
"/audiometer/shanesh"
+ RequestId[position] + "-"
+ str_useid);
start_or_not = true;
recorder.start();
Toast.makeText(context, "Recording Started",
Toast.LENGTH_LONG).show();
CountDownTimer countDowntimer = new CountDownTimer(
120000000, 1000) {
public void onTick(long millisUntilFinished) {
}
public void onFinish() {
try {
Toast.makeText(
context,
"Stop recording Automatically ",
Toast.LENGTH_LONG).show();
recorder.stop();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
};
countDowntimer.start();
} catch (IOException e) {
gotoGmail(e);
} catch (Exception e) {
gotoGmail(e);
}
}
}
}
});
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
try {
Typeface face = Typeface.createFromAsset(context.getAssets(),
"fonts/tahoma.ttf");
holder.txtViewTitle.setTypeface(face);
holder.txtViewTitle.setText(title[position]);
holder.txtViewDescription.setText(description[position]);
} catch (ArrayIndexOutOfBoundsException e) {
e.printStackTrace();
}
holder.stop.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
try {
if (isplaying2 == true) {
mPlayer2.stop();
isplaying2 = false;
} else {
holder.record.setBackgroundResource(R.drawable.page7_15);
if (flag_stop_position == position) {
b_Flag_Record_or_not = false;
if (start_or_not == true) {
b_play_or_not = false;
recorder.stop();
upload_or_not = true;
start_play = true;
Toast.makeText(context, "Stoped Recording",
Toast.LENGTH_LONG).show();
} else {
Toast.makeText(context,
" Please Start recording ",
Toast.LENGTH_LONG).show();
}
} else {
}
}
} catch (Exception e) {
gotoGmail(e);
}
}
});
holder.play.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
String temp = SaxParser2.str_completeORpendingFlag;
if (temp.equalsIgnoreCase("c")) {
try {
final MediaPlayer mPlayer = new MediaPlayer();
try {
mPlayer.setDataSource(Folderpath[position]);
mPlayer.prepare();
final int welcomeScreenDisplay = mPlayer
.getDuration();
welcomeThread = new Thread() {
int wait = 0;
#Override
public void run() {
try {
isplaying2 = true;
mPlayer.start();
while (wait < welcomeScreenDisplay) {
sleep(100);
wait += 100;
}
} catch (Exception e) {
} finally {
isplaying2 = false;
}
}
};
welcomeThread.start();
} catch (Exception e) {
gotoGmail(e);
}
} catch (Exception e) {
gotoGmail(e);
}
} else if (temp.equalsIgnoreCase("p")) {
try {
if (b_play_or_not == true) {
} else {
String str_useid = RequestTo[position];
java.io.File file = new java.io.File(Environment
.getExternalStorageDirectory()
+ "/audiometer/", "shanesh"
+ RequestId[position] + "-" + str_useid
+ ".amr");
if (file.exists()) {
Toast.makeText(context, "Playing",
Toast.LENGTH_LONG).show();
mPlayer2 = new MediaPlayer();
try {
mPlayer2.setDataSource(Environment
.getExternalStorageDirectory()
+ "/audiometer/shanesh"
+ RequestId[position]
+ "-"
+ str_useid + ".amr");
mPlayer2.prepare();
mPlayer2.start();
isplaying2 = true;
final int welcomeScreenDisplay = mPlayer2
.getDuration();
/**
* create a thread to show splash up to
* splash time
*/
welcomeThread = new Thread() {
int wait = 0;
#Override
public void run() {
try {mPlayer2.prepare();
while (wait < welcomeScreenDisplay) {
sleep(100);
wait += 100;
}
} catch (Exception e) {
} finally {
welcomeThread2 = new Thread() {
int wait = 0;
#Override
public void run() {
try {
mPlayer2.start();
while (wait < welcomeScreenDisplay) {
sleep(100);
wait += 100;
}
} catch (Exception e) {
} finally {
// frameAnimation_play.stop();
isplaying2 = false;
}
}
};
welcomeThread2.start();
}
}
};
welcomeThread.start();
} catch (Exception e) {
gotoGmail(e);
}
} else {
Toast.makeText(context, " File Not Found ",
Toast.LENGTH_LONG).show();
}
}
} catch (Exception e) {
gotoGmail(e);
}
}
}
});
holder.upload.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
glob_position = position;
// String str_useid = RequestTo[position];
if (upload_or_not == true) {
try {
new xyz().execute();
} catch (Exception e) {
gotoGmail(e);
}
}
}
});
return convertView;
}
private class xyz extends AsyncTask<Void, Void, Void> {
private final ProgressDialog dialog = new ProgressDialog(context);
protected void onPreExecute() {
try {
this.dialog.setMessage("Uploading...Please Wait..");
dialog.setIndeterminate(true);
dialog.setCancelable(false);
this.dialog.show();
// put your code which preload with processDialog
} catch (Exception e) {
gotoGmail(e);
}
}
#Override
protected Void doInBackground(Void... arg0) {
for (int i = 0; i < 100000; i++) {
}
it.sauronsoftware.ftp4j.FTPClient con = new it.sauronsoftware.ftp4j.FTPClient();
try {
String str_useid = RequestTo[glob_position];
con.connect("URL");
con.login("as", "asdasd");
con.changeDirectory("/rangam/RequestContent/audio");
con.setPassive(true);
con.setType(FTPClient.TYPE_BINARY);
con.upload(new java.io.File(Environment
.getExternalStorageDirectory()
+ "/audiometer/shanesh"
+ RequestId[glob_position] + "-" + str_useid + ".amr"));
String filename = "/shanesh" + RequestId[glob_position] + "-"
+ str_useid + ".amr";
con.logout();
con.disconnect(true);
String MachineName = Machinelist.str_Machinename;
sendFlagToServer(RequestId[glob_position], filename,
MachineName);
} catch (Exception e) {
gotoGmail(e);
}
return null;
}
protected void onPostExecute(final Void unused) {
if (this.dialog.isShowing()) {
try {
this.dialog.dismiss();
AlertDialog.Builder alertbox = new AlertDialog.Builder(
context);
alertbox.setTitle("Message");
alertbox.setMessage(":: Uploaded Successfully ::");
alertbox.setPositiveButton("OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface arg0,
int arg1) {
Intent intent_request = new Intent(context,
SaxParser2.class);
intent_request.putExtra("value", Machinelist.str_UIDValue);
intent_request.putExtra("machineName",
Machinelist.str_Machinename);
intent_request.putExtra("captureBack_or_not", 2);
context.startActivity(intent_request);
context.finish();
}
});
alertbox.show();
} catch (Exception e) {
gotoGmail(e);
}
}
}
}
private void sendFlagToServer(String requestID, String filename,
String machineName) {
HttpURLConnection connection;
OutputStreamWriter request = null;
String MachineName = Machinelist.str_Machinename;
URL url = null;
String parameters = "RequestID=" + requestID + "&FileName=" + filename
+ "&MachineName=" + MachineName + "&RequestType=A";
try {
url = new URL(
"URL");
connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded");
connection.setRequestMethod("POST");
request = new OutputStreamWriter(connection.getOutputStream());
request.write(parameters);
request.flush();
request.close();
String line = "";
InputStreamReader isr = new InputStreamReader(
connection.getInputStream());
BufferedReader reader = new BufferedReader(isr);
StringBuilder sb = new StringBuilder();
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
isr.close();
reader.close();
} catch (Exception e) {
gotoGmail(e);
}
}
public boolean onKeyDown(int keyCode, KeyEvent event) {
if ((keyCode == KeyEvent.KEYCODE_BACK)) {
try {
context.finish();
} catch (Exception e) {
gotoGmail(e);
}
}
return false;
}
void gotoGmail(Exception e) {
Writer writer = new StringWriter();
PrintWriter printWriter = new PrintWriter(writer);
e.printStackTrace(printWriter);
String s = writer.toString();
}
}
Ok,
So first you'll have to define "what is the number of views I'd need to load in order my user not to see that it's lazy loading ?" :
Let's say, you'd want to load 20 rows...
Now in you onscroll, or wherever you want but somewhere like on scroll or Adapter.getView, you'll have to know what is displayed on screen at the moment... Let me explain :
I want to load 20 rows so my user doesn't notice,
I am display 10 of them
and 10 of them are just hidden (not displayed if the guy doesn't scroll).
Now, I wan't to load 10 more when the guy just hit my 15th row
What could be the best way to do that ???
Humm, let's see, trying to find something that returns the (ABSOLUTE) number of the last row displayed on screen - this could be a nice solution.
An otehr solution could be that your 10 or 15th row is the first one displayed on screen ?
etc, etc...
I think stuffs like that should do the trick. ;)
Here is a sample I grabbed from Net. It is loading the items by listening to the Scroll of the ListView . For sample it is loading dates in ListView. After reached the end position it will load next 15 dates. It is Never Ending List . You can modify the adapter to your custom adapter. The concept is:
You have set of data
Loading first n no of items
Set the scroll listener to the listview
If scroll reaches Last Visible Item in Listview , You trigger the worker thread to load additional m no of items.
Notify listview from an UI thread.
int itemsPerPage = 15;
boolean loadingMore = false;
ArrayList<String> myListItems;
ArrayAdapter<String> adapter;
//For test data :-)
Calendar d = Calendar.getInstance();
this.getListView().setOnScrollListener(new OnScrollListener(){
//useless here, skip!
#Override
public void onScrollStateChanged(AbsListView view, int scrollState) {}
#Override
public void onScroll(AbsListView view, int firstVisibleItem,
int visibleItemCount, int totalItemCount) {
//what is the bottom item that is visible
int lastInScreen = firstVisibleItem + visibleItemCount;
//is the bottom item visible & not loading more already ? Load more !
if((lastInScreen == totalItemCount) && !(loadingMore)){
Thread thread = new Thread(null, loadMoreListItems);
thread.start();
}
}
});
//Load the first 15 items
Thread thread = new Thread(null, loadMoreListItems);
thread.start();
}
//Runnable to load the items
private Runnable loadMoreListItems = new Runnable() {
#Override
public void run() {
//Set flag so we cant load new items 2 at the same time
loadingMore = true;
//Reset the array that holds the new items
myListItems = new ArrayList<String>();
//Get 15 new listitems
for (int i = 0; i < itemsPerPage; i++) {
//Fill the item with some bogus information
myListItems.add("Date: " + (d.get(Calendar.MONTH)+ 1) + "/" + d.get(Calendar.DATE) + "/" + d.get(Calendar.YEAR) );
// +1 day :-D
d.add(Calendar.DATE, 1);
}
//Done! now continue on the UI thread
runOnUiThread(returnRes);
}
};
//Since we cant update our UI from a thread this Runnable takes care of that!
private Runnable returnRes = new Runnable() {
#Override
public void run() {
//Loop thru the new items and add them to the adapter
if(myListItems != null && myListItems.size() > 0){
for(int i=0;i<myListItems.size();i++)
adapter.add(myListItems.get(i));
}
//Update the Application title
setTitle("Neverending List with " + String.valueOf(adapter.getCount()) + " items");
//Tell to the adapter that changes have been made, this will cause the list to refresh
adapter.notifyDataSetChanged();
//Done loading more.
loadingMore = false;
}
};
EDIT:
You can get tutorial and full project here

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