【问题标题】:How to pass json data in another activity [duplicate]如何在另一个活动中传递json数据[重复]
【发布时间】:2016-12-28 17:40:02
【问题描述】:
public   class   MainActivity   extends   **strong text**

AppCompatActivity {

private String TAG = MainActivity.class.getSimpleName();

private ListView lv;

ArrayList<HashMap<String, String>> companyList;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    companyList = new ArrayList<>();
    lv = (ListView) findViewById(R.id.list_row_xml);

    new GetCompany().execute();
    lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
            Intent i = new Intent(MainActivity.this, SingleView.class);

            i.putExtra("venue", venue);
            startActivity(i);
        }
    });
}


private class GetCompany extends AsyncTask<Void, Void, JSONObject> {
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        Toast.makeText(MainActivity.this,"Json Data is downloading",Toast.LENGTH_LONG).show();

    }
    @RequiresApi(api = Build.VERSION_CODES.KITKAT)
    @Override
    protected JSONObject doInBackground(Void... arg0) {
        HttpHandler sh = new HttpHandler();
        // Making a request to url and getting response
        String url = "http://10.0.2.2:6060/api/v1/company/getInfo?limit=10&page=1";
        JSONArray company = sh.makeServiceCall(url);

        Log.e(TAG, "Response from url: " + company);

        if (company != null) {
            try {
                // JSONObject jsonObj = new JSONObject(jsonStr);

                // Getting JSON Array node
                //JSONArray company = new JSONArray(jsonStr);
                // System.out.println("Reached");
                // looping through All Contacts
                for (int i = 0; i < company.length(); i++) {
                    //System.out.println("Reached1");
                    JSONObject c = company.getJSONObject(i);
                    String id = c.getString("id");
                    String name = c.getString("companyName");

                    // Walking Details in  Json object
                    JSONObject walkingDetails=c.getJSONObject("walkingdetails");
                    String date = walkingDetails.getString("walkingdate");
                    String venue = walkingDetails.getString("venu");

                    // tmp hash map for single contact
                    HashMap<String, String> companyy = new HashMap<>();

                    // adding each child node to HashMap key => value
                    companyy.put("id",id);
                    companyy.put("date", date);
                    companyy.put("companyname", name);
                    companyy.put("venue", venue);


                    // adding contact to contact list
                    companyList.add(companyy);
                }
            } catch (final JSONException e) {
                Log.e(TAG, "Json parsing error: " + e.getMessage());
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(getApplicationContext(), "Json parsing error: " + e.getMessage(), Toast.LENGTH_LONG).show();
                    }
                });

            }
        } else {
            Log.e(TAG, "Couldn't get json from server.");
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    Toast.makeText(getApplicationContext(), "Couldn't get json from server. Check LogCat for possible errors!", Toast.LENGTH_LONG).show();
                }
            });
        }

        return null;
    }
 /*   @Override
    protected void onPostExecute(Void result) {
        super.onPostExecute(result);
        ListAdapter adapter = new SimpleAdapter(MainActivity.this, companyList,
                R.layout.list_row, new String[]{"date","companyname","venue"}, new int[]{ R.id.date, R.id.companyname, venue});
        lv.setAdapter(adapter);*/
    }
}

第二个活动:

public class SingleView extends AppCompatActivity {


EditText txtVenue;

// String[] Venue;
int position;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_single_view);

Intent i = getIntent();
    position = i.getExtras().getInt("positi`enter code here`on");
    txtVenue = (EditText) findViewById(R.id.Venue);
 }
} 

【问题讨论】:

    标签: android


    【解决方案1】:

    您不能直接将JSONObject 传递给另一个活动。但是您可以将 json 转换为字符串并传递它。然后在SecondActivity 中可以再次将其转换为 json。

    在FirstActivity中开始SecondActivity代码:

    Intent intent = new Intent(FirstActivity.this, SecondActivity.class);
    intent.putExtra("data", json.toString());
    startActivity(intent);
    

    然后从SecondActivity获取这个数据:

    String data = getIntent().getStringExtra("data");
    try {
        JSONObject json = new JSONObject(data);
    } catch (JSONException e) {
        e.printStackTrace();
    }
    

    祝你好运。

    【讨论】:

      【解决方案2】:

      您可以通过扩展 JSONObject 并实现 Serializable 接口来创建自己的类来实现。这样你就可以通过意图。

      【讨论】:

        【解决方案3】:

        您有两个选择: 1. 将json转换为字符串,作为字符串传递。 2. 为 json 制作模型类,使其可打包。将此对象传递给下一个活动。

        【讨论】:

          【解决方案4】:

          HashMap 不保留顺序。

          最好使用模型类,检索数据也容易。

          public class CompanyData {
          
              public String id;
              public String date;
              public String name;
              public String venue;
          }
          

          然后改变arraylist,

          ArrayList<CompanyData> companyList;
          

          然后存储值,

          CompanyData companyy = new CompanyData();
          
          companyy.id = id;
          companyy.date = date;
          companyy.name = name;
          companyy.venue = venue;
          
          companyList.add(companyy);
          

          然后实现onitemclicklistener,

          lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
              @Override
              public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
          
                  CompanyData data = companyList.get(position);
          
                  Intent i = new Intent(MainActivity.this, SingleView.class);
          
                  i.putExtra("venue", data.venue);
                  startActivity(i);
              }
          });
          

          ***要获取位置,只需在 onItemClickListener 中发送位置值

          lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
              @Override
              public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
          
                  CompanyData data = companyList.get(position);
          
                  Intent i = new Intent(MainActivity.this, SingleView.class);
          
                  i.putExtra("position", position);
                  startActivity(i);
              }
          });
          

          您也可以通过

          发送特定位置的所有数据
          CompanyData data = companyList.get(position);
          i.putExtra("data", data); //this will pass all data of clicked row
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2018-12-13
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多