mercredi 25 février 2015

how to retrive data from sqlite database? in android

is this correct code if i want to select a name from spinner and display its corresponding distance in text view?


public class MainActivity extends Activity implements OnClickListener,OnItemSelectedListener{ /** Called when the activity is first created. */



private Spinner spinner_s;
DatabaseHelper db;
ArrayAdapter<String> adapter;

Cursor cur;

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

db = new DatabaseHelper(this);

//insert stations into sqlite database
db.insertData("abc", 12);//name,distance
db.insertData("xyz", 10);

spinner_s = (Spinner) findViewById(R.id.spinner_src);
loadSpinner(spinner_s);
spinner_s.setOnItemSelectedListener(this);

cur = db.find_distance(spinner_s.getSelectedItem().toString());

if(cur.moveToFirst()) {
String dis = cur.getString(2);
TextView ag = (TextView) findViewById(R.id.tv_fare);
ag.setText(dis);
}


}


and in DatabaseHelper class i have:


public void insertData(String label, Integer dist) {



SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(name, label);
values.put(distance, dist);
db.insert(TABLE, null, values);
db.close();
}


public Cursor find_distance(String Selecteditem) {



String selectQuery = "SELECT distance FROM "+TABLE + " WHERE "+name +" = '"+ Selecteditem +"';" ;

String dis="";
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
cursor.moveToFirst();
//dis = cursor.getString(2);//cursor.getColumnIndex("distance"));
//cursor.close();
db.close();
return cursor;


}


When i run this code, i get error in emulator saying, unfortunately app has stopped!! what to do?


need some help!


Aucun commentaire:

Enregistrer un commentaire