displaying progressbar using threading - android

I am trying to display a progress bar using threading .. I accept that I do not have that much concept of threading.
Here is the code
public class Progress extends Activity {
static String[] display;
private static final int Progress = 0;
private ProgressBar mProgress;
private int mProgressStatus = 0;
private Handler mHandler = new Handler();
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.progress);
mProgress = (ProgressBar) findViewById(R.id.progressBar);
// Start lengthy operation in a background thread
new Thread(new Runnable() {
public void run() {
while (mProgressStatus < 100) {
mProgressStatus = doWork();
// Update the progress bar
mHandler.post(new Runnable() {
public void run() {
mProgress.setProgress(mProgressStatus);
}
});
}
}
private int doWork() {
display = new Logic().finaldata();
// TODO Auto-generated method stub
return 100;
}
}).start();
}
}
On running, the logcat message is
java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
What is the mistake that I am doing here?

So your problem will be elsewhere. I tried your example with Handler and it works for me.
package com.sajmon.threadsDemo;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.widget.ProgressBar;
import android.widget.TextView;
public class ThreadsDemoActivity extends Activity {
ProgressBar bar;
TextView label;
Handler handler = new Handler();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
bar = (ProgressBar) findViewById(R.id.progBar);
new Thread(new Runnable() {
int i = 0;
int progressStatus = 0;
public void run() {
while (progressStatus < 100) {
progressStatus += doWork();
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
// Update the progress bar
handler.post(new Runnable() {
public void run() {
bar.setProgress(progressStatus);
i++;
}
});
}
}
private int doWork() {
return i * 3;
}
}).start();
}
}
And XML:
<ProgressBar
android:id="#+id/progBar" style="?android:attr/progressBarStyleHorizontal"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/>
So look at this and edit your code similar with this.

Find the below example code for progress bar update using threads
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.TextView;
public class ThreadDemo1ProgressBar extends Activity
{
ProgressBar bar;
TextView msgWorking;
boolean isRunning = false;
Handler handler = new Handler(){
#Override
public void handleMessage(Message msg) {
bar.incrementProgressBy(5);
if (bar.getProgress() == bar.getMax()) {
msgWorking.setText("Done");
bar.setVisibility(View.INVISIBLE);
} else {
msgWorking.setText("Working..." +
bar.getProgress());
}
}// handleMessage
};
#Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.main);
bar = (ProgressBar) findViewById(R.id.progress);
bar.setMax(100);
msgWorking = (TextView) findViewById(R.id.TextView01);
}
public void onStart() {
super.onStart();
bar.setProgress(0);
Thread background = new Thread(new Runnable() {
public void run() {
try
{
for (int i = 0; i < 20 && isRunning; i++) {
Thread.sleep(1000);
handler.sendMessage(handler.obtainMessage());
}
}
catch(Throwable t) {
// just end the background thread
}
}
});
isRunning = true;
background.start();
}// onStart
public void onStop() {
super.onStop();
isRunning = false;
}
}// ThreadDemo1ProgressBar
The about example updating the progress bar for every 5 seconds.

I actually just create a thread instance once and it works anyway. This code was written in the Startup Activity. All you need to do is call showSpinner1() method to show/hide the spinner.
Ensure to do this
getWindow().requestFeature(Window.FEATURE_INDETERMINATE_PROGRESS); in your onCreate() method and use this code for toggling the spinner ON and OFF.
// Spinner related code - The thread is created just once and is used multiple times (works!!)
boolean toShow = false;
Thread spinner1Thread = new Thread("Show/Hide Spinner Thread") {
#Override
public void run() {
setProgressBarIndeterminateVisibility(toShow);
}
};
/**
* Shows and hides the spinner
* #param pShow
*/
public void showSpinner1(boolean pShow) {
toShow = pShow;
runOnUiThread(spinner1Thread);
}

Related

What is the process to include a progress Bar before an activity launches

Am trying to include a progessbar in my app before launching my activity.
If any one knows the perfect implementaion let me know.Am tried but not getting the desired solution.
Because of this issue m not able to work further.Plz i need help.
I know the Process how to include the progress Dialog but i want to include ProgessBar.What i really need to do.
M sharing my code that i hv tried:
package com.example.demo1;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.widget.ProgressBar;
public class MainActivity extends Activity {
private static final int PROGRESS = 0x1;
private ProgressBar mProgress;
private int mProgressStatus = 0;
private Handler mHandler = new Handler();
protected void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.activity_main);
mProgress = (ProgressBar) findViewById(R.id.progress_bar);
// Start lengthy operation in a background thread
new Thread(new Runnable() {
public void run() {
while (mProgressStatus < 100) {
mProgressStatus = doWork();
// Update the progress bar
mHandler.post(new Runnable() {
public void run() {
mProgress.setProgress(mProgressStatus);
}
});
}
}
private int doWork() {
// TODO Auto-generated method stub
return 0;
}
}).start();
}
}
https://dzone.com/articles/android-example-progress-bar see if this helps... They have shown buffering progress bar example also...I dont know which one you need but this can help you chose any of them as per requirements...
You can include splash activity like this:->
public class SplashActivity extends AppCompatActivity {
private Context context;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_splash);
context = this;
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
Intent intent = new Intent(SplashActivity.this, HomeActivity.class);
finish();
}
}, 1000);
}
}

Android Progress Bar not working for me

Progress bar is not working for me. I am try to show some details in Progress. But I can't, What I did wrongly? Please help me.
Activity Filename - MainActivity.java
package com.example.sqliteexample;
import android.os.Bundle;
import android.os.Handler;
import android.app.Activity;
import android.app.ProgressDialog;
import android.view.Menu;
public class MainActivity extends Activity {
private Handler handler = new Handler();
private ProgressDialog dialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//dialog = ProgressDialog.show(this,getString(R.string.loading) ,getString(R.string.alignMsg));
dialog = ProgressDialog.show(this,"Loading", "Loading the Image of the Day");
Thread th = new Thread()
{
public void run() {
handler.post(
new Runnable (){
#Override
public void run() {
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
e.printStackTrace();
}
dialog.dismiss();
}});
}};
th.start();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
Try it using handler.postDelayed :
dialog = ProgressDialog.show(this,
"Loading", "Loading the Image of the Day");
handler.postDelayed(runnable,10000);
}
Runnable runnable = new Runnable() {
#Override
public void run() {
/* dismiss dialog here*/
dialog.dismiss();
handler.removeCallbacks(runnable);
}
};
or you will need to move Thread.sleep(10000); inside Thread run method instead of inside Runnable which you are passing to Handler.post method as:
Thread th = new Thread()
{
public void run() {
/** call Thread.Sleep here... **/
Thread.sleep(10000);
handler.post(
....your code here....
The handler is defined in main activity and thus it will run on UI thread. You ask to sleep for 10 seconds and this won't work on the UI thread.
If you want to show the progress bar and dismiss it after 10 seconds then use handler.postDelayed(Runnable r, long delayMillis).
This is the code:
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// dialog = ProgressDialog.show(this,getString(R.string.loading) ,getString(R.string.alignMsg));
dialog = ProgressDialog.show(this, "Loading", "Loading the Image of the Day");
handler.postDelayed(new Runnable()
{
#Override
public void run()
{
dialog.dismiss();
}
}, 10000);
}
Hope it was helpful.

Make android screen change color once per second

I am a beginner to android, with some java under my belt. I have completed the make my first app tutorial only.
Next I want to make an app to use simple 2D graphics
To start, I want to find a way of flashing the screen between two colors (red and green) in an infinite loop
wait int seconds;
make screen red;
wait int seconds;
make screen green;
loop forever;
Could anyone please point me to a tutorial(s) or source code(s) that may help?
Many Thanks
How about you make a layout which fills the screen, lets call it llayout.
put this in the code:
static final int[] COLORS = {0xff0000, 0x00ff00};
static final int WAITTIME = 1000;
int currentColor = 0;
public void onCreate(Bundle b) {
setContentView(R.layout.mylayout);
final LinearLayout llayout = (LinearLayout) findViewById(R.id.llayout);
new Thread() {
public void run() {
while(true) {
Thread.sleep(WAITTIME);
currentColor++;
if (currentColor > COLORS.length)
currentColor = 0;
YourActivity.this.runOnUiThread(new Runnable() {
public void run() {
llayout.setBackgroundColor(COLORS[currentColor]);
}
});
}
}
}.start();
}
This should work. Using this code, you can add additional colors to the array COLORS.
Thanks for the input,
This code seems to work OK
package biz.consett.mydraw;
import android.app.Activity;
import android.graphics.Color;
import android.os.Bundle;
import android.view.View;
/* Flash the screen between red and green each second */
public class MainActivity extends Activity {
final static int INTERVAL = 1000; // 1000=1sec
private static View myView = null;
boolean whichColor = true;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myView = (View) findViewById(R.id.my_view);
myView.setBackgroundColor(Color.RED);// set initial colour
new Thread(new Runnable() {
public void run() {
while (true) {
try {
Thread.sleep(INTERVAL);
}
catch (InterruptedException e) {
e.printStackTrace();
}
updateColor();
whichColor = !whichColor;
}
}
}).start();
}
private void updateColor() {
runOnUiThread(new Runnable() {
#Override
public void run() {
if (whichColor)
myView.setBackgroundColor(Color.RED);
else
myView.setBackgroundColor(Color.GREEN);
}
});
}
}
Layout, activity_main.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">
<View
android:id="#+id/my_view"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
</View>
</RelativeLayout>
You already got a lot of solutions but just adding my own...
You will need a timer
#Override
protected void onCreate(Bundle bundle)
{
...
Timer timer = new Timer();
TimerTask updateColor = new SwitchColorTask();
timer.scheduleAtFixedRate(updateColor, 100, 100);
...
}
A timer task.
private boolean colorSwitched;
class SwitchColorTask extends TimerTask {
public void run() {
LinearLayout main = (LinearLayout)findViewById(R.id.main);
if(colorSwitched){
main.setBackgroundColor (Color.GREEN)
}
else{
main.setBackgroundColor (Color.RED)
}
colorSwitched=!colorSwitched
}
}
Taken from this post and edited for your case:
private int m_interval = 1000; // 1 second by default, can be changed later
private Handler m_handler;
private Layout mYourMainLayout //dont know what type of layout you use
private boolean which;
#Override
protected void onCreate(Bundle bundle)
{
...
mYourMainLayout = (Layout) this.findViewById(R.id.yourMainLayout);
m_handler = new Handler();
}
Runnable m_colorChanger = new Runnable()
{
#Override
public void run() {
if(which){
mYourMainLayout.setBackgroundColor(Color.GREEN)
}
else {
mYourMainLayout.setBackgroundColor(Color.RED)
}
which=!which
m_handler.postDelayed( m_colorChanger, m_interval);
}
};
This code implements the array of colors and works fine - many thanks.
(uses same manifest and layout)
package biz.consett.mydraw;
import android.app.Activity;
import android.graphics.Color;
import android.os.Bundle;
import android.view.View;
/*
* Simple use of Android Thread
* Flash the screen between an array of colours at an interval
*
*/
public class MainActivity extends Activity
static final int[] COLORS =
{AColor.RED, AColor.BLUE, AColor.GREEN};// colour array
// Colour Red Green Blue
// Index [0] [1] [2]
private int currentColor = 0;
private View MYVIEW = null;
//boolean whichColor = true;
final int interval = 100; // 0.6 second static final?
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
MYVIEW = (View) findViewById(R.id.my_view);
MYVIEW.setBackgroundColor(Color.RED);// set initial colour
new Thread(new Runnable()
{
// #Override
public void run()
{
while (true)
{
try
{
Thread.sleep(interval); // sleep for interval
}
catch (InterruptedException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
updateColor();
} // end of while true loop
}// end of run
}).start(); // end of runnable
} // end of onCreate bundle
private void updateColor()
{
runOnUiThread(new Runnable()
{
#Override
public void run()
{
if (currentColor > COLORS.length - 1)
{
currentColor = 0;
}
MYVIEW.setBackgroundColor(COLORS[currentColor]);
currentColor++;
}// end of run
});
}
}// -------------END OF MainActivity extends Activity-----------------------
package biz.consett.mydraw;
public class AColor
{
final static int RED = 0xFFFF0000; // hex alpha_R_G_B
final static int GREEN = 0xFF00FF00;
final static int BLUE = 0xFF0000FF;
final static int PURPLE = 0xFFAA00AA;
}

Open an activity after a certain amount of time?

I would like to implement a SplashScreen in my app. I found the best and easiest way is to launch an activity that shows a layout with an image view at the launch of the app and then adding android:noHistory="true" attribute to the manifest.
Now, how do I set the splashscreen activity to launch the MainActivity class after a certain amount of time? Lets say 2 seconds?
This is my splashscreen activity
public class SplashActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.splashscreen);
}
}
use
handler.postDelayed(runnable, delayinmilliseconds(2000 in your case));
final Runnable runnable = new Runnable()
{
public void run()
{
//start the new activity here.
}
};
Here is a complete sample.
package com.test.splash;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.ImageView;
public class splash extends Activity {
private static final int STOPSPLASH = 0;
//time in milliseconds
private static final long SPLASHTIME = 3000;a
private ImageView splash;
//handler for splash screen
private Handler splashHandler = new Handler() {
/* (non-Javadoc)
* #see android.os.Handler#handleMessage(android.os.Message)
*/
#Override
public void handleMessage(Message msg) {
switch (msg.what) {
case STOPSPLASH:
//remove SplashScreen from view
splash.setVisibility(View.GONE);
break;
}
super.handleMessage(msg);
}
};
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.main);
splash = (ImageView) findViewById(R.id.splashscreen);
Message msg = new Message();
msg.what = STOPSPLASH;
splashHandler.sendMessageDelayed(msg, SPLASHTIME);
}
}
public class TrackMyMoneyActivity extends Activity {
//member fields
private ProgressBar pbar = null;
private TextView counter_txt = null;
Thread splash_thread = null;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
pbar = (ProgressBar) findViewById(R.id.splashpbar);
counter_txt = (TextView) findViewById(R.id.countertxt);
//define thread
splash_thread = new Thread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
int i = 0;
for( i=0;i<100;i++){
pbar.setProgress(i);
// counter_txt.setText(i+" %");
try {
splash_thread.sleep(100);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if(i==100){
Intent intent = new Intent(getBaseContext(), LoginApp.class);
startActivity(intent);
}
}
});
splash_thread.start();
}
#Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
}
}
I hope it will be solved your solution.
You can also use java.util.Timer in this way:
new Timer().schedule(new TimerTask(){
public void run() {
startActivity(new Intent(SplashActivity.this, MainActivity.class));
}
}, 2000 /*amount of time in milliseconds before execution*/ );
public class Splashscreen extends Activity
{
private static final int SPLASH_TIME = 10 * 1000;// 3 seconds
Button logo;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// requestWindowFeature(Window.FEATURE_NO_TITLE);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.splashscreen);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
try {
new Handler().postDelayed(new Runnable() {
public void run() {
Intent intent = new Intent(Splashscreen.this,MainActivity.class);
startActivity(intent);
Splashscreen.this.finish();
//overridePendingTransition(R.anim.fade_in, R.anim.fade_out);
}
}, SPLASH_TIME);
new Handler().postDelayed(new Runnable() {
public void run() {
}
}, SPLASH_TIME);
} catch(Exception e){}
// METHOD 1
/****** Create Thread that will sleep for 5 seconds *************/
Thread background = new Thread() {
public void run() {
try {
// Thread will sleep for 5 seconds
sleep(50*1000);
// After 5 seconds redirect to another intent
Intent i=new Intent(getBaseContext(),MainActivity.class);
startActivity(i);
//Remove activity
finish();
} catch (Exception e) {
}
}
};
background.start();
}

how to change images on imageView after some interval

I have a problem that I want to paste images on ImageView in Android and that images are periodically changed after some interval. Means one by one images shown in ImageView. I am doing this with the help of Thread in java but I got some problem that Thread is not attached and something. Please review my code given below and tell me the exact error and how to remove that error or give me some diffrent way for doing this.
package com.ex.thread;
import com.ex.thread.R;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.widget.ImageView;
public class thread extends Activity implements Runnable{
/** Called when the activity is first created. */
public static Integer[] mThumbIds = {
R.drawable.al1,R.drawable.al2,R.drawable.al3,R.drawable.al4,
};
Thread th;
ImageView iv;
public void run()
{
for(int i=0;i<3;i++)
{
iv.setImageResource(mThumbIds[i]);
System.out.println("Sanat Pandey");
try{
Thread.sleep(3000);
}catch(Exception e)
{
System.out.println(e);
}
}
}
public void create()
{
Thread th = new Thread(new thread());
th.start();
try{
Thread.sleep(3000);
}catch(Exception e)
{
System.out.println(e);
}
}
#Override
public void onCreate(Bundle savedInstace)
{
super.onCreate(savedInstace);
setContentView(R.layout.main);
create();
}
}
Try this..It works out well...
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);``
//
//
int []imageArray={R.drawable.img1,R.drawable.img2,R.drawable.img3};
final Handler handler = new Handler();
Runnable runnable = new Runnable() {
int i=0;
public void run() {
imageView.setImageResource(imageArray[i]);
i++;
if(i>imageArray.length-1)
{
i=0;
}
handler.postDelayed(this, 50); //for interval...
}
};
handler.postDelayed(runnable, 2000); //for initial delay..
}
You can't use things in the UI thread from a background one. So this call:
iv.setImageResource(mThumbIds[i]);
Has to be done in the main thread. In fact you probably don't need a background thread at all to get the effect you're looking for. You can make that just an activity, no need to implement runnable. and then do something like this:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
iv = (ImageView) findViewById(R.id.yourImageViewID);
int i = 0;
Runnable r = Runnable(){
public void run(){
iv.setImageResource(mThumbIds[i]);
i++;
if(i >= mThumbIds.length){
i = 0;
}
iv.postDelayed(r, 3000); //set to go off again in 3 seconds.
}
};
iv.postDelayed(r,3000); // set first time for 3 seconds
Try this
it's working
public class vv extends Activity {
int b[] = {R.drawable.a, R.drawable.m, R.drawable.b, R.drawable.j, R.drawable.er, R.drawable.chan, R.drawable.vv};
public ImageView i;
int z = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
i = (ImageView) findViewById(R.id.image);
i.setImageResource(b[0]);
Thread timer = new Thread() {
public void run() {
try {
sleep(2000);
for (z = 0; z < b.length + 2; z++) {
if (z < b.length) {
sleep(2000);
runOnUiThread(new Runnable() {
public void run() {
i.setImageResource(b[z]);
}
});
} else {
z = 0;
}
}
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
System.out.println("finally");
}
}
};
timer.start();
}
}
try this code.the images was saved in drawable. please do insert a imageview in xml code. noted that the time interval for the following code is 1 sec.
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.ImageView;
public class MainActivity extends AppCompatActivity {
public ImageView iv;
public static Integer[] mThumbIds = {
R.drawable.pic1,R.drawable.pic2,R.drawable.pic3,R.drawable.pic4};
int i;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
iv = (ImageView) findViewById(R.id.imageView);
i=0;
t.start();
}
Thread t = new Thread() {
#Override
public void run() {
try {
while (!isInterrupted()) {
Thread.sleep(1000);
runOnUiThread(new Runnable() {
#Override
public void run() {
iv.setImageResource(mThumbIds[i]);
i++;
if(i >= mThumbIds.length){
i = 0;
}}});}}
catch (InterruptedException e) {
}}};
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final int img[] = {R.drawable.flower1, R.drawable.flower2, R.drawable.flower3, R.drawable.flower4};
layout = (RelativeLayout) findViewById(R.id.activity_main);
final Handler handler=new Handler();
Runnable runnable = new Runnable() {
int i = 0;
#Override
public void run() {
layout.setBackgroundResource(img[i]);
i++;
if (i > img.length - 1) {
i = 0;
}
handler.postDelayed(this, 4000); //for interval 4s..
}
};handler.postDelayed(runnable, 100); //for initial delay..
}

Categories

Resources