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.
Related
I have a dictionary database that contain more than 300,000 words, using cursoradapter to fill in ListView. When filter one word in ListView, the sotware delays, is there any way to filter word instantly?
This is code of the Main
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
db=new WordDbAdapter(this);
db.openDatabase();
Cursor cursor=db.getAllWord();
adapter=new SimpleCursorAdapter(this, R.layout.listview_item, cursor,new String[] {"word"},new int[] {R.id.title}, 0);
lv=(ListView) findViewById(R.id.listView1);
lv.setAdapter(adapter);
filter=(EditText) findViewById(R.id.editText1);
filter.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence cs, int arg1, int arg2, int arg3) {
// TODO Auto-generated method stub
adapter.getFilter().filter(cs.toString());
}
#Override
public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
int arg3) {
// TODO Auto-generated method stub
}
#Override
public void afterTextChanged(Editable arg0) {
// TODO Auto-generated method stub
}
});
This is code of the Database:
public Cursor getAllWord()
{
Cursor cursor = null;
try {
String sql="select rowid _id,word from anh_viet";
cursor=mdb.rawQuery(sql, null);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
Toast.makeText(mContext, e.getMessage(), Toast.LENGTH_LONG).show();
}
return cursor;
}
public Cursor filterWord(String key)
{
Cursor cursor = null;
try {
String sql="select rowid _id,word from anh_viet where word like '"+key+"%'";
cursor=mdb.rawQuery(sql, null);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
Toast.makeText(mContext, e.getMessage(), Toast.LENGTH_LONG).show();
}
return cursor;
}
Never write a query like this:
String sql="select rowid _id,word from anh_viet where word like '"+key+"%'";
Its insecure (you can have SQL injection) and it requires the db to reparse and optimize the query each time. Instead use a bind variable for the key. That will allow it to cache the search (speeding it up) and prevent any possibility of SQL injection.
I am trying to post message on Facebook, Twitter and Linkedin, but I am getting exception in my log cat i.e "Java.lang.nullPointerException" and "Message not posted" .No Toast is also executing as there are two Toast in MessageListener class "execute() method" one is "message posted" and another one is "message not posted".I have highligted these Toast in my code, I have tried my best but its not working even i have generated new keys also but still getting the same problem.
a
Please help me !!
Looking forward for reply..
Here is my code
public View getView(int position, View convertView, ViewGroup Parent) {
View vi=convertView;
final ViewHolder holder=new ViewHolder();
if (vi==null) {
vi= inflater.inflate(R.layout.raw_items, null);
Log.e("adapter","adaper set");
final LinearLayout shareBar=(LinearLayout) vi.findViewById(R.id.LinearLayoutshareBar);
adapter = new SocialAuthAdapter(new ResponseListener());
adapter.addProvider(Provider.FACEBOOK, R.drawable.facebook_share);
adapter.addProvider(Provider.TWITTER, R.drawable.tweet_button);
adapter.addProvider(Provider.LINKEDIN, R.drawable.linkedin_share);
adapter.enable(shareBar);
}
}
ResponseListener Class
class ResponseListener implements DialogListener
{
String msg;
#Override
public void onError(SocialAuthError e) {
// TODO Auto-generated method stub
Log.d("ShareBar", e.getMessage());
}
#Override
public void onCancel() {
// TODO Auto-generated method stub
Log.d("ShareBar", "Authentication Cancelled");
}
#Override
public void onBack() {
// TODO Auto-generated method stub
}
#Override
public void onComplete(Bundle values) {
// TODO Auto-generated method stub
final Dialog dialog = new Dialog(activity);
dialog.setTitle("Share Message");
dialog.setContentView(R.layout.dialog_view);
final EditText editText = (EditText)dialog.findViewById(R.id.shareText);
Button button = (Button)dialog.findViewById(R.id.updatebutton);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
msg=editText.getText().toString();
adapter.updateStatus(msg,new MessageListener(),true);
dialog.dismiss();
}
});
dialog.show();
}
}
MessageListener Class
private final class MessageListener implements SocialAuthListener<Integer> {
#Override
public void onExecute(String provider, Integer t) {
// TODO Auto-generated method stub
Integer status = t;
if (status.intValue() == 200 || status.intValue() == 201 ||status.intValue() == 204)
**Toast.makeText(activity, "Message posted",Toast.LENGTH_LONG).show();**
else
**Toast.makeText(activity, "Message not posted",Toast.LENGTH_LONG).show();**
Log.e("Execute", "I am onExecute");
}
#Override
public void onError(SocialAuthError e) {
// TODO Auto-generated method stub
Toast.makeText(activity,"i m error",1000).show();
}
}
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();
}
How to create a widget in the same program as the app?As in how to create a widget for an app which does the same functions?
This is the activity file:
public class SmsActivity extends Activity {
Button b1;
EditText a;
String b;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
a=(EditText)findViewById(R.id.e2);
a.addTextChangedListener(new TextWatcher(){
#Override
public void afterTextChanged(Editable s) {
// TODO Auto-generated method stub
b=a.getText().toString();
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count,int after) {
// TODO Auto-generated method stub
}
#Override
public void onTextChanged(CharSequence s, int start, int before,int count) {
// TODO Auto-generated method stub
}
});
b1= (Button) findViewById(R.id.b1);
b1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
try {
Intent sendIntent = new Intent();
sendIntent.setAction(Intent.ACTION_SEND);
sendIntent.putExtra(Intent.EXTRA_TEXT, b);
sendIntent.setType("text/plain");
startActivity(sendIntent);
}
catch (Exception e) {
Toast.makeText(getApplicationContext(),
"SMS failed, please try again later!",
Toast.LENGTH_LONG).show();
e.printStackTrace();
}
}
});
}
}
I don't want updation through widget. I just want the widget to do the exact same what the app does.
You can't do input with a widget, so you can't have EditText fields. Widgets are output only.
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)
}
}
}
}