ProgressBar not working - Java for Android App Development

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.

Related

[NEWBIE] ProgressDialog Not Working properly

I am a newbie in android development. I was learning some of these android Dialog API stuff. But i got stuck with progressDialogs. When I run the app in the sdk.. The Dialog never ends. Where as, it should terminate after 5 seconds. I am unable to understand the problem. Please help me out. Thanks in advance...
SOURCE CODE:
Code:
package com.example.dolaog;
import android.location.GpsStatus.Listener;
import android.os.Bundle;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.Toast;
public class MainActivity extends Activity implements OnClickListener, Runnable {
Button b, b2;
View a;
ProgressDialog d;
Thread t = new Thread();
[user=439709]@override[/user]
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
b = (Button) findViewById(R.id.button1);
b2 = (Button) findViewById(R.id.button2);
b.setOnClickListener(this);
b2.setOnClickListener(this);
}
[user=439709]@override[/user]
public void onClick(View arg0) {
switch (arg0.getId()) {
case R.id.button1:
showDialog(0);
break;
case R.id.button2:
d = ProgressDialog.show(this, "Initialising", " Please wait...", true);
t.start();
break;
}
}
public void run() {
// TODO Auto-generated method stub
try {
t.sleep(5000);
d.dismiss();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
[user=439709]@override[/user]
protected Dialog onCreateDialog(int g) {
switch (g) {
case 0:
Builder b = new AlertDialog.Builder(this);
b.setIcon(R.drawable.ic_launcher);
b.setTitle("From Crazyandroidgalaxy, please hit me !!");
b.setPositiveButton("asd", new DialogInterface.OnClickListener() {
[user=439709]@override[/user]
public void onClick(DialogInterface arg0, int arg1) {
// TODO Auto-generated method stub
Toast.makeText(getBaseContext(),
"I am Tanmay aka Crazyandroidgalaxy admin!",
Toast.LENGTH_LONG).show();
}
});
return b.create();
}
return null;
}
}
If you don't get a force close then it sounds like your thread never starts.
Code:
Thread t = new Thread();
Change that to just:
Code:
Thread t;
and in your OnCreate method:
Code:
t = new Thread();
The problem is that the run() method needs to be a method of the Thread. Use this:
Code:
Thread t = new Thread() {
public void run() {
// TODO Auto-generated method stub
try {
t.sleep(5000);
d.dismiss();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
};
However, this WILL NOT work due to the fact that you can just change the UI from the UI Thread.
So change it to this:
Code:
package com.example.dolaog;
import android.location.GpsStatus.Listener;
import android.os.Bundle;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.Toast;
[COLOR="Red"]import android.os.Handler;[/COLOR]
public class MainActivity extends Activity implements OnClickListener, Runnable {
Button b, b2;
View a;
ProgressDialog d;
[COLOR="Red"]Handler handler;
Thread t = new Thread() {
public void run() {
// TODO Auto-generated method stub
try {
sleep(5000);
handler.post(new Runnable() {
public void run() {
d.dismiss();
}
};
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
};[/COLOR]
[user=439709]@override[/user]
protected void onCreate(Bundle savedInstanceState) {
[COLOR="Red"] handler = new Handler();[/COLOR]
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
b = (Button) findViewById(R.id.button1);
b2 = (Button) findViewById(R.id.button2);
b.setOnClickListener(this);
b2.setOnClickListener(this);
}
[user=439709]@override[/user]
public void onClick(View arg0) {
switch (arg0.getId()) {
case R.id.button1:
showDialog(0);
break;
case R.id.button2:
d = ProgressDialog.show(this, "Initialising", " Please wait...", true);
t.start();
break;
}
}
[user=439709]@override[/user]
protected Dialog onCreateDialog(int g) {
switch (g) {
case 0:
Builder b = new AlertDialog.Builder(this);
b.setIcon(R.drawable.ic_launcher);
b.setTitle("From Crazyandroidgalaxy, please hit me !!");
b.setPositiveButton("asd", new DialogInterface.OnClickListener() {
[user=439709]@override[/user]
public void onClick(DialogInterface arg0, int arg1) {
// TODO Auto-generated method stub
Toast.makeText(getBaseContext(),
"I am Tanmay aka Crazyandroidgalaxy admin!",
Toast.LENGTH_LONG).show();
}
});
return b.create();
}
return null;
}
}
That should work.
Thank you so much!
Sent from my GT-S6102 using xda app-developers app
hiphop12ism said:
Thank you so much!
Sent from my GT-S6102 using xda app-developers app
Click to expand...
Click to collapse
You are welcome.
nikwen said:
You are welcome.
Click to expand...
Click to collapse
But can you, explain me the code modification. I am unfamiliar with the Handler class and post method...
Thanks :laugh:
hiphop12ism said:
But can you, explain me the code modification. I am unfamiliar with the Handler class and post method...
Thanks :laugh:
Click to expand...
Click to collapse
Yeah, the UI is created in one thread. That is what is called the "UI thread". The UI can just be modified from that UI thread.
If you want to modify the UI from another thread, you use handlers. If you pass a Runnable object to their run() method, that runnable will be executed in the UI thread. So you can modify the UI from that thread.
Better code would be using an AsyncTask. Basically, it is a wrapper class for Thread and Handler. (Additionally, there are some performance enhancement due to a thread pool.)
nikwen said:
Yeah, the UI is created in one thread. That is what is called the "UI thread". The UI can just be modified from that UI thread.
If you want to modify the UI from another thread, you use handlers. If you pass a Runnable object to their run() method, that runnable will be executed in the UI thread. So you can modify the UI from that thread.
Better code would be using an AsyncTask. Basically, it is a wrapper class for Thread and Handler. (Additionally, there are some performance enhancement due to a thread pool.)
Click to expand...
Click to collapse
Thank you so much.
But, the problem is... Whenever the 2nd button (b2) is clicked for the second time..
The app force closes..
hiphop12ism said:
Thank you so much.
But, the problem is... Whenever the 2nd button (b2) is clicked for the second time..
The app force closes..
Click to expand...
Click to collapse
That happens because the thread has already been started.
Check whether it is running and if it is not, start it. If it is, do nothing.
Use the isAlive() method for that.
Gotcha... Thanks!!
Sent from my GT-S6102 using xda app-developers app

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.

url loading handling in webview

Basic question, what did i do? Hahaha. What did i do to make url load inside webview?
At first i overridden shouldOverrideUrlLoading to control where the link loads, then i one time i removed it but url still loads inside webview. And now i need to once again override url loading because i need a link to be opened on the default browser, but i don't know how. I even tried what others suggested to force url loading on the default browser, but it doesn't work. Please help me. Here's my code:
Code:
package com.sample;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Bundle;
import android.os.StrictMode;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.graphics.Bitmap;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ProgressBar;
import android.widget.Toast;
public class MainActivity extends Activity
{
private WebView wv;
private ProgressBar progress;
private static String mycaturl="*url 1*";
private static String helpurl="*url 2*";
private static String fbackurl="*url 3*";
[user=1299008]@supp[/user]ressLint("NewApi")
[user=439709]@override[/user]
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitNetwork().build();
StrictMode.setThreadPolicy(policy);
if (reachable(this))
{
Toast.makeText(this, "Reachable", Toast.LENGTH_SHORT).show();
buildwv( savedInstanceState, WebSettings.LOAD_DEFAULT, mycaturl );
}
else
{
Toast.makeText(this, "Unreachable", Toast.LENGTH_SHORT).show();
eolc( savedInstanceState );
}
}
[user=1299008]@supp[/user]ressLint({ "SetJavaScriptEnabled" })
public void buildwv(Bundle sis, int load, String url)
{
this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR);
setContentView(R.layout.activity_main);
//assigning objects to variables
wv=(WebView) findViewById(R.id.wv);
wv.setWebViewClient( new wvc() );
progress=(ProgressBar) findViewById(R.id.progress);
//websettings
WebSettings ws = wv.getSettings();
ws.setAppCacheMaxSize( 100 * 1024 * 1024 ); // 100MB
ws.setAppCachePath( this.getCacheDir().getAbsolutePath() );
ws.setAllowFileAccess( true );
ws.setAppCacheEnabled( true );
ws.setJavaScriptEnabled( true );
ws.setCacheMode(load);
//if instance is saved, to catch orientation change
if(sis==null)
{ wv.loadUrl(url); }
}
public void eolc(final Bundle sis)
{
this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_NOSENSOR);
AlertDialog.Builder alertDialog = new AlertDialog.Builder( MainActivity.this );
alertDialog.setTitle("Unreachable Host");
alertDialog.setMessage("Host is unreachable. Load from cache or exit.");
alertDialog.setIcon(R.drawable.tick);
//alertDialog.setCanceledOnTouchOutside(false);
alertDialog.setCancelable(false);
alertDialog.setPositiveButton( "Load from Cache", new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog,int which)
{
// Write your code here to execute after dialog
Toast.makeText(getApplicationContext(), "You chose to load cache.", Toast.LENGTH_SHORT).show();
buildwv( sis, WebSettings.LOAD_CACHE_ELSE_NETWORK, mycaturl );
}
});
alertDialog.setNeutralButton( "Help", new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int which)
{
Toast.makeText(getApplicationContext(), "You chose Help. EOLC", Toast.LENGTH_SHORT).show();
buildwv( sis, WebSettings.LOAD_CACHE_ELSE_NETWORK, helpurl );
}
});
alertDialog.setNegativeButton( "Exit", new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int which)
{
// Write your code here to execute after dialog
Toast.makeText(getApplicationContext(), "You chose to exit.", Toast.LENGTH_SHORT).show();
finish();
}
});
alertDialog.create();
alertDialog.show();
}
public void roe()
{
this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_NOSENSOR);
AlertDialog.Builder alertDialog = new AlertDialog.Builder( MainActivity.this );
alertDialog.setTitle("Connection Lost");
alertDialog.setMessage("Connection to host was lost. Restart and load cache or exit.");
alertDialog.setIcon(R.drawable.tick);
alertDialog.setCancelable(false);
alertDialog.setPositiveButton( "Restart", new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog,int which)
{
Toast.makeText(getApplicationContext(), "You chose to restart and load cache.", Toast.LENGTH_SHORT).show();
Intent i = getBaseContext().getPackageManager()
.getLaunchIntentForPackage( getBaseContext().getPackageName() );
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK );
startActivity(i);
}
});
alertDialog.setNeutralButton( "Help", new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int which)
{
Toast.makeText(getApplicationContext(), "You chose Help. ROE", Toast.LENGTH_SHORT).show();
wv.stopLoading();
wv.loadUrl( helpurl );
}
});
alertDialog.setNegativeButton( "Exit", new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int which)
{
Toast.makeText(getApplicationContext(), "You chose to exit.", Toast.LENGTH_SHORT).show();
finish();
}
});
alertDialog.create();
alertDialog.show();
}
private class wvc extends WebViewClient
{
public void onPageStarted(WebView view, String url, Bitmap favicon)
{
progress.setVisibility(View.VISIBLE);
if (url.contains(mycaturl))
{
WebSettings ws = wv.getSettings();
if ( !reachable(getApplicationContext()) )
{
if ( ws.getCacheMode() == WebSettings.LOAD_DEFAULT )
{
roe();
}
else if ( ws.getCacheMode() == WebSettings.LOAD_CACHE_ELSE_NETWORK )
{
Toast.makeText(getApplicationContext(), "loading cache coz not reachable", Toast.LENGTH_SHORT).show();
}
}
else
{
if ( ws.getCacheMode() == WebSettings.LOAD_CACHE_ELSE_NETWORK )
{
Toast.makeText(getApplicationContext(), "Connection to server established.", Toast.LENGTH_SHORT).show();
}
}
}
}
[user=439709]@override[/user]
public void onPageFinished(WebView view, String url)
{
super.onPageFinished(view, url);
Toast.makeText(getApplicationContext(), "PAGE DONE LOADING!!", Toast.LENGTH_SHORT).show();
//circular progress bar close
progress.setVisibility(View.GONE);
}
[user=439709]@override[/user]
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl)
{
super.onReceivedError(view, errorCode, description, failingUrl);
wv.stopLoading();
WebSettings ws = wv.getSettings();
if ( ws.getCacheMode() == WebSettings.LOAD_DEFAULT )
{
wv.loadUrl(helpurl);
Toast.makeText(getApplicationContext(), "Page unavailable", Toast.LENGTH_SHORT).show();
}
else
{
wv.loadUrl(helpurl);
Toast.makeText(getApplicationContext(), "Page not cached", Toast.LENGTH_SHORT).show();
}
roe();
}
}
//checking connectivity by checking if site is reachable
public static boolean reachable(Context context)
{
final ConnectivityManager connMgr = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
final NetworkInfo netInfo = connMgr.getActiveNetworkInfo();
if (netInfo != null && netInfo.isConnected())
{
try
{
URL url = new URL(mycaturl);
HttpURLConnection urlc = (HttpURLConnection) url.openConnection();
urlc.setConnectTimeout(5000); // five seconds timeout in milliseconds
urlc.connect();
if (urlc.getResponseCode() == 200) // good response
{ return true; } else { return false; }
}
catch (IOException e)
{ return false; }
}
else
{ return false; }
}
[user=439709]@override[/user]
public boolean onCreateOptionsMenu(Menu menu)
{
super.onCreateOptionsMenu(menu);
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public void onBackPressed ()
{
if (wv.isFocused() && wv.canGoBack())
{ wv.goBack(); } else { finish(); }
}
[user=439709]@override[/user]
public boolean onOptionsItemSelected(MenuItem item)
{
switch (item.getItemId())
{
case R.id.item1:
wv.loadUrl( helpurl );
break;
case R.id.item2:
wv.loadUrl( fbackurl );
break;
case R.id.item3:
String currurl=wv.getUrl();
wv.loadUrl(currurl);
break;
case R.id.item4:
Intent i = getBaseContext().getPackageManager()
.getLaunchIntentForPackage( getBaseContext().getPackageName() );
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
break;
case R.id.item5:
finish();
break;
default:
break;
}
return true;
}
[user=439709]@override[/user]
protected void onSaveInstanceState(Bundle outState )
{
super.onSaveInstanceState(outState);
wv.saveState(outState);
}
[user=439709]@override[/user]
protected void onRestoreInstanceState(Bundle savedInstanceState)
{
super.onSaveInstanceState(savedInstanceState);
wv.restoreState(savedInstanceState);
}
}
Should i include manifest? Thanks in advance.
That's a messed Op . If your code is short. use code tags. If its big, use paste bin to make it easy for people to read the question and answer it!
vijai2011 said:
That's a messed Op . If your code is short. use code tags. If its big, use paste bin to make it easy for people to read the question and answer it!
Click to expand...
Click to collapse
Sorry, I'm still a newbie. Can you please teach me the proper way of coding android?
klutchmeister said:
Sorry, I'm still a newbie. Can you please teach me the proper way of coding android?
Click to expand...
Click to collapse
He just said that you should wrap your code into
Code:
tags or upload it elsewhere because nobody will read it as it is right now. Can you read that code from your browser? If you put it into [CODE] tags, it will look like this: [URL]http://forum.xda-developers.com/showthread.php?p=44976604#post44976604[/URL]
Then people will be able to read it. ;)
nikwen said:
He just said that you should wrap your code into
Code:
tags or upload it elsewhere because nobody will read it as it is right now. Can you read that code from your browser? If you put it into [CODE] tags, it will look like this: [URL]http://forum.xda-developers.com/showthread.php?p=44976604#post44976604[/URL]
Then people will be able to read it. ;)[/QUOTE]
Oh. sorry. Haha. There, thanks. :)
Click to expand...
Click to collapse

Radio app into a service

Hi I was looking for tutorials to make a radio app so I followed this one but the problem is that as soon as the app closes the music stops, how do I turn it into a service. Thanks
Code:
import android.app.Activity;
import android.os.Bundle;
import java.io.IOException;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnBufferingUpdateListener;
import android.media.MediaPlayer.OnPreparedListener;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ProgressBar;
public class myMain extends Activity implements OnClickListener {
private ProgressBar playSeekBar;
private Button buttonPlay;
private Button buttonStopPlay;
private MediaPlayer player;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
initializeUIElements();
initializeMediaPlayer();
}
private void initializeUIElements() {
playSeekBar = (ProgressBar) findViewById(R.id.progressBar1);
playSeekBar.setMax(100);
playSeekBar.setVisibility(View.INVISIBLE);
buttonPlay = (Button) findViewById(R.id.buttonPlay);
buttonPlay.setOnClickListener(this);
buttonStopPlay = (Button) findViewById(R.id.buttonStopPlay);
buttonStopPlay.setEnabled(false);
buttonStopPlay.setOnClickListener(this);
}
public void onClick(View v) {
if (v == buttonPlay) {
startPlaying();
} else if (v == buttonStopPlay) {
stopPlaying();
}
}
private void startPlaying() {
buttonStopPlay.setEnabled(true);
buttonPlay.setEnabled(false);
playSeekBar.setVisibility(View.VISIBLE);
player.prepareAsync();
player.setOnPreparedListener(new OnPreparedListener() {
public void onPrepared(MediaPlayer mp) {
player.start();
}
});
}
private void stopPlaying() {
if (player.isPlaying()) {
player.stop();
player.release();
initializeMediaPlayer();
}
buttonPlay.setEnabled(true);
buttonStopPlay.setEnabled(false);
playSeekBar.setVisibility(View.INVISIBLE);
}
private void initializeMediaPlayer() {
player = new MediaPlayer();
try {
player.setDataSource("stream url");
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
player.setOnBufferingUpdateListener(new OnBufferingUpdateListener() {
public void onBufferingUpdate(MediaPlayer mp, int percent) {
playSeekBar.setSecondaryProgress(percent);
Log.i("Buffering", "" + percent);
}
});
}
@Override
protected void onPause() {
super.onPause();
if (player.isPlaying()) {
player.stop();
}
}
}
benpaterson said:
Hi I was looking for tutorials to make a radio app so I followed this one but the problem is that as soon as the app closes the music stops, how do I turn it into a service. Thanks
Code:
import android.app.Activity;
import android.os.Bundle;
import java.io.IOException;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnBufferingUpdateListener;
import android.media.MediaPlayer.OnPreparedListener;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ProgressBar;
public class myMain extends Activity implements OnClickListener {
private ProgressBar playSeekBar;
private Button buttonPlay;
private Button buttonStopPlay;
private MediaPlayer player;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
initializeUIElements();
initializeMediaPlayer();
}
private void initializeUIElements() {
playSeekBar = (ProgressBar) findViewById(R.id.progressBar1);
playSeekBar.setMax(100);
playSeekBar.setVisibility(View.INVISIBLE);
buttonPlay = (Button) findViewById(R.id.buttonPlay);
buttonPlay.setOnClickListener(this);
buttonStopPlay = (Button) findViewById(R.id.buttonStopPlay);
buttonStopPlay.setEnabled(false);
buttonStopPlay.setOnClickListener(this);
}
public void onClick(View v) {
if (v == buttonPlay) {
startPlaying();
} else if (v == buttonStopPlay) {
stopPlaying();
}
}
private void startPlaying() {
buttonStopPlay.setEnabled(true);
buttonPlay.setEnabled(false);
playSeekBar.setVisibility(View.VISIBLE);
player.prepareAsync();
player.setOnPreparedListener(new OnPreparedListener() {
public void onPrepared(MediaPlayer mp) {
player.start();
}
});
}
private void stopPlaying() {
if (player.isPlaying()) {
player.stop();
player.release();
initializeMediaPlayer();
}
buttonPlay.setEnabled(true);
buttonStopPlay.setEnabled(false);
playSeekBar.setVisibility(View.INVISIBLE);
}
private void initializeMediaPlayer() {
player = new MediaPlayer();
try {
player.setDataSource("stream url");
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
player.setOnBufferingUpdateListener(new OnBufferingUpdateListener() {
public void onBufferingUpdate(MediaPlayer mp, int percent) {
playSeekBar.setSecondaryProgress(percent);
Log.i("Buffering", "" + percent);
}
});
}
@Override
protected void onPause() {
super.onPause();
if (player.isPlaying()) {
player.stop();
}
}
}
Click to expand...
Click to collapse
You'll have to learn about Android Service and extend that, instead of Activity.

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