[Q] How do I fix my issue with an infinite timer? - Java for Android App Development

Hi, I am trying to run a small app which is supposed to show a progress bar for appx. 3 seconds and then make it disappear. Currently the app starts the progress bar but it never stops and I'm not sure why as I don't see anything wrong with the code. Any help is appreciated @mmdeveloper10
Code:
import android.app.*;
import android.os.*;
import android.view.View;
import android.widget.Button;
import android.widget.*;
import java.util.*;
public class MainActivity extends Activity
{
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
int x = 1;
public void save(View v){
startTimer();
}
public void startTimer(){
Timer timer = new Timer();
timer.schedule(new TimerTask() {
@Override
public void run() {
runOnUiThread(new Runnable() {
@Override
public void run() {
if(x==1){
x++;
ProgressBar circle = (ProgressBar) findViewById(R.id.circle1);
circle.setVisibility(View.VISIBLE);
Button button = (Button) findViewById(R.id.button1);
button.setText("Saving...");
}
else if (x >= 3){
x++;
ProgressBar circle = (ProgressBar) findViewById(R.id.circle1);
circle.setVisibility(View.INVISIBLE);
Button button = (Button) findViewById(R.id.button1);
button.setText("World Saved.");
}
}
});
}
},0,1000);
}
}

If that is the whole code, then the problem is the else part of your timer task is never called. You should put a loop before the if statememt and a break statement in the else portion. Or better yet just use a loop put the else part outside the loop.
---------- Post added at 11:09 AM ---------- Previous post was at 11:05 AM ----------
Code:
@Override
public void run() {
while(x <= 3) {
if(x==1) {
...
x++;
} else {
...
}
//TODO: put 1 second delay codehere
}
Something like this....
Click to expand...
Click to collapse

Thanks so much for the quick reply. It is working as expected now.

Related

[Q] android sdk buttons

just copyed this of a website and added a button to it, can some tell me if its right or is there a much more simpler way?
package com.example.button;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class Main extends Activity {
Button button1;
Button button2;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
button1 = (Button)findViewById(R.id.button1);
button1.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
setContentView(R.layout.main2);
}
}
);
button2 = (Button)findViewById(R.id.button2);
button2.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
setContentView(R.layout.main2);
}
}
);
}
}

CountDownTimer suggestions

Hello, I'm making this app which uses a CountdownTimer on its main activity which starts at a certain time. So far I've been able to set up the Timer and the BroadcastReceiver. The problem occurs when starting the timer. This is the code:
Code:
public class MainActivity extends Activity{
public static TextView countdown;
[user=439709]@override[/user]
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
countdown = (TextView) findViewById(R.id.textview1);
getCountdownTime();
}
public void getCountdownTime(){
//do some stuff
long time = //result from actions
//here I setup the AlarmManager
c.set(Calendar.HOUR_OF_DAY, hour);
c.set(Calendar.MINUTE, minute);
// Put time in an intent
Intent intent = new Intent(this, AlarmReceiver.class);
intent.putExtra("alarm_message", "Alarm pending");
intent.putExtra("time_remaining", time);
PendingIntent sender = PendingIntent.getBroadcast(this, 1234,
intent, PendingIntent.FLAG_UPDATE_CURRENT);
// Get the AlarmManager service
AlarmManager am = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
am.set(AlarmManager.RTC_WAKEUP, c.getTimeInMillis(), sender);
public static void startTimer(final long millisInFuture, long refreshMillis) {
timer = new CountDownTimer(millisInFuture, refreshMillis) {
SimpleDateFormat formatter = new SimpleDateFormat("mm:ss");
[user=439709]@override[/user]
public void onFinish() {
System.out.println("Timer Completed.");
countdown.setText("Finished");
}
[user=439709]@override[/user]
public void onTick(long millisUntilFinished) {
String time = formatter.format(millisUntilFinished);
countdown.setText(time);
}
}.start();
}
}
This is the alarm receiver class which calls the startTimer() method on the Activity:
Code:
public class AlarmReceiver extends BroadcastReceiver {
[user=439709]@override[/user]
public void onReceive(Context context, Intent intent) {
try {
Bundle bundle = intent.getExtras();
String message = bundle.getString("alarm_message");
long time = bundle.getLong("time_remaining");
MainActivity.startTimer(time, 1000);
} catch (Exception e) {
e.printStackTrace();
}
}
In the end, I get a findViewById NullPointerException.
But if i start the timer from the main Activity, not the Receiver, it runs fine.
Maybe I could use other ways to deal with it such as a service or an AsyncTask?
Is it the line in the onCreate method causing the NPE?
Note that you can only change views in the thread which created them!
The CountDownTimer is initialized in the thread of the BroadcastReceiver. That is why it cannot change the text of the TextView.
You will need to use a handler. Check this: http://www.vogella.com/articles/AndroidBackgroundProcessing/article.html#handler
Can you please help me with the code? I've never worked with handlers before. I had no idea what they were till I read your link.
Sent from my One S using Tapatalk 2
Chris95X8 said:
Can you please help me with the code? I've never worked with handlers before. I had no idea what they were till I read your link.
Sent from my One S using Tapatalk 2
Click to expand...
Click to collapse
Of course.
Add this to your Activity:
Code:
public Handler handler;
public void onCreate (Bundle savedInstanceState) {
...
handler = new Handler();
...
and then in your BroadcastReceiver:
Code:
[B]final[/B] long time = bundle.getLong("time_remaining");
handler.post(new Runnable() {
[user=439709]@override[/user]
public void run() {
((MainActivity) context).startTimer(time, 1000);
}
});
Change startTimer and the TextView to non-static.
---------- Post added at 11:07 PM ---------- Previous post was at 10:56 PM ----------
That should work.
---------- Post added at 11:09 PM ---------- Previous post was at 11:07 PM ----------
However, what I ask myself: What do you need the BroadcastReceiver for?
I would create a TimerTask and start that. (Google that)
There's no Handler variable in the AlarmReciever class though. Tried adding a public Handler handler and got a NPE.
Making startTimer non-static results in an error on MainActivity.startTimer(time, 1000);
I need a Broadcast Receiver because I'm using the Alarm Manager to start the countdown at a specific time (say 7:00 am).
Chris95X8 said:
There's no Handler variable in the AlarmReciever class though. Tried adding a public Handler handler and got a NPE.
Click to expand...
Click to collapse
Yes, that is because the methods were static. Try the new code. It should work now.
Nope, still got a NPE. BTW, I had to make the Context final in the onReceive method.
It results in a NPE. Because you need to cast context to MainActivity. (Look at my edited code)
However, wait a moment. I have got a better idea.
---------- Post added at 11:23 PM ---------- Previous post was at 11:20 PM ----------
My new idea.
Start the Timer/TimerTask in the onCreate method of MainActivity.
Launch the MainActivity with an Intent from the BroadcastReceiver.
There is no other way of doing it if you want it to start at a specific time.
Static methods will not work here!
---------- Post added at 11:25 PM ---------- Previous post was at 11:23 PM ----------
That way the Timer can be started if the app is launched by the BroadcastReceiver or by the user any other way.
From what I read, TimerTasks are not always good.
Isn't there something like an activity without UI that can update the views or something?
Sent from my One S using Tapatalk 2
Chris95X8 said:
From what I read, TimerTasks are not always good.
Isn't there something like an activity without UI that can update the views or something?
Sent from my One S using Tapatalk 2
Click to expand...
Click to collapse
You cannot easily modify a view from anything else than the Activity.
You could create a Sevice and call an update method of the MainActivity. This update method would need to be non static.
---------- Post added at 07:04 AM ---------- Previous post was at 06:56 AM ----------
Now I have done some searching. It appears to be even easier. There is already a class for that: android.os.CountDownTimer
Check this: http://stackoverflow.com/questions/10010684/android-countdown
Well yeah, that's what I'm using.
Sent from my One S using Tapatalk 2
Chris95X8 said:
Well yeah, that's what I'm using.
Sent from my One S using Tapatalk 2
Click to expand...
Click to collapse
Oh, I am sorry. I did not see that.
As already stated I would start it in the Activity and call the Activity by the BroadcastReceiver.
I see... Wouldn't the timer be always running though?
I'll think about it.
Sent from my One S using Tapatalk 2
Chris95X8 said:
I see... Wouldn't the timer be always running though?
I'll think about it.
Sent from my One S using Tapatalk 2
Click to expand...
Click to collapse
What do you meen with always running?
Hey I just wanted to say that I fixed my problem. Instead of starting the timer from the broadcast receiver, I started a service which runs the timer. On second tick, the service broadcasts intents that contain the remaining time which are received by another broadcast receiver on my UI class. Hence problem solved.
Sent from my One S using Tapatalk 2
Android Countdown Timer Run In Background
MainActivity.java
package com.countdowntimerservice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import java.text.SimpleDateFormat;
import java.util.Calendar;
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private Button btn_start, btn_cancel;
private TextView tv_timer;
String date_time;
Calendar calendar;
SimpleDateFormat simpleDateFormat;
EditText et_hours;
SharedPreferences mpref;
SharedPreferences.Editor mEditor;
@override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
init();
listener();
}
private void init() {
btn_start = (Button) findViewById(R.id.btn_timer);
tv_timer = (TextView) findViewById(R.id.tv_timer);
et_hours = (EditText) findViewById(R.id.et_hours);
btn_cancel = (Button) findViewById(R.id.btn_cancel);
mpref = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
mEditor = mpref.edit();
try {
String str_value = mpref.getString("data", "");
if (str_value.matches("")) {
et_hours.setEnabled(true);
btn_start.setEnabled(true);
tv_timer.setText("");
} else {
if (mpref.getBoolean("finish", false)) {
et_hours.setEnabled(true);
btn_start.setEnabled(true);
tv_timer.setText("");
} else {
et_hours.setEnabled(false);
btn_start.setEnabled(false);
tv_timer.setText(str_value);
}
}
} catch (Exception e) {
}
}
private void listener() {
btn_start.setOnClickListener(this);
btn_cancel.setOnClickListener(this);
}
@override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btn_timer:
if (et_hours.getText().toString().length() > 0) {
int int_hours = Integer.valueOf(et_hours.getText().toString());
if (int_hours<=24) {
et_hours.setEnabled(false);
btn_start.setEnabled(false);
calendar = Calendar.getInstance();
simpleDateFormat = new SimpleDateFormat("HH:mm:ss");
date_time = simpleDateFormat.format(calendar.getTime());
mEditor.putString("data", date_time).commit();
mEditor.putString("hours", et_hours.getText().toString()).commit();
Intent intent_service = new Intent(getApplicationContext(), Timer_Service.class);
startService(intent_service);
}else {
Toast.makeText(getApplicationContext(),"Please select the value below 24 hours",Toast.LENGTH_SHORT).show();
}
/*
mTimer = new Timer();
mTimer.scheduleAtFixedRate(new TimeDisplayTimerTask(), 5, NOTIFY_INTERVAL);*/
} else {
Toast.makeText(getApplicationContext(), "Please select value", Toast.LENGTH_SHORT).show();
}
break;
case R.id.btn_cancel:
Intent intent = new Intent(getApplicationContext(),Timer_Service.class);
stopService(intent);
mEditor.clear().commit();
et_hours.setEnabled(true);
btn_start.setEnabled(true);
tv_timer.setText("");
break;
}
}
private BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
@override
public void onReceive(Context context, Intent intent) {
String str_time = intent.getStringExtra("time");
tv_timer.setText(str_time);
}
};
@override
protected void onResume() {
super.onResume();
registerReceiver(broadcastReceiver,new IntentFilter(Timer_Service.str_receiver));
}
@override
protected void onPause() {
super.onPause();
unregisterReceiver(broadcastReceiver);
}
}
Timer_Service.java
package com.countdowntimerservice;
import android.app.Service;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Handler;
import android.os.IBinder;
import android.preference.PreferenceManager;
import android.support.annotation.Nullable;
import android.util.Log;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.TimeUnit;
public class Timer_Service extends Service {
public static String str_receiver = "com.countdowntimerservice.receiver";
private Handler mHandler = new Handler();
Calendar calendar;
SimpleDateFormat simpleDateFormat;
String strDate;
Date date_current, date_diff;
SharedPreferences mpref;
SharedPreferences.Editor mEditor;
private Timer mTimer = null;
public static final long NOTIFY_INTERVAL = 1000;
Intent intent;
@nullable
@override
public IBinder onBind(Intent intent) {
return null;
}
@override
public void onCreate() {
super.onCreate();
mpref = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
mEditor = mpref.edit();
calendar = Calendar.getInstance();
simpleDateFormat = new SimpleDateFormat("HH:mm:ss");
mTimer = new Timer();
mTimer.scheduleAtFixedRate(new TimeDisplayTimerTask(), 5, NOTIFY_INTERVAL);
intent = new Intent(str_receiver);
}
class TimeDisplayTimerTask extends TimerTask {
@override
public void run() {
mHandler.post(new Runnable() {
@override
public void run() {
calendar = Calendar.getInstance();
simpleDateFormat = new SimpleDateFormat("HH:mm:ss");
strDate = simpleDateFormat.format(calendar.getTime());
Log.e("strDate", strDate);
twoDatesBetweenTime();
}
});
}
}
public String twoDatesBetweenTime() {
try {
date_current = simpleDateFormat.parse(strDate);
} catch (Exception e) {
}
try {
date_diff = simpleDateFormat.parse(mpref.getString("data", ""));
} catch (Exception e) {
}
try {
long diff = date_current.getTime() - date_diff.getTime();
int int_hours = Integer.valueOf(mpref.getString("hours", ""));
long int_timer = TimeUnit.HOURS.toMillis(int_hours);
long long_hours = int_timer - diff;
long diffSeconds2 = long_hours / 1000 % 60;
long diffMinutes2 = long_hours / (60 * 1000) % 60;
long diffHours2 = long_hours / (60 * 60 * 1000) % 24;
if (long_hours > 0) {
String str_testing = diffHours2 + ":" + diffMinutes2 + ":" + diffSeconds2;
Log.e("TIME", str_testing);
fn_update(str_testing);
} else {
mEditor.putBoolean("finish", true).commit();
mTimer.cancel();
}
}catch (Exception e){
mTimer.cancel();
mTimer.purge();
}
return "";
}
@override
public void onDestroy() {
super.onDestroy();
Log.e("Service finish","Finish");
}
private void fn_update(String str_time){
intent.putExtra("time",str_time);
sendBroadcast(intent);
}
}

Need help with my app

Hi I'm working on a custom Android launcher I'm running into a little problem I have an image button that indicates show all applications but the problem is I don't know the code syntax to show all installed applications when that button is clicked!!
Please help I tried googling for the last four hours and getting very frustrated
Thanks in advance
Rapsong11
Sent from my Nexus 4 using xda app-developers app
Maybe you should use PackageManager to query the installed applications for you.
For example, when you want the list of launchable activities. You can do like this:
Code:
// create a intent for the query below
Intent mainIntent = new Intent(Intent.ACTION_MAIN, null);
// add the intent category you want, if need
mainIntent.addCategory(Intent.CATEGORY_LAUNCHER);
// get the instance of the package manager
PackageManager packageManager = context.getPackageManager();
// these are the activies you want
List<ResolveInfo> activities = packageManager.queryIntentActivities(mainIntent, 0);
Hope can help you
Code:
Here is my code:
package com.d4a.SchoolLauncher;
import java.util.List;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.net.Uri;
import android.os.Bundle;
import android.provider.Settings;
import android.view.View;
import android.widget.HorizontalScrollView;
import android.widget.ImageButton;
import android.widget.ScrollView;
import android.content.Context;
import com.d4a.SchoolLauncher.R;
public class LauncherActivity extends Activity{
[user=439709]@override[/user]
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//scroller
final HorizontalScrollView scroller= (HorizontalScrollView) findViewById(R.id.scroller);
scroller.setSmoothScrollingEnabled(true);
//apps
final ImageButton apps= (ImageButton) findViewById(R.id.all_apps); //my all apps button
apps.setOnClickListener(new View.OnClickListener() {
[user=439709]@override[/user]
public void onClick(View v) {
Intent mainIntent = new Intent(Intent.ACTION_MAIN, null);
mainIntent.addCategory(Intent.CATEGORY_LAUNCHER);
PackageManager packageManager = context.getPackageManager();
List<ResolveInfo> activities = packageManager.queryIntentActivities(mainIntent, 0);
}
});
final ImageButton wbrowser= (ImageButton) findViewById(R.id.wbrowser);
wbrowser.setOnClickListener(new View.OnClickListener() {
[user=439709]@override[/user]
public void onClick(View v) {
String url = "http://www.google.com";
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse(url));
startActivity(i);
}
});
final ImageButton osettings= (ImageButton) findViewById(R.id.osettings);
osettings.setOnClickListener(new View.OnClickListener() {
[user=439709]@override[/user]
public void onClick(View v) {
startActivity(new Intent(Settings.ACTION_SETTINGS));
}
});
//remove from home screen button
//apps
final ImageButton delapps= (ImageButton) findViewById(R.id.delapps);
delapps.setOnClickListener(new View.OnClickListener() {
[user=439709]@override[/user]
public void onClick(View v) {
apps.setVisibility(View.GONE);
delapps.setVisibility(View.GONE);
}
});
//web browser
final ImageButton delwbrowser= (ImageButton) findViewById(R.id.delwbrowser);
delwbrowser.setOnClickListener(new View.OnClickListener() {
[user=439709]@override[/user]
public void onClick(View v) {
wbrowser.setVisibility(View.GONE);
delwbrowser.setVisibility(View.GONE);
}
});
//web browser
final ImageButton delosettings= (ImageButton) findViewById(R.id.dellosettings);
delosettings.setOnClickListener(new View.OnClickListener() {
[user=439709]@override[/user]
public void onClick(View v) {
osettings.setVisibility(View.GONE);
delosettings.setVisibility(View.GONE);
}
});
//add button
final ImageButton addshortcut= (ImageButton) findViewById(R.id.addshortcut);
addshortcut.setOnClickListener(new View.OnClickListener() {
[user=439709]@override[/user]
public void onClick(View v) {
startActivity(new Intent("com.PhysicsPhantom.Launcher"));
}
});
//done button
final ImageButton done= (ImageButton) findViewById(R.id.done);
done.setOnClickListener(new View.OnClickListener() {
[user=439709]@override[/user]
public void onClick(View v) {
delwbrowser.setVisibility(View.GONE);
delosettings.setVisibility(View.GONE);
delapps.setVisibility(View.GONE);
done.setVisibility(View.GONE);
addshortcut.setVisibility(View.GONE);
}
});
//edit button
final ImageButton edit= (ImageButton) findViewById(R.id.edit);
edit.setOnClickListener(new View.OnClickListener() {
[user=439709]@override[/user]
public void onClick(View v) {
if (apps.getVisibility()==View.VISIBLE){
delapps.setVisibility(View.VISIBLE);
}
if (wbrowser.getVisibility()==View.VISIBLE){
delwbrowser.setVisibility(View.VISIBLE);
}
if (osettings.getVisibility()==View.VISIBLE){
delosettings.setVisibility(View.VISIBLE);
}
done.setVisibility(View.VISIBLE);
addshortcut.setVisibility(View.VISIBLE);
}
});
//code to open editor for all delete buttons
//apps
apps.setOnLongClickListener(new View.OnLongClickListener() {
[user=439709]@override[/user]
public boolean onLongClick(View v) {
if (delapps.getVisibility()==View.GONE){
delapps.setVisibility(View.VISIBLE);
}
else{
delapps.setVisibility(View.GONE);
}
return true;
}
});
//web browser
wbrowser.setOnLongClickListener(new View.OnLongClickListener() {
[user=439709]@override[/user]
public boolean onLongClick(View v) {
if (delwbrowser.getVisibility()==View.GONE){
delwbrowser.setVisibility(View.VISIBLE);
}
else{
delwbrowser.setVisibility(View.GONE);
}
return true;
}
});
//settings
osettings.setOnLongClickListener(new View.OnLongClickListener() {
[user=439709]@override[/user]
public boolean onLongClick(View v) {
if (delosettings.getVisibility()==View.GONE){
delosettings.setVisibility(View.VISIBLE);
scroller.fullScroll(ScrollView.FOCUS_RIGHT);
}
else{
delosettings.setVisibility(View.GONE);
}
return true;
}
});
}
}
I get a error at: PackageManager packageManager = context.getPackageManager();
The error is as follows: context cannot be resolved
please help!!
[ code] tags would be helpful
out of ideas said:
[ code] tags would be helpful
Click to expand...
Click to collapse
just added code tags
sorry about that lol
You dont have startActivity in your launcher button
Can you please give me a code example fairly new to this
Sent from my Nexus 4 using xda app-developers app
Well, if you just want a activity list and launches when clicked, you can simply create a LauncherActivity.
Can you please show me using my code example where I would place that at? Thank you so much
Rapsong11
Sent from my Nexus 4 using xda app-developers app
rapsong11 said:
Can you please show me using my code example where I would place that at? Thank you so much
Rapsong11
Sent from my Nexus 4 using xda app-developers app
Click to expand...
Click to collapse
1. create new class MyLauncherActivity
2. override the method "getTargetIntent()" in LauncherActivity
Code:
...
import android.app.LauncherActivity;
public class MyLauncherActivity extends LauncherActivity {
 [user=439709]@override[/user]
protected Intent getTargetIntent () {
// just a example, you should replace the method yourself
Intent intent = new Intent();
intent.setAction(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_LAUNCHER);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
return intent;
}
}
3. replace the code inside your onClick method to the R.id.all_apps button :
Code:
Intent intent = new Intent(this, MyLauncherActivity.class);
startActivity(intent);
4. don't forget to declare MyLauncherActivity in your AndroidMenifest.xml
5. try to do it yourself with others' experience, but not just ask for the code, that's not good for a coder. Wish you can understand this.

ProgressBar not working

Hey, I was working on progress Bars. But I am having a little trouble. On the following code, The bar seems to work perfectly, but just when its done loading. The app crashes. Please help me out. Thanks in advance
Code:
package com.example.progresses;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.ProgressBar;
public class MainActivity extends Activity {
ProgressBar b;
int progressStatus = 0;
static int progress = 0;
Thread t;
Handler hand = new Handler();
[user=439709]@override[/user]
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
b = (ProgressBar) findViewById(R.id.progressBar1);
b.setMax(200);
new Thread(new Runnable() {
public void run() {
while (progressStatus <= 200) {
progressStatus = doWork();
hand.post(new Runnable() {
public void run() {
b.setProgress(progressStatus);
}
});
}
b.setVisibility(View.GONE);
}
}).start();
}
private int doWork() {
try {
Thread.sleep(50);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return ++progress;
}
}
LOGCAT
You have to do this via the handler, too:
Code:
b.setVisibility(View.GONE);
Every action regarding the UI from another thread has to be done via an handler.
nikwen said:
You have to do this via the handler, too:
Code:
b.setVisibility(View.GONE);
Every action regarding the UI from another thread has to be done via an handler.
Click to expand...
Click to collapse
Thank you!
hiphop12ism said:
Thanks you!
Click to expand...
Click to collapse
Welcome.

How to add sound with ImageSwitcher

Respected developers , I m creating app of alphabets , I am unable to add sound with imageswitcher,
I want when user press next button , It should give next image with its sound
my code is
Code:
I have sound in Row folder name a,b,c
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.ImageSwitcher;
import android.widget.ImageView;
import android.widget.Toast;
import android.widget.ViewSwitcher.ViewFactory;
public class New extends ActionBarActivity implements ViewFactory {
ImageSwitcher is;
int [] imgid = {R.drawable.i1,
R.drawable.i2,
R.drawable.i3,
R.drawable.i4};
Button prev, next;
int count =0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.poetry);
final Button switchact = (Button) findViewById(R.id.btn1);
switchact.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent act2 = new Intent(view.getContext(), MainActivity.class);
startActivity(act2);
}
});
is = (ImageSwitcher)findViewById(R.id.imageSwitcher1);
prev = (Button)findViewById(R.id.button1);
next = (Button)findViewById(R.id.button2);
is.setFactory(this);
is.setInAnimation(this, android.R.anim . slide_in_left);
is.setOutAnimation(this, android.R.anim.slide_out_right);
prev.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
if(count>0)
{
count--;
try{
is.setImageResource(imgid[count]);
}
catch(Exception e)
{
e.printStackTrace();
}
}
else
{
Toast.makeText(New.this, "First", Toast.LENGTH_LONG).show();
}
}
});
next.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
if(count<imgid.length)
{
try{
is.setImageResource(imgid[count]);
}
catch(Exception e)
{
e.printStackTrace();
}
count++;
}
else
{
Toast.makeText(New.this, "Last", Toast.LENGTH_LONG).show();
}
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public boolean appnot(View v){
Intent sharingIntent = new Intent(android.content.Intent.ACTION_SEND);
sharingIntent.setType("text/plain");
String shareBody = "http://rafeeqsir.in";
sharingIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, "I found a best Urdu Learing App Please try");
sharingIntent.putExtra(android.content.Intent.EXTRA_TEXT, shareBody);
startActivity(Intent.createChooser(sharingIntent, "Share via"));
return false;
}
public void about(View v){
{
new AlertDialog.Builder(this)
.setTitle(R.string.app_about)
.setNegativeButton(R.string.str_ok,
new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialoginterface, int i)
{
}
})
.show();
}
}
public void exit(View v){
{
new AlertDialog.Builder(this)
.setTitle(R.string.app_exit)
.setIcon(R.drawable.ic_launcher)
.setMessage(R.string.app_exit_message)
.setNegativeButton(R.string.exit,
new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialoginterface, int i)
{
System.exit(0);
}
})
.show();
}
}
@Override
public View makeView() {
// TODO Auto-generated method stub
ImageView iv = new ImageView(this);
iv.setScaleType(ImageView.ScaleType.FIT_CENTER);
iv.setLayoutParams(new ImageSwitcher.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
return iv;
}
}
please help me about it

Categories

Resources