Unable to hide Action Bar before starting another activity - android-layout

I'm trying to first create an activity, then after 2 seconds, I want to hide the action bar and then after another 2 secs, I want to start another activity but this code - getActionBar().hide() isn't working. Here is my code -
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_start);
//final ActionBar actionbar = getActionBar();
Thread timer1 = new Thread() {
public void run(){
try{
sleep(2000);
} catch(InterruptedException e){
e.printStackTrace();
} finally{
getActionBar().hide();
}
}
};
timer1.start();
Thread timer2 = new Thread() {
public void run(){
try{
sleep(2000);
} catch(InterruptedException e){
e.printStackTrace();
} finally{
Intent intent = new Intent("app.lost_and_found_0.STARTINGPOINT");
startActivity(intent);
}
}
};
timer2.start();
}
Is there something wrong I'm doing wrong?
My application theme is set to Theme.Holo.Light in manifest file.

Use getSupportActionBar() instead of getActionBar(). As on the class, you need to extend ActionBarActivity.

Related

Go to another activity not main activity after splash screen

I have a splash screen in which i am checking user is logged in or not if logged in go to dashboard otherwise go to login activity. I am using sharedpref. Issue is (which I am unable to resolve) after splash screen login screen appears for a brief moment than dashboard. Splash > Login > Dash what i Want is Splash > Dash (if user logged in). Login is the main activity of my project. Here is the code:
public class SplashScreen extends AppCompatActivity {
private SessionManager sessionManager;
private BroadcastReceiver broadcastReceiver;
private SharedPreferences prefs;
private boolean isLogin;
private int accessID;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
sessionManager = new SessionManager(this);
broadcastReceiver = new CheckNetStatus();
broadcastIntent();
}
#RequiresApi(api = Build.VERSION_CODES.M)
#Override
protected void onResume(){
super.onResume();
new CheckNetStatus().onReceive(SplashScreen.this,new
Intent(ConnectivityManager.CONNECTIVITY_ACTION));
try {
prefs = getSharedPreferences(SessionManager.PREF_NAME, 0); // Declare
SharedPreferences
accessID = prefs.getInt(SessionManager.KEY_ACCESSID, 0); // get Access Id from
SharedPreferences
isLogin = Utils.getLoginStatus(SplashScreen.this); // Check Login is true or false
} catch (Exception e) {
e.printStackTrace();
}
Thread splashTread = new Thread() {
#RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
#Override
public void run() { // run thread
try {
synchronized (this) {
Thread.sleep(3000); // Screen stay for 3 sec.
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (isLogin)
{
// if (accessID == 0) { // access Id is ZERO open AddMoneyActivity.class
// try {
// } catch (Exception e) {
// e.printStackTrace();
// }
// } else if (accessID == 1) {// access Id is ONE open
ProfileStepOneActivity.class
try {
Intent intent = new Intent(SplashScreen.this, Dashboard.class);
startActivity(intent);
finishAffinity(); // Finish stack
} catch (Exception e) {
e.printStackTrace();
}
} else {// Login is False goto Login Activity
try {
Intent intent = new Intent(SplashScreen.this, MainActivity.class);
startActivity(intent);
finish();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
};
splashTread.start();
}
public void broadcastIntent() {
registerReceiver(broadcastReceiver, new
IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));
}
#Override
protected void onPause() {
super.onPause();
try {
LocalBroadcastManager.getInstance(this).unregisterReceiver(broadcastReceiver);
//unregisterReceiver(broadcastReceiver);
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
protected void onStop(){
super.onStop();
try {
LocalBroadcastManager.getInstance(this).unregisterReceiver(broadcastReceiver);
// unregisterReceiver(broadcastReceiver);
} catch (Exception e) {
e.printStackTrace();
}
}
}
My mistake....i was redirecting to main activity ie login activity in netstats class(where i was checking the net connection) ie why it was showing login screen for a moment issue resolved now

Execute Button in seconds Android Studio

Is there a way for a button to be executed in seconds without touching it.
The following code execute the button in one second but after i touch the button. My question is can this be achieved without touching the button?
View.OnClickListener mButtonStartListener = new View.OnClickListener() {
public void onClick(View v) {
try {
mHandler.removeCallbacks(hMyTimeTask);
// Parameters
// r The Runnable that will be executed.
// delayMillis The delay (in milliseconds) until the Runnable will be executed.
mHandler.postDelayed(hMyTimeTask, 1000); // delay 1 second
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
};
private Runnable hMyTimeTask = new Runnable() {
public void run() {
nCounter++;
hTextView.setText("Hallo from thread counter: " + nCounter);
}
};
/**
*
*/
View.OnClickListener mButtonStopListener = new View.OnClickListener() {
public void onClick(View v) {
mHandler.removeCallbacks(hMyTimeTask);
}
};
You may simulate click event by following code
View.performClick();
originally posted at https://stackoverflow.com/a/4877526/5329101.
Try .onLoadCompleteListener instead of .onClickListener

Android MediaPlayer seek bar current position thread issues

Hi I am new to android and I am learning by example. I am trying to make an activity that has a list view of all songs in my raw folder with media player controls at the bottom. I have everything working so far but I can't seem to get the SeekBar to stop force closing.
Here is the code:
public class music extends ListActivity implements Runnable {
private ArrayList<sound> mSounds = null;
private soundadapter mAdapter = null;
private ImageButton playbtn;
private SeekBar seekbar;
private int total;
private MediaPlayer mp = null;
private TextView selelctedFile = null;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.music);
selelctedFile = (TextView) findViewById(R.id.selectedfile);
seekbar = (SeekBar) findViewById(R.id.seekbar);
seekbar.setProgress(0);
// create a simple list
mSounds = new ArrayList<sound>();
sound s = new sound();
s.setDescription("Rudolph The Red Nosed Reindeer");
s.setSoundResourceId(R.raw.rudolphtherednosereindeer);
mSounds.add(s);
s = new sound();
s.setDescription("Battery");
s.setSoundResourceId(R.raw.battery);
mSounds.add(s);
mAdapter = new soundadapter(this, R.layout.listitem, mSounds);
setListAdapter(mAdapter);
playbtn = (ImageButton) findViewById(R.id.play);
playbtn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
try {
if (mp.isPlaying()) {
mp.pause();
playbtn.setImageResource(android.R.drawable.ic_media_play);
} else {
mp.start();
playbtn.setImageResource(android.R.drawable.ic_media_pause);
}
} catch (Exception e) {
e.printStackTrace();
// TODO: handle exception
}
}
});
}
#Override
public void onListItemClick(ListView parent, View v, int position, long id) {
sound s = (sound) mSounds.get(position);
if (mp != null) {
mp.reset();
mp.release();
}
mp = MediaPlayer.create(this, s.getSoundResourceId());
selelctedFile.setText(s.getDescription());
playbtn.setImageResource(android.R.drawable.ic_media_pause);
mp.start();
total = mp.getDuration();
seekbar.setMax(total);
seekbar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onStopTrackingTouch(SeekBar seekbar) {
// TODO Auto-generated method stub
}
#Override
public void onStartTrackingTouch(SeekBar seekbar) {
// TODO Auto-generated method stub
}
#Override
public void onProgressChanged(SeekBar seekBar, int progress,
boolean fromUser) {
// TODO Auto-generated method stub
if (fromUser) {
mp.seekTo(progress);
seekBar.setProgress(progress);
}
}
});
Thread currentThread = new Thread(this);
currentThread.start();
}
#Override
public void run() {
// TODO Auto-generated method stub
try {
while (mp != null) {
int currentPosition = mp.getCurrentPosition();
Message msg = new Message();
msg.what = currentPosition;
threadHandler.sendMessage(msg);
Thread.sleep(100);
}
}
catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
}
}
private Handler threadHandler = new Handler() {
public void handleMessage(Message msg) {
// super.handleMessage(msg);
// txt.setText(Integer.toString(msg.what));
seekbar.setProgress(msg.what);
}
};
#Override
protected void onPause() {
// TODO Auto-generated method stub
mp.stop();
mp.release();
mp = null;
}
#Override
protected void onDestroy() {
// TODO Auto-generated method stub
if(mp != null) {
mp.stop();
mp.release();
mp = null;
}
}
}
and here is the error i keep getting when i click several times on different songs:
04-14 02:53:00.452: W/dalvikvm(27452): threadid=19: thread exiting with uncaught exception (group=0x40018560)
04-14 02:53:00.466: E/AndroidRuntime(27452): FATAL EXCEPTION: Thread-22
04-14 02:53:00.466: E/AndroidRuntime(27452): java.lang.IllegalStateException
04-14 02:53:00.466: E/AndroidRuntime(27452): at android.media.MediaPlayer.getCurrentPosition(Native Method)
04-14 02:53:00.466: E/AndroidRuntime(27452): at net.cybercore.collapsingfromwithin.music.run(music.java:145)
04-14 02:53:00.466: E/AndroidRuntime(27452): at java.lang.Thread.run(Thread.java:1019)
Line error 145 is :
int currentPosition = mp.getCurrentPosition();
I cannot for the life of me figure out why it works for 3 or 4 times playing and then it kills the app.
Any help is appreciated. I have already looked at several other sites for examples including http://www.androidhive.info/2012/03/android-building-audio-player-tutorial/ and http://www.androiddevblog.net/android/playing-audio-in-android
**
UPDATE
**
I think I fixed it. thanks for your help I found Thread using for seekbar on android mediaplayer so i changed it to
#Override
public void run() {
// TODO Auto-generated method stub
try {
while (mp != null) {
int currentPosition = mp.getCurrentPosition();
Message msg = new Message();
msg.what = currentPosition;
threadHandler.sendMessage(msg);
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
System.out.println("interrupt exeption" + e);
}
}
}
catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
System.out.println("My exeption" + e);
}
}
I still get the errors but they are not killing my app. I don't think this is right way to do it but its working.
You should prepare your media player when instanciating it.
A MediaPlayer object must first enter the Prepared state before playback can be started.
There are two ways (synchronous vs. asynchronous) that the Prepared state can be reached: either a call to prepare() (synchronous) which transfers the object to the Prepared state once the method call returns, or a call to prepareAsync() (asynchronous) which first transfers the object to the Preparing state after the call returns (which occurs almost right way) while the internal player engine continues working on the rest of preparation work until the preparation work completes. When the preparation completes or when prepare() call returns, the internal player engine then calls a user supplied callback method, onPrepared() of the OnPreparedListener interface, if an OnPreparedListener is registered beforehand via setOnPreparedListener(android.media.MediaPlayer.OnPreparedListener).
Read it here
so you should call mp.prepare() after instanciating the player.
also you should make sure the media player in playing to run the run method. I'd start by adding
mp.isPlaying() to the while line.
while (mp != null && mp.isPlaying()) {
...
}
IllegalStateException means that you are on an illegal state to call that method, like for instance, if the player is stopped.
I'm not sure, but I think this will stop the run method when you pause the music. So you should try to avoid this. I create a boolean to identify that the player is playing or paused and use it on the while.

onClick and setImagResource [Android] API 10

I'm trying to understand why it's occuring me the following problem.
I have an ImageView and i set an image to it, then i setup a onClickListener to it, so when you click to image it change the image (to a new image) by image01.setImageResource(R.drawable.newImage). After that i call a method where i check a condition, if it is true i change the image again to the default one.
But I can't see the change because it change immediately. I also insert a sleep to make it slower.
(By default in the xml code i setted the image to oldImage)
Ok... maybe it's not clear.. so let's see the CODE:
private void myMethod(){
ImageView image01 = (ImageView) findViewById(R.id.image01);
image01.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
//When you click on image it change!
image01.setImageResource(R.drawable.newImage);
checkImg(image01);
}
});
}
private void checkGame(ImageView img){
try{
Thread.sleep(1000);
if(condition)
img.setImageResource(R.drawable.oldImage);
}catch (Exception e) {
e.printStackTrace();
}
}
I saw immediately the oldImage. What's the problem?
Is it possible that the view change are not applied in myMethod() until all methods inside it will terminate?
Thanks in advance
Using Thread.sleep() method, you are actually making wait to main UI thread. The main UI thread's methods are not synchronized. Be aware of that.
Please go through the developers.android site for using of threads painlessly... before seeing the your useful code.
private void myMethod(){
ImageView image01 = (ImageView) findViewById(R.id.image01);
image01.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
//When you click on image it change!
image01.setImageResource(R.drawable.newImage);
checkGame(image01);
}
});
}
private void checkGame(ImageView img){
try{
// Thread.sleep(1000);
if(condition)
image01.postDelayed(new Runnable() {
#Override
public void run() {
image01.setImageResource(R.drawable.oldImage);
}
}, 2000);
}catch (Exception e) {
e.printStackTrace();
}
}

How to enable a button after 5 seconds

everyone! I need to make a Button disabled for 5 seconds, and the caption of the button must be "Skip" plus the time the button will stay disabled.
I have made a class CTimer that extends Thread, and defined the run method with run(Button). The run method receives the Button which Caption will be modified and is as follows:
public void run(Button skip){
for ( int i=5; i<0; i--)
{
skip.setText("Skip (" + i + ")");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
skip.setEnabled(true);
}
The problem is that the code does not work, any thouhts, anyone?
I have tried the following code & it works fine for me:
public class Main_TestProject extends Activity
{
private Button b;
private int index = 5;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
b = (Button) findViewById(R.id.my_button);
b.setEnabled(false);
hHandler.sendEmptyMessage(0);
}
private Handler hHandler = new Handler()
{
#Override
public void handleMessage(Message msg)
{
if(index > 0)
{
try
{
b.setText("Skip (" + String.valueOf(index) + ")");
index--;
Thread.sleep(1000);
hHandler.sendEmptyMessage(0);
}
catch (InterruptedException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
else
{
b.setEnabled(true);
}
}
};
}

Resources