简体   繁体   English

如何将值从json列表视图中的选定项目发送到另一个活动?

[英]How to send values from a selected item on a json listview to another activity?

I'm making an app that gets countries data (name, latitude, longitude, ...) from JSON and creates a listview , where each item is a different country. 我正在制作一个从JSON获取国家/地区数据(名称,纬度,经度,...)并创建listview ,其中每个项目都是一个不同的国家/地区。

That part is working but, every time I click on a item it opens the MapActivity, with the map centered in that country. 该部分正在运行,但是,每次我单击某个项目时,它都会打开MapActivity,地图以该国家/地区为中心。 The problem is that I can't send the coordinates from the MainActivity to the MapsActivity. 问题是我无法将坐标从MainActivity发送到MapsActivity。

public class TodasAsCategorias extends AppCompatActivity {

private String TAG = TodasAsCategorias.class.getSimpleName();
private ProgressDialog pDialog;
private ListView lv;
private static String url = "http://*************/api/continent/any/country/all?id=siF1uXXEsltXOi5CWlSIzy7EABlnE5iF33bnNmfAHJiYXYNmjY";
ArrayList<HashMap<String, String>> listaPaises;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_todas_as_categorias);
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    getSupportActionBar().setTitle("Categorias");

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


@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
        case android.R.id.home:
            finish();
            return true;
        default:
            return super.onOptionsItemSelected(item);
    }
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.main, menu);
    menu.findItem(R.id.spinner_cat).setVisible(false);
    menu.findItem(R.id.spinner_pais).setVisible(false);
    return true;
}

private class GetPaises extends AsyncTask<Void, Void, Void> implements Serializable {
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        pDialog = new ProgressDialog(TodasAsCategorias.this);
        pDialog.setMessage("Aguarde...");
        pDialog.setCancelable(false);
        pDialog.show();
    }

    @Override
    protected Void doInBackground(Void... params) {
        HttpHandler sh = new HttpHandler();
        final String jsonStr = sh.makeServiceCall(url);
        Log.e(TAG, "Response from URL: " + jsonStr);
        if (jsonStr != null) {
            try {
                JSONArray array = new JSONArray(jsonStr);
                for (int i = 0; i < array.length(); i++) {
                    JSONObject jsonObject = array.getJSONObject(i);
                    JSONArray paises = jsonObject.optJSONArray("paises");
                    if (paises != null) {
                        for (int j = 0; j < paises.length(); j++) {
                            JSONObject jsonObject1 = paises.getJSONObject(j);

                            String K_PAIS = jsonObject1.getString("K_PAIS");
                            String Designacao = jsonObject1.getString("Designacao");
                            String URL_IMAGE_SMALL = jsonObject1.getString("URL_IMAGE_SMALL");
                            String Coord_LAT = jsonObject1.getString("Coord_LAT");
                            String Coord_LONG = jsonObject1.getString("Coord_LONG");
                            String Coord_Zoom = jsonObject1.getString("Coord_Zoom");

                            HashMap<String, String> pais = new HashMap<>();

                            pais.put("K_PAIS", K_PAIS);
                            pais.put("Designacao", Designacao);
                            pais.put("URL_IMAGE_SMALL", URL_IMAGE_SMALL);
                            pais.put("Coord_LAT", Coord_LAT);
                            pais.put("Coord_LONG", Coord_LONG);
                            pais.put("Coord_Zoom", Coord_Zoom);

                            listaPaises.add(pais);
                        }
                    }
                }
            } catch (final JSONException e) {
                Log.e(TAG, "Json parsing error: " + e.getMessage());
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(getApplicationContext(), "Json parsin 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 errpr!", Toast.LENGTH_LONG).show();
                }
            });
        }
        return null;
    }

    @Override
    protected void onPostExecute(Void result) {
        super.onPostExecute(result);
        if (pDialog.isShowing()) {
            pDialog.dismiss();
        }
        ListAdapter adapter = new SimpleAdapter(TodasAsCategorias.this, listaPaises, R.layout.list_item, new String[]{ "Designacao","Coord_LAT", "Coord_LONG", "Coord_Zoom"},
                new int[]{R.id.Designacao,R.id.Lat, R.id.Long, R.id.Zoom});
        lv.setAdapter(adapter);
        lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> pare, View view, int position, long id) {
                Intent intent = new Intent(TodasAsCategorias.this, MapsActivity.class);

                startActivity(intent);
            }
        });
    }
}
}

HashMap implements Serializable so we can send HashMap object using putExtra and receive it using getSerializableExtra HashMap实现Serializable ,所以我们可以把HashMap使用对象putExtra和使用接收它getSerializableExtra

TodasAsCategorias activity TodasAsCategorias活动

  @Override
  public void onItemClick(AdapterView<?> pare, View view, int position, long id)     
  {
       Intent intent = new Intent(TodasAsCategorias.this, MapsActivity.class);
       intent.putExtra("data", listaPaises.get(position));
       startActivity(intent);
  }

In MapsActivity MapsActivity

protected void onCreate(Bundle bundle) {
    super.onCreate(savedInstanceState);

    Intent intent = getIntent();
    HashMap<String, String> hashMap = (HashMap<String, String>)intent.getSerializableExtra("data");
    String lat = hashMap.get("Coord_LAT");
    String longi = hashMap.get("Coord_LONG");
}

Transmit your data to MapsActivity via Extras. 通过Extras将数据传输到MapsActivity。 Start activity like this: 开始这样的活动:

Intent intent = new Intent(TodasAsCategorias.this, MapsActivity.class);
intent.putExtra("Coord_LAT", value);
intent.putExtra("Coord_LONG", value);
startActivity(intent);

And retrieve data in MapsActivity: 并在MapsActivity中检索数据:

String Coord_LAT = getIntent().getStringExtra("Coord_LAT");
String Coord_LONG = getIntent().getStringExtra("Coord_LONG");

The onItemClick() method, provides the "position" of the list item that was clicked. onItemClick()方法提供了被单击的列表项的“位置”。 The item at the position contains the latitude and longitude that you need to pass to the other activity I guess. 该位置处的项目包含您传递给其他活动的纬度和经度,我猜是这样。 Then, the latitude and longitude can be passed as explained by the other answers, using Extras. 然后,可以使用Extras按照其他答案的说明传递纬度和经度。

Updated: since your listaPaises is an instance variable, @PavneetSingh answer would be more straight forward. 更新:由于您的listaPaises是一个实例变量,因此@PavneetSingh答案会更直接。

You may override the getItem(int position) of the SimpleAdapter to return the HashMap entry: 您可以重写SimpleAdapter的getItem(int position)以返回HashMap条目:

ListAdapter adapter = new SimpleAdapter(this, listaPaises, R.layout.list_item,
                new String[]{"Designacao", "Coord_LAT", "Coord_LONG", "Coord_Zoom"},
                new int[]{R.id.Designacao, R.id.Lat, R.id.Long, R.id.Zoom}) {
            @Override
            public Object getItem(int position) {
                if (listaPaises!=null) {
                    return listaPaises.get(position);
                }
                return super.getItem(position);
            }
        };

then in your ListView's setOnItemClickListener(...) method, you can get the returned entry by calling: 然后在ListView的setOnItemClickListener(...)方法中,可以通过调用以下命令获取返回的条目:

HashMap<String, String> pais = (HashMap<String, String>) adapter.getItem(position)

and pass the HashMap entry with Intent's putExtra() method to MapsActivity. 并将带有Intent的putExtra()方法的HashMap条目传递给MapsActivity。

Kindly note that in order to call the adapter within the anonymous inner class, you would need to change the local variable ListAdapter adapter to instance variable of your class. 请注意,为了在匿名内部类中调用适配器,您需要将局部变量ListAdapter适配器更改为类的实例变量。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何从ListView获取选定的项目值 - How to Get Selected Item values from ListView 加载新活动时,将选定项从ListView Android传递到另一个活动会引发NullPointerException - Passing selected item from ListView Android to another Activity throws a NullPointerException when loading the new activity 如何在另一个活动中将列表项名称从列表视图转换为文本视图? - How to get the list item name from a listview to a textview in another activity? 从另一个Activity更新ListView的项目 - Updating an item of ListView from another Activity Android-从另一个活动将项目添加到ListView - Android - Adding item to ListView from another Activity 无法在另一个活动上显示listView中的项目 - Unable to display item from listView on another activity 将listView数据从一个活动发送到另一个活动 - Send listView data from one activity to another 如何将一项活动中的项目从一项活动发送到另一项 - How to send Items from one activity to another on item checked 从另一个活动中单击按钮后,从活动中删除列表视图项 - Delete a listview item from activity on button click from another activity 将ListView项目onclick解析为另一个活动,并匹配JSON中的特定数据 - Parsing a ListView item onclick to another activity and match a specific data from JSON
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM