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
Related
Let's say I have this code:
XML
<FrameLayout android:layout_height="match_parent"
android:layout_width="match_parent"
xmlns:android="http://schemas.android.com/apk/res/android" >
<android.support.v7.widget.RecyclerView
android:id="#+id/photo_recycler_view"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</FrameLayout>
Program
private class FetchItemsTask extends AsyncTask<Void, Void, List<GalleryItem>> {
private String mQuery;
public FetchItemsTask(String query) {
mQuery = query;
}
#Override
protected List<GalleryItem> doInBackground(Void... params) {
if (mQuery == null) {
return new FlickrFetchr().fetchRecentPhotos();
} else {
return new FlickrFetchr().searchPhotos(mQuery);
}
}
#Override
protected void onPostExecute(List<GalleryItem> galleryItems) {
mItems = galleryItems;
setupAdapter();
}
}
How do I implement a spinning ProgressBar and hide the RecyclerView while the AsycnTask does its work in the background? Sorry if this seems like a simple question, but the only answers that I've found use ProgressDialog, which is deprecated as of API 26. Thank you in advance.
Override the Pre-execute Method and show the progress dialog.
You can show the spinner in onPreExecute() and hide it in onPostExecute().
class Your_Class extends AsyncTask<...>
{
ProgressBar pb;
Your_Class(){
// initialize pb
}
Protected void onPreExecute(){
// show progressbar
}
protected void onPostExecute(Bitmap image){
// hide progressbar
}
}
I am trying to show progress dialog and update it inside runOnUiThread
but the progress bar never shown. when I replace the runOnUiThread with "new Thread" it work fine. But I want it to work with runOnUiThread
here is my code , I have deleted unnecessary codes
public class test extends Activity {
private ProgressDialog progress;
Handler progressBarHandler = new Handler();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
testing();
}
public void testing() {
progress=new ProgressDialog(this);
progress.setMessage("Saving Progress");
progress.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
progress.setProgress(0);
progress.setMax(100);
progress.setCancelable(false);
progress.show();
runOnUiThread(new Runnable() {
#Override
public void run() {
//do some work
for (int i =0; i<100;i++){
//some work
progressBarHandler.post(new Runnable() {
#Override
public void run() {
progress.setProgress(finalCount);
}
});
}
}
}
Try this
public class MainActivity extends AppCompatActivity {
private ProgressDialog progress;
Handler workHandler;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
progress=new ProgressDialog(this);
progress.setMessage("Saving Progress");
progress.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
progress.setProgress(0);
progress.setMax(100);
progress.setCancelable(false);
progress.show();
workHandler = new Handler(new HandlerThread("workHandlerThread").getLooper());
workHandler.post(new Runnable() {
#Override
public void run() {
//Do some work
runOnUiThread(new Runnable() {
#Override
public void run() {
progress.setProgress(/*work result*/);
}
});
}
});
}
}
The idea is you do the work on the HandlerThread bound to workHandler, and post the results back the the UI using runOnUiThread()
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);
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 :)
I wrote below method to show progress bar but the progress bar rounded by white box fits the screen width and i do not know why.
public void showProgressBar() {
AlertDialog.Builder builder = new AlertDialog.Builder(activity);
ProgressBar pbar = new ProgressBar(activity, null,
android.R.attr.progressBarStyleLargeInverse);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(30, 50);
pbar.setLayoutParams(params);
builder.setView(pbar);
builder.setCancelable(true);
progressBar = builder.create();
progressBar.show();
}
when execute the above method the progress shown as this image.
progress bar problem
How i can solve this issue?
You should use a ProgressDialog and no, it doesn't fit the screen width.
ProgressDialog pd=new ProgressDialog(activity);
pd.setProgressStyle(ProgressDialog.STYLE_SPINNER);
pd.setIndeterminate(true);
pd.setCancelable(false);
pd.show();
This should give you what you want.
Do this:
ProgressDialog pd;//declare as a global variable
public void showProgressBar() {
pd=new ProgressDialog(activity);
pd.setProgressStyle(ProgressDialog.STYLE_SPINNER);
pd.setIndeterminate(true);
pd.setCancelable(false);
pd.show();
}
Dismiss the ProgressDialog wherever you want later.
I solved it by stupid way but it works fine at me.
public abstract class AbstractScreen implements IActivity {
protected Response response;
protected FragmentActivity activity;
private CustomProgressDialog progress;
public AbstractScreen(FragmentActivity activity) {
this.activity = activity;
}
public abstract void loadScreen();
#Override
public void preExecution() {
// TODO Auto-generated method stub
}
#Override
public void postExecution(Response response) {
// TODO Auto-generated method stub
}
public void showProgressBar() {
progress = new CustomProgressDialog(activity);
progress.show();
}
public void closeProgress() {
progress.dismiss();
}
public FragmentActivity getActivity() {
return activity;
}
private class CustomProgressDialog extends Dialog {
private Context context;
public CustomProgressDialog(Context context) {
super(context);
this.context = context;
loadScreen();
}
public void loadScreen() {
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.progress);
setCancelable(false);
}
}
}
add this layout file also.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_height="fill_parent"
android:layout_width="fill_parent"
android:orientation="vertical"
android:layout_marginRight="-7dp"
>
<ProgressBar
android:layout_width="fill_parent"
android:layout_height="wrap_content"
style="?android:attr/progressBarStyleLarge"
android:id="#+id/progressbar"
android:layout_gravity="center_horizontal"
android:max="100"
/>
</LinearLayout>