如何在另一个活动中传递json数据

时间:2016-12-28 08:59:33

标签: android

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

4 个答案:

答案 0 :(得分:1)

您无法直接将JSONObject传递给其他活动。但是你可以将json转换为字符串并传递它。然后在SecondActivity中,您可以再次将其转换为json。

SecondActivity中启动FirstActivity个代码:

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();
}
祝你好运。

答案 1 :(得分:0)

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

答案 2 :(得分:0)

HashMaps不会保留排序。

更好地使用模型类,也可以轻松检索数据。

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

答案 3 :(得分:0)

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