在ArrayList上将数据从一个活动传递到另一个活动项目单击

时间:2016-03-24 15:23:48

标签: java android

我正在开发一个应用程序(字典) 使用Volley从JSON格式的链接获取单词,发音,定义,图像名称 然后解析JSON并在屏幕顶​​部显示单词列表和EditText以搜索单词。一切都好。但我不知道如何处理点击事件,如何将所选项目的数据传递给另一个活动并在那里接收 因此,当选择列表项时,DetailsActivity应显示Word,发音,定义和设置图像名称(如果有)。

我从网络服务中收到的 JSON

{
  "words": [

    {
      "id": "1",
      "the_word": "first word",
      "pronunciation": "pronun",
      "definition": "def",
      "image_name": "img_01"
    },
    {
      "id": "2",
      "the_word": "second word",
      "pronunciation": "pronun2",
      "definition": "def2",
      "image_name": "img_02"
    },
    {
      "id": "3",
      "the_word": "third word",
      "pronunciation": "pronun3",
      "definition": "def3",
      "image_name": "img_03"
    }

  ]
}

Word.java 类作为模型

public class Word {

    private String the_word;
    private String pronunciation;
    private String definition;
    private String image_name;


    public String getThe_word() {
        return the_word;
    }

    public void setThe_word(String the_word) {
        this.the_word = the_word;
    }

    public String getPronunciation() {
        return pronunciation;
    }

    public void setPronunciation(String pronunciation) {
        this.pronunciation = pronunciation;
    }

    public String getDefinition() {
        return definition;
    }

    public void setDefinition(String definition) {
        this.definition = definition;
    }

    public String getImage_name() {
        return image_name;
    }

    public void setImage_name(String image_name) {
        this.image_name = image_name;
    }


}

WordAdapter.java 类作为适配器(稍后我将处理图像)

public class WordAdapter extends BaseAdapter {

    Context context;
    LayoutInflater inflater;
    List<Word> data;

    public WordAdapter(Context context, List<Word> data) {
        this.context = context;
        this.data = data;
    }




    @Override
    public int getCount() {
        return data.size();
    }

    @Override
    public Object getItem(int position) {
        return null;
    }

    @Override
    public long getItemId(int position) {
        return 0;
    }

    @Override
    public View getView(final int position, View convertView, ViewGroup parent) {

        TextView word;

        inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

        View itemView = inflater.inflate(R.layout.word_item, parent, false);

        word = (TextView) itemView.findViewById(R.id.t_word);
        word.setText(data.get(position).getThe_word());

        return itemView;
    }

}

这是列表活动类

public class WordsList extends AppCompatActivity {


        private static final String url = "http://mywebaddress.com/dictionary/showWords.php";

        ListView listView;
        WordAdapter adapter;
        ProgressDialog PD;
        List<Word> arrayListOfWords;
        EditText editText;


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

            listView = (ListView) findViewById(R.id.list);

            editText = (EditText) findViewById(R.id.search);

            PD = new ProgressDialog(this);
            PD.setMessage("Loading ...");
            PD.show();

            getListView().setOnItemClickListener(new ListItemClickListener());

            ReadDataFromDB();

            editText.addTextChangedListener(filterTextWatcher);

        }



        private void ReadDataFromDB() {
            PD.show();

            JsonObjectRequest jsonObject = new JsonObjectRequest(Method.POST, url,new Response.Listener<JSONObject>() {

                        @Override
                        public void onResponse(JSONObject response) {

                                arrayListOfWords = new ArrayList<>();

                                try {
                                    JSONArray ja = response.getJSONArray("words");
                                    for (int i = 0; i < ja.length(); i++) {
                                        JSONObject jsonWordsList = ja.getJSONObject(i);
                                        Word word = new Word();
                                        word.setThe_word(jsonWordsList.optString("the_word"));
                                        word.setPronunciation(jsonWordsList.optString("pronunciation"));
                                        word.setDefinition(jsonWordsList.optString("definition"));
                                        word.setImage_name(jsonWordsList.optString("image_name"));

                                        arrayListOfWords.add(word);

                                        PD.dismiss();

                                    }
                                } catch (JSONException e) {
                                    e.printStackTrace();
                                    Toast.makeText(getApplicationContext(), "inside JSONException", Toast.LENGTH_LONG).show();
                                }

                            adapter = new WordAdapter(WordsList.this, arrayListOfWords);
                            editText.addTextChangedListener(filterTextWatcher);
                            listView.setAdapter(adapter);

                            adapter.notifyDataSetChanged();
                        }
                    }, new Response.ErrorListener() {

                @Override
                public void onErrorResponse(VolleyError error) {
                    PD.dismiss();
                }
            });


            AppController.getInstance().addToRequestQueue(jsonObject);

        }

        private TextWatcher filterTextWatcher = new TextWatcher() {

            public void afterTextChanged(Editable s) {
            }

            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            public void onTextChanged(CharSequence s, int start, int before, int count) {
                List<Word> foundItems = new ArrayList<>();
                if (arrayListOfWords != null) {
                    getWordsList(s, foundItems);
                    listView.setAdapter(new WordAdapter(getApplicationContext(), foundItems));
                    adapter.notifyDataSetChanged();
                }

            }

        };

        public void getWordsList(CharSequence s, List<Word> list) {
            for (Word word : arrayListOfWords) {
                if (word.getThe_word().contains(s)) {
                    list.add(word);
                }
            }
        }

        public ListView getListView() {
            return listView;
        }



        class ListItemClickListener implements ListView.OnItemClickListener {

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

                Intent i = new Intent(WordsList.this,DetailsActivity.class);
                i.putExtra("selected_word", (Parcelable) arrayListOfWords.get(position));
                startActivity(i);

            }

        }
    }

正如我所说的一切正常但是在列表项上点击!
实际上这段代码就是问题:

class ListItemClickListener implements ListView.OnItemClickListener {

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

            Intent i = new Intent(WordsList.this,DetailsActivity.class);
            i.putExtra("selected_word", (Parcelable) arrayListOfWords.get(position));
            startActivity(i);

        }

    }

如何将列表中所选项目的the_word,发音,定义和image_name传递给 DetailsActivity.java 以及如何将它们传递到那里?

谢谢!

修改
所以我找到了一种非常简单的方法来传递我一直使用的数据!!!
但是我不确定这是不是最好的做法而且我确信有更好的方法。考虑到你将要传递更多数据的时间,然后我的解决方案将令人沮丧 这就是我在做的事:
使用putExtra发送...

class ListItemClickListener implements ListView.OnItemClickListener {

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

            String passingWord = String.valueOf(arrayListOfWords.get(position).getThe_word());
            String passingPr = String.valueOf(arrayListOfWords.get(position).getPronunciation());
            String passingDf = String.valueOf(arrayListOfWords.get(position).getDefinition());
            String passingIm = String.valueOf(arrayListOfWords.get(position).getImage_name());

            Intent i = new Intent(WordsList.this,DetailsActivity.class);
            i.putExtra("selected_word", passingWord);
            i.putExtra("selected_pr", passingPr);
            i.putExtra("selected_df", passingDf);
            i.putExtra("selected_im", passingIm);
            startActivity(i);

        }

    }

并在 DetailsActivity.java 获取StringExtra:

Intent intent = getIntent();
String the_word = intent.getStringExtra("selected_word");
String pronunciation = intent.getStringExtra("selected_pr");
String definition = intent.getStringExtra("selected_df");
String image_name = intent.getStringExtra("selected_im");


修改
上述代码没有问题,直到您搜索单词而不是单击列表项,DetailsActivity会显示不同的选定单词详细信息。
实际上,当您搜索单词时,列表中可能会有两个或三个项目通过过滤字母显示。如果选择第一个,在DetailsActivity中,您将看到整个词典列表中第一个单词的详细信息。这意味着所选位置是错误的 所以我改变了我的代码并重新编写它,这次它按照我的预期工作。我会分享它作为这个问题的答案,对谁来说可能有这样的麻烦。

2 个答案:

答案 0 :(得分:0)

我认为在活动之间实现发送复合对象的最佳方法是EventBus。您只需创建一个要传递的新对象(可以是任何类型,例如您的自定义类)并使用:

MyClass myObject = new MyClass; // initialize the object how you like
//and post it
eventBus.post(myObject);

然后在&#39;接收器&#39;活动,创建一个@Subscribe方法,该方法将监听正在接收的此类对象:

@Subscribe
public void onMyClassEvent(MyClass myObject){
    //your logic here
}

EventBus 工作并不难,他们有很棒的指南,但如果你遇到任何麻烦,请写下来。

答案 1 :(得分:0)

尝试以下代码获取意图数据:

String the_word = getIntent().getExtras().getString("selected_word");
String pronunciation = getIntent().getExtras().getString("selected_pr");
String definition = getIntent().getExtras().getString("selected_df");
String image_name = getIntent().getExtras().getString("selected_im");