Attaching a spinner widget to recycler view(Android) - android

I want to add multiple spinners to my recycler view, I am using parse as my backend, I have created one but this doesn't give me expected results.And I also have no idea how to do onclick if my items get listed inside a spinner 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
EDIT
I have edited my code above
Ok i have solved this issue by putting Getter_Setter list directly to adapter .
Now my issue is how to solve Onclick on selected items
EDIT
This is only creating a single spinner, i need multiple spinner ie acccording to my list

Related

Add dynamically Spinners in list or recyclerView

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

Loading data from sqlite database with AsyncTask and display inside recyclerview items

I have a Navigation menu with nav menu on it. When clicked on each nav menu, the specific fragment is opened.For example, when I click on Words nav menu, words item display with recyclerView items on it. I'm fetching data from offline and external SQLite database and display on recyclerView items. Now I want to fetch data in another thread, NOT in the main thread, because I want increase loading speed data and app performance. But I don't know how to do this. please help me with a code. I read the same subject on the internet, but I still now have my issue.
this is my AllWordsFragment
public class AllWordsFragment extends Fragment {
private List<WordsList> wordsLists = new ArrayList<>();
private Cursor cursor;
ProgressBar progressBar;
RecyclerView recyclerView;
AllWordsAdapter allWordsAdapter;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater,
#Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.all_words_fragment, container, false);
progressBar = view.findViewById(R.id.progressBar);
progressBar.setMax(600);
allWordsAdapter = new AllWordsAdapter(getActivity(), wordsLists);
allWordsAdapter.notifyDataSetChanged();
recyclerView = view.findViewById(R.id.recyclerViewAllWords);
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getActivity());
recyclerView.setLayoutManager(layoutManager);
recyclerView.setItemAnimator(new DefaultItemAnimator());
recyclerView.setHasFixedSize(true);
recyclerView.setAdapter(allWordsAdapter);
loadingWords();
return view;
}
private void loadingWords() {
WordDatabase wordDatabase = new WordDatabase(getActivity());
try {
wordDatabase.createDatabase();
wordDatabase.openDatabase();
} catch (SQLiteException e) {
e.printStackTrace();
}
try {
cursor = wordDatabase.QueryData("SELECT Word, Definition, Example, WordList, ImageWord FROM Words");
if (cursor != null && cursor.moveToFirst()) {
do {
WordsList wordList = new WordsList();
wordList.setWordTitle(cursor.getString(0));
wordList.setDefinition(cursor.getString(1));
wordList.setExample(cursor.getString(2));
wordList.setVocubList(cursor.getString(3));
wordList.setImageWord(cursor.getString(4));
wordsLists.add(wordList);
} while (cursor.moveToNext());
wordDatabase.close();
}
} catch (SQLiteException w) {
w.printStackTrace();
} finally {
if (cursor != null) {
cursor.close();
}
}
}
and this is my AllWordsAdapter
public class AllWordsAdapter extends RecyclerView.Adapter {
private int lastPosition = -1;
protected Context context;
private List<WordsList> wordsListList = new ArrayList<>();
public AllWordsAdapter(Context context, List<WordsList> wordsListList) {
this.context = context;
this.wordsListList = wordsListList;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(context).inflate(R.layout.all_words_item, parent, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(final ViewHolder holder, int position) {
WordsList wordsList = wordsListList.get(position);
holder.wordTitle.setText(wordsList.getWordTitle());
holder.definitionWord.setText(Html.fromHtml(wordsList.getDefinition()));
holder.exampleWord.setText(Html.fromHtml(wordsList.getExample()));
holder.labelWordList.setLabelText(wordsList.getVocubList());
//get image from assets with Glide.
String pathImage = wordsList.getImageWord();
String assetsPath = "file:///android_asset/";
Glide.with(context)
.asBitmap()
.load(Uri.parse(assetsPath + "" + pathImage))
.into(holder.wordImage);
Log.d("path", assetsPath + "" + pathImage);
Typeface headerFont = Typeface.createFromAsset(context.getAssets(), "fonts/Roboto-Bold.ttf");
holder.wordTitle.setTypeface(headerFont);
Typeface customFont = Typeface.createFromAsset(context.getAssets(), "fonts/Roboto-Italic.ttf");
holder.exampleWord.setTypeface(customFont);
holder.definitionWord.setTypeface(customFont);
//cal animation function
setAnimation(holder.itemView, position);
holder.relativeLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(context, AllWordsDetails.class);
intent.putExtra("word", holder.wordTitle.getText().toString());
context.startActivity(intent);
}
});
}
#Override
public int getItemCount() {
return wordsListList.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
private CircleImageView wordImage;
private LabelTextView labelWordList;
private TextView wordTitle, definitionWord, exampleWord;
private RelativeLayout relativeLayout;
public ViewHolder(View itemView) {
super(itemView);
wordTitle = itemView.findViewById(R.id.allWordTitle);
wordImage = itemView.findViewById(R.id.circleHeaderImage);
exampleWord = itemView.findViewById(R.id.exampleAllWord);
definitionWord = itemView.findViewById(R.id.definitionAllWord);
labelWordList = itemView.findViewById(R.id.labelWordList);
relativeLayout = itemView.findViewById(R.id.relativeAllWords);
}
}
private void setAnimation(View viewToAnimation, int position) {
// If the bound view wasn't previously displayed on screen, it's animated
if (position > lastPosition) {
ScaleAnimation scaleAnimation = new ScaleAnimation(0.0f, 1.0f, 0.0f, 1.0f,
Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
scaleAnimation.setDuration(new Random().nextInt(501));//to make duration random number between [0,501)
viewToAnimation.startAnimation(scaleAnimation);
lastPosition = position;
}
}
}
I know must be use AsyncTask and do this in background, but I don't know how do this ? Please help me with a code. Thanks .
create an AsyncTask class inside your class:
class WordLoaderTask extends AsyncTask<Void, Void, Void> {
protected Void doInBackground(Void... params) {
loadingWords();
}
protected void onPostExecute(Void param) {
allWordsAdapter.notifyDataSetChanged();
}
}//asyncClass
replace calling loadingWords() in onCreate() with this line:
new WordLoaderTask().execute();
if you (for some reason or a way of using app) start getting duplicates in your ListView, then add wordsLists.clear(); as first line inside the do{} in loadingWords() method
Try like this
public class AllWordsFragment extends Fragment {
private List<WordsList> wordsLists = new ArrayList<>();
private Cursor cursor;
ProgressBar progressBar;
RecyclerView recyclerView;
AllWordsAdapter allWordsAdapter;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater,
#Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.all_words_fragment, container, false);
progressBar = view.findViewById(R.id.progressBar);
progressBar.setMax(600);
allWordsAdapter = new AllWordsAdapter(getActivity(), wordsLists);
allWordsAdapter.notifyDataSetChanged();
recyclerView = view.findViewById(R.id.recyclerViewAllWords);
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getActivity());
recyclerView.setLayoutManager(layoutManager);
recyclerView.setItemAnimator(new DefaultItemAnimator());
recyclerView.setHasFixedSize(true);
recyclerView.setAdapter(allWordsAdapter);
loadingWords();
return view;
}
private static LoadWordsTask extends AsyncTask<Void, Void, List<WordsList>> {
private Context context;
private AllWordsAdapter adapter;
private List<WordsList> wordsLists;
public LoadWordsTask(Context context, AllWordsAdapter adapter, List<WordsList> wordsLists) {
this.context = context;
this.adapter = adapter;
this.wordsLists = wordsLists;
}
#Override
public List<WordsList> doInBackground() {
List<WordsList> data = new ArrayList<>();
WordDatabase wordDatabase = new WordDatabase(getActivity());
try {
wordDatabase.createDatabase();
wordDatabase.openDatabase();
} catch (SQLiteException e) {
e.printStackTrace();
}
try {
cursor = wordDatabase.QueryData("SELECT Word, Definition, Example, WordList, ImageWord FROM Words");
if (cursor != null && cursor.moveToFirst()) {
do {
WordsList wordList = new WordsList();
wordList.setWordTitle(cursor.getString(0));
wordList.setDefinition(cursor.getString(1));
wordList.setExample(cursor.getString(2));
wordList.setVocubList(cursor.getString(3));
wordList.setImageWord(cursor.getString(4));
data.add(wordList);
} while (cursor.moveToNext());
wordDatabase.close();
}
} catch (SQLiteException w) {
w.printStackTrace();
} finally {
if (cursor != null) {
cursor.close();
}
}
return data;
}
#Override
public void onPostExecute(List<WordsList> data) {
this.wordsLists.addAll(data);
this.adapter.notifyDataSetChanged();
}
}
}

How to intent a parse query?

In parse i have a class A which has a column (relation) named - view, which relates to class B( contains different images with different object id's).Now what i want to achieve is that : in android i have a activity(A) which has a recycle view which shows all the items of class A. The items are clickable which when clicked brings up the items from class B in parse to activity(B) . Now the issue is we are unable to intent a parse query from activity (A) to activity(B), so that we can display the items of class B in Activity(B).
Is there any different method for this? Any example for this would be of additional help.
EDIT
MainActivity
public class MainActivity extends AppCompatActivity {
ProgressDialog mProgressDialog;
GridAdapter gridAdapter;
RecyclerView recyclerView;
private List<Grid_G_S> grid_list = new ArrayList<>();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Get the view from gridview_main.xml
setContentView(R.layout.activity_main);
// Execute RemoteDataTask AsyncTask
new RemoteDataTask().execute();
}
// RemoteDataTask AsyncTask
private class RemoteDataTask extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Create a progressdialog
mProgressDialog = new ProgressDialog(MainActivity.this);
// Set progressdialog title
mProgressDialog.setTitle("Parse.com GridView Tutorial");
// Set progressdialog message
mProgressDialog.setMessage("Loading...");
mProgressDialog.setIndeterminate(false);
// Show progressdialog
mProgressDialog.show();
}
#Override
protected Void doInBackground(Void... params) {
// Create the array
grid_list = new ArrayList<>();
try {
ParseQuery<ParseObject> query = new ParseQuery<>("CardViewClass");
List<ParseObject> object1 = query.find();
for (final ParseObject country : object1) {
// Locate images in flag column
ParseFile image = (ParseFile) country.get("images");
ParseRelation<ParseObject> p = country.getRelation("view");
ParseQuery p2 = p.getQuery();
String f = image.getUrl();
Log.i("yji"," "+p2);
List<ParseObject> oc = p2.find();
for (ParseObject country2:oc){
ParseFile imgs = (ParseFile) country2.get("autoImage");
String fr = imgs.getUrl();
}
Grid_G_S setter = new Grid_G_S();
setter.setX(p2);
setter.setTitles((String) country.get("scrollText1"));
setter.setImages(f);
grid_list.add(setter);
}
}catch (ParseException e){
Log.e("err", e.getMessage());
} catch (com.parse.ParseException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
recyclerView = (RecyclerView) findViewById(R.id.recycler);
RecyclerView.LayoutManager mLayoutManager = new GridLayoutManager(getApplicationContext(),3);
gridAdapter = new GridAdapter(MainActivity.this, grid_list);
recyclerView.setLayoutManager(mLayoutManager);
recyclerView.setItemAnimator(new DefaultItemAnimator());
recyclerView.setAdapter(gridAdapter);
mProgressDialog.dismiss();
}
GridAdapter
public class GridAdapter extends RecyclerView.Adapter {
Context context;
LayoutInflater inflater;
private List<Grid_G_S> grid_g_sList = null;
private ArrayList<Grid_G_S> arraylist;
public GridAdapter(Context context, List<Grid_G_S> grid_list) {
this.context = context;
this.grid_g_sList = grid_list;
inflater = LayoutInflater.from(context);
this.arraylist = new ArrayList<>();
this.arraylist.addAll(grid_list);
}
public class MyViewHolder extends RecyclerView.ViewHolder {
TextView titles;
ImageView gridImages;
View mview;
MyViewHolder(View v) {
super(v);
mview = v;
titles = (TextView) v.findViewById(R.id.grid_single_text);
gridImages = (ImageView) v.findViewById(R.id.grid_single_image);
}
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.grid_single_row, parent, false);
return new MyViewHolder(itemView);
}
#Override
public void onBindViewHolder(MyViewHolder holder, final int position) {
Grid_G_S item = grid_g_sList.get(position);
holder.titles.setText(item.getTitles());
Picasso.with(context)
.load(grid_g_sList.get(position).getImages())
.into(holder.gridImages);
holder.mview.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(context, Secondactivity.class);
intent.putExtra("image", grid_g_sList.get(position).getImages());
intent.putExtra("query", String.valueOf(grid_g_sList.get(position).getX()));
context.startActivity(intent);
}
});
}
#Override
public int getItemCount() {
return grid_g_sList.size();
}
GridGetterSetter
public class Grid_G_S {
String Images;
String Titles;
ParseQuery x;
public String getImages() {
return Images;
}
public void setImages(String images) {this.Images = images;}
public String getTitles() {
return Titles;
}
public void setTitles(String titles) {this.Titles = titles;}
public ParseQuery getX() {
return x;
}
public void setX(ParseQuery x) {this.x = x;}
SecondActivity
public class Secondactivity extends AppCompatActivity {
String q1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_secondactivity);
new DownloadingTask().execute();
Intent i = getIntent();
String images = i.getStringExtra("image");
q1 = i.getStringExtra("query");
Log.i("this is ", " " + q1);
}
private class DownloadingTask extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... voids) {
ParseQuery<ParseObject> query = new ParseQuery<>("CardViewClass");
try {
List<ParseObject> object1 = query.find();
for (final ParseObject country : object1) {
// Locate images in flag column
}
} catch (ParseException e) {
e.printStackTrace();
}
return null;
}
}

Displaying Multiple Images From Parse.com Using RecyclerView Is Only Displaying One Of My Three Images

I have three images stored in a table class called: "events" and table column called: "image" on Parse.com
I used two queries 1 to handle the displaying of the images and one to get another table's information (Those are all Strings)
THE PROBLEM IS:
The query that i used to get all the images only displays one of the three images in the RecyclerView instead of all three.
How can i display all three images from Parse.com inside a RecyclerView?
MY MAIN ACTIVITY:
public class MainActivity extends Activity {
//Defining Variables
protected Toolbar toolbar;
protected NavigationView navigationView;
private DrawerLayout drawerLayout;
protected Button mButtonHeader;
protected TextView mDayOfTheWeek;
protected TextView mDate;
//protected Context context;
//private long pageId = 137317903012386L;
private RecyclerView mRecyclerView;
//New Variables
private CustomAdapter mAdapter;
//Weather variables
//private ImageView weatherIconImageView;
private TextView temperatureTextView;
private TextView conditionTextView;
private TextView locationTextView;
private ProgressDialog dialog;
private ProgressDialog progressDialog;
final List<Information> data = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//RecyclerView with Parse
mRecyclerView = (RecyclerView) findViewById(R.id.recycler_view_layout);
mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
mAdapter = new CustomAdapter(getApplicationContext(), data);
//The Query i used to get the three images
ParseQuery<ParseObject> queryImgs = new ParseQuery<ParseObject> ("events");
//queryImgs.orderByAscending("order");
//queryImgs.setLimit(10);
queryImgs.findInBackground(new FindCallback<ParseObject>() {
#Override
public void done(final List<ParseObject> objects, ParseException e) {
//for (ParseObject obj_food : objects) {
//if (obj_food.getInt("order") == order) {
for (int i = 0; i < objects.size(); i++) {
//final ParseFile file = obj_food.getParseFile("image");
//Information information = new Information();
//information.mEventsPhotoID = objects.get(i).getParseFile("image");
final ParseFile file = objects.get(i).getParseFile("image");
//bitmap
file.getDataInBackground(new GetDataCallback() {
public void done(byte[] data, ParseException e) {
if (e == null) {
Bitmap bmp = BitmapFactory
.decodeByteArray(
data, 0,
data.length);
// Get the ImageView from
// main.xml
mEventsPhotoID = (ParseImageView) findViewById(R.id.eventsPhotoID);
//mEventsPhotoIDTwo = (ParseImageView)findViewById(R.id.eventsPhotoID);
// Set the Bitmap into the
// ImageView
mEventsPhotoID.setImageBitmap(bmp);
//mEventsPhotoIDTwo.setImageBitmap(bmp);
}
}
});
//}
//order++;
}
mRecyclerView.setAdapter(mAdapter);
}
});
//Query to load String data into the card view/recycler view
ParseQuery<ParseObject> query = ParseQuery.getQuery("events");
query.findInBackground(new FindCallback<ParseObject>() {
#Override
public void done(List<ParseObject> objects, ParseException e) {
if (e == null) {
for (int i = 0; i < objects.size(); i++) {
Information information = new Information();
information.mNewstTitle = objects.get(i).getString("name");
information.mNewsStory = objects.get(i).getString("shortinfo");
//information.partyCost = parseObject.getString("partyName");
String url=objects.get(i).getParseFile("image").getUrl();
//information.mEventsPhotoID = objects.getParseFile("partyFlyerImage");
//information.mEventsPhotoID = objects.get(i).getParseFile("image");
//information.mNewsPhotoIcon = R.drawable.newsitem));
//Initialize ImageView
ParseImageView imageViewPicasso = (ParseImageView) findViewById(R.id.eventsPhotoID);
//Loading image from below url into imageView
Picasso.with(MainActivity.this)
.load(url)
.into(imageViewPicasso);
data.add(information);
}
} else {
// something went wrong
}
//adapter.notifyItemRangeInserted(startPosition, imageUrls.length);
mRecyclerView.setAdapter(mAdapter);
}
});
}//END onCreate
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
drawerLayout.openDrawer(GravityCompat.START);
return true;
}
return super.onOptionsItemSelected(item);
}
}//End Main Activity
MY ADAPTER CLASS:
public class CustomAdapter extends RecyclerView.Adapter<CustomAdapter.MyViewHolder> {
//private List<String> imageUrls = new ArrayList<>();
List<Information> data = Collections.emptyList();
private LayoutInflater inflater;
private Context context;
/*public CustomAdapter (Context context,List<Information>data){
this.context=context;
inflater=LayoutInflater.from(context);
this.data= data;
}*/
public CustomAdapter (Context context,List<Information>data){
this.context=context;
inflater=LayoutInflater.from(context);
this.data= data;
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType){
View view= inflater.inflate(R.layout.cardview_upcomingshows, parent, false);
MyViewHolder holder = new MyViewHolder(view);
return holder;
}
#Override
public void onBindViewHolder(MyViewHolder holder, int position){
Information current= data.get(position);
//holder.mEventsPhotoID.setImageResource(current.mEventsPhotoID);
holder.mNewstTitle.setText(current.mNewstTitle);
holder.mNewsStory.setText(current.mNewsStory);
holder.mEventsPhotoID.setParseFile(current.mEventsPhotoID);
//holder.mEventsPhotoIDTwo.setParseFile(current.mEventsPhotoIDTwo);
}
#Override
public int getItemCount(){
return data.size();
}
class MyViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
//ImageView mEventsPhotoID;
TextView mNewstTitle;
TextView mNewsStory;
ParseImageView mEventsPhotoID;
//ParseImageView mEventsPhotoIDTwo;
public MyViewHolder(View itemView) {
super(itemView);
//promoterImage = (ParseImageView) itemView.findViewById(R.id.promoterPicImage);
mEventsPhotoID = (ParseImageView) itemView.findViewById(R.id.eventsPhotoID);
//mEventsPhotoIDTwo = (ParseImageView) itemView.findViewById(R.id.eventsPhotoIDTwo);
mNewstTitle = (TextView) itemView.findViewById(R.id.newsTitle);
mNewsStory = (TextView) itemView.findViewById(R.id.newsStory);
mNewstTitle.setOnClickListener(this);
mNewsStory.setOnClickListener(this);
itemView.setOnClickListener(this);
}
#Override
public void onClick(View v) {
Toast.makeText(context, "Recycle Click" + getLayoutPosition(), Toast.LENGTH_SHORT).show();
if(getLayoutPosition()==0){
Intent intentEventsWebView = new Intent(itemView.getContext(), EventsWebViewActivity.class);
//intentIndependenceDay.putExtra("MyClass", myclass);
intentEventsWebView.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
itemView.getContext().startActivity(intentEventsWebView);
}
if(getLayoutPosition()==1){
Intent intentIndependenceDay = new Intent(itemView.getContext(), NextActivity.class);
//intentIndependenceDay.putExtra("MyClass", myclass);
intentIndependenceDay.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
itemView.getContext().startActivity(intentIndependenceDay);
}
if(getLayoutPosition()==2){
Intent intentShelleyMaxwellDance = new Intent(itemView.getContext(), OtherActivity.class);
//intentIndependenceDay.putExtra("MyClass", myclass);
intentShelleyMaxwellDance.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
itemView.getContext().startActivity(intentShelleyMaxwellDance);
}
}
}
}
MY DATA MODEL CLASS(CONTAINING DATA FOR THE RECYCLER VIEW):
public class Information {
String mNewstTitle;
String mNewsStory;
ParseFile mEventsPhotoID;
}
instead of reading the ParseFile yourself, try using the Url approach mentioned here:
Displaying ParseFile Containing Images Using Their Urls In A RecyclerView

Data on cardview are changed while scrolling RecyclerView

I am newbie to Android apps development.
I have a class, which contains RecyclerView.
public class ScreenOne extends Fragment implements SwipeRefreshLayout.OnRefreshListener {
private RecyclerView mRecyclerView;
private FilmSetAdapter mAdapter;
private RecyclerView.LayoutManager mLayoutManager;
SwipeRefreshLayout mSwipeRefreshLayout;
RequestTask requestTask;
ArrayList<Film> listOfFilms;
ArrayList<Cinema> listOfCinemas;
ArrayList<String> cityIDs;
public ScreenOne() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.screen_one, container,
false);
mRecyclerView = (RecyclerView) rootView.findViewById(R.id.recycler_view);
mLayoutManager = new LinearLayoutManager(getActivity());
//mRecyclerView.setHasFixedSize(true);
mRecyclerView.setLayoutManager(mLayoutManager);
//mRecyclerView.setItemAnimator(new DefaultItemAnimator());
listOfFilms = new ArrayList<>();
mAdapter = new FilmSetAdapter(listOfFilms);
mRecyclerView.setAdapter(mAdapter);
mSwipeRefreshLayout = (SwipeRefreshLayout) rootView.findViewById(R.id.refresh);
mSwipeRefreshLayout.setOnRefreshListener(this);
mSwipeRefreshLayout.setColorScheme(R.color.blue, R.color.cyan, R.color.grey_blue, R.color.lightblue);
try {
updateFilms();
} catch (InterruptedException e) {
e.printStackTrace();
}
return rootView;
}
private void updateFilms() throws InterruptedException {
requestTask = new RequestTask();
try {
requestTask.execute().get();
} catch (ExecutionException e) {
e.printStackTrace();
}
}
private boolean isNetworkConnected() {
ConnectivityManager cm =
(ConnectivityManager) getActivity().getSystemService(getActivity().CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
return netInfo != null && netInfo.isConnectedOrConnecting();
}
#Override
public void onRefresh() {
Toast.makeText(getActivity(), R.string.refresh_started, Toast.LENGTH_SHORT).show();
mSwipeRefreshLayout.setRefreshing(true);
mAdapter.setDataset(new ArrayList<Film>());
mAdapter.notifyDataSetChanged();
try {
updateFilms();
} catch (InterruptedException e) {
e.printStackTrace();
}
DatabaseHandler database = new DatabaseHandler(getActivity());
mAdapter = new FilmSetAdapter(database.getAllFilms());
mRecyclerView.swapAdapter(mAdapter, false);
database.close();
mSwipeRefreshLayout.postDelayed(new Runnable() {
#Override
public void run() {
mSwipeRefreshLayout.setRefreshing(false);
Toast.makeText(getActivity(), R.string.refresh_finished, Toast.LENGTH_SHORT).show();
}
}, 3000);
}
class RequestTask extends AsyncTask<Void, Void, Void> {
protected void getPreferenciesCity()
{
cityIDs = new ArrayList<>();
SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(getActivity());
Set<String> selections = sharedPrefs.getStringSet("cities", null);
try {
Log.d("SHARED PREFERENCES CITY", selections.toString());
cityIDs.addAll(selections);
}catch (NullPointerException e){Log.d("SHARED PREFERENCES CITY", "SP are empty");}
}
#Override
protected void onPreExecute() {
super.onPreExecute();
listOfFilms = new ArrayList<>();
getPreferenciesCity();
}
#Override
protected Void doInBackground(Void... params) {
if(isNetworkConnected()) {
DatabaseHandler database = new DatabaseHandler(getActivity());
database.clearFilms();
try {
HttpHandler httpHandler = new HttpHandler();
listOfFilms = new ArrayList<>(httpHandler.listOfFilmsRequest(cityIDs));
listOfCinemas = new ArrayList<>(httpHandler.listOfCinemasRequest());
Film film;
Cinema cinema;
for (Iterator<Film> filmiterator = listOfFilms.iterator(); filmiterator.hasNext(); ) {
film = filmiterator.next();
if (database.isInDatabase(film.getID()))
database.updateFilm(film);
else
database.addFilm(film);
}
for (Iterator<Cinema> cinemaiterator = listOfCinemas.iterator(); cinemaiterator.hasNext(); ) {
cinema = cinemaiterator.next();
if (database.CinemaIsInDatabase(cinema.getIDCinema()))
database.updateCinema(cinema);
else
database.addCinema(cinema);
}
database.close();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
DatabaseHandler database = new DatabaseHandler(getActivity());
mAdapter.setDataset(database.getAllFilms());
mAdapter.notifyDataSetChanged();
}
}
}
It executes a method, which is placed in the AsyncTask class. This method downloads data from server, puts it to database first and after that sets the recycler view adapter. The problem is that sometimes text data are changed while scrolling it. See attached video.
Code of adapter is:
public class FilmSetAdapter extends RecyclerView.Adapter<FilmSetAdapter.ViewHolder>{
private ArrayList<Film> mDataset;
final static String LOG_TAG = "FilmSetAdapter";
public void setDataset(ArrayList<Film> allFilms) {
mDataset = new ArrayList<>(allFilms);
}
public static class ViewHolder extends RecyclerView.ViewHolder {
public static TextView filmTitle;
public TextView country;
public TextView ticketsFrom;
public TextView rating;
public TextView format;
public ImageView poster;
public int id;
public ViewHolder(final View itemView) {
super(itemView);
filmTitle = (TextView) itemView.findViewById(R.id.filmtitle);
country = (TextView)itemView.findViewById(R.id.country);
ticketsFrom = (TextView) itemView.findViewById(R.id.ticketsfrom);
rating = (TextView)itemView.findViewById(R.id.rating);
poster = (ImageView) itemView.findViewById(R.id.poster);
format = (TextView) itemView.findViewById(R.id.format);
format.setTypeface(null, Typeface.BOLD_ITALIC);
}
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext())
.inflate(R.layout.cardview, parent, false);
final ViewHolder vh = new ViewHolder(v);
v.setOnClickListener(new View.OnClickListener() {
#Override public void onClick(View v) {
Log.d(LOG_TAG, "Нажата карточка. Вызов из activity "+v.toString());
Intent intent = new Intent(v.getContext(),FilmInfoActivity.class);
intent.putExtra("EXTRA_FILM_ID", vh.id);
v.getContext().startActivity(intent);
}
});
return vh;
}
#Override
public void onBindViewHolder(final ViewHolder holder, int position) {
// - get element from your dataset at this position
// - replace the contents of the view with that element
holder.filmTitle.setText(mDataset.get(position).getTitle().toString()+" ID="+mDataset.get(position).getID()+" POS="+position);
holder.country.setText(mDataset.get(position).getCountry());
holder.ticketsFrom.setText(holder.ticketsFrom.getContext().getString(R.string.tickets_from) +
mDataset.get(position).getRating().toString());
holder.rating.setText(holder.rating.getContext().getString(R.string.rating_kinopoisk) +
mDataset.get(position).getRating());
holder.id = mDataset.get(position).getID();
holder.format.setText(mDataset.get(position).getFormat());
Picasso.with(holder.poster.getContext()).
load(mDataset.get(position).getPoster()).
skipMemoryCache().
into(holder.poster);
}
#Override
public int getItemCount() {
if(mDataset != null)
return mDataset.size();
return 0;
}
public FilmSetAdapter(ArrayList<Film> myDataset) {
mDataset = new ArrayList<>(myDataset);
}
}
I have no clue on how to sort it out.
it seem to that there is a typo mistake in your code, look at that, you have in your ViewHolder:
public static TextView filmTitle;
But then you work with it like with your other fields:
#Override
public void onBindViewHolder(final ViewHolder holder, int position) {
// - get element from your dataset at this position
// - replace the contents of the view with that element
holder.filmTitle.setText(mDataset.get(position).getTitle() + ...);
...
}
A little advice for you as a newbie: just.. pay more attention to your code, and you'll be fine in programming :)

Categories

Resources