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">
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.
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.
Hello I tried to initialize Presenter object into my fragment but Its throw ClassCastException
E/AndroidRuntime: FATAL EXCEPTION: main Process: com.varshaawebteam.tp_comment_mvp, PID: 22672
java.lang.ClassCastException: com.varshaawebteam.tp_comment_mvp.HomeActivity.HomeActivity cannot be cast to com.varshaawebteam.tp_comment_mvp.TournamentListActvity.Presenter.ITournamentPresenter
at com.varshaawebteam.tp_comment_mvp.TournamentListActvity.TournamentListFragment.onCreateView(TournamentListFragment.java:51)
at android.support.v4.app.Fragment.performCreateView(Fragment.java:2192)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1299)
at android.support.v4.app.FragmentManagerImpl.moveFragmentToExpectedState(FragmentManager.java:1528)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1595)
at android.support.v4.app.BackStackRecord.executeOps(BackStackRecord.java:758)
at android.support.v4.app.FragmentManagerImpl.executeOps(FragmentManager.java:2363)
at android.support.v4.app.FragmentManagerImpl.executeOpsTogether(FragmentManager.java:2149)
at android.support.v4.app.FragmentManagerImpl.optimizeAndExecuteOps(FragmentManager.java:2103)
at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:2013)
at android.support.v4.app.FragmentManagerImpl$1.run(FragmentManager.java:710)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
HomeActivity.java (Main Class)
public class HomeActivity extends AppCompatActivity implements HomeViewInterface, IHomePresenter {
SlidingPaneLayout slide_pane;
HomePresenter homePresenter;
private Toolbar mToolbar;
SharedPreferences pref_login;
Gson gson;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
slide_pane = (SlidingPaneLayout) findViewById(R.id.slide_pane);
homePresenter = new HomePresenter(this, this, this);
mToolbar = (Toolbar) findViewById(R.id.toolbar);
if (mToolbar != null) {
setSupportActionBar(mToolbar);
}
mToolbar.setTitle("My Games");
pref_login = getSharedPreferences(Pref_Data.PREF_LOGIN, MODE_PRIVATE);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
gson = new Gson();
mToolbar.setNavigationIcon(R.drawable.ic_drawer);
mToolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (slide_pane.isOpen()) {
slide_pane.closePane();
} else {
slide_pane.openPane();
}
}
});
slide_pane = (SlidingPaneLayout) findViewById(R.id.slide_pane);
drawer_fragment menu = new drawer_fragment();
getSupportFragmentManager().beginTransaction().add(R.id.ll_drawer, menu).commit();
homePresenter.getdrawerselection(0);
}
#Override
public void getdrawerselection(int i) {
}
#Override
public void openmygamefragment() {
}
#Override
public void opentournamentfragment() {
}
#Override
public void setdrawerselection(int i) {
try {
slide_pane.closePane();
} catch (Exception e) {
e.printStackTrace();
}
if (i == 0) {
setTitle("My Game");
homePresenter.openmygamefragment();
Log.e("Game:-", "Game");
} else if (i == 1) {
setTitle("Tournament List");
Log.e("Tournament:-", "Tournament");
homePresenter.opentournamentfragment();
} else if (i == 2) {
Toast.makeText(this, "logout", Toast.LENGTH_SHORT).show();
}
}
#Override
public void setmygamefragment() {
}
#Override
public void settournamnetfragment() {
TournamentListFragment tournament = new TournamentListFragment();
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.fragment_container, tournament, "frag1")
.addToBackStack("2")
.commit();
}
}
TournamentPresenter.java (Presenter)
public class TournamentPresenter implements ITournamentPresenter {
private final Services services;
private final android.content.Context context;
private final ITournamentPresenter mListener;
private final ITournamentView tournamentview;
private Dialog progressDialog;
ArrayList<TournamentRes_data> tournamentResDatas = new ArrayList<TournamentRes_data>();
public TournamentPresenter(ITournamentPresenter listener, ITournamentView tournamentView, Context context) {
this.mListener = listener;
this.context = context;
this.services = new Services();
this.tournamentview = tournamentView;
}
#Override
public void tournamentready(Response<TournamentRes> response) {
}
public void gettournamentlistcall(double lat, double longii) {
progressDialog = new Dialog(context);
progressDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
progressDialog.getWindow().setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT));
progressDialog.setContentView(R.layout.progress_bar_custom);
progressDialog.setCancelable(true);
progressDialog.show();
services.getAPI()
.getList_Results(lat, longii)
.enqueue(new Callback<TournamentRes>() {
#Override
public void onResponse(Call<TournamentRes> call, Response<TournamentRes> response) {
if (!response.body().getDATA().isEmpty()) {
mListener.tournamentready(response);
}
}
#Override
public void onFailure(Call<TournamentRes> call, Throwable t) {
call.cancel();
progressDialog.dismiss();
Toast.makeText(context, "Server Error", Toast.LENGTH_SHORT).show();
}
});
}
}
and finally this is my fragment where I am getting error of cast exceptions
TournamentListFragment.java (View)
public class TournamentListFragment extends Fragment implements ITournamentPresenter, ITournamentView {
GPSTracker gps;
ListView lvTournaments;
private Dialog progressDialog;
TextView tvNoData;
Tournament_List_Adapter tournament_list_adapter;
TournamentPresenter tournamnetpresenter;
ArrayList<TournamentRes_data> tournamentResDatas = new ArrayList<TournamentRes_data>();
Context context;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
final View rootView = inflater.inflate(R.layout.frag_tournament, container, false);
gps = new GPSTracker(getActivity());
context = getActivity();
lvTournaments = (ListView) rootView.findViewById(R.id.listview);
tvNoData = (TextView) rootView.findViewById(R.id.listview_data);
tournamnetpresenter = new TournamentPresenter((ITournamentPresenter) getActivity(), (ITournamentView) getActivity(), getActivity());
Toast.makeText(getActivity(), "Tournament", Toast.LENGTH_SHORT).show();
if (gps.canGetLocation()) {
tournamnetpresenter.gettournamentlistcall(gps.getLatitude(), gps.getLongitude());
} else {
gps.showSettingsAlert();
}
return rootView;
}
#Override
public void tournamentready(Response<TournamentRes> response) {
if (!response.body().getDATA().isEmpty()) {
tournamentResDatas.addAll(response.body().getDATA());
if (tournamentResDatas.size() == 0) {
tvNoData.setVisibility(View.VISIBLE);
tvNoData.bringToFront();
} else {
tvNoData.setVisibility(View.GONE);
}
if (tournament_list_adapter != null) {
lvTournaments.setAdapter(tournament_list_adapter);
} else {
tournament_list_adapter = new Tournament_List_Adapter(getActivity(), tournamentResDatas);
lvTournaments.setAdapter(tournament_list_adapter);
}
}
}
#Override
public void getlistready() {
}
}
Please review my code and help me with concern. my question is simple I am not able to initialize Presenter in Fragment class.
The error because your HomeActivity does not implement ITournamentPresenter and TournamentListFragment does.
You should try to change this line to this:
tournamnetpresenter = new TournamentPresenter(this, this, getContext());
I looked into other threads, but found no solution for this, except it was originally detected for API 21, i.e. Lollipop. While, I am facing this issue in Lollipop as well as post-Lollipop versions.
I am using YouTube Data API, to display the content of the particular channel in my app. And I am successful in getting the response from the API and displaying content in the RecyclerView.
But when I try to load the video in the YouTubeSupportFragment, the app crashes while invoking the cueVideo() of YouTubeSupportFragment with the following exception.
Note: I am using the latest version (1.2.2) of the YouTube API.
Here's the exception thrown by the YouTube Player:
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.acme.youtubeplayer, PID: 16757
java.lang.IllegalArgumentException: Service Intent must be explicit: Intent { act=com.google.android.youtube.api.service.START }
at android.app.ContextImpl.validateServiceIntent(ContextImpl.java:2101)
at android.app.ContextImpl.bindServiceCommon(ContextImpl.java:2225)
at android.app.ContextImpl.bindService(ContextImpl.java:2203)
at android.content.ContextWrapper.bindService(ContextWrapper.java:560)
at com.google.android.youtube.player.internal.r.e(Unknown Source)
at com.google.android.youtube.player.YouTubePlayerView.a(Unknown Source)
at com.google.android.youtube.player.YouTubePlayerSupportFragment.a(Unknown Source)
at com.google.android.youtube.player.YouTubePlayerSupportFragment.onCreateView(Unknown Source)
at android.support.v4.app.Fragment.performCreateView(Fragment.java:2192)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1299)
at android.support.v4.app.FragmentManagerImpl.moveFragmentToExpectedState(FragmentManager.java:1528)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1595)
at android.support.v4.app.BackStackRecord.executeOps(BackStackRecord.java:758)
at android.support.v4.app.FragmentManagerImpl.executeOps(FragmentManager.java:2363)
at android.support.v4.app.FragmentManagerImpl.executeOpsTogether(FragmentManager.java:2149)
at android.support.v4.app.FragmentManagerImpl.optimizeAndExecuteOps(FragmentManager.java:2103)
at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:2013)
at android.support.v4.app.FragmentManagerImpl$1.run(FragmentManager.java:710)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:145)
at android.app.ActivityThread.main(ActivityThread.java:7007)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1404)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1199)
Here's my ListFragment.java, where the app crashes:
public class ListFragment extends android.support.v4.app.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 static final String KEY_TRANSITION_EFFECT = "transition_effect";
private static final int RECOVERY_REQUEST = 1;
private int mCurrentTransitionEffect = JazzyHelper.HELIX;
private JazzyRecyclerViewScrollListener jazzyScrollListener;
YouTubePlayerView youtube_player;
MyPlayerStateChangeListener playerStateChangeListener;
MyPlaybackEventListener playbackEventListener;
YouTubePlayer playerFragment;
JSONObject jObjectAPI;
JSONArray jArrayResponse;
int listSize;
JSONObject jObjectResponse, jObject;
public static final String YOUTUBE_API = "https://www.googleapis.com/youtube/v3/search?key=" + Config.YOUTUBE_API_KEY + "&channelId=" + Config.YOUTUBE_CHANNEL_ID + "&part=snippet,id&order=date&maxResults=20";
//Local Variables
RecyclerView recyclerView;
Button seekToButton;
YouTubePlayerSupportFragment youTubePlayerFragment;
String[] thumbnailVideo;
String[] titleVideo;
String[] descriptionVideo;
String[] idVideo;
int itemLayoutRes = R.layout.item;
boolean isStaggered = false;
private OnFragmentInteractionListener mListener;
private ProgressDialog pDialog;
public ListFragment() {
// 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 ListFragment.
*/
// TODO: Rename and change types and number of parameters
public static ListFragment newInstance(String param1, String param2) {
ListFragment fragment = new ListFragment();
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);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_list, container, false);
// Inflate the layout for this fragment
recyclerView = (RecyclerView) view.findViewById(R.id.rv_video_list);
recyclerView.setLayoutManager(createLayoutManager(itemLayoutRes, isStaggered));
recyclerView.setHasFixedSize(false);
new GetList().execute();
return view;
}
// 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;
}
}
#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);
}
private RecyclerView.LayoutManager createLayoutManager(int itemLayoutRes, boolean isStaggered) {
if (itemLayoutRes == R.layout.item) {
return new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false);
} else {
if (isStaggered) {
return new StaggeredGridLayoutManager(1, StaggeredGridLayoutManager.VERTICAL);
} else {
return new GridLayoutManager(getActivity(), 1);
}
}
}
private void setupJazziness(int effect) {
mCurrentTransitionEffect = effect;
jazzyScrollListener.setTransitionEffect(mCurrentTransitionEffect);
}
private void showMessage(String message) {
Toast.makeText(getActivity(), message, Toast.LENGTH_LONG).show();
}
public final class MyPlaybackEventListener implements YouTubePlayer.PlaybackEventListener {
#Override
public void onPlaying() {
// Called when playback starts, either due to user action or call to play().
showMessage("Playing");
}
#Override
public void onPaused() {
// Called when playback is paused, either due to user action or call to pause().
showMessage("Paused");
}
#Override
public void onStopped() {
// Called when playback stops for a reason other than being paused.
showMessage("Stopped");
}
#Override
public void onBuffering(boolean b) {
// Called when buffering starts or ends.
}
#Override
public void onSeekTo(int i) {
// Called when a jump in playback position occurs, either
// due to user scrubbing or call to seekRelativeMillis() or seekToMillis()
}
}
public final class MyPlayerStateChangeListener implements YouTubePlayer.PlayerStateChangeListener {
#Override
public void onLoading() {
// Called when the youtube_player is loading a video
// At this point, it's not ready to accept commands affecting playback such as play() or pause()
playerFragment.loadVideo(idVideo.toString());
}
#Override
public void onLoaded(String s) {
// Called when a video is done loading.
// Playback methods such as play(), pause() or seekToMillis(int) may be called after this callback.
playerFragment.play();
}
#Override
public void onAdStarted() {
// Called when playback of an advertisement starts.
playerFragment.pause();
}
#Override
public void onVideoStarted() {
// Called when playback of the video starts.
}
#Override
public void onVideoEnded() {
// Called when the video reaches its end.
if (playerFragment.hasNext()) {
playerFragment.next();
}
}
#Override
public void onError(YouTubePlayer.ErrorReason errorReason) {
// Called when an error occurs.
Toast.makeText(getActivity(), "Please check your Internet Connection", Toast.LENGTH_LONG).show();
}
}
public static JSONObject getJSONObjectFromURL(String urlString) throws IOException, JSONException {
HttpURLConnection urlConnection = null;
URL url = new URL(urlString);
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.setReadTimeout(10000 /* milliseconds */);
urlConnection.setConnectTimeout(15000 /* milliseconds */);
urlConnection.setDoOutput(true);
urlConnection.connect();
BufferedReader br = new BufferedReader(new InputStreamReader(url.openStream()));
char[] buffer = new char[1024];
String jsonString;
StringBuilder sb = new StringBuilder();
String line;
while ((line = br.readLine()) != null) {
sb.append(line + "\n");
}
br.close();
jsonString = sb.toString();
System.out.println("JSON: " + jsonString);
return new JSONObject(jsonString);
}
private class GetList extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(getActivity());
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(Void... params) {
try {
jObjectAPI = getJSONObjectFromURL(YOUTUBE_API);
Log.e("response", String.valueOf(jObjectAPI));
jArrayResponse = jObjectAPI.getJSONArray("items");
Log.e("array", String.valueOf(jArrayResponse));
listSize = jArrayResponse.length();
thumbnailVideo = new String[listSize];
titleVideo = new String[listSize];
descriptionVideo = new String[listSize];
idVideo = new String[listSize];
for (int i = 0; i < listSize; i++) {
jObjectResponse = jArrayResponse.getJSONObject(i);
thumbnailVideo[i] = jObjectResponse.getJSONObject("snippet").getJSONObject("thumbnails")
.getJSONObject("default")
.optString("url");
titleVideo[i] = jObjectResponse.getJSONObject("snippet").optString("title");
if (!(jObjectResponse.getJSONObject("snippet").optString("description").equals(""))
&& !(jObjectResponse.getJSONObject("snippet").optString("description").equals(null))
&& (jObjectResponse.getJSONObject("snippet").optString("description").length() > 0)) {
descriptionVideo[i] = jObjectResponse.getJSONObject("snippet").optString("description");
} else {
descriptionVideo[i] = "No Description Found";
}
idVideo[i] = jObjectResponse.getJSONObject("id").optString("videoId");
}
} catch (JSONException e) {
e.printStackTrace();
Log.e("JSON Exception", e.toString());
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// Dismiss the progress dialog
if (pDialog.isShowing())
pDialog.dismiss();
/**
* Updating parsed JSON data into ListView
**/
recyclerView.setAdapter(new VideoListAdapter(thumbnailVideo, titleVideo, descriptionVideo, idVideo, itemLayoutRes, getActivity()));
jazzyScrollListener = new JazzyRecyclerViewScrollListener();
recyclerView.setOnScrollListener(jazzyScrollListener);
setupJazziness(R.anim.slide_left_in);
playerStateChangeListener = new MyPlayerStateChangeListener();
playbackEventListener = new MyPlaybackEventListener();
youTubePlayerFragment = new YouTubePlayerSupportFragment();
youTubePlayerFragment.initialize(Config.YOUTUBE_API_KEY, new YouTubePlayer.OnInitializedListener() {
#Override
public void onInitializationSuccess(YouTubePlayer.Provider provider, YouTubePlayer player, boolean wasRestored) {
playerFragment = player;
player.setPlayerStateChangeListener(playerStateChangeListener);
player.setPlaybackEventListener(playbackEventListener);
if (!wasRestored) {
player.cueVideos(Arrays.asList(idVideo));
}
}
#Override
public void onInitializationFailure(YouTubePlayer.Provider arg0, YouTubeInitializationResult errorReason) {
// TODO Auto-generated method stub
if (errorReason.isUserRecoverableError()) {
errorReason.getErrorDialog(getActivity(), RECOVERY_REQUEST).show();
} else {
String error = String.format(getString(R.string.player_error), errorReason.toString());
Toast.makeText(getActivity(), error, Toast.LENGTH_LONG).show();
}
}
});
android.support.v4.app.FragmentManager fmPlayer = getFragmentManager();
FragmentTransaction transaction = fmPlayer.beginTransaction();
transaction.replace(R.id.youtube_player_view, youTubePlayerFragment);
transaction.commit();
}
}
}
Here's my Adapter class:
public class VideoListAdapter extends Adapter<VideoListAdapter.VideoListViewHolder> {
private List<String> thumbnail;
private List<String> title;
private List<String> desc;
private List<String> id;
private int itemLayoutRes;
private static Activity mContext;
public VideoListAdapter(String[] videoThumbnail, String[] videoTitle, String[] videoDesc, String[] videoId, int itemLayoutRes, Activity context) {
this.thumbnail = Arrays.asList(videoThumbnail);
this.title = Arrays.asList(videoTitle);
this.desc = Arrays.asList(videoDesc);
this.id = Arrays.asList(videoId);
this.itemLayoutRes = itemLayoutRes;
this.mContext = context;
}
#Override
public VideoListAdapter.VideoListViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from(parent.getContext());
View view;
view = inflater.inflate(itemLayoutRes, parent, false);
return new VideoListViewHolder(view);
}
#Override
public void onBindViewHolder(final VideoListViewHolder holder, final int position) {
Picasso.with(mContext).load(thumbnail.get(position)).into(new Target() {
#Override
public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) {
// loaded bitmap is here (bitmap)
holder.thumbnailVideo.setImageBitmap(bitmap);
}
#Override
public void onBitmapFailed(Drawable errorDrawable) {
Toast.makeText(mContext, "Image load failed", Toast.LENGTH_LONG).show();
}
#Override
public void onPrepareLoad(Drawable placeHolderDrawable) {
}
});
Log.e("thumbnail Adapter", String.valueOf(thumbnail.get(position)));
holder.titleVideo.setText(title.get(position));
holder.descVideo.setText(desc.get(position));
holder.idVideo = id.get(position);
}
#Override
public int getItemCount() {
return title.size();
}
#Override
public int getItemViewType(int position) {
// return isStaggered ? position % 2 : 0;
return position;
}
public static class VideoListViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
final TextView titleVideo, descVideo;
final YouTubeThumbnailView thumbnailVideo;
String idVideo;
public VideoListViewHolder(View view) {
super(view);
thumbnailVideo = (YouTubeThumbnailView) view.findViewById(R.id.thumbnail_video);
titleVideo = (TextView) view.findViewById(R.id.title_video);
descVideo = (TextView) view.findViewById(R.id.desc_video);
}
#Override
public void onClick(View v) {
Intent intent = new Intent(mContext, YouTubeBaseActivity.class);
//Intent intent = YouTubeStandalonePlayer.createVideoIntent((Activity) v.getContext(), Config.YOUTUBE_API_KEY, idVideo);
v.getContext().startActivity(intent);
}
}
}
Finally I got rid of this issue. I replaced the YouTubeSupportFragment with YouTubeBaseActivity and used YouTubePlayerView to play the video.
In other words, I used an Activity extending YouTubeBaseActivity to play the video instead of a Fragment.
Hope it helps someone getting the issue.
I want to fetch some data from website and i am using jsoup for that.But there is a problem, when i use jsoup in an asynctask it work well but i am going to this process via a navigation view and when i click to an item it starts but navigation view is not closing and progress bar is not working,so i coulnd't know what should i do.
The question is:
Should i try to use different method like(threads , asynctaskloader etc.) or is there a way to prevent these problems.
Here is my onCreateView method of fragment :
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState)
{
View rootView = inflater.inflate(R.layout.tab_fragment_container, container, false);
newspapers = readFromFile("20 Name.txt");
newspapersPath = readFromFile("20 Path.txt");
FetchingInstantNews fetchingInstantNews = new FetchingInstantNews((AppCompatActivity)getActivity(),newspapers,newspapersPath);
try
{
cardItems = fetchingInstantNews.execute().get();
}
catch (Exception ex)
{
ex.printStackTrace();
}
mRecylerView = (RecyclerView)rootView.findViewById(R.id.recyclerView);
setupRecyclerView(mRecylerView);
return rootView;
}
Here is my asynctask class:
public class FetchingInstantNews extends AsyncTask<Void,Void,ArrayList<CardItem>>
{
private String[] newspapers,newspapersPath;
private AppCompatActivity activity;
private ProgressDialog progressDialog;
private Document doc,innerDoc;
private Elements[] elementses = new Elements[14];
private static String site,innerSite;
public FetchingInstantNews(AppCompatActivity activity,String[] newspapers,String[] newspapersPath)
{
this.newspapers = newspapers;
this.newspapersPath = newspapersPath;
this.activity = activity;
}
#Override
protected void onPreExecute()
{
super.onPreExecute();
progressDialog = new ProgressDialog(activity);
progressDialog.setTitle("Haberler");
progressDialog.setMessage("Haberleriniz Hazırlanıyor..");
progressDialog.setIndeterminate(false);
}
#Override
protected ArrayList<CardItem> doInBackground(Void... voids)
{
ArrayList<CardItem> cardViews = new ArrayList<>();
for(int i=0;i<newspapers.length;i++)
{
site = newspapersPath[i];
try
{
doc = Jsoup.connect(site).timeout(120*1000)
.userAgent("Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:25.0) Gecko/20100101 Firefox/25.0")
.referrer("http://www.google.com")
.get();
elementses[0] = doc.select("div[class=wrapper-new]");
elementses[1] = elementses[0].select("section[id=top]");
elementses[2] = elementses[1].select("section[class=manset-wrap c]");
elementses[3] = elementses[2].select("div[class=site-box box box-list]");
elementses[4] = elementses[3].select("div[class=us]");
elementses[5] = elementses[4].select("div[class=sol]");
elementses[6] = elementses[5].select("div[class=manset]");
elementses[7] = elementses[6].select("div[class=m-item]");
elementses[8] = elementses[7].select("article");
int perCount=0;
for (Element articleItem : elementses[8])
{
if(perCount >= 3)
{
break;
}
CardItem cardItem = new CardItem();
elementses[9] = articleItem.select("a");
cardItem.setPubDate(elementses[9].select("meta[itemprop=datePublished]").attr("content")); //Date
cardItem.setDescription(elementses[9].select("meta[itemprop=headline]").attr("content")); // desc
cardItem.setThumbnailUrl(elementses[9].select("img").attr("data-src")); // thumb
try
{
elementses[10] = elementses[6].select("nav");
elementses[11] = elementses[10].select("div[class=sol]").select("span");
cardItem.setName(elementses[11].text().replace("Son","")); // title
}
catch (Exception ex)
{
ex.printStackTrace();
}
try
{
innerSite = elementses[9].attr("href");
innerDoc = Jsoup.connect(innerSite).timeout(100*1000)
.userAgent("Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:25.0) Gecko/20100101 Firefox/25.0")
.referrer("http://www.google.com")
.get();
elementses[12] = innerDoc.select("div[class=flexwrap]");
elementses[13] = elementses[12].select("iframe");
cardItem.setPath(elementses[13].attr("src"));
}
catch (Exception ex)
{
ex.printStackTrace();
}
perCount++;
cardViews.add(cardItem);
}
}
catch (Exception ex)
{
ex.printStackTrace();
}
}
return cardViews;
}
#Override
protected void onPostExecute(ArrayList<CardItem> aVoid)
{
progressDialog.dismiss();
super.onPostExecute(aVoid);
}
}
Here is my Main Activity:
private Toolbar mToolbar;
private DrawerLayout mDrawerLayout;
private NavigationView mNavigationView;
private ActionBarDrawerToggle mActionBarDrawerToggle;
private RelativeLayout mStockLayout;
private TabLayout mTabLayout;
private FragmentManager mFragmentManager;
private FragmentTransaction mFragmentTransaction;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mToolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(mToolbar);
getSupportActionBar().setHomeButtonEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
mFragmentManager = getSupportFragmentManager();
mFragmentTransaction = mFragmentManager.beginTransaction();
mDrawerLayout = (DrawerLayout)findViewById(R.id.drawer_layout);
mNavigationView = (NavigationView) findViewById(R.id.navigation_view);
if (mNavigationView != null)
{
setupDrawerContent(mNavigationView);
}
mActionBarDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout, mToolbar, R.string.app_name, R.string.app_name) {
#Override
public void onDrawerOpened(View drawerView)
{
super.onDrawerOpened(drawerView);
}
#Override
public void onDrawerClosed(View drawerView)
{
super.onDrawerClosed(drawerView);
}
};
mFragmentTransaction.replace(R.id.frame,new TabFragmentsContainer());
mDrawerLayout.setDrawerListener(mActionBarDrawerToggle);
mActionBarDrawerToggle.syncState();
}
private void setupDrawerContent(NavigationView navigationView)
{
navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener()
{
#Override
public boolean onNavigationItemSelected(MenuItem menuItem)
{
menuItem.setChecked(true);
switch (menuItem.getItemId())
{
case R.id.anasayfa:
mDrawerLayout.closeDrawers();
changeFragment(new FragmentsContainer(),true);
break;
case R.id.anlık:
if(mDrawerLayout.isDrawerOpen(mNavigationView))
{
mDrawerLayout.closeDrawer(mNavigationView);
}
else
{
mDrawerLayout.openDrawer(mNavigationView);
}
changeFragment(new TabFragmentsContainer(),false);
break;
case R.id.ilkler:
Log.d("Frag","İlkler");
break;
case R.id.ulusal:
Log.d("Frag","Ulusal");
break;
}
return true;
}
});
}
Thanks in advance!.
Here's the thing, you really should not use your AsyncTask with get(). The get() method will block your UI thread which is likely the reason why your progress bar is not displayed and navigation drawer not closing.
Instead you should implement a callback mechanism, that is, tell your AsyncTask to call you back when the task is finished. Below is an example for your case:
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState)
{
View rootView = inflater.inflate(R.layout.tab_fragment_container, container, false);
newspapers = readFromFile("20 Name.txt");
newspapersPath = readFromFile("20 Path.txt");
FetchingInstantNews fetchingInstantNews = new FetchingInstantNews((AppCompatActivity)getActivity(),newspapers,newspapersPath);
try
{
fetchingInstantNews.execute(); // do not call get()
}
catch (Exception ex)
{
ex.printStackTrace();
}
cardItems = new ArrayList<CardItems>(); // initialise recycler view with an empty list for now, because AsyncTask will not finish before you setup RecyclerView.
mRecylerView = (RecyclerView)rootView.findViewById(R.id.recyclerView);
setupRecyclerView(mRecylerView);
return rootView;
}
// This method is called AFTER asynctask is finished
public void stepsAfterAsyncTask(ArrayList<CardItem> result)
{
cardItems = result;
// Re-initialise adapter with result data
mRecylerView = (RecyclerView)rootView.findViewById(R.id.recyclerView);
setupRecyclerView(mRecylerView);
// make sure you notify adapter to use the new cardItems
mRecylerView.getAdapter().notifyDataSetChanged();
}
Your AsyncTask:
public class FetchingInstantNews extends AsyncTask<Void,Void,ArrayList<CardItem>>
{
private String[] newspapers,newspapersPath;
//....
//....
#Override
protected void onPostExecute(ArrayList<CardItem> result)
{
activity.stepsAfterAsyncTask(result); // call back your activity with the result
progressDialog.dismiss();
super.onPostExecute(result);
}
}
I don't know what your setupRecyclerView method looks like, so you will need to make changes according to your needs.