I just want to develop an application that can scan barcode and I also just learned to develop the application. Well the problem dan i'm confusing is, how do the results of the scan barcode send data and match the data then appear like "User Registered".
I use the library from ZXING and RETROFIT,
here is my coding:
public class ScanQRCodeActivity extends AppCompatActivity implements ZXingScannerView.ResultHandler {
private ZXingScannerView mScannerView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_scan_qrcode);
mScannerView = new ZXingScannerView(this);
setContentView(mScannerView);
}
#Override
protected void onResume() {
super.onResume();
mScannerView.setResultHandler(this);
mScannerView.startCamera();
}
#Override
protected void onPause() {
super.onPause();
mScannerView.stopCamera();
}
#Override
public void handleResult(Result rawresult) {
if (rawresult == postData()) {
// i must write what?
}
Log.v("TAG", rawresult.getText());
Log.v("TAG", rawresult.getBarcodeFormat().toString());
final AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Hasil Scan");
builder.setMessage(rawresult.getText());
builder.setNeutralButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.cancel();
}
});
builder.create();
builder.show();
mScannerView.resumeCameraPreview(this);
}
And my model had 2 like this:
public class DataRegisteredIn {
#SerializedName("data")
#Expose
private RegisteredIn data;
#SerializedName("status")
#Expose
private String status;
public RegisteredIn getData() {
return data;
}
public void setData(RegisteredIn data) {
this.data = data;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
}
and this :
public class RegisteredIn {
#SerializedName("participants_id")
#Expose
private Integer participantsId;
#SerializedName("registration_number")
#Expose
private String registrationNumber;
#SerializedName("title_name")
#Expose
private String titleName;
#SerializedName("call_badge_name")
#Expose
private String callBadgeName;
#SerializedName("family_name")
#Expose
private String familyName;
#SerializedName("first_name")
#Expose
private String firstName;
#SerializedName("last_title")
#Expose
private String lastTitle;
#SerializedName("event_meals_id")
#Expose
private Integer eventMealsId;
#SerializedName("place")
#Expose
private String place;
#SerializedName("item_name")
#Expose
private String itemName;
public Integer getParticipantsId() {
return participantsId;
}
public void setParticipantsId(Integer participantsId) {
this.participantsId = participantsId;
}
public String getRegistrationNumber() {
return registrationNumber;
}
public void setRegistrationNumber(String registrationNumber) {
this.registrationNumber = registrationNumber;
}
public String getTitleName() {
return titleName;
}
public void setTitleName(String titleName) {
this.titleName = titleName;
}
public String getCallBadgeName() {
return callBadgeName;
}
public void setCallBadgeName(String callBadgeName) {
this.callBadgeName = callBadgeName;
}
public String getFamilyName() {
return familyName;
}
public void setFamilyName(String familyName) {
this.familyName = familyName;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastTitle() {
return lastTitle;
}
public void setLastTitle(String lastTitle) {
this.lastTitle = lastTitle;
}
public Integer getEventMealsId() {
return eventMealsId;
}
public void setEventMealsId(Integer eventMealsId) {
this.eventMealsId = eventMealsId;
}
public String getPlace() {
return place;
}
public void setPlace(String place) {
this.place = place;
}
public String getItemName() {
return itemName;
}
public void setItemName(String itemName) {
this.itemName = itemName;
}
}
This is also the first time I ask, so for example there is something I need to add let me clear, please tell me clearly because honestly I am very beginner.
thank you
Updated
this is a little picture what I want to make, in the picture to the left it is my application that can only get the value of the barcode but like the picture is the right one that I want, so like the value of the barcode is translated into a shape like the picture in right.
Related
I am again trying to use TMBD api. I am using a recyclerview to map the data into a list.But the response I am getting from the retrofit response is null.
Main Activity:
public class MainActivity extends AppCompatActivity {
public final static String BASE_URL="https://api.themoviedb.org";
public final static String apiKey="<ApiKey>";
public final static String language="en-US";
public final static String TAG="tag";
#BindView(R.id.recyclerView)
RecyclerView movieList;
DisplayAdapter adapter;
MovieResponse result;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButterKnife.bind(this);
Retrofit retrofit=new Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
ApiInterface apiInterface=retrofit.create(ApiInterface.class);
apiInterface.getMovies(apiKey,language,1)
.enqueue(new Callback<MovieResponse>() {
#Override
public void onResponse(Call<MovieResponse> call, Response<MovieResponse> response) {
if(response.isSuccessful())
{
result=response.body();
Log.e(TAG, "onCreate: "+result );
}
}
#Override
public void onFailure(Call<MovieResponse> call, Throwable t) { }
});
Log.e(TAG, "onCreate: "+result );
adapter=new DisplayAdapter(getApplicationContext(),result);
RecyclerView.LayoutManager layoutManager=new GridLayoutManager(getApplicationContext(),1);
movieList.setLayoutManager(layoutManager);
movieList.setAdapter(adapter);
}
}
Response Class:
public class MovieResponse {
private int page;
private int total_results;
private int total_pages;
private List<ResultsBean> results;
public int getPage() {
return page;
}
public void setPage(int page) {
this.page = page;
}
public int getTotal_results() {
return total_results;
}
public void setTotal_results(int total_results) {
this.total_results = total_results;
}
public int getTotal_pages() {
return total_pages;
}
public void setTotal_pages(int total_pages) {
this.total_pages = total_pages;
}
public List<ResultsBean> getResults() {
return results;
}
public void setResults(List<ResultsBean> results) {
this.results = results;
}
public static class ResultsBean {
private double popularity;
private int vote_count;
private boolean video;
private String poster_path;
private int id;
private boolean adult;
private String backdrop_path;
private String original_language;
private String original_title;
private String title;
private double vote_average;
private String overview;
private String release_date;
private List<Integer> genre_ids;
public double getPopularity() {
return popularity;
}
public void setPopularity(double popularity) {
this.popularity = popularity;
}
public int getVote_count() {
return vote_count;
}
public void setVote_count(int vote_count) {
this.vote_count = vote_count;
}
public boolean isVideo() {
return video;
}
public void setVideo(boolean video) {
this.video = video;
}
public String getPoster_path() {
return poster_path;
}
public void setPoster_path(String poster_path) {
this.poster_path = poster_path;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public boolean isAdult() {
return adult;
}
public void setAdult(boolean adult) {
this.adult = adult;
}
public String getBackdrop_path() {
return backdrop_path;
}
public void setBackdrop_path(String backdrop_path) {
this.backdrop_path = backdrop_path;
}
public String getOriginal_language() {
return original_language;
}
public void setOriginal_language(String original_language) {
this.original_language = original_language;
}
public String getOriginal_title() {
return original_title;
}
public void setOriginal_title(String original_title) {
this.original_title = original_title;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public double getVote_average() {
return vote_average;
}
public void setVote_average(double vote_average) {
this.vote_average = vote_average;
}
public String getOverview() {
return overview;
}
public void setOverview(String overview) {
this.overview = overview;
}
public String getRelease_date() {
return release_date;
}
public void setRelease_date(String release_date) {
this.release_date = release_date;
}
public List<Integer> getGenre_ids() {
return genre_ids;
}
public void setGenre_ids(List<Integer> genre_ids) {
this.genre_ids = genre_ids;
}
}
}
The Api Interface:
public interface ApiInterface {
#GET("3/movie/popular")
Call<MovieResponse> getMovies(
#Query("api_key") String apiKey,
#Query("language")String language,
#Query("page")int page
);
}
I am learning the concept of api calling. I dont understand why the response is null. If anybody could explai the reason it will be very helpfull.
This can be several things from what you posted.
It can be that the Java models don't match the JSON. You'd have to double check this.
It can be that you're getting an error, in which case retrofit does not have a response.body(), but rather a response.errorBody(). You can check this by debugging and checking response.erroeBody().string().
Or it could to be a classic example of asynch behaviour being handled like it's synchronous.
adapter=new DisplayAdapter(getApplicationContext(),result);
In this case you're using result, but it's assigned inside the retrofit callback which most likely finished after you create the adapter and hence result is still null.
You can move the creation of the adapter and setting it to the list inside the callback:
public void onResponse(Call<MovieResponse> call, Response<MovieResponse> response) {
if(response.isSuccessful())
{
result=response.body();
Log.e(TAG, "onCreate: "+result );
adapter=new DisplayAdapter(getApplicationContext(),result);
RecyclerView.LayoutManager layoutManager=new GridLayoutManager(getApplicationContext(),1);
movieList.setLayoutManager(layoutManager);
movieList.setAdapter(adapter);
}
}
These are the only things that come to mind. Hope it helps.
EDIT
After taking a look at the github project, the only thing I found that is crashing the app is inside DisplayAdapter.java line 44:
holder.movieRating.setText((int) listOfMovies.getResults().get(position).getVote_average());
When you call setText that accepts an int you are in fact calling a method that will look in your strings.xml for a string with the id equal to the int you passed in. In this case, you are passing the vote average as an int. I'm guessing that what you want is to display the vote average, so the solution is to convert the double vote average to a string. This can easily be achieved with String.valueOf:
holder.movieRating.setText(String.valueOf(listOfMovies.getResults().get(position).getVote_average()));
Perhaps the most interesting bit is in the log message android.content.res.Resources$NotFoundException: String resource ID #0x7. This is thrown when trying to look for the string that doesn't exist.
my problem is when I scan Qr code, I want to get the class file variables
and send via btnSearch button to an another activity. plz help me how to do it? sorry for poor English
This is My class file
public class UploadDataGetter {
#SerializedName("record_id")
private int id;
#SerializedName("full_name")
private static String name;
#SerializedName("full_address")
private String address;
#SerializedName("contact")
private String contact;
#SerializedName("dilivery_place")
private String dplace;
#SerializedName("dilivery_place")
private String fdetails;
#SerializedName("no_of_normal")
private int noOfNormal;
#SerializedName("no_of_classified")
private int noOfClassified;
#SerializedName("no_of_cds")
private int noOfCds;
public UploadDataGetter(
//constuctor's para
int record_id,
String full_name,
String full_address,
String contact_number,
String dilivery_place ,
String further_details,
int no_of_normal,
int no_of_classified,
int no_of_cds
)
{
id = record_id;
name = full_name;
address = full_address;
contact = contact_number;
dplace = dilivery_place;
fdetails = further_details;
noOfNormal = no_of_normal;
noOfClassified= no_of_classified;
noOfCds = no_of_cds;
String img_collector ;
String dilivery_status ;
double geo_long;
double geo_lat;
}
public
int getId() {
return id;
}
public
void setId(int id) {
this.id = id;
}
public static
String getName() {
return name;
}
public
void setName(String name) {
this.name = name;
}
public
String getAddress() {
return address;
}
public
void setAddress(String address) {
this.address = address;
}
public
String getContact() {
return contact;
}
public
void setContact(String contact) {
this.contact = contact;
}
public
String getDplace() {
return dplace;
}
public
void setDplace(String dplace) {
this.dplace = dplace;
}
public
String getFdetails() {
return fdetails;
}
public
void setFdetails(String fdetails) {
this.fdetails = fdetails;
}
public
int getNoOfNormal() {
return noOfNormal;
}
public
void setNoOfNormal(int noOfNormal) {
this.noOfNormal = noOfNormal;
}
public
int getNoOfClassified() {
return noOfClassified;
}
public
void setNoOfClassified(int noOfClassified) {
this.noOfClassified = noOfClassified;
}
public
int getNoOfCds() {
return noOfCds;
}
public
void setNoOfCds(int noOfCds) {
this.noOfCds = noOfCds;
}
this is my Qr Activity,
public class QrActivity extends AppCompatActivity {
public static UploadDataGetter id;
public static UploadDataGetter name;
public static UploadDataGetter address;
public static UploadDataGetter dplace;
public static UploadDataGetter fdetails;
public static UploadDataGetter noOfNormal;
public static UploadDataGetter noOfClassified;
public static UploadDataGetter noOfCds;
public static UploadDataGetter img_collector;
public static UploadDataGetter dilivery_status;
/**
* QR code declaration
*/
Button btnscan, btnSearch;
TextView lblSearch;
TextView ID;
TextView DPlace;
TextView Address;
TextView name;
TextView contact;
private Object uploadDataGetter;
private String result;
#Override
protected
void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_qr);
btnscan = (Button) findViewById(R.id.btnscan);
btnscan.setClickable(false);
btnSearch = (Button) findViewById(R.id.btnSearch);
btnSearch.setClickable(false);
lblSearch = (TextView) findViewById(R.id.lblSearch);
final Activity activity = this;
btnscan.setOnClickListener(new View.OnClickListener() {
#Override
public
void onClick(View v) {
btnscan.setClickable(true);
IntentIntegrator integrator = new IntentIntegrator(activity);
integrator.setDesiredBarcodeFormats(IntentIntegrator.QR_CODE_TYPES);
integrator.setPrompt("Scan");
integrator.setCameraId(0);
integrator.setBeepEnabled(false);
integrator.setBarcodeImageEnabled(false);
integrator.initiateScan();
}
});
//call the class var
if (this.getIntent().getAction().equals("moveData"))
moveData();
}
private void moveData() {
String id = uploadDataGetter.toString();
String name = uploadDataGetter.toString();
String address = uploadDataGetter.toString();
String dplace = uploadDataGetter.toString();
String noOfNormal= uploadDataGetter.toString();
String noOfClassified = uploadDataGetter.toString();
String noOfCds = uploadDataGetter.toString();
//this is for Calling class file
}
#Override
protected
void onActivityResult(int requestCode, int resultCode, Intent data) {
IntentResult result = IntentIntegrator.parseActivityResult(requestCode, resultCode, data);
if (result != null) {
if (result.getContents() == null) {
Toast.makeText(this, "You cancelled the scanning", Toast.LENGTH_SHORT).show();
} else {
/**
* Qr code result
* */
lblSearch.setText(result.getContents());
// Toast.makeText(this, result.getContents(), Toast.LENGTH_SHORT).show();
}
} else {
super.onActivityResult(requestCode, resultCode, data);
}
// "Go to Second Activity" button click
View.OnClickListener listener = new View.OnClickListener() {
#Override
public
void onClick(View v) {
btnSearch.setClickable(true);
Intent myIntent= new Intent(QrActivity.this, DistributionDetails.class);
myIntent.setAction("moveData");
startActivity(myIntent);
}
};
btnscan.setOnClickListener(listener);
btnSearch.setOnClickListener(listener);
}
public
void getResults(View view) {
}
}
Replace your class with this
public class UploadDataGetter implements Serializable {
#SerializedName("record_id")
private int id;
#SerializedName("full_name")
private String name;
#SerializedName("full_address")
private String address;
#SerializedName("contact")
private String contact;
#SerializedName("dilivery_place")
private String dplace;
#SerializedName("dilivery_place")
private String fdetails;
#SerializedName("no_of_normal")
private int noOfNormal;
#SerializedName("no_of_classified")
private int noOfClassified;
#SerializedName("no_of_cds")
private int noOfCds;
public UploadDataGetter(
//constuctor's para
int record_id,
String full_name,
String full_address,
String contact_number,
String dilivery_place,
String further_details,
int no_of_normal,
int no_of_classified,
int no_of_cds
) {
id = record_id;
name = full_name;
address = full_address;
contact = contact_number;
dplace = dilivery_place;
fdetails = further_details;
noOfNormal = no_of_normal;
noOfClassified = no_of_classified;
noOfCds = no_of_cds;
String img_collector;
String dilivery_status;
double geo_long;
double geo_lat;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getContact() {
return contact;
}
public void setContact(String contact) {
this.contact = contact;
}
public String getDplace() {
return dplace;
}
public void setDplace(String dplace) {
this.dplace = dplace;
}
public String getFdetails() {
return fdetails;
}
public void setFdetails(String fdetails) {
this.fdetails = fdetails;
}
public int getNoOfNormal() {
return noOfNormal;
}
public void setNoOfNormal(int noOfNormal) {
this.noOfNormal = noOfNormal;
}
public int getNoOfClassified() {
return noOfClassified;
}
public void setNoOfClassified(int noOfClassified) {
this.noOfClassified = noOfClassified;
}
public int getNoOfCds() {
return noOfCds;
}
public void setNoOfCds(int noOfCds) {
this.noOfCds = noOfCds;
}
}
now send this to new activity in intent like this
Intent intent=new Intent(this, NewActivity.class);
int.putExtra("data", YOUR_UPDATE_DATA_GETTER_OBJECT);
Now get the object in the new activity like this
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
public class NewActivity extends Activity {
private UploadDataGetter dataGetter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent intent=getIntent();
if(intent.hasExtra("data")){
dataGetter= (UploadDataGetter) intent.getSerializableExtra("data");
Log.d("NewActivity","ID: "+dataGetter.getId());
}
}
}
API File
METHOD : GET
OUTPUT:
{
"status": true,
"message": "Subjects found.",
"data": {
"subjects": [
{
"subj_id": "2",
"name": "Maths",
"img": "Math.jpg"
},
{
"subj_id": "1",
"name": "Physics",
"img": "physics.png"
}
],
"total": 2
}
}
Model Class
public class SubjectTopics
{
#SerializedName("status")
#Expose
private Boolean status;
#SerializedName("message")
#Expose
private String message;
#SerializedName("data")
#Expose
private Data data;
public Boolean getStatus() {
return status;
}
public void setStatus(Boolean status) {
this.status = status;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public Data getData() {
return data;
}
public void setData(Data data) {
this.data = data;
}
}
public class Data {
#SerializedName("subjects")
#Expose
private List<Subjects> subjects = null;
#SerializedName("total")
#Expose
private Integer total;
public List<Subjects> getSubjects() {
return subjects;
}
public void setSubjects(List<Subjects> subjects) {
this.subjects = subjects;
}
public Integer getTotal() {
return total;
}
public void setTotal(Integer total) {
this.total = total;
}
}
public class Subjects {
#SerializedName("subj_id")
#Expose
private String subjId;
#SerializedName("name")
#Expose
private String name;
#SerializedName("img")
#Expose
private String img;
public String getSubjId() {
return subjId;
}
public void setSubjId(String subjId) {
this.subjId = subjId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getImg() {
return img;
}
public void setImg(String img) {
this.img = img;
}
}
My Adapter
public class MoviesAdapter extends RecyclerView.Adapter<MoviesAdapter.MovieViewHolder> {
private List<Subjects> movies;
private int rowLayout;
private Context context;
public static class MovieViewHolder extends RecyclerView.ViewHolder {
private TextView subjectName;
private TextView ID;
private ImageView ImageV;
private RelativeLayout relativeClick;
public MovieViewHolder(View v) {
super(v);
subjectName = (TextView) itemView.findViewById(R.id.textView);
relativeClick = (RelativeLayout) itemView.findViewById(R.id.relative_click);
ImageV = (ImageView) itemView.findViewById(R.id.imageView);
}
}
public MoviesAdapter(List<Subjects> movies, int rowLayout, Context context) {
this.movies = movies;
this.rowLayout = rowLayout;
this.context = context;
}
#Override
public MoviesAdapter.MovieViewHolder onCreateViewHolder(ViewGroup parent,
int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(rowLayout, parent, false);
return new MoviesAdapter.MovieViewHolder(view);
}
#Override
public void onBindViewHolder(MoviesAdapter.MovieViewHolder holder, final int position) {
holder.subjectName.setText(movies.get(position).getName());
holder.relativeClick.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(context, SubjectTopicList.class);
intent.putExtra("subject_id", movies.get(position).getSubjId());
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent);
}
});
Picasso.with(context)
.load(movies.get(position).getImg())
.placeholder(R.drawable.load)
.into(holder.ImageV);
}
#Override
public int getItemCount() {
return movies.size();
}
}
Activity
private void getSubjects() {
progressBar.setVisibility(View.VISIBLE);
Call<SubjectTopics> getProductsModelClassCall = webService.getSubjects();
getProductsModelClassCall.enqueue(new Callback<SubjectTopics>() {
#Override
public void onResponse(Call<SubjectTopics> call, Response<SubjectTopics> response) {
if (response.isSuccessful()) {
List<Subjects> movies = response.body().getData().getSubjects();
MoviesAdapter newAd=new MoviesAdapter(movies, R.layout.unit_test_row, getApplicationContext());
recyclerView.setAdapter(newAd);
} else {
APIError apiError = ErrorUtils.parseError(response);
Toast.makeText(UnitTestSubjects.this, ""+apiError, Toast.LENGTH_SHORT).show();
}
if (progressBar.isEnabled())
progressBar.setVisibility(View.INVISIBLE);
progressBar.setVisibility(View.GONE);
}
#Override
public void onFailure(Call<SubjectTopics> call, Throwable t) {
Toast.makeText(UnitTestSubjects.this, "Please Try Again", Toast.LENGTH_SHORT).show();
if (progressBar.isEnabled())
progressBar.setVisibility(View.INVISIBLE);
progressBar.setVisibility(View.GONE);
}
});
}
Retrofit Code
public class ServiceGenerator {
private final static String TAG = "ApiCall";
public static Retrofit getRetrofit(){
HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
// set your desired log level
logging.setLevel(HttpLoggingInterceptor.Level.BODY);
OkHttpClient.Builder httpClient = new OkHttpClient.Builder();
// add your other interceptors …
// add logging as last interceptor
httpClient.addInterceptor(logging); // <-- this is the important line!
httpClient.connectTimeout(10, TimeUnit.SECONDS).readTimeout(14, TimeUnit.SECONDS).writeTimeout(16, TimeUnit.SECONDS);
Gson gson = new GsonBuilder()
.setDateFormat("yyyy-MM-dd'T'HH:mm:ssZ")
.create();
return new Retrofit.Builder()
.baseUrl(WebServices.BASE_URL)
.client(httpClient.build())
.addConverterFactory(GsonConverterFactory.create(gson))
.build();
}
public static Api getApi(){
return getRetrofit().create(Api.class);
}
}
After calling API's using Retrofit 2.0, Unable to get any response and getting this error:
Failure:
retrofit2.ExecutorCallAdapterFactory$ExecutorCallbackCall#5321
every-time after callback it directly coming out from the method
I have tried all possible ways to solve but not able to find any solution regarding this.
I think this is internal retrofit error or in the pojo class I guess. Please help!
I need to Show Registration Form With Spinner Using Fragments and get the data using Json
This is kind of register form. At the bottom we have change language button which will reset the form and will be shown in arabic / english.
[
{
"Id":1,
"TitleEN":"Kuwait",
"TitleAR":"الكويت",
"CurrencyId":1,
"CurrencyEN":"Kuwaiti Dinar",
"CurrencyAR":"دينار كويتى",
"CodeEN":"KWD",
"CodeAR":"د.ك",
"Code":"965"
},
{
"Id":2,
"TitleEN":"Emirates",
"TitleAR":"الإمارات",
"CurrencyId":2,
"CurrencyEN":"Emirati Dirham",
"CurrencyAR":"درهم إماراتي",
"CodeEN":"AED",
"CodeAR":"درهم",
"Code":"971"
},
{
"Id":3,
"TitleEN":"Saudi Arabia",
"TitleAR":"السعودية",
"CurrencyId":3,
"CurrencyEN":"Saudi Riyal",
"CurrencyAR":"ريال سعودى",
"CodeEN":"SAR",
"CodeAR":"ر.س",
"Code":"966"
}
]
Note.I assume you have followed the first 3 steps from this [question][1]
and will start from the following
Step 1
Add spinner in xml
<Spinner
android:id="#+id/spinner"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:prompt="#string/spinner_title" />
Step 2
In ApiInterface Class add the following code
#GET("/app/app.asmx/GetCountries")
Call<List<Country>> getCountry();
Step 3
Create new model class by name Country
public class Country {
#SerializedName("Id")
#Expose
private Integer id;
#SerializedName("TitleEN")
#Expose
private String titleEN;
#SerializedName("TitleAR")
#Expose
private String titleAR;
#SerializedName("CurrencyId")
#Expose
private Integer currencyId;
#SerializedName("CurrencyEN")
#Expose
private String currencyEN;
#SerializedName("CurrencyAR")
#Expose
private String currencyAR;
#SerializedName("CodeEN")
#Expose
private String codeEN;
#SerializedName("CodeAR")
#Expose
private String codeAR;
#SerializedName("Code")
#Expose
private String code;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getTitleEN() {
return titleEN;
}
public void setTitleEN(String titleEN) {
this.titleEN = titleEN;
}
public String getTitleAR() {
return titleAR;
}
public void setTitleAR(String titleAR) {
this.titleAR = titleAR;
}
public Integer getCurrencyId() {
return currencyId;
}
public void setCurrencyId(Integer currencyId) {
this.currencyId = currencyId;
}
public String getCurrencyEN() {
return currencyEN;
}
public void setCurrencyEN(String currencyEN) {
this.currencyEN = currencyEN;
}
public String getCurrencyAR() {
return currencyAR;
}
public void setCurrencyAR(String currencyAR) {
this.currencyAR = currencyAR;
}
public String getCodeEN() {
return codeEN;
}
public void setCodeEN(String codeEN) {
this.codeEN = codeEN;
}
public String getCodeAR() {
return codeAR;
}
public void setCodeAR(String codeAR) {
this.codeAR = codeAR;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
}
Step 4
find view in activity or fragment and add call the request and get response and add the response in spinner adapter.Initialize a string list out side the onCreate method
List<String> codes = new ArrayList<String>();
APIInterface apiInterfacePages;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Spinner spinner = (Spinner) findViewById(R.id.spinner);
apiInterfacePages= PageApiClient.getRetrofit().create(APIInterface.class);
Call<List<Country>> getCountry = apiInterfacePages.getCountry();
getCountry.enqueue(new Callback<List<Country>>() {
#Override
public void onResponse(Call<List<Country>> call, Response<List<Country>> response) {
countryList = response.body();
for (int i = 0; i < countryList.size(); i++) {
codes.add(countryList.get(i).getCode());
}
ArrayAdapter<String> adapterTime = new ArrayAdapter<>(MainActivity.this, android.R.layout.simple_spinner_dropdown_item, codes);
spinner.setAdapter(adapterTime);
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
Toast.makeText(MainActivity.this, "" + countryList.get(i).getTitleEN(), Toast.LENGTH_SHORT).show();
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
}
#Override
public void onFailure(Call<List<Country>> call, Throwable t) {
}
});
}
I am trying to pass Parcelable object from the A activity to B activity via intent:
Intent intent = new Intent (A.this, B.class);
intent.putExtra ("post", mypost); // where post implements Parcelable`
In B Activity I got the post object in this way:
Post myPost = getIntent().getParcelableExtra("post");
In B activity myPost object fields are mixed, e.g. I have postText and postDate fields in Post model, the values of this fields in B activity are mixed.
Why this can happen? My model class look likes the following:
public class Post implements Parcelable, Serializable {
private static final long serialVersionUID = 2L;
#SerializedName("author")
private User author;
#SerializedName("comments_count")
private String commentsCount;
#SerializedName("image")
private String imageToPost;
#SerializedName("parent_key")
private String parentKey;
#SerializedName("created_date")
private String postDate;
#SerializedName("id")
private String postId;
#SerializedName("text")
private String postText;
#SerializedName("title")
private String postTitle;
#SerializedName("shared_post_id")
private String sharedPostId;
#SerializedName("url")
private String urlToPost;
#SerializedName("video")
private String videoToPost;
public Post() {
}
public Post(Parcel in) {
author = (User) in.readValue(getClass().getClassLoader());
commentsCount = in.readString();
imageToPost = in.readString();
parentKey = in.readString();
postDate = in.readString();
postId = in.readString();
postText = in.readString();
postTitle = in.readString();
sharedPostId = in.readString();
urlToPost = in.readString();
videoToPost = in.readString();
}
public static final Creator<Post> CREATOR = new Creator<Post>() {
#Override
public Post createFromParcel(Parcel in) {
return new Post(in);
}
#Override
public Post[] newArray(int size) {
return new Post[size];
}
};
public User getAuthor() {
return author;
}
public void setAuthor(User author) {
this.author = author;
}
public String getPostDate() {
return postDate;
}
public void setPostDate(String postDate) {
this.postDate = postDate;
}
public String getPostTitle() {
return postTitle;
}
public void setPostTitle(String postTitle) {
this.postTitle = postTitle;
}
public String getPostText() {
return postText;
}
public void setPostText(String postText) {
this.postText = postText;
}
public String getPostId() {
return postId;
}
public void setPostId(String postId) {
this.postId = postId;
}
public String getUrlToPost() {
return urlToPost;
}
public void setUrlToPost(String urlToPost) {
this.urlToPost = urlToPost;
}
public String getImageToPost() {
return imageToPost;
}
public void setImageToPost(String imageToPost) {
this.imageToPost = imageToPost;
}
public String getVideoToPost() {
return videoToPost;
}
public void setVideoToPost(String videoToPost) {
this.videoToPost = videoToPost;
}
public String getParentKey() {
return parentKey;
}
public void setParentKey(String parentKey) {
this.parentKey = parentKey;
}
public String getCommentsCount() {
return commentsCount;
}
public void setCommentsCount(String commentsCount) {
this.commentsCount = commentsCount;
}
public String getSharedPostId() {
return sharedPostId;
}
public void setSharedPostId(String sharedPostId) {
this.sharedPostId = sharedPostId;
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeValue(author);
dest.writeString(commentsCount);
dest.writeString(imageToPost);
dest.writeString(parentKey);
dest.writeString(postDate);
dest.writeString(postId);
dest.writeString(postText);
dest.writeString(postTitle);
dest.writeString(sharedPostId);
dest.writeString(urlToPost);
dest.writeString(videoToPost);
}
}
Add describeContents and writeToParcel.
Examples:
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(name);
dest.writeString(email);
dest.writeString(pass);
dest.writeFloat(amountPaid);
dest.writeString(url);
dest.writeInt(age);
}