2016-08-29 4 views
0
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 
+0

프로필 활동의 의도에서 전달한 학생 ID를 얻었습니까? –

+1

당신이 사용하는 코드가별로 좋지 않으므로 pojo 클래스를 사용하여 데이터를 저장하고 전역 변수에서 데이터를 검색하십시오. 어댑터 클래스를 사용하여 데이터를 표시 한 클래스에서 다른 클래스로 데이터를 보낼 수 있습니다. –

+0

@IchigoKurosaki 아니요, student_id는 mysql에 저장되어 있으며 거기에서 가져 와서 학생 목록 활동을 볼 수 있습니다. – Tan

답변

0

이 @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);이되고 의도를 통해 전달됩니다.

희망이 도움이됩니다.

+0

오, 고맙습니다. – Tan

0

어댑터의 경우 목록 항목의 레이아웃에 "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")); 
} 
}