Search in sources :

Example 1 with Address

use of android.location.Address in project Talon-for-Twitter by klinker24.

the class TweetFragment method getInfo.

public void getInfo(final View favButton, final TextView favCount, final TextView retweetCount, final long tweetId, final View retweetButton) {
    Thread getInfo = new Thread(new Runnable() {

        @Override
        public void run() {
            String location = "";
            String via = "";
            long realTime = 0;
            boolean retweetedByMe = false;
            try {
                Twitter twitter = getTwitter();
                TwitterMultipleImageHelper helper = new TwitterMultipleImageHelper();
                status = twitter.showStatus(tweetId);
                ArrayList<String> i = new ArrayList<String>();
                if (picture) {
                    i = helper.getImageURLs(status, twitter);
                }
                final ArrayList<String> images = i;
                GeoLocation loc = status.getGeoLocation();
                try {
                    Geocoder geocoder = new Geocoder(context, Locale.getDefault());
                    List<Address> addresses = geocoder.getFromLocation(loc.getLatitude(), loc.getLongitude(), 1);
                    if (addresses.size() > 0) {
                        Address address = addresses.get(0);
                        location += address.getLocality() + ", " + address.getCountryName();
                    } else {
                        location = "";
                    }
                } catch (Exception x) {
                    location = "";
                }
                via = android.text.Html.fromHtml(status.getSource()).toString();
                final String sfavCount;
                if (status.isRetweet()) {
                    twitter4j.Status status2 = status.getRetweetedStatus();
                    via = android.text.Html.fromHtml(status2.getSource()).toString();
                    realTime = status2.getCreatedAt().getTime();
                    sfavCount = status2.getFavoriteCount() + "";
                } else {
                    realTime = status.getCreatedAt().getTime();
                    sfavCount = status.getFavoriteCount() + "";
                }
                retweetedByMe = status.isRetweetedByMe();
                final String retCount = "" + status.getRetweetCount();
                final String timeDisplay;
                if (!settings.militaryTime) {
                    timeDisplay = DateFormat.getDateInstance(DateFormat.MEDIUM, Locale.US).format(realTime) + " " + DateFormat.getTimeInstance(DateFormat.SHORT, Locale.US).format(realTime);
                } else {
                    timeDisplay = DateFormat.getDateInstance(DateFormat.MEDIUM, Locale.GERMAN).format(realTime) + " " + DateFormat.getTimeInstance(DateFormat.SHORT, Locale.GERMAN).format(realTime);
                }
                final String fVia = " " + getResources().getString(R.string.via) + " " + via;
                final String fLoc = location.equals("") ? "" : "\n" + location;
                final boolean fRet = retweetedByMe;
                final long fTime = realTime;
                final Status fStatus = status;
                ((Activity) context).runOnUiThread(new Runnable() {

                    @Override
                    public void run() {
                        retweetCount.setText(" " + retCount);
                        if (retweetButton instanceof ImageButton) {
                            if (fRet) {
                                if (!settings.addonTheme) {
                                    ((ImageButton) retweetButton).setColorFilter(context.getResources().getColor(R.color.app_color));
                                } else {
                                    ((ImageButton) retweetButton).setColorFilter(settings.accentInt);
                                }
                            } else {
                                ((ImageButton) retweetButton).clearColorFilter();
                            }
                        } else {
                            if (fRet) {
                                if (!settings.addonTheme) {
                                    retweetButton.setBackgroundColor(context.getResources().getColor(R.color.app_color));
                                } else {
                                    retweetButton.setBackgroundColor(settings.accentInt);
                                }
                            } else {
                                retweetButton.setBackgroundColor(getResources().getColor(android.R.color.transparent));
                            }
                        }
                        timetv.setText(timeDisplay + fVia);
                        timetv.append(fLoc);
                        favCount.setText(" " + sfavCount);
                        if (favButton instanceof ImageButton) {
                            if (fStatus.isFavorited()) {
                                TypedArray a = context.getTheme().obtainStyledAttributes(new int[] { R.attr.favoritedButton });
                                int resource = a.getResourceId(0, 0);
                                a.recycle();
                                if (!settings.addonTheme) {
                                    ((ImageButton) favButton).setColorFilter(context.getResources().getColor(R.color.app_color));
                                } else {
                                    ((ImageButton) favButton).setColorFilter(settings.accentInt);
                                }
                                ((ImageButton) favButton).setImageDrawable(context.getResources().getDrawable(resource));
                                isFavorited = true;
                            } else {
                                TypedArray a = context.getTheme().obtainStyledAttributes(new int[] { R.attr.notFavoritedButton });
                                int resource = a.getResourceId(0, 0);
                                a.recycle();
                                ((ImageButton) favButton).setImageDrawable(context.getResources().getDrawable(resource));
                                isFavorited = false;
                                ((ImageButton) favButton).clearColorFilter();
                            }
                        } else {
                            if (fStatus.isFavorited()) {
                                TypedArray a = context.getTheme().obtainStyledAttributes(new int[] { R.attr.favoritedButton });
                                int resource = a.getResourceId(0, 0);
                                a.recycle();
                                if (!settings.addonTheme) {
                                    favButton.setBackgroundColor(context.getResources().getColor(R.color.app_color));
                                } else {
                                    favButton.setBackgroundColor(settings.accentInt);
                                }
                                isFavorited = true;
                            } else {
                                isFavorited = false;
                                favButton.setBackgroundColor(getResources().getColor(android.R.color.transparent));
                            }
                        }
                        for (String s : images) {
                            Log.v("talon_image", s);
                        }
                        if (images.size() > 1) {
                            Log.v("talon_images", "size: " + images.size());
                            try {
                                mAttacher.setOnViewTapListener(new PhotoViewAttacher.OnViewTapListener() {

                                    @Override
                                    public void onViewTap(View view, float x, float y) {
                                        Intent viewPics = new Intent(context, ViewPictures.class);
                                        viewPics.putExtra("images", images);
                                        startActivity(viewPics);
                                    }
                                });
                            } catch (Exception e) {
                                // addon theme without the attacher
                                profilePic.setOnClickListener(new View.OnClickListener() {

                                    @Override
                                    public void onClick(View v) {
                                        Intent viewPics = new Intent(context, ViewPictures.class);
                                        viewPics.putExtra("images", images);
                                        startActivity(viewPics);
                                    }
                                });
                            }
                        }
                    }
                });
            } catch (Exception e) {
            }
        }
    });
    getInfo.setPriority(Thread.MAX_PRIORITY);
    getInfo.start();
}
Also used : ViewPictures(com.klinker.android.twitter.activities.tweet_viewer.ViewPictures) Address(android.location.Address) ArrayList(java.util.ArrayList) TwitterMultipleImageHelper(com.klinker.android.twitter.utils.api_helper.TwitterMultipleImageHelper) Intent(android.content.Intent) Geocoder(android.location.Geocoder) PhotoViewAttacher(uk.co.senab.photoview.PhotoViewAttacher) ImageView(android.widget.ImageView) View(android.view.View) AdapterView(android.widget.AdapterView) TextView(android.widget.TextView) FileNotFoundException(java.io.FileNotFoundException) IOException(java.io.IOException) Point(android.graphics.Point) ImageButton(android.widget.ImageButton) TypedArray(android.content.res.TypedArray) List(java.util.List) ArrayList(java.util.ArrayList)

Example 2 with Address

use of android.location.Address in project Android-ReactiveLocation by mcharmas.

the class FallbackReverseGeocodeObservable method alternativeReverseGeocodeQuery.

/**
     * This function fetches a list of addresses for the set latitude, longitude and maxResults properties from the
     * Google Geocode API (http://maps.googleapis.com/maps/api/geocode).
     *
     * @return List of addresses
     * @throws IOException   In case of network problems
     * @throws JSONException In case of problems while parsing the json response from google geocode API servers
     */
private List<Address> alternativeReverseGeocodeQuery() throws IOException, JSONException {
    URL url = new URL(String.format(Locale.ENGLISH, "http://maps.googleapis.com/maps/api/geocode/json?" + "latlng=%1$f,%2$f&sensor=true&language=%3$s", latitude, longitude, locale.getLanguage()));
    HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
    StringBuilder stringBuilder = new StringBuilder();
    List<Address> outResult = new ArrayList<>();
    try {
        BufferedReader reader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream(), "UTF-8"));
        String line;
        while ((line = reader.readLine()) != null) {
            stringBuilder.append(line);
        }
        // Root json response object
        JSONObject jsonRootObject = new JSONObject(stringBuilder.toString());
        // No results status
        if ("ZERO_RESULTS".equalsIgnoreCase(jsonRootObject.getString("status"))) {
            return Collections.emptyList();
        }
        // Other non-OK responses status
        if (!"OK".equalsIgnoreCase(jsonRootObject.getString("status"))) {
            throw new RuntimeException("Wrong API response");
        }
        // Process results
        JSONArray results = jsonRootObject.getJSONArray("results");
        for (int i = 0; i < results.length() && i < maxResults; i++) {
            Address address = new Address(Locale.getDefault());
            String addressLineString = "";
            JSONObject sourceResult = results.getJSONObject(i);
            JSONArray addressComponents = sourceResult.getJSONArray("address_components");
            // Assemble address by various components
            for (int ac = 0; ac < addressComponents.length(); ac++) {
                String longNameVal = addressComponents.getJSONObject(ac).getString("long_name");
                String shortNameVal = addressComponents.getJSONObject(ac).getString("short_name");
                JSONArray acTypes = addressComponents.getJSONObject(ac).getJSONArray("types");
                String acType = acTypes.getString(0);
                if (!TextUtils.isEmpty(longNameVal)) {
                    if (acType.equalsIgnoreCase("street_number")) {
                        if (TextUtils.isEmpty(addressLineString)) {
                            addressLineString = longNameVal;
                        } else {
                            addressLineString += " " + longNameVal;
                        }
                    } else if (acType.equalsIgnoreCase("route")) {
                        if (TextUtils.isEmpty(addressLineString)) {
                            addressLineString = longNameVal;
                        } else {
                            addressLineString = longNameVal + " " + addressLineString;
                        }
                    } else if (acType.equalsIgnoreCase("sublocality")) {
                        address.setSubLocality(longNameVal);
                    } else if (acType.equalsIgnoreCase("locality")) {
                        address.setLocality(longNameVal);
                    } else if (acType.equalsIgnoreCase("administrative_area_level_2")) {
                        address.setSubAdminArea(longNameVal);
                    } else if (acType.equalsIgnoreCase("administrative_area_level_1")) {
                        address.setAdminArea(longNameVal);
                    } else if (acType.equalsIgnoreCase("country")) {
                        address.setCountryName(longNameVal);
                        address.setCountryCode(shortNameVal);
                    } else if (acType.equalsIgnoreCase("postal_code")) {
                        address.setPostalCode(longNameVal);
                    }
                }
            }
            // Try to get the already formatted address
            String formattedAddress = sourceResult.getString("formatted_address");
            if (!TextUtils.isEmpty(formattedAddress)) {
                String[] formattedAddressLines = formattedAddress.split(",");
                for (int ia = 0; ia < formattedAddressLines.length; ia++) {
                    address.setAddressLine(ia, formattedAddressLines[ia].trim());
                }
            } else if (!TextUtils.isEmpty(addressLineString)) {
                // If that fails use our manually assembled formatted address
                address.setAddressLine(0, addressLineString);
            }
            // Finally add address to resulting set
            outResult.add(address);
        }
    } finally {
        urlConnection.disconnect();
    }
    return Collections.unmodifiableList(outResult);
}
Also used : Address(android.location.Address) InputStreamReader(java.io.InputStreamReader) ArrayList(java.util.ArrayList) JSONArray(org.json.JSONArray) URL(java.net.URL) HttpURLConnection(java.net.HttpURLConnection) JSONObject(org.json.JSONObject) BufferedReader(java.io.BufferedReader)

Example 3 with Address

use of android.location.Address in project weiciyuan by qii.

the class GoogleGeoCoderDao method get.

public String get() {
    Geocoder geocoder = new Geocoder(activity, Locale.getDefault());
    List<Address> addresses = null;
    try {
        if (!Utility.isGPSLocationCorrect(geoBean)) {
            return null;
        }
        addresses = geocoder.getFromLocation(geoBean.getLat(), geoBean.getLon(), 1);
    } catch (IOException e) {
    }
    if (addresses != null && addresses.size() > 0) {
        Address address = addresses.get(0);
        StringBuilder builder = new StringBuilder();
        int size = address.getMaxAddressLineIndex();
        for (int i = 0; i < size; i++) {
            builder.append(address.getAddressLine(i));
        }
        return builder.toString();
    }
    return null;
}
Also used : Address(android.location.Address) IOException(java.io.IOException) Geocoder(android.location.Geocoder)

Example 4 with Address

use of android.location.Address in project robolectric by robolectric.

the class ShadowGeocoder method makeAddress.

private Address makeAddress() {
    Address address = new Address(Locale.getDefault());
    address.setLatitude(simulatedLatitude);
    address.setLongitude(simulatedLongitude);
    ReflectionHelpers.setField(address, "mHasLatitude", hasLatitude);
    ReflectionHelpers.setField(address, "mHasLongitude", hasLongitude);
    return address;
}
Also used : Address(android.location.Address)

Example 5 with Address

use of android.location.Address in project muzei by romannurik.

the class GalleryArtSource method ensureMetadataExists.

private void ensureMetadataExists(@NonNull Uri imageUri) {
    Cursor existingMetadata = getContentResolver().query(GalleryContract.MetadataCache.CONTENT_URI, new String[] { BaseColumns._ID }, GalleryContract.MetadataCache.COLUMN_NAME_URI + "=?", new String[] { imageUri.toString() }, null);
    if (existingMetadata == null) {
        return;
    }
    boolean metadataExists = existingMetadata.moveToFirst();
    existingMetadata.close();
    if (!metadataExists) {
        // No cached metadata or it's stale, need to pull it separately using Exif
        ContentValues values = new ContentValues();
        values.put(GalleryContract.MetadataCache.COLUMN_NAME_URI, imageUri.toString());
        try (InputStream in = getContentResolver().openInputStream(imageUri)) {
            if (in == null) {
                return;
            }
            ExifInterface exifInterface = new ExifInterface(in);
            String dateString = exifInterface.getAttribute(ExifInterface.TAG_DATETIME);
            if (!TextUtils.isEmpty(dateString)) {
                Date date = sExifDateFormat.parse(dateString);
                values.put(GalleryContract.MetadataCache.COLUMN_NAME_DATETIME, date.getTime());
            }
            float[] latlong = new float[2];
            if (exifInterface.getLatLong(latlong)) {
                // Reverse geocode
                List<Address> addresses = null;
                try {
                    addresses = mGeocoder.getFromLocation(latlong[0], latlong[1], 1);
                } catch (IllegalArgumentException e) {
                    Log.w(TAG, "Invalid latitude/longitude, skipping location metadata", e);
                }
                if (addresses != null && addresses.size() > 0) {
                    Address addr = addresses.get(0);
                    String locality = addr.getLocality();
                    String adminArea = addr.getAdminArea();
                    String countryCode = addr.getCountryCode();
                    StringBuilder sb = new StringBuilder();
                    if (!TextUtils.isEmpty(locality)) {
                        sb.append(locality);
                    }
                    if (!TextUtils.isEmpty(adminArea)) {
                        if (sb.length() > 0) {
                            sb.append(", ");
                        }
                        sb.append(adminArea);
                    }
                    if (!TextUtils.isEmpty(countryCode) && !sOmitCountryCodes.contains(countryCode)) {
                        if (sb.length() > 0) {
                            sb.append(", ");
                        }
                        sb.append(countryCode);
                    }
                    values.put(GalleryContract.MetadataCache.COLUMN_NAME_LOCATION, sb.toString());
                }
            }
            getContentResolver().insert(GalleryContract.MetadataCache.CONTENT_URI, values);
        } catch (ParseException | IOException | NumberFormatException | StackOverflowError e) {
            Log.w(TAG, "Couldn't read image metadata.", e);
        }
    }
}
Also used : ContentValues(android.content.ContentValues) Address(android.location.Address) InputStream(java.io.InputStream) ExifInterface(android.support.media.ExifInterface) IOException(java.io.IOException) Cursor(android.database.Cursor) Date(java.util.Date) ParseException(java.text.ParseException)

Aggregations

Address (android.location.Address)34 Geocoder (android.location.Geocoder)22 IOException (java.io.IOException)18 Locale (java.util.Locale)6 Location (android.location.Location)4 ArrayList (java.util.ArrayList)4 List (java.util.List)3 SuppressLint (android.annotation.SuppressLint)1 ContentValues (android.content.ContentValues)1 Intent (android.content.Intent)1 TypedArray (android.content.res.TypedArray)1 Cursor (android.database.Cursor)1 Point (android.graphics.Point)1 LocationManager (android.location.LocationManager)1 ExifInterface (android.support.media.ExifInterface)1 View (android.view.View)1 AdapterView (android.widget.AdapterView)1 ImageButton (android.widget.ImageButton)1 ImageView (android.widget.ImageView)1 TextView (android.widget.TextView)1