Related
when I listen push message from BroadcastReceiver I can take message but it makes slow other services for example I am sending "Message is taken" to my web service when I take push message but I can't send to my webservice it works very slowly when I listen to BroadcastReceiver for take message and when I delete BroadcastReceiver I can send message to my webservice very fastly
package jsonparse;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Looper;
import android.os.Message;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import com.androidhive.pushnotifications.MapsActivity;
import com.androidhive.pushnotifications.R;
import com.androidhive.pushnotifications.ServerUtilities;
import com.androidhive.pushnotifications.WakeLocker;
import com.daasuu.ahp.AnimateHorizontalProgressBar;
import com.google.android.gcm.GCMRegistrar;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import static com.androidhive.pushnotifications.CommonUtilities.DISPLAY_MESSAGE_ACTION;
import static com.androidhive.pushnotifications.CommonUtilities.EXTRA_MESSAGE;
import static com.androidhive.pushnotifications.CommonUtilities.SENDER_ID;
public class ListViewAdapter extends BaseAdapter implements OnClickListener{
// Declare Variables
Context context;
LayoutInflater inflater;
ArrayList<HashMap<String, String>> data;
ImageLoader imageLoader;
HashMap<String, String> resultp = new HashMap<String, String>();
//ProgressBar mprogressBar;
TextView fulness;
TextView location_info;
TextView descrip;
JSONObject jsonobject;
private Handler mHandler = new Handler();
private int mProgressStatus=0;
String get_enlem,get_boylam;
double dble_get_enlem,dble_get_boylam;
String dest_city_name,dest_state_name,dest_country_name;
NetworkInfo ni;
ConnectivityManager cm;
String get_location;
String device_id;
String sonuc;
SharedPreferences prefs;
String get_groupID, get_customerID;
String get_desc;
String get_toplam;
// Asyntask
AsyncTask<Void, Void, Void> mRegisterTask;
public static String name;
public static String email;
Context con;
public ListViewAdapter(Context context,
ArrayList<HashMap<String, String>> arraylist) {
this.context = context;
data = arraylist;
imageLoader = new ImageLoader(context);
}
#Override
public int getCount() {
return data.size();
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
public View getView(final int position, View convertView, ViewGroup parent) {
// Declare Variables
/*
TextView rank;
TextView country;
TextView population;
ImageView flag;
*/
TextView location;
AnimateHorizontalProgressBar progressBar;
Button cop_toplandi;
inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View itemView = inflater.inflate(R.layout.listview_item, parent, false);
// Get the position
resultp = data.get(position);
// Locate the TextViews in listview_item.xml
//rank = (TextView) itemView.findViewById(R.id.rank);
//country = (TextView) itemView.findViewById(R.id.country);
//population = (TextView) itemView.findViewById(R.id.population);
//Get Device IMEI number
TelephonyManager telephonyManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
device_id = telephonyManager.getDeviceId();
Log.i("IMEI NUMBER", device_id);
// Getting name, email from intent
Intent i = ((Activity) context).getIntent();
name = i.getStringExtra("get_message_name");
email = i.getStringExtra("email");
Handler handler = new Handler();
final Runnable r = new Runnable() {
public void run() {
// Make sure the device has the proper dependencies.
GCMRegistrar.checkDevice(context);
// Make sure the manifest was properly set - comment out this line
// while developing the app, then uncomment it when it's ready.
GCMRegistrar.checkManifest(context);
context.registerReceiver(mHandleMessageReceiver, new IntentFilter(
DISPLAY_MESSAGE_ACTION));
// Get GCM registration id
final String regId = GCMRegistrar.getRegistrationId(context);
// Check if regid already presents
if (regId.equals("")) {
// Registration is not present, register now with GCM
GCMRegistrar.register(context, SENDER_ID);
} else {
// Device is already registered on GCM
if (GCMRegistrar.isRegisteredOnServer(context)) {
// Skips registration.
// Toast.makeText(getApplicationContext(), "Already registered with GCM", Toast.LENGTH_LONG).show();
} else {
// Try to register again, but not in the UI thread.
// It's also necessary to cancel the thread onDestroy(),
// hence the use of AsyncTask instead of a raw thread.
final Context contextm = context;
mRegisterTask = new AsyncTask<Void, Void, Void>() {
#Override
protected Void doInBackground(Void... params) {
// Register on our server
// On server creates a new user
ServerUtilities.register(contextm, name, email, regId);
return null;
}
#Override
protected void onPostExecute(Void result) {
mRegisterTask = null;
}
};
mRegisterTask.execute(null, null, null);
}
}
}
};
handler.postDelayed(r, 1000);
prefs = context.getSharedPreferences("login_page", context.MODE_PRIVATE);
get_groupID = prefs.getString("user_groupID", "alınmadı");
get_customerID = prefs.getString("user_customerID", "alınmadı");
if (get_groupID.equals("null")) {
get_groupID = "0";
}
if (get_customerID.equals("null")) {
get_customerID = "0";
}
location = (TextView) itemView.findViewById(R.id.location);
progressBar = (AnimateHorizontalProgressBar) itemView.findViewById(R.id.animate_progress_bar);
fulness = (TextView) itemView.findViewById(R.id.txt_percentage_of_fulness);
descrip = (TextView) itemView.findViewById(R.id.txt_desc);
get_location = resultp.get(MainActivity.COUNTRY);
cop_toplandi = (Button) itemView.findViewById(R.id.secret_button);
cop_toplandi.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(context.getApplicationContext(),"Başarıyla Gönderildi",Toast.LENGTH_SHORT).show();
new Send_save_status().execute();
}
});
location_info = (TextView) itemView.findViewById(R.id.location_info);
// Locate the ImageView in listview_item.xml
//flag = (ImageView) itemView.findViewById(R.id.flag);
// Capture position and set results to the TextViews
//rank.setText(resultp.get(MainActivity.RANK));
//country.setText(resultp.get(MainActivity.COUNTRY));
//population.setText(resultp.get(MainActivity.POPULATION));
location.setText(resultp.get(MainActivity.COUNTRY));
location_info.setText(resultp.get(MainActivity.Location_info));
String get_descrip = resultp.get(MainActivity.DESCB);
if(get_descrip != "0"){
descrip.setText(resultp.get(MainActivity.DESCB));
cop_toplandi.setVisibility(View.VISIBLE);
}
get_enlem = resultp.get(MainActivity.POPULATION);
get_boylam = resultp.get(MainActivity.FLAG);
get_toplam = resultp.get(MainActivity.Toplam);
//dble_get_enlem = Double.parseDouble(get_enlem);
//dble_get_boylam = Double.parseDouble(get_boylam);
// Capture position and set results to the ImageView
// Passes flag images URL into ImageLoader.class
//imageLoader.DisplayImage(resultp.get(MainActivity.FLAG), flag);
// Capture ListView item click
String a = resultp.get(MainActivity.RANK);
int b = Integer.parseInt(a);
progressBar.setMax(100);
progressBar.setProgress(b);
//progressBar.setProgressWithAnim(b);
fulness.setText("%"+(b*1));
//mprogressBar = (ProgressBar) itemView.findViewById(R.id.progressBar);
//mprogressBar.setProgress(b);
/*
ObjectAnimator anim = ObjectAnimator.ofInt(mprogressBar, "progress", 0, 80);
anim.setDuration(5000);
anim.setInterpolator(new DecelerateInterpolator());
anim.start();
*/
/*
//Get location name from latitude and longitude
Geocoder geocoder = new Geocoder(context, Locale.getDefault());
List<Address> addresses = null;
try {
addresses = geocoder.getFromLocation(dble_get_enlem, dble_get_boylam, 1);
} catch (IOException e) {
e.printStackTrace();
}
dest_city_name = addresses.get(0).getAddressLine(0);
dest_state_name = addresses.get(0).getAddressLine(1);
dest_country_name = addresses.get(0).getAddressLine(2);
location_info.setText(dest_city_name + " " + dest_country_name);
*/
itemView.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
ni = cm.getActiveNetworkInfo();
if (ni != null && ni.isConnected()) {
Toast.makeText(context,context.getString(R.string.progressdialog_message), Toast.LENGTH_SHORT).show();
// Get the position
resultp = data.get(position);
Intent intent = new Intent(context, MapsActivity.class);
// Pass all data rank
intent.putExtra("level", resultp.get(MainActivity.RANK));
// Pass all data country
intent.putExtra("imei", resultp.get(MainActivity.COUNTRY));
// Pass all data population
intent.putExtra("enlem",resultp.get(MainActivity.POPULATION));
// Pass all data flag
intent.putExtra("boylam", resultp.get(MainActivity.FLAG));
// Start SingleItemView Class
context.startActivity(intent);
}else{
Toast.makeText(context.getApplicationContext(),context.getApplicationContext().getString(R.string.network_connection),Toast.LENGTH_SHORT).show();
}
}
});
return itemView;
}
#Override
public void onClick(View v) {
switch (v.getId()){
}
}
/**
* Receiving push messages
* */
private final BroadcastReceiver mHandleMessageReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String newMessage = intent.getExtras().getString(EXTRA_MESSAGE);
// Waking up mobile if it is sleeping
WakeLocker.acquire(context);
//context.sendBroadcast(new Intent("com.google.android.intent.action.GTALK_HEARTBEAT"));
//context.sendBroadcast(new Intent("com.google.android.intent.action.MCS_HEARTBEAT"));
// Showing received message
//lblMessage.append(newMessage + "\n");
//Toast.makeText(getApplicationContext(), "New Message: " + newMessage, Toast.LENGTH_LONG).show();
//descrip.setText(newMessage);
// Intent go = new Intent(context.getApplicationContext(),IsEmri.class);
//context.startActivity(go);
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("Acil Durum!!!");
builder.setMessage(newMessage)
.setCancelable(false)
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// TODO: handle the OK
}
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog alertDialog = builder.create();
alertDialog.show();
// Releasing wake lock
WakeLocker.release();
}
};
/*
Send GroupID and customerID every five minutes to services
*/
private class Send_save_status extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Create a progressdialog
}
#Override
protected Void doInBackground(Void... params) {
//Toast.makeText(getApplicationContext(), getApplicationContext().getString(R.string.gprs_adres) + address, Toast.LENGTH_LONG).show();
// make sure you close the gps after using it. Save user's battery power
//mGPSService.closeGPS();
StringBuilder str_url = new StringBuilder();
str_url.append("http://78.186.62.169:8090/TrackBinSvc.svc/saveStatus/");
Log.i("str_url1", "" + str_url);
str_url.append(device_id + "/");
Log.i("strl_url2", "" + str_url);
str_url.append(get_location + "/");
Log.i("strl_url3", "" + str_url);
str_url.append("opened" + "/");
Log.i("strl_url3", "" + str_url);
str_url.append(get_groupID + "/");
Log.i("strl_url3", "" + str_url);
str_url.append(get_customerID);
Log.i("strl_url3", "" + str_url);
String str = str_url.toString();
//"http://192.168.0.39:8090/TrackBinSvc.svc/Get_All_Mobile/admin/1234"
try {
jsonobject = JSONfunctions
.getJSONfromURL(str);
// Locate the array name in JSON
sonuc = jsonobject.getString("SendUpdateCordinatesResult");
} catch (JSONException e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void args) {
}
}
}
Problem is: The broadcast receiver that you are registering is implemented on the Main thread. The broadcast receiver handler is ALWAYS EXECUTED ON THE MAIN THREAD, thus, making your entire process slower. To implement receiver's own thread, you can explicitly do so by providing it's own Handler thread.
Register your broadcast receiver like this:
HandlerThread receiverHandlerThread = new HandlerThread("threadName");
receiverHandlerThread.start();
Looper looper = receiverHandlerThread.getLooper();
Handler handler = new Handler(looper);
context.registerReceiver(mHandleMessageReceiver,newIntentFilter(DISPLAY_MESSAGE_ACTION),null,handler);
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
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.
import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.entity.BufferedHttpEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.view.ViewParent;
import android.webkit.WebView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.ViewAnimator;
public class NewsScreenAdapter extends BaseAdapter {
LayoutInflater inflater;
public GifDecoderView webview1;
public static viewholder holder;
View view = null;
public static Context context;
public ImageLoader IL;
public String imgUrl;
public static String addurl;
public NewsScreenActivity activity;
String image;
public static String str;
public static Date parsed;
public static String ac, cat_id;
int storyLenght;
public NewsScreenAdapter(NewsScreenActivity a) {
// TODO Auto-generated constructor stub
context = a.getApplicationContext();
this.activity = a;
inflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
IL = new ImageLoader(activity.getApplicationContext());
}
#Override
public int getCount() {
// TODO Auto-generated method stub
// return NewsScreenActivity.arrayList_header.size();
return NewsScreenActivity.TotalDataArray.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public int getItemViewType(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public int getViewTypeCount() {
// TODO Auto-generated method stub
return NewsScreenActivity.TotalDataArray.size();
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
View vi = convertView;
holder = new viewholder();
vi = inflater.inflate(R.layout.newsscren_row, null);
holder.news_header_title = (TextView) vi.findViewById(R.id.header_title);
holder.ll_data = (LinearLayout) vi.findViewById(R.id.data);
vi.setTag(holder);
holder.news_header_title.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
cat_id = NewsScreenActivity.arrayList_header.get(position);
ac = ((NewsScreenActivity.MainData) NewsScreenActivity.TotalDataArray.get(position)).catId;
activity.startActivity(new Intent(activity,CategoryActivity.class).putExtra("id", ac));
}
});
holder.ll_data.removeAllViews();
try {
storyLenght = ((NewsScreenActivity.MainData) NewsScreenActivity.TotalDataArray.get(position)).storyArr.size();
} catch (Exception e) {
// TODO: handle exception
}
Log.d("Adapter ", " story Lenght " + storyLenght);
for (int i = 0; i < storyLenght; i++) {
view = LayoutInflater.from(activity).inflate(R.layout.sub_row, null);
holder.short_text = (TextView) view.findViewById(R.id.short_text);
holder.image = (ImageView) view.findViewById(R.id.image);
holder.des = (TextView) view.findViewById(R.id.des);
holder.date_time = (TextView) view.findViewById(R.id.date_time);
holder.llAdd = (LinearLayout) view.findViewById(R.id.sub_llAdd);
holder.imgAdd = (ImageView) view.findViewById(R.id.imgAdd);
try{
holder.image.setTag(NewsScreenActivity.arrayList_image.get(i));
IL.DisplayImage(
((NewsScreenActivity.ImagesData) ((NewsScreenActivity.StoryData) ((NewsScreenActivity.MainData) NewsScreenActivity.TotalDataArray
.get(position)).storyArr.get(i)).imageArr.get(0)).smallurl, activity, holder.image);
notifyDataSetChanged();
} catch (Exception e) {
// TODO: handle exception
}
try {
holder.short_text.setText(((NewsScreenActivity.StoryData) ((NewsScreenActivity.MainData) NewsScreenActivity.TotalDataArray.get(position)).storyArr.get(i)).title);
holder.des.setText(((NewsScreenActivity.StoryData) ((NewsScreenActivity.MainData) NewsScreenActivity.TotalDataArray.get(position)).storyArr.get(i)).description);
String st = ((NewsScreenActivity.StoryData) ((NewsScreenActivity.MainData) NewsScreenActivity.TotalDataArray
.get(position)).storyArr.get(i)).date;
parsed = new Date(Long.parseLong(st.substring(6, st.length() - 2)));
SimpleDateFormat sdf = new SimpleDateFormat("MMM dd,yyyy hh:mmaa");
System.out.println(sdf.format(parsed));
String concat = sdf.format(parsed);
String data = concat;
String half1 = data.substring(0, 11);
Log.e("1st date", "" + half1);
SimpleDateFormat display_date = new SimpleDateFormat("dd.MM.yyyy");
Date d_date = new Date();
String dis_date = display_date.format(parsed);
String half2 = data.substring(11, 19);
Log.e("2st time", "" + half2);
SimpleDateFormat currentdate = new SimpleDateFormat("MMM dd,yyyy");
Date currunt = new Date();
String day = currentdate.format(currunt);
if (half1.equalsIgnoreCase(day) == true) {
holder.date_time.setText(half2);
Log.v("if condition", "" + half2);
} else {
half1 = dis_date;
holder.date_time.setText(half1);
Log.v("else condition", "" + half1);
}
Log.e("currunt time", "" + day);
holder.news_header_title.setText(((NewsScreenActivity.MainData) NewsScreenActivity.TotalDataArray
.get(position)).catDisplay);
if (!((NewsScreenActivity.StoryData) ((NewsScreenActivity.MainData) NewsScreenActivity.TotalDataArray
.get(position)).storyArr.get(i)).advertising
.equalsIgnoreCase("null")) {
holder.short_text.setVisibility(view.GONE);
holder.date_time.setVisibility(view.GONE);
holder.des.setVisibility(view.GONE);
imgUrl = ((NewsScreenActivity.StoryData) ((NewsScreenActivity.MainData) NewsScreenActivity.TotalDataArray
.get(position)).storyArr.get(i)).adData.imageurl;
// TODO Auto-generated method stub
addurl = ((NewsScreenActivity.StoryData) ((NewsScreenActivity.MainData) NewsScreenActivity.TotalDataArray
.get(position)).storyArr.get(i)).adData.targeturl;
//-----------------GIF Image view ------------
//holder.imgAdd.setImageBitmap(IL.getBitmap(imgUrl));
holder.imgAdd.setImageBitmap(loadImageFromUrl(imgUrl));
/* InputStream is = null;
try {
is = (InputStream) new URL(imgUrl).getContent();
webview1 = new GifDecoderView(context, is);
activity.setContentView(webview1);
} catch (Exception e) {
return null;
}*/
try {
InputStream is = (InputStream) new URL(imgUrl).getContent();
GifDecoderView webview1 = new GifDecoderView(activity, is);
// GifMovieView webview1 = new GifMovieView(activity, is);
// holder.llAdd.addView(webview1, holder.imgAdd.getLayoutParams());
} catch (Exception e) {
// TODO: handle exception
}
holder.imgAdd.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
activity.startActivity(new Intent(activity, AdvertismentActivity.class));
}
});
Log.i("---", "---------" + imgUrl);
holder.llAdd.setVisibility(View.VISIBLE);
}
holder.ll_data.addView(view);
Log.i("Set Tag", position+"OK"+i);
view.setTag(position+"OK"+i);
view.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
String tag = (String) v.getTag();
String[] arr = tag.split("OK");
int p = Integer.parseInt(arr[0]);
int i = Integer.parseInt(arr[1]);
Log.i("Pos and I", p + " " + i );
str = ((NewsScreenActivity.StoryData) ((NewsScreenActivity.MainData) NewsScreenActivity.TotalDataArray .get(p)).storyArr.get(i)).storyid;
Log.i("Pos and I and STR", p + " " + i + " " + str);
Intent intent = new Intent(context,ShowFullDescriprion.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.putExtra("id", str);
intent.putExtra("cat", p);
intent.putExtra("pos",i);
context.startActivity(intent);
}
});
} catch (Exception e) {
// TODO: handle exception
}
}
return vi;
}
public static String getDate(long milliSeconds, String dateFormat) {
// Create a DateFormatter object for displaying date in specified
// format.
DateFormat formatter = new SimpleDateFormat(dateFormat);
// Create a calendar object that will convert the date and time value in
// milliseconds to date.
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(milliSeconds);
return formatter.format(calendar.getTime());
}
public static class viewholder {
TextView news_header_title, short_text, des, date_time;
LinearLayout ll_data, llAdd;
public ImageView image, imgAdd;
}
public static Bitmap loadImageFromUrl(String url) {
URL m;
InputStream i = null;
BufferedInputStream bis = null;
ByteArrayOutputStream out =null;
try {
m = new URL(url);
i = (InputStream) m.getContent();
bis = new BufferedInputStream(i,1024 * 8);
out = new ByteArrayOutputStream();
int len=0;
byte[] buffer = new byte[1024];
while((len = bis.read(buffer)) != -1){
out.write(buffer, 0, len);
}
out.close();
bis.close();
} catch (MalformedURLException e1) {
e1.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
byte[] data = out.toByteArray();
Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);
//Drawable d = Drawable.createFromStream(i, "src");
return bitmap;
}
}
import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONObject;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.StrictMode;
import android.text.Html;
import android.util.Log;
import android.view.GestureDetector;
import android.view.GestureDetector.SimpleOnGestureListener;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
public class ShowFullDescriprion extends Activity implements OnClickListener {
ImageView show_image, adv_image, refresh,show_home;
TextView title_text, des_text, date_time_txt;
Button back_btn;
LinearLayout ll, llAdv;
public static String url, full_des, advertising, adurl = "",img,
targeturl;
ProgressDialog progressDialog;
TextView mDisplay;
AsyncTask<Void, Void, Void> mRegisterTask;
String TAG = "ShowFullDescriprion";
public static ArrayList<String> catId = new ArrayList<String>();
public static ArrayList<String> catDisp = new ArrayList<String>();
public static ArrayList<String> next_arraylist = new ArrayList<String>();
public static ArrayList<String> privious_arraylist = new ArrayList<String>();
//public static ArrayList<String> arrayList_advertising = new ArrayList<String>();
SimpleGestureFilter simpleGestureFilter;
LinearLayout llCat;
TextView tvCatDisp;
private static final int SWIPE_MIN_DISTANCE = 200;
private static final int SWIPE_MAX_OFF_PATH = 250;
private static final int SWIPE_THRESHOLD_VELOCITY = 200;
int swpCnt = 0;
int SWIPE_MAX_VALUE = 1;
int PIC_WIDTH = 0;
private GestureDetector gestureDetector;
View.OnTouchListener gestureListener;
#SuppressWarnings("unused")
private Animation animleftin = null, animleftout = null,
animrightin = null, animrightout = null;
public static String idS, titleS, dateS, descS, next, privious, adv;
public static String bigimageS=null;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.showfull_description);
back_btn = (Button) findViewById(R.id.button1);
llCat = (LinearLayout) findViewById(R.id.llCategory);
// llCat.setOnClickListener(this);
adv_image = (ImageView) findViewById(R.id.imgAdd);
refresh = (ImageView) findViewById(R.id.refresh_btn);
show_home=(ImageView)findViewById(R.id.showfull_des_home);
llAdv = (LinearLayout) findViewById(R.id.llAdd);
// simpleGestureFilter = new SimpleGestureFilter(this, this);
// int SWIPE_MAX_VALUE_new = ((NewsScreenActivity.MainData) NewsScreenActivity.TotalDataArray.get(getIntent().getExtras().getInt("cat"))).storyArr.size();
//swpCnt = ((CategoryActivity.MainData) CategoryActivity.TotalDataArray.get(getIntent().getExtras().getInt("cat"))).storyArr.indexOf(getIntent().getExtras().getString("id"));
//((NewsScreenActivity.StoryData) ((NewsScreenActivity.MainData) NewsScreenActivity.TotalDataArray .get(p)).storyArr.get(i)).storyid;
//String temp = ((CategoryActivity.StoryData) ((CategoryActivity.MainData) CategoryActivity.TotalDataArray .get(getIntent().getExtras().getInt("cat"))).storyArr.get(getIntent().getExtras().getString("pos"))).storyid;
// Log.i("Show full Description .....", "********************** cat "+getIntent().getExtras().getInt("cat")+" **** id *** "+getIntent().getExtras().getString("id"));
//Log.i("Show full Description .....", "********************** SWIPE_MAX_VALUE_new "+ SWIPE_MAX_VALUE_new+" *** swpCnt **** "+temp +"**** Array *** "+((CategoryActivity.MainData) CategoryActivity.TotalDataArray.get(getIntent().getExtras().getInt("cat"))).storyArr.get(5));
try {
// SWIPE_MAX_VALUE = ((NewsScreenActivity.MainData) NewsScreenActivity.TotalDataArray.get(getIntent().getExtras().getInt("cat"))).storyArr.size();
SWIPE_MAX_VALUE = ((CategoryActivity.MainData) CategoryActivity.TotalDataArray.get(getIntent().getExtras().getInt("cat"))).storyArr.size();
swpCnt = getIntent().getExtras().getInt("pos");
} catch (Exception e) {
// TODO: handle exception
}
url = "http://maritimeglobalnews.com/json/story/"+ getIntent().getExtras().getString("id");
new StoryDataAsyn().execute();
title_text = (TextView) findViewById(R.id.show_full_des_title_txt);
show_image = (ImageView) findViewById(R.id.show_full_des_image);
des_text = (TextView) findViewById(R.id.show_full_des_txt);
date_time_txt = (TextView) findViewById(R.id.show_full_des_datetime_txt);
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
show_home.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
startActivity(new Intent(getBaseContext(), NewsScreenActivity.class));
finish();
}
});
/* Log.i(TAG,
"================Inside OnCreate Method==============================");
checkNotNull(SERVER_URL, "SERVER_URL");
checkNotNull(SENDER_ID, "SENDER_ID");
// Make sure the device has the proper dependencies.
GCMRegistrar.checkDevice(getBaseContext());
// Make sure the manifest was properly set - comment out this line
// while developing the app, then uncomment it when it's ready.
GCMRegistrar.checkManifest(getBaseContext());
registerReceiver(mHandleMessageReceiver, new IntentFilter(
DISPLAY_MESSAGE_ACTION));
final String regId = GCMRegistrar.getRegistrationId(this);
if (regId.equals("")) {
Log.i(TAG,
"================Inside if in regId=null ==============================");
// Automatically registers application on startup.
GCMRegistrar.register(this, SENDER_ID);
} else {
Log.i(TAG,
"================Inside else in regId=null ==============================");
// Device is already registered on GCM, needs to check if it is
// registered on our server as well.
if (GCMRegistrar.isRegisteredOnServer(this)) {
// Skips registration.
Log.i(TAG,
"================Inside else in regId=null Already register on Server =============================");
mDisplay.append(getString(R.string.already_registered) + "\n");
} else {
Log.i(TAG,
"================Inside else in regId=null trying to register on Server =============================");
// Try to register again, but not in the UI thread.
// It's also necessary to cancel the thread onDestroy(),
// hence the use of AsyncTask instead of a raw thread.
final Context context = this;
mRegisterTask = new AsyncTask<Void, Void, Void>() {
#Override
protected Void doInBackground(Void... params) {
Log.i(TAG,
"================Inside doInBackground Method==============================");
boolean registered = ServerUtilities.register(context,
regId);
// At this point all attempts to register with the app
// server failed, so we need to unregister the device
// from GCM - the app will try to register again when
// it is restarted. Note that GCM will send an
// unregistered callback upon completion, but
// GCMIntentService.onUnregistered() will ignore it.
if (!registered) {
GCMRegistrar.unregister(context);
}
return null;
}
#Override
protected void onPostExecute(Void result) {
Log.i(TAG,
"================Inside onPostExecute Method==============================");
mRegisterTask = null;
}
};
mRegisterTask.execute(null, null, null);
}
} */
back_btn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
ShowFullDescriprion.this.finish();
}
});
refresh.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
new StoryDataAsyn().execute();
}
});
gestureDetector = new GestureDetector(new MyGestureDetector());
gestureListener = new View.OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
return gestureDetector.onTouchEvent(event);
}
};
prepareAnimations();
}
#Override
public boolean onTouchEvent(MotionEvent event) {
// TODO Auto-generated method stub
return super.onTouchEvent(event);
}
/*boolean net;
//onCreate
net = void isOnline() {
}
if (net == true)
{
//perform internet related tasks in the app
}
//function
public boolean isOnline1() {
ConnectivityManager cm = (ConnectivityManager) this
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = cm.getActiveNetworkInfo();
return activeNetworkInfo != null;
// return cm.getActiveNetworkInfo().isConnected();
}*/
public class StoryDataAsyn extends AsyncTask<Void, Void, Void> {
// NewsScreenActivity obj = new NewsScreenActivity();
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
// if (isNetworkConnected() == true)
// {
progressDialog = new ProgressDialog(ShowFullDescriprion.this);
progressDialog.setMessage("Loding ...");
progressDialog.setCancelable(false);
progressDialog.show();
/* } else {
AlertDialog connection = new AlertDialog.Builder(
ShowFullDescriprion.this)
.setTitle("No Network Found")
.setMessage(
"Internet Connection Reqired To Use this Application")
.setPositiveButton("Ok",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int whichButton)
{
}
}).create();
connection.show();
}
*/ }
#Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
catId.clear();
catDisp.clear();
getData(url);
return null;
}
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
if (isNetworkConnected() == true) {
progressDialog.dismiss();
title_text.setText(titleS);
/*if(bigimageS!= null && !bigimageS.equals(""))
{
show_image.setImageBitmap(decodeImage(bigimageS));
Log.v("if", ""+bigimageS);
}else
{
show_image.setImageBitmap(decodeImage(null));
Log.v("else", ""+bigimageS);
}
*/
if(isBlank(bigimageS)==true)
{
show_image.setVisibility(View.GONE);
show_image.setImageBitmap(decodeImage(null));
}
else if(isBlank(bigimageS)==false)
{
show_image.setImageBitmap(decodeImage(bigimageS));
}
// show_image.setImageBitmap(loadImageFromUrl(bigimageS));
//show_image.setImageBitmap(decodeImage(bigimageS));
des_text.setText(Html.fromHtml(descS));
Date parsed = new Date(Long.parseLong(dateS.substring(6,
dateS.length() - 2)));
SimpleDateFormat sdf = new SimpleDateFormat("MMM dd,yyyy hh:mmaa");
System.out.println(sdf.format(parsed));
date_time_txt.setText(sdf.format(parsed));
llCat.removeAllViews();
for (int i = 0; i < catId.size(); i++) {
tvCatDisp = new TextView(ShowFullDescriprion.this);
tvCatDisp.setText("");
tvCatDisp.setText(catDisp.get(i));
tvCatDisp.setBackgroundResource(R.drawable.box);
tvCatDisp.setTextColor(Color.BLACK);
tvCatDisp.setTextSize(18);
tvCatDisp.setTag(i);
Log.e("tvCatDisp............", ""+catDisp.get(i));
tvCatDisp.setOnClickListener(ShowFullDescriprion.this);
tvCatDisp.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
int pos = Integer.parseInt(v.getTag().toString());
startActivity(new Intent(ShowFullDescriprion.this,
CategoryActivity.class).putExtra("id",catId.get(pos)));
}
});
llCat.addView(tvCatDisp);
}
llAdv.removeAllViews();
if ((!adurl.equalsIgnoreCase("")) && adurl != null) {
llAdv.setVisibility(View.VISIBLE);
ImageLoader il = new ImageLoader(ShowFullDescriprion.this);
// adv_image.setImageBitmap(il.getBitmap(adurl));
// adv_image.setImageBitmap(loadImageFromUrl(adurl));
try {
InputStream is = (InputStream) new URL(adurl).getContent();
GifDecoderView webview1 = new GifDecoderView(ShowFullDescriprion.this, is);
// activity.setContentView(webview1);
llAdv.addView(webview1,adv_image.getLayoutParams());
// holder.imgAdd.setImageBitmap(IL.getBitmap(imgUrl));
} catch (Exception e) {
}
llAdv.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
// Intent showAdvIntent =new Intent(ShowFullDescriprion.this,AdvertismentActivity.class);
// showAdvIntent.putExtra("id",targeturl);
startActivity(new Intent(getBaseContext(),AdvertismentActivity.class));
Log.e("show add url...", ""+targeturl);
}
});
}
}else
{
llAdv.setVisibility(View.GONE);
AlertDialog connection = new AlertDialog.Builder(
ShowFullDescriprion.this)
.setTitle("No Network Found")
.setMessage(
"Internet Connection Reqired To Use this Application")
.setPositiveButton("Ok",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int whichButton)
{
// new StoryDataAsyn().execute();
progressDialog.dismiss();
}
}).create();
connection.show();
}
}
}
public boolean isNetworkConnected() {
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo ni = cm.getActiveNetworkInfo();
if (ni == null) {
return false;
} else
return true;
}
public void getData(String url) {
HttpClient client = new DefaultHttpClient();
HttpConnectionParams.setConnectionTimeout(client.getParams(), 10000); // Timeout
try {
HttpPost request = new HttpPost(url);
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpResponse res = httpClient.execute(request);
Log.i("Request", request.toString());
String JsonResponseData = EntityUtils.toString(res.getEntity());
Log.i("JSON", JsonResponseData);
JSONObject mainJsonObj = new JSONObject(JsonResponseData);
titleS = mainJsonObj.getString("Title");
dateS = mainJsonObj.getString("Date");
descS = mainJsonObj.getString("ContentHTML");
next = mainJsonObj.getString("NextStoryEID");
next_arraylist.add(next);
Log.e("next id", "" + next_arraylist);
Log.e("nextstring id", "" + next);
privious = mainJsonObj.getString("PrevStoryEID");
privious_arraylist.add(privious);
Log.e("privious id", "" + privious_arraylist);
Log.e("privious string id", "" + privious);
try {
JSONArray tmpAd = mainJsonObj.optJSONArray("advertising");
adurl = tmpAd.getJSONObject(0).getString("ImageUrl");
targeturl = tmpAd.getJSONObject(0).getString("TargetUrl");
Log.v("target url is", "" + targeturl);
} catch (Exception e) {
// TODO: handle exception
}
try {
JSONArray tmpimg = mainJsonObj.optJSONArray("images");
bigimageS = tmpimg.getJSONObject(0).getString("iPhoneBigImageURL");
Log.v("bigimageS is", "" + bigimageS);
} catch (Exception e) {
// TODO: handle exception
}
JSONArray categJsonArr = mainJsonObj.getJSONArray("categories");
for (int i = 0; i < categJsonArr.length(); i++) {
catId.add(categJsonArr.getJSONObject(i) .getString("CategoryEID"));
catDisp.add(categJsonArr.getJSONObject(i).getString("CategoryDisplay"));
}
} catch (Exception e) {
e.printStackTrace();
}
}
public static Bitmap loadImageFromUrl(String url) {
URL m;
InputStream i = null;
BufferedInputStream bis = null;
ByteArrayOutputStream out =null;
try {
m = new URL(url);
i = (InputStream) m.getContent();
bis = new BufferedInputStream(i,1024 * 8);
out = new ByteArrayOutputStream();
int len=0;
byte[] buffer = new byte[1024];
while((len = bis.read(buffer)) != -1){
out.write(buffer, 0, len);
}
out.close();
bis.close();
} catch (MalformedURLException e1) {
e1.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
byte[] data = out.toByteArray();
Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);
//Drawable d = Drawable.createFromStream(i, "src");
return bitmap;
}
public static Bitmap decodeImage(String arrayList_image) {
URL aURL;
try {
aURL = new URL(arrayList_image);
URLConnection conn = aURL.openConnection();
conn.connect();
InputStream is = conn.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is);
Bitmap bm = BitmapFactory.decodeStream(bis);
bis.close();
is.close();
return bm;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
public boolean dispatchTouchEvent(MotionEvent me) {
this.gestureDetector.onTouchEvent(me);
return super.dispatchTouchEvent(me);
}
class MyGestureDetector extends SimpleOnGestureListener {
#Override
public boolean onDown(MotionEvent e) {
// TODO Auto-generated method stub
return super.onDown(e);
}
#Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,
float velocityY) {
Log.e("Inside onfling", "Call");
if (Math.abs(e1.getY() - e2.getY()) > SWIPE_MAX_OFF_PATH)
return false;
// right to left swipe
if (e1.getX() - e2.getX() > SWIPE_MIN_DISTANCE && Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) {
url = "http://maritimeglobalnews.com/json/story/"+next;
new StoryDataAsyn().execute();
Log.d("url next mate", ""+url);
Log.d("right to left privious.....", ""+next_arraylist);
try {
Log.i("","swip count " + swpCnt+" ***** "+((CategoryActivity.MainData) CategoryActivity.TotalDataArray.get(getIntent().getExtras().getInt("cat"))).storyArr.size());
} catch (Exception e) {
// TODO: handle exception
}
if (swpCnt >= 0 && swpCnt < SWIPE_MAX_VALUE - 1)
{
swpCnt++;
/* url = "http://maritimeglobalnews.com/json/story/"+next;
new StoryDataAsyn().execute();
Log.d("url next mate", ""+url);
Log.d("right to left privious.....", ""+next_arraylist); */
}
}
else if (e2.getX() - e1.getX() > SWIPE_MIN_DISTANCE && Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY ){
url = "http://maritimeglobalnews.com/json/story/"+privious;
Log.v("previousid first if", ""+privious);
Log.i("right to left privious first if.....", ""+privious_arraylist);
new StoryDataAsyn().execute();
if (swpCnt > 0 && swpCnt <= SWIPE_MAX_VALUE - 1) {
swpCnt--;
/*url = "http://maritimeglobalnews.com/json/story/"+privious;
Log.v("url",""+url);
Log.v("previousid 2 if", ""+privious);
new StoryDataAsyn().execute(); */
}
try {
Log.i("","swip count " + swpCnt+" ***** "+((CategoryActivity.MainData) CategoryActivity.TotalDataArray.get(getIntent().getExtras().getInt("cat"))).storyArr.size());
} catch (Exception e) {
// TODO: handle exception
}
/*if (swpCnt > 0 && swpCnt <= SWIPE_MAX_VALUE - 1)
{
swpCnt--;
url = "http://maritimeglobalnews.com/json/story/"+privious;
Log.v("previousid 3 if", ""+privious);
Log.i("right to left privious. 3 if", ""+privious_arraylist);
new StoryDataAsyn().execute();
} */
}
return false;
}
}
private void prepareAnimations() {
animleftin = new TranslateAnimation(Animation.RELATIVE_TO_PARENT,
+1.0f, Animation.RELATIVE_TO_PARENT, 0.0f,
Animation.RELATIVE_TO_PARENT, 0.0f,
Animation.RELATIVE_TO_PARENT, 0.0f);
animleftout = new TranslateAnimation(Animation.RELATIVE_TO_PARENT,
0.0f, Animation.RELATIVE_TO_PARENT, -1.0f,
Animation.RELATIVE_TO_PARENT, 0.0f,
Animation.RELATIVE_TO_PARENT, 0.0f);
animrightin = new TranslateAnimation(Animation.RELATIVE_TO_PARENT,
-1.0f, Animation.RELATIVE_TO_PARENT, 0.0f,
Animation.RELATIVE_TO_PARENT, 0.0f,
Animation.RELATIVE_TO_PARENT, 0.0f);
animrightout = new TranslateAnimation(Animation.RELATIVE_TO_PARENT,
0.0f, Animation.RELATIVE_TO_PARENT, +1.0f,
Animation.RELATIVE_TO_PARENT, 0.0f,
Animation.RELATIVE_TO_PARENT, 0.0f);
}
/*#Override
protected void onDestroy() {
Log.i(TAG,
"================Inside OnDestroy Method==============================");
if (mRegisterTask != null) {
mRegisterTask.cancel(true);
}
unregisterReceiver(mHandleMessageReceiver);
GCMRegistrar.onDestroy(this);
super.onDestroy();
}
private void checkNotNull(Object reference, String name) {
Log.i(TAG,
"================Inside checkNotNull Method==============================");
if (reference == null) {
throw new NullPointerException(getString(R.string.error_config,
name));
}
}
private final BroadcastReceiver mHandleMessageReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
Log.i(TAG,
"================Inside OnReceive in BroadcastReceiver Method==============================");
String newMessage = intent.getExtras().getString(EXTRA_MESSAGE);
mDisplay.append(newMessage + "\n");
}
};*/
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (v == tvCatDisp) {
// TODO Auto-generated method stub
startActivity(new Intent(ShowFullDescriprion.this,
CategoryActivity.class).putExtra("id", catId.get((Integer)v.getTag())));
}
}
public static boolean isBlank(String string) {
if (bigimageS == null || bigimageS.length() == 0)
return true;
int l = bigimageS.length();
for (int i = 0; i < l; i++) {
if (!Character.isWhitespace(bigimageS.codePointAt(i)))
return false;
}
return true;
}
}
You're not reusing your list items. This is why the list is starting to "stutter".
There are a lot of answers on this problem that display the concept of reusing ListView items.
Like this one
In general: within your getView method, check if the convertView is null. If it is, inflate your view. If it's not null, just insert the items that you want to display. This should solve your stuttering list view problem.
Please use for existing layout in BaseAdpter as below
ViewHolder holder = null;
if ( convertView == null )
{
/* There is no view at this position, we create a new one.
In this case by inflating an xml layout */
convertView = mInflater.inflate(R.layout.listview_item, null);
holder = new ViewHolder();
holder.toggleOk = (ToggleButton) convertView.findViewById( R.id.togOk );
convertView.setTag (holder);
}
else
{
/* We recycle a View that already exists */
holder = (ViewHolder) convertView.getTag ();
}
this may helps you
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());
}
}
}
}