DIsplay files downloaded from json on main screen? - java

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

Related

Updating cluster markers pictures

I am creating a social media app that helps people find their friends. One feature that I want to include is users being able to choose their profile picture. However I am having issues updating cluster marker pictures. Basically I am using volly to connect to a db to get the most recent user data. This method is called when I click a button. I did something similar to change the users profile picture with success. I am not sure why this is not working if anyone can give pointers that would be great.
private void updateMapMarkers(){
//mMap.clear(); not sure if i need to do this or not
//mClusterManager.clearItems(); also tried this
mClusterManager.removeItems(mClusterMarkers);
RequestQueue queue = Volley.newRequestQueue(MainActivity.this);
String url = "http://some ip address/update_everyones_cords.php?THIS_USER_ID=" + MainActivity.THIS_USER_ID;
JsonArrayRequest jsObjRequest = new JsonArrayRequest(Request.Method.GET, url,null,
new Response.Listener<JSONArray>() {
public void onResponse(JSONArray response){
try {
ArrayList<ClusterMarker> mClusterMarkersUpdated = new ArrayList<>();
for (int i = 0; i < response.length(); i++) {
JSONObject rec = response.getJSONObject(i);
String userName = rec.getString("userName");
String profilePicture = rec.getString("profilePicture");
int userID = rec.getInt("ID");
int avatar;
if (profilePicture.equals("default")){
avatar = R.drawable.androidlogo;
} else {
avatar = Integer.parseInt(THIS_USER_PIC);
}
if (userID == THIS_USER_ID){
ClusterMarker thisUser = new ClusterMarker(
new LatLng(THIS_CORDSV1, THIS_CORDSV2),
THIS_USER_NAME,
"This is you",
avatar,
THIS_USER_ID);
mClusterManager.addItem(thisUser);
mClusterMarkersUpdated.add(thisUser);
Log.wtf(TAG,userName);
} else {
Log.wtf(TAG,userName);
ClusterMarker thisUser = new ClusterMarker(
new LatLng(THIS_CORDSV1, THIS_CORDSV2),
userName,
"determine route to",
avatar,
userID);
mClusterManager.addItem(thisUser);
mClusterMarkersUpdated.add(thisUser);
}
}
mClusterMarkers = mClusterMarkersUpdated;
} catch (JSONException e) {
Toast.makeText(MainActivity.this, "jason obj ex:" + e.toString(), Toast.LENGTH_SHORT).show();
}
}
}, new Response.ErrorListener() {
public void onErrorResponse(VolleyError er){
Toast.makeText(MainActivity.this, "volley error:" + er.toString(), Toast.LENGTH_LONG).show();
}
}
); queue.add(jsObjRequest);
mClusterManager.cluster();
}
I also tried something like this, also didn't work. When I say it doesn't work I do not get any errors just a blank map with no markers at least for the above method. For the below attempt nothing at all happens.
int defaultImage = R.drawable.androidlogo;
mImageUrlsLarger.add(defaultImage + "");
mClusterMarkers.get(i).setIconPicture(defaultImage);
mClusterManager.cluster();
public class CustomClusterItem implements ClusterItem {
private final LatLng position;
private String title;
private String snippet;
private String tag;
private String imageUrl;
public CustomClusterItem(double lat, double lng) {
this.position = new LatLng(lat, lng);
}
//getters and setters
}
CustomClusterRenderer.Java
public class CustomClusterRenderer extends DefaultClusterRenderer<CustomClusterItem> implements GoogleMap.OnCameraIdleListener {
private CameraIdleListener listener;
//used to keep strong reference to 'Target' object, otherwise objects get garbage collected and picasso will fail to load image
private List<Target> targetList = new ArrayList<>();
private IconGenerator greenIconGenerator;
private ImageView greenImageView;
private Context context;
public CustomClusterRenderer(Context context, GoogleMap map, ClusterManager<CustomClusterItem> clusterManager) {
super(context, map, clusterManager);
this.context = context;
prepareImageViews(context);
prepareIconGenerator(context);
}
public void setCameraIdleListener(CameraIdleListener cameraIdleListener) {
this.listener = cameraIdleListener;
}
public void clearTargetList() {
targetList.clear();
}
private void prepareIconGenerator(Context context) {
greenIconGenerator = new IconGenerator(context);
greenIconGenerator.setColor(ContextCompat.getColor(context, R.color.priority_green));
greenIconGenerator.setContentView(greenImageView);
}
private void prepareImageViews(Context context) {
final int mDimension = (int) context.getResources().getDimension(R.dimen._30sdp);
final int padding = (int) context.getResources().getDimension(R.dimen._8sdp);
greenImageView = new ImageView(context);
greenImageView.setLayoutParams(new ViewGroup.LayoutParams(mDimension, mDimension));
greenImageView.setPadding(padding, padding, padding, padding);
}
#Override
protected void onBeforeClusterItemRendered(final CaseClusterItem item,
final MarkerOptions markerOptions) {
Bitmap largeIcon = BitmapFactory.decodeResource(context.getResources(), R.drawable.ic_action_settings);
getImageView(item.getPriority()).setImageBitmap(largeIcon);
Bitmap icon = greenIconGenerator.makeIcon();
markerOptions.icon(BitmapDescriptorFactory.fromBitmap(icon));
}
#Override
protected void onClusterItemRendered(final CustomClusterItem clusterItem,
final Marker marker) {
super.onClusterItemRendered(clusterItem, marker);
Target target = new Target() {
#Override
public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) {
//TODO - find the root cause for IllegalArgumentException
try {
greenImageView.setImageBitmap(bitmap);
Bitmap icon = greenIconGenerator.makeIcon();
marker.setIcon(BitmapDescriptorFactory.fromBitmap(icon));
} catch (IllegalArgumentException e) {
LogHelper.printErrorLog("Not sure about the cause of issue, need to rectify");
}
}
#Override
public void onBitmapFailed(Drawable errorDrawable) {
}
#Override
public void onPrepareLoad(Drawable placeHolderDrawable) {
}
};
if (!TextUtils.isEmpty(clusterItem.getImageUrl())) {
getPicasso().load(clusterItem.getImageUrl()).resize(60, 60).into(target);
targetList.add(target);
}
}
#Override
public void onCameraIdle() {
if (listener != null) {
listener.onCameraIdle();
}
}
public interface CameraIdleListener {
void onCameraIdle();
}
}
HomeFragment.Java
public class HomeFragment extends BaseFragment implements OnMapReadyCallback, GoogleMap.OnCameraIdleListener, GoogleMap.OnMarkerClickListener, ClusterManager.OnClusterItemClickListener<CustomClusterItem>, ClusterManager.OnClusterClickListener<CustomClusterItem>, CustomClusterRenderer.CameraIdleListener{
private ClusterManager<CustomClusterItem> clusterManager;
private CustomClusterRenderer clusterRenderer;
private void generateMarkerFromCase(List<CustomListResponse.DataBean.CaseBean> caseList) {
clusterRenderer.clearTargetList();
if (caseList == null) {
ToastHelper.show("No cases found.");
return;
}
for (final CustomListResponse.DataBean.CustomBean caseBean : caseList) {
try {
final double lat = Double.parseDouble(caseBean.getLat());
final double lng = Double.parseDouble(caseBean.getLongX());
String markerUrl;
markerUrl = caseBean.getParent_category().getImage();
if (markerUrl == null) {
markerUrl = caseBean.getCategory().getImage();
}
CustomClusterItem clusterItem = new CustomClusterItem(lat, lng);
clusterItem.setTag(caseBean.getId());
clusterItem.setImageUrl(markerUrl);
clusterItem.setPriority(caseBean.getPriority());
clusterManager.addItem(clusterItem);
} catch (NumberFormatException e) {
LogHelper.printErrorLog("Lat or Lng is null, bcz app is still in development mode : " + caseBean.getTitle() + " , Des - " + caseBean.getDescription());
}
}
clusterManager.cluster();
zoomOutMap();
}
#Override
public void onMapReady(GoogleMap map) {
this.googleMap = map;
clusterManager = new ClusterManager<>(getContext(), googleMap);
clusterManagerAlgorithm = new NonHierarchicalDistanceBasedAlgorithm();
clusterManager.setAlgorithm(clusterManagerAlgorithm);
clusterRenderer = new CustomClusterRenderer(getContext(), googleMap, clusterManager);
clusterRenderer.setCameraIdleListener(this);
clusterManager.setRenderer(clusterRenderer);
this.googleMap.setOnCameraIdleListener(clusterManager);
this.googleMap.setOnMarkerClickListener(clusterManager);
clusterManager.setOnClusterItemClickListener(this);
clusterManager.setOnClusterClickListener(this);
}
}

How to Show Progress Dialog in non activity class

I'm creating a small utility app to show Movies list from Database. The app contains Mainactivity which further contain Tablayout with 3 Tabbar and one Fragment Class which loads class called Moviesult and it handles the call and display popular movies, New Movies and favourites with below code
switch (fragType) {
case POPULAR:
MoviesUtil.getPopularMovies(getActivity(), callback);
break;
case TOP_RATED:
MoviesUtil.getTopRatedMovies(getActivity(), callback);
break;
case FAVORITES:
MoviesUtil.getFavoritesMovies(getActivity(), callback);
break;
}
I am trying to show ProgressDialog as the Movies are loading in Background insetad of Blank screen and hide once movie load is complete. But I'm unable to do so.
I tried using
ProgressDialog progress;
and
progress.setTitle("Logging In");
progress.setMessage("Please Wait...");
progress.setCanceledOnTouchOutside(false);
progress.show();
inside
private static void getMovies(final Activity activity, final String type, final MoviesCallback callback) {
AsyncTask.execute(new Runnable() {
#Override
public void run() {
if (Util.isConnected(activity, false) && !type.equals(TYPE_FAVORITES)) {
getMoviesFromApi(activity, type);
}
getMoviesFromDb(activity, type, callback);
//code Here
}
But it throws error non-static cannot be applied to static class. How can I solve this please help.
Below is my Class File
public class MoviesUtil {
private static final Webb WEBB = Webb.create();
private static final String TMDB_API_MOVIES_URL = "http://api.themoviedb.org/3/movie/%s?api_key=%s&page=%s";
private static final String TMDB_API_VIDEOS_URL = "http://api.themoviedb.org/3/movie/%s/videos?api_key=%s";
private static final String TMDB_API_REVIEWS_URL = "http://api.themoviedb.org/3/movie/%s/reviews?api_key=%s";
private static final String TMDB_POSTER_URL = "https://image.tmdb.org/t/p/w185%s";
private static final String TMDB_BACKDROP_URL = "https://image.tmdb.org/t/p/w300%s";
private static final String TYPE_POPULAR = "popular";
private static final String TYPE_TOP_RATED = "top_rated";
private static final String TYPE_FAVORITES = "favorites";
ProgressDialog progressDialog;
public static boolean isFavorite(Context context, Movie movie) {
Cursor cursor = context.getContentResolver()
.query(MovieContract.CONTENT_URI,
null,
String.format("%s = ? and %s = ?", MovieContract.MOVIE_ID, MovieContract.TYPE),
new String[]{movie.getId() + "", TYPE_FAVORITES},
null
);
boolean isFavorite = cursor.getCount() > 0;
cursor.close();
return isFavorite;
}
public static boolean toggleFavorite(Context context, Movie movie) {
if (isFavorite(context, movie)) {
deleteMovie(context, TYPE_FAVORITES, movie);
return false;
} else {
saveMovie(context, TYPE_FAVORITES, movie);
return true;
}
}
public static void getPopularMovies(Activity activity, MoviesCallback callback) {
getMovies(activity, TYPE_POPULAR, callback);
}
public static void getTopRatedMovies(Activity activity, MoviesCallback callback) {
getMovies(activity, TYPE_TOP_RATED, callback);
}
public static void getFavoritesMovies(Activity activity, MoviesCallback callback) {
getMovies(activity, TYPE_FAVORITES, callback);
}
private static void getMovies(final Activity activity, final String type, final MoviesCallback callback) {
AsyncTask.execute(new Runnable() {
#Override
public void run() {
if (Util.isConnected(activity, false) && !type.equals(TYPE_FAVORITES)) {
getMoviesFromApi(activity, type);
}
getMoviesFromDb(activity, type, callback);
}
});
}
private static void getMoviesFromApi(Activity activity, String type) {
String apiUrl = String.format(TMDB_API_MOVIES_URL, type, activity.getString(R.string.tmdb_api_key), 1);
try {
JSONArray moviesJson = WEBB.get(apiUrl)
.asJsonObject()
.getBody()
.getJSONArray("results");
List<Movie> movies = toMovies(activity, moviesJson);
deleteMovies(activity, type);
saveMovies(activity, type, movies);
} catch (JSONException e) {
e.printStackTrace();
}
}
private static void getMoviesFromDb(Activity activity, String type, final MoviesCallback callback) {
try {
Cursor cursor = activity.getContentResolver()
.query(MovieContract.CONTENT_URI,
null,
MovieContract.TYPE + " = ?",
new String[]{type},
null
);
final List<Movie> movies = toMovies(cursor);
cursor.close();
activity.runOnUiThread(new Runnable() {
#Override
public void run() {
callback.success(movies);
}
});
} catch (final Exception e) {
activity.runOnUiThread(new Runnable() {
#Override
public void run() {
callback.error(e);
}
});
}
}
public static void getReviewsFromApi(final Activity activity, final Movie movie, final ReviewsCallback callback) {
if (Util.isConnected(activity, false)) {
AsyncTask.execute(new Runnable() {
#Override
public void run() {
String apiUrl = String.format(TMDB_API_REVIEWS_URL, movie.getId(), activity.getString(R.string.tmdb_api_key));
final List<Review> reviews = new ArrayList<>();
try {
JSONArray reviewsJson = WEBB.get(apiUrl)
.asJsonObject()
.getBody()
.getJSONArray("results");
reviews.addAll(toReviews(reviewsJson));
} catch (final Exception e) {
activity.runOnUiThread(new Runnable() {
#Override
public void run() {
callback.error(e);
}
});
}
if (reviews.isEmpty()) {
Review review = new Review();
review.setContent(activity.getString(R.string.no_review_found));
reviews.add(review);
}
activity.runOnUiThread(new Runnable() {
#Override
public void run() {
callback.success(reviews);
}
});
}
});
} else {
Review review = new Review();
review.setContent(activity.getString(R.string.conn_internet));
final List<Review> reviews = new ArrayList<>();
reviews.add(review);
activity.runOnUiThread(new Runnable() {
#Override
public void run() {
callback.success(reviews);
}
});
}
}
private static void saveMovie(final Context context, final String type, final Movie movie) {
AsyncTask.execute(new Runnable() {
#Override
public void run() {
List<Movie> movies = new ArrayList<>();
movies.add(movie);
saveMovies(context, type, movies);
}
});
}
private static void saveMovies(Context context, String type, List<Movie> movies) {
if (movies != null) {
ContentValues[] moviesValues = new ContentValues[movies.size()];
for (int i = 0; i < movies.size(); i++) {
try {
Movie movie = movies.get(i);
ContentValues movieValues = new ContentValues();
movieValues.put(MovieContract.MOVIE_ID, movie.getId());
movieValues.put(MovieContract.TYPE, type);
movieValues.put(MovieContract.TITLE, movie.getTitle());
movieValues.put(MovieContract.OVERVIEW, movie.getOverview());
movieValues.put(MovieContract.POSTER_URL, movie.getPosterUrl());
movieValues.put(MovieContract.BACKDROP_URL, movie.getBackdropUrl());
movieValues.put(MovieContract.TRAILER_URL, movie.getTrailerUrl());
movieValues.put(MovieContract.RELEASE_DATE, Util.toDbDate(movie.getReleaseDate()));
movieValues.put(MovieContract.RATING, movie.getRating());
movieValues.put(MovieContract.ADULT, movie.isAdult() ? 1 : 0);
moviesValues[i] = movieValues;
} catch (Exception ignore) {
}
}
context.getContentResolver()
.bulkInsert(MovieContract.CONTENT_URI, moviesValues);
}
}
private static void deleteMovie(final Context context, final String type, final Movie movie) {
AsyncTask.execute(new Runnable() {
#Override
public void run() {
context.getContentResolver()
.delete(MovieContract.CONTENT_URI,
MovieContract.MOVIE_ID + " = ? and " + MovieContract.TYPE + " = ?",
new String[]{movie.getId() + "", type});
}
});
}
private static void deleteMovies(final Context context, final String type) {
AsyncTask.execute(new Runnable() {
#Override
public void run() {
context.getContentResolver()
.delete(MovieContract.CONTENT_URI,
MovieContract.TYPE + " = ?",
new String[]{type});
}
});
}
private static List<Movie> toMovies(Cursor cursor) {
List<Movie> movies = new ArrayList<>();
while (cursor.moveToNext()) {
Movie movie = new Movie();
movie.setId(cursor.getInt(
cursor.getColumnIndex(MovieContract.MOVIE_ID)));
movie.setTitle(cursor.getString(
cursor.getColumnIndex(MovieContract.TITLE)));
movie.setOverview(cursor.getString(
cursor.getColumnIndex(MovieContract.OVERVIEW)));
movie.setPosterUrl(cursor.getString(
cursor.getColumnIndex(MovieContract.POSTER_URL)));
movie.setBackdropUrl(cursor.getString(
cursor.getColumnIndex(MovieContract.BACKDROP_URL)));
movie.setTrailerUrl(cursor.getString(
cursor.getColumnIndex(MovieContract.TRAILER_URL)));
movie.setReleaseDate(Util.toDate(cursor.getString(
cursor.getColumnIndex(MovieContract.RELEASE_DATE))));
movie.setRating(cursor.getFloat(
cursor.getColumnIndex(MovieContract.RATING)));
movie.setAdult(cursor.getInt(
cursor.getColumnIndex(MovieContract.ADULT)) == 1);
movies.add(movie);
}
return movies;
}
private static List<Movie> toMovies(Context context, JSONArray jsonMovies) {
List<Movie> movies = new ArrayList<>();
if (jsonMovies != null) {
for (int i = 0; i < jsonMovies.length(); i++) {
try {
JSONObject jsonMovie = jsonMovies.getJSONObject(i);
int movieId = jsonMovie.getInt("id");
Movie movie = new Movie();
movie.setId(movieId);
movie.setTitle(jsonMovie.getString("title"));
movie.setOverview(jsonMovie.getString("overview"));
movie.setPosterUrl(String.format(TMDB_POSTER_URL, jsonMovie.getString("poster_path")));
movie.setBackdropUrl(String.format(TMDB_BACKDROP_URL, jsonMovie.getString("backdrop_path")));
movie.setTrailerUrl(getTrailerUrl(context, movieId));
movie.setReleaseDate(Util.toDate(jsonMovie.getString("release_date")));
movie.setRating((float) jsonMovie.getDouble("vote_average"));
movie.setAdult(jsonMovie.getBoolean("adult"));
movies.add(movie);
} catch (Exception e) {
e.printStackTrace();
}
}
}
return movies;
}
private static List<Review> toReviews(JSONArray jsonReviews) {
List<Review> reviews = new ArrayList<>();
if (jsonReviews != null) {
for (int i = 0; i < jsonReviews.length(); i++) {
try {
JSONObject jsonReview = jsonReviews.getJSONObject(i);
Review review = new Review();
review.setAuthor(jsonReview.getString("author"));
review.setContent(jsonReview.getString("content"));
reviews.add(review);
} catch (Exception e) {
e.printStackTrace();
}
}
}
return reviews;
}
private static String getTrailerUrl(Context context, int movieId) {
String apiUrl = String.format(TMDB_API_VIDEOS_URL, movieId, context.getString(R.string.tmdb_api_key));
try {
JSONArray trailersJson = WEBB.get(apiUrl)
.asJsonObject()
.getBody()
.getJSONArray("results");
for (int i = 0; i < trailersJson.length(); i++) {
JSONObject trailerJson = trailersJson.getJSONObject(i);
if (trailerJson.getString("site").toLowerCase().equals("youtube")) {
return "https://youtube.com/watch?v=" + trailerJson.getString("key");
}
}
return "";
} catch (Exception e) {
e.printStackTrace();
return "";
}
}
}
Thanks in advance.
Your ProgressDialog is not static in MoviesUtil
Change it to
private static ProgressDialog progressDialog;
You can add a ProgressBar to your xml file:
<ProgressBar
android:id="#+id/loading_bar"
style="#style/Widget.AppCompat.ProgressBar"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"/>
And when the downloading is finished just hide it:
ProgressBar progressBar = (ProgressBar) findViewById(R.id.loading_bar);
progressBar.setVisibility(View.GONE);

Android changing google gallery picker to normal gallery picker

i found a code about gallery picker and it pick photos from google images. But i want to pick photos from normal gallery. Here is the code :
public class ImageCrop {
private static final String TAG = "ImageCrop";
private static final boolean REMOVE_TEMP_FILE = true;
private static final boolean DEBUG = false;
Context context;
public static final int PICK_FROM_CAMERA = 0;
public static final int PICK_FROM_ALBUM = 1;
public static final int PERMISSION_FROM_CAMERA = 3;
private static final int PHOTO_SIZE = 1000;
private static final String ACTIVITY_NAME_PHOTOS = "com.google.android.apps.photos";
private static final String ACTIVITY_NAME_PLUS = "com.google.android.apps.plus";
private static boolean mUseActivityPhoto = false;
private static boolean mUseActivityPlus = false;
private static Uri mImageCaptureUri;
private static Bitmap mCropBitmap;
private static String mTempImagePath;
private static int mLastAction = PICK_FROM_CAMERA;
private static final String CAMERA_TEMP_PREFIX = "camera_";
private static final String CROP_TEMP_PREFIX = "crop_";
private static final String IMAGE_EXT = ".png";
public static void checkPackages(Activity context, Intent intentPhoto) {
final PackageManager pm = context.getPackageManager();
final Intent intent = new Intent(Intent.ACTION_MAIN, null);
intent.addCategory(Intent.CATEGORY_LAUNCHER);
mUseActivityPhoto = false;
mUseActivityPlus = false;
final List<ResolveInfo> infos = pm.queryIntentActivities(intent, PackageManager.MATCH_ALL);
for (ResolveInfo info : infos) {
if(info.activityInfo.packageName.equals(ACTIVITY_NAME_PHOTOS)) {
final List<ResolveInfo> photoInfos = pm.queryIntentActivities(intentPhoto, PackageManager.MATCH_ALL);
for (ResolveInfo photoInfo : photoInfos) {
if(photoInfo.activityInfo.packageName.equals(ACTIVITY_NAME_PHOTOS)) {
Log.d(TAG,"mUseActivityPhoto TRUE");
mUseActivityPhoto = true;
break;
}
}
}
else if(info.activityInfo.packageName.equals(ACTIVITY_NAME_PLUS)) {
final List<ResolveInfo> photoInfos = pm.queryIntentActivities(intentPhoto, PackageManager.MATCH_ALL);
for (ResolveInfo photoInfo : photoInfos) {
if(photoInfo.activityInfo.packageName.equals(ACTIVITY_NAME_PLUS)) {
Log.d(TAG,"mUseActivityPlus TRUE");
mUseActivityPlus = true;
break;
}
}
}
}
}
public static void takeCameraAction(Activity context) {
if(DEBUG)
Log.d(TAG, "takeCameraAction");
if (ImageCrop.checkPermissions(context)) {
ImageCrop.doTakeCameraAction(context);
} else {
mLastAction = ImageCrop.PICK_FROM_CAMERA;
}
}
public static void takeAlbumAction(Activity context) {
if(DEBUG)
Log.d(TAG, "takeAlbumAction");
if(ImageCrop.checkPermissions(context)) {
ImageCrop.doTakeAlbumAction(context);
}
else {
mLastAction = ImageCrop.PICK_FROM_ALBUM;
}
}
private static void doTakeCameraAction(Activity context) {
if(DEBUG)
Log.d(TAG, "doTakeCameraAction");
final Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
final String url = CAMERA_TEMP_PREFIX + String.valueOf(System.currentTimeMillis()) + IMAGE_EXT;
final File file = new File(Environment.getExternalStorageDirectory(), url);
mTempImagePath = file.getAbsolutePath();
mImageCaptureUri = Uri.fromFile(file);
intent.putExtra(MediaStore.EXTRA_OUTPUT, mImageCaptureUri);
context.startActivityForResult(intent, PICK_FROM_CAMERA);
}
private static void doTakeAlbumAction(Activity context) {
if(DEBUG)
Log.d(TAG, "doTakeAlbumAction");
final Intent intent = new Intent(Intent.ACTION_PICK);
intent.setType(MediaStore.Images.Media.CONTENT_TYPE);
checkPackages(context, intent);
if(mUseActivityPhoto) {
if(DEBUG)
Log.d(TAG, "doTakeAlbumAction setPackage ACTIVITY_NAME_PHOTOS");
intent.setPackage(ACTIVITY_NAME_PHOTOS);
}
else if(mUseActivityPlus) {
if(DEBUG)
Log.d(TAG, "doTakeAlbumAction setPackage ACTIVITY_NAME_PLUS");
intent.setPackage(ACTIVITY_NAME_PLUS);
}
context.startActivityForResult(intent, ImageCrop.PICK_FROM_ALBUM);
}
private static void removeTempFile() {
// 캡쳐 파일 삭제
if(mImageCaptureUri != null) {
final String capturePath = mImageCaptureUri.getPath();
if(capturePath != null) {
Log.w(TAG, "removeTempFile capturePath=" + capturePath);
final File captureFile = new File(capturePath);
if(captureFile != null) {
if (captureFile.getAbsoluteFile().exists()) {
captureFile.delete();
}
}
}
}
if(mTempImagePath != null) {
Log.w(TAG, "removeTempFile mTempImagePath=" + mTempImagePath);
final File tempFile = new File(mTempImagePath);
if(tempFile != null) {
if(tempFile.getAbsoluteFile().exists()) {
tempFile.delete();
}
}
}
}
private static void removeDataFile(Intent data) {
if(data == null) {
Log.w(TAG, "removeDataFile data == null");
return;
}
if(data.getData() == null) {
Log.w(TAG, "removeDataFile data.getData() == null");
return;
}
final String dataPath = data.getData().getPath();
if(dataPath == null) {
Log.w(TAG, "removeDataFile dataPath == null");
return;
}
Log.w(TAG, "removeDataFile dataPath=" + dataPath);
final File dataFile = new File(dataPath);
if(dataFile == null) {
Log.w(TAG, "removeDataFile dataFile == null");
return;
}
if(dataFile.getAbsoluteFile().exists()) {
dataFile.delete();
}
}
private static File cropFileFromPhotoData(Activity context, Intent data) {
if(DEBUG)
Log.d(TAG, "cropFileFromPhotoData");
if(data.getData() == null) {
Log.e(TAG, "cropFileFromPhotoData data.getData() == null");
return null;
}
final String dataPath = data.getData().getPath();
if (dataPath == null) {
Log.e(TAG, "cropFileFromPhotoData dataPath == null");
return null;
}
File dataFile = null;
if(dataPath.startsWith("/external")) {
final Uri dataUri = Uri.parse("content://media"+dataPath);
final String dataFilePath = getRealPathFromURI(context, dataUri);
dataFile = new File(dataFilePath);
boolean exist = dataFile.exists();
long length = dataFile.length();
if(DEBUG)
Log.d(TAG, "cropFileFromPhotoData dataFilePath=" + dataFilePath + " exist="+exist + " length=" +length);
}
else {
dataFile = new File(dataPath);
boolean exist = dataFile.exists();
long length = dataFile.length();
if(DEBUG)
Log.d(TAG, "cropFileFromPhotoData dataPath=" + dataPath + " exist="+exist + " length=" +length);
}
return dataFile;
}
public static void pickFromCamera(Activity context, Intent data) {
if(DEBUG)
Log.d(TAG, "pickFromCamera => launchCropActivity");
if(mTempImagePath == null || mTempImagePath.isEmpty()) {
Log.e(TAG, "pickFromCamera mTempImagePath error");
return;
}
}
public static String getRealPathFromURI(Activity context, Uri contentUri) {
Cursor cursor = null;
final String[] proj = { MediaStore.Images.Media.DATA };
String ret = null;
try {
cursor = context.getContentResolver().query(contentUri, proj, null, null, null);
final int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
ret = cursor.getString(column_index);
}
catch(Exception e) {
Log.e(TAG, "getRealPathFromURI exception");
return null;
}
if (cursor != null) {
cursor.close();
}
return ret;
}
if(readEnable && writeEnable && cameraEnable) {
switch(mLastAction) {
case ImageCrop.PICK_FROM_CAMERA:
if(DEBUG)
Log.d(TAG, "doTakeCameraAction");
ImageCrop.doTakeCameraAction(context);
break;
case ImageCrop.PICK_FROM_ALBUM:
if(DEBUG)
Log.d(TAG, "doTakeAlbumAction");
ImageCrop.doTakeAlbumAction(context);
break;
}
}
}
}
I want to use this way to pick photos:
private void selectCover() {
Intent intent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(Intent.createChooser(intent, getText(R.string.label_select_img)), SELECT_COVER);
}
But i can't convert this to normal gallery. How to solve this? Thanks
You can use this, it will open only Gallery :
public void handleGallery(){
Intent photoPickerIntent = new Intent(Intent.ACTION_PICK);
photoPickerIntent.setType("image/*");
startActivityForResult(photoPickerIntent, REQUEST_CODE_GALLERY);
}
public void handleCamera(){
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
try {
intent.putExtra("return-data", true);
startActivityForResult(intent, REQUEST_CODE_TAKE_PICTURE);
} catch (Exception e) {
Log.d("error", "cannot take picture", e);
}
}
Then onActivityResult :
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode != RESULT_OK) {
return;
}
Bitmap bitmap;
switch (requestCode) {
case REQUEST_CODE_GALLERY:
try {
Uri uri = data.getData();
try {
bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), uri);
Bitmap bitmapScaled = Bitmap.createScaledBitmap(bitmap, 800, 800, true);
Drawable drawable=new BitmapDrawable(bitmapScaled);
mImage.setImageDrawable(drawable);
mImage.setVisibility(View.VISIBLE);
mImageString=HelperUtils.encodeTobase64(bitmap);
} catch (IOException e) {
Log.v("galeri", "hata var : "+e.getMessage());
}
} catch (Exception e) {
Log.v("kamera", "hata var : "+e.getMessage());
}
break;
case REQUEST_CODE_TAKE_PICTURE:
bitmap = (Bitmap) data.getExtras().get("data");
mImage.setImageBitmap(bitmap);
mImage.setVisibility(View.VISIBLE);
mImageString=HelperUtils.encodeTobase64(bitmap);
break;
}
super.onActivityResult(requestCode, resultCode, data);
}

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>

android dropbox authentication and upload in different activities

I am trying to upload a file from dropbox in another activity from where i autenticate to dropbox. I have this RegisterActivity.java where the user registers and then later when the registration is completed the webbrowser comes up and the user has to allow the dropbox authentication.
later in my app on another activity the user is going to upload a video to dropbox. the upload is made by ASyncTask and works well. The problem is now that i dont want to reauthenticate again. How do i fix that? Is it on the same session or do i start a new session? Now Iam trying to use the sam mDBApi form RegisterAcitivity but i think that is wrong. The keys are stored in the storeKeys() method and saves them in SharedPreferences.
Thank you very much in advance
Here is my RegisterActivity in pastebin which works. http://pastebin.com/K06JUWXv
Here is the activity that where i call my ASyncTask UploadFile:
public class ShowVideo extends Activity{
final static private String ACCOUNT_PREFS_NAME = "prefs";
final static private String ACCESS_KEY_NAME = "ACCESS_KEY";
final static private String ACCESS_SECRET_NAME = "ACCESS_SECRET";
private DropboxAPI<AndroidAuthSession> mDBApi = RegisterActivity.mDBApi;
private String[] storedKeys = getKeys();
UploadFile upload;
public static String path = "";
public static String fileName;
private VideoView ww;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); //Forces landscape orientation which is what the camera uses.
setContentView(R.layout.showvideo);
Button yesButton = (Button) findViewById(R.id.yesButton);
Button noButton = (Button) findViewById(R.id.NoButton);
Button dbButton = (Button) findViewById(R.id.dropboxButton);
dbButton.setOnClickListener(new OnClickListener(){
public void onClick(View v){
if(v.getId() == R.id.dropboxButton){
if (mDBApi.getSession().isLinked() == true){
Log.d("ShowVideo", "TRUE");
}
if (mDBApi.getSession().isLinked() == false){
Log.d("ShowVideo", "FALSE");
}
}
}
});
yesButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
if(v.getId() == R.id.yesButton){
UploadFile upload = new UploadFile(ShowVideo.this,mDBApi,path);
upload.execute();
}
}
});
noButton.setOnClickListener(new OnClickListener() {
public void onClick(View w) {
File file = new File(path);
boolean deleted = false;
deleted = file.delete();
Log.e("TAG", Boolean.toString(deleted));
Intent intent = new Intent(ShowVideo.this, CaptureVideo.class);
startActivity(intent);
}
});
ww = (VideoView) findViewById(R.id.satisfiedVideoView);
path = getRealPathFromURI(CaptureVideo.uriVideo);
fileName = getFileNameFromUrl(path);
//AndroidAuthSession session = new AndroidAuthSession(new AppKeyPair(ret[0], ret[1]), AccessType.APP_FOLDER);
//mDBApi = new DropboxAPI<AndroidAuthSession>(session);
}
private void playVideo(){
ww.setVideoURI(CaptureVideo.uriVideo);
ww.setMediaController(new MediaController(this));
ww.start();
ww.requestFocus();
}
public static String getFileNameFromUrl(String path) {
String[] pathArray = path.split("/");
return pathArray[pathArray.length - 1];
}
public String getRealPathFromURI(Uri contentUri) {
String[] proj = { MediaStore.Images.Media.DATA };
Cursor cursor = managedQuery(contentUri, proj, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
/**DROPBOX-METHOD------------------------------------------*/
private String[] getKeys() {
SharedPreferences prefs = getSharedPreferences(ACCOUNT_PREFS_NAME, 0);
String key = prefs.getString(ACCESS_KEY_NAME, null);
String secret = prefs.getString(ACCESS_SECRET_NAME, null);
if (key != null && secret != null) {
String[] ret = new String[2];
ret[0] = key;
ret[1] = secret;
return ret;
} else {
return null;
}
}
}
Here is my ASyncTask if you would take a look at that. Shouldn't be needed.
public class UploadFile extends AsyncTask<Void, Long, Boolean> {
DropboxAPI<AndroidAuthSession> dDBApi;
Context dContext;
private String SAVE_PATH;
public UploadFile(Context context,DropboxAPI<AndroidAuthSession> mDBApi, String path) {
dContext = context.getApplicationContext();
dDBApi = mDBApi;
SAVE_PATH = path;
}
#Override
protected Boolean doInBackground(Void... params) {
FileInputStream inputStream = null;
try {
File file = new File(SAVE_PATH);
inputStream = new FileInputStream(file);
Entry newEntry = dDBApi.putFileOverwrite("/GAMES/GAME_BETWEEN_USER_A_USER_B/" + "PresentVideo.mp4", inputStream, file.length(), null);
}
catch (DropboxException e) {
Log.e("DbExampleLog", "Something went wrong while uploading.");
} catch (FileNotFoundException e) {
Log.e("DbExampleLog", "File not found.");
} catch (IOException e) {
Log.e("DbExampleLog", "Another Exception:" + e.getMessage());
e.printStackTrace();
} catch (Exception e) {
Log.e("DbExampleLog", "Another Exception:" + e.getMessage());
e.printStackTrace();
}
finally {
if (inputStream != null) {
try {
inputStream.close();
}
catch (IOException e) {
}
}
}
return null;
}
}

Categories

Resources