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>
Related
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();
}
}
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 will make rooting Tool but I want 'if I press the button, Download Manager turn on' code. Please tell me
and I'm going to start developing with the help ..
public class MainActivity extends Activity
{
DownLoadComplte mDownload;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void startDownload()
{
DownloadManager mManager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
Request mRqRequest = new Request(Uri.parse("http://androidtrainningcenter.blogspot.in/2012/11/android-webview-loading-custom-html-and.html"));
mRqRequest.setDescription("This is File");
mRqRequest.setDestinationUri(Uri.parse("/sdcard/download"));
long idDownLoad=mManager.enqueue(mRqRequest);
}
#Override
protected void onStart() {
super.onStart();
mDownload = new DownLoadComplte();
registerReceiver(mDownload, new IntentFilter(
DownloadManager.ACTION_DOWNLOAD_COMPLETE));
}
#Override
protected void onDestroy() {
super.onDestroy();
unregisterReceiver(mDownload);
}
private class DownLoadComplte extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equalsIgnoreCase(
DownloadManager.ACTION_DOWNLOAD_COMPLETE)) {
Toast.makeText(context, "Download Complte", Toast.LENGTH_LONG)
.show();
}
}
}}
XML CODE
<?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">
<Button
android:text="Start Download"
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="onClick"/>
</LinearLayout>
Thank you for any help & really appreciate
Replace your code with this:
Java Code:
public void startDownload(View v)
{//do something..
}
XML Code:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="fill_parent"
android:layout_height="fill_parent">
<Button
android:text="Start Download"
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="startDownload"/> // Change this
</LinearLayout>
I want to show a "boot logo" or image before of setting the final layout of the main activity. Actually i do this:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.authors);
mContext = this;
showAuthors();
where showAuthors run this:
private void showAuthors()
{
setContentView(R.layout.authors);
Thread logoTimer = new Thread() {
public void run() {
try {
sleep(3000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
}
}
};
logoTimer.start();
try {
logoTimer.join();
setContentView(R.layout.activity_main);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
the file authors.xml ( R.layout.authors ) is the same of activity_main, but clean, containing just a pair of strings with my name and email:
<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"
android:background="#raw/call2"
android:src="#raw/call2"
android:scaleType = "centerCrop"
tools:context=".MainActivity" >
<TextView
android:id="#+id/authorsTV"
android:textColor="#FF6600"
android:textSize="16.5sp"
android:textStyle="bold"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_marginLeft="33dp"
android:text="#string/serviceStatus" />
</RelativeLayout>
the problem is: all works, but the screen is all white as an empty layout.
where i'm doing wrong? thank you all if consider to reply me!
You should not call thread.join from the main thread, because you can get an ANR crash.
Here's how to do it with minimal changes to your existing code. Remove everything after logoTimer.start(), and put this inside the try block, immediately after sleep(3000):
runOnUiThread(new Runnable(){
public void run(){
setContentView(R.layout.activity_main);
}
});
But it would be cleaner to rewrite that whole method like this:
private void showAuthors()
{
setContentView(R.layout.authors);
new Handler().postDelayed( new Runnable(){
public void run(){
setContentView(R.layout.activity_main);
}
}, 3000);
}
First you have two ways of showing a splash screen,
1.with activity
public class SplashActivity extends Activity implements Runnable
{
#Override
protected void onCreate(Bundle savedInstanceState)
{
...
setContentView(R.layout.act_spalsh);
hideSplashActivity();
}
private void hideSplashActivity()
{
new Handler().postDelayed(this, 3000);
}
#Override //from runnable
public void run()
{
startActivity(new Intent(this, MainActivity .class));
finish();
}
2.with dialog
public class MainActivity extends Activity implements Runnable
{
Dialog splashDialog;
#Override
protected void onCreate(Bundle savedInstanceState)
{
...
splashDialog = new Dialog(this,android.R.style.Theme_Black_NoTitleBar_Fullscreen);
splashDialog.setContentView(R.layout.dlg_splash);
splashDialog.show();
hideSplashDialog();
setContentView(R.layout.act_main);
}
private void hideSplashDialog()
{
new Handler().postDelayed(this, 3000);
}
#Override //from runnable
public void run()
{
splashDialog.dismiss();
splashDialog = null;
}
I prefer using dialog unless you have some trouble with that
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.