Have spinner dependent on item selected on other spinner - android

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();
}
});

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();
}
}
}

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.

How to turn quiz from the text type to the image type in android?

These questions of the text type
I want to turn them into questions type of image
in the sense explained
The question I want to be an image, not (5 + 2),(2+15),....
is that possible???
I am Beginning in android
public void onCreate(SQLiteDatabase db) {
dbase = db;
String sql = "CREATE TABLE IF NOT EXISTS " + TABLE_QUEST + " ( "
+ KEY_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " + KEY_QUES
+ " TEXT, " + KEY_ANSWER + " TEXT, " + KEY_OPTA + " TEXT, "
+ KEY_OPTB + " TEXT, " + KEY_OPTC + " TEXT)";
db.execSQL(sql);
addQuestion();
// db.close();
}
private void addQuestion() {
Question q1 = new Question("5+2 = ?", "7", "8", "6", "7");
this.addQuestion(q1);
Question q2 = new Question("2+18 = ?", "18", "19", "20", "20");
this.addQuestion(q2);
Question q3 = new Question("10-3 = ?", "6", "7", "8", "7");
this.addQuestion(q3);
Question q4 = new Question("5+7 = ?", "12", "13", "14", "12");
this.addQuestion(q4);
Question q5 = new Question("3-1 = ?", "1", "3", "2", "2");
this.addQuestion(q5);
Question q6 = new Question("0+1 = ?", "1", "0", "10", "1");
this.addQuestion(q6);
Question q7 = new Question("9-9 = ?", "0", "9", "1", "0");
this.addQuestion(q7);
Question q8 = new Question("3+6 = ?", "8", "7", "9", "9");
this.addQuestion(q8);
Question q9 = new Question("1+5 = ?", "6", "7", "5", "6");
this.addQuestion(q9);
Question q10 = new Question("7-5 = ?", "3", "2", "6", "2");
this.addQuestion(q10);
Question q11 = new Question("7-2 = ?", "7", "6", "5", "5");
this.addQuestion(q11);
Question q12 = new Question("3+5 = ?", "8", "7", "5", "8");
this.addQuestion(q12);
Question q13 = new Question("0+6 = ?", "7", "6", "5", "6");
this.addQuestion(q13);
Question q14 = new Question("12-10 = ?", "1", "2", "3", "2");
this.addQuestion(q14);
Question q15 = new Question("12+2 = ?", "14", "15", "16", "14");
this.addQuestion(q15);
Question q16 = new Question("2-1 = ?", "2", "1", "0", "1");
this.addQuestion(q16);
Question q17 = new Question("6-6 = ?", "6", "12", "0", "0");
this.addQuestion(q17);
Question q18 = new Question("5-1 = ?", "4", "3", "2", "4");
this.addQuestion(q18);
Question q19 = new Question("4+2 = ?", "6", "7", "5", "6");
this.addQuestion(q19);
Question q20 = new Question("5+1 = ?", "6", "7", "5", "6");
this.addQuestion(q20);
Question q21 = new Question("5-4 = ?", "5", "4", "1", "1");
this.addQuestion(q21);
// END
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldV, int newV) {
// Drop older table if existed
db.execSQL("DROP TABLE IF EXISTS " + TABLE_QUEST);
// Create tables again
onCreate(db);
}
// Adding new question
public void addQuestion(Question quest) {
// SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_QUES, quest.getQUESTION());
values.put(KEY_ANSWER, quest.getANSWER());
values.put(KEY_OPTA, quest.getOPTA());
values.put(KEY_OPTB, quest.getOPTB());
values.put(KEY_OPTC, quest.getOPTC());
// Inserting Row
dbase.insert(TABLE_QUEST, null, values);
}
public List<Question> getAllQuestions() {
List<Question> quesList = new ArrayList<Question>();
// Select All Query
String selectQuery = "SELECT * FROM " + TABLE_QUEST;
dbase = this.getReadableDatabase();
Cursor cursor = dbase.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
Question quest = new Question();
quest.setID(cursor.getInt(0));
quest.setQUESTION(cursor.getString(1));
quest.setANSWER(cursor.getString(2));
quest.setOPTA(cursor.getString(3));
quest.setOPTB(cursor.getString(4));
quest.setOPTC(cursor.getString(5));
quesList.add(quest);
} while (cursor.moveToNext());
}
// return quest list
return quesList;
}
}
Try this code
Bitmap src = BitmapFactory.decodeResource(getResources(), R.drawable.yourimage); // the original file yourimage.jpg i added in resources
Bitmap dest = Bitmap.createBitmap(src.getWidth(), src.getHeight(), Bitmap.Config.ARGB_8888);
String yourText = "3+5 = ?";
Canvas cs = new Canvas(dest);
Paint tPaint = new Paint();
tPaint.setTextSize(35);
tPaint.setColor(Color.BLUE);
tPaint.setStyle(Style.FILL);
cs.drawBitmap(src, 0f, 0f, null);
float height = tPaint.measureText("yY");
float width = tPaint.measureText(yourText);
float x_coord = (src.getWidth() - width)/2;
cs.drawText(yourText, x_coord, height+15f, tPaint); // 15f is to put space between top edge and the text, if you want to change it, you can
try {
dest.compress(Bitmap.CompressFormat.JPEG, 100, new FileOutputStream(new File("/sdcard/ImageAfterAddingText.jpg")));
// dest is Bitmap, if you want to preview the final image, you can display it on screen also before saving
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
This code generates image from custom text
Don't forget to add permission in Manifest file
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
You have several options. A couple of them:
Use a Map
Keep a Map where the keys is the Question ID in your data base. The values stored in the map for each key could be the Images Views (loaded as resources for instance)
Add a field in DB
Add a field with the relative path of the image and load the corresponding image for every question.
You can store the path as an String in your DB and then recover the image as this:
File imgFile = new File("/path/of/image/image.jpg");
if(imgFile.exists()){
Bitmap myBitmap = BitmapFactory.decodeFile(imgFile.getAbsolutePath());
// This image view is defined as a resource.... just set the bitmap
ImageView myImage = (ImageView) findViewById(R.id.anyImageView);
myImage.setImageBitmap(myBitmap);
}

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