This question already has answers here:
How can I fix 'android.os.NetworkOnMainThreadException'?
(66 answers)
NetworkOnMainThread
(3 answers)
Closed 9 years ago.
I am trying to parse .pls file to get urls to play. I used following code, but it is giving networkonmainthread exception. I never did threaded apps before; How can I run this class on new thread?
public class GetStreamingUrl {
private static String LOGTAG = "GetStreamingUrl";
private Context mContext;
public String url1;
public LinkedList<String> url2;
public GetStreamingUrl(Context context) {
Log.i(LOGTAG, "call to constructor");
this.mContext = context;
}
public LinkedList<String> getStreamingUrl(String url) {
Log.i(LOGTAG, "get streaming url");
final BufferedReader br;
String murl = null;
LinkedList<String> murls = null;
try {
URLConnection mUrl = new URL(url).openConnection();
br = new BufferedReader(
new InputStreamReader(mUrl.getInputStream()));
murls = new LinkedList<String>();
while (true) {
try {
String line = br.readLine();
if (line == null) {
break;
}
murl = parseLine(line);
if (murl != null && !murl.equals("")) {
murls.add(murl);
}
} catch (IOException e) {
e.printStackTrace();
}
}
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Log.i(LOGTAG, "url to stream :" + murl);
return murls;
}
private String parseLine(String line) {
if (line == null) {
return null;
}
String trimmed = line.trim();
if (trimmed.indexOf("http") >= 0) {
return trimmed.substring(trimmed.indexOf("http"));
}
return "";
}
}
I am trying to parse .pls file to get urls to play. I used following code, but it is giving networkonmainthread exception. I never did threaded apps before; How can I run this class on new thread?
Just do this:
new Thread(new Runnable() {
#Override
public void run() {
// DO YOUR STUFFS HERE
}
}).start();
Hope this helps.
You can use AsyncTask and do the work inside it. Follow the link below for more details:
http://developer.android.com/reference/android/os/AsyncTask.html
Related
I am working on a chat client application and I have made a server. I managed to make the client connect to the server, but then when I send a message to the server, there's no reaction from the server.
Here is the part of the code of my server that is not working
class ClientConnect implements Runnable {
private DataInputStream in = null;
private DataOutputStream out = null;
Socket client;
ClientConnect(Socket client) {
try {
this.client = client;
/* obtain an input stream to this client ... */
in = new DataInputStream (client.getInputStream());
/* ... and an output stream to the same client */
setOut(new DataOutputStream (client.getOutputStream()));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void run() {
String msg, response;
ChatServerProtocol protocol = new ChatServerProtocol(this);
try {
while (true) {
if (in.available() > 0){
msg = in.readUTF();
response = protocol.process(msg);
getOut().writeBytes("SERVER: " + response);
}
}
} catch (IOException e) {
System.err.println(e);
} finally {
// The connection is closed for one reason or another
try {
client.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public void sendMsg(String msg) {
try {
getOut().writeBytes(msg);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public DataOutputStream getOut() {
return out;
}
public void setOut(DataOutputStream out) {
this.out = out;
}
}
And here is the client :
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
String response = null;
EditText nicknameField = (EditText)findViewById(R.id.nicknameField);
EditText passwordField = (EditText)findViewById(R.id.passwordField);
nickname = nicknameField.getText().toString();
password = passwordField.getText().toString();
switch(v.getId()){
case R.id.signin:
new SendMessage(this).execute("SIGNUP " + nickname + " " + password );
break;
case R.id.signup:
new SendMessage(this).execute("SIGNUP " + nickname + " " + password );
break;
}
}
private String onPostExecuteSendMessage() {
return null;
}
public void showMessage(String response) {
Builder builder = new AlertDialog.Builder(this);
builder.setMessage(response);
AlertDialog dialog = builder.create();
dialog.show();
}
public void getClientSocket(Socket client) {
this.client = client;
try {
out = new DataOutputStream (client.getOutputStream());
in = new DataInputStream (client.getInputStream());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public DataOutputStream getOut() {
// TODO Auto-generated method stub
return this.out;
}
public DataInputStream getIn() {
// TODO Auto-generated method stub
return this.in;
}
public void goMenuChat() {
// TODO Auto-generated method stub
Intent intent = new Intent(this, MenuChatActivity.class);
startActivity(intent);
}
}
Also I used an Asynctask to send message from the client :
package client.chatclient;
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.lang.ref.WeakReference;
import android.os.AsyncTask;
public class SendMessage extends AsyncTask<String, String, String> {
private static final String msg_OK = "OK";
private static final String msg_NICK_IN_USE = "NICK IN USE";
private static final String msg_UNKNOWN_CMD = "UNKNOWN CMD";
private static final String msg_INVALID = "INVALID COMMAND";
private static final String msg_SEND_FAILED = "FAILED TO SEND";
private static final String msg_INCORRECT_IDS = "INCORRECT IDS";
private static final String msg_DISCONNECT = "DISCONNECT";
private WeakReference<MainActivity> activity;
private String message;
private String response = "";
private DataOutputStream out;
private DataInputStream in;
public SendMessage(MainActivity act){
super();
activity = new WeakReference<MainActivity>(act);
}
protected String doInBackground(String... message) {
this.message = message[0];
this.out = activity.get().getOut();
this.in = activity.get().getIn();
try {
out.writeBytes(this.message);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
response = convertStreamToString(this.in);
return response;
}
protected void onPostExecute(String response) {
if ((response == msg_INCORRECT_IDS) || (response == msg_NICK_IN_USE)){
activity.get().showMessage(response);
}
else if (response == msg_OK){
activity.get().goMenuChat();
}
}
private static String convertStreamToString(DataInputStream in) {
/*
* To convert the InputStream to String we use the
* BufferedReader.readLine() method. We iterate until the BufferedReader
* return null which means there's no more data to read. Each line will
* appended to a StringBuilder and returned as String.
*/
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
} catch (IOException e) {
e.printStackTrace();
}
return sb.toString();
}
}
I send my message from the client by clicking on a button then it goes to the SendMessage class, and send the message to the server and normally the server should receive my message in the loop "while (true)..." and sends back a response according to the protocol that I've implemented.
I really don't know what is wrong. If you know how to solve this issue or have some solutions, please tell me ! If you want more details, ask me ! :)
Thank you very much !
EDIT:
I instanciated my ClientConnect here
public class ChatServer {
private static int port = 8080;
public static void main (String[] args) throws IOException {
ServerSocket server = new ServerSocket(port); /* start listening on the port */
System.out.println( "Listening on "+ server );
Socket client = null;
while(true) {
try {
client = server.accept();
System.out.println( "Connection from " + client );
/* start a new thread to handle this client */
Thread t = new Thread(new ClientConnect(client));
t.start();
} catch (IOException e) {
System.err.println("Accept failed.");
System.err.println(e);
System.exit(1);
server.close();
}
}
}
}
EDIT: I found where the problem is. I put some log() statements as you said
log.d(null,"beforeconvert")
try {
log.d(null,"convert")
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
} catch (IOException e) {
log.d(null,"errorconvert")
e.printStackTrace();
}
After that in logcat, it just shows "beforeconvert". I don't really know what the problem is ? while ((line = reader.readLine()) != null) is surely the problem. When I use the debugger step by step in eclipse, it stops at this line and doesn't even go inside the loop.
EDIT : I REALLY don't know why, but when I quit the emulator when running my app, it shows everything.
Listening on ServerSocket[addr=0.0.0.0/0.0.0.0,localport=8080]
Connection from Socket[addr=/127.0.0.1,port=56646,localport=8080]
client connected
msg received
error !
SIGNUP Nickname Password
SIGNUP Nickname Password
msg converted
OK
java.net.SocketException: Connection reset
at java.net.SocketInputStream.read(Unknown Source)
at java.net.SocketInputStream.read(Unknown Source)
at java.io.DataInputStream.read(Unknown Source)
at sun.nio.cs.StreamDecoder.readBytes(Unknown Source)
at sun.nio.cs.StreamDecoder.implRead(Unknown Source)
at sun.nio.cs.StreamDecoder.read(Unknown Source)
at java.io.InputStreamReader.read(Unknown Source)
at java.io.BufferedReader.fill(Unknown Source)
at java.io.BufferedReader.readLine(Unknown Source)
at java.io.BufferedReader.readLine(Unknown Source)
at server.ClientConnect.convertStreamToString(ChatServer.java:357)
at server.ClientConnect.run(ChatServer.java:304)
at java.lang.Thread.run(Unknown Source)
java.net.SocketException: Connection reset by peer: socket write error
When you are writing data to output stream in the end you need to flush
this.out.flush();
I think this is why the data is not sent and received
Hope that helps.
Edit:
Let me try to explain in general idea..
When you are opening a socket you have a connection to another machince.
So the
in.available();
and
socket.accpet();
Should work.. once you are writing into outputstream you must flush in order to see the data(or close, i think it flushes before it get closed).
Anyway i attach a link to an example.. You should try this one, Or look at parts you have problem with..
http://examples.javacodegeeks.com/android/core/socket-core/android-socket-example/
Not very easy to explain:
I have this app for streaming online radio. The problem was first with m3u format (which android somehow cannot normally stream like pls), so I have to parse the url with this ParserM3UToURL (that I found somewhere)... like this:
Uri u = Uri.parse(ParserM3UToURL.parse(STREAM_URL, sdkVersion, c));
player = MediaPlayer.create(c, u);
Mostly it works ok but it has one bug...
I'm testing this on two devices one old 2.2.2. (api level 17), other 4.3 (api level 23). Older device works fine. It can stream radio over wifi or mobile data, but the newer device has some problem with streaming over mobile data (on wifi it works ok). The application crashes because the parse function returns null: http://pastebin.com/ghbAqGzM
And I assume there are many more phones with 4.x than 2.x android. Which of course is very painful for me. Somehow I have to fix this.. So I really hope somebody will have some clue about this. I hope my explanation was not to confusing...
This is the ParserM3UToURL.parse() function:
public static String parse(String paramString, int sdkVersion, Context c)
{
try
{
StrictModeWrapper.init(c);
HttpURLConnection localHttpURLConnection = (HttpURLConnection)new URL(paramString).openConnection();
InputStream localInputStream = localHttpURLConnection.getInputStream();
BufferedReader localBufferedReader = new BufferedReader(new InputStreamReader(localInputStream));
StringBuffer localStringBuffer = new StringBuffer();
while (true)
{
String str = localBufferedReader.readLine();
if (str == null)
{
localHttpURLConnection.disconnect();
localBufferedReader.close();
localInputStream.close();
break;
}
if (str.contains("http"))
{
localHttpURLConnection.disconnect();
localBufferedReader.close();
localInputStream.close();
return str;
}
localStringBuffer.append(str);
}
}
catch (Exception e)
{
e.printStackTrace();
}
return null;
}
Below is what i worked on to stream radio (m3Urls). The example below uses a service. When the service is started, the url is parsed. Note that in the onPostExecute, parsed file is prepared. Once the file is prepared(completed buffering), the file is played/started and stopped upon completion.
public class BackgroundRadioService extends Service implements
OnCompletionListener, OnPreparedListener{
MediaPlayer mediaPlayer;
#Override
public void onCreate() {
mediaPlayer = new MediaPlayer();
mediaPlayer.setOnCompletionListener(this);
mediaPlayer.setOnPreparedListener(this);
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
parseM3uUrlAndPrepare("http://listen.radionomy.com/andalousse.m3u");
return START_STICKY;
}
private void parseM3uUrlAndPrepare(final String url){
AsyncTask<String, Integer, String> asyn = new AsyncTask<String, Integer, String>(){
HttpClient httpClient;
HttpGet getRequest;
HttpResponse httpResponse = null;
String filePath = "";
#Override
protected void onPreExecute() {
super.onPreExecute();
httpClient = new DefaultHttpClient();
getRequest = new HttpGet(url);
}
#Override
protected String doInBackground(String... params) {
try {
httpResponse = httpClient.execute(getRequest);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if(httpResponse != null)
if (httpResponse.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
// ERROR MESSAGE
} else {
InputStream inputStream = null;
try {
inputStream = httpResponse.getEntity().getContent();
} catch (IllegalStateException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
String line;
try {
while ((line = bufferedReader.readLine()) != null) {
//Log.v("PLAYLISTLINE", "ORIG: " + line);
if (line.startsWith("#")) { // Metadata
} else if (line.length() > 0) {
filePath = "";
if (line.startsWith("http://")) { // Assume it's a full URL
filePath = line;
} else { // Assume it's relative
try{
filePath = getRequest.getURI().resolve(line).toString();
}catch(IllegalArgumentException e){
}catch(Exception e){
}
}
}
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
inputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return filePath;
}
#Override
protected void onPostExecute(String filePath) {
try {
mediaPlayer.setDataSource(filePath);
mediaPlayer.prepareAsync(); //this will prepare file a.k.a buffering
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
};
asyn.execute("");
}
#Override
public void onPrepared(MediaPlayer mp) {
// TODO Auto-generated method stub
mediaPlayer.start();
}
#Override
public void onCompletion(MediaPlayer mp) {
mediaPlayer.stop();
}
}//end of Service class declaration
Note: This ignores playlists hence assumes the m3u parsed will return only one file. Let me know if you would like to handle playlists so I modify my answer :)
I solved it thanks to this question's comments: POST request failing when in 3G
The problem was actually with proxies on 3G. So if proxies are disabled, no weird http requests.
I modified my code a little. Thanks to Nana's answer I no longer need a m3u parser. I also no longer use HttpClient but HttpURLConnection instead. So when calling URL.openConnection() I add the Proxy.NO_PROXY parameter to that function and bam!
So the solution is "use HttpURLConnection not HttpClient and add NO_PROXY parameter":
conn = (HttpURLConnection) the_url.openConnection( Proxy.NO_PROXY );
I want to retrieve the contents of this file and save that to a string.
I've tried using AsyncTask (based on this answer) and here is my class.
class RetreiveURLTask extends AsyncTask<Void, Void, String> {
private Exception exception = null;
public String ResultString = null;
protected String doInBackground(Void ... something) {
URL url;
try {
url = new URL("http://stream.lobant.net/ccfm.info");
HttpURLConnection urlConnection;
urlConnection = (HttpURLConnection) url.openConnection();
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
String stream_url = IOUtils.toString(in, "UTF-8");
urlConnection.disconnect();
return stream_url;
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
} catch (Exception e) {
this.exception = e;
return null;
}
}
protected void onPostExecute(String stream_url) {
// TODO: check this.exception
// TODO: do something with the feed
if (this.exception != null)
this.exception.printStackTrace();
this.ResultString = stream_url;
}
}
I've tried using my AsyncTask class like this:
AsyncTask<Void, Void, String> stream_task = new RetreiveURLTask().execute();
String stream_url = stream_task.ResultString;
but ResultString isn't recognised.
I'm confused about how this all works. Since the AsyncTask runs in the background, even if I could assign my string to one of the public variables, there is no guarentee that it will be valid when I make the assignment. Even if I were to use some kind of getResult() function, I would need to know when to call it so that the code has completed executing.
So, how is this usually done?
(Also, is my http read code ok?)
My ability: I can code, but am new to android.
Use an interface
new RetreiveURLTask(ActivityName.this).execute();
In your asyctask
TheInterface listener;
In the constructor
public RetreiveURLTask (Context context)
{
listener = (TheInterface) context;
}
The interface
public interface TheInterface {
public void theMethod(String result);
}
In onPostExecute
if (listener != null)
{
listener.theMethod(stream_url);
}
In your activity class implement the interface
implements RetreiveURLTask.TheInterface
Implement the method
#Override
public void theMethod(String result) {
// update ui using result
}
// try this way
RetreiveURLTask task = new RetreiveURLTask();
task.execute();
private void response(String responseData){
// here you write your code which use responseData
}
class RetreiveURLTask extends AsyncTask<Void, Void, String> {
private Exception exception = null;
public String ResultString = null;
protected String doInBackground(Void ... something) {
URL url;
try {
url = new URL("http://stream.lobant.net/ccfm.info");
HttpURLConnection urlConnection;
urlConnection = (HttpURLConnection) url.openConnection();
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
String stream_url = IOUtils.toString(in, "UTF-8");
urlConnection.disconnect();
return stream_url;
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
} catch (Exception e) {
this.exception = e;
return null;
}
}
protected void onPostExecute(String stream_url) {
// TODO: check this.exception
// TODO: check this.exception
// TODO: do something with the feed
super.onPostExecute(stream_url);
response(stream_url)
}
}
Make this
public String ResultString = "";
Global
Asynctask is not the main class here , that's the reason you get ResultString cannot be resolved or is not a field
make it a global variable then you'll be able to access it
The execution of the AsyncTask is started in the background, while the assignment is carried out immediately after the execution began. Therefore, the assignment is carried out before the execution of the AsyncTask is complete.
Your best bet is to conduct the assignment in the OnPostExecute() method.
I want to play a .pls file for my android application using this url http://playerservices.streamtheworld.com/pls/VIRGINRADIO_DUBAIAAC.pls
I know that it is not possible to play .pls files using MediaPlayer directly.So I parsed this file using a Pls parser and set each url to a media player.But it won't work .Also shows the error error (1, -2147483648).
public class PlayListParser {
private BufferedReader reader;
public PlayListParser(String url) {
try {
URL plsFileUrl = new URL(url.trim());
URLConnection urlConnection = plsFileUrl.openConnection();
// InputStream input = new BufferedInputStream(urlConnection.openStream());
InputStream iStream = urlConnection.getInputStream();
this.reader = new BufferedReader(new InputStreamReader(iStream));
// this.reader = new BufferedReader(new FileReader(file), 1024);
} catch (MalformedURLException e) {
Log.e("PlayListParser", "Got MalformedURLException = " + e.getMessage());
} catch (IOException e) {
Log.e("PlayListParser", "Got IOException = " + e.getMessage());
}
}
public List<String> getUrls() {
LinkedList<String> urls = new LinkedList<String>();
while (true) {
try {
String line = reader.readLine();
if (line == null) {
break;
}
String url = parseLine(line);
if (url != null && !url.equals("")) {
urls.add(url);
}
} catch (IOException e) {
e.printStackTrace();
}
}
return urls;
}
private String parseLine(String line) {
if (line == null) {
return null;
}
String trimmed = line.trim();
if (trimmed.indexOf("http") >= 0) {
return trimmed.substring(trimmed.indexOf("http"));
}
return "";
}
}
PlayListParser playListParser = new PlayListParser(URL_PLS_STREAMING);
List<String > playList = playListParser.getUrls();
if(playList != null && ! playList.isEmpty()){
for(String url : playList){
MediaPlayer mediaPlayer = new MediaPlayer();
try {
mediaPlayer.setDataSource(playList.get(0));//"http://stream2.streamq.net:8020/");
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mediaPlayer.prepareAsync();
mediaPlayer.setOnPreparedListener(new OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
mp.start();
}
});
//mediaPlayer.prepare();
} catch (IllegalArgumentException e) {
Log.e("MainActivity","Got IllegalArgumentException = " + e.getMessage());
} catch (IllegalStateException e) {
Log.e("MainActivity","Got IllegalStateException = " + e.getMessage());
} catch (IOException e) {
Log.e("MainActivity","Got IOException = " + e.getMessage());
}
}
}
How can i play this .pls file? I could not find a good reference about it.Also i want to play,pause,and rewind these files.
Thanks in Advance
Get URL from .pls file
This will return URL like http://stream2.streamq.net:8020
package com.direct.radio.global;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.LinkedList;
import android.content.Context;
import android.util.Log;
public class GetStreamingUrl {
private static String LOGTAG = "GetStreamingUrl";
private Context mContext;
public GetStreamingUrl(Context context) {
Log.i(LOGTAG, "call to constructor");
this.mContext = context;
}
public LinkedList<String> getStreamingUrl(String url) {
Log.i(LOGTAG, "get streaming url");
final BufferedReader br;
String murl = null;
LinkedList<String> murls = null;
try {
URLConnection mUrl = new URL(url).openConnection();
br = new BufferedReader(
new InputStreamReader(mUrl.getInputStream()));
murls = new LinkedList<String>();
while (true) {
try {
String line = br.readLine();
if (line == null) {
break;
}
murl = parseLine(line);
if (murl != null && !murl.equals("")) {
murls.add(murl);
}
} catch (IOException e) {
e.printStackTrace();
}
}
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Log.i(LOGTAG, "url to stream :" + murl);
return murls;
}
private String parseLine(String line) {
if (line == null) {
return null;
}
String trimmed = line.trim();
if (trimmed.indexOf("http") >= 0) {
return trimmed.substring(trimmed.indexOf("http"));
}
return "";
}
}
Activity_Player.java or Service_Player.java
you can write this code as per your need , Define this method
LinkedList<String> urls;
private LinkedList<String> fGetPlayableUrl(String mPls) {
GetStreamingUrl oGetStreamingUrl = new GetStreamingUrl(Activity_Splash.this);
urls = oGetStreamingUrl.getStreamingUrl(mPls);
return urls;
}
Here, fGetPlayableUrl(String mPls) pass .pls URL. Now you have streaming URL.
MediaPlayer mMediaPlayer = new MediaPlayer();
Now, pass URL to
mMediaPlayer.setDataSource(urls.toString());
mMediaPlayer.prepareAsync();
mMediaPlayer.start();
Android Media Player:
I'm able to play .mp3 file from URL.
While playing .pls getting eroor.
Code:
try{
String url=".pls url";
mediaPlayer = new MediaPlayer();
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mediaPlayer.setDataSource(url);
mediaPlayer.prepare();
mediaPlayer.start();
}catch(Exception
System.out.println("## Exception while playing: "+e);
mediaPlayer .release();
mediaPlayer = null;
}
Error:
09-12 12:44:04.026: E/MediaPlayer(704): error (1, -2147483648)
09-12 12:44:04.026: I/System.out(704): ## Exception while playing: java.io.IOException: Prepare failed.: status=0x1
If by pls you mean playlist information file, then mediaplayer cannot handle pls files.
.pls files are not media files. So you cannot play .pls files. Usually .pls are handled by the app and app extracts the information from the pls file and play the music file to which pls is pointing to.
String musicUlrPath;
LinkedList<String> streamingUrlList;
streamingUrlList=new LinkedList<String>();
ExecuteArrayList executeArrayList=new ExecuteArrayList();
executeArrayList.execute("blank");
class ExecuteArrayList extends AsyncTask<String, String, String>
{
#Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
try {
streamingUrlList=getStreamingUrl(pathFromJson);//you are geting path during json response
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
musicUlrPath=(streamingUrlList.get(0));
}
}
public LinkedList<String> getStreamingUrl(String url) {
Log.i(LOGTAG, "get streaming url");
final BufferedReader br;
String murl = null;
LinkedList<String> murls = null;
try {
URLConnection mUrl = new URL(url).openConnection();
br = new BufferedReader(
new InputStreamReader(mUrl.getInputStream()));
murls = new LinkedList<String>();
while (true) {
try {
String line = br.readLine();
if (line == null) {
break;
}
murl = parseLine(line);
if (murl != null && !murl.equals("")) {
murls.add(murl);
}
} catch (IOException e) {
e.printStackTrace();
}
}
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Log.i(LOGTAG, "url to stream :" + murl);
return murls;
}
private String parseLine(String line) {
if (line == null) {
return null;
}
String trimmed = line.trim();
if (trimmed.indexOf("http") >= 0) {
return trimmed.substring(trimmed.indexOf("http"));
}
return "";
}
now set the extracted path
mediaPlayer.setDataSource(musicUlrPath);
Extract pls file in notepad , It will show like this
playlist]
File1=Alternative\everclear -URL
Title1=Everclear - So Much For The Afterglow
Length1=233
File2=Comedy\Weird Al - Everything You Know Is Wrong.mp3
.
.
NumberOfEntries=5
Version=2.
Use that URL in Media player.It will work.