JSON Parsing Issue with Spinners
Asked Answered
S

5

11

All my spinners are connected with each other, they are not independent, I would like to show options in spinner2 and spinner3 based on the selection in spinner1 (I mean based on category chosen by user in spinner1)

In onCreate I am populating data into Spinners, but in spinner2 and spinner3 I am getting data that belongs to CategoryB whereas they must populate with CategoryA data only.

So where is my mistake? Here is my JSON Parsing code:

               categoryArrayList = new ArrayList<Category>();
               cArrayList = new ArrayList<String>();

                ...................................

                // Array Level 1 --- START
            JSONArray jarray = jsono.getJSONArray("categories");

            for (int i = 0; i < jarray.length(); i++) {
                JSONObject object = jarray.getJSONObject(i);

                Category language = new Category();                     
                language.setName(object.getString("category_name"));
                Log.d("category_name::-", object.getString("category_name"));

                language.setTypeArrayList(typeArrayList);
                categoryArrayList.add(language);
                cArrayList.add(categoryArrayList.get(i).getName());

                // Array Level 1 --- END

                // Array Level 2 --- START

                JSONArray jsarray = object.getJSONArray("types");
                typeArrayList = new ArrayList<Type>();
                tArrayList = new ArrayList<String>();
                for (int j = 0; j < jsarray.length(); j++) {
                    JSONObject jjobject = jsarray.getJSONObject(j);

                    Type genre = new Type();

                    genre.setName(jjobject.getString("type_name"));
                    Log.d("type_name::-", jjobject.getString("type_name"));     

                    genre.setServiceArrayList(serviceArrayList);
                    typeArrayList.add(genre);
                    tArrayList.add(typeArrayList.get(j).getName());     

                    // Array Level 2 --- END

                    // Array Level 3 --- START

                    JSONArray jsonarray = jjobject.getJSONArray("services");
                    serviceArrayList = new ArrayList<Service>();
                    sArrayList = new ArrayList<String>();
                    for (int k = 0; k < jsonarray.length(); k++) {
                        JSONObject jjjobject = jsonarray.getJSONObject(k);

                        Service movie = new Service();

                        movie.setName(jjjobject.getString("service_name"));
                        Log.d("service_name::-", jjjobject.getString("service_name"));

                        serviceArrayList.add(movie);    
                        sArrayList.add(serviceArrayList.get(k).getName());

                        // Array Level 3 --- END
                    }

                }       

            }

            return true;
        }

And here is how i am populating Spinners:

            spinner1.setAdapter(new ArrayAdapter<String>(CategoryActivity.this,
                     android.R.layout.simple_spinner_dropdown_item,
                     cArrayList));

            spinner2.setAdapter(new ArrayAdapter<String>(CategoryActivity.this,
                    android.R.layout.simple_spinner_dropdown_item,
                    tArrayList));

            spinner3.setAdapter(new ArrayAdapter<String>(CategoryActivity.this,
                    android.R.layout.simple_spinner_dropdown_item,
                    sArrayList));
Stralka answered 11/9, 2015 at 5:3 Comment(15)
I think you should correct you expected out in spinner3 because it do not refer to Category A arrayLevey
@Mohit but my spinners are connected with each other if user select Category A in spinner1 then only show data that belongs to CategoryA in spinner2 and spinner3, in a same way for CategoryB...Stralka
that's what I am reffering ....please trace you expected output to your json..I mean there is no CatA TypeB ServiceA in "category_name":"Category A",Levey
@Oreo: you doing in wrong wayHolytide
Can you please post what exact value should be in spinner2,spinner3 when your select "Category A"Levey
@Oreo: your problem solved?Holytide
@ρяσѕρєяK no bhaiya still facing issue, tried everything i know, now i need your helpStralka
@Oreo: try it as pastebin.com/QsWbwb7wHolytide
@ρяσѕρєяK bhaiya getting: Type mismatch: cannot convert from String to ArrayList<Type> : at this point: ArrayList<Type> arrtype_name=categoryArrayList.get(0).getName();Stralka
Use getarrtype_name instead of getNameHolytide
@ρяσѕρєяK bhaiya getting NPE here: ArrayList<Type> arrtype_name=categoryArrayList.get(0).getTypeArrayList(); ... check this: paste.ofcode.org/kqe4pnLiQ88hQTZRU6zdYFStralka
Let us continue this discussion in chat.Holytide
@Oreo: please show parsing codeHolytide
@Stralka can you provide the JSON data?Tetrabranchiate
@ρяσѕρєяK bhaiya aapke bhai ko apki help chahiye: #32946941Stralka
B
5

Oreo. Here is the full code.

Category class

public class Category {

    String name;
    ArrayList<ArrayList<Type>> type;
    Category()
    {
        name = "";
        type = new ArrayList<ArrayList<Type>>(); 
    }

    void setName(String s)
    {
        name =s;
    }

    public String getName()
    {
        return name;
    }

    void setTypeArrayList(ArrayList<Type> serviceArrayList)
    {
        type.add(serviceArrayList);
    }

    ArrayList<Type> getTypeArrayList(int i)
    {
        return type.get(i);
    }
}

Type class

import java.util.ArrayList;

public class Type {
    String type;
    ArrayList<ArrayList<Service>> service;

    public Type() {
        // TODO Auto-generated constructor stub
        type = "";
        service = new ArrayList<ArrayList<Service>>();
    }
    void setName(String s)
    {
        type =s;
    }

    public String getName()
    {
        return type;
    }

    void setServiceArrayList(ArrayList<Service> serviceArrayList)
    {
        service.add(serviceArrayList);
    }

    ArrayList<Service> getServiceArrayList(int i)
    {
        return service.get(i);
    }
}

Service class

public class Service {

    String service;

    public Service() {
        // TODO Auto-generated constructor stub
        service ="";
    }

    void setName(String s)
    {
        service =s;
    }

    public String getName()
    {
        return service;
    }
}

initialize global

 int catpos =0;
 ArrayList<Category> categoryArrayList = new ArrayList<Category>();
 ArrayList<String> cArrayList = new ArrayList<String>();
 ArrayList<Type> typeArrayList;
 ArrayList<Service> serviceArrayList;

doInbackground

    //your http request and response process


    JSONObject jsono;
    try {
        jsono = new JSONObject(data);

        JSONArray jarray = jsono.getJSONArray("categories");

        for (int i = 0; i < jarray.length(); i++) {
            JSONObject object = jarray.getJSONObject(i);

            Category language = new Category();
            language.setName(object.getString("category_name"));
            Log.d("category_name::-", object.getString("category_name"));

            JSONArray jsarray = object.getJSONArray("types");
            typeArrayList = new ArrayList<Type>();
            tArrayList = new ArrayList<String>();
            for (int j = 0; j < jsarray.length(); j++) {
                JSONObject jjobject = jsarray.getJSONObject(j);

                Type genre = new Type();

                genre.setName(jjobject.getString("type_name"));
                Log.d("type_name::-", jjobject.getString("type_name"));

                JSONArray jsonarray = jjobject.getJSONArray("services");
                serviceArrayList = new ArrayList<Service>();
                sArrayList = new ArrayList<String>();
                for (int k = 0; k < jsonarray.length(); k++) {
                    JSONObject jjjobject = jsonarray.getJSONObject(k);

                    Service movie = new Service();

                    movie.setName(jjjobject.getString("service_name"));
                    Log.d("service_name::-",
                            jjjobject.getString("service_name"));

                    serviceArrayList.add(movie);
                    sArrayList.add(serviceArrayList.get(k).getName());
                }
                genre.setServiceArrayList(serviceArrayList);
                typeArrayList.add(genre);
                tArrayList.add(typeArrayList.get(j).getName());
            }

            language.setTypeArrayList(typeArrayList);
            categoryArrayList.add(language);
            cArrayList.add(categoryArrayList.get(i).getName());

        }
    } catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

onPostExecute Method

    tArrayList = new ArrayList<String>();
    sArrayList = new ArrayList<String>();

    Category c = categoryArrayList.get(0);      
    typeArrayList = c.getTypeArrayList(0);
    for(int i=0;i<typeArrayList.size();i++)
        tArrayList.add(typeArrayList.get(i).getName());
    Type t = typeArrayList.get(0);
    serviceArrayList = t.getServiceArrayList(0);
    for(int i=0;i<serviceArrayList.size();i++)
        sArrayList.add(serviceArrayList.get(i).getName());

    spinner1.setAdapter(new ArrayAdapter<String>(CategoryActivity.this,
            android.R.layout.simple_spinner_dropdown_item, cArrayList));

    spinner2.setAdapter(new ArrayAdapter<String>(CategoryActivity.this,
            android.R.layout.simple_spinner_dropdown_item, tArrayList));


    spinner3.setAdapter(new ArrayAdapter<String>(CategoryActivity.this,
            android.R.layout.simple_spinner_dropdown_item, sArrayList));

    spinner1.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
        public void onItemSelected(AdapterView<?> parent, View view,
                int pos, long id) {

            catpos = pos;
            tArrayList = new ArrayList<String>();
            sArrayList = new ArrayList<String>();
            Category c = categoryArrayList.get(pos);        
            typeArrayList = c.getTypeArrayList(0);
            for(int i=0;i<typeArrayList.size();i++)
                tArrayList.add(typeArrayList.get(i).getName());
            Type t = typeArrayList.get(0);
            serviceArrayList = t.getServiceArrayList(0);
            for(int i=0;i<serviceArrayList.size();i++)
                sArrayList.add(serviceArrayList.get(i).getName());

            spinner2.setAdapter(new ArrayAdapter<String>(CategoryActivity.this,
                    android.R.layout.simple_spinner_dropdown_item, tArrayList));


            spinner3.setAdapter(new ArrayAdapter<String>(CategoryActivity.this,
                    android.R.layout.simple_spinner_dropdown_item, sArrayList));


        }

        @Override
        public void onNothingSelected(AdapterView<?> arg0) {
            // TODO Auto-generated method stub

        }
    });

    spinner2.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
        public void onItemSelected(AdapterView<?> parent, View view,
                int pos, long id) {

            sArrayList = new ArrayList<String>();
            Category c = categoryArrayList.get(catpos);     
            typeArrayList = c.getTypeArrayList(0);              
            Type t = typeArrayList.get(pos);
            serviceArrayList = t.getServiceArrayList(0);
            for(int i=0;i<serviceArrayList.size();i++)
                sArrayList.add(serviceArrayList.get(i).getName());

            spinner3.setAdapter(new ArrayAdapter<String>(CategoryActivity.this,
                    android.R.layout.simple_spinner_dropdown_item, sArrayList));                
        }

        @Override
        public void onNothingSelected(AdapterView<?> arg0) {
            // TODO Auto-generated method stub

        }
    });
Bathrobe answered 11/9, 2015 at 6:21 Comment(10)
sorry but i need solution in my existing code, because i know i am doing a very little mistake.. would you point out me my mistake, ok just let me know how can i use this line in my code as per my existing code: tArrayList = hasMap.get(categories.get(0));Stralka
did u populate the spinner each time spinner item change?Bathrobe
can you just tell me, what i have should write in my existing code to get this: tArrayList = hasMap.get(categories.get(0)); because this is the only thing i am missing in my code, this will show spinner2 with categoryA items only in onCreateStralka
if you did your tArrayList and sArrayList contains the last loop values that's category B -->types on your tArrayList and types 2nd service on your sArrayList.Bathrobe
i know that's why i am asking you for the solution, modify this line as per my existing code: tArrayList = hasMap.get(categories.get(0));Stralka
that is initialize the spinner on onCreate method. categories.get(0) returns first "Category A" type.Bathrobe
yes i know that's why i am saying modify this line as per my existing codeStralka
categoryArrayList.get(cArrayList.get(0));Bathrobe
did u got the answer?Bathrobe
here is my attempt with your method : #32536112Stralka
N
2

This should do what you want, however, I am not sure why you are reading a json, but you seems to know the content already. i.e. you want something so specific in spinner 3

           categoryArrayList = new ArrayList<Category>();
           cArrayList = new ArrayList<String>();

            ...................................

            JSONArray jarray = jsono.getJSONArray("categories");

            for (int i = 0; i < jarray.length(); i++) {
                JSONObject object = jarray.getJSONObject(i);

                Category language = new Category();                     
                language.setName(object.getString("category_name"));
                Log.d("category_name::-", object.getString("category_name"));

                language.setTypeArrayList(typeArrayList);
                categoryArrayList.add(language);
                cArrayList.add(categoryArrayList.get(i).getName());

            }

            JSONArray jsarray = jarray.getJSONObject(0).getJSONArray("types");
            typeArrayList = new ArrayList<Type>();
            tArrayList = new ArrayList<String>();
            for (int j = 0; j < jsarray.length(); j++) {
                JSONObject jjobject = jsarray.getJSONObject(j);

                Type genre = new Type();

                genre.setName(jjobject.getString("type_name"));
                Log.d("type_name::-", jjobject.getString("type_name"));                     

                genre.setServiceArrayList(serviceArrayList);
                typeArrayList.add(genre);
                tArrayList.add(typeArrayList.get(j).getName());         
            }       

            JSONArray jsonarray = jsarray.getJSONObject(1).getJSONArray("services");
            serviceArrayList = new ArrayList<Service>();
            sArrayList = new ArrayList<String>();
            for (int k = 0; k < jsonarray.length(); k++) {
                JSONObject jjjobject = jsonarray.getJSONObject(k);

                Service movie = new Service();

                movie.setName(jjjobject.getString("service_name"));
                Log.d("service_name::-", jjjobject.getString("service_name"));

                serviceArrayList.add(movie);    
                sArrayList.add(serviceArrayList.get(k).getName());
            }
            return true;
Notability answered 11/9, 2015 at 5:36 Comment(1)
no not at all my all the spinners are connected with each other (if i have to make them) they are not independent, i would like to show options in spinner2 and spinner3 based on the selection in spinner1Stralka
L
2

My strategy would be:

1) First, populate your spinner 1 and populate your spinner 2, 3 according to selected item (which is first item) of spinner 1.

2) Put spinner1.setOnItemSelectedListener() and send an event when item is changed on spinner 1 inside this method. To send event, use Otto.

3) Register Otto on your Activity, Fragment and @Subscribe to that event. So when you select item in spinner 1 you will get notified immediately inside @Subscribe and you have to change your spinner 2,3 with spinner1.setAdapter() and spinner2.setAdapter() in there.

Longobard answered 16/9, 2015 at 7:26 Comment(0)
G
2

You tArrayList is being populated wrongly. You're populating your Spinner with this code:

        spinner2.setAdapter(new ArrayAdapter<String>(CategoryActivity.this,
                android.R.layout.simple_spinner_dropdown_item,
                tArrayList));

But the variable tArrayList is only getting the last value that it reads. You're using a for loop, but on every loop you restart the tArrayList variable, so at the end it will have only the last value.

[...]
for (int i = 0; i < jarray.length(); i++) {
        [...]
        tArrayList = new ArrayList<String>();

One of the solutions could be something like that:

  • Create a List of Lists
  • At each loop, you create a new tArrayList variable and initialize it.
  • At the end of the second for loop (where you populate it) you add the created list to the global list of lists.
  • When you select and option from the spinner1, you get that position from the List of list and use it to populate your spinner2.


List<List<String>> tArrayListOfLists = new ArrayList<ArrayList<>>();
for(...){ // First for loop
    List<String> tArrayList = new ArrayList<>();
    for(...) { // Second for loop
         tArrayList.add("your strings");
    }
    tArrayListOfLists.add(tArrayList);
}

Then you'll have a list of lists with the items you need. To list for the user selection on the spinner and fill it:

spinner1.setOnItemSelectedListener(new OnItemSelectedListener() 
{
    @Override
    public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) 
    {
        // Get the selected position
        List<String> selectedList = tArrayListOfLists.get(position);

        spinner2.setAdapter(new ArrayAdapter<String>(CategoryActivity.this,
        android.R.layout.simple_spinner_dropdown_item, selectedList));
    }

    @Override
    public void onNothingSelected(AdapterView<?> parentView) {
        // Clear the list 2
    }
});
Gilson answered 16/9, 2015 at 14:40 Comment(0)
G
2

Taken from this site:

This example shows how to populate second spinner based on selection of first spinner.

XML: Layout File Entry

res/layout/activity_spinner_ex4.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <!-- Label -->

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:padding="8dip"
        android:text="@string/lblAcc" />

    <!-- Spinner Dropdown -->

    <Spinner
        android:id="@+id/spinner1"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_marginLeft="8dip"
        android:layout_marginRight="8dip"
        android:layout_marginTop="10dip"
        android:entries="@array/acc_type" />

    <!-- Select Label -->

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:padding="8dip"
        android:text="@string/lblSubAcc" />

    <!-- Spinner Dropdown -->
    <Spinner
        android:id="@+id/spinner2"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dip"
        android:layout_marginLeft="8dip"
        android:layout_marginRight="8dip"
    />
</LinearLayout>

XML: Strings File Entries

res/values/strings.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>

    <string name="app_name">Spinner Example</string>
    <string name="action_settings">Settings</string>
    <string name="lblAcc">Select Account Type</string>
    <string name="lblSubAcc">Select Account Head</string>

    <string-array name="acc_type">
        <item>Income</item>
        <item>Expense</item>
    </string-array>

</resources>

Main Activity

SpinnerEx4Activity.java

package com.bar.example.androidspinnerexample;

import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.Toast;

public class SpinnerEx4Activity extends Activity implements
OnItemSelectedListener{
Spinner s1,s2;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_spinner_ex4);
        s1 = (Spinner)findViewById(R.id.spinner1);
        s2 = (Spinner)findViewById(R.id.spinner2);
        s1.setOnItemSelectedListener(this);
    }
    @Override
    public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2,
            long arg3) {
        // TODO Auto-generated method stub
        String sp1= String.valueOf(s1.getSelectedItem());
        Toast.makeText(this, sp1, Toast.LENGTH_SHORT).show();
        if(sp1.contentEquals("Income")) {
            List<String> list = new ArrayList<String>();
            list.add("Salary");
            list.add("Sales");
            list.add("Others");
            ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this,
                android.R.layout.simple_spinner_item, list);
            dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
            dataAdapter.notifyDataSetChanged();
            s2.setAdapter(dataAdapter);
        }
        if(sp1.contentEquals("Expense")) {
            List<String> list = new ArrayList<String>();
            list.add("Conveyance");
            list.add("Breakfast");
            list.add("Purchase");
            ArrayAdapter<String> dataAdapter2 = new ArrayAdapter<String>(this,
                android.R.layout.simple_spinner_item, list);
            dataAdapter2.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
            dataAdapter2.notifyDataSetChanged();
            s2.setAdapter(dataAdapter2);
        }

    }
    @Override
    public void onNothingSelected(AdapterView<?> arg0) {
        // TODO Auto-generated method stub

    }
}
Googolplex answered 18/9, 2015 at 10:16 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.