2015-06-25 134 views
1

我正在嘗試在Android中使用SQLite數據庫進行CRUD操作以獲取列表視圖。我正在使用片段,活動和自定義基礎適配器。我可以成功突出顯示,刪除或編輯項目,並更新列表視圖和適配器。Android:在刪除操作後查看ListView項目視圖刪除項目

當我刪除一個項目(列表視圖和適配器已更新)時遇到問題,然後嘗試選擇並突出顯示後面的項目。編輯操作引用了最近刪除的項目。當我刪除一個項目並重新加載活動時,一切都按預期工作。

這使我相信列表視圖刷新和數據庫操作按預期工作,但適配器在刪除後不更新。也許這與我將它傳遞給持久高亮目的所選位置的方式有關。

代碼如下。請讓我知道,如果你需要我張貼更多或有任何改進意見的建議。

ChampionListFragment.java(我們的主列表視圖)

`

package com.androidtitan.trooptracker.Fragment; 

import android.app.Activity; 
import android.app.Fragment; 
import android.os.Bundle; 
import android.util.Log; 
import android.view.LayoutInflater; 
import android.view.View; 
import android.view.ViewGroup; 
import android.widget.AdapterView; 
import android.widget.ImageView; 
import android.widget.ListView; 
import android.widget.TextView; 

import com.androidtitan.alphaarmyapp.R; 
import com.androidtitan.trooptracker.Adapter.ChampionAdapter; 
import com.androidtitan.trooptracker.Data.DatabaseHelper; 
import com.androidtitan.trooptracker.Data.Division; 
import com.androidtitan.trooptracker.Data.Soldier; 
import com.androidtitan.trooptracker.Interface.ChampionDataPullInterface; 
import com.androidtitan.trooptracker.Interface.ChampionInterface; 

import java.util.ArrayList; 
import java.util.List; 

public class ChampionListFragment extends Fragment { 

DatabaseHelper databaseHelper; 
ChampionInterface championInterface; 
ChampionDataPullInterface pullInterface; 

ImageView deleter; 
ImageView editer; 
ImageView adder; 
TextView proceedBtn; //this will "slide" the fragment to 

TextView championHeader; 
ChampionAdapter adapter; 
ListView listView; 

Division focusDivision; 
Soldier focusSoldier; 
ArrayList<Soldier> soldierItems; 
List<Soldier> troops; 

int selection = -1; 
public int receivedIndex = -1; 

@Override 
public void onAttach(Activity activity) { 
    super.onAttach(activity); 
    try { 
     championInterface = (ChampionInterface) activity; 
    } catch (ClassCastException e) { 
     throw new ClassCastException(activity.toString() 
       + " must implement OnFragmentInteractionListener"); 
    } 

    try { 
     pullInterface = (ChampionDataPullInterface) activity; 
    } catch(ClassCastException e) { 

     throw new ClassCastException(activity.toString() 
       + " must implement MainDataPullInterface"); 
    } 

    receivedIndex = pullInterface.getDivisionIndex(); 
} 

public ChampionListFragment() { 
    // Required empty public constructor 
} 

@Override 
public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 

    if(savedInstanceState != null) { 
    } 

    databaseHelper = DatabaseHelper.getInstance(getActivity()); 

    soldierItems = new ArrayList<Soldier>(); 

    troops = databaseHelper.getAllSoldiersByDivision(databaseHelper.getAllDivisions().get(receivedIndex)); 
    soldierItems.addAll(troops); 


    Runnable runnable = new Runnable() { 
     @Override 
     public void run() { 
      adapter.notifyDataSetChanged(); 
      listView.invalidateViews(); 
     } 
    }; 

} 

@Override 
public View onCreateView(LayoutInflater inflater, ViewGroup container, 
         Bundle savedInstanceState) { 
    View v = inflater.inflate(R.layout.fragment_listview_champion, container, false); 

    deleter = (ImageView) getActivity().findViewById(R.id.deleteBtn); 
    editer = (ImageView) getActivity().findViewById(R.id.editBtn); 
    adder = (ImageView) getActivity().findViewById(R.id.addBtn); 

    championHeader = (TextView) v.findViewById(R.id.championHeader); 
    championHeader.setText(databaseHelper.getAllDivisions().get(receivedIndex).getName()); 

    listView = (ListView) v.findViewById(R.id.championList); 
    adapter = new ChampionAdapter(getActivity(), getListItems()); 
    listView.setAdapter(adapter); 

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

      if (!troops.get(position).isSelected()) { 

       troops.get(position).setIsSelected(true); 

       if (selection != -1) { 
        troops.get(selection).setIsSelected(false); 
       } 

       selection = position; 
       championInterface.setListViewSelection(selection); 

      } 
      else { 

       troops.get(position).setIsSelected(false); 

       selection = -1; 
       listView.invalidateViews(); 

       championInterface.setListViewSelection(-1); 
      } 

      for (int i = 0; i <= listView.getLastVisiblePosition() - listView.getFirstVisiblePosition(); i++) { 

       View item = listView.getChildAt(i); 
       item.setBackgroundColor(0xFFFFFFFF); 
      } 
      view.setBackgroundColor(0xCC448AFF); 

      Log.e("CLFonItemClick", troops.get(position).getfName() + " " + troops.get(position).isSelected()); 

     } 
    }); 

    deleter.setOnClickListener(new View.OnClickListener() { 
     @Override 
     public void onClick(View v) { 

      if(selection != -1) { 

       focusDivision = databaseHelper.getAllDivisions().get(receivedIndex); 
       focusSoldier = databaseHelper.getAllSoldiersByDivision(focusDivision).get(selection); 

       for(Soldier s : troops) { 
        s.setIsSelected(false); 
       } 

       databaseHelper.deleteSoldier(focusSoldier); 

       adapter.removeItem(selection); 

       selection = -1; 
       Log.e("CLFdeleter", "selection: " + String.valueOf(selection)); 

       championInterface.setListViewSelection(-1); 

      } 

     } 
    }); 

    editer.setOnClickListener(new View.OnClickListener() { 
     @Override 
     public void onClick(View v) { 
      Log.e("CFLediter", "selection: " + String.valueOf(selection)); 

      if(selection != -1) { 
       //this will populate our Adder Fragment 
       focusSoldier = soldierItems.get(selection); 

       for(Soldier s : troops) { 
        s.setIsSelected(false); 
       } 
       championInterface.soldierPasser(selection, receivedIndex, 
         focusSoldier.getfName(), 
         focusSoldier.getlName()); 
      } 
     } 
    }); 

    adder.setOnClickListener(new View.OnClickListener() { 
     @Override 
     public void onClick(View v) { 

      if(selection != -1) { 
       focusSoldier = soldierItems.get(selection); 
       focusSoldier.setIsSelected(false); 
      } 

      //when we receive our divIndex then that is what we will pass into this method 
      championInterface.soldierPasser(selection, receivedIndex, null, null); 
     } 
    }); 

    return v; 
} 

@Override 
public void onDetach() { 
    super.onDetach(); 
    championInterface = null; 
} 

private List<Soldier> getListItems() { 
    ArrayList<Soldier> soldierItems = new ArrayList<Soldier>(); 

    if (receivedIndex == -1) { 
     soldierItems.addAll(databaseHelper.getAllSoldiers()); 

    } else { 
     soldierItems.addAll(databaseHelper.getAllSoldiersByDivision(databaseHelper.getAllDivisions().get(receivedIndex))); 
    } 
    return soldierItems; 
} 


} ` 

ChampionActivity.java

`包com.androidtitan.trooptracker.Activity;

import android.app.FragmentTransaction; 
import android.content.Intent; 
import android.os.Bundle; 
import android.support.v7.app.AppCompatActivity; 
import android.support.v7.widget.Toolbar; 
import android.util.Log; 

import com.androidtitan.alphaarmyapp.R; 
import com.androidtitan.trooptracker.Fragment.ChampionListFragment; 
import com.androidtitan.trooptracker.Interface.ChampionInterface; 
import com.androidtitan.trooptracker.Interface.ChampionDataPullInterface; 

public class ChampionActivity extends AppCompatActivity implements ChampionDataPullInterface, ChampionInterface{ 

ChampionListFragment championFragment; 
//ChampionDataPullInterface push4frag2pull; 

int divisionIndex; 
int selectionIndex = - 1; 

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_champion); 

    //Data Section 

    Intent intent = getIntent(); 
    divisionIndex = intent.getIntExtra("landingDivision", -1); 
    Log.e("ChampAonCreate", "divisionIndex: " + divisionIndex); 
    Bundle args = new Bundle(); 
    args.putInt("num", divisionIndex); 

    //View Section 
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); 
    setSupportActionBar(toolbar); 
    getSupportActionBar().setDisplayShowTitleEnabled(false); 


    championFragment = new ChampionListFragment(); 
    championFragment.setArguments(args); 


    FragmentTransaction fragTran = getFragmentManager().beginTransaction(); 
    fragTran.replace(R.id.championContainer, championFragment, "championFragment").commit(); 

} 


@Override 
public void tabInteraction(int id) { 

} 

@Override 
public void soldierPasser(int soldierInt, int divisionInt, String first, String last) { 
    Log.e("CAdeleter", "selection " + String.valueOf(soldierInt)); 


    Intent intent = new Intent(this, AdderActivity.class); 
    intent.putExtra("editSoloIndex", soldierInt); 
    intent.putExtra("editSoloDivIndex", divisionInt); 
    intent.putExtra("editSoloFirst", first); 
    intent.putExtra("editSoloLast", last); 
    startActivity(intent); 
} 

//this is going to be once we have more fragments such as maps and what's nearby 
@Override 
public void drawerListViewSelection(int selection) { 

} 

@Override 
public void adderFragDivReference(int divIndex) { 

    Intent intent = new Intent(this, AdderActivity.class); 
    intent.putExtra("divIndex", divIndex); 
    ChampionActivity.this.finish(); 
    startActivity(intent); 

} 

@Override 
public void setListViewSelection(int selection) { 
    selectionIndex = selection; 
} 

public int getListViewSelection() { 
    return selectionIndex; 
} 


@Override 
public int getDivisionIndex() { 
    return divisionIndex; 
} 



@Override 
public void onBackPressed() { 
    Intent intent = new Intent(this, LandingActivity.class); 
    this.finish(); 
    startActivity(intent); 
} 
} ` 

ChampionAdapter.java

`

package com.androidtitan.trooptracker.Adapter; 

import android.app.Activity; 
import android.content.Context; 
import android.util.Log; 
import android.view.LayoutInflater; 
import android.view.View; 
import android.view.ViewGroup; 
import android.widget.BaseAdapter; 
import android.widget.TextView; 

import com.androidtitan.alphaarmyapp.R; 
import com.androidtitan.trooptracker.Activity.ChampionActivity; 
import com.androidtitan.trooptracker.Data.DatabaseHelper; 
import com.androidtitan.trooptracker.Data.Soldier; 

import java.util.List; 

/** 
* Created by amohnacs on 6/19/15. 
*/ 

/* 
todo: we need to take the implementation of highlighting our listview items in the adapter form ADDERFRAGMENT 
todo: and implement them in the getView here. 
todo: We might have to deal with passing the 'oldDivision' and 'divSelected' variables 
todo: maybe create some headers. 
*/ 
public class ChampionAdapter extends BaseAdapter { 
private Activity context; 
DatabaseHelper databaseHelper; 

private List<Soldier> adapterData; 
private LayoutInflater layoutInflater; 

private int selection = -1; 

public ChampionAdapter(Activity acontext, List<Soldier> soldiers) { 
    this.context = acontext; 
    this.adapterData = soldiers; 
    layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); 

    databaseHelper = DatabaseHelper.getInstance(context); 

} 

@Override 
public int getCount() { 
    return adapterData.size(); 
} 

@Override 
public Object getItem(int position) { 
    return adapterData.get(position); 
} 

@Override 
public long getItemId(int position) { 
    return adapterData.get(position).getId(); 
} 

@Override 
public View getView(int position, View convertView, ViewGroup parent) { 
    ListViewHolder viewHolder; 

    selection = ((ChampionActivity) context).getListViewSelection(); 

    if(convertView == null) { 
     //inflate the listview_item_row.xml 
     LayoutInflater li = (LayoutInflater) context 
       .getSystemService(Context.LAYOUT_INFLATER_SERVICE); 
    convertView = li.inflate(R.layout.listview_champion_item, null); 
     viewHolder = new ListViewHolder(); 
     convertView.setTag(viewHolder); 
    viewHolder.firstItem = (TextView) convertView.findViewById(R.id.champ_text); 
    } 
    else { 
     viewHolder = (ListViewHolder) convertView.getTag(); 
    } 

    //ListViewSelection 
    if (position == selection) { 
     convertView.setBackgroundColor(0xCC448AFF); 
    } 
    else { 
     convertView.setBackgroundColor(0xFFFFFFFF); 
    } 

    viewHolder.firstItem.setText(adapterData.get(position).getfName() + " " 
      + adapterData.get(position).getlName()); 

    Log.e("CLFonItemClick", adapterData.get(position).getfName() + " " + adapterData.get(position).isSelected()); 

    return convertView; 
} 

class ListViewHolder { 
    public TextView firstItem; 
} 

public void removeItem(int itemPosition) { 
    //Remove the according group. Dont forget to remove the children aswell! 

    adapterData.remove(itemPosition); 
    notifyDataSetChanged(); 
    notifyDataSetInvalidated(); 

} 

}` 

ChampionInterface.java

` 
public interface ChampionInterface { 
    public void tabInteraction(int id); 
    public void soldierPasser(int soldierInt, int divisionInt, String first, String last); 
    public void drawerListViewSelection(int selection); 
    public void adderFragDivReference(int divIndex); 
    public void setListViewSelection(int selection); 
} 
` 
+0

你的數據模型是sqlite數據庫,那麼你爲什麼使用BaseAdapter?請使用SimpleCursorAdapter,請參閱Notepatd演示:http://developer.android.com/training/notepad/index.html,您將看到您的生活如何變得更加輕鬆... – pskink

+0

謝謝!遊標適配器絕對可以讓所有事情變得更加清潔。問題依然存在。這是因爲我的數據庫只在我的片段的onCreate()方法上更新,當它需要通過onClick()操作更新表時。 – androidtitan

+0

http://developer.android.com/training/notepad/notepad-ex2.html^F第3步 – pskink

回答

0

嘗試調用

Soldier toDelete = adapter.getItem(selection); 
databaseHelper.deleteSoldier(toDelete); 

if(//deletion successful){ 
    adpater.removeItem(selection); 
} 

這樣你不會重新加載你實際上沒有使用的數據庫中的對象!