How to display images from url in StackView Widget with this - android

I have built a stackview widget for home Screen but i dont know how to load images into it so the user will be able to flip through the images and see different ones.
Here is the code i am using now and this is where the images are suppose to be downloaded and set to the remote View
I dont how to go about doing this and setting it to the remote view to display in the widget.
Here is the code i am using.. i followed the tutorial here on the developers website
http://developer.android.com/resources/samples/StackWidget/index.html
public class StackWidgetService extends RemoteViewsService {
#Override
public RemoteViewsFactory onGetViewFactory(Intent intent) {
return new StackRemoteViewsFactory(this.getApplicationContext(), intent);
}
private static final int mCount = 10;
private List<WidgetItem> mWidgetItems = new ArrayList<WidgetItem>();
private Context mContext;
private int mAppWidgetId;
class StackRemoteViewsFactory implements RemoteViewsService.RemoteViewsFactory{
public StackRemoteViewsFactory(Context context, Intent intent){
mContext = context;
mAppWidgetId = intent.getIntExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, AppWidgetManager.INVALID_APPWIDGET_ID);
}
#Override
public int getCount() {
return mCount;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public RemoteViews getLoadingView() {
// TODO Auto-generated method stub
return null;
}
#Override
public RemoteViews getViewAt(int position) {
RemoteViews rv = new RemoteViews(mContext.getPackageName(), R.layout.widget_item);
rv.setTextViewText(R.id.widget_item, mWidgetItems.get(position).text);
Bundle extras = new Bundle();
extras.putInt(stackWidgetProvider.EXTRA_ITEM, position);
Intent fillnIntent = new Intent();
fillnIntent.putExtras(extras);
rv.setOnClickFillInIntent(R.id.widget_item, fillnIntent);
//Do heavy lifting here, Downloading images from a network or website.
return rv ;
}
#Override
public int getViewTypeCount() {
// TODO Auto-generated method stub
return 0;
}
#Override
public boolean hasStableIds() {
// TODO Auto-generated method stub
return false;
}
#Override
public void onCreate() {
// TODO Auto-generated method stub
}
#Override
public void onDataSetChanged() {
// TODO Auto-generated method stub
}
#Override
public void onDestroy() {
// TODO Auto-generated method stub
}
}
}

Have you tried including the images in the drawable or assets folder, and then loading the images from there? Once you know how to do that, then retrieving images from the web or other network location will be an easier jump.
As far as getting the image from the web, check out: http://asantoso.wordpress.com/2008/03/07/download-and-view-image-from-the-web/

Related

How to get mediaplayer object which is in class extending service to another fragment class

I have an activity in which i call service class through intent and pass uri to the service class ,in service class in onstartcommand() ,i get the uri and create mediaplayer object and play the song using mp.start(). In another fragment class,i use the intent and get the same uri which activity passes to service class ,and generate the mp object ,using this object ,i am able to get the getduration(),but i m not able to getCurrentposition() of the mediaplayer object which is playing in service class
MusicService.java
public class MusicService extends Service implements MediaPlayerControl
{
public MediaPlayer mp=new MediaPlayer();
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
#Override
public int onStartCommand(Intent intent, int flags,int startId) {
// TODO Auto-generated method stub
try{
Bundle extras=intent.getExtras();
if(extras!=null)
{
if(mp.isPlaying())
{
String f=extras.getString("musicsrv");
Uri uri=Uri.parse(f);
mp.stop();
mp.release();
mp=MediaPlayer.create(getApplicationContext(),uri);
mp.start();
}
else
{
String f=extras.getString("musicsrv");
Uri uri=Uri.parse(f);
mp=MediaPlayer.create(getApplicationContext(),uri);
mp.start();
}
}
}
catch(Exception e0)
{}
return super.onStartCommand(intent, flags, startId);
}
#Override
public boolean canPause() {
// TODO Auto-generated method stub
return false;
}}
Fragment.java
public class Fraggy extends Fragment {
ImageView iv;
MusicService m;
TextView endpos,startpos;
SeekBar seekbar;
public MediaPlayer mp1;
private double startTime=0;
private double endTime=0;
private Handler myhandler=new Handler();;
private int forwardTime=5000;
private int backwardTime=5000;
int oneTimeOnly;
int c;
#Override
public void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onViewCreated(view, savedInstanceState);
Toast.makeText(getActivity(), "hello",Toast.LENGTH_LONG).show();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View myview=inflater.inflate(R.layout.activity_mainlayout,container,false);
endpos=(TextView) myview.findViewById(R.id.textView2);
startpos=(TextView) myview.findViewById(R.id.textView1);
seekbar=(SeekBar) myview.findViewById(R.id.seekBar1);
Bundle extras1=getActivity().getIntent().getExtras();
if(extras1!=null)
{
String d=extras1.getString("uri");
Uri uri=Uri.parse(d);
try {
mp1=MediaPlayer.create(getActivity(), uri);
startTime=mp1.getCurrentPosition();// Here i m not able to get the current position
if(oneTimeOnly==0)
{
seekbar.setMax((int) endTime);
oneTimeOnly=1;
}
c=mp1.getDuration();//This works fine
endpos.setText(String.format("%d min,%d sec",TimeUnit.MILLISECONDS.toMinutes((long)c),TimeUnit.MILLISECONDS.toSeconds((long)c)-TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes((long)c))));
startpos.setText(String.format("%d min,%d sec",TimeUnit.MILLISECONDS.toMinutes((long)startTime),TimeUnit.MILLISECONDS.toSeconds((long)startTime)-TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes((long)startTime))));
seekbar.setProgress((int)startTime);
myhandler.postDelayed(upDateSong,100);
} catch (IllegalArgumentException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (SecurityException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IllegalStateException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
TextView tv=(TextView) myview.findViewById(R.id.textView3);
Bundle extras=getActivity().getIntent().getExtras();
if(extras!=null)
{
String d=extras.getString("name");
tv.setText(d);
}
}
return myview;
}
private Runnable upDateSong=new Runnable()
{
public void run()
{
startTime=mp1.getCurrentPosition();
startpos.setText(String.format("%d min,%d sec",TimeUnit.MILLISECONDS.toMinutes((long)startTime),TimeUnit.MILLISECONDS.toSeconds((long)startTime)-TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes((long)startTime))));
seekbar.setProgress((int)startTime);
myhandler.postDelayed(upDateSong,100);
}
}};
You need to get the same object what the service is now having,
Look for the binding the service to the activity,
here,
You can use the same object to both the place after binding the activity to the service.
And then you will be able to perform all the controls.

Android Service - Three different song is playing for one image

Hi I am creating a application for kids, It shows a Alphabets(Images) from A to Z in GridView. If u click S it will open the S in separate activity where you can swipe S to T,V,U...etc.. or You can swipe back to R,Q,P... etc.. And it has to play the song for S if u open S(For eg, S for Something). I achieved this using ViewPager.
What my problem is if I click S its playing the song for all R,S,T instead of playing a single track.
I don't know How to Fix it???
MainActivity
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
GridView gridView = (GridView) findViewById(R.id.grid_view);
// Instance of ImageAdapter Class
gridView.setAdapter(new ImageAdapter(this));
/**
* On Click event for Single Gridview Item
* */
gridView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View v,
int position, long id) {
// Sending image id to FullScreenActivity
Intent i = new Intent(getApplicationContext(), IndividualAlphabet.class);
// passing array index
i.putExtra("id", position);
startActivity(i);
}
});
}
#Override
protected void onRestart() {
// TODO Auto-generated method stub
super.onRestart();
startService(new Intent(MainActivity.this,MediaPlayerService.class));
}
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
startService(new Intent(MainActivity.this,MediaPlayerService.class));
}
}
Service (This is for Song)
public class MediaPlayerService extends Service{
MediaPlayer myMediaPlayer;
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
#Override
public void onCreate() {
super.onCreate();
Toast.makeText(this,"Service created ...", Toast.LENGTH_LONG).show();
myMediaPlayer=MediaPlayer.create(getApplicationContext(),R.raw.alphabets);
myMediaPlayer.setLooping(false);
}
#Override
public void onStart(Intent intent, int startId) {
// TODO Auto-generated method stub
super.onStart(intent, startId);
myMediaPlayer.start();
}
#Override
public boolean onUnbind(Intent intent) {
// TODO Auto-generated method stub
return super.onUnbind(intent);
}
public void onDestroy() {
super.onDestroy();
Toast.makeText(this, "Service destroyed ...", Toast.LENGTH_LONG).show();
myMediaPlayer.stop();
}
}
For Individual Activity
public class IndividualAlphabet extends Activity {
private String[] alphabets;
public static int[] mRaw = {
R.raw.a,R.raw.b,R.raw.c,R.raw.d,R.raw.e,R.raw.f,R.raw.g,R.raw.h,R.raw.i,R.raw.j,
R.raw.k,R.raw.l,R.raw.m,R.raw.n,R.raw.o,R.raw.p,R.raw.q,R.raw.r,R.raw.s,R.raw.t,
R.raw.u,R.raw.v,R.raw.w,R.raw.x,R.raw.y,R.raw.z
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_individual_alphabet);
// get intent data
Intent i = getIntent();
// Selected image id
int position = i.getExtras().getInt("id");
SwipeImageAdapter adapter = new SwipeImageAdapter(this);
ViewPager myPager = (ViewPager) findViewById(R.id.pager);
myPager.setAdapter(adapter);
myPager.setCurrentItem(position);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.individual_alphabet, 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 void playSong() {
startService(new Intent(IndividualAlphabet.this,MediaPlayerService.class));
}
public void stopSong() {
stopService(new Intent(IndividualAlphabet.this,MediaPlayerService.class));
}
#Override
public void onBackPressed() {
// TODO Auto-generated method stub
super.onBackPressed();
stopSong();
}
#Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
stopService(new Intent(IndividualAlphabet.this,MediaPlayerService.class));
}
#Override
public void finish() {
// TODO Auto-generated method stub
super.finish();
stopService(new Intent(IndividualAlphabet.this,MediaPlayerService.class));
}
}
And for Swipe Adapter
public class SwipeImageAdapter extends PagerAdapter{
Activity activity;
Context context;
public static int[] mThumbIds = {
R.drawable.a, R.drawable.b,
R.drawable.c, R.drawable.d,
R.drawable.e, R.drawable.f,
R.drawable.g, R.drawable.h,
R.drawable.i, R.drawable.j,
R.drawable.k, R.drawable.l,
R.drawable.m, R.drawable.n,
R.drawable.o,R.drawable.p,
R.drawable.q,R.drawable.r,
R.drawable.s,R.drawable.t,
R.drawable.u,R.drawable.v,
R.drawable.w,R.drawable.x,
R.drawable.y,R.drawable.z
};
public static int[] mRaw = {
R.raw.a,R.raw.b,
R.raw.c,R.raw.d,
R.raw.e,R.raw.f,
R.raw.g,R.raw.h,
R.raw.i,R.raw.j,
R.raw.k,R.raw.l,
R.raw.m,R.raw.n,
R.raw.o,R.raw.p,
R.raw.q,R.raw.r,
R.raw.s,R.raw.t,
R.raw.u,R.raw.v,
R.raw.w,R.raw.x,
R.raw.y,R.raw.z
};
public SwipeImageAdapter(Activity act) {
this.activity = act;
this.context=act.getBaseContext();
}
public int getCount() {
return mThumbIds.length;
}
#SuppressWarnings("deprecation")
public Object instantiateItem(View collection, int position) {
ImageView view = new ImageView(activity);
view.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT,
LayoutParams.FILL_PARENT));
view.setScaleType(ScaleType.FIT_CENTER);
view.setImageResource(mThumbIds[position]);
view.setPadding(10, 10, 10, 10);
((ViewPager) collection).addView(view, 0);
MediaPlayer mp5 = MediaPlayer.create(activity.getBaseContext(),mRaw[position]);
mp5.start();
return view;
}
#Override
public void destroyItem(View arg0, int arg1, Object arg2) {
((ViewPager) arg0).removeView((View) arg2);
}
#Override
public boolean isViewFromObject(View arg0, Object arg1) {
return arg0 == ((View) arg1);
}
#Override
public Parcelable saveState() {
return null;
}
}
Someone help me to fix this app...

AsyncTaskLoader is not working properly on fragment

I am trying to implement an AsyncTaskLoader running in a fragment and i don't know exactly the reason why onLoadFinished never is called. I am not sure if the context that i pass is the proper one.
This is the basic and custom AsyncTaskLoader:
public static class CustomAsyncLoader extends AsyncTaskLoader<String>
{
public CustomAsyncLoader(Context context) {
super(context);
// do some initializations here
}
#Override
protected void onForceLoad() {
// TODO Auto-generated method stub
super.onForceLoad();
}
#Override
public void deliverResult(String apps) {
}
#Override
protected void onStopLoading() {
// Attempts to cancel the current load task if possible
cancelLoad();
}
#Override
public void onCanceled(String apps) {
super.onCanceled(apps);
}
#Override
public String loadInBackground() {
String result = "";
// ...
// do long running tasks here
// ...
return result;
}
}
Here i will show you the 3 methods overwritted:
#Override
public Loader<String> onCreateLoader(int arg0, Bundle arg1) {
// TODO Auto-generated method stub
return new CustomAsyncLoader(root.getContext());
}
#Override
public void onLoadFinished(Loader<String> arg0, String arg1) {
// TODO Auto-generated method stub
Toast.makeText(mContext, "onLoadFinish", Toast.LENGTH_LONG).show();
}
#Override
public void onLoaderReset(Loader<String> arg0) {
// TODO Auto-generated method stub
}
In the method onResume of my fragment i am calling to init the loader:
getLoaderManager().initLoader(0, null, this).forceLoad();
and the last detail to comment is how the fragment implemented the loader callback:
public class FragmentName extends CustomFragment implements LoaderManager.LoaderCallbacks<String>
Let see if anybody could help me about how implement it. Thanks in advance.
You must call super.deliverResult(apps) in deliverResult method. Otherwise super class of your CustomAsyncLoader won't take care of delivering result to registered listener.

using gridview inside a runnable gives error

Can somebody explain how to use the GridView inside a Runnable.
Handler starthandler = new Handler();
Runnable startrun= new Runnable(){
#Override
public void run() {
G1=(GridView)findViewById(R.id.balloongrid);
G1.setAdapter(new BalloonImageAdaper(this));
}
};
The above code gives the following error:
The constructor Cacrballoonclass.BalloonImageAdaper(new Runnable(){}) is undefined
public class BalloonImageAdaper extends BaseAdapter{ // create a class by name
imageadapter so as to fill the gridview with data
private Context ballooncontext;
public BalloonImageAdaper (Context c) {
ballooncontext = c;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return balloonthumbs.length;
}
#Override
public Object getItem(int arg0) {
// TODO Auto-generated method stub
return null;
}
#Override
public long getItemId(int arg0) {
// TODO Auto-generated method stub
return 0;
}
#Override
public View getView(int arg0, View arg1, ViewGroup arg2) {
// TODO Auto-generated method stub
ImageView balloonimageview;
if(arg1==null){
balloonimageview = new ImageView(ballooncontext);
balloonimageview.setLayoutParams(new GridView.LayoutParams(75,75));
balloonimageview.setScaleType(ImageView.ScaleType.CENTER_CROP);
balloonimageview.setPadding(7, 7, 7, 7);
}else {
balloonimageview = (ImageView)arg1;
}
// lets inflate balloon randomly
int rballoon = new Random().nextInt(ballooninstruct.length);
balloonimageview.setImageResource(balloonthumbs[rballoon]);
balloonimageview.setTag(balloonthumbs[rballoon]);
return balloonimageview;
}
}// class imageAdapter extends baseadapter
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onResume();
finish();
}
}//class ends cacrballoonclasss
Replace
new BalloonImageAdaper(this)
with
new BalloonImageAdaper(mContext) // mContext: reference to any Context (Activity or whatever)
(If that's inside an Activity you can use NameOfActivity.this.)
The this inside your Runnable is referring to your Runnable and not, like I assume you want it to reference to, your Activity.

how to send data in service based android app

I want to send data from one application A to other application B using AIDL file. My appl A is like below,
public class LibValue {
public static native int intFromJNI(int n);
static {
System.loadLibrary("hello");
System.out.println("LibValue : Loading library");
}
I am getting value from JNI file to above class. The data from above class to send another app B using AIDL service is like below.
IEventService.aidl
interface IEventService {
int intFromJNI(in int n);
}
for this I written IEventImpl.java class
public class IEventImpl extends IEventService.Stub{
int result;
#Override
public int intFromJNI(int n) throws RemoteException {
// TODO Auto-generated method stub
System.out.println("IEventImpl"+LibValue.intFromJNI(n));
return LibValue.intFromJNI(n);
}
}
To access above class I writtn service class like below
public class EventService extends Service {
public IEventImpl iservice;
#Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
Log.i("EventService", "indside onBind");
return this.iservice;
}
#Override
public void onCreate() {
// TODO Auto-generated method stub
super.onCreate();
this.iservice = new IEventImpl();
Log.i("EventService", "indside OncREATE");
}
#Override
public boolean onUnbind(Intent intent) {
// TODO Auto-generated method stub
return super.onUnbind(intent);
}
#Override
public void onDestroy() {
// TODO Auto-generated method stub
this.iservice = null;
super.onDestroy();
}
All above classes are server side. The below class is Client(app) class to access data.
public class EventClient extends Activity implements OnClickListener, ServiceConnection{
public IEventService myService;
private Button button;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_event_client);
button = (Button)findViewById(R.id.button1);
this.button.setOnClickListener(this);
}
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
if (!super.bindService(new Intent(IEventService.class.getName()),
this, BIND_AUTO_CREATE)) {
Log.w("EventClient", "Failed to bind to service");
System.out.println("inside on resume");
}
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
super.unbindService(this);
}
#Override
public void onServiceConnected(ComponentName name, IBinder service) {
// TODO Auto-generated method stub
this.myService = IEventService.Stub.asInterface(service);
Log.i("EventClient", "ServiceConnected");
}
#Override
public void onServiceDisconnected(ComponentName name) {
// TODO Auto-generated method stub
Log.d("EventClient", "onServiceDisconnected()'ed to " + name);
// our IFibonacciService service is no longer connected
this.myService = null;
}
I am trying to access data from service class but not able to find out the way. can anybody tell how to access data from service to client application ?
Thanks

Categories

Resources