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.
Related
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...
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.
I have searched other posts but haven't found any describing my particular problem. Many of them refer to calling publishProgress from doInBackground. I am calling publishProgress from onPreExecute expecting a dialog to be displayed to inform a user that data is being fetched. The AsyncTask is being launched from the user making a selection from a Spinner. Rather than the dialog being displayed, the UI freezes until the AsyncTask completes. I have added in log messages and it appears that although publishProgress is called in onPreExecute, onProgressUpdate is not being executed until after doInBackground is completed.
The activity:
public class MainActivity extends Activity implements OnItemSelectedListener{
private Spinner spinner;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#Override
protected void onResume() {
super.onResume();
spinner = (Spinner)findViewById(R.id.spinner);
SpinnerAdapter adapter = new CustomSpinnerAdapter<String>(this, new String[]{"one", "two", "three"});
spinner.setAdapter(adapter);
spinner.setOnItemSelectedListener(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;
}
#SuppressLint("NewApi")
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
try{
FetchDataTask fetchDataTask = new FetchDataTask();
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB){
fetchDataTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, "data");
} else{
fetchDataTask.execute("data");
}
fetchDataTask.await();
} catch (InterruptedException e){
e.printStackTrace();
}
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
public class FetchDataTask extends AsyncTask<String, Integer, Boolean> {
private final String TAG = FetchDataTask.class.getSimpleName();
private final Integer FETCHING_DATA = 1;
CountDownLatch countDownLatch = new CountDownLatch(1);
ProgressDialog dialog;
#Override
protected void onPostExecute(Boolean result) {
super.onPostExecute(result);
Log.d(TAG,"Exiting onPostExecute");
dialog.dismiss();
}
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
publishProgress(FETCHING_DATA);
Log.d(TAG, "Exiting onPreExecute");
}
#Override
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
dialog = ProgressDialog.show(MainActivity.this, "Fetching", "Data");
Log.d(TAG, "Exiting onProgressUpdate");
}
#Override
protected Boolean doInBackground(String... arg0) {
/*
* Fetching data here
*/
Log.d(TAG, "Exiting doInBackground");
countDownLatch.countDown();
return true;
}
public void await() throws InterruptedException{
countDownLatch.await();
}
}
}
The Spinner:
public class CustomSpinnerAdapter<T> implements SpinnerAdapter {
Context context;
T[] values;
public CustomSpinnerAdapter(Context context, T[] values){
this.context = context;
this.values = values;
for(T value: this.values){
Log.d("Spinner", value.toString());
}
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return values.length;
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return values[position];
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public int getItemViewType(int position) {
// TODO Auto-generated method stub
return android.R.layout.simple_spinner_dropdown_item;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
TextView v = new TextView(context);
v.setTextColor(Color.BLACK);
v.setText(values[position].toString());
return v;
}
#Override
public int getViewTypeCount() {
// TODO Auto-generated method stub
return 1;
}
#Override
public boolean hasStableIds() {
// TODO Auto-generated method stub
return false;
}
#Override
public boolean isEmpty() {
// TODO Auto-generated method stub
return false;
}
#Override
public void registerDataSetObserver(DataSetObserver observer) {
// TODO Auto-generated method stub
}
#Override
public void unregisterDataSetObserver(DataSetObserver observer) {
// TODO Auto-generated method stub
}
#Override
public View getDropDownView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
return this.getView(position, convertView, parent);
}
}
The view:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<Spinner
android:id="#+id/spinner"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
</RelativeLayout>
I am think this might have something to do with executing the AsyncTask from the Spinner selection because simply executing it in the Activity without connecting it to the Spinner does not have this problem. Any assistance would be appreciated.
You dont keep on showing dialog on progress update, instead you show it onPreExecute update it onProgressUpdate and hide it onPostExecute or cancel. and in your case you dont need the publish progress since progressBar is indefinite
#Override
protected void onPreExecute()
{
super.onPreExecute();
Log.d(TAG, "Exiting onPreExecute");
dialog = ProgressDialog.show(MainActivity.this, "Fetching", "Data");
}
#Override
protected Boolean doInBackground(String... arg0)
{
Log.d(TAG, "Exiting doInBackground");
countDownLatch.countDown();
//publishProgress(x);
return true;
}
public void await() throws InterruptedException
{
countDownLatch.await();
}
#Override
protected void onProgressUpdate(Integer... values)
{
super.onProgressUpdate(values);
Log.d(TAG, "Exiting onProgressUpdate");
// update progressbar value
// ex progresssBar.setProgress(values[0]);
}
#Override
protected void onPostExecute(Boolean result)
{
super.onPostExecute(result);
Log.d(TAG,"Exiting onPostExecute");
dialog.dismiss();
}
I have used android view pager to display images and text now what i want is that if a user is not changing the images then it should start to change the images automatically after a few seconds and when the user again starts using his finger then the images should not change automatically?
I tried to use the handler to create a delay but it did not worked for me?
Please help anyone
public class SimpleImageViewerActivity extends Activity implements ViewPager.OnPageChangeListener{
private Handler handler;
ViewPager myPager;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.imageslideshow);
MyPagerAdapter adapter = new MyPagerAdapter();
myPager = (ViewPager) findViewById(R.id.slideShowPager);
myPager.setAdapter(adapter);
myPager.setCurrentItem(0);
handler = new Handler();
myPager.setOnPageChangeListener(this);
}
private class MyPagerAdapter extends PagerAdapter {
public int getCount() {
return 5;
}
public Object instantiateItem(View collection, int position) {
LayoutInflater inflater = (LayoutInflater) collection.getContext()
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
int resId = 0;
switch (position) {
case 0:
resId = R.layout.farleft;
break;
case 1:
resId = R.layout.left;
break;
case 2:
resId = R.layout.middle;
break;
case 3:
resId = R.layout.right;
break;
case 4:
resId = R.layout.farright;
break;
}
View view = inflater.inflate(resId, null);
((ViewPager) collection).addView(view, 0);
return view;
}
#Override
public void destroyItem(View arg0, int arg1, Object arg2) {
((ViewPager) arg0).removeView((View) arg2);
}
#Override
public void finishUpdate(View arg0) {
// TODO Auto-generated method stub
}
#Override
public boolean isViewFromObject(View arg0, Object arg1) {
return arg0 == ((View) arg1);
}
#Override
public void restoreState(Parcelable arg0, ClassLoader arg1) {
// TODO Auto-generated method stub
}
#Override
public Parcelable saveState() {
// TODO Auto-generated method stub
return null;
}
#Override
public void startUpdate(View arg0) {
// TODO Auto-generated method stub
}
}
#Override
public void onPageScrollStateChanged(int arg0) {
// TODO Auto-generated method stub
}
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
// TODO Auto-generated method stub
updateUI(arg2);
}
#Override
public void onPageSelected(int arg0) {
// TODO Auto-generated method stub
//updateUI(arg0);
}
public void onNothingSelected(AdapterView<?> adapterView) {
final int i =0;
adapterView.postDelayed(new Runnable(){
#Override
public void run() {
// TODO Auto-generated method stub
updateUI(i);
}
}, 5000);
Toast.makeText(this, "In nothing selected method",Toast.LENGTH_SHORT).show();
}
private void updateUI(final int fi) {
/* handler.post(new Runnable() {
public void run() {
gallery.setSelection(i);
viewPager.setCurrentItem(i);
//textView.setText("Photo #" + i);
}
});*/
handler.postDelayed(new Runnable() {
public void run() {
int i=fi;
int j = i;
myPager.setCurrentItem(j++);
System.out.println("Hello");
}
},1000);
}
}
Use javautil timer and set one up and at the end of timer you can use
class UpdateTimeTask extends TimerTask {
public void run() {
//Code for the viewPager to change view
}
}
// Code to schedule the timer
timer = new Timer();
timer.schedule(new UpdateTimeTask(), 100, 200);
Hope this helps, use the android docs for exact API calls
<ViewPager>.setCurrentitem(i++%<MaxViews>)
As far as UI update is concerned you can do it via handler, So call a handler inside timertask class, you can do something like this :
Timer timer=null;
static int time_tomove = 0;
class UpdateTimeTask extends TimerTask {
public void run() {
//Code for the viewPager to change view
System.out.println("The value of the time_tomove ");
time_tomove++;
Message msg = handler_timer.obtainMessage();
Bundle b = new Bundle();
b.putInt("time", time_tomove);
msg.setData(b);
handler_timer.sendMessage(msg);
}
}
public static Handler handler_timer = new Handler(){
#Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
magazineHolder.setCurrentItem(time_tomove);
}
};
After doing this you can call the below two lines inside either your onresume or oncreate() method
timer = new Timer();
timer.schedule(new UpdateTimeTask(), 100, 2000);
Kotlin way
This is from a Fragment context, remove requireActivity() if you are in an Activity
private var timer: Timer? = null
private var page = 0
private var maxPages = 4
// Use this method to setup your viewpager in your onCreate() or onActivityCreated() methods
fun setupViewPager(){
viewPager2.adapter = MyAdapter()
viewPager2.isUserInputEnabled = false
pageSwitcher(5)
}
fun pageSwitcher(seconds: Int) {
timer = Timer()
timer!!.scheduleAtFixedRate(RemindTask(), 0, seconds * 1000.toLong())
}
class RemindTask:TimerTask(){
override fun run() {
requireActivity().runOnUiThread {
if(page == maxPages){
page = 0
}else{
viewPager2.setCurrentItem(page++,true)
}
}
}
}
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/