如何将对象从列表视图返回到先前的活动?

时间:2018-01-05 14:24:49

标签: android listview

情况如此: 我有2个活动:A和B. 致电startActivityForResult(B,AN_INTEGER)。 B从具有JSONArray(称为"内容")的网站获取JSONObject,该网站具有多个JSONObject(由id,name,last_name组成)。我使用listview仅显示每行中的名称和last_name。我想要的是:当用户点击一个项目时,B将整个对象返回给A(id,name和last_name)。 我怎样才能做到这一点?

这就是我现在所拥有的:

A类:

public class A extends AppCompatActivity {

    ImageButton botonBuscarPaciente;
    int AN_INTEGER = 1;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_a);

        botonBuscarPaciente = findViewById(R.id.buttonBuscarPaciente);

        botonBuscarPaciente.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent b = new Intent(getBaseContext(), B.class);
                startActivityForResult(b,AN_INTEGER);
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == AN_INTEGER) {
            if(resultCode == Activity.RESULT_OK){
                // your code to continue processing
            }
            if (resultCode == Activity.RESULT_CANCELED) {
                // if no result
            }
        }
    }
}

B组:

public class B extends AppCompatActivity {

    ListView listViewPacientes;

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

        listViewPacientes = findViewById(R.id.listViewPacientes);
        listViewPacientes.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Intent resultadoIntent = new Intent();
                resultadoIntent.putExtra();//here should go the Object to return
            }
        });
        buscar();
    }

    private void buscar(){
        String url = getString(R.string.url);

        JsonObjectRequest jsObjRequest = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {

            @Override
            public void onResponse(JSONObject response) {
                try {
                    ArrayList<String> tubeLines = new ArrayList<>();

                    for(int i=0;i<response.length();i++) {

                        // Get current json object
                        JSONObject line = response.getJSONArray("content").getJSONObject(i);

                        int id = Integer.parseInt(line.optString("id"));
                        String name = line.optString("name");
                        String last_name = line.optString("last_name");

                        Agente agente = new Agente(id,
                                name,
                                last_name);

                        String nameAndLastname = line.optString("name")
                                +" "
                                +line.optString("last_name");
                        // add all items
                        tubeLines.add(nameAndLastname);
                    }

                    ListView myListView = findViewById(R.id.listViewPacientes);
                    ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(getApplicationContext(), android.R.layout.simple_list_item_1, tubeLines);
                    myListView.setAdapter(arrayAdapter);

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

        }, new Response.ErrorListener() {

            @Override
            public void onErrorResponse(VolleyError error) {
                Log.d("errorJSON",error.toString());

            }
        });

        // Access the RequestQueue through your singleton class.
        ConexionApi.getInstance(this).addToRequestQueue(jsObjRequest);
    }
}

最后,Agente类是一个带有Parcelable的简单POJO:

public class Agente implements Parcelable{
    private int id;
    private String name;
    private String last_name;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getLastName() {
        return last_name;
    }

    public void setLastName(String last_name) {
        this.last_name = last_name;
    }

    public Agente(int id, String name, String last_name) {
        this.id = id;
        this.name = name;
        this.last_name = last_name;
    }

    @Override
    public int describeContents() {
        return 0;
    }

    @Override
    public void writeToParcel(Parcel dest, int flags) {
        dest.writeInt(id);
        dest.writeString(name);
        dest.writeString(last_name);
    }

    public static final Parcelable.Creator<Agente> CREATOR
            = new Parcelable.Creator<Agente>() {
        public Agente createFromParcel(Parcel in) {
            return new Agente(in);
        }

        public Agente[] newArray(int size) {
            return new Agente[size];
        }
    };

    private Agente(Parcel in) {
        id = in.readInt();
        name = in.readString();
        last_name = in.readString();
    }
}

1 个答案:

答案 0 :(得分:1)

在活动中,您可以使用setResult()返回任何结果。但你应该首先将数组转换为字符串:

Intent data = new Intent();
JSONArray array = ...
data.putExtra("array", array.toString());
setResult(Activity.RESULT_OK, data);
finish();

在您的主要活动中,获取字符串并将其转换为正常 JSONArray

public void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == request_Code) {
        if (resultCode == Activity.RESULT_OK) {
            try {
                String jsonArray = data.getStringExtra("array");
                JSONArray array = new JSONArray(jsonArray);
                // ...
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    }
}