2013-02-08 5 views
2

데이터베이스 (ID, 이름)에서 데이터를 가져와 ListView에 (이름)을 표시하고 싶습니다. 사용자가 클릭 할 때 작업을 수행하려면 데이터베이스 (ID)를 가져와야합니다. 나는 그것을 얻는다. 그러나 나의 해결책은 그런 단순한 물건을 위해 복잡하게 보인다. 어떻게 든 (id)를 숨겨진 방법으로 ListView에 저장하고 사용자가 항목을 선택하면 가져올 수 있습니다. 이 작업을 수행 할 수있는 간단한 방법이ListView에서 데이터베이스 ID 가져 오기

class Route { //structure to store the data in ListView 
    public int id; 
    public String name; 
    public Route (int Id, String Name) { 
     id = Id; 
     name = Name; 
    } 
} 

// Create a custom adapter, we also created a corresponding 
// layout (route_row) for each item of the ListView 
public class MySimpleArrayAdapter extends ArrayAdapter<Route> { 
     private final Context context; 
     private final String[] values; 

     public MySimpleArrayAdapter(Context context, ArrayList<Route> routes) { 
     super(context, R.layout.route_row, routes); 
     this.context = context; 
     //Get the list of string array to display in the ListView 
     String[] values = new String[routes.size()]; 
     //Loop around all the items to get the list of values to be displayed 
     for (int i=0; i<routes.size(); i++) values[i] = 
        routes.get(i).id + " - " + routes.get(i).name; 
     //We added route.id to route.name for debugging but route.id is not necessary 
     this.values = values; //String array used to display data in the ListView 
     } 

     @Override 
     public View getView(int position, View convertView, ViewGroup parent) { 
     LayoutInflater inflater = (LayoutInflater) context 
      .getSystemService(Context.LAYOUT_INFLATER_SERVICE); 
     View rowView = inflater.inflate(R.layout.route_row, parent, false); 
     TextView textView = (TextView) rowView.findViewById(R.id.routeName); 
     textView.setText(values[position]); 

     return rowView; 
     } 
    } 

//output is a JSON array composed of JSON object routes 
void DisplayListView(String output) { (id, name) 
    ListView listView = (ListView) findViewById(R.id.listView1); 

    ArrayList<Route> list = new ArrayList<Route>(); 

    //Convert the JSON to ArrayList<Route> 
    try { 
    JSONArray json = new JSONArray(output); //Get JSON array 
    JSONObject jsonObj; 
    int id; 
    String name; 
    for(int i=0;i<json.length();i++) { 
     jsonObj = json.getJSONObject(i); //Get each JSON object 
     id = jsonObj.getInt("Id"); 
     name = jsonObj.getString("Name"); 
     list.add(new Route(id, name)); 
    } 
    } 
    catch (Exception ex) { 
     Log.w("Commute", ex.toString()); 
     ex.printStackTrace(); 
    } 

    //Create ArrayAdapter 
    MySimpleArrayAdapter adapter = new MySimpleArrayAdapter(getApplicationContext(), 
                    list); 
    // Assign adapter to ListView 
    listView.setAdapter(adapter); 

    //Set a listener 
    listView.setOnItemClickListener(new OnItemClickListener() { 
      @Override 
      public void onItemClick(AdapterView<?> parent, View view, 
      int position, long id) { 
      Toast.makeText(getApplicationContext(), 
       "Click ListItem Number " + 
          ((Route)parent.getItemAtPosition(position)).id, 
          Toast.LENGTH_LONG) 
       .show(); 
      //It works when user clicks we display route.id 
      } 
     }); 
    } 

없을까 : 여기 내 솔루션입니다? 나는 비슷한 질문을 찾았지만 간단하거나 명확한 대답을 찾지 못했습니다.
사용자 지정 어댑터를 피할 수 있습니까? 난 그냥 각 라인에 대한 텍스트와 간단한 ListView를 표시하고자합니다.
ArrayAdapter 주위를 반복하여 피할 수 있습니까? 그것은 정말로 불충분 한 방법입니다.

+0

나는 그것이 가장 좋은 방법인지 전혀 모르겠지만, 실제로 저장할 수있는 숨겨진'텍스트 뷰에서 id''그 '또는 레이블을 붙이고 해당 객체에 대해 'android : visibility = "gone"을 설정하면됩니다. –

답변

0

: 그럼 당신은 이런 식으로 뭔가를 사용할 수 있습니다. ListActivity를 만들기

  • 사용자 정의 배열 어댑터에서

  • (항목 클릭에 대한 리스너를 등록 처리됩니다) 시작하는 더 좋은 방법입니다, 재정의 : public long getItemId (int position) 해당 ID를 반환 할 때 onListItemClick GET 라는.

  • SimpleCursorAdapter를 사용할 때 데이터베이스 ID는 onListItemClick으로 자동 식별됩니다. 하여 SimpleCursorAdapter의 결합을 할 때 우리가 ID를 제공하기 때문에 어쩌면이다 :
    new String[] { "Name", "IsOffer", "Distance", BaseColumns._ID }, //Columns from table BaseColumns._ID new int[] { R.id.name, R.id.isOffer, R.id.distance, R.id.id },

0

보기의 setTag() 메소드를 사용하여보기에 사용자 고유의 객체를 첨부하십시오. 나중에 그러나 여기에서 해답의 일부입니다 내가 대답을 자세히 설명합니다

 vh.favourite.setOnClickListener(new View.OnClickListener() { 
     @Override 
     public void onClick(View view) { 
      ForumThread th = (((ViewHolder) view.getTag()).thread); 
      th.setWatched(!th.isWatched()); 
      th.saveLater(); 
      notifyDataSetChanged(); 
     } 
    });