在另一个类中使用JSONArray?

时间:2016-01-07 09:20:54

标签: java android arrays json

我有一个微调器,可以在下拉列表中加载客户名称。

微调器从JSON数组中获取字符串。 我还有一些文本视图,其中当微调器选择改变时,所选客户的名称,地址,电话号码应该加载。

但是JSONArray在另一个类中使用,我如何在另一个类中使用JSONArray?(当微调器选择发生变化时,如何加载正确的客户详细信息?)

这是我的代码:

     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) {
                }

            }
        }

这就是jsonObj的样子:

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

(只有2&#34;客户&#34;,因为它的虚拟数据)

4 个答案:

答案 0 :(得分:5)

如果要跨不同组件使用,另一个选项是使用Parcelable Interface。以下是一个Pojo类,其元素名称和job_title作为一个对象,可以使用接口 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];
    }};
}

您可以通过执行以下操作来填充pojo类

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

并将其发送到ext意图

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

通过后续步骤检索下一个意图中的数据

ContactPojo contactPojo=new ContactPojo();
contactPojo=getIntent().getParcelableExtra("Data");
Log.i(AppConstants.APPUILOG, "Name: " + contactPojo.getName() );

答案 1 :(得分:4)

您可以将JsonArray转换为字符串,如下所示:

String jsonString = jsonArray.toString();

将其保存在共享首选项中:

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

然后在其他课程中访问它。

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

获得String后,将其转换回JsonArray:

JsonArray jsonArray = new JsonArray(jsonString);

答案 2 :(得分:1)

您可以将json保存在一个文件中,然后可以在另一个类或其他任何类中获取它:

用于处理数据保存和获取的类:

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

要将json保存在文件中,请使用RetriveandSaveJSONdatafromfile.objectToFile(obj)并从文件使用中获取数据

 path = Environment.getExternalStorageDirectory() + File.separator +   
"/AppName/App_cache/data" + File.separator; 
 RetriveandSaveJSONdatafromfile.objectFromFile(path);

答案 3 :(得分:1)

1)你可以在mainactivity中获得另一个类的intsance并将json数据作为字符串响应传递

2)使用广播监听器和服务。在服务中写下您的json响应,并使用广播意图将其发送回mainactivity。主活动中的广播接收器可以监听具有json数据的服务。还要更新文本视图。