How to load mysql listview data into fragment - android

i want to load Mysql data into listview into fragment
which contain image and text view stored previously into mysql database
this is my code but it show me error in getLayoutInflater
how can i do this ?
public class NewsFragment extends Fragment {
RequestQueue requestQueue;
String url = "http://giclub.esy.es/show.php";
ListView listView;
View myView;
ArrayList<NewsList> Newslistitem = new ArrayList<NewsList>();
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
myView = inflater.inflate(R.layout.newslayout,container,false);
listView = (ListView) myView.findViewById(R.id.listView);
requestQueue = Volley.newRequestQueue(this.getActivity());
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, url,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONArray jsonArray = response.getJSONArray("allstudents");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject respons = jsonArray.getJSONObject(i);
String id = respons.getString("id");
String name = respons.getString("name");
String info = respons.getString("info");
String img = respons.getString("img");
Newslistitem.add(new NewsList(id,name, info, img));
}
listAllItme();
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("VOLLEY", "ERROR");
}
}
);
requestQueue.add(jsonObjectRequest);
return myView;
}
public void listAllItme() {
listAdpter lA = new listAdpter(Newslistitem);
listView.setAdapter(lA);
}
/* public void onClick(View view) {
Intent intent = new Intent(this.getActivity(),NewsFragment.class);
startActivity(intent);
finish();
}*/
class listAdpter extends BaseAdapter {
ArrayList<NewsList> listA = new ArrayList<NewsList>();
public listAdpter(ArrayList<NewsList> listA) {
this.listA = listA;
}
#Override
public int getCount() {
return listA.size();
}
#Override
public Object getItem(int position) {
return listA.get(position).id;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater layoutInflater = getLayoutInflater();
View view = layoutInflater.inflate(R.layout.news_itm, null);
//TextView id = (TextView) view.findViewById(R.id.textView_id);
TextView name = (TextView) view.findViewById(R.id.textaddress);
TextView info = (TextView) view.findViewById(R.id.text_info);
ImageView img = (ImageView) view.findViewById(R.id.newspic);
// id.setText(listA.get(position).id);
name.setText(listA.get(position).name);
info.setText(listA.get(position).info);
Picasso.with(NewsFragment.this.getActivity()).load("http://giclub.esy.es/image/" + listA.get(position).img).into(img);
return view;
}
}
}
NewsList.java
public class NewsList {
public String id;
public String name;
public String info;
public String img;
public NewsList(String id ,String name, String info, String img) {
this.id = id;
this.name = name;
this.info = info;
this.img = img;
}
}
news_itm.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">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<ImageView
android:id="#+id/newspic"
android:layout_width="200dp"
android:layout_height="200dp"
android:layout_gravity="center"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:layout_alignParentEnd="true" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="اقرأ المزيد"
android:textAlignment="center"
android:id="#+id/text_info"
android:layout_gravity="center"
android:layout_centerVertical="true"
android:layout_alignParentStart="true"
android:layout_marginStart="35dp" />
<TextView
android:text="TextView"
android:layout_width="150dp"
android:layout_height="wrap_content"
android:layout_marginTop="27dp"
android:textSize="15dp"
android:id="#+id/textaddress"
android:layout_alignParentTop="true"
android:layout_alignParentStart="true" />
</RelativeLayout>
</LinearLayout>
how can i do that ?

first of all i will recommend to split the code between the ui and the data access, then load the data in a different threat and not in the ui thread
try loading the screen first with a dummy data to check that the layout and the screen works properly then connect it to the "DAL" with your saved data

Your are inflating the newslayout While Your layout is **news_itm.xml**
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
myView inflater.inflate(R.layout.**newslayout**,container,false);

Related

Unable to display fetch data from MYSQL database in custom gridview in android

In my app I use grid view to display data. grid view is in a fragment.I already retrieve data from mysql database in Log cat but that json data not display in custom grid.
activity_product_list.xml
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:tools="http://schemas.android.com/tools"
tools:context=".DrawerActivity">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginBottom="8dp"
android:layout_marginEnd="8dp"
android:layout_marginLeft="8dp"
android:layout_marginRight="8dp"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent">
<TextView
android:id="#+id/header2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="PRODUCTS : -"
android:textSize="20sp"
android:textStyle="bold"
android:textColor="#color/blue"/>
<GridView
android:id="#+id/productlist"
android:layout_below="#+id/header2"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:numColumns="2"
android:horizontalSpacing="2dp"
android:layout_marginTop="#dimen/activity_horizontal_margin">
</GridView>
</RelativeLayout>
ProductListFragment.java
public class ProductListFragment extends Fragment {
List<Product> productList;
GridView gridView;
CustomProductList customProductList;
int categoryid;
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.activity_product_list, container,false);
gridView = (GridView) rootView.findViewById(R.id.productlist);
final GlobalVariable ID = (GlobalVariable)getActivity().getApplication();
categoryid = ID.getCategoryid();
productList = new ArrayList<>();
loadProduct();
customProductList = new CustomProductList(getActivity(),productList);
gridView.setAdapter(customProductList);
return rootView;
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
}
private void loadProduct() {
String PRODUCT_URL = "http://192.168.0.101/cart/product/get_all_product.php?vcategoryid="+categoryid;
StringRequest stringRequest= new StringRequest(Request.Method.GET, PRODUCT_URL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject obj = new JSONObject(response);
JSONArray array = obj.getJSONArray("products");
for (int i = 0; i < array.length(); i++){
//getting the user from the response
JSONObject userJson = array.getJSONObject(i);
Product product = new Product();
product.setProductid(userJson.getInt("productid"));
product.setProductName(userJson.getString("productname"));
product.setProductDesc(userJson.getString("productdesc"));
product.setPrice(userJson.getString("productprice"));
productList.add(product);
Log.e("product",userJson+"");
}
customProductList.notifyDataSetChanged();
Log.e("product",customProductList+"");
//customCategoryList = new CustomCategoryList(getActivity(),categoryList);
//recyclerView.setAdapter(customCategoryList);
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
Volley.newRequestQueue(getActivity()).add(stringRequest);
}
}
custom_product_list.xml
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<ImageView
android:layout_width="200dp"
android:layout_height="200dp"
android:src="#drawable/home_appliances"/>
<TextView
android:id="#+id/productName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Redmi"
android:textStyle="bold"
android:textColor="#color/black"
android:textSize="22sp"/>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:layout_marginTop="5dp">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="RS."
android:textSize="20sp"
android:textStyle="bold"
android:textColor="#color/black"/>
<TextView
android:id="#+id/price"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="9999"
android:textSize="20sp"
android:textStyle="bold"
android:textColor="#color/blue"
android:layout_marginLeft="10dp"/>
</LinearLayout>
CustomProductList.java
public class CustomProductList extends BaseAdapter {
private Context mCtx;
private List<Product> productList;
public CustomProductList(Context mCtx, List<Product> productList) {
this.mCtx = mCtx;
this.productList = productList;
}
#Override
public int getCount() {
return 0;
}
#Override
public Object getItem(int i) {
return null;
}
#Override
public long getItemId(int i) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) mCtx
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View gridView;
if (convertView == null) {
gridView = new View(mCtx);
// get layout from mobile.xml
gridView = inflater.inflate(R.layout.custom_product_list, null);
TextView productname = (TextView) gridView.findViewById(R.id.productName);
TextView price = (TextView) gridView.findViewById(R.id.price);
// getting data for the row
Product product = productList.get(position);
// set data
productname.setText(product.getProductName());
price.setText(product.getPrice());
} else {
gridView = (View) convertView;
}
return gridView;
}
}
This is my code.All data comes from database in logcat as json..But All not display in grid.Please help me.Tell me What is the problem.
Solution:
You forgot to get count the updated list, hence chenge the below code:
#Override
public int getCount() {
return 0;
}
to this:
#Override
public int getCount() {
return this.productList.size();
}
That's it. Hope it helps.

E/RecyclerView: No adapter attached; skipping layout. using ASYNC TASK

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

compare listview time with currenttime

There are 3 textviews and 1 button in my listview.One of textview contains time.I want button must get clicked after 20mins of intime.I want to compare Intime with current time and if difference >20 mins then button must get clicked.Following is my code-
MainActivity.java
public class MainActivity extends Activity {
TextView txtno,txtname,txtintime;
ListView listView;
ArrayList<Model> data;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
txtno=(TextView)findViewById(R.id.no);
txtname=(TextView)findViewById(R.id.name);
txtintime=(TextView)findViewById(R.id.intime);
listView = (ListView) findViewById(R.id.list);
data=new ArrayList<>();
data.add(new Model(1,"ABC","11:45:50 AM"));
data.add(new Model(2,"PQR","11:50:50 AM"));
data.add(new Model(1,"XyZ","12:45:50 PM"));
data.add(new Model(1,"SHjhsj","04:45:50 PM"));
Custom c=new Custom(this,data);
listView.setAdapter(c);
}
}
Model.java
public class Model {
int no;
String name,intime;
public Model(int no, String name, String intime) {
this.no = no;
this.name = name;
this.intime = intime;
}
public int getNo() {
return no;
}
public void setNo(int no) {
this.no = no;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getIntime() {
return intime;
}
public void setIntime(String intime) {
this.intime = intime;
}
}
Custom.java
public class Custom extends BaseAdapter {
Activity a;
ArrayList<Model> data;
public Custom(Activity a, ArrayList<Model> data) {
this.a = a;
this.data = data;
}
#Override
public int getCount() {
return data.size();
}
#Override
public Object getItem(int i) {
return data.get(i);
}
#Override
public long getItemId(int i) {
return i;
}
public class Viewholder {
TextView srno, name, intime;
Button end;
}
#Override
public View getView(final int i, View convertView, ViewGroup viewGroup) {
Viewholder viewholder = null;
if (convertView == null) {
viewholder = new Viewholder();
LayoutInflater li = a.getLayoutInflater();
convertView = li.inflate(R.layout.list_item, viewGroup, false);
viewholder.srno = (TextView) convertView.findViewById(R.id.cno);
viewholder.name = (TextView) convertView.findViewById(R.id.cname);
viewholder.intime = (TextView) convertView.findViewById(R.id.ctime);
viewholder.end = (Button) convertView.findViewById(R.id.cend);
convertView.setTag(viewholder);
}else {
viewholder=(Viewholder)convertView.getTag();
}
final Model model = data.get(i);
viewholder.srno.setText(valueOf(data.get(i).getNo()));
viewholder.name.setText(valueOf(data.get(i).getName()));
viewholder.intime.setText(valueOf(data.get(i).getIntime()));
viewholder.end.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(a, data.get(i).getName()+" Exited", Toast.LENGTH_LONG).show();
}
});
return convertView;
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
tools:context="com.example.abc.timer.MainActivity">
<TextView
android:layout_width="70dp"
android:layout_height="50dp"
android:id="#+id/no"
android:text="CustNo"
android:textSize="20dp"
android:textColor="#000"/>
<TextView
android:layout_width="80dp"
android:layout_height="50dp"
android:id="#+id/name"
android:layout_toRightOf="#+id/no"
android:text="Name"
android:textSize="20dp"
android:textColor="#000"/>
<TextView
android:layout_width="80dp"
android:layout_height="50dp"
android:id="#+id/intime"
android:layout_toRightOf="#+id/name"
android:text="InTime"
android:textSize="20dp"
android:textColor="#000"/>
<TextView
android:layout_width="70dp"
android:layout_height="50dp"
android:id="#+id/exit"
android:text="Exit"
android:layout_toRightOf="#+id/intime"
android:textSize="20dp"
android:textColor="#000"/>
<ListView
android:layout_width="match_parent"
android:layout_height="400dp"
android:layout_below="#+id/no"
android:id="#+id/list"
></ListView>
</RelativeLayout>
list_item.xml
<?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">
<TextView
android:layout_width="70dp"
android:layout_height="match_parent"
android:id="#+id/cno"
android:gravity="center"/>
<TextView
android:layout_width="70dp"
android:layout_height="match_parent"
android:id="#+id/cname"
android:gravity="center"/>
<TextView
android:layout_width="80dp"
android:layout_height="match_parent"
android:id="#+id/ctime"
android:gravity="center"/>
<Button
android:layout_width="90dp"
android:layout_height="40dp"
android:text="End"
android:id="#+id/cend"
android:background="#c14c4a"
android:gravity="center"/>
</LinearLayout>
Use an AlarmManager with your specified time and the moment alarm will trigger you can enable the button, hence enabling the click event for the button.
Edit:
Either you can go ahead with handler object and use handler.postDelayed() method or there itself you can create a Timer Object and schedule the timer task within that object and do the stuff.
Assuming that u know how to convert the time strings into timestamps,modify ur adapter like this:
public class Custom extends BaseAdapter {
Activity a;
ArrayList<Model> data;
public Custom(Activity a, ArrayList<Model> data) {
this.a = a;
this.data = data;
}
#Override
public int getCount() {
return data.size();
}
#Override
public Object getItem(int i) {
return data.get(i);
}
#Override
public long getItemId(int i) {
return i;
}
public class Viewholder {
TextView srno, name, intime;
Button end;
}
#Override
public View getView(final int i, View convertView, ViewGroup viewGroup) {
Viewholder viewholder = null;
if (convertView == null) {
viewholder = new Viewholder();
LayoutInflater li = a.getLayoutInflater();
convertView = li.inflate(R.layout.list_item, viewGroup, false);
viewholder.srno = (TextView) convertView.findViewById(R.id.cno);
viewholder.name = (TextView) convertView.findViewById(R.id.cname);
viewholder.intime = (TextView) convertView.findViewById(R.id.ctime);
viewholder.end = (Button) convertView.findViewById(R.id.cend);
convertView.setTag(viewholder);
}else {
viewholder=(Viewholder)convertView.getTag();
}
final Model model = data.get(i);
viewholder.srno.setText(valueOf(data.get(i).getNo()));
viewholder.name.setText(valueOf(data.get(i).getName()));
viewholder.intime.setText(valueOf(data.get(i).getIntime()));
final Runnable r = new Runnable() {
public void run() {
viewholder.end.setEnabled(true);
}
};
if(yourObjectTimestamp - currentTimeStamp > 20){ //this u need to do on ur own
viewholder.end.setEnabled(true); // I assumed u know how to convert times to timestamps
}else{
viewholder.end.setEnabled(false);
long timeDiffInMillis = yourObjectTimestamp - currentTimeStamp;
handler.postDelayed(r,timeDiffInMillis );
}
viewholder.end.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(a, data.get(i).getName()+" Exited", Toast.LENGTH_LONG).show();
}
});
return convertView;
}
}

getView() not called even when getCount() has results

Sorry for my english, not my first language.
Im creating an app in Android and I have a issue:
I have a TabBar with 2 fragments (1 - ProductFragment and 2 - CartFragment), in second Fragment (CartFragment) I have a ListView and that ListView is initial null.
CartFragment Layout:
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="15dp">
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical">
<ListView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/lancarvenda_carrinho_lvwresultado"
android:orientation="vertical" />
</LinearLayout>
</FrameLayout>
In ProductFragment I have a button with onclick, that onclick Intents another activity and in that activity I add values in my public Custom List:
public static List<PesquisarProdutoResponse> Carrinho = new ArrayList<>();
When I done with adding values that I need, I close that activity and return to TabBar and expects that ListView has been populated.
The method that populate my public list:
private void PesquisarProduto()
{
RequestQueue sQueue = Volley.newRequestQueue(getActivity());
String sEnderecoBase = "http://www.my-url";
StringRequest sRequest = new StringRequest(Request.Method.POST, sEnderecoBase, new Response.Listener<String>() {
#Override
public void onResponse(String response)
{
PesquisarProdutoResponse sResultado = new Gson().fromJson((String) response, PesquisarProdutoResponse.class);
if (sResultado.getCodigoRetorno() != 0)
{
//lastText = "Produto não encontrado";
//barcodeView.setStatusText("Produto não encontrado");
}
else
{
Variaveis.Carrinho.add(sResultado);
try {
List<PesquisarProdutoObjetoRetorno> sCarrinhoAuxiliar = new ArrayList<>();
for (int i = 0; i < Variaveis.Carrinho.size(); i++) {
PesquisarProdutoObjetoRetorno sItem = Variaveis.Carrinho.get(i).getDadosProduto();
sCarrinhoAuxiliar.add(sItem);
}
LancarVendaCarrinhoListViewAdapter sAdaptador = new LancarVendaCarrinhoListViewAdapter(getActivity(),
sCarrinhoAuxiliar);
fCarrinhoResultado.setAdapter(sAdaptador);
sAdaptador.notifyDataSetChanged();
Object oi = fCarrinhoResultado.getCount();
oi.toString();
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
}, new Response.ErrorListener()
{
#Override
public void onErrorResponse(VolleyError error)
{
byte[] sBytesResposta = error.networkResponse.data;
String sTexto = new String(sBytesResposta);
Mensagem.ExibirAlert(getActivity(), String.valueOf(error.networkResponse.statusCode));
}
})
{
#Override
public Map<String, String> getHeaders() throws AuthFailureError
{
Map<String, String> sHeaders = new HashMap<>();
sHeaders.put("Authorization", "Bearer " + Variaveis.ApiToken);
return sHeaders;
}
#Override
public byte[] getBody() throws AuthFailureError
{
return new Gson().toJson(sCorpoBusca).getBytes();
}
#Override
public String getBodyContentType()
{
return "application/json";
}
};
sQueue.add(sRequest);
}
ListView Adapter:
public class LancarVendaCarrinhoListViewAdapter extends BaseAdapter
{
private Context mContext;
//private LayoutInflater mInflater;
private List<PesquisarProdutoObjetoRetorno> mDataSource;
public LancarVendaCarrinhoListViewAdapter(Context context, List<PesquisarProdutoObjetoRetorno> items)
{
mContext = context;
mDataSource = items;
}
#Override
public int getCount() {
return mDataSource.size();
}
#Override
public Object getItem(int position) {
return mDataSource.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent)
{
try
{
LayoutInflater mInflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View sView = mInflater.inflate(R.layout.activity_lancarvenda_carrinho_list_view_item, parent, false);
PesquisarProdutoObjetoRetorno sItem = (PesquisarProdutoObjetoRetorno) getItem(position);
TextView descricao = (TextView)sView.findViewById(R.id.lancarvenda_carrinho_item_txtdescricao);
descricao.setText(sItem.getDescricao());
TextView preco = (TextView)sView.findViewById(R.id.lancarvenda_carrinho_item_txvpreco);
preco.setText(String.valueOf(sItem.getPreco()));
EditText quantidade = (EditText)sView.findViewById(R.id.lancarvenda_carrinho_item_etquantidade);
quantidade.setText("1");
return sView;
}
catch (Exception e)
{
e.printStackTrace();
return null;
}
}
}
My layout of row:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal">
<de.hdodenhof.circleimageview.CircleImageView xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/lancarvenda_carrinho_item_imvFoto"
android:layout_width="80dp"
android:layout_height="80dp"
android:layout_gravity="center_horizontal"
android:background="#drawable/circulo_foto2"
app:border_color="#898989"
app:border_width="2dp" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:layout_marginLeft="10dp">
<TextView
android:id="#+id/lancarvenda_carrinho_item_txtdescricao"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:text="Relogio"
android:textSize="20dp"
android:textStyle="bold"
android:layout_marginRight="8dp"
android:lines="2"
android:minLines="2"
android:singleLine="false"/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal">
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TextView
android:id="#+id/lancarvenda_carrinho_item_txvpreco"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="8dp"
android:text="R$ 399,89"
android:textColor="#1ba39c"
android:textSize="20dp"
android:layout_marginRight="70dp"/>
<EditText
android:id="#+id/lancarvenda_carrinho_item_etquantidade"
android:layout_width="50dp"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:backgroundTint="#9a9b9c"
android:hint="0"
android:textColor="#2a2d2e"
android:layout_marginRight="8dp"/>
</RelativeLayout>
</LinearLayout>
</LinearLayout>
</LinearLayout>
</RelativeLayout>
In debug mode, when code pass in getCount in Adapter, I have size more than 1 and my list still not show! Even if I close TabBar and reopen and set adapter (with values) on onCreate method.
What can I do to my ListView show?
EDIT
I inflate listview on onCreate:
super.onCreate(savedInstanceState);
LayoutInflater sInflater = getActivity().getLayoutInflater();
View sView = sInflater.inflate(R.layout.fragment_lancarvenda_carrinho, null);
fCarrinhoResultado = (ListView) sView.findViewById(R.id.lancarvenda_carrinho_lvwresultado);
Try making your list a member of the class instead of a local variable
private void PesquisarProduto()
{
RequestQueue sQueue = Volley.newRequestQueue(getActivity());
String sEnderecoBase = "http://www.my-url";
StringRequest sRequest = new StringRequest(Request.Method.POST, sEnderecoBase, new Response.Listener<String>() {
// Make cart list a private data member so it doesn't loose scope //
List<PesquisarProdutoObjetoRetorno> sCarrinhoAuxiliar;
#Override
public void onResponse(String response)
{
PesquisarProdutoResponse sResultado = new Gson().fromJson((String) response, PesquisarProdutoResponse.class);
if (sResultado.getCodigoRetorno() != 0)
{
//lastText = "Produto não encontrado";
//barcodeView.setStatusText("Produto não encontrado");
}
else
{
Variaveis.Carrinho.add(sResultado);
try {
sCarrinhoAuxiliar = new ArrayList<>();
...
}
...
}
...
}
...
}
...
}
Declare your List sCarrinhoAuxiliar and adapter sAdaptador as global.
Update your OnCreateView() as below:
// Global
List<PesquisarProdutoObjetoRetorno> sCarrinhoAuxiliar;
LancarVendaCarrinhoListViewAdapter sAdaptador;
.........................
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
....................
........................
sCarrinhoAuxiliar = new ArrayList<>();
sAdaptador = new LancarVendaCarrinhoListViewAdapter(getActivity(), sCarrinhoAuxiliar);
fCarrinhoResultado.setAdapter(sAdaptador);
.......................
...............
}
Update your onResponse() method as below:
#Override
public void onResponse(String response) {
.....................
..........................
try {
// Clear old data
sCarrinhoAuxiliar.clear();
for (int i = 0; i < Variaveis.Carrinho.size(); i++) {
PesquisarProdutoObjetoRetorno sItem = Variaveis.Carrinho.get(i).getDadosProduto();
sCarrinhoAuxiliar.add(sItem);
}
// Update list
sAdaptador.notifyDataSetChanged();
.............
....................
}
catch (Exception e) {
e.printStackTrace();
}
}
Hope this will help~
I got help from another forum and I was able to solve my problem:
I override two methods: OnCreate (inflate and receive view) and OnCreateView (find the product and put on listview), I eliminate method OnCreate and put everything on OnCreateView!
That solve my problem!
Thanks to everybody!

Android flipview in a fragment not working

Am trying to make a ui with flipview as in this tutorial. IThe tutorial deals with activities, but i want it in fragments case. That ie, the flip effect as well as its parent is a fragment. When i use activity it works, but on using fragment,only the empty textview shows up. Can anyone help me with this?
This is some part of the code
page.xml
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#ff3333" >
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="300dp">
<ImageView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:src="#drawable/banner"
android:id="#+id/head"/>
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:textSize="20dp"
android:id="#+id/header"
android:gravity="center"/>
</RelativeLayout>
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/des"
android:textSize="30dp"
android:gravity="center"/>
</FrameLayout>
fragment_news_feed :
<merge xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:flipview="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools">
<se.emilsjolander.flipview.FlipView
android:id="#+id/flip_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#ffffff"
flipview:orientation="vertical"
tools:context="com.excel.excelapp.fragment.NewsFeedFragment" >
</se.emilsjolander.flipview.FlipView>
<TextView
android:id="#+id/empty_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="Empty!"
android:textSize="32sp"
android:visibility="gone" />
</merge>
NewsFeedFragment.java
public class NewsFeedFragment extends Fragment implements NewsFlipAdapter.Callback, FlipView.OnFlipListener, FlipView.OnOverFlipListener{
private FlipView mFlipView;
private NewsFlipAdapter mAdapter;
int i=0,no_of_items=7;
public NewsFeedFragment() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
LinearLayout wrapper = new LinearLayout(getActivity());
View view = inflater.inflate(R.layout.fragment_news_feed, wrapper, true);
setUpView(view);
return wrapper;
}
private void setUpView(View view) {
mFlipView = (FlipView) view.findViewById(R.id.flip_view);
mAdapter = new NewsFlipAdapter(getActivity());
mAdapter.setCallback(this);
mFlipView.setAdapter(mAdapter);
mFlipView.setOnFlipListener(this);
mFlipView.peakNext(false);
mFlipView.setOverFlipMode(OverFlipMode.RUBBER_BAND);
mFlipView.setEmptyView(view.findViewById(R.id.empty_view));
mFlipView.setOnOverFlipListener(this);
}
#Override
public void onPageRequested(int page) {
mFlipView.smoothFlipTo(page);
}
#Override
public void onFlippedToPage(FlipView v, int position, long id) {
Log.i("pageflip", "Page: " + position);
if(position > mFlipView.getPageCount()-3 && mFlipView.getPageCount()<30){
mAdapter.addItems(5);
}
}
#Override
public void onOverFlip(FlipView v, OverFlipMode mode,
boolean overFlippingPrevious, float overFlipDistance,
float flipDistancePerPage) {
Log.i("overflip", "overFlipDistance = "+overFlipDistance);
}
NewsFlipAdapter.java
public class NewsFlipAdapter extends BaseAdapter {
public interface Callback {
public void onPageRequested(int page);
}
static class Item {
static long id = 0;
long mId;
public Item() {
mId = id++;
}
long getId() {
return mId;
}
}
private LayoutInflater inflater;
private Callback callback;
private List<Item> items = new ArrayList<Item>();
public NewsFlipAdapter(Context context) {
inflater = LayoutInflater.from(context);
}
public void setCallback(Callback callback) {
this.callback = callback;
}
#Override
public int getCount() {
return items.size();
}
#Override
public Object getItem(int position) {
return position;
}
#Override
public long getItemId(int position) {
return items.get(position).getId();
}
#Override
public boolean hasStableIds() {
return true;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
holder = new ViewHolder();
convertView = inflater.inflate(R.layout.page, parent, false);
holder.heading = (TextView) convertView.findViewById(R.id.header);
holder.description = (TextView) convertView.findViewById(R.id.des);
holder.header = (ImageView) convertView.findViewById(R.id.head);
// holder.firstPage = (Button) convertView.findViewById(R.id.first_page);
// holder.lastPage = (Button) convertView.findViewById(R.id.last_page);
// holder.firstPage.setOnClickListener(this);
// holder.lastPage.setOnClickListener(this);
// convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
return convertView;
}
static class ViewHolder {
TextView heading;
ImageView header;
TextView description;
}
/* #Override
public void onClick(View v) {
switch(v.getId()){
case R.id.first_page:
if(callback != null){
callback.onPageRequested(0);
}
break;
case R.id.last_page:
if(callback != null){
callback.onPageRequested(getCount()-1);
}
break;
}
}*/
public void addItems(int amount) {
TextView text;
for (int i = 0; i < amount; i++) {
items.add(new Item());
}
notifyDataSetChanged();
}
public void addItemsBefore(int amount) {
for (int i = 0; i < amount; i++) {
items.add(0, new Item());
}
notifyDataSetChanged();
}
I am not a 100 % sure about the following explanation, so please correct me if I am wrong.
The <merge> tag merges the inflated layout with it's parent view.
It generally doesn't seem to sit well with fragments as explained in more detail here.
So try to replace merge with LinearLayout in your fragment_newsfeed_layout:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:flipview="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools">
<se.emilsjolander.flipview.FlipView
android:id="#+id/flip_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#ffffff"
flipview:orientation="vertical"
tools:context="com.excel.excelapp.fragment.NewsFeedFragment" >
</se.emilsjolander.flipview.FlipView>
<TextView
android:id="#+id/empty_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="Empty!"
android:textSize="32sp"
android:visibility="gone" />
</LinearLayout>

Categories

Resources