Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/228.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Android adapter.notifyDataSetChanged()每次都会导致NullPointerException错误_Android - Fatal编程技术网

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

Android adapter.notifyDataSetChanged()每次都会导致NullPointerException错误,android,Android,更新数据库后,我无法将更改通知适配器。我必须退出活动并返回才能看到列表更新。我已经尝试了一些我读过的想法,但没有运气,所以我想我会发布我的代码,希望有人能看到这个bug的所在。谢谢 //public class ViolationsList extends ListActivity { public class ViolationsList extends Activity { // protected ListView violationsList; private static final

更新数据库后,我无法将更改通知适配器。我必须退出活动并返回才能看到列表更新。我已经尝试了一些我读过的想法,但没有运气,所以我想我会发布我的代码,希望有人能看到这个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();


            }
        }
    });



}
//公共类ViolationsList扩展了ListActivity{
公共类违规列表扩展活动{
//受保护的ListView违反列表;
私有静态最终字符串TAG=“MyActivity”;
受保护的静态字符串冲突=”;
受保护的字符串图\u或\u fql;
受保护字符串myFriendID=“未设置”;
受保护字符串图片=”;
受保护字符串响应=”;
受保护字符串名称=”;
选择布尔型中提琴;
long-friendId=0;
私有游标=null;
//这是数据库中自定义冲突的数组列表
private ArrayList myCustomsArrayList=新建ArrayList();
//自定义冲突的字符串数组
私有字符串[]自定义小提琴;
//用于将三个阵列构建为一个阵列的阵列列表
private ArrayList violationsCompArray=新建ArrayList();
字符串[]违反1;
字符串[]违反2;
列表视图列表;
专用适配器;
//listview的视图保持器
静态类视窗夹{
文本查看文本;
}
//
私有类SpecialAdapter扩展BaseAdapter{
//定义行的背景色。该行将在绿色亮和绿色暗之间交替。
私有int[]颜色=新int[]{0xff000000,0xff888888,0xFFCCCC};
私人停车场;
Typeface font1=Typeface.createFromAsset(getAssets(),“fonts/Colosalis Bold.ttf”);
Typeface font2=Typeface.createFromAsset(getAssets(),“fonts/helveticaneue.ttf”);
//将保存要绑定到列表的文本数据的变量。
//私有字符串[]数据;
private ArrayList data=new ArrayList();
//公共SpecialAdapter(上下文,字符串[]项){
公共SpecialLaDapter(上下文、数组列表项){
mInflater=LayoutInflater.from(上下文);
该数据=项目;
}
@凌驾
public int getCount(){
//返回数据长度;
返回data.size();
}
@凌驾
公共对象getItem(int位置){
返回位置;
}
@凌驾
公共长getItemId(int位置){
返回位置;
}
@凌驾
public void notifyDataSetChanged(){
//TODO自动生成的方法存根
super.notifyDataSetChanged();
}
//用于保存列表中每一行的视图
@凌驾
公共视图getView(int位置、视图转换视图、视图组父视图){
//ViewHolder保留对子视图的引用,以避免不必要的调用
//在每行上查找dviewbyd()。
视窗座;
if(convertView==null){
convertView=mInflater.充气(R.layout.row,空);
holder=新的ViewHolder();
holder.text=(TextView)convertView.findViewById(R.id.headline);
convertView.setTag(支架);
}否则{
holder=(ViewHolder)convertView.getTag();
}
//与持有者有效地绑定数据。
holder.text.setText((CharSequence)data.get(position));
//设置支架的背景色
int colorPos=位置%colors.length;
if((holder.text.getText().toString().equals(“原始”))| |(holder.text.getText().toString().equals(“自定义”)){
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;
}否则{
colorPos=0;
holder.text.setTypeface(font2);
}
convertView.setBackgroundColor(颜色[colorPos]);
返回视图;
}
}
////自定义违规数据库的代码
私有void insertCustom(字符串newinvalition){
DatabaseHelper DatabaseHelper=新的DatabaseHelper(此);
SQLiteDatabase db=databaseHelper.getWritableDatabase();
ContentValues cv=新的ContentValues();
cv.put(DatabaseHelper.TITLE,newViolation);
db.insert(“自定义违规”,DatabaseHelper.TITLE,cv);
cursor=db.query(“customViolations”,null,null,null,null,null);
开始管理游标(游标);
Log.v(标记,“cursor data=“+cursor.toString());
cursor.requery();
db.close();
更新数据();
adapter.notifyDataSetChanged();
}
私有void DeleteCustom(字符串newViolation)
{
DatabaseHelper DatabaseHelper=新的DatabaseHelper(此);
SQLiteDatabase db=databaseHelper.getWritableDatabase();
db.delete(“customViolations”、“myViolation”+“=?”,新字符串[]{violation});
Log.v(标签、违规);
db.close();
Log.v(标记“删除您的自定义违规行为”);
cursor.requery();
更新数据();
adapter.notifyDataSetChanged();
}
/////用于记录光标信息以备测试的代码!!!!
公共无效日志游标信息(游标游标游标1){
Log.i(标记“***游标开始***”+”结果:“+cursor1.getCount()+”列:“+cursor1.getColumnCount());
//打印列名
字符串rowHeaders=“| |”;
对于(int i=0;iSpecialAdapter adapter = new SpecialAdapter(this, violationsCompArray);
private SpecialAdapter adapter;
adapter = new SpecialAdapter(this, violationsCompArray);