adapter.notifyDataSetChanged()每次都会导致NullPointerException错误

时间:2012-05-15 01:15:32

标签: android

我的数据库更新后,无法通知适配器更改。我必须退出活动并返回以查看列表已更新。我已经尝试了一些我已经阅读但没有运气的想法,所以我想我会发布我的代码,希望有人可以看到这个bug所在的位置。谢谢!

//public class ViolationsList extends ListActivity {
public class ViolationsList extends Activity {

// protected ListView violationsList;
private static final String TAG = "MyActivity";

protected static String violation = "";
protected String graph_or_fql;
protected String myFriendID = "not set";
protected String picture = "";
protected String response = "";
protected String name = "";
boolean violatorSelected;
long friendId = 0;
private Cursor cursor=null;
//this is the array list for the custom violations from the database
private ArrayList<String> myCustomsArrayList = new ArrayList<String>();
//string array for custom violations
private String[] customViols;
//array list for building your three arrays into one array
private ArrayList<String> violationsCompArray = new ArrayList<String>();

String[] violations1;

String[] violations2;



ListView list;
private SpecialAdapter adapter;


//the view holder for the listview      
static class ViewHolder {
    TextView text;
}



//
private class SpecialAdapter extends BaseAdapter {



    //Defining the background color of rows. The row will alternate between green light and green dark.
    private int[] colors = new int[] { 0xff000000, 0xff888888, 0xffCCCCCC };
    private LayoutInflater mInflater;
    Typeface font1 = Typeface.createFromAsset(getAssets(), "fonts/Colossalis-Bold.ttf");
    Typeface font2 = Typeface.createFromAsset(getAssets(), "fonts/helveticaneue.ttf");
    //The variable that will hold our text data to be tied to list.

    //private String[] data;
    private ArrayList data = new ArrayList();


    //public SpecialAdapter(Context context, String[] items) {
    public SpecialAdapter(Context context, ArrayList items) {
        mInflater = LayoutInflater.from(context);
        this.data = items;
    }

    @Override
    public int getCount() {
        //return data.length;
        return data.size();
    }

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

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public void notifyDataSetChanged() {
        // TODO Auto-generated method stub
        super.notifyDataSetChanged();
    }

    //A view to hold each row in the list
    @Override
    public View getView(int position, View convertView, ViewGroup parent) {

        // A ViewHolder keeps references to children views to avoid unneccessary calls
        // to findViewById() on each row.
        ViewHolder holder;

        if (convertView == null) {
            convertView = mInflater.inflate(R.layout.row, null);

            holder = new ViewHolder();
            holder.text = (TextView) convertView.findViewById(R.id.headline);

            convertView.setTag(holder);
        } else {
            holder = (ViewHolder) convertView.getTag();
        }
        // Bind the data efficiently with the holder.
        holder.text.setText((CharSequence) data.get(position));


        //Set the background color of the holder
        int colorPos = position % colors.length;


        if ((holder.text.getText().toString().equals("ORIGINALS")) || (holder.text.getText().toString().equals("CUSTOM"))) {
            Log.v(TAG, holder.text.getText().toString());
            colorPos=1;  
            holder.text.setTypeface(font1);
            //holder.text.setTextColor(Color.parseColor("#000000"));


        } else if ("Make your own".equals(holder.text.getText().toString())) {
            Log.v(TAG, holder.text.getText().toString());
            colorPos=2;  



        }else {

            colorPos=0;
            holder.text.setTypeface(font2);
        }


        convertView.setBackgroundColor(colors[colorPos]);

        return convertView;
    }
}




////code for the custom violations database

private void insertCustom(String newViolation) {
    DatabaseHelper databaseHelper = new DatabaseHelper(this);
    SQLiteDatabase db = databaseHelper.getWritableDatabase();

    ContentValues cv = new ContentValues();
    cv.put(DatabaseHelper.TITLE, newViolation);


    db.insert("customViolations", DatabaseHelper.TITLE, cv);

    cursor = db.query("customViolations",null, null, null, null, null, null);
    startManagingCursor(cursor);
    Log.v(TAG, "cursor data = " + cursor.toString());


    cursor.requery();
    db.close();
    updateData();
    adapter.notifyDataSetChanged();



}

private void DeleteCustom(String newViolation)
{
    DatabaseHelper databaseHelper = new DatabaseHelper(this);
    SQLiteDatabase db = databaseHelper.getWritableDatabase();
    db.delete("customViolations", "myViolation" + "=?", new String[] { violation });



    Log.v(TAG, violation);
    db.close();
    Log.v(TAG, "delete your custom violation");


    cursor.requery();
    updateData();
    adapter.notifyDataSetChanged();


}


/////code to log cursor info   KEEP FOR TESTING!!!!
public void logCursorInfo(Cursor cursor1) {

    Log.i(TAG, "*** Cursor Begin *** " + " Results:" + cursor1.getCount() + " Columns: " + cursor1.getColumnCount());

    //print column names

    String rowHeaders = "|| ";
    for (int i = 0; i < cursor1.getColumnCount(); i++) {

        rowHeaders = rowHeaders.concat(cursor1.getColumnName(i) + " || ");
    }

    //print records
    cursor1.moveToFirst();
    while (cursor1.isAfterLast() == false) {

        String rowResults = "|| ";
        for (int i = 0;  i < cursor1.getColumnCount(); i++) {

            rowResults = rowResults.concat(cursor1.getString(i) + " || ");
        }
        Log.i(TAG, "Row " + cursor1.getPosition() + ": " + rowResults);
        cursor1.moveToNext();
    }


    Log.i(TAG, "***  Cursor End  ***");

}





///code to bring up text entry alert dialog
public void enterText() {


    //insert dialog builder
    AlertDialog.Builder alert = new AlertDialog.Builder(this);


    String Title = getResources().getString(R.string.dialogTitle);
    alert.setTitle(Title);

    //alert.setMessage("Message");

    // Set an EditText view to get user input 
    final EditText input = new EditText(this);
    int maxLength = 60;  
    InputFilter[] FilterArray = new InputFilter[1];  
    FilterArray[0] = new InputFilter.LengthFilter(maxLength);  
    input.setFilters(FilterArray); 
    alert.setView(input);

    alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int whichButton) {
            Editable value = input.getText();
            // Do something with value!
            insertCustom(value.toString());
            cursor.requery();


        }
    });

    alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int whichButton) {
            // Canceled.
        }
    });

    alert.show();


}

///code to bring up text entry alert dialog
public void editYourViolation() {


    //insert dialog builder
    AlertDialog.Builder yourEdit = new AlertDialog.Builder(this);


    String Title = getResources().getString(R.string.customdialogTitle);
    yourEdit.setTitle(Title);


    yourEdit.setPositiveButton("Use", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int whichButton) {
            // Do something with value!
            createViolation();
        }
    });

    yourEdit.setNegativeButton("Delete", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int whichButton) {
            // Canceled.
            DeleteCustom(violation);
        }
    });

    yourEdit.show();


}



///create the violation
public void createViolation() {


    Intent myIntent = new Intent(getApplicationContext(),
            Selection.class);
    myIntent.putExtra("friendId", friendId);
    myIntent.putExtra("name", name);
    myIntent.putExtra("picture", picture);
    myIntent.putExtra("violation", violation);
    myIntent.putExtra("violatorSelected", violatorSelected);

    startActivity(myIntent);

}



public void querydatabase() {
    DatabaseHelper databaseHelper = new DatabaseHelper(this);
    SQLiteDatabase db = databaseHelper.getWritableDatabase();
    cursor = db.query("customViolations",null, null, null, null, null, null);

}


public void populateArray() {

    cursor.moveToFirst();
    while(!cursor.isAfterLast()) {
        myCustomsArrayList.add(cursor.getString(cursor.getColumnIndex(DatabaseHelper.TITLE)));
        cursor.moveToNext();
    }
    customViols = (String[]) myCustomsArrayList.toArray(new String[myCustomsArrayList.size()]);

}




private void updateData() {
    querydatabase();
    populateArray();
    for(String i : violations1)
    {
        violationsCompArray.add(i);
    }
    //these are your custom violations
    for(String z : customViols)
    {
        violationsCompArray.add(z);
    }
    //original violations list
    for(String s : violations2)
    {
        violationsCompArray.add(s);
    }





}


@Override
public void onCreate(Bundle savedInstanceState) {




    super.onCreate(savedInstanceState);

    Bundle extras = getIntent().getExtras();
    response = extras.getString("API_RESPONSE");
    graph_or_fql = extras.getString("METHOD");
    friendId = extras.getLong("friendId");
    name = extras.getString("name");
    picture = extras.getString("picture");
    violatorSelected = extras.getBoolean("violatorSelected");
    Log.v(TAG, "violations list created");

    setContentView(R.layout.violations_list);

    violations1 = getResources().getStringArray(
            R.array.violations_array1);

    violations2 = getResources().getStringArray(
            R.array.violations_array2);

    ListView list = (ListView) findViewById(R.id.violations_list);
    list.setTextFilterEnabled(true);

    //set up the database connection and cursor for the custom violations

    updateData();

    SpecialAdapter adapter = new SpecialAdapter(this, violationsCompArray); 
    list.setAdapter(adapter);




    ///new onItemClickListener
    list.setOnItemClickListener(new OnItemClickListener() {
        public void onItemClick(AdapterView parent, View view,
                int position, long id) {

            for(String i : customViols)
            {
                Log.v(TAG, i);
            }   



            String text = (String) ((TextView) view).getText();
            violation = text;


            //the make your own value will launch the text editor
            if ("Make your own".equals(violation)) {
                Log.v(TAG, "create the code for Make your own screen");
                enterText();
                //these values are section headers and should have no selection effect                  
            }else if("ORIGINALS".equals(violation) || "CUSTOM".equals(violation))   {
                Toast.makeText(getApplicationContext(), violation,
                        Toast.LENGTH_SHORT).show();
                //test to see if the violation is from the custom violations list   
            }else if(Arrays.asList(customViols).contains(violation)) {

                editYourViolation();  

                //use one of the originals                      
            }else {

                createViolation();


            }
        }
    });



}

}

1 个答案:

答案 0 :(得分:3)

在onCreate中,您将适配器定义为:

SpecialAdapter adapter = new SpecialAdapter(this, violationsCompArray);

但随后在其他地方你引用了同名的私有成员变量

private SpecialAdapter adapter;

非常需要解决这个问题,你只需要将onCreate中的行更改为:

adapter = new SpecialAdapter(this, violationsCompArray);

这样它引用的是类成员变量,而不是你正在创建的本地变量。