Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/217.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 CustomAdapter中的SearchView_Android - Fatal编程技术网

Android CustomAdapter中的SearchView

Android CustomAdapter中的SearchView,android,Android,我想在我的Listview中实现一个SearchView,从数据库中获取哪些项目。。。我不知道是否必须使用EditText进行搜索,或者使用SearchView。如果我写一些字母,在我的列表视图中将只显示以千个字母开头的千个项目 主要活动: public class MyActivity extends Activity implements AppCompatCallback { private AppCompatDelegate delegate; Toolbar toolbar; priv

我想在我的Listview中实现一个SearchView,从数据库中获取哪些项目。。。我不知道是否必须使用EditText进行搜索,或者使用SearchView。如果我写一些字母,在我的列表视图中将只显示以千个字母开头的千个项目

主要活动:

public class MyActivity extends Activity implements AppCompatCallback {
private AppCompatDelegate delegate;
Toolbar toolbar;
private android.support.v7.app.ActionBarDrawerToggle mDrawerToggle;
private DrawerLayout drawerLayout;
private CustomCursorAdapter customAdapter;
private PersonDataBaseHelper databaseHelper;
private static final int ENTER_DATA_REQUEST_CODE = 1;
private ListView listView;
View LiniarLayout;
private static final String TAG = MyActivity.class.getSimpleName();
TextView myalbums ;



/**
 * Called when the activity is first created.
 */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    delegate = AppCompatDelegate.create(this, this);

    //call the onCreate() of the AppCompatDelegate
    delegate.onCreate(savedInstanceState);

    //use the delegate to inflate the layout
    delegate.setContentView(R.layout.main);
 LiniarLayout = (View)findViewById(R.id.LiniarLayout);
    //add the Toolbar
    Toolbar toolbar= (Toolbar) findViewById(R.id.mytoolbar);
myalbums = (TextView) findViewById(R.id.myalbums);
    delegate.setSupportActionBar(toolbar);
    delegate.setTitle("Photo Album");

toolbar.getBackground().setAlpha(250);

drawerLayout = (DrawerLayout)findViewById(R.id.drawer_layout);
    mDrawerToggle = new android.support.v7.app.ActionBarDrawerToggle(this ,       drawerLayout,R.string.drawer_open,R.string.drawer_close);

    drawerLayout.setDrawerListener(mDrawerToggle);

    databaseHelper = new PersonDataBaseHelper(this);

    listView = (ListView) findViewById(R.id.list_data);

    // Database query can be a time consuming task ..
    // so its safe to call database query in another thread
    // Handler, will handle this stuff for you <img  src="http://s0.wp.com/wp-includes/images/smilies/icon_smile.gif?m=1129645325g" alt=":)" class="wp-smiley">


    new Handler().post(new Runnable() {
        @Override
        public void run() {
            customAdapter = new CustomCursorAdapter(MyActivity.this, databaseHelper.getAllData());
            listView.setAdapter(customAdapter);
        }
    });
    listView.setOnItemClickListener(new OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            Log.d(TAG, "cliker on item" + position);
drawerLayout.closeDrawer(LiniarLayout);
            TextView name1 = (TextView) parent.getChildAt(position- listView.getFirstVisiblePosition()).findViewById(R.id.tv_person_name);
            String name = name1.getText().toString();
            Toast.makeText(MyActivity.this, "You selected ''"+name+" ''",Toast.LENGTH_SHORT).show();
String name2 = "/"+name+"/";
            String numeAplicatie = "/PhotoAlbum/";


            File filepath = Environment.getExternalStorageDirectory();
            File dir = new File(filepath.getAbsolutePath()
                    +numeAplicatie +name2);
            if(!dir.exists()) {
                dir.mkdirs();
            }
            Intent myIntent = new Intent(MyActivity.this, AlbumActivity.class);
            myIntent.putExtra("nameAlbum",name2);
            myIntent.putExtra("nameAlbum2",name);
            startActivity(myIntent);

        }
    });

    listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
        @Override
        public boolean onItemLongClick(final AdapterView<?> parent, View view, final int position, final long id) {
            AlertDialog.Builder builder = new AlertDialog.Builder(MyActivity.this);
            TextView name1 = (TextView) parent.getChildAt(position - listView.getFirstVisiblePosition()).findViewById(R.id.tv_person_name);
            final String name = name1.getText().toString();
          Toast.makeText(MyActivity.this ,"You selected"+" ''"+name+"''", LENGTH_SHORT).show();

            builder.setCancelable(false);
            builder.setMessage("Are you sure you want to delete ''" + name + "'' ?");
            builder.setNeutralButton("Cancel", new DialogInterface.OnClickListener() {

                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.cancel();

                }

            });
            builder.setPositiveButton("Delete", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    databaseHelper.deleteSingleRow(id);
                    customAdapter.changeCursor(databaseHelper.getAllData());
                    dialog.dismiss();
                    Toast.makeText(MyActivity.this ,"''" +name+"''"+" deleted",Toast.LENGTH_SHORT).show();
                    File filepath = Environment.getExternalStorageDirectory();
                    File dir = new File(filepath.getAbsolutePath()
                            +"/"+name+"/" );
                    deleteDir(dir);
                }
            });

            builder.setTitle("Delete Album");
            AlertDialog dialog = builder.create();
            dialog.show();
            return true;
        }
    });
    Field mDragger = null;//mRightDragger for right obviously
    try {
        mDragger = drawerLayout.getClass().getDeclaredField(
                "mLeftDragger");
    } catch (NoSuchFieldException e) {
        e.printStackTrace();
    }
    mDragger.setAccessible(true);
    ViewDragHelper draggerObj = null;
    try {
        draggerObj = (ViewDragHelper) mDragger.get(drawerLayout);
    } catch (IllegalAccessException e) {
        e.printStackTrace();
    }

    Field mEdgeSize = null;
    try {
        mEdgeSize = draggerObj.getClass().getDeclaredField("mEdgeSize");
    } catch (NoSuchFieldException e) {
        e.printStackTrace();
    }
    mEdgeSize.setAccessible(true);
    int edge = 0;
    try {
        edge = mEdgeSize.getInt(draggerObj);
    } catch (IllegalAccessException e) {
        e.printStackTrace();
    }

    try {
        mEdgeSize.setInt(draggerObj, edge * 10);
    } catch (IllegalAccessException e) {
        e.printStackTrace();
    }

}



@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_main, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();
switch (item.getItemId()){
case R.id.action_setting:
    startActivityForResult(new Intent(this, EnterDataActivity.class), ENTER_DATA_REQUEST_CODE);
}
    //noinspection SimplifiableIfStatement

     if(id==android.R.id.home){
        if(drawerLayout.isDrawerOpen(LiniarLayout)){
            drawerLayout.closeDrawer(LiniarLayout);
        }else{drawerLayout.openDrawer(LiniarLayout);
        if(databaseHelper.getAllData()==null){
            myalbums.setText("Create Album");
        }
        }
    }

    return super.onOptionsItemSelected(item);
}
public void onClickEnterData(View btnAdd) {

    startActivityForResult(new Intent(this, EnterDataActivity.class), ENTER_DATA_REQUEST_CODE);

}
public static boolean deleteDir(File dir) {
    if (dir.isDirectory()) {
        String[] children = dir.list();
        for (int i=0; i<children.length; i++) {
            boolean success = deleteDir(new File(dir, children[i]));
            if (!success) {
                return false;
            }
        }
    }

    // The directory is now empty so delete it
    return dir.delete();
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {

    super.onActivityResult(requestCode, resultCode, data);

    if (requestCode == ENTER_DATA_REQUEST_CODE && resultCode == RESULT_OK) {

        databaseHelper.insertData(data.getExtras().getString("tag_person_name"));

        customAdapter.changeCursor(databaseHelper.getAllData());
        drawerLayout.openDrawer(LiniarLayout);



    }
}

@Override
public void onSupportActionModeStarted(ActionMode mode) {

}

@Override
public void onSupportActionModeFinished(ActionMode mode) {

}

@Nullable
@Override
public ActionMode onWindowStartingSupportActionMode(ActionMode.Callback  callback) {
    return null;
}
}
和我的数据库助手:

 public class PersonDataBaseHelper {

private static final String TAG =    PersonDataBaseHelper.class.getSimpleName();

// database configuration
// if you want the onUpgrade to run then change the database_version
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = "mydatabase.db";

// table configuration
private static final String TABLE_NAME = "person_table";         // Table name
private static final String PERSON_TABLE_COLUMN_ID = "_id";     // a column named "_id" is required for cursor
private static final String PERSON_TABLE_COLUMN_NAME = "person_name";

public static final String KEY_IMG = "image";

private DatabaseOpenHelper openHelper;
private SQLiteDatabase database;

// this is a wrapper class. that means, from outside world, anyone will communicate with PersonDatabaseHelper,
// but under the hood actually DatabaseOpenHelper class will perform database CRUD operations
public PersonDataBaseHelper(Context aContext) {

    openHelper = new DatabaseOpenHelper(aContext);
    database = openHelper.getWritableDatabase();
}

public void insertData (String aPersonName) {

    // we are using ContentValues to avoid sql format errors

    ContentValues contentValues = new ContentValues();

    contentValues.put(PERSON_TABLE_COLUMN_NAME, aPersonName);


    database.insert(TABLE_NAME, null, contentValues);
}

public Cursor getAllData () {

    String buildSQL = "SELECT * FROM " + TABLE_NAME;

    Log.d(TAG, "getAllData SQL: " + buildSQL);

    return database.rawQuery(buildSQL,null);
}
public boolean deleteSingleRow(long rowId)
{

    return database.delete(TABLE_NAME, PERSON_TABLE_COLUMN_ID + "=" + rowId, null) > 0;
}
// this DatabaseOpenHelper class will actually be used to perform database related operation

private class DatabaseOpenHelper extends SQLiteOpenHelper {

    public DatabaseOpenHelper(Context aContext) {
        super(aContext, DATABASE_NAME, null, DATABASE_VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase sqLiteDatabase) {
        // Create your tables here

        String buildSQL = "CREATE TABLE " + TABLE_NAME + "( " + PERSON_TABLE_COLUMN_ID + " INTEGER PRIMARY KEY, " +
                PERSON_TABLE_COLUMN_NAME + " TEXT )";

        Log.d(TAG, "onCreate SQL: " + buildSQL);

        sqLiteDatabase.execSQL(buildSQL);
    }

    @Override
    public void onUpgrade(SQLiteDatabase sqLiteDatabase, int oldVersion, int newVersion) {
        // Database schema upgrade code goes here

        String buildSQL = "DROP TABLE IF EXISTS " + TABLE_NAME;

        Log.d(TAG, "onUpgrade SQL: " + buildSQL);

        sqLiteDatabase.execSQL(buildSQL);       // drop previous table

        onCreate(sqLiteDatabase);               // create the table from the beginning
    }
}
 }

你可以使用
EditText
SearchView
,我想
SearchView
更好地与UI集成,你能帮我编写一些代码吗?是的,我看到这个@RobVoisey,但这是我在android中的第一种大型应用,我不知道如何组合,我需要一些帮助:)好的,但是我链接的文章告诉了你它是如何完成的,我只是重复它说的没有用,我不能让它变得更简单。你可以使用
EditText
SearchView
,我想
SearchView
更好地与UI集成,你能帮我编写一些代码吗?是的,我看到了@RobVoisey,但这是我在安卓系统中的第一款大型应用程序,我不知道如何组合,我需要一些帮助:)好的,但是我链接的文章告诉你它是如何完成的,我只是重复它所说的没有用,我不能让它变得更简单。
 public class PersonDataBaseHelper {

private static final String TAG =    PersonDataBaseHelper.class.getSimpleName();

// database configuration
// if you want the onUpgrade to run then change the database_version
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = "mydatabase.db";

// table configuration
private static final String TABLE_NAME = "person_table";         // Table name
private static final String PERSON_TABLE_COLUMN_ID = "_id";     // a column named "_id" is required for cursor
private static final String PERSON_TABLE_COLUMN_NAME = "person_name";

public static final String KEY_IMG = "image";

private DatabaseOpenHelper openHelper;
private SQLiteDatabase database;

// this is a wrapper class. that means, from outside world, anyone will communicate with PersonDatabaseHelper,
// but under the hood actually DatabaseOpenHelper class will perform database CRUD operations
public PersonDataBaseHelper(Context aContext) {

    openHelper = new DatabaseOpenHelper(aContext);
    database = openHelper.getWritableDatabase();
}

public void insertData (String aPersonName) {

    // we are using ContentValues to avoid sql format errors

    ContentValues contentValues = new ContentValues();

    contentValues.put(PERSON_TABLE_COLUMN_NAME, aPersonName);


    database.insert(TABLE_NAME, null, contentValues);
}

public Cursor getAllData () {

    String buildSQL = "SELECT * FROM " + TABLE_NAME;

    Log.d(TAG, "getAllData SQL: " + buildSQL);

    return database.rawQuery(buildSQL,null);
}
public boolean deleteSingleRow(long rowId)
{

    return database.delete(TABLE_NAME, PERSON_TABLE_COLUMN_ID + "=" + rowId, null) > 0;
}
// this DatabaseOpenHelper class will actually be used to perform database related operation

private class DatabaseOpenHelper extends SQLiteOpenHelper {

    public DatabaseOpenHelper(Context aContext) {
        super(aContext, DATABASE_NAME, null, DATABASE_VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase sqLiteDatabase) {
        // Create your tables here

        String buildSQL = "CREATE TABLE " + TABLE_NAME + "( " + PERSON_TABLE_COLUMN_ID + " INTEGER PRIMARY KEY, " +
                PERSON_TABLE_COLUMN_NAME + " TEXT )";

        Log.d(TAG, "onCreate SQL: " + buildSQL);

        sqLiteDatabase.execSQL(buildSQL);
    }

    @Override
    public void onUpgrade(SQLiteDatabase sqLiteDatabase, int oldVersion, int newVersion) {
        // Database schema upgrade code goes here

        String buildSQL = "DROP TABLE IF EXISTS " + TABLE_NAME;

        Log.d(TAG, "onUpgrade SQL: " + buildSQL);

        sqLiteDatabase.execSQL(buildSQL);       // drop previous table

        onCreate(sqLiteDatabase);               // create the table from the beginning
    }
}
 }