java.lang.NullPointerException on using Retrofit v2 Library - android

I am using Retrofit v2 library compile 'com.squareup.retrofit:retrofit:2.0.0-beta2' for making network requests .While posting data to server,i am getting null response .I am sending the JSON data to server.
1.MyAPI.java
public interface MyAPI {
#GET("{roomID}")
Call<List<Message>>loadMessages(#Path("roomID") String roomID);
#POST("almabay_oauth/authorize")
Call<Example>login(#Body String str);
}
2.UserLogin.java
public class UserLogin {
#SerializedName("email")
String email;
#SerializedName("password")
String password;
public UserLogin(String email, String password) {
this.email = email;
this.password = password;
}
public String toString() {
return "UserLogin {email =" + email + ",password = " + password + "}";
}
}
3.MainActivity.java
Retrofit retrofit1 = new Retrofit.Builder()
.baseUrl("http://phpstack-11819-25991-62288.cloudwaysapps.com/")
.addConverterFactory(GsonConverterFactory.create())
.build();
MyAPI myPostApi = retrofit1.create(MyAPI.class);
UserLogin userLogin = new UserLogin("j#yahoo.com", "Admin123#");
Gson gson = new Gson();
String json = gson.toJson(userLogin);
Log.e("json",json);
Call<Example> call1 = myPostApi.login(json);
call1.enqueue(new Callback<Example>() {
#Override
public void onResponse(Response<Example> response, Retrofit retrofit) {
Log.e("Response", String.valueOf(response.body()));
Example example = response.body();
Detail detail = example.getDetail();
Log.e("Access Token", detail.getAccessToken());
}
#Override
public void onFailure(Throwable t) {
Log.e("Failure", String.valueOf(t));
}
});
This is the segment of code using Retrofit Library for Posting email ID and Password to server.Here u can see,I am converting the object containing emailID and password into JSON using GSON library and posting the JSON string to server.
4.Expected Response
{
"detail": {
"id": "249",
"user_id": "479",
"access_token": "TwxqCJvgYfNeh6AeEZvjHWpjJMtH9va22ItErYVqeIEvOeKsegLWcbgVYJD7fOai",
"added_on": "2015-10-17 16:39:55",
"updated_on": "2015-10-17 16:39:55",
"status": "1",
"success": true,
"userInfo": {
"userInfo": {
"timeline": {
"wall_user_id": "479"
},
"logged": true,
"user": {
"id": "479",
"birthday": "2016-01-24",
"comment_privacy": "everyone",
"confirm_followers": "1",
"current_city": "",
"follow_privacy": "everyone",
"gender": "male",
"hometown": null,
"message_privacy": "everyone",
"timeline_post_privacy": "a:1:{i:0;s:1:\"5\";}",
"feed_section": "1",
"post_privacy": "a:1:{i:0;s:1:\"5\";}",
"current_city_id": "",
"userSkills": "",
"birth": {
"date": "24",
"month": "01",
"year": "2016"
},
"about": "jhjjkk\nhjjhjkj\nhjj",
"active": "1",
"avatar_id": "397",
"cover_id": "403",
"cover_position": "35",
"email": "nishantkango#yahoo.co.in",
"email_verification_key": null,
"email_verified": "0",
"language": null,
"last_logged": "1453645993",
"name": "Nishant Kango",
"time": "0",
"timestamp": "2016-01-24 14:33:13",
"timezone": null,
"type": "user",
"username": null,
"verified": false,
"user_id": "479",
"first_name": "Nishant",
"middle_name": null,
"last_name": "Kango",
"dob": "2016-01-24",
"mobile": "8699022278",
"title": null,
"marital_status": "",
"childrens": "0",
"hobbies": "Travelling",
"interests": "Technology",
"feed_back": null,
"status": "approved",
"profile_pic": null,
"date_created": "2014-10-29 00:00:00",
"date_modified": "2016-01-24 14:28:24",
"activation_code": null,
"social_login_type": "facebook",
"facebook_id": "10205077190793111",
"linked_in_id": null,
"google_id": null,
"employment_status": null,
"is_deleted": "0",
"website": "http://www.nishantkango.com",
"reference_institute": "",
"industry": "0",
"proffesion_type": "",
"url": "http://phpstack-11819-25991-62288.cloudwaysapps.com/user/timeline/e6b34e9a0311a7f829e09d2d7c4b313e",
"cover": {
"id": "403",
"active": "1",
"album_id": "0",
"extension": "jpg",
"name": "IMG_3686.JPG",
"post_id": "0",
"temp": "0",
"timeline_id": "0",
"type": "photo",
"url": "common/marvel/photos/2015/09/ofRL7_403_bbf94b34eb32268ada57a3be5062fe7d",
"complete_url": "http://phpstack-11819-25991-62288.cloudwaysapps.com/common/marvel/photos/2015/09/ofRL7_403_bbf94b34eb32268ada57a3be5062fe7d.jpg",
"post_url": "/index.php?tab1=story&id=0"
},
"actual_cover_url": "http://phpstack-11819-25991-62288.cloudwaysapps.com/common/marvel/photos/2015/09/ofRL7_403_bbf94b34eb32268ada57a3be5062fe7d.jpg",
"cover_url": "http://phpstack-11819-25991-62288.cloudwaysapps.com/common/marvel/photos/2015/09/ofRL7_403_bbf94b34eb32268ada57a3be5062fe7d_cover.jpg",
"avatar": {
"id": "397",
"active": "1",
"album_id": "0",
"extension": "jpg",
"name": "IMG_3734.JPG",
"post_id": "0",
"temp": "0",
"timeline_id": "0",
"type": "photo",
"url": "common/marvel/photos/2015/09/2jY3t_397_e46de7e1bcaaced9a54f1e9d0d2f800d",
"complete_url": "http://phpstack-11819-25991-62288.cloudwaysapps.com/common/marvel/photos/2015/09/2jY3t_397_e46de7e1bcaaced9a54f1e9d0d2f800d.jpg",
"post_url": "/index.php?tab1=story&id=0"
},
"thumbnail_url": "http://phpstack-11819-25991-62288.cloudwaysapps.com/common/marvel/images/default-male-avatar.png",
"avatar_url": "http://phpstack-11819-25991-62288.cloudwaysapps.com/common/marvel/images/default-male-avatar.png",
"online": false
}
},
"totalRecords": "0",
"timelineJobInfo": false,
"privacyArray": [{
"privacy_option_id": "1",
"privacy_option_name": "Only Me"
}, {
"privacy_option_id": "2",
"privacy_option_name": "Friends"
}, {
"privacy_option_id": "3",
"privacy_option_name": "Mentors"
}, {
"privacy_option_id": "4",
"privacy_option_name": "Mentees"
}, {
"privacy_option_id": "5",
"privacy_option_name": "Everyone"
}],
"educationInfo": [{
"user_qualification_id": "35",
"user_id": "479",
"institute_name": "G.S.S.SCHOOL.BHOTA",
"qualification_type": "high school",
"from_month": null,
"to_month": null,
"from_year": "0",
"to_year": "2004",
"other_qualification_type_description": "",
"field_of_study": "",
"date_created": "2015-03-14 16:07:34",
"date_modified": "2015-03-30 12:07:46",
"currently_studing_here": null,
"program_id": null,
"institute_id": "104",
"logo": ""
}, {
"user_qualification_id": "36",
"user_id": "479",
"institute_name": "Himachal Pradesh University",
"qualification_type": "bachelors degree",
"from_month": null,
"to_month": null,
"from_year": null,
"to_year": "2011",
"other_qualification_type_description": null,
"field_of_study": null,
"date_created": "2015-03-14 16:07:35",
"date_modified": "2015-03-14 16:07:35",
"currently_studing_here": null,
"program_id": null,
"institute_id": "105",
"logo": ""
}, {
"user_qualification_id": "69",
"user_id": "479",
"institute_name": "Bhavan Vidyalaya",
"qualification_type": "secondary school",
"from_month": null,
"to_month": null,
"from_year": "2011",
"to_year": "2015",
"other_qualification_type_description": "",
"field_of_study": "",
"date_created": "2015-06-16 14:36:42",
"date_modified": "2015-06-16 14:34:40",
"currently_studing_here": null,
"program_id": null,
"institute_id": "51",
"logo": "1432290512HbMWOd18Do.jpg"
}, {
"user_qualification_id": "70",
"user_id": "479",
"institute_name": "D.A.V College, Chandigarh",
"qualification_type": "secondary school",
"from_month": null,
"to_month": null,
"from_year": "0",
"to_year": "2015",
"other_qualification_type_description": "",
"field_of_study": "",
"date_created": "2015-06-25 18:39:21",
"date_modified": "2015-07-02 11:50:57",
"currently_studing_here": null,
"program_id": null,
"institute_id": "65",
"logo": "1427433797f9zgcZJE5Y.jpg"
}],
"professionalInfo": [{
"user_profession_id": "100",
"user_id": "479",
"industry": null,
"organisation": "VebificTechnologies",
"designation": "CTO",
"city": "Chandigarh, India",
"month_from": "1",
"month_to": "3",
"year_from": "2015",
"year_to": "2015",
"profession_type": null,
"job_profile": "",
"date_created": "2015-03-23 10:50:35",
"date_modified": "2016-01-16 10:38:41",
"org_type": null,
"currently_working_here": null,
"functional_area": null,
"on_level": null,
"work_meta": null,
"migrated": "1"
}, {
"user_profession_id": "110",
"user_id": "479",
"industry": null,
"organisation": "Microsoft",
"designation": "Software Developer",
"city": "Chandigarh, India",
"month_from": "1",
"month_to": "3",
"year_from": "2015",
"year_to": "2015",
"profession_type": null,
"job_profile": "",
"date_created": "2015-03-30 16:37:28",
"date_modified": "2016-01-16 10:39:30",
"org_type": null,
"currently_working_here": null,
"functional_area": null,
"on_level": null,
"work_meta": null,
"migrated": "1"
}, {
"user_profession_id": "83",
"user_id": "479",
"industry": null,
"organisation": "Intelegain Technology Pvt. Ltd",
"designation": "Sr. Programmer Analyst",
"city": "Chandigarh",
"month_from": "12",
"month_to": "11",
"year_from": "2011",
"year_to": "2014",
"profession_type": null,
"job_profile": "Managing team and projects",
"date_created": "2014-11-29 16:52:27",
"date_modified": "2014-11-29 16:52:27",
"org_type": null,
"currently_working_here": null,
"functional_area": null,
"on_level": null,
"work_meta": null,
"migrated": "0"
}, {
"user_profession_id": "93",
"user_id": "479",
"industry": null,
"organisation": "Freelance",
"designation": "Web Developer",
"city": null,
"month_from": "1",
"month_to": "3",
"year_from": "2011",
"year_to": "2015",
"profession_type": null,
"job_profile": null,
"date_created": "2015-03-14 16:07:35",
"date_modified": "2016-01-16 10:38:41",
"org_type": null,
"currently_working_here": null,
"functional_area": null,
"on_level": null,
"work_meta": null,
"migrated": "1"
}, {
"user_profession_id": "96",
"user_id": "479",
"industry": null,
"organisation": "Freelance",
"designation": "Web Developer",
"city": null,
"month_from": "1",
"month_to": "3",
"year_from": "2011",
"year_to": "2015",
"profession_type": null,
"job_profile": null,
"date_created": "2015-03-19 18:41:46",
"date_modified": "2016-01-16 10:38:41",
"org_type": null,
"currently_working_here": null,
"functional_area": null,
"on_level": null,
"work_meta": null,
"migrated": "1"
}],
"friendWithYou": false,
"mutualFriends": null,
"photos": null
}
},
"statusCode": "200"
}
I have written POJO for the response.
5.Example.java
public class EducationInfo {
#SerializedName("user_qualification_id")
#Expose
private String userQualificationId;
#SerializedName("user_id")
#Expose
private String userId;
#SerializedName("institute_name")
#Expose
private String instituteName;
#SerializedName("qualification_type")
#Expose
private String qualificationType;
#SerializedName("from_month")
#Expose
private Object fromMonth;
#SerializedName("to_month")
#Expose
private Object toMonth;
#SerializedName("from_year")
#Expose
private String fromYear;
#SerializedName("to_year")
#Expose
private String toYear;
#SerializedName("other_qualification_type_description")
#Expose
private String otherQualificationTypeDescription;
#SerializedName("field_of_study")
#Expose
private String fieldOfStudy;
#SerializedName("date_created")
#Expose
private String dateCreated;
#SerializedName("date_modified")
#Expose
private String dateModified;
#SerializedName("currently_studing_here")
#Expose
private Object currentlyStudingHere;
#SerializedName("program_id")
#Expose
private Object programId;
#SerializedName("institute_id")
#Expose
private String instituteId;
#SerializedName("logo")
#Expose
private String logo;
/**
*
* #return
* The userQualificationId
*/
public String getUserQualificationId() {
return userQualificationId;
}
/**
*
* #param userQualificationId
* The user_qualification_id
*/
public void setUserQualificationId(String userQualificationId) {
this.userQualificationId = userQualificationId;
}
/**
*
* #return
* The userId
*/
public String getUserId() {
return userId;
}
/**
*
* #param userId
* The user_id
*/
public void setUserId(String userId) {
this.userId = userId;
}
/**
*
* #return
* The instituteName
*/
public String getInstituteName() {
return instituteName;
}
/**
*
* #param instituteName
* The institute_name
*/
public void setInstituteName(String instituteName) {
this.instituteName = instituteName;
}
/**
*
* #return
* The qualificationType
*/
public String getQualificationType() {
return qualificationType;
}
/**
*
* #param qualificationType
* The qualification_type
*/
public void setQualificationType(String qualificationType) {
this.qualificationType = qualificationType;
}
/**
*
* #return
* The fromMonth
*/
public Object getFromMonth() {
return fromMonth;
}
/**
*
* #param fromMonth
* The from_month
*/
public void setFromMonth(Object fromMonth) {
this.fromMonth = fromMonth;
}
/**
*
* #return
* The toMonth
*/
public Object getToMonth() {
return toMonth;
}
/**
*
* #param toMonth
* The to_month
*/
public void setToMonth(Object toMonth) {
this.toMonth = toMonth;
}
/**
*
* #return
* The fromYear
*/
public String getFromYear() {
return fromYear;
}
/**
*
* #param fromYear
* The from_year
*/
public void setFromYear(String fromYear) {
this.fromYear = fromYear;
}
/**
*
* #return
* The toYear
*/
public String getToYear() {
return toYear;
}
/**
*
* #param toYear
* The to_year
*/
public void setToYear(String toYear) {
this.toYear = toYear;
}
/**
*
* #return
* The otherQualificationTypeDescription
*/
public String getOtherQualificationTypeDescription() {
return otherQualificationTypeDescription;
}
/**
*
* #param otherQualificationTypeDescription
* The other_qualification_type_description
*/
public void setOtherQualificationTypeDescription(String otherQualificationTypeDescription) {
this.otherQualificationTypeDescription = otherQualificationTypeDescription;
}
/**
*
* #return
* The fieldOfStudy
*/
public String getFieldOfStudy() {
return fieldOfStudy;
}
/**
*
* #param fieldOfStudy
* The field_of_study
*/
public void setFieldOfStudy(String fieldOfStudy) {
this.fieldOfStudy = fieldOfStudy;
}
/**
*
* #return
* The dateCreated
*/
public String getDateCreated() {
return dateCreated;
}
/**
*
* #param dateCreated
* The date_created
*/
public void setDateCreated(String dateCreated) {
this.dateCreated = dateCreated;
}
/**
*
* #return
* The dateModified
*/
public String getDateModified() {
return dateModified;
}
/**
*
* #param dateModified
* The date_modified
*/
public void setDateModified(String dateModified) {
this.dateModified = dateModified;
}
/**
*
* #return
* The currentlyStudingHere
*/
public Object getCurrentlyStudingHere() {
return currentlyStudingHere;
}
/**
*
* #param currentlyStudingHere
* The currently_studing_here
*/
public void setCurrentlyStudingHere(Object currentlyStudingHere) {
this.currentlyStudingHere = currentlyStudingHere;
}
/**
*
* #return
* The programId
*/
public Object getProgramId() {
return programId;
}
/**
*
* #param programId
* The program_id
*/
public void setProgramId(Object programId) {
this.programId = programId;
}
/**
*
* #return
* The instituteId
*/
public String getInstituteId() {
return instituteId;
}
/**
*
* #param instituteId
* The institute_id
*/
public void setInstituteId(String instituteId) {
this.instituteId = instituteId;
}
/**
*
* #return
* The logo
*/
public String getLogo() {
return logo;
}
/**
*
* #param logo
* The logo
*/
public void setLogo(String logo) {
this.logo = logo;
}
}
I dont know where is the the issue.Am i using the correct way to POST JSON String ?I am getting Null response here.Plz help me to fix the issue.

Related

how to get and display json array data from our auto generated pojo class?

I have searched all over the internet but i am not able to parse my json array from pojo class.Application is getting crashed again and again.Please can anyone tell me how to parse and display json array from a complex json response.This is my JSON response.
From this i want to parse my department name,description, product name and category list.
{ "departmentAndCategory": [
{
"departmentName": "Apparels",
"departmentDescription": "Apparels",
"storeId": null,
"categoryList": [],
"id": 1
},
{
"departmentName": "Footwear",
"departmentDescription": "footwear for men,women and kids",
"storeId": null,
"categoryList": [
{
"departmentId": 10,
"categoryName": "Footwear",
"categoryDescription": "Footwear for men,women and kids",
"parentCategoryId": null
},
{
"departmentId": 10,
"categoryName": "Vehicles",
"categoryDescription": "Two and Four wheelers",
"parentCategoryId": null
}
],
"id": 10
},
{
"departmentName": "Appliances",
"departmentDescription": "TV,Washing Machines,Refrigerators etc.",
"storeId": null,
"categoryList": [
{
"departmentId": 11,
"categoryName": "Appliances",
"categoryDescription": "Appliances for home like TV,Washing Machines,Refrigerators etc.",
"parentCategoryId": null
},
{
"departmentId": 11,
"categoryName": "Vehicles",
"categoryDescription": "Two and Four wheelers",
"parentCategoryId": null
}
],
"id": 11
},
{
"departmentName": "Electronics",
"departmentDescription": "Mobile Phones,Routers etc.",
"storeId": null,
"categoryList": [
{
"departmentId": 12,
"categoryName": "Electronics",
"categoryDescription": "Electrnocs for personal use like Mobile Phones,Routers etc.",
"parentCategoryId": null
}
],
"id": 12
},
{
"departmentName": "Home & Furniture",
"departmentDescription": "All your Home & Furniture needs",
"storeId": null,
"categoryList": [],
"id": 2
},
{
"departmentName": "test",
"departmentDescription": "test",
"storeId": null,
"categoryList": [],
"id": 14
},
{
"departmentName": "apparels",
"departmentDescription": "apparels",
"storeId": null,
"categoryList": [],
"id": 15
},
{
"departmentName": "Levi`s Tshirt",
"departmentDescription": "Levi`s Tshirt",
"storeId": null,
"categoryList": [],
"id": 16
}],"productsAndDeals": [ {
"imageName": null,
"smallImage": null,
"productName": "Levis T-shirt",
"productDescription": "A good fabric from levis",
"productPrice": 2000,
"productInStock": 7,
"productAvailability": "Product is available",
"title": "Clothes",
"dealList": [],
"id": 1
},
{
"imageName": null,
"smallImage": null,
"productName": "skin-fit",
"productDescription": "best blue jeans",
"productPrice": 1000,
"productInStock": 15,
"productAvailability": "Product is available",
"title": "Jeans",
"dealList": [
{
"dealImage": "dev.beacon.interrait.com/resources/deal-1.jpg",
"productsId": 2,
"categoryId": 1,
"expiryDate": null,
"discountPercentage": 60,
"discountAmount": 600,
"isActive": "False",
"dealNotes": null,
"dealName": "Massive discount on skin fit jeans",
"id": 1
}
],
"id": 2
},
{
"imageName": null,
"smallImage": null,
"productName": "bell-bottoms",
"productDescription": "best blue jeans",
"productPrice": 1200,
"productInStock": 15,
"productAvailability": "Product is available",
"title": "Jeans",
"dealList": [
{
"dealImage": "dev.beacon.interrait.com/resources/deal-1.jpg",
"productsId": 3,
"categoryId": 1,
"expiryDate": null,
"discountPercentage": 40,
"discountAmount": 480,
"isActive": "False",
"dealNotes": null,
"dealName": "Massive discount on bell bottoms",
"id": 2
}
],
"id": 3
},
{
"imageName": null,
"smallImage": null,
"productName": "curve-jeans",
"productDescription": "best blue jeans",
"productPrice": 1200,
"productInStock": 15,
"productAvailability": "Product is available",
"title": "Jeans",
"dealList": [
{
"dealImage": "dev.beacon.interrait.com/resources/deal-1.jpg",
"productsId": 4,
"categoryId": 1,
"expiryDate": null,
"discountPercentage": 50,
"discountAmount": 600,
"isActive": "False",
"dealNotes": null,
"dealName": "Massive discount on curve jeans",
"id": 3
}
],
"id": 4
},
{
"imageName": null,
"smallImage": null,
"productName": "Aman",
"productDescription": "",
"productPrice": 1000,
"productInStock": 12,
"productAvailability": "Product is available",
"title": "Tshirt",
"dealList": [],
"id": 6
},
{
"imageName": null,
"smallImage": null,
"productName": "T-shirts for Men",
"productDescription": "New T-shirt collection",
"productPrice": 599,
"productInStock": 0,
"productAvailability": "Product not in stock",
"title": "T-shirts",
"dealList": [],
"id": 7
},
{
"imageName": null,
"smallImage": null,
"productName": "abvgc",
"productDescription": "askkkdd",
"productPrice": null,
"productInStock": 1,
"productAvailability": "Product is available",
"title": "dddrr",
"dealList": [],
"id": 19
},
{
"imageName": null,
"smallImage": null,
"productName": "top",
"productDescription": "askkkdd",
"productPrice": null,
"productInStock": 1,
"productAvailability": "Product is available",
"title": "dddrr",
"dealList": [],
"id": 20
},
{
"imageName": null,
"smallImage": null,
"productName": "topsss",
"productDescription": "askkkdfffd",
"productPrice": null,
"productInStock": 1,
"productAvailability": "Product is available",
"title": "dddrr",
"dealList": [],
"id": 21
},
{
"imageName": null,
"smallImage": null,
"productName": "topsss",
"productDescription": "askkkdfffd",
"productPrice": null,
"productInStock": 1,
"productAvailability": "Product is available",
"title": "dddrr",
"dealList": [],
"id": 22
},
{
"imageName": null,
"smallImage": null,
"productName": "sample",
"productDescription": "sample",
"productPrice": null,
"productInStock": 10,
"productAvailability": "Product is available",
"title": "Product",
"dealList": [],
"id": 23
},
{
"imageName": null,
"smallImage": null,
"productName": "sample",
"productDescription": "sample",
"productPrice": null,
"productInStock": 10,
"productAvailability": "Product is available",
"title": "Product",
"dealList": [],
"id": 24
},
{
"imageName": null,
"smallImage": null,
"productName": "sample",
"productDescription": "sample",
"productPrice": null,
"productInStock": 10,
"productAvailability": "Product is available",
"title": "Product",
"dealList": [],
"id": 25
},
{
"imageName": null,
"smallImage": null,
"productName": "mobile",
"productDescription": "smartphones",
"productPrice": null,
"productInStock": 1,
"productAvailability": "Product is available",
"title": "dddrr",
"dealList": [],
"id": 30
},
{
"imageName": null,
"smallImage": null,
"productName": "Apples",
"productDescription": "fresh apples from farm",
"productPrice": 150,
"productInStock": 90,
"productAvailability": "Product is available",
"title": "Red apples",
"dealList": [],
"id": 31
},
{
"imageName": null,
"smallImage": null,
"productName": "slippers and jackets",
"productDescription": "Slip Ons",
"productPrice": 210,
"productInStock": 45,
"productAvailability": "Product is available",
"title": "Liberty slippes",
"dealList": [],
"id": 110
},
{
"imageName": null,
"smallImage": null,
"productName": "glucose",
"productDescription": "glucone D",
"productPrice": 60,
"productInStock": 123,
"productAvailability": "Product is available",
"title": "Glucose for health",
"dealList": [],
"id": 117
},
{
"imageName": null,
"smallImage": null,
"productName": "jackets",
"productDescription": "rugged jackets",
"productPrice": 210,
"productInStock": 45,
"productAvailability": "Product is available",
"title": "Liberty slippes",
"dealList": [],
"id": 121
},
{
"imageName": null,
"smallImage": null,
"productName": "Stationary",
"productDescription": "pens,pencil",
"productPrice": 10,
"productInStock": 100,
"productAvailability": "Product is available",
"title": "--",
"dealList": [],
"id": 127
},
{
"imageName": null,
"smallImage": null,
"productName": "bat",
"productDescription": "cricket bats",
"productPrice": 500,
"productInStock": 20,
"productAvailability": "Product is available",
"title": "games for kids",
"dealList": [],
"id": 128
},
{
"imageName": null,
"smallImage": null,
"productName": "ball",
"productDescription": "cricket bats",
"productPrice": 500,
"productInStock": 20,
"productAvailability": "Product is available",
"title": "games for kids",
"dealList": [],
"id": 130
},
{
"imageName": null,
"smallImage": null,
"productName": "sports",
"productDescription": "cricket bats",
"productPrice": 500,
"productInStock": 20,
"productAvailability": "Product is available",
"title": "games for kids",
"dealList": [],
"id": 131
},
{
"imageName": null,
"smallImage": null,
"productName": "garden",
"productDescription": "axe",
"productPrice": 500,
"productInStock": 20,
"productAvailability": "Product is available",
"title": "-",
"dealList": [],
"id": 132
}
]
}
Here you can use following classes to parse your Response:
Create Two classes:
1. DepartmentAndCategory
2. ProductsAndDeals
//DepartmentAndCategory class
public class DepartmentAndCategory {
private List<CategoryList> categoryList;
private String departmentDescription;
private String departmentName;
public DepartmentAndCategory(String departmentName,String departmentDescription,
List<CategoryList> categoryList){
this.departmentName = departmentName;
this.departmentDescription = departmentDescription;
this.categoryList = categoryList;
}
public List<CategoryList> getCategoryList() {
return categoryList;
}
public void setCategoryList(List<CategoryList> categoryList) {
this.categoryList = categoryList;
}
public String getDepartmentDescription ()
{
return departmentDescription;
}
public void setDepartmentDescription (String departmentDescription)
{
this.departmentDescription = departmentDescription;
}
public String getDepartmentName ()
{
return departmentName;
}
public void setDepartmentName (String departmentName)
{
this.departmentName = departmentName;
}
#Override
public String toString()
{
return "ClassPojo [ categoryList = "+categoryList+", departmentDescription = "+departmentDescription+", departmentName = "+departmentName+"]";
}
}
//ProductsAndDeals class
public class ProductsAndDeals {
private String productName;
public ProductsAndDeals(){}
public ProductsAndDeals(String productName){
this.productName = productName;
}
public String getProductName() {
return productName;
}
public void setProductName(String productName) {
this.productName = productName;
}
#Override
public String toString()
{
return "ClassPojo [productName = "+productName+"]";
}
}
// Then main class to parse the response
public class MainActivity extends AppCompatActivity {
List<DepartmentAndCategory> departmentAndCategoryList = new ArrayList<>();
List<ProductsAndDeals> productsAndDealsList = new ArrayList<>();
private static final String TAG = "MainActivity";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
int i=0;
//Pass your response String here
ParseResponse(Response.RESPONSE);
String[] departNameArray = new String[departmentAndCategoryList.size()];
//printing Department Name, Department Description and Category List
for (DepartmentAndCategory list : departmentAndCategoryList){
Log.e(TAG,"Departname : "+list.getDepartmentName());
Log.e(TAG,"DepartDesc :"+list.getDepartmentDescription());
departNameArray[i] = list.getDepartmentName();
i++;
for (CategoryList list1 : list.getCategoryList()){
Log.e(TAG,"departmentId "+list1.getDepartmentId());
Log.e(TAG,"categoryName "+list1.getCategoryName());
Log.e(TAG,"categoryDescription "+list1.getCategoryDescription());
Log.e(TAG,"parentCategoryId "+list1.getParentCategoryId());
}
}
//departName array
for (int j=0;j<departNameArray.length;j++){
Log.e(TAG,"DepartName : "+departNameArray[j]);
}
//printing Product Name
for (ProductsAndDeals dealsList : productsAndDealsList){
Log.e(TAG,"Product name : "+dealsList.getProductName());
}
}
private void ParseResponse(String response){
try {
JSONObject rootObj = new JSONObject(response);
JSONArray department = rootObj.optJSONArray("departmentAndCategory");
for (int i=0;i<department.length();i++){
List<CategoryList> mCategoryList = new ArrayList<>();
JSONObject departmentObj = department.getJSONObject(i);
String departName = departmentObj.getString("departmentName");
String departDesc = departmentObj.getString("departmentDescription");
JSONArray categoryArray = departmentObj.optJSONArray("categoryList");
for (int j=0;j<categoryArray.length();j++){
JSONObject categoryObj = categoryArray.getJSONObject(j);
String departId = categoryObj.getString("departmentId");
String categoryName = categoryObj.getString("categoryName");
String categoryDescription = categoryObj.getString("categoryDescription");
String parentCategoryId = categoryObj.getString("parentCategoryId");
CategoryList categoryList = new CategoryList(categoryName,categoryDescription,
departId,parentCategoryId);
mCategoryList.add(categoryList);
}
DepartmentAndCategory departmentAndCategory = new DepartmentAndCategory(
departName,departDesc,mCategoryList
);
departmentAndCategoryList.add(departmentAndCategory);
}
JSONArray product = rootObj.optJSONArray("productsAndDeals");
for (int i=0;i<product.length();i++){
JSONObject productObj = product.getJSONObject(i);
String productName = productObj.getString("productName");
ProductsAndDeals productsAndDeals = new ProductsAndDeals(productName);
productsAndDealsList.add(productsAndDeals);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}

Have spinner dependent on item selected on other spinner

I want to show the number of days depending on the month chosen. Like if month chosen is January show dates till 31 but if it is february show until 29. I saw and tried some solutions but they didn't work out for me.
Here's my SignUpActivity class:
public class SignupActivity extends AppCompatActivity {
EditText first;
EditText last;
TextView birth;
Spinner month;
Spinner date;
Spinner year;
EditText email;
EditText phone;
EditText username;
EditText password;
Button done;
String[] dayOptions = new String[]{
"1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", "23", "24", "25", "26", "27", "28", "29", "30", "31"
};
String[] dayOptions2 = new String[]{
"1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", "23", "24", "25", "26", "27", "28", "29", "30"
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_signup);
first = (EditText) findViewById(R.id.firstName);
last = (EditText) findViewById(R.id.lastName);
birth = (TextView) findViewById(R.id.birthText);
month = (Spinner) findViewById(R.id.birthMonth);
date = (Spinner) findViewById(R.id.birthDate);
year = (Spinner) findViewById(R.id.birthYear);
email = (EditText) findViewById(R.id.email);
phone = (EditText) findViewById(R.id.phoneNumber);
username = (EditText) findViewById(R.id.usernameEdit);
password = (EditText) findViewById(R.id.passwordEdit);
done = (Button) findViewById(R.id.done);
// month dropdown
final Spinner monthDrop = (Spinner) findViewById(R.id.birthMonth);
String[] monthOptions = new String[]{
"January", "February", "March", "April", "June", "July", "August", "September", "October", "November", "December"
};
ArrayAdapter<String> monthAdapter = new ArrayAdapter<>(this, android.R.layout.simple_spinner_dropdown_item, monthOptions);
monthDrop.setAdapter(monthAdapter);
// days dropdown
Spinner dateDrop = (Spinner) findViewById(R.id.birthDate);
String[] dayOptions = new String[]{
"1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", "23", "24", "25", "26", "27", "28", "29", "30", "31"
};
ArrayAdapter<String> adapter = new ArrayAdapter<>(this, android.R.layout.simple_spinner_dropdown_item, dayOptions);
dateDrop.setAdapter(adapter);
// year dropdown
Spinner yearDrop = (Spinner) findViewById(R.id.birthYear);
String[] yearOptions = new String[]{
"1990", "1991", "1992", "1993", "1994", "1995", "1996", "1997", "1998", "1999", "2000", "2001", "20012", "2003", "2004", "2005", "2006"
};
ArrayAdapter<String> yearAdapter = new ArrayAdapter<>(this, android.R.layout.simple_spinner_dropdown_item, yearOptions);
yearDrop.setAdapter(yearAdapter);
// CharSequence[] dateOptions = new CharSequence[] {
// };
done.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (first.getText().toString().equals("") || last.getText().toString().equals("") ||
email.getText().toString().equals("") || phone.getText().toString().equals("") ||
username.getText().toString().equals("") || password.getText().toString().equals("") || first.getText().toString().startsWith(" ") ||
last.getText().toString().startsWith(" ") || email.getText().toString().startsWith(" ") || phone.getText().toString().startsWith(" ") ||
username.getText().toString().startsWith(" ") || password.getText().toString().startsWith(" ")) {
Toast.makeText(getApplicationContext(), "Please fill all blanks", Toast.LENGTH_SHORT).show();
} else {
Intent intent = new Intent(SignupActivity.this, MainActivity.class);
startActivity(intent);
Toast.makeText(getApplicationContext(), "You have been signed up as " + first.getText().toString() + " " + last.getText().toString() + " (" + username.getText().toString() + ")", Toast.LENGTH_SHORT).show();
}
}
});
}
Any help would be appreciated! Thanks in advance!
UPDATE: I tried #siva35's answer but then the date dropdown options are all gone. My code is:
month.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) {
// int intPosition = position;
if(position == 0 || position == 2 || position == 4 || position == 5 || position == 7 || position == 9 ||position == 11) {
// Spinner date = (Spinner) findViewById(R.id.birthDate);
String[] dayOptions = new String[]{
"1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", "23", "24", "25", "26", "27", "28", "29", "30", "31"
};
ArrayAdapter<String> adapter = new ArrayAdapter<>(getApplication(), android.R.layout.simple_spinner_dropdown_item, dayOptions);
date.setAdapter(adapter);
} else if(position == 3 || position == 5 || position == 6 || position == 9 || position == 11 ) {
String[] dayOptions = new String[]{
"1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", "23", "24", "25", "26", "27", "28", "29", "30"
};
ArrayAdapter<String> adapter = new ArrayAdapter<>(getApplication(), android.R.layout.simple_spinner_dropdown_item, dayOptions);
date.setAdapter(adapter);
} else if(position == 1) {
String[] dayOptions = new String[]{
"1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", "23", "24", "25", "26", "27", "28"
};
ArrayAdapter<String> adapter = new ArrayAdapter<>(getApplication(), android.R.layout.simple_spinner_dropdown_item, dayOptions);
date.setAdapter(adapter);
} else {
Toast.makeText(getApplicationContext(), "Not working", Toast.LENGTH_LONG).show();
}
}
#Override
public void onNothingSelected(AdapterView<?> parentView) {
Toast.makeText(getApplicationContext(), "Please select something", Toast.LENGTH_LONG).show();
}
});
use OnItemSelectedListener() method.
month.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) {
// your code here to display date options
}
#Override
public void onNothingSelected(AdapterView<?> parentView) {
// your code here
}
})
;
Thanks #siva35 for your answer! I got an answer to my own question. My code for it is:
month.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view,
int pos, long id) {
List<String> s = Arrays.asList(getResources().getStringArray(R.array.item_day));
if (pos == 0 || pos == 2 || pos == 4 || pos == 8 || pos == 9
|| pos == 11) {
ArrayAdapter<String> dayadapter = new ArrayAdapter<String>(SignupActivity.this, android.R.layout.simple_spinner_item,s);
date.setAdapter(dayadapter);
} else if (pos == 1) {
s = s.subList(0,28);
ArrayAdapter<String> dayadapter = new ArrayAdapter<String>(SignupActivity.this, android.R.layout.simple_spinner_item,s);
date.setAdapter(dayadapter);
} else {
s = s.subList(0,30);
ArrayAdapter<String> dayadapter = new ArrayAdapter<String>(SignupActivity.this, android.R.layout.simple_spinner_item,s);
date.setAdapter(dayadapter);
}
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
Toast.makeText(getApplicationContext(), "Please select something", Toast.LENGTH_SHORT).show();
}
});

How to parse Array of Objects in Android

I am parsing the following json response but there is some problem in parsing,the code I'm trying is not parsing and I am not getting any exception or response.
The code that I had applied to parse it is:
ArrayList<Model_BarcodeDetail> DownloadBarcode(String api_token) {
ArrayList<Model_BarcodeDetail> barcodeList = new ArrayList<Model_BarcodeDetail>();
HttpClient httpClient = new DefaultHttpClient();
HttpPost postRequest = new HttpPost(Utility.BASE_URL
+ "?q=webservice/barcode_list&token=" + api_token +"&page="+"1"
+ "&return=json");
String url = Utility.BASE_URL
+ "?q=webservice/barcode_list&token=" + api_token +"&page="+"1"
+ "&return=json";
System.out.println("======url::"+url);
String result = "";
ArrayList<Model_BarcodeDetail> group_list = null;
ArrayList<Model_BarcodeList_Child> child_list = null;
try {
group_list = new ArrayList<Model_BarcodeDetail>();
ResponseHandler<String> responseHandler = new BasicResponseHandler();
result = httpClient.execute(postRequest, responseHandler);
JSONObject root = new JSONObject(result);
JSONObject obj = root.getJSONObject("");
System.out.println("====objjjj: "+obj.toString());
JSONArray arraylist=obj.names();
for (int i = 0; i < arraylist.length(); i++) {
child_list = new ArrayList<Model_BarcodeList_Child>();
JSONObject jsonObj = arraylist.getJSONObject(i);
System.out.println("---json" + jsonObj);
Model_BarcodeDetail data = new Model_BarcodeDetail();
data.setReference((jsonObj.getString("ref")));
System.out.println("======refinprsing--"+data.getReference());
// data.setName((jsonObj.getString("name")));
// data.setDescription((jsonObj.getString("desc")));
// data.setPrice((jsonObj.getString("price")));
// data.setTotal(data.getPrice().trim());
// data.setFixedTotal(data.getPrice().trim());
JSONArray obj2 = jsonObj.getJSONArray("barcodes");
for (int j = 0; j < obj2.length(); j++) {
JSONObject json = obj2.getJSONObject(j);
System.out.println("---json" + json);
Model_BarcodeList_Child data2 = new Model_BarcodeList_Child();
data2.setBarcode((json.getString("barcode")));
System.out.println("=======barcodeinparsing: "+data2.getBarcode());
data2.setColor((json.getString("color")));
data2.setSize((json.getString("size")));
data2.setPrice(json.getString("price"));
data2.setStock(json.getString("stock"));
data2.setAlis_code(json.getString("alias_code"));
child_list.add(data2);
}
data.setChildItems(child_list);
group_list.add(data);
}
for (int k = 0; k < group_list.size(); k++) {
System.out.println("-----==data itemref "
+ group_list.get(k).getReference());
for (int y = 0; y < group_list.get(k).getChildItems().size(); y++) {
System.out.println("-----====data color "
+ group_list.get(k).getChildItems().get(y)
.getColor());
}
}
} catch (Exception e) {
Log.i("Exception in DownloadBarcodechanges method: ", e.getMessage());
return null;
}
return group_list;
}
Here is the json:
{
"000002": {
"ref": "000002",
"barcodes": [
{
"barcode": "000002014001",
"path": null,
"alias_code": null,
"color": "GREY",
"price": "10.50",
"size": "S",
"stock": "0"
},
{
"barcode": "000002014002",
"path": null,
"alias_code": null,
"color": "GREY",
"price": "10.50",
"size": "M",
"stock": "2"
},
{
"barcode": "000002014003",
"path": null,
"alias_code": null,
"color": "GREY",
"price": "10.50",
"size": "L",
"stock": "1"
},
{
"barcode": "000002014004",
"path": null,
"alias_code": null,
"color": "GREY",
"price": "10.50",
"size": "XL",
"stock": "0"
},
{
"barcode": "000002014005",
"path": null,
"alias_code": null,
"color": "GREY",
"price": "10.50",
"size": "XXL",
"stock": "1"
},
{
"barcode": "000002014006",
"path": null,
"alias_code": null,
"color": "GREY",
"price": "13.50",
"size": "2XL",
"stock": "3"
},
{
"barcode": "000002014007",
"path": null,
"alias_code": null,
"color": "GREY",
"price": "13.50",
"size": "3XL",
"stock": "5"
},
{
"barcode": "000002014008",
"path": null,
"alias_code": null,
"color": "GREY",
"price": "13.50",
"size": "4XL",
"stock": "6"
},
{
"barcode": "000002014009",
"path": null,
"alias_code": null,
"color": "GREY",
"price": "13.50",
"size": "5XL",
"stock": "5"
},
{
"barcode": "000002014010",
"path": null,
"alias_code": null,
"color": "GREY",
"price": "10.50",
"size": "6XL",
"stock": "2"
}
]
},
"000012": {
"ref": "000012",
"barcodes": [
{
"barcode": "000012030001",
"path": null,
"alias_code": null,
"color": "BLUE",
"price": "19.99",
"size": "S",
"stock": "1"
},
{
"barcode": "000012030002",
"path": null,
"alias_code": null,
"color": "BLUE",
"price": "19.99",
"size": "M",
"stock": "3"
},
{
"barcode": "000012030003",
"path": null,
"alias_code": null,
"color": "BLUE",
"price": "19.99",
"size": "L",
"stock": "4"
},
{
"barcode": "000012030004",
"path": null,
"alias_code": null,
"color": "BLUE",
"price": "19.99",
"size": "XL",
"stock": "2"
},
{
"barcode": "000012030005",
"path": null,
"alias_code": null,
"color": "BLUE",
"price": "19.99",
"size": "XXL",
"stock": "0"
},
{
"barcode": "000012030006",
"path": null,
"alias_code": null,
"color": "BLUE",
"price": "19.99",
"size": "2XL",
"stock": "0"
},
{
"barcode": "000012030007",
"path": null,
"alias_code": null,
"color": "BLUE",
"price": "19.99",
"size": "3XL",
"stock": "0"
},
{
"barcode": "000012030008",
"path": null,
"alias_code": null,
"color": "BLUE",
"price": "19.99",
"size": "4XL",
"stock": "0"
},
{
"barcode": "000012030009",
"path": null,
"alias_code": null,
"color": "BLUE",
"price": "19.99",
"size": "5XL",
"stock": "0"
},
{
"barcode": "000012030010",
"path": null,
"alias_code": null,
"color": "BLUE",
"price": "19.99",
"size": "6XL",
"stock": "0"
}
]
},
"pager": {
"current_page": 1,
"start": 0,
"limit": 50,
"total": "354",
"pages": 8
}
}
According to your json Response do parsing like below
JSONObject root = new JSONObject(result);
JSONArray array = root.getJSONArray("array");
String boolean = root.getString("boolean");
String null= root.getString("null");
String number= root.getString("number");
String string = root.getString("string");
JSONArray array_1 = root.getJSONArray("object");
first check your result is not getting null ? please check log.
Based on the json provided change this:
JSONObject root = new JSONObject(result);
JSONObject obj = root.getJSONObject("");
System.out.println("====objjjj: "+obj.toString());
JSONArray arraylist=obj.names();
To this:
JSONObject root = new JSONObject(result);
JSONArray arraylist= root.names();
for (int i = 0; i < arraylist.length(); i++) {
child_list = new ArrayList<Model_BarcodeList_Child>();
JSONObject jsonObj = root.getJSONObject(arrayList.getString(i));
I would also add a check to see if the name equals pager, in that case continue;
Here is solution
JSONObject root = new JSONObject(result);
if(root != null){
Iterator iter = root.keys();
while (iter.hasNext()){
try {
String key = (String) iter.next();
JSONObject itemObject = root.getJSONObject(key);
} catch (JSONException e) {
}
}
}

How to store nested JSONArray value in SqliteDatabase in android?

How to store nested JSONArray value in SQLite Database?
getting value from JSONArray and It is also stored it in ArrayList both working fine.
My JSONArray List is,
{
"resultFlag": true,
"successMessage": "Data Received",
"Questions": [
{
"questionType": "Trivia",
"timeRequired": "10",
"questionID": "64",
"question": "Which section of the Indian IT act 2008 deals with cyber stalking?",
"answer": [
{
"ansID": "261",
"ans": "Section 24",
"correct": "0"
},
{
"ansID": "262",
"ans": "Section 72",
"correct": "1"
},
{
"ansID": "263",
"ans": "Section 27",
"correct": "0"
},
{
"ansID": "264",
"ans": "Section 42",
"correct": "0"
}
]
},
{
"questionType": "Trivia",
"timeRequired": "10",
"questionID": "66",
"question": "What should you do when your online friends want to meet you?",
"answer": [
{
"ansID": "269",
"ans": "Go ahead, make plans and meet them wherever and whenever they want",
"correct": "0"
},
{
"ansID": "270",
"ans": "Inform your parents and make sure that you meet where there are a lot of people around",
"correct": "1"
},
{
"ansID": "271",
"ans": "Never meet anyone in person that you met online, it’s just not safe",
"correct": "0"
},
{
"ansID": "272",
"ans": "Ignore their request",
"correct": "0"
}
]
},
{
"questionType": "Trivia",
"timeRequired": "10",
"questionID": "70",
"question": "te",
"answer": [
{
"ansID": "285",
"ans": "tr",
"correct": "1"
},
{
"ansID": "286",
"ans": "tr",
"correct": "0"
},
{
"ansID": "287",
"ans": "tr",
"correct": "0"
},
{
"ansID": "288",
"ans": "tr",
"correct": "0"
}
]
},
{
"questionType": "Trivia",
"timeRequired": "10",
"questionID": "91",
"question": "When A Player Deliberately Harasses Other Players Within An Online Game, it is known as ",
"answer": [
{
"ansID": "369",
"ans": "Griefing",
"correct": "1"
},
{
"ansID": "370",
"ans": "Spamming",
"correct": "0"
},
{
"ansID": "371",
"ans": "Scamming",
"correct": "0"
},
{
"ansID": "372",
"ans": "Grooming",
"correct": "0"
}
]
},
{
"questionType": "Trivia",
"timeRequired": "10",
"questionID": "153",
"question": "Which of the following is not a communication channel for a Phisher?",
"answer": [
{
"ansID": "617",
"ans": "Email Account",
"correct": "0"
},
{
"ansID": "618",
"ans": "Instant Messaging",
"correct": "0"
},
{
"ansID": "619",
"ans": "Social Media Account",
"correct": "0"
},
{
"ansID": "620",
"ans": "Search Engine",
"correct": "1"
}
]
}
]
}
I get Successfully response from Server but not store in ArrayList answer value for related question.
My Java Code is,
//Question
static String[] question_id;
static String[] question_type;
static String[] time_required;
static String[] question;
//Answer
static String[] answer_id;
static String[] answer;
static String[] correct;
//Question Array List
static List<String> arr_question_id = new ArrayList<String>();
static List<String> arr_question_type = new ArrayList<String>();
static List<String> arr_time_required = new ArrayList<String>();
static List<String> arr_question = new ArrayList<String>();
//Answer Array List
static List<String> arr_answer_id = new ArrayList<String>();
static List<String> arr_answer = new ArrayList<String>();
static List<String> arr_correct = new ArrayList<String>();
JsonObjectRequest jsonObjReq = new JsonObjectRequest(Request.Method.POST,
Url, params, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
// Parsing json object response
// response will be a json object
Boolean resultFlag = response.getBoolean("resultFlag");
if (resultFlag == true) {
String success = response.getString("successMessage");
JSONArray json_array_question = response.getJSONArray("Questions");
question_type = new String[json_array_question.length()];
time_required = new String[json_array_question.length()];
question_id = new String[json_array_question.length()];
question = new String[json_array_question.length()];
for (int i = 0; i < json_array_question.length(); i++) {
JSONObject json_object_question = json_array_question.getJSONObject(i);
question_type[i] = json_object_question.getString("questionType");
time_required[i] = json_object_question.getString("timeRequired");
question_id[i] = json_object_question.getString("questionID");
question[i] = json_object_question.getString("question");
JSONArray json_array_answer = json_object_question.getJSONArray("answer");
answer_id = new String[json_array_answer.length()];
answer = new String[json_array_answer.length()];
correct = new String[json_array_answer.length()];
for (int j = 0; j < json_array_answer.length(); j++) {
JSONObject json_object_answer = json_array_answer.getJSONObject(j);
answer_id[j] = json_object_answer.getString("ansID");
answer[j] = json_object_answer.getString("ans");
correct[j] = json_object_answer.getString("correct");
arr_answer_id.add(answer_id[j]);
arr_answer.add(answer[j]);
arr_correct.add(correct[j]);
}
arr_question_type.add(question_type[i]);
arr_time_required.add(time_required[i]);
arr_question_id.add(question_id[i]);
arr_question.add(question[i]);
}
*for (int i = 0; i < arr_question_id.size(); i++) {
item_solo_trivia.setQuestionType(arr_question_type.get(i));
item_solo_trivia.setTimeRequired(arr_time_required.get(i));
item_solo_trivia.setQuestionId(arr_question_id.get(i));
item_solo_trivia.setQuestion(arr_question.get(i));
for (j = 0; j < arr_answer_id.size(); j++) {
item_solo_trivia.setAnswerId(arr_answer_id.get(j));
item_solo_trivia.setAnswer(arr_answer.get(j));
item_solo_trivia.setCorrect(arr_correct.get(j));
}
}*
} else if (resultFlag == false) {
String error = response.getString("errorMessage");
Toast.makeText(activity.getApplicationContext(), error, Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(activity,
"Error: " + e.getMessage(),
Toast.LENGTH_LONG).show();
}
hidepDialog();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(activity,
error.getMessage(), Toast.LENGTH_SHORT).show();
// hide the progress dialog
hidepDialog();
}
});
// Adding request to request queue
AppController.getInstance().addToRequestQueue(jsonObjReq);
}
Problem with This code, How to Resolve it?
for (int i = 0; i < arr_question_id.size(); i++) {
item_solo_trivia.setQuestionType(arr_question_type.get(i));
item_solo_trivia.setTimeRequired(arr_time_required.get(i));
item_solo_trivia.setQuestionId(arr_question_id.get(i));
item_solo_trivia.setQuestion(arr_question.get(i));
for (j = 0; j < arr_answer_id.size(); j++) {
item_solo_trivia.setAnswerId(arr_answer_id.get(j));
item_solo_trivia.setAnswer(arr_answer.get(j));
item_solo_trivia.setCorrect(arr_correct.get(j));
}
}
And Table is,
//Create Table
public static final String CREATE = "CREATE TABLE IF NOT EXISTS "
+ TABLE
+ " ( "
+ KEY_ID
+ "INTEGER AUTOINCREMENT,"
+ KEY_USER_ID
+ " text not null , "
+ KEY_QUESTION_TYPE
+ " text not null , "
+ KEY_QUESTION_ID
+ " text not null , "
+ KEY_QUESTION
+ " text not null , "
+ KEY_ANSWER_ID_1
+ " text not null , "
+ KEY_ANSWER_ID_2
+ " text not null , "
+ KEY_ANSWER_ID_3
+ " text not null , "
+ KEY_ANSWER_ID_4
+ " text not null , "
+ KEY_ANSWER_1
+ " text not null , "
+ KEY_ANSWER_2
+ " text not null , "
+ KEY_ANSWER_3
+ " text not null , "
+ KEY_ANSWER_4
+ " text not null , "
+ KEY_CORRECT_1
+ " text not null , "
+ KEY_CORRECT_2
+ " text not null , "
+ KEY_CORRECT_3
+ " text not null , "
+ KEY_CORRECT_4 + " text not null" + ");";
How to store Answer list into related Question in SqliteDatabase?
Please Help me and Suggest me.
Thanks.

Android: org.json.jsonobject values

I'am fetching the data from the server and storing in my android application, but i get exception.
error message: JSONArray cannot be converted to JSONObject.
#Override
protected void onPostExecute(Boolean result) {
super.onPostExecute(result);
if (result) {
Log.d("response", response.toString());
JSONArray discoverArray = (JSONArray) response.optJSONArray("users");
ArrayList<Discover> discovers = new ArrayList<Discover>();
if (discoverArray != null) {
for (int i = 0; i < discoverArray.length(); i++) {
JSONObject discoverObj = (JSONObject) discoverArray.opt(i);
if (discoverObj != null) {
Discover discover = new Discover();
discover.setAge(discoverObj.optString("age"));
discover.setMutualFriend(discoverObj.optInt("mutualFriend"));
discover.setMutualInterest(discoverObj.optInt("mutualInterest"));
discover.setName(discoverObj.optString("name"));
discovers.add(discover);
}
}
}
Logcat:
org.json.JSONException: Value [{"locationCity":null,"fbCityName":"Százhalombatta","fbCityId":"105979396100282","lastUpdate":"2014-03-05 17:31:13","locale":"hu-HU","locationLongitude":"20","pictures":[{"order":1,"id":false,"url":"https://graph.facebook.com/100001290188792/picture/?width=600&height=600&type=square"}],"lastname":"Ilona","androidPushType":null,"bounce":"0","androidPush":null,"id":"20916","subscribe":"1","locationLatitude":"47","facebook":"100001290188792","name":"Karácsony Ilona","gender":"2","dateRegister":"2013-10-05 22:31:31","orientation":"1","hash":"37e8fd18cb29583879616c47ab87072e","iphonePush":null,"locationRadius":"30","fbLongitude":"18.9333","firstname":"Karácsony","lastLogin":"2014-01-15 10:13:35","email":"cusi28#freemail.hu","iphonePushType":null,"dob":null,"active":"1","fbLatitude":"47.3333","fbAccessToken":"CAAFiaFvj7I0BABZBZBXVwfs6tBSjoIWL133Ehkuzv0y39KziqvfBYYsPs1ep0mb8nHwO6OXw82qwQOusyuO9R5Aq7QcvY4I3xWh0eoxRkp40VZB3ZBITu2Mq5ZAl0RtWLwIdqtIIKiZA7Rh6WJz2cJRvKkHFm9TvzXTrUsVW6HvqeuYpL1q3sk"},{"locationCity":null,"fbCityName":null,"fbCityId":null,"lastUpdate":"2013-11-24 22:33:01","locale":"hu-HU","locationLongitude":"20","pictures":[{"order":1,"id":false,"url":"https://graph.facebook.com/100001346586576/picture/?width=600&height=600&type=square"}],"lastname":"Bognár","androidPushType":null,"bounce":"0","androidPush":null,"id":"20954","subscribe":"1","locationLatitude":"47","facebook":"100001346586576","name":"Szaszy Bognár","gender":"2","dateRegister":"2013-10-06 22:18:14","orientation":"1","hash":"f18cad1db764dd7fe394ac4e4707b84a","iphonePush":null,"locationRadius":"30","fbLongitude":null,"firstname":"Szaszy","lastLogin":"2013-10-06 22:18:14","email":null,"iphonePushType":null,"dob":null,"active":"1","fbLatitude":null,"fbAccessToken":"CAAFiaFvj7I0BAHohcV2ZCbUZC8sx1vhv2ylYBehttW22kmyLz2YdVpoZAabxSQPWPzQwUZAyCQCDRTMxPZCH2buyOkxFrcX7cefZBMUD2rbFZAbLbQZA6gXnHJ4zWJsroh1mKOlnfRjoNkyXTpG4csLzfTfLLydUYHtNKOpAiQa1VLkrtrKFv1dz"},{"locationCity":"2231932","fbCityName":null,"fbCityId":null,"lastUpdate":"2013-11-25 22:33:01","locale":"hu-HU","locationLongitude":"19.08333300000","pictures":[{"order":1,"id":false,"url":"https://graph.facebook.com/559072666/picture/?width=600&height=600&type=square"}],"lastname":"Kerekes","androidPushType":null,"bounce":"0","androidPush":null,"id":"20968","subscribe":"1","locationLatitude":"47.50000000000","facebook":"559072666","name":"Zsofia Kerekes","gender":"2","dateRegister":"2013-10-07 10:47:34","orientation":"1","hash":"4d9eb81eca14f5f362c2813c0c2fe3f3","iphonePush":null,"locationRadius":"10","fbLongitude":null,"firstname":"Zsofia","lastLogin":"2013-10-07 10:47:34","email":"zs.kerekes.13#gmail.com","iphonePushType":null,"dob":null,"active":"1","fbLatitude":null,"fbAccessToken":"CAAFiaFvj7I0BAKCdRjhUiNZBDkWcovRfoEJnKo2pkoYDpnW13PqptEr9FoIeJGLRD1f6dItf9sGhPcReWDdXY3qpEZCPFTp3YK6BOPaDzlY6834PFALImlFOF6uPQBnD2tIC0DYtCZAB1Jvr7jCD6at4MDIi9IHWiEUklj5cFLSzeirYZAhS0JcY7GOi9T0ZD"}] of type org.json.JSONArray cannot be converted to JSONObject
[
{
"active": "1",
"androidPush": null,
"androidPushType": null,
"bounce": "0",
"dateRegister": "2013-10-05 22:31:31",
"dob": null,
"email": "dwdwdwd",
"facebook": "wsda",
"fbAccessToken": "wdwdw",
"fbCityId": "105979396100282",
"fbCityName": "Sz\u00e1zhalombatta",
"fbLatitude": "47.3333",
"fbLongitude": "18.9333",
"firstname": "Kar\u00e1csony",
"gender": "2",
"hash": "wwwwwwwwww",
"id": "20916",
"iphonePush": null,
"iphonePushType": null,
"lastLogin": "2014-01-15 10:13:35",
"lastUpdate": "2014-03-05 17:31:13",
"lastname": "dd",
"locale": "hu-HU",
"locationCity": null,
"locationLatitude": "47",
"locationLongitude": "20",
"locationRadius": "30",
"orientation": "1",
"pictures": [
{
"id": false,
"order": 1,
"url": "dddd"
}
],
"subscribe": "1"
},
{
"active": "1",
"androidPush": null,
"androidPushType": null,
"bounce": "0",
"dateRegister": "2013-10-06 22:18:14",
"dob": null,
"email": null,
"facebook": "ddddd",
"fbAccessToken": "dddwdwdw",
"fbCityId": null,
"fbCityName": null,
"fbLatitude": null,
"fbLongitude": null,
"firstname": "dwdwdw",
"gender": "2",
"hash": "ddwdw",
"id": "20954",
"iphonePush": null,
"iphonePushType": null,
"lastLogin": "2013-10-06 22:18:14",
"lastUpdate": "2013-11-24 22:33:01",
"lastname": "wdwdw",
"locale": "hu-HU",
"locationCity": null,
"locationLatitude": "47",
"locationLongitude": "20",
"locationRadius": "30",
"name": "ddddr",
"orientation": "1",
"pictures": [
{
"id": false,
"order": 1,
"url": "wwwww"
}
],
"subscribe": "1"
},
{
"active": "1",
"androidPush": null,
"androidPushType": null,
"bounce": "0",
"dateRegister": "2013-10-07 10:47:34",
"dob": null,
"email": "asdasd",
"facebook": "ddddd",
"fbAccessToken": "dddd",
"fbCityId": null,
"fbCityName": null,
"fbLatitude": null,
"fbLongitude": null,
"firstname": "ddwwda",
"gender": "2",
"hash": "dwwdwdwdw",
"id": "20968",
"iphonePush": null,
"iphonePushType": null,
"lastLogin": "2013-10-07 10:47:34",
"lastUpdate": "2013-11-25 22:33:01",
"lastname": "ddddd",
"locale": "hu-HU",
"locationCity": "2231932",
"locationLatitude": "47.50000000000",
"locationLongitude": "19.08333300000",
"locationRadius": "10",
"name": "wwwwwww",
"orientation": "1",
"pictures": [
{
"id": false,
"order": 1,
"url": "photo"
}
],
"subscribe": "1"
}
]
Thank you very much for your help.
Replace
JSONObject discoverObj = (JSONObject) discoverArray.opt(i);
with
JSONObject discoverObj = discoverArray.getJSONObject(i);
Review the below code
#Override
protected void onPostExecute(Boolean result) {
super.onPostExecute(result);
if (result) {
Log.d("response", response.toString());
JSONArray discoverArray = (JSONArray) response.optJSONArray("users");
ArrayList<Discover> discovers = new ArrayList<Discover>();
if (discoverArray != null) {
for (int i = 0; i < discoverArray.length(); i++) {
JSONObject discoverObj = discoverArray.getJSONObject(i);
if (discoverObj != null) {
Discover discover = new Discover();
discover.setAge(discoverObj.optString("age"));
discover.setMutualFriend(discoverObj.optInt("mutualFriend"));
discover.setMutualInterest(discoverObj.optInt("mutualInterest"));
discover.setName(discoverObj.optString("name"));
discovers.add(discover);
}
}
}

Categories

Resources