My ProgressBar does not appear on Android - android

I have this code for the 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:padding="15px"
>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Loading..."
/>
<ProgressBar android:id="#+id/progressBar"
android:paddingTop="10px"
style="?android:attr/progressBarStyleHorizontal"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:max="100" />
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="#+id/txt"
/>
</LinearLayout>
Then for the class :
public class Loading extends Activity {
ProgressBar bar;
TextView txt;
int total=0;
boolean isRunning=false;
// handler for the background updating
Handler handler=new Handler() {
#Override
public void handleMessage(Message msg) {
total=total+5;
String perc=String.valueOf(total).toString();
txt.setText(perc+"% completed");
bar.incrementProgressBy(5);
}
};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.loading_bar);
bar=(ProgressBar)findViewById(R.id.progressBar);
txt=(TextView)findViewById(R.id.txt);
}
public void onStart() {
super.onStart();
// reset the bar to the default value of 0
bar.setProgress(0);
// create a thread for updating the progress bar
Thread background=new Thread(new Runnable() {
public void run() {
try {
for (int i=0;i<20 && isRunning;i++) {
// wait 1000ms between each update
Thread.sleep(1000);
handler.sendMessage(handler.obtainMessage());
}
}
catch (Throwable t) {
}
}
});
isRunning=true;
// start the background thread
background.start();
}
public void onStop() {
super.onStop();
isRunning=false;
}
}
And with this I call it on another activity:
public void onClick (View v)
{
switch (v.getId())
{
case R.id.buttonNext3:
Intent Loading = new Intent(this, Loading.class);
startActivity(Loading);
getContent();
Call();
db.generation();
Intent Next3 = new Intent(this, FoodPlanning.class);
startActivity(Next3);
break;
}
}
But it is not work on mine, it just show blackscreen but it still on progress .... I want the loading bar appear when I click the button and the process still on progress. any idea? Thx u

As suggested by Adil, AsyncTask is the preferred method to run background tasks with easy options to run certain commands on the UI thread, while pushing the rest to the background. See this example from the SDK (http://developer.android.com/reference/android/os/AsyncTask.html):
private class DownloadFilesTask extends AsyncTask<URL, Integer, Long> {
protected Long doInBackground(URL... urls) {
int count = urls.length;
long totalSize = 0;
for (int i = 0; i < count; i++) {
totalSize += Downloader.downloadFile(urls[i]);
publishProgress((int) ((i / (float) count) * 100));
}
return totalSize;
}
protected void onProgressUpdate(Integer... progress) {
setProgressPercent(progress[0]);
}
protected void onPostExecute(Long result) {
showDialog("Downloaded " + result + " bytes");
}
}
Note the "onProgressUpdate" method as well as the doInBackground.

Related

Android TextView.setText does not work as expected

**I configured a simple single TextView layout (see below after the code) to change the display changing from 10 up to 20. What I see is "20" being displayed. My code is as follows. Want to know why only the last number ("20") is displayed omitting the intermediate ones(10 thru 19))
package com.example.test;
import android.R.string;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.widget.TextView;
import android.widget.Toast;
public class TestActivity extends Activity {
public TextView mytv;
public Toast mtoast;
#Override
protected void onCreate(Bundle savedInstanceState) {
int i = 10;
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test);
mytv = (TextView) findViewById(R.id.myhw);
mtoast = Toast.makeText(this, String.valueOf(i), Toast.LENGTH_LONG);
while (i++ < 20) {
mtoast.setText(String.valueOf(i));
mtoast.show();
mytv.setText(String.valueOf(i));
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.test, menu);
return true;
}
}
The relevant layout is as follows.
<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"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context=".TestActivity" >
<TextView
android:id="#+id/myhw"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/hello_world" />
</RelativeLayout>
because the view is not shown until onResume call and after that the activity is displayed, all you are doing is changing the view content in onCreate method, after onCreate activity goes to onStart and onResume so when onCreate finishes the textView value is 20 and after onResume it sets the value to 20.
for more information look at activity life cycle at :
http://developer.android.com/reference/android/app/Activity.html
You shouldn't sleep the UI thread in the first place.
What you probably want to do is to use another thread, let it sleeps for a couple of seconds and, each time you update the UI, use the UI (main) thread. You can do it in several ways, but the simples probably is using an AsyncTask, as:
public class MyActivity extends Activity {
public TextView mytv;
public Toast mtoast;
private int i;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my);
i = 10;
mytv = (TextView) findViewById(R.id.myhw);
mtoast = Toast.makeText(this, String.valueOf(i), Toast.LENGTH_LONG);
new AsyncTask<Void, String, Void>() {
#Override
protected Void doInBackground(Void... voids) {
while (i < 20) {
publishProgress(String.valueOf(i));
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
i++;
}
return null;
}
#Override
protected void onProgressUpdate(String... values) {
super.onProgressUpdate(values);
mtoast.setText(values[0]);
mtoast.show();
mytv.setText(values[0]);
}
}.execute();
}
}
Want to know why only the last number ("20") is displayed omitting the intermediate ones(10 thru 19))
It doesn't work because you sleep the UI Thread.
To make this work, you would have to do it through a Thread, you can use an AsyncTask for this, or a Timer object as i specified below, anyways i recommend the use of AsyncTask.
Once i was doing something simmilar, you could use a Timer object for this.
Using the method: scheduleAtFixedRate(TimerTask task, long delay, long period)
The Docs for this method says
Schedules the specified task for repeated fixed-rate execution, beginning after the specified delay.
It means after the seconds from the second parameter, it will start, using the third parameter as delay for each execution. You will have to cancel it, calling the method:cancel();
final Timer timer = new Timer();
timer.scheduleAtFixedRate(new TimerTask() {
#Override
public void run() {
runOnUiThread(new Runnable() {
#Override
public void run() {
if (counter == 20) {
timer.cancel();
counter = 0;
time.setText("Ta-da! I'm Done ");
}else{
counter += 1;
if (time != null)
time.setText(String.valueOf(counter));
}
}
});
}
}, delay, period);
Even further: A Thread.sleep is not the proper way to update a GUI and watch how it changes. The value it will take is the last one. The activity will be blocked until the last is shown.
If you want to see that effect, you should programm a Thread which communicates the main thread every X seconds, and the main thread should listen the Thread to change it.
For example, you could use an AsyncTask and use onProgressUpdate.
Edited with some code:
MainActivity
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#Override
protected void onResume(){
super.onResume();
/* Running AsyncTask */
myAsyncTask bkg = new myAsyncTask();
/* I'll pass an integer parameter: milliseconds to wait. */
bkg.execute(3000);
}
private class myAsyncTask extends AsyncTask<Integer, Integer, String> {
#Override
protected void onPreExecute() {
/* TODO: Do BEFORE background process */
Toast.makeText(getApplicationContext(),"I'm going to do a background task!", Toast.LENGTH_SHORT).show();
}
#Override
protected String doInBackground(Integer... parameters) {
/* TODO: What to do in Background */
/* Retrieving parameter passed */
int milliseconds = parameters[0];
try {
Thread.sleep(milliseconds);
publishProgress(milliseconds); /* Will prompt that value */
} catch (InterruptedException e) {
e.printStackTrace();
return "ERROR";
}
int i = 0;
while (i++ < 20) {
try {
Thread.sleep(milliseconds);
publishProgress(i);
} catch (InterruptedException e) {
e.printStackTrace();
return "ERROR";
}
}
return "OK";
}
#Override
protected void onPostExecute(String result) {
/* TODO: After execution of thread */
if(result.equals("OK"))
Toast.makeText(getApplicationContext(),"Correctly Processed", Toast.LENGTH_SHORT).show();
if(result.equals("ERROR"))
Toast.makeText(getApplicationContext(),"Failed", Toast.LENGTH_SHORT).show();
}
#Override
protected void onProgressUpdate(Integer... values) {
/* TODO: Here you can access UI elements as your TextView */
TextView tv = (TextView) findViewById(R.id.tvExample);
tv.setText(values[0]+"");
}
}
}
layout/main_activity.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"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin"
tools:context="com.myapplication2.app.MainActivity"
android:id="#+id/whatever">
<TextView
android:text="#string/hello_world"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true"
android:id="#+id/tvExample" />
Use the code (tested on device) provided below:
public class TestActivity extends Activity {
private Handler mHandler;
public TextView mytv;
private int i;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_toast_showing_acounter);
mytv = (TextView) findViewById(R.id.myhw);
mHandler = new Handler();
i = 10;
scheduleHandler();
}
private void scheduleHandler() {
mHandler.postDelayed(new Runnable() {
#Override
public void run() {
showCounter();
if (i < 20) {
scheduleHandler();
}
}
}, 5000);
}
private void showCounter() {
Toast.makeText(this, String.valueOf(i), Toast.LENGTH_LONG).show();
mytv.setText(String.valueOf(i));
i++;
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.test, menu);
return true;
}
}

ProgressDialog is shown in non-UI thread

This code is from a book. a Progress Dialog seems to be shown in non-UI thread.
But as I know only in the UI thread It is possible.
I wonder why it is possible to show a ProgressDialog in non-Ui thread.
public class BackWork3 extends Activity
{
TextView mResult;
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.backwork);
mResult = (TextView)findViewById(R.id.result);
}
public void mOnClick(View v)
{
int start = 0, end = 100;
int result;
WaitDlg dlg = new WaitDlg(BackWork3.this, "WaitTest", "Now calculating");
dlg.start();
result = Accumulate(start, end);
mResult.setText("" + result);
WaitDlg.stop(dlg);
}
int Accumulate(int start, int end)
{
int sum = 0;
for (int i = start; i <= end; i++)
{
sum += i;
try { Thread.sleep(20); } catch (InterruptedException e) {;}
}
return sum;
}
}
class WaitDlg extends Thread
{
Context mContext;
String mTitle;
String mMsg;
ProgressDialog mProgress;
Looper mLoop;
WaitDlg(Context context, String title, String msg)
{
mContext = context;
mTitle = title;
mMsg = msg;
setDaemon(true);
}
public void run()
{
Looper.prepare();
mProgress = new ProgressDialog(mContext);
mProgress.setProgressStyle(ProgressDialog.STYLE_SPINNER);
mProgress.setTitle(mTitle);
mProgress.setMessage(mMsg);
mProgress.setCancelable(false);
mProgress.show();
mLoop = Looper.myLooper();
Looper.loop();
}
static void stop(WaitDlg dlg)
{
dlg.mProgress.dismiss();
try { Thread.sleep(100); } catch (InterruptedException e) {;}
dlg.mLoop.quit();
}
}
//------------------------------------------------------------------------------
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
>
<Button
android:id="#+id/start"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="mOnClick"
android:text="Start"
/>
<TextView
android:id="#+id/result"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="40sp"
android:text="result"
/>
</LinearLayout>
The code is using Looper inside non UI thread that creates a handler and this looper becomes a reference to that Handler. This way you can play with UI elements in non UI thread.
According to Docs.
Looper.Prepare():
Initialize the current thread as a looper. This gives you a chance to create handlers that then reference this looper, before actually starting the loop.
Hope this helps

Progress bar onclick button in android?

How to bring a progress bar on clicking a button in an activity i have an button in my main activity and if i click the button i want to display a progress bar i dont wanna use a secondary activity for this i have done with 2 activities but i need it to be done in main activity itself.
thank you
My code:
Home Activity :
public void load(View v){
Intent intent = new Intent(this,Splash.class);
this.startActivity(intent);
}
Splash Activity :
public class Splash extends Activity {
private long ms = 0;
private long splashTime = 20000;
private boolean splashActive = true;
private boolean paused = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.splash);
Thread mythread = new Thread() {
public void run() {
try {
while (splashActive && ms < splashTime) {
if (!paused)
ms = ms + 100;
sleep(100);
}
} catch (Exception e) {
} finally {
Intent intent = new Intent(Splash.this, Home.class);
startActivity(intent);
}
}
};
mythread.start();
}
}
You can do like this
ProgressDialog progress;
progress = new ProgressDialog(this);
progress.setTitle("Please Wait!!");
progress.setMessage("Wait!!");
progress.setCancelable(true);
progress.setProgressStyle(ProgressDialog.STYLE_SPINNER);
progress.show();
call this code where you want to display your ProgressBar.
There is one more method to show the ProgressBar on Button Click.
Put this code in your xml
<ProgressBar
android:id="#+id/progressBar1"
style="?android:attr/progressBarStyleLarge"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:visibility="invisible" />
and just write following code on your Button click in java file.
progressBar.setVisibility(View.VISIBLE);
It will show the Progressbar on your Button Click.
I believe the user2306156 will not be in need of this now, hopefully someone who is looking for this will be glad to know i guess.
put this code in your xml
<ProgressBar
style="#android:style/Widget.Material.Light.ProgressBar"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/checkBox"
android:layout_centerHorizontal="true"
android:layout_marginTop="57dp"
android:id="#+id/progressBar" />
put this in your activity code
spinner=(ProgressBar)findViewById(R.id.progressBar);
spinner.setVisibility(View.GONE);
and this in your onClick of the activity code
spinner.setVisibility(View.VISIBLE);
See this Android Progress Bar Example
public class MyAndroidAppActivity extends Activity {
Button btnStartProgress;
ProgressDialog progressBar;
private int progressBarStatus = 0;
private Handler progressBarHandler = new Handler();
private long fileSize = 0;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
addListenerOnButton();
}
public void addListenerOnButton() {
btnStartProgress = (Button) findViewById(R.id.btnStartProgress);
btnStartProgress.setOnClickListener(
new OnClickListener() {
#Override
public void onClick(View v) {
// prepare for a progress bar dialog
progressBar = new ProgressDialog(v.getContext());
progressBar.setCancelable(true);
progressBar.setMessage("In Progress ...");
progressBar.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
progressBar.setProgress(0);
progressBar.setMax(100);
progressBar.show();
//reset progress bar status
progressBarStatus = 0;
//reset filesize
fileSize = 0;
new Thread(new Runnable() {
public void run() {
while (progressBarStatus < 100) {
// process some tasks
progressBarStatus = doSomeTasks();
// your computer is too fast, sleep 1 second
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
// Update the progress bar
progressBarHandler.post(new Runnable() {
public void run() {
progressBar.setProgress(progressBarStatus);
}
});
}
// ok, file is downloaded,
if (progressBarStatus >= 100) {
// sleep 2 seconds, so that you can see the 100%
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
// close the progress bar dialog
progressBar.dismiss();
}
}
}).start();
}
});
}
// file download simulator... a really simple
public int doSomeTasks() {
while (fileSize <= 1000000) {
fileSize++;
if (fileSize == 100000) {
return 10;
} else if (fileSize == 200000) {
return 20;
} else if (fileSize == 300000) {
return 30;
}
// ...add your own
}
return 100;
}
}
Another Option is to use the nifty Spezi-Views, it contains a ProgressButton which is quite easy to use:
<de.halfreal.spezi.views.ProgressButton
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Press me"
app:selectedText="I am loaded"
app:unselectedText="Press me again"
app:loadingDrawable="#drawable/spinner"
/>
and in code:
...
//show a rotation spinner, and no text (or the loading text)
progressButton.enableLoadingState();
//show no animation, but the selected/ unselected text
progressButton.disableLoadingState();
...

progressbar doesn't show on screen

I need to show a second activity after the progress bar is filled. I tried the code below but it doesn't show the progress bar and just shows my second activity.
This is the code:
public class MiSuper2 extends Activity {
String strListas[] = null;
private ProgressBar mProgress;
private int mProgressStatus = 0;
private Handler mHandler = new Handler();
private StoreData stdArticulos = null;
public Cursor cursor = null;
private long fileSize = 0;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
stdArticulos = new StoreData(this);
fileSize = 0;
setContentView(R.layout.main);
stdArticulos = new StoreData(this);
cursor = stdArticulos.leerArticulos();
mProgress = (ProgressBar) findViewById(R.id.progressbar_activity);
new Thread(new Runnable() {
public void run() {
while (mProgressStatus < 100) {
mProgressStatus = doWork();
mHandler.post(new Runnable() {
public void run() {
mProgress.setProgress(mProgressStatus);
}
});
}
}
}).start();
if(cursor.moveToFirst()) {
do{
strListas[cursor.getPosition()] = cursor.getString(cursor.getPosition());
}while(cursor.moveToNext());
}
Intent intent = new Intent(MiSuper2.this, PntArticulo.class);
startActivity(intent);
}
public int doWork() {
while (fileSize <= 1000000) {
fileSize++;
return (int) fileSize;
}
return 100;
}
}
This is the 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:gravity="center_horizontal"
android:orientation="vertical" >
<ImageView
android:id="#+id/imvLogo"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/presentacion"
android:contentDescription="#string/logo"/>
<ProgressBar
android:id="#+id/progressbar_activity"
style="?android:attr/progressBarStyleHorizontal"
android:layout_width="200dp"
android:layout_height="wrap_content" android:layout_marginTop="100dp"/>
</LinearLayout>
Please help
It looks like you are using the doWork() function to take up time so that you're progress bar does something. Even though you wrote a big loop, it still executes very quickly so you don't see your progress bar move. Rather, you want to simulate your Thread doing something computationally intensive by using Thread.sleep() which takes an argument that is the time to sleep in milliseconds.
Try changing your code to this:
new Thread(new Runnable() {
public void run() {
while (mProgressStatus < 100) {
try {
mProgressStatus += doWork();
} catch (InterruptedException e) {
e.printStackTrace();
}
mHandler.post(new Runnable() {
public void run() {
mProgress.setProgress(mProgressStatus);
}
});
}
runOnUiThread(new Runnable() {
#Override
public void run() {
startActivity(new Intent(MiSuper2.this, Second.class));
}
});
}
}).start();
And...
public int doWork() throws InterruptedException {
Thread.sleep(1000);
return 1;
}
This will increment your progress bar by 1% every second. And finally, the documentation on Thread.sleep(): https://developer.android.com/reference/java/lang/Thread.html#sleep(long)
EDIT: Ramz beat me to this answer, but doesn't provide an explanation of why it's the answer. Hopefully my explanation helps.
EDIT2: I think you edited your questions since I started looking at it a second time. You had some errors in your XML before, but now it is gone. Regardless, your problem is now that you need the call to startActivity() inside your worker thread. Otherwise, the UI thread does not wait for the doWork() function to return and immediately starts the other Activity when your app starts. Sorry, I should have mentioned this before. The code I posted above is updated with this change.
Please try this code SplashScreen.java
package com.cud.point;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.widget.ProgressBar;
import android.widget.TextView;
public class SplashScreen extends Activity {
ProgressBar bar;
TextView txt;
int total=0;
boolean isRunning=false;
// handler for the background updating
Handler handler=new Handler() {
#Override
public void handleMessage(Message msg) {
total=total+20;
String perc=String.valueOf(total).toString();
txt.setText(perc+"% completed");
bar.incrementProgressBy(20);
}
};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.splash);
bar=(ProgressBar)findViewById(R.id.progress);
txt=(TextView)findViewById(R.id.txt);
Handler x = new Handler();
x.postDelayed(new SplashHandler(), 5000);
}
class SplashHandler implements Runnable
{
public void run() {
// TODO Auto-generated method stub
startActivity(new Intent(getApplication(),YourSecound Activity.class));
SplashScreen.this.finish();
}
}
public void onStart() {
super.onStart();
// reset the bar to the default value of 0
bar.setProgress(0);
// create a thread for updating the progress bar
Thread background=new Thread(new Runnable() {
public void run() {
try {
for (int i=0;i<5 && isRunning;i++) {
// wait 100ms between each update
Thread.sleep(1000);
handler.sendMessage(handler.obtainMessage());
}
}
catch (Throwable t) {
} } });
isRunning=true;
// start the background thread
background.start();
}
public void onStop() {
super.onStop();
isRunning=false;
}
}
splash.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
android:padding="15px" >
<TextView
android:id="#+id/textView1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Loading......" />
<TextView
android:id="#+id/txt"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/imageView1"/>
<ImageView
android:id="#+id/imageView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/splash" />
<ProgressBar
android:id="#+id/progress"
style="?android:attr/progressBarStyleHorizontal"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/imageView1"
android:layout_alignLeft="#+id/imageView1"
android:max="100" />
</RelativeLayout>
this is an example of my project so please make necessary change in xml file

Android ProgressBar with threads

I am working on ProgressBar class in android, but I can't make it progress through 5 seconds and load the application. Everything works but the progress bar not progressing. Here is the code.
public class StartPoint extends Activity{
ProgressBar progressBar;
private int progressBarStatus = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.splash);
progressBar = (ProgressBar)findViewById(R.id.progressBar1);
Thread timer = new Thread(){
public void run(){
try{
sleep(5000);
while(progressBarStatus < 5000){
progressBar.setProgress(progressBarStatus);
progressBarStatus += 1000;
}
}catch(InterruptedException e){
e.printStackTrace();
}finally{
Intent openMainList = new Intent(StartPoint.this, in.isuru.caf.MainList.class);
startActivity(openMainList);
}
}
};
timer.start();
}
protected void onPause(){
super.onPause();
finish();
}
}
And here is the layout file splash.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<ImageView
android:id="#+id/imageView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/mary_mother_of_god" />
<ProgressBar
android:id="#+id/progressBar1"
style="?android:attr/progressBarStyleHorizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1.67" />
</LinearLayout>
You can't update a UI Widget from a different thread. You need to do something like:
Thread timer = new Thread(){
public void run(){
try{
sleep(5000);
while(progressBarStatus < 5000){
StartPoint.this.runOnUIThread(new Runnable(){
public void run()
{
progressBar.setProgress(progressBarStatus);
progressBarStatus += 1000;
}
});
}
}catch(InterruptedException e){
e.printStackTrace();
}finally{
Intent openMainList = new Intent(StartPoint.this, in.isuru.caf.MainList.class);
startActivity(openMainList);
}
}
};
timer.start();

Categories

Resources