i am trying to have a Recycler view in the form of a list view and i want to set a fragment to show more details under the list
this is my adapter layout
<RelativeLayout
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="wrap_content"
android:layout_marginBottom="20dp"
android:layout_marginTop="2dp"
android:id ="#+id/relative_layout_text"
>
<ImageView
android:layout_width="55dp"
android:layout_height="55dp"
android:id="#+id/image_view_food_image"
android:layout_alignParentLeft="true"
android:background="#drawable/common_google_signin_btn_icon_dark_normal"/>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/linear_layout_text"
android:layout_toRightOf="#+id/image_view_food_image">
<TextView
android:id="#+id/text_view_title"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="19dp"
android:textStyle="bold"
android:textColor="#color/colorTitle"
android:layout_alignParentTop="true"/>
<TextView
android:id="#+id/text_view_name"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textStyle="bold"
android:layout_alignParentTop="true"
android:layout_marginTop="5dp"/>
</LinearLayout>
<FrameLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/fragments"
android:layout_below="#+id/linear_layout_text"></FrameLayout>
</RelativeLayout>
and heres how i initiate my fragment in the adapter
public class FirebaseAdapter extends RecyclerView.Adapter<FirebaseAdapter.MyViewHolder> {
private int lastPosition = -1;
private View views ;
private List<Foods> FoodArray = new ArrayList<>();
private Context mContext ;
private ArrayList<String> itemsDesc = new ArrayList<>();
public class MyViewHolder extends RecyclerView.ViewHolder {
public TextView title,name;
public ImageView foodImage;
public RelativeLayout relativeLayout;
public FrameLayout frameLayout;
public MyViewHolder(View view) {
super(view);
title = (TextView) view.findViewById(R.id.text_view_title);
name = (TextView) view.findViewById(R.id.text_view_name);
foodImage = (ImageView) view.findViewById(R.id.image_view_food_image);
relativeLayout = (RelativeLayout) view.findViewById(R.id.relative_layout_text);
frameLayout = (FrameLayout) view.findViewById(R.id.fragments);
views = view;
}
}
public FirebaseAdapter(Context context,List<Foods> Foods){
this.FoodArray = Foods;
this.mContext = context;
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.menu_list, parent, false);
return new MyViewHolder(itemView);
}
#Override
public void onBindViewHolder(final MyViewHolder holder, int position) {
holder.title.setText(FoodArray.get(position).getTitle());
holder.name.setText(FoodArray.get(position).getName());
itemsDesc.add(FoodArray.get(position).getTitle());
itemsDesc.add(FoodArray.get(position).getName());
itemsDesc.add(FoodArray.get(position).getURL());
DownloadImage Downloader = new DownloadImage(holder.foodImage);
Downloader.execute(FoodArray.get(position).getURL());
setAnimation(holder.relativeLayout, position);
Fragment blankFragment = new BlankFragment();
Bundle bundle = new Bundle();
bundle.putStringArrayList("Food",itemsDesc);
blankFragment.setArguments(bundle);
((FragmentActivity)mContext).getSupportFragmentManager().beginTransaction()
.add(holder.frameLayout.getId(),blankFragment,"BlankFragment").addToBackStack(null).commit();
}
//this is to download async
public class DownloadImage extends AsyncTask<String,Void,Bitmap>{
private ImageView mImageView;
public DownloadImage(ImageView imageView){
this.mImageView = imageView;
}
//this is the code for downloading the image
#Override
protected Bitmap doInBackground(String ... url){
Bitmap Image = null;
try{
InputStream is = new URL(url[0]).openStream();
Image = BitmapFactory.decodeStream(is);
}catch(MalformedURLException ex){
ex.printStackTrace();
}
catch(IOException ex ){
ex.printStackTrace();
}
return Image;
}
#Override
protected void onPostExecute(Bitmap result) {
if (result != null) {
mImageView.setImageBitmap(result);
}
}
}
private void setAnimation(View viewToAnimate, int position)
{
// If the bound view wasn't previously displayed on screen, it's animated
if (position > lastPosition)
{
Animation animation = AnimationUtils.loadAnimation(viewToAnimate.getContext(), android.R.anim.slide_in_left);
viewToAnimate.startAnimation(animation);
lastPosition = position;
}
}
#Override
public int getItemCount(){return FoodArray.size();}
}
and heres the code for my fragment
public class BlankFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState)
{
View view = inflater.inflate(R.layout.fragment_blank,container,false);
TextView title = (TextView)view.findViewById(R.id.text_view_title);
TextView description = (TextView)view.findViewById(R.id.text_view_description);
ImageView foodImage = (ImageView) view.findViewById(R.id.image_view_big_food_image);
ArrayList<String> foods = getArguments().getStringArrayList("Food");
title.setText(foods.get(0));
description.setText(foods.get(1));
DownloadImage Downloader = new DownloadImage(foodImage);
Downloader.execute(foods.get(2));
return view;
}
public class DownloadImage extends AsyncTask<String,Void,Bitmap> {
private ImageView mImageView;
public DownloadImage(ImageView imageView){
this.mImageView = imageView;
}
//this is the code for downloading the image
#Override
protected Bitmap doInBackground(String ... url){
Bitmap Image = null;
try{
InputStream is = new URL(url[0]).openStream();
Image = BitmapFactory.decodeStream(is);
}catch(MalformedURLException ex){
ex.printStackTrace();
}
catch(IOException ex ){
ex.printStackTrace();
}
return Image;
}
#Override
protected void onPostExecute(Bitmap result) {
if (result != null) {
mImageView.setImageBitmap(result);
}
}
}
So with my current code i am expecting the data to be like this
But i got this instead
so i am unsure on how to make it so i can get my expected results
Please and thanks and advance
Guys i found my problem and there's no solution to this as the answer stated in this person question in stackoverflow here he stated that initializing a fragment in the onBindView is possible but you can't do it if you're gonna use only one specific id as the fragment will stack on it instead of adding one on each recycler item
Related
I am creating food shop app in which click on menu button on home page it should redirect to grid view ,
i have created image grid layout xml and image grid class , but not able to map it with button on home page
this is my main activity
public class TimmyRestaurantActivity extends Activity {
Button go_to_menu,go_to_order_list,findstore,info;
//Button custinfo;
String user_name;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Intent myintent = getIntent();
Bundle extras = myintent.getExtras();
user_name = extras.getString("cust_name");
Toast.makeText(TimmyRestaurantActivity.this, "Welcome " + user_name ,Toast.LENGTH_LONG ).show();
// initialise form widget
go_to_menu=(Button)findViewById(R.id.Go_To_Menu);
go_to_menu.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Intent i=new Intent(TimmyRestaurantActivity.this,
ImageAdapter.class);
startActivity(i);
}
}
this is my gridlayout
<?xml version="1.0" encoding="utf-8"?>
<GridView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/grid_view"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:numColumns="auto_fit"
android:columnWidth="90dp"
android:horizontalSpacing="10dp"
android:verticalSpacing="10dp"
android:gravity="center"
android:stretchMode="columnWidth" >
</GridView>
this is adaptor class for my grid
public class ImageAdapter extends BaseAdapter {
private Context mContext;
// Keep all Images in array
public Integer[] mThumbIds = {
R.drawable.img15, R.drawable.img15,
R.drawable.img15, R.drawable.img15
};
// Constructor
public ImageAdapter(Context c){
mContext = c;
}
#Override
public int getCount() {
return mThumbIds.length;
}
#Override
public Object getItem(int position) {
return mThumbIds[position];
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ImageView imageView = new ImageView(mContext);
imageView.setImageResource(mThumbIds[position]);
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setLayoutParams(new GridView.LayoutParams(70, 70));
return imageView;
}
}
and on menuscreen.java i am trying call my gridadapater
public class MenuScreen extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.grid_layout);
GridView gridView = (GridView) findViewById(R.id.grid_view);
// Instance of ImageAdapter Class
gridView.setAdapter(new ImageAdapter(this));
}
on click button , this error comes
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.restaurant/com.restaurant.MenuScreen}:
java.lang.RuntimeException: Your content must have a ExpandableListView whose id attribute is 'android.R.id.list'
How can i properly redirect from home page button to grid view page , please suggest
Add a placeholder in your main laout(R.layout.main)
<FrameLayout
android:layout_height="match_parent"
android:id="#+id/place_men"
android:layout_width="match_parent">
</FrameLayout>
and chnage the code like
go_to_menu.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
//starting new fragment on button click
MenuScreen menuScreen =new MenuScreen();
getSupportFragmentManager().beginTransaction().replace(R.id.place_men, menuScreen).commit();
}
});
Also MenuScreen extends android.support.v4.app.Fragment
activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#f0f0f0">
<GridView
android:id="#+id/gridView"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_margin="5dp"
android:columnWidth="100dp"
android:drawSelectorOnTop="true"
android:gravity="center"
android:numColumns="auto_fit"
android:stretchMode="columnWidth"
android:verticalSpacing="5dp"
android:focusable="true"
android:clickable="true"/>
</RelativeLayout>
grid_item_layout.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="5dp"
android:background="#drawable/grid_color_selector"
android:orientation="vertical"
android:padding="5dp">
<ImageView
android:id="#+id/image"
android:layout_width="100dp"
android:layout_height="100dp" />
<TextView
android:id="#+id/text"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="5dp"
android:gravity="center"
android:textSize="12sp" />
</LinearLayout>
GridViewAdapter.class
public class GridViewAdapter extends ArrayAdapter {
private Context context;
private int layoutResourceId;
private ArrayList data = new ArrayList();
public GridViewAdapter(Context context, int layoutResourceId, ArrayList data) {
super(context, layoutResourceId, data);
this.layoutResourceId = layoutResourceId;
this.context = context;
this.data = data;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
ViewHolder holder = null;
if (row == null) {
LayoutInflater inflater = ((Activity) context).getLayoutInflater();
row = inflater.inflate(layoutResourceId, parent, false);
holder = new ViewHolder();
holder.imageTitle = (TextView) row.findViewById(R.id.text);
holder.image = (ImageView) row.findViewById(R.id.image);
row.setTag(holder);
} else {
holder = (ViewHolder) row.getTag();
}
ImageItem item = data.get(position);
holder.imageTitle.setText(item.getTitle());
holder.image.setImageBitmap(item.getImage());
return row;
}
static class ViewHolder {
TextView imageTitle;
ImageView image;
}
}
ImageItem.class pojo class
public class ImageItem {
private Bitmap image;
private String title;
public ImageItem(Bitmap image, String title) {
super();
this.image = image;
this.title = title;
}
public Bitmap getImage() {
return image;
}
public void setImage(Bitmap image) {
this.image = image;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
}
MainActivity.class
public class MainActivity extends ActionBarActivity {
private GridView gridView;
private GridViewAdapter gridAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
gridView = (GridView) findViewById(R.id.gridView);
gridAdapter = new GridViewAdapter(this, R.layout.grid_item_layout, getData());
gridView.setAdapter(gridAdapter);
}
// Prepare some dummy data for gridview
private ArrayList<ImageItem> getData() {
final ArrayList<ImageItem> imageItems = new ArrayList<>();
TypedArray imgs = getResources().obtainTypedArray(R.array.image_ids);
for (int i = 0; i < imgs.length(); i++) {
Bitmap bitmap = BitmapFactory.decodeResource(getResources(), imgs.getResourceId(i, -1));
imageItems.add(new ImageItem(bitmap, "Image#" + i));
}
return imageItems;
}
}
Please follow this code implementation for Gridview
And in your button click event
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent(YourActivity.this, MainActivity.class);
startActivity(intent);
}
});
Follow this link for working example
Image GridView
I'm working on a page in which I have a button which takes you to the video gallery which I have created. From this you select some videos(thumbnails) and then hit the arrow to come back to the same place from where I hit the button to come to the Custom gallery with the selected videos.
Basically the map goes like this :
Button(from AddFragment)->VideoGallery->Select videos-> AddFragment with selected videos which is visible inside the recycler view
Now when I hit the button I come to my videogallery but when I select some videos from the gallery and come back to the AddFragment it shows nothing and one error comes up that is E/RecyclerView: No adapter attached; skipping layout
Now I have used Bundle to extract the sent data and populate it in my AddFragment.
I'm giving out the code for you :
1. AddFragment.java
public class AddFragment extends Fragment {
private ImageButton nextActivity;
private RecyclerView recyclerView;
private ProgressDialog videoProgressDialog;
ArrayList<File> checkedList = new ArrayList<>();
ImageAdapter imageAdapter;
Button button;
public AddFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_add, container, false);
nextActivity = (ImageButton) view.findViewById(R.id.gotoButton);
recyclerView = (RecyclerView) view.findViewById(R.id.grid_add_view);
button = (Button) view.findViewById(R.id.buttonToGallery);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startActivity(new Intent(getContext(),VideoGalleryActivity.class));
}
});
return view;
}
//making adapter for RecyclerView which loads the desired files
class ImageAdapter extends RecyclerView.Adapter<ViewHolder>{
private LayoutInflater mInflater;
private Bitmap bitmap;
private ArrayList<File> fileName;
public ImageAdapter(ArrayList<File> checkedList) {
fileName = checkedList;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
Log.e("ADAPTER SETTING","DOING");
//getting the passed value from videogallery
Bundle bundle = new Bundle();
ArrayList<String> getValue = bundle.getStringArrayList("sendData");
Log.e("RECEIVED_DATA======",getValue.toString());
//adding the files to the list
for(String pathName : getValue){
File filePath = new File(pathName);
checkedList.add(filePath);
}
//setting the adapter
imageAdapter = new ImageAdapter(checkedList);
recyclerView.setAdapter(imageAdapter);
recyclerView.setVisibility(View.VISIBLE);
View items = mInflater.from(parent.getContext()).inflate(R.layout.custom_added_video,
parent,false);
items.setLayoutParams(new AbsListView.LayoutParams(215,215));
return new ViewHolder(items);
}
#Override
public int getItemViewType(int position) {
return super.getItemViewType(position);
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
if(fileName != null){
bitmap = ThumbnailUtils.createVideoThumbnail(fileName.get(position).toString(),1);
holder.imageView.setImageBitmap(bitmap);
}
}
#Override
public int getItemCount() {
return fileName.size();
}
}
class ViewHolder extends RecyclerView.ViewHolder {
public ImageView imageView;
//public ImageButton imageButton;
public ViewHolder(View itemView) {
super(itemView);
//imageButton = (ImageButton) itemView.findViewById(R.id.addVideos);
imageView = (ImageView) itemView.findViewById(R.id.galleryImageView);
}
} }
2. fragment_add.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:background="#color/colorWhite"
tools:context="in.pinelane.myhovi.AddFragment">
<!-- TODO: Update blank fragment layout -->
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:id="#+id/linearLayout"
android:padding="19dp">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="17dp"
android:textStyle="bold"
android:text="Choose Videos"
android:textColor="#color/colorBackground"/>
<View
android:layout_width="0dp"
android:layout_height="0dp"
android:layout_weight="1" />
<ImageButton
android:id="#+id/gotoButton"
android:layout_width="25sp"
android:layout_height="25sp"
android:background="#00ffffff"
android:src="#mipmap/ic_arrow_forward_black_24dp"/>
</LinearLayout>
<Button
android:id="#+id/buttonToGallery"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Gallery"/>
<android.support.v7.widget.RecyclerView
android:id="#+id/grid_add_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center" />
Inflates this layout
custom_added_video.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="wrap_content"
android:background="#color/colorWhite"
android:layout_marginTop="3dp"
android:layout_marginBottom="3dp"
android:layout_marginEnd="3dp"
android:layout_marginStart="3dp">
<!--<ImageButton-->
<!--android:id="#+id/addVideos"-->
<!--android:layout_width="match_parent"-->
<!--android:layout_height="wrap_content"-->
<!--android:src="#mipmap/ic_add_black_24dp"-->
<!--android:layout_margin="3dp"-->
<!--android:background="#drawable/edittext_border"-->
<!--android:layout_centerInParent="true"/>-->
<ImageView
android:id="#+id/galleryImageView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:scaleType="centerCrop"
android:layout_margin="3dp"
android:layout_centerInParent="true"/>
Any idea would be of great help! Thanks
I've tried defining the below code in onCreate but I got a NullPointerException so I defined the same inside the onCreateViewHolder but no result just No Adapter attached; skipping layout
Log.e("ADAPTER SETTING","DOING");
//getting the passed value from videogallery
Bundle bundle = new Bundle();
ArrayList<String> getValue = bundle.getStringArrayList("sendData");
Log.e("RECEIVED_DATA======",getValue.toString());
//adding the files to the list
for(String pathName : getValue){
File filePath = new File(pathName);
checkedList.add(filePath);
}
//setting the adapter
imageAdapter = new ImageAdapter(checkedList);
recyclerView.setAdapter(imageAdapter);
recyclerView.setVisibility(View.VISIBLE);
EDITS
I've made some changes inside my code and user onActivityResult and startActivityForResult in this fragment but still no result. My AddFragment is still blank and not showing any result
Edited AddFragment.java
public class AddFragment extends Fragment {
private ImageButton nextActivity;
private RecyclerView recyclerView;
ArrayList<File> checkedList = new ArrayList<>();
ImageAdapter imageAdapter;
Button button;
private static final int CustomGallerySelectId = 1;//Set Intent Id
public AddFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_add, container, false);
nextActivity = (ImageButton) view.findViewById(R.id.gotoButton);
recyclerView = (RecyclerView) view.findViewById(R.id.grid_add_view);
button = (Button) view.findViewById(R.id.buttonToGallery);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startActivityForResult(new Intent(getContext(),VideoGalleryActivity.class),CustomGallerySelectId);
}
});
//setting the adapter
imageAdapter = new ImageAdapter(checkedList);
GridLayoutManager videoGrid = new GridLayoutManager(getContext(),3);
recyclerView.setLayoutManager(videoGrid);
recyclerView.setAdapter(imageAdapter);
recyclerView.setVisibility(View.VISIBLE);
return view;
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch(requestCode){
case CustomGallerySelectId :
if(requestCode == RESULT_OK){
Log.e("ADAPTER SETTING","DOING");
//getting the passed value from videogallery
Bundle bundle = new Bundle();
ArrayList<String> getValue = bundle.getStringArrayList("sendData");
Log.e("RECEIVED_DATA======",getValue.toString());
//adding the files to the list
for(String pathName : getValue) {
File filePath = new File(pathName);
checkedList.add(filePath);
}
}
}
}
//making adapter for RecyclerView which loads the desired files
class ImageAdapter extends RecyclerView.Adapter<ViewHolder>{
private LayoutInflater mInflater;
private Bitmap bitmap;
private ArrayList<File> fileName;
public ImageAdapter(ArrayList<File> checkedList) {
fileName = checkedList;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View items = mInflater.from(parent.getContext()).inflate(R.layout.custom_added_video,
parent,false);
items.setLayoutParams(new AbsListView.LayoutParams(215,215));
return new ViewHolder(items);
}
#Override
public int getItemViewType(int position) {
return super.getItemViewType(position);
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
if(fileName != null){
bitmap = ThumbnailUtils.createVideoThumbnail(fileName.get(position).toString(),1);
holder.imageView.setImageBitmap(bitmap);
}
}
#Override
public int getItemCount() {
return fileName.size();
}
}
class ViewHolder extends RecyclerView.ViewHolder {
public ImageView imageView;
//public ImageButton imageButton;
public ViewHolder(View itemView) {
super(itemView);
//imageButton = (ImageButton) itemView.findViewById(R.id.addVideos);
imageView = (ImageView) itemView.findViewById(R.id.galleryImageView);
}
} }
Move this code:
//setting the adapter
imageAdapter = new ImageAdapter(checkedList);
recyclerView.setAdapter(imageAdapter);
recyclerView.setVisibility(View.VISIBLE);
to your createView() method.
In createView you are inflating the layout, you are finding the RecyclerView but you are not setting an adapter to it. The RecyclerView doesn't have any data to show, so it's skipped from the layout for a performance boost. You should also set a LayoutManager. If you need a simple list, you should use LinearLayoutManager.
The createViewHolder() method is called once for each visible element of your RecyclerView. It's not the right place to perform the initial setup of your RecyclerView.
i've had a problem, when i've tried to view this below fragment showing "skipping layout". Can any one help me out how to solve this problem please.
I'm getting this "No adapter attached; skipping layout." when i CLICK any imageview on ThirdFragment UI ayout, not when the images display in Thirdfragment UI layout.
ThirdFrament.java
public class ThirdFragment extends Fragment implements RecyclerViewAdapter.ItemListener {
static final String url = "https://jsonparsingdemo-cec5b.firebaseapp.com/jsonData/moviesData.txt" ;
RecyclerView recyclerView;
RecyclerViewAdapter adapter;
AutoFitGridLayoutManager layoutManager;
private static List<JsonURLFullModel> cart;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView= inflater.inflate(R.layout.fragment_third, container, false);
recyclerView = (RecyclerView) rootView.findViewById(R.id.recyclerView);
new JSONTask().execute(url, this);
// Inflate the layout for this fragment
return rootView;
}
public class JSONTask extends AsyncTask<Object, String, ThirdFragModel> {
// Url , , return_value_of_doInBackground
//private ProgressDialog dialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
//dialog.show(); // this is for ProgressDialog
}
#Override
protected ThirdFragModel doInBackground(Object... params) {
//send and receive data over the web
// can be used to send and receive "streaming" data whose length is not
// known in advance
HttpURLConnection connection = null;
BufferedReader reader = null;
try {
URL url = new URL(params[0].toString());
RecyclerViewAdapter.ItemListener itemListener = (RecyclerViewAdapter.ItemListener) params[1];
connection = (HttpURLConnection) url.openConnection();
connection.connect();
InputStream stream = connection.getInputStream(); // this is used to store
// the response, response is always stream
reader = new BufferedReader(new InputStreamReader(stream));
// BufferedReader reads the stream line by line and then store in the reader
StringBuffer buffer = new StringBuffer();
String line = "";
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
String finalJson = buffer.toString(); // this contails whole JSON data from the URL
JSONObject parentObject = new JSONObject(finalJson);
JSONArray parentArray = parentObject.getJSONArray("movies"); // "movies" is the JSON Array-object in JSON data URL
List<JsonURLFullModel> movieModelList = new ArrayList<>();
//StringBuffer finalBufferedaData = new StringBuffer();
for (int i = 0; i < parentArray.length(); i++) {
JSONObject finalObject = parentArray.getJSONObject(i); // getting first json object from JSON ARRAY "movies"
JsonURLFullModel movieModel = new JsonURLFullModel();
movieModel.setMovie(finalObject.getString("movie"));
movieModel.setImage(finalObject.getString("image"));
movieModelList.add(movieModel); // adding the final object in list
//finalBufferedaData.append(movieName +"-"+ year +"\n");
}
ThirdFragModel thirdFragModel= new ThirdFragModel(itemListener,movieModelList);
return thirdFragModel;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
} finally {
if (connection != null)
connection.disconnect();
try {
if (reader != null)
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
#Override
protected void onPostExecute(ThirdFragModel result) {
super.onPostExecute(result);
//jsonfull.setText(result);
//dialog.dismiss(); // closing dialog, before the content load in ListView(i.e until application lodading it will run, then dialog closes)
adapter = new RecyclerViewAdapter(getActivity(), result.getMovieModelList(), result.getItemListener());
/**
AutoFitGridLayoutManager that auto fits the cells by the column width defined.
**/
layoutManager = new AutoFitGridLayoutManager(getActivity(), 500);
recyclerView.setLayoutManager(layoutManager);
recyclerView.setAdapter(adapter);
/**
Simple GridLayoutManager that spans two columns
**/
/*GridLayoutManager manager = new GridLayoutManager(this, 2, GridLayoutManager.VERTICAL, false);
recyclerView.setLayoutManager(manager);*/
//AnimationUtils.animate(jsonFullL1, true);
}
}
public void moveToLoginActivity() {
Intent intent = new Intent(getActivity(), LoginActivity.class);
startActivity(intent);
}
#Override
public void onItemClick(int mPosition,List<JsonURLFullModel> mValues ) {
Log.d("Fragposition",mPosition+":"+mValues);
Toast.makeText(getActivity(), mValues.get(mPosition).getMovie() + " is clicked", Toast.LENGTH_SHORT).show();
//Intent intent = new Intent(getActivity(), FullScreenViewActivity.class);
Intent intent = new Intent(getActivity(), FullScreenViewInitialActivity.class);
intent.putExtra("position", mPosition);
intent.putExtra("values", (Serializable) mValues);
startActivity(intent);
}
public static List<JsonURLFullModel> getCart() {
if(cart == null) {
cart = new Vector<JsonURLFullModel>();
}
return cart;
}
}
Here is my adapter class which we used in ThirdFragment class as shown above
RecyclerViewAdapter.java
public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.ViewHolder> {
static List<JsonURLFullModel> mValues;
Context mContext;
private ItemListener mListener;
static int mPosition;
public RecyclerViewAdapter(Context context, List<JsonURLFullModel> values, ItemListener itemListener) {
mValues = values;
mContext = context;
mListener=itemListener;
}
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
public TextView textView;
public ImageView imageView;
public RelativeLayout relativeLayout;
JsonURLFullModel item;
public ViewHolder(View v) {
super(v);
v.setOnClickListener(this);
textView = (TextView) v.findViewById(R.id.textView1);
imageView = (ImageView) v.findViewById(R.id.imageView1);
relativeLayout = (RelativeLayout) v.findViewById(R.id.relativeLayout);
}
public void setData(final JsonURLFullModel item) {
this.item = item;
Log.d("INFO",item.getImage());
//https://futurestud.io/tutorials/picasso-image-resizing-scaling-and-fit
Picasso.with(mContext)
.load(item.getImage())
.error(R.drawable.ferrari)
.noPlaceholder()
.noFade()
.fit()
.into(imageView, new com.squareup.picasso.Callback() {
#Override
public void onSuccess() {
//Success image already loaded into the view
Log.d("INFO","success");
}
#Override
public void onError() {
//Error placeholder image already loaded into the view, do further handling of this situation here
Log.d("INFO","error");
}
});
/*imageView.post(new Runnable() {
#Override
public void run(){
Glide.with(mContext).load(item.getImage()).asBitmap().override(1080, 600).into(imageView);
}
});*/
textView.setText(item.getMovie());
}
#Override
public void onClick(View view) {
if (mListener != null) {
mListener.onItemClick(getAdapterPosition(),mValues); // this.getPosition() is depricated
// in API 22 and we got getAdapterPosition()
}
}
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(mContext).inflate(R.layout.recycler_view_item, parent, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(ViewHolder Vholder, int position) {
Vholder.setData(mValues.get(position));
mPosition=position;
}
#Override
public int getItemCount() {
return mValues.size();
}
//Below interface implimentation can be found in ThirdFragment
// you can write below interface separetly or in you can write in this class like below
public interface ItemListener {
void onItemClick(int mPosition, List<JsonURLFullModel> mValues);
}
}
FullScreenViewInitialActivity.java
public class FullScreenViewInitialActivity extends FragmentActivity {
ImageFragmentPagerAdapter imageFragmentPagerAdapter;
ViewPager viewPager;
static ArrayList<JsonURLFullModel> mValues;
static int position;
Button addToBagButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_fullscreen_view_initial);
addToBagButton = (Button) findViewById(R.id.b_add_to_bag);
Intent i = getIntent();
position=i.getIntExtra("position",0);
Log.d("Acposition",""+position);
mValues = (ArrayList<JsonURLFullModel>) getIntent().getSerializableExtra("values");
imageFragmentPagerAdapter = new ImageFragmentPagerAdapter(getSupportFragmentManager());
viewPager = (ViewPager) findViewById(R.id.intial_pager);
viewPager.setAdapter(imageFragmentPagerAdapter);
viewPager.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
CircleIndicator circleIndicator = (CircleIndicator) findViewById(R.id.imageIndicator);
circleIndicator.setViewPager(viewPager);
/*viewPager.setOnClickListener(new View.OnClickListener(){
public void onClick(View v){
Intent intent = new Intent(FullScreenViewInitialActivity.this, FullScreenViewActivity.class);
intent.putExtra("position", position);
intent.putExtra("values", (Serializable) mValues);
startActivity(intent);
}
});*/
final List<JsonURLFullModel> cart = ThirdFragment.getCart();
final JsonURLFullModel selectedProduct = mValues.get(position);
addToBagButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
cart.add(selectedProduct);
Log.d("cart",""+cart.size());
//finish();
Button b_add_to_bag = (Button) findViewById(R.id.b_add_to_bag);
b_add_to_bag.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent reviewOrderIntent = new Intent(FullScreenViewInitialActivity.this, FullScreenViewReviewActivity.class);
startActivity(reviewOrderIntent);
}
});
}
});
if(cart.contains(selectedProduct)) {
addToBagButton.setEnabled(false);
addToBagButton.setText("Item in Cart");
}
}
public static class ImageFragmentPagerAdapter extends FragmentPagerAdapter {
public ImageFragmentPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public int getCount() {
return mValues.size();
}
#Override
public Fragment getItem(int position) {
SwipeFragment fragment = new SwipeFragment();
return SwipeFragment.newInstance(position);
}
}
public static class SwipeFragment extends Fragment {
#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");*/
//JsonURLFullModel imageFileName = mValues.get(position);
try {
BitmapFactory.Options options = new BitmapFactory.Options();
/*options.inJustDecodeBounds = true;
options.inPreferredConfig = Bitmap.Config.ARGB_8888;*/
URL url = new URL(mValues.get(position).getImage());
Log.d("position",""+position);
Bitmap bitmap = BitmapFactory.decodeStream(url.openConnection().getInputStream(),null, options);
if (bitmap != null)
imageView.setImageBitmap(bitmap);
else
System.out.println("The Bitmap is NULL");
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
imageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getActivity(), mValues.get(position).getMovie(), Toast.LENGTH_SHORT).show();
}
});
return swipeView;
}
static SwipeFragment newInstance(int position) {
SwipeFragment swipeFragment = new SwipeFragment();
Bundle bundle = new Bundle();
bundle.putInt("position", position);
swipeFragment.setArguments(bundle);
return swipeFragment;
}
}
}
third_fragment.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:fitsSystemWindows="true"
tools:context=".MainActivity">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.v7.widget.RecyclerView
android:id="#+id/recyclerView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scrollbars="vertical"
/>
<!--removed from recycler view
app:layout_behavior="#string/appbar_scrolling_view_behavior"-->
</RelativeLayout>
</android.support.design.widget.CoordinatorLayout>
recycler_view_item.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:card_view="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<android.support.v7.widget.CardView
android:id="#+id/cardView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/colorAccent"
card_view:cardCornerRadius="#dimen/margin10"
card_view:cardElevation="#dimen/margin10"
card_view:cardMaxElevation="#dimen/margin10"
card_view:contentPadding="#dimen/margin10"
card_view:cardPreventCornerOverlap="false"
android:layout_marginStart="10dp"
android:layout_marginEnd="10dp">
<RelativeLayout
android:id="#+id/relativeLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:layout_gravity="center">
<ImageView
android:id="#+id/imageView1"
android:layout_width="match_parent"
android:layout_height="150dp"
android:scaleType="fitXY"
android:padding="5dp"
android:layout_alignParentTop="true"/>
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:textColor="#color/colorPrimary"
android:layout_marginTop="10dp"
android:layout_below="#+id/imageView1" />
</RelativeLayout>
</android.support.v7.widget.CardView>
</LinearLayout>
activity_fullscreen_view_initial
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="match_parent"
android:layout_alignParentTop="true"
android:orientation="vertical">
<ScrollView
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:fillViewport="true"
android:layout_weight="1">
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_above="#+id/cart_button_layout"
android:layout_alignParentTop="true"
android:orientation="vertical">
<android.support.v4.view.ViewPager
android:id="#+id/intial_pager"
android:layout_width="fill_parent"
android:layout_height="fill_parent" />
<me.relex.circleindicator.CircleIndicator
android:id="#+id/imageIndicator"
android:layout_width="match_parent"
android:layout_height="48dp"
android:layout_alignBottom="#+id/intial_pager"
android:layout_marginBottom="10dp" />
</LinearLayout>
</ScrollView>
<ScrollView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:fillViewport="true"
>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<include
layout="#layout/full_screen_size_picker"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
</ScrollView>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/cart_button_layout"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="5dp"
android:gravity="bottom"
android:paddingLeft="5dp"
android:paddingRight="5dp"
android:layout_alignParentBottom="true"
android:orientation="horizontal">
<Button
android:id="#+id/b_save"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginRight="5dp"
android:layout_weight="1"
android:background="#D3D3D3"
android:text="save"
android:textColor="#000000" />
<Button
android:id="#+id/b_add_to_bag"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="5dp"
android:layout_weight="1"
android:background="#color/colorPrimary"
android:text="add to bag"
android:textColor="#FFF" />
</LinearLayout>
</LinearLayout>
swipe_fragment.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:id="#+id/imageView"
android:layout_gravity="center_horizontal"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true" />
</LinearLayout>
Try setting the setting the RecyclerView with an empty Adapter before you execute your AsyncTask.
View rootView= inflater.inflate(R.layout.fragment_third, container, false);
recyclerView = (RecyclerView) rootView.findViewById(R.id.recyclerView);
-->recyclerView.setAdapter(new RecyclerViewAdapter(getActivity(), new ArrayList<>(), null);
new JSONTask().execute(url, this);
Then create a method in the RecyclerViewAapter to load the the populated List<JsonURLFullModel> from the AsyncTask's onPostExecute.
public void loadJson(List<JsonURLFullModel> jsonList){
mValues = jsonList;
notifyDataSetChanged();
}
If that doesn't work trying loading on the Ui thread from Asynctask using runOnUiThread
runOnUiThread(new Runnable() {
#Override
public void run() {
adapter.loadJson(...)
}
});
Edit 1 Adding loadJson to your RecyclerViewAapter.class
#Override
public int getItemCount() {
return mValues.size();
}
public void loadJson(List<JsonURLFullModel> jsonList){
mValues = jsonList;
notifyDataSetChanged();
}
//Below interface implimentation can be found in ThirdFragment
// you can write below interface separetly or in you can write in this class like below
public interface ItemListener {
void onItemClick(int mPosition, List<JsonURLFullModel> mValues);
}
Call the method in your PostExecute
#Override
protected void onPostExecute(ThirdFragModel result) {
super.onPostExecute(result);
//jsonfull.setText(result);
//dialog.dismiss(); // closing dialog, before the content load in ListView(i.e until application lodading it will run, then dialog closes)
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
adapter.loadJson(result.getMovieModelList());
}
});
}
Also add your the Layout manager for the RecyclerView in onCreateView
View rootView= inflater.inflate(R.layout.fragment_third, container, false);
recyclerView = (RecyclerView) rootView.findViewById(R.id.recyclerView);
-->recyclerView.setAdapter(new RecyclerViewAdapter(getActivity(), new ArrayList<>(), null);
layoutManager = new AutoFitGridLayoutManager(getActivity(), 500);
recyclerView.setLayoutManager(layoutManager);
In my app,I get some data from my server. They are displayed fine,but when I pass them in my Detailed Fragment,then all views are null:(.
So here is my code.
public class MainActivityFragment extends Fragment {
public static final String TAG = "AelApp";
public static ArrayList<MyModel> listItemsList;
RecyclerView myList;
public static MatchReportsAdapter adapter;
public MainActivityFragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
updateMatchReport();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
getActivity().setTitle("Match Report");
View rootView = inflater.inflate(R.layout.fragment_main_activity, container, false);
listItemsList = new ArrayList<>();
myList = (RecyclerView)rootView.findViewById(R.id.listview_match_reports);
final LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity());
myList.setHasFixedSize(true);
myList.setLayoutManager(linearLayoutManager);
adapter = new MatchReportsAdapter(getActivity(), listItemsList);
myList.setAdapter(adapter);
return rootView;
}
public void updateMatchReport(){
Intent i = new Intent(getActivity(), MatchReport.class);
getActivity().startService(i);
}
}
Adapter
public class MatchReportsAdapter extends
RecyclerView.Adapter<MatchReportsAdapter.RowHolder>{
private List<MyModel> reportsList;
private Context mContext;
private ImageLoader mImageLoader;
private int focused = 0;
public MatchReportsAdapter(Activity activity, List<MyModel> reportsLists){
this.reportsList = reportsLists;
this.mContext=activity;
}
#Override
public RowHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.row_items,null);
final RowHolder holder = new RowHolder(v);
return holder;
}
#Override
public void onBindViewHolder(RowHolder holder, int position) {
final MyModel listItems = reportsList.get(position);
holder.itemView.setSelected(focused==position);
holder.getLayoutPosition();
mImageLoader = AppController.getInstance().getImageLoader();
holder.thumbnail.setImageUrl(listItems.getImage(),mImageLoader);
holder.thumbnail.setDefaultImageResId(R.drawable.reddit_placeholder);
holder.name.setText(Html.fromHtml(listItems.getTitle()));
holder.relativeLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String article = listItems.getArticle();
String image = listItems.getImage();
Intent i = new Intent(mContext, DetailedActivity.class);
i.putExtra("articleKey",article);
i.putExtra("imageKey",image);
mContext.startActivity(i);
}
});
}
#Override
public int getItemCount() {
return reportsList.size();
}
public class RowHolder extends RecyclerView.ViewHolder{
protected NetworkImageView thumbnail;
protected TextView name;
protected RelativeLayout relativeLayout;
public RowHolder(View itemView) {
super(itemView);
this.relativeLayout = (RelativeLayout)
itemView.findViewById(R.id.recLayout);
this.thumbnail =
(NetworkImageView)itemView.findViewById(R.id.thumbnail);
this.name = (TextView)itemView.findViewById(R.id.title);
}
}
}
DetailedActivity
public class DetailedActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_detailed);
if(savedInstanceState == null){
getSupportFragmentManager()
.beginTransaction()
.add(R.id.detailed_match_reports,new DetailedActivityFragment())
.commit();
}
}
}
DetailedActivityFragment
public class DetailedActivityFragment extends Fragment {
TextView articleTextView;
String image;
String article;
ImageView imageView;
public DetailedActivityFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View v = inflater.inflate(R.layout.fragment_detailed_activity, container, false);
articleTextView = (TextView)getActivity().findViewById(R.id.articleTextView);
imageView = (ImageView)getActivity().findViewById(R.id.imageNews);
Intent i = getActivity().getIntent();
article = i.getStringExtra("articleKey");
image = i.getStringExtra("imageKey");
Picasso.with(getActivity()).load(image).into(imageView);
articleTextView.setText(article);
return v;
}
}
All of my data are passed after clicking a row good. I know this as I debug the following lines.
article = i.getStringExtra("articleKey");
image = i.getStringExtra("imageKey");
and see that both String variables are not null. However,the both views(TextView,ImageView) of my detailed fragment are null.
Maybe I am doing something wrong with my xml file,and I don't see it.
activity_main.xml
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/match_reports"
tools:context="theo.testing.androidservices.fragments.MainActivityFragment">
</FrameLayout>
fragment_main_activity
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/recLayout"
tools:context=".activities.MainActivity"
android:background="#fff">
<android.support.v7.widget.RecyclerView
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:id="#+id/listview_match_reports"
android:layout_alignParentStart="true"
android:layout_alignParentLeft="true"
/>
</RelativeLayout>
activity_detailed.xml
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/detailed_match_reports"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="theo.testing.androidservices.activities.DetailedActivity"
tools:ignore="MergeRootFrame">
</FrameLayout>
and finally
fragment_detailed_activity
<?xml version="1.0" encoding="utf-8"?>
<ScrollView android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/imageNews"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
xmlns:android="http://schemas.android.com/apk/res/android">
<TextView
android:layout_gravity="center_horizontal"
android:padding="10dp"
android:text="xcvxcvxcv"
android:textColor="#000"
android:layout_marginTop="5dp"
android:textAppearance="?android:attr/textAppearanceMedium"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/articleTextView"/>
</ScrollView>
What am I missing?
Thanks
Theo.
Change these
articleTextView = (TextView)getActivity().findViewById(R.id.articleTextView);
imageView = (ImageView)getActivity().findViewById(R.id.imageNews);
to
articleTextView = (TextView)v.findViewById(R.id.articleTextView);
imageView = (ImageView)v.findViewById(R.id.imageNews);
You'r passing data to DetailActivity. So first retrieve in DetailActivity and then pass to DetailFragment.
Also you need to pass data to DetailFragment using Bundle with setArguments(bundle)
Your Textview articleTextView is in the fragment but you are finding it in the activitys xml:
articleTextView = (TextView)getActivity().findViewById(R.id.articleTextView);
insetad you should do:
articleTextView = (TextView)(v.findViewById(R.id.articleTextView));
Do the same for Imageviewl.
So I have this list of city objects (which contain an image, the name of the city, and a integer value). And for each of these city objects I want to programatically create a new cardView and insert it into a fragment. Currently, nothing shows up...
Here is my fragment xml code.
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.NestedScrollView
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:paddingTop="24dp"
android:id="#+id/fragCards_LL">
</LinearLayout>
</android.support.v4.widget.NestedScrollView>
Here is the code for my fragment activity.
public class FragmentCards extends Fragment
{
private ArrayList<CityFolders> cityFolders = new ArrayList<>();
private OnCardsFragmentListener mListener;
private LinearLayout linearLayout;
private View view;
public FragmentCards() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
// Inflate the layout for this fragment
view = inflater.inflate(R.layout.fragment_fragment_cards, container, false);
setUpLinearLayout();
setUpCityFolders();
//TextView myText = (TextView) view.findViewById(R.id.fragCards_numberOfCardsTextContent);
//Toast.makeText(getActivity(), myText.getText(), Toast.LENGTH_SHORT).show();
return inflater.inflate(R.layout.fragment_fragment_cards, container, false);
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnCardsFragmentListener)
{
mListener = (OnCardsFragmentListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement OnCheeseCategoriesFragmentListener");
}
}
private void setUpLinearLayout()
{
linearLayout = (LinearLayout) view.findViewById(R.id.fragCards_LL);
linearLayout.setOrientation(LinearLayout.VERTICAL);
linearLayout.setLayoutParams(new NestedScrollView.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
}
private void setUpCityFolders()
{
if(!Global_Class.getInstance().getValue().cityFoldersArrayList.isEmpty())
{
cityFolders = Global_Class.getInstance().getValue().cityFoldersArrayList;
for(CityFolders cityFolder : cityFolders)
{
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
lp.setMargins(64,64,64,64);
lp.height = 200;//180dp = 720pixels
lp.width = 1408;//330dp = 1320 pixels.
CardView cityCardView = new CardView(getActivity());// ERROR
cityCardView.setBackgroundColor(000000);
cityCardView.setLayoutParams(lp);
linearLayout.addView(cityCardView, 0);
}
}
}
public interface OnCardsFragmentListener
{
void disableCollapse();
}
}
So, don't know what I am doing wrong here... hope someone can help, maybe point out what im doing wrong?
Also, in my cardView, going horizontally, I want to have an imageview, then a textview, followed by another textview. How would I inflate those parts of the cardView and fill them with an image, and 2 texts from my cityFolder object? Hope you guys can help me with an answer!
Cheers
EDIT:
So i implemented a recycler view and..nothing shows up on the screen... This recycler view just holds simple views with each view having an imageview and a textview, and nothing shows up..
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:paddingTop="24dp"
android:id="#+id/fragCards_LL">
<android.support.v7.widget.RecyclerView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/fragCards_RecyclerView">
</android.support.v7.widget.RecyclerView>
</LinearLayout>
Here is my xml code for the view for each item in the recycler view
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:layout_width="100dp"
android:layout_height="100dp"
android:src="#drawable/fullstar"
android:id="#+id/fragCardsCity_imageview"
android:layout_gravity="center_vertical"
android:padding="8dp"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Star City"
android:layout_gravity="center_vertical"
android:id="#+id/fragCardsCity_textView"
android:padding="8dp"/>
</LinearLayout>
And finally, here is my java code.
public class FragmentCards extends Fragment
{
private ArrayList<CityFolders> cityFolders = new ArrayList<>();
private LinearLayout linearLayout;
private View rootView;
private RecyclerView recyclerView;
private CityViewAdapter cityAdapter;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
// Inflate the layout for this fragment
rootView = inflater.inflate(R.layout.fragment_cards, container, false);
linearLayout = (LinearLayout) rootView.findViewById(R.id.fragCards_LL);
recyclerView = (RecyclerView) rootView.findViewById(R.id.fragCards_RecyclerView);
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
cityAdapter = new CityViewAdapter(getActivity(),getData());
recyclerView.setAdapter(cityAdapter);
recyclerView.setItemAnimator(new DefaultItemAnimator());
return rootView;
}
public static ArrayList<myData> getData()
{
ArrayList<myData> data = new ArrayList<>();
int[] icons = {R.drawable.fullstar,R.drawable.fullstar,R.drawable.fullstar,R.drawable.fullstar};
String[] titles = {"San Francisco","Seattle","Tokyo","Osaka"};
for(int i = 0; i < titles.length && i < icons.length; i++)
{
myData current = new myData();
current.iconId = icons[i];
current.cityName = titles[i];
data.add(current);
}
return data;
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
}
private static class myData
{
private int iconId;
private String cityName;
}
private class CityViewAdapter extends RecyclerView.Adapter<CityViewAdapter.MyViewHolder>
{
private LayoutInflater inflater;
private ArrayList<myData> infoList = new ArrayList<>();
public CityViewAdapter(Context context, ArrayList<myData> data)
{
inflater = LayoutInflater.from(context);
this.infoList = data;
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType)
{
View view = inflater.inflate(R.layout.fragment_cards_cityview,parent,false);
MyViewHolder holder = new MyViewHolder(view);//special way to avoid "findViewById everytime you make a view
return holder;
}
#Override
public void onBindViewHolder(MyViewHolder holder, int position)
{
myData current = infoList.get(position);
holder.title.setText(current.cityName);
holder.icon.setImageResource(current.iconId);
}
#Override
public int getItemCount() {
return 0;
}
class MyViewHolder extends RecyclerView.ViewHolder
{
TextView title;
ImageView icon;
public MyViewHolder(View itemView)
{
super(itemView);
title = (TextView) itemView.findViewById(R.id.fragCardsCity_textView);
icon = (ImageView) itemView.findViewById(R.id.fragCardsCity_imageview);
}
}
}
}