How to Initialize Presenter In Fragment using MVP structure of Android - android

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());

Related

How to call a specific Fragment's getActivity()?

My problem is that i have a recyclerview implemented on a fragment that uses Room. RecyclerView, Adapter and Database need to be together in one class (i guess).
My problem is that if I put them into StudentActivity,
recyclerView = findViewById(R.id.SubjectRecyclerView);
will be null, because the Fragment won't be available by the time this function called.
If i put them into StudentSubjectsFragment,
everything would be good, but NewSubjectDialogFragment tells me that StudentActivity needs to implement NewSubjectDialogFragment because of this:
private NewSubjectDialogListener listener;
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
FragmentActivity activity = getActivity();
if (activity instanceof NewSubjectDialogListener) {
listener = (NewSubjectDialogListener) activity;
} else {
throw new RuntimeException("Activity must implement the NewSubjectDialogListener interface!");
}
}
If at the
FragmentActivity activity = getActivity();
line somehow I would be able to call the getActivity() function of StudentSubjectsFragment class, I think it would solve my problem, and then the class that would implement the NewSubjectDialogFragment would be the StudentSubjectsFragment instead of StudentActivity.
I tried this:
FragmentActivity activity = getActivity().getSupportFragmentManager().findFragmentByTag("StudentSubjectsFragment").getActivity();
But activity is null.
StudentSubjectsFragment class:
public class StudentSubjectsFragment extends Fragment
implements NewSubjectDialogFragment.NewSubjectDialogListener,
SubjectAdapter.SubjectClickListener {
public static final String TAG = "StudentSubjectsFragment";
private RecyclerView recyclerView;
private SubjectAdapter adapter;
private SubjectDatabase database;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container,
#Nullable Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.student_subjects, container, false);
FloatingActionButton fab = rootView.findViewById(R.id.fabbb);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
new NewSubjectDialogFragment().show(getActivity().getSupportFragmentManager(), NewSubjectDialogFragment.TAG);
}
});
database = Room.databaseBuilder(
getActivity(),
SubjectDatabase.class,
"subject-list"
).build();
recyclerView = rootView.findViewById(R.id.SubjectRecyclerView);
adapter = new SubjectAdapter(this);
loadItemsInBackground();
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
recyclerView.setAdapter(adapter);
return rootView;
}
private void loadItemsInBackground() {
new AsyncTask<Void, Void, List<Subject>>() {
#Override
protected List<Subject> doInBackground(Void... voids) {
return database.subjectDao().getAll();
}
#Override
protected void onPostExecute(List<Subject> subjects) {
adapter.update(subjects);
}
}.execute();
}
#Override
public void onItemChanged(final Subject item) {
new AsyncTask<Void, Void, Boolean>() {
#Override
protected Boolean doInBackground(Void... voids) {
database.subjectDao().update(item);
return true;
}
#Override
protected void onPostExecute(Boolean isSuccessful) {
Log.d("StudentActivity", "Subject update was successful");
}
}.execute();
}
#Override
public void onItemDeleted(final Subject item) {
new AsyncTask<Void, Void, Boolean>() {
#Override
protected Boolean doInBackground(Void... voids) {
database.subjectDao().deleteItem(item);
return true;
}
}.execute();
}
#Override
public void onSubjectCreated(final Subject newItem) {
new AsyncTask<Void, Void, Subject>() {
#Override
protected Subject doInBackground(Void... voids) {
newItem.id = database.subjectDao().insert(newItem);
return newItem;
}
#Override
protected void onPostExecute(Subject subject) {
adapter.addItem(subject);
}
}.execute();
}
}
StudentActivity class:
public class StudentActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_student);
ViewPager vpProfile = findViewById(R.id.vpStudent);
vpProfile.setAdapter(new StudentPagerAdapter(getSupportFragmentManager()));
}
}
NewSubjectDialogFragment class:
public class NewSubjectDialogFragment extends DialogFragment {
private EditText nameEditText;
public static final String TAG = "NewSubjectDialogFragment";
public interface NewSubjectDialogListener {
void onSubjectCreated(Subject newItem);
}
private NewSubjectDialogListener listener;
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
FragmentActivity activity = getActivity().getSupportFragmentManager().findFragmentByTag("StudentSubjectsFragment").getActivity();
if (activity instanceof NewSubjectDialogListener) {
listener = (NewSubjectDialogListener) activity;
} else {
throw new RuntimeException("Activity must implement the NewSubjectDialogListener interface!");
}
}
private boolean isValid() {
return nameEditText.getText().length() > 0;
}
private Subject getSubject() {
Subject subject = new Subject();
subject.name = nameEditText.getText().toString();
return subject;
}
#NonNull
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
return new AlertDialog.Builder(requireContext())
.setTitle(R.string.new_subject_item)
.setView(getContentView())
.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
if (isValid()) {
listener.onSubjectCreated(getSubject());
}
}
})
.setNegativeButton(R.string.cancel, null)
.create();
}
private View getContentView() {
final View contentView = LayoutInflater.from(getContext()).inflate(R.layout.dialog_new_subject_item, null);
nameEditText = contentView.findViewById(R.id.SubjectNameEditText);
return contentView;
}
}
I think there is a way to change NewSubjectDialogFragment to work with StudentSubjectsFragment but I am a beginner in android developing and don't know how to do it.
Solution of Mike M. worked perfectly.
The working code parts are the following:
NewSubjectDialogFragment:
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Fragment fragment = getParentFragment();
if (fragment instanceof NewSubjectDialogListener) {
listener = (NewSubjectDialogListener) fragment;
} else {
throw new RuntimeException("Fragment must implement the NewSubjectDialogListener interface!");
}
}
StudentSubjectFragment:
FloatingActionButton fab = rootView.findViewById(R.id.fabbb);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
new NewSubjectDialogFragment().show(getChildFragmentManager(), NewSubjectDialogFragment.TAG);
}
});

Viewpager operations triggered on wrong reference

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.

Android Class Cast Exception inside Fragment

current I'm facing a problem which I cannot solve, I have a controller, a fragment, and an Activity, the problem is, I need the application context inside the controller, so I created an instance of the controller from the Fragment, and passed the appContext as an argument in its constructor, but an exception is thrown which is class cast exception in function getReligions() inside my controller at the line where I have a call back, any ideas how to solve this?
Here is my code
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
controller = new Controller(getActivity().getApplicationContext());
imageUploadHandler = new ImageHandler(getApplicationContext());
rootView = inflater.inflate(R.layout.setup_edit_profile, container, false);
}
public void getReligions() {
if (religions != null) {
religionSpinner();
return;
}
controller.getReligions();
}
In the controller class
public void getReligions(){
JSONObject params = new JSONObject();
RequestQueue queue = Volley.newRequestQueue(context);
String url = "https://www.doyousonder.com/api/1.0.0/religion";
queue.add(new JsonObjectRequest(com.android.volley.Request.Method.GET, url, params,
new Response.Listener<JSONObject>() {
public void onResponse(JSONObject response) {
((GeneralCallBack)context).VolleyResponse(response,"Religions");
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}) {
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
params.put("Authorization", orientation_adj.getContext().getResources().getString(R.string.bearer));
return params;
}
});
}
myLogCat:
java.lang.ClassCastException:
com.eseed.sonder.utils.orientation_adj cannot be cast to
com.eseed.sonder.utils.GeneralCallBack
at com.eseed.sonder.utils.Controller$61.onResponse(Controller.java:904)
at com.eseed.sonder.utils.Controller$61.onResponse(Controller.java:902)
at com.android.volley.toolbox.JsonRequest.deliverResponse(JsonRequest.java:65)
at com.android.volley.ExecutorDelivery$ResponseDeliveryRunnable.run(ExecutorDelivery.java:99)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:234)
at android.app.ActivityThread.main(ActivityThread.java:5526)
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)
Here're my callbacks
#Override
public void VolleyResponse(String data) {
}
#Override
public void VolleyResponse(JSONObject response) {
}
#Override
public void VolleyResponse(JSONObject response, String data) {
Gson gson = new Gson();
if(data.equals("Religions")){
try {
Type t = new TypeToken<ReligionData[]>() {}.getType();
religions = gson.fromJson(String.valueOf(response.getJSONObject("data").getJSONArray("list_of_religions")), t);
religion_names = new String[religions.length + 1];
religion_names[0] = "Select";
for (int i = 0; i < religions.length; i++) {
religion_names[i + 1] = (religions[i].religion_name);
}
religionSpinner();
} catch (JSONException e) {
e.printStackTrace();
}
}else if(data.equals("Nationalities")){
try {
Type t = new TypeToken<NationalityData[]>() {
}.getType();
nationalities = gson.fromJson(String.valueOf(response.getJSONObject("data").getJSONArray("list_of_nationalities")), t);
nationality_names = new String[nationalities.length + 1];
nationality_names[0] = "Select";
for (int i = 0; i < nationalities.length; i++) {
nationality_names[i + 1] = (nationalities[i].nationality_name);
}
nationalitySpinner();
loadingIcon.hide();
} catch (JSONException e) {
System.out.println(e.getMessage());
}
}
}
`public class orientation_adj extends Application {
private static Context mContext;
#Override
public void onCreate() {
super.onCreate();
Fabric.with(this, new Crashlytics());
mContext = this;
// register to be informed of activities starting up
registerActivityLifecycleCallbacks(new ActivityLifecycleCallbacks() {
#Override
public void onActivityCreated(Activity activity,
Bundle savedInstanceState) {
// new activity created; force its orientation to portrait
activity.setRequestedOrientation(
ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
}
#Override
public void onActivityStarted(Activity activity) {
}
#Override
public void onActivityResumed(Activity activity) {
}
#Override
public void onActivityPaused(Activity activity) {
}
#Override
public void onActivityStopped(Activity activity) {
}
#Override
public void onActivitySaveInstanceState(Activity activity, Bundle outState) {
}
#Override
public void onActivityDestroyed(Activity activity) {
}
});
}
public static Context getContext(){
return mContext;
}
}
Your problem is here
class orientation_adj extends Application
And here
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
controller = new Controller(getActivity().getApplicationContext());
Your Application class isn't the context that implemented the interface, I assume the Activity is
In that case, you only need
controller = new Controller(getActivity());
After that, set up some additional log statements and breakpoints to debug the callback code better

onclicklistener for ImageView in butterknife is not working

This is my view binder code. Here the acceptbutton and reject button is not working.
#Layout(R.layout.item)
public class TinderCard implements AsyncTaskCompleteListener {
SessionManager msession;
private static final String LIKE = "1";
private static final String DISLIKE = "2";
private int size,match;
String suggestionid;
private FindMatchesExecute execute;
#View(R.id.profileImageView)
private ImageView profileImageView;
#View(R.id.nameAgeTxt)
private TextView nameAgeTxt;
#View(R.id.acceptBtn)
private ImageView acceptbutton;
#View(R.id.rejectBtn)
private ImageView dislike_button;
private Data mProfile;
private Context mContext;
public int count=0;
#View(R.id.swipeView)
private SwipePlaceHolderView mSwipeView;
Activity activity;
public TinderCard(Context context, Data profile, SwipePlaceHolderView swipeView,FindMatchesExecute execu) {
mContext = context;
mProfile = profile;
mSwipeView = swipeView;
this.execute=execu;
msession=new SessionManager(mContext);
}
#Resolve
private void onResolved(){
Glide.with(mContext).load(mProfile.getPicture()).into(profileImageView);
nameAgeTxt.setText(mProfile.getName() + ", " + mProfile.getAge());
suggestionid=mProfile.getUserid();
profileImageView.setOnClickListener(new android.view.View.OnClickListener() {
#Override
public void onClick(android.view.View v) {
Intent i=new Intent(mContext,UserProfile.class);
i.putExtra("suggestion_id",mProfile.getUserid());
mContext.startActivity(i);
}
});
The listener part of the accept and reject button is not working. What am I missing in my code.
acceptbutton.setOnClickListener(new android.view.View.OnClickListener() {
#Override
public void onClick(android.view.View v) {
mSwipeView.doSwipe(true);
}
});
dislike_button.setOnClickListener(new android.view.View.OnClickListener() {
#Override
public void onClick(android.view.View v) {
mSwipeView.doSwipe(false);
}
});
}
#SwipeOut
private void onSwipedOut(){
Log.d("shan", "onSwipedOut");
HashMap<String, String> map = new HashMap<>();
map.put(Const.URL, Constant.like_dislike);
map.put(Const.Params.TOKEN, msession.getToken());
map.put(Const.Params.ID, msession.getID());
map.put(Const.Params.LIKE_DISLIKE_STATUS, DISLIKE);
map.put(Const.Params.SUGGESTION_ID, suggestionid);
Log.d("shanUpdatePref", "login map" + map);
// new MultiPartRequester(this, map, Const.ServiceCode.UPDATE_DOB, this);
new HttpRequester(mContext, Const.POST, map, Const.ServiceCode.LIKE_DISLIKE, this);
execute.onExecute();
}
#SwipeCancelState
protected void onSwipeCancelState(){
Log.d("EVENT", "onSwipeCancelState");
}
#SwipeIn
private void onSwipeIn()
{
//FindMatchesFragment.size--;
HashMap<String, String> map = new HashMap<>();
map.put(Const.URL, Constant.like_dislike);
map.put(Const.Params.TOKEN, msession.getToken());
map.put(Const.Params.ID, msession.getID());
map.put(Const.Params.LIKE_DISLIKE_STATUS, LIKE);
map.put(Const.Params.SUGGESTION_ID, suggestionid);
Log.d("shanUpdatePref", "login map" + map);
new HttpRequester(mContext, Const.POST, map, Const.ServiceCode.LIKE_DISLIKE, this);
execute.onExecute();
}
#SwipeInState
private void onSwipeInState(){
Log.d("EVENT", "onSwipeInState");
}
#SwipeOutState
private void onSwipeOutState(){
Log.d("EVENT", "onSwipeOutState");
}
#Override
public void onTaskCompleted(String response, int serviceCode) {
JSONObject jsonObject;
switch (serviceCode) {
case Const.ServiceCode.LIKE_DISLIKE:
Log.d("shan", "task1");
Log.d("shanResponse",response);
try {
jsonObject = new JSONObject(response);
if (jsonObject.getString("success").equals("true")) {
JSONObject like= jsonObject.getJSONObject("like");
Log.d("shanStatus",like.optString("status"));
match=like.optInt("match");
if(match==1)
{
String picture=like.optString("picture");
String user_pictre=like.optString("user_image");
String name=like.optString("name");
String userid=like.optString("suggestion_id");
Fragment MatchFoundScreen = new MatchFoundScreen();
Bundle args = new Bundle();
args.putString("name", name);
args.putString("picture",picture);
args.putString("user_image", user_pictre);
args.putString("suggestion_id", userid);
args.putInt("match",match);
MatchFoundScreen.setArguments(args);
FragmentManager fragmentManager =((FragmentActivity) mContext).getSupportFragmentManager();
fragmentManager.beginTransaction().replace(R.id.frame, MatchFoundScreen).commit();
}
} else {
Utility.showShortToast(mContext, jsonObject.getString("error_message"));
}
} catch (JSONException e) {
e.printStackTrace();
}
break;
}
}
}
Someone please guide me to resolve this. Thanks in advance.
This is my fragment class.
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
msession = new SessionManager(getActivity());
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
Log.i("Find Match", "oncreateview called");
view = inflater.inflate(R.layout.find_matches, null);
rlayout=(LinearLayout) view.findViewById(R.id.likedislikebuttonlayout);
frame=(FrameLayout)view.findViewById(R.id.frame2);
LocationManager locationManagerresume = (LocationManager) getActivity().getSystemService(LOCATION_SERVICE);
if (!locationManagerresume
.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
showGPSDisabledAlertToUser();
}
cd = new ConnectionDetector(getActivity());
if (!cd.isConnectingToInternet()) {
Toast.makeText(getActivity(), "No Internet", Toast.LENGTH_SHORT)
.show();
}
mSwipeView = (SwipePlaceHolderView)view.findViewById(R.id.swipeView);
rippleBackground = (RippleBackground) view.findViewById(R.id.content);
rippleBackground.startRippleAnimation();
noUsers=(TextView)view.findViewById(R.id.noUsers);
profileimage = (CircleImageView) view.findViewById(R.id.profileimage);
Glide.with(getActivity()).load(msession.getProfileImage())
.into(profileimage);
mGoogleApiClient = new GoogleApiClient.Builder(getActivity())
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
mLocationRequest = LocationRequest.create()
.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY)
.setInterval(10 * 1000)
.setFastestInterval(1 * 1000);
al = new ArrayList<>();
mContext = getActivity();
mSwipeView.getBuilder()
.setDisplayViewCount(1)
.setSwipeDecor(new SwipeDecor()
.setPaddingTop(20)
.setRelativeScale(0.01f)
.setSwipeInMsgLayoutId(R.layout.tinder_swipe_in_msg_view)
.setSwipeOutMsgLayoutId(R.layout.tinder_swipe_out_msg_view));
return view;
}
Use ButterKnife.bind(getActivity()) when ever you are in activity use this and for fragments use getActivity().
It's a way of using context in different places for more details
#OnClick(R.id.iv_image)
void ivBack() {
//TODO For Back Action
finish();
}
use latest
compile 'com.jakewharton:butterknife:8.1.0'
apt 'com.jakewharton:butterknife-compiler:8.1.0'
more details about lib

How to update a textview in a dialog fragment from an activity?

It may be a silly question but I didn't find a good way to update a dialogfragment's textview from an activity in my android app.
What I'd like to do is to update the textview every second with a counter value and once the time elapsed, a Runnable closes the dialog fragment.
The dialog is closed once the time is elapsed, no problem but I cannot update the textview I want.
Here's my code for the dialog:
public class AlertDialog extends DialogFragment {
private String message = null;
private String title = null;
private ImageView imgV = null;
private TextView msgTv = null;
private TextView counterTv = null;
private Button okBtn = null;
private int imageId = 0;
public static int AUTOMATIC_CLOSE = 100001;
private AlertDialogListener mDialogListener;
public void setImage(int i){
imageId = i;
}
public void setContent(String ttl, String msg){
message = msg;
title = ttl;
}
public boolean hasContent(){
return message != null && title != null;
}
public AlertDialog(){
}
public void performClick(){
okBtn.performClick();
}
public void updateField(String text){
counterTv.setText(text);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.dialog, container);
msgTv = (TextView)v.findViewById(R.id.textDialog);
imgV = (ImageView)v.findViewById(R.id.imageDialog);
counterTv = (TextView)v.findViewById(R.id.timeCounterDialog);
if(imageId != 0)
imgV.setImageResource(imageId);
else
imgV.setImageResource(R.drawable.error_icon);
if(hasContent()){
msgTv.setText(message);
getDialog().setTitle(title);
}
else{
getDialog().setTitle("ERROR");
msgTv.setText("An unexcepted error occured");
}
okBtn = (Button)v.findViewById(R.id.validateButton);
okBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(mDialogListener != null){
mDialogListener.onFinishedDialog();
}
}
});
return v;
}
#Override
public void onStart() {
mDialogListener.onStartedDialog();
super.onStart();
}
#Override
public void onAttach(Activity activity) {
mDialogListener = (AlertDialogListener) activity;
super.onAttach(activity);
}
#Override
public void onDetach() {
mDialogListener = null;
super.onDetach();
}
public interface AlertDialogListener{
void onStartedDialog();
void onFinishedDialog();
}
}
And this is how I launch it:
class myActivity extends Activity implements AlertDialogListener{
protected void onCreate(Bundle savedInstanceState){
"""some init stuff"""
button.setOnClickListener(new View.OnClickListener() {
showAlertDialog();
}
}
#Override
public void onStartedDialog() {
AutoCloseRunnable mAutoClose = new AutoCloseRunnable();
mHandler.postDelayed(mAutoClose, 1000);
}
#Override
public void onFinishedDialog() {
this.finish();
}
private void showAlertDialog(){
FragmentManager fm = getFragmentManager();
mAlertDialog = new AlertDialog();
mAlertDialog.setContent("No Connection available", "Please enable your internet connection.");
mAlertDialog.setImage(R.drawable.error_icon);
mAlertDialog.show(fm, "fragment_alert");
}
private void updateAlertDialog(String text){
mAlertDialog.updateField(text);
}
private void autoCloseAlertDialog(){
mAlertDialog.performClick();
}
public class AutoCloseRunnable implements Runnable{
#Override
public void run() {
int closeCpt = 10;
while(closeCpt >= 0){
try {
Thread.sleep(1000);
updateAlertDialog("Will close automatically in " + closeCpt + " seconds.");
closeCpt--;
} catch (InterruptedException e) {
e.printStackTrace();
}
}
autoCloseAlertDialog();
}
}
}
Does anyone know how to proceed?
I solved it, simply use asynctask it's easier to handle UI updates like this.

Categories

Resources