android - 如何从 ListView 中获取值并将 JSON 数据传递给另一个 Activity

标签 android

现在我可以解析来自 JSON 的数据 如何从 Listview 获取值 OnItemClickListener 并将其传递给另一个 Activity ?像这样/p>

这是我的代码

JSON 字符串

[
  {
    "project_id": "10",
    "cat_id": "0",
    "project_name": "BMW Showroom",
    "project_status": "1",
    "project_date": "2014-11-28",
    "project_ordering": "1",
    "project_start": "2014-11-28",
    "project_finish": "2014-11-29",
    "project_location": "Pattanakarn",
    "project_pm": "11",
    "project_foreman": "9",
    "user_id": "9",
    "user_fname": "Panya",
    "user_lname": "Smunya",
    "user_nickname": "Foreman4",
    "user_address": "",
    "user_email": "pan@gmail.com",
    "user_pass": "12345",
    "user_status": "1",
    "user_dateregis": "2014-01-23",
    "depart_id": "2",
    "position": "Foreman"
  },
  {
    "project_id": "9",
    "cat_id": "1",
    "project_name": "TRUE Big-C ",
    "project_status": "1",
    "project_date": "2014-11-28",
    "project_ordering": "1",
    "project_start": "2014-11-28",
    "project_finish": "2014-11-29",
    "project_location": "Nakhon Pathom",
    "project_pm": "0",
    "project_foreman": "6",
    "user_id": "6",
    "user_fname": "Tongdang",
    "user_lname": "Boonlap",
    "user_nickname": "Foreman1",
    "user_address": "",
    "user_email": "tong@gmail.com",
    "user_pass": "12345",
    "user_status": "1",
    "user_dateregis": "2014-01-23",
    "depart_id": "2",
    "position": "Foreman"
  },
  {
    "project_id": "8",
    "cat_id": "1",
    "project_name": "PTT Srinakarin",
    "project_status": "1",
    "project_date": "2014-11-08",
    "project_ordering": "1",
    "project_start": "2014-11-04",
    "project_finish": "2014-12-31",
    "project_location": "Srinakarin",
    "project_pm": "10",
    "project_foreman": "2",
    "user_id": "2",
    "user_fname": "Patcharin",
    "user_lname": "Udsaha",
    "user_nickname": "Patcha",
    "user_address": "Bangkok",
    "user_email": "p@gmail.com",
    "user_pass": "12345",
    "user_status": "3",
    "user_dateregis": "2014-01-22",
    "depart_id": "2",
    "position": "Programmer"
  },
  {
    "project_id": "6",
    "cat_id": "1",
    "project_name": "CIMB ",
    "project_status": "1",
    "project_date": "2014-01-23",
    "project_ordering": "1",
    "project_start": "2014-01-23",
    "project_finish": "2014-08-15",
    "project_location": "Sathon Branch",
    "project_pm": "13",
    "project_foreman": "7",
    "user_id": "7",
    "user_fname": "Apisit",
    "user_lname": "Jannual",
    "user_nickname": "Foreman2",
    "user_address": "",
    "user_email": "ap@gmail.com",
    "user_pass": "12345",
    "user_status": "1",
    "user_dateregis": "2014-01-23",
    "depart_id": "2",
    "position": "Foreman"
  }
]

PrePostActivity.java

public class PrePostActivity extends Activity {

    private ListView listViewPost;
    private ListView mListView;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_project);
        listViewPost = (ListView) findViewById(R.id.listViewPost);

       listViewPost.setOnItemClickListener(menuLsnr);



    }

    @Override
    protected void onResume() {
        super.onResume();
        buildList();
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        if (id == R.id.action_settings) {

            Intent i = new Intent(PrePostActivity.this, addProjectActivity.class);
            startActivity(i);
            return true;
        }

        if (id == R.id.feed) {

            Intent i = new Intent(PrePostActivity.this, MainActivity.class);
            startActivity(i);
            return true;
        }
        return super.onOptionsItemSelected(item);
    }





    private void parseJson(String  jsonStr){

        try
        {
            // Our data is json array
            JSONArray resultArray = new JSONArray(jsonStr);

            // Array list stores each row data
            // Array member is HashMap stores <col_name, col_value>
            ArrayList<HashMap<String, String>> list_data
                    = new ArrayList<HashMap<String, String>>();

            // Loop read each member of JSONArray
            for(int i=0; i<resultArray.length(); i++)
            {
                JSONObject recordObj = resultArray.getJSONObject(i);

                String project_id = recordObj.getString("project_id");
                String project_name = recordObj.getString("project_name");
                String project_location = recordObj.getString("project_location");
                String foremanName = recordObj.getString("user_fname");
                String foremanSur = recordObj.getString("user_lname");

                // Create HashMap to store row values
                HashMap<String, String> recordData =
                        new HashMap<String, String>();
                recordData.put("project_name", project_name);
                recordData.put("project_location","AREA: " + project_location + "| PM:" + foremanName + " " + foremanSur );
                list_data.add(recordData);
            }

            // Load data from ArrayList list_data onto ListView
            // List Entry Layout use Android's simple_list_item_2
            String[] from = new String[]{"project_name", "project_location"};
            int[] to = new int[]{android.R.id.text1, android.R.id.text2};
            SimpleAdapter adapter = new SimpleAdapter(PrePostActivity.this,
                    list_data, android.R.layout.simple_list_item_2,
                    from, to);
            listViewPost.setAdapter(adapter);
        }
        catch (Exception e)
        {
            Toast.makeText(PrePostActivity.this,
                    "JSON Format Error", Toast.LENGTH_LONG).show();
        }

    }


    private AdapterView.OnItemClickListener menuLsnr =
            new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view,
                                        int position, long id) {

                    Intent intent = new Intent();
                    intent.setClass(PrePostActivity.this, PostActivity.class);

                    intent.putExtra("position", position);


              Toast.makeText(PrePostActivity.this,"Welcome ", Toast.LENGTH_LONG).show();

                    startActivity(intent);

                }
            };




    //////////GET POST FROM SERVER //////////

    private void buildList(){
        getPostTask task = new getPostTask();
        task.execute();

    }

    private  class getPostTask extends AsyncTask<Void, Void,String> {


        @Override
        protected String doInBackground(Void... params) {

            String url ="MY_JSON_URL";
            HttpClient httpClient = new DefaultHttpClient();
            HttpGet get = new HttpGet(url);


            try
            {
                HttpResponse response = httpClient.execute(get);
                HttpEntity response_entity= response.getEntity();
                InputStream is = response_entity.getContent();

                BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"),8);
                StringBuilder sb = new StringBuilder();
                String line =null;

                while ((line = reader.readLine()) !=null){
                    sb.append(line+ "\n");
                }

                is.close();
                return  sb.toString();


            } catch (IOException e) {
                e.printStackTrace();

                return null;
            }

        }

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
        }

        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);

            if(s!=null){
                parseJson(s);
            }

            //Toast.makeText(MainActivity.this,s,Toast.LENGTH_LONG).show();
        }
    }


}

最佳答案

您可以简单地在列表项点击时从 arraylist 中获取值

 String project_name = list_data.get(position).get("project_name");
 String project_location = list_data.get(position).get("project_location");

作为

传递给 Activity
 intent.putExtra("project_name ", project_name);
 intent.putExtra("project_location ", project_location);

现在像在另一个 Activity 中一样检索

 String projectname = getIntent().getStringExtra("project_name");
 String project_location  = getIntent().getStringExtra("project_location");

编辑:

 public class PrePostActivity extends Activity {

  private ListView listViewPost;
  private ListView mListView;
  ArrayList<HashMap<String, String>> list_data
                = new ArrayList<HashMap<String, String>>();


  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_project);
    listViewPost = (ListView) findViewById(R.id.listViewPost);

    listViewPost.setOnItemClickListener(menuLsnr);
    }


  private AdapterView.OnItemClickListener menuLsnr =
        new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                                    int position, long id) {

             try {
                String project_name = list_data.get(position).get("project_name");
                String project_location = list_data.get(position).get("project_location");
                Intent intent = new Intent();
                intent.setClass(PrePostActivity.this, PostActivity.class);

               // intent.putExtra("position", position);
                intent.putExtra("project_name ", project_name);
                intent.putExtra("project_location ", project_location);


          Toast.makeText(PrePostActivity.this,"Welcome ", Toast.LENGTH_LONG).show();

                startActivity(intent);

             }catch (NullPointerException ex){
             }

            }
        };

    private void parseJson(String  jsonStr){

    try
    {
        // Our data is json array
        JSONArray resultArray = new JSONArray(jsonStr);


        // Loop read each member of JSONArray
        for(int i=0; i<resultArray.length(); i++)
        {
            JSONObject recordObj = resultArray.getJSONObject(i);

            String project_id = recordObj.getString("project_id");
            String project_name = recordObj.getString("project_name");
            String project_location = recordObj.getString("project_location");
            String foremanName = recordObj.getString("user_fname");
            String foremanSur = recordObj.getString("user_lname");

            // Create HashMap to store row values
            HashMap<String, String> recordData =
                    new HashMap<String, String>();
            recordData.put("project_name", project_name);
            recordData.put("project_location","AREA: " + project_location + "| PM:" + foremanName + " " + foremanSur );
            list_data.add(recordData);
        }

        // Load data from ArrayList list_data onto ListView
        // List Entry Layout use Android's simple_list_item_2
        String[] from = new String[]{"project_name", "project_location"};
        int[] to = new int[]{android.R.id.text1, android.R.id.text2};
        SimpleAdapter adapter = new SimpleAdapter(PrePostActivity.this,
                list_data, android.R.layout.simple_list_item_2,
                from, to);
        listViewPost.setAdapter(adapter);
    }
    catch (Exception e)
    {
        Toast.makeText(PrePostActivity.this,
                "JSON Format Error", Toast.LENGTH_LONG).show();
    }

    }

关于android - 如何从 ListView 中获取值并将 JSON 数据传递给另一个 Activity,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27309727/

相关文章:

android - Kotlin 协程中 observeOn 和 subscribeOn 的等价物

android - 部分手机浏览器水平滚动div渲染(主要是android 2.2)

android - 使用默认的android图像查看器显示图片

java - 我可以更改 final int 的值吗

android - 注入(inject)交互器android mvp

java - 如何在 mainActivity 布局的工具栏中删除这个箭头?

android - 这个警告是由我的应用程序引起的吗? - "Implicit intents with startService are not safe"

java - 从 for 循环抛出错误实例化多个按钮

android - SPAN_POINT_MARK 和 SPAN_MARK_POINT 有什么区别?

android - 如何在android中为平板电脑和手机设置不同的方向