I am making use of cardview and every card has a pop menu which opens another activity. "data" array is displayed on the card and I want the respective array "document_list" to be displayed on opening of other activity. Below is the code but all of the items are getting displayed. So how do I limit or restrict ? data(id) == document_list(property_id).
CARDVIEW FRAGMENT
StringRequest stringRequest = new StringRequest(Request.Method.POST,"URL",
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
//converting the string to json array object
JSONObject object = new JSONObject(response);
if (object.getInt("status") == 200) {
JSONArray jsonArray = object.getJSONArray("data");
// String userData = jsonArray.getString(0);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject pobj = jsonArray.getJSONObject(i);
pobj.getString("id");
JSONObject pobj1 = new JSONObject(pobj.getString("owner_details"));
mylistList.add(new Mylist(
//other elements
pobj.getString("sas_application_no"),
pobj1.getString("name"),
pobj1.getString("mobile")
));
}
}
CARDVIEW ADAPTER
holder.buttonViewOption.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
PopupMenu popup = new PopupMenu(mCtx, holder.buttonViewOption);
popup.inflate(R.menu.options_menu);
popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
#Override
public boolean onMenuItemClick(MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_document:
//handle menu2 click
id = mylist.getId();
Bundle bundle = new Bundle();
bundle.putString("id",id);
DocFragment newfragment1 = new DocFragment();
FragmentTransaction fragmentTransaction1 =((AppCompatActivity)mCtx).getSupportFragmentManager().beginTransaction();
fragmentTransaction1.replace(R.id.container_view1, newfragment1);
fragmentTransaction1.addToBackStack(null);
fragmentTransaction1.commit();
NavigationActivity.container_view1.setVisibility(View.VISIBLE);
break;
}
return false;
}
});
Doc_fragment is the new activity which opens the cardview with below code. So on click of R.id.menu_document: I need to pass the "id" which is to fetched from CARDVIEW FRAGMENT? How do I do it?
public class DocFragment extends Fragment {
//a list to store all the products
List<DocList> docList;
DocAdapter docAdapter;
//the recyclerview
RecyclerView recyclerView;
private String sid = "";
public View onCreateView(#NonNull LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
View root = inflater.inflate(R.layout.fragment_doc, container, false);
if (getArguments() != null) {
sid = getArguments().getString("id");
Toast.makeText(getActivity(), sid, Toast.LENGTH_LONG).show();
}
docList = new ArrayList<>();
recyclerView = (RecyclerView) root.findViewById(R.id.recyclerView1);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
//docList.add(new DocList("abc","123","asdf"));
//creating recyclerview adapter
docAdapter = new DocAdapter(getContext(), docList);
recyclerView.setAdapter(docAdapter);
loadMenuData();
return root;
}
public void loadMenuData() {
StringRequest stringRequest = new StringRequest(Request.Method.POST, "url",
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
//converting the string to json array object
//String selectedId = getIntent().getStringExtra("selectedId");
JSONObject object = new JSONObject(response);
if (object.getInt("status") == 200) {
JSONArray jsonArray = object.getJSONArray("data");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject pobj = jsonArray.getJSONObject(i);
if (!sid.equals(pobj.optString("id", "")))
continue;
JSONArray jsonArray1 = pobj.getJSONArray("document_list");
for (int j = 0; j < jsonArray1.length(); j++) {
JSONObject dobj = jsonArray1.getJSONObject(j);
docList.add(new DocList(
dobj.getString("document_name"),
dobj.getString("description"),
dobj.getString("doc_no")
));
}
}
}
//creating adapter object and setting it to recyclerview
docAdapter = new DocAdapter(getContext(), docList);
recyclerView.setAdapter(docAdapter);
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
//adding our stringrequest to queue
Volley.newRequestQueue(getContext()).add(stringRequest);
}
}
{
"status": 200,
"data": [
{
"id": "5",
"property_type": "AGRICULTURAL",
"name": "A D ",
"site_no": "SY NO 21",
"p_id_no": "21",
"sas_application_no": "13",
"latitude": "12",
"longitude": "33",
"status": "OWNED",
"purchase_year": "2007",
"owner_details": {
"name": "A D",
"mobile": "776006"
},
"size": "41724",
"unit": "SQF",
"document_list": [
{
"property_id": "5",
"document_type_id": "4",
"file_path": "https://demoapi.dyuppar.in/uploads",
"document_name": "Encumbrance Certificate",
"description": null,
"doc_no": null
},
{
"property_id": "5",
"document_type_id": "3",
"file_path": "https://demoapi.dyuppar.in/uploads",
"document_name": "Mother Deed",
"description": null,
"doc_no": null
},
{
"property_id": "5",
"document_type_id": "84",
"file_path": "https://demoapi.dyuppar.in/uploads",
"document_name": "MUTATION COPY ",
"description": null,
"doc_no": null
},
{
"property_id": "5",
"document_type_id": "87",
"file_path": "https://demoapi.dyuppar.in/uploads",
"document_name": "OLD E C",
"description": null,
"doc_no": null
},
{
"property_id": "5",
"document_type_id": "83",
"file_path": "https://demoapi.dyuppar.in/uploads",
"document_name": "OTHER DOCUMENTS ",
"description": null,
"doc_no": null
},
]
},
{
"id": "9",
"property_type": "AGRICULTURAL",
"name": "A D ",
"site_no": "SY NO 19/1 ",
"p_id_no": "19/1",
"sas_application_no": "12",
"latitude": "12",
"longitude": "45",
"status": "OWNED",
"purchase_year": "2007",
"owner_details": {
"name": "A D ",
"mobile": "7760906"
},
"size": "2",
"unit": "ACR",
"document_list": [
{
"property_id": "9",
"document_type_id": "4",
"file_path": "https://demoapi.dyuppar.in/uploads",
"document_name": "Encumbrance Certificate",
"description": null,
"doc_no": null
},
{
"property_id": "9",
"document_type_id": "43",
"file_path": "https://demoapi.dyuppar.in/uploads",
"document_name": "GPA",
"description": null,
"doc_no": null
},
]
},
You can do something like this:
In your CardViewFragment set the arguments when the card is selected like following:
switch (item.getItemId()) {
case R.id.menu_document:
//handle menu2 click
Bundle bundle = new Bundle();
bundle.putString("selectedId",selectedId);//get this id from your object/model .e.g list.get(postion).getId() , do it as per your strcuture setup.
DocFragment newfragment1 = new DocFragment();
newfragment1.setArguments(bundle);
FragmentTransaction fragmentTransaction1 =((AppCompatActivity)mCtx).getSupportFragmentManager().beginTransaction();
fragmentTransaction1.replace(R.id.container_view1, newfragment1);
fragmentTransaction1.addToBackStack(null);
fragmentTransaction1.commit();
NavigationActivity.container_view1.setVisibility(View.VISIBLE);
break;
}
In your DocFragment create a global variable and match it with the data coming from your source.
private String selectedId = "";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
selectedId = getArguments().getString("selectedId");
}
}
Then match that id while fetching in DocFragment
try {
//converting the string to json array object
JSONObject object = new JSONObject(response);
if (object.getInt("status") == 200) {
JSONArray jsonArray = object.getJSONArray("data");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject pobj = jsonArray.getJSONObject(i);
// compare id passed from main activity, which was selected by user
if (!selectedId.equals(pobj.optString("id", "")))
continue;
JSONArray jsonArray1 = pobj.getJSONArray("document_list");
for (int j = 0; j < jsonArray1.length(); j++) {
JSONObject dobj = jsonArray1.getJSONObject(j);
docList.add(new DocList(
dobj.getString("document_name"),
dobj.getString("description"),
dobj.getString("doc_no")
));
}
}
}
} catch (Exception e) {
}
Related
I'm trying to retrieve the objects inside a json array such as id and brand within creditcard.
{
"result_count": "2",
"total_no_of_rows": "2",
"status": {
"status_code": "-1",
"status_text": "Success"
},
"cards": [
{
"creditCard": {
"id": "CRC-9C7I2BGN8RJY",
"brand": "AMEX",
"first6": "376449",
"last4": "3005",
"store": true
},
"method": "CREDIT_CARD"
},
{
"creditCard": {
"id": "CRC-FXDA9E2YCWWQ",
"brand": "ELO",
"first6": "636297",
"last4": "7013",
"store": true
},
"method": "CREDIT_CARD"
}
]
}
I'm using the request below unsuccessfully because it returns card with no values.
JsonObjectRequest req = new JsonObjectRequest(Request.Method.GET,
url, null, response -> {
arrayData.clear();
try {
JSONArray cards = response.getJSONArray("cards");
for (int i = 0; i < cards.length(); i++) {
JSONObject token = cards.getJSONObject(i);
CardList card = new CardList(
token.getString("id"),
token.getString("brand"),
token.getString("first6"),
token.getString("last4"),
token.getBoolean("store"));
arrayData.add(card);
}
Log.v("arrayData", String.valueOf(arrayData));
} catch (JSONException e) {
Log.v("arrayDataError", String.valueOf(e));
e.printStackTrace();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.v("arrayDataError", String.valueOf(error));
}
});
Could someone help? Thanks.
Follows the solution for those who need it:
JSONArray cards = response.getJSONArray("cards");
for (int i = 0; i < cards.length(); i++) {
JSONObject token = cards.getJSONObject(i);
JSONObject creditCard = token.getJSONObject("creditCard");
card_method = token.getString("method").equals("CREDIT_CARD") ?
getString(R.string.creditcard) : getString(R.string.debitcard);
CardList card = new CardList(
creditCard.getString("id"),
creditCard.getString("brand"),
creditCard.getString("first6"),
creditCard.getString("last4"),
creditCard.getBoolean("store"));
arrayData.add(card);
}
In my Android app, I am fetching the details of Points table of a tournament to convert the output to a string from JSON object to Java
JSON object is shown below:
{
"group": {
"Teams": [
{
"name": "Team 1",
"p": "10",
"w": "9",
"l": "1",
"points": "18"
},
{
"name": "Team 2",
"p": "10",
"w": "9",
"l": "1",
"points": "18"
},
{
"name": "Team 3",
"p": "10",
"w": "9",
"l": "1",
"points": "18"
},
{
"name": "Team 4",
"p": "10",
"w": "6",
"l": "4",
"points": "12"
},
{
"name": "Team 5",
"p": "10",
"w": "6",
"l": "4",
"points": "12"
},
{
"name": "Team 6",
"p": "10",
"w": "6",
"l": "4",
"points": "12"
},
{
"name": "Team 7",
"p": "10",
"w": "5",
"l": "5",
"points": "11"
},
{
"name": "Team 8",
"p": "10",
"w": "5",
"l": "5",
"points": "11"
}
]
}
}
Android Java Code is below:
JSONObject match = new JSONObject(response);
if (match.has("group")) {
JSONObject group = match.getJSONObject("group");
if (match.has("Teams")) {
JSONObject teams = group.getJSONObject("Teams");
if (teams.has("0")) {
JSONObject teams_object = teams.getJSONObject("0");
String team_name = teams_object.getString("name");
String matches_played = teams_object.getString("p");
String matches_won = teams_object.getString("w");
String matches_lost = teams_object.getString("l");
String points = teams_object.getString("points");
}
}
}
But I am getting the error where I print the error message through getMessage() method. Here is the error below:
Error: Value ["name","p","w","l","points"] at header of type org.json.JSONArray cannot be converted to JSONObject
Can anyone please help like where I am going wrong or what is the fix ? Thanks in advance
In your Json Teams holds the Array of Object and you are parsing wrong.
Try this
JSONObject jsonObject = new JSONObject(response);
JSONObject groups = jsonObject.getJSONObject("group");
JSONArray teams = groups.getJSONArray("Teams");
for(int i=0;i<teams.length();i++){
JSONObject obj = teams.getJSONObject(i);
name.append(obj.getString("name")+"\n");
}
There is 4 mistakes in your code,
1.You have to check whether group has teams instead match has teams.
2.You have to get team as JSONArray instead of JSONObject because it is array.
3.You have to check the size of team, instead of find the object with key 0, there is no object with name 0 in your group,
4.You have to get the object based on index instead of key(ie., 0)
Please check the working code, this is tested
try {
JSONObject match = new JSONObject(response);
if (match.has("group")) {
JSONObject group = match.getJSONObject("group");
if (group.has("Teams")) {
JSONArray teams = group.getJSONArray("Teams");
if (teams.length() > 0) {
JSONObject teams_object =(JSONObject) teams.get(0);
String team_name = teams_object.getString("name");
String matches_played = teams_object.getString("p");
String matches_won = teams_object.getString("w");
String matches_lost = teams_object.getString("l");
String points = teams_object.getString("points");
Log.v(TAG, team_name);
}
}
}
} catch (JSONException e) {
e.printStackTrace();
}
try {
JSONObject jsonObject = new JSONObject(response.body().string());
JSONObject subObject = jsonObject.getJSONObject("group") ;
JSONArray jsonArray = subObject.getJSONArray("Teams");
for (int i=0; i<jsonArray.length(); i++){
JSONObject object = jsonArray.getJSONObject(i);
String name = jsonObject.getString("name");
String p= jsonObject.getString("p");
String w= jsonObject.getString("w");
String l= jsonObject.getString("l");
String points = jsonObject.getString("points");
}
} catch (Exception e) {
e.printStackTrace();
}
if (match.has("group")) {
JSONObject group = match.getJSONObject("group");
if (match.has("Teams")) {
JSONArray teams = group.getJSONArray("Teams");
// for only 0th element use below code else looping
JSONObject teams_object = (JSONObject) teams.get(0);
String team_name = teams_object.getString("name");
String matches_played = teams_object.getString("p");
String matches_won = teams_object.getString("w");
String matches_lost = teams_object.getString("l");
String points = teams_object.getString("points");
}
}
Error: Value ["name","p","w","l","points"] at header of type
org.json.JSONArray cannot be converted to JSONObject
You are getting the error because there is an Array of Teams and you are trying parse with JSONObject
Please check below code snippet. It will work.
try {
JSONObject match = new JSONObject("your_response");
if (match.has("group")) {
JSONObject group = match.getJSONObject("group");
if (group.has("Teams")) {
JSONArray teams = group.getJSONArray("Teams");
for(int i=0; i < teams.length(); i++){
JSONObject teams_object = (JSONObject) teams.get(i);
String team_name = teams_object.getString("name");
String matches_played = teams_object.getString("p");
String matches_won = teams_object.getString("w");
String matches_lost = teams_object.getString("l");
String points = teams_object.getString("points");
}
}
}
} catch (JSONException e) {
e.printStackTrace();
}
Try this #SaAsh, I have just edited by taking your answer
if (match.has("group")) {
JSONObject group = match.getJSONObject("group");
if (match.has("Teams")) {
JSONObject teams = group.getJsonArray("Teams");
for(int i = 0 ; i < teams.length();i++){
JSONObject teams_object = teams.getJSONObject("i");
String team_name = teams_object.getString("name");
String matches_played = teams_object.getString("p");
String matches_won = teams_object.getString("w");
String matches_lost = teams_object.getString("l");
String points = teams_object.getString("points");
}
}
}
}
I am getting data from the json. I have sorted the country name accordingly alphabetically.but when i click on the spinner item i am getting the worng id of the item.can anyone tell me how can i get the id of the sorted item of the spinner.
This is my json:-
{
"Status": 1,
"StatusMessage": "Country and Country Area List",
"data": [
{
"CountryID": "1",
"CountryName": "India",
"CountryArea": [
{
"CountryID": "1",
"AreaID": "1",
"AreaName": "Kuwait City(Capital)"
},
{
"CountryID": "1",
"AreaID": "2",
"AreaName": " Hawally"
},
]
},
{
"CountryID": "2",
"CountryName": "Dubai",
"CountryArea": [
{
"CountryID": "2",
"AreaID": "6",
"AreaName": " Jeddah"
},
{
"CountryID": "2",
"AreaID": "7",
"AreaName": " Riyadh"
This is the method by which i am getting data from the json :-
public void requestDataCountry() {
mProgressDialog.show();
StringRequest countrylistrequest = new StringRequest(Request.Method.GET, GlobalData.COUNTRYLISTURL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
mProgressDialog.dismiss();
final JSONObject jObject = new JSONObject(response);
if (jObject.getString("Status").equals("1")) {
JSONArray jsonArray = jObject.getJSONArray("data");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
mCountryName = jsonObject.getString("CountryName");
mId = jsonObject.getString("CountryID");
mCountryList.add(mCountryName);
Collections.sort(mCountryList);
getCountryId.add(mId);
JSONArray jsonArray1 = jsonObject.getJSONArray("CountryArea");
for (int j = 0; j < jsonArray1.length(); j++) {
JSONObject jsonObject1 = jsonArray1.getJSONObject(j);
String countryAreaId = jsonObject1.getString("CountryID");
mAreaName = jsonObject1.getString("AreaName");
mAreaList.add(mAreaName);
}
}
countryAdapter.notifyDataSetChanged();
} else {
}
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError volleyError) {
}
}) {
};
RequestQueue countryqueue = Volley.newRequestQueue(getContext());
countryqueue.add(countrylistrequest);
}
This is my Spinner Code :-
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.menu, menu);
super.onCreateOptionsMenu(menu, inflater);
this.menu = menu;
MenuItem menuItem = menu.findItem(R.id.menu_spinner).setVisible(true);
mCountrySpinner = (Spinner) MenuItemCompat.getActionView(menuItem);
countryAdapter = new ArrayAdapter<String>(getContext(), android.R.layout.simple_spinner_dropdown_item, mCountryList);
countryAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
mCountrySpinner.setAdapter(countryAdapter);
mCountrySpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
mCountrySerachId = getCountryId.get(position);
mEditor.putString(KEY_COUNTRY_ID, mCountrySerachId);
mEditor.commit();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
}
My problem is when i click on the spinner item like i click on Dubai(CountryName)as per my json then i am getting the id 1(CountryID).while i click on the Dubai(CountryName) it should get the id 2(CountryID). i knew the problem i sorted the CountryName but i did not sort the CountryID.then my question is how can i sort the CountryID according to the CountryName.
Save your parsed values(ID and Country name) in a Hashmap. Then sort the hashmap using the code below.
public LinkedHashMap<Integer, String> sortHashMapByValues(
HashMap<Integer, String> passedMap) {
List<Integer> mapKeys = new ArrayList<>(passedMap.keySet());
List<String> mapValues = new ArrayList<>(passedMap.values());
Collections.sort(mapValues);
Collections.sort(mapKeys);
LinkedHashMap<Integer, String> sortedMap =
new LinkedHashMap<>();
Iterator<String> valueIt = mapValues.iterator();
while (valueIt.hasNext()) {
String val = valueIt.next();
Iterator<Integer> keyIt = mapKeys.iterator();
while (keyIt.hasNext()) {
Integer key = keyIt.next();
String comp1 = passedMap.get(key);
String comp2 = val;
if (comp1.equals(comp2)) {
keyIt.remove();
sortedMap.put(key, val);
break;
}
}
}
return sortedMap;
}
I am new in android dev i am fetch data from URL and want to set name in spinner and send their id to server
MY JSON
{
"data": [{
"name": "RELIANCE CDMA",
"ID": "1"
}, {
"name": "IDEA",
"ID": "5"
}, {
"name": "AIRTEL",
"ID": "7"
}, {
"name": "MTNL DELHI",
"ID": "8"
}, {
"name": "MTNL MUMBAI",
"ID": "8"
}, {
"name": "VODAFONE",
"ID": "12"
}, {
"name": "LOOP",
"ID": "13"
}, {
"name": "BSNL",
"ID": "14"
}, {
"name": "AIRCEL",
"ID": "19"
}, {
"name": "TATA INDICOM",
"ID": "23"
}, {
"name": "VIRGIN CDMA",
"ID": "27"
}, {
"name": "RELIANCE GSM",
"ID": "32"
}, {
"name": "TATA DOCOMO",
"ID": "35"
}, {
"name": "VIRGIN GSM",
"ID": "36"
}, {
"name": "MTS",
"ID": "38"
}, {
"name": "UNINOR",
"ID": "41"
}, {
"name": "VIDEOCON",
"ID": "43"
}, {
"name": "T24",
"ID": "52"
}]
}
and i am using this code
in android
CODE
private class DownloadJSON extends AsyncTask<Void, Void, Void> {
protected Void doInBackground(Void... params) {
json_data = new ArrayList<Json_Data>();
datalist = new ArrayList<String>();
jsonobject = JSONfunctions
.getJSONfromURL("http://www.myurl.com/index.php"); // example only
Log.d("Response: ", "> " + jsonobject);
try {
jsonarray = jsonobject.getJSONArray("data");
for (int i = 0; i < jsonarray.length(); i++) {
jsonobject = jsonarray.getJSONObject(i);
Json_Data worldpop = new Json_Data();
worldpop.setName(jsonobject.optString("name"));
worldpop.setId(jsonobject.optString("ID"));
json_data.add(worldpop);
datalist.add(jsonobject.optString("name"));
}
} catch (Exception e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return null;
}
protected void onPostExecute(Void args) {
Spinner mySpinner = (Spinner)getView().findViewById(R.id.operator_spinner);
mySpinner
.setAdapter(new ArrayAdapter<String>(getActivity(),
android.R.layout.simple_spinner_dropdown_item,
datalist));
mySpinner
.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> arg0,
View arg1, int position, long arg3) {
String opt_code = datalist.get(position);
}
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
}
}
but this code only show name in spinner but not select any id form my json
It should be:
private class DownloadJSON extends AsyncTask<Void, Void, Void> {
protected Void doInBackground(Void... params) {
json_data = new ArrayList<Json_Data>();
datalist = new ArrayList<Pair<String, String>>();
jsonobject = JSONfunctions
.getJSONfromURL("http://www.myurl.com/index.php"); // example only
Log.d("Response: ", "> " + jsonobject);
try {
jsonarray = jsonobject.getJSONArray("data");
for (int i = 0; i < jsonarray.length(); i++) {
jsonobject = jsonarray.getJSONObject(i);
Json_Data worldpop = new Json_Data();
worldpop.setName(jsonobject.optString("name"));
worldpop.setId(jsonobject.optString("ID"));
json_data.add(worldpop);
datalist.add(new Pair<String, String>(jsonobject.optString("ID"), jsonobject.optString("name"));
}
} catch (Exception e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return null;
}
protected void onPostExecute(Void args) {
Spinner mySpinner = (Spinner) getView().findViewById(R.id.operator_spinner);
mySpinner
.setAdapter(new ArrayAdapter<String>(getActivity(),
android.R.layout.simple_spinner_dropdown_item,
datalist));
mySpinner
.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> arg0,
View arg1, int position, long arg3) {
String opt_code = datalist.get(position).first;
}
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
}
}
But it seems to me that you don't understand what's going on in that code, so highly suggest to sort out in that.
And one more advice - don'y use AsyncTask, and take a look on Retrofit.
i want to parse userinfo Array and some string in it. and getuserlistdata array and some string in it. please help me how to parse this response.This is my respons.
{
"status": "true",
"data": {
"userinfo": [
{
"id": "77",
"firstname": "Test",
}
],
"getuserlistdata": [
{
"address": "Kasauli, Himachal Pradesh, India"
"hostImage": [
{
"id": "551",
"hostid": "122",
"images": "user_21t657.jpg",
"description": ""
},
{
"id": "3954",
"hostid": "122",
"images": "user_251541535.jpg",
"description": ""
},
],
]
}
}
Sir, This my code.
protected Void doInBackground(Void...arg0) {
// Creating service handler class instance
ServiceHandler2 sh = new ServiceHandler2();
String url_links = "http://192.168.0.65/hostandguest/android/viewprofile?uid=77";
Log.d("url_links: ", "> " + url_links);
String jsonStr = sh.makeServiceCall(url_links, ServiceHandler2.GET);
Log.v("Profile:", "> " + jsonStr);
if (jsonStr != null) {
try {
JSONObject obj = new JSONObject(jsonStr);
status = obj.getString("status");
data = obj.getString("data");
if (status.equalsIgnoreCase("false")) {
} else {
jsonarr = obj.getJSONArray("userinfo");
for (int i = 0; i < jsonarr.length(); i++) {
JSONObject c = jsonarr.getJSONObject(i);
String fname = c.getString("firstname");
Datein_arr.add(fname);
String id = c.getString("id");
}
jsonarr2 = obj.getJSONArray("getuserlistdata");
for (int j = 0; j < jsonarr2.length(); j++) {
JSONObject jo = jsonarr2.getJSONObject(j);
address = jo.getString("address");
Log.v("address", "" + address);
Log.v("Profile:", "777777777777777777777777777777777777");
hostimgrr2 = obj.getJSONArray("hostImage");
if (hostimgrr2.length() == 0) {
ch_img.add("https://s3-ap-southeast-1.amazonaws.com/nanoweb/hostguesthome/uploadedfile/hostImages/user_12707aaf22_original.jpg");
det_img.add("https://s3-ap-southeast-1.amazonaws.com/nanoweb/hostguesthome/uploadedfile/hostImages/user_12707aaf22_original.jpg");
} else {
for (int k = 0; k < hostimgrr2.length(); k++) {
JSONObject js = hostimgrr2.getJSONObject(k);
img = js.getString("images");
Log.v("img", "" + img);
if (k == 0) {
ch_img.add("https://s3-ap-southeast-1.amazonaws.com/nanoweb/hostguesthome/uploadedfile/hostImages/" + img);
}
ch_img.add("https://s3-ap-southeast-1.amazonaws.com/nanoweb/hostguesthome/uploadedfile/hostImages/" + img);
}
}
}
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Try like below code to parse JSONArray.
try {
private ArrayList<UserInfo> userInfoList = new ArrayList<UserInfo>();
JSONObject jsonObject = new JSONObject(jsonData); // jsonData is your reponse string
JSONArray userinfo = jsonData.getJSONArray("userinfo");
for(int i = 0; i < userinfo.length(); i++) {
JSONObject jObject = userinfo.getJSONObject(i);
UserInfo userInfo = new UserInfo();
userInfo.setId( jObject.getString("id") );
userInfo.setFirstname( jObject.getString("firstname") );
userInfoList.add(userInfo);
}
} catch (Exception e) {
e.printStackTrace();
}
UserInfo class as follow.
public class UserInfo {
public String id = "";
public String firstname = "";
public String getID() {
return coursePrice;
}
public void setID(String id) {
this.id = id;
}
public String getFirstname() {
return coursePrice;
}
public void setFirstname(String firstname) {
this.firstname = firstname;
}
}
First you have to validate your jsondata.
You can goto JSONLint to check whether your json is valid or not
{
"status": "true",
"data": {
"userinfo": [
{
"id": "77",
"firstname": "Test"
}
],
"getuserlistdata": [
{
"address": "Kasauli, Himachal Pradesh, India",
"hostImage": [
{
"id": "551",
"hostid": "122",
"images": "user_21t657.jpg",
"description": ""
},
{
"id": "3954",
"hostid": "122",
"images": "user_251541535.jpg",
"description": ""
}
]
}
]
}
}
And You are parsing a JSONObject as String.
ie, it should be obj.getJSONObject("data"); instead of obj.getString("data");
Also check for other parsing issues like this.