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

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

Related

cardView in a RecyclerView is not showing any item

I am trying to make an App that has two tabs in a ViewPager and each tab are fragments and should have a card View in a RecyclerView.I fetch the data from an API added it in an ArrayList. I dont see any error in my Adapter class and DailyMenuFrag. I will appreciate any kind of help
DailyMenuFrag.java
public class DailyMenuFrag extends Fragment {
private List<DailyData> data_list;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
data_list = new ArrayList<>();
load_data();
View view = inflater.inflate(R.layout.fragment_daily_menu, container, false);
RecyclerView recyclerView = (RecyclerView) view.findViewById(R.id.recycler_view);
DailyDataAdapter adapter = new DailyDataAdapter(getActivity(), data_list);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity());
recyclerView.setLayoutManager(linearLayoutManager);
recyclerView.setAdapter(adapter);
TextView textView = (TextView) view.findViewById(R.id.tt);
textView.setText("hellp");
return view;
}
public void load_data() {
task.execute("http://yemekapp.kuarkdijital.com.tr/home.php");
}
AsyncTask<String, Void, String> task = new AsyncTask<String, Void, String>() {
#Override
protected String doInBackground(String... params) {
URL url;
HttpURLConnection URLConnection = null;
String current = "";
try {
url = new URL(params[0]);
URLConnection = (HttpURLConnection) url.openConnection();
URLConnection.connect();
InputStream inputStream = URLConnection.getInputStream();
InputStreamReader reader = new InputStreamReader(inputStream);
int data = reader.read();
while (data != -1) {
current += (char) data;
data = reader.read();
}
JSONObject dailyObject = null;
JSONObject popularObject = null;
JSONObject jsonObject = new JSONObject(current);
JSONObject banner = jsonObject.getJSONObject("banner");
String daily = jsonObject.getString("daily");
String popular = jsonObject.getString("popular");
JSONArray dailyArray = new JSONArray(daily);
JSONArray popularArray = new JSONArray(popular);
for (int i = 0; i < dailyArray.length(); i++) {
dailyObject = dailyArray.getJSONObject(i);
popularObject = popularArray.getJSONObject(i);
DailyData singleData = new DailyData(dailyObject.getInt("id"), dailyObject.getString("Servings"), dailyObject.getString("Title"), dailyObject.getString("CookTime"), dailyObject.getString("Image"));
data_list.add(singleData);
Log.i("data", data_list.size() + "");
}
}
catch (JSONException e) {
e.printStackTrace();
}
catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return current;
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
}
};
}
DailyDataAdapter.java
public class DailyDataAdapter extends RecyclerView.Adapter<DailyDataAdapter.ViewHolder> {
Context context;
List<DailyData> dailyDataList;
public DailyDataAdapter(Context context, List<DailyData> dailyDatas) {
this.context = context;
this.dailyDataList = dailyDatas;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.card,parent,false);
return new ViewHolder(itemView);
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
holder.title.setText(dailyDataList.get(position).getTitle());
holder.cookTime.setText(dailyDataList.get(position).getCookTime());
holder.servings.setText(dailyDataList.get(position).getServings());
//Image
Glide.with(context).load(dailyDataList.get(position).getImage_link()).into(holder.thumbnail);
}
#Override
public int getItemCount() {
return dailyDataList.size();
}
public class ViewHolder extends RecyclerView.ViewHolder{
public TextView cookTime,servings,title;
public ImageView thumbnail;
public ViewHolder(View itemView) {
super(itemView);
title = (TextView) itemView.findViewById(R.id.title);
servings = (TextView) itemView.findViewById(R.id.servings);
cookTime = (TextView) itemView.findViewById(R.id.cooktime);
thumbnail = (ImageView) itemView.findViewById(R.id.thumbnail);
}
}
}
MainActivity.java
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if(savedInstanceState == null){
ViewPagger viewPagger = new ViewPagger();
FragmentManager manager = getSupportFragmentManager();
FragmentTransaction transaction = manager.beginTransaction();
transaction.replace(R.id.fragment_container,viewPagger);
transaction.commit();
}
}
}
ViewPAgger.java
public class ViewPagger extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_view_pagger,container,false);
ViewPager viewPager = (ViewPager) view.findViewById(R.id.view_pager);
TabLayout tabLayout = (TabLayout) view.findViewById(R.id.tab);
viewPager.setAdapter(new FragmentPagerAdapter(getChildFragmentManager()) {
#Override
public Fragment getItem(int position) {
return position == 0? new DailyMenuFrag():new PopularMenuFrag();
}
#Override
public int getCount() {
return 2;
}
#Override
public CharSequence getPageTitle(int position) {
return position == 0? "Daily":"Popular";
}
});
tabLayout.setupWithViewPager(viewPager);
return view;
}
}
ViewPagger.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"
tools:context="com.nejat.yemektarifiproject.ViewPagger">
<android.support.design.widget.TabLayout
android:id="#+id/tab"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="40dp">
</android.support.design.widget.TabLayout>
<android.support.v4.view.ViewPager
android:id="#+id/view_pager"
android:layout_width="match_parent"
android:layout_height="match_parent">
</android.support.v4.view.ViewPager>
</FrameLayout>
card.xml
<?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="wrap_content"
xmlns:card_view="http://schemas.android.com/tools">
<android.support.v7.widget.CardView
android:id="#+id/card_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="center"
android:layout_margin="5dp"
android:elevation="3dp"
card_view:cardCornerRadius="0dp">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:id="#+id/thumbnail"
android:layout_width="match_parent"
android:layout_height="160dp"
android:background="?attr/selectableItemBackgroundBorderless"
android:clickable="true"
android:scaleType="fitXY" />
<TextView
android:id="#+id/title"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#id/thumbnail"
android:paddingLeft="10dp"
android:paddingRight="10dp"
android:paddingTop="10dp"
android:textColor="#4c4c4c"
android:textSize="15dp" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/title"
android:orientation="horizontal">
<TextView
android:id="#+id/servings"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#id/title"
android:paddingBottom="10dp"
android:paddingLeft="10dp"
android:paddingRight="10dp"
android:textSize="10dp"
android:layout_weight="1"/>
<TextView
android:id="#+id/cooktime"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#id/title"
android:layout_weight="1"
android:paddingBottom="10dp"
android:paddingLeft="10dp"
android:paddingRight="10dp"
android:textSize="10dp" />
</LinearLayout>
</RelativeLayout>
</android.support.v7.widget.CardView>
</LinearLayout>
Fragment_DailyMenuFrag.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"
tools:context="com.nejat.yemektarifiproject.DailyMenuFrag">
<android.support.v7.widget.RecyclerView
android:id="#+id/recycler_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
>
</android.support.v7.widget.RecyclerView>
<TextView
android:id="#+id/tt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
</FrameLayout>
Add this
adapter.notifyDataSetChanged() in postExecute
I think you are forgetting to notify adapter about data change after you are getting data.
Declare your Adapter Global so you can call it from any where
DailyDataAdapter adapter = null;
and initialize it like this in your onCreateView
adapter = new DailyDataAdapter(getActivity(), data_list);
so call this notifyDataSetChanged() after doInBackground in your onPostExecute
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
adapter.notifyDataSetChanged();
}
this should work for you.

SwipeRefreshLayout + ViewPager with Fragments not working

I have implemented the SwipeRefreshLayout in many of the pages,and it working fine. but here i got stuck with one specific implementation , where i have a SwipeRefreshLayout for the ViewPager and ViewPager holding the FragmentPagerAdapter.
In my case , I have a ViewPager with two tabs and each holding the fragment with RecyclerView. On main page I have a SwipeRefreshLayout and on the onRefresh i need to load the API and update the fragments in ViewPager. Updating is working fine but unfortunately RecyclerView inside the Fragment ( ViewPager tab Item ) not scrolling top and it always calling the SwipeToRefresh.
I am familiar with using the SwipeRefreshLayout with RecyclerView, but here the problem is the main child of the SwipeRefreshLayout is ViewPager and it having the Fragment inside it and that fragment is holding the RecyclerView.
I have a thought of moving the SwipeRefreshLayout inside the fragments for the RecyclerView , but again here i have challenges like both the Fragments is having the same API. So that i am using the SwipeRefreshLayout directly on ViewPager to refresh my data.
Here is some of my codes.
MainContacts.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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">
<LinearLayout
android:id="#+id/ll_no_records"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_centerInParent="true"
android:gravity="center"
android:orientation="vertical"
android:visibility="gone">
<ImageView
android:id="#+id/iv_retry"
android:layout_width="60dp"
android:layout_height="60dp"
android:layout_gravity="center"
android:contentDescription="#string/todo"
android:src="#drawable/ic_reload" />
<TextView
android:id="#+id/textError"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="25dp"
android:gravity="center"
android:text="#string/no_contact_found"
android:textAppearance="#style/Base.TextAppearance.AppCompat.Medium"
android:textColor="#color/colorDarkGray" />
</LinearLayout>
<LinearLayout
android:id="#+id/ll_process"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_centerInParent="true"
android:alpha="1"
android:gravity="center"
android:orientation="vertical"
android:visibility="visible">
<ProgressBar
android:id="#+id/progress"
android:layout_width="50dp"
android:layout_height="40dp"
android:layout_gravity="center"
android:indeterminate="true" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:text="#string/fetching"
android:textAppearance="#style/Base.TextAppearance.AppCompat.Medium"
android:textColor="#color/colorDarkGray" />
</LinearLayout>
<android.support.v4.widget.SwipeRefreshLayout
android:id="#+id/swipeRefreshLayout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:id="#+id/contacts_screen"
android:layout_width="match_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<android.support.design.widget.TabLayout
android:id="#+id/my_contacts_tabs"
style="#style/MyCustomTabLayout"
android:layout_width="match_parent"
app:tabBackground="#color/colorWhite"
android:layout_height="wrap_content" />
<android.support.v4.view.ViewPager
android:id="#+id/my_contacts_view_pager"
android:layout_width="match_parent"
android:layout_height="0px"
android:layout_weight="1"
android:background="#android:color/transparent" >
</android.support.v4.view.ViewPager>
</LinearLayout>
</android.support.v4.widget.SwipeRefreshLayout>
</RelativeLayout>
contacts.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:hc="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:id="#+id/ll_no_records"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_centerInParent="true"
android:gravity="center"
android:orientation="vertical"
android:visibility="gone">
<ImageView
android:id="#+id/iv_retry"
android:layout_width="60dp"
android:layout_height="60dp"
android:layout_gravity="center"
android:contentDescription="#string/todo"
android:src="#drawable/ic_reload" />
<TextView
android:id="#+id/textError"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="25dp"
android:gravity="center"
android:text="#string/no_contact_found"
android:textAppearance="#style/Base.TextAppearance.AppCompat.Medium"
android:textColor="#color/colorDarkGray" />
</LinearLayout>
<com.diegocarloslima.fgelv.lib.FloatingGroupExpandableListView
android:id="#+id/contactList"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="#id/searchContainer"
android:animateLayoutChanges="true"
android:childDivider="#android:color/transparent" />
</RelativeLayout>
MainFragment ( Which i am using to load the child fragments , SwipeTORefreshLayout + ViewPager here)
public class MainFragment extends BaseFragment {
private TextView mTextError;
private LinearLayout llNoRecords, ll_process;
private ImageView iv_retry;
private MaterialSearchView materialSearchView;
PHCJsonResponseContactDetailModel mContactResponseModel;
int expandableListSelectionType = ExpandableListView.PACKED_POSITION_TYPE_NULL;
boolean actionModeEnabled;
private Activity mActivity;
SwipeRefreshLayout mSwipeRefreshLayout;
private ViewPager viewPager;
TabLayout tabLayout;
ContactsTabPagerAdapter mAdapter;
ArrayList<PHCContactDetailModel> mContactList =new ArrayList<>();
ArrayList<PHCContactDetailModel> mFavoriteList;
boolean isSwipeToRefresh;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
mActivity = getActivity();
View view = inflater.inflate(R.layout.phc_contact_fragment, container, false);
getViewId(view);
setListener();
if (isNetworkAvailable()) {
if(((MainDrawerActivity)mActivity).getPHCContactFragmentData()==null)
getAllContactData();
else
updateWidgets();
} else {
showNoNetworkToast();
llNoRecords.setVisibility(View.VISIBLE);
mTextError.setText(getResources().getText(R.string.no_internet_retry));
}
return view;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
#Override
public void onResume() {
super.onResume();
}
/*#Override
public void onPrepareOptionsMenu(final Menu menu) {
getActivity().getMenuInflater().inflate(R.menu.menu_fragment_group, menu);
}*/
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.menu_fragment_contacts, menu);
MenuItem item = menu.findItem(R.id.action_search);
materialSearchView.setMenuItem(item);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == R.id.action_create_group) {
Intent createGroupIntent = new Intent(getActivity(), PHCCreateGroupActivity.class);
createGroupIntent.putExtra("comeFrom", PHCAppConstant.GROUP_ADD);
getActivity().startActivity(createGroupIntent);
}
return super.onOptionsItemSelected(item);
}
private void setListener() {
iv_retry.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (isNetworkAvailable()) {
getAllContactData();
} else {
showNoNetworkToast();
}
}
});
}
private void getViewId(View view) {
mTextError = (TextView) view.findViewById(R.id.textError);
ll_process = (LinearLayout) view.findViewById(R.id.ll_process);
llNoRecords = (LinearLayout) view.findViewById(R.id.ll_no_records);
iv_retry = (ImageView) view.findViewById(R.id.iv_retry);
viewPager = (ViewPager) view.findViewById(R.id.my_contacts_view_pager);
tabLayout = (TabLayout) view.findViewById(R.id.my_contacts_tabs);
mSwipeRefreshLayout = (SwipeRefreshLayout) view.findViewById(R.id.swipeRefreshLayout);
mSwipeRefreshLayout.setColorSchemeResources(R.color.colorPrimary,
android.R.color.holo_green_dark,
android.R.color.holo_orange_dark,
android.R.color.holo_blue_dark);
mSwipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
if(mContactResponseModel!=null && mContactResponseModel.getData().size() >0)
{
isSwipeToRefresh = true;
getAllContactData();
}
}
});
materialSearchView = (MaterialSearchView) getActivity().findViewById(R.id.search_view);
}
private void getAllContactData() {
if (isNetworkAvailable()) {
// showProgress();
PHCApiInterface apiService = PHCApiClient.getClient(getActivity()).create(PHCApiInterface.class);
Call<PHCJsonResponseContactDetailModel> call = apiService.contactData(getApplicationData(getActivity()).getAuthToken(), getApplicationData(getActivity()).getUserID());
call.enqueue(new Callback<PHCJsonResponseContactDetailModel>() {
#Override
public void onResponse(Call<PHCJsonResponseContactDetailModel> call, Response<PHCJsonResponseContactDetailModel> response) {
Log.d(TAG, "getContacts URL " + response.raw().request().url());
Log.d(TAG, "getContacts Resp " + new Gson().toJson(response.body()));
mContactResponseModel = response.body();
((MainDrawerActivity)mActivity).setPHCContactFragmentData(mContactResponseModel);
if(mSwipeRefreshLayout.isRefreshing())
{
// cancel the Visual indication of a refresh
mSwipeRefreshLayout.setRefreshing(false);
}
if(isSwipeToRefresh)
{
isSwipeToRefresh=false;
updateWidgets();
}
else
updateWidgets();
}
#Override
public void onFailure(Call<PHCJsonResponseContactDetailModel> call, Throwable t) {
if(mSwipeRefreshLayout.isRefreshing())
{
// cancel the Visual indication of a refresh
mSwipeRefreshLayout.setRefreshing(false);
}
isSwipeToRefresh=false;
dismissProgress();
mTextError.setVisibility(View.VISIBLE);
}
});
} else {
isSwipeToRefresh=false;
if(mSwipeRefreshLayout.isRefreshing())
{
// cancel the Visual indication of a refresh
mSwipeRefreshLayout.setRefreshing(false);
}
showNoNetworkAlert();
}
}
private void updateWidgets() {
if (mContactResponseModel.getStatusCode() == 401 || mContactResponseModel.getStatusCode() == 402) {
showSessionExpireAlert(mContactResponseModel.getStatusMessage(), mContactResponseModel.getStatusCode());
return;
}
if (mContactResponseModel != null && mContactResponseModel.getStatusCode() == 1) {
dismissProgress();
mTextError.setVisibility(View.GONE);
mContactList = mContactResponseModel.getData();
mFavoriteList = mContactResponseModel.getData();
if(mContactList!=null && mContactList.size()>0)
{
llNoRecords.setVisibility(View.GONE);
mAdapter = new ContactsTabPagerAdapter(getActivity().getApplicationContext(), getChildFragmentManager(), mContactList , mFavoriteList);
viewPager.setAdapter(mAdapter);
tabLayout.setupWithViewPager(viewPager);
}
else {
llNoRecords.setVisibility(View.VISIBLE);
}
} else {
dismissProgress();
mTextError.setVisibility(View.VISIBLE);
}
}
public void dismissProgress() {
ll_process.setVisibility(View.GONE);
super.dismissProgress();
}
private void initiateContactChat(final PHCFacilityDetailsModel facilityDetailsModel, final int groupPosition, final int childPosition) {
String header = getApplicationData(getActivity()).getAuthToken();
PHCApiInterface apiService = PHCApiClient.getClient(getActivity()).create(PHCApiInterface.class);
Call<PHCContactInitiateChatResponseModel> call = apiService.initiateContactChat(header, facilityDetailsModel.getUserId(), getApplicationData(getActivity()).getUserID(), 0);
call.enqueue(new Callback<PHCContactInitiateChatResponseModel>() {
#Override
public void onResponse(Call<PHCContactInitiateChatResponseModel> call, Response<PHCContactInitiateChatResponseModel> response) {
Log.d(TAG, "initiateContactChat URL " + response.raw().request().url());
Log.d(TAG, "initiateContactChat Resp " + new Gson().toJson(response.body()));
PHCContactInitiateChatResponseModel mContactInitiateChatModel = response.body();
if (mContactInitiateChatModel != null && mContactInitiateChatModel.getStatusCode() == 1) {
Intent chatIntent = new Intent(getActivity(), PHCChatActivity.class);
// chatIntent.putExtra("headerName",mData.get(groupPosition).getFacilityDetails().get(childPosition).getUserName());
chatIntent.putExtra("headerName", facilityDetailsModel.getUserName());
chatIntent.putExtra("groupId", mContactInitiateChatModel.getData().getGroupId());
getActivity().startActivity(chatIntent);
}
}
#Override
public void onFailure(Call<PHCContactInitiateChatResponseModel> call, Throwable t) {
Toast.makeText(getActivity(), "Something went wrong! Please try again", Toast.LENGTH_SHORT).show();
}
});
}
}
ContactsTabPagerAdapter.java
public class ContactsTabPagerAdapter extends FragmentPagerAdapter {
/**
* The Page count.
*/
final int PAGE_COUNT = 2;
private String[] tabTitles = { "Contacts", "Favorites" };
private ArrayList<PHCContactDetailModel> mContactsList;
private ArrayList<PHCContactDetailModel> mFavoritesList;
Context mContext ;
public ContactsTabPagerAdapter(Context context, FragmentManager fm ,ArrayList<PHCContactDetailModel> contacts , ArrayList<PHCContactDetailModel> favs) {
super(fm);
this.mContext = context;
this.mContactsList = contacts;
this.mFavoritesList=favs;
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
ContactsFragment mContactsFragment =new ContactsFragment();
Bundle bundle=new Bundle();
bundle.putSerializable("Contacts", (Serializable) mContactsList);
mContactsFragment.setArguments(bundle);
return mContactsFragment;
case 1:
FavoritesFragment mFavoritesFragment=new FavoritesFragment();
Bundle pastBundle=new Bundle();
pastBundle.putSerializable("Favorites", (Serializable) mFavoritesList);
mFavoritesFragment.setArguments(pastBundle);
return mFavoritesFragment;
}
return null;
}
#Override
public int getCount() {
return 2;
}
#Override
public CharSequence getPageTitle(int position) {
// Generate title based on item position
return tabTitles[position];
}
/**
* Update.
*
* #param lContactsList contact list to update
* #param lFavoritesList favorites list to update
*/
//call this method to update fragments in ViewPager dynamically
public void update(ArrayList<PHCContactDetailModel> lContactsList, ArrayList<PHCContactDetailModel> lFavoritesList) {
this.mContactsList = lContactsList;
this.mFavoritesList = lFavoritesList;
notifyDataSetChanged();
}
#Override
public int getItemPosition(Object object) {
if (object instanceof UpdatableFragment) {
((UpdatableFragment) object).update(mContactsList, mFavoritesList);
}
//don't return POSITION_NONE, avoid fragment recreation.
return super.getItemPosition(object);
}
}
ContactsFragment.java
public class ContactsFragment extends BaseFragment implements UpdatableFragment{
private static final String TAG = "ContactFragmentTab";
private FloatingGroupExpandableListView mContactExpandableList;
private PHCContactAdapter mAdapter;
WrapperExpandableListAdapter wrapperAdapter;
boolean actionModeEnabled;
private LinearLayout llNoRecords;
private ArrayList<PHCContactDetailModel> mContactsData;
public ContactsFragment() {
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onActivityCreated(savedInstanceState);
}
#SuppressWarnings("unchecked")
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_contacts, container, false);
getViewId(rootView);
Bundle bundle= getArguments();
if(bundle !=null)
{
Log.d(TAG, "bundle is not empty");
mContactsData= (ArrayList<PHCContactDetailModel>) bundle.getSerializable("Contacts");
}
System.out.print("Contacts Size::" + mContactsData.size());
if(mContactsData!=null)
{
updateWidgets();
}
return rootView;
}
private void updateWidgets() {
mAdapter = new PHCContactAdapter(getActivity(), mContactsData, new ListShowingHidingListener() {
#Override
public void listHideAndShow(boolean isData) {
if (isData) {
llNoRecords.setVisibility(View.GONE);
mContactExpandableList.setVisibility(View.VISIBLE);
listUpdate();
} else {
llNoRecords.setVisibility(View.VISIBLE);
mContactExpandableList.setVisibility(View.GONE);
}
}
});
wrapperAdapter = new WrapperExpandableListAdapter(mAdapter);
mContactExpandableList.setAdapter(wrapperAdapter);
try {
for (int i = 0; i < wrapperAdapter.getGroupCount(); i++) {
mContactExpandableList.expandGroup(i);
}
} catch (Exception e) {
Log.e("Exception in Expand", "" + e);
}
}
private void listUpdate() {
try {
for (int i = 0; i < wrapperAdapter.getGroupCount(); i++) {
mContactExpandableList.expandGroup(i);
}
} catch (Exception e) {
Log.e("Exception in Expand", "" + e);
}
}
private void getViewId(View view) {
// mContactExpandableList = (ExpandableListView) view.findViewById(R.id.contactList);
mContactExpandableList = (FloatingGroupExpandableListView) view.findViewById(R.id.contactList);
}
#Override
public void update(ArrayList<PHCContactDetailModel> contactsData, ArrayList<PHCContactDetailModel> favoritesData) {
this.mContactsData = contactsData;
updateWidgets();
}
}
similarly i have Favorites example as well. Mostly both will look like same, that's why not posting it here.
Sorry for posting the long question. Any help regarding this. Apologies for my poor English. Thanks in Advance.

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!

How to load mysql listview data into fragment

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

ListFragment doesn't show firebase/firebaseui items

As the title says, my ListFragment doesn't show items retrieved from firebase, here my code:
CONTAINER:
public class MainPageLogin extends AppCompatActivity {
private BottomBar mBottomBar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_page_login);
// mBottomBar = BottomBar.attach(this, savedInstanceState);
mBottomBar = BottomBar.attachShy((CoordinatorLayout) findViewById(R.id.myCoordinator),
findViewById(R.id.myScrollingContent), savedInstanceState);
mBottomBar.setFragmentItems(getSupportFragmentManager(), R.id.fragmentContainer,
new BottomBarFragment(ChatListFragment.newInstance(R.layout.chat_list_fragment,0), R.drawable.ic_action_user, "Chat"),
new BottomBarFragment(PollListFragment.newInstance(R.layout.poll_list_fragment,1), R.drawable.ic_assessment, "Sondaggi"),
new BottomBarFragment(ContactListFragment.newInstance(R.layout.contact_list_fragment,2), R.drawable.ic_contacts, "Contatti")
);
mBottomBar.setActiveTabColor("#C83F09");
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
// Necessary to restore the BottomBar's state, otherwise we would
// lose the current tab on orientation change.
mBottomBar.onSaveInstanceState(outState);
}}
CONTAINER XML
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/myCoordinator"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true">
<android.support.v4.widget.NestedScrollView
android:id="#+id/myScrollingContent"
android:layout_width="match_parent"
android:layout_height="match_parent">
<FrameLayout
android:id="#+id/fragmentContainer"
android:layout_width="match_parent"
android:layout_height="200dp"></FrameLayout>
</android.support.v4.widget.NestedScrollView>
</android.support.design.widget.CoordinatorLayout>
LISTFRAGMENT JAVA
public class ChatListFragment extends ListFragment {
ListView usr_chats;
Button btn_crea;
StringBuilder total;
TextView nochat;
RequestQueue queue;
TextView chat_item;
FirebaseListAdapter<String> Fireadapter;
View v;
public ChatListFragment(){}
public static ChatListFragment newInstance(int res, int i){
ChatListFragment f = new ChatListFragment();
Bundle args = new Bundle();
args.putInt("res", res);
args.putInt("choice",i);
f.setArguments(args);
return f;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
v = inflater.inflate(R.layout.chat_list_fragment, container, false);
nochat = (TextView) v.findViewById(R.id.no_chat);
btn_crea = (Button) v.findViewById(R.id.crea_chat);
usr_chats = (ListView) v.findViewById(android.R.id.list);
//-------------------------------
return v;
}
#Override
public void onViewCreated (View view, Bundle savedInstanceState) {
total = new StringBuilder();
total.append("");
btn_crea.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(getContext(),contacts.class);
intent.putExtra("KEY",total.toString());
startActivity(intent);
}
});
Firebase.setAndroidContext(getContext());
try {
FileInputStream inputStream = getActivity().openFileInput("usr_basekey");
BufferedReader r = new BufferedReader(new InputStreamReader(inputStream));
String line;
while ((line = r.readLine()) != null) {
total.append(line);
}
r.close();
inputStream.close();
//Log.d("VOTA",total.toString());
} catch (FileNotFoundException e) {
Log.d("VOTA", "FILE NON TROVATO:" + e.getMessage());
} catch (IOException e) {
Log.d("VOTA", "IO EXCEPTION:" + e.getMessage());
}
Firebase myFirebaseRef = new Firebase("https://fiery-fire-7347.firebaseio.com/user/"+total.toString());
myFirebaseRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot snapshot) {
String user_params = snapshot.getValue().toString();
try {
JSONObject jsonO = new JSONObject(user_params);
String user_name = jsonO.getString("name");
} catch (JSONException e) {
e.printStackTrace();
}
}
#Override
public void onCancelled(FirebaseError error) {
}
});
Firebase chats = myFirebaseRef.child("chatadded");
queue = Volley.newRequestQueue(getContext());
Log.d("VOTA","preListAdapter");
Fireadapter = new FirebaseListAdapter<String>(
getActivity(),
String.class,
R.layout.chat_user_list,
chats
) {
#Override
protected void populateView(View view, final String s, int i) {
chat_item = (TextView) view.findViewById(R.id.chat_name_for_users);
String url = "https://fiery-fire-7347.firebaseio.com/chats/"+s+"/nomeChat.json";
StringRequest stringRequest = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d("VOTA","ResponseAdapter-"+response);
chat_item.setText(response);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d("VOTA", "Volley Error: " + error);
}
});
queue.add(stringRequest);
}
};
usr_chats.setAdapter(Fireadapter);
Log.d("VOTA", "postListAdapter");
usr_chats.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent intent = new Intent(getContext(), ChatActivityHome.class);
intent.putExtra("nChat","");
intent.putExtra("myKey",total.toString());
intent.putExtra("kChat", Fireadapter.getItem(position));
startActivity(intent);
}
});
//-----------------------------
}}
LISTVIEW 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:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.gitlab.votateam.votateam.MainPage">
<ListView
android:id="#+id/android:list"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_above="#+id/crea_chat"
android:layout_alignParentTop="true" />
<TextView
android:textColor="#737373"
android:id="#+id/no_chat"
android:text=""
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignTop="#+id/android:list"
android:layout_centerHorizontal="true"
android:layout_marginTop="102dp" />
<Button
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Crea Chat"
android:id="#+id/crea_chat"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true" />
</RelativeLayout>
ITEMS XML
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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="70dp"
android:layout_height="70dp"
android:id="#+id/imageView"
android:src="#drawable/def_groupchat_profile"
/>
<TextView
android:textColor="#737373"
android:text=""
android:id="#+id/chat_name_for_users"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_toRightOf="#+id/imageView"
android:layout_toEndOf="#+id/imageView"
android:layout_marginLeft="14dp"
android:layout_marginStart="14dp"
android:layout_marginTop="12dp" />
</RelativeLayout>
I'm sure the code works, and the error should be related to XML because my log shows the correct "response" from the firebase DB.
You're firing an async request to get a string StringRequest. By the time that string comes back, Android is not expecting changes to the view anymore and it doesn't update the view.
The solution is typically to call notifyDataSetChanged():
StringRequest stringRequest = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d("VOTA","ResponseAdapter-"+response);
chat_item.setText(response);
}
}, ...

Categories

Resources