How do you get SQlite data on id?
-
There's a SQLITE database. Database elements are released
ListView
♪My job is:
onItemClick
move to another activate where all data from the compressed component are releasedListView
♪ I'm moving to a new activate through this.intent.putextra
ID element.Show me how to get data from the database by ID?
package com.example.maxim.sqlite;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;public class Kontakt extends AppCompatActivity {
long DIFFICULTY_EASY;
TextView konname;
TextView konphone;
long userId;
SQLiteDatabase db;
String name;
int phone;
DatabaseHelper sqlHelper;@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_kontakt);
//получаем строку и формируем имя ресурса
userId = getIntent().getLongExtra("id", DIFFICULTY_EASY);
Log.d("my","лог "+userId);konname=(TextView)findViewById(R.id.konname); konphone=(TextView)findViewById(R.id.konphone); sqlHelper = new DatabaseHelper(getApplicationContext()); db = sqlHelper.getReadableDatabase(); String selection = "_id = ?"; String[] selectionArgs = new String[] {String.valueOf(userId)}; Cursor c = db.query("kontakts", null, selection, selectionArgs, null, null, null); if(c.moveToFirst()){ name = c.getString(c.getColumnIndexOrThrow ("COLUMN_NAME")); phone = c.getInt(c.getColumnIndexOrThrow ("COLUMN_PHONE")); } Log.d("my","лог "+name+phone);
}
}
-
Method
query
orrawQuery
♪ Below is the using methodquery
♪For this, we'll set up the parameters for it: the name of the table, not the name of the OBD as you have in the code, a set of unloading columns if you need anything to be transferred.
null
the condition for which the sample is made, without the keywordWHERE
and, as we want to avoid injections, parameters for the conditions of the individual mass. Other parametersnull
because we don't care about grading, fixing, etc. This is the code:String selection = "_id = ?"; String[] selectionArgs = new String[] {String.valueOf(id)}; Cursor c = db.query("TABLE_NAME", null, selection, selectionArgs, null, null, null); if(c.moveToFirst()){ // достаем данные из курсора }
By the way, I'd like to draw attention to the fact that you don't have to do two consistent challenges to methods.
moveToFirst()
andmoveToNext()
the first element will be missed. One of them is enough, depending on what you want, to get the first element, or to go all the way to the cadet.