I designed an app that has two buttons one to start a counter and a second one to stop. Starting the counter works fine but when I click the stop button the app crashes.
What is the problem with my code?
public class MainActivity extends AppCompatActivity {
int i=1;
TextView txt;
Counter ct;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void bustart(View view) {
startTime();
}
public void buop(View view) {
ct.cancel();
}
public void startTime(){
i=1;
txt=(TextView)findViewById(R.id.textView);
ct=new Counter(5000,1000);
ct.start();
}
public class Counter extends CountDownTimer{
Counter(long millisInFuture,long countDownInterval){
super(millisInFuture,countDownInterval);
}
public void onTick(long millisUntilFinished) {
txt.setText(String.valueOf(i));
i++;
}
public void onFinish() {
txt.setText("Done");
}
}
}
Insure You Are give buop onClick to your Xml.,,Like that
<Button
android:id="#+id/btn1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:onClick="buop"
android:layout_centerInParent="true"
android:padding="20dp"
android:text="Cancel"
android:visibility="visible"
/>
<Button
android:id="#+id/btn2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:onClick="bustart"
android:layout_centerInParent="true"
android:padding="20dp"
android:text="Start"
android:visibility="visible"
android:layout_below="#+id/btn1"
/>
Take boolean to ensure timer is start other if you cancel button without start is crash generate. otherwise your code fine...
boolean timerStart=false;
public void bustart(View view) {
if(!timerStart) {
timerStart=true;
startTime();
}
}
public void buop(View view) {
if(timerStart) {
timerStart=false;
ct.cancel();
}
}
Related
So I am using SpeechRecognizer along with RecognitionListener to recognize user speech. It works fine but the problem is when I tested it I noticed that it doesn't call onEndOfSpeech after I finishes talking. It waits around 7 to 10 seconds and then onEndOfSpeech and onResult are called. I don' know the reason for this delay.
Here is the code:
public class MainActivity extends AppCompatActivity {
protected static final int REQUEST_OK = 1;
SpeechRecognizer sr;
TextView mText;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mText = (TextView) findViewById(R.id.text1);
RecognitionListener recognitionListener=new RecognitionListener() {
#Override
public void onReadyForSpeech(Bundle bundle) {
Toast.makeText(MainActivity.this,"Start takling",Toast.LENGTH_SHORT).show();
}
#Override
public void onBeginningOfSpeech() {
}
#Override
public void onRmsChanged(float v) {
}
#Override
public void onBufferReceived(byte[] bytes) {
}
#Override
public void onEndOfSpeech() {
Toast.makeText(MainActivity.this,"onEndOfSpeech",Toast.LENGTH_SHORT).show();
}
#Override
public void onError(int i) {
}
#Override
public void onResults(Bundle bundle) {
Toast.makeText(MainActivity.this,"onResults",Toast.LENGTH_SHORT).show();
ArrayList<String> voiceResults =
bundle.getStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION);
if (voiceResults != null) {
String text = voiceResults.get(0);
Toast.makeText(MainActivity.this,text,Toast.LENGTH_SHORT).show();
}
}
#Override
public void onPartialResults(Bundle bundle) {
}
#Override
public void onEvent(int i, Bundle bundle) {
}
};
sr = SpeechRecognizer.createSpeechRecognizer(this);
sr.setRecognitionListener(recognitionListener);
findViewById(R.id.button1).setOnClickListener( new View.OnClickListener() {
#Override
public void onClick(View v)
{
Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, "en-US");
sr.startListening(intent);
}
});
}
#Override
protected void onDestroy() {
super.onDestroy();
sr.destroy();
}
}
activity_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=".MainActivity" >
<TextView
android:id="#+id/text1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="132dp"
android:text="..." ></TextView>
<ImageButton
android:id="#+id/button1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/text1"
android:layout_centerHorizontal="true"
android:layout_margin="10dp"
android:layout_marginTop="37dp"
android:src="#android:drawable/ic_btn_speak_now" ></ImageButton>
</RelativeLayout>
I finally got YouTube live streaming to play on my app, the only inconvenience is when I go into full screen mode the player stops and it doesn't play anymore, also sometimes when I stop the player and try to play again it plays for 2 seconds then stops, I know YouTube live is on beta stage but that doesn't mean we couldn't find a solution for this, does anybody have any suggestions on how to solve this issue?
LiveYouTube.java
public class LiveYouTube extends YouTubeBaseActivity implements YouTubePlayer.OnInitializedListener {
public static final String API_KEY = "AIzaSyBMwV1heA9q75LkybRCK5SXXTJWADRtmDh4";
//http://youtu.be/<VIDEO_ID>
public static final String VIDEO_ID = "URS94beDtJA";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
/** attaching layout xml **/
setContentView(R.layout.youtubelive);
/** Initializing YouTube player view **/
YouTubePlayerView youTubePlayerView = (YouTubePlayerView) findViewById(R.id.youtube_player);
youTubePlayerView.initialize(API_KEY, this);
}
#Override
public void onInitializationFailure(Provider provider, YouTubeInitializationResult result) {
Toast.makeText(this, "Failured to Initialize!", Toast.LENGTH_LONG).show();
}
#Override
public void onInitializationSuccess(Provider provider, YouTubePlayer player, boolean wasRestored) {
/** add listeners to YouTubePlayer instance **/
player.setPlayerStateChangeListener(playerStateChangeListener);
player.setPlaybackEventListener(playbackEventListener);
/** Start buffering **/
if (!wasRestored) {
player.cueVideo(VIDEO_ID);
}
}
private PlaybackEventListener playbackEventListener = new PlaybackEventListener() {
#Override
public void onBuffering(boolean arg0) {
}
#Override
public void onPaused() {
}
#Override
public void onPlaying() {
}
#Override
public void onSeekTo(int arg0) {
}
#Override
public void onStopped() {
}
};
private PlayerStateChangeListener playerStateChangeListener = new PlayerStateChangeListener() {
#Override
public void onAdStarted() {
}
#Override
public void onError(ErrorReason arg0) {
}
#Override
public void onLoaded(String arg0) {
}
#Override
public void onLoading() {
}
#Override
public void onVideoEnded() {
}
#Override
public void onVideoStarted() {
}
};
youtubelive.xml
<LinearLayout 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:orientation="vertical" xmlns:app="http://schemas.android.com/apk/res-auto">
<RelativeLayout
android:id="#+id/rel"
android:layout_width="fill_parent"
android:layout_height="#dimen/play_list_row_height"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:background="#c00311" >
<TextView
android:id="#+id/tv_title"
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:ellipsize="end"
android:gravity="center"
android:text="LIVE VIDEO"
android:textColor="#color/video_descrption_top_bar_text"
android:textSize="#dimen/video_view_top_bar_font_size"
android:textStyle="bold" />
</RelativeLayout>
<com.google.android.youtube.player.YouTubePlayerView
android:id="#+id/youtube_player"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#fff"
android:padding="0dp" />
<ImageView
android:id="#+id/logo"
android:layout_width="340dp"
android:layout_height="wrap_content"
android:layout_marginTop="-13dp"
android:src="#drawable/shadow_line" />
I am working on an app that is used to stream songs online. I am able to play the song on clicking on it.
The problem with me is that I have a CircularSeekBar in all the Activities and I need to manage it on all the screens. If a song is played from any activity CircularSeekBar should be visible on all the screens. What I am able to do is When a song is played I am able to show the seekbar on that particular activity but not able to manage that seekbar on any other activity.
Below is the sample of one of my xml files:
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/white"
android:orientation="vertical">
</LinearLayout>
<include layout="#layout/seek_bar_layout"></include>
</android.support.design.widget.CoordinatorLayout>
Please let me know how to manage that Seekbar on all the Activities.
Thanks in Advance.
You can't manage activity view when other is visible.
You can solve it by any boolean flag (for example: isSongPlaying = false). When you start playing your song set it to true. In each activity in onResume check that flag and show / hide your SeekBar.
Try to avoid using public static and use any other way.
EDIT:
According to your comments i created very simple example how you can solve your problem using service. Remember this code need much improvements.
SongService
public class SongService extends Service {
ActivityManager activityManager;
IBinder iBinder;
boolean playingSong = false;
Worker worker;
public SongService() {
iBinder = new MyBinder();
}
private void playSong(String path) {
if(worker != null) {
worker.cancel(true);
}
worker = new Worker();
worker.execute();
}
#Nullable
#Override
public IBinder onBind(Intent intent) {
return iBinder;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
return super.onStartCommand(intent, flags, startId);
}
private class Worker extends AsyncTask<Void, Integer, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
playingSong = true;
}
#Override
protected Void doInBackground(Void... params) {
for (int i = 100; i > -1; i--) {
publishProgress(i);
try {
Thread.sleep(100l);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
return null;
}
#Override
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
if (activityManager != null) {
activityManager.publishProgress(values[0]);
}
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
playingSong = false;
activityManager.onSongFinish();
}
}
public class MyBinder extends Binder {
public SongService getSongService() {
return SongService.this;
}
public void BindView(ActivityManager activityManager) {
SongService.this.activityManager = activityManager;
}
public void playSong(String path) {
SongService.this.playSong(path);
}
public boolean isPlayingSong() {
return playingSong;
}
}
public interface ActivityManager {
void publishProgress(int progress);
void onSongFinish();
}
}
MainActivity:
public class MainActivity
extends AppCompatActivity
implements ServiceConnection, SongService.ActivityManager {
TextView progress;
Button play;
Button next;
SongService.MyBinder myBinder;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
progress = (TextView) findViewById(R.id.progress);
play = (Button) findViewById(R.id.play);
play.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(myBinder != null) {
//Your path to song
myBinder.playSong("");
play.setEnabled(false);
}
}
});
next = (Button) findViewById(R.id.next);
next.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, MainActivity2.class);
startActivity(intent);
}
});
}
#Override
protected void onStart() {
super.onStart();
Intent mIntent = new Intent(this, SongService.class);
bindService(mIntent, this, BIND_AUTO_CREATE);
}
#Override
protected void onStop() {
super.onStop();
unbindService(this);
}
#Override
public void onServiceConnected(ComponentName name, IBinder service) {
if(service instanceof SongService.MyBinder) {
myBinder = (SongService.MyBinder) service;
myBinder.BindView(this);
if (myBinder.isPlayingSong()) {
play.setEnabled(false);
}
else {
play.setEnabled(true);
}
}
}
#Override
public void onServiceDisconnected(ComponentName name) {
myBinder = null;
}
#Override
public void publishProgress(int progress) {
this.progress.setText("Progress: " + progress);
}
#Override
public void onSongFinish() {
play.setEnabled(true);
}
}
MainActivity2
This activity class looks exacly the same like MainActivity but have different layout file.
MainActivity - Layout:
<?xml version="1.0" encoding="utf-8"?>
<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="com.example.aszymanski2.serviceanddelegatepatternexample.MainActivity">
<TextView
android:id="#+id/progress"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<Button
android:text="Play"
android:id="#+id/play"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"/>
<Button
android:text="SecondActivity"
android:id="#+id/next"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"/>
</RelativeLayout>
MainActivity2 - Layout:
<?xml version="1.0" encoding="utf-8"?>
<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="com.example.aszymanski2.serviceanddelegatepatternexample.MainActivity">
<TextView
android:id="#+id/progress"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<Button
android:text="Play"
android:id="#+id/play"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"/>
<Button
android:text="Back"
android:id="#+id/next"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"/>
</RelativeLayout>
I am working on Payment based application. so in this case in first screen user has to selectproduct items and moves to next screen, in screen 2 he has to choose the payment method either
cash or card. in screen one the store names are displaying from web service. i have handled that
in A sync Task.if he choose cash mode from screen 2, the payment will be get authorized and
displays the respective message.
But in case if he wants to go back the product screen(screen 1) from the screen 2,screen 1 will
not call the web service again. it should be as the same way . but if the payment is completed it
will be refreshed. how do i achieve this? Do i mention the whole operation in on Resume method.
Check this below example by Commonsware, hope this helps you.
public class RotationAsync extends Activity {
private ProgressBar bar=null;
RotationAwareTask task=null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
bar=(ProgressBar)findViewById(R.id.progress);
Button next = (Button) findViewById(R.id.next);
next.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
Intent i = new Intent (RotationAsync.this, First.class);
startActivity(i);
}
});
task=(RotationAwareTask)getLastNonConfigurationInstance();
if (task==null) {
task=new RotationAwareTask(this);
task.execute();
}
else {
task.attach(this);
updateProgress(task.getProgress());
if (task.getProgress()>=100) {
markAsDone();
}
}
}
#Override
public Object onRetainNonConfigurationInstance() {
task.detach();
return(task);
}
void updateProgress(int progress) {
bar.setProgress(progress);
}
void markAsDone() {
findViewById(R.id.completed).setVisibility(View.VISIBLE);
}
static class RotationAwareTask extends AsyncTask<Void, Void, Void> {
RotationAsync activity=null;
int progress=0;
RotationAwareTask(RotationAsync activity) {
attach(activity);
}
#Override
protected Void doInBackground(Void... unused) {
for (int i=0;i<20;i++) {
SystemClock.sleep(500);
publishProgress();
}
return(null);
}
#Override
protected void onProgressUpdate(Void... unused) {
if (activity==null) {
Log.w("RotationAsync", "onProgressUpdate() skipped -- no activity");
}
else {
progress+=5;
activity.updateProgress(progress);
}
}
#Override
protected void onPostExecute(Void unused) {
if (activity==null) {
Log.w("RotationAsync", "onPostExecute() skipped -- no activity");
}
else {
activity.markAsDone();
}
}
void detach() {
activity=null;
}
void attach(RotationAsync activity) {
this.activity=activity;
}
int getProgress() {
return(progress);
}
}
}
First.java
public class First extends Activity{
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.first);
Button b = (Button) findViewById(R.id.button1);
b.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
finish();
}
});
}
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="fill_parent"
android:layout_height="fill_parent"
>
<ProgressBar android:id="#+id/progress"
style="?android:attr/progressBarStyleHorizontal"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/>
<TextView android:id="#+id/completed"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Work completed!"
android:visibility="invisible"
/>
<Button
android:id="#+id/next"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Next" />
</LinearLayout>
first.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" >
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Back" />
</LinearLayout>
I am using the countdowntimer to countdown Here is my code:
public class countdownnow extends Activity{
TextView tv;
private CDwnTimer countDownTimer;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.countdown_disp);
tv = (TextView)findViewById(R.id.textView1);
countDownTimer = new MalibuCountDownTimer(30000, 1050);
countDownTimer.start();
}
// CountDownTimer class
public class CDwnTimer extends CountDownTimer {
public CDwnTimer(long startTime, long interval) {
super(startTime, interval);
}
#Override
public void onFinish() {
tv.setText("00");
}
#Override
public void onTick(long millisUntilFinished) {
int convert = (int) millisUntilFinished/1000;
String testString = String.format("%02d",convert);
CharSequence cs = new String(testString);
tv.setText(cs);
}
}
}
Initially this works fine but when I leave this activity and then go to another activity then come back, the textview does not countdown anymore? TextView tv continues to run through the line but it does not update. Is the activity freed up and initialize the same id of the Textview? Any hints would be great. Thanks.
How did you leave the activity?
I simulated your program and when I leave MainActivity to the OtherActivity and go back, the textView keep counting down. The code is as below:
public class MainActivity extends Activity {
private CDwnTimer countDownTimer;
private Button btn;
private TextView tv;
#Override
public void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
tv = (TextView)findViewById(R.id.tv);
btn = (Button) findViewById(R.id.btnEnter);
btn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// call sendMessage method
Intent startActivityIntent =new Intent(MainActivity.this, OtherActivity.class);
MainActivity.this.startActivity(startActivityIntent);
}
});
countDownTimer = new CDwnTimer(30000, 1050);
countDownTimer.start();
}
// CountDownTimer class
public class CDwnTimer extends CountDownTimer {
public CDwnTimer(long startTime, long interval) {
super(startTime, interval);
}
#Override
public void onFinish() {
tv.setText("00");
}
#Override
public void onTick(long millisUntilFinished) {
int convert = (int) millisUntilFinished/1000;
String testString = String.format("%02d",convert);
CharSequence cs = new String(testString);
tv.setText(cs);
}
}
}
main.xml file for MainActivity layout:
<LinearLayout 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:orientation="vertical">
<TextView
android:id="#+id/tv"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="TextView"
android:layout_weight="6"/>
<Button
android:id="#+id/btnEnter"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="282dp"
android:layout_marginLeft="21dp"
android:text="Button"
android:layout_weight="2"/>
</LinearLayout>