【问题标题】:Send data to new activity from listview JSON from mysql将数据从 mysql 的 listview JSON 发送到新活动
【发布时间】:2016-08-29 12:54:21
【问题描述】:
I use bundle before but it only return null,
 how can i get the name of the student_name that populated from database using json of the clicked item and show it into new activity?

 public void ListDrawer() {
    final List<Map<String, String>> studentList = new ArrayList<Map<String, String>>();

    try {
        JSONObject jsonResponse = new JSONObject(jsonResult);
        JSONArray jsonMainNode = jsonResponse.optJSONArray("student_info");

        for (int i = 0; i < jsonMainNode.length(); i++) {
            JSONObject jsonChildNode = jsonMainNode.getJSONObject(i);
            String name = jsonChildNode.optString("student_name");
            String number = jsonChildNode.optString("student_id");
            String outPut = name + "-" + number;
            studentList.add(createStudent("Students", outPut));
        }
    } catch (JSONException e) {
        Toast.makeText(getApplicationContext(), "Error" + e.toString(),
                Toast.LENGTH_SHORT).show();
    }
 ////////////////////////////////// UPDATE LISTVIEW ITEMS ONCLICK

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

            //Do your logic for getting the student variables here
            Intent intent = new Intent(MainPage.this,Profile.class);

            intent.putExtra("student ", String.valueOf(id));

            startActivity(intent);
        }
    });

//////////////////////////////////////UPDATE
    SimpleAdapter simpleAdapter = new SimpleAdapter(this, studentList,
            android.R.layout.simple_list_item_1,
            new String[] { "Students" }, new int[] { android.R.id.text1 });
    listView.setAdapter(simpleAdapter);
    Toast.makeText(getApplication(), "Logged in Successfully", Toast.LENGTH_SHORT).show();

  Above is mylistview and my onItemClicked function

  i use json to retrieve the list of students from mysql and view it in listview and now im trying to pass data from the selected student in listview to new activity

 [1]: http://i.stack.imgur.com/zc56O.jpg

【问题讨论】:

  • 您是否从个人资料活动中的意图中获得了学生 ID?
  • 您正在使用的代码不太可取,因此使用 pojo 类存储数据并从这些全局变量中检索数据。使用适配器类显示数据,然后您可以将数据从一个类发送到另一个班级
  • @IchigoKurosaki 不,student_id 存储在 mysql 中,我从那里获取以查看学生列表活动。
  • @brahmyadigopula 哦,我明白了,谢谢!

标签: android mysql json listview


【解决方案1】:

要添加@brahmyadigopula 评论,使用POJO 更简单,如果您已经使用JSON 作为首选方式,您可以使用Google 库将JSON strings 转换为Objects,只需一行代码。

https://github.com/google/gson

然后,您可以使用相同的库将对象转换为 JSON 字符串,并将其作为字符串传递给 Intent,然后在 Activity 中将其作为字符串“捕获”,然后将其转换回对象并按照您的方式使用它希望。

看起来像这样:

public class User { private String name; private String number; (getters/setters) }

然后在您的适配器中,您将执行以下操作: User user = new Gson().fromJson(jsonMainNode, User.class); 这样您就可以在获取数据时获得更清晰的代码。因此,当使用意图传递数据时,您只需将 User 对象转换为字符串即可:String jsonString = new Gson().toJson(user); 并将其传递给意图。

希望这会有所帮助。

【讨论】:

    【解决方案2】:

    对于您的适配器,您使用“android.R.layout.simple_list_item_1”作为列表项的布局。结果,这将为您提供一个简单的 TextView,并且此 TextView 将包含整个学生信息(姓名-编号)作为完整的字符串变量。 对于您的问题,我有 3 个解决方案:

    1- 获取项目TextView的文本并使用split函数获取学生信息如下:

    listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
    
                //Get the item full text content
                String studentInfo = listView.getItemAtPosition(position).toString();
    
                //Split using the space " "
                ArrayList<String> studentInfoArray = new ArrayList<>(Arrays.asList(studentInfo.split(" ")));
    
                //Split using the dash "-"
                String lastObject = studentInfoArray.get(studentInfoArray.size() - 1);
                ArrayList<String> lastObjectInfoArray = new ArrayList<>(Arrays.asList(lastObject.split("-")));
    
                //Rearrange the student name
                //Sometimes the name is composed of more than two words
                String studentName = "";
                for (int i = 0; i < studentInfoArray.size() - 1; i++) {
                    studentName += " " + studentInfoArray.get(i);
                }
                studentName += " " + lastObjectInfoArray.get(0);
    
                //Create the intent to start the Profile activity
                //Add student info to extras
                Intent intent = new Intent(MainPage.this,Profile.class);
                intent.putExtra("studentName", studentName);
                intent.putExtra("studentID", lastObjectInfoArray.get(lastObjectInfoArray.size() - 1));
                startActivity(intent);
            }
        });
    

    2- 为您的 ListView 适配器创建一个自定义布局,它将在 LinearLayout 中包含 2 个 TextView,一个用于名称,一个用于数字。然后,您可以像这样轻松地分别获取每个信息:

    listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
    
            //Get the list item subviews using IDs of the custom item layout
            TextView tvStudentName = (TextView)view.findViewById(R.id.tvStudentName);
            TextView tvStudentNumber = (TextView)view.findViewById(R.id.tvStudentNumber);
    
            //Create the intent to start the Profile activity
            //Add student info to extras
            Intent intent = new Intent(MainPage.this,Profile.class);
            intent.putExtra("studentName", tvStudentName.getText());
            intent.putExtra("studentID", tvStudentNumber.getText());
            startActivity(intent);
        }
    });
    

    3- 将您的学生列表设为全局变量,然后直接从数组中获取信息:

    public class MainPage extends Activity {
    
    //Declare studentList as a global variable
    List<Map<String, String>> studentList = new ArrayList<>();
    .
    .
    .
    
    //Change the structure of your ListDrawer method
    public void ListDrawer() {
        try {
            JSONObject jsonResponse = new JSONObject(jsonResult);
            JSONArray jsonMainNode = jsonResponse.optJSONArray("student_info");
    
            for (int i = 0; i < jsonMainNode.length(); i++) {
                JSONObject jsonChildNode = jsonMainNode.getJSONObject(i);
                String name = jsonChildNode.optString("student_name");
                String number = jsonChildNode.optString("student_id");
    
                //Add the student info to a new Hashmap object
                //Add the student to the array
                Map<String, String> studentInfo = new HashMap<>();
                studentInfo.put("student_name", name);
                studentInfo.put("student_id", number);
                studentList.add(i, studentInfo);
            }
        } catch (JSONException e) {
            Toast.makeText(getApplicationContext(), "Error" + e.toString(),
                    Toast.LENGTH_SHORT).show();
        }
    }
    }
    

    然后,将数据发送到 Profile 活动:

    listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
    
            //Create the intent to start the Profile activity
            //Add student info to extras
            Intent intent = new Intent(MainPage.this,Profile.class);
            intent.putExtra("studentName", studentList.get(position).get("student_name"));
            intent.putExtra("studentID", studentList.get(position).get("student_id"));
            startActivity(intent);
    
        }
    });
    

    最后,检索从 MainPage Activity 发送到 Profile Activity 的信息:

    public class Profile extends Activity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        .
        .
    
        Log.e("EXTRA", "Student Name : " + getIntent().getExtras().getString("studentName"));
        Log.e("EXTRA", "Student ID : " + getIntent().getExtras().getString("studentID"));
    }
    }
    

    【讨论】:

      猜你喜欢
      • 2019-07-31
      • 1970-01-01
      • 2016-03-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多