This question already has answers here:
NetworkOnMainThreadException [duplicate]
(5 answers)
How can I fix 'android.os.NetworkOnMainThreadException'?
(66 answers)
Closed 9 years ago.
when I launched my application I have a problem with emulator 4.1 and 4.2 even I have already made the Internet permission, logcat shows this mssage:
Error in http connectionandroid.os.NetworkOnMainThreadException ?
package com.example.eagletracking;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.media.audiofx.BassBoost.Settings;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.widget.Toast;
public class GPSTrackingActivity extends Activity implements LocationListener {
Toast toast;
boolean isGPSAvaible;
private LocationManager lm;
private Location location;
private static String key =DBconection.key;
Calendar currentDate;
SimpleDateFormat formatter;
public static double latitude; // latitude
public static double longitude; // longitude
Handler handler = new Handler() {
public void handleMessage(android.os.Message msg) {
if (msg.what == 0) {
synchronisation();
}
else if (msg.what == 1) {
updateDatabase(location);
}
}
};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.accueil);
if (isInternetAvailable(this)) {
Thread th = new Thread() {
public void run() {
try {
while (true) {
Thread.sleep(80000);
{
handler.sendEmptyMessage(0);
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
};
th.start();
}
}
public static boolean isInternetAvailable(Context context) {
boolean isInternetAvailable = false;
try {
ConnectivityManager connectivityManager = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connectivityManager
.getActiveNetworkInfo();
if (networkInfo != null && (networkInfo.isConnected())) {
isInternetAvailable = true;
}
} catch (Exception exception) {
// Do Nothing
}
return isInternetAvailable;
}
#Override
protected void onResume() {
super.onResume();
try {
lm = (LocationManager) getSystemService(LOCATION_SERVICE);
isGPSAvaible = lm.isProviderEnabled (LocationManager.GPS_PROVIDER);
if (isGPSAvaible)
{
abonnementGPS();
}
} catch (Exception e) {
e.printStackTrace();
}
}
private void abonnementGPS() {
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 10000, 0,
this);
if (lm != null) {
location = lm
.getLastKnownLocation(LocationManager.GPS_PROVIDER);
Thread th = new Thread() {
public void run() {
try {
while (location != null) {
Thread.sleep(6000);
{
handler.sendEmptyMessage(1);
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
};
th.start();
}
}
private void synchronisation() {
DBconection maBaseSQLite = new DBconection(GPSTrackingActivity.this);
SQLiteDatabase db = maBaseSQLite.getReadableDatabase();
Cursor c = maBaseSQLite.getAllRows();
int col = c.getCount(); // col=0 pas de enregistrement qui
// verifie la condition
if (col == 0) {
Toast.makeText(GPSTrackingActivity.this, "Pas de donnees ",
Toast.LENGTH_LONG).show();
// effacer le contenue champ login et mot de passe
} else {
c.moveToFirst();
while (c.isAfterLast() == false) {
// conversion int to string casting
String id = "" + c.getInt(0);
String longitude = c.getString(1);
String latitude = c.getString(2);
String time = c.getString(3);
String key_employe = c.getString(4);
InputStream is = null;
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(
4);
// nameValuePairs.add(new BasicNameValuePair("id",
// ch1));
nameValuePairs.add(new BasicNameValuePair("longitude",
longitude));
nameValuePairs
.add(new BasicNameValuePair("latitude", latitude));
nameValuePairs.add(new BasicNameValuePair("time", time));
nameValuePairs.add(new BasicNameValuePair("key_employe", key_employe));
c.moveToNext();
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(
"http://10.0.2.2:8888/android/synchron.php");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
} catch (Exception e) {
Log.d("connexion_expired",
"Error in http connection" + e.toString());
}
}
}
c.close();
maBaseSQLite.del();
maBaseSQLite.close();
}
private void updateDatabase(Location location) {
DBconection maBaseSQLite = new DBconection(GPSTrackingActivity.this);
SQLiteDatabase DB = maBaseSQLite.getWritableDatabase();
// maBaseSQLite.onCreate(DB);
//maBaseSQLite.onUpgrade(DB, 0, 0);
longitude= location.getLatitude();
latitude=location.getLatitude();
currentDate = Calendar.getInstance();
formatter = new SimpleDateFormat("yyyy/MMM/dd HH:mm:ss");
maBaseSQLite.addPoint(String.valueOf(longitude),
String.valueOf(latitude),
formatter.format(currentDate.getTime()),(key));
Log.i("insert ", "ok");
maBaseSQLite.close();
}
#Override
public void onLocationChanged(Location arg0) {
}
#Override
public void onProviderDisabled(String arg0) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String arg0) {
// TODO Auto-generated method stub
}
#Override
public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
// TODO Auto-generated method stub
}
}
NetworkOnMainThread exception occurs when you are running network related operation on the main UI thread. http://developer.android.com/reference/android/os/NetworkOnMainThreadException.html
You use should use a asynctask for this purpose or create your own thread.
You are making a http request on the main ui thread.
http://developer.android.com/reference/android/os/AsyncTask.html
Check the link above especially the topic under the heading The 4 steps.
Example:
class TheTask extends AsyncTask<Void,Void,Void>
{
protected void onPreExecute()
{ super.onPreExecute();
//display progressdialog.
}
protected void doInBackground(Void ...params)
{
//Network related opearaiton. Do not update ui here
return null;
}
protected void onPostExecute(Void result)
{
super.onPostExecute(result);
//dismiss progressdialog.
//update ui
}
}
As doc says about NetworkOnMainThreadException:
the exception that is thrown when an application attempts to perform a networking operation on its main thread.
So, you're getting this error because you're running your client in the main Thread. To avoid this exception you can use an AsyncTask, Executor or simply using a Thread
Related
This question already has answers here:
How can I fix 'android.os.NetworkOnMainThreadException'?
(66 answers)
Closed 9 years ago.
I'm novice with web service and i try to create a web service with netbeans, i test it with rest client (mozilla plugin) it work but when i try to use the android client, it's doesn't and i receive this android.os.NetworkOnMainThreadException in my logcat. Here is the code
<pre><code>
package cg.skylab.clientrest;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Scanner;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.annotation.TargetApi;
import android.app.ListActivity;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.StrictMode;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
import cg.skylab.clientrest.model.Personne;
public class ListePersonnel extends ListActivity {
private ArrayList<Personne> personnes = new ArrayList<Personne>();
private String adresse;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.liste);
startActivityForResult(new Intent(this, ChoixServeur.class), 1);
}
protected void onActivityResult(int requestCode, int resultCode,
Intent intention) {
if (resultCode == RESULT_OK) {
adresse = intention.getStringExtra("adresse");
try {
miseAJour();
} catch (Exception ex) {
Toast.makeText(this, "Reponse incorrecte", Toast.LENGTH_SHORT).show();
String tagException = ex.toString();
String tagAdresse = intention.getStringExtra("adresse");
Log.i(tagException, "Exception");
Log.i(tagAdresse, "Adresse IP");
}
}
}
#Override
protected void onResume() {
super.onResume();
if (adresse != null)
try {
miseAJour();
} catch (Exception ex) {
}
}
#Override
protected void onStop() {
super.onStop();
finish();
}
public void miseAJour() throws IOException, JSONException {
HttpClient client = new DefaultHttpClient();
HttpGet requete = new HttpGet("http://"+adresse+":8080/Personnel/rest/"+1);
HttpResponse reponse = client.execute(requete);
if (reponse.getStatusLine().getStatusCode() == 200) {
Scanner lecture = new Scanner(reponse.getEntity().getContent());
StringBuilder contenu = new StringBuilder();
while (lecture.hasNextLine())
contenu.append(lecture.nextLine() + '\n');
JSONArray tableauJSON = new JSONArray(contenu.toString());
StringBuilder message = new StringBuilder();
personnes.clear();
for (int i = 0; i < tableauJSON.length(); i++) {
JSONObject json = tableauJSON.getJSONObject(i);
Personne personne = new Personne();
personne.setId(json.getLong("id"));
personne.setNom(json.getString("nom"));
personne.setPrenom(json.getString("prenom"));
personne.setNaissance(json.getLong("naissance"));
personne.setTelephone(json.getString("telephone"));
personnes.add(personne);
}
setListAdapter(new ArrayAdapter<Personne>(this,
android.R.layout.simple_list_item_1, personnes));
} else
Toast.makeText(this, "Problème de connexion avec le serveur",
Toast.LENGTH_SHORT).show();
}
public void edition(View v) {
Intent intention = new Intent(this, Personnel.class);
intention.putExtra("id", 0);
intention.putExtra("adresse", adresse);
startActivity(intention);
}
protected void onListItemClick(ListView liste, View v, int position, long id) {
Personne personne = personnes.get(position);
Intent intention = new Intent(this, Personnel.class);
intention.putExtra("id", personne.getId());
intention.putExtra("adresse", adresse);
intention.putExtra("nom", personne.getNom());
intention.putExtra("prenom", personne.getPrenom());
intention.putExtra("naissance", personne.getNaissance());
intention.putExtra("telephone", personne.getTelephone());
startActivity(intention);
}
}
</code></pre>
You are getting NewtworkOnMainThread exception because you are making network calls on the UI thread. This is a bad practice because it can block/bog down your UI thread which would make your app feel slow.
To avoid that error you have to use AsyncTask.
You have to use like this:
public class DowloadTest extends AsyncTask<String, Integer, String> {
#Override
protected void onPreExecute() {
};
#Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
// Call your web service here
return null;
}
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
// Update your UI here
return;
}
}
For more detail check out this article
I am writing a service based app with a bound service, and the service's onBind() method never seems to be called (testing it with Toasts and Logs).
The service:
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Binder;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
import android.widget.Toast;
import com.gmail.zack.yovel.FlickAround.MyActivity;
import com.gmail.zack.yovel.FlickAround.R;
import org.json.JSONArray;
import org.json.JSONObject;
import java.util.ArrayList;
/**
* Created with IntelliJ IDEA.
* User: Ziky
* Date: 09/04/13
* Time: 19:06
* To change this template use File | Settings | File Templates.
*/
public class UpdateService extends Service implements LocationListener, UpdatePhotosTask.OnHttpResponseListener {
private final static String API_KEY = "5255c7b02750c0fa4b15bd8ad4ec1fb7";
private final static String GET_PHOTOS_FOR_LOCATION_SCHEMA = "http://api.flickr.com/services/rest/?method=flickr.photos.search&api_key=" + API_KEY + "&lat=%d&lon=%d&format=json&nojsoncallback=1";
private static final String KEY_PHOTOS = "photos";
private static final String KEY_PHOTO = "photo";
private int NOTIFICATION = R.string.update_service_started;
private NotificationManager mNManager;
private LocationManager mLManager;
private String mProvider;
private Location mLocation;
private IBinder mBinder = new LocalBinder();
private UpdatePhotosTask task;
#Override
public IBinder onBind(Intent intent) {
Toast.makeText(this, "UpdateService.onBind()", Toast.LENGTH_LONG).show();
Log.i("test", "UpdateService.onBind()");
mLManager.requestLocationUpdates(mProvider, 0, 1000, this);
return mBinder;
}
#Override
public void onCreate() {
mNManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
showNotification();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.i("LocalService", "Received start id " + startId + ": " + intent);
mLManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
mProvider = mLManager.getBestProvider(criteria, false);
mLocation = mLManager.getLastKnownLocation(mProvider);
return START_STICKY;
}
#Override
public void onDestroy() {
mNManager.cancel(NOTIFICATION);
Toast.makeText(this, R.string.update_service_stoped, Toast.LENGTH_SHORT).show();
}
private void showNotification() {
CharSequence text = getText(R.string.update_service_active);
Notification notification = new Notification(R.drawable.refresh, text, System.currentTimeMillis());
PendingIntent contentIntent = PendingIntent.getActivity(this, 0, new Intent(this, MyActivity.class), 0);
notification.setLatestEventInfo(this, getText(R.string.update_service_label), text, contentIntent);
mNManager.notify(NOTIFICATION, notification);
}
#Override
public void onLocationChanged(Location location) {
beginUpdate(location);
}
private void beginUpdate(Location location) {
Toast.makeText(this, "beginning update", Toast.LENGTH_LONG).show();
String url = buildUrl(location);
task = new UpdatePhotosTask(this);
task.execute(url);
}
private String buildUrl(Location location) {
return String.format(GET_PHOTOS_FOR_LOCATION_SCHEMA, location.getLatitude(), location.getLongitude());
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
#Override
public void onHttpResponse(ArrayList<String> responses) {
if (responses.size() > 0) {
String response = responses.get(0);
try {
JSONObject jsonObject = new JSONObject(response);
jsonObject = jsonObject.getJSONObject(KEY_PHOTOS);
JSONArray jsonArray = jsonObject.getJSONArray(KEY_PHOTO);
ArrayList<String> photos = new ArrayList<String>();
for (int i = 0, length = jsonArray.length(); i < length; i++) {
jsonObject = jsonArray.getJSONObject(i);
Log.i("photo info", jsonObject.toString());
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
public class LocalBinder extends Binder {
public UpdateService getService() {
return UpdateService.this;
}
}
}
The AsyncTask:
import android.os.AsyncTask;
import android.util.Log;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
/**
* Created with IntelliJ IDEA.
* User: Ziky
* Date: 09/04/13
* Time: 07:38
* To change this template use File | Settings | File Templates.
*/
public class UpdatePhotosTask extends AsyncTask<String, Void, ArrayList<String>> {
private OnHttpResponseListener listener;
public UpdatePhotosTask(OnHttpResponseListener listener) {
this.listener = listener;
}
#Override
protected ArrayList<String> doInBackground(String... urls) {
ArrayList<String> responses = new ArrayList<String>();
for (String url : urls) {
StringBuilder response = new StringBuilder();
DefaultHttpClient client = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
try {
HttpResponse execute = client.execute(httpGet);
StatusLine statusLine = execute.getStatusLine();
int statusCode = statusLine.getStatusCode();
if (statusCode == 200) {
InputStream content = execute.getEntity().getContent();
BufferedReader buffer = new BufferedReader(new InputStreamReader(content));
String s = "";
while ((s = buffer.readLine()) != null) {
response.append(s);
}
responses.add(response.toString());
} else {
Log.e(this.getClass().toString(), "Failed to download photo list");
}
} catch (IOException e) {
e.printStackTrace();
}
}
return responses;
}
#Override
protected void onPostExecute(ArrayList<String> responses) {
listener.onHttpResponse(responses);
}
public interface OnHttpResponseListener {
public void onHttpResponse(ArrayList<String> responses);
}
}
The activity:
import android.app.Activity;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.os.StrictMode;
import android.widget.Toast;
import com.gmail.zack.yovel.FlickAround.background.UpdateService;
public class MyActivity extends Activity {
private UpdateService mUpdateService;
private ServiceConnection mConnection = new ServiceConnection() {
#Override
public void onServiceConnected(ComponentName name, IBinder service) {
mUpdateService = ((UpdateService.LocalBinder) service).getService();
Toast.makeText(MyActivity.this, R.string.update_service_connected, Toast.LENGTH_SHORT).show();
}
#Override
public void onServiceDisconnected(ComponentName name) {
mUpdateService = null;
Toast.makeText(MyActivity.this, R.string.local_service_disconnected, Toast.LENGTH_SHORT).show();
}
};
private boolean mIsBound;
void doBindService() {
Toast.makeText(this, "MyActivity.doBindService()", Toast.LENGTH_LONG).show();
bindService(new Intent(this, UpdateService.class), mConnection, BIND_AUTO_CREATE);
mIsBound = true;
}
void doUnbindService() {
if (mIsBound) {
unbindService(mConnection);
mIsBound = false;
}
}
#Override
protected void onDestroy() {
super.onDestroy();
doUnbindService();
}
/**
* Called when the activity is first created.
*/
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// Activate StrictMode
StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
.detectAll().penaltyLog().penaltyDeath().build());
StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder().detectAll()
.penaltyLog().penaltyDeath().build());
}
#Override
protected void onStart() {
super.onStart();
doBindService();
}
}
Why isn't it working?
Probably the most common source of binding silently failing is not having the service listed in the manifest. This does not raise an exception, so your app does not crash, but there should be a message (warning, IIRC) in LogCat pointing out your issue.
I am parsing rss feed using xml parsing in my app. I integrated facebook in my app. My requirement is when I click on share button it shares my content with image title and single description.
My main activity in which I store parse data.
SplashActivity.java
package com.example.shareslab;
import java.util.ArrayList;
import java.util.List;
import com.example.shareslab.R;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.Html;
import android.text.Spanned;
import android.text.Html.ImageGetter;
import android.util.Log;
import android.view.Gravity;
import android.view.ViewGroup.LayoutParams;
import android.widget.Toast;
public class SplashActivity extends Activity {
/** Called when the activity is first created. */
ProgressDialog progress;
private List<com.example.shareslab.Message> messages;
public static String singleDescription;
public static String title;
static List<String>imageURLAmit;
static List<String> titles;
static List<String> description,link;
public static String[][] arrays;
public static ArrayList<String> galleryImages;
public static int position=0;
//Handle user current location
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.splash_activity);
// Register the listener with the Location Manager to receive location updates
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo info = cm.getActiveNetworkInfo();
Log.d("net status ", "show "+info);
if (info != null && info.isAvailable()) {
Log.d("net connected", "show "+info);
System.out.println("Connection OKK");
new DownloadCities().execute();
}
else{
Log.d("net not connected", "show "+info);
Toast.makeText(SplashActivity.this, "Check Internet connection. And try again.", Toast.LENGTH_LONG).show();
}
}
private class DownloadCities extends AsyncTask<String, Void, String> {
private String ResultString = "";
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
if(progress.isShowing()){
System.out.println("IN POST EXE");
progress.dismiss();
startActivity(new Intent(SplashActivity.this,MessageList.class));
}
super.onPostExecute(result);
}
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
progress = ProgressDialog.show(SplashActivity.this, "","Loading....");
progress.setIndeterminate(true);
progress.getWindow().setGravity(Gravity.BOTTOM);;
super.onPreExecute();
}
#Override
protected String doInBackground(String... arg0) {
// TODO Auto-generated method stub
try {
System.out.println("Going to call getCitiesFromServer()");
loadFeed();
}
catch (Exception e) { // <-- Use the correct exception type
ResultString = "Some error message";
}
return null;
}
}
private void loadFeed(){
position=0;
try{
BaseFeedParser parser = new BaseFeedParser();
messages = parser.parse();
titles = new ArrayList<String>(messages.size());
description = new ArrayList<String>(messages.size());
link = new ArrayList<String>(messages.size());
arrays=new String[messages.size()][];
final List<String> imageURL=new ArrayList<String>(1);
imageURLAmit=new ArrayList<String>(messages.size());
for (com.example.shareslab.Message msg : messages){
Spanned title=Html.fromHtml(msg.getTitle());
titles.add(title.toString());
link.add(msg.getLink().toString());
Spanned data=Html.fromHtml(msg.getDescription(),new ImageGetter() {
public Drawable getDrawable(String source) {
// TODO Auto-generated method stub
imageURL.add(source);
return null;
}
},null);
if(imageURL.size()!=0){
imageURLAmit.add(imageURL.get(0));
}else{
imageURLAmit.add("http://blog.kevinlearynet.netdna-cdn.com/files/applausemeter-300x200.jpg");
}
System.out.println("Position b4 loop : "+position);
int j;
arrays[position]=imageURL.toArray(new String[imageURL.size()]);
System.out.println("2D array colomn length : "+arrays[position].length);
position++;
System.out.println("Position afeter loop : "+position);
imageURL.clear();
description.add( data.toString());
System.out.println("End addition");
}
System.out.println("Final Image URL lenght : "+imageURL.size());
} catch (Throwable t){
Log.e("AndroidNews",t.getMessage(),t);
}
}
}`
here my Facebookc.java class for Facebook share.
Facebookc.java
package com.example.shareslab;
import com.example.shareslabfb.DialogError;
import com.example.shareslabfb.Facebook;
import com.example.shareslabfb.Facebook.DialogListener;
import com.example.shareslabfb.FacebookError;
import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.widget.Toast;
public class Facebookc extends Activity{
private static final String APP_ID = "392939617444978";
private static final String[] PERMISSIONS = new String[] {"publish_stream"};
private static final String TOKEN = "access_token";
private static final String EXPIRES = "expires_in";
private static final String KEY = "facebook-credentials";
private Facebook facebook;
private String messageToPost;
public boolean saveCredentials(Facebook facebook) {
Editor editor = getApplicationContext().getSharedPreferences(KEY, Context.MODE_PRIVATE).edit();
editor.putString(TOKEN, facebook.getAccessToken());
editor.putLong(EXPIRES, facebook.getAccessExpires());
return editor.commit();
}
public boolean restoreCredentials(Facebook facebook) {
SharedPreferences sharedPreferences = getApplicationContext().getSharedPreferences(KEY, Context.MODE_PRIVATE);
facebook.setAccessToken(sharedPreferences.getString(TOKEN, null));
facebook.setAccessExpires(sharedPreferences.getLong(EXPIRES, 0));
return facebook.isSessionValid();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
facebook = new Facebook(APP_ID);
restoreCredentials(facebook);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.facebook_dialog);
String facebookMessage = getIntent().getStringExtra("facebookMessage");
if (facebookMessage == null){
facebookMessage = "";
}
messageToPost = facebookMessage;
}
public void doNotShare(View button){
finish();
}
public void share(View button){
if (! facebook.isSessionValid()) {
loginAndPostToWall();
}
else {
postToWall(messageToPost);
}
}
public void loginAndPostToWall(){
facebook.authorize(this, PERMISSIONS, Facebook.FORCE_DIALOG_AUTH, new LoginDialogListener());
}
public void postToWall(String message){
Bundle parameters = new Bundle();
parameters.putString("message", message);
parameters.putString("name", "titles.get(position)");
parameters.putString("caption","shareslab.com");
parameters.putString("link", "http://www.shareslab.com");
parameters.putString("picture", "imageURLAmit.get(position)");
parameters.putString("description","description.get(position)");
try {
facebook.request("me");
String response = facebook.request("me/feed", parameters, "POST");
Log.d("Tests", "got response: " + response);
if (response == null || response.equals("") ||
response.equals("false")) {
showToast("Blank response.");
}
else {
showToast("Message posted to your facebook wall!");
}
finish();
} catch (Exception e) {
showToast("Failed to post to wall!");
e.printStackTrace();
finish();
}
}
class LoginDialogListener implements DialogListener {
public void onComplete(Bundle values) {
saveCredentials(facebook);
if (messageToPost != null){
postToWall(messageToPost);
}
}
public void onFacebookError(FacebookError error) {
showToast("Authentication with Facebook failed!");
finish();
}
public void onError(DialogError error) {
showToast("Authentication with Facebook failed!");
finish();
}
public void onCancel() {
showToast("Authentication with Facebook cancelled!");
finish();
}
}
private void showToast(String message){
Toast.makeText(getApplicationContext(), message, Toast.LENGTH_SHORT).show();
}
}
If your image is saved in SDCard, then you can use the below code after getting the uri of image :-
Here in code, uri of image is declared as imageUri.
public void performPostToWall(Uri imageUri){
byte[] data = null;
ContentResolver cr = context.getContentResolver();
InputStream in = null;
try {
in = cr.openInputStream(imageUri);
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 1;
Bitmap thumb = BitmapFactory.decodeStream(in, null, options);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
thumb.compress(Bitmap.CompressFormat.JPEG, 100, baos);
data = baos.toByteArray();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (Exception e) {
Toast.makeText(context, "Unable to upload image", Toast.LENGTH_LONG).show();
}
Bundle params = new Bundle();
params.putByteArray("picture", data);
if (!(captionText == null || captionText.equals("")))
params.putString("caption", captionText);
Request req = new Request(session, "me/photos", params, HttpMethod.POST, new Request.Callback() {
#Override
public void onCompleted(Response response) {
context.onPostToMyWallWithImageResponse(response);
}
});
req.executeAsync();
}
tyr this code
public void postToWall(String message){
try {
String response=facebook.request("me");
Bundle parameters = new Bundle();
parameters.putString("message", _id);
parameters.putString("caption", " message.");
parameters.putString("description", "A secret message is waiting for you.");
parameters.putString("name", "A Secret Message For You");
parameters.putString("picture", "http://sheokhanda.files.wordpress.com/2010/06/spring-colors.jpg");
parameters.putString("link", "http://www.google.com" );
response = facebook.request("me/feed", parameters, "POST");
Log.d("Tests", "got response: " + response);
if (response == null || response.equals("") || response.equals("false")) {
Log.i(TAG, "Blank Response...");
}
else {
Log.i(TAG, "Message posted to your facebook wall!..");
}
} catch (Exception e) {
e.printStackTrace();
}
}
it requires this permissions publish_stream
The problem is, the onPanChanged() method gets called twice causing the points to flash before they are plotted every time a user moves or pans around the map. What can I do to make the onPanChanged() method only get called once. In the code, I even try to turn off the listener and turn it back on when I exit the AsyncTask.
I would like you to share some of your thoughts and opinions.
// MapActivity
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.graphics.drawable.Drawable;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;
import com.google.android.maps.Overlay;
import com.google.android.maps.OverlayItem;
public class MapActivityNearby extends MapActivity implements EnhancedMapView.OnPanChangeListener {
private EnhancedMapView mv;
private static final String TAG = "MAPACTIVITY";
private static final String PREF_NAME = "cookie";
private double lat;
private double lng;
private ArrayList<MapItem> allCats;
private GeoPoint p;
private float latMin;
private float latMax;
private float longMin;
private float longMax;
private MapController mapControl;
private List<Overlay> mapOverlays;
private MyItemizedOverlay itemizedOverlay;
boolean waitTime = true;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.map_nearby);
LinearLayout ll = (LinearLayout) findViewById(R.id.maplayout);
mv = new EnhancedMapView(this, "api_key");
mv.setClickable(true);
mv.setBuiltInZoomControls(true);
mv.setOnZoomChangeListener(new EnhancedMapView.OnZoomChangeListener() {
#Override
public void onZoomChange(MapView view, int newZoom, int oldZoom) {
Log.d("test", "zoom changed from " + oldZoom + " to " + newZoom);
}
});
ViewGroup.LayoutParams lp = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
mv.setLayoutParams(lp);
ll.addView(mv);
SharedPreferences cookies = getSharedPreferences(PREF_NAME,
Context.MODE_PRIVATE);
lat = Double.parseDouble(cookies.getString("lat", "0"));
lng = Double.parseDouble(cookies.getString("lng", "0"));
GeoPoint p = new GeoPoint((int) (lat * 1E6), (int) (lng * 1E6));
mapControl = mv.getController();
mapControl.setZoom(11);
mapControl.setCenter(p);
}
public void onResume()
{
super.onResume();
if (isNetworkAvailable(MapActivityNearby.this))
{
PlotPoints plot = new PlotPoints();
plot.execute(mv);
}
else
{
AlertDialog.Builder builder = new AlertDialog.Builder(MapActivityNearby.this);
builder.setMessage("No network connection. Please try again when your within coverage area.")
.setTitle("Network Connection")
.setCancelable(false)
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
//close dialog
}
});
AlertDialog alert = builder.create();
alert.show();
}
}
#Override
protected boolean isRouteDisplayed() {
// TODO Auto-generated method stub
return false;
}
public void plotPoints(ArrayList<MapItem> i) {
mapOverlays = mv.getOverlays();
// first overlay
Drawable drawable;
drawable = getResources().getDrawable(R.drawable.marker);
itemizedOverlay = new MyItemizedOverlay(drawable, mv);
mapOverlays.add(itemizedOverlay);
for (MapItem x : i) {
GeoPoint point = new GeoPoint((int) (x.getLat() * 1E6),
(int) (x.getLng() * 1E6));
OverlayItem overlayItem = new OverlayItem(point,
x.getTitle(), x.getSubtitle());
itemizedOverlay.addOverlay(overlayItem);
}
GeoPoint point = new GeoPoint((int) (((latMin + latMax) * 1E6) / 2), (int) (((longMin + longMax) * 1E6) /2));
MapController mc = mv.getController();
mc.setCenter(point);
}
private class PlotPoints extends AsyncTask<EnhancedMapView, Void, Boolean> {
String result = "";
InputStream is;
#Override
protected void onPreExecute() {
turnOff();
}
#Override
protected Boolean doInBackground(EnhancedMapView...params) {
turnOff();
int maxCount = 100;
EnhancedMapView mapView = params[0];
for (int i = 0; i < maxCount; i++)
{
p = mapView.getMapCenter();
float latCenter = (float) (p.getLatitudeE6()) / 1000000;
float longCenter = (float) (p.getLongitudeE6()) / 1000000;
float latSpan = (float) (mapView.getLatitudeSpan()) / 1000000;
float longSpan = (float) (mapView.getLongitudeSpan()) / 1000000;
latMax = latCenter + (latSpan/2);
latMin = latCenter - (latSpan/2);
longMax = longCenter + (longSpan/2);
longMin = longCenter - (longSpan/2);
if (latMin == latMax)
{
try
{
Thread.sleep(80);
}
catch(InterruptedException e)
{
}
}
else
{
p = mapView.getMapCenter();
latCenter = (float) (p.getLatitudeE6()) / 1000000;
longCenter = (float) (p.getLongitudeE6()) / 1000000;
latSpan = (float) (mapView.getLatitudeSpan()) / 1000000;
longSpan = (float) (mapView.getLongitudeSpan()) / 1000000;
latMax = latCenter + (latSpan/2);
latMin = latCenter - (latSpan/2);
longMax = longCenter + (longSpan/2);
longMin = longCenter - (longSpan/2);
break;
}
}
log(latMin);
log(latMax);
try {
final String catURL = "url";
log(catURL.toString());
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(catURL);
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("PHPSESSID", getCookie()));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
result = convertStreamToString();
log(result);
allCats = new ArrayList<MapItem>();
JSONObject object = new JSONObject(result);
JSONArray temp = object.getJSONArray("l");
log("Starting download");
log(temp.length());
long start = System.currentTimeMillis();
for (int k = 0; k < temp.length(); k++) {
JSONObject j = temp.getJSONObject(k);
MapItem c = new MapItem();
c.setObject_id(j.getInt("object_id"));
c.setTitle(j.getString("title"));
c.setColor(j.getString("color"));
c.setLat(j.getDouble("lat"));
c.setLng(j.getDouble("lng"));
c.setSubtitle(j.getString("subtitle"));
allCats.add(c);
log(allCats.toString());
}
long end = System.currentTimeMillis();
log("Download Took: " + (end - start) / 1000 + " seconds.");
// log(allCats.toString());
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return true;
}
#Override
protected void onPostExecute(Boolean results) {
// pBar.setVisibility(View.GONE);
plotPoints(allCats);
turnOn();
}
private String convertStreamToString() {
try {
BufferedReader reader = new BufferedReader(
new InputStreamReader(is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result = sb.toString();
result.trim();
} catch (Exception e) {
Log.e("log_tag", "Error converting result " + e.toString());
}
return result;
}
}
public String getCookie() {
String cookie = "";
SharedPreferences cookies = getSharedPreferences(PREF_NAME,
Context.MODE_PRIVATE);
if (cookies.contains("cookie")) {
cookie = cookies.getString("cookie", "null");
}
return cookie;
}
private void log(Object obj) {
Log.d(TAG, TAG + " :: " + obj.toString());
}
public static boolean isNetworkAvailable(Context context) {
ConnectivityManager connectivity = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
if (connectivity != null) {
NetworkInfo[] info = connectivity.getAllNetworkInfo();
if (info != null) {
for (int i = 0; i < info.length; i++) {
if (info[i].getState() == NetworkInfo.State.CONNECTED) {
return true;
}
}
}
}
return false;
}
#Override
public void onPanChange(MapView view, GeoPoint newCenter, GeoPoint oldCenter) {
Log.d("test", "center changed from " + oldCenter.getLatitudeE6() + "," + oldCenter.getLongitudeE6() + " to " + newCenter.getLatitudeE6() + "," + newCenter.getLongitudeE6());
if(!mv.getOverlays().isEmpty())
{
mv.getOverlays().clear();
mv.postInvalidate();
}
if (isNetworkAvailable(MapActivityNearby.this))
{
PlotPoints log = new PlotPoints();
log.execute(mv);
}
else
{
AlertDialog.Builder builder = new AlertDialog.Builder(MapActivityNearby.this);
builder.setMessage("No network connection. Please try again when your within coverage area.")
.setTitle("Network Connection")
.setCancelable(false)
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
//close dialog
}
});
AlertDialog alert = builder.create();
alert.show();
}
}
public void turnOn ()
{
mv.setOnPanChangeListener(this);
}
public void turnOff ()
{
mv.setOnPanChangeListener(null);
}
}
// EnhancedMapView
import java.util.Timer;
import java.util.TimerTask;
import android.content.Context;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapView;
public class EnhancedMapView extends MapView {
public interface OnZoomChangeListener {
public void onZoomChange(MapView view, int newZoom, int oldZoom);
}
public interface OnPanChangeListener {
public void onPanChange(MapView view, GeoPoint newCenter, GeoPoint oldCenter);
}
private EnhancedMapView _this;
// Set this variable to your preferred timeout
private long events_timeout = 500L;
private boolean is_touched = false;
private GeoPoint last_center_pos;
private int last_zoom;
private Timer zoom_event_delay_timer = new Timer();
private Timer pan_event_delay_timer = new Timer();
private EnhancedMapView.OnZoomChangeListener zoom_change_listener;
private EnhancedMapView.OnPanChangeListener pan_change_listener;
public EnhancedMapView(Context context, String apiKey) {
super(context, apiKey);
_this = this;
last_center_pos = this.getMapCenter();
last_zoom = this.getZoomLevel();
}
public EnhancedMapView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public EnhancedMapView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
public void setOnZoomChangeListener(EnhancedMapView.OnZoomChangeListener l) {
zoom_change_listener = l;
}
public void setOnPanChangeListener(EnhancedMapView.OnPanChangeListener l) {
pan_change_listener = l;
}
#Override
public boolean onTouchEvent(MotionEvent ev) {
if (ev.getAction() == 1) {
is_touched = false;
} else {
is_touched = true;
}
return super.onTouchEvent(ev);
}
#Override
public void computeScroll() {
super.computeScroll();
if (getZoomLevel() != last_zoom) {
// if computeScroll called before timer counts down we should drop it and start it over again
zoom_event_delay_timer.cancel();
zoom_event_delay_timer = new Timer();
zoom_event_delay_timer.schedule(new TimerTask() {
#Override
public void run() {
zoom_change_listener.onZoomChange(_this, getZoomLevel(), last_zoom);
last_zoom = getZoomLevel();
}
}, events_timeout);
}
// Send event only when map's center has changed and user stopped touching the screen
if (!last_center_pos.equals(getMapCenter()) && !is_touched) {
pan_event_delay_timer.cancel();
pan_event_delay_timer = new Timer();
try
{
pan_event_delay_timer.schedule(new TimerTask() {
#Override
public void run() {
try
{
pan_change_listener.onPanChange(_this, getMapCenter(), last_center_pos);
last_center_pos = getMapCenter();
}
catch (IllegalArgumentException e)
{
Log.v("IllegalArgumentException", e.toString());
}
catch (IllegalStateException e)
{
Log.v("IllegalStateException", e.toString());
}
catch (NullPointerException e)
{
Log.v("NullPointerException", e.toString());
}
}
}, events_timeout);
}
catch (IllegalArgumentException e)
{
Log.v("IllegalArgumentException", e.toString());
}
catch (IllegalStateException e)
{
Log.v("IllegalStateException", e.toString());
}
catch (NullPointerException e)
{
Log.v("NullPointerException", e.toString());
}
}
}
}
Why does this app stop answering then I press play? It sometimes show a "the application is not responding" but it works if I wait.
It works nice on my emulator, but not on my phone (or any other phone I tried).
All it does is streaming sound.
package comunicera.se;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import android.app.ListActivity;
import android.content.Context;
import android.media.MediaPlayer;
import android.net.ConnectivityManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Html;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ProgressBar;
import android.widget.TextView;
public class Godnattsaga extends ListActivity {
/** Called when the activity is first created. */
ListView list;
TextView spelandesSagqa;
//private ProgressDialog mProgressDialog;
ProgressBar myProgressBar;
int myProgress = 0;
MediaPlayer mp = new MediaPlayer();
String BASEURL = "http://godnattsaga.nu/sagor";
public static long glCurrentSaga = 0;
public static String giCode = null;
int giAntalSagor = 0;
int possWhenPaused = 0;
ProgressBar myBufferProgressBar;
TextView buffrarText;
int progress;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
try
{
new Thread(buffer).start();
String lsSagor = getFileFromUrl(BASEURL+"/gratisSagor.txt");
final String[] laList = lsSagor.split("~");
giAntalSagor = laList.length;
//String saga = laList[0].replaceAll("#", "\n");
String[] laSaga = laList[0].split("#");
final String[] guiLaList = new String[giAntalSagor];
for (int i = 0; i < giAntalSagor; i++)
{
guiLaList[i] = laList[i].replaceAll("#", "\n");
}
changeSpelandesSaga(laSaga[0]);
setList (guiLaList);
ListView list = getListView();
list.setTextFilterEnabled(true);
list.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
String liCode = kop(id);
glCurrentSaga = id;
String[] laSaga = laList[(int) glCurrentSaga].split("#");
changeSpelandesSaga(laSaga[0]);
}
});
final Button button = (Button) findViewById(R.id.SpelaPause);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
selectDownloadOrPLay(laList);
}
});
glCurrentSaga = 0;
changeSpelandesSaga(laSaga[0]);
}
catch (Exception e)
{
changeSpelandesSaga("Check your connection, are you in flightmode?");
}
}
public void selectDownloadOrPLay(String[] laList) {
String[] laSaga = laList[(int) glCurrentSaga].split("#");
String url = BASEURL+"/gratis/"+laSaga[0].replaceAll(" ", "_")+".mp3";
if (mp.isPlaying())
{
mp.pause();
possWhenPaused=mp.getCurrentPosition();
}
else if (possWhenPaused != 0)
{
mp.start();
}
else
{
startSaga (url);
}
}
private String kop(long id)
{
mp.pause();
return "gratis";
}
public void setList (String[] laList)
{
/*
*
final String[] lAList = new String[3];
lAList[0] = "Saga 1 \n";
lAList[1] = "Saga 2 \n";
lAList[2] = "Saga 3";
setList (lAList);
*
*/
setContentView(R.layout.main);
ArrayAdapter<String> appointmentList = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, laList);
list=(ListView)findViewById(android.R.id.list);
list.setAdapter(appointmentList);
}
public void changeSpelandesSaga(String sagaRubrik)
{
possWhenPaused = 0;
TextView t = new TextView(this);
t=(TextView)findViewById(R.id.spelandesSaga);
t.setText(Html.fromHtml("<b>"+sagaRubrik+"</b>"));
}
private void startSaga(String url)
{
try {
mp.reset();
mp.setDataSource(url);
mp.prepare();
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
mp.start();
myProgressBar=(ProgressBar)findViewById(R.id.mProgressDialog);
new Thread(myThread).start();
}
private Runnable myThread = new Runnable(){
#Override
public void run() {
// TODO Auto-generated method stub
while (myProgress<100){
try{
myHandle.sendMessage(myHandle.obtainMessage());
Thread.sleep(1000);
}
catch(Throwable t){
}
}
}
Handler myHandle = new Handler(){
double poss = 0.0;
double sagaleng = 0.0;
#Override
public void handleMessage(Message msg) {
// TODO Auto-generated method stub
poss = mp.getCurrentPosition();
sagaleng = mp.getDuration();
progress = (int) ((int)poss / sagaleng * 100);
myProgress = progress;
myProgressBar.setProgress(progress);
}
};
};
public static String getFileFromUrl(String url)
{
InputStream content = null;
try
{
HttpGet httpGet = new HttpGet(url);
HttpClient httpclient = new DefaultHttpClient();
// Execute HTTP Get Request
HttpResponse response = httpclient.execute(httpGet);
content = response.getEntity().getContent();
}
catch (Exception e)
{
showNoConnection ();
return null;
}
BufferedReader rd = new BufferedReader(new InputStreamReader(content), 4096);
String line;
StringBuilder sb = new StringBuilder();
try {
while ((line = rd.readLine()) != null) {
sb.append(line);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
rd.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return sb.toString();
}
public boolean isOnline() {
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
boolean connected = cm.getActiveNetworkInfo().isConnectedOrConnecting();
return connected;
}
private static void showNoConnection()
{
}
private Runnable buffer = new Runnable(){
#Override
public void run() {
// TODO Auto-generated method stub
while (myProgress<100){
try{
myHandle.sendMessage(myHandle.obtainMessage());
Thread.sleep(1000);
}
catch(Throwable t)
{
}
}
}
Handler myHandle = new Handler(){
#Override
public void handleMessage(Message msg) {
// TODO Auto-generated method stub
//SpelaPause.setImageURI("pauseicon");
myBufferProgressBar = (ProgressBar)findViewById(R.id.mBuffrar);
TextView bufferText = (TextView)findViewById(R.id.buffrarText);
if (mp.isPlaying() && progress == 0)
{
myBufferProgressBar.setVisibility(View.VISIBLE);
bufferText.setVisibility(View.VISIBLE);
}
else
{
myBufferProgressBar.setVisibility(View.INVISIBLE);
bufferText.setVisibility(View.INVISIBLE);
}
}
};
};
}
If your application uses internet, it is possible, that the phone has worse connection than your comp. For example, if they both run on the SAME WiFi, at the same point, phones are connected MUCH worse than PC. Slower connection - you have to wait...
Read http://developer.android.com/guide/practices/design/responsiveness.html and http://developer.android.com/guide/practices/design/performance.html - VERY useful. For example, you will know the name of your problem - bad responsiveness (not performance) - for better further searches. :-)
All long-lasting tasks should be run in separate thread, not in UI thread. You call getFileFromUrl(..) from onCreate(..) method. This cause hangings.
I recommend you not to do any time consuming task in onCreate(..) method. In general an activity won't be shown till onCreate(..) is finished.
You are using getFileFromUrl in your onCreate method. Your method just performs the download action, which in case could last some time. You should always move long running tasks into it's own thread and notify the UI thread only.
Consider never running big logic in the UI thread, the UI thread should only be responsible for UI stuff.
To download a file in an async manner try to use the AsyncTask: http://developer.android.com/reference/android/os/AsyncTask.html
This code works, without responsiveness problems. But the buffering takes to long time so I need another solution.
I'm posting some code if someone else have the same problem
package comunicera.se;
import java.io.IOException;
import android.app.Activity;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
public class GodnattsagaTest1 extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final Button button = (Button) findViewById(R.id.SpelaPause);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
selectDownloadOrPLay();
}
});
}
public void selectDownloadOrPLay() {
Toast.makeText(getApplicationContext(), "Before ... ", Toast.LENGTH_SHORT).show();
Saga.startSaga ();
Toast.makeText(getApplicationContext(), "after ... ", Toast.LENGTH_SHORT).show();
}
}
class Saga
{
static MediaPlayer mp = new MediaPlayer();
static void startSaga()
{
new Thread(spelaSaga).start();
}
private static Runnable spelaSaga = new Runnable(){
#Override
public void run() {
// TODO Auto-generated method stub
try {
mp.reset();
mp.setDataSource("http://godnattsaga.nu/sagor/gratis/Fisken.mp3");
mp.prepare();
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
mp.start();
}
};
}
I believe it has something to do with the progress bar you use. I use one and it slows my app. Not sure if the progress bar must slow the app or there is another way to avoid this though.