通过活动解析JSON对象

时间:2017-12-12 19:06:33

标签: android json

我有一个活动,目前显示谷歌API工作正常的酒吧列表,我试图得到它,以便通过onclick解析“名称”和其他细节。目前它打开一个新活动,但我无法获得我用putExtra发送的解析JSON。 任何帮助赞赏。

Bars.java

public class Bars extends AppCompatActivity {

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

    private ProgressDialog pDialog;
     ListView lv;

    // URL to get Results JSON
    private static String url = "https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=40.785091,-73.968285&radius=1000&type=restaurant,bar,food,point_of_interest&keyword=bar&opennow=true&key=MYAPICODE";

    ArrayList<HashMap<String, String>> resultsList;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_bars);

        resultsList = new ArrayList<>();
        lv = (ListView) findViewById(R.id.list);
        new Getresults().execute();
    }

    //Async task class to get json by making HTTP call

    private class Getresults extends AsyncTask<Void, Void, Void> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            // Showing progress dialog
            pDialog = new ProgressDialog(Bars.this);
            pDialog.setMessage("Please wait...");
            pDialog.setCancelable(false);
            pDialog.show();

        }

        @Override
        protected Void doInBackground(Void... arg0) {
            HttpConnect sh = new HttpConnect();

            // Making a request to url and getting response
            String jsonStr = sh.makeServiceCall(url);

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

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

                    // Getting JSON Array node
                    JSONArray results = jsonObj.getJSONArray("results");

                    // looping through All results
                    for (int i = 0; i < results.length(); i++) {
                        JSONObject c = results.getJSONObject(i);

                        String name = c.getString("name");
                        String vicinity = c.getString("vicinity");
                        String rating = c.getString("rating");




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

                        // adding each child node to HashMap key => value
                        result.put("name", name);
                        result.put("vicinity", vicinity);
                        result.put("rating", rating) ;

                        // adding result to result list
                        resultsList.add(result);
                    }
                } 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);
            // Dismiss the progress dialog
            if (pDialog.isShowing())
                pDialog.dismiss();
            /**
             * Updating parsed JSON data into ListView
             * */
            ListAdapter adapter = new SimpleAdapter(
                    Bars.this, resultsList,
                    R.layout.list_item, new String[]{"name", "vicinity",
                    "rating" }, new int[]{name,
                    R.id.vicinity, R.id.rating});

            lv.setAdapter(adapter);

            // on lick listener to send name position
            lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {

                    Intent newActivity = new Intent(Bars.this, 
                    SecondActivity.class);
                    newActivity.putExtra("position", position);
                    newActivity.putExtra("name", name);

                    startActivity(newActivity);


                }
            });
        }

    }

}

如您所见,最后一部分将“name”和“position”发送到secondActivity Class,如下所示

public class SecondActivity extends AppCompatActivity {

    String name;
    Intent getName;
    Bundle extras;

    TextView name1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_second);

        String name = getIntent().getStringExtra("name");

        getName = this.getIntent();
        extras = getName.getExtras();


       // Intent intent = getIntent();
      //  String name = intent.getStringExtra( name: "name");






    }
    public void name(View view){
        name1 = (TextView)findViewById(R.id.name);

       getIntent().getStringExtra("name");


    }


}

2 个答案:

答案 0 :(得分:0)

我看不到你初始化名字的位置。但是我可以在你的ListAdapter adapter = new SimpleAdapter( Bars.this, resultsList, R.layout.list_item, new String[]{"name", "vicinity", "rating" }, new int[]{name, R.id.vicinity, R.id.rating}); 块中看到你编写了这段代码

name

在上面的代码中,您提到intint[]{name,R.id.vicinity, R.id.rating}); 。看到这一行。

intent.getStringExtra('name')

因此,在第二项活动中调用hash,您无法获得名称的价值。

答案 1 :(得分:0)

您需要从adapterView访问适配器,然后按位置获取hashMap并拉出项目

@Override public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
    ListAdapter adapter = (ListAdapter) adapterView.getAdapter()
    HashMap<String, String> map = (HashMap) adapter.getItem(position)
    String name = map.get("name") // may be a null

    Intent newActivity = new Intent(Bars.this, SecondActivity.class);
    newActivity.putExtra("position", position);
    newActivity.putExtra("name", name);
    startActivity(newActivity);
}