JSON using loopj android listview failed - java

I'm doing a Movie Project, I want to use parsing JSON to listview, I'm using loopj library, I already implement the code, but it does not work, the listview is still empty, I don't know where the error this is my code, I will show the item class first,
public class MovieItem {
private int id;
private String title;
private String description;
private String rate;
public MovieItem(JSONObject object){
try {
String title = object.getJSONArray("results").getJSONObject(0).getString("title");
String description = object.getJSONArray("results").getJSONObject(0).getString("overview");
double movieRatet = object.getJSONArray("results").getJSONObject(0).getDouble("vote_average");
String movieRate = new DecimalFormat("#.#").format(movieRatet);
this.title = title;
this.description = description;
this.rate = movieRate;
}
catch (Exception e){
e.printStackTrace();
}
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getRate() {
return rate;
}
public void setRate(String rate) {
this.rate = rate;
}
}
next, the loader is
public ArrayList<MovieItem> loadInBackground() {
Log.d("LOAD BG","1");
SyncHttpClient client = new SyncHttpClient();
final ArrayList<MovieItem> movieItemses = new ArrayList<>();
final String url = "https://api.themoviedb.org/3/search/movie?api_key="+API_KEY+"&language=en-US&query=annabelle";
client.get(url, new AsyncHttpResponseHandler() {
#Override
public void onStart() {
super.onStart();
setUseSynchronousMode(true);
}
#Override
public void onSuccess(int statusCode, Header[] headers,
byte[] responseBody) {
try {
String result = new String(responseBody);
JSONObject responseObject = new JSONObject(result);
JSONArray list = responseObject.getJSONArray("list");
for (int i = 0 ; i < list.length() ; i++){
JSONObject movie = list.getJSONObject(i);
MovieItem movieItems = new MovieItem(movie);
movieItemses.add(movieItems);
}
Log.d("REQUEST SUCCESS","1");
}catch (Exception e){
e.printStackTrace();
Log.d("REQUEST FAILED","1");
}
}
#Override
public void onFailure(int statusCode, Header[] headers,
byte[] responseBody, Throwable error) {
}
});
for (int i = 0 ; i< movieItemses.size() ; i++){
Log.d("Title",movieItemses.get(i).getTitle());
}
Log.d("BEFORE RETURN","1");
return movieItemses;
}
protected void onReleaseResources(ArrayList<MovieItem> data) {
//nothing to do.
}
pls someone help me, I already fix this problem, but nothing different
FYI I'm using API from themoviedb

Related

how to upload file from retrofit android java

am using retrofit for insert data to my webservice, I have made it before but without uploading the image and the insert is successful, the input field through the model class not in interface,how I add an input field fot uploading files through the model so that it can be sent to my web services storage folder?
I have tried but failed please help
for my insert in activity
btnsubmit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String tanggal = textdate.getText().toString();
SimpleDateFormat formatter1=new SimpleDateFormat("dd/MM/yyyy");
Date date1= null;
try {
date1 = formatter1.parse(tanggal);
} catch (ParseException e) {
e.printStackTrace();
}
SwabtestModel sw = new SwabtestModel();
sw.sethasil(texthasil.getText().toString());
sw.settanggal(date1);
sw.settempat(texttempat.getText().toString());
sw.setuserid(Integer.valueOf(txtuserid.getText().toString()));
sw.setFile_name(new File(txturi.getText().toString()));
save(sw);
}
});
public void save(SwabtestModel sw){
Call<SwabtestModel> call = swabtestService.addswab(sw);
call.enqueue(new Callback<SwabtestModel>() {
#Override
public void onResponse(Call<SwabtestModel> call, Response<SwabtestModel> response) {
if(response.isSuccessful()){
String status = response.body().getStatus();
Toast.makeText(SwabtestActivity.this, status, Toast.LENGTH_LONG).show(); }
}
#Override
public void onFailure(Call<SwabtestModel> call, Throwable t) {
Log.e("ERROR: ", t.getMessage());
}
});
}
for my file chooser
public void onActivityResult(int request_code, int result_code, Intent data){
super.onActivityResult(request_code,result_code,data);
if(request_code==request_code && result_code== Activity.RESULT_OK){
if(data==null){
return;
}
uri= data.getData();
filePath = uri.getPath();
txturi.setText(filePath);
}
}
public void openfilechooser(){
Intent intent= new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("*/*");
startActivityForResult(intent,request_code);
}
for my model class
public class SwabtestModel {
#SerializedName("hasil")
#Expose
private String hasil;
#SerializedName("tanggal")
#Expose
private Date tanggal;
#SerializedName("tempat")
#Expose
private String tempat;
#SerializedName("file_name")
#Expose
private File file_name;
#SerializedName("user_id")
#Expose
private Integer user_id;
String data;
String status;
public SwabtestModel(String hasil, Date tanggal, String tempat){
this.hasil = hasil;
this.tanggal = tanggal;
this.tempat = tempat;
}
public void sethasil(String hasil) {
this.hasil = hasil;
}
public String gethasil(){
return hasil;
}
public void settanggal(Date tanggal) {
this.tanggal = tanggal;
}
public Date gettanggal(){
return tanggal;
}
public void settempat(String tempat) {
this.tempat = tempat;
}
public String gettempat(){
return tempat;
}
public void setuserid(Integer user_id) {
this.user_id = user_id;
}
public Integer getuserid(){
return user_id;
}
public void setFile_name( File file_name) {
this.file_name =file_name ;
}
public File getfilename(){
return file_name;
}
public String getData() {
return data;
}
public String getStatus() {
return status;
}
}
my interface
public interface swabtestService
{
#GET("hasil-antigen-list")
Call<List<SwabtestModel>> getUsers();
#POST("insert-hantigen")
Call<SwabtestModel> addswab(#Body SwabtestModel swabtest);
}
To upload files you should use Multipart, Please refer to this post for example and please ping me if you have any queries https://stackoverflow.com/a/39953566
Take a data in list like #Part List<MultipartBody.Part> partFile
private List<MultipartBody.Part> getMapPartListSave(List<PojoAttachDocList> fields) {
List<MultipartBody.Part> mapPart = new ArrayList<>();
for (int i = 0; i < fields.size(); i++) {
**PojoAttachDocList** attachDoc = fields.get(i);
if (!attachDoc.isAttached() && attachDoc.getDocFile() != null && attachDoc.getDocFile().exists()
&& attachDoc.getDocFile().length() > 0) {
String fileParam = PARAMS_DOCUMENT + "[" + i + "]";
mapPart.add(MultipartBody.Part.createFormData(fileParam, attachDoc.getDocFile().getName(),
RequestBody.create(MediaType.parse("*/*"), attachDoc.getDocFile())));
}
}
return mapPart;
}
Convert it to MultipartBody

How to pass raw data in API request using Retrofit2 [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 3 years ago.
I am trying to call login API using Retrofit2.
But in onResponse i alwasy get null as response.
Login API endpoint
#FormUrlEncoded
#POST("/api/login/{mobile}")
Call<ResObj> userLogin( #Field("phoneNumber") String mobile );
And the API implementation
private void doLogin(final String mobile){
Call<ResObj> call = userService.login(mobile);
call.enqueue(new Callback<ResObj>() {
#Override
public void onResponse(Call<ResObj> call, Response<ResObj> response) {
ResObj resObj = response.body(); // here i am getting null response.body()
if(resObj.getMessage().equals("true")){
Intent intent = new Intent(Login.this, ListActivity.class);
intent.putExtra("mobile", mobile);
startActivity(intent);
} else{
Toast.makeText(Login.this, "Phone Number is incorrect!", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onFailure(Call<ResObj> call, Throwable t) {
Toast.makeText(Login.this, t.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
ResObj class:
public class ResObj {
private String message;
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}
I just want to know what causes the error and what are possible solutions.
UPDATE
POSTMAN
You are getting null response in your login API. It may be due to many reasons. You can check your API is working as expected or not using POSTMAN.
And inside your code, you can prevent this type of exception by checking OBJECT is null or not. like the following.
#Override
public void onResponse(Call<ResObj> call, Response<ResObj> response) {
ResObj resObj = response.body();
if(resObj != null){ // checking object is not null
if(resObj.getStatus()){
Intent intent = new Intent(Login.this, ListActivity.class);
intent.putExtra("mobile", mobile);
startActivity(intent);
} else{
Toast.makeText(Login.this, "Phone Number is incorrect!", Toast.LENGTH_SHORT).show();
}
}else{
// handle null response here.
}
}
Update:
According to your Response JSON, Your Model(ResObj) class should be like the following.
public class ResObj
{
private String date;
private String address;
private String accountName;
private String contactPerson;
private String timeOut;
private String problem;
private String srNo;
private String fieldEngineer;
private String joNo;
private String irNo;
private String designation;
private String email;
private String timeIn;
private String productType;
private boolean status;
private String contactNo;
public String getDate ()
{
return date;
}
public void setDate (String date)
{
this.date = date;
}
public String getAddress ()
{
return address;
}
public void setAddress (String address)
{
this.address = address;
}
public String getAccountName ()
{
return accountName;
}
public void setAccountName (String accountName)
{
this.accountName = accountName;
}
public String getContactPerson ()
{
return contactPerson;
}
public void setContactPerson (String contactPerson)
{
this.contactPerson = contactPerson;
}
public String getTimeOut ()
{
return timeOut;
}
public void setTimeOut (String timeOut)
{
this.timeOut = timeOut;
}
public String getProblem ()
{
return problem;
}
public void setProblem (String problem)
{
this.problem = problem;
}
public String getSrNo ()
{
return srNo;
}
public void setSrNo (String srNo)
{
this.srNo = srNo;
}
public String getFieldEngineer ()
{
return fieldEngineer;
}
public void setFieldEngineer (String fieldEngineer)
{
this.fieldEngineer = fieldEngineer;
}
public String getJoNo ()
{
return joNo;
}
public void setJoNo (String joNo)
{
this.joNo = joNo;
}
public String getIrNo ()
{
return irNo;
}
public void setIrNo (String irNo)
{
this.irNo = irNo;
}
public String getDesignation ()
{
return designation;
}
public void setDesignation (String designation)
{
this.designation = designation;
}
public String getEmail ()
{
return email;
}
public void setEmail (String email)
{
this.email = email;
}
public String getTimeIn ()
{
return timeIn;
}
public void setTimeIn (String timeIn)
{
this.timeIn = timeIn;
}
public String getProductType ()
{
return productType;
}
public void setProductType (String productType)
{
this.productType = productType;
}
public boolean getStatus ()
{
return status;
}
public void setStatus (boolean status)
{
this.status = status;
}
public String getContactNo ()
{
return contactNo;
}
public void setContactNo (String contactNo)
{
this.contactNo = contactNo;
}
}
You are passing parameter as raw data(according to your screen-shot). So your API endpoint would be like below.
#Headers("Content-Type: application/json")
#POST("/api/login")
Call<ResObj> userLogin(#Body JsonObject jsonObject);
And call your API like this
private void doLogin(final String mobile){
try {
JsonObject paramObject = new JsonObject();
paramObject.addProperty("mobile", mobile);
} catch (JSONException e) {
e.printStackTrace();
}
Call<ResObj> call = userService.login(paramObject);
call.enqueue(new Callback<ResObj>() {
//your rest of code
});
}
UPDATE-2:
To send object from one Activity to another using intent you have to make your model class Percelable. like this
// implements Parcelable
public class ResObj implements Parcelable {
// ...........your previous code here
// just simply add the following methods
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(date);
dest.writeString(address);
dest.writeString(accountName);
dest.writeString(contactPerson);
dest.writeString(timeOut);
dest.writeString(problem);
dest.writeString(srNo);
dest.writeString(fieldEngineer);
dest.writeString(joNo);
dest.writeString(irNo);
dest.writeString(designation);
dest.writeString(email);
dest.writeString(timeIn);
dest.writeString(productType);
dest.writeByte((byte) (status ? 1 : 0));
dest.writeString(contactNo);
}
public static final Parcelable.Creator<ResObj> CREATOR
= new Parcelable.Creator<ResObj>() {
public ResObj createFromParcel(Parcel in) {
return new ResObj(in);
}
public ResObj[] newArray(int size) {
return new ResObj[size];
}
};
protected ResObj(Parcel in) {
date = in.readString();
address = in.readString();
accountName = in.readString();
contactPerson = in.readString();
timeOut = in.readString();
problem = in.readString();
srNo = in.readString();
fieldEngineer = in.readString();
joNo = in.readString();
irNo = in.readString();
designation = in.readString();
email = in.readString();
timeIn = in.readString();
productType = in.readString();
status = in.readByte() != 0;
contactNo = in.readString();
}
}
Now pass your object via intent like the following.
if(resObj != null){
if(resObj.getStatus()){
Intent intent = new Intent(Login.this, ListActivity.class);
intent.putExtra("your_key", resObj); // pass resObj and use same key to get data
startActivity(intent);
} else{
Toast.makeText(Login.this, "Phone Number is incorrect!", Toast.LENGTH_SHORT).show();
}
}
Get data from your ListActivity like this
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
final ResObj yourObject = getIntent().getParcelableExtra("your_key"); // make sure you use same key like data.
// Now you can use your data like that
yourEditText.setText(yourObject.getEmail());
}

Android Volley Convert JSONArray to ArrayList<MyObject>

I have JsonObject
JSON Object
I have method which return JSONArray. I want to pass first field and get only data array. And then cast it to my Array List. I will really appriciated for any suggestion from you.
void getUsersBeacons(){
type = new TypeToken<List<Beacon>>(){}.getType();
JSONArray myReq = new JSONArray(Request.Method.GET, Url + testId + Url2, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
try{
JSONArray buffArray = response.getJSONArray(2);
JSONArray bufJsonArray = response.getJSONArray(1);
beaconsList = converter.fromJson(bufJsonArray.toString(), type);
}catch (Exception e){
e.printStackTrace();
}
}
});
VolleySingleton.getInstance(getActivity().getApplicationContext()).addToRequestQueue(myReq);
}
Beacon class:
public class Beacon {
private Object idBeacon;
private String friendlyName;
private String imageUrl;
public Beacon(Object idBeacon, String friendlyName, String imageUrl) {
this.idBeacon = idBeacon;
this.friendlyName = friendlyName;
this.imageUrl = imageUrl;
}
public Object getIdBeacon() {
return idBeacon;
}
public void setIdBeacon(Object idBeacon) {
this.idBeacon = idBeacon;
}
public String getFriendlyName() {
return friendlyName;
}
public void setFriendlyName(String friendlyName) {
this.friendlyName = friendlyName;
}
public String getImageUrl() {
return imageUrl;
}
public void setImageUrl(String imageUrl) {
this.imageUrl = imageUrl;
}
}
If I understand correctly, you better pass in JSONArray instead of string and parse it's contents, like this:
public static List<Beacon> fromJson(JSONArray array)
{
ArrayList<Beacon> res = new ArrayList<>();
for (int i = 0; i < array.length(); ++i)
{
JSONObject beacon = array.getJSONObject(i);
res.add(new Beacon(beacon.getInt("beaconId"), beacon.getString("name"), beacon.getString("imageUrl"))));
}
return res;
}
UPD: in response to your comment, you must use Response.Listener<JSONObject> instead of Response.Listener<JSONArray>, and then do this:
public void onResponse(JSONObject response)
{
JSONArray array = response.getJSONArray("data");
converter.fromJson(array);
}

How to deserialize a JSON Object in a multidimensional array

I have this JSON data and I would like to deserialize it with Android to get it as an object to use in my class.
I get this folowing error :
Could not read JSON: Unrecognized field "card_details"
[
{
"id": "9",
"cat_id": "CAT-8584ce02f180b57a8c6d66570f696e02",
"app_id": "null",
"status": "1",
"lft": "1",
"rgt": "2",
"parent_cat_id": "0",
"added_date": "2017-01-12 12:41:29",
"last_edit_date": "2017-01-12 12:46:09",
"language_id": "0",
"category_id": "CAT-8584ce02f180b57a8c6d66570f696e02",
"name": "Sport",
"description": "This is sport category",
"image": "notitia/USR-70903638005256656/app-content/cat-img-da1161af03df255a989f8df5fc2e15bd.png",
"tags": "",
"custom_url": "sport",
"card_details": {
"nom_carte": "Pinacolada",
"prix": "5000",
"image": "notitia/USR-44043694343417880/app-content/e0fa7beb401e8fe77727f5a8241ff872.jpg",
"validity": "1"
}
}
]
Here is my AsyncTask to retrieve the data:
private class HttpRequestTaskCarte extends AsyncTask<Void,Void,Item[]> {
#Override
protected Item[] doInBackground(Void... params) {
try {
final String url = "http://domain.com/link.php?target=multi";
RestTemplate restTemplate = new RestTemplate();
restTemplate.getMessageConverters().add(new MappingJackson2HttpMessageConverter());
Item[] greeting = restTemplate.getForObject(url, Item[].class);
return greeting;
} catch (Exception e) {
//Toast.makeText(getActivity(), "Error Loading !", Toast.LENGTH_SHORT).show();
Log.e("MainActivity", e.getMessage(), e);
}
return null;
}
protected void onPreExecute(){
progressDialog = new ProgressDialog(getActivity(),
R.style.AppTheme_Dark_Dialog);
progressDialog.setIndeterminate(true);
progressDialog.setMessage("chargement des elements...");
progressDialog.show();
}
#Override
protected void onPostExecute(Item[] greeting) {
Log.d("okokok",""+greeting.length);
progressDialog.dismiss();
}
}
And here is the class that I am using to deserialize:
public class Item {
private List<card_details> carte;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getCat_id() {
return cat_id;
}
public void setCat_id(String cat_id) {
this.cat_id = cat_id;
}
public String getApp_id() {
return app_id;
}
public void setApp_id(String app_id) {
this.app_id = app_id;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getLft() {
return lft;
}
public void setLft(String lft) {
this.lft = lft;
}
public String getRgt() {
return rgt;
}
public void setRgt(String rgt) {
this.rgt = rgt;
}
public String getParent_cat_id() {
return parent_cat_id;
}
public void setParent_cat_id(String parent_cat_id) {
this.parent_cat_id = parent_cat_id;
}
public String getAdded_date() {
return added_date;
}
public void setAdded_date(String added_date) {
this.added_date = added_date;
}
public String getLast_edit_date() {
return last_edit_date;
}
public void setLast_edit_date(String last_edit_date) {
this.last_edit_date = last_edit_date;
}
public String getLanguage_id() {
return language_id;
}
public void setLanguage_id(String language_id) {
this.language_id = language_id;
}
public String getCategory_id() {
return category_id;
}
public void setCategory_id(String category_id) {
this.category_id = category_id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
public String getTags() {
return tags;
}
public void setTags(String tags) {
this.tags = tags;
}
public String getCustom_url() {
return custom_url;
}
public void setCustom_url(String custom_url) {
this.custom_url = custom_url;
}
public List<Detail_cartes> getCarte() {
return carte;
}
public void setCarte(List<Detail_cartes> carte) {
this.carte = carte;
}
public static class Detail_cartes{
private String nom_carte ;
private String prix ;
private String image ;
private String validity ;
}
}
JSONArray array=new JSONArray(your data);
JSONObject obj=array.getJSONObject(0);
JSONObject cardDetail=obj.getJSONObject("card_details");
Hii u can use the following code:
JSONArray jsonarray = new JSONArray(jsonStr);
for (int i = 0; i < jsonarray.length(); i++) {
JSONObject jsonobject = jsonarray.getJSONObject(i);
String name = jsonobject.getString("name");
String url = jsonobject.getString("url");
}

How to sort the string ArrayList?

I am parsing the JSON array successfully. But I have a String which has numbers. So I want to sort all the data according to the numbers. I had been checked so many examples but I couldn't implement them in my code.So please help me.
Here is my code. here the "count" is the, string threw which I want to sort the data.
a.java
#Override
protected Void doInBackground(Void... params) {
ServiceHandler serviceHandler = new ServiceHandler();
String jsonStr = serviceHandler.makeServiceCall(
JSONUrl.categoriesUrl, ServiceHandler.GET);
Log.d("Response Categories:", ">" + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
categoriesJSONArray = jsonObj
.getJSONArray(JSONUrl.TAG_DATA);
for (int i = 0; i < categoriesJSONArray.length(); i++) {
JSONObject c = categoriesJSONArray.getJSONObject(i);
GridViewItem gridCategoriesItem = new GridViewItem();
gridCategoriesItem.setSlug(c
.getString(JSONUrl.TAG_CATEGORIES_SLUG));
gridCategoriesItem.setImage(c
.getString(JSONUrl.TAG_CATEGORIES_IMAGE));
gridCategoriesItem.setCount(c
.getString(JSONUrl.TAG_CATEGORIES_COUNT));
mGridArrayCategories.add(gridCategoriesItem);
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.d("ServiceHandler", "Couldn't get any data from the url");
}
return null;
}
GridViewItem.java
public class GridViewItem {
String image;
String slug;
String count;
String name;
public GridViewItem() {
super();
}
public GridViewItem(String image, String slug, String count,
String name) {
super();
this.image = image;
this.slug = slug;
this.count = count;
this.name = name;
}
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
public String getSlug() {
return slug;
}
public void setSlug(String slug) {
this.slug = slug;
}
public String getCount() {
return count;
}
public void setCount(String count) {
this.count = count;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
Instead of using bubble sort which is o(n2).
You can use the native sort from the Collection class
example:
Collections.sort(mGridArrayCategories, new Comparator<GridViewItem>() {
public int compare(GridViewItem s, GridViewItem s2) {
return Integer.parseInt(s2.getCount()) - Integer.parseInt(s.getCount()); //this will sort your arrayList in decending order
}
});
You need to parse your string to int so it will be sorted according to the count
You can use Collection.sort().
for sorting any kind of ArrayLsit Object.
Collections.sort(listOfStringArrays,new Comparator<String[]>() {
public int compare(String[] strings, String[] otherStrings) {
return strings[1].compareTo(otherStrings[1]);
}
});

Categories

Resources