从listview中获取特定的json对象

时间:2016-11-15 11:36:25

标签: android json listview

我的课程基于在线教程,我还没有完全理解它(正在研究它),但它的工作。

它填充了listview,现在我想获取id并在更详细的活动中显示与该id相关的数据。

我已经获得了我点击的项目的ID:

list.setOnItemClickListener(new AdapterView.OnItemClickListener() {

    @Override
    public void onItemClick(AdapterView<?> arg0, View view, int position,
                            long id) {
        Log.e("item clicks", "selected: " + position);



    }
});

但是现在,我不知道我将如何做到这一点,获取我点击的位置的数据。

我有一个内部课程&#34; GetObras&#34;但我不能在我的onCreate上使用它的变量,我试着让它们全局化等等

 public class MainActivity extends ActionBarActivity implements SearchView.OnQueryTextListener{

    private String TAG = MainActivity.class.getSimpleName();
    private ProgressDialog pDialog;
    private ListView list;

    private static String url = "http://ploran.gear.host/scriptobras6.php";

    ArrayList<HashMap<String, String>> obrasList;

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

        obrasList = new ArrayList<HashMap<String, String>>();
        list = (ListView)findViewById(R.id.list1);

        new GetObras().execute();

        list.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> arg0, View view, int position,
                                    long id) {
                Log.e("item clicks", "selected: " + position);



            }
        });
    }

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

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

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

            // 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);
                    JSONArray obras = new JSONArray(jsonStr);
                    // Getting JSON Array node
                    //JSONArray obras = jsonObj.getJSONArray("obras");

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

                        String id = c.getString("Id");
                        String nomeObra = c.getString("NomeObra");
                        String idCliente = c.getString("idCliente");
                        String DataLevantamento = c.getString("DataPLevantamento");
                        String DataRealizacao = c.getString("DataRLevantamento");
                        String Estado = c.getString("Estado");
                        String DataMateriais = c.getString("DataRMateriais");
                        String DataInicioObra = c.getString("DataInicioObra");
                        String DataConclusao = c.getString("DataConclusao");
                        String DataVestoria = c.getString("DataVestoria");
                        String Obs = c.getString("Obs");
                        String Prompor = c.getString("Prompor");
                        String Levantpor = c.getString("Levantpor");
                        String executpor = c.getString("executpor");

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

                        // adding each child node to HashMap key => value
                        obra.put("Id", id);
                        obra.put("nomeObra", nomeObra);
                        obra.put("idCliente", idCliente);
                        obra.put("DataLevantamento", DataLevantamento);
                        obra.put("DataRealizacao", DataRealizacao);
                        obra.put("Estado", Estado);
                        obra.put("DataMateriais", DataMateriais);
                        obra.put("DataIncioObra", DataInicioObra);
                        obra.put("DataConclusao", DataConclusao);
                        obra.put("DataVestoria", DataVestoria);
                        obra.put("Obs", Obs);
                        obra.put("Prompor", Prompor);
                        obra.put("Levantpor", Levantpor);
                        obra.put("executpor", executpor);

                        // adding contact to contact list
                        obrasList.add(obra);
                    }
                } 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(
                    MainActivity.this, obrasList,
                    R.layout.list_item, new String[]{"nomeObra", "idCliente",
                    "Estado"}, new int[]{R.id.name,
                    R.id.email, R.id.mobile});

            list.setAdapter(adapter);
        }
    }

    List<String> cities;

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_search, menu);

        MenuItem searchItem = menu.findItem(R.id.search);

        return true;
    }

    @Override
    public boolean onQueryTextSubmit(String query) {
        // User pressed the search button
        return false;
    }

    @Override
    public boolean onQueryTextChange(String newText) {
        // User changed the text
        return false;
    }
}

如果我认为是正确的,我可以从GetObras中的doInBackground方法获取JsonArray并执行:

JSONObject c = obras.getJSONObject(position);

谢谢。

1 个答案:

答案 0 :(得分:2)

您可以使用obrasList参考来检索它。正在将obrasList传递给适配器。

以下是示例代码:

obrasList.get(position).get(yourkey);

希望这会对你有所帮助.. :))