2012-05-03 3 views
0

키 - 값 쌍이 포함 된 사용자 정의 BaseAdapter이 있습니다. 내 ListView에서 목록의 항목을 짧게 클릭하면 목록에서 항목을 제거하고 싶습니다. 내 문제는 notifyDataSetChanged을 실행하는 방법을 모른다는 것입니다 - 아래 onListItemClick을 참조하십시오.onListItemClick()에서 사용자 정의 BaseAdapter에서 항목을 제거 할 수 없습니다.

나는 고통을 일으키는 MyCustomAdapter에 생성자가 있습니다.

아래 코드는 두 클래스입니다.

1 등급

Dynamiclists extends ListActivity

등급 1 급에서 2

MyCustomAdapter extends BaseAdapter

, 그때 onListItemClick에 의해 지시받은 위치에서 HashMap지도에서 제거 할 것 클래스 2를 업데이트하십시오.

package telephone.org; 


import java.util.HashMap; 
import java.util.Set; 
import java.util.Map.Entry; 

import telephone.org.MyService.LocalBinder; 
import android.app.ActivityManager; 
import android.app.ListActivity; 
import android.app.ActivityManager.RunningServiceInfo; 
import android.content.ComponentName; 
import android.content.Context; 
import android.content.Intent; 
import android.content.ServiceConnection; 
import android.database.Cursor; 
import android.net.Uri; 
import android.os.Bundle; 
import android.os.IBinder; 
import android.provider.ContactsContract; 
import android.provider.ContactsContract.PhoneLookup; 
import android.util.Log; 
import android.view.LayoutInflater; 
import android.view.View; 
import android.view.ViewGroup; 
import android.widget.BaseAdapter; 
import android.widget.ListView; 
import android.widget.TextView; 
import android.widget.Toast; 
import android.widget.AdapterView.OnItemLongClickListener; 


//class 1 
public class DynamicLists extends ListActivity { 


    MyService mService; 
    boolean mBound = false; 


//class 2 /////////////////////////////////// 
public class MyCustomAdapter extends BaseAdapter { 


    public HashMap<String, Integer> mData = new HashMap<String,Integer>(); 
    private String[] mKeys; 
    //constructor  
    public MyCustomAdapter(DynamicLists dynamicLists, int row, HashMap<String, Integer> map){ 
    mData = map; 
    mKeys = mData.keySet().toArray(new String[map.size()]); 
    Log.d(TAG, "INSIDE ADAPTER constructor HELLO WORLD " + map.entrySet()); 

} 

public MyCustomAdapter(MyService mService, int row, Object map) { 
     // TODO Auto-generated constructor stub 
    } 

@Override 
public View getView(int position, View convertView, ViewGroup parent) { 
//TODO Auto-generated method stub 

    Log.d(TAG, "inside getview "); 
    View row=convertView; 

if (row==null){ 
    LayoutInflater inflater=getLayoutInflater(); 
    row=inflater.inflate(R.layout.row, null); 
} 

TextView label =(TextView)row.findViewById(R.id.blocked); 
label.setText(mKeys[position] + " " + getItem(position).toString()); //key + value 
return row; 


} 



@Override 
public int getCount() 
{ 
    // TODO Auto-generated method stub 
    return mData.size(); 
} 
@Override 
public Object getItem(int position) 
{ 
    // TODO Auto-generated method stub 
    Log.d(TAG, "inside getitem " + mData.get(mKeys[position])); 
    return mData.get(mKeys[position]); 
} 
@Override 
public long getItemId(int position) 
{ 
    // TODO Auto-generated method stub 
    return position; 
} 

} //end of class 2 //////////////////////// 



private static final String TAG = "DynamicList"; 

//class 1 

public static HashMap<String, Integer> map = new HashMap<String, Integer>(); 

/** Called when the activity is first created. */ 
@Override 
public void onCreate(Bundle savedInstanceState) { 
super.onCreate(savedInstanceState); 


} 


@Override 
protected void onListItemClick(ListView l, View v, int position, long id) { 
//TODO Auto-generated method stub 

//remove entries from hashmap map 
String selection = l.getItemAtPosition(position).toString(); 
String[] tkeys; 
tkeys = map.keySet().toArray(new String[map.size()]); 
Integer toremove = map.get(tkeys[position]); 
Toast.makeText(this, "The value is" + map.get(tkeys[position]), Toast.LENGTH_LONG).show(); 
map.remove(toremove); 
//how to notify MyCustomAdapter of changes 

//end of remove entries from hashmap map 
} 

@Override 
public void onStart() { 
    super.onStart(); 
    isMyServiceRunning(); 

} 


public void onStop() { 
    super.onStop(); 
    // Unbind from the service 
    if (mBound) { 
    unbindService(mConnection); 
    mBound = false; 
    } 
} 

private boolean isMyServiceRunning() { 
    ActivityManager manager = (ActivityManager) getSystemService(ACTIVITY_SERVICE); 
    for (RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) { 
     if ("telephone.org.MyService".equals(service.service.getClassName())) 
     { 
      Toast.makeText(getApplicationContext(),"SERVICE IS RUNNING", Toast.LENGTH_LONG).show(); 
      Intent intent = new Intent(this, MyService.class); 
      bindService(intent, mConnection, Context.BIND_AUTO_CREATE); //SEE INTERACT WITH SERVICE BELOW 


      return true; 
     } 
    } 
      Toast.makeText(getApplicationContext(),"SERVICE IS STOPPED AND IS NOT RUNNING", Toast.LENGTH_LONG).show(); 
    return false; 
} 

//INTERACT WITH SERVICE 
/** Defines callbacks for service binding, passed to bindService() */ 
private ServiceConnection mConnection = new ServiceConnection() { 
@Override 
public void onServiceConnected(ComponentName className, IBinder service) { 
// We've bound to LocalService, cast the IBinder and get LocalService instance 
LocalBinder binder = (LocalBinder) service; 
mService = binder.getService(); 
mBound = true; 
Set<Entry<String, Integer>> whatsup = mService.getNumbers(); 
Toast.makeText(getApplicationContext(),"NUMBER INTERACTION IS" + whatsup, Toast.LENGTH_LONG).show(); 
Log.d(TAG, "ELEMENTS from service are:" + whatsup); 
Toast.makeText(getApplicationContext(),"NUMBER OF ENTRIES IS" + whatsup.size(), Toast.LENGTH_LONG).show(); 


//convert SET BACK TO HASHMAP 
for (Entry<String,Integer> entry : whatsup) { 

    String name = null; 
    String[] projection = new String[] { 
      ContactsContract.PhoneLookup.DISPLAY_NAME}; 
    Uri uri = Uri.withAppendedPath(PhoneLookup.CONTENT_FILTER_URI, Uri.encode(entry.getKey())); 
    Cursor cursor = getContentResolver().query(uri, projection, null, null, null); 

    if (cursor.moveToFirst()) { 
     name = cursor.getString(cursor.getColumnIndex(ContactsContract.PhoneLookup.DISPLAY_NAME)); 
    } 
    Toast.makeText(getApplicationContext(),"RESOLVED NAME IS " + name, Toast.LENGTH_LONG).show(); 
    projection = null; 
    map.put(name,entry.getValue()); 
    } 


setListAdapter(new MyCustomAdapter(DynamicLists.this, R.layout.row, map)); 

} 

//end CONVERT SET BACK TO HASHMAP 


@Override 
public void onServiceDisconnected(ComponentName arg0) { 
mBound = false; 
} 
}; 
//END INTERACTION WITH SERVICE 

} //end of class 1 

답변

0

들여 쓰기에 약간의 문제가 있지만 onListItemClick 함수가 올바른 HashMap/행을 제거했음을 확인 했습니까?

getListAdapter().notifyDataSetChanged(); 

그러나 나는 당신이 예를 tkeys[position] 여기처럼 position를 사용하는 방법을 좋아하지 않는다 : 그럼 onListItemClick 호출의 끝 부분에 있는지를 비교합니다. 위치는 의 색인입니다. 항목이고, id는 의 색인입니다. 모두 항목입니다. 그러나 그것이 작동하면 나는 불만 없습니다. .

public void onListItemClick(ListView l, View v, int position, long id) { 
    MyCustomAdapter adapter = getListAdapter(); 
    map.remove(adapter.get((int) id)); 
    adapter.notifyDataSetChanged(); 
} 
+0

안녕하세요 샘, 내가 onListItemClick도 정확하지 생각받은 위치 :

나는이 테스트를하지 않은,하지만 그것이 다른 방법으로 작동합니다은 (map 가정하면 ListView에가에서 내장 된 모음입니다 목록에서 postion을 나타냅니다. 0 위치에서 해시 맵 맵에서 해당 항목을 삭제하고 notifydatasetchange를 삭제하려고합니다. 어떻게해야 할 지 혼란 스럽습니다. – user803271

+0

감사합니다. sam 나는 그레이엄을 많이 숙지했습니다. – user803271

+0

다시 업데이트했는데,이 코드는 작동해야하지만 여전히 앱의 스키마를 보는 데 문제가 있습니다. – Sam

관련 문제