将数据从Fragment listview项传递到Activity字符串变量onitemclicklistener

时间:2017-11-02 11:39:45

标签: android listview android-fragments android-intent

我正在尝试将ListView项从片段传递给String变量" url"在活动中,intent成功创建了活动,但是当我尝试传递数据时,我遇到了问题。 fragment类有一个带有json数据的listview,它会显示图片,标题和名称的列表。当用户选择一个项目时,它会将它们带到活动中。我希望他们的选择将列表视图中的名称转移到另一个活动中的url变量。所以网址改为" https://.....id="来自片段的" https://.....id=" + 名称。 多数民众赞成将使用任何列表视图项目的新网址更改recyclerview。

我的片段:

public class Accueil extends Fragment {

ArrayList<articles> arrayList;
ListView lv;
public static String URL1=null;
class ReadJSON extends AsyncTask<String, Integer, String> {

    @Override
    protected String doInBackground(String... params) {
        return readURL(params[0]);
    }

    @Override
    protected void onPostExecute(String content) {
        JSONObject jsonObject = null;
        try {
            jsonObject = new JSONObject(content);
        } catch (JSONException e1) {
            e1.printStackTrace();
        }
        JSONArray jsonArray = null;
        try {
            jsonArray = jsonObject.getJSONArray("articles");
        } catch (JSONException e1) {
            e1.printStackTrace();
        }
        for (int i = 0; i < jsonArray.length(); i++) {
            JSONObject articlesobject = null;
            try {
                articlesobject = jsonArray.getJSONObject(i);
            } catch (JSONException e1) {
                e1.printStackTrace();
            }
            try {
                arrayList.add(new articles(
                        articlesobject.getString("picture"),
                        articlesobject.getString("title"),
                        articlesobject.getString("name")
                ));
            } catch (JSONException e1) {
                e1.printStackTrace();
            }
            CustomListAdaper adaper = new CustomListAdaper(
                    getActivity().getApplicationContext(), 
R.layout.custom_list_layout, arrayList
            );
            lv.setAdapter(adaper);
        }

    }


    private String readURL(String theURL) {
        StringBuilder content = new StringBuilder();
        try {
            URL url = new URL(theURL);
            URLConnection urlConnection = url.openConnection();
            BufferedReader bufferedReader = new BufferedReader(new 
InputStreamReader(urlConnection.getInputStream()));
            String line;
            while ((line = bufferedReader.readLine()) != null) {
                content.append(line + "\n");
            }
            bufferedReader.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return content.toString();
    }
}
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                     Bundle savedInstanceState) {
arrayList = new ArrayList<>();
View rootView = inflater.inflate(R.layout.accueil, container, false);
lv = (ListView) rootView.findViewById(R.id.ListView1);
getActivity().runOnUiThread(new Runnable() {
    @Override
    public void run() {
        new Accueil.ReadJSON().execute("http://wach.ma/mobile/home.php");
    }

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

        String selectedFromList = 
(lv.getItemAtPosition(position).toString());

        Intent i = new Intent(getActivity(), Test.class);

        i.putExtra("name", selectedFromList);
         startActivity(i);
    }

});
return rootView;
}
}

我的活动:

public class Test extends AppCompatActivity {
public String URL_DATA="http://wach.ma/mobile/category.php?id=";

private RecyclerView recyclerView;
private RecyclerView.Adapter adapter;
private List<ListItem> listItems;

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_test);
    recyclerView = (RecyclerView) findViewById(R.id.recyclerview);
    recyclerView.setHasFixedSize(true);
    recyclerView.setLayoutManager(new LinearLayoutManager(this));
    listItems = new ArrayList<>();
    Intent i = getIntent();
    String s1 = i.getStringExtra("name");
    URL_DATA=URL_DATA+s1;
    loadRecyclerViewData();
}
private void loadRecyclerViewData(){
    final ProgressDialog progressDialog = new ProgressDialog(this);
    progressDialog.setMessage("Chargement...");
    progressDialog.show();
    StringRequest stringRequest = new StringRequest(Request.Method.GET, 
URL_DATA, new Response.Listener<String>() {
        @Override
        public void onResponse(String s) {
            progressDialog.dismiss();
            try {
                JSONObject jsonObject = new JSONObject(s);
                JSONArray array = jsonObject.getJSONArray("articles");

                for(int i = 0; i<array.length();i++){
                    JSONObject o = array.getJSONObject(i);
                    ListItem item = new ListItem(
                            o.getString("picture"),
                            o.getString("name"),
                            o.getString("city"),
                            o.getString("add_time"),
                            o.getString("price")
                    );
                    listItems.add(item);
                }
                adapter = new Myadapter(listItems, getApplicationContext());
                recyclerView.setAdapter(adapter);
            } catch (JSONException e) {
                e.printStackTrace();
            }

        }
    },
            new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError volleyError) {
                    Toast.makeText(getApplicationContext(), 
volleyError.getMessage(), Toast.LENGTH_LONG).show();

                }
            });
    RequestQueue requestQueue = Volley.newRequestQueue(this);
    requestQueue.add(stringRequest);
}
}

提前谢谢你,我很抱歉我的英语不好

2 个答案:

答案 0 :(得分:0)

我认为你的问题来自于此String selectedFromList = (lv.getItemAtPosition(position).toString());

lv.getItemAtPosition(position)返回一个Object,它是listView Adapter的一个项目! 在此对象上调用toString()将不会返回任何好处:)

OnClickListener有一个View in参数,在您的情况下,是您单击的Item View。 您可以在OnClickListener中检索包含名称字段的TextView,并获取此TextView的字符串,如下所示:

@Override
public void onItemClick(AdapterView<?> parent, View view, int postion, long id) {
    String name = ((TextView) view.findViewById(R.id.myNameField)).getText().toString();
}

希望能帮助你:)

PS:下次发布你的XML代码;)

答案 1 :(得分:0)

我修好了,只需改变一下:

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

    String selectedFromList = 
(lv.getItemAtPosition(position).toString());

    Intent i = new Intent(getActivity(), Test.class);

    i.putExtra("name", selectedFromList);
     startActivity(i);
}

});
return rootView;

到此:

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

        String selectedFromList= 
String.valueOf(arrayList.get(position).getIdd());

        Intent i = new Intent(getActivity(), Test.class);

        i.putExtra("name", selectedFromList);
         startActivity(i);
    }

});
return rootView;