Earlier, I was using below code in my app to get data from users table and to get data from jobs table based on userid, was getting both user id along with names of job assigned to that user.
public String[] getAllData() {
String selectQuery = "SELECT id FROM " + TABLE_USERS;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
String[] data = null;
if (cursor.moveToFirst()) {
do {
int id = cursor.getInt(cursor.getColumnIndex("id"));
Log.d("TAG","id:-"+id);
// select statement to fetch data from jobs table based on userid that matches to id of users table
String select = "SELECT name FROM " + TABLE_JOBS+ " where userid =" +id;
Cursor c = db.rawQuery(select, null);
if (c.moveToFirst()) {
do {
String name = c.getString(c.getColumnIndex("name"));
Log.d("TAG","name:-"+name);
} while (c.moveToNext());
}
} while (cursor.moveToNext());
}
db.close();
return data;
}
But now i have improvised my code, now using Pojo class for both users and jobs table.
And now i am using something like this:
// Getting All data
public List<Users> getAllvalues() {
List<Users> listUser = new ArrayList<Users>();
List<Record> listRecord = new ArrayList<Record>();
// Select All Query
String selectQuery = "SELECT * FROM " + TABLE_USERS;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
Users user = new Users();
user.setId(Integer.parseInt(cursor.getString(cursor.getColumnIndex("id"))));
String select = "SELECT name FROM " + TABLE_JOBS+ " where userid =" +detail.getId();
Cursor c = db.rawQuery(select, null);
if (c.moveToFirst()) {
do {
Jobs job = new Jobs();
record.setRname(c.getString(c.getColumnIndex("name")));
listJobs.add(job);
} while (c.moveToNext());
}
listUsers.add(user);
} while (cursor.moveToNext());
}
return listUsers;
}
And to fetch in an Activity, I am using this code:
buttonGet.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
// Reading data Already present in the Database
Log.d("Reading: ", "Reading all data..");
List<Users> user = dh.getAllvalues();
for (Users us : user) {
String id = "Id: " + us.getId();
Log.d("value: ", id);
}
}
});
Here I want to know How can i get Job name, based on userid ? Now I am only getting user id, not jobs those assigned to that particular user ...
OR
I have to make change in my code, If yes so what and where I have to make change ?
Aucun commentaire:
Enregistrer un commentaire