繁体   English   中英

如何使用 ArrayList HashMap 将 listview onItemClick 数据发送到另一个活动

[英]How to send listview onItemClick data to another activity with ArrayList HashMap

我对 android 开发相当陌生。 我这里有一个应用程序,它应该将staffList中的值发送到另一个活动。

查看员工活动.java

package com.example.activity.AdminModule;

import androidx.appcompat.app.AppCompatActivity;

import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;

import com.example.helper.HttpHandler;
import com.example.login1.AppConfig;
import com.example.login1.MainActivity;
import com.example.login1.R;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;

public class ViewStaffActivity extends AppCompatActivity {

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

    private ProgressDialog pDialog;
    private ListView lv;


    ArrayList<HashMap<String,String >> staffList;

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

        staffList = new ArrayList<>();

        lv = (ListView)findViewById(R.id.staffListView);


        new GetStaff().execute();



    }


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

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

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

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

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

            if (jsonStr != null) {
                try {
                    JSONObject jsonObj = new JSONObject(jsonStr.substring(jsonStr.indexOf("{"), jsonStr.lastIndexOf("}") + 1));

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

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

                        String name = c.getString("name");
                        String email = c.getString("email");
                        String created_at = c.getString("created_at");
                        String user_type = c.getString("user_type");


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

                        // adding each child node to HashMap key => value
                        Staff.put("name", name);
                        Staff.put("email", email);
                        Staff.put("user_type", user_type);
                        Staff.put("created_at", created_at);

                        // adding contact to contact list
                        staffList.add(Staff);
                    }
                } 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(
                    ViewStaffActivity.this, staffList,
                    R.layout.list_item, new String[]{"name", "email",
                    "created_at","user_type"}, new int[]{R.id.name,
                    R.id.email, R.id.created_at,R.id.user_type});

            lv.setAdapter(adapter);

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




                    String test = staffList.get(position).toString();
                    Intent intent = new Intent(ViewStaffActivity.this,ProfileCRUD.class);
                    intent.putExtra("data",staffList.get(position));
                    startActivity(intent);
                }
            });

        }

    }



}


当我通过将.get(position).toString()分配给String test来测试是否有任何值时,它输出了我单击的正确值。

    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {




                    String test = staffList.get(position).toString();
                    Intent intent = new Intent(ViewStaffActivity.this,ProfileCRUD.class);
                    intent.putExtra("data",staffList.get(position));
                    startActivity(intent);
                }

但是,当我使用intent将值传递给PROFILE_CRUD.java时,它返回name: null hashmap size: 4在此行name.setText(hashMap.get("name"));

package com.example.activity.AdminModule;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.os.Bundle;
import android.widget.TextView;

import com.example.login1.R;

import java.util.HashMap;


public class ProfileCRUD extends AppCompatActivity {
    private TextView name;
    private TextView email;
    private TextView user_type;
    private TextView created_at;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        name = (TextView)findViewById(R.id.nameTextView);
        email = (TextView)findViewById(R.id.emailTextView);
        user_type = (TextView)findViewById(R.id.userTypeTextView);
        created_at = (TextView)findViewById(R.id.createdAtTextView);

        /*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");*/

        Intent intent = getIntent();
        HashMap<String, String> hashMap = (HashMap<String, String>)intent.getSerializableExtra("data");

        name.setText(hashMap.get("name"));
        email.setText(hashMap.get("email"));
        user_type.setText(hashMap.get("user_type"));
        created_at.setText(hashMap.get("created_at"));

任何帮助,将不胜感激!

编辑在正确解决方案的帮助下修复了它。 name.setText返回 null 的原因是因为我的布局文件没有setContentView

除了在意图中传递 HashMap 之外,您还可以拆分 Bundle 中的每个值。 像这样:

Intent intent = new Intent(ViewStaffActivity.this,ProfileCRUD.class);
HashMap<String, String> hashMap = staffList.get(position);
Bundle extras = new Bundle();
extras.putString("NAME", hashmap.get("name"));
extras.putString("EMAIL", hashmap.get("email"));
extras.putString("USER_TYPE", hashmap.get("user_type"));
extras.putString("CREATED_AT", hashmap.get("created_at"));
intent.putExtras(extras);
startActivity(intent);

然后在您将使用的另一个 Activity 的 onCreate() 中:

Bundle extras = getIntent().getExtras();
String name = extras.get("NAME");
...

您可以将 HashMap 转换为 json 并通过意图发送。 使用以下代码发送意图:

String jsonStaff = (new Gson()).toJson(staffList.get(position));
intent.putExtra("jsonStaff", jsonStaff);

并像下面这样在另一个活动中获得意图:

String jsonStaff = intent.getStringExtra("jsonStaff");
HashMap<String,String > dataStaff = (new Gson()).fromJson(jsonStaff, new HashMap<String,String >().getClass());

就这些。

暂无
暂无

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM