简体   繁体   English

将数据从“片段”列表视图项传递到“活动”字符串变量onitemclicklistener

[英]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. 我试图将ListView项目从片段传递到活动中的字符串变量“ url”,该意图成功创建了活动,但是当我尝试传递数据时却在其中运行问题。 the fragment class has a listview with json data that brings up the list of picture,title and name . fragment类具有一个带有json数据的listview,它显示了picture,title和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. 我希望他们的选择将名称从列表视图转移到其他活动中的url变量。 so the url changed from " https://.....id= " to " https://.....id= "+ name from the fragment. “这样的URL从改变://.....id= HTTPS ”到“ HTTPS://.....id= ” + 名字从片段。 thats will make the recyclerview changed with the new url for any listview item clicked. 多数民众赞成将使recyclerview更改为新的url,单击任何listview项目。

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()); 我认为您的问题来自于此: String selectedFromList = (lv.getItemAtPosition(position).toString());

lv.getItemAtPosition(position) returns an Object which is an item of the listView Adapter ! lv.getItemAtPosition(position)返回一个Object,它是listView Adapter的一项! Calling toString() on this object will return nothing good :) 在此对象上调用toString()不会返回任何结果:)

The OnClickListener has a View in parameter which is the parent View, in your case, the Item View you clicked. OnClickListener具有一个View in参数,它是父视图,在您的情况下是您单击的Item视图。 You can retrieve the TextView holding the name field in the OnClickListener and get the string of this TextView like this : 您可以在OnClickListener中检索包含name字段的TextView,并获取此TextView的字符串,如下所示:

@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 ;) PS:下次也发布您的XML代码;)

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;

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

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