Weather App, how to get latitude and longitude from MapActivity - java

It's my first time using stackoverflow so sorry for my question. I have been learning java and swift for only 4-5 month, so I'm just a beginner.
I'm writing a simple app with google Map and some other features like Weather Activity.
Map Activity running perfectly, Weather Activity also, but only with static latitude and longitude:
asyncTask.execute("28.125696","-15.440090" );
How to implement get currentLocation.getLatitude(), currentLocation.getLongitude() from MainActivityWeather in asyncTask.execute(...); ?
Am I thinking right? Is it a good way to build a weather app with a current location data? Map Activity:
public class MapActivity extends AppCompatActivity implements OnMapReadyCallback, GoogleApiClient.OnConnectionFailedListener {
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
}
#Override
public void onMapReady(GoogleMap googleMap) {
Toast.makeText(this, "Map is Ready", Toast.LENGTH_SHORT).show();
Log.d(TAG, "onMapReady: map is ready");
mMap = googleMap;
if (mLocationPermissionsGranted) {
getDeviceLocation();
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
mMap.setMyLocationEnabled(true);
mMap.getUiSettings().setMyLocationButtonEnabled(false);
init();
}
}
private static final String TAG = "MapActivity";
private static final String FINE_LOCATION = Manifest.permission.ACCESS_FINE_LOCATION;
private static final String COURSE_LOCATION = Manifest.permission.ACCESS_COARSE_LOCATION;
private static final int LOCATION_PERMISSION_REQUEST_CODE = 1234;
private static final float DEFAULT_ZOOM = 15f;
public static final LatLngBounds LAT_LNG_BOUNDS = new LatLngBounds(
new LatLng(-40, -168), new LatLng(71, 136)
);
//widgets
private AutoCompleteTextView mSearchText;
private ImageView mGps;
//vars
private Boolean mLocationPermissionsGranted = false;
private GoogleMap mMap;
private FusedLocationProviderClient mFusedLocationProviderClient;
private PlaceAutoCompleteAdapter mPlaceAutoCompleteAdapter;
private GoogleApiClient mGoogleApiClient;
private PlaceInfo mPlace;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_map);
mSearchText = (AutoCompleteTextView) findViewById(R.id.input_search);
mGps = (ImageView) findViewById(R.id.ic_gps);
getLocationPermission();
BottomNavigationView bottomNav = findViewById(R.id.bottom_nav);
BottomNavigationViewHelper.removeShiftMode(bottomNav);
bottomNav.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()){
case R.id.nav_menu:
Intent intent0 = new Intent(MapActivity.this, MainActivity.class);
startActivity(intent0);
break;
case R.id.nav_note:
Intent intent1 = new Intent(MapActivity.this, MainListActivity.class);
startActivity(intent1);
break;
case R.id.nav_map:
break;
case R.id.nav_attraction:
Intent intent3 = new Intent(MapActivity.this, MainActivityGrid.class);
startActivity(intent3);
break;
}
return false;
}
});
}
private void init(){
Log.d(TAG, "init: initializing");
mGoogleApiClient = new GoogleApiClient
.Builder(this)
.addApi(Places.GEO_DATA_API)
.addApi(Places.PLACE_DETECTION_API)
.enableAutoManage(this, this)
.build();
mSearchText.setOnItemClickListener(mAutocompleteClickListener );
mPlaceAutoCompleteAdapter = new PlaceAutoCompleteAdapter(this, mGoogleApiClient, LAT_LNG_BOUNDS, null);
mSearchText.setAdapter(mPlaceAutoCompleteAdapter);
mSearchText.setOnEditorActionListener(new TextView.OnEditorActionListener() {
#Override
public boolean onEditorAction(TextView textView, int actionId, KeyEvent keyEvent) {
if(actionId == EditorInfo.IME_ACTION_SEARCH
|| actionId == EditorInfo.IME_ACTION_DONE
|| keyEvent.getAction() == KeyEvent.ACTION_DOWN
|| keyEvent.getAction() == KeyEvent.KEYCODE_ENTER){
//execute our method for searching
geoLocate();
}
return false;
}
});
mGps.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d(TAG, "onClick: clicked gps icon");
getDeviceLocation();
}
});
hideSoftKeyboard();
}
private void geoLocate(){
Log.d(TAG, "geoLocate: geolocating");
String searchString = mSearchText.getText().toString();
Geocoder geocoder = new Geocoder(MapActivity.this);
List<Address> list = new ArrayList<>();
try{
list = geocoder.getFromLocationName(searchString,1);
}catch (IOException e) {
Log.d(TAG, "geoLocate: IOException " +e.getMessage());
}
if(list.size() > 0 ){
Address address = list.get(0);
Log.d(TAG, "geoLocate: found a location "+ address.toString());
moveCamera(new LatLng(address.getLatitude(), address.getLongitude()), DEFAULT_ZOOM, address.getAddressLine(0));
}
}
private void getDeviceLocation(){
Log.d(TAG, "getDeviceLocation: getting the devices current location");
mFusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(this);
try{
if(mLocationPermissionsGranted){
final Task location = mFusedLocationProviderClient.getLastLocation();
location.addOnCompleteListener(new OnCompleteListener() {
#Override
public void onComplete(#NonNull Task task) {
if(task.isSuccessful()&& task.getResult() != null){
Log.d(TAG, "onComplete: found location!");
Location currentLocation = (Location) task.getResult();
moveCamera(new LatLng(currentLocation.getLatitude(), currentLocation.getLongitude()),
DEFAULT_ZOOM, "My location");
}else{
Log.d(TAG, "onComplete: current location is null");
Toast.makeText(MapActivity.this, "unable to get current location", Toast.LENGTH_SHORT).show();
}
}
});
}
}catch (SecurityException e){
Log.e(TAG, "getDeviceLocation: SecurityException: " + e.getMessage() );
}
}
private void moveCamera(LatLng latLng, float zoom, String title){
Log.d(TAG, "moveCamera: moving the camera to: lat: " + latLng.latitude + ", lng: " + latLng.longitude );
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, zoom));
if(!title.equals("My location")){
MarkerOptions options = new MarkerOptions().position(latLng).title(title);
mMap.addMarker(options);
}
hideSoftKeyboard();
}
private void initMap(){
Log.d(TAG, "initMap: initializing map");
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
mapFragment.getMapAsync(MapActivity.this);
}
private void getLocationPermission(){
Log.d(TAG, "getLocationPermission: getting location permissions");
String[] permissions = {Manifest.permission.ACCESS_FINE_LOCATION,
Manifest.permission.ACCESS_COARSE_LOCATION};
if(ContextCompat.checkSelfPermission(this.getApplicationContext(),
FINE_LOCATION) == PackageManager.PERMISSION_GRANTED){
if(ContextCompat.checkSelfPermission(this.getApplicationContext(),
COURSE_LOCATION) == PackageManager.PERMISSION_GRANTED){
mLocationPermissionsGranted = true;
initMap();
}else{
ActivityCompat.requestPermissions(this,
permissions,
LOCATION_PERMISSION_REQUEST_CODE);
}
}else{
ActivityCompat.requestPermissions(this,
permissions,
LOCATION_PERMISSION_REQUEST_CODE);
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
Log.d(TAG, "onRequestPermissionsResult: called.");
mLocationPermissionsGranted = false;
switch(requestCode){
case LOCATION_PERMISSION_REQUEST_CODE:{
if(grantResults.length > 0){
for(int i = 0; i < grantResults.length; i++){
if(grantResults[i] != PackageManager.PERMISSION_GRANTED){
mLocationPermissionsGranted = false;
Log.d(TAG, "onRequestPermissionsResult: permission failed");
return;
}
}
Log.d(TAG, "onRequestPermissionsResult: permission granted");
mLocationPermissionsGranted = true;
//initialize our map
initMap();
}
}
}
}
private void hideSoftKeyboard(){
this.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
}
private AdapterView.OnItemClickListener mAutocompleteClickListener = new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
hideSoftKeyboard();
final AutocompletePrediction item = mPlaceAutoCompleteAdapter.getItem(i);
final String placeId = item.getPlaceId();
PendingResult<PlaceBuffer> placeResult = Places.GeoDataApi
.getPlaceById(mGoogleApiClient, placeId);
placeResult.setResultCallback(mUpdatePlaceDetailsCallback);
}
};
private ResultCallback<PlaceBuffer> mUpdatePlaceDetailsCallback = new ResultCallback<PlaceBuffer>() {
#Override
public void onResult(#NonNull PlaceBuffer places) {
if (!places.getStatus().isSuccess()) {
Log.d(TAG, "onResult: Place query did not mplete successfully" + places.getStatus().toString());
places.release();
return;
}
final Place place = places.get(0);
try{
mPlace = new PlaceInfo();
mPlace.setName(place.getName().toString());
Log.d(TAG, "onResult: name: " + place.getName());
mPlace.setAddress(place.getAddress().toString());
Log.d(TAG, "onResult: address: " + place.getAddress());
mPlace.setAttributions(place.getAttributions().toString());
Log.d(TAG, "onResult: attributions: " + place.getAttributions());
mPlace.setId(place.getId());
Log.d(TAG, "onResult: id:" + place.getId());
mPlace.setLatlng(place.getLatLng());
Log.d(TAG, "onResult: latlng: " + place.getLatLng());
mPlace.setRating(place.getRating());
Log.d(TAG, "onResult: rating: " + place.getRating());
mPlace.setPhoneNumber(place.getPhoneNumber().toString());
Log.d(TAG, "onResult: phone number: " + place.getPhoneNumber());
mPlace.setWebsiteUri(place.getWebsiteUri());
Log.d(TAG, "onResult: website uri: " + place.getWebsiteUri());
Log.d(TAG, "onResult: place: " + mPlace.toString());
}catch (NullPointerException e){
Log.e(TAG, "onResult: NullPointerException: " + e.getMessage() );
}
moveCamera(new LatLng(place.getViewport().getCenter().latitude,
place.getViewport().getCenter().longitude), DEFAULT_ZOOM, mPlace.getName());
places.release();
}
};}
Wheather Activities:
public class MainActivityWeather extends AppCompatActivity {
private static final String TAG = "WeatherActivity";
TextView cityField, detailsField, currentTemperatureField, humidity_field, pressure_field, weatherIcon, updatedField;
Typeface weatherFont;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// getSupportActionBar().hide();
setContentView(R.layout.activity_main_weather);
weatherFont = Typeface.createFromAsset(getApplicationContext().getAssets(), "fonts/weathericons-regular-webfont.ttf");
cityField = (TextView)findViewById(R.id.city_field);
updatedField = (TextView)findViewById(R.id.updated_field);
detailsField = (TextView)findViewById(R.id.details_field);
currentTemperatureField = (TextView)findViewById(R.id.current_temperature_field);
humidity_field = (TextView)findViewById(R.id.humidity_field);
pressure_field = (TextView)findViewById(R.id.pressure_field);
weatherIcon = (TextView)findViewById(R.id.weather_icon);
weatherIcon.setTypeface(weatherFont);
Function.placeIdTask asyncTask =new Function.placeIdTask(new Function.AsyncResponse() {
public void processFinish(String weather_city, String weather_description, String weather_temperature, String weather_humidity, String weather_pressure, String weather_updatedOn, String weather_iconText, String sun_rise) {
cityField.setText(weather_city);
updatedField.setText(weather_updatedOn);
detailsField.setText(weather_description);
currentTemperatureField.setText(weather_temperature);
humidity_field.setText("Humidity: "+weather_humidity);
pressure_field.setText("Pressure: "+weather_pressure);
weatherIcon.setText(Html.fromHtml(weather_iconText));
}
});
asyncTask.execute( ); // asyncTask.execute("Latitude", "Longitude")
}}
public class Function {
private static final String OPEN_WEATHER_MAP_URL =
"http://api.openweathermap.org/data/2.5/weather?lat=%s&lon=%s&units=metric";
private static final String OPEN_WEATHER_MAP_API = "fdbf72863aba44b6fc7ce9e3324a689f";
public static String setWeatherIcon(int actualId, long sunrise, long sunset){
int id = actualId / 100;
String icon = "";
if(actualId == 800){
long currentTime = new Date().getTime();
if(currentTime>=sunrise && currentTime<sunset) {
icon = "";
} else {
icon = "";
}
} else {
switch(id) {
case 2 : icon = "";
break;
case 3 : icon = "";
break;
case 7 : icon = "";
break;
case 8 : icon = "";
break;
case 6 : icon = "";
break;
case 5 : icon = "";
break;
}
}
return icon;
}
public interface AsyncResponse {
void processFinish(String output1, String output2, String output3, String output4, String output5, String output6, String output7, String output8);
}
public static class placeIdTask extends AsyncTask<String, Void, JSONObject> {
public AsyncResponse delegate = null;//Call back interface
public placeIdTask(AsyncResponse asyncResponse) {
delegate = asyncResponse;//Assigning call back interfacethrough constructor
}
#Override
protected JSONObject doInBackground(String... params) {
JSONObject jsonWeather = null;
try {
jsonWeather = getWeatherJSON(params[0], params[1]);
} catch (Exception e) {
Log.d("Error", "Cannot process JSON results", e);
}
return jsonWeather;
}
#Override
protected void onPostExecute(JSONObject json) {
try {
if(json != null){
JSONObject details = json.getJSONArray("weather").getJSONObject(0);
JSONObject main = json.getJSONObject("main");
DateFormat df = DateFormat.getDateTimeInstance();
String city = json.getString("name").toUpperCase(Locale.US) + ", " + json.getJSONObject("sys").getString("country");
String description = details.getString("description").toUpperCase(Locale.US);
String temperature = String.format("%.2f", main.getDouble("temp"))+ "°";
String humidity = main.getString("humidity") + "%";
String pressure = main.getString("pressure") + " hPa";
String updatedOn = df.format(new Date(json.getLong("dt")*1000));
String iconText = setWeatherIcon(details.getInt("id"),
json.getJSONObject("sys").getLong("sunrise") * 1000,
json.getJSONObject("sys").getLong("sunset") * 1000);
delegate.processFinish(city, description, temperature, humidity, pressure, updatedOn, iconText, ""+ (json.getJSONObject("sys").getLong("sunrise") * 1000));
}
} catch (JSONException e) {
//Log.e(LOG_TAG, "Cannot process JSON results", e);
}
}
}
public static JSONObject getWeatherJSON(String lat, String lon){
try {
URL url = new URL(String.format(OPEN_WEATHER_MAP_URL, lat, lon));
HttpURLConnection connection =
(HttpURLConnection)url.openConnection();
connection.addRequestProperty("x-api-key", OPEN_WEATHER_MAP_API);
BufferedReader reader = new BufferedReader(
new InputStreamReader(connection.getInputStream()));
StringBuffer json = new StringBuffer(1024);
String tmp="";
while((tmp=reader.readLine())!=null)
json.append(tmp).append("\n");
reader.close();
JSONObject data = new JSONObject(json.toString());
// This value will be 404 if the request was not
// successful
if(data.getInt("cod") != 200){
return null;
}
return data;
}catch(Exception e){
return null;
}
}}

Related

This is code of image and video of instagram dowloading by link.. after downloading 4 ,5 photos or videos this code not work

This is code of image and video of instagram dowloading by link.. after downloading 4 ,5 photos or videos this code not work .and getting error findata class ..
public class FindData {
private Context context;
private GetDat getData;
String netsubType;
NetworkInfo activeNetworkInfo1;
Boolean s;
public FindData(Context context, GetDat getData) {
this.context = context;
this.getData = getData;
}
public void data(String stringData) {
ArrayList<String> arrayList = new ArrayList<>();
if (stringData.matches("https://www.instagram.com/(.*)")) {
String[] data = stringData.split(Pattern.quote("?"));
String string = data[0];
// if (isNetworklow()) {
//
// Toast.makeText(context, "network low", Toast.LENGTH_SHORT).show();
// }
if (isNetworkAvailable()) {
if (Method.isDownload) {
AsyncHttpClient client = new AsyncHttpClient();
client.get(string + "?__a=1", null, new AsyncHttpResponseHandler() {
#Override
public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
String res = new String(responseBody);
try {
JSONObject jsonObject = new JSONObject(res);
String link = null;
JSONObject objectGraphql = jsonObject.getJSONObject("graphql");
JSONObject objectMedia = objectGraphql.getJSONObject("shortcode_media");
boolean isVideo = objectMedia.getBoolean("is_video");
if (isVideo) {
link = objectMedia.getString("video_url");
} else {
link = objectMedia.getString("display_url");
}
arrayList.add(link);
try {
JSONObject objectSidecar = objectMedia.getJSONObject("edge_sidecar_to_children");
JSONArray jsonArray = objectSidecar.getJSONArray("edges");
arrayList.clear();
String edgeSidecar = null;
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject object = jsonArray.getJSONObject(i);
JSONObject node = object.getJSONObject("node");
boolean is_video_group = node.getBoolean("is_video");
if (is_video_group) {
edgeSidecar = node.getString("video_url");
} else {
edgeSidecar = node.getString("display_url");
}
arrayList.add(edgeSidecar);
}
} catch (Exception e) {
Log.e("error_show", e.toString());
}
getData.getData(arrayList, "", true);
Toast.makeText(context, "success", Toast.LENGTH_SHORT).show();
} catch (JSONException e) {
Log.e("........POOR NETWORK ........", e.toString());
getData.getData(arrayList, context.getResources().getString(R.string.not_support), false);
Toast.makeText(context, " poor network", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
Log.e("...........on failure +Tag............",error.toString());
Toast.makeText(context, "try again error", Toast.LENGTH_SHORT).show();
getData.getData(arrayList, context.getResources().getString(R.string.wrong), false);
}
});
} else {
getData.getData(arrayList,"ff ", false);
}
} else {
getData.getData(arrayList, context.getResources().getString(R.string.internet_connection), false);
Toast.makeText(context, "no network", Toast.LENGTH_SHORT).show();
}
} else {
getData.getData(arrayList, "invalid link copy again", false);
}
}
//network check
public boolean isNetworkAvailable() {
Log.e("TAG", "=============onFailure===============");
ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
assert connectivityManager != null;
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
//netsubType.equals( TelephonyManager.NETWORK_TYPE_EDGE)||netsubType.equals( TelephonyManager.NETWORK_TYPE_1xRTT ));
return activeNetworkInfo != null && activeNetworkInfo.isConnected();
}
}
public class DownloadService extends Service {
private int position = 0;
private RemoteViews rv;
private OkHttpClient client;
private final int CHANEL_ID = 105;
private NotificationCompat.Builder builder;
private NotificationManager notificationManager;
private static final String CANCEL_TAG = "c_tag";
private final String NOTIFICATION_CHANNEL_ID = "download_service";
public static final String ACTION_START = "com.download.action.START";
public static final String ACTION_STOP = "com.download.action.STOP";
private final Handler mHandler = new Handler(new Handler.Callback() {
#Override
public boolean handleMessage(#NotNull Message message) {
int progress = Integer.parseInt(message.obj.toString());
switch (message.what) {
case 1:
rv.setTextViewText(R.id.nf_title, getString(R.string.app_name));
rv.setProgressBar(R.id.progress, 100, progress, false);
rv.setTextViewText(R.id.nf_percentage, getResources().getString(R.string.downloading) + " " + "(" + progress + " %)");
notificationManager.notify(CHANEL_ID, builder.build());
break;
case 2:
if (Constant.downloadArray.size() - 1 != position) {
position++;
init(Constant.downloadArray.get(position));
} else {
// Toast.makeText(getApplicationContext(), getResources().getString(R.string.downloading), Toast.LENGTH_SHORT).show();
position = 0;
stopForeground(false);
stopSelf();
Events.AdapterNotify adapterNotify = new Events.AdapterNotify("");
GlobalBus.getBus().post(adapterNotify);
Method.isDownload = true;
}
break;
}
return false;
}
});
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate() {
super.onCreate();
notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
builder = new NotificationCompat.Builder(this, NOTIFICATION_CHANNEL_ID);
builder.setChannelId(NOTIFICATION_CHANNEL_ID);
builder.setSmallIcon(R.drawable.ic_baseline_notes);
builder.setTicker(getResources().getString(R.string.downloading));
builder.setWhen(System.currentTimeMillis());
builder.setOnlyAlertOnce(true);
rv = new RemoteViews(getPackageName(), R.layout.my_custom_notification);
rv.setTextViewText(R.id.nf_title, getString(R.string.app_name));
rv.setProgressBar(R.id.progress, 100, 0, false);
rv.setTextViewText(R.id.nf_percentage, getResources().getString(R.string.downloading) + " " + "(0%)");
Intent intentClose = new Intent(this, DownloadService.class);
intentClose.setAction(ACTION_STOP);
PendingIntent closeIntent = PendingIntent.getService(this, 0, intentClose, 0);
rv.setOnClickPendingIntent(R.id.nf_close, closeIntent);
builder.setCustomContentView(rv);
NotificationChannel mChannel;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
CharSequence name = getResources().getString(R.string.app_name);// The user-visible name of the channel.
mChannel = new NotificationChannel(NOTIFICATION_CHANNEL_ID, name, NotificationManager.IMPORTANCE_HIGH);
notificationManager.createNotificationChannel(mChannel);
}
startForeground(CHANEL_ID, builder.build());
}
#Override
public void onDestroy() {
super.onDestroy();
stopForeground(false);
stopSelf();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
super.onStartCommand(intent, flags, startId);
try {
if (intent.getAction() != null && intent.getAction().equals(ACTION_START)) {
Method.isDownload = false;
init(Constant.downloadArray.get(position));
}
if (intent.getAction() != null && intent.getAction().equals(ACTION_STOP)) {
if (client != null) {
for (Call call : client.dispatcher().runningCalls()) {
if (call.request().tag().equals(CANCEL_TAG))
call.cancel();
}
}
Method.isDownload = true;
stopForeground(false);
stopSelf();
}
} catch (Exception e) {
Log.d("error", e.toString());
stopForeground(false);
stopSelf();
}
return START_STICKY;
}
public void init(final String downloadUrl) {
final String iconsStoragePath = Environment.getExternalStorageDirectory() + getResources().getString(R.string.download_folder_path);
File file = new File(iconsStoragePath);
if (!file.exists()) {
file.mkdir();
}
//Using Date class
Date date = new Date();
//Pattern for showing milliseconds in the time "SSS"
#SuppressLint("SimpleDateFormat")
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss:SSS");
String stringDate = sdf.format(date);
//Using Calendar class
Calendar cal = Calendar.getInstance();
String s = sdf.format(cal.getTime());
final String string;
if (downloadUrl.contains(".jpg")) {
string = "Image-" + s + ".jpg";
} else {
string = "Image-" + s + ".mp4";
}
Log.d("file_name", string);
new Thread(new Runnable() {
#Override
public void run() {
client = new OkHttpClient();
Request.Builder builder = new Request.Builder()
.url(downloadUrl)
.addHeader("Accept-Encoding", "identity")
.get()
.tag(CANCEL_TAG);
Call call = client.newCall(builder.build());
call.enqueue(new Callback() {
#Override
public void onFailure(#NonNull Call call, #NonNull IOException e) {
Log.e("TAG", "=============onFailure222===============");
e.printStackTrace();
Log.d("error_downloading", e.toString());
// Method.isDownload = true;
}
#Override
public void onResponse(#NonNull Call call, #NonNull Response response) throws IOException {
Log.e("TAG", "=============onResponse===============");
Log.e("TAG", "request headers:" + response.request().headers());
Log.e("TAG", "response headers:" + response.headers());
assert response.body() != null;
ResponseBody responseBody = ProgressHelper.withProgress(response.body(), new ProgressUIListener() {
//if you don't need this method, don't override this methd. It isn't an abstract method, just an empty method.
#Override
public void onUIProgressStart(long totalBytes) {
super.onUIProgressStart(totalBytes);
Log.e("TAG", "onUIProgressStart:" + totalBytes);
}
#Override
public void onUIProgressChanged(long numBytes, long totalBytes, float percent, float speed) {
Log.e("TAG", "=============start===============");
Log.e("TAG", "numBytes:" + numBytes);
Log.e("TAG", "totalBytes:" + totalBytes);
Log.e("TAG", "percent:" + percent);
Log.e("TAG", "speed:" + speed);
Log.e("TAG", "============= end ===============");
Message msg = mHandler.obtainMessage();
msg.what = 1;
msg.obj = (int) (100 * percent) + "";
mHandler.sendMessage(msg);
}
//if you don't need this method, don't override this methd. It isn't an abstract method, just an empty method.
#Override
public void onUIProgressFinish() {
super.onUIProgressFinish();
Log.e("TAG", "onUIProgressFinish:");
Message msg = mHandler.obtainMessage();
msg.what = 2;
msg.obj = 0 + "";
mHandler.sendMessage(msg);
if (downloadUrl.contains(".jpg")) {
if (Constant.imageArray != null) {
Constant.imageArray.add(0, new File(iconsStoragePath + "/" + string));
}
} else {
if (Constant.videoArray != null) {
Constant.videoArray.add(0, new File(iconsStoragePath + "/" + string));
}
}
try {
MediaScannerConnection.scanFile(getApplicationContext(), new String[]{iconsStoragePath + "/" + string},
null,
(path, uri) -> {
});
} catch (Exception e) {
e.printStackTrace();
}
}
});
try {
BufferedSource source = responseBody.source();
File outFile = new File(iconsStoragePath + "/" + string);
BufferedSink sink = Okio.buffer(Okio.sink(outFile));
source.readAll(sink);
sink.flush();
source.close();
} catch (Exception e) {
Log.d("show_data", e.toString());
}
}
});
}
}).start();
}
}
**error in FindData class2022-03-11 08:32:20.701 1631-1631/?
E/downloaderinst: Unknown bits set in runtime_flags: 0x8000
2022-03-11 08:59:02.413 1631-1631/com.pinit.downloaderinst3 E/TAG: =============onFailure===============
2022-03-11 08:59:02.539 1631-1631/com.pinit.downloaderinst3 E/DecorView: mWindow.mActivityCurrentConfig is null
2022-03-11 08:59:03.999 1631-1631/com.pinit.downloaderinst3 E/........POOR NETWORK ........: org.json.JSONException: Value <!DOCTYPE of type java.lang.String cannot be converted to JSONObject
2022-03-11 08:59:04.007 1631-1631/com.pinit.downloaderinst3 E/InputMethodManager: prepareNavigationBarInfo() rootView is null
2022-03-11 08:59:04.123 1631-1631/com.pinit.downloaderinst3 E/ViewRootImpl: sendUserActionEvent() mView returned.

DIsplay files downloaded from json on main screen?

I'm parsing a json to display a list of files a user can tap to download. I want to display the files the users have chosen to download on my main screen. this is the code when they download a file.
public final class Main extends Activity {
// Log tag for this class
private static final String TAG = "Main";
// Callback code for request of storage permission
final private int PERMISSIONS_REQUEST_STORAGE = 735;
// JSON Node Names
private static final String TAG_TYPE = "plans";
private static final String TAG_NAME = "name";
private static final String TAG_FILENAME = "filename";
private static final String TAG_URL = "url";
private static final String TAG_SHOULD_NOT_CACHE = "shouldNotCache";
// Files to delete
private static final ArrayList<String> filesToGetDeleted = new ArrayList<>();
// Strings displayed to the user
private static String offline;
private static String noPDF;
private static String localLoc;
private static String jsonURL;
// PDF Download
private static DownloadManager downloadManager;
private static long downloadID;
private static File file;
#SuppressLint("StaticFieldLeak")
private static SwipeRefreshLayout swipeRefreshLayout;
private final BroadcastReceiver downloadReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context arg0, Intent arg1) {
final DownloadManager.Query query = new DownloadManager.Query();
query.setFilterById(downloadID);
final Cursor cursor = downloadManager.query(query);
if (cursor.moveToFirst()) {
final int columnIndex = cursor
.getColumnIndex(DownloadManager.COLUMN_STATUS);
final int status = cursor.getInt(columnIndex);
switch (status) {
case DownloadManager.STATUS_SUCCESSFUL:
final Uri path = Uri.fromFile(file);
final Intent pdfIntent = new Intent(Intent.ACTION_VIEW);
pdfIntent.setDataAndType(path, "application/pdf");
pdfIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
try {
startActivity(pdfIntent);
} catch (ActivityNotFoundException e) {
Utils.makeLongToast(Main.this, noPDF);
Log.e(TAG, e.getMessage());
}
break;
case DownloadManager.STATUS_FAILED:
Utils.makeLongToast(Main.this,
getString(R.string.down_error));
break;
case DownloadManager.STATUS_PAUSED:
Utils.makeLongToast(Main.this,
getString(R.string.down_paused));
break;
case DownloadManager.STATUS_PENDING:
Utils.makeLongToast(Main.this,
getString(R.string.down_pending));
break;
case DownloadManager.STATUS_RUNNING:
Utils.makeLongToast(Main.this,
getString(R.string.down_running));
break;
}
}
}
};
// Data from JSON file
private ArrayList<HashMap<String, String>> downloadList = new ArrayList<>();
private static void checkDir() {
final File dir = new File(Environment.getExternalStorageDirectory() + "/"
+ localLoc + "/");
if (!dir.exists()) dir.mkdir();
}
#Override
protected void onResume() {
super.onResume();
final IntentFilter intentFilter = new IntentFilter(
DownloadManager.ACTION_DOWNLOAD_COMPLETE);
registerReceiver(downloadReceiver, intentFilter);
}
#Override
protected void onPause() {
super.onPause();
unregisterReceiver(downloadReceiver);
}
#Override
protected void onDestroy() {
super.onDestroy();
// Delete files which should not get cached.
for (String file : filesToGetDeleted) {
final File f = new File(file);
if (f.exists()) {
f.delete();
}
}
}
#Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
switch (requestCode) {
case PERMISSIONS_REQUEST_STORAGE:
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
Utils.makeLongToast(Main.this, getString(R.string.permission_write_external_storage_success));
}
else {
final String permission_write_external_storage_failure = getString(R.string.permission_write_external_storage_failure);
final String app_title = getString(R.string.app_name);
final String message = String.format(permission_write_external_storage_failure, app_title);
Utils.makeLongToast(Main.this, message);
boolean showRationale = ActivityCompat.shouldShowRequestPermissionRationale(Main.this, permissions[0]);
if (!showRationale) {
Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
Uri uri = Uri.fromParts("package", getPackageName(), null);
intent.setData(uri);
startActivity(intent);
}
}
break;
}
}
private void update(boolean force, boolean firstLoad) {
downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
swipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.swipeRefreshLayout_main);
offline = getString(R.string.status_offline);
noPDF = getString(R.string.except_nopdf);
localLoc = getString(R.string.gen_loc);
jsonURL = getString(R.string.gen_json);
checkDir();
if (firstLoad) {
try {
downloadList = (ArrayList<HashMap<String, String>>) Utils.readObject(this, "downloadList");
if (downloadList != null) {
setList(true, true);
}
} catch (ClassNotFoundException | IOException e) {
Log.e(TAG, e.getMessage());
}
}
// Parse the JSON file of the plans from the URL
JSONParse j = new JSONParse();
j.force = force;
j.online = !Utils.isNoNetworkAvailable(this);
j.execute();
}
private void setList(final boolean downloadable, final boolean itemsAvailable) {
if (itemsAvailable) {
try {
Utils.writeObject(this, "downloadList", downloadList);
} catch (IOException e) {
Log.e(TAG, e.getMessage());
}
}
final ListView list = (ListView) findViewById(R.id.listView_main);
final ListAdapter adapter = new SimpleAdapter(this, downloadList,
android.R.layout.simple_list_item_1, new String[]{TAG_NAME},
new int[]{android.R.id.text1});
list.setAdapter(adapter);
// React when user click on item in the list
if (itemsAvailable) {
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View v, int pos,
long id) {
int hasStoragePermission = ContextCompat.checkSelfPermission(Main.this,
Manifest.permission.WRITE_EXTERNAL_STORAGE);
if (hasStoragePermission != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(Main.this,
new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
PERMISSIONS_REQUEST_STORAGE);
return;
}
final Uri downloadUri = Uri.parse(downloadList.get(pos).get(TAG_URL));
final String title = downloadList.get(pos).get(TAG_NAME);
final String shouldNotCache = downloadList.get(pos).get(TAG_SHOULD_NOT_CACHE);
file = new File(Environment.getExternalStorageDirectory() + "/"
+ localLoc + "/"
+ downloadList.get(pos).get(TAG_FILENAME) + ".pdf");
final Uri dst = Uri.fromFile(file);
if (file.exists()) {
final Intent pdfIntent = new Intent(Intent.ACTION_VIEW);
pdfIntent.setDataAndType(dst, "application/pdf");
pdfIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
try {
startActivity(pdfIntent);
} catch (ActivityNotFoundException e) {
Utils.makeLongToast(Main.this, noPDF);
Log.e(TAG, e.getMessage());
}
return;
}
if (downloadable && !Utils.isNoNetworkAvailable(Main.this)) {
// Download PDF
final Request request = new Request(downloadUri);
request.setTitle(title).setDestinationUri(dst);
downloadID = downloadManager.enqueue(request);
if (shouldNotCache.equals("true")) {
filesToGetDeleted.add(file.toString());
}
} else {
Utils.makeLongToast(Main.this, offline);
}
}
});
}
swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
update(true, false);
}
});
}
private class JSONParse extends AsyncTask<String, String, JSONObject> {
public boolean force = false;
public boolean online = false;
#Override
protected void onPreExecute() {
super.onPreExecute();
swipeRefreshLayout.post(new Runnable() {
#Override
public void run() {
swipeRefreshLayout.setRefreshing(true);
}
});
}
#Override
protected JSONObject doInBackground(String... args) {
return JSONParser.getJSONFromUrl(Main.this, jsonURL, force, online);
}
#Override
protected void onPostExecute(JSONObject json) {
swipeRefreshLayout.post(new Runnable() {
#Override
public void run() {
swipeRefreshLayout.setRefreshing(false);
}
});
downloadList.clear();
if (json == null) {
String error = getString(R.string.except_json);
if (!online) {
error = offline;
}
final HashMap<String, String> map = new HashMap<>();
map.put(TAG_NAME, error);
downloadList.add(map);
setList(false, false);
return;
}
try {
// Get JSON Array from URL
final JSONArray j_plans = json.getJSONArray(TAG_TYPE);
for (int i = 0; i < j_plans.length(); i++) {
final JSONObject c = j_plans.getJSONObject(i);
// Storing JSON item in a Variable
final String ver = c.getString(TAG_FILENAME);
final String name = c.getString(TAG_NAME);
final String api = c.getString(TAG_URL);
String shouldNotCache = "";
if (c.has(TAG_SHOULD_NOT_CACHE)) {
shouldNotCache = c.getString(TAG_SHOULD_NOT_CACHE);
}
// Adding value HashMap key => value
final HashMap<String, String> map = new HashMap<>();
map.put(TAG_FILENAME, ver);
map.put(TAG_NAME, name);
map.put(TAG_URL, api);
map.put(TAG_SHOULD_NOT_CACHE, shouldNotCache);
downloadList.add(map);
setList(online, true);
}
} catch (JSONException e) {
Log.e(TAG, e.getMessage());
}
}
}
SO how do I get the result of the above code and display it on main screen every time the user opens app

Skipped 1492 frames! The application may be doing too much work on its main thread.How to show loader while skipping frames in app? [duplicate]

This question already has answers here:
The application may be doing too much work on its main thread
(21 answers)
Closed 1 year ago.
As I am new to android I couldn't fix this skipped 1000+ frames issue.Help me to sort out this and help me to add loading progress bar while this skipping frames action takes place before opening map. This is my map code.
RouteMap.java
public class RouteMap extends android.support.v4.app.FragmentActivity
implements OnClickListener, OnInfoWindowClickListener,
DirecitonReceivedListener, OnMapReadyCallback {
public List<String> destinations;
ImageView img_home, img_menu;
private GoogleMap mMap;
ProgressDialog prgDialog;
model modelData;
private Button btnDirection;
double latitude, longitude;
LinearLayout linear_back;
LatLng startPosition, start;
String startPositionTitle;
Vibrator vibrator;
String startPositionSnippet;
Double desc1_long, desc1_lat;
LatLng destinationPosition1;
String destinationPositionTitle;
String destinationPositionSnippet;
MarkerOptions mDestination1, mStart;
ToggleButton tbMode;
GPSTracker gps;
Geocoder gCoder;
ArrayList<Address> addresses = null;
ArrayList<Address> adres2 = null;
SupportMapFragment mapFragment;
public final static double AVERAGE_RADIUS_OF_EARTH = 6371;
TextView back_txt;
openMap openMap;
String mapStatus = "start";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_route_map);
back_txt = (TextView) findViewById(R.id.txt_back);
try {
back_txt = (TextView) findViewById(R.id.txt_back);
modelData = model.getInstance();
vibrator = (Vibrator) getApplicationContext().getSystemService(Context.VIBRATOR_SERVICE);
gps = new GPSTracker(RouteMap.this);
latitude = gps.getLatitude();
longitude = gps.getLongitude();
gCoder = new Geocoder(RouteMap.this);
addresses = (ArrayList<Address>) gCoder.getFromLocation(latitude, longitude, 1);
tbMode = (ToggleButton) findViewById(R.id.tbMode);
mapFragment = ((SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map));
mapFragment.getMapAsync(this);
btnDirection = (Button) findViewById(R.id.btnDirection);
btnDirection.setOnClickListener(this);
tbMode.setChecked(true);
} catch (IOException e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(), "Please Check your Data connection or Turn on your Location", Toast.LENGTH_LONG).show();
}
}
public int calculateDistance(double userLat, double userLng, double venueLat, double venueLng) {
final int R = 6371;
try {
Double latDistance = deg2rad(venueLat - userLat);
Double lonDistance = deg2rad(venueLng - userLng);
Double a = Math.sin(latDistance / 2) * Math.sin(latDistance / 2)
+ Math.cos(deg2rad(userLat)) * Math.cos(deg2rad(venueLat))
* Math.sin(lonDistance / 2) * Math.sin(lonDistance / 2);
Double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
double distance = R * c * 1000; // convert to meters
double height = 0 - 0;
distance = Math.pow(distance, 2) + Math.pow(height, 2);
return (int) Math.sqrt(distance);
} catch (Exception ex) {
Toast.makeText(getApplicationContext(), "Please Check your Destination's GeoCode ", Toast.LENGTH_LONG).show();
}
return 0;
}
private double deg2rad(double deg) {return (deg * Math.PI / 180.0);}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap=googleMap;
//setUpMap();
try {
mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
}
mMap.setMyLocationEnabled(true);
mMap.setIndoorEnabled(true);
mMap.getUiSettings().setZoomControlsEnabled(true);
mMap.getUiSettings().setMyLocationButtonEnabled(true);
mMap.getUiSettings().setCompassEnabled(true);
mMap.getUiSettings().setAllGesturesEnabled(true);
String[] arr = new String[modelData.outletList.size()];
for(int i=0;i<modelData.outletList.size();i++)
{
String str1 = modelData.outletList.get(i)[2];
String str2 = modelData.outletList.get(i)[3];
String newString = str1+","+str2;
arr[i] = newString;
}
String[] latTempArr = arr;
String strKey = "";
double curLatitude = latitude;
double curLongtitude = longitude;
double desLat;
double desLng;
Map<String, Integer> final_arr = new HashMap<String, Integer>();
Map<String, Integer> final_arr2 = new HashMap<String, Integer>();
List<Integer> intTempArr = new ArrayList<Integer>();
List<Integer> intTempArr2 = new ArrayList<Integer>();
for(int j=0;j<arr.length;j++)
{
intTempArr = new ArrayList<Integer>();
for (int k=0;k<latTempArr.length;k++)
{
String[] arr_temp = latTempArr[k].split(",");
//System.out.println(arr_temp[0]);
desLat = Double.parseDouble(arr_temp[0]);
desLng = Double.parseDouble(arr_temp[1]);
int temp = calculateDistance(curLatitude,curLongtitude,desLat,desLng);
intTempArr.add(temp);
final_arr.put(latTempArr[k],temp);
}
Collections.sort(intTempArr);
Integer[] array = new Integer[intTempArr.size()];
intTempArr.toArray(array);
for (Map.Entry<String, Integer> entry : final_arr.entrySet()) {
try{
if (entry.getValue().equals(array[0])) { //get next best path
List<String> list = new ArrayList<String>(Arrays.asList(latTempArr)); // remove the best path to find next one
list.remove(entry.getKey());
latTempArr = list.toArray(new String[0]);
String[] arr_temp2 = entry.getKey().split(",");
//System.out.println(arr_temp[0]);
curLatitude = Double.parseDouble(arr_temp2[0]);
curLongtitude = Double.parseDouble(arr_temp2[1]);
strKey = entry.getKey();
intTempArr2.add(entry.getValue());
final_arr2.put(strKey,entry.getValue());
}
}
catch(Exception e)
{
}
}
//System.out.println(intTempArr);
}
//int i = 0;
destinations = new ArrayList<String>();
for(int i =0;i<intTempArr2.size();i++) {
for(String Key : final_arr2.keySet()) {
//System.out.println();
if(final_arr2.get(Key) == intTempArr2.get(i)) {
destinations.add(Key);
break;
}
}
}
System.out.println(destinations);
for(int i = 0;i < destinations.size();i++) {
//Toast.makeText(getApplicationContext(), " ListItem : " + i, Toast.LENGTH_LONG).show();
String desti1 = destinations.get(i);
String[] des = desti1.split(",");
desc1_lat = Double.parseDouble(des[0]);
desc1_long = Double.parseDouble(des[1]);
startPosition = new LatLng(latitude, longitude);
startPositionTitle = addresses.get(0).getLocality();
startPositionSnippet = addresses.get(0).getAddressLine(1)+"," +" "+ addresses.get(0).getAddressLine(2);
try {
adres2 = (ArrayList<Address>) gCoder.getFromLocation(desc1_lat, desc1_long, 1);
} catch (IOException e) {
e.printStackTrace();
}
destinationPosition1 = new LatLng(desc1_lat, desc1_long);
destinationPositionTitle = adres2.get(0).getLocality();
destinationPositionSnippet =adres2.get(0).getAddressLine(1)+"," +" "+adres2.get(0).getAddressLine(2);
// mMap.setOnInfoWindowClickListener(this);
mMap.setInfoWindowAdapter(new GoogleMap.InfoWindowAdapter() {
#Override
public View getInfoWindow(Marker marker) {
return null;
}
#Override
public View getInfoContents(Marker marker) {
View v = getLayoutInflater().inflate(R.layout.marker, null);
TextView info= (TextView) v.findViewById(R.id.info);
info.setText(marker.getSnippet().toString());
return v;
}
});
mDestination1 = new MarkerOptions()
.position(destinationPosition1)
.title(destinationPositionTitle)
.snippet(destinationPositionSnippet)
.icon(BitmapDescriptorFactory.fromResource(R.drawable.pin1));
mStart = new MarkerOptions()
.position(startPosition)
.title(startPositionTitle)
.snippet(startPositionSnippet)
.icon(BitmapDescriptorFactory.fromResource(R.drawable.pin2));
mMap.addMarker(mDestination1);
mMap.addMarker(mStart);
latitude = desc1_lat;
longitude = desc1_long;
LatLng locations = new LatLng(latitude,longitude);
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(locations, 5.5f));
}
}catch (Exception ex)
{
/*Toast.makeText(getApplicationContext(), "Please Check your Data connection or Turn on your Location", Toast.LENGTH_LONG).show();*/
}
}
public void clearMap() {
mMap.clear();
}
#Override
public void onClick(View v) {
try
{
Locale mLocale = new Locale("en");
Log.d("Display language = ", "" + mLocale.getDisplayLanguage());
gCoder = new Geocoder(RouteMap.this,mLocale);
gps = new GPSTracker(RouteMap.this);
latitude = gps.getLatitude();
longitude = gps.getLongitude();
for(int i = 0;i<destinations.size();i++) {
String desti1 = destinations.get(i);
String[] des = desti1.split(",");
desc1_lat = Double.parseDouble(des[0]);
desc1_long = Double.parseDouble(des[1]);
startPosition = new LatLng(latitude, longitude);
startPositionTitle = addresses.get(0).getLocality();
startPositionSnippet = addresses.get(0).getAddressLine(1)+","+" "+addresses.get(0).getAddressLine(2);
destinationPosition1 = new LatLng(desc1_lat, desc1_long);
destinationPositionTitle = adres2.get(0).getLocality();
destinationPositionSnippet =adres2.get(0).getAddressLine(1)+","+""+ adres2.get(0).getAddressLine(2);
mMap.setOnInfoWindowClickListener(this);
mStart = new MarkerOptions()
.position(startPosition)
.title(startPositionTitle)
.snippet(startPositionSnippet)
.icon(BitmapDescriptorFactory.fromResource(R.drawable.pin1));
mDestination1 = new MarkerOptions()
.position(destinationPosition1)
.title(destinationPositionTitle)
.snippet(destinationPositionSnippet)
.icon(BitmapDescriptorFactory.fromResource(R.drawable.pin2));
if (v == btnDirection) {
// clearMap();
mMap.addMarker(mDestination1);
mMap.addMarker(mStart);
if (tbMode.isChecked()) {
new GetRotueListTask(RouteMap.this, startPosition,
destinationPosition1, GMapV2Direction.MODE_DRIVING, this)
.execute();
} else {
new GetRotueListTask(RouteMap.this, startPosition,
destinationPosition1, GMapV2Direction.MODE_WALKING, this)
.execute();
}
}
latitude = desc1_lat;
longitude = desc1_long;
}
}catch (Exception ex)
{
Toast.makeText(getApplicationContext(), "Please Check your Data connection or Turn on your Location", Toast.LENGTH_LONG).show();
}
}
#Override
public void OnDirectionListReceived(List<LatLng> mPointList) {
try
{
if (mPointList != null) {
PolylineOptions rectLine = new PolylineOptions().width(10).color(
Color.RED);
for (int i = 0; i < mPointList.size(); i++) {
rectLine.add(mPointList.get(i));
}
mMap.addPolyline(rectLine);
gps = new GPSTracker(RouteMap.this);
latitude = gps.getLatitude();
longitude = gps.getLongitude();
start = new LatLng(latitude, longitude);
CameraPosition mCPFrom = new CameraPosition.Builder()
.target(start).zoom(15.5f).bearing(0).tilt(25)
.build();
final CameraPosition mCPTo = new CameraPosition.Builder()
.target(destinationPosition1).zoom(15.5f).bearing(0)
.tilt(50).build();
changeCamera(CameraUpdateFactory.newCameraPosition(mCPFrom),
new CancelableCallback() {
#Override
public void onFinish() {
changeCamera(CameraUpdateFactory
.newCameraPosition(mCPTo),
new CancelableCallback() {
#Override
public void onFinish() {
LatLngBounds bounds = new LatLngBounds.Builder()
.include(start)
.include(
destinationPosition1)
.build();
changeCamera(
CameraUpdateFactory
.newLatLngBounds(
bounds, 50),
null, false);
}
#Override
public void onCancel() {
}
}, false);
}
#Override
public void onCancel() {
}
}, true);
}
}catch (Exception ex)
{
Toast.makeText(getApplicationContext(), "Please Check your Data Connection", Toast.LENGTH_LONG).show();
}
}
private void changeCamera(CameraUpdate update, CancelableCallback callback,
boolean instant) {
if (instant) {
mMap.animateCamera(update, 1, callback);
} else {
mMap.animateCamera(update, 4000, callback);
}
}
#Override
protected void onResume() {
super.onResume();
}
#Override
public void onInfoWindowClick(Marker marker) {
}
private class openMap extends AsyncTask<String, Void, String>
{
ProgressDialog mProgressDialog;
Context ctx;
public openMap(Context ctx)
{
this.ctx=ctx;
mProgressDialog = new ProgressDialog(RouteMap.this);
}
#Override
protected void onPreExecute() {
super.onPreExecute();
mProgressDialog.setMessage("Loading Map..Please wait....");
mProgressDialog.setIndeterminate(true);
mProgressDialog.setCancelable(false);
mProgressDialog.show();
// Toast.makeText(getApplicationContext(), "Syncing DB...", Toast.LENGTH_LONG).show();
}
#Override
protected String doInBackground(String... urls)
{
return "Success";
}
#Override
protected void onPostExecute(String result)
{
mProgressDialog.dismiss();
try
{
if(result.equalsIgnoreCase("Success")) {
}
else
{
Toast.makeText(getApplicationContext(), "Please Check your Data connection or Turn on your Location", Toast.LENGTH_LONG).show();
}
}catch (Exception e){}
}
}
}
From this code above what changes should I make to fix the Skipped
1000+ frames issue and also help me add loader before opening the
map...
Geocoder.getFromLocation() is an expensive call that does a network call to Google's servers, so don't make it on the UI thread.
Have a look at Processes and Threads in the android developer docs for various ways of making the request in the background.
The code that you write in OnMapReady function is to much, please remove that code from there I can see there are more then 4 "for" loops in onMapReady, move that part to to some where else like OnCreate() create all maps and lists that you want.
Just ues OnMapReady function for placing markers

Android - Cant get latitude/longitude value to store and pass on variable

I am trying to store the latitude/longitude to variables x3 and x4 to pass on Spot[] array but it returns 0. I tried printing it on onConnected method and it works fine.
I also tried other methods to add marker on google map and I put map.addMarker on onConnected method instead but my app closes. If u can suggest where to put addMarker please do. Thanks.
GoogleMap map;
private static Location mLastLocation;
private static GoogleApiClient mGoogleApiClient;
static double x3;
static double x4;
LatLng userloc;
#Override
public void onConnected(Bundle connectionHint) {
mLastLocation = LocationServices.FusedLocationApi.getLastLocation(
mGoogleApiClient);
if (mLastLocation != null) {
x3 = mLastLocation.getLatitude();
x4 = mLastLocation.getLongitude();
userloc = new LatLng(x3,x4);
txtPlateno.setText(String.valueOf(x3+" - "+x4)); // PRINT TEST ONLY WITH CORRECT RESULT
}
}
private static Spot[] SPOTS_ARRAY = new Spot[]{
new Spot("YOU ARE HERE", "DESC ", "", new LatLng(x3, x4)), // NOT SHOWN IN MAP AT ALL
new Spot("Besabella Parking Lot",
"Address: Sta Cruz Labogon, Mandaue City\n " +
"Fee: \n " +
"No. of available space: \n " +
"Distance:" + x3 + "KM", "", new LatLng(10.351763, 123.953683)),
// TESTING x3 ON DISTANCE WITH RESULT 0.0
};
You can call add marker after getting lat/long and also can move camera on that for reference you can check following code
public class MapDialogFragment extends DialogFragment implements LibListner, OnClickListener, OnInfoWindowClickListener {
private View dialog;
private MarkerOptions markerOptions;
private SupportMapFragment mMapFragment;
private GoogleMap mMap;
private TextView tvBackText, tvback;
// private ArrayList<String> getClickedTitle;
private ArrayList<Data> newData;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// Utility.Log("onCreateView");
getDialog().getWindow().requestFeature(Window.FEATURE_NO_TITLE);
// //
getDialog().getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
getDialog().getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
// getDialog().getWindow()
// .getAttributes().windowAnimations = R.style.DialogAnimation;
if (dialog != null) {
ViewGroup parent = (ViewGroup) dialog.getParent();
if (parent != null)
parent.removeView(dialog);
}
try {
dialog = inflater.inflate(R.layout.dlg_map, container, false);
} catch (Exception e) {
/* map is already there, just return view as it is */
}
return dialog;
}
#Override
public void onStart() {
super.onStart();
// Utility.Log("onStart");
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Utility.Log("onCreate");
FragmentManager fm = getChildFragmentManager();
mMapFragment = (SupportMapFragment) fm.findFragmentById(R.id.mapView);
if (mMapFragment == null) {
mMapFragment = SupportMapFragment.newInstance();
fm.beginTransaction().replace(R.id.mapView, mMapFragment).commit();
}
}
#Override
public void onActivityCreated(Bundle arg0) {
super.onActivityCreated(arg0);
init();
loadMap();
initMap();
listner();
}
private void loadMap() {
String map = Utility.BASE_URL + "mall/location";
new GetLibResponse(MapDialogFragment.this, new LocationGeneralModel(), getActivity(), map, Utility.LOCATIONCOMMON, true, true);
}
#Override
public void onResume() {
super.onResume();
try {
int chkGooglePlayServices = GooglePlayServicesUtil.isGooglePlayServicesAvailable(getActivity());
markerOptions = new MarkerOptions();
if (chkGooglePlayServices != ConnectionResult.SUCCESS) {
GooglePlayServicesUtil.getErrorDialog(chkGooglePlayServices, getActivity(), 1122).show();
} else {
mMap = mMapFragment.getMap();
mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
}
mMap.setMyLocationEnabled(false);
mMap.setOnInfoWindowClickListener(this);
// if (isSearch) {
// mMap.setOnMapClickListener(MapDialogFragment.this);
// mMap.setOnMapLongClickListener(MapDialogFragment.this);
// mMap.setOnMarkerDragListener(MapDialogFragment.this);
//
// if (latitude != null && longitude != null && latitude != "" && longitude != "") {
// mMap.clear();
// markerOptions
// .position(
// new LatLng(Double.parseDouble(latitude), Double.parseDouble(longitude)));
// mMap.addMarker(markerOptions);
// mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(
// new LatLng(Double.parseDouble(latitude), Double.parseDouble(longitude)),
// 15.0f));
//
// }
// } else {
// mMap.clear();
// markerOptions
// .position(
// new LatLng(Double.parseDouble(flat), Double.parseDouble(flong)));
// mMap.addMarker(markerOptions);
// mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(
// new LatLng(Double.parseDouble(flat), Double.parseDouble(flong)),
// 15.0f));
// }
} catch (Exception e) {
e.printStackTrace();
}
}
private void init() {
tvback = (TextView) dialog.findViewById(R.id.frg_location_tvBack);
tvback.setOnClickListener(this);
tvBackText = (TextView) dialog.findViewById(R.id.frg_location_tvBackText);
tvBackText.setOnClickListener(this);
}
private void listner() {
}
private void initMap() {
}
private MainFragmentActivity mainActivity() {
return ((MainFragmentActivity) getActivity());
}
#Override
public void onResponseComplete(Object clsGson, int requestCode) {
if (requestCode == Utility.LOCATIONCOMMON) {
if (mainActivity() != null) {
mainActivity().mLocationGeneralModel = (LocationGeneralModel) clsGson;
if ((mainActivity().mLocationGeneralModel != null) && (mainActivity().mLocationGeneralModel.data != null)
&& (mainActivity().mLocationGeneralModel.data.size() != 0)) {
ArrayList<Double> vLat = new ArrayList<Double>();
ArrayList<Double> vLong = new ArrayList<Double>();
ArrayList<String> vName = new ArrayList<String>();
ArrayList<Data> newData = new ArrayList<LocationGeneralModel.Data>();
for (int pin = 0; pin < mainActivity().mLocationGeneralModel.data.size(); pin++) {
try {
if (!mainActivity().mLocationGeneralModel.data.get(pin).vLat.equals("")) {
// Log.d("TAG", mainActivity().mLocationGeneralModel.data.get(pin).vLat);
vLat.add(Double.parseDouble(mainActivity().mLocationGeneralModel.data.get(pin).vLat));
vLong.add(Double.parseDouble(mainActivity().mLocationGeneralModel.data.get(pin).vLong));
vName.add((mainActivity().mLocationGeneralModel.data.get(pin).vName_en));
double vLatitude[] = new double[vLat.size()];
double vLongitude[] = new double[vLong.size()];
for (int getArray = 0; getArray < vLat.size(); getArray++) {
vLatitude[getArray] = vLat.get(getArray);
vLongitude[getArray] = vLong.get(getArray);
newData.add(mainActivity().mLocationGeneralModel.data.get(pin));
}
multipleMarker(vLatitude, vLongitude, vName, newData);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
}
}
#Override
public void onResponseError(String errorMessage, int requestCode) {
}
private void multipleMarker(double latitude[], double longitude[], ArrayList<String> vName, ArrayList<Data> newData) {
this.newData = newData;
mMap.clear();
// LatLngBounds.Builder builder = new LatLngBounds.Builder();
// for (Marker marker : markers) {
// builder.include(marker.getPosition());
// }
// LatLngBounds bounds = builder.build();
// getClickedTitle = new ArrayList<String>();
for (int i = 0; i < latitude.length; i++) {
// Log.d("TAG", "Marker Add" + latitude[i] + " " + longitude[i]);
MarkerOptions marker = new MarkerOptions().position(new LatLng(latitude[i], longitude[i])).title(vName.get(i));
mMap.addMarker(marker);
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(latitude[i], longitude[i]), 5));
}
// getClickedTitle = vName;
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.frg_location_tvBack:
dismiss();
break;
case R.id.frg_location_tvBackText:
dismiss();
break;
}
}
#Override
public void onInfoWindowClick(Marker arg0) {
for (int counter = 0; counter < newData.size(); counter++) {
if (arg0.getTitle().equals(newData.get(counter).vName_en)) {
Data data = newData.get(counter);
MallPerticularsFragment mFragment = new MallPerticularsFragment();
Bundle bundle = new Bundle();
bundle.putString("mall_name", data.vName_en);
bundle.putString("mall_locEn", data.vLocation);
mFragment.setArguments(bundle);
((MainFragmentActivity) getActivity()).displayFragmentWithArg(mFragment);
}
}
}
}

Android Foursquare how to get the token

I have an app that connects to my Foursquare account. The authentication is successful, but when it comes to showing my username (it shows null) and the list of venues around me, I can't get through it.
What should be done?
Main.java
public class Main extends Activity {
private FoursquareApp mFsqApp;
private ListView mListView;
private NearbyAdapter mAdapter;
private ArrayList<FsqVenue> mNearbyList;
private ProgressDialog mProgress;
public static final String CLIENT_ID = "XXXXXXXXXXXXXXX";
public static final String CLIENT_SECRET = "XXXXXXXXXXXXXXXXXXX";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final TextView nameTv = (TextView) findViewById(R.id.tv_name);
Button connectBtn = (Button) findViewById(R.id.b_connect);
final EditText latitudeEt = (EditText) findViewById(R.id.et_latitude);
final EditText longitudeEt = (EditText)findViewById(R.id.et_longitude);
Button goBtn = (Button) findViewById(R.id.b_go);
mListView = (ListView) findViewById(R.id.lv_places);
mFsqApp = new FoursquareApp(this, CLIENT_ID, CLIENT_SECRET);
mAdapter = new NearbyAdapter(this);
mNearbyList = new ArrayList<FsqVenue>();
mProgress = new ProgressDialog(this);
mProgress.setMessage("Loading data ...");
if (mFsqApp.hasAccessToken()) nameTv.setText("Connected as " + mFsqApp.getUserName());
FsqAuthListener listener = new FsqAuthListener() {
#Override
public void onSuccess() {
Toast.makeText(Main.this, "Connected as " + mFsqApp.getUserName(), Toast.LENGTH_SHORT).show();
nameTv.setText("Connected as " + mFsqApp.getUserName());
}
#Override
public void onFail(String error) {
Toast.makeText(Main.this, error, Toast.LENGTH_SHORT).show();
}
};
mFsqApp.setListener(listener);
//get access token and user name from foursquare
connectBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
mFsqApp.authorize();
}
});
//use access token to get nearby places
goBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
String latitude = latitudeEt.getText().toString();
String longitude = longitudeEt.getText().toString();
if (latitude.equals("") || longitude.equals("")) {
Toast.makeText(Main.this, "Latitude or longitude is empty", Toast.LENGTH_SHORT).show();
return;
}
double lat = Double.valueOf(latitude);
double lon = Double.valueOf(longitude);
loadNearbyPlaces(lat, lon);
}
});
}
private void loadNearbyPlaces(final double latitude, final double longitude) {
mProgress.show();
new Thread() {
#Override
public void run() {
int what = 0;
try {
mNearbyList = mFsqApp.getNearby(latitude, longitude);
} catch (Exception e) {
what = 1;
e.printStackTrace();
}
mHandler.sendMessage(mHandler.obtainMessage(what));
}
}.start();
}
private Handler mHandler = new Handler() {
#Override
public void handleMessage(Message msg) {
mProgress.dismiss();
if (msg.what == 0) {
if (mNearbyList.size() == 0) {
Toast.makeText(Main.this, "No nearby places available", Toast.LENGTH_SHORT).show();
return;
}
mAdapter.setData(mNearbyList);
mListView.setAdapter(mAdapter);
} else {
Toast.makeText(Main.this, "Failed to load nearby places", Toast.LENGTH_SHORT).show();
}
}
};
}
FoursquareApp.java
public class FoursquareApp {
private FoursquareSession mSession;
private FoursquareDialog mDialog;
private FsqAuthListener mListener;
private ProgressDialog mProgress;
private String mTokenUrl;
private String mAccessToken;
public static final String CALLBACK_URL = "https://www.foursquare.com";
private static final String AUTH_URL = "https://foursquare.com/oauth2/authenticate";
private static final String TOKEN_URL = "https://foursquare.com/oauth2/access_token";
private static final String API_URL = "https://api.foursquare.com/v2";
private static final String TAG = "FoursquareApi";
public FoursquareApp(Context context, String clientId, String clientSecret) {
mSession = new FoursquareSession(context);
mAccessToken = mSession.getAccessToken();
mTokenUrl = TOKEN_URL + "?client_id=" + clientId + "&client_secret=" + clientSecret + "&grant_type=authorization_code"
+ "&redirect_uri=" + CALLBACK_URL;
String url = AUTH_URL + "?client_id=" + clientId + "&response_type=code" + "&redirect_uri=" + CALLBACK_URL;
FsqDialogListener listener = new FsqDialogListener() {
#Override
public void onComplete(String code) {
getAccessToken(code);
}
#Override
public void onError(String error) {
mListener.onFail("Authorization failed");
}
};
mDialog = new FoursquareDialog(context, url, listener);
mProgress = new ProgressDialog(context);
mProgress.setCancelable(false);
}
private void getAccessToken(final String code) {
mProgress.setMessage("Getting access token ...");
mProgress.show();
new Thread() {
#Override
public void run() {
Log.i(TAG, "Getting access token");
int what = 0;
try {
URL url = new URL(mTokenUrl + "&code=" + code);
Log.i(TAG, "Opening URL " + url.toString());
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.setDoInput(true);
//urlConnection.setDoOutput(true);
urlConnection.connect();
JSONObject jsonObj = (JSONObject) new JSONTokener(streamToString(urlConnection.getInputStream())).nextValue();
mAccessToken = jsonObj.getString("access_token");
} catch (Exception ex) {
what = 1;
ex.printStackTrace();
}
mHandler.sendMessage(mHandler.obtainMessage(what, 1, 0));
}
}.start();
}
private void fetchUserName() {
mProgress.setMessage("Finalizing ...");
new Thread() {
#Override
public void run() {
Log.i(TAG, "Fetching user name");
int what = 0;
try {
String v = timeMilisToString(System.currentTimeMillis());
URL url = new URL(API_URL + "/users/self?oauth_token=" + mAccessToken + "&v=" + v);
Log.d(TAG, "Opening URL " + url.toString());
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.setDoInput(true);
urlConnection.setDoOutput(true);
urlConnection.connect();
String response = streamToString(urlConnection.getInputStream());
JSONObject jsonObj = (JSONObject) new JSONTokener(response).nextValue();
JSONObject resp = (JSONObject) jsonObj.get("response");
JSONObject user = (JSONObject) resp.get("user");
String firstName = user.getString("firstName");
String lastName = user.getString("lastName");
Log.i(TAG, "Got user name: " + firstName + " " + lastName);
mSession.storeAccessToken(mAccessToken, firstName + " " + lastName);
} catch (Exception ex) {
what = 1;
ex.printStackTrace();
}
mHandler.sendMessage(mHandler.obtainMessage(what, 2, 0));
}
}.start();
}
private Handler mHandler = new Handler() {
#Override
public void handleMessage(Message msg) {
if (msg.arg1 == 1) {
if (msg.what == 0) {
fetchUserName();
} else {
mProgress.dismiss();
mListener.onFail("Failed to get access token");
}
} else {
mProgress.dismiss();
mListener.onSuccess();
}
}
};
public boolean hasAccessToken() {
return (mAccessToken == null) ? false : true;
}
public void setListener(FsqAuthListener listener) {
mListener = listener;
}
public String getUserName() {
return mSession.getUsername();
}
public void authorize() {
mDialog.show();
}
public ArrayList<FsqVenue> getNearby(double latitude, double longitude) throws Exception {
ArrayList<FsqVenue> venueList = new ArrayList<FsqVenue>();
try {
String v = timeMilisToString(System.currentTimeMillis());
String ll = String.valueOf(latitude) + "," + String.valueOf(longitude);
URL url = new URL(API_URL + "/venues/search?ll=" + ll + "&oauth_token=" + mAccessToken + "&v=" + v);
Log.d(TAG, "Opening URL " + url.toString());
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.setDoInput(true);
//urlConnection.setDoOutput(true);
urlConnection.connect();
String response = streamToString(urlConnection.getInputStream());
JSONObject jsonObj = (JSONObject) new JSONTokener(response).nextValue();
JSONArray groups = (JSONArray) jsonObj.getJSONObject("response").getJSONArray("groups");
int length = groups.length();
if (length > 0) {
for (int i = 0; i < length; i++) {
JSONObject group = (JSONObject) groups.get(i);
JSONArray items = (JSONArray) group.getJSONArray("items");
int ilength = items.length();
for (int j = 0; j < ilength; j++) {
JSONObject item = (JSONObject) items.get(j);
FsqVenue venue = new FsqVenue();
venue.id = item.getString("id");
venue.name = item.getString("name");
JSONObject location = (JSONObject) item.getJSONObject("location");
Location loc = new Location(LocationManager.GPS_PROVIDER);
loc.setLatitude(Double.valueOf(location.getString("lat")));
loc.setLongitude(Double.valueOf(location.getString("lng")));
venue.location = loc;
venue.address = location.getString("address");
venue.distance = location.getInt("distance");
venue.herenow = item.getJSONObject("hereNow").getInt("count");
venue.type = group.getString("type");
venueList.add(venue);
}
}
}
} catch (Exception ex) {
throw ex;
}
return venueList;
}
private String streamToString(InputStream is) throws IOException {
String str = "";
if (is != null) {
StringBuilder sb = new StringBuilder();
String line;
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
while ((line = reader.readLine()) != null) {
sb.append(line);
}
reader.close();
} finally {
is.close();
}
str = sb.toString();
}
return str;
}
private String timeMilisToString(long milis) {
SimpleDateFormat sd = new SimpleDateFormat("yyyyMMdd");
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(milis);
return sd.format(calendar.getTime());
}
public interface FsqAuthListener {
public abstract void onSuccess();
public abstract void onFail(String error);
}
}
FsqVenue.java
public class FsqVenue {
public String id;
public String name;
public String address;
public String type;
public Location location;
public int direction;
public int distance;
public int herenow;
}
FoursquareDialog.java
public class FoursquareDialog extends Dialog {
static final float[] DIMENSIONS_LANDSCAPE = {460, 260};
static final float[] DIMENSIONS_PORTRAIT = {280, 420};
static final FrameLayout.LayoutParams FILL = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT,
ViewGroup.LayoutParams.FILL_PARENT);
static final int MARGIN = 4;
static final int PADDING = 2;
private String mUrl;
private FsqDialogListener mListener;
private ProgressDialog mSpinner;
private WebView mWebView;
private LinearLayout mContent;
private TextView mTitle;
private static final String TAG = "Foursquare-WebView";
public FoursquareDialog(Context context, String url, FsqDialogListener listener) {
super(context);
mUrl = url;
mListener = listener;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mSpinner = new ProgressDialog(getContext());
mSpinner.requestWindowFeature(Window.FEATURE_NO_TITLE);
mSpinner.setMessage("Loading...");
mContent = new LinearLayout(getContext());
mContent.setOrientation(LinearLayout.VERTICAL);
setUpTitle();
setUpWebView();
Display display = getWindow().getWindowManager().getDefaultDisplay();
final float scale = getContext().getResources().getDisplayMetrics().density;
float[] dimensions = (display.getWidth() < display.getHeight()) ? DIMENSIONS_PORTRAIT : DIMENSIONS_LANDSCAPE;
addContentView(mContent, new FrameLayout.LayoutParams((int) (dimensions[0] * scale + 0.5f),
(int) (dimensions[1] * scale + 0.5f)));
CookieSyncManager.createInstance(getContext());
CookieManager cookieManager = CookieManager.getInstance();
cookieManager.removeAllCookie();
}
private void setUpTitle() {
requestWindowFeature(Window.FEATURE_NO_TITLE);
Drawable icon = getContext().getResources().getDrawable(R.drawable.foursquare_icon);
mTitle = new TextView(getContext());
mTitle.setText("Foursquare");
mTitle.setTextColor(Color.WHITE);
mTitle.setTypeface(Typeface.DEFAULT_BOLD);
mTitle.setBackgroundColor(0xFF0cbadf);
mTitle.setPadding(MARGIN + PADDING, MARGIN, MARGIN, MARGIN);
mTitle.setCompoundDrawablePadding(MARGIN + PADDING);
mTitle.setCompoundDrawablesWithIntrinsicBounds(icon, null, null, null);
mContent.addView(mTitle);
}
private void setUpWebView() {
mWebView = new WebView(getContext());
mWebView.setVerticalScrollBarEnabled(false);
mWebView.setHorizontalScrollBarEnabled(false);
mWebView.setWebViewClient(new TwitterWebViewClient());
mWebView.getSettings().setJavaScriptEnabled(true);
mWebView.loadUrl(mUrl);
mWebView.setLayoutParams(FILL);
mContent.addView(mWebView);
}
private class TwitterWebViewClient extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
Log.d(TAG, "Redirecting URL " + url);
if (url.startsWith(FoursquareApp.CALLBACK_URL)) {
String urls[] = url.split("=");
mListener.onComplete(urls[1]);
FoursquareDialog.this.dismiss();
return true;
}
return false;
}
#Override
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
Log.d(TAG, "Page error: " + description);
super.onReceivedError(view, errorCode, description, failingUrl);
mListener.onError(description);
FoursquareDialog.this.dismiss();
}
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
Log.d(TAG, "Loading URL: " + url);
super.onPageStarted(view, url, favicon);
mSpinner.show();
}
#Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
String title = mWebView.getTitle();
if (title != null && title.length() > 0) {
mTitle.setText(title);
}
mSpinner.dismiss();
}
}
public interface FsqDialogListener {
public abstract void onComplete(String accessToken);
public abstract void onError(String error);
}
}
FoursquareSession.java
public class FoursquareSession {
private SharedPreferences sharedPref;
private Editor editor;
private static final String SHARED = "Foursquare_Preferences";
private static final String FSQ_USERNAME = "username";
private static final String FSQ_ACCESS_TOKEN = "access_token";
public FoursquareSession(Context context) {
sharedPref = context.getSharedPreferences(SHARED, Context.MODE_PRIVATE);
editor = sharedPref.edit();
}
public void storeAccessToken(String accessToken, String username) {
editor.putString(FSQ_ACCESS_TOKEN, accessToken);
editor.putString(FSQ_USERNAME, username);
editor.commit();
}
public void resetAccessToken() {
editor.putString(FSQ_ACCESS_TOKEN, null);
editor.putString(FSQ_USERNAME, null);
editor.commit();
}
public String getUsername() {
return sharedPref.getString(FSQ_USERNAME, null);
}
public String getAccessToken() {
return sharedPref.getString(FSQ_ACCESS_TOKEN, null);
}
}
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="net.londatiga.fsq"
android:versionCode="1"
android:versionName="1.0">
<application android:icon="#drawable/icon" android:label="#string/app_name">
<activity android:name=".Main" android:label="#string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
<uses-permission android:name="android.permission.INTERNET"></uses- permission>
</manifest>

Categories

Resources