im now searching for 2 hours for a small error that makes this code doesnt work:
The Activity:
UpdateThread t;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
requestWindowFeature(Window.FEATURE_NO_TITLE);
this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_fullscreen);
}
#Override
protected void onResume() {
t = new UpdateThread(this, this);
t.start();
super.onResume();
}
And the Thread:
public UpdateThread(FullscreenActivity a, Context c) {
this.c = c;
this.a = a;
}
#Override
public void run() {
if(enabled) return;
enabled = true;
while(true) {
a.runOnUiThread(new Runnable() {
#Override
public void run() {
RelativeLayout view = (RelativeLayout) a.findViewById(R.id.view);
view.removeAllViews();
try {
TextView t = new TextView(c);
t.setText("asd");
t.setVisibility(View.VISIBLE);
t.setX(22);
t.setY(123);
t.setScaleX(0.9f);
t.setScaleY(0.9f);
t.setBackgroundColor(Color.YELLOW);
view.addView(t);
} catch(Exception e) {e.printStackTrace();}
Log.d("Finished drawing!"," drawed!");
}
});
}
Layout XML File:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/view"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="${packageName}.${activityClass}" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/hello_world"
android:id="#+id/asd"/>
</RelativeLayout>
This code should add a TextView to the FullscreenActivity, but nothing happens.
Im using Android level 12, all Software up to date, my phone is the SGS3.
Thank you for you help, im looking forward to the solution :)
Related
Recently I changed from andoroid to androidx. After that, my app crash after successfully sign in. The following quotes are the errors:
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void com.google.android.material.tabs.TabLayout.setupWithViewPager(androidx.viewpager.widget.ViewPager)' on a null object reference
After a lot of research, some suggest that use finishUpdate method but my app still crashes.
#Override public void finishUpdate(ViewGroup container) {
try{
super.finishUpdate(container);
}
catch (NullPointerException nullPointerException){
System.out.println("Catch the NullPointerException in MainActivityFragmentsAdapter.finishUpdate");
}
}
I also have tried to replace code tabLayout.setupWithViewPager(viewPager); to codes below but same error
viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
//tabLayout.addOnTabSelectedListener(new TabLayout.ViewPagerOnTabSelectedListener(viewPager));
tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
viewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
The codes below are my MainActivity class
public class MainActivity extends BaseActivity {
MainActivityFragmentsAdapter mainActivityFragmentsAdapter;
ViewPager viewPager;
String SAVE_INSTANCE_STATE_KEY = "MainActivityFragmentConfig";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mainActivityFragmentsAdapter = new MainActivityFragmentsAdapter(getSupportFragmentManager());
viewPager = findViewById(R.id.main_view_pager);
viewPager.setAdapter(mainActivityFragmentsAdapter);
if(savedInstanceState != null ) {
position = savedInstanceState.getInt(SAVE_INSTANCE_STATE_KEY);
viewPager.setCurrentItem(position);
}
final TabLayout tabLayout = findViewById(R.id.main_tab_layout);
tabLayout.setupWithViewPager(viewPager); // This is the ERROR LINE
viewPager.setOffscreenPageLimit(4);
setTabIcons(tabLayout);
ActivityCompat.requestPermissions(MainActivity.this, new String[]
{android.Manifest.permission.ACCESS_FINE_LOCATION, android.Manifest.permission.ACCESS_COARSE_LOCATION}, 100);
}
#Override
public void onRestoreInstanceState(Bundle savedInstanceState, PersistableBundle persistentState) {
super.onRestoreInstanceState(savedInstanceState, persistentState);
if(savedInstanceState != null ) {
int position = savedInstanceState.getInt(SAVE_INSTANCE_STATE_KEY);
viewPager.setCurrentItem(position);
}
}
#Override
public void onStart() {
super.onStart();
}
int position;
#Override
protected void onPause() {
super.onPause();
position = viewPager.getCurrentItem();
}
#Override
protected void onResume() {
super.onResume();
viewPager.setCurrentItem(position);
}
public void setTabIcons(TabLayout tabLayout) {
int icons[]= {
R.drawable.ic_calendar,
R.drawable.ic_task_complete,
R.drawable.ic_alarm_clock,
R.drawable.ic_man_user
};
for(int i = 0; i < icons.length; i++) {
tabLayout.getTabAt(i).setIcon(icons[i]);
}
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
Log.d("MAIN ACTIVITY", "Saving instance state");
outState.putInt(SAVE_INSTANCE_STATE_KEY, viewPager.getCurrentItem());
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.fyp.selfzenapp.MainActivity">
<androidx.viewpager.widget.ViewPager
android:id="#+id/main_view_pager"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginBottom="60dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<include
android:id="#+id/main_tab_layout_include"
layout="#layout/main_tab_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
I'm trying to implement the "swipe to refresh" in my fragment. I did it by inserting a timer in my main activity, by using the Timer class, which refresh, but I would like to improve it by implementing a function directly inside the fragment itself. This is the code:
public class HomeFragment extends Fragment {
private RecyclerView recyclerView;
public HomeFragment() {
}
public static HomeFragment newInstance(String param1, String param2) {
HomeFragment fragment = new HomeFragment();
Bundle args = new Bundle();
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.main_fragment, container, false);
recyclerView = view.findViewById(R.id.rc_view);
loadMovie();
return view;
}
private void loadMovie() {
ApiService apiService = ApiBuilder.getClient(getContext()).create(ApiService.class);
recyclerView.setLayoutManager(new LinearLayoutManager(getContext(),LinearLayoutManager.HORIZONTAL, false));
Call<MovieResponse> call = apiService.getDiscover(BuildConfig.API_KEY,Values.LANGUAGE,Values.SORT_BY[0], Values.ADULT, Values.GENRE[1], Values.PAGE[0]);
call.enqueue(new Callback<MovieResponse>() {
#Override
public void onResponse(Call<MovieResponse>call, Response<MovieResponse> response) {
final List<MovieModel> movies = response.body().getResults();
recyclerView.setAdapter(new MoviesAdapter(movies, R.layout.content_main, getContext()));
recyclerView.addOnItemTouchListener(new RecyclerView.OnItemTouchListener() {
GestureDetector gestureDetector = new GestureDetector(getContext(), new GestureDetector.SimpleOnGestureListener() {
public boolean onSingleTapUp(MotionEvent e){
return true;
}
});
#Override
public boolean onInterceptTouchEvent(RecyclerView rv, MotionEvent e) {
View child = rv.findChildViewUnder(e.getX(), e.getY());
if (child != null && gestureDetector.onTouchEvent(e)){
int position = rv.getChildAdapterPosition(child);
Intent i = new Intent(getContext(), DetailActivity.class);
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
i.putExtra(DetailActivity.EXTRA_TITLE, movies.get(position).getTitle());
i.putExtra(DetailActivity.EXTRA_OVERVIEW, movies.get(position).getOverview());
i.putExtra(DetailActivity.EXTRA_TIME, movies.get(position).getReleaseDate());
i.putExtra(DetailActivity.EXTRA_POSTER, movies.get(position).getPosterPath());
i.putExtra(DetailActivity.EXTRA_LANGUAGE, movies.get(position).getOriginalLanguage());
try{
List<Integer> genr = movies.get(position).getGenreIds();
i.putExtra(DetailActivity.EXTRA_GENRES, genr.toString());
} catch (Exception ex) {
ex.printStackTrace();
}
getContext().startActivity(i);
}
return false;
}
#Override
public void onTouchEvent(RecyclerView rv, MotionEvent e) {
}
#Override
public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) {
}
});
if (movies != null ){
MovieModel firstMovie = movies.get(0);
if(firstMovie != null) {
Log.i("TAG", firstMovie.getTitle());
}
}
}
#Override
public void onFailure(Call<MovieResponse>call, Throwable t) {
}
});
}
}
This is the Timer I implemented in the main activity, which I want to remove:
TimerTask timertask = new TimerTask() {
#Override
public void run() {
handler.post(new Runnable() {
public void run() {
startService(new Intent(MainActivity.this, TimerService.class));
}
});
}
};
Timer timer = new Timer();
timer.schedule(timertask, 0, 10*SECONDS);
EDIT:
I updated my code by implementing the SwipeRefreshLayout inside the onCreate method but it still doesn't works:
mPullToRefresh = view.findViewById(R.id.swipe_list);
final Handler handler = new Handler();
mPullToRefresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
handler.postDelayed(new Runnable() {
#Override
public void run() {
loadMovie(); //load your moview from here
mPullToRefresh.setRefreshing(false);
}
}, 1000);
}
});
This is my fragment layout updated:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent"
>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Movies"
android:layout_marginLeft="#dimen/_10sdp"
android:layout_marginRight="#dimen/_10sdp"
android:textSize="#dimen/_20ssp"
android:textStyle="bold"
android:textColor="#ffffff"/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="#dimen/_5sdp"
android:text="Action"
android:layout_marginLeft="#dimen/_10sdp"
android:layout_marginRight="#dimen/_10sdp"
android:textSize="#dimen/_12ssp"
android:textColor="#color/colorAccent"/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:minHeight="#dimen/_150sdp"
android:layout_marginTop="#dimen/_10sdp"
android:orientation="vertical">
<androidx.recyclerview.widget.RecyclerView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:id="#+id/rc_view"/>
</LinearLayout>
<androidx.swiperefreshlayout.widget.SwipeRefreshLayout
android:id="#+id/swipe_list"
android:layout_width="match_parent"
android:layout_height="match_parent">
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/recycler_view_list"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</androidx.swiperefreshlayout.widget.SwipeRefreshLayout>
</LinearLayout>
There is a Layout to implement the functionality.
Put this in your fragment xml file:-
<androidx.swiperefreshlayout.widget.SwipeRefreshLayout
android:id="#+id/swipe_list"
android:layout_width="match_parent"
android:layout_height="match_parent">
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/recycler_view_list"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</androidx.swiperefreshlayout.widget.SwipeRefreshLayout>
Now in your Fragment:-
1) do the
SwipeRefreshLayout mPullToRefresh = view.findViewById(R.id.swipe_list)
2) then,
mPullToRefresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
mHandler.postDelayed(new Runnable() {
#Override
public void run() {
loadMovie(); //load your moview from here
mPullToRefresh.setRefreshing(false);
}
}, 1000);
}
});
Please Up-Vote If Found Useful.
I have an SplashScreen and a MainActivity, when tha app launchs it displays the Splash Screen (3 secs delay) then the MainActivity, but when I click a BarNotification of mi App (outside of the App) the Splash Screen Displays(3 seconds delay) and the App Crashes, in LogCat he MainActivity Destroys itself between the Splash Screen Intent LifeCycle. (at lines 29,30 logcat)
main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<WebView
android:id="#+id/browser"
android:layout_width="match_parent"
android:layout_height="match_parent"
/>
</LinearLayout>
splash.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:gravity="center"
android:background="#color/white"
>
<ImageView android:layout_width="wrap_content"
android:contentDescription="splash screen"
android:id="#+id/splash"
android:src="#drawable/splash"
android:layout_height="wrap_content"
android:scaleType="centerInside"/>
</LinearLayout>
Why I'm not able to Launch correctly the App through the Bar Notificaction?
Here is some code:
MainActivity.java
public class MainActivity extends Activity {
private WebView webview;
public MainActivity() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
log.debug("onCreate(): " + savedInstanceState);
MyApplication.startSomeMobileCore(this);
MyApplication.startSomeMobileNotifier(this);
setContentView(R.layout.main);
onNewIntent(getIntent());
}
#Override
protected void onStart() {
log.debug("onStart()");
super.onStart();
}
#Override
protected void onRestart() {
super.onRestart();
this.wasRestarted = true;
}
#Override
protected void onResume() {
super.onResume();
}
protected void onPause() {
super.onPause();
this.receivedIntent = false;
}
protected void onStop() {
super.onStop();
this.receivedIntent = false;
}
public void onDestroy() {
super.onDestroy();
}
#Override
public void onNewIntent(Intent intent) {
log.debug("onNewIntent(): " + intent);
super.onNewIntent(intent);
if(intent == null) {
log.warn("Received null intent, will ignore");
}
if ("OK".equals(authCode)) {
if (intent != null && intent.getData() != null &&
("content".equals(intent.getData().getScheme()) ||
"http".equals(intent.getData().getScheme()))) {
log.debug("intent.getData() :" + intent.getData() + "; intent.getData().getScheme() : " + intent.getData().getScheme());
String requestedPath;
if ("http".equals(intent.getData().getScheme())) {
requestedPath = URLDecoder.decode(intent.getData().toString());
} else {
requestedPath = intent.getData().getPath();
}
showResource(requestedPath);
} else {
log.debug("Intent without data -> go to entry page after splash screen");
showResource(Configuration.properties.getProperty(""));
}
} else {
Intent errorIntent = new Intent(this, ErrorIntent.class);
startActivity(errorIntent);
// finish actual activity
finish();
}
log.debug("Show splash screen");
Intent intentSplash = new Intent(this, SplashIntent.class);
startActivity(intentSplash);
}
void showResource(String resourceToShow) {
webview = (WebView)findViewById(R.id.browser);
webview.getSettings().setRenderPriority(WebSettings.RenderPriority.HIGH);
webview.getSettings().setCacheMode(WebSettings.LOAD_DEFAULT);
webview.setWebViewClient(new WebViewClient());
webview.getSettings().setJavaScriptEnabled(true);
webview.getSettings().setDomStorageEnabled(true);
webview.loadUrl(resourceToShow);
}
}
SplashIntent.java
public class SplashIntent extends Activity {
// Time splash screen should be shown (in ms)
private static final int splashTime = 3000;
static Logger log = Logger.getLogger(SplashIntent.class);
#Override
public void onCreate(final Bundle savedInstanceState) {
log.debug("SplashIntent: onCreate");
super.onCreate(savedInstanceState);
setContentView(R.layout.splash);
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
public void run() {
log.debug("SplashIntent: killing splash");
finish();
}
}, splashTime);
}
}
logcat
Hope you guys can help me with this... I'm really out of ideas at this point
Try this inside your SplashIntent class
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
Intent mainIntent = new Intent(Splash.this,MainActivity.class);
SplashIntent.this.startActivity(mainIntent);
SplashIntent.this.finish();
},splashTime);
Using the button in MainActivity how can i call sprite.move("left") (which will move the sprite left twice a second) that has to be run in GView?
MainActivity.java
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.main);
Button button = (Button) findViewById(R.id.button);
button.setOnTouchListener(new View.OnTouchListener() {
private Handler mHandler;
#Override
public boolean onTouch(View v, MotionEvent event) {
switch(event.getAction()) {
case MotionEvent.ACTION_DOWN:
if (mHandler != null)
return true;
mHandler = new Handler();
mHandler.postDelayed(mAction, 0);
break;
case MotionEvent.ACTION_UP:
if (mHandler == null)
return true;
mHandler.removeCallbacks(mAction);
mHandler = null;
break;
}
return false;
}
Runnable mAction = new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(), "Performing action...", Toast.LENGTH_LONG).show();
mHandler.postDelayed(this, 500);
}
};
});
}
}
main.xml
<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="match_parent"
tools:context="${packageName}.${activityClass}" >
<com.viracide.depth.GView
android:id="#+id/gview"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:layout_marginBottom="180dp"
android:layout_marginLeft="40dp"
android:layout_marginTop="40dp"
android:layout_marginRight="40dp">
</com.viracide.depth.GView>
<Button
android:id="#+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/gview"
android:layout_alignParentBottom="true"
android:layout_marginBottom="73dp"
android:text="Button" />
</RelativeLayout>
GView.java
public class GView extends View {
private Bitmap bmp;
sprite sprite; //sprite image
public GView(Context context) {
super(context);
bmp = BitmapFactory.decodeResource(getResources(), R.drawable.bit);
}
public void draw(Canvas canvas) {
canvas.drawColor(Color.WHITE);
canvas.drawBitmap(bmp, 10 , 10, null);
}
}
public class MainActivity extends Activity {
GView mGView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.main);
// initialize here
mGView = (GView)findViewById(R.id.gview);
// put this anywhere and make sure you do not violate UI thread constraint for making any UI changes
mGview.<yourmethod>()
...
I have a code like the below:
main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<ProgressBar
android:id="#+id/progressbar"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
BasicViews2Activity.java
public class BasicViews2Activity extends Activity
{
static int progress;
ProgressBar progressBar;
int progressStatus = 0;
Handler handler = new Handler();
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
progress = 0;
progressBar = (ProgressBar) findViewById(R.id.progressbar);
//---do some work in background thread--
new Thread(new Runnable()
{
public void run()
{
//---do some work here--
while (progressStatus < 10)
{
progressStatus = doSomeWork();
}
//---hides the progress bar---
handler.post(new Runnable()
{
public void run()
{
progressBar.setVisibility(View.GONE);
}
});
}
//---do some long running work here--
private int doSomeWork()
{
try {
Thread.sleep(500);
} catch (InterruptedException e)
{
e.printStackTrace();
}
return ++progress;
}
}).start();
}
}
Why did we use two runnable objects inside the thread class to cancel the progressbar? Couldn't we do it inside the first runnable obj – just after while loop, without another object?
The asyncTask class can be used easily with progressbars. AS they have an onPreexecute and onPostexecute with which we can update the ui thread from the background activity.
public static final int DIALOG_DOWNLOAD_PROGRESS = 0;
private ProgressDialog mProgressDialog;
#Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case DIALOG_DOWNLOAD_PROGRESS:
mProgressDialog = new ProgressDialog(this);
mProgressDialog.setMessage("waiting 5 minutes..");
mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
mProgressDialog.setCancelable(false);
mProgressDialog.show();
return mProgressDialog;
default:
return null;
}
}
Then write an async task to update progress..
private class DownloadZipFileTask extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
showDialog(DIALOG_DOWNLOAD_PROGRESS);
}
#Override
protected String doInBackground(String... urls) {
//Copy you logic to calculate progress and call
publishProgress("" + progress);
}
protected void onProgressUpdate(String... progress) {
mProgressDialog.setProgress(Integer.parseInt(progress[0]));
}
#Override
protected void onPostExecute(String result) {
dismissDialog(DIALOG_DOWNLOAD_PROGRESS);
}
}
Hope this makes your code easier...
#shaon007 sorry for late post, Yes you can do it with single runnable class
Like below
create your xml just the way you have created
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<ProgressBar
android:id="#+id/progressbar"
android:visibility="invisible"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
Keep visibility option invisible for the start
Then in your mainActivity you have to do three things those are
1) Create Handler object
2) Create anonymous runnable class
3) Call run() method from runnable with setting your progressbar visibility
As follows
public class MainActivity extends AppCompatActivity {
Handler handler;
private ProgressBar progressBar;
private int checkCount = 5000; // counter for progressbar visibility
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
progressBar = (ProgressBar) findViewById(R.id.progressbar);
handler = new Handler(); // handler object
// runnable class
final Runnable runnable = new Runnable() {
#Override
public void run() {
progressBar.setVisibility(View.VISIBLE);
checkCount -= 1000;
if(checkCount > 0) {
handler.postDelayed(this,1000);
}
else {
progressBar.setVisibility(View.INVISIBLE);
Toast.makeText(MainActivity.this,"Progress bar invisible",Toast.LENGTH_SHORT).show();
// Or your other work
}
}
};
handler.postDelayed(runnable,1000); // will start run() method after 1 second
}
}
And your done