I'm using non activity class to populate Framelayout. I want to show the progress bar when the Framelayout is loading and hide once it is Framelayout
loading is complete.
I have experience with Activity Class but I was unable to show or hide progress bar with non -activity class
I'm calling this method first when app is started
private static void getMovies(final Activity activity, final String type, final MoviesCallback callback)
Here is my Class Code
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";
private static 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);
progressDialog = new ProgressDialog(activity);
progressDialog.setMax(100);
progressDialog.setMessage("Its loading....");
progressDialog.setTitle("ProgressDialog bar example");
progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
progressDialog.show();
}
});
}
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);
progressDialog.dismiss();
}
});
} 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 "";
}
}
}
How can I do this.
Any help is appreciated and Thankss in advance.
and my log cat error is
09-05 20:10:57.639 2183-2891/? E/GpsXtraDownloader: No XTRA servers were specified in the GPS configuration
09-05 20:10:58.319 9101-9101/com.nepalpolice.cinemaghar E/dalvikvm: Could not find class 'android.graphics.drawable.RippleDrawable', referenced from method android.support.v7.widget.AppCompatImageHelper.hasOverlappingRendering
09-05 20:10:58.359 9101-9101/com.nepalpolice.cinemaghar E/Iconics: Wrong icon name: 2131165281
09-05 20:10:58.600 9101-9101/com.nepalpolice.cinemaghar E/RecyclerView: No adapter attached; skipping layout
No adapter attached; skipping layout
No adapter attached; skipping layout
09-05 20:10:58.790 9101-9101/com.nepalpolice.cinemaghar E/RecyclerView: No adapter attached; skipping layout
No adapter attached; skipping layout
No adapter attached; skipping layout
09-05 20:11:06.758 9101-9101/com.nepalpolice.cinemaghar E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.nepalpolice.cinemaghar, PID: 9101
java.lang.NullPointerException
at com.nepalpolice.cinemaghar.util.MoviesUtil$2.run(MoviesUtil.java:138)
at android.os.Handler.handleCallback(Handler.java:733)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5018)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
at dalvik.system.NativeStart.main(Native Method)
Solution:
Instead of:
ProgressBar progressBar;
write:
ProgressDialog progressDialog;
Modify:
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);
progressDialog = new ProgressDialog(activity);
progressDialog.setMax(100);
progressDialog.setMessage("Its loading....");
progressDialog.setTitle("ProgressDialog bar example");
progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
progressDialog.show();
}
});
}
then in here, add:
final List<Movie> movies = toMovies(cursor);
cursor.close();
activity.runOnUiThread(new Runnable() {
#Override
public void run() {
callback.success(movies);
.........(Write Here)
}
});
this:
progressDialog.dismiss();
Let me know if it works.
Related
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);
}
}
Can any one help me whats wrong in my code
unable to save ArrayList document value in shared Preference
getting null value in Debug of Array List Document
please help me
Thanks in advance
here is my JSON response
{
"errCode": 0,
"message": "Success",
"responseDestinationDocument": [
{
"name": "United Arab Emirates",
"document": [
{
"name": "Passport Front",
"id": "2",
"notes": [
{
"name": "Upload colored passport copies."
},
{
"name": "Passport should be valid 6 months from the date of entry in Sri Lanka."
},
{
"name": "DDDDDDD"
}
]
},
{
"name": "Passport Back",
"id": "3",
"notes": [
{
"name": "Upload colored passport copy."
}
]
},
{
"name": "Photograph",
"id": "4",
"notes": [
{
"name": "Upload photograph with white background"
}
]
}
]
}
]
}
I want to save ArrayList document value in shared Preference
Here is activity code
public class UploadDocumentsActivity extends AppCompatActivity {
private MyCustomAdapter myCustomAdapter;
protected ViewDialog viewDialog;
String destination_id, start_date, end_date, no_of_travellers, destination_name, package_id, radioSexButton, booking_id, count_index;
private List<ResponseBookingDocument> responseBookingDocumentArrayList;
private List<Document> document1ArrayList;
Document document1;
private RecyclerView recyclerView_Identity;
private static final int SELECT_PICTURE = 100;
private static final int STORAGE_PERMISSION_CODE = 123;
final Handler handler = new Handler();
final int delay = 1000; //milliseconds
private ImageView imageView1;
String selectedImagePath;
private Uri filePath_1;
private boolean isOnTag = false;
Bitmap bitmap;
preivate ArrayList<String> nameList = new ArrayList<>();
preivate ArrayList<String> idList = new ArrayList<>();
TextView continueTextView;
private Runnable mToast = new Runnable() {
#Override
public void run() {
// documentRequiredCall();
handler.postDelayed(this, 1000);
}
};
ResponseBookInfo responseBookInfo;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_upload_documents);
viewDialog = new ViewDialog(this);
viewDialog.setCancelable(false);
// Log.e("document1", document1.getId() + "");
try {
document1 = PrefUtils.getDocId(UploadDocumentsActivity.this);
Log.e("document1", document1.getId() + "");
} catch (Exception e) {
e.printStackTrace();
}
Intent i = getIntent();
destination_id = i.getStringExtra("destination_id");
package_id = i.getStringExtra("package_id");
radioSexButton = i.getStringExtra("radioSexButton");
booking_id = i.getStringExtra("booking_id");
count_index = i.getStringExtra("count_index");
Log.e("BookING", booking_id + "");
destination_name = i.getStringExtra("destination_name");
start_date = i.getStringExtra("start_date");
end_date = i.getStringExtra("end_date");
no_of_travellers = i.getStringExtra("no_of_travellers");
recyclerView_Identity = findViewById(R.id.recyclerView_Identity);
continueTextView = findViewById(R.id.continueTextView);
LinearLayoutManager layoutManager = new LinearLayoutManager(UploadDocumentsActivity.this);
layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
recyclerView_Identity.setLayoutManager(layoutManager);
recyclerView_Identity.setHasFixedSize(true);
continueTextView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(UploadDocumentsActivity.this, ApplicationFormActivity.class);
i.putExtra("booking_id", booking_id);
i.putExtra("count_index", count_index);
i.putExtra("start_date", start_date);
i.putExtra("end_date", end_date);
startActivity(i);
}
});
documentRequiredCall();
//
Log.e("Values", destination_id + " " + package_id + " " + end_date + " " + no_of_travellers + " " + count_index + "");
}
public void documentRequiredCall() {
Call<DocumentFetchModel> call = RetrofitClient
.getInstance().getApi().documentFetchModel(booking_id, count_index);
showProgressDialog();
call.enqueue(new Callback<DocumentFetchModel>() {
#Override
public void onResponse(Call<DocumentFetchModel> call, retrofit2.Response<DocumentFetchModel> response) {
final DocumentFetchModel documentFetchModel = response.body();
hideProgressDialog();
PrefUtils.setDocId(documentFetchModel.getResponseBookingDocument().get(0).getDocument(), UploadDocumentsActivity.this);
int size = documentFetchModel.getResponseBookingDocument().get(0).getDocument().size();
for (int i = 0; i < size; i++) {
nameList.add(documentFetchModel.getResponseBookingDocument().get(0).getDocument().get(i).getName());
idList.add(documentFetchModel.getResponseBookingDocument().get(0).getDocument().get(i).getId());
}
//here is app preference class saving the values
AppPreference.setNameList(this, nameList);
AppPreference.setIdList(this, idLIst);
if (documentFetchModel.getErrCode().booleanValue() == true) {
responseBookingDocumentArrayList = new ArrayList<ResponseBookingDocument>();
try {
Log.e("Booking_Document", new Gson().toJson(response.body()));
document1ArrayList = documentFetchModel.getResponseBookingDocument().get(0).getDocument();
myCustomAdapter = new MyCustomAdapter(document1ArrayList);
recyclerView_Identity.setAdapter(myCustomAdapter);
myCustomAdapter.notifyDataSetChanged();
} catch (Exception e) {
e.printStackTrace();
}
} else {
Toast.makeText(UploadDocumentsActivity.this, documentFetchModel.getMessage() + "", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onFailure(Call<DocumentFetchModel> call, Throwable t) {
hideProgressDialog();
Toast.makeText(UploadDocumentsActivity.this, t.getMessage() + "", Toast.LENGTH_LONG).show();
Log.e("Error", t.getMessage() + "");
}
});
}
protected void hideProgressDialog() {
viewDialog.dismiss();
}
protected void showProgressDialog() {
viewDialog.show();
}
protected void showProgressDialog(String message) {
showProgressDialog();
}
public class MyCustomAdapter extends RecyclerView.Adapter<MyCustomAdapter.MyViewHolder> {
private List<Document> moviesList;
public class MyViewHolder extends RecyclerView.ViewHolder {
public TextView textTitle;
public ImageView imageUpload, imageFetch;
private List<Note> noteArrayList;
private MyCustomAdapter2 myCustomAdapter2;
private RecyclerView recyclerView_Identity_Bullets;
public MyViewHolder(View view) {
super(view);
textTitle = view.findViewById(R.id.textTitle);
imageUpload = view.findViewById(R.id.imageUpload);
imageFetch = view.findViewById(R.id.imageFetch);
recyclerView_Identity_Bullets = view.findViewById(R.id.recyclerView_Identity_Bullets);
LinearLayoutManager layoutManager2 = new LinearLayoutManager(UploadDocumentsActivity.this);
layoutManager2.setOrientation(LinearLayoutManager.VERTICAL);
recyclerView_Identity_Bullets.setLayoutManager(layoutManager2);
recyclerView_Identity_Bullets.setHasFixedSize(true);
}
}
public MyCustomAdapter(List<Document> moviesList) {
this.moviesList = moviesList;
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.item_upload_document, parent, false);
return new MyCustomAdapter.MyViewHolder(itemView);
}
public void clear() {
int size = this.moviesList.size();
if (size > 0) {
for (int i = 0; i < size; i++) {
this.moviesList.remove(0);
}
this.notifyItemRangeRemoved(0, size);
}
}
#Override
public void onBindViewHolder(final MyViewHolder holder, final int position) {
final Document datum = moviesList.get(position);
holder.textTitle.setText(datum.getName() + "");
holder.noteArrayList = datum.getNotes();
holder.myCustomAdapter2 = new MyCustomAdapter2(holder.noteArrayList);
holder.recyclerView_Identity_Bullets.setAdapter(holder.myCustomAdapter2);
if (datum.getImageName().equals("")) {
holder.imageFetch.setVisibility(View.GONE);
holder.imageUpload.setVisibility(View.VISIBLE);
holder.imageUpload.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(UploadDocumentsActivity.this, datum.getId(), Toast.LENGTH_SHORT).show();
}
});
} else {
holder.imageUpload.setVisibility(View.GONE);
holder.imageFetch.setVisibility(View.VISIBLE);
Picasso.with(UploadDocumentsActivity.this).load(datum.getImageName() + "").into(holder.imageFetch);
}
}
#Override
public int getItemCount() {
return moviesList.size();
}
}
public class MyCustomAdapter2 extends RecyclerView.Adapter<MyCustomAdapter2.MyViewHolder> {
private List<Note> moviesList;
public class MyViewHolder extends RecyclerView.ViewHolder {
public TextView textBullet;
public MyViewHolder(View view) {
super(view);
textBullet = view.findViewById(R.id.textBullet);
}
}
public MyCustomAdapter2(List<Note> moviesList) {
this.moviesList = moviesList;
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.item_upload_bullets_and_image, parent, false);
return new MyViewHolder(itemView);
}
public void clear() {
int size = this.moviesList.size();
if (size > 0) {
for (int i = 0; i < size; i++) {
this.moviesList.remove(0);
}
this.notifyItemRangeRemoved(0, size);
}
}
#Override
public void onBindViewHolder(MyViewHolder holder, final int position) {
final Note datum = moviesList.get(position);
holder.textBullet.setText(" \u25CF " + datum.getName() + "");
Log.e("textBullet", datum.getName() + "");
}
#Override
public int getItemCount() {
return moviesList.size();
}
}
#Override
public void onStart() {
super.onStart();
mToast.run();
}
#Override
public void onStop() {
super.onStop();
handler.removeCallbacks(mToast);
}
}
Here is Model Class
public class DocumentFetchModel {
#SerializedName("errCode")
#Expose
private Boolean errCode;
#SerializedName("message")
#Expose
private String message;
#SerializedName("responseBookingDocument")
#Expose
private List<ResponseBookingDocument> responseBookingDocument = null;
public Boolean getErrCode() {
return errCode;
}
public void setErrCode(Boolean errCode) {
this.errCode = errCode;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public List<ResponseBookingDocument> getResponseBookingDocument() {
return responseBookingDocument;
}
public void setResponseBookingDocument(List<ResponseBookingDocument> responseBookingDocument) {
this.responseBookingDocument = responseBookingDocument;
}
}
public class ResponseBookingDocument {
#SerializedName("name")
#Expose
private String name;
#SerializedName("document")
#Expose
private List<Document> document = null;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public List<Document> getDocument() {
return document;
}
public void setDocument(List<Document> document) {
this.document = document;
}
}
public class DocumentFetchModel {
#SerializedName("errCode")
#Expose
private Boolean errCode;
#SerializedName("message")
#Expose
private String message;
#SerializedName("responseBookingDocument")
#Expose
private List<ResponseBookingDocument> responseBookingDocument = null;
public Boolean getErrCode() {
return errCode;
}
public void setErrCode(Boolean errCode) {
this.errCode = errCode;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public List<ResponseBookingDocument> getResponseBookingDocument() {
return responseBookingDocument;
}
public void setResponseBookingDocument(List<ResponseBookingDocument> responseBookingDocument) {
this.responseBookingDocument = responseBookingDocument;
}
}
Here is ComplexPreference
public class ComplexPreferences {
private static ComplexPreferences complexPreferences;
private Context context;
private SharedPreferences preferences;
private SharedPreferences.Editor editor;
private static Gson GSON = new Gson();
Type typeOfObject = new TypeToken<Object>() {
}.getType();
private ComplexPreferences(Context context, String namePreferences, int mode) {
this.context = context;
if (namePreferences == null || namePreferences.equals("")) {
namePreferences = "complex_preferences";
}
preferences = context.getSharedPreferences(namePreferences, mode);
editor = preferences.edit();
}
public static ComplexPreferences getComplexPreferences(Context context,
String namePreferences, int mode) {
// if (complexPreferences == null) {
complexPreferences = new ComplexPreferences(context,
namePreferences, mode);
// }
return complexPreferences;
}
public void putObject(String key, Object object) {
if(object == null){
throw new IllegalArgumentException("object is null");
}
if(key.equals("") || key == null){
throw new IllegalArgumentException("key is empty or null");
}
editor.putString(key, GSON.toJson(object));
}
public void commit() {
editor.commit();
}
public void clearObject() {
editor.clear();
}
public <T> T getObject(String key, Class<T> a) {
String gson = preferences.getString(key, null);
if (gson == null) {
return null;
} else {
try{
return GSON.fromJson(gson, a);
} catch (Exception e) {
throw new IllegalArgumentException("Object storaged with key " + key + " is instanceof other class");
}
}
}
}
Here is PrefUtils Class
public class PrefUtils {
public static DocumentFetchModel getDoc(Context ctx) {
ComplexPreferences complexPreferences = ComplexPreferences.getComplexPreferences(ctx, "get_doc", 0);
DocumentFetchModel currentUser = complexPreferences.getObject("docs", DocumentFetchModel.class);
return currentUser;
}
public static void setDoc(DocumentFetchModel currentUser, Context ctx) {
ComplexPreferences complexPreferences = ComplexPreferences.getComplexPreferences(ctx, "get_doc", 0);
complexPreferences.putObject("docs", currentUser);
complexPreferences.commit();
}
}
you can save list in sharedpreference like this:-
public class AppPreferences {
private static SharedPreferences mPrefs;
private static SharedPreferences.Editor mPrefsEditor;
public static Set<String> getName(Context ctx) {
mPrefs = PreferenceManager.getDefaultSharedPreferences(ctx);
return mPrefs.getStringSet("nameList", null);
}
public static void setName(Context ctx, ArrayList<String> value) {
mPrefs = PreferenceManager.getDefaultSharedPreferences(ctx);
mPrefsEditor = mPrefs.edit();
Set<String> set = new HashSet<>();
set.addAll(value);
mPrefsEditor.putStringSet("nameList", set);
mPrefsEditor.commit();
}
public static void clearNameList(Context ctx) {
mPrefs = PreferenceManager.getDefaultSharedPreferences(ctx);
mPrefsEditor = mPrefs.edit();
Set<String> set = new HashSet<>();
mPrefsEditor.putStringSet("nameList", set);
mPrefsEditor.commit();
}
}
to set list :-
setCamEval(activity, list);
to get list :-
getCamEval(this);
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
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);
I have a splash screen using AsyncTask, it will download some data from database and store the data in ArrayList. This ArrayList will be used for RecyclerView in fragments of MainActivity.class.
The problem is when I run the app from Android Studio to my phone, everything works perfectly. But, when I destroy the app and run it manually from my phone it will display blank white screen and then it will crash. And if I run once again after it crashed, the app will work. So, this app will always work only if I run it from Android Studio or after it crashed.
The error says that it is caused by the empty list. If I'm not mistaken, I think the AsyncTask doesn't seem to work properly after the activity is destroyed. But I don't know how to fix it. Please help me to solve this problem.
SplashScreen.java
public class SplashScreenActivity extends AppCompatActivity {
public static Event event;
private static List<Feed> feedList;
private static List<Event> eventList;
private static List<Event> todayList;
private static List<Event> upcomingList;
private static List<Partner> partnerList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_splashscreen);
Time today = new Time(Time.getCurrentTimezone());
today.setToNow();
Config.TODAY_DATE = String.valueOf(today.monthDay) + "-" + String.valueOf(today.month) + "-" + String.valueOf(today.year);
new DownloadData().execute("");
}
class DownloadData extends AsyncTask<String, Integer, String>
{
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
startActivity(new Intent(getBaseContext(), WelcomeActivity.class));
finish();
}
#Override
protected String doInBackground(String... params) {
RequestHandler rh = new RequestHandler();
String JSON_STRING = rh.sendGetRequest(Config.URL_GET_ALL_DATA);
JSONObject jsonObject;
eventList = new ArrayList<>();
todayList = new ArrayList<>();
upcomingList = new ArrayList<>();
partnerList = new ArrayList<>();
feedList = new ArrayList<>();
try {
jsonObject = new JSONObject(JSON_STRING);
JSONArray getEvent = jsonObject.getJSONArray(Config.TAG_JSON_EVENT);
for (int i = 0; i < getEvent.length(); i++) {
int id = getEvent.getJSONObject(i).getInt(Config.TAG_ID);
int eoId = getEvent.getJSONObject(i).getInt(Config.TAG_EO_ID);
String eoName = getEvent.getJSONObject(i).getString(Config.TAG_EO_NAME);
String title = getEvent.getJSONObject(i).getString(Config.TAG_TITLE);
String day = getEvent.getJSONObject(i).getString(Config.TAG_DAY);
String date = getEvent.getJSONObject(i).getString(Config.TAG_DATE);
int price = getEvent.getJSONObject(i).getInt(Config.TAG_PRICE);
event = new Event(id, eoId, eoName, title, day, date, price);
eventList.add(event);
if(Config.TODAY_DATE.equals(event.getDate())){
todayList.add(event);
} else {
upcomingList.add(event);
}
}
JSONArray getPartner = jsonObject.getJSONArray(Config.TAG_JSON_PARTNER);
for (int i = 0; i < getPartner.length(); i++) {
int pId = getPartner.getJSONObject(i).getInt(Config.TAG_ID);
String pName = getPartner.getJSONObject(i).getString(Config.TAG_NAME);
String pEmail = getPartner.getJSONObject(i).getString(Config.TAG_EMAIL);
String pPhone = getPartner.getJSONObject(i).getString(Config.TAG_PHONE);
String pPhoto = getPartner.getJSONObject(i).getString(Config.TAG_PHOTO_URL);
Partner partner = new Partner(pId, pName, pEmail, pPhone, pPhoto);
partnerList.add(partner);
}
JSONArray getArticle = jsonObject.getJSONArray(Config.TAG_JSON_ARTICLE);
for (int i = 0; i < getArticle.length(); i++) {
int feedId = getArticle.getJSONObject(i).getInt(Config.TAG_ID);
String feedAuthor = getArticle.getJSONObject(i).getString(Config.TAG_FEED_AUTHOR);
String feedTitle = getArticle.getJSONObject(i).getString(Config.TAG_FEED_TITLE);
String feedContent = getArticle.getJSONObject(i).getString(Config.TAG_FEED_CONTENT);
String feedDate = getArticle.getJSONObject(i).getString(Config.TAG_FEED_DATE);
String feedThumbnail = getArticle.getJSONObject(i).getString(Config.TAG_FEED_THUMBNAIL);
Feed feed = new Feed(feedId, feedAuthor, feedTitle, feedContent, feedDate, feedThumbnail);
feedList.add(feed);
}
} catch (JSONException e) {
e.printStackTrace();
}
return JSON_STRING;
}
}
public static List<Feed> getFeedList(){ return feedList;}
public static List<Event> getEventList() {return eventList;}
public static List<Event> getTodayList() { return todayList;}
public static List<Event> getUpcomingList() { return upcomingList;}
public static List<Partner> getPartnerList() {return partnerList;}
}
DiscoverFragment.java
public class DiscoverFragment extends Fragment implements ViewPager.OnPageChangeListener, View.OnClickListener {
protected View view;
private LinearLayout pager_indicator;
private int dotsCount;
private ImageView[] dots;
private List<Feed> feedList;
private List<Event> eventList;
private List<Partner> partnerList;
public DiscoverFragment() {}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_discover, container, false);
RecyclerView recyclerViewEvent = (RecyclerView) view.findViewById(R.id.discover_event_recycler_view);
RecyclerView recyclerViewPartner = (RecyclerView) view.findViewById(R.id.discover_partner_recycler_view);
ClickableViewPager intro_images = (ClickableViewPager) view.findViewById(R.id.pager_introduction);
pager_indicator = (LinearLayout) view.findViewById(R.id.viewPagerCountDots);
eventList = SplashScreenActivity.getEventList();
partnerList = SplashScreenActivity.getPartnerList();
feedList = SplashScreenActivity.getFeedList();
EventAdapter eventAdapter = new EventAdapter(getContext(), eventList);
DiscoverPartnerAdapter discoverPartnerAdapter = new DiscoverPartnerAdapter(getContext(), partnerList);
DiscoverFeedAdapter mAdapter = new DiscoverFeedAdapter(getContext(), feedList);
final LinearLayoutManager layoutManagerEvent = new LinearLayoutManager(getContext());
final LinearLayoutManager layoutManagerPartner = new LinearLayoutManager(getContext());
layoutManagerEvent.setOrientation(LinearLayoutManager.HORIZONTAL);
layoutManagerPartner.setOrientation(LinearLayoutManager.HORIZONTAL);
addBottomDots(0);
intro_images.setAdapter(mAdapter);
intro_images.setCurrentItem(0);
intro_images.addOnPageChangeListener(this);
intro_images.setOnItemClickListener(new ClickableViewPager.OnItemClickListener() {
#Override
public void onItemClick(int position) {
Config.FEED_ID = position;
startActivity(new Intent(getContext(), ArticleActivity.class));
}
});
return view;
}
private void addBottomDots(int currentPage) {
dots = new ImageView[feedList.size()]; //the problem
pager_indicator.removeAllViews();
for (int i = 0; i < dots.length; i++) {
dots[i] = new ImageView(getContext());
dots[i].setImageDrawable(getResources().getDrawable(R.drawable.nonselecteditem_dot));
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.WRAP_CONTENT,
LinearLayout.LayoutParams.WRAP_CONTENT
);
params.setMargins(4, 0, 4, 0);
pager_indicator.addView(dots[i], params);
}
if (dots.length > 0)
dots[currentPage].setImageDrawable(getResources().getDrawable(R.drawable.selecteditem_dot));
}
#Override
public void onClick(View v) {
switch (v.getId()) {
}
}
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
addBottomDots(position);
for (int i = 0; i < dotsCount; i++) {
dots[i].setImageDrawable(getResources().getDrawable(R.drawable.nonselecteditem_dot));
}
dots[position].setImageDrawable(getResources().getDrawable(R.drawable.selecteditem_dot));
}
}
LogCat
01-29 00:40:57.565 32535-32535/com.irmaelita.esodiaapp E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.irmaelita.esodiaapp, PID: 32535
java.lang.NullPointerException: Attempt to invoke interface method 'int java.util.List.size()' on a null object reference
at com.irmaelita.esodiaapp.fragment.DiscoverFragment.addBottomDots(DiscoverFragment.java:181)
at com.irmaelita.esodiaapp.fragment.DiscoverFragment.onCreateView(DiscoverFragment.java:158)
feedList is null. You create feedList instance when DownloadData task is executed. But you call feedList.size() in addBottomDots when fragment view should be created. So, most probably addBottomDots is called before DownloadData task is executed. You need to fix it.
The feedlist in your discover fragment is going empty while initializing. Please set a null check before doing so.It not about running from android studio.If I have understood it correctly you are trying to access a list from splasScreen activity after finishing it. ie in post execute you finish the current activity and the fragment is in main activity,so the list is going null.So if this is the case (and please correct me if not) then either download the data somewhere centrally or best way send it to main activity with intent and use it there. Also when running from android studio kill the app manually and run it again,while the phone is connected and see if it crashes in current scenario.
Send your data from doInBackground to MainActivity with sendBroadcast
Add broadcast method in DownloadData class
private void broadcast(SplashParcel parcel) {
Intent i = new Intent("splash_parcel");
i.putExtra("values", parcel);
sendBroadcast(i);
}
#Override
protected String doInBackground(String... params) {
// your code
// ..
try {
// your code
// ..
// send splashParcel to MainActivity
SplashParcel splashParcel = new SplashParcel(feedList, eventList, todayList, upcomingList, partnerList);
broadcast (splashParcel);
} catch (JSONException e) {
e.printStackTrace();
}
return JSON_STRING;
}
Add new class SplashParcel.java
public class SplashParcel implements Parcelable {
public static final Creator<SplashParcel> CREATOR = new Creator<SplashParcel>() {
#Override
public SplashParcel createFromParcel(Parcel in) {
return new SplashParcel(in);
}
#Override
public SplashParcel[] newArray(int size) {
return new SplashParcel[size];
}
};
private static List<Feed> _feedList;
private static List<Event> _eventList;
private static List<Event> _todayList;
private static List<Event> _upcomingList;
private static List<Partner> _partnerList;
protected SplashParcel(Parcel in) {
_feedList = new ArrayList<Feed>();
in.readList(_feedList, null);
_eventList = new ArrayList<Event>();
in.readList(_eventList, null);
_todayList = new ArrayList<Event>();
in.readList(_todayList, null);
_upcomingList = new ArrayList<Event>();
in.readList(_upcomingList, null);
_partnerList = new ArrayList<Partner>();
in.readList(_partnerList, null);
}
public SplashParcel(List<Feed> feedList, List<Event> eventList, List<Event> todayList, List<Event> upcomingList, List<Partner> partnerList) {
_feedList = feedList;
_eventList = eventList;
_todayList = todayList;
_upcomingList = upcomingList;
_partnerList = partnerList;
}
public SplashParcel() {
}
public List<Feed> getFeedList() {
return _feedList;
}
public void setFeedList(List<Feed> feedList) {
_feedList = feedList;
}
public List<Event> getEventList() {
return _eventList;
}
public void setEventList(List<Event> eventList) {
_eventList = eventList;
}
public List<Event> getTodayList() {
return _todayList;
}
public void setTodayList(List<Event> todayList) {
_todayList = todayList;
}
public List<Event> getUpcomingList() {
return _upcomingList;
}
public void setUpcomingList(List<Event> upcomingList) {
_upcomingList = upcomingList;
}
public List<Partner> getPartnerList() {
return _partnerList;
}
public void setPartnerList(List<Partner> partnerList) {
_partnerList = partnerList;
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel parcel, int i) {
parcel.writeList(_feedList);
parcel.writeList(_eventList);
parcel.writeList(_todayList);
parcel.writeList(_upcomingList);
parcel.writeList(_partnerList);
}
}
MainActivity.java
// member variable
private BroadcastReceiver _splashReceiver;
private Bundle _bundle = new Bundle();
#Override
protected void onResume() {
super.onResume();
splashReceiver();
}
// receive splashParcel from SplashScreenActivity
private void splashReceiver() {
if (_splashReceiver == null) {
_splashReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
SplashParcel splashParcel = intent.getParcelableExtra("values");
if (splashParcel != null) {
// save splashParcel into _budle
_bundle.putParcelable("splash_parcel", splashParcel);
}
}
};
registerReceiver(_splashReceiver, new IntentFilter("splash_parcel"));
}
}
//Send _bundle to DiscoverFragment
private void showDiscoverFragment(){
if(_bundle != null) {
// create instance of discoverFragment with passing _bundle as arguments
DiscoverFragment discoverFragment = new DiscoverFragment();
discoverFragment.setArguments(_bundle);
// replace activity_main.xml with discoverFragment
getSupportFragmentManager().beginTransaction().replace(R.id.main_container, discoverFragment).addBackStack(null).commit();
}
}
In onCreateView of DiscoverFragment:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
SplashParcel splashParcel = getArguments().getParcelable("splash_parcel");
if(splashParcel != null) {
// your splashParcel ready in here
List<Feed> feedList = splashParcel.getFeedList()
List<Event> eventList = splashParcel.getEventList()
List<Event> todayList = splashParcel.getTodayList();
List<Event> upcommingList = splashParcel.getUpcomingList();
List<Partner> partnerList = splashParcel.getPartnerList();
}
}