Android view pager change pages automatically after a few seconds - android

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)
}
}
}
}

Related

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...

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 can I make a view invisible after 3 seconds?

I am using a handler in the adapter file to make the view invisible after 3 sconds, but it does not update the view. Where is my problem and how can I fix it?
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
try {
Bundle bun = getIntent().getExtras();
if (!bun.isEmpty()) {
selecte_pos = bun.getInt("pos");
}
} catch (Exception e) {
}
Display display = getWindowManager().getDefaultDisplay();
width = display.getWidth();
height = display.getHeight();
System.out.println("full image activity");
ar = getIntent().getStringArrayListExtra("PhotoList");
System.out.println("full list size: " + ar.size());
imageLoader = new ImageLoader(this);
setContentView(R.layout.full_image_view_layout);
mPager = (ViewPager) findViewById(R.id.full_image_view_pager);
adapter = new MyPagerAdapter();
mPager.setAdapter(adapter);
mPager.setCurrentItem(selecte_pos);
}
class MyPagerAdapter extends PagerAdapter {
public int getCount() {
return ar.size();
}
Handler pagerHandler=new Handler(){
public void handleMessage(Message msg){
if(msg.what==1){
//if (istimer == true) {
System.out.println("page handler");
System.out.println("");
Toast.makeText(getApplicationContext(), "hi", 1).show();
shareLayout.setVisibility(View.INVISIBLE);
adapter.notifyDataSetChanged();
//}
}
}
};
#Override
public Object instantiateItem(ViewGroup container, final int position) {
System.out.println("view page clciking");
LayoutInflater layoutInflater = (LayoutInflater) container
.getContext().getSystemService(LAYOUT_INFLATER_SERVICE);
View v = layoutInflater.inflate(R.layout.imageview, null);
try {
final ImageView imageView = (ImageView) v
.findViewById(R.id.full_pager_adapter_iv);
shareLayout = (LinearLayout) v.findViewById(R.id.buttonslayout);
shareLayout.setVisibility(View.VISIBLE);
imageLoader.DisplayImage(ar.get(position), imageView);
if (first) {
System.out.println("fisr condition");
first = false;
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
pagerHandler.sendEmptyMessage(1);
//adapter.notifyDataSetChanged();
}
}, SPLASH_DISPLAY_LENGHT);
}
/**if(istimer1== true)
{
System.out.println("else part");
istimer1 = false;
shareLayout.setVisibility(View.VISIBLE);
adapter.notifyDataSetChanged();
}**/
imageView.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
System.out.println("img clicking");
if (shareLayout.getVisibility() == View.INVISIBLE) {
System.out.println("invisible");
istimer = false;
istimer1 = true;
shareLayout.setVisibility(View.VISIBLE);
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
//istimer = true;
//istimer1 = false;
pagerHandler.sendEmptyMessage(1);
//adapter.notifyDataSetChanged();
}
}, SPLASH_DISPLAY_LENGHT);
adapter.notifyDataSetChanged();
}
if (shareLayout.getVisibility() == View.VISIBLE) {
System.out.println("visible");
istimer = true;
istimer1 = false;
shareLayout.setVisibility(View.INVISIBLE);
adapter.notifyDataSetChanged();
}
}
});
LinearLayout btnshare = (LinearLayout) v
.findViewById(R.id.btnshare);
btnshare.setTag(position);
btnshare.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
int pos = (Integer) v.getTag();
String s = ar.get(pos);
// String s = bean.getImagePath();
File file = new File(s);
Intent sendMailIntent = new Intent(Intent.ACTION_SEND);
sendMailIntent.setType("image/jpeg");
sendMailIntent.putExtra(
android.content.Intent.EXTRA_TEXT, "");
sendMailIntent.putExtra(Intent.EXTRA_STREAM,
Uri.fromFile(file));
/* sendMailIntent.setType("image/*"); */
startActivity(Intent.createChooser(sendMailIntent, ""));
}
});
} catch (Exception e) {
}
((ViewPager) container).addView(v, 0);
return v;
}
#Override
public void destroyItem(ViewGroup collection, int position, Object view) {
((ViewPager) collection).removeView((View) view);
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view == object;
}
#Override
public int getItemPosition(Object object) {
// TODO Auto-generated method stub
return POSITION_NONE;
}
}
#Override
public void onBackPressed() {
// TODO Auto-generated method stub
super.onBackPressed();
finish();
}
private Handler mTimerHandler = new Handler();
private void stopTimer() {
if (mTimer1 != null) {
mTimer1.cancel();
mTimer1.purge();
}
}
private void startTimer() {
mTimer1 = new Timer();
mTt1 = new TimerTask() {
public void run() {
mTimerHandler.post(new Runnable() {
public void run() {
System.out.println("timesatrs");
// TODO
if (shareLayout.getVisibility() == View.VISIBLE) {
System.out.println("time completed");
shareLayout.setVisibility(View.INVISIBLE);
}
}
});
}
};
mTimer1.schedule(mTt1, 6000);
}
}
getWindow().getDecorView().getRootView().postDelayed(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
yourView.setVisibility(View.VISIBLE);
}
}, 5000);
// Call this when u initalise view in onCreate
You don't need to create a new handler every time, when you need to send message to handler which you already created. You can send delayed message like this pagerHandler.sendEmptyMessageDelayed(1, SPLASH_DISPLAY_LENGHT);
And are you sure, you are trying to update current shareLayout ?
Add the below coding in your class file.
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
view.setVisibility(View.GONE); }
}, 3000);
This will helps you in achieving what you want.

listview scolling in android is slow

i have a listview with a heavy inflation of three different custom rows .From these rows i have to collect data and fill the database and finally get that data also .Now the problem is that the number of rows created depends upon user it may b as high as 100. And my list becomes very slow in scrolling .Now what i want to know is will it be helpful to put all of my list functioning in Async task i mean its creation as well as its execution. below is my code snippet.
private class Async extends AsyncTask<String, Integer, String>{
#Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
runOnUiThread(new Runnable() {
public void run() {
lv.setAdapter(new EfficientAdapterAB(Measure_New.this));
new EfficientAdapterAB(Measure_New.this).notifyDataSetChanged();
//stuff that updates ui
}
});
return null;
}
}
private class EfficientAdapterAB extends BaseAdapter {
private LayoutInflater mInflater;
View[] view;
ViewHolderAB holderAB;
/* RadioButton[] ob=new RadioButton[n];
RadioButton[] ra=new RadioButton[n];*/
AndroidOpenDbHelper androidOpenDbHelperObj = new AndroidOpenDbHelper(Measure_New.this);
SQLiteDatabase sqliteDatabase = androidOpenDbHelperObj.getReadableDatabase();
String q="SELECT * FROM ab_measurement WHERE job_id=" +"\""+Settings.jobid +"\"";
Cursor cursor = sqliteDatabase.rawQuery(q,null);
public EfficientAdapterAB(Context context) {
mInflater = LayoutInflater.from(context);
}
public int getCount() {
System.out.println("in getcount value of n is "+n);
view = new View[n+2];
return n+2;
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(final int position, View convertView, ViewGroup parent) {
final RadioButton[] ob=new RadioButton[n];
final RadioButton[] ra=new RadioButton[n];
holderAB = new ViewHolderAB();
final EditText edit_a_ft,edit_a_inch,edit_b_ft,edit_b_inch,edit_ab_a_ft,edit_ab_a_inch,edit_ab_b_ft,edit_ab_b_inch;
if (view[position] == null) {
if(position==0){
convertView = mInflater.inflate(R.layout.measure_upper_bar, null);
txt_ft_mtr=(TextView)convertView.findViewById(R.id.textView_ft_mtr);
txt_inch_cm=(TextView)convertView.findViewById(R.id.textView_inch_cm);
if(Settings.metric_count==1){
txt_ft_mtr.setText(""+"Meter");
txt_inch_cm.setText(""+"Centimeter");
}
user_input= (EditText) convertView.findViewById(R.id.Num_edittxt_measure_new);
gettingUserInput();
new EfficientAdapterAB(Measure_New.this).notifyDataSetChanged();
System.out.println("after gettinguserInput value of n is "+n);
feet=(EditText)convertView.findViewById(R.id.Feet_edittxt);
inch =(EditText)convertView.findViewById(R.id.Inches_Edittxt);
feet.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
// TODO Auto-generated method stub
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
// TODO Auto-generated method stub
}
#Override
public void afterTextChanged(Editable s) {
// TODO Auto-generated method stub
try{
val_feet_baseline=Integer.parseInt(feet.getText().toString());
}catch (Exception e) {
// TODO: handle exception
}
}
});
inch.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
// TODO Auto-generated method stub
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
// TODO Auto-generated method stub
}
#Override
public void afterTextChanged(Editable s) {
// TODO Auto-generated method stub
try{
val_inch_baseline=Integer.parseInt(inch.getText().toString());
if(val_inch_baseline>=ft_mtr){
inch_greater=true;
ft_baseline=val_feet_baseline+(val_inch_baseline/ft_mtr);
val_inch_baseline=val_inch_baseline%ft_mtr;
feet.setText(""+ft_baseline);
inch.setText(""+val_inch_baseline);
System.out.println("yes its working values of feet and inch is "+"feet"+ft_baseline+"inch"+val_inch_baseline);
}
}
catch (Exception e) {
// TODO: handle exception
}
}
});
if(inch_greater==true){
baseline_length=String.valueOf(ft_baseline).concat(".").concat(String.valueOf(val_inch_baseline));
feet.setText(""+ft_baseline);
System.out.println("in the if part");
inch_greater=false;
}
else{
baseline_length=String.valueOf(val_feet_baseline).concat(".").concat(String.valueOf(val_inch_baseline));
System.out.println("in the else part");
feet.setText(""+val_feet_baseline);
}
inch.setText(""+val_inch_baseline);
if(val_feet_baseline==0){
feet.setText(""+"");
}
if(val_inch_baseline==0){
inch.setText(""+"");
}
user_input.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
user_input.setText("");
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.showSoftInput(user_input, InputMethodManager.SHOW_IMPLICIT);
((InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE)).toggleSoftInput(InputMethodManager.SHOW_FORCED, InputMethodManager.HIDE_IMPLICIT_ONLY);
}
});
rb_A = (RadioButton)convertView.findViewById(R.id.radio_A);
rb_B = (RadioButton)convertView.findViewById(R.id.radio_B);
rb_AB = (RadioButton)convertView.findViewById(R.id.radio_A_B);
rb_A.setOnClickListener(Measure_New.this);
rb_B.setOnClickListener(Measure_New.this);
rb_AB.setOnClickListener(Measure_New.this);
view[position] = convertView;
}
else if(position==n+1){
convertView=mInflater.inflate( R.layout.details_continue_btn, null);
convertView.findViewById(R.id.btn_Continue).setOnClickListener(Measure_New.this);
convertView.findViewById(R.id.btn_exit_restart).setOnClickListener(Measure_New.this);
view[position] = convertView;
}
else{
if(optn_checkd==1){
setDatabase();
convertView = mInflater.inflate(R.layout.a_xml, null);
txt_A_ft_mtr=(TextView)convertView.findViewById(R.id.textView_A_ft_mtr);
txt_A_inch_cm=(TextView)convertView.findViewById(R.id.TextView_A_inch_cm);
if(Settings.metric_count ==1){
txt_A_ft_mtr.setText(""+"A(m.)");
txt_A_inch_cm.setText(""+"A(cm.)");
}
holderAB.text = (TextView) convertView.findViewById(R.id.num_txt);
holderAB.text.setText(""+(position));
edit_a_ft=(EditText) convertView.findViewById(R.id.editText_A_ft);
edit_a_inch=(EditText) convertView.findViewById(R.id.editText_A_inch);
if(position<=n){
textChangeListenerForFeet(edit_a_ft,position,al_edit_A_ft);
textChangeListenerForInch(edit_a_inch,edit_a_ft,position,al_edit_A_inch);
}
System.out.println("in else value of position before crashing is"+position+" "+(position-1)+" "+ n);
if(position<=n){
ob[position-1]=(RadioButton)convertView.findViewById(R.id.radio_Obstruction_a);
ob[position-1].setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if(radio__ob_flag[position-1]==true){
ob[position-1].setButtonDrawable(R.drawable.redioon);
obstruction/*[position-1]*/="Y";
radio__ob_flag[position-1]=false;
}
else{
ob[position-1].setButtonDrawable(R.drawable.rediooff);
radio__ob_flag[position-1]=true;
obstruction/*[position-1]*/="N";
}
try{
al_ob_a.add(position-1,obstruction/*[position-1]*/);
al_ob_a.remove(position);
}catch(Exception e){
}
System.out.println("wooooow here i am ob"+al_ob_a);
}
});
}
if(position<=n){
ra[position-1]=(RadioButton)convertView.findViewById(R.id.radio_Raisedwall_a);
ra[position-1].setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if(radio__ra_flag[position-1]==true){
ra[position-1].setButtonDrawable(R.drawable.redioon);
radio__ra_flag[position-1]=false;
obstruction/*[position-1]*/="Y";
}
else{
ra[position-1].setButtonDrawable(R.drawable.rediooff);
radio__ra_flag[position-1]=true;
obstruction/*[position-1]*/="N";
}
try{
al_ra_a.add(position-1,obstruction/*[position-1]*/);
al_ra_a.remove(position);
}catch(Exception e){
}
System.out.println("wooooow here i am ra "+al_ra_a);
}
});
}
if(getttingFromDbForMeasure()==true){
if(position<=n){
retainingInput(al_edit_A_ft,position,edit_a_ft);
retainingInput(al_edit_A_inch,position,edit_a_inch);
retainingInputForRadio( al_ob_a,position,ob);
retainingInputForRadio(al_ra_a ,position,ra);
}
}
}
First of all, You need to utilize convertView in Yours adapter getView(). This would let You use view holder. Currently You only assign values to viewHolder, but not set it as tag or retrieve values back (to avoid redundant findViewById calls).
Checkout this Google I/O video from Romain Guy and, also checkout the code from that session slides.

How to show seekbar along with the custom mediaplayer

i have build a custom media player and i want to show the seekbar also.
The seekbar is showing for now but is not functional i.e. it is not progressing when the song is played. Let me know where am i wrong . Following is the code
public class myPlayer extends Activity implements Runnable,SeekBar.OnSeekBarChangeListener {
MediaPlayer mPlayer;
Button play,stop;
SeekBar seekbar;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
seekbar = (SeekBar)findViewById(R.id.seekbar);
mPlayer = MediaPlayer.create(this,R.raw.sajnave);
play=(Button)findViewById(R.id.play);
stop=(Button)findViewById(R.id.stop);
Toast.makeText(myPlayer.this, ""+mPlayer.getDuration(), Toast.LENGTH_SHORT).show();
play.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
mPlayer.start();
}
});
stop.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Toast.makeText(myPlayer.this, ""+mPlayer.getCurrentPosition(), Toast.LENGTH_SHORT).show();
mPlayer.stop();
}
});
}
#Override
public void run() {
// TODO Auto-generated method stub
int currentPosition = 0;
int total = mPlayer.getDuration();
seekbar.setMax(total);
while (mPlayer != null && currentPosition < total) {
try {
Thread.sleep(1000);
currentPosition = mPlayer.getCurrentPosition();
} catch (InterruptedException e) {
return;
} catch (Exception e) {
return;
}
seekbar.setProgress(currentPosition);
}
}
#Override
public void onProgressChanged(SeekBar arg0, int arg1, boolean arg2) {
// TODO Auto-generated method stub
mPlayer.seekTo(arg1);
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
}
Call updatePosition() method after mediplayer starts..It works for me.
private final Handler handler = new Handler();
private final Runnable updatePositionRunnable = new Runnable() {
public void run() {
updatePosition();
}
};
private void updatePosition() {
handler.removeCallbacks(updatePositionRunnable);
if (player != null) seekbar.setProgress(player.getCurrentPosition());
handler.postDelaye(updatePositionRunnable, 500);
}
#Override
public void onProgressChanged(SeekBar arg0, int arg1, boolean arg2) {
// TODO Auto-generated method stub
player.seekTo(arg1);
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
SurfaceView mPreview=(SurfaceView)findViewById(R.id.surface);
mPreview.postDelayed(runnable,200);
Runnable runnable = new Runnable() {
#Override
public void run() {
if (mMediaPlayer != null) {
if (isPlaying) {
// converting current position into seconds so dividing by
// 1000
try {
currentPosition = mMediaPlayer.getCurrentPosition();
mVideoProgress
.setProgress((int) ((currentPosition / (float) mMediaPlayer
.getDuration()) * 100f));
} catch (Exception e) {
e.printStackTrace();
}
mPreview.postDelayed(runnable, 150);
}
}
}
};

Categories

Resources