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
답변
이 @brahmyadigopula 코멘트에 추가 MySQL에서 목록보기 JSON에서 새로운 활동에 데이터를 보내기입니다 방법이 더 간단하고 이미 preferd의 방법으로 JSON을 사용하는 경우, 당신은에 JSON strings
을 변환하기위한 구글의 라이브러리를 사용할 수 있습니다 한 줄의 코드로 Objects
https://github.com/google/gson
그런 다음 당신은 그냥 같은 라이브러리와 JSON 객체를 스트링으로 변환하고 문자열로 활동의 String로서 의도와 '캐치'그것을 통해 그것을 통과 개체로 다시 변환 할 수 있으며 원하는대로 사용하십시오.
그것은 다음과 같이 보일 것입니다 :
public class User { private String name; private String number; (getters/setters) }
그리고 어댑터에 당신이 할 것을 : 데이터를 가져올 때 User user = new Gson().fromJson(jsonMainNode, User.class);
그래서 당신이 다음 청소기 코드를 가질 수 있습니다. 따라서 데이터를 의도와 함께 전달할 때 개체를 문자열로 변환하면 String jsonString = new Gson().toJson(user);
이되고 의도를 통해 전달됩니다.
희망이 도움이됩니다.
오, 고맙습니다. – Tan
어댑터의 경우 목록 항목의 레이아웃에 "android.R.layout.simple_list_item_1"을 (를) 사용하고 있습니다. 결과적으로 간단한 TextView가 제공되며이 TextView는 전체 학생 변수 (이름 - 번호)를 전체 String 변수로 포함합니다. 다음과 같이
1- 항목 텍스트 뷰의 텍스트를 가져 학생들의 정보를 얻기 위해 분할 기능을 사용 :
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에 대한 사용자 정의 레이아웃을 생성 나는 당신의 문제에 대한 3 개 솔루션을 LinearLayout에 2 개의 TextViews를 포함하고, 하나는 이름을, 하나는 Number를 포함합니다. 그런 다음, 당신은 쉽게 다음과 같이 개별적으로 각각의 정보를 얻을 수 있습니다
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();
}
}
}
보내 프로필 활동 데이터 :
: 마지막으로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 활동에서 보낸 정보를 검색 할
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"));
}
}
- 1. 는 <true>를 예상하지만,
- 2. fstream에서 <<를 사용하여 쓰기
- 3. 는 이전 요소 (추가)를 사용하여 JQuery와
- 4. 는 셀레늄 (파이썬)를 사용하여 셀레늄
- 5. 는 Windows.Web.HttpClient PostAsync()를
- 6. <<를 사용하여 문자열을 추가하는 것이 예상대로 작동하지 않지만 +를 사용하여
- 7. SFINAE를 사용하여 글로벌 연산자 <<를 확인하십시오.
- 8. JavaScript를 사용하여 <img ...>을 (를)
- 9. 는 조건 (COUT)를
- 10. 는 = "true"를
- 11. 는 sIo.sockets.clients()를
- 12. 는 $를 "이스케이프"
- 13. <<는 파이썬에서 무엇을합니까?
- 14. 는 << 중복 항목을
- 15. 는 <유닉스
- 16. 어떻게 <code>.htaccess</code>를 사용하여,
- 17. COUT의 여러 선두로부터 걸쳐-포장 "<<"를 사용하여 정규식
- 18. mongoid에서 '<<'를 사용하여 임베드 된 항목에 after_save를 할당하면?
- 19. 는 "a"는 "B"를 입력
- 20. 는 <String>
- 21. Swift에서 +++ 및 <<<는 무엇입니까?
- 22. PHP <<<는 무슨 뜻입니까?
- 23. 는
- 24. 는 경우 FindByName <EntryCell> ("txtCell")를 사용하여 런타임에 값을 entrycell 변경할 수 없습니다
- 25. nodejs keystone : "<"를 "<"으로 바꿉니다.
- 26. 연산자 "<<"를 포인터에 사용
- 27. ios : <CLLocationManagerDelegate>를 사용하여 CLLocationCoordinate2D를 얻는 방법
- 28. 내가 <code>/<?=>|[^\s\w]|\w+/g</code>를 사용하여 일치
- 29. 는 <BR>
- 30. 는 <String>
프로필 활동의 의도에서 전달한 학생 ID를 얻었습니까? –
당신이 사용하는 코드가별로 좋지 않으므로 pojo 클래스를 사용하여 데이터를 저장하고 전역 변수에서 데이터를 검색하십시오. 어댑터 클래스를 사용하여 데이터를 표시 한 클래스에서 다른 클래스로 데이터를 보낼 수 있습니다. –
@IchigoKurosaki 아니요, student_id는 mysql에 저장되어 있으며 거기에서 가져 와서 학생 목록 활동을 볼 수 있습니다. – Tan