【问题标题】:Use JSONArray in another class?在另一个类中使用 JSONArray?
【发布时间】:2016-04-11 14:53:00
【问题描述】:

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

微调器从 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 个“客户”,因为它是虚拟数据)

【问题讨论】:

  • 您想将spinnerArray 发送到其他活动吗?
  • 如果您的客户太多,我建议您创建一个数据库并将条目保存到其中。您可以使用 3rd 方库来简化工作,例如:greendao-orm.com 或 ormlite.com/sqlite_java_android_orm.shtml
  • 我已经从 webAPI 获取了这个 JSON 数组(它从数据库中获取数据)
  • 好的,所以如果您的应用程序应该离线工作。我发现最好的方法是“重新创建”与网络上的数据库相同的数据库并在您的应用程序中使用它。数据将是整体可访问的,并且使用 ORM 库,您无需手动解析对象等。

标签: java android arrays json


【解决方案1】:

您可以将 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);

一旦你获得了字符串,将它转换回 JsonArray :

JsonArray jsonArray = new JsonArray(jsonString);

【讨论】:

    【解决方案2】:

    您可以将您的 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】:

      如果你想跨不同的组件使用,另一种选择是使用 Parcelable Interface。下面是一个 Pojo 类,其中包含元素 name 和 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 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() );
      

      【讨论】:

        【解决方案4】:

        1)您可以在 mainactivity 中获取其他类的实例,并将 json 数据作为字符串响应传递

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

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2016-04-06
          • 1970-01-01
          • 2017-08-16
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多