In my actvity I have a viewPager with for example 3 pages.
In all of theses pages, I have a YouTubePlayer with a different id video.
The problem is that all the YouTubePlayer component has the same video at the same time.
Concretely :
When the first page is displayed, the YouTubePlayer show the first video, so all seems to be ok.
When I try to scroll to the 2nd page, I can see that the 2nd YouTubePlayer show the same video.
When the 2nd page is completely displayed (After scrolling), behind the view pager prepare the 3rd page. So on the 3rd page the 3rd id video is set to the YouTubePlayer component. At that moment the 2nd page currently displayed switch automatically to the 3rd video.
It was like if the instance of YouTubePlayer was single for all the pages.
But on each page new FragmentYouTubePlayer() is correctly called.
I don't understand where is the problem.
Finally, I wonder if it's possible to use severals YouTubePlayer component (in a viewpager) at the same time or not ?
Thanks for your help.
I don't remember exactly what was wrong, but yes, I solved my problem. So, if it can help you, here is the code :
In my main activity, using PagerAdapter :
private class ScreenSlidePagerAdapter extends FragmentStatePagerAdapter {
public ScreenSlidePagerAdapter(android.support.v4.app.FragmentManager fm) {
super(fm);
}
#Override
public android.support.v4.app.Fragment getItem(int position) {
fragmentYouTubeContent = FragmentYouTubeContent.create(position);
return fragmentYouTubeContent;
}
#Override
public int getCount() {
int nb = 3;
return nb;
}
}
My FragmentYouTubeContent.class
package com.orange.OrangeJobs;
import java.util.List;
import com.google.android.youtube.player.YouTubeInitializationResult;
import com.google.android.youtube.player.YouTubeStandalonePlayer;
import com.google.android.youtube.player.YouTubeThumbnailLoader;
import com.google.android.youtube.player.YouTubeThumbnailView;
import android.support.v4.app.Fragment;
import android.annotation.SuppressLint;
import android.app.Dialog;
import android.content.Intent;
import android.content.pm.ResolveInfo;
import android.content.res.Configuration;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.TextView;
import android.widget.Toast;
public class FragmentYouTubeContent extends Fragment implements YouTubeThumbnailView.OnInitializedListener {
public static final int REQ_START_STANDALONE_PLAYER = 101;
private static final int REQ_RESOLVE_SERVICE_MISSING = 2;
private static final int RECOVERY_DIALOG_REQUEST = 1;
/**
* The fragment's page number.
*/
private int mPageNumber;
private String urlYouTube;
private boolean canHideStatusBar = false;
private Dialog errorDialog;
FrameLayout rl;
private YouTubeThumbnailView thumbnailView;
/**
* Factory method for this fragment class. Constructs a new fragment for the given page number.
*/
public static FragmentYouTubeContent create(int pageNumber) {
FragmentYouTubeContent fragment = new FragmentYouTubeContent();
fragment.setPageNumber(pageNumber);
return fragment;
}
public FragmentYouTubeContent() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#SuppressLint("InlinedApi")
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
setRetainInstance(true);
ViewGroup rootView = (ViewGroup) inflater.inflate(R.layout.youtube, container, false);
urlYouTube = "YOUR_VIDEO_URL";
if (!"".equals(urlYouTube)) {
thumbnailView = (YouTubeThumbnailView) rootView.findViewById(R.id.youtubethumbnailview);
thumbnailView.initialize(Params.YOUTUBE_KEY, this);
thumbnailView.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View arg0) {
// Launch standalone YoutTube player
Intent intent = null;
intent = YouTubeStandalonePlayer.createVideoIntent(getActivity(), YOUTUBE_KEY, urlYouTube, 0, true, false);
if (intent != null) {
if (canResolveIntent(intent)) {
canHideStatusBar = true;
startActivityForResult(intent, REQ_START_STANDALONE_PLAYER);
} else {
// Could not resolve the intent - must need to install or update the YouTube API service.
YouTubeInitializationResult
.SERVICE_MISSING
.getErrorDialog(getActivity(), REQ_RESOLVE_SERVICE_MISSING).show();
}
}
}});
}
return rootView;
}
#Override
public void onResume() {
super.onResume();
boolean isLandscape = false;
int currentOrientation = getResources().getConfiguration().orientation;
if (currentOrientation == Configuration.ORIENTATION_LANDSCAPE) {
isLandscape = true;
}
else {
isLandscape = false;
}
if (canHideStatusBar && this.isVisible() && isLandscape) {
Utils.hideStatusBar(getActivity());
canHideStatusBar = false;
}
}
#Override
public void onPause() {
super.onPause();
}
#Override
public void onInitializationSuccess(YouTubeThumbnailView thumbnailView, YouTubeThumbnailLoader thumbnailLoader) {
thumbnailLoader.setVideo(urlYouTube);
}
#Override
public void onInitializationFailure(YouTubeThumbnailView thumbnailView, YouTubeInitializationResult errorReason) {
if (errorReason.isUserRecoverableError()) {
if (errorDialog == null || !errorDialog.isShowing()) {
errorDialog = errorReason.getErrorDialog(getActivity(), RECOVERY_DIALOG_REQUEST);
errorDialog.show();
}
} else {
String errorMessage = String.format(getString(R.string.error_thumbnail_view), errorReason.toString());
Toast.makeText(getActivity(), errorMessage, Toast.LENGTH_LONG).show();
}
}
// ***** Private methods *************************************************************************************
private boolean canResolveIntent(Intent intent) {
List<ResolveInfo> resolveInfo = getActivity().getPackageManager().queryIntentActivities(intent, 0);
return resolveInfo != null && !resolveInfo.isEmpty();
}
// ***** Properties methods *************************************************************************************
/**
* Returns the page number represented by this fragment object.
*/
public int getPageNumber() {
return mPageNumber;
}
/**
* #param pageNumber the pageNumber to set
*/
public void setPageNumber(int pageNumber) {
this.mPageNumber = pageNumber;
}
/**
* #return the canHideStatusBar
*/
public boolean isCanHideStatusBar() {
return canHideStatusBar;
}
/**
* #param canHideStatusBar the canHideStatusBar to set
*/
public void setCanHideStatusBar(boolean canHideStatusBar) {
this.canHideStatusBar = canHideStatusBar;
}
}
My layout : youtube.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:clipToPadding="false"
android:background="#color/black"
android:scrollbarStyle="outsideOverlay"
android:orientation="horizontal" >
<com.google.android.youtube.player.YouTubeThumbnailView
android:id="#+id/youtubethumbnailview"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:contentDescription="#string/empty_string"
android:src="#drawable/ic_media_embed_play"
/>
</RelativeLayout>
Related
I am trying to implement a dynamic list update to FragmentStatePagerAdapter. I have a list of few fragments which have radio buttons, edit text, and different other fragments having just a single view.
Now the logic revolves around radio button fragment, so lets suppose you have a list having 10 elements and the list item showing the radio button is 6, and there are 2 options for the user to select on the radio button fragment. If user selects 1st option then 8th item should be shown and 7th should be skipped and if 2nd option is selected then 7th should be shown and then 9th.
I have added a view pager, and have an associated FragmentStatePagerAdapter associated with it. Now I was able to populate the list based on the option but when I refresh list in the adapter, it does not hops from 6th to 8th and still shows 7th.
Can someone help me around it on how can I implement the hopping mechanism on FragmentStatePagerAdapter?
Adapter
import android.support.annotation.NonNull;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.view.ViewGroup;
import java.util.List;
public class OrderDetailsAdapter extends FragmentPagerAdapter {
private final Logger log = LoggerFactory.getLogger(OrderDetailsAdapter.class);
private List<IndexedFragments> adapterList;
private FragmentManager fragmentManager;
public OrderDetailsAdapter(FragmentManager fragmentManager, List<IndexedFragments> adapterList) {
super(fragmentManager);
this.fragmentManager = fragmentManager;
this.adapterList = adapterList;
}
#Override
public Fragment getItem(int position) {
final IndexedFragments indexedFragment = adapterList.get(position);
return indexedFragment.getFragment();
}
#Override
public int getCount() {
if (adapterList.isEmpty()) {
return 0;
} else {
return adapterList.size();
}
}
#Override
public int getItemPosition(#NonNull Object object) {
return POSITION_NONE;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
log.debug("Destroying fragment position {}", position);
}
public void updateList(List<IndexedFragments> indexedFragments) {
adapterList.clear();
log.debug("Fragment List OrderDetailsAdapter after clearing {} on {}", adapterList.size(), adapterList);
adapterList.addAll(indexedFragments);
log.debug("Fragment List OrderDetailsAdapter after adding indexed fragments {} on {}", adapterList.size(), adapterList);
notifyDataSetChanged();
}
}
Model Class
import android.support.v4.app.Fragment;
import java.io.Serializable;
public class IndexedFragments implements Serializable {
private final static long serialVersionUID = -304520750038118996L;
private Integer index;
private Fragment fragment;
private boolean isSkippedRequested = false;
public Integer getIndex() {
return index;
}
public void setIndex(Integer index) {
this.index = index;
}
public Fragment getFragment() {
return fragment;
}
public void setFragment(Fragment fragment) {
this.fragment = fragment;
}
public boolean isSkippedRequested() {
return isSkippedRequested;
}
public void setSkippedRequested(boolean skippedRequested) {
isSkippedRequested = skippedRequested;
}
}
FormsActivity
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.Toast;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import javax.inject.Inject;
import dagger.Binds;
import dagger.Module;
import dagger.Subcomponent;
import dagger.android.ActivityKey;
import dagger.android.AndroidInjection;
import dagger.android.AndroidInjector;
import dagger.multibindings.IntoMap;
public class FormsActivity extends AppCompatActivity implements FragmentNavigationListener {
private static String CHECK_BOX = "checkbox";
private static String RADIO_BUTTON = "radio";
private static String TEXT_INPUT = "text";
private static String NUMERIC_INPUT = "numeric";
private static String VIDEO_VIEW = "video";
private static String IMAGE_VIEW = "image";
private final Logger log = LoggerFactory.getLogger(FormsActivity.class);
public LinkedHashMap<String, String> stringLinkedHashMap;
#Inject
protected BaseRetrofit restRequests;
#Inject
protected AppUtils appUtils;
private FormData formData;
private ViewPager viewPager;
private ProgressBar progressBar;
private Button submitButton;
private Toolbar toolbar;
private List<Frmdtl> formDataList;
private List<IndexedFragments> fragmentList;
private Context context;
private OrderDetailsAdapter orderDetailsAdapter;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
AndroidInjection.inject(this);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_forms);
context = this;
Intent intent = getIntent();
if (intent != null) {
formData = (FormData) intent.getSerializableExtra(AppConstants.FORMS_ACTIVITY);
}
restRequests.setContext(this);
initializeViews();
populateFragments(formData);
}
#Override
public void onBackPressed() {
showAlertDialog();
}
private void initializeViews() {
submitButton = findViewById(R.id.submit_button);
toolbar = findViewById(R.id.toolbar_main_activity);
setSupportActionBar(toolbar);
progressBar = findViewById(R.id.progress_bar_layout);
}
private void showAlertDialog() {
Dialog dialog = new AlertDialogFragment().createWarningDialog(context, getString(R.string.warning),
getString(R.string.saved_form_data_lost),
R.string.ok,
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int which) {
appUtils.getFormAnswersList().clear();
finish();
}
});
dialog.setCanceledOnTouchOutside(true);
dialog.show();
}
#SuppressLint("ClickableViewAccessibility")
private void populateFragments(FormData formData) {
formDataList = formData.getOrderDetails().getFrmdtl();
fragmentList = new ArrayList<>();
for (Frmdtl frmdtl : formDataList) {
Fragment fragment = null;
if (frmdtl.getFieldType().equalsIgnoreCase(TEXT_INPUT)) {
fragment = createTextFieldFragment(frmdtl, null);
} else if (frmdtl.getFieldType().equalsIgnoreCase(NUMERIC_INPUT)) {
fragment = createTextFieldFragment(frmdtl, NUMERIC_TYPE);
} else if (frmdtl.getFieldType().equalsIgnoreCase(CHECK_BOX)) {
fragment = createCheckBoxFragment(frmdtl);
} else if (frmdtl.getFieldType().equalsIgnoreCase(RADIO_BUTTON)) {
fragment = createRadioButtonFragment(frmdtl);
} else if (frmdtl.getFieldType().equalsIgnoreCase(VIDEO_VIEW)) {
fragment = createVideoViewFragment(frmdtl);
} else if (frmdtl.getFieldType().equalsIgnoreCase(IMAGE_VIEW)) {
fragment = createImageViewFragment(frmdtl);
}
if (fragment != null) {
IndexedFragments indexedFragments = new IndexedFragments();
indexedFragments.setFragment(fragment);
indexedFragments.setIndex(frmdtl.getIndex());
fragmentList.add(indexedFragments);
}
}
viewPager = findViewById(R.id.fragment_view_pager);
orderDetailsAdapter = new OrderDetailsAdapter(getSupportFragmentManager(), fragmentList);
viewPager.setAdapter(orderDetailsAdapter);
viewPager.setOffscreenPageLimit(0);
}
private Fragment createTextFieldFragment(Frmdtl formData, String inputType) {
FormEditTextFragment formEditTextFragment = new FormEditTextFragment();
Bundle bundle = new Bundle();
bundle.putSerializable(FORM_DATA, formData);
bundle.putString(INPUT_TYPE, inputType);
formEditTextFragment.setArguments(bundle);
log.debug("Form Data Id for text {}", formData.getId());
return formEditTextFragment;
}
private Fragment createCheckBoxFragment(Frmdtl formData) {
FormCheckBoxFragment formCheckBoxFragment = new FormCheckBoxFragment();
Bundle bundle = new Bundle();
bundle.putSerializable(FORM_DATA, formData);
formCheckBoxFragment.setArguments(bundle);
log.debug("Form Data Id for check {}", formData.getId());
return formCheckBoxFragment;
}
private Fragment createRadioButtonFragment(Frmdtl frmdtl) {
FormRadioButtonFragment formRadioButtonFragment = new FormRadioButtonFragment();
Bundle bundle = new Bundle();
bundle.putSerializable(FORM_DATA, frmdtl);
bundle.putSerializable(ORDER_DETAILS, formData.getOrderDetails());
formRadioButtonFragment.setArguments(bundle);
log.debug("Form Data Id for radio {}", frmdtl.getId());
return formRadioButtonFragment;
}
private Fragment createVideoViewFragment(Frmdtl formData) {
FormVideoFragment formVideoFragment = new FormVideoFragment();
Bundle bundle = new Bundle();
bundle.putSerializable(FORM_DATA, formData);
formVideoFragment.setArguments(bundle);
log.debug("Form Data Id for video {}", formData.getId());
return formVideoFragment;
}
private Fragment createImageViewFragment(Frmdtl formData) {
FormImageFragment formImageFragment = new FormImageFragment();
Bundle bundle = new Bundle();
bundle.putSerializable(FORM_DATA, formData);
formImageFragment.setArguments(bundle);
log.debug("Form Data Id for image {}", formData.getId());
return formImageFragment;
}
private void navigateBetweenFragments(int navigation, List<String> stringList, Integer currentIndex) {
if (navigation == NEXT_NAVIGATION) {
if (stringList != null && !stringList.isEmpty() && currentIndex != null) {
processLogicBasedFragments(stringList, currentIndex);
viewPager.setCurrentItem(viewPager.getCurrentItem() + 1);
return;
}
if (viewPager.getCurrentItem() == fragmentList.size() - 1) {
log.debug("FormData list size {}", formDataList.size());
log.debug("Moving to {} form", viewPager.getCurrentItem() + 1);
submitButton.setVisibility(View.VISIBLE);
submitButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
progressBar.setVisibility(View.VISIBLE);
attemptFormUpload();
}
});
} else {
viewPager.setCurrentItem(viewPager.getCurrentItem() + 1);
}
}
if (navigation == PREVIOUS_NAVIGATION) {
viewPager.setCurrentItem(viewPager.getCurrentItem() - 1);
}
}
private void processLogicBasedFragments(List<String> stringList, Integer currentIndex) {
List<IndexedFragments> indexedFragmentsList = new ArrayList<>();
for (int i = 0; i < fragmentList.size(); i++) {
Integer index = fragmentList.get(i).getIndex();
if (index.compareTo(currentIndex) <= 0) {
indexedFragmentsList.add(fragmentList.get(i));
}
}
for (int i = 0; i < fragmentList.size(); i++) {
IndexedFragments indexedFragments = fragmentList.get(i);
if (stringList.contains(String.valueOf(indexedFragments.getIndex()))) {
indexedFragmentsList.add(indexedFragments);
} else if (!stringList.contains(String.valueOf(indexedFragments.getIndex()))
&& fragmentList.get(i).getIndex().compareTo(currentIndex) > 0) {
indexedFragments.setSkippedRequested(true);
indexedFragmentsList.add(indexedFragments);
}
}
fragmentList.clear();
log.debug("Fragment List Forms Activity after clearing {} on {}", fragmentList.size(), fragmentList);
fragmentList.addAll(indexedFragmentsList);
log.debug("Fragment List Forms Activity after adding indexed fragments {} on {}", fragmentList.size(), fragmentList);
orderDetailsAdapter.updateList(indexedFragmentsList);
}
private void attemptFormUpload() {
try {
if (appUtils.isNetworkConnected(context)) {
uploadForm();
} else {
preserveFormDataForFutureUpload();
Toast.makeText(context, R.string.no_connection, Toast.LENGTH_LONG).show();
progressBar.setVisibility(GONE);
finish();
}
} catch (IOException e) {
log.error("Error in attempting to upload form {}", e.fillInStackTrace());
}
}
private void uploadForm() throws UnsupportedEncodingException {
restRequests.uploadForm(formData.getOrderDetails().getId(),
String.valueOf(formData.getOrderDetails().getFormId()),
formData.getOrderDetails().getLatitude(),
formData.getOrderDetails().getLongitude(),
appUtils.getFormAnswersList(), new RestRequestListener() {
#Override
public void onSuccessResponse(String response) {
appUtils.getFormAnswersList().clear();
progressBar.setVisibility(GONE);
finish();
}
#Override
public void onErrorResponse(Throwable t) {
appUtils.getFormAnswersList().clear();
progressBar.setVisibility(GONE);
finish();
}
});
}
private void preserveFormDataForFutureUpload() throws IOException {
OfflineSubmittedOrder offlineSubmittedOrder = new OfflineSubmittedOrder();
List<FormAnswers> formAnswers = new ArrayList<>(appUtils.getFormAnswersList());
offlineSubmittedOrder.setFormAnswersList(formAnswers);
offlineSubmittedOrder.setOrderDetail(formData.getOrderDetails());
appUtils.getFormAnswersList().clear();
appUtils.getOfflineSubmittedOrders().add(offlineSubmittedOrder);
appUtils.writeObject(getApplicationContext(), FORM_ANSWER_LIST_CACHE, appUtils.getOfflineSubmittedOrders());
appUtils.setSubmissionPending(true);
}
#Override
public void onFragmentNavigationTriggered(int navigation, List<String> stringList, Integer currentIndex) {
navigateBetweenFragments(navigation, stringList, currentIndex);
}
#Subcomponent
public interface FormsActivitySubcomponent extends AndroidInjector<FormsActivity> {
#SuppressWarnings({"InnerClassTooDeeplyNested", "ClassNameSameAsAncestorName"})
#Subcomponent.Builder
abstract class Builder extends AndroidInjector.Builder<FormsActivity> {
}
}
#SuppressWarnings("InterfaceNeverImplemented")
#Module(subcomponents = FormsActivity.FormsActivitySubcomponent.class)
public interface FormsActivityModule {
#Binds
#IntoMap
#ActivityKey(FormsActivity.class)
AndroidInjector.Factory<? extends Activity>
bindFormsActivityInjectorFactory(FormsActivity.FormsActivitySubcomponent.Builder builder);
}
}
I am quite new to Android programming! I have managed to have TTS work but not for fragments. I am trying to swipe some images, and speak something each time I do that. I am not getting any error, however, the text is not spoken. Here's the code:
package com.example.nightrain.sliderTTS1;
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.speech.tts.TextToSpeech;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import java.util.Locale;
public class Wild extends FragmentActivity{
ImageFragmentPagerAdapter imageFragmentPagerAdapter;
ViewPager viewPager;
public static final String[] IMAGE_NAME = {
"1", "2", "3"};
static final int NUM_ITEMS = IMAGE_NAME.length;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_pager);
imageFragmentPagerAdapter = new ImageFragmentPagerAdapter(getSupportFragmentManager());
viewPager = (ViewPager) findViewById(R.id.pager);
viewPager.setAdapter(imageFragmentPagerAdapter);
}
public static class ImageFragmentPagerAdapter extends FragmentPagerAdapter {
public ImageFragmentPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public int getCount() {
return NUM_ITEMS;
}
#Override
public Fragment getItem(int position) {
SwipeFragment fragment = new SwipeFragment();
return fragment.newInstance(position);
}
}
public static class SwipeFragment extends Fragment implements TextToSpeech.OnInitListener {
private static TextToSpeech tts;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View swipeView = inflater.inflate(R.layout.swipe_fragment, container, false);
ImageView imageView = (ImageView) swipeView.findViewById(R.id.imageView);
Bundle bundle = getArguments();
int position = bundle.getInt("position");
String imageFileName = IMAGE_NAME[position];
int imgResId = getResources().getIdentifier(imageFileName, "drawable", "com.example.nightrain.sliderTTS1");
imageView.setImageResource(imgResId);
tts = new TextToSpeech( getActivity(), SwipeFragment.this );
speak("help");
return swipeView;
}
static SwipeFragment newInstance(int position) {
SwipeFragment swipeFragment = new SwipeFragment();
Bundle bundle = new Bundle();
bundle.putInt("position", position);
swipeFragment.setArguments(bundle);
return swipeFragment;
}
public void onInit(int status) {
Log.d("Speech", "OnInit - Status ["+status+"]");
if (status == TextToSpeech.SUCCESS) {
Log.d("Speech", "Success!");
tts.setLanguage(Locale.US);
}
}
#Override
public void onDestroy() {
if (tts != null) {
tts.stop();
tts.shutdown();
}
super.onDestroy();
}
public void speak( String text){
tts.speak( text, TextToSpeech.QUEUE_FLUSH, null, "1" );
}
}
}
Figured it out. I was trying to use speak() before onInit(). It is interesting that I could use speak outside onInit() with no issues in activity, however, for fragment I needed to mode the speak() method and all necessary code inside onInit(). Since it is system called, I could found no way to force it to work outside it.
I want to pass dogruYanlis value which is an integer array to these fragments. If I try to handle this with bundle it it sends anything. The array that I received in fragment class is always null. I think that I can't handle with bundle but I don't know how I can solve this problem...
The Activity that I want to send data
package oztiryaki.my;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
public class result extends AppCompatActivity {
private Toolbar toolbar;
private TabLayout tabLayout;
private ViewPager viewPager;
private Bundle bundle;
int[] dogruYanlis;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_result);
toolbar = (Toolbar) findViewById(R.id.toolbarResult);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
viewPager = (ViewPager) findViewById(R.id.viewpager);
setupViewPager(viewPager);
tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(viewPager);
Bundle list = getIntent().getExtras();
if(list == null){
return;
}
dogruYanlis = list.getIntArray("dogruYanlis");
}
#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;
}
private void setupViewPager(ViewPager viewPager) {
ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
bundle = new Bundle();
bundle.putIntArray("dogruYanlis", dogruYanlis);
result2015Fragment f15 = new result2015Fragment();
f15.setArguments(bundle);
result2014Fragment f14 = new result2014Fragment();
f14.setArguments(bundle);
result2013Fragment f13 = new result2013Fragment();
f13.setArguments(bundle);
adapter.addFragment(f15, "2015");
adapter.addFragment(f14, "2014");
adapter.addFragment(f13, "2013");
viewPager.setAdapter(adapter);
}
class ViewPagerAdapter extends FragmentPagerAdapter {
private final List<Fragment> mFragmentList = new ArrayList<>();
private final List<String> mFragmentTitleList = new ArrayList<>();
public ViewPagerAdapter(FragmentManager manager) {
super(manager);
}
#Override
public Fragment getItem(int position) {
return mFragmentList.get(position);
}
#Override
public int getCount() {
return mFragmentList.size();
}
public void addFragment(Fragment fragment, String title) {
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}
#Override
public CharSequence getPageTitle(int position) {
return mFragmentTitleList.get(position);
}
}
}
The one of fragment activity
package oztiryaki.my;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;
/**
* Created by oztir on 21.02.2016.
*/
public class result2015Fragment extends Fragment {
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.result2015,container,false);
int[] dogruYanlis = getArguments().getIntArray("dogruYanlis");
if(dogruYanlis == null){
Toast.makeText(getActivity(),"null sory:(", Toast.LENGTH_LONG).show();
}
TextView ygs1hp = (TextView) v.findViewById(R.id.ygs1hp);
return v;
}
public void getArray(int[] dogruYanlis){
Toast.makeText(getActivity(),Integer.toString(dogruYanlis[0]), Toast.LENGTH_LONG).show();
}
}
I had a similar struggle, maybe this will help. In case if your variables in the activity are not changing after it is created, there is one simple way to reach out to the activity's variables from the fragment it creates:
get the context in the fragment
then you can get the value of the variable from the fragment
Context context;
public void onViewCreated(View v, Bundle savedInstanceState) {
context = getActivity();
int i = ((result)context).dogruYanlis[0];
}
Try to create a Fragment using the wizard that Android studio provides, which gives you a dummy Fragment, with all the Fragment methods you need to pass data and such:
package FRAGMENTS;
import android.app.Fragment;
import android.content.Context;
import android.net.Uri;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;
public class FragmentLifecycleDemo extends Fragment {
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String TEXT1 = "text1";
private static final String TEXT2 = "text2";
// the two strings are going to be used here
private TextView title;
private TextView subtitle;
private String text1;
private String text2;
private Context c;
private OnFragmentInteractionListener mListener;
public FragmentLifecycleDemo(Context c) {
// Required empty public constructor
this.c = c;
}
public static FragmentLifecycleDemo newInstance(String title, String subtitle, Context c) {
FragmentLifecycleDemo fragment = new FragmentLifecycleDemo(c);
Bundle args = new Bundle();
args.putString(TEXT1, title);
args.putString(TEXT2, subtitle);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Toast.makeText(c, "Hi! onCreate has just been called.", Toast.LENGTH_SHORT).show();
if (getArguments() != null) {
text1 = getArguments().getString(TEXT1);
text2 = getArguments().getString(TEXT2);
}
}
private void init(View v) {
title = (TextView) v.findViewById(R.id.txtTry);
title.setText(text1);
subtitle = (TextView) v.findViewById(R.id.txtReal);
subtitle.setText(text2);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_lifecycle_demo, container, false);
init(v);
Toast.makeText(c, "Greetings from onCreateView!", Toast.LENGTH_SHORT).show();
return v;
}
// TODO: Rename method, update argument and hook method into UI event
public void onButtonPressed(Uri uri) {
Toast.makeText(c, "Is it me, or a button has just been pressed?", Toast.LENGTH_SHORT).show();
if (mListener != null) {
mListener.onFragmentInteraction(uri);
}
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
Toast.makeText(c, "Howdy! I've just been attached to the activity.", Toast.LENGTH_SHORT).show();
if (context instanceof OnFragmentInteractionListener) {
mListener = (OnFragmentInteractionListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement OnFragmentInteractionListener");
}
}
#Override
public void onDetach() {
super.onDetach();
Toast.makeText(c, "Oh no! I've been detached u.u", Toast.LENGTH_SHORT).show();
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);
}
}
As you can see, the method where you should get the Bundle is the onCreate one, that receives the data you want to be available on the Fragment, which was send from the constructor named newInstance.
I am trying to get the bitmap of my mImageView in a Fragment class.
I notices that I can see the correct drawables, but bitmap is only created sometimes, while most often is Null.
Here is the code:
package com.example.android.displayingbitmaps.ui;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.Toast;
import com.example.android.displayingbitmaps.R;
import com.example.android.displayingbitmaps.util.ImageFetcher;
import com.example.android.displayingbitmaps.util.ImageWorker;
import com.example.android.displayingbitmaps.util.Utils;
/**
* This fragment will populate the children of the ViewPager from {#link ImageDetailActivity}.
*/
public class ImageDetailFragment extends Fragment {
private static final String IMAGE_DATA_EXTRA = "extra_image_data";
private String mImageUrl;
private ImageView mImageView;
private ImageFetcher mImageFetcher;
/**
* Factory method to generate a new instance of the fragment given an image number.
*
* #param imageUrl The image url to load
* #return A new instance of ImageDetailFragment with imageNum extras
*/
public static ImageDetailFragment newInstance(String imageUrl) {
final ImageDetailFragment f = new ImageDetailFragment();
final Bundle args = new Bundle();
args.putString(IMAGE_DATA_EXTRA, imageUrl);
f.setArguments(args);
return f;
}
/**
* Empty constructor as per the Fragment documentation
*/
public ImageDetailFragment() {}
/**
* Populate image using a url from extras, use the convenience factory method
* {#link ImageDetailFragment#newInstance(String)} to create this fragment.
*/
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mImageUrl = getArguments() != null ? getArguments().getString(IMAGE_DATA_EXTRA) : null;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate and locate the main ImageView
final View v = inflater.inflate(R.layout.image_detail_fragment, container, false);
mImageView = (ImageView) v.findViewById(R.id.imageView);
return v;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
// Use the parent activity to load the image asynchronously into the ImageView (so a single
// cache can be used over all pages in the ViewPager
if (ImageDetailActivity.class.isInstance(getActivity())) {
mImageFetcher = ((ImageDetailActivity) getActivity()).getImageFetcher();
mImageFetcher.loadImage(mImageUrl, mImageView);
BitmapDrawable drawable = (BitmapDrawable) mImageView.getDrawable();
Bitmap bitmap = drawable.getBitmap();
Toast.makeText(getActivity(), "Drawable is: "+drawable,Toast.LENGTH_SHORT).show(); }
// Pass clicks on the ImageView to the parent activity to handle
if (OnClickListener.class.isInstance(getActivity()) && Utils.hasHoneycomb()) {
mImageView.setOnClickListener((OnClickListener) getActivity());
}
}
#Override
public void onDestroy() {
super.onDestroy();
if (mImageView != null) {
// Cancel any pending image work
ImageWorker.cancelWork(mImageView);
mImageView.setImageDrawable(null);
}
}
}
FragmentActivity class
import android.annotation.TargetApi;
import android.app.ActionBar;
import android.os.Build.VERSION_CODES;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.app.NavUtils;
import android.support.v4.view.ViewPager;
import android.util.DisplayMetrics;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.WindowManager.LayoutParams;
import android.widget.ImageView;
import android.widget.Toast;
import com.example.android.displayingbitmaps.BuildConfig;
import com.example.android.displayingbitmaps.R;
import com.example.android.displayingbitmaps.provider.Images;
import com.example.android.displayingbitmaps.util.ImageCache;
import com.example.android.displayingbitmaps.util.ImageFetcher;
import com.example.android.displayingbitmaps.util.Utils;
public class ImageDetailActivity extends FragmentActivity implements OnClickListener {
private static final String IMAGE_CACHE_DIR = "images";
public static final String EXTRA_IMAGE = "extra_image";
private ImagePagerAdapter mAdapter;
private ImageFetcher mImageFetcher;
private ViewPager mPager;
private ImageView mImageView;
#TargetApi(VERSION_CODES.HONEYCOMB)
#Override
public void onCreate(Bundle savedInstanceState) {
if (BuildConfig.DEBUG) {
Utils.enableStrictMode();
}
super.onCreate(savedInstanceState);
setContentView(R.layout.image_detail_pager);
// Fetch screen height and width, to use as our max size when loading images as this
// activity runs full screen
final DisplayMetrics displayMetrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
final int height = displayMetrics.heightPixels;
final int width = displayMetrics.widthPixels;
// For this sample we'll use half of the longest width to resize our images. As the
// image scaling ensures the image is larger than this, we should be left with a
// resolution that is appropriate for both portrait and landscape. For best image quality
// we shouldn't divide by 2, but this will use more memory and require a larger memory
// cache.
final int longest = (height > width ? height : width) / 2;
ImageCache.ImageCacheParams cacheParams =
new ImageCache.ImageCacheParams(this, IMAGE_CACHE_DIR);
cacheParams.setMemCacheSizePercent(0.25f); // Set memory cache to 25% of app memory
// The ImageFetcher takes care of loading images into our ImageView children asynchronously
mImageFetcher = new ImageFetcher(this, longest);
mImageFetcher.addImageCache(getSupportFragmentManager(), cacheParams);
mImageFetcher.setImageFadeIn(false);
// Set up ViewPager and backing adapter
mAdapter = new ImagePagerAdapter(getSupportFragmentManager(), Images.imageUrls.length);
mPager = (ViewPager) findViewById(R.id.pager);
mPager.setAdapter(mAdapter);
mPager.setPageMargin((int) getResources().getDimension(R.dimen.horizontal_page_margin));
mPager.setOffscreenPageLimit(2);
// Set up activity to go full screen
getWindow().addFlags(LayoutParams.FLAG_FULLSCREEN);
// Enable some additional newer visibility and ActionBar features to create a more
// immersive photo viewing experience
if (Utils.hasHoneycomb()) {
final ActionBar actionBar = getActionBar();
// Hide title text and set home as up
actionBar.setDisplayShowTitleEnabled(false);
actionBar.setDisplayHomeAsUpEnabled(true);
// Hide and show the ActionBar as the visibility changes
mPager.setOnSystemUiVisibilityChangeListener(
new View.OnSystemUiVisibilityChangeListener() {
#Override
public void onSystemUiVisibilityChange(int vis) {
if ((vis & View.SYSTEM_UI_FLAG_LOW_PROFILE) != 0) {
actionBar.hide();
} else {
actionBar.show();
}
}
});
// Start low profile mode and hide ActionBar
mPager.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LOW_PROFILE);
actionBar.hide();
}
// Set the current item based on the extra passed in to this activity
final int extraCurrentItem = getIntent().getIntExtra(EXTRA_IMAGE, -1);
if (extraCurrentItem != -1) {
mPager.setCurrentItem(extraCurrentItem);
}
}
#Override
public void onResume() {
super.onResume();
mImageFetcher.setExitTasksEarly(false);
}
#Override
protected void onPause() {
super.onPause();
mImageFetcher.setExitTasksEarly(true);
mImageFetcher.flushCache();
}
#Override
protected void onDestroy() {
super.onDestroy();
mImageFetcher.closeCache();
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
NavUtils.navigateUpFromSameTask(this);
return true;
case R.id.clear_cache:
mImageFetcher.clearCache();
Toast.makeText(
this, R.string.clear_cache_complete_toast,Toast.LENGTH_SHORT).show();
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main_menu, menu);
return true;
}
/**
* Called by the ViewPager child fragments to load images via the one ImageFetcher
*/
public ImageFetcher getImageFetcher() {
return mImageFetcher;
}
/**
* The main adapter that backs the ViewPager. A subclass of FragmentStatePagerAdapter as there
* could be a large number of items in the ViewPager and we don't want to retain them all in
* memory at once but create/destroy them on the fly.
*/
private class ImagePagerAdapter extends FragmentStatePagerAdapter {
private final int mSize;
public ImagePagerAdapter(FragmentManager fm, int size) {
super(fm);
mSize = size;
}
#Override
public int getCount() {
return mSize;
}
#Override
public Fragment getItem(int position) {
return ImageDetailFragment.newInstance(Images.imageUrls[position]);
}
}
/**
* Set on the ImageView in the ViewPager children fragments, to enable/disable low profile mode
* when the ImageView is touched.
*/
#TargetApi(VERSION_CODES.HONEYCOMB)
#Override
public void onClick(View v) {
final int vis = mPager.getSystemUiVisibility();
//Toast.makeText(this, "Value is: " + ,Toast.LENGTH_SHORT).show();
if ((vis & View.SYSTEM_UI_FLAG_LOW_PROFILE) != 0) {
mPager.setSystemUiVisibility(View.SYSTEM_UI_FLAG_VISIBLE);
} else {
mPager.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LOW_PROFILE);
}
}
}
As you can see I put a Toast that show me this:
When Toast is Drawable:
When Toast is Bitmap, shows bitmap null sometimes for same image (as I swipe back and forward through the gallery):
Bitmap not null on same image:
I am using an AVD image of Android M 6.0
I am developing Horizontal Scrolling pages and tabs
MY app is working well in all devices in foreground, but when it goes to background, after one hour, the logs saying that Process com.example.myapp has died. When i reopen the app , the gridview data is not appearing but when scrolling horizontally , getView() method displaying all data like images and text.
that means app has data but view is not formed when process has died. And if i press back button and re-open the app, It is working good
My MainActivity.java is here
package com.bbgusa.bbgdemo.ui.phone;
import java.util.List;
import java.util.Vector;
import org.json.JSONObject;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.ViewPager;
import android.view.View;
import android.widget.TabHost;
import com.bbgusa.bbgdemo.R;
import com.bbgusa.bbgdemo.listener.phone.CustomViewPager;
import com.bbgusa.bbgdemo.ui.chat.phone.ChatFragmentTab;
import com.bbgusa.bbgdemo.ui.dialpad.phone.DialerFragment;
import com.bbgusa.bbgdemo.ui.home.phone.AlarmFragmentPhone;
import com.bbgusa.bbgdemo.ui.home.phone.HomeFragment;
import com.bbgusa.bbgdemo.ui.home.phone.HomeFragmentTab;
import com.bbgusa.bbgdemo.ui.home.phone.InfoFragPhone;
import com.bbgusa.bbgdemo.ui.home.phone.MapPhone;
import com.bbgusa.bbgdemo.ui.home.phone.WeatherFragmentPhone;
import com.bbgusa.bbgdemo.ui.messages.phone.MessagesFragment;
import com.bbgusa.bbgdemo.ui.settings.phone.AboutFragment;
import com.bbgusa.bbgdemo.ui.tablet.ConstantsManager;
import com.bbgusa.bbgdemo.ui.tablet.OnFragmentChangedListenerPhone;
import com.bbgusa.bbgdemo.utils.common.UConnectUtils;
public class MainActivity extends FragmentActivity implements TabHost.OnTabChangeListener, ViewPager.OnPageChangeListener, OnFragmentChangedListenerPhone {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_phone);
this.initialiseTabHost(savedInstanceState);
initialiseViewPager();
}
/**
* Initialise ViewPager
*/
private void initialiseViewPager() {
List<Fragment> fragments = new Vector<Fragment>();
fragments.add(Fragment.instantiate(this,HomeFragmentTab.class.getName()));
fragments.add(Fragment.instantiate(this, DialerFragment.class.getName()));
fragments.add(Fragment.instantiate(this,MessagesFragment.class.getName()));
fragments.add(Fragment.instantiate(this,ChatFragmentTab.class.getName()));
fragments.add(Fragment.instantiate(this, AboutFragment.class.getName()));
this.mPagerAdapter = new PagerAdapter(super.getSupportFragmentManager(), fragments);
this.mViewPager = (CustomViewPager) findViewById(R.id.tabviewpager);
this.mViewPager.setAdapter(this.mPagerAdapter);
this.mViewPager.setOnPageChangeListener(this);
this.mViewPager.setOffscreenPageLimit(5);
this.mViewPager.setCurrentItem(0);
}
#Override
public void onFragmentChangePhone(JSONObject response, String whichView, String title, String mPhoneNo) {
Bundle b = new Bundle();
if(response != null)
b.putString("JSONObject", response.toString());
if(title != null)
b.putString("Title", title);
String propertyId = UConnectUtils.getPropertyId(mPref, getString(R.string.property_id));
b.putString(UConnectUtils.PROPERTY_ID_KEY, propertyId);
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction ft = fragmentManager.beginTransaction();
Fragment fragment = null;
if (whichView.equals(ConstantsManager.GRIDVIEWPAGER)) {
// getSupportFragmentManager().popBackStack();
fragment = new HomeFragment();
} else if (whichView.equals(ConstantsManager.WEATHER)) {
fragment = new WeatherFragmentPhone();
}else if (whichView.equals(ConstantsManager.ALARM)) {
fragment = new AlarmFragmentPhone();
}else if (whichView.equals(ConstantsManager.MAPS)) {
fragment = new MapPhone();
}else if (whichView.equals(ConstantsManager.HELP)) {
fragment = new InfoFragPhone();
}
if (whichView.equals(ConstantsManager.MAPS)) { // to show plus-icon on map top right corner
HomeFragment.getInstance().onGridViewVisibilityChanged(true);
HomeFragmentTab.getInstance().onFragmentTabChange(View.VISIBLE , title, "", View.VISIBLE);
} else if (!whichView.equals(ConstantsManager.GRIDVIEWPAGER)) {
HomeFragment.getInstance().onGridViewVisibilityChanged(true);
HomeFragmentTab.getInstance().onFragmentTabChange(View.VISIBLE , title, mPhoneNo, View.GONE);
}
fragment.setArguments(b);
ft.add(R.id.main_home_frag, fragment);
if (whichView.equals(ConstantsManager.GRIDVIEWPAGER)) {
fragmentManager.popBackStack();
} else {
ft.addToBackStack(fragment.toString());
}
ft.commit();
}
#Override
public void onPageScrollStateChanged(int arg0) {
// TODO Auto-generated method stub
}
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
// TODO Auto-generated method stub
}
#Override
public void onPageSelected(int arg0) {
// TODO Auto-generated method stub
}
#Override
public void onTabChanged(String tabId) {
// TODO Auto-generated method stub
}
}
and my HomeFragmentTab.java is
package com.bbgusa.bbgdemo.ui.home.phone;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.bbgusa.bbgdemo.R;
import com.bbgusa.bbgdemo.ui.phone.MainActivity;
import com.bbgusa.bbgdemo.ui.tablet.ConstantsManager;
import com.bbgusa.bbgdemo.ui.tablet.OnFragmentTabChangedListener;
#SuppressLint("NewApi")
public class HomeFragmentTab extends Fragment implements OnFragmentTabChangedListener{
private static final String TAG = HomeFragmentTab.class.getSimpleName();
private static HomeFragmentTab tab;
private MainActivity activityPhone;
public static HomeFragmentTab getInstance() {
return tab;
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
activityPhone = (MainActivity) activity;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v;
if (container == null) {
return null;
}
Log.i(TAG, "onCreateView");
v = inflater.inflate(R.layout.hometab_phone, container, false);
tab = this;
activityPhone.onFragmentChangePhone(null, ConstantsManager.GRIDVIEWPAGER, getResources().getString(R.string.app_name), "");
return v;
}
#Override
public void onFragmentTabChange(int i, String title, String mPhoneNo, int mapV) {
}
}
and HomeFragment.java is
package com.bbgusa.bbgdemo.ui.home.phone;
import java.util.Locale;
import org.json.JSONArray;
import org.json.JSONObject;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.SharedPreferences;
import android.content.res.Resources;
import android.graphics.drawable.ColorDrawable;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.view.ViewTreeObserver.OnGlobalLayoutListener;
import android.view.Window;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.ImageView;
import android.widget.LinearLayout;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.bbgusa.bbgdemo.R;
import com.bbgusa.bbgdemo.ui.ImageCacheManager;
import com.bbgusa.bbgdemo.ui.cms.tablet.TestTopics;
import com.bbgusa.bbgdemo.ui.cms.tablet.TopicList;
import com.bbgusa.bbgdemo.ui.phone.MainActivity;
import com.bbgusa.bbgdemo.ui.tablet.onGridViewVisibilityChangedListener;
import com.bbgusa.bbgdemo.utils.common.UCConstants;
import com.bbgusa.bbgdemo.utils.common.UConnectUtils;
import com.viewpagerindicator.IconPageIndicator;
import com.viewpagerindicator.IconPagerAdapter;
import com.viewpagerindicator.PageIndicator;
public class HomeFragment extends Fragment implements onGridViewVisibilityChangedListener{
private static final String TAG = HomeFragment.class.getSimpleName();
private ViewPager mViewPager;
private MainActivity activity;
private PageIndicator mIndicator;
private Animation mRotateAnim;
private Dialog indiacatorDialog;
private LinearLayout homeFragmentLL;
private static HomeFragment homeFragment;
public static final HomeFragment getInstance() {
return homeFragment;
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
this.activity = (MainActivity) activity;
}
#Override
public void onCreate(Bundle savedInstanceState) {
Log.i(TAG, "onCreate");
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
if (container == null) {
return null;
}
View v = inflater.inflate(R.layout.home_phone, container, false);
homeFragment = this;
UConnectUtils.setLauncher(true);
mViewPager = (ViewPager) v.findViewById(R.id.viewpager);
mIndicator = (IconPageIndicator) v.findViewById(R.id.indicator);
homeFragmentLL = (LinearLayout) v.findViewById(R.id.homeFragment);
indiacatorDialog = new Dialog(getActivity());
indiacatorDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
indiacatorDialog.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
indiacatorDialog.setContentView(R.layout.indicator_dialog);
indiacatorDialog.setCanceledOnTouchOutside(false);
Window window = indiacatorDialog.getWindow();
window.setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT));
mRotateAnim = AnimationUtils.loadAnimation(getActivity(), R.anim.rotate_and_scale);
UConnectUtils.addAnimationFrameCount(mRotateAnim);
indicatorAnim();
// for property id
// if (activity.isInterNetAvailable()) {
Log.i(TAG, "onCreateView========== isInterNetAvailable");
new CmsPropertyAsync(activity).execute(UCConstants.CMS_CONFIG_URL, UCConstants.CMS_CONFIG_KEY);
// }
return v;
}
protected void parseJson(JSONObject rootResponce) {
TestTopics.imageUrls.clear();
TestTopics.titles.clear();
TestTopics.mMainMenuID.clear();
TestTopics.mViewType.clear();
TestTopics.mPhoneNo.clear();
try {
//get the Version
String version = rootResponce.optString("VERSION");
SharedPreferences mPref;
SharedPreferences.Editor edit;
mPref = PreferenceManager.getDefaultSharedPreferences(getActivity().getApplicationContext());
edit = mPref.edit();
edit.putString(getResources().getString(R.string.pref_cms_version_key), version).commit();
JSONArray jsonArray = rootResponce.getJSONArray("MAINMENU");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject childMenuObject = jsonArray.getJSONObject(i);
int mainMenuID = childMenuObject.optInt("mainMenuId");
String title = childMenuObject.optString("title");
String viewType = childMenuObject.optString("viewType");
String imageUrl = childMenuObject.optString("imageUrl");
String phoneNo = childMenuObject.optString("phoneNo");
TestTopics.mMainMenuID.add(mainMenuID);
TestTopics.imageUrls.add(imageUrl);
TestTopics.titles.add(title);
TestTopics.mViewType.add(viewType);
TestTopics.mPhoneNo.add(phoneNo);
}
// Create a TopicList for this demo. Save it as the shared instance
// in
// TopicList
String sampleText = getResources().getString(R.string.sample_topic_text);
TopicList tlist = new TopicList(sampleText);
TopicList.setInstance(tlist);
// Create an adapter object that creates the fragments that we need
// to display the images and titles of all the topics.
MyAdapter mAdapter = new MyAdapter(getActivity().getSupportFragmentManager(), tlist, getResources());
// mViewPager.removeAllViews();
mViewPager.setAdapter(mAdapter);
// mViewPager.setPageTransformer(true, new DepthPageTransformer());
mIndicator.setViewPager(mViewPager);
mIndicator.setCurrentItem(0);
mIndicator.notifyDataSetChanged();
ViewTreeObserver observer = mViewPager.getViewTreeObserver();
observer.addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
#SuppressLint("NewApi")
#SuppressWarnings("deprecation")
#Override
public void onGlobalLayout() {
mViewPager.bringChildToFront(mViewPager.getChildAt(0));
if(Build.VERSION.SDK_INT >= UCConstants.ICE_CREAM_SANDWICH_MR1){
mViewPager.getViewTreeObserver().removeOnGlobalLayoutListener(this);
}else{
mViewPager.getViewTreeObserver().removeGlobalOnLayoutListener(this);
}
}
});
/*Fragment f = new GridViewFragment();
FragmentTransaction t = getFragmentManager().beginTransaction();
t.replace(R.id.main_home_frag, f);
t.commit();*/
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Adapter class
*
* This adapter class sets up GridFragment objects to be displayed by a
* ViewPager.
*/
public static class MyAdapter extends FragmentStatePagerAdapter implements IconPagerAdapter {
private TopicList mTopicList;
private int mNumItems = 0;
private int mNumFragments = 0;
/**
* Return a new adapter.
*/
public MyAdapter(FragmentManager fm, TopicList db, Resources res) {
super(fm);
setup(db, res);
}
/**
* Get the number of fragments to be displayed in the ViewPager.
*/
#Override
public int getCount() {
Log.i(TAG, "getCount : mNumFragments = "+mNumFragments);
return mNumFragments;
}
/**
* Return a new GridFragment that is used to display n items at the
* position given.
*
* #param position
* int - the position of the fragement; 0..numFragments-1
*/
#Override
public Fragment getItem(int position) {
// Create a new Fragment and supply the fragment number, image
// position, and image count as arguments.
// (This was how arguments were handled in the original pager
// example.)
Bundle args = new Bundle();
args.putInt("num", position + 1);
args.putInt("firstImage", position * mNumItems);
// The last page might not have the full number of items.
int imageCount = mNumItems;
if (position == (mNumFragments - 1)) {
int numTopics = mTopicList.getNumTopics();
int rem = numTopics % mNumItems;
if (rem > 0)
imageCount = rem;
}
args.putInt("imageCount", imageCount);
args.putSerializable("topicList", TopicList.getInstance());
// Return a new GridFragment object.
Log.i(TAG, "created fragmenat number:==== "+position+" "+1);
GridViewFragmentPhone f = new GridViewFragmentPhone();
f.setArguments(args);
Log.i(TAG, "getItem : imageCount = "+imageCount);
return f;
}
/**
* Set up the adapter using information from a TopicList and resources
* object. When this method completes, all the instance variables of the
* adapter are valid;
*
* #param tlist
* TopicList
* #param res
* Resources
* #return void
*/
void setup(TopicList tlist, Resources res) {
mTopicList = tlist;
if ((tlist == null) || (res == null)) {
mNumItems = 2;//DEFAULT_NUM_ITEMS;
mNumFragments = 2;//DEFAULT_NUM_FRAGMENTS;
} else {
int numTopics = tlist.getNumTopics();
int numRowsGV = res.getInteger(R.integer.num_of_rows_gridview);
int numColsGV = res.getInteger(R.integer.num_of_cols_gridview);
int numTopicsPerPage = numRowsGV * numColsGV;
int numFragments = numTopics / numTopicsPerPage;
if (numTopics % numTopicsPerPage != 0)
numFragments++; // Add one if there is a partial page
mNumFragments = numFragments;
mNumItems = numTopicsPerPage;
}
} // end setup
#Override
public int getIconResId(int index) {
int[] ICON = new int[mNumFragments];
for (int i = 0; i < mNumFragments; i++) {
ICON[i] = R.drawable.slidericon;
}
return ICON[index % ICON.length];
}
} // end class MyAdapter
#Override
public void onGridViewVisibilityChanged(boolean hide) {
if(hide){
homeFragmentLL.setVisibility(View.GONE);
}else {
homeFragmentLL.setVisibility(View.VISIBLE);
}
}
#Override
public void onDetach() {
super.onDetach();
activity = null;
}
#Override
public void onDestroy() {
super.onDestroy();
}
private class CmsPropertyAsync extends AsyncTask<String, Void, String> {
MainActivity context;
CmsPropertyAsync(MainActivity activityTab) {
context = activityTab;
}
#Override
protected String doInBackground(String... params) {
String propertyId = UConnectUtils.getPropertyId(PreferenceManager.getDefaultSharedPreferences(context),getResources().getString(R.string.property_id));
if(propertyId != null && propertyId.length() > 0){
return propertyId;
}
return UConnectUtils.requestPropertyId(params[0], params[1]);
}
#Override
protected void onPostExecute(String propertyId) {
if(propertyId == null){
indiacatorDialog.dismiss();
showPropertyIdTimeoutAlert(getActivity());
return;
}
SharedPreferences.Editor editor = PreferenceManager.getDefaultSharedPreferences(context).edit();
editor.putString(getString(R.string.property_id),propertyId).commit();
String url = null;
String locale = Locale.getDefault().getLanguage();
url = UCConstants.CMS_BASE_URL+"mainMenu?propertyId="+propertyId+"&lang="+locale;
JsonObjectRequest jsObjRequest = new JsonObjectRequest(
Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
parseJson(response);
indiacatorDialog.dismiss();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
if (activity != null) {
// activity.getConnection(error);
}
indiacatorDialog.dismiss();
}
});
ImageCacheManager.getInstance().getQueueForMainmenu().add(jsObjRequest);
}
}
private void indicatorAnim() {
if (indiacatorDialog != null) {
ImageView alertIndicator = (ImageView) indiacatorDialog.findViewById(R.id.alert_indicator);
alertIndicator.startAnimation(mRotateAnim);
if (!getActivity().isFinishing()) {
indiacatorDialog.show();
}
}
}
// Show alert for Time out
private void showPropertyIdTimeoutAlert(final Activity context) {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(context);
alertDialog.setIcon(R.drawable.alert_dialog_icon);
alertDialog.setTitle(context.getString(R.string.timeout_msg));
alertDialog.setMessage(context.getString(R.string.timeout_msg2));
alertDialog.setPositiveButton("OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
indicatorAnim();
// for property id
new CmsPropertyAsync(activity).execute(UCConstants.CMS_CONFIG_URL, UCConstants.CMS_CONFIG_KEY);
}
});
alertDialog.setNegativeButton("Cancel", new OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
getActivity().finish();
}
});
AlertDialog alert = alertDialog.create();
alert.setCancelable(false);
alert.setCanceledOnTouchOutside(false);
if (context != null && !context.isFinishing()) {
alert.show();
}
}
}
Actually, some data is being saved with onSavedInstaceState(). The data is not being deleted when process has been killed on LowMemory.
I fixed this with
#Override
protected void onSaveInstanceState(Bundle outState) {
//super.onSaveInstanceState(outState);
}
Just do not call super class. Just comment like above