Home » Android » java – Use JSONArray in another class?

java – Use JSONArray in another class?

Posted by: admin June 15, 2020 Leave a comment

Questions:

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)

How to&Answers:

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

Answer:

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

Answer:

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

Answer:

1)you can get the intsance of the other class in your mainactivity and pass the json data as a string response

2)Use broadcast listener and service. Write your json response in a service and send it back to the mainactivity using a broadcast intent. The broadcast receiver in your main activity can listen to the service, which has the json data. Also update the textviews.