How to intent a parse query? - android

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

Related

How set Jsoup data to RecyclerView in AsyncTask

I'm parsing website title from URL, and set this title to RecyclerView item. When I call constructor, but I must use AsyncTasck for correctly work Jsoup. How can I set received data to RecyclerView?
I can do public MyAsyncTasck instead of private, but i don't now if it is right.
My MainActivity.java:
public class MainActivity extends AppCompatActivity {
public static final String TAG = "mLog";
#BindView(R.id.recycler_view)
RecyclerView recyclerView;
#BindView(R.id.imageView)
ImageView imageView;
private RecyclerView.Adapter adapter;
private List<ListItem> listItems;
ListItem item;
String URL = "https://sinoptik.ua/%D0%BF%D0%BE%D0%B3%D0%BE%D0%B4%D0%B0-
%D0%B2%D0%B8%D0%BD%D0%BD%D0%B8%D1%86%D0%B0";
Document document;
// Received data from Jsoup
String head = "something";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButterKnife.bind(this);
MyAsyncTask myAsyncTask = new MyAsyncTask();
myAsyncTask.execute();
recyclerView.setLayoutManager(new LinearLayoutManager(this));
listItems = new ArrayList<>();
item = new ListItem(head, "desc1");
listItems.add(item);
adapter = new MyRecViewAdapter(listItems, this);
recyclerView.setAdapter(adapter);
}
private class MyAsyncTask extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... voids) {
try {
document = Jsoup.connect(URL).get();
head = document.title();
} catch (IOException e ) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
// ??????
}
}
}
And MyRecViewAdapter.java:
public class MyRecViewAdapter extends RecyclerView.Adapter<MyRecViewAdapter.ViewHolder>{
private List<ListItem> listItems;
private Context context;
public MyRecViewAdapter(List<ListItem> listItems, Context context) {
this.listItems = listItems;
this.context = context;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext())
.inflate(R.layout.list_item, parent, false);
//return our view
return new ViewHolder(v);
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
ListItem listItem = listItems.get(position);
holder.tvHead.setText(listItem.getHead());
holder.tvDesc.setText(listItem.getDesc());
}
#Override
public int getItemCount() {
return listItems.size();
}
public static class ViewHolder extends RecyclerView.ViewHolder {
public TextView tvHead;
public TextView tvDesc;
public ViewHolder(View itemView) {
super(itemView);
tvHead = (TextView) itemView.findViewById(R.id.tv_head);
tvDesc = (TextView) itemView.findViewById(R.id.tv_desc);
}
}
}
And the ListItem.java
public class ListItem {
private String head;
private String desc;
public ListItem(String head, String desc) {
this.head = head;
this.desc = desc;
}
public String getHead() {
return head;
}
public String getDesc() {
return desc;
}
}
You need to set the data got from your API call using the AsyncTask into your listItems which are being represented in your RecyclerView. Then you need to call notifyDataSetChanged in order to show the newly updated the in your RecyclerView.
So you need to modify the doInBackground function in your AsyncTask like the following.
private class MyAsyncTask extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... voids) {
try {
document = Jsoup.connect(URL).get();
listItems.clear();
ListItem item = new ListItem(document.title, document.desc);
listItems.add(item);
adapter.notifyDataSetChanged();
} catch (IOException e ) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
// ??????
}
}

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

Attaching a spinner widget to recycler view(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

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