I am using floating action button for navigation from one activity to another but when i am clicking then app is crashing, there is no problem in floating action button, problem is in another activity where its been navigated. And its been navigated to uploadPost class.
public class uploadPost extends Fragment implements SelectPhotoDialog.OnPhotoSelectedListener {
private static final String TAG = "uploadPost";
#Override
public void getImagePath(Uri imagePath) {
Log.d(TAG, "getImagePath: setting the image to imageview");
UniversalImageLoader.setImage(imagePath.toString(), mPostImage);
//assign to global variable
mSelectedBitmap = null;
mSelectedUri = imagePath;
}
#Override
public void getImageBitmap(Bitmap bitmap) {
Log.d(TAG, "getImageBitmap: setting the image to imageview");
mPostImage.setImageBitmap(bitmap);
//assign to a global variable
mSelectedUri = null;
mSelectedBitmap = bitmap;
}
//widgets
private ImageView mPostImage;
private EditText mTitle, mDescription, mPrice, mCountry, mStateProvince, mCity, mContactEmail,mCollege;
private Button mPost;
private ProgressBar mProgressBar;
//vars
private Bitmap mSelectedBitmap;
private Uri mSelectedUri;
private byte[] mUploadBytes;
private double mProgress = 0;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.activity_upload_post, container, false);
mPostImage = view.findViewById(R.id.post_image);
mTitle = view.findViewById(R.id.input_title);
mDescription = view.findViewById(R.id.input_description);
mPrice = view.findViewById(R.id.input_price);
mCountry = view.findViewById(R.id.input_country);
mStateProvince = view.findViewById(R.id.input_state_province);
mCity = view.findViewById(R.id.input_city);
mContactEmail = view.findViewById(R.id.input_email);
mCollege = view.findViewById(R.id.input_clg);
mPost = view.findViewById(R.id.btn_post);
mProgressBar = (ProgressBar) view.findViewById(R.id.progressBar);
mCountry.setText("India");
mStateProvince.setText("Maharashtra");
mCity.setText("Pune");
getActivity().getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);
init();
return view;
}
private void init(){
mPostImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d(TAG, "onClick: opening dialog to choose new photo");
SelectPhotoDialog dialog = new SelectPhotoDialog();
dialog.show(getFragmentManager(), getString(R.string.dialog_select_photo));
dialog.setTargetFragment(uploadPost.this, 1);
}
});
mPost.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d(TAG, "onClick: attempting to post...");
if(!isEmpty(mTitle.getText().toString())
&& !isEmpty(mDescription.getText().toString())
&& !isEmpty(mPrice.getText().toString())
&& !isEmpty(mCountry.getText().toString())
&& !isEmpty(mStateProvince.getText().toString())
&& !isEmpty(mCity.getText().toString())
&& !isEmpty(mContactEmail.getText().toString())){
//we have a bitmap and no Uri
if(mSelectedBitmap != null && mSelectedUri == null){
uploadNewPhoto(mSelectedBitmap);
}
//we have no bitmap and a uri
else if(mSelectedBitmap == null && mSelectedUri != null){
uploadNewPhoto(mSelectedUri);
}
}else{
Toast.makeText(getActivity(), "You must fill out all the fields", Toast.LENGTH_SHORT).show();
}
}
});
}
private void uploadNewPhoto(Bitmap bitmap){
Log.d(TAG, "uploadNewPhoto: uploading a new image bitmap to storage");
BackgroundImageResize resize = new BackgroundImageResize(bitmap);
Uri uri = null;
resize.execute(uri);
}
private void uploadNewPhoto(Uri imagePath){
Log.d(TAG, "uploadNewPhoto: uploading a new image uri to storage.");
BackgroundImageResize resize = new BackgroundImageResize(null);
resize.execute(imagePath);
}
public class BackgroundImageResize extends AsyncTask<Uri, Integer, byte[]>{
Bitmap mBitmap;
public BackgroundImageResize(Bitmap bitmap) {
if(bitmap != null){
this.mBitmap = bitmap;
}
}
#Override
protected void onPreExecute() {
super.onPreExecute();
Toast.makeText(getActivity(), "compressing image", Toast.LENGTH_SHORT).show();
showProgressBar();
}
#Override
protected byte[] doInBackground(Uri... params) {
Log.d(TAG, "doInBackground: started.");
if(mBitmap == null){
try{
RotateBitmap rotateBitmap = new RotateBitmap();
mBitmap = rotateBitmap.HandleSamplingAndRotationBitmap(getActivity(), params[0]);
}catch (IOException e){
Log.e(TAG, "doInBackground: IOException: " + e.getMessage());
}
}
byte[] bytes = null;
Log.d(TAG, "doInBackground: megabytes before compression: " + mBitmap.getByteCount() / 1000000 );
bytes = getBytesFromBitmap(mBitmap, 100);
Log.d(TAG, "doInBackground: megabytes before compression: " + bytes.length / 1000000 );
return bytes;
}
#Override
protected void onPostExecute(byte[] bytes) {
super.onPostExecute(bytes);
mUploadBytes = bytes;
hideProgressBar();
//execute the upload task
executeUploadTask();
}
}
private void executeUploadTask(){
Toast.makeText(getActivity(), "uploading image", Toast.LENGTH_SHORT).show();
final String postId = FirebaseDatabase.getInstance().getReference().push().getKey();
final StorageReference storageReference = FirebaseStorage.getInstance().getReference()
.child("posts/users/" + FirebaseAuth.getInstance().getCurrentUser().getUid() +
"/" + postId + "/post_image");
UploadTask uploadTask = storageReference.putBytes(mUploadBytes);
uploadTask.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Toast.makeText(getActivity(), "Post Success", Toast.LENGTH_SHORT).show();
//insert the download url into the firebase database
Uri firebaseUri = taskSnapshot.getDownloadUrl();
Log.d(TAG, "onSuccess: firebase download url: " + firebaseUri.toString());
DatabaseReference reference = FirebaseDatabase.getInstance().getReference();
Post post = new Post();
post.setImage(firebaseUri.toString());
post.setCity(mCity.getText().toString());
post.setContact_email(mContactEmail.getText().toString());
post.setCountry(mCountry.getText().toString());
post.setDescription(mDescription.getText().toString());
post.setPost_id(postId);
post.setPrice(mPrice.getText().toString());
post.setState_province(mStateProvince.getText().toString());
post.setTitle(mTitle.getText().toString());
post.setUser_id(FirebaseAuth.getInstance().getCurrentUser().getUid());
post.setCollege(mCollege.getText().toString());
reference.child(getString(R.string.node_posts))
.child(postId)
.setValue(post);
resetFields();
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(getActivity(), "could not upload photo", Toast.LENGTH_SHORT).show();
}
}).addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
#Override
public void onProgress(UploadTask.TaskSnapshot taskSnapshot) {
double currentProgress = (100 * taskSnapshot.getBytesTransferred()) / taskSnapshot.getTotalByteCount();
if( currentProgress > (mProgress + 15)){
mProgress = (100 * taskSnapshot.getBytesTransferred()) / taskSnapshot.getTotalByteCount();
Log.d(TAG, "onProgress: upload is " + mProgress + "& done");
Toast.makeText(getActivity(), mProgress + "%", Toast.LENGTH_SHORT).show();
}
}
});
}
public static byte[] getBytesFromBitmap(Bitmap bitmap, int quality){
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, quality,stream);
return stream.toByteArray();
}
private void resetFields(){
UniversalImageLoader.setImage("", mPostImage);
mTitle.setText("");
mDescription.setText("");
mPrice.setText("");
mCountry.setText("India");
mStateProvince.setText("Maharashtra");
mCity.setText("Pune");
mContactEmail.setText("");
mCollege.setText("");
}
private void showProgressBar(){
mProgressBar.setVisibility(View.VISIBLE);
}
private void hideProgressBar(){
if(mProgressBar.getVisibility() == View.VISIBLE){
mProgressBar.setVisibility(View.INVISIBLE);
}
}
/**
* Return true if the #param is null
* #param string
* #return
*/
private boolean isEmpty(String string){
return string.equals("");
}
}
And it is been navigated from SearchActivity class
public class SearchActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener{
private static final String TAG = "SearchActivity";
private static final int REQUEST_CODE = 1;
private FirebaseAuth.AuthStateListener mAuthStateListener;
//widgets
private TabLayout mTabLayout;
public ViewPager mViewPager;
//vars
public SectionsPagerAdapter mPagerAdapter;
//navigation drawer
private DrawerLayout mDrawerLayout;
private ActionBarDrawerToggle mToggle;
//user info
TextView uname,uemail;
String pemail,pname;
ImageView pimage;
CoordinatorLayout navigation;
FloatingActionButton fab;
#RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_search);
mTabLayout = (TabLayout) findViewById(R.id.tabs);
mViewPager = (ViewPager) findViewById(R.id.viewpager_container);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer);
navigation = (CoordinatorLayout) findViewById(R.id.error);
mToggle = new ActionBarDrawerToggle(this,mDrawerLayout,R.string.open,R.string.close)
{
/* Called when a drawer has settled in a completely close state. */
public void onDrawerClosed(View view) {
// fab.setVisibility(View.VISIBLE);
//navigation.setVisibility(View.VISIBLE);
}
/** Called when a drawer has settled in a completely open state. */
public void onDrawerOpened(View drawerView) {
// fab.setVisibility(View.INVISIBLE);
// navigation.setVisibility(View.INVISIBLE);
}
};
mDrawerLayout.addDrawerListener(mToggle);
mToggle.syncState();
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
NavigationView navigationView = (NavigationView) findViewById(R.id.navigation_view);
navigationView.setNavigationItemSelectedListener(this);
fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setBackgroundTintList(ColorStateList.valueOf(ContextCompat.getColor(getApplicationContext(),R.color.red4)));
View header = navigationView.getHeaderView(0);
pimage = (ImageView) header.findViewById(R.id.pimage);
uname = (TextView) header.findViewById(R.id.uname);
uemail = (TextView) header.findViewById(R.id.emailo);
SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(SearchActivity.this);
pemail = sharedPref.getString("email", "Not Available");
pname = sharedPref.getString("username", "Not Available");
uname.setText(pname);
uemail.setText(pemail);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(SearchActivity.this,uploadPost.class);
startActivity(intent);
}
});
setupFirebaseListener();
verifyPermissions();
}
private void setupFirebaseListener() {
Log.d(TAG, "setupFirebaseListener: setting up the auth state listener.");
mAuthStateListener = new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
FirebaseUser user = firebaseAuth.getCurrentUser();
if (user != null) {
Log.d(TAG, "onAuthStateChanged: signed_in: " + user.getUid());
} else {
Log.d(TAG, "onAuthStateChanged: signed_out");
Toast.makeText(SearchActivity.this, "Signed out", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(SearchActivity.this, LoginActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
}
}
};
}
#Override
public void onStart() {
super.onStart();
FirebaseAuth.getInstance().addAuthStateListener(mAuthStateListener);
}
#Override
public void onStop() {
super.onStop();
if (mAuthStateListener != null) {
FirebaseAuth.getInstance().removeAuthStateListener(mAuthStateListener);
}
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if(mToggle.onOptionsItemSelected(item)){
return true;
}
return super.onOptionsItemSelected(item);
}
private void setupViewPager(){
mPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
mPagerAdapter.addFragment(new SearchFragment());
mPagerAdapter.addFragment(new WatchListFragment());
// mPagerAdapter.addFragment(new PostFragment());
mViewPager.setAdapter(mPagerAdapter);
mTabLayout.setupWithViewPager(mViewPager);
mTabLayout.getTabAt(0).setText(getString(R.string.fragment_search));
mTabLayout.getTabAt(1).setText(getString(R.string.fragment_watch_list));
// mTabLayout.getTabAt(2).setText(getString(R.string.fragment_post));
}
private void verifyPermissions(){
Log.d(TAG, "verifyPermissions: asking user for permissions");
String[] permissions = {Manifest.permission.READ_EXTERNAL_STORAGE,
Manifest.permission.WRITE_EXTERNAL_STORAGE,
Manifest.permission.CAMERA};
if(ContextCompat.checkSelfPermission(this.getApplicationContext(),
permissions[0]) == PackageManager.PERMISSION_GRANTED
&& ContextCompat.checkSelfPermission(this.getApplicationContext(),
permissions[1]) == PackageManager.PERMISSION_GRANTED
&& ContextCompat.checkSelfPermission(this.getApplicationContext(),
permissions[2]) == PackageManager.PERMISSION_GRANTED){
setupViewPager();
}else{
ActivityCompat.requestPermissions(SearchActivity.this,
permissions,
REQUEST_CODE);
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
verifyPermissions();
}
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
int id = item.getItemId();
if(id == R.id.profile){
Intent intent = new Intent(SearchActivity.this,test.class);
startActivity(intent);
Toast.makeText(this,"Profile",Toast.LENGTH_SHORT).show();
}
if(id == R.id.aboutus){
Intent intent = new Intent(SearchActivity.this,Aboutus.class);
startActivity(intent);
Toast.makeText(this,"About Us",Toast.LENGTH_SHORT).show();
}
if(id == R.id.mypost){
Intent intent = new Intent(SearchActivity.this,MyPosts.class);
startActivity(intent);
Toast.makeText(this,"My Post",Toast.LENGTH_SHORT).show();
}
if(id == R.id.logout){
Log.d(TAG, "onClick: attempting to sign out the user.");
FirebaseAuth.getInstance().signOut();
}
return false;
}
}
I am not able to understand the error which i am seeing on my logs
FATAL EXCEPTION: main
Process: codingwithmitch.com.forsale, PID: 13518
java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{codingwithmitch.com.forsale/codingwithmitch.com.forsale.uploadPost}: java.lang.ClassCastException: codingwithmitch.com.forsale.uploadPost cannot be cast to android.app.Activity
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2561)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2724)
at android.app.ActivityThread.-wrap12(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1473)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6123)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:867)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:757)
Caused by: java.lang.ClassCastException: codingwithmitch.com.forsale.uploadPost cannot be cast to android.app.Activity
at android.app.Instrumentation.newActivity(Instrumentation.java:1100)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2551)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2724)
at android.app.ActivityThread.-wrap12(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1473)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6123)
my SearchActivity xml file:
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:fab="http://schemas.android.com/tools"
android:id="#+id/drawer"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/White"
android:fitsSystemWindows="true">
<android.support.design.widget.CoordinatorLayout
android:id="#+id/error"
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.design.widget.AppBarLayout
android:id="#+id/app_bar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/white"
android:elevation="10dp"
android:fitsSystemWindows="true">
<android.support.design.widget.CollapsingToolbarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:layout_scrollFlags="scroll|exitUntilCollapsed">
<android.support.design.widget.TabLayout
android:id="#+id/tabs"
android:layout_width="match_parent"
android:layout_height="50dp"
app:layout_collapseMode="parallax">
</android.support.design.widget.TabLayout>
</android.support.design.widget.CollapsingToolbarLayout>
</android.support.design.widget.AppBarLayout>
<android.support.v4.view.ViewPager
android:id="#+id/viewpager_container"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior">
</android.support.v4.view.ViewPager>
<com.getbase.floatingactionbutton.FloatingActionButton
android:id="#+id/fab"
android:layout_width="42dp"
android:layout_height="53dp"
android:layout_gravity="bottom|end"
android:layout_margin="#dimen/fab_margin"
android:scaleType="center"
android:src="#drawable/ic_camera_alt_black_24dp"
app:fabSize="normal"
fab:layout_editor_absoluteX="342dp"
fab:layout_editor_absoluteY="458dp">
</com.getbase.floatingactionbutton.FloatingActionButton>
</android.support.design.widget.CoordinatorLayout>
<android.support.design.widget.NavigationView
android:id="#+id/navigation_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="start"
app:headerLayout="#layout/header"
app:menu="#menu/nav_menu"></android.support.design.widget.NavigationView>
</android.support.v4.widget.DrawerLayout>
You are getting the error :
cannot be cast to android.app.Activity
because you are trying to load uploadPost as an Activity but it extends Fragment so you get the "cannot be cast to android.app.Activity" error.
You must decide whether you want to load it as a Fragment or an Activity. If you want to load uploadPost as an Activity you need to extend to an Activity not Fragment
EDIT
If you wish to continue to use it as a Fragment you must use a FragmentTransaction to either add() the Fragment or replace() a Fragment in your activity layout.
You can replace a Fragment like this example:
Fragment fragment = new UploadPost();
if(fragment != null) {
FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
//If you want to play around with different transaction animations
//fragmentTransaction.setCustomAnimations(android.R.anim.fade_in, android.R.anim.fade_out);
fragmentTransaction.replace(R.id.content_main, fragment, "0");
fragmentTransaction.commit();
}
Where R.id.content_main is just a RelativeLayout in my MainActivity which is replaced by the uploadPost fragment.
And as 0X0nosugar indicated: It is java naming convention to capitalize class names. Please adopt this convention--otherwise you will make it more difficult to understand your code.
EDIT 2
Often a Fragment will be used to swap views in an container Activity. For example I use them to swap views in combination with a DrawerLayout. In this case I will continue to replace fragments, but never really remove one explicitly.
For example I will have a xml layout file very similar to your "SearchActivity" file. Just below the </android.support.design.widget.AppBarLayout> tag I will introduce a RelativeLayout with the id android:id="#+id/content_main". This RelativeLayout is just a dummy container view and is being replaced with whatever is in my selected Fragment. So you would need to change the onClick code to replace the fragment as I showed above.
With another action you might want to either remove that fragment or replace it with another... that all depends on your app design--which I do not know.
Related
I am having a Viewpager where i am loading data of different categories. I want to show a custom dialog popup whenever user stays on a particular category for 5 seconds or more asking the user if he/she wants to share the content. For that i have used a custom dialog and am hiding/showing based on the condition.
But the problem is, that if i want to open the dialog if the user stays on Viewpager item at position let's say 3, the dialog is opening for the Viewpager item at position 4.
I am not sure why it's referencing the wrong Viewpager item.
I am including the code of Adapter class for the reference.
ArticleAdapter.java
public class ArticleAdapter extends PagerAdapter {
public List<Articles> articlesListChild;
private LayoutInflater inflater;
Context context;
View rootView;
View customArticleShareDialog, customImageShareDialog;
public int counter = 0;
int contentType = 0;
int userId;
public ArticleAdapter(Context context, List<Articles> articlesListChild, int userId) {
super();
this.context = context;
this.userId = userId;
this.articlesListChild = articlesListChild;
}
#Override
public int getCount() {
return articlesListChild.size();
}
#Override
public void destroyItem(View collection, int position, Object view) {
((ViewPager) collection).removeView((View) view);
}
private Timer timer;
private TimerTask timerTask;
public void startTimer() {
timer = new Timer();
initializeTimerTask();
timer.schedule(timerTask, 5*1000, 5*1000);
}
private void initializeTimerTask() {
timerTask = new TimerTask() {
public void run() {
switch (contentType) {
case 1:
showShareDialog("articles");
break;
case 2:
showShareDialog("images");
break;
default :
// Do Nothing
}
}
};
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view == object;
}
#SuppressLint("ClickableViewAccessibility")
#Override
public Object instantiateItem(ViewGroup container, final int position) {
inflater = LayoutInflater.from(container.getContext());
View viewLayout = inflater.inflate(R.layout.article_single_item, null, false);
final ImageView contentIv, imageContentIv;
final TextView sharingTextTv;
final LinearLayout articleShareBtn, articlesLayout, imagesLayout, customArticleShareDialog, customImageShareDialog;
contentIv = viewLayout.findViewById(R.id.content_iv);
articleShareBtn = viewLayout.findViewById(R.id.article_share_btn);
articlesLayout = viewLayout.findViewById(R.id.articles_layout);
imagesLayout = viewLayout.findViewById(R.id.images_layout);
imageContentIv = viewLayout.findViewById(R.id.image_content_iv);
sharingTextTv = viewLayout.findViewById(R.id.sharing_text_tv);
customArticleShareDialog = viewLayout.findViewById(R.id.articles_share_popup);
customImageShareDialog = viewLayout.findViewById(R.id.images_share_popup);
rootView = viewLayout.findViewById(R.id.post_main_cv);
viewLayout.setTag(rootView);
articleShareBtn.setTag(rootView);
// Images
if (articlesListChild.get(position).getArticleCatId() == 1) {
articlesLayout.setVisibility(GONE);
imagesLayout.setVisibility(View.VISIBLE);
RequestOptions requestOptions = new RequestOptions();
requestOptions.placeholder(R.drawable.placeholder);
Glide.with(context)
.setDefaultRequestOptions(requestOptions)
.load(articlesListChild.get(position).getArticleImage())
.into(imageContentIv);
imageContentIv.setScaleType(ImageView.ScaleType.FIT_XY);
sharingTextTv.setText("Found this image interesting? Share it with your friends.");
counter = 0;
startTimer();
// Articles
} else if (articlesListChild.get(position).getArticleCatId() == 2){
RequestOptions requestOptions = new RequestOptions();
requestOptions.placeholder(R.drawable.placeholder);
articlesLayout.setVisibility(View.VISIBLE);
Glide.with(context)
.setDefaultRequestOptions(requestOptions)
.load(articlesListChild.get(position).getArticleImage())
.into(contentIv);
contentIv.setScaleType(ImageView.ScaleType.FIT_XY);
sharingTextTv.setText("Found this article interesting? Share it with your friends.");
counter = 0;
startTimer();
}
container.addView(viewLayout, 0);
return viewLayout;
}
public void showShareDialog(String categoryType) {
if (categoryType.equalsIgnoreCase("articles")) {
new Handler(Looper.getMainLooper()).post(new Runnable() {
public void run() {
customArticleShareDialog.setVisibility(View.VISIBLE);
}
});
} else if (categoryType.equalsIgnoreCase("images")) {
new Handler(Looper.getMainLooper()).post(new Runnable() {
public void run() {
customImageShareDialog.setVisibility(View.VISIBLE);
}
});
}
}
}
ArticleActivity.java
public class ArticleActivity extends AppCompatActivity {
#BindView(R.id.toolbar)
Toolbar toolbar;
#BindView(R.id.drawer_layout)
DrawerLayout drawer;
#BindView(R.id.articles_view_pager)
ViewPager articlesViewPager;
#BindView(R.id.constraint_head_layout)
CoordinatorLayout constraintHeadLayout;
private ArticleAdapter articleAdapter;
private List<List<Articles>> articlesList = null;
private List<Articles> articlesListChild = new ArrayList<>();
private List<Articles> articlesListChildNew = new ArrayList<>();
SessionManager session;
Utils utils;
final static int MY_PERMISSIONS_WRITE_EXTERNAL_STORAGE = 1;
int userIdLoggedIn;
LsArticlesSharedPreference lsArticlesSharedPreference;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
ButterKnife.bind(this);
toolbar.setTitle("");
toolbar.bringToFront();
session = new SessionManager(getApplicationContext());
if (session.isLoggedIn()) {
HashMap<String, String> user = session.getUserDetails();
String userId = user.get(SessionManager.KEY_ID);
userIdLoggedIn = Integer.valueOf(userId);
} else {
userIdLoggedIn = 1000;
}
utils = new Utils(getApplicationContext());
String storedTime = PreferenceManager.getDefaultSharedPreferences(getApplicationContext()).getString("lastUsedDate", "");
System.out.println("lastUsedDate : " + storedTime);
if (utils.isNetworkAvailable()) {
insertData();
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
toggle.getDrawerArrowDrawable().setColor(getResources().getColor(R.color.colorWhite));
drawer.addDrawerListener(toggle);
if (ContextCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
MY_PERMISSIONS_WRITE_EXTERNAL_STORAGE);
}
articleAdapter = new ArticleAdapter(getApplicationContext(), articlesListChild, userIdLoggedIn);
toggle.syncState();
clickListeners();
toolbar.setVisibility(View.GONE);
} else {
Intent noInternetIntent = new Intent(getApplicationContext(), NoInternetActivity.class);
startActivity(noInternetIntent);
}
}
#Override
public void onBackPressed() {
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
finishAffinity();
super.onBackPressed();
}
}
#Override
public void onStart() {
super.onStart();
}
#Override
public void onStop() {
super.onStop();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.home, menu);
return true;
}
#Override
public boolean onSupportNavigateUp() {
finish();
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_refresh:
articleAdapter.notifyDataSetChanged();
insertData();
Toast.makeText(this, "Refreshed", Toast.LENGTH_SHORT).show();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
#SuppressLint("ClickableViewAccessibility")
public void clickListeners() {
}
private void insertData() {
Intent intent = new Intent(getBaseContext(), OverlayService.class);
startService(intent);
final SweetAlertDialog pDialog = new SweetAlertDialog(ArticleActivity.this, SweetAlertDialog.PROGRESS_TYPE);
pDialog.getProgressHelper().setBarColor(getResources().getColor(R.color.colorPrimary));
pDialog.setTitleText("Loading");
pDialog.setCancelable(false);
pDialog.show();
Api.getClient().getHomeScreenContents(userIdLoggedIn, new Callback<ArticlesResponse>() {
#Override
public void success(ArticlesResponse articlesResponse, Response response) {
articlesList = articlesResponse.getHomeScreenData();
if (!articlesList.isEmpty()) {
for (int i = 0; i < articlesList.size(); i++) {
articlesListChildNew = articlesList.get(i);
articlesListChild.addAll(articlesListChildNew);
}
articleAdapter = new ArticleAdapter(getApplicationContext(), articlesList, articlesListChild, userIdLoggedIn, toolbar);
articlesViewPager.setAdapter(articleAdapter);
articleAdapter.notifyDataSetChanged();
pDialog.dismiss();
} else {
List<Articles> savedArticles = lsArticlesSharedPreference.getFavorites(getApplicationContext());
if (!savedArticles.isEmpty()) {
articleAdapter = new ArticleAdapter(getApplicationContext(), articlesList, savedArticles, userIdLoggedIn, toolbar);
articlesViewPager.setAdapter(articleAdapter);
articleAdapter.notifyDataSetChanged();
pDialog.dismiss();
} else {
Api.getClient().getAllArticles(new Callback<AllArticlesResponse>() {
#Override
public void success(AllArticlesResponse allArticlesResponse, Response response) {
articlesListChild = allArticlesResponse.getArticles();
articleAdapter = new ArticleAdapter(getApplicationContext(), articlesList, articlesListChild, userIdLoggedIn, toolbar);
articlesViewPager.setAdapter(articleAdapter);
articleAdapter.notifyDataSetChanged();
};
#Override
public void failure(RetrofitError error) {
Log.e("articlesData", error.toString());
}
});
pDialog.dismiss();
}
}
}
#Override
public void failure(RetrofitError error) {
pDialog.dismiss();
Toast.makeText(ArticleActivity.this, "There was some error fetching the data.", Toast.LENGTH_SHORT).show();
}
});
}
}
Issue reason:
You face this issue because the viewpager preload fragments in background. It means that when you see 3rd fragment, the viewpager is instantiating 4th. Due to this workflow your timer for 3rd screen is cancelled and timer for 4th screen is started. Check out this link to understand what is going on.
Solution:
I would do next:
Then set page change listener for your adapter. How to do it
In this listener you can get current page and start timer for this page (and cancel timer for previously visible page).
You don't need to call startTimer() method when you instantiate item in instantiateItem() method.
Here is my situation.
In this screen, I click the comments button.
The Comment activity opens and I type what I want.
The comment is added successfully in firebase and it takes me back in detail activity.
So far everything is great! Now let's add another comment. Now you see I get duplicate comments.
I hope you see that too. Now in the DetailActivity I have a method called queryFirebaseDb() and that method is called inside both onCreate() and onResume() methods. If I don't use the onResume() method the data will not be display after clicking the back button from the CommentActivity. You see where I am going now right? The question is how to avoid duplicate data after coming back from CommentActivity. Here is my code.
public class DetailActivity extends AppCompatActivity {
ArrayList<Comment> commentArrayList;
ImageView mImageView;
TextView mTitle;
TextView mDate;
TextView mDescription;
TextView mAuthor;
ToggleButton mFavBtn;
private TextView noCommentsTextView;
private TextView commentsTextView;
private ImageButton imageButton;
private FloatingActionButton mShareBtn;
private String newsTitle;
private String newsImage;
private String newsDate;
private String newsDescription;
private static String NEWS_SHARE_HASHTAG = "#EasyNewsApp";
private String date1;
private String date2;
private String newsUrl;
private String newsAuthor;
private Cursor favoriteCursor;
private DatabaseReference mDatabase;
private static Bundle bundle = new Bundle();
private Uri uri;
private RecyclerView mRecyclerView;
private DisplayCommentsAdapter displayCommentsAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_detail);
Toolbar toolbar = (Toolbar) findViewById(R.id.detail_toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
Intent i = getIntent();
mAuthor = (TextView) findViewById(R.id.detail_author);
mImageView = (ImageView) findViewById(R.id.detail_image_view);
mTitle = (TextView) findViewById(R.id.detail_title);
mDate = (TextView) findViewById(R.id.detail_publish_date);
mDescription = (TextView) findViewById(R.id.detail_description);
noCommentsTextView = (TextView)findViewById(R.id.noCommentsTextView);
commentsTextView = (TextView)findViewById(R.id.commentsTextView);
mShareBtn = (FloatingActionButton) findViewById(R.id.share_floating_btn);
mFavBtn = (ToggleButton) findViewById(R.id.fav_news_btn);
imageButton = (ImageButton)findViewById(R.id.detail_comment_image_btn);
mRecyclerView = (RecyclerView)findViewById(R.id.recycler_comments);
LinearLayoutManager manager = new LinearLayoutManager(this);
mRecyclerView.setLayoutManager(manager);
mRecyclerView.setHasFixedSize(true);
mRecyclerView.addItemDecoration(new SimpleDividerItemDecoration(this));
commentArrayList = new ArrayList<>();
mDatabase = FirebaseDatabase.getInstance().getReference();
mFavBtn.setTextOn(null);
mFavBtn.setText(null);
mFavBtn.setTextOff(null);
newsAuthor = i.getStringExtra("author");
newsImage = i.getStringExtra("image");
newsTitle = i.getStringExtra("newsTitle");
newsDate = i.getStringExtra("date");
newsDescription = i.getStringExtra("description");
newsUrl = i.getStringExtra("url");
date1 = newsDate.substring(0, 10);
date2 = newsDate.substring(11, 19);
Picasso.with(this).load(newsImage)
.placeholder(R.drawable.ic_broken_image)
.into(mImageView);
mTitle.setText(newsTitle);
mAuthor.setText("Author: " + newsAuthor);
mDescription.setText(newsDescription);
mDate.setText(date2 + ", " + date1);
mShareBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent shareIntent = createShareNewsIntent();
startActivity(shareIntent);
}
});
imageButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent commentIntent = new Intent(DetailActivity.this, CommentActivity.class);
commentIntent.putExtra("newsTitle",newsTitle);
startActivity(commentIntent);
}
});
/**
* Handling the add/remove news part. We check if the specific news article
* exists in favourite.db.
*/
favoriteCursor = getContentResolver().query(FavouriteContract.FavouriteEntry.CONTENT_URI,
null,
FavouriteContract.FavouriteEntry.COLUMN_NEWS_TITLE + "=?",
new String[]{newsTitle},
null);
/**
* If yes then set the toggle button to true
*/
if (favoriteCursor.getCount() > 0) {
try {
mFavBtn.setChecked(true);
} finally {
favoriteCursor.close();
}
}
/**
* Else click the toggle button to add the news article as favourite
*/
mFavBtn.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton compoundButton, final boolean isChecked) {
/**
* If checked the add the news article as favourite.
*/
if (isChecked) {
new AsyncTask<Void, Void, Void>() {
#Override
protected Void doInBackground(Void... voids) {
ContentValues contentValues = new ContentValues();
contentValues.put(FavouriteContract.FavouriteEntry.COLUMN_NEWS_TITLE, newsTitle);
contentValues.put(FavouriteContract.FavouriteEntry.COLUMN_NEWS_AUTHOR, newsAuthor);
contentValues.put(FavouriteContract.FavouriteEntry.COLUMN_NEWS_DESCRIPTION, newsDescription);
contentValues.put(FavouriteContract.FavouriteEntry.COLUMN_NEWS_URL, newsUrl);
contentValues.put(FavouriteContract.FavouriteEntry.COLUMN_NEWS_URL_TO_IMAGE, newsImage);
contentValues.put(FavouriteContract.FavouriteEntry.COLUMN_NEWS_PUBLISHED_AT, newsDate);
//The actual insertion in the db.
uri = getContentResolver().insert(FavouriteContract.FavouriteEntry.CONTENT_URI, contentValues);
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
Toast.makeText(DetailActivity.this, "Article with title: " + newsTitle + " was added", Toast.LENGTH_SHORT).show();
}
}.execute();
} else {
/**
* If you uncheck the toggle button then delete the news article from the favourite db.
*/
Uri newsTitleOfFavNews = FavouriteContract.FavouriteEntry.buildNewsUriWithTitle(newsTitle);
//String title = uri.getPathSegments().get(1);// Get the task ID from the URI path
getContentResolver().delete(
newsTitleOfFavNews,
null,
null);
Toast.makeText(DetailActivity.this, "News article deleted from favourites ", Toast.LENGTH_SHORT).show();
}
}
});
queryFirebaseDb();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.detail_menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
super.onOptionsItemSelected(item);
if(item.getItemId() == R.id.detail_browser_btn){
Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(newsUrl));
startActivity(browserIntent);
} if(item.getItemId() == android.R.id.home){
NavUtils.navigateUpFromSameTask(this);
return true;
}
return true;
}
private Intent createShareNewsIntent() {
Intent shareIntent = ShareCompat.IntentBuilder.from(this)
.setType("text/plain")
.setText(NEWS_SHARE_HASHTAG + "\n\n\n" + newsTitle
+ "\n\n\n" + newsDescription
+ "\n\n\n" + newsDate)
.getIntent();
return shareIntent;
}
#Override
protected void onStart() {
super.onStart();
//queryFirebaseDb();
}
#Override
protected void onRestart() {
super.onRestart();
queryFirebaseDb();
//displayCommentsAdapter.notifyDataSetChanged();
}
public void queryFirebaseDb(){
/**
* Querying the database to check if the specific article has comments.
*/
mDatabase = FirebaseDatabase.getInstance().getReference();
Query query = mDatabase.child("comments").orderByChild("newsTitle").equalTo(newsTitle);
query.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if(dataSnapshot.exists()){
for(DataSnapshot dataSnapshots : dataSnapshot.getChildren()){
Comment comment = dataSnapshots.getValue(Comment.class);
//mUserDatabase = FirebaseDatabase.getInstance().getReference().child("Users").child(userId);
commentArrayList.add(comment);
displayCommentsAdapter = new DisplayCommentsAdapter(this,commentArrayList);
mRecyclerView.setAdapter(displayCommentsAdapter);
displayCommentsAdapter.setCommentsData(commentArrayList);
//Log.d(LOG_TAG, String.valueOf(commentArrayList.size()));
}
noCommentsTextView.setVisibility(View.GONE);
//commentsTextView.setVisibility(View.VISIBLE);
}else{
//Toast.makeText(DisplayComments.this,"There are no comments posted",Toast.LENGTH_LONG).show();
noCommentsTextView.setVisibility(View.VISIBLE);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
/*
#Override
protected void onPause() {
super.onPause();
bundle.putBoolean("ToggleButtonState", mFavBtn.isChecked());
}
#Override
public void onResume() {
super.onResume();
mFavBtn.setChecked(bundle.getBoolean("ToggleButtonState",false));
}
*/
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
mFavBtn.setChecked(savedInstanceState.getBoolean("ToggleButtonState",false));
savedInstanceState.putParcelableArrayList("newsList",commentArrayList);
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putBoolean("ToggleButtonState",mFavBtn.isChecked());
outState.getParcelableArrayList("newsList");
}
}
and
public class CommentActivity extends AppCompatActivity {
private static final String REQUIRED = "Required";
private static final String TAG = CommentActivity.class.getSimpleName();
Toolbar toolbar;
DatabaseReference mDatabase;
EditText titleEt;
EditText bodyEt;
Button commentBtn;
String newsTitle;
Intent i;
String name;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_comment);
toolbar = (Toolbar) findViewById(R.id.comment_toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setTitle("Add comment");
mDatabase = FirebaseDatabase.getInstance().getReference();
titleEt = (EditText) findViewById(R.id.comment_title);
bodyEt = (EditText) findViewById(R.id.comment_body);
commentBtn = (Button) findViewById(R.id.comment_btn);
i = getIntent();
newsTitle = i.getStringExtra("newsTitle");
commentBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
submitPost();
}
});
}
private void submitPost() {
final String title = titleEt.getText().toString();
final String body = bodyEt.getText().toString();
// Title is required
if (TextUtils.isEmpty(title)) {
titleEt.setError(REQUIRED);
return;
}
// Body is required
if (TextUtils.isEmpty(body)) {
bodyEt.setError(REQUIRED);
return;
}
// Disable button so there are no multi-posts
setEditingEnabled(false);
Toast.makeText(this, "Posting...", Toast.LENGTH_SHORT).show();
// [START single_value_read]
final String userId = FirebaseAuth.getInstance().getCurrentUser().getUid();
mDatabase.child("Users").child(userId).addListenerForSingleValueEvent(
new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
// Get user value
User user = dataSnapshot.getValue(User.class);
// [START_EXCLUDE]
if (user == null) {
// User is null, error out
Log.e(TAG, "User " + userId + " is unexpectedly null");
Toast.makeText(CommentActivity.this,
"Error: could not fetch user.",
Toast.LENGTH_SHORT).show();
} else {
// Write new post
name = dataSnapshot.child("name").getValue().toString();
Calendar c = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy hh:mm:ss");
String strDate = sdf.format(c.getTime());
writeNewPost(userId,strDate,name,newsTitle, title, body);
}
// Finish this Activity, back to the stream
setEditingEnabled(true);
finish();
// [END_EXCLUDE]
}
#Override
public void onCancelled(DatabaseError databaseError) {
Log.w(TAG, "getUser:onCancelled", databaseError.toException());
// [START_EXCLUDE]
setEditingEnabled(true);
// [END_EXCLUDE]
}
});
// [END single_value_read]
}
private void writeNewPost(String userId,String date,String
commentAuthor, String newsTitle, String commentTitle, String
commentBody){
String key = mDatabase.child("comments").push().getKey();
Comment comment = new Comment(userId, date,
commentAuthor,newsTitle,commentTitle,commentBody);
Map<String, Object> commentValues = comment.toMap();
Map<String, Object> childUpdates = new HashMap<>();
childUpdates.put("/comments/" + key, commentValues);
mDatabase.updateChildren(childUpdates);
}
private void setEditingEnabled(boolean enabled) {
titleEt.setEnabled(enabled);
bodyEt.setEnabled(enabled);
if (enabled) {
commentBtn.setVisibility(View.VISIBLE);
} else {
commentBtn.setVisibility(View.GONE);
}
}
}
UPDATE
I used this
#Override
protected void onRestart() {
super.onRestart();
finish();
startActivity(getIntent());
}
and voila!
Some stuff I thought you would know when doing Android:
Basically, in android, you need to understand how the life cycle works. So, when you call queryFirebaseDb() from onCreate and from onResume, your app is doing two queries at the same time when activity starts initially.
Lifecycle is like this OnCreate -> onResume. So, it makes sense that when activity starts, query gets executed once on onCreate than on onResume based on your logic.
Answer is here
I noticed that you are using ArrayList<Comment> commentArrayList;, which is an ArrayList structure, which lets you have duplicate data. And, if you look into the behavior of Firebase and how your query is structured, it is like this,
Query query = mDatabase.child("comments").orderByChild("newsTitle").equalTo(newsTitle);
This query means that you are taking all the comments, the previous comment and the new comment, (not just new comment), which I think you either just want (1) to get recently added comment or (2) to replace the old comments with new one.
The first way of doing this sounds complicated to me, though that is not impossible. But, second way of doing is rather easy.
Therefore, to solve this,
simply, replace the arrayList you have with this data.
if(dataSnapshot.exists()){
ArrayList<Comment> tempComments = new ArrayList();
for(DataSnapshot dataSnapshots : dataSnapshot.getChildren()){
Comment comment = dataSnapshots.getValue(Comment.class);
//mUserDatabase = FirebaseDatabase.getInstance().getReference().child("Users").child(userId);
tempComments.add(comment);
//Log.d(LOG_TAG, String.valueOf(commentArrayList.size()));
}
commentArrayList = tempComments; //assuming you want to store the data in the class fields
displayCommentsAdapter = new DisplayCommentsAdapter(this,commentArrayList);
mRecyclerView.setAdapter(displayCommentsAdapter);
displayCommentsAdapter.setCommentsData(commentArrayList);
noCommentsTextView.setVisibility(View.GONE);
//commentsTextView.setVisibility(View.VISIBLE);
}
I am trying to make a volley request to api's url. The problem is that data is fetched appropriately, but every time data set updates, the whole recycler view refreshes again and begins from the start; in the docs it is mentioned that use notifyDataSetChanged() as the last resort. How can it be avoided and what are the best practices for such tasks? Any design pattern that should be followed?
Here is the Fragment Code :-
public class PageFragment extends Fragment implements SortDialogCallback {
private static final String TAG = PageFragment.class.getSimpleName();
/**
* Unsplash API, By Default=10
*/
private static final String per_page = "10";
public static String order_By;
/**
* Unsplash API call parameter, By Default=latest
* Change it in Pager Fragment, based on Tab tapped
*/
RecyclerView recyclerView;
ImageAdapter imageAdapter;
GridLayoutManager layoutManager;
EndlessRecyclerViewScrollListener scrollListener;
FloatingActionButton actionButton;
FrameLayout no_internet_container;
Bundle savedInstanceState;
// Attaching Handler to the main thread
Handler handler = new Handler();
boolean shouldHandlerRunAgain = true;
private ArrayList<DataModel> model;
/**
* Handler is attached to the Main Thread and it's message queue, because it is the one who created it.
* <p>
* Handler is responsible for checking every second that are we connected to internet, and if we are, then :-
* 1. Then we remove empty view
* 2. Make the network call
* 3. Stop handler from posting the code again using shouldHandlerRunAgain variable
* 3.1 This is a kill switch otherwise handler will post the runnable again and again to the message queue, which will be executed as soon as it reaches the looper
* <p>
* Handler removeCallbacks is used to remove all the pending runnables in the Message Queue
*/
Runnable job = new Runnable() {
#Override
public void run() {
Log.d(TAG, "Thread run " + job.hashCode());
swapViews();
if (shouldHandlerRunAgain)
handler.postDelayed(job, HANDLER_DELAY_TIME);
}
};
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putString("ORDER_BY", order_By);
}
#Override
public void onResume() {
super.onResume();
if (handler != null)
handler.post(job);
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.d(TAG, "Starting Handler");
layoutManager = new GridLayoutManager(getContext(), 2);
scrollListener = new EndlessRecyclerViewScrollListener(layoutManager) {
public void onLoadMore(int page, int totalItemsCount, RecyclerView view) {
Log.w(TAG, "On load More Called with page number " + page);
loadDataUsingVolley(page, order_By);
}
};
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.search:
Toast.makeText(getContext(), "Async task", Toast.LENGTH_SHORT).show();
break;
default:
Toast.makeText(getContext(), "Invalid Options", Toast.LENGTH_SHORT).show();
}
return true;
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.menu_page_fragment, menu);
}
private void swapViews() {
if (detectConnection(getContext()) == false) {
recyclerView.setVisibility(View.INVISIBLE);
actionButton.setVisibility(View.INVISIBLE);
no_internet_container.setVisibility(View.VISIBLE);
} else {
Log.d(TAG, "Removing callbacks from handler and stopping it from posting");
shouldHandlerRunAgain = false;
handler.removeCallbacks(job, null);
handler = null;
recyclerView.setVisibility(View.VISIBLE);
actionButton.setVisibility(View.VISIBLE);
no_internet_container.setVisibility(View.INVISIBLE);
if (savedInstanceState != null) {
loadDataUsingVolley(1, savedInstanceState.getString("ORDER_BY"));
} else {
order_By = "latest";
loadDataUsingVolley(1, order_By);
}
}
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, final Bundle savedInstanceState) {
this.savedInstanceState = savedInstanceState;
View view = inflater.inflate(R.layout.fragment_page, container, false);
actionButton = (FloatingActionButton) view.findViewById(R.id.sort_button);
actionButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
SortDialog sortDialog = new SortDialog();
sortDialog.setTargetFragment(PageFragment.this, 911);
sortDialog.show(getChildFragmentManager(), "sortfragment");
}
});
recyclerView = (RecyclerView) view.findViewById(R.id.recyclerview);
recyclerView.setHasFixedSize(true);
no_internet_container = (FrameLayout) view.findViewById(R.id.no_internet_container);
return view;
}
void setUpRecyclerView() {
if (imageAdapter == null)
imageAdapter = new ImageAdapter(getContext(), (model==null)?new ArrayList<DataModel>():model);
recyclerView.setAdapter(imageAdapter);
recyclerView.setLayoutManager(layoutManager);
recyclerView.addOnScrollListener(scrollListener);
}
void loadDataUsingVolley(int page, String order_by) {
final ProgressDialog dialog = ProgressDialog.show(getContext(), "Wallser", "Loading");
RequestQueue requestQueue = Volley.newRequestQueue(getContext());
String URL = "https://api.unsplash.com/photos/?page=" + page + "&client_id=" + api_key + "&per_page=" + per_page + "&order_by=" + order_by;
Log.d(TAG, URL);
JsonArrayRequest objectRequest = new JsonArrayRequest(Request.Method.GET, URL, null, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray array) {
int len = array.length();
if (model == null)
model = new ArrayList<>();
for (int i = 0; i < len; i++) {
try {
JSONObject object = array.getJSONObject(i);
String id = object.getString("id");
JSONObject object1 = object.getJSONObject("urls");
String imageURL = object1.getString("regular");
JSONObject object2 = object.getJSONObject("links");
String downloadURL = object2.getString("download");
model.add(new DataModel(imageURL, downloadURL, id));
Log.d(TAG, downloadURL);
} catch (JSONException e) {
e.printStackTrace();
}
}
if (dialog != null) {
dialog.dismiss();
}
Log.d(TAG, model.size() + "");
setUpRecyclerView();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
dialog.dismiss();
Toast.makeText(getContext(), "" + error.getMessage(), Toast.LENGTH_SHORT).show();
}
});
requestQueue.add(objectRequest);
}
/**
* marks a new network call to Unsplash API
* Thus, set model array list to null, to start fresh.
* as model is reset, ImageAdapter also needs to start fresh.
*
* #param order_by
*/
#Override
public void onDialogFinish(String order_by) {
model = null;
imageAdapter=null;
order_By = order_by;
loadDataUsingVolley(1, order_By);
}
}
I am new to android and currently I want to develop an application that need to request network using volley. However, it returns error below:
Caused by: java.lang.IllegalStateException: RequestQueue not initialized
at com.myapp.zeptomobile.myapp.app.StaggeredDemoApplication.getRequestQueue(StaggeredDemoApplication.java:35)
at com.myapp.zeptomobile.myapp.FlickrActivity.onCreate(FlickrActivity.java:75)
at android.app.Activity.performCreate(Activity.java:5248)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2164)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2249)
at android.app.ActivityThread.access$800(ActivityThread.java:141)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1212)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5052)
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:793)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:609)
at dalvik.system.NativeStart.main(Native Method)
01-18 14:07:15.655 24065-24065/com.myapp.zeptomobile.myapp I/Process: Sending signal. PID: 24065 SIG: 9
Below is the Main Program
enter public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener, FragmentRecent.OnFragmentInteractionListener,
FragmentAseanGirl.OnFragmentInteractionListener,FragmentFlickrStart.OnFragmentInteractionListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
if (savedInstanceState == null) {
Fragment fragment = null;
Class fragmentClass = null;
fragmentClass = FragmentRecent.class;
try {
fragment = (Fragment) fragmentClass.newInstance();
} catch (Exception e) {
e.printStackTrace();
}
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction().replace(R.id.flContent, fragment).commit();
}
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
}
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
Fragment fragment = null;
Class fragmentClass = null;
if (id == R.id.nav_camera) {
fragmentClass = FragmentRecent.class;
} else if (id == R.id.nav_gallery) {
fragmentClass = FragmentAseanGirl.class;
} else if (id == R.id.nav_slideshow) {
fragmentClass = FragmentRecent.class;
} else if (id == R.id.nav_manage) {
fragmentClass = FragmentFlickrStart.class;
} else if (id == R.id.nav_share) {
fragmentClass = FragmentRecent.class;
} else if (id == R.id.nav_send) {
fragmentClass = FragmentAseanGirl.class;
}
try {
fragment = (Fragment) fragmentClass.newInstance();
} catch (Exception e) {
e.printStackTrace();
}
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction().replace(R.id.flContent, fragment).commit();
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
#Override
public void onFragmentInteraction(Uri uri) {
}
}
Below is the Fragment program
public class FragmentFlickrStart extends Fragment {
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
private OnFragmentInteractionListener mListener;
public FragmentFlickrStart() {
// Required empty public constructor
}
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* #param param1 Parameter 1.
* #param param2 Parameter 2.
* #return A new instance of fragment FragmentTwo.
*/
// TODO: Rename and change types and number of parameters
public static FragmentFlickrStart newInstance(String param1, String param2) {
FragmentFlickrStart fragment = new FragmentFlickrStart();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
Intent intent = new Intent(getActivity(),FlickrActivity.class);
startActivity(intent);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_flickrstart, container, false);
}
// TODO: Rename method, update argument and hook method into UI event
public void onButtonPressed(Uri uri) {
if (mListener != null) {
mListener.onFragmentInteraction(uri);
}
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnFragmentInteractionListener) {
mListener = (OnFragmentInteractionListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement OnFragmentInteractionListener");
}
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
/**
* This interface must be implemented by activities that contain this
* fragment to allow an interaction in this fragment to be communicated
* to the activity and potentially other fragments contained in that
* activity.
* <p/>
* See the Android Training lesson <a href=
* "http://developer.android.com/training/basics/fragments/communicating.html"
* >Communicating with Other Fragments</a> for more information.
*/
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
void onFragmentInteraction(Uri uri);
}
}
Below is the Activity program
public class FlickrActivity extends Activity{
private StaggeredGridView mStaggeredView;
private RequestQueue mVolleyQueue;
private ProgressDialog mProgress;
private int currPage=1;
GsonRequest<FlickrResponsePhotos> gsonObjRequest;
private RelativeLayout mListFooter;
private boolean isLoading = false;
private final String TAG_REQUEST = "MY_TAG";
private StaggeredGridView.OnScrollListener scrollListener = new StaggeredGridView.OnScrollListener() {
public void onTop() {
}
public void onScroll() {
}
public void onBottom() {
loadMoreData();
}
};
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_flickr);
//actionBarSetup();
// Initialise Volley Request Queue. added to fix TBS
if(mVolleyQueue==null){
mVolleyQueue= Volley.newRequestQueue(getApplicationContext());
}
mVolleyQueue = StaggeredDemoApplication.getRequestQueue();
mListFooter = (RelativeLayout) findViewById(R.id.footer);
mStaggeredView = (StaggeredGridView) findViewById(R.id.staggeredview);
// Be sure before calling initialize that you haven't initialised from XML
//mStaggeredView.initialize(2, StaggeredGridView.Mode.FIXED);
mStaggeredView.setOnScrollListener(scrollListener);
showProgress();
flickerGetImagesRequest();
}
public void onStop() {
super.onStop();
if(mProgress != null)
mProgress.dismiss();
}
private void loadMoreData() {
if ( isLoading )
return;
mListFooter.setVisibility(View.VISIBLE);
isLoading = true;
flickerGetImagesRequest();
}
private void flickerGetImagesRequest() {
String url = "https://api.flickr.com/services/rest";
Uri.Builder builder = Uri.parse(url).buildUpon();
builder.appendQueryParameter("api_key", "5e045abd4baba4bbcd866e1864ca9d7b");
//builder.appendQueryParameter("method", "flickr.interestingness.getList"); //TBS
builder.appendQueryParameter("method", "flickr.photos.search");
builder.appendQueryParameter("tags","bikinigirl,lingerine");
//builder.appendQueryParameter("sort","relevance");
builder.appendQueryParameter("format", "json");
builder.appendQueryParameter("nojsoncallback", "1");
builder.appendQueryParameter("per_page", "10");
builder.appendQueryParameter("page", Integer.toString(currPage));
gsonObjRequest = new GsonRequest<FlickrResponsePhotos>(Request.Method.GET, builder.toString(),
FlickrResponsePhotos.class, null, new Response.Listener<FlickrResponsePhotos>() {
#Override
public void onResponse(FlickrResponsePhotos response) {
try {
if(response != null) {
parseFlickrImageResponse(response);
currPage++;
}
} catch (Exception e) {
e.printStackTrace();
showToast("JSON parse error");
}
stopProgress();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// Handle your error types accordingly.For Timeout & No connection error, you can show 'retry' button.
// For AuthFailure, you can re login with user credentials.
// For ClientError, 400 & 401, Errors happening on client side when sending api request.
// In this case you can check how client is forming the api and debug accordingly.
// For ServerError 5xx, you can do retry or handle accordingly.
if( error instanceof NetworkError) {
} else if( error instanceof ClientError) {
} else if( error instanceof ServerError) {
} else if( error instanceof AuthFailureError) {
} else if( error instanceof ParseError) {
} else if( error instanceof NoConnectionError) {
} else if( error instanceof TimeoutError) {
}
//mStaggeredView.onRefreshComplete();
stopProgress();
showToast(error.getMessage());
}
});
gsonObjRequest.setTag(TAG_REQUEST);
mVolleyQueue.add(gsonObjRequest);
}
private void showProgress() {
mProgress = ProgressDialog.show(this, "", "Loading...");
}
private void stopProgress() {
isLoading = false;
mListFooter.setVisibility(View.GONE);
mProgress.cancel();
}
private void showToast(String msg) {
Toast.makeText(FlickrActivity.this, msg, Toast.LENGTH_LONG).show();
}
#TargetApi(Build.VERSION_CODES.GINGERBREAD)
private void parseFlickrImageResponse(FlickrResponsePhotos response) {
FlickrGetImagesResponse photos = response.getPhotos(); //pass array of images to Picture Activity
String[] photoUrl;
photoUrl = new String[photos.getPhotos().size()];
for (int index = 0; index < photos.getPhotos().size(); index++) {
FlickrImage flkrImage = photos.getPhotos().get(index);
photoUrl[index]=flkrImage.getImageUrl();
StaggeredGridViewItem item = null;
item = new GridItem(this, flkrImage,photoUrl); //pass one image of index
mStaggeredView.addItem(item);
}
}
}
Below is the Queue Request program
public class StaggeredDemoApplication extends Application {
private static Context applicationContext;
private static RequestQueue mRequestQueue;
private static ImageLoader mImageLoader;
private static BitmapLruCache mBitmapCache;
public static boolean INIT_FLAG = true;
public void onCreate() {
super.onCreate();
applicationContext = this.getApplicationContext();
mRequestQueue = Volley.newRequestQueue(applicationContext);
long size = Runtime.getRuntime().maxMemory()/4;
mBitmapCache = new BitmapLruCache(50);//(int)size);
mImageLoader = new ImageLoader(mRequestQueue, mBitmapCache);
}
public static RequestQueue getRequestQueue() {
if (mRequestQueue != null) {
return mRequestQueue;
} else {
throw new IllegalStateException("RequestQueue not initialized");
}
}
public static ImageLoader getImageLoader() {
if (mImageLoader != null) {
return mImageLoader;
} else {
throw new IllegalStateException("ImageLoader not initialized");
}
}
}
The line that shows error is at FlickrActivity.java
mVolleyQueue = StaggeredDemoApplication.getRequestQueue();
Below is my manifest file
<?xml version="1.0" encoding="utf-8"?>
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity
android:name=".MainActivity"
android:label="#string/app_name"
android:theme="#style/AppTheme.NoActionBar">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".FlickrActivity"
android:label="#string/app_name"
android:theme="#style/AppTheme.NoActionBar">
<intent-filter>
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
<activity
android:name=".FullScreenImageActivity"
android:screenOrientation="portrait" />
</application>
Please advise and help...THank you!
Register your application class name in manifest to avoid Request not initialized issue
<application
android:name=".StaggeredDemoApplication"
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme">
I have the following class:
...
public class FragmentMapa extends Fragment {
/*
* Atributos
*/
private static String LOG_TAG = "FragmentMapa";
private HomeActivity homeActivity;
private GoogleMap mMapa;
private DrawerLayout mDrawer;
private ActionBarDrawerToggle mDrawerToggle;
private ListView mDrawerList;
private ListView mDrawerRightList;
private RelativeLayout mDrawerRelativeLayout;
private String[] mRightDrawerMenuTitles;
private ImageView mDiputacionLogo;
private IncidenciasFetchAsyncTask mFetchIncidenciasTask;
private Incidencias mIs;
private CamarasFetchAsyncTask mFetchCamarasTask;
private Camaras mCams;
private ViabilidadesInvernalesFetchAsyncTask mFetchViabilidadesInvernalesTask;
private ViabilidadesInvernales mVis;
private static LatLng POS_CENTRAL = new LatLng(43.243968,-2.896957);
private static LatLng limiteSurOesteBizkaia = new LatLng(42.895853,-3.594589);
private static LatLng limiteNorEsteBizkaia = new LatLng(43.540351,-2.180099);
private static final LatLngBounds BOUNDS = new LatLngBounds(limiteSurOesteBizkaia, limiteNorEsteBizkaia);
private ArrayList<Marker> markersIncidencias = new ArrayList<Marker>();
private ArrayList<Marker> markersObras = new ArrayList<Marker>();
private ArrayList<Marker> markersCamaras = new ArrayList<Marker>();
private ArrayList<Marker> markersViabilidadInvernal = new ArrayList<Marker>();
/*
* Métodos
*/
public FragmentMapa() {
}
#Override
public void onAttach (Activity activity) {
super.onAttach(activity);
homeActivity = (HomeActivity) activity;
mRightDrawerMenuTitles = getResources().getStringArray(R.array.mapa_submenu_options);
mDrawer = homeActivity.getmDrawer();
mDrawerRightList = homeActivity.getmDrawerRightList();
mDrawerRightList.setAdapter(new ArrayAdapter<String>(
homeActivity.getSupportActionBar().getThemedContext(),
R.layout.rightdrawer_map_list_item,
mRightDrawerMenuTitles
));
mDrawerRightList.setOnItemClickListener(new DrawerItemClickListener());
}
#Override
public void onCreate (Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView (LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.mapa, container, false);
setupMapIfNeeded();
return rootView;
}
private void setupMapIfNeeded() {
if( mMapa == null ){
SupportMapFragment smf = (SupportMapFragment) getChildFragmentManager().findFragmentById(R.id.mapaPrincipal);
if( smf != null ){
//Toast.makeText(getActivity(), "VAAAMOOSS", Toast.LENGTH_SHORT).show();
mMapa = smf.getMap();
}/*else{
Toast.makeText(getActivity(), "smf es null...", Toast.LENGTH_SHORT).show();
}*/
if( mMapa != null ){
setupMap();
}
}
}
private void setupMap() {
//Toast.makeText(getActivity(), "A configurar el mapa!!", Toast.LENGTH_SHORT).show();
CameraPosition camPos;
camPos = new CameraPosition.Builder()
.target(POS_CENTRAL)
.zoom((float) 9.5)
.build();
final CameraUpdate camUpd =
CameraUpdateFactory.newCameraPosition(camPos);
mMapa.animateCamera(camUpd);
mMapa.setOnCameraChangeListener(new OnCameraChangeListener() {
#Override
public void onCameraChange(CameraPosition newPos) {
float maxZoom = 17.0f;
if( !BOUNDS.contains(newPos.target) ){
//Mover la cámara al centro si se
//va más allá de los límites
mMapa.animateCamera(camUpd);
}
if(newPos.zoom > maxZoom){
mMapa.animateCamera(CameraUpdateFactory.zoomTo(maxZoom));
}
}
});
mMapa.setOnInfoWindowClickListener( new OnInfoWindowClickListener(){
public void onInfoWindowClick(Marker aMarker) {
Toast.makeText(getActivity(), "info window pulsado", Toast.LENGTH_SHORT).show();
if( markersCamaras.contains(aMarker) ){
Camara c = mCams.getCamaraByCoord(aMarker.getPosition());
homeActivity.showCameraFragment(c);
}
}
});
}
#Override
public void onActivityCreated (Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
}
#Override
public void onViewStateRestored (Bundle savedInstanceState) {
super.onViewStateRestored(savedInstanceState);
}
#Override
public void onStart () {
super.onStart();
}
#Override
public void onResume () {
super.onResume();
}
#Override
public void onPause () {
super.onPause();
}
#Override
public void onStop () {
super.onStop();
}
#Override
public void onDestroyView () {
super.onDestroyView();
}
#Override
public void onDestroy () {
super.onDestroy();
}
#Override
public void onDetach () {
super.onDetach();
}
/* The click listener for ListView in the navigation drawer */
private class DrawerItemClickListener implements OnItemClickListener {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
final int thePos = position;
mDrawer.setDrawerListener( new DrawerLayout.SimpleDrawerListener(){
#Override
public void onDrawerClosed(View drawerView) {
boolean wasChecked = !mDrawerRightList.isItemChecked(thePos);
//Toast.makeText(homeActivity, "Item pulsado: " + wasChecked, Toast.LENGTH_SHORT).show();
mDrawerRightList.setItemChecked(thePos, !wasChecked);
switch (thePos) {
case 0:
//Incidencias
//Toast.makeText(homeActivity, "Incidencias", Toast.LENGTH_SHORT).show();
if(!wasChecked){
//Toast.makeText(homeActivity, "Incidencias estaba sin pulsar", Toast.LENGTH_SHORT).show();
getIncidenciasObras();
introducirIncidencias();
}else{
//Toast.makeText(homeActivity, "Incidencias estaba pulsado", Toast.LENGTH_SHORT).show();
removeIncidenciasMarkers();
}
break;
case 1:
//Obras
//Toast.makeText(homeActivity, "Obras", Toast.LENGTH_SHORT).show();
if(!wasChecked){
//Toast.makeText(homeActivity, "Obras estaba sin pulsar", Toast.LENGTH_SHORT).show();
getIncidenciasObras();
introducirObras();
}else{
//Toast.makeText(homeActivity, "Obras estaba pulsado", Toast.LENGTH_SHORT).show();
removeObrasMarkers();
}
break;
case 2:
//Cámaras
//Toast.makeText(homeActivity, "Cámaras", Toast.LENGTH_SHORT).show();
if(!wasChecked) {
getCamaras();
introducirCamaras();
}else
removeCamarasMarkers();
break;
case 3:
//Viabilidad invernal
//Toast.makeText(homeActivity, "Viabilidad invernal", Toast.LENGTH_SHORT).show();
if(!wasChecked){
getViabilidadesInvernales();
introducirViabilidadInvernal();
}else
removeViabilidadInvernalMarkers();
break;
default:
//Toast.makeText(homeActivity, "Default", Toast.LENGTH_SHORT).show();
break;
}
}
});
if(mDrawer.isDrawerOpen(Gravity.END))
mDrawer.closeDrawer(mDrawerRightList);
}
}
private void getViabilidadesInvernales(){
mVis = ViabilidadesInvernales.getInstance();
if(mVis.isEmptyViabilidadesInvernales()){
mFetchViabilidadesInvernalesTask = new ViabilidadesInvernalesFetchAsyncTask(homeActivity);
try {
mVis = mFetchViabilidadesInvernalesTask.execute("es").get();
} catch (InterruptedException e) {
Log.e(LOG_TAG, "Error InterruptedException: " + e.getMessage());
e.printStackTrace();
} catch (ExecutionException e) {
Log.e(LOG_TAG, "Error ExecutionException: " + e.getMessage());
e.printStackTrace();
}
}
}
...
private void introducirViabilidadInvernal() {
if(markersViabilidadInvernal.isEmpty()){
Marker aMarker;
for (ViabilidadInvernal vi : mVis.getViabilidades()) {
String estado = "";
BitmapDescriptor icon;
if(vi.getEstado() == PuertoEstado.ABIERTO){
estado = getResources().getString(R.string.mapa_puerto_abierto);
icon = BitmapDescriptorFactory.fromResource(R.drawable.marker_puertoabierto);
}else{
//vi.getEstado() == PuertoEstado.CERRADO
estado = getResources().getString(R.string.mapa_puerto_cerrado);
icon = BitmapDescriptorFactory.fromResource(R.drawable.marker_puertocerrado);
}
aMarker = mMapa.addMarker(new MarkerOptions()
.position(vi.getCoord())
.title(vi.getT())
.snippet(estado)
.icon(icon));
markersViabilidadInvernal.add(aMarker);
}
}
}
private void removeViabilidadInvernalMarkers() {
for(Marker aMarker : markersViabilidadInvernal){
aMarker.remove();
}
}
...
private class ViabilidadesInvernalesFetchAsyncTask extends AsyncTask<String, Void, ViabilidadesInvernales>{
private ProgressDialog mPd;
private HomeActivity ownerActivity;
private Context context;
private Exception exceptionToBeThrown;
public ViabilidadesInvernalesFetchAsyncTask(Activity activity){
this.ownerActivity = (HomeActivity) activity;
context = activity;
this.exceptionToBeThrown = null;
mPd = new ProgressDialog(context);
}
#Override
protected void onPreExecute() {
super.onPreExecute();
mPd.setTitle("cargando");
mPd.setMessage("miralo");
//mPd.setTitle(getResources().getString(R.string.mapa_cargando_titulo));
//mPd.setMessage(getResources().getString(R.string.mapa_cargando, getResources().getString(R.string.mapa_cargando_elemento_viabilidad)));
mPd.setCancelable(false);
mPd.setIndeterminate(true);
mPd.setProgressStyle(ProgressDialog.STYLE_SPINNER);
mPd.show();
}
#Override
protected ViabilidadesInvernales doInBackground(String... params) {
String idioma = params[0];
if(!idioma.equalsIgnoreCase("es") && !idioma.equalsIgnoreCase("eu")){
idioma = "es";
}
SystemClock.sleep(5000);
ViabilidadesInvernalesParser vip = new ViabilidadesInvernalesParser();
ViabilidadesInvernales lasViabilidades = vip.parse(idioma);
Log.d(LOG_TAG, lasViabilidades.toString());
ViabilidadesInvernales vis = ViabilidadesInvernales.getInstance();
return vis;
}
#Override
protected void onPostExecute(ViabilidadesInvernales vis) {
super.onPostExecute(vis);
mVis = vis;
if(mPd != null){
mPd.dismiss();
}
// Check if exception exists.
//if (exceptionToBeThrown != null) {
//TODO
//ownerActivity.handleXXX();
//throw exceptionToBeThrown;
//}
}
}
....
}
The aim is to show a Dialog (ProgressDialog) when an AsyncTask is executed, so that the Dialog remains in front of the UI for a moment and then, the map (which was being shown previously) returns to the front. More exactly, you launch the application (home activity), you open the left drawer, press Mapa and go to the current fragment. An empty map is shown. You open the right drawer and press a button. Just afterwards, the process of launching AsyncTask is executed (and my desired ProgressDialog).
I don't know why, but the ProgressDialog is not being shown, but I have realised that the "sleep" process is ok (and the AsyncTask is executed properly every time).
Can anybody lend me a hand?
PS: My main activity (HomeActivity) launches fragments. The main activity has two drawers: left drawer is always visible, and right drawer is only visible when launching the FragmentMapa (the fragment I'm showing you right now). Might this issue be due to the Drawer behaviour?
THANK YOU SO MUCH
SOLVED. Anyone who faces this problem, check the following post: https://stackoverflow.com/a/3291713/828551.
You must create an interface, create an instance of it within the AsyncTask and implement the interface the main class where you launch the AsyncTask.