Android:删除操作后查看ListView项目视图已删除项目

时间:2015-06-25 02:44:24

标签: android android-listview android-studio android-adapter

我正在尝试使用Android中的SQLite数据库进行CRUD操作以获得列表视图。我正在使用片段,活动和自定义基础适配器。我可以成功突出显示,删除或编辑项目,并更新列表视图和适配器。

当我删除项目(列表视图和适配器已更新)时遇到问题,然后我尝试选择并立即突出显示项目。编辑操作引用最近删除的项目。当我删除一个项目并重新加载活动时,一切都按预期工作。

这让我相信列表视图刷新和数据库操作正在按预期工作,但删除后适配器没有更新。也许它与我传递选定位置的方式有关,以便持续突出显示。

代码如下。如果您需要我发布更多或者有任何改进建议,请告诉我。

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

`package 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);
}
`

1 个答案:

答案 0 :(得分:0)

尝试致电

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

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

这样您就不会从实际不使用的数据库中重新加载对象了!