Reputation: 4563
I want to display listview in my songlist activity,.. For that i have created MyService class that i am going to use for playback service. In that MyService class i have created method that will get al the songs available on SDCard. I want to display all that song in listview of songlist Activity by using service.
Here is my code in songList Activity :
private ServiceConnection serviceConnection = new ServiceConnection() {
public void onServiceDisconnected(ComponentName name) {
objservice = null;
}
public void onServiceConnected(ComponentName name, IBinder service) {
// TODO Auto-generated method stub
objservice = ((MyService.LocalBinder) service).getService();
adapter = (ListAdapter) objservice.getSongList();
}
};
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.playlist);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
bindService(new Intent(PlayListActivity.this, MyService.class),
serviceConnection, BIND_AUTO_CREATE);
setListAdapter(adapter);
}
Service class code :
public class MyService extends Service {
private MediaPlayer mp = null;
private ArrayList<HashMap<String, String>> songsList = new ArrayList<HashMap<String, String>>();
private ListAdapter adapter = null;
@Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return new LocalBinder();
}
@Override
public void onCreate() {
}
public class LocalBinder extends Binder {
MyService getService() {
return MyService.this;
}
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
return START_STICKY;
}
public ListAdapter getSongList() {
final ArrayList<HashMap<String, String>> songsListData = new ArrayList<HashMap<String, String>>();
Cursor cursor = getContentResolver().query(
android.provider.MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
null, null, null, null);
if (cursor == null) {
// Query Failed , Handle error.
} else if (!cursor.moveToFirst()) {
// No media on the device.
} else {
int titleColumn = cursor
.getColumnIndex(android.provider.MediaStore.Audio.Media.TITLE);
int idColumn = cursor
.getColumnIndexOrThrow(android.provider.MediaStore.Audio.Media.DATA);
int artistcolumn = cursor
.getColumnIndex(android.provider.MediaStore.Audio.Media.ARTIST);
int durationcolumn = cursor
.getColumnIndex(android.provider.MediaStore.Audio.Media.DURATION);
int id = cursor
.getColumnIndex(android.provider.MediaStore.Audio.Media._ID);
for (int i = 0; i < cursor.getCount(); i++) {
String thisTitle = cursor.getString(titleColumn);
String path = cursor.getString(idColumn);
String artist = cursor.getString(artistcolumn);
Long duration = cursor.getLong(durationcolumn);
Utilities objUtilities = new Utilities();
String timeDuration = objUtilities
.milliSecondsToTimer(duration);
String ID = cursor.getString(id);
HashMap<String, String> song = new HashMap<String, String>();
song.put("songTitle", thisTitle);
song.put("songPath", path);
song.put("artist", artist);
song.put("duration", timeDuration);
song.put("id", ID);
songsList.add(song);
cursor.moveToNext();
}
}
for (int i = 0; i < songsList.size(); i++) {
// creating new HashMap
HashMap<String, String> song = songsList.get(i);
// adding HashList to ArrayList
songsListData.add(song);
}
String[] from = { "songTitle", "artist", "duration" };
int[] to = { R.id.songTitle, R.id.songArtist, R.id.duration };
return adapter = new SimpleAdapter(this, songsListData,
R.layout.playlist_item, from, to) {
public long getItemId(int position) {
return songsListData.indexOf(getItem(position));
}
};
}
}
So what is my error?
Upvotes: 3
Views: 3807
Reputation: 6604
I am late in this discussion.
I go through this way to bind service.
This is Client.java class
package com.example.bindservice.binder;
import java.util.ArrayList;
import java.util.Calendar;
import com.example.bindservice.binder.Server.LocalBinder;
import android.app.Activity;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
public class Client extends Activity {
Handler handler;
boolean mBounded;
Server mServer = new Server();
TextView text;
ListView list;
Button button;
Calendar calendar;
int minute;
Intent mIntent;
ArrayList<String> arlstText;
ArrayAdapter<String> adapterList;
static HandlerText handlerAct;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//calendar = new GregorianCalendar();
text = (TextView)findViewById(R.id.text);
button = (Button) findViewById(R.id.button);
list = (ListView) findViewById(R.id.list);
// minute = calendar.get(Calendar.MINUTE);
// Log.i("Log", "Minute is: "+minute);
// final String[] data = mServer.names;
handlerAct = new HandlerText();
arlstText = new ArrayList<String>();
adapterList = new ArrayAdapter<String>(Client.this,android.R.layout.simple_list_item_1, arlstText );
list.setAdapter(adapterList);
button.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
text.setText(mServer.getTime());
}
});
}
@Override
protected void onStart() {
super.onStart();
Log.i("Log", "M in onStart");
mIntent = new Intent(this, Server.class);
bindService(mIntent, mConnection, BIND_AUTO_CREATE);
}
ServiceConnection mConnection = new ServiceConnection() {
public void onServiceDisconnected(ComponentName name) {
Log.i("Log", "M in onServiceDisconnected");
Toast.makeText(Client.this, "Service is disconnected", 1000).show();
mBounded = false;
mServer = null;
}
public void onServiceConnected(ComponentName name, IBinder service) {
Log.i("Log", "M in onServiceConnected");
Toast.makeText(Client.this, "Service is connected", 100).show();
mBounded = true;
LocalBinder mLocalBinder = (LocalBinder)service;
mServer = mLocalBinder.getServerInstance();
Log.i("Log", "Server Instance is: "+mLocalBinder.getServerInstance().toString());
}
};
@Override
protected void onStop() {
super.onStop();
Log.i("Log", "M in onStop");
if(mBounded) {
unbindService(mConnection);
mBounded = false;
}
}
class HandlerText extends Handler{
@Override
public void handleMessage(Message msg) {
// TODO Auto-generated method stub
super.handleMessage(msg);
String text= (String)msg.obj;
//String text = mServer.a;
arlstText.add(text);
adapterList.notifyDataSetChanged();
// stopService(mIntent);
// startService(mIntent);
//Toast.makeText(Client.this, "activity "+text, 1000).show();
}
}
}
Here is the Server.java class which extends Service class
package com.example.bindservice.binder;
import java.security.PublicKey;
import java.text.SimpleDateFormat;
import java.util.Date;
import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.util.Log;
import android.widget.Toast;
public class Server extends Service implements Runnable {
Message msg;
static String[] names = {
"Dwight D. Eisenhower",
"John F. Kennedy",
"Lyndon B. Johnson",
"Richard Nixon",
"Gerald Ford",
"Jimmy Carter",
"Ronald Reagan",
"George H. W. Bush",
"Bill Clinton",
"George W. Bush",
"Barack Obama"
};
private boolean isServiceRunning;
/*Handler handler = new Handler()
{
@Override
public void handleMessage(Message msg) {
// TODO Auto-generated method stub
super.handleMessage(msg);
msg.obj= (Object)names;
String[] data = Server.data(names);
for(int i = 0 ; i < data.length ; i++)
{
Log.i("Log", "data"+data[i]);
}
Toast.makeText(Server.this, "Service Started", 1000).show();
}
};*/
public static String[] data(String[] name)
{
name = names;
return name;
}
IBinder mBinder = new LocalBinder();
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
// TODO Auto-generated method stub
return 0;
}
public Server() {
// TODO Auto-generated constructor stub
Thread t = new Thread(this);
t.start();
}
@Override
public void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
isServiceRunning = false;
Log.i("Log", "The onDestroy is callled");
}
@Override
public void onCreate() {
// TODO Auto-generated method stub
super.onCreate();
/* ArrayAdapter<String> adapterList = new ArrayAdapter<String>(Server.this,android.R.layout.simple_list_item_1, names);
list.setAdapter(adapterList);*/
isServiceRunning = true;
}
@Override
public IBinder onBind(Intent intent) {
Log.i("Log", "M in onBind of server" );
return mBinder;
}
@Override
public void onRebind(Intent intent) {
// TODO Auto-generated method stub
super.onRebind(intent);
Log.i("Log", "M in onRebind");
}
@Override
public boolean onUnbind(Intent intent) {
// TODO Auto-generated method stub
return true;
}
public class LocalBinder extends Binder {
public Server getServerInstance() {
Log.i("Log", "M in getServerInstance of server" );
return Server.this;
}
}
public String getTime() {
Log.i("Log", "M in getTime of server class");
SimpleDateFormat mDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//Log.i("Log", "Time"+mDateFormat.toString());
return mDateFormat.format(new Date());
}
@Override
public void run() {
Log.i("Log", "run");
int i = 0,ai;
long millisec = 0,tempmilli;
while(isServiceRunning)
//while(millisec != 60000)
{
Log.i("Log", "while");
Log.i("Log", "Its started");
try {
/*tempmilli = 10000;
millisec = millisec + tempmilli;*/
Thread.sleep(3000);
for( ai = i ; ai< names.length; ai ++)
{
/*msg.obj = names[i];
Client.handlerAct.sendMessage(msg);
msg = Message.obtain();*/
//msg.recycle();
Log.i("Log", "ai is"+ai);
Log.i("Log", "i is"+i);
msg = Client.handlerAct.obtainMessage();
msg.obj = names[ai];
Client.handlerAct.sendMessage(msg);
break;
}
i = i+1;
Log.i("Log", "I outside loop"+i);
//Message msg = new Message();
//Message msg = Message.obtain();
/*msg = handler.obtainMessage();
msg.obj = "Hi";
Client.handlerAct.sendMessage(msg);*/
/* msg = handler.obtainMessage();
msg.obj = "Bye";
Client.handlerAct.sendMessage(msg);*/
Log.i("Log", "Loop breaked");
}
catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
Hope this will clear and build some more ideas.
Thanks
Upvotes: 0
Reputation: 4563
My problem has been solved. I have created one method that will set adapter to my listview. i have called that method ater connected to my service :
public void updateListView() {
setListAdapter(adapter);
ListView lv = getListView();
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
int songIndex = (int) id;
// Starting new intent
Intent in = new Intent(getApplicationContext(),
AndroidBuildingMusicPlayerActivity.class);
// Sending songIndex to PlayerActivity
in.putExtra("songIndex", songIndex);
in.putExtra("listFlag", 0);
startActivity(in);
}
});
}
call this method here :
public void onServiceConnected(ComponentName name, IBinder service) {
// TODO Auto-generated method stub
objservice = ((MyService.LocalBinder) service).getService();
adapter = (ListAdapter) objservice.getSongList();
updateListView(); // here was my problem
}
This is the way you can update listview by using service . Thanx.
Upvotes: 1