Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use JSONArray in another class?

I have got a spinner that loads the name of the customers in the dropdown.

The spinner gets the string from a JSON array. I have also got a few textviews where the Name,Adress,Telephone number of the selected customer should load when the spinners selection changes.

But the JSONArray is used in another class, how can I use the JSONArray in another class?(How can I load the correct customer details when spinner selection changes?)

This my code:

     public class Gegevens extends Main {

            Spinner spCustomers;


            private JSONObject jsonChildNode;
            private JSONArray jsonMainNode;
            private String name;
            private TextView txtNaam;
            private TextView txtAdres;

            @Override
            protected void onCreate(Bundle savedInstanceState) {
                super.onCreate(savedInstanceState);
                setContentView(R.layout.activity_gegevens);
                new AsyncLoadCustDetails().execute();
                spCustomers = (Spinner) findViewById(R.id.spKlanten);
                spCustomers.setOnItemSelectedListener(new mySelectedListener());
                txtNaam = (TextView)findViewById(R.id.txtNaam);



            }


            protected class AsyncLoadCustDetails extends
                    AsyncTask<Void, JSONObject, ArrayList<String>> {
                ArrayList<CustomerDetailsTable> custTable = null;

                @Override
                protected ArrayList<String> doInBackground(Void... params) {

                    RestAPI api = new RestAPI();
                    ArrayList<String> spinnerArray = null;
                    try {

                        JSONObject jsonObj = api.GetCustomerDetails();

                        JSONParser parser = new JSONParser();

                        custTable = parser.parseCustomerDetails(jsonObj);
                        spinnerArray = new ArrayList<String>();
//All i can think of is make new array for each value?

                        Log.d("Customers: ", jsonObj.toString());
                        jsonMainNode = jsonObj.optJSONArray("Value");
                        for (int i = 0; i < jsonMainNode.length(); i++) {
                            jsonChildNode = jsonMainNode.getJSONObject(i);
                            name = jsonChildNode.optString("Naam");


                            spinnerArray.add(name);
                        }


                    } catch (Exception e) {
                        Log.d("AsyncLoadCustDetails", e.getMessage());

                    }

                    return spinnerArray;
                }

                @Override
                protected void onPostExecute(ArrayList<String> spinnerArray) {
                    ArrayAdapter<String> spinnerArrayAdapter = new ArrayAdapter<String>(getApplicationContext(), R.layout.spinner_item, spinnerArray);
                    spinnerArrayAdapter.setDropDownViewResource(R.layout.spinner_item); // The drop down view
                    spCustomers.setAdapter(spinnerArrayAdapter);

                }



            }

            public class mySelectedListener implements AdapterView.OnItemSelectedListener {

                @Override
                public void onItemSelected(AdapterView parent, View view, int pos, long id) {



                    String value = (String) parent.getItemAtPosition(pos);
                    txtNaam.setText(value); //got the name working since it wasnt that hard
    //load the other details in the textviews

                }

                @Override
                public void onNothingSelected(AdapterView parent) {
                }

            }
        }

This is what the jsonObj looks like:

{
  "Successful": true,
  "Value": [
    {
      "Naam": "Google",
      "Adres": "Kerkstraat 3",
      "Postcode": "4455 AK Roosendaal",
      "Telefoon": "0165-559234",
      "Email": "[email protected]",
      "Website": "www.google.nl"
    },
    {
      "Naam": "Apple",
      "Adres": "Kerkstraat 4",
      "Postcode": "4455 AD Roosendaal",
      "Telefoon": "0164-559234",
      "Email": "[email protected]",
      "Website": "www.apple.nl"
    }
  ]
}

(Only 2 "customers", since its dummy data)

like image 581
Yoshi Avatar asked Jan 07 '16 09:01

Yoshi


People also ask

How pass JSON array from one activity to another in Android?

JSONObject jObject = new JSONObject("Your Json Response"); Intent obj_intent = new Intent(Main. this, Main1. class); Bundle b = new Bundle(); b. putString("Array",jObject4.

Can we convert JSONArray to JSONObject?

We can also add a JSONArray to JSONObject. We need to add a few items to an ArrayList first and pass this list to the put() method of JSONArray class and finally add this array to JSONObject using the put() method.

What is the difference between JSONObject and JSONArray?

JSONObject and JSONArray are the two common classes usually available in most of the JSON processing libraries. A JSONObject stores unordered key-value pairs, much like a Java Map implementation. A JSONArray, on the other hand, is an ordered sequence of values much like a List or a Vector in Java.

What is the use of JSONArray?

JsonArray represents an immutable JSON array (an ordered sequence of zero or more values). It also provides an unmodifiable list view of the values in the array. A JsonArray object can be created by reading JSON data from an input source or it can be built from scratch using an array builder object.

What is the difference between a jsonobject and a jsonarray?

Values may not be Double#isNaN (), Double#isInfinite (), or of any type not listed here. JSONArray has the same type coercion behavior and optional/mandatory accessors as JSONObject. See that class' documentation for details.

What are the types of arrays in JSON?

1 Arrays as JSON Objects. Arrays in JSON are almost the same as arrays in JavaScript. In JSON, array values must be of type string, number, object, array, boolean or null. 2 Arrays in JSON Objects 3 Accessing Array Values 4 Looping Through an Array 5 Nested Arrays in JSON Objects 6 Modify Array Values 7 Delete Array Items

How to get the value of a specified field in jsonarray?

6) We store each index record into a JSONObject. In order to get the JSON object of a particular index, we use getJSONObject () method of JSONArray. 7) To get a value of a specified field, we use the get () method of the JSONObject by passing the field name as a string in the get () method.

How to deserialize a JSON object to an array?

1 Answer 1 ActiveOldestScore 12 The JSON you have will work if you simply deserialize it as a List<RootObject>: var h = JsonConvert.DeserializeObject<List<RootObject>>(string); Or an array: var h = JsonConvert.DeserializeObject<RootObject[]>(string);


3 Answers

If you want to use across different components, another option is to use Parcelable Interface. The following is a Pojo class with elements name and job_title that has made as an object which can be passed across intents using interface Parcelable

public class ContactPojo implements Parcelable{
       private String name;
       private String job_title;
       public void setName(String name) {
        this.name = name;
       }

       public void setJob_title(String job_title) {
        this.job_title = job_title;
       }
    public String getName() {
        return name;
    }

    public String getJob_title() {
        return job_title;
    }
    private ContactPojo(Parcel parcel){
        name=parcel.readString();
        job_title=parcel.readString();
    }
    @Override
    public int describeContents() {
        return 0;
    }
    @Override
    public void writeToParcel(Parcel parcel, int flags) {
        parcel.writeString(name);
        parcel.writeString(job_title);
    }
public static final Parcelable.Creator<ContactPojo> CREATOR = new
            Parcelable.Creator<ContactPojo>() {
                public ContactPojo createFromParcel(Parcel in) {
                    return new ContactPojo(in);
                }

                public ContactPojo[] newArray(int size) {
                    return new ContactPojo[size];
    }};
}

You can populate the pojo class by the doing the following

ContactPojo contactPojo= new ContactPojo();
contactPojo.setName("name");
contactPojo.setJob_title("name");

and send it to ext intent by this

Intent intent=new Intent(this, DetailView.class);
intent.putExtra("Data", contactPojo);

Retrieve the data in next intent by next steps

ContactPojo contactPojo=new ContactPojo();
contactPojo=getIntent().getParcelableExtra("Data");
Log.i(AppConstants.APPUILOG, "Name: " + contactPojo.getName() );
like image 112
Sreehari Avatar answered Oct 19 '22 04:10

Sreehari


You can convert the JsonArray to string as follow :

String jsonString = jsonArray.toString();

save it in shared preference :

                    SharedPreferences settings = getSharedPreferences(
                            "pref", 0);
                    SharedPreferences.Editor editor = settings.edit();
                    editor.putString("jsonString", jsonString);
                    editor.commit();

And then access it in other class.

SharedPreferences settings = getSharedPreferences(
                            "pref", 0);
                    String jsonString= settings 
                            .getString("jsonString", null);

Once you have obtained the String, convert it back to JsonArray :

JsonArray jsonArray = new JsonArray(jsonString);
like image 23
rahul Avatar answered Oct 19 '22 04:10

rahul


You can save your json in a file and then can fetch it in Another class or anywhere like this :

class to handle saving and fetching of data :

public class RetriveandSaveJSONdatafromfile {

 public static String objectToFile(Object object) throws IOException {
        String path = Environment.getExternalStorageDirectory() + File.separator + "/AppName/App_cache" + File.separator;
        File dir = new File(path);
        if (!dir.exists()) {
            dir.mkdirs();
        }
        path += "data";
        File data = new File(path);
        if (!data.createNewFile()) {
            data.delete();
            data.createNewFile();
        }
        ObjectOutputStream objectOutputStream = new ObjectOutputStream(new FileOutputStream(data));
        objectOutputStream.writeObject(object);
        objectOutputStream.close();
        return path;
    }

    public static Object objectFromFile(String path) throws IOException, ClassNotFoundException {
        Object object = null;
        File data = new File(path);
        if(data.exists()) {
            ObjectInputStream objectInputStream = new ObjectInputStream(new FileInputStream(data));
            object = objectInputStream.readObject();
            objectInputStream.close();
        }
        return object;
    }
}

To save json in a file use RetriveandSaveJSONdatafromfile.objectToFile(obj) and to fetch data from file use

 path = Environment.getExternalStorageDirectory() + File.separator +   
"/AppName/App_cache/data" + File.separator; 
 RetriveandSaveJSONdatafromfile.objectFromFile(path);
like image 1
Kapil Rajput Avatar answered Oct 19 '22 03:10

Kapil Rajput