How to connect volley to recyclerview? - json

I am trying to take data from web and by the help of volley and display it in Recylerview.
I can easily display data in toast but in case of recylerview I am having problem. I have follow Slidenerd from youtube:
https://www.youtube.com/playlist?list=PLonJJ3BVjZW6CtAMbJz1XD8ELUs1KXaTD
but it not displaying in Recyclerview, any ideas?
FragmentCollege.java class:
public class FragmentCollege extends Fragment {
public static final String URL_EDUSANJAL_COLLEGE = "http://edusanjal.com/api/edusanjal/college/?format=json";
private VolleySingleton volleySingleton;
private ImageLoader imageLoader;
private RequestQueue requestQueue;
private ArrayList<College> listCollege = new ArrayList<>();
private RecyclerView listCollegeHits;
private AdapterCollege mAdapterCollege;
public FragmentCollege() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
volleySingleton = VolleySingleton.getInstance();
requestQueue = volleySingleton.getRequestQueue();
}
private void sendJsonRequest() {
JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET,
URL_EDUSANJAL_COLLEGE,
(String) null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
listCollege = parseJSONResponse(response);
mAdapterCollege.setCollegeList(listCollege);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
requestQueue.add(request);
}
private ArrayList<College> parseJSONResponse(JSONObject response) {
ArrayList<College> listCollege = new ArrayList<>();
if (response == null || response.length() == 0) {
try {
StringBuilder data = new StringBuilder();
JSONArray arrayCollege = response.getJSONArray(KEY_OBJECTS);
for (int i = 0; i < arrayCollege.length(); i++) {
JSONObject currentCollege = arrayCollege.getJSONObject(i);
Long id = currentCollege.getLong(KEY_ID);
String title = currentCollege.getString(KEY_TITLE);
String city = currentCollege.getString(KEY_CITY);
String phone = currentCollege.getString(KEY_PHONE);
data.append(id + "\n" + title + "\n" + city + "\t" + phone + "\n" + "\n");
College college = new College();
college.setId(id);
college.setTitle(title);
college.setCity(city);
college.setPhone(phone);
listCollege.add(college);
}
} catch (JSONException e) {
}
L.T(getActivity(), listCollege.toString());
}
return listCollege;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_college, container, false);
listCollegeHits = (RecyclerView) view.findViewById(R.id.listCollegeHits);
listCollegeHits.setLayoutManager(new LinearLayoutManager(getActivity()));
mAdapterCollege = new AdapterCollege(getActivity());
listCollegeHits.setAdapter(mAdapterCollege);
sendJsonRequest();
// Inflate the layout for this fragment
return view;
}
}
fragemnt_college.xml:
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.edusanjal.edusanjal.activity.CollegeFragment">
<!-- TODO: Update blank fragment layout -->
<android.support.v7.widget.RecyclerView
android:id="#+id/listCollegeHits"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<TextView
android:id="#+id/textVolleyError"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:padding="#dimen/size_word"
android:text="#FF4444"
android:visibility="gone"/>
custom_college_layout.xml:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginBottom="#dimen/size_byte"
android:layout_marginLeft="#dimen/size_word"
android:layout_marginRight="#dimen/size_word"
android:layout_marginTop="#dimen/size_byte">
<ImageView
android:id="#+id/collegeLogo"
android:layout_width="#dimen/college_thumbnail_width"
android:layout_height="#dimen/college_thumbnail_height"
android:layout_centerVertical="true"
android:src="#mipmap/ic_launcher"/>
<TextView
android:id="#+id/collegeTitle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:layout_alignTop="#+id/collegeLogo"
android:layout_marginLeft="56dp"
android:alpha="0.87"
android:gravity="right"
android:padding="#dimen/size_half_byte"
android:text="Aadikabi Bhanubhakta Higher Secondary School"
android:textSize="#dimen/size_text_primary"/>
<TextView
android:id="#+id/collegePhone"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:layout_below="#+id/collegeTitle"
android:layout_marginLeft="56dp"
android:alpha="0.87"
android:gravity="right"
android:padding="#dimen/size_half_byte"
android:text="Phone"
android:textSize="#dimen/size_text_primary"/>
<TextView
android:id="#+id/collegeCity"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:layout_below="#+id/collegePhone"
android:layout_marginLeft="56dp"
android:alpha="0.87"
android:gravity="right"
android:padding="#dimen/size_half_byte"
android:text="city"
android:textSize="#dimen/size_text_primary"/>
<TextView
android:id="#+id/collegeCreatedOn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_below="#id/collegeCity"
android:alpha="0.87"
android:padding="#dimen/size_half_byte"
android:text="31-31-31"
android:textSize="#dimen/size_text_secondary"/>
AdapterCollege.java:
public class AdapterCollege extends RecyclerView.Adapter<AdapterCollege.ViewHolderCollege> {
private ArrayList<College> listCollege = new ArrayList<>();
private LayoutInflater mLayoutInflater;
private VolleySingleton volleySingleton;
private ImageLoader imageLoader;
private DateFormat dateFormatter=new SimpleDateFormat("yyyy-MM-dd");
public AdapterCollege(Context context) {
mLayoutInflater = mLayoutInflater.from(context);
volleySingleton = VolleySingleton.getInstance();
imageLoader = volleySingleton.getImageLoader();
}
public void setCollegeList(ArrayList<College> listCollege) {
this.listCollege = listCollege;
notifyItemRangeChanged(0, listCollege.size());
}
#Override
public ViewHolderCollege onCreateViewHolder(ViewGroup parent, int viewType) {
View view = mLayoutInflater.inflate(R.layout.custom_college_layout, parent, false);
ViewHolderCollege viewHolder = new ViewHolderCollege(view);
return viewHolder;
}
#Override
public void onBindViewHolder(ViewHolderCollege holder, int position) {
College currentCollege = listCollege.get(position);
holder.collegeTitle.setText(currentCollege.getTitle());
Date collegeCreatedOn=currentCollege.getCreatedOn();
if(collegeCreatedOn!=null){
String formattedDate=dateFormatter.format(collegeCreatedOn);
holder.collegeCreatedOn.setText(formattedDate);
}
else{
holder.collegeCreatedOn.setText(Constants.NA);
}
holder.collegeCity.setText(currentCollege.getCity());
holder.collegePhone.setText(currentCollege.getPhone());
String urlLogo = currentCollege.getUrlLogo();
loadImages(urlLogo, holder);
}
private void loadImages(String urlLogo, final ViewHolderCollege holder) {
if (!urlLogo.equals(Constants.NA)) {
imageLoader.get(urlLogo, new ImageLoader.ImageListener() {
#Override
public void onResponse(ImageLoader.ImageContainer response, boolean isImmediate) {
holder.collegeLogo.setImageBitmap(response.getBitmap());
}
#Override
public void onErrorResponse(VolleyError error) {
}
});
}
}
#Override
public int getItemCount() {
return listCollege.size();
}
static class ViewHolderCollege extends RecyclerView.ViewHolder {
ImageView collegeLogo;
TextView collegeTitle;
TextView collegeCreatedOn;
TextView collegePhone;
TextView collegeCity;
public ViewHolderCollege(View itemView) {
super(itemView);
collegeLogo = (ImageView) itemView.findViewById(R.id.collegeLogo);
collegeTitle = (TextView) itemView.findViewById(R.id.collegeTitle);
collegeCreatedOn = (TextView) itemView.findViewById(R.id.collegeCreatedOn);
collegePhone = (TextView) itemView.findViewById(R.id.collegePhone);
collegeCity = (TextView) itemView.findViewById(R.id.collegeCity);
}
}
pojo class => College.java:
public class College {
private long id;
private String title;
private Date createdOn;
private String phone;
private String city;
private String urlLogo;
public College(){
}
public College(long id,
String title,
Date createdOn,
String phone,
String city,
String urlLogo){
this.id=id;
this.title=title;
this.createdOn=createdOn;
this.phone=phone;
this.city=city;
this.urlLogo=urlLogo;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public Date getCreatedOn() {
return createdOn;
}
public void setCreatedOn(Date createdOn) {
this.createdOn = createdOn;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getUrlLogo() {
return urlLogo;
}
public void setUrlLogo(String urlLogo) {
this.urlLogo = urlLogo;
}
#Override
public String toString() {
return "ID: "+id+
"Title "+title+
"Date "+createdOn+
"Phone "+phone+
"City "+city+
"urlLogo "+urlLogo+
"\n";
}
}
network class => VolleySingleton.java:
public class VolleySingleton {
private static VolleySingleton sInstance = null;
private ImageLoader mImageLoader;
private RequestQueue mRequestQueue;
private VolleySingleton() {
mRequestQueue = Volley.newRequestQueue(MyApplication.getAppContext());
mImageLoader = new ImageLoader(mRequestQueue, new ImageLoader.ImageCache() {
private LruCache<String, Bitmap> cache = new LruCache<>((int) (Runtime.getRuntime().maxMemory() / 1024) / 8);
#Override
public Bitmap getBitmap(String url) {
return cache.get(url);
}
#Override
public void putBitmap(String url, Bitmap bitmap) {
cache.put(url, bitmap);
}
});
}
public static VolleySingleton getInstance() {
if (sInstance == null) {
sInstance = new VolleySingleton();
}
return sInstance;
}
public RequestQueue getRequestQueue() {
return mRequestQueue;
}
public ImageLoader getImageLoader(){
return mImageLoader;
}

Related

Passing a method data to other method in same Activity

I am newbie to Android Studio and I am making my final year project.
I made a QR code scanner that can retrieve data from HTTP using Rest API.
My question is: I need to send all the JSON data to other activity, based on my research I need to put intent on my button, because of that I need to pass my JsonRequest data to Btn_BuyClicked method so I can send all those to next activity.
I used AndroidHive MovieTickets so Im not changing so much coding.
Please help me. Thank you.
public class TicketResultActivity extends AppCompatActivity {
private static final String TAG = TicketResultActivity.class.getSimpleName();
private Button btnBuy;
private ImageView imgPoster;
private ProgressBar progressBar;
private TicketView ticketView;
private TextView txtDirector;
private TextView txtYear_created;
private TextView txtError;
private TextView txtType_powder;
private TextView txtApa_number;
private TextView txtLocation;
private TextView txtDate_expired;
private Button signOut;
private FirebaseAuth auth;
private class Movie {
String director;
String year_created;
String type_powder;
#SerializedName("released")
boolean isReleased;
String apa_number;
String poster;
String location;
String date_expired;
private Movie() {
}
public String getApa_number() {
return this.apa_number;
}
public String getDirector() {
return this.director;
}
public String getPoster() {
return this.poster;
}
public String getYear_created() {
return this.year_created;
}
public String getType_powder() {
return this.type_powder;
}
public String getLocation() {
return this.location;
}
public String getDate_expired() {
return this.date_expired;
}
public boolean isReleased() {
return this.isReleased;
}
}
NotificationCompat.Builder notification;
private static final int uniqueID = 250298;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_ticket_result);
setSupportActionBar((Toolbar) findViewById(R.id.toolbar));
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
this.txtApa_number = (TextView) findViewById(R.id.apa_number);
this.txtDirector = (TextView) findViewById(R.id.director);
this.txtYear_created = (TextView) findViewById(R.id.year_created);
this.txtLocation = (TextView) findViewById(R.id.location);
this.txtDate_expired = (TextView) findViewById(R.id.date_expired);
this.imgPoster = (ImageView) findViewById(R.id.poster);
this.txtType_powder = (TextView) findViewById(R.id.type_powder);
this.btnBuy = (Button) findViewById(R.id.btn_buy);
this.imgPoster = (ImageView) findViewById(R.id.poster);
this.txtError = (TextView) findViewById(R.id.txt_error);
this.ticketView = (TicketView) findViewById(R.id.layout_ticket);
this.progressBar = (ProgressBar) findViewById(R.id.progressBar);
String barcode = getIntent().getStringExtra("code");
if (TextUtils.isEmpty(barcode)) {
Toast.makeText(getApplicationContext(), "Barcode is empty!", Toast.LENGTH_LONG).show();
finish();
}
searchBarcode(barcode);
}
public void btn_buyClicked(View view) {
notification.setSmallIcon(R.drawable.qrcode);
notification.setTicker("This is the ticker");
notification.setWhen(System.currentTimeMillis());
notification.setContentTitle("Fire Extinguisher Scanner");
Intent intent = new Intent(this, Test.class);
startActivity(new Intent(TicketResultActivity.this, Test.class));
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
notification.setContentIntent(pendingIntent);
NotificationManager nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
nm.notify(uniqueID, notification.build());
}
private void searchBarcode(String barcode) {
MyApplication.getInstance().addToRequestQueue(new JsonObjectRequest(Request.Method.GET, barcode, null, new Listener<JSONObject>() {
public void onResponse(JSONObject response) {
Log.e(TicketResultActivity.TAG, "Ticket response: " + response.toString());
if (response.has("error")) {
TicketResultActivity.this.showNoTicket();
} else {
TicketResultActivity.this.renderMovie(response);
}
}
}, new ErrorListener() {
public void onErrorResponse(VolleyError error) {
Log.e(TicketResultActivity.TAG, "Error: " + error.getMessage());
TicketResultActivity.this.showNoTicket();
}
}));
}
private void showNoTicket() {
this.txtError.setVisibility(View.VISIBLE);
this.ticketView.setVisibility(View.GONE);
this.progressBar.setVisibility(View.GONE);
}
public void renderMovie(JSONObject response) {
try {
Movie movie = (Movie) new Gson().fromJson(response.toString(), Movie.class);
if (movie != null) {
this.txtApa_number.setText(movie.getApa_number());
this.txtDirector.setText(movie.getDirector());
this.txtYear_created.setText(movie.getYear_created());
this.txtType_powder.setText(movie.getType_powder());
this.txtDate_expired.setText(BuildConfig.FLAVOR + movie.getDate_expired());
this.txtLocation.setText(movie.getLocation());
Glide.with(this).load(movie.getPoster()).into(this.imgPoster);
notification.setContentText("Fire Extinguisher "+ movie.getApa_number()+"successfully remind!");
if (movie.isReleased()) {
this.btnBuy.setText(getString(R.string.btn_buy_now));
this.btnBuy.setTextColor(ContextCompat.getColor(this, R.color.colorPrimary));
} else {
this.btnBuy.setText(getString(R.string.btn_buy_now));
this.btnBuy.setTextColor(ContextCompat.getColor(this, R.color.colorPrimary));
}
this.ticketView.setVisibility(View.VISIBLE);
this.progressBar.setVisibility(View.GONE);
return;
}
showNoTicket();
} catch (JsonSyntaxException e) {
Log.e(TAG, "JSON Exception: " + e.getMessage());
showNoTicket();
Toast.makeText(getApplicationContext(), "Error occurred. Check your LogCat for full report", Toast.LENGTH_SHORT).show();
} catch (Exception e2) {
showNoTicket();
Toast.makeText(getApplicationContext(), "Error occurred. Check your LogCat for full report", Toast.LENGTH_SHORT).show();
}
}
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == android.R.id.home) {
finish();
}
return super.onOptionsItemSelected(item);
}
}
This is my TicketResultActivity.java class UPDATED CODE
private static class Movie implements Parcelable {
String director;
String year_created;
String type_powder;
#SerializedName("released")
boolean isReleased;
String apa_number;
String poster;
String location;
String date_expired;
public Movie() {
}
public Movie(Parcel in) {
director = in.readString();
year_created = in.readString();
type_powder = in.readString();
isReleased = in.readByte() != 0;
apa_number = in.readString();
poster = in.readString();
location = in.readString();
date_expired = in.readString();
}
public String getApa_number(){
return this.apa_number;
}
public String getYear_created() {
return year_created;
}
public String getType_powder() {
return type_powder;
}
public String getDirector() {
return director;
}
public String getPoster() {
return poster;
}
public String getLocation() {
return location;
}
public boolean isReleased() {
return isReleased;
}
public String getDate_expired() {
return date_expired;
}
public void setApa_number(String apa_number){
this.apa_number = apa_number;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(director);
dest.writeString(year_created);
dest.writeString(type_powder);
dest.writeByte((byte) (isReleased ? 1 : 0));
dest.writeString(apa_number);
dest.writeString(poster);
dest.writeString(location);
dest.writeString(date_expired);
}
public static final Parcelable.Creator<Movie> CREATOR = new Parcelable.Creator<Movie>() {
#Override
public Movie createFromParcel(Parcel in) {
return new Movie(in);
}
#Override
public Movie[] newArray(int size) {
return new Movie[size];
}
};
#Override
public int describeContents() {
return 0;
}
}
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_ticket_result);
setSupportActionBar((Toolbar) findViewById(R.id.toolbar));
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
this.txtApa_number = (TextView) findViewById(R.id.apa_number);
this.txtDirector = (TextView) findViewById(R.id.director);
this.txtYear_created = (TextView) findViewById(R.id.year_created);
this.txtLocation = (TextView) findViewById(R.id.location);
this.txtDate_expired = (TextView) findViewById(R.id.date_expired);
this.imgPoster = (ImageView) findViewById(R.id.poster);
this.txtType_powder = (TextView) findViewById(R.id.type_powder);
this.btnBuy = (Button) findViewById(R.id.btn_buy);
this.imgPoster = (ImageView) findViewById(R.id.poster);
this.txtError = (TextView) findViewById(R.id.txt_error);
this.ticketView = (TicketView) findViewById(R.id.layout_ticket);
this.progressBar = (ProgressBar) findViewById(R.id.progressBar);
String barcode = getIntent().getStringExtra("code");
if (TextUtils.isEmpty(barcode)) {
Toast.makeText(getApplicationContext(), "Barcode is empty!", Toast.LENGTH_LONG).show();
finish();
}
searchBarcode(barcode);
}
public void btn_buyClicked(View view) {
// In activity or fragment
Movie movie = new Movie();
movie.setApa_number("xyz");
Intent intent = new Intent(this, Test.class);
intent.putExtra("parcel_data", movie);
startActivity(intent);
}
private void searchBarcode(String barcode) {
MyApplication.getInstance().addToRequestQueue(new JsonObjectRequest(Request.Method.GET, barcode, null, new Listener<JSONObject>() {
public void onResponse(JSONObject response) {
Log.e(TicketResultActivity.TAG, "Ticket response: " + response.toString());
if (response.has("error")) {
TicketResultActivity.this.showNoTicket();
} else {
TicketResultActivity.this.renderMovie(response);
}
}
}, new ErrorListener() {
public void onErrorResponse(VolleyError error) {
Log.e(TicketResultActivity.TAG, "Error: " + error.getMessage());
TicketResultActivity.this.showNoTicket();
}
}));
}
private void showNoTicket() {
this.txtError.setVisibility(View.VISIBLE);
this.ticketView.setVisibility(View.GONE);
this.progressBar.setVisibility(View.GONE);
}
public void renderMovie(JSONObject response) {
try {
Movie movie = (Movie) new Gson().fromJson(response.toString(), Movie.class);
if (movie != null) {
this.txtApa_number.setText(movie.getApa_number());
this.txtDirector.setText(movie.getDirector());
this.txtYear_created.setText(movie.getYear_created());
this.txtType_powder.setText(movie.getType_powder());
this.txtDate_expired.setText(BuildConfig.FLAVOR + movie.getDate_expired());
this.txtLocation.setText(movie.getLocation());
Glide.with(this).load(movie.getPoster()).into(this.imgPoster);
if (movie.isReleased()) {
this.btnBuy.setText(getString(R.string.btn_buy_now));
this.btnBuy.setTextColor(ContextCompat.getColor(this, R.color.colorPrimary));
} else {
this.btnBuy.setText(getString(R.string.btn_buy_now));
this.btnBuy.setTextColor(ContextCompat.getColor(this, R.color.colorPrimary));
}
this.ticketView.setVisibility(View.VISIBLE);
this.progressBar.setVisibility(View.GONE);
return;
}
showNoTicket();
} catch (JsonSyntaxException e) {
Log.e(TAG, "JSON Exception: " + e.getMessage());
showNoTicket();
Toast.makeText(getApplicationContext(), "Error occurred. Check your LogCat for full report", Toast.LENGTH_SHORT).show();
} catch (Exception e2) {
showNoTicket();
Toast.makeText(getApplicationContext(), "Error occurred. Check your LogCat for full report", Toast.LENGTH_SHORT).show();
}
}
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == android.R.id.home) {
finish();
}
return super.onOptionsItemSelected(item);
}
}
This is Test.java Class
public class Test extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test);
Movie movie = (Movie) getIntent().getParcelableExtra("parcel_data");
String apa_number = movie.getApa_number();
TextView textView1 = findViewById(R.id.textView2);
textView1.setText(apa_number);
}
}
Use Parcelable is an interface. A class who implements Parcelable can write to and read from a Parcel.
You need to follow 3 points to create a Parcelable class.
A Class must implement Parcelable interface
A Class must have a non-null static field CREATOR of a type that implements Parcelable.Creator interface.
Override writeToParcel method and write member variable in Parcel. Make sure to read variables in the same sequence in which they are written in Parcel. Order of read and write matters.
private class Movie implements Parcelable{
String director;
String year_created;
String type_powder;
#SerializedName("released")
boolean isReleased;
String apa_number;
String poster;
String location;
String date_expired;
public Movie() {
}
// In constructor you will read the variables from Parcel. Make sure to read them in the same sequence in which you have written them in Parcel.
public Movie(Parcel in) {
director = in.readString();
year_created = in.readString();
release_date = in.readString();
poster = in.readString();
}
public String getApa_number() {
return this.apa_number;
}
public String getDirector() {
return director;
}
public void setDirector(String director) {
this.director = director;
}
// This is where you will write your member variables in Parcel. Here you can write in any order. It is not necessary to write all members in Parcel.
#Override
public void writeToParcel(Parcel dest, int flags) {
// Write data in any order
dest.writeString(director);
dest.writeString(year_created);
dest.writeString(release_date);
dest.writeString(poster);
}
// This is to de-serialize the object
public static final Parcelable.Creator<Movie> CREATOR = new Parcelable.Creator<Movie>(){
public Movie createFromParcel(Parcel in) {
return new Movie(in);
}
public Movie[] newArray(int size) {
return new Movie[size];
}
};
}
Now you can pass a Parcelable object using Intent.
// In activity or fragment
Movie movie = new Movie();
movie.setDirector("xyz");
// now you can set all values like :year created, is released whatever.
// using context and next component class to create intent
Intent intent = new Intent(this, NextActivity.class);
// using putExtra(String key, Parcelable value) method
intent.putExtra(“parcel_data”, movie);
startActivity(intent);
You can access this data in NextActivity –
public class NextActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
// Using getParcelableExtra(String key) method
Movie movie = (Movie) getIntent().getParcelableExtra("parcel_data");
String director = movie.getDirector();
}
}
There are so many ways to send data from one activity to another activity. If you Have Primitive or Json string type data then you can directly put that data into the intent.
But if in case you have Model class and you need to pass it. Then you have two ways:
Serializable
Parcelable
But Android recommend to use Parcelable.
You can also add plugin to android studio to generate the parcelable code.

Issue with deserializing nested json

I am working on deserializing the below JSON:
{"self":"http://members.cs.com/rest/api/user?username=abc#cs.com",
"key":"abc#cs.com",
"name":"abc#cs.com",
"emailAddress":"abc#cs.com",
"displayName":"ABC",
"active":true,
"members":{"size":1,"items":[{"name":"member-users","self":"http://members.cs.com/rest/api/user?username=abc#cs.com"}]},
"expand":"members"}
I have created the following classes:
#JsonIgnoreProperties(ignoreUnknown = true)
public class UserList {
private String name;
private String emailAddress;
private String displayName;
private boolean active;
List<MemberName> members = new ArrayList<>();
#JsonCreator
public UserList(#JsonProperty("name") String name, #JsonProperty("emailAddress") String emailAddress, #JsonProperty("displayName") String displayName, #JsonProperty("active") boolean active, #JsonProperty("members") List<MemberName> members) {
this.name = name;
this.emailAddress = emailAddress;
this.displayName = displayName;
this.active = active;
this.members.addAll(groups);
}
//getters
}
#JsonIgnoreProperties(ignoreUnknown = true)
public class MemberName {
private String name;
#JsonCreator
public MemberName(#JsonProperty("name") String name) {
this.name = name;
}
public String getName() {
return name;
}
}
When I don't give the members as a property the deserialization works fine and I can see the values for the name, displayName, active, emailAddress. The problem happens with the MemberName.
Could someone help with this?
This worked for me:
Class Items as below:
public class Items {
private String name;
private String self;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSelf() {
return self;
}
public void setSelf(String self) {
this.self = self;
}
}
Members class as below:
public class Members {
private int size;
private List<Items> items;
public int getSize() {
return size;
}
public void setSize(int size) {
this.size = size;
}
public List<Items> getItems() {
return items;
}
public void setItems(List<Items> items) {
this.items = items;
}
}
Data class as below:
public class Data {
private String self;
private String key;
private String name;
private String emailAddress;
private String displayName;
private boolean active;
private Members members;
private String expand;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSelf() {
return self;
}
public void setSelf(String self) {
this.self = self;
}
public String getKey() {
return key;
}
public void setKey(String key) {
this.key = key;
}
public String getEmailAddress() {
return emailAddress;
}
public void setEmailAddress(String emailAddress) {
this.emailAddress = emailAddress;
}
public String getDisplayName() {
return displayName;
}
public void setDisplayName(String displayName) {
this.displayName = displayName;
}
public boolean isActive() {
return active;
}
public void setActive(boolean active) {
this.active = active;
}
public Members getMembers() {
return members;
}
public void setMembers(Members members) {
this.members = members;
}
public String getExpand() {
return expand;
}
public void setExpand(String expand) {
this.expand = expand;
}
}
The deserialization as below:
public static void main(String[] args) throws JsonParseException, JsonMappingException, IOException {
String jsonString = "{\"self\": \"http://members.cs.com/rest/api/user?username=abc#cs.com\",\"key\": \"abc#cs.com\",\"name\": \"abc#cs.com\","
+ "\"emailAddress\": \"abc#cs.com\",\"displayName\": \"ABC\",\"active\": true,\"members\": {\"size\": 1,\"items\": [{"
+ "\"name\": \"member-users\",\"self\": \"http://members.cs.com/rest/api/user?username=abc#cs.com\" }]},\"expand\": \"members\"}";
ObjectMapper mapper = new ObjectMapper();
Data obj = mapper.readValue(jsonString,Data.class);
System.out.println(obj.getSelf());
System.out.println(obj.getKey());
System.out.println(obj.getName());
System.out.println(obj.getEmailAddress());
System.out.println(obj.getDisplayName());
System.out.println(obj.isActive());
System.out.println(obj.getMembers().getSize());
System.out.println(obj.getMembers().getItems().get(0).getName());
System.out.println(obj.getMembers().getItems().get(0).getSelf());
System.out.println(obj.getExpand());
}

How to load data(json) into recycler view using volley

I have implemented recyclerview in my application and now i need to fetch data from the server and i just came to know about volley being the best way to fetch data. I searched online but i am unable to find a proper tutorial for the same.
This is how i initialized the recyclerview in my code.(which has hardcoded data set)
mRecyclerView = (RecyclerView) findViewById(R.id.recyclerview);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
mRecyclerView.setLayoutManager(linearLayoutManager);
mAdapter = new CardAdapter();
mRecyclerView.setAdapter(mAdapter);
here is the adapter code.
public class CardAdapter extends RecyclerView.Adapter<CardAdapter.ViewHolder> {
ArrayList<BusRouteNameDetails> mItems;
public int TAG=0;
public CardAdapter() {
super();
mItems = new ArrayList<>();
BusRouteNameDetails routename = new BusRouteNameDetails();
routename.setName("xyz");
routename.setNumber("X4");
mItems.add(routename);
routename = new BusRouteNameDetails();
routename.setName("xyz");
routename.setNumber("X4");
mItems.add(routename);
routename = new BusRouteNameDetails();
routename.setName("xyz");
routename.setNumber("X4");
mItems.add(routename);
routename = new BusRouteNameDetails();
routename.setName("xyz");
routename.setNumber("X4");
mItems.add(routename);
routename = new BusRouteNameDetails();
routename.setName("xyz");
routename.setNumber("X4");
mItems.add(routename);
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View v = LayoutInflater.from(viewGroup.getContext())
.inflate(R.layout.busroutename_list, viewGroup, false);
ViewHolder viewHolder = new ViewHolder(v);
return viewHolder;
}
#Override
public void onBindViewHolder(ViewHolder viewHolder, int i) {
BusRouteNameDetails routename = mItems.get(i);
viewHolder.tvName.setText(routename.getName());
viewHolder.tvRoutename.setText(routename.getNumber());
Log.e("TAG","i value="+ i);
if(i==mItems.size()-1)
viewHolder.seperator.setVisibility(View.INVISIBLE);
}
#Override
public int getItemCount() {
Log.e("TAG","item size"+ mItems.size());
return mItems.size();
}
class ViewHolder extends RecyclerView.ViewHolder{
public TextView tvName;
public TextView tvRoutename;
public View seperator;
public ViewHolder(View itemView) {
super(itemView);
tvName = (TextView)itemView.findViewById(R.id.RouteName1);
tvRoutename = (TextView)itemView.findViewById(R.id.Route_src_dest);
seperator=(View)itemView.findViewById(R.id.seperator);
}
}
}
And here are the getters and setters
public class BusRouteNameDetails {
private String mName;
private String mNumber;
public String getName() {
return mName;
}
public void setName(String name) {
this.mName = name;
}
public String getNumber() {
return mNumber;
}
public void setNumber(String Number) {
this.mNumber = Number;
}
}
You can try as my following solution:
Let's assume the server response as the following JSON:
[
{
"name": "Person 1",
"age": 30
},
{
"name": "Person 2",
"age": 20
},
{
"name": "Person 3",
"age": 40
}
]
In your Android project:
public class Person {
String name;
Integer age;
Person() {
}
}
public class RVAdapter extends RecyclerView.Adapter<RVAdapter.PersonViewHolder> {
List<Person> persons;
RVAdapter(List<Person> persons) {
this.persons = persons;
}
#Override
public PersonViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.cardview, parent, false);
PersonViewHolder pvh = new PersonViewHolder(v);
return pvh;
}
#Override
public void onBindViewHolder(PersonViewHolder holder, int position) {
holder.personName.setText(persons.get(position).name);
holder.personAge.setText(String.valueOf(persons.get(position).age));
}
#Override
public int getItemCount() {
if (persons != null) {
return persons.size();
}
return 0;
}
#Override
public void onAttachedToRecyclerView(RecyclerView recyclerView) {
super.onAttachedToRecyclerView(recyclerView);
}
public static class PersonViewHolder extends RecyclerView.ViewHolder {
CardView cv;
TextView personName;
TextView personAge;
PersonViewHolder(View itemView) {
super(itemView);
cv = (CardView) itemView.findViewById(R.id.cv);
personName = (TextView) itemView.findViewById(R.id.person_name);
personAge = (TextView) itemView.findViewById(R.id.person_age);
}
}
}
Then in your Activity:
...
RecyclerView rv = (RecyclerView)findViewById(R.id.rv);
rv.setHasFixedSize(true);
LinearLayoutManager llm = new LinearLayoutManager(mContext);
rv.setLayoutManager(llm);
final RVAdapter rvAdapter = new RVAdapter(personList);
rv.setAdapter(rvAdapter);
RequestQueue requestQueue = Volley.newRequestQueue(mContext);
String url = "http://192.16.1.100/api/persons";
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(url, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
try {
if (response.length() > 0) {
personList.clear();
for (int i = 0; i < response.length(); i++) {
JSONObject jsonObject = response.getJSONObject(i);
Person person = new Person();
if (!jsonObject.isNull("name")) {
person.name = jsonObject.getString("name");
}
if (!jsonObject.isNull("age")) {
person.age = jsonObject.getInt("age");
}
personList.add(i, person);
}
rvAdapter.notifyDataSetChanged();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// do something
}
});
requestQueue.add(jsonArrayRequest);
...
Here is the result
Hope this helps!

gwt+gxt+spring+mybatis+mysql the result is output

The program compiles without errors. I can not understand why the widget is not displayed.
GreetingServise
#RemoteServiceRelativePath("springGwtServices/greetingService")
public interface GreetingService extends RemoteService {
Greeting getGreeting(String text);
void addGreeting(String author, String text);
void updateGreeting(String author, String text);
void deleteGreeting(String text);
List<Greeting> getGreetings();
}
GreetingServiceAsync
public interface GreetingServiceAsync extends RemoteService {
void getGreeting(String text, AsyncCallback<Greeting> async);
void addGreeting(String author, String text, AsyncCallback<Void> async);
void updateGreeting(String author, String text, AsyncCallback<Void> async);
void deleteGreeting(String text, AsyncCallback<Void> async);
void getGreetings( AsyncCallback<List<Greeting>> callback);
}
HelloGWT
public class HelloGWT implements IsWidget, EntryPoint {
static Logger logger = Logger.getLogger(HelloGWT.class);
private static final GreetingMapper props = GWT.create(GreetingMapper.class);
private static final GreetingServiceImpl impl = GWT.create(GreetingServiceImpl.class);
private ContentPanel panel;
public Widget asWidget() {
if (panel == null) {
ColumnConfig<Greeting, String> nameCol = new ColumnConfig<Greeting, String>(props.author(), 50, SafeHtmlUtils.fromTrustedString("<b>Company</b>"));
ColumnConfig<Greeting, String> symbolCol = new ColumnConfig<Greeting, String>(props.text(), 100, "Symbol");
List<ColumnConfig<Greeting, ?>> columns = new ArrayList<ColumnConfig<Greeting, ?>>();
columns.add(nameCol);
columns.add(symbolCol);
ColumnModel<Greeting> cm = new ColumnModel<Greeting>(columns);
ToolTipConfig config = new ToolTipConfig("Example Info", "This examples includes resizable panel, reorderable columns and grid state. Text selection is allowed.");
config.setMaxWidth(225);
ToolButton info = new ToolButton(ToolButton.QUESTION);
info.setToolTipConfig(config);
ListStore<Greeting> store = new ListStore<Greeting>(props.id());
store.addAll(impl.getGreetings());
final Grid<Greeting> grid = new Grid<Greeting>(store, cm);
grid.setAllowTextSelection(true);
grid.getView().setAutoExpandColumn(nameCol);
grid.getView().setStripeRows(true);
grid.getView().setColumnLines(true);
grid.setBorders(false);
grid.setColumnReordering(true);
// Stage manager, turn on state management
grid.setStateful(true);
grid.setStateId("gridExample");
// Stage manager, load previous state
GridStateHandler<Greeting> state = new GridStateHandler<Greeting>(grid);
state.loadState();
SimpleComboBox<String> typeCombo = new SimpleComboBox<String>(new StringLabelProvider<String>());
typeCombo.setTriggerAction(ComboBoxCell.TriggerAction.ALL);
typeCombo.setEditable(false);
typeCombo.setWidth(100);
typeCombo.add("Row");
typeCombo.add("Cell");
typeCombo.setValue("Row");
// we want to change selection model on select, not value change which fires on blur
typeCombo.addSelectionHandler(new SelectionHandler<String>() {
public void onSelection(SelectionEvent<String> event) {
boolean cell = event.getSelectedItem().equals("Cell");
if (cell) {
CellSelectionModel<Greeting> c = new CellSelectionModel<Greeting>();
c.addCellSelectionChangedHandler(new CellSelectionChangedEvent.CellSelectionChangedHandler<Greeting>() {
public void onCellSelectionChanged(CellSelectionChangedEvent<Greeting> event) {
}
});
grid.setSelectionModel(c);
} else {
grid.setSelectionModel(new GridSelectionModel<Greeting>());
}
}
});
typeCombo.addValueChangeHandler(new ValueChangeHandler<String>() {
public void onValueChange(ValueChangeEvent<String> event) {
}
});
ToolBar toolBar = new ToolBar();
toolBar.setEnableOverflow(false);
toolBar.add(new LabelToolItem("Selection Mode: "));
toolBar.add(typeCombo);
VerticalLayoutContainer con = new VerticalLayoutContainer();
con.add(toolBar, new VerticalLayoutContainer.VerticalLayoutData(1, -1));
con.add(grid, new VerticalLayoutContainer.VerticalLayoutData(1, 1));
panel = new ContentPanel();
panel.setHeadingText("Basic Grid");
panel.setPixelSize(600, 300);
panel.addTool(info);
final Resizable resizable = new Resizable(panel, Resizable.Dir.E, Resizable.Dir.SE, Resizable.Dir.S);
panel.addExpandHandler(new ExpandEvent.ExpandHandler() {
public void onExpand(ExpandEvent event) {
resizable.setEnabled(true);
}
});
panel.addCollapseHandler(new CollapseEvent.CollapseHandler() {
public void onCollapse(CollapseEvent event) {
resizable.setEnabled(false);
}
});
panel.setWidget(con);
// Enables quicktips (qtitle for the heading and qtip for the
// content) that are setup in the change GridCellRenderer
new QuickTip(grid);
}
return panel;
}
public void onModuleLoad() {
// State manager, initialize the state options
StateManager.get().setProvider(new CookieProvider("/", null, null, GXT.isSecure()));
RootPanel.get().add(asWidget());
BasicConfigurator.configure();
logger.info("Entering application.");
Bar bar = new Bar();
bar.doIt();
logger.info("Exiting application.");
}
}
GreetingMapper
public interface GreetingMapper extends PropertyAccess<Greeting> {
#Select("SELECT * FROM greetings WHERE text = #{text}")
Greeting getGreeting(#Param("text") String text);
#Select("INSERT INTO greetings (author, text) VALUES (#{author}, #{text})")
void addGreeting(#Param("author") String author, #Param("text") String text);
#Select("UPDATE greetings SET author = #{author} where text = #{text}")
void updateGreeting(#Param("author") String author, #Param("text") String text);
#Select("DELETE FROM greetings WHERE text = #{text}")
void deleteGreeting(#Param("text") String text);
#Select("SELECT * FROM greetings")
List<Greeting> getGreetings();
ModelKeyProvider<Greeting> id();
ValueProvider<Greeting, String> author();
ValueProvider<Greeting, String> text();
}
GreetingServiceImpl
#Service("greetingService")
public class GreetingServiceImpl implements GreetingService {
#Autowired
private GreetingMapper greetingMapper;
#Override
public Greeting getGreeting(String text) {
return greetingMapper.getGreeting(text);
}
#Override
public void addGreeting(String author, String text) {
greetingMapper.addGreeting(author, text);
}
#Override
public void updateGreeting(String author, String text) {
greetingMapper.updateGreeting(author, text);
}
#Override
public void deleteGreeting(String text) {
greetingMapper.deleteGreeting(text);
}
#Override
public List<Greeting> getGreetings() {
return greetingMapper.getGreetings();
}
}
Greeting
public class Greeting extends BaseModelData implements Serializable{
private Integer id;
private String author;
private String text;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
}

Struts2 json model

I get the following problems when enter my action:
Struts Problem Report
Struts has detected an unhandled exception:
Messages:
java.lang.reflect.InvocationTargetException
org.apache.struts2.json.JSONException: java.lang.reflect.InvocationTargetException
org.apache.struts2.json.JSONException:
org.apache.struts2.json.JSONException: java.lang.reflect.InvocationTargetException
File:
model/Empresa.java
Line number: 34
//ACTION
private static final long serialVersionUID = 1L;
private SincronizaService service = new SincronizaServiceImp();
//Your result List
private List<Sincroniza> gridModel;
//get how many rows we want to have into the grid - rowNum attribute in the grid
private Integer rows = 0;
//Get the requested page. By default grid sets this to 1.
private Integer page = 0;
// sorting order - asc or desc
private String sord;
// get index row - i.e. user click to sort.
private String sidx;
// Search Field
private String searchField;
// The Search String
private String searchString;
// he Search Operation ['eq','ne','lt','le','gt','ge','bw','bn','in','ni','ew','en','cn','nc']
private String searchOper;
// Your Total Pages
private Integer total = 0;
// All Record
private Integer records = 0;
public String execute() throws Exception
{
int to = (rows * page);
int from = to - rows;
//Count Rows (select count(*) from custumer)
records = 5;//CustumerDAO.count();
//Your logic to search and select the required data.
gridModel = service.lista();//CustumerDAO.find(from, to);
//calculate the total pages for the query
total =(int) Math.ceil((double)records / (double)rows);
return SUCCESS;
}
public String getJSON() throws Exception
{
return execute();
}
public List<Sincroniza> getGridModel() {
return gridModel;
}
public void setGridModel(List<Sincroniza> gridModel) {
this.gridModel = gridModel;
}
public Integer getRows() {
return rows;
}
public void setRows(Integer rows) {
this.rows = rows;
}
public Integer getPage() {
return page;
}
public void setPage(Integer page) {
this.page = page;
}
public String getSord() {
return sord;
}
public void setSord(String sord) {
this.sord = sord;
}
public String getSidx() {
return sidx;
}
public void setSidx(String sidx) {
this.sidx = sidx;
}
public String getSearchField() {
return searchField;
}
public void setSearchField(String searchField) {
this.searchField = searchField;
}
public String getSearchString() {
return searchString;
}
public void setSearchString(String searchString) {
this.searchString = searchString;
}
public String getSearchOper() {
return searchOper;
}
public void setSearchOper(String searchOper) {
this.searchOper = searchOper;
}
public Integer getTotal() {
return total;
}
public void setTotal(Integer total) {
this.total = total;
}
public Integer getRecords() {
return records;
}
public void setRecords(Integer records) {
this.records = records;
}
//MODEL
private static final long serialVersionUID = 1L;
private Integer idempresa;
private String descripcion;
private String abreviacion;
private String alterno_id;
private Date fecha_alta;
private Date fecha_cambios;
private Date fecha_baja;
public Empresa(int idempresa, String descripcion, String abreviacion,
String alterno_id, Date fecha_alta, Date fecha_cambios,
Date fecha_baja) {
super();
this.idempresa = idempresa;
this.descripcion = descripcion;
this.abreviacion = abreviacion;
this.alterno_id = alterno_id;
this.fecha_alta = fecha_alta;
this.fecha_cambios = fecha_cambios;
this.fecha_baja = fecha_baja;
}
public Empresa(){}
public int getIdempresa() {
return idempresa;//THIS IS LINE 34
}
public void setIdempresa(int idempresa) {
this.idempresa = idempresa;
}
public String getDescripcion() {
return descripcion;
}
public void setDescripcion(String descripcion) {
this.descripcion = descripcion;
}
public String getAbreviacion() {
return abreviacion;
}
public void setAbreviacion(String abreviacion) {
this.abreviacion = abreviacion;
}
public String getAlterno_id() {
return alterno_id;
}
public void setAlterno_id(String alterno_id) {
this.alterno_id = alterno_id;
}
public Date getFecha_alta() {
return fecha_alta;
}
public void setFecha_alta(Date fecha_alta) {
this.fecha_alta = fecha_alta;
}
public Date getFecha_cambios() {
return fecha_cambios;
}
public void setFecha_cambios(Date fecha_cambios) {
this.fecha_cambios = fecha_cambios;
}
public Date getFecha_baja() {
return fecha_baja;
}
public void setFecha_baja(Date fecha_baja) {
this.fecha_baja = fecha_baja;
}
//STRUTS-ACTION EXTENDS STRUTS.XML
<action name="irSincronizar" class="action.JsonTable">
<result name="success" type="json">/prueba.jsp</result>
</action>
//STRUTS.XML
<constant name="struts.devMode" value="true"/>
<constant name="struts.configuration.xml.reload" value="true"/>
<include file="struts-usuario.xml"/>
<include file="struts-navegacion.xml"/>
<package name="struts" extends="struts-default,tiles-default,json-default">
</package>