I am showing one dialog fragment (showing progress ) in my activity . Calling rest api methods are in my activity . Based on rest api results , I need to some progress in the dialog fragment . So I need to call a method of dialog fragment from activity . I tried with event bus , (Firing from Activity caught on Dialog Fragment ) - But events are not caught in dialog fragment . Is there any other solution ?
Fragment Code:
public class SyncProgressFragment extends BaseDialogFragment {
#BindView(R.id.layout_cancel)
LinearLayout layoutCancel;
#BindView(R.id.sync_with_master_breadcrumbs)
BreadcrumbsView syncWithMasterBreadCrumbs;
#BindView(R.id.master_breadcrumbs)
BreadcrumbsView masterBreadCrumbs;
#BindView(R.id.tvStep)
AppCompatTextView tvStep;
#BindView(R.id.tv_create_defect_title)
AppCompatTextView tvTitle;
private ThreadBus bus;
private FragmentManager manager;
private GoogleApiHelper googleApiHelper;
private Handler handler;
private Runnable runnable;
private boolean isOld;
private boolean isSync;
//private long requestId;
private BreadcrumbsView breadcrumbsView;
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
bus = AppController.getInstance().getBus();
bus.register(this);
googleApiHelper = AppController.getInstance().getGoogleApiHelper();
googleApiHelper.reconnect();
if (getArguments() != null) {
Bundle bundle = getArguments();
isOld = bundle.getBoolean(AppConstants.IS_OLD,false);
isSync = bundle.getBoolean(AppConstants.IS_OLD,false);
}
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
initUI();
}
private void initUI() {
if (isOld && isSync)
tvTitle.setText(getString(R.string.syncing_old_data_with_bo));
else if(!isOld && isSync)
tvTitle.setText(getString(R.string.syncing_data_with_bo));
else {
tvTitle.setText(getString(R.string.downloading_master_data));
}
if(isSync) {
breadcrumbsView = syncWithMasterBreadCrumbs;
syncWithMasterBreadCrumbs.setVisibility(View.VISIBLE);
masterBreadCrumbs.setVisibility(View.GONE);
tvStep.setText(getString(R.string.sending_data));
}
else{
breadcrumbsView = masterBreadCrumbs;
masterBreadCrumbs.setVisibility(View.VISIBLE);
syncWithMasterBreadCrumbs.setVisibility(View.GONE);
tvStep.setText(getString(R.string.getting_master_data));
}
}
private void initValues() {
handler = new Handler();
}
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
Dialog dialog = super.onCreateDialog(savedInstanceState);
// request a window without the title
dialog.getWindow().requestFeature(Window.FEATURE_NO_TITLE);
dialog.setCanceledOnTouchOutside(false);
dialog.setCancelable(false);
dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
return dialog;
}
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_sync_progress, container, false);
ButterKnife.bind(this, view);
initValues();
return view;
}
#Override
public void onStart() {
super.onStart();
}
#Override
public void onResume() {
super.onResume();
}
#Override
public void onPause() {
super.onPause();
}
#Override
public void onStop() {
super.onStop();
}
#Override
public void onDestroy() {
super.onDestroy();
if (bus != null) {
bus.unregister(this);
}
try {
handler.removeCallbacks(runnable);
} catch (Exception e) {
}
}
#Override
public void onDestroyView() {
super.onDestroyView();
}
#Override
public void setCancelable(boolean cancelable) {
super.setCancelable(cancelable);
}
#Override
public void onCancel(DialogInterface dialog) {
super.onCancel(dialog);
}
#Override
public void onDismiss(DialogInterface dialog) {
super.onDismiss(dialog);
try {
handler.removeCallbacks(runnable);
} catch (Exception e) {
}
}
#OnClick({R.id.img_close, R.id.layout_cancel})
public void onViewClicked(View view) {
switch (view.getId()) {
case R.id.layout_cancel:
case R.id.img_close:
dismissAllowingStateLoss();
break;
}
}
#Subscribe
public void onSyncGotResponse(SyncGotResponse syncGotResponse) {
Utilities.log(SyncProgressFragment.class,"onSyncGotResponse",""+syncGotResponse.isSuccess());
if(syncGotResponse.isSuccess()) {
breadcrumbsView.nextStep();
tvStep.setText(getString(R.string.synced_data_with_bo));
}
else
dismissAllowingStateLoss();
}
#Subscribe
public void onMasterGotResponse(MasterGotResponse masterGotResponse) {
Utilities.log(SyncProgressFragment.class,"onMasterGotResponse",""+masterGotResponse.isSuccess());
if(masterGotResponse.isSuccess()) {
tvStep.setText(getString(R.string.downloaded_data_from_bo));
breadcrumbsView.nextStep();
}
else
dismissAllowingStateLoss();
}
}
Activity Code:
#Override
public void dataSyncSuccess(DataSyncResponse dataSyncResponse) {
bus.post(new SyncGotResponse(true));
}
#Override
public void dataSyncFailure(String msg) {
UiUtils.showToast(getContext(), msg);
bus.post(new SyncGotResponse(false));
}
//Calling Rest Api method
if (CheckInternetConnection(getContext())) {
try {
presenter.data_sync();
Bundle bundle = new Bundle();
bundle.putBoolean(AppConstants.IS_OLD,false);
bundle.putBoolean(AppConstants.IS_SYNC,true);
syncProgressFragment.setArguments(bundle);
syncProgressFragment.setCancelable(false);
syncProgressFragment.show(getSupportFragmentManager(), syncProgressFragment.getTag());
} catch (JSONException e) {
e.printStackTrace();
}
} else {
ShowSanckBarShow();
}
Related
if the page is loaded, the button is active, if not, how can I do passive control?
What I want to do is, if the Viewpager Page is loaded, the button is active, if not, the Button is Passive. But I couldn't do any kind.
Is there anyone who can help?
If viewpager2 is installed Button enabled, if viewpager2 is not installed button false;
List<Movie> movieList = new ArrayList<>();
private ImageButton btn_down, btn_fav;
private Button btn_setter;
private DatabaseReference movies;
private IFirebaseLoadDone iFirebaseLoadDone;
public CartoonFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_cartoon, container, false);
movies = FirebaseDatabase.getInstance().getReference("Sports");
movies.keepSynced(true);
iFirebaseLoadDone = this;
loadMovie();
viewPager2 = view.findViewById(R.id.viewPager2_);
btn_down = view.findViewById(R.id.btn_down);
btn_setter = view.findViewById(R.id.btn_setter);
btn_fav = view.findViewById(R.id.btn_fav);
btn_down.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
SaveToGallery();
}
});
btn_setter.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
btn_fav.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
return view;
}
private void loadMovie() {
movies.addValueEventListener(this);
}
#Override
public void onFirebaseLoadSuccess(List<Movie> movieList) {
viewPagerAdapter = new ViewPagerAdapter(getContext(), movieList, viewPager2);
viewPager2.setAdapter(viewPagerAdapter);
}
#Override
public void onFirebasLoadFailed(String message) {
}
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot moviesSnapShot : dataSnapshot.getChildren())
movieList.add(moviesSnapShot.getValue(Movie.class));
Collections.reverse(movieList);
iFirebaseLoadDone.onFirebaseLoadSuccess(movieList);
viewPagerAdapter.notifyDataSetChanged();
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
iFirebaseLoadDone.onFirebasLoadFailed(databaseError.getMessage());
}
#Override
public void onDestroy() {
movies.removeEventListener(this);
super.onDestroy();
}
#Override
public void onResume() {
super.onResume();
}
#Override
public void onStop() {
movies.removeEventListener(this);
super.onStop();
}
}
Replace your methods with mine.
private void loadMovie() {
movies.addValueEventListener(this);
btn_down.setEnabled(false);
btn_fav.setEnabled(false);
btn_setter.setEnabled(false);
}
Firebase methods
#Override
public void onFirebaseLoadSuccess(List<Movie> movieList) {
viewPagerAdapter = new ViewPagerAdapter(getContext(), movieList, viewPager2);
viewPager2.setAdapter(viewPagerAdapter);
if(movieList!=null && !movieList.isEmpty()){
btn_down.setEnabled(true);
btn_fav.setEnabled(true);
btn_setter.setEnabled(true);
}
}
#Override
public void onFirebasLoadFailed(String message) {
btn_down.setEnabled(false);
btn_fav.setEnabled(false);
btn_setter.setEnabled(false);
}
There was an error loading
private void loadMovie() {
movies.addValueEventListener(this);
btn_down.setEnabled(false);
btn_fav.setEnabled(false);
btn_setter.setEnabled(false);
}
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ImageButton.setEnabled(boolean)' on a null object reference
at com.example.duvarlar.Fragment.CartoonFragment.loadMovie(CartoonFragment.java:386)
at com.example.duvarlar.Fragment.CartoonFragment.onCreateView(CartoonFragment.java:90)
I'm buliding a simple android app, and i got this error when i try to send data to API. I use RxJava and Retrofit, and I use Model View Presenter.
I got this error "btnservice is a null object reference"
I always got btnservice null, please help to solve this.
Thank you
This the JSON
request:
{
name: '',
mobile: '',
email: ''
}
This my BaseActivtiy
public abstract class BaseActivity extends AppCompatActivity {
#BindString(R.string.loading)
public String loading;
#BindInt(R.integer.success_code)
public int successCode;
#BindInt(R.integer.success_activication_code)
public int activicationSuccessCode;
protected BTNService btnService;
protected abstract int getLayout();
private ProgressDialog progressDialog;
private CompositeSubscription subscriptions;
protected RxBus bus;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(getLayout());
Icepick.restoreInstanceState(this, savedInstanceState);
ButterKnife.bind(this);
this.progressDialog = new ProgressDialog(this);
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
Icepick.saveInstanceState(this, outState);
}
#Override
protected void onStart() {
super.onStart();
this.subscriptions = new CompositeSubscription();
}
#Override
public void onStop() {
super.onStop();
}
#Override
protected void onDestroy() {
super.onDestroy();
this.progressDialog.dismiss();
}
public BTNService getBTNService() {
return btnService;
}
public RxBus getBus() {
return bus;
}
public void showProgressDialog(String message) {
if (progressDialog != null) {
progressDialog.setMessage(message);
progressDialog.show();
}
}
public void dismissProgressDialog() {
progressDialog.hide();
}
public boolean isFragmentNotNull(String tag) {
if (getSupportFragmentManager().findFragmentByTag(tag) != null) {
return true;
} else {
return false;
}
}
public boolean isFragmentVisible(String tag) {
if (isFragmentNotNull(tag)
&& getSupportFragmentManager().findFragmentByTag(tag).isVisible()) {
return true;
} else {
return false;
}
}
}
This my BaseFragment
public abstract class BaseFragment extends Fragment implements Validator.ValidationListener {
#BindString(R.string.loading)
public String loading;
#BindInt(R.integer.success_code)
public int successCode;
#BindInt(R.integer.success_activication_code)
public int activicationSuccessCode;
#BindString(R.string.connection_error)
public String connectionError;
protected abstract int getLayout();
protected Validator validator;
private CompositeSubscription subscriptions;
protected RxBus bus;
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
this.bus = ((BaseActivity) getActivity()).getBus();
}
#Override
public void onStart() {
super.onStart();
this.subscriptions = new CompositeSubscription();
/* this.subscriptions
.add(bus.toObserverable()
.subscribe(new Action1<Object>() {
#Override
public void call(Object event) {
if (event instanceof RxBusObject) {
RxBusObject busObject = (RxBusObject) event;
busHandler();
}
}
})
);*/
}
#Override
public void onStop() {
super.onStop();
this.subscriptions.clear();
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(getLayout(), container, false);
ButterKnife.bind(this, view);
return view;
}
public RxBus getBus() {
return this.bus;
}
#Override
public void onValidationSucceeded() {
}
#Override
public void onValidationFailed(List<ValidationError> errors) {
for (ValidationError error : errors) {
View view = error.getView();
String message = error.getCollatedErrorMessage(getActivity());
if (view instanceof EditText) {
EditText et = ((EditText) view);
et.setError(message);
et.requestFocus();
} else {
Toast.makeText(getActivity(), message, Toast.LENGTH_LONG).show();
}
}
}
public void showSuccessDialog(String message, final Boolean isFinishActivity) {
new MaterialDialog.Builder(getActivity())
.iconRes(R.mipmap.ic_launcher)
.title(getString(R.string.success).toUpperCase())
.titleColor(Color.WHITE)
.content(message)
.contentColor(Color.WHITE)
.positiveText(R.string.ok)
.positiveColor(Color.WHITE)
.onPositive(new MaterialDialog.SingleButtonCallback() {
#Override
public void onClick(MaterialDialog dialog, DialogAction which) {
if (isFinishActivity) {
getActivity().finish();
}
}
})
.cancelable(false)
.show();
}
public void showProgressDialog(String message) {
((BaseActivity) getActivity()).showProgressDialog(message);
}
public Validator getValidator() {
return validator;
}
public BTNService.Api getApi() {
return ((BaseActivity) getActivity()).getBTNService().getApi();
}
public void dismissProgressDialog() {
((BaseActivity) getActivity()).dismissProgressDialog();
}
}
This my Retrofit Class
public BTNService(Context context) {
if (retrofit==null) {
Retrofit retrofit = new Retrofit.Builder()
.client(provideOkHttpClient(context))
.baseUrl(BASE_URL)
.build();
this.api = retrofit.create(Api.class);
}
}
private OkHttpClient provideOkHttpClient(final Context context) {
HttpLoggingInterceptor httpLoggingInterceptorinterceptor = new HttpLoggingInterceptor();
httpLoggingInterceptorinterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
OkHttpClient.Builder httpClient = new OkHttpClient.Builder();
httpClient.addInterceptor(httpLoggingInterceptorinterceptor);
httpClient.addInterceptor(new Interceptor() {
#Override
public Response intercept(Chain chain) throws IOException {
Request request = chain.request();
Response response = chain.proceed(request);
return response;
}
});
return httpClient.build();
}
public Api getApi() {
return api;
}
public interface Api {
#POST(PORTAL_URL + "customer/register")
Observable<SignUpResponse> regsiterCustomer(#Path("email") String Email,
#Path("name") String Name,
#Path("mobile") String PhoneNumber);
}
and this my Presenter
public class SignUpPresenter {
private SignUpFragment fragment;
public SignUpPresenter(SignUpFragment fragment) {
this.fragment = fragment;
}
public SignUpRequest constructSignUpRequest() {
SignUpRequest request = new SignUpRequest();
request.setName(getAndTrimValueFromEditText(fragment.etName));
request.setEmail(getAndTrimValueFromEditText(fragment.etEmail));
request.setMobile(getAndTrimValueFromEditText(fragment.etPhone));
return request;
}
private String getAndTrimValueFromEditText(EditText e) {
return e.getText().toString().trim();
}
void signup (){
this.register(constructSignUpRequest());
}
void register(final SignUpRequest signUpRequest) {
fragment.showProgressDialog(fragment.loading);
fragment.getApi().regsiterCustomer(
signUpRequest.getName(),
signUpRequest.getEmail(),
signUpRequest.getMobile())
.subscribeOn(Schedulers.io())
.subscribe(new Observer<GenericResponse>() {
#Override
public void onCompleted() {
}
#Override
public void onError(Throwable e) {
fragment.dismissProgressDialog();
Timber.e(e.getLocalizedMessage());
Toast.makeText(fragment.getContext(), fragment.connectionError, Toast.LENGTH_SHORT).show();
}
#Override
public void onNext(GenericResponse genericResponse) {
fragment.dismissProgressDialog();
Toast.makeText(fragment.getContext(), genericResponse.getInfo(), Toast.LENGTH_SHORT).show();
if (genericResponse.getCode() == fragment.successCode) {
/*fragment.gotoActivationCodeActivity(SignUpRequest.getEmail(), SignUpRequest.get());*/
fragment.gotoQuestionActivity(signUpRequest.getEmail(), signUpRequest.getEmail(), signUpRequest.getMobile());
}
}
});
}
public static <T> Function<BaseResponse<T>, Observable<T>> convertDataFlatMap() {
return new Function<BaseResponse<T>, Observable<T>>() {
#Override
public Observable<T> apply(BaseResponse<T> response) {
if (!Constants.SUCCESS_CODE.equals(response.getStatus_code())) {
BaseErrorResponse baseErrorResponse = new BaseErrorResponse();
baseErrorResponse.setError(response.getStatus_code(),
response.getStatus());
return Observable.error(BaseException.toServerError(baseErrorResponse));
}
T data = response.getData();
if (null == data) {
return Observable.empty();
}
return Observable.just(response.getData());
}
};
}
I'm using Rxjava 2, Maybe useful for you.
I have parent fragment called OpFragment. From this fragment are inherited all fragments in my app.
public abstract class OpFragment extends Fragment {
private Loading loading;
public abstract int getLayoutId();
public abstract void getData();
public abstract void setListeners();
protected BackHandlerInterface backHandlerInterface;
public boolean onBackPressed(){
return false;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRetainInstance(true);
if(!(getActivity() instanceof BackHandlerInterface)) {
throw new ClassCastException("Hosting activity must implement BackHandlerInterface");
} else {
backHandlerInterface = (BackHandlerInterface) getActivity();
}
FragmentArgs.inject(this);
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(getLayoutId(), container, false);
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
if(!isAdded()){
return;
}
getData();
setListeners();
}
protected String returnName() {
return null;
}
public void showTitle() {
EventBus.getDefault().post(new ShowName(returnName()));
}
#Override
public void onDestroyView() {
super.onDestroyView();
}
public Loading getLoading() {
if (this.loading == null) {
this.loading = new Loading(this.getActivity());
}
return this.loading;
}
/**
* Gets a component for dependency injection by its type.
*/
#SuppressWarnings("unchecked")
protected <C> C getComponent(Class<C> componentType) {
return componentType.cast(((HasComponent<C>) getActivity()).getComponent());
}
#Override
public void onStart() {
super.onStart();
backHandlerInterface.setSelectedFragment(this);
}
public interface BackHandlerInterface {
void setSelectedFragment(OpFragment backHandledFragment);
}
#Override
public void onResume() {
super.onResume();
sendGAScreens();
}
private void sendGAScreens() {
final Tracker tracker = OpApp.getDefaultTracker();
if(tracker != null) {
tracker.setScreenName(getClass().getSimpleName());
tracker.send(new HitBuilders.ScreenViewBuilder().build());
}
}
}
There are methods getData() and setListeners() inside onViewCreated.
I don't want to recall this methods after screen rotation. How can I do that ?
Simply checking savedInstanceState == null not gave me expected result.
override this method to detect screen rotation in your fragment and set some flag if its screen rotation. as shown below:
#Override
public void onConfigurationChanged(Configuration newConfig)
{
Log.d("tag", "config changed");
super.onConfigurationChanged(newConfig);
int orientation = newConfig.orientation;
if (orientation == Configuration.ORIENTATION_PORTRAIT || orientation == Configuration.ORIENTATION_LANDSCAPE)
flag= true;
....
}
and in your onViewCreated() do like this
if(!flag){
// call your functions
}
I'm experiencing an strange behavior of Fragment life-cycle each time that i rotate the screen. Only the first half of life-cycle methods are getting called, onPause,onSaveInstanceState,onStop, onDestroyView,onDestroy and onDetach. The other half (onAttach ...-onResume) are not getting called. The Activity associated with the Fragment is calling all its life-cycle methods.
Any help would be highly appreciated because I'm stuck on this issue.
Thanks in advance.
Here the entire code of the Activity and the static nested class where is the Fragment:
public class MoviesFeed extends AppCompatActivity {
private static boolean mTwoPane;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.d("ACT","onCreate");
setContentView(R.layout.themoviedb_main);
if(findViewById(R.id.detail_activity_container)!=null) {
//the detail_activity_container will be present only in large-screen
//Layouts (res/Layout-sw600dp. If this view is present, then the activity
//should be in two-pane mode
mTwoPane=true;
//In two-pane mode, show the detail view in this activity by adding
// or replacing the detail fragment using a fragment transaction
DetailActivityFragment detailActivityFragment=new DetailActivityFragment();
// Bundle bundle=new Bundle();
// bundle.putBoolean("twopane",mTwoPane);
// detailActivityFragment.setArguments(bundle);
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.detail_activity_container, detailActivityFragment)
.commit();
}
} else {
mTwoPane=false;
}
}
#Override
protected void onStart() {
Log.d("ACT","onStart");
super.onStart();
}
#Override
protected void onResume() {
Log.d("ACT","onResume");
super.onResume();
}
#Override
protected void onPause() {
Log.d("ACT","onPause");
super.onPause();
}
#Override
protected void onStop() {
Log.d("ACT","onStop");
super.onStop();
}
#Override
protected void onRestart() {
Log.d("ACT","onRestart");
super.onRestart();
}
#Override
protected void onDestroy() {
Log.d("ACT","onDestroy");
super.onDestroy();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.movies_feed_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) {
startActivity(new Intent(this,SettingsActivity.class));
return true;
}
return super.onOptionsItemSelected(item);
}
public static class MoviesFeedFragment extends Fragment implements AdapterView.OnItemClickListener {
private static final int APPROX_FIXED_IMAGE_WIDTH=170;
private GridView mGridView;
private MovieAdapter mMovieAdapter;
private ArrayList<Response.Movie> mListMovies=new ArrayList<Response.Movie>();
private TimeMeasure mTm;
private boolean mFromDetailsActivity =false;
private boolean mUserRotation=false;
private boolean mFavoritesMode=false;
#Override
public void onAttach(Activity activity) {
Log.d("FRAG", "onAttach");
super.onAttach(activity);
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.d("FRAG", "onCreate");
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view= inflater.inflate(R.layout.fragment_moviesfeed, container, false);
Log.d("FRAG", "onCreateView");
mGridView= (GridView) view.findViewById(R.id.gridView);
mGridView.setOnItemClickListener(this);
mMovieAdapter = new MovieAdapter(getActivity(), mListMovies);
mGridView.setAdapter(mMovieAdapter);
//for tablets specially
// float scalefactor = getResources().getDisplayMetrics().density * APPROX_FIXED_IMAGE_WIDTH;
// Point size=new Point();
// getWindowManager().getDefaultDisplay().getSize(size);
// int number=size.x;
// int columns = (int) ((float) number / (float) scalefactor);
//
// mGridView.setNumColumns(columns);
if(savedInstanceState!=null){
mUserRotation=true;
ArrayList<Response.Movie> tempList=new ArrayList<Response.Movie>();
tempList=savedInstanceState.getParcelableArrayList("mListMovies");
mListMovies.clear();
mListMovies.addAll(tempList);
mMovieAdapter = new MovieAdapter(getActivity(), mListMovies);
mGridView.setAdapter(mMovieAdapter);
}
return view;
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
Log.d("FRAG", "onActivity");
super.onActivityCreated(savedInstanceState);
}
#Override
public void onPause() {
Log.d("FRAG", "onPause");
super.onPause();
}
#Override
public void onStop() {
Log.d("FRAG", "onStop");
super.onStop();
}
#Override
public void onSaveInstanceState(Bundle outState) {
Log.d("FRAG", "onSaveInstanceState");
super.onSaveInstanceState(outState);
outState.putParcelableArrayList("mListMovies", mListMovies);
}
#Override
public void onResume() {
Log.d("FRAG", "onResume");
super.onResume();
if (mFromDetailsActivity !=true && mUserRotation!=true) {
executeCallToMoviesApi();
} else if(mFromDetailsActivity==true && mFavoritesMode==true) {
getFavoritesMovies();
}
mFromDetailsActivity =false;
mUserRotation=false;
}
#Override
public void onDestroyView() {
Log.d("FRAG", "onDestroyView");
super.onDestroyView();
}
#Override
public void onDestroy() {
Log.d("FRAG", "onDestroy");
super.onDestroy();
}
#Override
public void onDetach() {
Log.d("FRAG", "onDetach");
super.onDetach();
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
if (mTwoPane==true) {
DetailActivityFragment detailActivityFragment=new DetailActivityFragment();
Bundle args=new Bundle();
args.putString("movieId", String.valueOf(mListMovies.get(position).getId()));
//Response.Movie movie=new Response.Movie();
//movie.setId(mListMovies.get(position).getId());
//args.putParcelable("movie",movie);
args.putBoolean("favoritesMode",mFavoritesMode);
detailActivityFragment.setArguments(args);
getActivity().getSupportFragmentManager().beginTransaction()
.replace(R.id.detail_activity_container,detailActivityFragment)
.commit();
} else {
Intent intent = new Intent(getActivity(), DetailActivity.class);
intent.putExtra("favoritesMode", mFavoritesMode);
intent.putExtra("movieId", mListMovies.get(position).getId());
mFromDetailsActivity = true;
startActivity(intent);
}
}
public void executeCallToMoviesApi(){
SharedPreferences sharedPreferences= PreferenceManager.getDefaultSharedPreferences(getActivity());
String orderStr= sharedPreferences.getString(getString(R.string.pref_order_key),
getString(R.string.pref_order_default));
mFavoritesMode=false;
if (orderStr.equals(getString(R.string.pref_popularity))){
getActivity().setTitle(getString(R.string.mainactivity_title_popularity));
getMoviesByPopularity();
}
if (orderStr.equals(getString(R.string.pref_rate))){
getActivity().setTitle(getString(R.string.mainactivity_title_rate));
getMoviesByRate();
}
if (orderStr.equals(getString(R.string.pref_favorites))) {
getActivity().setTitle(getString(R.string.mainactivity_title_favorites));
mFavoritesMode=true;
getFavoritesMovies();
}
}
public void getMoviesByPopularity(){
ApiClient.MyApi myApi=ApiClient.getMyApiClient();
myApi.getMoviesByPopularityDesc(AppConstants.API_KEY, callbackResponse());
}
public void getMoviesByRate(){
ApiClient.MyApi myApi=ApiClient.getMyApiClient();
myApi.getMoviesByAverageRate(AppConstants.API_KEY, callbackResponse());
}
private Callback<Response> callbackResponse() {
return new Callback<Response>() {
#Override
public void success(Response response, retrofit.client.Response response2) {
// Message.displayToast(MoviesFeed.this, "success");
mListMovies.clear();
mListMovies.addAll((ArrayList) response.getResults());
mMovieAdapter = new MovieAdapter(getActivity(), mListMovies);
mGridView.setAdapter(mMovieAdapter);
}
#Override
public void failure(RetrofitError error) {
Log.v("VILLANUEVA", "error:" + error.getMessage().toString());
Message.displayToast(getActivity(), "failure" + error.getMessage().toString());
}
};
}
public void getFavoritesMovies(){
List<MovieDetail> tempListDetail;
ArrayList<Response.Movie> tempList=new ArrayList<Response.Movie>();
SharedPreferenceManager sharedPreferenceManager=new SharedPreferenceManager(getActivity());
tempListDetail = sharedPreferenceManager.getFavoritesList();
Response.Movie tempMovie;
if (tempListDetail!=null) {
for (MovieDetail movieDetail : tempListDetail) {
tempMovie = new Response.Movie();
tempMovie.setId(movieDetail.getId());
tempMovie.setPoster_path(movieDetail.getPoster_path());
tempList.add(tempMovie);
}
mListMovies.clear();
mListMovies.addAll(tempList);
}
mMovieAdapter = new MovieAdapter(getActivity(), mListMovies);
mGridView.setAdapter(mMovieAdapter);
}
}//MoviesFeedFragment
Screenshots, before and after rotation.
Before:
After:
Log
I have a dialog that I want to display, and I cannot. The activity that I'm calling it from has an opengl es SurfaceViewRenderer. Some code is below. The text 'here' shows, and some of the activity from the fragment is going on in the background (I see some of the println statements from there) but no fragment is visible. I do not see 'is visible' in the logs.
public void goToFrag() {
dDial = new MYDialogFragment();
Bundle args = new Bundle();
dDial.setArguments(args);
dDial.show(getFragmentManager(), "dDialog");
if (dDial.isVisible() ) System.out.println("is visible");
System.out.println("here");
}
so here's some more info. I tried to run the 'goToFrag()' method from the 'runOnUIThread()' method and the fragment appears, but only for a second. Then the PlayActivity (what I'm calling the activity that launches the Fragment and contains the GLSurfaceRenderer) disappears. After that I'm back at the activity that calls the PlayActivity. There's no error output that I can find.
//from OpenGL SurfaceViewRenderer...
public void goToFrag() {
mPlayActivity.runOnUiThread(new Runnable() {
#Override
public void run() {
mPlayActivity.goToFrag();
}
});
}
More code might help
public class APDuellingDialogFragment extends DialogFragment {
public boolean mDebugMessages = true;
public OnFragmentReturnListener mListener;
public View v;
public ListView mListView;
public RadioGroup radio_left_right;
public interface OnFragmentReturnListener {
public void onActivityResult(int requestCode, int resultCode, Intent data);
}
public APDuellingDialogFragment() {
mBT = new APDuellingBluetooth(this);
mList = new ArrayList<APDuellingBluetooth.MenuItem>();
mSocketsLaunched = false;
}
public static APDuellingDialogFragment newInstance() {
APDuellingDialogFragment dialog = new APDuellingDialogFragment();
//dialog.setStyle(DialogFragment.STYLE_NO_FRAME, R.style.AppTheme);
dialog.setShowsDialog(true);
dialog.setRetainInstance(true);
dialog.setCancelable(false);
return dialog;
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
if (mDebugMessages) System.out.println("on attach");
//...
// This makes sure that the container activity has implemented
// the callback interface. If not, it throws an exception
try {
mListener = (OnFragmentReturnListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement OnHeadlineSelectedListener");
}
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (mDebugMessages) System.out.println("on create");
}
#Override
public void onDismiss(DialogInterface dialog) {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
v = inflater.inflate(R.layout.fragment_ap_dueling, container, false);
if (mDebugMessages) System.out.println("on create view");
}
Button button_close = (Button)v.findViewById(R.id.duel_button_close);
button_close.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
dismiss();
}
});
Button button_rescan = (Button)v.findViewById(R.id.duel_button_rescan);
button_rescan.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if(mBT.isBluetoothSupported()) {
//...
}
}
});
radio_left_right = (RadioGroup) v.findViewById(R.id.duel_right_left_group);
radio_left_right.setOnCheckedChangeListener( new RadioGroup.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup radioGroup, int i) {
//...
}
});
Switch switch_audio = (Switch) v.findViewById(R.id.duel_switch_sound);
switch_audio.setOnCheckedChangeListener( new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
//...
}
});
mListView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> adapterView, View view, int i, long l) {
//...
return false;
}
});
return v;
}
public void restartGameFromFragment() {
if(mDebugMessages) System.out.println("restartgamefrom fragment");
Intent mIntent = prepareIntentForGame();
mListener.onActivityResult(AP.INTENT_ACTIVITY_DUEL_SETUP, Activity.RESULT_OK, mIntent);
dismiss();
}
public Intent prepareIntentForGame() {
Intent mIntent = new Intent();
//...
return mIntent;
}
#Override
public void onDestroy() {
super.onDestroy();
if (mDebugMessages) System.out.println("on destroy");
}
}
finally this:
public class MYActivityPlay extends Activity implements MYDuellingDialogFragment.OnFragmentReturnListener {
private MYGLSurfaceView myMYView;
public MYButtonManager mButtons;
public MYReadXML mXML;
public MYDuellingDialogFragment duelDialogFragment;
public RelativeLayout mTitleAndScoresView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mIntent = this.getIntent();
mMode = mIntent.getIntExtra(MY.INTENT_MODE_CONSTANT, MY.MODE_PLAY);
mIntentLevel = mIntent.getIntExtra(MY.INTENT_LEVEL_CONSTANT, 1);
mScore = mIntent.getLongExtra(MY.INTENT_SCORE_CONSTANT, 0);
mHealth = mIntent.getIntExtra(MY.INTENT_HEALTH_CONSTANT, MYDirector.FULL_HEALTH_CONST);
mPlayButtonPressedCount = mIntent.getIntExtra(MY.INTENT_PLAY_PRESSED_CONSTANT, 0);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(
WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
startSurfaceView();
if (mMode == MY.MODE_DUEL) goToFrag(); // <--here is problem!!
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
//....
}
public void startSurfaceView() {
if (true ) {
Display display = ((WindowManager) getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();
Point size = new Point();
display.getSize(size);
mButtons = new MYButtonManager(this.getApplicationContext(), size.x ,size.y );
MYSound mSounds = new MYSound(this);
LayoutInflater mInflater = (LayoutInflater)getApplicationContext().getSystemService
(Context.LAYOUT_INFLATER_SERVICE);
View mTitleAndScore = mInflater.inflate(R.layout.overlay_title_score, null);
myMYView = new MYGLSurfaceView(/*some stuff here*/);
RelativeLayout mRelative = new RelativeLayout(this);
mRelative.addView(myMYView);
mRelative.addView(mTitleAndScore);
mRelative.addView(mButtons);
setContentView(mRelative);
this.setupTitleAndScore();
}
}
}
this is the final piece.