I'm trying to display an ArrayList of Integers inside of a RecyclerView, the Integer values in the ArrayList are downloaded from JSON, all that is done, the thing I need help with is to display them in a RecyclerView.
This is my code so far but the RecyclerView does not display anything.
All code updated to my current code
Here's part of the MainActivity:
public class MainActivity extends AppCompatActivity {
private ActivityMainViewModel viewmodel;
RecyclerView recyclerView;
MainAdapter mAdapter;
public static ArrayList<Integer> rideList = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//setContentView(R.layout.activity_main);
ActivityMainBinding binding = DataBindingUtil.setContentView(this, R.layout.activity_main);
viewmodel = new ActivityMainViewModel();
binding.setViewmodel(viewmodel);
recyclerView = (RecyclerView) findViewById(R.id.recycler_view);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
mAdapter = new MainAdapter(rideList);
recyclerView.setAdapter(mAdapter);
}
Here's the MainAdapter class:
class MainAdapter extends android.support.v7.widget.RecyclerView.Adapter<MainAdapter.ViewHolder> {
private ArrayList<Integer> rideList;
public MainAdapter(ArrayList<Integer> rideList)
{
this.rideList = rideList;
}
#Override
public MainAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType)
{
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.row, parent, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(MainAdapter.ViewHolder holder, int position)
{
holder.rideHeight.setText(String.valueOf(rideList.get(position)));
}
#Override
public int getItemCount()
{
return rideList.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
public TextView rideHeight;
public ViewHolder(View itemView) {
super(itemView);
rideHeight = (TextView) itemView.findViewById(R.id.rideHeight_textView);
}
}
}
row.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="wrap_content">
<TextView
android:id="#+id/rideHeight_textView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:textSize="20sp"/>
</LinearLayout>
I know that it probably looks a mess but that's because I have been searching both on google and youtube on how to use RecyclerView so I might have mixed from different tutorials and tried somethings myself.
Thanks!
Edit: JsonData code added on request:
JsonData:
public class JsonData
{
public ObservableField<String> dropHeight = new ObservableField<>();
public ObservableField<String> rideCount = new ObservableField<>();
int eID;
int sID;
public JsonData()
{
dropHeight.set("");
rideCount.set("");
}
public void downloadFromSkistar()
{
if (SettingsActivity.submitClicked)
{
eID = SettingsActivity.x;
sID = SettingsActivity.y;
}
else
{
eID = 3206;
sID = 11;
}
try
{
URL url = new URL("https://www.skistar.com/myskistar/api/v2/views/statisticspage.json?entityId=" + eID + "&seasonId=" + sID + " ");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(10000 /* milliseconds */);
conn.setConnectTimeout(15000 /* milliseconds */);
conn.setRequestMethod("GET");
// Starts the query
conn.connect();
int response = conn.getResponseCode();
Log.i("AndroidExample", "Response: " + response);
if (response == 200)
{
String json = getJson(conn.getInputStream());
JSONObject jsonObject = new JSONObject(json);
JSONArray jsonArray = jsonObject.getJSONArray("rideStatistics");
int reponame = 0;
int rHeight = 0;
for (int i = 0; i < jsonArray.length(); i++)
{
JSONObject skiRun = jsonArray.getJSONObject(i);
reponame += skiRun.getInt("height");
rHeight += skiRun.getInt("height");
MainActivity.rideList.add(new Integer(rHeight));
rHeight = 0;
}
final int height = reponame;
final int count = jsonArray.length();
new Handler(Looper.getMainLooper()).post(new Runnable() {
#Override
public void run() {
dropHeight.set("" + height);
rideCount.set("" + count);
}
});
}
}
catch (Exception e)
{
Log.i("AndroidExample", "Error");
}
finally
{
}
}
private String getJson(InputStream stream) throws IOException
{
BufferedReader reader;
reader = new BufferedReader(new InputStreamReader(stream, "UTF-8"));
StringBuilder builder = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
builder.append(line + '\n');
}
//Should be placed in finally
stream.close();
return builder.toString();
}
}
You can use like..
Model..to set value and get value
public class CustomModel {
private int it;
public int getIt() {
return it;
}
public void setIt(int it) {
this.it = it;
}
}
Adapter ...
private class MainAdapter extends RecyclerView.Adapter<MainAdapter.ViewHolder>{
public MainAdapter(ArrayList<CustomModel> list){
dataSet = list;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {
View itemLayoutView = LayoutInflater.from(viewGroup.getContext()).inflate(
R.layout.row, null);
itemLayoutView.setLayoutParams(new RecyclerView.LayoutParams(RecyclerView.LayoutParams.MATCH_PARENT, RecyclerView.LayoutParams.WRAP_CONTENT));
MainAdapter.ViewHolder viewHolder = new MainAdapter.ViewHolder(itemLayoutView);
return viewHolder;
}
#Override
public void onBindViewHolder(ViewHolder viewHolder, int position) {
CustomModel cardModel = dataSet.get(position);
viewHolder.rideHeight_textView.setText(String.valueOf(cardModel.getId()));
}
#Override
public int getItemCount() {
return dataSet.size();
}
public void updateList(List<CustomModel> temp) {
dataSet = (ArrayList<CustomModel>) temp;
notifyDataSetChanged();
}
public class ViewHolder extends RecyclerView.ViewHolder {
public TextView rideHeight_textView;
public ViewHolder(View itemLayoutView) {
super(itemLayoutView);
rideHeight_textView = (TextView) itemLayoutView .findViewById(R.id.rideHeight_textView);
itemLayoutView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//action ****
}
});
}
}
}
Just call like
ArrayList<CustomModel> menuList = new ArrayList<>();
CustomModel c = new CustomModel();
c.setIt(1);
recyclerView.setHasFixedSize(true);
// ListView
recyclerView.setLayoutManager(new LinearLayoutManager(Your activity.this));
// create an Object for Adapter
MainAdapter mAdapter = new MainAdapter(menuList);
// set the adapter object to the Recyclerview
recyclerView.setAdapter(mAdapter);
row.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:background="#ffffff"
android:padding="#dimen/activity_vertical_margin"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:id="#+id/rideHeight_textView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textColor="#000000"
android:textSize="20sp"/>
</LinearLayout>
recyclerView = (RecyclerView) findViewById(R.id.recycler_view);
recyclerView.setHasFixedSize(true);
LinearLayoutManager layoutManager = new LinearLayoutManager(context);
layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
recyclerView.setLayoutManager(layoutManager);
mAdapter = new MainAdapter(JsonData.rideList, MainActivity.this);
recyclerView.setAdapter(mAdapter);
mAdapter.notifyDataSetChanged();
adapter:
class MainAdapter extends android.support.v7.widget.RecyclerView.Adapter<MainAdapter.ViewHolder> {
private ArrayList<Integer> rideList = new ArrayList<>();
private Context context;
public MainAdapter(ArrayList<Integer> rideList, Context context)
{
this.context = context;
this.rideList = rideList;
}
#Override
public MainAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType)
{
View view = LayoutInflater.from(context).inflate(R.layout.row, parent, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(MainAdapter.ViewHolder holder, int position)
{
holder.rideHeight.setText(String.valueOf(rideList.get(position)));
}
#Override
public int getItemCount()
{
return rideList.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
public TextView rideHeight;
public ViewHolder(View itemView) {
super(itemView);
rideHeight = (TextView) itemView.findViewById(R.id.rideHeight_textView);
}
}
}
row.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:background="#ffffff"
android:padding="#dimen/activity_vertical_margin"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:id="#+id/rideHeight_textView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textColor="#000000"
android:textSize="20sp"/>
</LinearLayout>
For starters you are not calling your data fetcher method in JsonData class. Your code is kind of messy so you can try the following solution:
In your adapter class add this method:
public void setList(ArrayList<Integer> rideList)
{
this.rideList = rideList;
notifyDataSetChanged();
}
Then in you JsonData class add:
private MainAdapter adapter;
public JsonData(MainAdapter adapter)
{
this.adapter = adapter;
dropHeight.set("");
rideCount.set("");
}
And change downloadFromSkistar to:
public void downloadFromSkistar()
{
if (SettingsActivity.submitClicked)
{
eID = SettingsActivity.x;
sID = SettingsActivity.y;
}
else
{
eID = 3206;
sID = 11;
}
new AsyncTask<Void, Void, List<Integer>>() {
#Override
protected List<Integer> doInBackground(Void... voids) {
try
{
URL url = new
URL("https://www.skistar.com/myskistar/api/v2/views/statisticspage.json?
entityId=" + eID + "&seasonId=" + sID + " ");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(10000 /* milliseconds */);
conn.setConnectTimeout(15000 /* milliseconds */);
conn.setRequestMethod("GET");
// Starts the query
conn.connect();
int response = conn.getResponseCode();
Log.i("AndroidExample", "Response: " + response);
if (response == 200)
{
String json = getJson(conn.getInputStream());
JSONObject jsonObject = new JSONObject(json);
JSONArray jsonArray = jsonObject.getJSONArray("rideStatistics");
int reponame = 0;
int rHeight = 0;
for (int i = 0; i < jsonArray.length(); i++)
{
JSONObject skiRun = jsonArray.getJSONObject(i);
reponame += skiRun.getInt("height");
rHeight += skiRun.getInt("height");
rideList.add(new Integer(rHeight));
rHeight = 0;
}
}
}
catch (Exception e)
{
Log.i("AndroidExample", "Error");
}
finally
{
}
return rideList;
}
#Override
protected void onPostExecute(List<Integer> list)
{
super.onPostExecute(list);
adapter.setList(rideList);
}
};
}
And in the end finally change MainActivity to:
public class MainActivity extends AppCompatActivity {
private ActivityMainViewModel viewmodel;
RecyclerView recyclerView;
MainAdapter mAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//setContentView(R.layout.activity_main);
ActivityMainBinding binding = DataBindingUtil.setContentView(this, R.layout.activity_main);
viewmodel = new ActivityMainViewModel();
binding.setViewmodel(viewmodel);
recyclerView = (RecyclerView) findViewById(R.id.recycler_view);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
mAdapter = new MainAdapter(JsonData.rideList);
recyclerView.setAdapter(mAdapter);
new JsonData(mAdapter).downloadFromSkistar();
}
PS: You are going to get NetworkOnMainThread exception. So try to add the network code in AsyncTask
Here's what I did to solve it, and btw I'm also using the SwipeRefreshLayout.
public class MainActivity extends AppCompatActivity {
private ActivityMainViewModel viewmodel;
RecyclerView recyclerView;
MainAdapter mAdapter;
public static ArrayList<Integer> rideList = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//setContentView(R.layout.activity_main);
ActivityMainBinding binding = DataBindingUtil.setContentView(this, R.layout.activity_main);
viewmodel = new ActivityMainViewModel();
binding.setViewmodel(viewmodel);
recyclerView = (RecyclerView) findViewById(R.id.recycler_view);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
mAdapter = new MainAdapter(rideList);
recyclerView.setAdapter(mAdapter);
viewmodel.jdDownloadFromSkistar();
final SwipeRefreshLayout swipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.swipelayout);;
swipeRefreshLayout.setColorSchemeResources(R.color.refresh,R.color.refresh1,R.color.refresh2);
swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
swipeRefreshLayout.setRefreshing(true);
refreshRecyclerView();
swipeRefreshLayout.setRefreshing(false);
}
});
}
private void refreshRecyclerView()
{
mAdapter.notifyDataSetChanged();
}
So what I did was make a call to the jdDownloadFromSkistar(); Method and when I swipe to refresh it updates the adapter by using the notifyDataSetChanged(); method.
Related
I have a problem, when i swipe to refresh the data, the first swipe is ok but after that every swipe reload and add the same data over and over again, by the end i have a list with same items over and over... I'm using a loader. I tried to clear before but i don't understand what's wrong with my code, if someone could explain it to me. Thank You.
Here my code :
public static final String EXTRA_URL = "imageUrl";
public static final String EXTRA_APKNAME = "apkname";
public static final String EXTRA_APKSIZE = "apksize";
public static final String EXTRA_APKFILE = "apkfile";
private RecyclerView mRecyclerView;
private MyAdapter mExampleAdapter;
private ArrayList<one_item> mExampleList;
private RequestQueue mRequestQueue;
private SwipeRefreshLayout swipeRefreshLayout;
#SuppressLint("RestrictedApi")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getSupportActionBar().setTitle("APK VIP CHINA");
getSupportActionBar().setDefaultDisplayHomeAsUpEnabled(true);
swipeRefreshLayout = findViewById(R.id.refreshlayout);
mRecyclerView = findViewById(R.id.recycler_view);
mRecyclerView.setHasFixedSize(true);
mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
mExampleList = new ArrayList<>();
mRequestQueue = Volley.newRequestQueue(this);
parseJSON();
swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
parseJSON();
swipeRefreshLayout.setRefreshing(false);
}
});
}
private void parseJSON() {
String url = "http://apkvip.net/json2.php";
JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONArray jsonArray = response.getJSONArray("data");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject hit = jsonArray.getJSONObject(i);
String creatorName = hit.getString("ten");
String creatorsize = hit.getString("apk_size");
String creatorfile = hit.getString("link_apk");
String imageUrl = hit.getString("link_img");
mExampleList.add(new one_item(imageUrl, creatorName, creatorsize, creatorfile));
}
mExampleAdapter = new MyAdapter(MainActivity.this, mExampleList);
mRecyclerView.setAdapter(mExampleAdapter);
mExampleAdapter.setOnItemClickListener(MainActivity.this);
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
});
mRequestQueue.add(request);
}
public void onItemClick(int position) {
Intent detailIntent = new Intent(this, activity_detail.class);
one_item clickedItem = mExampleList.get(position);
detailIntent.putExtra(EXTRA_URL, clickedItem.getmImageUrl());
detailIntent.putExtra(EXTRA_APKNAME, clickedItem.getMapkname());
detailIntent.putExtra(EXTRA_APKSIZE, clickedItem.getMapksize());
detailIntent.putExtra(EXTRA_APKFILE, clickedItem.getMapkfile());
startActivity(detailIntent);
}}
My adapter:
private ArrayList<one_item> mExampleList;
private OnItemClickListener mListener;
public interface OnItemClickListener {
void onItemClick(int position);
}
public void setOnItemClickListener(OnItemClickListener listener) {
mListener = listener;
}
public MyAdapter(Context context, ArrayList<one_item> exampleList) {
mContext = context;
mExampleList = exampleList;
}
#Override
public ExampleViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(mContext).inflate(R.layout.one_item, parent, false);
return new ExampleViewHolder(v);
}
#Override
public void onBindViewHolder(ExampleViewHolder holder, int position) {
one_item currentItem = mExampleList.get(position);
String imageUrl = currentItem.getmImageUrl();
String apkname = currentItem.getMapkname();
String apksize = currentItem.getMapksize();
String apkfile = currentItem.getMapkfile();
holder.mTextViewname.setText(apkname);
holder.mTextViewsize.setText(apksize);
holder.mTextViewfile.setText(apkfile);
Picasso.get().load(imageUrl).fit().centerInside().into(holder.mImageView);
}
#Override
public int getItemCount() {
return mExampleList.size();
}
#Override
public long getItemId(int position) {
return position;
}
public class ExampleViewHolder extends RecyclerView.ViewHolder {
public ImageView mImageView;
public TextView mTextViewname, mTextViewsize, mTextViewfile;
public ExampleViewHolder(View itemView) {
super(itemView);
mImageView = itemView.findViewById(R.id.image);
mTextViewname = itemView.findViewById(R.id.name);
mTextViewsize = itemView.findViewById(R.id.size);
mTextViewfile = itemView.findViewById(R.id.file);
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mListener != null) {
int position = getAdapterPosition();
if (position != RecyclerView.NO_POSITION) {
mListener.onItemClick(position);
}
}
}
});}}}
my activitymain.xml:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_height="match_parent"
tools:context=".MainActivity"
android:background="#FFFFFF"
android:orientation="vertical"
android:padding="5dp">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Recommended Apps"
android:textColor="#000"
android:textStyle="bold"
android:textSize="20sp"
android:layout_marginBottom="10dp"
/>
<androidx.swiperefreshlayout.widget.SwipeRefreshLayout
android:id="#+id/refreshlayout"
android:layout_width="wrap_content"
android:layout_height="match_parent"
>
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/recycler_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scrollbars="vertical"
android:padding="5dp" />
</androidx.swiperefreshlayout.widget.SwipeRefreshLayout>
Just use mExampleList.clear() at the first line of your parseJSON() function
and then you'll be able to add the "updated" items.
In addition I'd suggest that you move swipeRefreshLayout.setRefreshing(false) to the end of Volley onResponse and onError() implementation -
Right now you're telling the swipeRefreshLayout to stop refreshing before the request(that happens asynchronously) has finished
You are initializing your adapter every time you do a swipe.
Change this constructor of MyAdapter code.
public MyAdapter(Context context, ArrayList<one_item> exampleList) {
mContext = context;
mExampleList = exampleList;
}
to,
public MyAdapter(Context context) {
mContext = context;
}
public setExampleList(ArrayList<one_item> exampleList){
mExampleList = exampleList;
}
Now change your onCreate function to.
#SuppressLint("RestrictedApi")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getSupportActionBar().setTitle("APK VIP CHINA");
getSupportActionBar().setDefaultDisplayHomeAsUpEnabled(true);
swipeRefreshLayout = findViewById(R.id.refreshlayout);
mRecyclerView = findViewById(R.id.recycler_view);
mRecyclerView.setHasFixedSize(true);
mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
mExampleList = new ArrayList<>();
mRequestQueue = Volley.newRequestQueue(this);
//Changed Code
mExampleAdapter = new MyAdapter(MainActivity.this);
mRecyclerView.setAdapter(mExampleAdapter);
mExampleAdapter.setOnItemClickListener(MainActivity.this);
parseJSON();
swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
parseJSON();
swipeRefreshLayout.setRefreshing(false);
}
});
}
private void parseJSON() {
String url = "http://apkvip.net/json2.php";
JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONArray jsonArray = response.getJSONArray("data");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject hit = jsonArray.getJSONObject(i);
String creatorName = hit.getString("ten");
String creatorsize = hit.getString("apk_size");
String creatorfile = hit.getString("link_apk");
String imageUrl = hit.getString("link_img");
mExampleList.add(new one_item(imageUrl, creatorName, creatorsize, creatorfile));
}
//Changed Code
mExampleAdapter.setExampleList(mExampleList);
mExampleAdapter.notifyDataSetChanged();
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
});
mRequestQueue.add(request);
}
I have added a comment of the code block where I have made the changes.
Feel free to comment in case you have any queries.
same data appear in whole Recyclerview and position increasing but data same appear
in useradapter i log the position and position increase but data is same in onbindviewholder
useradapter
public class useradapter extends RecyclerView.Adapter<useradapter.CustomView> {
String nn = "m";
List<allusermodel> list1;
private Context context;
private LayoutInflater layoutInflater;
public useradapter(Context context, List<allusermodel> list1) {
Log.e("reached1", nn);
this.context = context;
this.list1 = list1;
}
#Override
public useradapter.CustomView onCreateViewHolder(final ViewGroup parent, final int viewType) {
Log.e("reached2", nn);
if (layoutInflater == null) {
layoutInflater = LayoutInflater.from(parent.getContext());
}
final Entrys newsBinding = Entrys.inflate(layoutInflater, parent, false);
// View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.innerlayout,parent,false);
return new CustomView(newsBinding);
}
#Override
public void onBindViewHolder(useradapter.CustomView holder,int position) {
Log.e("reached3", nn);
// News news = newsList.get(position);
// holder.desc.setText(news.getDesc());
allusermodel newsModel1 = list1.get(position);
// Log.e("list", String.valueOf(list1));
Log.e("nameeeee",newsModel1.getAll_user());
// Log.e("position", String.valueOf(position));
//Log.e("names",newsModel1.getAll_user());
holder.bind(newsModel1);
}
#Override
public int getItemCount() {
return list1.size();
}
public class CustomView extends RecyclerView.ViewHolder {
private Entrys newsBinding;
// public TextView title;
//TextView title, desc;
public CustomView(Entrys newsBinding) {
super(newsBinding.getRoot());
this.newsBinding = newsBinding;
Log.e("reached4", nn);
// title = (TextView)itemView.findViewById(R.id.titleval);
//desc =(TextView)itemView.findViewById(R.id.descval);
newsBinding.setRecyclerclick(new Presenters2() {
#Override
public void onclickListener() {
int pos = getAdapterPosition();
if (pos != RecyclerView.NO_POSITION) {
allusermodel clickedDataItem = list1.get(pos);
Intent intent = new Intent(context, messagelist.class);
intent.putExtra("clickid", clickedDataItem.getId());
context.startActivity(intent);
}
}
});
}
public void bind(allusermodel newsModel1)
{
Log.e("reached5", String.valueOf(newsModel1));
//String j = newsModel1.getAll_user();
// Log.e("bind",nn);
this.newsBinding.setAlluserentry(newsModel1);
}
public Entrys getNewsBinding() {
Log.e("reached6", nn);
return newsBinding;
}
}
}
userlist
public class userlist extends AppCompatActivity {
private static final String TAG = "userlist";
private RecyclerView recyclerView;
private LinearLayoutManager linearLayoutManager;
private DividerItemDecoration dividerItemDecoration;
private useradapter customAdapter;
private DataManager2 dataManger;
private List<allusermodel> newsList;
private RecyclerView.Adapter adapter;
String token2;
String URL1 = "https://chat.promactinfo.com/api/user";
private int userid;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_userlist);
SharedPreferences pref = getSharedPreferences("MyPrefs", Context.MODE_PRIVATE);
token2 = pref.getString("sherdtoken", "");
Log.e("token", token2);
dataManger = new DataManager2(this);
recyclerView = (RecyclerView) findViewById(R.id.recycle);
/*recyclerView.setLayoutManager(new LinearLayoutManager(this));
newsList = new ArrayList<>();
customAdapter = new useradapter(this, newsList);
recyclerView.setAdapter(customAdapter);*/
newsList = new ArrayList<>();
getdata();
}
public void getdata() {
dataManger.sendVolleyRequest1(token2, userlist.this, new DataValue() {
#Override
public void setJsonDataResponse1(JSONArray response) {
allusermodel userModel = new allusermodel();
// newsList = new ArrayList<>();
for (int i = 0; i < response.length(); i++) {
try {
JSONObject jsonObject = response.getJSONObject(i);
// Log.e("final", String.valueOf(i));
// userid = jsonObject.getInt("id");
userModel.setId(jsonObject.getInt("id"));
// Log.e("getid", String.valueOf(jsonObject.getInt("id")));
userModel.setAll_user(jsonObject.getString("name"));
// Log.e("getname", String.valueOf(jsonObject.getString("name")));
newsList.add(userModel);
// Log.e("userlist", String.valueOf(newsList));
} catch (JSONException jsonDataResponse) {
Log.e("error", String.valueOf(jsonDataResponse));
}
}
adapter = new useradapter(getApplicationContext(),newsList);
linearLayoutManager = new LinearLayoutManager(getApplicationContext());
linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
dividerItemDecoration = new DividerItemDecoration(recyclerView.getContext(), linearLayoutManager.getOrientation());
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(linearLayoutManager);
recyclerView.addItemDecoration(dividerItemDecoration);
recyclerView.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
#Override
public void setVolleyError1(VolleyError volleyError) {
Log.e("Volley", volleyError.toString());
}
});
}
}
allusermodel
public class allusermodel extends BaseObservable {
public int id;
public String all_user;
public allusermodel() {
}
public allusermodel(int id,String name ) {
this.id = id;
this.all_user = name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getAll_user() {
return all_user;
}
public void setAll_user(String all_user) {
this.all_user = all_user;
}
#Override
public String toString() {
return "allusermodel{" +
"id=" + id +
", all_user='" + all_user + '\'' +
'}';
}
}
userlist.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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"
tools:context="com.example.mayurpancholi.chat_mvvm.userlist"
android:orientation="vertical">
<android.support.v7.widget.RecyclerView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/recycle"
android:scrollbars="vertical">
</android.support.v7.widget.RecyclerView>
innerlayout.xml
<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android">
<data class ="Entrys">
<variable
name="alluserentry"
type="com.example.mayurpancholi.chat_mvvm.viewmodel.allusermodel"/>
<variable
name="recyclerclick"
type="com.example.mayurpancholi.chat_mvvm.interfaces.Presenters2"/>
</data>
<LinearLayout
android:layout_width="match_parent"
android:layout_marginTop="10dp"
android:padding="10dp"
android:onClick="#{()->recyclerclick.onclickListener()}"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/titleval"
android:textSize="20dp"
android:text="#{alluserentry.all_user}"
android:textStyle="bold"
android:layout_marginTop="10dp"
/>
</LinearLayout>
</layout>
whole recyclerview have same data which i previous add in api
(if i enter name in entry then it show previous entry in whole recylerview
ane then if i enter name1 in entry then it show name in whole recylerview )
It seems, the issue is coming because you have created the Model object outside the for loop when you are populating the data from sever. As a result the last value in the list will show to all the RecyclerView items.
Now the solution is that you create the model inside the "for-loop" as a first statement.
public void getdata() {
dataManger.sendVolleyRequest1(token2, userlist.this, new DataValue() {
#Override
public void setJsonDataResponse1(JSONArray response) {
//allusermodel userModel = new allusermodel();
// newsList = new ArrayList<>();
for (int i = 0; i < response.length(); i++) {
allusermodel userModel = new allusermodel();
try {
JSONObject jsonObject = response.getJSONObject(i);
I hope it will resolve your issue.
I have a recyclerview and set text some textview in it. when I scroll down or my fragment goes to onPause state my data loss.
what can i do?
import static com.test.mohammaddvi.snappfood.Adapter.SectionListDataAdapter.decodeSampledBitmapFromResource;
public class RecyclerViewMenuFragmentAdapter extends RecyclerView.Adapter<RecyclerViewMenuFragmentAdapter.SingleItemInMenuFragment> {
private ArrayList<Food> foodList;
private Context mContext;
public RecyclerViewMenuFragmentAdapter(ArrayList<Food> foodList, Context mContext) {
this.foodList = foodList;
this.mContext = mContext;
}
#NonNull
#Override
public RecyclerViewMenuFragmentAdapter.SingleItemInMenuFragment onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.foodlist, null);
return new RecyclerViewMenuFragmentAdapter.SingleItemInMenuFragment(v);
}
#Override
public void onBindViewHolder(final RecyclerViewMenuFragmentAdapter.SingleItemInMenuFragment holder, int position) {
Food food = foodList.get(position);
holder.foodName.setText(food.getName());
holder.foodDetails.setText(food.getDetails());
holder.foodPrice.setText(food.getPrice() + " تومان ");
holder.foodOrderNumber.setVisibility(View.INVISIBLE);
holder.foodMinusButton.setVisibility(View.INVISIBLE);
holder.foodOrderNumber.setText(0 + "");
holder.foodImage.setImageBitmap(decodeSampledBitmapFromResource(mContext.getResources(), mContext.getResources().getIdentifier(food.getImage(),
"drawable", mContext.getPackageName()), 50, 50));
handleClick(holder, position);
}
private void handleClick(final SingleItemInMenuFragment holder, final int position) {
holder.foodPlusButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int orderNumber = Integer.parseInt(holder.foodOrderNumber.getText().toString());
holder.foodOrderNumber.setText(orderNumber + 1 + "");
holder.foodOrderNumber.setVisibility(View.VISIBLE);
holder.foodMinusButton.setVisibility(View.VISIBLE);
}
});
holder.foodMinusButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int orderNumber = Integer.parseInt(holder.foodOrderNumber.getText().toString());
if (orderNumber > 1) {
holder.foodOrderNumber.setText(orderNumber - 1 + "");
holder.foodOrderNumber.setVisibility(View.VISIBLE);
}
if (orderNumber == 1) {
holder.foodOrderNumber.setText(orderNumber - 1 + "");
holder.foodOrderNumber.setVisibility(View.INVISIBLE);
holder.foodMinusButton.setVisibility(View.INVISIBLE);
}
}
});
}
#Override
public int getItemCount() {
return (null != foodList ? foodList.size() : 0);
}
public class SingleItemInMenuFragment extends RecyclerView.ViewHolder {
TextView foodName;
TextView foodPrice;
Button foodPlusButton;
Button foodMinusButton;
TextView foodOrderNumber;
ImageView foodImage;
TextView foodDetails;
SingleItemInMenuFragment(View itemView) {
super(itemView);
this.foodName = itemView.findViewById(R.id.foodName);
this.foodImage = itemView.findViewById(R.id.imageFood);
this.foodPrice = itemView.findViewById(R.id.foodPrice);
this.foodDetails = itemView.findViewById(R.id.foodDetails);
this.foodPlusButton = itemView.findViewById(R.id.plusbutton);
this.foodMinusButton = itemView.findViewById(R.id.minusbutton);
this.foodOrderNumber = itemView.findViewById(R.id.ordernumber);
}
}
}
and this is my fragment that i use recyclerview in that:
public class MenuFragment extends Fragment{
private static final String TAG = "menufragment";
ArrayList<Food> allfoods = new ArrayList<>();
RecyclerView recyclerview;
private static Bundle bundle;
private final String KEY_RECYCLER_STATE= "recycler_state";
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.menufragment, container, false);
}
#Override
public void onStart() {
super.onStart();
String jsonFilePath = "foods.json";
recyclerview = getActivity().findViewById(R.id.lstitems);
RecyclerViewMenuFragmentAdapter adapter = new RecyclerViewMenuFragmentAdapter(allfoods, getContext());
recyclerview.setLayoutManager(new LinearLayoutManager(getContext(), LinearLayoutManager.VERTICAL, false));
recyclerview.setHasFixedSize(true);
recyclerview.setAdapter(adapter);
parsJson(jsonFilePath);
}
//this method is for read a local json and return a string
public String readLocalJson(String jsonFile) {
String json;
try {
InputStream is = getActivity().getAssets().open(jsonFile);
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
json = new String(buffer, "UTF-8");
} catch (IOException e) {
e.printStackTrace();
return null;
}
return json;
}
public void parsJson(String jsonFilePath) {
try {
JSONObject obj = new JSONObject(readLocalJson(jsonFilePath));
JSONArray jsonArray = obj.getJSONArray("results");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
String image = jsonObject.getString("image");
JSONArray jsonArrayFoot = jsonObject.getJSONArray("foots");
for (int j = 0; j < jsonArrayFoot.length(); j++) {
JSONObject jsonObjectFoot = jsonArrayFoot.getJSONObject(j);
String foodName = jsonObjectFoot.getString("name");
String fooddetails = jsonObjectFoot.getString("fooddetails");
String price = jsonObjectFoot.getString("price");
allfoods.add(new Food(foodName, price, fooddetails, image));
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
Basically, you just initialized the data on onStart which will eventually called when your activity/fragment is resumed, and because of that all data you've changed was overwritten to initial data.
Move your onStart initialization to onViewCreated:
#Override
public void onViewCreated() {
super.onViewCreated();
String jsonFilePath = "foods.json";
recyclerview = getActivity().findViewById(R.id.lstitems);
RecyclerViewMenuFragmentAdapter adapter = new RecyclerViewMenuFragmentAdapter(allfoods, getContext());
recyclerview.setLayoutManager(new LinearLayoutManager(getContext(), LinearLayoutManager.VERTICAL, false));
recyclerview.setHasFixedSize(true);
recyclerview.setAdapter(adapter);
parsJson(jsonFilePath);
}
And for scrolling, its normal because RecyclerView recycles the view from the list above but the data is not, so what you need to do is store values from the list source.
#Override
public void onBindViewHolder(final RecyclerViewMenuFragmentAdapter.SingleItemInMenuFragment holder, int position) {
Food food = foodList.get(position);
holder.foodName.setText(food.getName());
holder.foodDetails.setText(food.getDetails());
holder.foodPrice.setText(food.getPrice() + " تومان ");
holder.foodOrderNumber.setVisibility(View.INVISIBLE);
holder.foodMinusButton.setVisibility(View.INVISIBLE);
holder.foodOrderNumber.setText(food.getFoodOrderNumber());
holder.foodImage.setImageBitmap(decodeSampledBitmapFromResource(mContext.getResources(), mContext.getResources().getIdentifier(food.getImage(),
"drawable", mContext.getPackageName()), 50, 50));
handleClick(holder, position);
}
private void handleClick(final SingleItemInMenuFragment holder, final int position) {
holder.foodPlusButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int orderNumber = Integer.parseInt(holder.foodOrderNumber.getText().toString());
int newOrderNumber = orderNumber + 1;
Food food = foodList.get(position);
food.setFoodOrderNumber(newOrderNumber);
holder.foodOrderNumber.setText(newOrderNumber + "");
holder.foodOrderNumber.setVisibility(View.VISIBLE);
holder.foodMinusButton.setVisibility(View.VISIBLE);
}
});
holder.foodMinusButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Food food = foodList.get(position);
int orderNumber = food.getFoodOrderNumber();
if (orderNumber > 1) {
int newOrderNumber = orderNumber - 1;
food.setFoodOrderNumber(newOrderNumber);
holder.foodOrderNumber.setText(newOrderNumber + "");
holder.foodOrderNumber.setVisibility(View.VISIBLE);
}
if (orderNumber == 1) {
int newOrderNumber = orderNumber - 1;
food.setFoodOrderNumber(newOrderNumber);
holder.foodOrderNumber.setText(newOrderNumber + "");
holder.foodOrderNumber.setVisibility(View.INVISIBLE);
holder.foodMinusButton.setVisibility(View.INVISIBLE);
}
}
});
}
And on your Food object just add this field and functions:
public class Food {
int foodOrderNumber;
public int getFoodOrderNumber() {
return foodOrderNumber;
}
public void setFoodOrderNumber(int foodOrderNumber) {
this.foodOrderNumber = foodOrderNumber;
}
}
add this line to your onBindViewHolder method and check again if the problem still exits:
holder.setIsRecyclable(false);
i am trying to implement two recyclerview in one layout with same adapter. but only one recyclerview is showing.
MainActivity.java
public class MainActivity extends AppCompatActivity {
List<DataAdapter> ListOfdataAdapter;
String HTTP_JSON_URL = "http://example.com";
String Image_Name_JSON = "Menu_name";
String Image_URL_JSON = "Menu_image";
JsonArrayRequest RequestOfJSonArray ;
RequestQueue requestQueue ;
View view ;
int RecyclerViewItemPosition ;
RecyclerView.LayoutManager layoutManagerOfrecyclerView;
RecyclerView.Adapter recyclerViewadapter;
ArrayList<String> ImageTitleNameArrayListForClick;
long Category_ID;
String MenuAPI;
private RecyclerView secondRecyclerView;
private RecyclerView.LayoutManager secondLayoutManager;
private RecyclerView firstrecyclerView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ImageTitleNameArrayListForClick = new ArrayList<>();
// menu API url
Intent iGet = getIntent();
Category_ID = iGet.getLongExtra("category_id",0);
MenuAPI += Category_ID;
ListOfdataAdapter = new ArrayList<>();
firstrecyclerView = (RecyclerView) findViewById(R.id.recyclerview1);
firstrecyclerView.setHasFixedSize(true);
layoutManagerOfrecyclerView = new LinearLayoutManager(MainActivity.this, LinearLayoutManager.HORIZONTAL, true);
firstrecyclerView.setLayoutManager(layoutManagerOfrecyclerView);
firstrecyclerView.post(new Runnable() {
#Override
public void run() {
JSON_HTTP_CALL();// a method which requests remote data
}
});
secondRecyclerView = (RecyclerView) findViewById(R.id.recyclerview2);
secondRecyclerView.setHasFixedSize(true);
secondLayoutManager = new LinearLayoutManager(MainActivity.this, LinearLayoutManager.VERTICAL, true);
secondRecyclerView.setLayoutManager(secondLayoutManager);
secondRecyclerView.post(new Runnable() {
#Override
public void run() {
JSON_HTTP_CALL2();// a method which requests remote data
}
});
// Implementing Click Listener on RecyclerView.
}
public void JSON_HTTP_CALL(){
RequestOfJSonArray = new JsonArrayRequest(HTTP_JSON_URL + "/api/example.php" +"&category_id=2",
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
ParseJSonResponse(response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
requestQueue = Volley.newRequestQueue(MainActivity.this);
requestQueue.add(RequestOfJSonArray);
}
public void ParseJSonResponse(JSONArray array){
for(int i = 0; i<array.length(); i++) {
DataAdapter GetDataAdapter2 = new DataAdapter();
JSONObject json = null;
try {
json = array.getJSONObject(i);
GetDataAdapter2.setImageTitle2(json.getString(Image_Name_JSON));
// Adding image title name in array to display on RecyclerView click event.
ImageTitleNameArrayListForClick.add(json.getString(Image_Name_JSON));
GetDataAdapter2.setImageUrl2(HTTP_JSON_URL + "/" + json.getString(Image_URL_JSON));
} catch (JSONException e) {
e.printStackTrace();
}
ListOfdataAdapter.add(GetDataAdapter2);
}
recyclerViewadapter = new RecyclerViewAdapter(ListOfdataAdapter, getApplicationContext());
firstrecyclerView.setAdapter(recyclerViewadapter);
}
public void JSON_HTTP_CALL2(){
RequestOfJSonArray = new JsonArrayRequest(HTTP_JSON_URL + "/api/example.php" +"&category_id=2",
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
ParseJSonResponse2(response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
requestQueue = Volley.newRequestQueue(MainActivity.this);
requestQueue.add(RequestOfJSonArray);
}
public void ParseJSonResponse2(JSONArray array){
for(int i = 0; i<array.length(); i++) {
DataAdapter GetDataAdapter2 = new DataAdapter();
JSONObject json = null;
try {
json = array.getJSONObject(i);
GetDataAdapter2.setImageTitle2(json.getString(Image_Name_JSON));
// Adding image title name in array to display on RecyclerView click event.
ImageTitleNameArrayListForClick.add(json.getString(Image_Name_JSON));
GetDataAdapter2.setImageUrl2(HTTP_JSON_URL + "/" + json.getString(Image_URL_JSON));
} catch (JSONException e) {
e.printStackTrace();
}
ListOfdataAdapter.add(GetDataAdapter2);
}
recyclerViewadapter = new RecyclerViewAdapter(ListOfdataAdapter, getApplicationContext());
secondRecyclerView.setAdapter(recyclerViewadapter);
}
}
Adapter class
public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.ViewHolder> {
Context context;
List<DataAdapter> dataAdapters;
ImageLoader imageLoader;
private Activity activity;
private static final int CITY_TYPE = 0;
JsonArrayRequest RequestOfJSonArray;
private static final int EVENT_TYPE = 1;
public RecyclerViewAdapter(Activity act) {
this.activity = act;
}
public RecyclerViewAdapter(List<DataAdapter> getDataAdapter, Context context){
super();
this.dataAdapters = getDataAdapter;
this.context = context;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view;
switch (viewType) {
case CITY_TYPE:
view = LayoutInflater.from(parent.getContext()).inflate(R.layout.cardview, parent, false);
return new ViewHolder(view);
case EVENT_TYPE:
view = LayoutInflater.from(parent.getContext()).inflate(R.layout.card2, parent, false);
return new ViewHolder(view);
}
return null;
}
#Override
public void onBindViewHolder(ViewHolder Viewholder, int position) {
DataAdapter dataAdapterOBJ = dataAdapters.get(position);
imageLoader = ImageAdapter.getInstance(context).getImageLoader();
if (dataAdapterOBJ != null) {
switch (dataAdapterOBJ.getType()) {
case CITY_TYPE:
imageLoader.get(dataAdapterOBJ.getImageUrl2(),
ImageLoader.getImageListener(
Viewholder.VollyImageView,//Server Image
R.mipmap.ic_launcher,//Before loading server image the default showing image.
android.R.drawable.ic_dialog_alert //Error image if requested image dose not found on server.
)
);
Viewholder.VollyImageView.setImageUrl(dataAdapterOBJ.getImageUrl2(), imageLoader);
Viewholder.ImageTitleTextView.setText(dataAdapterOBJ.getImageTitle2());
break;
case EVENT_TYPE:
imageLoader.get(dataAdapterOBJ.getImageUrl2(),
ImageLoader.getImageListener(
Viewholder.VollyImageView,//Server Image
R.mipmap.ic_launcher,//Before loading server image the default showing image.
android.R.drawable.ic_dialog_alert //Error image if requested image dose not found on server.
)
);
Viewholder.VollyImageView.setImageUrl(dataAdapterOBJ.getImageUrl2(), imageLoader);
Viewholder.ImageTitleTextView.setText(dataAdapterOBJ.getImageTitle2());
break;
}
}
}
#Override
public int getItemCount() {
return dataAdapters.size();
}
class ViewHolder extends RecyclerView.ViewHolder{
public TextView ImageTitleTextView;
public NetworkImageView VollyImageView ;
public ViewHolder(View itemView) {
super(itemView);
ImageTitleTextView = (TextView) itemView.findViewById(R.id.MenuNameTV) ;
VollyImageView = (NetworkImageView) itemView.findViewById(R.id.VolleyImageView) ;
}
}
}
main activity xml
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="10dp"
android:text="Most Watched"/>
<!-- A RecyclerView to display horizontal list -->
<android.support.v7.widget.RecyclerView
android:id="#+id/recyclerview1"
android:scrollbars="none"
android:layout_width="fill_parent"
android:layout_height="240dp"
android:paddingLeft="0dp"
android:paddingRight="15dp"
android:paddingTop="15dp"
android:paddingBottom="25dp"
android:background="#ffc000"/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="10dp"
android:text="All Dramas"/>
<!-- A RecyclerView to display vertical list -->
<android.support.v7.widget.RecyclerView
android:id="#+id/recyclerview2"
android:layout_width="fill_parent"
android:layout_height="240dp"
android:paddingLeft="0dp"
android:paddingRight="15dp"
android:paddingTop="15dp"
android:paddingBottom="25dp"/>
i try every possible way available on internet but dont get solution.
Anything wrong i am doing?
any idea how to run two recyclerview with above code.
thankx
You can do this-
<android.support.v4.widget.NestedScrollView>
<LinearLayout>
.
.
.
</LinearLayout>
</android.support.v4.widget.NestedScrollView>
This is used to attach 2 or more scrolling views together and one more thing you can do is to make the height of recycler view as "wrap_content".
Hope this helps.
I want to add n numbers of spinners in list view or recycler view for ex if n is 4 , 4 spinner should be there with different items inside them.
I have tried with recycler view but as its name says it recycles view , I dont think that more view can be added (I am not sure). Below is my code
public class Online3 extends AppCompatActivity {
List<String> categories1, categories2, categories3, categories4, categories13, categories12, categories5, categories6;
String objectId;
private List<Array_G_S> list = new ArrayList<>();
RecyclerView recyclerView;
ArrayAdap adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_online3);
Intent intent = getIntent();
objectId = intent.getStringExtra("objId");
String txt = intent.getStringExtra("imageText");
if (objectId != null) {
Log.i("sand", objectId);
} else {
Log.i("sand", txt);
}
new RemoteTask().execute();
}
private class RemoteTask extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... params) {
ParseQuery<ParseObject> query = new ParseQuery<>("OnlineShopping");
query.whereEqualTo("objectId", objectId);
List<ParseObject> object1 = null;
try {
object1 = query.find();
for (final ParseObject country : object1) {
if (country != null) {
ParseRelation<ParseObject> p = country.getRelation("arrayRelation");
ParseQuery p2 = p.getQuery();
List<ParseObject> oc = p2.find();
for (ParseObject country2 : oc) {
if (country2 != null) {
categories1 = country2.getList("eType");
Array_G_S gs = new Array_G_S();
gs.setStringList(categories1);
list.add(gs);
}
}
}
// Locate images in flag column
}
} catch (com.parse.ParseException e1) {
e1.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
recyclerView = (RecyclerView) findViewById(R.id.arrayRecy);
recyclerView.setNestedScrollingEnabled(false); // Smooth Scrolling
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getApplicationContext());
adapter = new ArrayAdap(getApplicationContext(), list);
recyclerView.setLayoutManager(layoutManager);
recyclerView.setItemAnimator(new DefaultItemAnimator());
recyclerView.setAdapter(adapter);
}
}
Below is my Adapter Class
public class ArrayAdap extends RecyclerView.Adapter<ArrayAdap.MyViewHolder> {
private Context context;
private List<Array_G_S> list = null;
ArrayAdapter<Array_G_S> dataAdapter;
public ArrayAdap(Context context, List<Array_G_S> list) {
this.context = context;
this.list = list;
}
#Override
public ArrayAdap.MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.spinner, parent, false);
return new MyViewHolder(itemView);
}
#Override
public void onBindViewHolder(ArrayAdap.MyViewHolder holder, int position) {
Array_G_S gs = list.get(position);
dataAdapter = new ArrayAdapter<String>(context,android.R.layout.simple_spinner_item,gs.getStringList());
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
holder.spinner.setAdapter(dataAdapter);
}
#Override
public int getItemCount() {
return list.size();
}
public class MyViewHolder extends RecyclerView.ViewHolder {
Spinner spinner;
public MyViewHolder(View v) {
super(v);
spinner = (Spinner) v.findViewById(R.id.spin);
}
}
And this is the screenshot of what I am getting