简体   繁体   中英

Passing Data from Fragment listview item to Activity string variable onitemclicklistener

I am trying to pass a ListView item from a fragment to a String variable "url" in activity, The intent successfully creates the activity however I run issues into it when I try passing data. the fragment class has a listview with json data that brings up the list of picture,title and name . when a user selects an item it brings them to the activity. I want their selection transfer the name from the listview to the url variable in the other activity. so the url changed from " https://.....id= " to " https://.....id= "+ name from the fragment. thats will make the recyclerview changed with the new url for any listview item clicked.

my fragment:

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;
}
}

my activity:

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);
}
}

Thank you in advance, and i'm very sorry for my bad English

Your problem comes from this I think : String selectedFromList = (lv.getItemAtPosition(position).toString());

lv.getItemAtPosition(position) returns an Object which is an item of the listView Adapter ! Calling toString() on this object will return nothing good :)

The OnClickListener has a View in parameter which is the parent View, in your case, the Item View you clicked. You can retrieve the TextView holding the name field in the OnClickListener and get the string of this TextView like this :

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

Hope that will help you :)

PS : Post your XML code as well next time ;)

I fix it, just change this:

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;

to this:

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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