So I have a CameraFragment which is called from MainFragment.The problem is I am using a custom Listener to pass the image Data to MainFragment.java.Here is how I call the CameraFragment.java
In MainFragment.java:
public static class MainFragment extends Fragment implements CameraFragment.CameraFragmentHolder.CameraListener {
ImageView mImageView;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
mImageView = (ImageView) rootView.findViewById(R.id.image_view);
return rootView;
}
private OnClickListener onCameraFragmentClicked = new OnClickListener() {
#Override
public void onClick(View v) {
FragmentTransaction fragmentTransaction = getActivity().getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.container, CameraFragment.CameraFragmentHolder.newInstance(MainFragmentHolder.this, 0, false));
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
}
};
#Override
public void onImageSaved(byte[] data) {
if (data != null) {
Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);
mImageView.setImageBitmap(bitmap);
}
} else {
Log.v(TAG, "Didn't get any result");
}
}
}
Then in CameraFragment.java I implement the following:
CameraFragment.java
private byte[] mCameraData;
private CameraListener mListener;
public interface CameraListener {
public void onImageSaved(byte[] data);
}
private OnClickListener mDoneButtonClickListener = new OnClickListener() {
#Override
public void onClick(View v) {
if (mCameraData != null) {
removeCameraView();
sendImageDataToListener();
} else {
mCamera = null;
removeCameraView();
}
}
};
//Send image back to Listener
private void sendImageDataToListener() {
if (mCameraData != null) {
mListener.onImageSaved(mCameraData);
} else {
Log.v("CAMERA IMAGE ERROR:", "NO IMAGE DATA");
}
}
private void removeCameraView() {
getActivity().getSupportFragmentManager().popBackStack();
}
My problem is in MainFragment in the CallBackListener when I try to setImageBitmap nothing happens.
So #Selvin it 's actually possible. What I did was onViewStateRestored. I read over the android API a bit. This shouldn't give any problems but I 'm still skeptical about it since I' ve not fully tested it.i modified the MainFragment.java as follows.
In the MainFragment.java:
Bitmap cameraImage;
#Override
public void onViewStateRestored(Bundle savedInstanceState) {
super.onViewStateRestored(savedInstanceState);
if (cameraImage != null) {
mImageView.setImageBitmap(cameraImage);
}
}
#Override
public void onImageSaved(byte[] data) {
if (data != null) {
Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);
cameraImage = bitmap;
}
} else {
Log.v(TAG, "Didn't get any result");
}
Related
I'm getting the object from modelView as you guys see.
Every thing is perfectly working apart from my viewpager fragment when I first come to my pager fragment it shows data when I go through forward and then come backward it disappears my data and my layout structure.
My viewModel have data always have a data but my recyclerview is not showing it.
BrandFragment is a base fragment having viewpager in it.
BrandFragment :
public class BrandFragment extends Fragment {
#BindView(R.id.brandtablayout)
TabLayout brandtablayout;
#BindView(R.id.brandpager)
ViewPager brandpager;
#BindView(R.id.backgroundImage)
ImageView backgroundImage;
#BindView(R.id.brandIcon)
CircleImageView brandIcon;
#BindView(R.id.brandName)
TextView brandName;
#BindView(R.id.brandTagLine)
TextView brandTagLine;
#BindView(R.id.brandRatingBar)
RatingBar brandRatingBar;
#BindView(R.id.noInternet)
ImageView noInternet;
private Brand brand;
int chipId;
private KProgressHUD mProgressBar;
private ShareViewModel shareViewModel;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_brand, container, false);
brandpager = view.findViewById(R.id.brandpager);
brandtablayout = view.findViewById(R.id.brandtablayout);
backgroundImage = view.findViewById(R.id.backgroundImage);
brandIcon = view.findViewById(R.id.brandIcon);
brandName = view.findViewById(R.id.brandName);
brandTagLine= view.findViewById(R.id.brandTagLine);
brandRatingBar = view.findViewById(R.id.brandRatingBar);
noInternet = view.findViewById(R.id.noInternet);
brandtablayout.addTab(brandtablayout.newTab().setText("Product"));
brandtablayout.addTab(brandtablayout.newTab().setText("Profile"));
brandtablayout.setTabGravity(TabLayout.GRAVITY_FILL);
BrandProfileViewPagerAdapter brandProfileAdapter = new BrandProfileViewPagerAdapter(getFragmentManager(), brandtablayout.getTabCount());
brandpager.setAdapter(brandProfileAdapter);
brandtablayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
brandpager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
progressbar("Getting Brand Detail","Please wait...");
return view;
}
private void getBrandDetails() {
WebServiceFactory.getInstance().getBrandDetails(chipId).enqueue(new Callback<Brand>() {
#Override
public void onResponse(Call<Brand> call, Response<Brand> response) {
if (response.body().getFlag() == 1) {
brand = response.body();
shareViewModel.setBrandProductsMutableLiveData(brand.getBrandProducts());
shareViewModel.setBrandSpecificationsMutableLiveData(brand.getBrandSpecifications());
brandProfileDetails();
mProgressBar.dismiss();
}else {
mProgressBar.dismiss();
}
}
#Override
public void onFailure(Call<Brand> call, Throwable t) {
mProgressBar.dismiss();
}
});
}
private void brandProfileDetails(){
if (brand.getBrandSpecifications() != null){
brandRatingBar.setRating(brand.getBrandSpecifications().getBrandRates());
brandName.setText(brand.getBrandSpecifications().getBrandName());
Picasso.get().load(AppConstants.imagePath(brand.getBrandSpecifications().getBrandBg())).into(backgroundImage);
brandTagLine.setText(brand.getBrandSpecifications().getBrandSlogan());
Picasso.get().load(AppConstants.imagePath(brand.getBrandSpecifications().getBrandIcon())).into(brandIcon);
}
mProgressBar.dismiss();
}
#Override
public void onViewCreated (#NonNull View view, #Nullable Bundle savedInstanceState){
super.onViewCreated(view, savedInstanceState);
shareViewModel = ViewModelProviders.of((FragmentActivity) requireActivity()).get(ShareViewModel.class);
shareViewModel.getChipId().observe(getViewLifecycleOwner(), new Observer<Integer>() {
#Override
public void onChanged(Integer id) {
chipId =id;
if (InternetConnection.checkConnection(getContext())) {
// Internet Available...
noInternet.setVisibility(View.GONE);
getBrandDetails();
} else {
noInternet.setVisibility(View.VISIBLE);
mProgressBar.dismiss();
Toast.makeText(getContext(), "Check your internet Connection", Toast.LENGTH_SHORT).show();
// Internet Not Available...
}
}
});
}
private void progressbar(String title, String detail){
mProgressBar = KProgressHUD.create(getContext())
.setStyle(KProgressHUD.Style.SPIN_INDETERMINATE)
.setLabel(title)
.setDetailsLabel(detail)
.setCancellable(false)
.setAnimationSpeed(2)
.setDimAmount(0.5f)
.show();
}
}
BrandProductFragment :
public class BrandProductFragment extends Fragment implements RecyclerviewOnClickInterface, CategoryRecyclerviewInterface, ChipsInterface, MyButtonClickListener {
int tabCount;
#BindView(R.id.brandPopularProduct)
TextView brandPopularProduct;
#BindView(R.id.brandNewProduct)
TextView brnadNewProduct;
#BindView(R.id.brandHighestProduct)
TextView brandHighestProduct;
#BindView(R.id.brandLowestProduct)
TextView brandLowestProduct;
#BindView(R.id.brandProductRecyclerview)
RecyclerView brandProductRecyclerview;
BrandProfilePopularAdapter brandProfilePopularAdapter;
BrandNewReleaseAdapter brandNewReleaseAdapter;
BrandProductHighestAdapter brandProductHighestAdapter;
BrandLowestAdapter brandLowestAdapter;
BrandProducts brandProductData;
ShareViewModel shareViewModel;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_brand_product, container, false);
tabCount = 0;
brandPopularProduct = view.findViewById(R.id.brandPopularProduct);
brnadNewProduct = view.findViewById(R.id.brandNewProduct);
brandHighestProduct = view.findViewById(R.id.brandHighestProduct);
brandLowestProduct = view.findViewById(R.id.brandLowestProduct);
brandProductRecyclerview = view.findViewById(R.id.brandProductRecyclerview);
buttonOnClick();
return view;
}
private void buttonOnClick() {
brandPopularProduct.setOnClickListener(v -> {
tabCount = 1;
tabSelector();
if (brandProductData != null) {
getBrandProductPopular(brandProductData);
}
});
brnadNewProduct.setOnClickListener(v -> {
tabCount = 2;
tabSelector();
if (brandProductData != null) {
getBrandProductNewRelease();
}
});
brandHighestProduct.setOnClickListener(v -> {
tabCount = 3;
tabSelector();
if (brandProductData != null) {
getBrandProductHighest();
}
});
brandLowestProduct.setOnClickListener(v -> {
tabCount = 4;
tabSelector();
if (brandProductData != null) {
getBrandProductLowest();
}
});
}
private void tabSelector() {
if (tabCount == 1) {
brandPopularProduct.setTextColor(ContextCompat.getColor(getContext(), R.color.fontColor));
brandPopularProduct.setTextSize(20);
brnadNewProduct.setTextSize(18);
brandLowestProduct.setTextSize(18);
brandHighestProduct.setTextSize(18);
brnadNewProduct.setTextColor(ContextCompat.getColor(getContext(), R.color.fontColor2));
brandHighestProduct.setTextColor(ContextCompat.getColor(getContext(), R.color.fontColor2));
brandLowestProduct.setTextColor(ContextCompat.getColor(getContext(), R.color.fontColor2));
} else if (tabCount == 2) {
brnadNewProduct.setTextColor(ContextCompat.getColor(getContext(), R.color.fontColor));
brandPopularProduct.setTextSize(18);
brnadNewProduct.setTextSize(20);
brandLowestProduct.setTextSize(18);
brandHighestProduct.setTextSize(18);
brandPopularProduct.setTextColor(ContextCompat.getColor(getContext(), R.color.fontColor2));
brandHighestProduct.setTextColor(ContextCompat.getColor(getContext(), R.color.fontColor2));
brandLowestProduct.setTextColor(ContextCompat.getColor(getContext(), R.color.fontColor2));
} else if (tabCount == 3) {
brandHighestProduct.setTextColor(ContextCompat.getColor(getContext(), R.color.fontColor));
brandPopularProduct.setTextSize(18);
brnadNewProduct.setTextSize(18);
brandLowestProduct.setTextSize(18);
brandHighestProduct.setTextSize(20);
brnadNewProduct.setTextColor(ContextCompat.getColor(getContext(), R.color.fontColor2));
brandPopularProduct.setTextColor(ContextCompat.getColor(getContext(), R.color.fontColor2));
brandLowestProduct.setTextColor(ContextCompat.getColor(getContext(), R.color.fontColor2));
} else if (tabCount == 4) {
brandLowestProduct.setTextColor(ContextCompat.getColor(getContext(), R.color.fontColor));
brandPopularProduct.setTextSize(18);
brnadNewProduct.setTextSize(18);
brandLowestProduct.setTextSize(20);
brandHighestProduct.setTextSize(18);
brnadNewProduct.setTextColor(ContextCompat.getColor(getContext(), R.color.fontColor2));
brandHighestProduct.setTextColor(ContextCompat.getColor(getContext(), R.color.fontColor2));
brandPopularProduct.setTextColor(ContextCompat.getColor(getContext(), R.color.fontColor2));
}
}
private void getBrandProductPopular(BrandProducts brandProductData) {
if (brandProductData.getPOPULARPRODUCTS() != null){
brandProfilePopularAdapter = new BrandProfilePopularAdapter(getContext(), brandProductData.getPOPULARPRODUCTS(), this);
GridLayoutManager mLayoutManager = new GridLayoutManager(getContext(), 2);
brandProductRecyclerview.setLayoutManager(mLayoutManager);
brandProductRecyclerview.setAdapter(brandProfilePopularAdapter);
recyclerviewAnimation(brandProductRecyclerview);
}
}
private void getBrandProductNewRelease() {
if ( brandProductData.getNEWRELEASEPRODUCTS() != null){
brandNewReleaseAdapter = new BrandNewReleaseAdapter(getContext(), brandProductData.getNEWRELEASEPRODUCTS(), this);
GridLayoutManager mLayoutManager = new GridLayoutManager(getContext(), 2);
brandProductRecyclerview.setLayoutManager(mLayoutManager);
brandProductRecyclerview.setAdapter(brandNewReleaseAdapter);
recyclerviewAnimation(brandProductRecyclerview);
}
}
private void getBrandProductHighest() {
if (brandProductData.getHIGHESTPRODUCTS() != null){
brandProductHighestAdapter = new BrandProductHighestAdapter(getContext(), brandProductData.getHIGHESTPRODUCTS(), this);
GridLayoutManager mLayoutManager = new GridLayoutManager(getContext(), 2);
brandProductRecyclerview.setLayoutManager(mLayoutManager);
brandProductRecyclerview.setAdapter(brandProductHighestAdapter);
recyclerviewAnimation(brandProductRecyclerview);
}
}
private void getBrandProductLowest() {
if ( brandProductData.getLOWESTPRODUCTS() != null){
brandLowestAdapter = new BrandLowestAdapter(getContext(), brandProductData.getLOWESTPRODUCTS(), this);
GridLayoutManager mLayoutManager = new GridLayoutManager(getContext(), 2);
brandProductRecyclerview.setLayoutManager(mLayoutManager);
brandProductRecyclerview.setAdapter(brandLowestAdapter);
recyclerviewAnimation(brandProductRecyclerview);
}
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
shareViewModel = ViewModelProviders.of((FragmentActivity) getContext()).get(ShareViewModel.class);
shareViewModel.getBrandProduct().observe(getViewLifecycleOwner(), new Observer<BrandProducts>() {
#Override
public void onChanged(BrandProducts brandProducts) {
Log.e("getBrands", brandProducts.toString());
brandProductData = brandProducts;
getBrandProductPopular(brandProductData);
}
});
}
private void recyclerviewAnimation(RecyclerView recyclerView) {
Context context = recyclerView.getContext();
LayoutAnimationController layoutAnimationController = AnimationUtils.loadLayoutAnimation(context, R.anim.layout_animation_fall_down);
recyclerView.setLayoutAnimation(layoutAnimationController);
recyclerView.getAdapter().notifyDataSetChanged();
recyclerView.scheduleLayoutAnimation();
}
int productId;
#Override
public void onItemClick(int position) {
shareViewModel.setProductIdMutable(brandProductData.getPOPULARPRODUCTS().get(position).getProductId());
fragmentTransaction();
}
#Override
public void onItemClickCategory(int position) {
shareViewModel.setProductIdMutable(brandProductData.getNEWRELEASEPRODUCTS().get(position).getProductId());
fragmentTransaction();
}
#Override
public void onChipItemClick(int position) {
shareViewModel.setProductIdMutable(brandProductData.getHIGHESTPRODUCTS().get(position).getProductId());
fragmentTransaction();
}
#Override
public void onclick(int position) {
shareViewModel.setProductIdMutable(brandProductData.getLOWESTPRODUCTS().get(position).getProductId());
fragmentTransaction();
}
private void fragmentTransaction() {
Bundle bundle = new Bundle();
bundle.putString("BrandProduct", "brand");
PreviewProductFragment previewProductFragment = new PreviewProductFragment();
previewProductFragment.setArguments(bundle);
FragmentTransaction fragmentTransaction = getFragmentManager().beginTransaction().addToBackStack("");
fragmentTransaction.setCustomAnimations(R.anim.enter_right_to_left, R.anim.exit_right_to_left);
fragmentTransaction.replace(R.id.tabbed_framelayout, previewProductFragment);
fragmentTransaction.commit();
}
}
BrandProfileViewPagerAdapter this is my viewPager Adapter :
public class BrandProfileViewPagerAdapter extends FragmentStatePagerAdapter {
private int tabCount;
public BrandProfileViewPagerAdapter(#NonNull FragmentManager fm, int tabs) {
super(fm, tabs);
this.tabCount=tabs;
}
#NonNull
#Override
public Fragment getItem(int position) {
switch (position){
case 0:
BrandProductFragment brandProductFragment = new BrandProductFragment();
return brandProductFragment;
case 1:
BrandProfileFragment brandProfileFragment= new BrandProfileFragment();
return brandProfileFragment;
default:
return null;
}
}
#Override
public int getCount() {
return tabCount;
}
}
Before :
After :
a problem in my code arose after fixing some other bugs. My activity which "should" show detailed information of movies doesn't get displayed properly instead, just a blank activity opens.
my detail activity:
public class detailsActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_details);
Intent intent = getIntent();
String fragment = intent.getExtras().getString("FRAGMENT");
if(fragment.equals("MOVIE")) {
MovieGridFragment frag = new MovieGridFragment();
getSupportFragmentManager().beginTransaction().replace(R.id.fl_detail_fragment,frag).commit();
} else {
getFragmentManager().beginTransaction().replace(R.id.fl_detail_fragment, new displayMovieDetails()).commit();
}
}}
the mainActivity :
public class MainActivity extends AppCompatActivity implements clickInterfaceHelper {
public static String sorterString = null;
public static String urlBase = "https://api.themoviedb.org/3/movie/";
public static String urlFinal = null;
RequestQueue requestQueue;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if(savedInstanceState == null) {
MovieGridFragment fragment = new MovieGridFragment();
fragment.setClickListener(this);
getSupportFragmentManager().beginTransaction()
.add(R.id.activity_container, fragment)
.commit();
movieData.movieDataPosition = 0;
}
if(savedInstanceState != null) {
sorterString = savedInstanceState.getString("SORTER");
}
if(savedInstanceState == null)
movieData.movieDataPosition = 0;
if(sorterString==null)
sorterString="popular?";
if(sorterString!="favorite" && sorterString!=null) {
if(networkChecker.isNetworkAvailableChecker(this)) {
movieRequest();
}
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main_menu_act, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if(id == R.id.m_popularity_action) {
if(sorterString != "popular?") {
sorterString = "popular?";
if(networkChecker.isNetworkAvailableChecker(this))
movieRequest();
}
return true;
}
if(id == R.id.m_action_voter) {
if(sorterString != "top_rated?") {
sorterString = "top_rated?";
if(networkChecker.isNetworkAvailableChecker(this))
movieRequest();
}
return true;
}
if(id == R.id.m_favorite_btn) {
if(sorterString != "favorite") {
SQLiteOpenHelper helper = new movieDataDbHelper(this);
SQLiteDatabase database = helper.getReadableDatabase();
Cursor cursor= database.query(movieDataContract.contractEntry.TABLE_NAME,
new String[] {
movieDataContract.contractEntry.ID,
movieDataContract.contractEntry.IMG_PATH},null,null,null,null,null);
if(cursor.getCount() == 0) {
Toast.makeText(this, "there are no favorite movies yet!",Toast.LENGTH_SHORT).show();
} else {
sorterString = "favorite";
showFavoriteFragment();
}
database.close();
helper.close();
cursor.close();
}
return true;
}
return super.onOptionsItemSelected(item);
}
public void showFavoriteFragment() {
favoriteMoviesDetailsFragment fragment = new favoriteMoviesDetailsFragment();
try {
getFragmentManager().beginTransaction().replace(R.id.activity_container,fragment).commit();
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public void onSaveInstanceState(Bundle outState, PersistableBundle outPersistentState) {
outState.putString("SORTER", sorterString);
outState.putInt("POSITION",movieData.movieDataPosition);
super.onSaveInstanceState(outState, outPersistentState);
}
public void movieRequest() {
final MovieGridFragment gridFragment = new MovieGridFragment();
gridFragment.setClickListener(this);
urlFinal = urlBase + sorterString + movieData.apiKey;
urlFinal.trim();
requestQueue = Volley.newRequestQueue(this);
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, urlFinal, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONArray array = response.getJSONArray("results");
movieData.movieDataArray = new movieData[array.length()];
for (int i = 0; i < array.length(); i++) {
movieData movie = new movieData();
JSONObject jsonObject = array.getJSONObject(i);
movie.setMovieId(jsonObject.getString("id"));
movie.setMovieImagePath(jsonObject.getString("poster_path"));
movie.setMovieTitle(jsonObject.getString("original_title"));
movie.setMoviePlot(jsonObject.getString("overview"));
movie.setMovieVoting(jsonObject.getString("vote_average"));
movie.setMovieReleaseDate(jsonObject.getString("release_date"));
movieData.movieDataArray[i] = movie;
}
gridFragment.movieDataList = Arrays.asList(movieData.movieDataArray);
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.activity_container, gridFragment);
try {
transaction.commitAllowingStateLoss();
} catch (Exception e) {
e.printStackTrace();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("volley", String.valueOf(error));
}
}
);
requestQueue.add(jsonObjectRequest);
}
#Override
public void clickOnItem(int id) {
movieData.movieDataPosition = id;
if(movieData.movieDataArray == null) {
movieRequest();
} else {
Intent intent = new Intent(this, detailsActivity.class);
intent.putExtra("FRAGMENT","MOVIE");
startActivity(intent);
}
}
#Override
public void favoriteMovieItem(int movieId) {
movieData.dbPosition = movieId;
Intent intent = new Intent(this,detailsActivity.class);
intent.putExtra("FRAGMENT","favorite");
startActivity(intent);
}
}
and the movieFragment which should display the data:
public class MovieGridFragment extends Fragment {
public clickInterfaceHelper clickListener;
private GridView movieGridView;
private int index;
public List<movieData> movieDataList = new ArrayList<>();
public MovieGridFragment() {} //empty constructor
#Override
public void onAttach(Context context) {
//this.clickListener = (clickInterfaceHelper) context;
super.onAttach(context);
}
public void setClickListener(clickInterfaceHelper listener) {
this.clickListener = listener;
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
setHasOptionsMenu(true);
if(movieDataList.isEmpty() && networkChecker.isNetworkAvailableChecker(getContext())) {
movieDataList = new ArrayList<movieData>();
}
if(!movieDataList.isEmpty() && !networkChecker.isNetworkAvailableChecker(getContext())) {
movieDataList = new ArrayList<movieData>();
}
if(savedInstanceState != null) {
index = savedInstanceState.getInt("INDEX");
if(movieDataList.isEmpty()) {
movieDataList.addAll(Arrays.asList((movieData[]) savedInstanceState.getSerializable("OLDMOVIEDATA")));
}
}
View rootView = inflater.inflate(R.layout.movie_display_fragment, container, false);
movieGridView = (GridView) rootView.findViewById(R.id.gv_movie_display);
movieAdapter adapter = new movieAdapter(getActivity(),movieDataList);
adapter.notifyDataSetChanged();
movieGridView.setAdapter(adapter);
movieGridView.smoothScrollToPosition(index);
movieGridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
if(clickListener != null)
clickListener.clickOnItem(position);
}
});
return rootView;
}
#Override
public void onSaveInstanceState(Bundle outState) {
outState.putSerializable("OLDMOVIEDATA",movieData.movieDataArray);
outState.putInt("INDEX",movieGridView.getFirstVisiblePosition());
super.onSaveInstanceState(outState);
}
}
the activity_details layout:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context=".detailsActivity">
<FrameLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/fl_detail_fragment">
</FrameLayout>
</LinearLayout>
You should use getSupportFragmentManager().beginTransaction().add() for the first time.
Then when you added a fragment before you should use getSupportFragmentManager().beginTransaction().replace()
EDIT
public class MovieGridFragment extends Fragment {
public clickInterfaceHelper clickListener;
private GridView movieGridView;
private int index;
public List<movieData> movieDataList = new ArrayList<>();
public void setMovieDataList(List<movieData> movieDataList) {
this.movieDataList = movieDataList;
}
public void setClickListener(clickInterfaceHelper listener) {
this.clickListener = listener;
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
setHasOptionsMenu(true);
View rootView = inflater.inflate(R.layout.movie_display_fragment, container, false);
movieGridView = (GridView) rootView.findViewById(R.id.gv_movie_display);
if (movieDataList != null) {
initMovieGrid();
}
return rootView;
}
private void initMovieGrid() {
movieAdapter adapter = new movieAdapter(getActivity(), movieDataList);
adapter.notifyDataSetChanged();
movieGridView.setAdapter(adapter);
movieGridView.smoothScrollToPosition(index);
movieGridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
if (clickListener != null)
clickListener.clickOnItem(position);
}
});
}
}
To use the fragment:
MovieGridFragment fragment = new MovieGridFragment();
fragment.setClickListener(this);
fragment.setMovieDataList(movieDataList);
getSupportFragmentManager().beginTransaction()
.add(R.id.activity_container, fragment).commit();
If you don't have the the list of movies before you use your fragment, you could use this code for fragment:
public class MovieGridFragment extends Fragment {
public clickInterfaceHelper clickListener;
private GridView movieGridView;
private int index;
public List<movieData> movieDataList = new ArrayList<>();
public void setMovieDataList(List<movieData> movieDataList) {
this.movieDataList = movieDataList;
if (movieDataList != null) {
initMovieGrid();
}
}
public void setClickListener(clickInterfaceHelper listener) {
this.clickListener = listener;
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
setHasOptionsMenu(true);
View rootView = inflater.inflate(R.layout.movie_display_fragment, container, false);
movieGridView = (GridView) rootView.findViewById(R.id.gv_movie_display);
return rootView;
}
private void initMovieGrid() {
movieAdapter adapter = new movieAdapter(getActivity(), movieDataList);
adapter.notifyDataSetChanged();
movieGridView.setAdapter(adapter);
movieGridView.smoothScrollToPosition(index);
movieGridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
if (clickListener != null)
clickListener.clickOnItem(position);
}
});
}
}
Then create your fragment without using setMovieDataList() and when you get the movies data, use the method setMovieDataList()
public class MainActivity extends AppCompatActivity implements clickInterfaceHelper {
//...
MovieGridFragment mFragment;
//...
Create:
mFragment = new MovieGridFragment();
fragment.setClickListener(this);
getSupportFragmentManager().beginTransaction()
.add(R.id.activity_container, fragment).commit();
After you get the data:
mFragment.setMovieDataList(movieDataList);
You should prepend Intent extras with an unique identifier, but i'm not sure if this is what's causing the problem.
I'm very sorry for your effort but i'm just plain out stupid...
I opened the wrong Fragment....
My recyclerview is not updating correctly after the back button is
pressed.
The recyclerview works fine before the back button is pressed
The data is properly updated (seen in the log) but the recyclerview does not reflect the change
The purpose of the handler is to poll the database for a notification (working fine)
The notification toast is displayed everytime
I am not receiving any errors
If I can provide any other information to help do not hesitate to ask.
Main:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_chat_room);
recView = (RecyclerView) findViewById(R.id.recyclerViewMessages);
linearLayoutManager = new LinearLayoutManager(this) {};
linearLayoutManager.setReverseLayout(true);
recView.setLayoutManager(linearLayoutManager);
listData = (ArrayList) MessagingData.getMessageListData();
adapter = new RecyclerViewAdapterMessaging(listData, this);
recView.setAdapter(adapter);
adapter.setItemClickCallback(this);
final Handler h = new Handler();
final int delay = 2000; //milliseconds
h.postDelayed(new Runnable(){
public void run(){
Notify_Message_Async notify_message_async = new Notify_Message_Async(ctx);
notify_message_async.execute(NOTIFICATION, message_id);
System.out.println(global.getNotification());
if(global.getNotification()==1){
Toast.makeText(ctx, "Notified",
Toast.LENGTH_LONG).show();
try {
refresh_receive();
} catch (ExecutionException e) {
Toast.makeText(ctx, "catch",
Toast.LENGTH_LONG).show();
e.printStackTrace();
} catch (InterruptedException e) {
Toast.makeText(ctx, "catch",
Toast.LENGTH_LONG).show();
e.printStackTrace();
}
}
h.postDelayed(this, delay);
}
}, delay);
}
public void refresh_receive() throws ExecutionException, InterruptedException {
String method = "receive_message";
Receive_Live_Message_Async receive_live_message_async = new Receive_Live_Message_Async(this);
receive_live_message_async.execute(method, message_id).get();// Setup the message
adapter.setListData((ArrayList)MessagingData.getMessageListData());
adapter.notifyDataSetChanged();
global.setNotification(0);//reset notification
}
Adapter:
public class RecyclerViewAdapterMessaging extends RecyclerView.Adapter<RecyclerViewAdapterMessaging.Holder> {
private View v;
private List<List_Item_Messaging> listData;
private LayoutInflater inflater;
Global global = new Global();
private ItemClickCallback itemClickCallback;
Context context;
public interface ItemClickCallback {
void onItemClick(View v, int p);
void onSecondaryIconClick(int p);
}
public void setItemClickCallback(final ItemClickCallback itemClickCallback) {
this.itemClickCallback = itemClickCallback;
}
public RecyclerViewAdapterMessaging(List<List_Item_Messaging> listData, Context c) {
inflater = LayoutInflater.from(c);
context = c;
this.listData = listData;
}
#Override
public int getItemViewType(int position) {//0 for self... /1 for Other
List_Item_Messaging item = listData.get(position);
//ENSURE GLOBAL USERNAME NOT NULL
String other_username = item.getMessage_username();
if (other_username == null) {
((Activity) context).finish();
}
if (item.getMessage_username().trim().equals(global.getUserName())) {
System.out.println("The usernames are the same");
return 0;
} else {
System.out.println("The usernames are the NOT same");
return 1;
}
}
#Override
public Holder onCreateViewHolder(ViewGroup parent, int viewType) {
switch (viewType) {
case 0:
View view = inflater.inflate(R.layout.chat_thread, parent, false);// Self
v = view;
break;
case 1:
View view2 = inflater.inflate(R.layout.chat_thread_other, parent, false);// Not self
int width2 = global.getScreenWidth();
v = view2;
break;
}
return new Holder(v);
}
#Override
public void onBindViewHolder(Holder holder, int position) {
List_Item_Messaging item = listData.get(position);
holder.conversation.setText(item.getMessage_conversation());
}
public void setListData(ArrayList<List_Item_Messaging> exerciseList) {
this.listData.clear();
this.listData.addAll(exerciseList);
}
#Override
public int getItemCount() {
return listData.size();
}
class Holder extends RecyclerView.ViewHolder implements View.OnClickListener {
ImageView thumbnail;
//ImageView secondaryIcon;
TextView conversation;
View message_container;
public Holder(View itemView) {
super(itemView);
conversation = (TextView) itemView.findViewById(R.id.conversation_textview);
message_container = itemView.findViewById(R.id.message_container);
message_container.setOnClickListener(this);
}
#Override
public void onClick(View v) {
if (v.getId() == R.id.message_container) {
itemClickCallback.onItemClick(v, getAdapterPosition());
} else {
itemClickCallback.onSecondaryIconClick(getAdapterPosition());
}
}
}
public void clearItems() {
listData.clear();
this.notifyDataSetChanged();
}
}
I have referenced the following to no solution:
notifyDataSetChanged not working on RecyclerView
smoothScrollToPosition after notifyDataSetChanged not working in android
adapter.notifyDataSetChange() not working after called from onResume()
change a little in your code
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_chat_room);
recView = (RecyclerView) findViewById(R.id.recyclerViewMessages);
linearLayoutManager = new LinearLayoutManager(this) {};
linearLayoutManager.setReverseLayout(true);
recView.setLayoutManager(linearLayoutManager);
// change here
if (listData != null)
listData.clear();
else listData = new <> ArrayList();
listData.addAdd((ArrayList)MessagingData.getMessageListData());
adapter = new RecyclerViewAdapterMessaging(listData, this);
recView.setAdapter(adapter);
adapter.setItemClickCallback(this);
final Handler h = new Handler();
final int delay = 2000; //milliseconds
then make a small change here
public void refresh_receive() throws ExecutionException, InterruptedException {
String method = "receive_message";
Receive_Live_Message_Async receive_live_message_async = new Receive_Live_Message_Async(this);
receive_live_message_async.execute(method, message_id).get();// Setup the message
// changing here
dataList.clear();
dataList.addAdd((ArrayList)MessagingData.getMessageListData())
adapter.setListData(dataList);
adapter.notifyDataSetChanged();
global.setNotification(0);//reset notification
}
another problem in your code, you are using receive_live_message_async AsyncTask
put your update code in onPostExecute
public class receive_live_message_async extends AsyncTask {
#Override
protected Object doInBackground(Object[] objects) {
return null;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected void onPostExecute(Object o) {
// call your refresh_receive(); here
super.onPostExecute(o);
}
}
similarly when you are call receive_live_message_async.execute(); update your recyclerView in onPostExecute
#Override
protected void onPostExecute(Object o) {
dataList.clear();
dataList.addAll((ArrayList)MessagingData.getMessageListData());
adapter.notifyDataSetChanged();
super.onPostExecute(o);
}
So I am trying to pickup Java and especially Android programming. But I am pretty new to this so please have patience :-) This is probably very simple for you Android and Java experts.
What I want to accomplish is loop through all of my friends and create a button for each one of them. The looping part works, the creating of a button does not. You can see in the code what I already tried. The facebook example is using two Activities: MainActivity, PickerActivity and two Fragments: SplashFragment, SelectFragment. I have a a layout for the each Activity and each Fragment. I want to place the button on the selection.xml layout but I am not sure on how to do it. I hope I made myself clear :-)
What I did is, use the facebook sdk and the Scrumptious example I am trying to enhance the friendpicker. The example and especially the friendpicker already works. It shows all my friends I can select them and upon clicking okay I can get them using friendPickerFragment.getSelection();
code from PickerActivity.java:
friendPickerFragment.setOnDoneButtonClickedListener(
new PickerFragment.OnDoneButtonClickedListener() {
#Override
public void onDoneButtonClicked(PickerFragment<?> fragment) {
//here I am getting the selected facebook user
List<GraphUser> FriendListToPlay = friendPickerFragment.getSelection();
for (GraphUser User: FriendListToPlay) {
Log.i("info",User.getId()+' '+User.getName());
/* create button for every facebook user chosen
Button myButton = new Button(PickerActivity.this);
myButton.setText(User.getName() + " waiting for game");
LinearLayout ll = (LinearLayout)findViewById(R.id.linear_view);
LayoutParams lp = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
ll.addView(myButton, lp);
*/
}
finishActivity();
}
});
SelectionFragment:
public class SelectionFragment extends Fragment {
public static String OwnId = "";
public static GraphUser OwnUser = null;
private static final String TAG = "SelectionFragment";
private static final int REAUTH_ACTIVITY_CODE = 100;
private ProfilePictureView profilePictureView;
private TextView userNameView;
private ListView listView;
private List<BaseListElement> listElements;
private UiLifecycleHelper uiHelper;
private Session.StatusCallback callback = new Session.StatusCallback() {
#Override
public void call(final Session session, final SessionState state, final Exception exception) {
onSessionStateChange(session, state, exception);
}
};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
uiHelper = new UiLifecycleHelper(getActivity(), callback);
uiHelper.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
super.onCreateView(inflater, container, savedInstanceState);
View view = inflater.inflate(R.layout.selection,
container, false);
// Find the user's profile picture custom view
profilePictureView = (ProfilePictureView) view.findViewById(R.id.selection_profile_pic);
profilePictureView.setCropped(true);
// Find the user's name view
userNameView = (TextView) view.findViewById(R.id.selection_user_name);
// Find the list view
listView = (ListView) view.findViewById(R.id.selection_list);
// Set up the list view items, based on a list of
// BaseListElement items
listElements = new ArrayList<BaseListElement>();
// Add an item for the friend picker
listElements.add(new PeopleListElement(0));
// Set the list view adapter
listView.setAdapter(new ActionListAdapter(getActivity(),
R.id.selection_list, listElements));
// Check for an open session
Session session = Session.getActiveSession();
if (session != null && session.isOpened()) {
// Get the user's data
makeMeRequest(session);
}
return view;
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REAUTH_ACTIVITY_CODE) {
uiHelper.onActivityResult(requestCode, resultCode, data);
} else if (resultCode == Activity.RESULT_OK) {
// Do nothing for now
}
}
private void makeMeRequest(final Session session) {
// Make an API call to get user data and define a
// new callback to handle the response.
Request request = Request.newMeRequest(session, new Request.GraphUserCallback() {
#Override
public void onCompleted(GraphUser user, Response response) {
// If the response is successful
if (session == Session.getActiveSession()) {
if (user != null) {
// Set the id for the ProfilePictureView
// view that in turn displays the profile picture.
profilePictureView.setProfileId(user.getId());
// Set the Textview's text to the user's name.
userNameView.setText(user.getName());
OwnId = user.getId();
OwnUser = user;
//ServiceAsyncTask task = new ServiceAsyncTask();
//task.run();
}
}
if (response.getError() != null) {
// Handle errors, will do so later.
}
}
});
request.executeAsync();
}
private void onSessionStateChange(final Session session, SessionState state, Exception exception) {
if (session != null && session.isOpened()) {
// Get the user's data.
makeMeRequest(session);
}
}
#Override
public void onResume() {
super.onResume();
uiHelper.onResume();
}
#Override
public void onSaveInstanceState(Bundle bundle) {
super.onSaveInstanceState(bundle);
uiHelper.onSaveInstanceState(bundle);
}
#Override
public void onPause() {
super.onPause();
uiHelper.onPause();
}
#Override
public void onDestroy() {
super.onDestroy();
uiHelper.onDestroy();
}
private class PeopleListElement extends BaseListElement {
public PeopleListElement(int requestCode) {
super(getActivity().getResources().getDrawable(R.drawable.action_people),
getActivity().getResources().getString(R.string.action_people),
getActivity().getResources().getString(R.string.action_people_default),
requestCode);
}
#Override
protected View.OnClickListener getOnClickListener() {
return new View.OnClickListener() {
#Override
public void onClick(View view) {
startPickerActivity(PickerActivity.FRIEND_PICKER, getRequestCode());
}
};
}
#Override
protected void populateOGAction(OpenGraphAction action) {
// TODO Auto-generated method stub
}
}
private class ActionListAdapter extends ArrayAdapter<BaseListElement> {
private List<BaseListElement> listElements;
public ActionListAdapter(Context context, int resourceId, List<BaseListElement> listElements) {
super(context, resourceId, listElements);
this.listElements = listElements;
for (int i = 0; i < listElements.size(); i++) {
listElements.get(i).setAdapter(this);
}
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = convertView;
if (view == null) {
LayoutInflater inflater =
(LayoutInflater) getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(R.layout.listitem, null);
}
BaseListElement listElement = listElements.get(position);
if (listElement != null) {
view.setOnClickListener(listElement.getOnClickListener());
ImageView icon = (ImageView) view.findViewById(R.id.icon);
TextView text1 = (TextView) view.findViewById(R.id.text1);
TextView text2 = (TextView) view.findViewById(R.id.text2);
if (icon != null) {
icon.setImageDrawable(listElement.getIcon());
}
if (text1 != null) {
text1.setText(listElement.getText1());
}
if (text2 != null) {
text2.setText(listElement.getText2());
}
}
return view;
}
}
private void startPickerActivity(Uri data, int requestCode) {
Intent intent = new Intent();
intent.setData(data);
intent.setClass(getActivity(), PickerActivity.class);
startActivityForResult(intent, requestCode);
}
public void createButton() {
}
}
Ok, this is the best I could do without fully knowing the code.
As far as I can tell, then ActionListAdapter is responsible for creating the list of friends. If I am right, then what you need to do is.
Alter res/layout/listitem, adding a Button view with an id, for examples sake let it be btn_friend
// Somewhere in res/layout/listitem
<Button
android:id="#+id/btn_friend"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
Alter ActionListAdapter to set the text an listen for clicks
private class ActionListAdapter extends ArrayAdapter<BaseListElement> {
private List<BaseListElement> listElements;
public ActionListAdapter(Context context, int resourceId, List<BaseListElement> listElements) {
super(context, resourceId, listElements);
this.listElements = listElements;
for (int i = 0; i < listElements.size(); i++) {
listElements.get(i).setAdapter(this);
}
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = convertView;
if (view == null) {
LayoutInflater inflater =
(LayoutInflater) getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(R.layout.listitem, null);
}
BaseListElement listElement = listElements.get(position);
if (listElement != null) {
view.setOnClickListener(listElement.getOnClickListener());
ImageView icon = (ImageView) view.findViewById(R.id.icon);
TextView text1 = (TextView) view.findViewById(R.id.text1);
TextView text2 = (TextView) view.findViewById(R.id.text2);
Button btn = (Button) view.findViewById(R.id.btn_friend);
if (icon != null) {
icon.setImageDrawable(listElement.getIcon());
}
if (text1 != null) {
text1.setText(listElement.getText1());
}
if (text2 != null) {
text2.setText(listElement.getText2());
}
if (btn != null) {
// I do not know exactly what text1 and text2 is
btn.setText(text1 + " waiting for game");
btn.setOnClickListener(new OnClickListener() {
#Override public void onClick(View v) {
Toast.makeText(getActivity(), text1+ " " + text2 + " clicked!", Toast.LENGTH_SHORT).show();
}
});
}
}
return view;
}
}
Hope I have not misunderstood how the code works.
I've got the below code from the AOSP wallpaper selector and im trying to simple display my wallpaper preview image as centerCrop on a tablet and FitXY on a phone, simply because the wallpaper image may not be big enough to fill the activity screen on a tablet therefore i want to centerCrop it.
Now the way im loading my center image is via my fragment and i do not have a specific ImageView i could simple change between to xml files (The easy way). Im just looking for some help on the best way to achieve this.
Here is the code - (Full Code)
public class WallpaperChooser extends Activity {
#Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.wallpaper_chooser_base);
Fragment fragmentView = getFragmentManager().findFragmentById(
R.id.wallpaper_chooser_fragment);
if (fragmentView == null) {
DialogFragment fragment = WallpaperChooserDialogFragment
.newInstance();
fragment.show(getFragmentManager(), "dialog");
}
}
public class WallpaperChooserDialogFragment extends DialogFragment implements
AdapterView.OnItemSelectedListener, AdapterView.OnItemClickListener {
private static final String TAG = "MainActivity.WallpaperChooserDialogFragment";
private static final String EMBEDDED_KEY = "org.app.wallpapers."
+ "WallpaperChooserDialogFragment.EMBEDDED_KEY";
private static final String SD = Environment.getExternalStorageDirectory().getAbsolutePath();
private boolean mEmbedded;
private Bitmap mBitmap = null;
private ImageAdapter mAdapter;
private ImageView image;
private ArrayList<Integer> mThumbs;
private ArrayList<Integer> mImages;
private WallpaperLoader mLoader;
private WallpaperDrawable mWallpaperDrawable = new WallpaperDrawable();
public static WallpaperChooserDialogFragment newInstance() {
WallpaperChooserDialogFragment fragment = new WallpaperChooserDialogFragment();
fragment.setCancelable(true);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (savedInstanceState != null && savedInstanceState.containsKey(EMBEDDED_KEY)) {
mEmbedded = savedInstanceState.getBoolean(EMBEDDED_KEY);
} else {
mEmbedded = isInLayout();
}
}
#Override
public void onSaveInstanceState(Bundle outState) {
outState.putBoolean(EMBEDDED_KEY, mEmbedded);
}
private void cancelLoader() {
if (mLoader != null && mLoader.getStatus() != WallpaperLoader.Status.FINISHED) {
mLoader.cancel(true);
mLoader = null;
}
}
#Override
public void onDetach() {
super.onDetach();
cancelLoader();
}
#Override
public void onDestroy() {
super.onDestroy();
cancelLoader();
}
#Override
public void onDismiss(DialogInterface dialog) {
super.onDismiss(dialog);
/* On orientation changes, the dialog is effectively "dismissed" so this is called
* when the activity is no longer associated with this dying dialog fragment. We
* should just safely ignore this case by checking if getActivity() returns null
*/
Activity activity = getActivity();
if (activity != null) {
activity.finish();
}
}
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
findWallpapers();
return null;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
findWallpapers();
if (mEmbedded) {
View view = inflater.inflate(R.layout.wallpaper_chooser, container, false);
view.setBackgroundDrawable(mWallpaperDrawable);
final Gallery gallery = (Gallery) view.findViewById(R.id.gallery);
gallery.setCallbackDuringFling(false);
gallery.setOnItemSelectedListener(this);
//gallery.setAdapter(new ImageAdapter(getActivity()));
mAdapter = new ImageAdapter(getActivity());
gallery.setAdapter(mAdapter);
return view;
}
return null;
}
private void selectWallpaper(int position) {
try {
WallpaperManager wpm = (WallpaperManager) getActivity().getSystemService(
Context.WALLPAPER_SERVICE);
wpm.setResource(mImages.get(position));
Activity activity = getActivity();
activity.setResult(Activity.RESULT_OK);
activity.finish();
} catch (IOException e) {
Log.e(TAG, "Failed to set wallpaper: " + e);
}
}
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
selectWallpaper(position);
}
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
if (mLoader != null && mLoader.getStatus() != WallpaperLoader.Status.FINISHED) {
//image.startAnimation(animFadeOut);
mLoader.cancel();
}
mLoader = (WallpaperLoader) new WallpaperLoader().execute(position);
}
public void onNothingSelected(AdapterView<?> parent) {
}
private void findWallpapers() {
mThumbs = new ArrayList<Integer>(24);
mImages = new ArrayList<Integer>(24);
final Resources resources = getResources();
final String packageName = resources.getResourcePackageName(R.array.all_wallpapers);
addWallpapers(resources, packageName, R.array.all_wallpapers);
}
private void addWallpapers(Resources resources, String packageName, int list) {
final String[] extras = resources.getStringArray(list);
for (String extra : extras) {
int res = resources.getIdentifier(extra, "drawable", packageName);
if (res != 0) {
final int thumbRes = resources.getIdentifier(extra + "_thumb",
"drawable", packageName);
if (thumbRes != 0) {
mThumbs.add(thumbRes);
mImages.add(res);
}
}
}
}
private class ImageAdapter extends BaseAdapter implements ListAdapter, SpinnerAdapter {
private LayoutInflater mLayoutInflater;
ImageAdapter(Activity activity) {
mLayoutInflater = activity.getLayoutInflater();
}
public int getCount() {
return mThumbs.size();
}
public Bitmap getImage(int i)
{
return getBitmap(((Integer)mImages.get(i)).intValue());
}
public Bitmap getItem(int i)
{
return getBitmap(((Integer)mImages.get(i)).intValue());
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
View view;
if (convertView == null) {
view = mLayoutInflater.inflate(R.layout.wallpaper_item, parent, false);
} else {
//image.startAnimation(animFadeIn);
view = convertView;
}
image = (ImageView) view.findViewById(R.id.wallpaper_image);
int thumbRes = mThumbs.get(position);
image.setImageResource(thumbRes);
Drawable thumbDrawable = image.getDrawable();
if (thumbDrawable != null) {
thumbDrawable.setDither(true);
} else {
Log.e(TAG, "Error decoding thumbnail resId=" + thumbRes + " for wallpaper #"
+ position);
}
return view;
}
}
class WallpaperLoader extends AsyncTask<Integer, Void, Bitmap> {
BitmapFactory.Options mOptions;
WallpaperLoader() {
mOptions = new BitmapFactory.Options();
mOptions.inDither = false;
mOptions.inPreferredConfig = Bitmap.Config.ARGB_8888;
}
#Override
protected Bitmap doInBackground(Integer... params) {
if (isCancelled()) return null;
try {
return BitmapFactory.decodeResource(getResources(),
mImages.get(params[0]), mOptions);
} catch (OutOfMemoryError e) {
return null;
}
}
#Override
protected void onPostExecute(Bitmap b) {
if (b == null) return;
if (!isCancelled() && !mOptions.mCancel) {
// Help the GC
if (mBitmap != null) {
mBitmap.recycle();
}
View v = getView();
if (v != null) {
mBitmap = b;
mWallpaperDrawable.setBitmap(b);
v.postInvalidate();
} else {
mBitmap = null;
mWallpaperDrawable.setBitmap(null);
}
mLoader = null;
} else {
b.recycle();
}
}
void cancel() {
mOptions.requestCancelDecode();
super.cancel(true);
}
}
static class WallpaperDrawable extends Drawable {
Bitmap mBitmap;
int mIntrinsicWidth;
int mIntrinsicHeight;
/* package */void setBitmap(Bitmap bitmap) {
mBitmap = bitmap;
if (mBitmap == null)
return;
mIntrinsicWidth = mBitmap.getWidth();
mIntrinsicHeight = mBitmap.getHeight();
}
#Override
public void draw(Canvas canvas) {
if (mBitmap == null) return;
int width = canvas.getWidth();
int height = canvas.getHeight();
int x = (width - mIntrinsicWidth) / 2;
int y = (height - mIntrinsicHeight) / 2;
canvas.drawBitmap(mBitmap, x, y, null);
}
#Override
public int getOpacity() {
return android.graphics.PixelFormat.OPAQUE;
}
}
private Bitmap getBitmap(int i)
{
System.out.println(i);
if(i != 0)
{
System.out.println("ResourceID != 0");
Bitmap bitmap = BitmapFactory.decodeResource(getResources(), i);
PrintStream printstream = System.out;
StringBuilder stringbuilder = new StringBuilder("Bitmap = null = ");
boolean flag;
if(bitmap == null)
flag = true;
else
flag = false;
printstream.println(stringbuilder.append(flag).toString());
if(bitmap != null)
return bitmap;
}
return null;
}
Test if the device is a tablet or a phone ?
public boolean isTablet(Context context) {
boolean xlarge = ((context.getResources().getConfiguration().screenLayout & Configuration.SCREENLAYOUT_SIZE_MASK) == 4);
boolean large = ((context.getResources().getConfiguration().screenLayout & Configuration.SCREENLAYOUT_SIZE_MASK) == Configuration.SCREENLAYOUT_SIZE_LARGE);
return (xlarge || large);
}