【问题标题】:Android sqlite database get id from list viewAndroid sqlite 数据库从列表视图中获取 id
【发布时间】:2014-04-01 21:47:06
【问题描述】:

我有一个工作数据库,放在我的资产文件夹中我需要,但现在他们要求我放置一个搜索框来查找特定项目并且它不起作用,因为我使用列表视图上的位置来知道单击了哪些项目,现在当我使用搜索框时,位置和 ID 会发生变化。

public class MainActivity extends Activity {
ListView datos;
ListAdapter adapter;
SQLiteConnector sqlConnect;
EditText search;
TextView _id;
ListAdapter intento;

SQLiteHelper dbTools = new SQLiteHelper (this);


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    datos = (ListView)  findViewById(R.id.listView1);
    sqlConnect = new SQLiteConnector(this);
    search = (EditText) findViewById(R.id.editTextbuscar);

    adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, sqlConnect.getAllRecord());
    datos.setAdapter(adapter);


    search.addTextChangedListener(new TextWatcher() {




        @Override
        public void onTextChanged(CharSequence cs, int arg1, int arg2,
                int arg3) {
            ((Filterable) MainActivity.this.adapter).getFilter().filter(cs);

        }

        @Override
        public void beforeTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {

        }

        @Override
        public void afterTextChanged(Editable arg0) {
        }

    });

    datos.setOnItemClickListener(new OnItemClickListener() {

        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {


        long posicion = (id + 1);

        String fraccionValues = String.valueOf(posicion);

        Intent detailsint = new Intent(getApplication(), Details.class);

        detailsint.putExtra("_id", fraccionValues);

        Toast.makeText(getApplicationContext(), fraccionValues + " selected", Toast.LENGTH_LONG).show();

        startActivity(detailsint);

        }       

    });

}

}

我需要一种不同的方式来识别列表中的项目,这是点击后调用的活动代码

public void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.details_activity);
    Fraccion = (TextView) findViewById(R.id.viewfraccion);
    Descripcion = (TextView) findViewById(R.id.viewdescripcion);
    ADV = (TextView) findViewById(R.id.viewadv);


    Intent theIntent = getIntent();

    String _id = theIntent.getStringExtra("_id");

    HashMap<String, String> fraccionMap = dbtools.getFraccionInfo(_id);

    if(fraccionMap.size()!=0) {

        Fraccion.setText(fraccionMap.get("fraccion"));
        Descripcion.setText(fraccionMap.get("descripcion"));
        ADV.setText(fraccionMap.get("adv"));

    }

}

}

有人告诉我使用 id insted of position 但它给了我相同的结果,他们告诉我这是因为我没有在我的数据库中包含 _id 但我做了。

请帮助我,我正在实习,我需要让这个工作,这份工作将帮助我获得很多经验,为上大学做好准备。

这是 sqlite 连接器

public SQLiteConnector (Context context) {
    sqlHelper = new SQLiteHelper (context) ;

}

public List<String> getAllRecord() {
List<String> fraccionesList = new ArrayList<String>();
String selectQuery = "SELECT * FROM " + TABLE_RECORD + " ORDER BY _id"; //+ " WHERE COLUMN = Fraccion";

database = sqlHelper.getReadableDatabase();
cursor = database.rawQuery(selectQuery, null);

if (cursor.moveToFirst()) {
    do {
        fraccionesList.add(cursor.getString(1));
    }

    while (cursor.moveToNext());

    }

database.close();
return fraccionesList;

}

}

和 sqliteopenhelper

公共类 SQLiteHelper 扩展 SQLiteOpenHelper {

private static String DB_PATH="/data/data/com.as.sqliteviewer/databases/";
private static String DB_NAME="Tarifa.s3db";
private static int VERSION = 1;
private SQLiteDatabase myDataBase;
private final Context myContext;

public SQLiteHelper (Context context) {
    super(context, DB_NAME, null, VERSION);                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          
    myContext = context;
    try {
        createDatabase();
        }
    catch (IOException ioe) {
        throw new Error ("Unable to create database");

    }
}

public void createDatabase() throws IOException {
    boolean dbExist = checkDataBase();

    if (dbExist) {
        System.out.println ("DB EXIST");
    }

    else {
        this.getReadableDatabase();
        this.close();
        copyDataBase();

    }
}

public void copyDataBase() throws IOException {
    InputStream myInput = myContext.getAssets().open(DB_NAME);
    String outFileName = DB_PATH + DB_NAME;
    OutputStream myOutput = new FileOutputStream(outFileName);

    byte[] buffer = new byte [1024];
    int length;
    while ((length = myInput.read(buffer)) > 0) {
        myOutput.write(buffer, 0, length);

    }

    myOutput.flush();
    myOutput.close();
    myInput.close();

}

private boolean checkDataBase() {
    SQLiteDatabase checkDB = null;

    try {
        String myPath = DB_PATH + DB_NAME;
        checkDB = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);
    }
    catch (SQLiteException e) {
        System.out.println("Database doesn't exist yet.");
    }

    if (checkDB != null) {
        checkDB.close();

    }

    return checkDB != null ? true : false;

}

@Override
public synchronized void close() {
    if (myDataBase  != null)
        myDataBase.close();

    super.close();

}

@Override
public void onCreate(SQLiteDatabase arg0) {

}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

}

public HashMap<String, String> getFraccionInfo(String id) {
    HashMap<String, String> fraccionMap = new HashMap<String, String>();

    SQLiteDatabase database = this.getReadableDatabase();

    String selectQuery = "SELECT * FROM fracciones WHERE _id ='" + id + "'";

    Cursor cursor = database.rawQuery(selectQuery, null);
    if (cursor.moveToFirst()) {
        do {

            fraccionMap.put("_id", cursor.getString(0));
            fraccionMap.put("fraccion", cursor.getString(1));
            fraccionMap.put("descripcion", cursor.getString(2));
            fraccionMap.put("adv", cursor.getString(3));

        } while (cursor.moveToNext());
    }
return fraccionMap;
}

}

【问题讨论】:

    标签: android database sqlite listview listadapter


    【解决方案1】:

    我从 SQLiteOpenHelper 更改了 getFraccionInfo 中的查询

    public HashMap<String, String> getFraccionInfo(String id) {
        HashMap<String, String> fraccionMap = new HashMap<String, String>();
    
        SQLiteDatabase database = this.getReadableDatabase();
    
        String selectQuery ="SELECT * FROM fracciones WHERE fraccion = '" + id + "'";
    
        //String selectQuery = "SELECT * FROM fracciones WHERE _id ='" + id + "'";
    
        Cursor cursor = database.rawQuery(selectQuery, null);
        if (cursor.moveToFirst()) {
            do {
    
                fraccionMap.put("_id", cursor.getString(0));
                fraccionMap.put("fraccion", cursor.getString(1));
                fraccionMap.put("descripcion", cursor.getString(2));
                fraccionMap.put("adv", cursor.getString(3));
    
            } while (cursor.moveToNext());
        }
    return fraccionMap;
    }
    

    }

    在我的主要活动中,我得到了在视图中显示的文本

    String fraccionValues = ((TextView)view.findViewById(android.R.id.text1)).getText().toString();
    

    现在查询使用“分数”视图的文本从我的数据库中查找其他信息。

    我有图片,但由于我的声誉,我无法上传。

    我有一个博客,我会在那里上传图片

    Blog

    【讨论】:

      【解决方案2】:

      也许您可以使用 setTag() 并为 View/position/id 提供您想要的唯一标签。我将它用于一些购物车的东西 - 用项目的目录号或 sku 标记视图,然后我不必记住用户点击了哪个位置/id - 我只是获取视图的 getTag()

      编辑:

      如果你想设置标签,那很简单:

       someView.setTag(someValue);
      

      在我的自定义列表视图中,我在 getView() 中设置了每个项目的标签

      someView.setTag(value_dereived_from_position);
      

      然后,在我的代码的其他部分,我可能会响应单击或按钮按下。我可以查询视图并检查标签:

      Object index = some_other_view.getTag();
      if (index == expected_value) {
         // do something 
      }
      

      【讨论】:

      • 你能举个例子吗?
      • 我需要自动为数据库中的所有项目(数千个)添加标签
      猜你喜欢
      • 2019-06-01
      • 1970-01-01
      • 1970-01-01
      • 2017-05-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多