Respected developers , I m creating app of alphabets , I am unable to add sound with imageswitcher,
I want when user press next button , It should give next image with its sound
my code is
Code:
I have sound in Row folder name a,b,c
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.ImageSwitcher;
import android.widget.ImageView;
import android.widget.Toast;
import android.widget.ViewSwitcher.ViewFactory;
public class New extends ActionBarActivity implements ViewFactory {
ImageSwitcher is;
int [] imgid = {R.drawable.i1,
R.drawable.i2,
R.drawable.i3,
R.drawable.i4};
Button prev, next;
int count =0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.poetry);
final Button switchact = (Button) findViewById(R.id.btn1);
switchact.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent act2 = new Intent(view.getContext(), MainActivity.class);
startActivity(act2);
}
});
is = (ImageSwitcher)findViewById(R.id.imageSwitcher1);
prev = (Button)findViewById(R.id.button1);
next = (Button)findViewById(R.id.button2);
is.setFactory(this);
is.setInAnimation(this, android.R.anim . slide_in_left);
is.setOutAnimation(this, android.R.anim.slide_out_right);
prev.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
if(count>0)
{
count--;
try{
is.setImageResource(imgid[count]);
}
catch(Exception e)
{
e.printStackTrace();
}
}
else
{
Toast.makeText(New.this, "First", Toast.LENGTH_LONG).show();
}
}
});
next.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
if(count<imgid.length)
{
try{
is.setImageResource(imgid[count]);
}
catch(Exception e)
{
e.printStackTrace();
}
count++;
}
else
{
Toast.makeText(New.this, "Last", Toast.LENGTH_LONG).show();
}
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public boolean appnot(View v){
Intent sharingIntent = new Intent(android.content.Intent.ACTION_SEND);
sharingIntent.setType("text/plain");
String shareBody = "http://rafeeqsir.in";
sharingIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, "I found a best Urdu Learing App Please try");
sharingIntent.putExtra(android.content.Intent.EXTRA_TEXT, shareBody);
startActivity(Intent.createChooser(sharingIntent, "Share via"));
return false;
}
public void about(View v){
{
new AlertDialog.Builder(this)
.setTitle(R.string.app_about)
.setNegativeButton(R.string.str_ok,
new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialoginterface, int i)
{
}
})
.show();
}
}
public void exit(View v){
{
new AlertDialog.Builder(this)
.setTitle(R.string.app_exit)
.setIcon(R.drawable.ic_launcher)
.setMessage(R.string.app_exit_message)
.setNegativeButton(R.string.exit,
new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialoginterface, int i)
{
System.exit(0);
}
})
.show();
}
}
@Override
public View makeView() {
// TODO Auto-generated method stub
ImageView iv = new ImageView(this);
iv.setScaleType(ImageView.ScaleType.FIT_CENTER);
iv.setLayoutParams(new ImageSwitcher.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
return iv;
}
}
please help me about it
Related
Hi I'm working on a custom Android launcher I'm running into a little problem I have an image button that indicates show all applications but the problem is I don't know the code syntax to show all installed applications when that button is clicked!!
Please help I tried googling for the last four hours and getting very frustrated
Thanks in advance
Rapsong11
Sent from my Nexus 4 using xda app-developers app
Maybe you should use PackageManager to query the installed applications for you.
For example, when you want the list of launchable activities. You can do like this:
Code:
// create a intent for the query below
Intent mainIntent = new Intent(Intent.ACTION_MAIN, null);
// add the intent category you want, if need
mainIntent.addCategory(Intent.CATEGORY_LAUNCHER);
// get the instance of the package manager
PackageManager packageManager = context.getPackageManager();
// these are the activies you want
List<ResolveInfo> activities = packageManager.queryIntentActivities(mainIntent, 0);
Hope can help you
Code:
Here is my code:
package com.d4a.SchoolLauncher;
import java.util.List;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.net.Uri;
import android.os.Bundle;
import android.provider.Settings;
import android.view.View;
import android.widget.HorizontalScrollView;
import android.widget.ImageButton;
import android.widget.ScrollView;
import android.content.Context;
import com.d4a.SchoolLauncher.R;
public class LauncherActivity extends Activity{
[user=439709]@override[/user]
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//scroller
final HorizontalScrollView scroller= (HorizontalScrollView) findViewById(R.id.scroller);
scroller.setSmoothScrollingEnabled(true);
//apps
final ImageButton apps= (ImageButton) findViewById(R.id.all_apps); //my all apps button
apps.setOnClickListener(new View.OnClickListener() {
[user=439709]@override[/user]
public void onClick(View v) {
Intent mainIntent = new Intent(Intent.ACTION_MAIN, null);
mainIntent.addCategory(Intent.CATEGORY_LAUNCHER);
PackageManager packageManager = context.getPackageManager();
List<ResolveInfo> activities = packageManager.queryIntentActivities(mainIntent, 0);
}
});
final ImageButton wbrowser= (ImageButton) findViewById(R.id.wbrowser);
wbrowser.setOnClickListener(new View.OnClickListener() {
[user=439709]@override[/user]
public void onClick(View v) {
String url = "http://www.google.com";
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse(url));
startActivity(i);
}
});
final ImageButton osettings= (ImageButton) findViewById(R.id.osettings);
osettings.setOnClickListener(new View.OnClickListener() {
[user=439709]@override[/user]
public void onClick(View v) {
startActivity(new Intent(Settings.ACTION_SETTINGS));
}
});
//remove from home screen button
//apps
final ImageButton delapps= (ImageButton) findViewById(R.id.delapps);
delapps.setOnClickListener(new View.OnClickListener() {
[user=439709]@override[/user]
public void onClick(View v) {
apps.setVisibility(View.GONE);
delapps.setVisibility(View.GONE);
}
});
//web browser
final ImageButton delwbrowser= (ImageButton) findViewById(R.id.delwbrowser);
delwbrowser.setOnClickListener(new View.OnClickListener() {
[user=439709]@override[/user]
public void onClick(View v) {
wbrowser.setVisibility(View.GONE);
delwbrowser.setVisibility(View.GONE);
}
});
//web browser
final ImageButton delosettings= (ImageButton) findViewById(R.id.dellosettings);
delosettings.setOnClickListener(new View.OnClickListener() {
[user=439709]@override[/user]
public void onClick(View v) {
osettings.setVisibility(View.GONE);
delosettings.setVisibility(View.GONE);
}
});
//add button
final ImageButton addshortcut= (ImageButton) findViewById(R.id.addshortcut);
addshortcut.setOnClickListener(new View.OnClickListener() {
[user=439709]@override[/user]
public void onClick(View v) {
startActivity(new Intent("com.PhysicsPhantom.Launcher"));
}
});
//done button
final ImageButton done= (ImageButton) findViewById(R.id.done);
done.setOnClickListener(new View.OnClickListener() {
[user=439709]@override[/user]
public void onClick(View v) {
delwbrowser.setVisibility(View.GONE);
delosettings.setVisibility(View.GONE);
delapps.setVisibility(View.GONE);
done.setVisibility(View.GONE);
addshortcut.setVisibility(View.GONE);
}
});
//edit button
final ImageButton edit= (ImageButton) findViewById(R.id.edit);
edit.setOnClickListener(new View.OnClickListener() {
[user=439709]@override[/user]
public void onClick(View v) {
if (apps.getVisibility()==View.VISIBLE){
delapps.setVisibility(View.VISIBLE);
}
if (wbrowser.getVisibility()==View.VISIBLE){
delwbrowser.setVisibility(View.VISIBLE);
}
if (osettings.getVisibility()==View.VISIBLE){
delosettings.setVisibility(View.VISIBLE);
}
done.setVisibility(View.VISIBLE);
addshortcut.setVisibility(View.VISIBLE);
}
});
//code to open editor for all delete buttons
//apps
apps.setOnLongClickListener(new View.OnLongClickListener() {
[user=439709]@override[/user]
public boolean onLongClick(View v) {
if (delapps.getVisibility()==View.GONE){
delapps.setVisibility(View.VISIBLE);
}
else{
delapps.setVisibility(View.GONE);
}
return true;
}
});
//web browser
wbrowser.setOnLongClickListener(new View.OnLongClickListener() {
[user=439709]@override[/user]
public boolean onLongClick(View v) {
if (delwbrowser.getVisibility()==View.GONE){
delwbrowser.setVisibility(View.VISIBLE);
}
else{
delwbrowser.setVisibility(View.GONE);
}
return true;
}
});
//settings
osettings.setOnLongClickListener(new View.OnLongClickListener() {
[user=439709]@override[/user]
public boolean onLongClick(View v) {
if (delosettings.getVisibility()==View.GONE){
delosettings.setVisibility(View.VISIBLE);
scroller.fullScroll(ScrollView.FOCUS_RIGHT);
}
else{
delosettings.setVisibility(View.GONE);
}
return true;
}
});
}
}
I get a error at: PackageManager packageManager = context.getPackageManager();
The error is as follows: context cannot be resolved
please help!!
[ code] tags would be helpful
out of ideas said:
[ code] tags would be helpful
Click to expand...
Click to collapse
just added code tags
sorry about that lol
You dont have startActivity in your launcher button
Can you please give me a code example fairly new to this
Sent from my Nexus 4 using xda app-developers app
Well, if you just want a activity list and launches when clicked, you can simply create a LauncherActivity.
Can you please show me using my code example where I would place that at? Thank you so much
Rapsong11
Sent from my Nexus 4 using xda app-developers app
rapsong11 said:
Can you please show me using my code example where I would place that at? Thank you so much
Rapsong11
Sent from my Nexus 4 using xda app-developers app
Click to expand...
Click to collapse
1. create new class MyLauncherActivity
2. override the method "getTargetIntent()" in LauncherActivity
Code:
...
import android.app.LauncherActivity;
public class MyLauncherActivity extends LauncherActivity {
[user=439709]@override[/user]
protected Intent getTargetIntent () {
// just a example, you should replace the method yourself
Intent intent = new Intent();
intent.setAction(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_LAUNCHER);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
return intent;
}
}
3. replace the code inside your onClick method to the R.id.all_apps button :
Code:
Intent intent = new Intent(this, MyLauncherActivity.class);
startActivity(intent);
4. don't forget to declare MyLauncherActivity in your AndroidMenifest.xml
5. try to do it yourself with others' experience, but not just ask for the code, that's not good for a coder. Wish you can understand this.
I am building an android application to do various queries on my MySQL database. Once a successful login has returned on the main activity, I create a new Intent that holds search and query options. Here's the issue I am having. I keep getting a null pointer exception on stmt = con.createStatement(); Below is my logcat:
Code:
08-20 16:12:07.359 654-810/com.android.exchange D/ExchangeService: !!! deviceId unknown; stopping self and retrying
08-20 16:12:08.469 36-653/? E/SurfaceFlinger: ro.sf.lcd_density must be defined as a build property
08-20 16:12:11.559 1926-1949/com.example.testapplication W/System.err: java.lang.NullPointerException
08-20 16:12:11.559 1926-1949/com.example.testapplication W/System.err: at com.example.testapplication.Networking.Search(Networking.java:44)
08-20 16:12:11.559 1926-1949/com.example.testapplication W/System.err: at com.example.testapplication.ControlActivity$1.run(ControlActivity.java:53)
08-20 16:12:11.559 1926-1949/com.example.testapplication W/System.err: at java.lang.Thread.run(Thread.java:856)
08-20 16:12:12.369 654-654/com.android.exchange D/ExchangeService: !!! EAS ExchangeService, onStartCommand, startingUp = false, running = false
08-20 16:12:12.369 278-498/system_process W/ActivityManager: Unable to start service Intent { act=com.android.email.ACCOUNT_INTENT } U=0: not found
08-20 16:12:12.369 654-815/com.android.exchange D/ExchangeService: !!! Email application not found; stopping self
08-20 16:12:12.379 278-278/system_process W/ActivityManager: Unable to start service Intent { act=com.android.email.ACCOUNT_INTENT } U=0: not found
I'm curious whether it is better practice to close the connection and reopen it in the new intent? Or pass the connection between intents somehow?
Any input would be greatly appreciated!
wait...
Here are snippets of my code to help debug.
Code:
[user=439709]@override[/user]
public void onClick(View view) {
if(view.getId() == R.id.LoginButton) {
Toast.makeText(getApplicationContext(), "Attempting Connection", Toast.LENGTH_SHORT).show();
//Spawn new thread
new Thread(new Runnable() {
public void run() {
if(net.execLogin(mUserInput.getText().toString(), mPassInput.getText().toString())) {
runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(getApplicationContext(), "Connected to Database", Toast.LENGTH_LONG).show();
}
});
//start new activity
Handler handler = new Handler(Looper.getMainLooper());
handler.post(new Runnable() {
[user=439709]@override[/user]
public void run() {
Intent intent = new Intent(LoginActivity.this, ControlActivity.class);
startActivity(intent);
}
});
}
else {
runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(getApplicationContext(), "Connection Failed :(", Toast.LENGTH_LONG).show();
}
});
}
}
}).start();
}
}
And here is the new activity started by the above code:
Code:
package com.example.testapplication;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;
import java.util.ArrayList;
public class ControlActivity extends Activity implements View.OnClickListener {
private ArrayList<Hardware> list = new ArrayList<Hardware>();
EditText mEditText;
ListView mListView;
[user=439709]@override[/user]
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_control);
setupPage();
}
public void setupPage() {
Button search = (Button)findViewById(R.id.search);
search.setOnClickListener(this);
mEditText = (EditText)findViewById(R.id.editText);
mListView = (ListView)findViewById(R.id.listView);
}
[user=439709]@override[/user]
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.control, menu);
return true;
}
public void onClick(View view) {
if(view.getId() == R.id.search) {
new Thread(new Runnable() {
public void run() {
list = new Networking().Search("Type", mEditText.getText().toString());
}
}).start();
ArrayAdapter<Hardware> adapter = new ArrayAdapter<Hardware>(this, android.R.layout.simple_list_item_1, list);
adapter.notifyDataSetChanged();
mListView.setAdapter(adapter);
if(list == null) {
runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(getApplicationContext(), "0 Results Yielded :(", Toast.LENGTH_SHORT).show();
}
});
}
}
}
}
And here is the code I use to connect and query the database
Code:
import java.sql.*;
import java.util.*;
public class Networking implements DbQuery {
private static final String DRIVER = "org.mariadb.jdbc.Driver";
private static final String URL = "jdbc:mysql://146.187.16.32/Peirce";
ArrayList<Hardware> ara = new ArrayList<Hardware>();
Database db = new Database();
Hardware h1;
Connection con = null;
Statement stmt = null;
public boolean execLogin(String uName, String pWord) {
try {
Class.forName(DRIVER);
con = DriverManager.getConnection(URL, uName, pWord);
if(!con.isClosed()){
return true;
}
return false;
}catch(SQLException e) {
e.printStackTrace();
}catch(ClassNotFoundException e) {
e.printStackTrace();
}
return false;
}
public ArrayList<Hardware> Search(String arg, String target) {
try {
stmt = con.createStatement(); //throws null pointer exception
ResultSet rs = stmt.executeQuery("Select * from " + db.getTable() + " where " + arg + "='" + target + "';");
while(rs.next()) {
ara.add(new Hardware(rs.getString("Type"), rs.getString("Make"), rs.getString("Model"), rs.getString("Serial"), rs.getString("Comments")));
}
return ara;
}catch(SQLException e) {
e.printStackTrace();
}catch(NullPointerException e) {
e.printStackTrace();
}
return ara;
}
nevermind
i have figured it out.
Hi frends im working on my android final year project based on sockets..im using ssynctask to connect socket etc..Everything works fine, since I'm using AsyncTask to create a Socket connection ... the socket works fine in the doInBackground() method, but when I try to send Sensor data from theonSensorChanged() method, I get null pointer exception. I don't know what went wrong. in short Socket returns NULL outside asyncTask Class...can some 1 help me ?..
here is my code
Code:
package com.example.sensorsmart;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import android.app.Activity;
import android.content.Context;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity implements SensorEventListener{
private static final int SERVERPORT = 8222;
private static final String SERVER_IP = "192.168.0.101";
private SensorManager mSensorManager;
private Sensor mAccelerometer;
private TextView tv ;
public ServerSocket serverSocket=null;
public Socket socket = null;
public BufferedReader in ;
public BufferedWriter out;
public PrintWriter pw ;
public FileWriter writer=null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new MyTask().execute();
mSensorManager = (SensorManager)getSystemService(Context.SENSOR_SERVICE);
mAccelerometer mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
mSensorManager.registerListener(this, mAccelerometer,SensorManager.SENSOR_DELAY_NORMAL);
}
public void onStopClick(View view) {
mSensorManager.unregisterListener(this);}
private class MyTask extends AsyncTask<Void, Void, Void>
{
@Override
protected Void doInBackground(Void... arg0) {
try {
serverSocket = new ServerSocket(8222);
} catch (IOException e) {
e.printStackTrace();
}
try {
socket=serverSocket.accept();
Log.i("TcpServer", "CONNECTED");
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
pw = new PrintWriter(socket.getOutputStream(),true);
if(!in.ready())
{
Log.i("TcpServer", "READER IS NOT READY");
}
final String g;
final String c;
String b = null;
Log.i("TcpServer", "GOING");
g=in.readLine();
runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(getApplicationContext(),g, Toast.LENGTH_LONG).show();
}
});
} catch (IOException e) {
e.printStackTrace();
String response = e.getCause().toString();
Log.i("TCP",response);
}
return null;
}
}
@Override
public void onSensorChanged(SensorEvent event) {
float x = event.values[0];
float y = event.values[1];
float z = event.values[2];
pw.write("g"); //NULL POINT EXCEPTION THROWS HERE
}
}
LOGCAT:
Code:
02-06 11:31:54.250: E/AndroidRuntime(4108): FATAL EXCEPTION: main
02-06 11:31:54.250: E/AndroidRuntime(4108): java.lang.NullPointerException
02-06 11:31:54.250: E/AndroidRuntime(4108): at com.example.sensorsmart.MainActivity.onSensorChanged(MainActivity.java:196)
02-06 11:31:54.250: E/AndroidRuntime(4108): at android.hardware.SystemSensorManager$ListenerDelegate$1.handleMessage(SystemSensorManager.java:204)
02-06 11:31:54.250: E/AndroidRuntime(4108): at android.os.Handler.dispatchMessage(Handler.java:99)
02-06 11:31:54.250: E/AndroidRuntime(4108): at android.os.Looper.loop(Looper.java:137)
02-06 11:31:54.250: E/AndroidRuntime(4108): at android.app.ActivityThread.main(ActivityThread.java:4759)
02-06 11:31:54.250: E/AndroidRuntime(4108): at java.lang.reflect.Method.invokeNative(Native Method)
02-06 11:31:54.250: E/AndroidRuntime(4108): at java.lang.reflect.Method.invoke(Method.java:511)
02-06 11:31:54.250: E/AndroidRuntime(4108): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:791)
02-06 11:31:54.250: E/AndroidRuntime(4108): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:558)
02-06 11:31:54.250: E/AndroidRuntime(4108): at dalvik.system.NativeStart.main(Native Method)
you have to set the variable in onpostexecute() and also use
Code:
new MyTask().execute().get()
so you make sure the async task has finished for sure
Can u gv example ?
warlock9_0 said:
you have to set the variable in onpostexecute() and also use
Code:
new mytask().execute().get()
so you make sure the async task has finished for sure
Click to expand...
Click to collapse
frend can u give me an example ?
forget the execute().get() for now, maybe it is not needed
read the documents for asynctask and change your result type from void, to whatever you want to set
for example if you want only the PrintWriter to be set you can do this
Code:
package com.example.sensorsmart;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import android.app.Activity;
import android.content.Context;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity implements SensorEventListener{
private static final int SERVERPORT = 8222;
private static final String SERVER_IP = "192.168.0.101";
private SensorManager mSensorManager;
private Sensor mAccelerometer;
private TextView tv ;
public ServerSocket serverSocket=null;
public Socket socket = null;
public BufferedReader in ;
public BufferedWriter out;
public PrintWriter pw ;
public FileWriter writer=null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new MyTask().execute();
mSensorManager = (SensorManager)getSystemService(Context.SENSOR_SERVICE);
mAccelerometer mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
mSensorManager.registerListener(this, mAccelerometer,SensorManager.SENSOR_DELAY_NORMAL);
}
public void onStopClick(View view) {
mSensorManager.unregisterListener(this);}
private class MyTask extends AsyncTask<Void, Void, PrintWriter>
{
@Override
protected PrintWriter doInBackground(Void... arg0) {
try {
serverSocket = new ServerSocket(8222);
} catch (IOException e) {
e.printStackTrace();
}
try {
socket=serverSocket.accept();
Log.i("TcpServer", "CONNECTED");
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
pw = new PrintWriter(socket.getOutputStream(),true);
if(!in.ready())
{
Log.i("TcpServer", "READER IS NOT READY");
}
final String g;
final String c;
String b = null;
Log.i("TcpServer", "GOING");
g=in.readLine();
runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(getApplicationContext(),g, Toast.LENGTH_LONG).show();
}
});
} catch (IOException e) {
e.printStackTrace();
String response = e.getCause().toString();
Log.i("TCP",response);
}
return pw;
}
protected void onPostExecute(PrintWriter result) {
pw = result;
}
}
@Override
public void onSensorChanged(SensorEvent event) {
float x = event.values[0];
float y = event.values[1];
float z = event.values[2];
if(pw!=null) pw.write("g"); //NULL POINT EXCEPTION THROWS HERE
}
}
if you want other variables to be returned too, you can make a custom object as the type of the result
is it possible to pass socket instead mof printwriter?
hi friend thank u for ur reply...is it possible to pass socket in onpostexecute () ?
i tried with below code still socket is null in ONsensor Changed
Code:
private class MyTask extends AsyncTask<Void, Void,Socket>
{
@Override
protected Socket doInBackground(Void... arg0) {
// TODO Auto-generated method stub
try {
serverSocket = new ServerSocket(8222);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
socket=serverSocket.accept();
Log.i("TcpServer", "CONNECTED");
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
pw = new PrintWriter(socket.getOutputStream(),true);
//out = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
if(!in.ready())
{
Log.i("TcpServer", "READER IS NOT READY");
}
final String g;
final String c;
String b = null;
Log.i("TcpServer", "GOING");
g=in.readLine();
//Log.i("TcpServer", in.readLine());
runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(getApplicationContext(),g, Toast.LENGTH_LONG).show();
}
});
Log.i("TcpServer", "RECEIVED");
runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(getApplicationContext(),g, Toast.LENGTH_LONG).show();
}
});
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
String response = e.getCause().toString();
Log.i("TCP",response);
}
return socket;
}
protected void onPostExecute(Socket result) {
socket = result;
}
yes, you can pass the socket like you do
but in the onsensorchanged function you are using the printwriter (pw) you created in the doinbackground function which is null because you haven't passed it to the main thread
so, you either have to make a new object that will pass all the things to the main threat (socket, printwriter, bufferedreader) if you want them all, or pass the printwriter only, or you will initialize them on the post execute function
for example, you can return the socket and then do
Code:
protected void onPostExecute(Socket result) {
socket = result;
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
pw = new PrintWriter(socket.getOutputStream(),true);
}
still null
here is my entire code..i have done exactly what u said...still socket null in OnsensorChanged()
Code:
package com.example.sensorsmart;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import android.app.Activity;
import android.content.Context;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity implements SensorEventListener{
private static final int SERVERPORT = 8222;
private static final String SERVER_IP = "192.168.0.101";
private SensorManager mSensorManager;
private Sensor mAccelerometer;
private TextView tv ;
public ServerSocket serverSocket=null;
public Socket socket = null;
public BufferedReader in ;
public BufferedWriter out;
public PrintWriter pw ;
public FileWriter writer=null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new MyTask().execute();
mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
mAccelerometer = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
mSensorManager.registerListener(this, mAccelerometer, SensorManager.SENSOR_DELAY_NORMAL);
}
public void onStopClick(View view) {
mSensorManager.unregisterListener(this);
}
protected void onResume() {
super.onResume();
}
protected void onStop(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mSensorManager.unregisterListener(this);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
private class MyTask extends AsyncTask<Void, Void,Socket>
{
@Override
protected Socket doInBackground(Void... arg0) {
// TODO Auto-generated method stub
try {
serverSocket = new ServerSocket(8222);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
socket=serverSocket.accept();
Log.i("TcpServer", "CONNECTED");
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
pw = new PrintWriter(socket.getOutputStream(),true);
//out = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
if(!in.ready())
{
Log.i("TcpServer", "READER IS NOT READY");
}
final String g;
final String c;
String b = null;
Log.i("TcpServer", "GOING");
g=in.readLine();
//Log.i("TcpServer", in.readLine());
runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(getApplicationContext(),g, Toast.LENGTH_LONG).show();
}
});
Log.i("TcpServer", "RECEIVED");
runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(getApplicationContext(),g, Toast.LENGTH_LONG).show();
}
});
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
String response = e.getCause().toString();
Log.i("TCP",response);
}
return socket;
}
protected void onPostExecute(Socket result) {
socket = result;
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
pw = new PrintWriter(socket.getOutputStream(),true);
}
}
@Override
public void onAccuracyChanged(Sensor arg0, int arg1) {
// TODO Auto-generated method stub
}
@Override
public void onSensorChanged(SensorEvent event) {
pw.println("egaga");
}
public void CloseConn() throws IOException //not used
{
pw.flush();
in.close();
socket.close();
serverSocket.close();
}
}
Code:
public class MainActivity extends Activity implements SensorEventListener{
private static final int SERVERPORT = 8222;
private static final String SERVER_IP = "192.168.0.101";
private SensorManager mSensorManager;
private Sensor mAccelerometer;
private TextView tv ;
public ServerSocket serverSocket=null;
public Socket socket = null;
public BufferedReader in ;
public BufferedWriter out;
public PrintWriter pw ;
public FileWriter writer=null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new MyTask().execute();
mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
mAccelerometer = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
mSensorManager.registerListener(this, mAccelerometer, SensorManager.SENSOR_DELAY_NORMAL);
}
public void onStopClick(View view) {
mSensorManager.unregisterListener(this);
}
protected void onResume() {
super.onResume();
}
protected void onStop(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mSensorManager.unregisterListener(this);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
private class MyTask extends AsyncTask<Void, Void,AllInOne>
{
@Override
protected AllInOne doInBackground(Void... arg0) {
// TODO Auto-generated method stub
try {
serverSocket = new ServerSocket(8222);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
socket=serverSocket.accept();
Log.i("TcpServer", "CONNECTED");
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
pw = new PrintWriter(socket.getOutputStream(),true);
//out = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
if(!in.ready())
{
Log.i("TcpServer", "READER IS NOT READY");
}
final String g;
final String c;
String b = null;
Log.i("TcpServer", "GOING");
g=in.readLine();
//Log.i("TcpServer", in.readLine());
runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(getApplicationContext(),g, Toast.LENGTH_LONG).show();
}
});
Log.i("TcpServer", "RECEIVED");
runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(getApplicationContext(),g, Toast.LENGTH_LONG).show();
}
});
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
String response = e.getCause().toString();
Log.i("TCP",response);
}
return new AllInOne(socket,in,pw);
}
protected void onPostExecute(AllInOne result) {
socket = result.so;
in = result.re;
pw = result.pr;
}
}
@Override
public void onAccuracyChanged(Sensor arg0, int arg1) {
// TODO Auto-generated method stub
}
@Override
public void onSensorChanged(SensorEvent event) {
if(pw!=null) pw.println("egaga");
else Log.e("PrintWriter", null);
}
public void CloseConn() throws IOException //not used
{
pw.flush();
in.close();
socket.close();
serverSocket.close();
}
private class AllInOne {
public Socket so;
public BufferedReader re;
public PrintWriter pr;
public AllInOne(Socket s, BufferedReader r, PrintWriter p ){
this.so = s;
this.re = r;
this.pr = p;
}
}
}
try this
since you are initializing in and pw inside the doinbackground, you have to pass them to the main thread
so i added another class to hold all these and i pass them on result
finally you also have to check in the onsensorchanged if the pw is null because the asynctask may have not finished yet when this is called
null
async task not completed because of socket not closed?
Thank u
bro..some how i managed to get it work..thanks a lot for ur time..and nice to meet u..
I have coded this android app which produces a listView containing songs which are streamed from the internet, and the user can play them by clicking them using the mediaPlayer.
What i am having trouble with is allowing the user to add a song to the arrayList that populates the ListView within MainActivity.java. I have used the settings page to add textboxes so the user can add their songs by inputting, Song Name, Artist and the Direct Link to the song. Though the code i have used for this doesn't work, it should add the Song Name, Artist and Direct Link into the array_list_music ArrayList, then update the ListView, or at least i think that is how it should be done, although after entering details and clicking the 'Add Song' button, and returning to the main page, the ListView does not that the newly added song.
I have shown my code below.
So if someone could help with this problem, that would be great, thanks.
MainActivity.java
Code:
package com.groupassignment.musicplayer;
import java.util.ArrayList;
import android.app.ListActivity;
import android.content.Intent;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnPreparedListener;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.MediaController;
import android.widget.Toast;
public class MainActivity extends ListActivity implements OnPreparedListener, MediaController.MediaPlayerControl {
private static final String TAG = "AudioPlayer";
private ListView list;
public MainArrayAdapter adapter;
private MediaPlayer mediaPlayer;
private MediaController mediaController;
private String audioFile;
private Handler handler = new Handler();
ArrayList<String> array_list_music = new ArrayList<String>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
list = getListView();
mediaPlayer = new MediaPlayer();
mediaPlayer.setOnPreparedListener(this);
mediaController = new MediaController(this);
//ArrayList<String> array_list_music = new ArrayList<String>();
//Used to add a song to the array list
array_list_music
.add("Jar of Hearts"
+ " ### "
+ "Christina Perri"
+ " ### "
+ "LINK");
array_list_music
.add("Save The World"
+ " ### "
+ "Swedish House Mafia feat. John Martin"
+ " ### "
+ "LINK");
array_list_music
.add("Bromance"
+ " ### "
+ "Avicii"
+ " ### "
+ "LINK");
adapter = new MainArrayAdapter(MainActivity.this, array_list_music);
setListAdapter(adapter);
//used to display toast and to play song using the URL, when clicking on a song
list.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
Object item = getListView().getItemAtPosition(arg2);
String the_list_item = item.toString();
Toast.makeText(MainActivity.this, "You are now listening to: " + the_list_item, Toast.LENGTH_LONG).show();
String[] aux = the_list_item.split(" ### ");
String url_to_play = aux[2];
playAudio(url_to_play);//sends url from arraylist item to the playAudio method
}
});
}
//used to play audio using the android mediaPlayer
private void playAudio(String url_to_play) {
//stop & reset player
try {
mediaPlayer.stop();
mediaPlayer.reset();
} catch (Exception e) {
}
//set the url, prepare it, and then play it
try {
mediaPlayer.setDataSource(url_to_play);
mediaPlayer.prepare();
mediaPlayer.start();
} catch (Exception e) {
Log.e(TAG, "Could not open file " + url_to_play + ".", e);
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_settings:
Intent i_settings = new Intent(MainActivity.this, SettingsActivity.class);
startActivity(i_settings);
break;
}
return true;
}
@Override
public boolean onTouchEvent(MotionEvent event) {
mediaController.show();
return false;
}
//used to hide media controller, stop the media player and to release the url.
@Override
protected void onStop() {
super.onStop();
mediaController.hide();
mediaPlayer.stop();
mediaPlayer.release();
}
@Override
public boolean canPause() {
return true;
}
@Override
public boolean canSeekBackward() {
return true;
}
@Override
public boolean canSeekForward() {
return true;
}
@Override
public int getBufferPercentage() {
return 0;
}
@Override
public int getCurrentPosition() {
return mediaPlayer.getCurrentPosition();
}
@Override
public int getDuration() {
return mediaPlayer.getDuration();
}
@Override
public boolean isPlaying() {
return mediaPlayer.isPlaying();
}
@Override
public void pause() {
mediaPlayer.pause();
}
@Override
public void seekTo(int arg0) {
mediaPlayer.seekTo(arg0);
}
@Override
public void start() {
mediaPlayer.start();
}
public void onPrepared(MediaPlayer mediaPlayer) {
Log.d(TAG, "onPrepared");
mediaController.setMediaPlayer(this);
mediaController.setAnchorView(list);
handler.post(new Runnable() {
public void run() {
mediaController.setEnabled(true);
mediaController.show();
}
});
}
//------- what can you do from here -------
// implement your own media player with buttons since this one is not behaving "smart"..
// make next,previous buttons
// highlight the list item on click
// add your own server for playing music
// anything you want :)
}
MainArrayAdapter.java
Code:
package com.groupassignment.musicplayer;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import android.content.Context;
import android.database.DataSetObserver;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListAdapter;
import android.widget.TextView;
import com.groupassignment.musicplayer.R;
public class MainArrayAdapter extends ArrayAdapter<String> implements ListAdapter {
private final Context context;
private ArrayList<String> data_array;
private List<DataSetObserver> observers = new LinkedList<DataSetObserver>();
public MainArrayAdapter(Context context, ArrayList<String> list_of_ids) {
super(context, R.layout.main_list_rowlayout, list_of_ids);
this.context = context;
this.data_array = list_of_ids;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View rowView = inflater.inflate(R.layout.main_list_rowlayout, parent,
false);
TextView textView_main_row_song_name = (TextView) rowView
.findViewById(R.id.textView_main_row_song_name);
TextView textView_main_row_singer_name = (TextView) rowView
.findViewById(R.id.textView_main_row_singer_name);
try {
String[] aux = data_array.get(position).split(" ### ");
String song_name = aux[0];
String artist = aux[1];
String url = aux[2];
textView_main_row_song_name.setText(song_name);
textView_main_row_singer_name.setText(artist);
} catch (Exception e) {
// TODO: handle exception
}
return rowView;
}
public void setArray(ArrayList<String> data_array){
this.data_array = data_array;
for (DataSetObserver observer : observers){
observer.onChanged();
}
}
@Override
public void registerDataSetObserver(DataSetObserver dataSetObserver) {
((LinkedList) observers).addFirst(dataSetObserver);
}
@Override
public void unregisterDataSetObserver(DataSetObserver dataSetObserver) {
observers.remove(dataSetObserver);
}
}
SettingsActivity.java
Code:
package com.groupassignment.musicplayer;
import android.app.Activity;
import android.view.View;
import android.widget.EditText;
import com.groupassignment.musicplayer.R;
public class SettingsActivity extends Activity {
public String str ="";
String songName;
String artist;
String directLink;
protected void onCreate(android.os.Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_settings);
songName = ((EditText)findViewById(R.id.editTextSongName)).toString();
artist = ((EditText)findViewById(R.id.editTextArtist)).toString();
directLink = ((EditText)findViewById(R.id.editTextDirectLink)).toString();
};
public void buttonAddSongClicked(View v)
{
addSong(songName, artist, directLink);
}
private void addSong(String artist, String songName, String directLink)
{
MainActivity main = new MainActivity();
main.array_list_music
.add( songName
+ " ### "
+ artist
+ " ### "
+ directLink);
main.adapter.notifyDataSetChanged();
main.adapter = new MainArrayAdapter(main, main.array_list_music);
}
}
The problem is that you create new instances of adapter each time, instead of updating the existing one. Easy way to solve your problem is to change attributes of array_list_music and adapter to public static in your MainActivity and modify addSong inside SettingsActivity to:
Code:
private void addSong(String artist, String songName, String directLink)
{
MainActivity.array_list_music
.add( songName
+ " ### "
+ artist
+ " ### "
+ directLink);
MainActivity.adapter.notifyDataSetChanged();
}
Hi I was looking for tutorials to make a radio app so I followed this one but the problem is that as soon as the app closes the music stops, how do I turn it into a service. Thanks
Code:
import android.app.Activity;
import android.os.Bundle;
import java.io.IOException;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnBufferingUpdateListener;
import android.media.MediaPlayer.OnPreparedListener;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ProgressBar;
public class myMain extends Activity implements OnClickListener {
private ProgressBar playSeekBar;
private Button buttonPlay;
private Button buttonStopPlay;
private MediaPlayer player;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
initializeUIElements();
initializeMediaPlayer();
}
private void initializeUIElements() {
playSeekBar = (ProgressBar) findViewById(R.id.progressBar1);
playSeekBar.setMax(100);
playSeekBar.setVisibility(View.INVISIBLE);
buttonPlay = (Button) findViewById(R.id.buttonPlay);
buttonPlay.setOnClickListener(this);
buttonStopPlay = (Button) findViewById(R.id.buttonStopPlay);
buttonStopPlay.setEnabled(false);
buttonStopPlay.setOnClickListener(this);
}
public void onClick(View v) {
if (v == buttonPlay) {
startPlaying();
} else if (v == buttonStopPlay) {
stopPlaying();
}
}
private void startPlaying() {
buttonStopPlay.setEnabled(true);
buttonPlay.setEnabled(false);
playSeekBar.setVisibility(View.VISIBLE);
player.prepareAsync();
player.setOnPreparedListener(new OnPreparedListener() {
public void onPrepared(MediaPlayer mp) {
player.start();
}
});
}
private void stopPlaying() {
if (player.isPlaying()) {
player.stop();
player.release();
initializeMediaPlayer();
}
buttonPlay.setEnabled(true);
buttonStopPlay.setEnabled(false);
playSeekBar.setVisibility(View.INVISIBLE);
}
private void initializeMediaPlayer() {
player = new MediaPlayer();
try {
player.setDataSource("stream url");
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
player.setOnBufferingUpdateListener(new OnBufferingUpdateListener() {
public void onBufferingUpdate(MediaPlayer mp, int percent) {
playSeekBar.setSecondaryProgress(percent);
Log.i("Buffering", "" + percent);
}
});
}
@Override
protected void onPause() {
super.onPause();
if (player.isPlaying()) {
player.stop();
}
}
}
benpaterson said:
Hi I was looking for tutorials to make a radio app so I followed this one but the problem is that as soon as the app closes the music stops, how do I turn it into a service. Thanks
Code:
import android.app.Activity;
import android.os.Bundle;
import java.io.IOException;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnBufferingUpdateListener;
import android.media.MediaPlayer.OnPreparedListener;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ProgressBar;
public class myMain extends Activity implements OnClickListener {
private ProgressBar playSeekBar;
private Button buttonPlay;
private Button buttonStopPlay;
private MediaPlayer player;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
initializeUIElements();
initializeMediaPlayer();
}
private void initializeUIElements() {
playSeekBar = (ProgressBar) findViewById(R.id.progressBar1);
playSeekBar.setMax(100);
playSeekBar.setVisibility(View.INVISIBLE);
buttonPlay = (Button) findViewById(R.id.buttonPlay);
buttonPlay.setOnClickListener(this);
buttonStopPlay = (Button) findViewById(R.id.buttonStopPlay);
buttonStopPlay.setEnabled(false);
buttonStopPlay.setOnClickListener(this);
}
public void onClick(View v) {
if (v == buttonPlay) {
startPlaying();
} else if (v == buttonStopPlay) {
stopPlaying();
}
}
private void startPlaying() {
buttonStopPlay.setEnabled(true);
buttonPlay.setEnabled(false);
playSeekBar.setVisibility(View.VISIBLE);
player.prepareAsync();
player.setOnPreparedListener(new OnPreparedListener() {
public void onPrepared(MediaPlayer mp) {
player.start();
}
});
}
private void stopPlaying() {
if (player.isPlaying()) {
player.stop();
player.release();
initializeMediaPlayer();
}
buttonPlay.setEnabled(true);
buttonStopPlay.setEnabled(false);
playSeekBar.setVisibility(View.INVISIBLE);
}
private void initializeMediaPlayer() {
player = new MediaPlayer();
try {
player.setDataSource("stream url");
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
player.setOnBufferingUpdateListener(new OnBufferingUpdateListener() {
public void onBufferingUpdate(MediaPlayer mp, int percent) {
playSeekBar.setSecondaryProgress(percent);
Log.i("Buffering", "" + percent);
}
});
}
@Override
protected void onPause() {
super.onPause();
if (player.isPlaying()) {
player.stop();
}
}
}
Click to expand...
Click to collapse
You'll have to learn about Android Service and extend that, instead of Activity.