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!
Related
Why my pager adapter cant show the data that I load from openweather(as json format) cant show properly. I got five page in the slide view and the data in the first page will not show unless I load to the third page and the data in second page will show only when I load to the fourth page.
This is the coding of my slider java class
public class SliderAdapter extends PagerAdapter {
Context context;
LayoutInflater layoutInflater;
private static final String TAG = "SliderAdapter";
public SliderAdapter(Context context)
{
this.context=context;
}
public double[] slide_headings= new double[50];
public String[] slide_desc=new String[50];
public String[] slide_images= new String[50];
public static final String URL_DATA = "http://api.openweathermap.org/data/2.5/forecast?id=1732698&appid=4bdfb7127d4a85742cfbb201078ba566";
#Override
public int getCount() {
return 5;
}
#Override
public boolean isViewFromObject(View view,Object o) {
return view== o;
}
#Override
public Object instantiateItem(ViewGroup container,int position)
{
getData();
layoutInflater= (LayoutInflater) context.getSystemService(context.LAYOUT_INFLATER_SERVICE);
View view=layoutInflater.inflate(R.layout.slide_layout,container,false);
ImageView slideImageView=view.findViewById(R.id.imageView);
TextView slideHeading=view.findViewById(R.id.textView);
TextView slideDescription=view.findViewById(R.id.textView2);
Glide.with(context).load(slide_images[position]).into(slideImageView);
slideHeading.setText(Double.toString(slide_headings[position]));
slideDescription.setText(slide_desc[position]);
container.addView(view);
return view;
}
private void getData() {
final ProgressDialog progressDialog = new ProgressDialog(context);
progressDialog.setMessage("Loading data.....");
progressDialog.show();
StringRequest stringRequest = new StringRequest(Request.Method.POST,
URL_DATA,
new Response.Listener<String>() {
#Override
public void onResponse(String s) {
progressDialog.dismiss();
try {
JSONObject jsonObject = new JSONObject(s);
for (int i = 0; i < jsonObject.length(); i++) {
JSONArray JA = (JSONArray) jsonObject.get("list");
for (int j = 0; j < JA.length(); j++) {
JSONObject JO = JA.getJSONObject(j);
JSONObject jo = (JSONObject) JO.get("main");
slide_headings[j] = jo.getDouble("temp");
JSONArray ja = JO.getJSONArray("weather");
for (int k = 0; k < ja.length(); k++) {
JSONObject o = ja.getJSONObject(k);
slide_desc[j] = o.getString("main");
slide_images[j] = "http://openweathermap.org/img/w/" + o.getString("icon") + ".png";
}
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
},
//this method will run when there is error sending the request
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError volleyError) {
progressDialog.dismiss();
Toast.makeText(context, volleyError.getMessage(), Toast.LENGTH_LONG).show();
}
});
RequestQueue requestQueue = Volley.newRequestQueue(context);
requestQueue.add(stringRequest);
}
#Override
public void destroyItem(ViewGroup container, int position,Object object) {
container.removeView((RelativeLayout)object);
}
}
This is my example of my main java class
public class MainActivity extends AppCompatActivity {
private ViewPager mSLideViewPager;
private LinearLayout mDotLayout;
private SliderAdapter sliderAdapter;
private TextView[] mDots;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mSLideViewPager=findViewById(R.id.slideViewPager);
mDotLayout=findViewById(R.id.dotsLayout);
sliderAdapter=new SliderAdapter(this);
mSLideViewPager.setAdapter(sliderAdapter);
addDotsIndicator(0);
mSLideViewPager.addOnPageChangeListener(viewListener);
}
public void addDotsIndicator(int position){
mDotLayout.removeAllViews();
mDots=new TextView[5];
for(int i=0;i<mDots.length ;i++)
{
mDots[i] = new TextView(this);
mDots[i].setText(Html.fromHtml("•"));
mDots[i].setTextSize(35);
mDots[i].setTextColor(getResources().getColor(R.color.colorTransparentWhite));
mDotLayout.addView(mDots[i]);
}
if(mDots.length >0){
mDots[position].setTextColor(getResources().getColor(R.color.colorWhite));
}
}
ViewPager.OnPageChangeListener viewListener= new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int i, float v, int i1) {
}
#Override
public void onPageSelected(int i) {
addDotsIndicator(i);
}
#Override
public void onPageScrollStateChanged(int i) {
}
};
}
I have used array list instead of array and this solve my problems
How do I insert data from MySQL into Gridview on Fragments? I've tried it with a coding method used for Activity. I've changed a lot but it's still wrong. This is my coding:
/**
* A simple {#link Fragment} subclass.
*/
public class Product extends Fragment implements
SwipeRefreshLayout.OnRefreshListener {
GridView grid_product;
SwipeRefreshLayout swipe;
List<ProductData> newsList = new ArrayList<ProductData>();
private static final String TAG = Product.class.getSimpleName();
private static String url_list = Server.URL + "news.php?offset=";
private int offSet = 0;
int no;
ProductAdapter adapter;
public static final String TAG_NO = "no";
public static final String TAG_ID = "id";
public static final String TAG_JUDUL = "judul";
public static final String TAG_TGL = "tgl";
public static final String TAG_ISI = "isi";
public static final String TAG_GAMBAR = "gambar";
Handler handler;
Runnable runnable;
public Product() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_product, container, false);
swipe = (SwipeRefreshLayout) view.findViewById(R.id.swipe_refresh_layout);
grid_product = (GridView) view.findViewById(R.id.grid_product);
setProduct();
return view;
}
private void setProduct(){
adapter = new ProductAdapter(getActivity(), newsList);
grid_product.setAdapter(adapter);
grid_product.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//pindah activity
startActivity(new Intent(
getActivity(), DetailActivity.class
));
}
});
I don't know where the mistake is:
swipe.setOnRefreshListener(this);
swipe.post(new Runnable() {
#Override
public void run() {
swipe.setRefreshing(true);
newsList.clear();
adapter.notifyDataSetChanged();
callNews(0);
}
}
);
grid_product.setOnScrollListener(new AbsListView.OnScrollListener() {
private int currentVisibleItemCount;
private int currentScrollState;
private int currentFirstVisibleItem;
private int totalItem;
#Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
this.currentScrollState = scrollState;
this.isScrollCompleted();
}
#Override
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
this.currentFirstVisibleItem = firstVisibleItem;
this.currentVisibleItemCount = visibleItemCount;
this.totalItem = totalItemCount;
}
private void isScrollCompleted() {
if (totalItem - currentFirstVisibleItem == currentVisibleItemCount
&& this.currentScrollState == SCROLL_STATE_IDLE) {
swipe.setRefreshing(true);
handler = new Handler();
runnable = new Runnable() {
public void run() {
callNews(offSet);
}
};
handler.postDelayed(runnable, 3000);
}
}
});
}
#Override
public void onRefresh() {
newsList.clear();
adapter.notifyDataSetChanged();
callNews(0);
}
I don't know where the mistake is:
private void callNews(int page){
swipe.setRefreshing(true);
// Creating volley request obj
JsonArrayRequest arrReq = new JsonArrayRequest(url_list + page,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d(TAG, response.toString());
if (response.length() > 0) {
// Parsing json
for (int i = 0; i < response.length(); i++) {
try {
JSONObject obj = response.getJSONObject(i);
ProductData news = new ProductData();
no = obj.getInt(TAG_NO);
news.addId(obj.getString(TAG_ID));
news.addJudul(obj.getString(TAG_JUDUL));
if (obj.getString(TAG_GAMBAR) != "") {
news.addGambar(obj.getString(TAG_GAMBAR));
}
news.addDatetime(obj.getString(TAG_TGL));
news.addIsi(obj.getString(TAG_ISI));
// adding news to news array
newsList.add(news);
if (no > offSet)
offSet = no;
Log.d(TAG, "offSet " + offSet);
} catch (JSONException e) {
Log.e(TAG, "JSON Parsing error: " + e.getMessage());
}
// notifying list adapter about data changes
// so that it renders the list view with updated data
adapter.notifyDataSetChanged();
}
}
swipe.setRefreshing(false);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
swipe.setRefreshing(false);
}
});
// Adding request to request queue
AppController.getInstance().addToRequestQueue(arrReq);
}
}
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.
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;
}
}
I want to store information from the NFC tag I read and store in the database and show it all in another page but I am having problem in using implementing sqlite.I cant add the information to the database using sqlite.
Below is my checkin class from where I read from the NFC tag
public partial class Checkin : PhoneApplicationPage
{
private ProximityDevice _device;
private long _subscriptionIdNdef;
public static double Latitud_do { get; set; }
public static double Longtitude_do { get; set; }
public static string latitude { get; set; }
public static string longtitude { get; set; }
public static string Floor_st { get; set; }
public static string Zone_st { get; set; }
History store = new History();
public Checkin()
{
InitializeProximityDevice();
InitializeComponent();
}
private void SetLogStatus(string newStatus)
{
Dispatcher.BeginInvoke(() => { if (LogStatus != null) LogStatus.Text = newStatus; });
}
private void SetFloorStatus(string newStatus)
{
Dispatcher.BeginInvoke(() => { if (FloorStatus != null) FloorStatus.Text = newStatus; });
}
private void ApplicationBarIconButton_Click(object sender, System.EventArgs e)
{
MessageBox.Show(" ");
}
private void InitializeProximityDevice()
{
_device = Windows.Networking.Proximity.ProximityDevice.GetDefault();
if (_device != null)
{
_subscriptionIdNdef = _device.SubscribeForMessage("NDEF", MessageReceivedHandler);
}
}
private void MessageReceivedHandler(ProximityDevice sender, ProximityMessage message)
{
var rawMsg = message.Data.ToArray();
var ndefMessage = NdefMessage.FromByteArray(rawMsg);
////// Loop over all records contained in the NDEF message
foreach (NdefRecord record in ndefMessage)
{
if (NdefTextRecord.IsRecordType(record))
{
// Convert and extract URI info
var textRecord = new NdefTextRecord(record);
string[] str = textRecord.Text.Split('|');
var Floor_st = str[0];
var Zone_st = str[1];
var latitude = str[2];
var longtitude = str[3];
Latitud_do = double.Parse(latitude);
Longtitude_do = double.Parse(longtitude);
SetLogStatus("Floor: " + Floor_st + " Zone: " + Zone_st );
SetFloorStatus("Longitude: " + latitude + " Longitude: " + longtitude);
//store.AddDb(Floor_st, Zone_st, Latitud_do, Longtitude_do);
}
}
}
}
Below here is the main dbhelper class for the main sqlite functions
public class DbHelper
{
SQLiteConnection dbConn;
public async Task<bool> onCreate(string DB_PATH)
{
try
{
if (!CheckFileExists(DB_PATH).Result)
{
using (dbConn = new SQLiteConnection(DB_PATH))
{
dbConn.CreateTable<historyTableSQlite>();
}
}
return true;
}
catch
{
return false;
}
}
private async Task<bool> CheckFileExists(string fileName)
{
try
{
var store = await Windows.Storage.ApplicationData.Current.LocalFolder.GetFileAsync(fileName);
return true;
}
catch
{
return false;
}
}
//retrieve all list from the database
public ObservableCollection<historyTableSQlite> ReadHistory()
{
using (var dbConn = new SQLiteConnection(App.DB_PATH))
{
List<historyTableSQlite> myCollection = dbConn.Table<historyTableSQlite>().ToList<historyTableSQlite>();
ObservableCollection<historyTableSQlite> HistoryList = new ObservableCollection<historyTableSQlite>(myCollection);
return HistoryList;
}
}
// Insert the new info in the histrorytablesqlite table.
public void Insert(historyTableSQlite newcontact)
{
using (var dbConn = new SQLiteConnection(App.DB_PATH))
{
dbConn.RunInTransaction(() =>
{
dbConn.Insert(newcontact);
});
}
}
}
below is the class from where I read all the information
public class ReadAllContactsList
{
DbHelper Db_Helper = new DbHelper();
public ObservableCollection<historyTableSQlite> GetAllHistory()
{
return Db_Helper.ReadHistory();
}
}
}
And last is the class where I want to show all the information I have stored
ublic partial class History : PhoneApplicationPage
{
// string dbPath = Path.Combine(Windows.Storage.ApplicationData.Current.LocalFolder.Path, "db.sqlite");
ObservableCollection<historyTableSQlite> DB_HistoryList = new ObservableCollection<historyTableSQlite>();
public History()
{
InitializeComponent();
}
private void ReadHistoryList_Loaded(object sender, RoutedEventArgs e)
{
ReadAllContactsList dbhistory = new ReadAllContactsList();
DB_HistoryList = dbhistory.GetAllHistory();//Get all DB contacts
ListData.ItemsSource = DB_HistoryList.OrderByDescending(i => i.Id).ToList();//Latest contact ID can Display first
}
public void AddInfo(object sender, RoutedEventArgs e)
{
DbHelper Db_helper = new DbHelper();
Db_helper.Insert(new historyTableSQlite(
));
}
}
I followed the following post but still struglling
http://bsubramanyamraju.blogspot.com/2014/08/windowsphone-8-sqlite-storing-data-in.html
Thank you for your help in advance