Fetching row columns into edit texts, row id in textview - android

I have a page with a number edit texts, i want to populate these with columns of a raw with the row id equaling a textview value... this is what i have so far in the edit text page.
public class CBCreate extends Activity {
EditText EditRecipe,EditRecipe2,EditRecipe3;
Button Rname;
CBDataBaseHelper entry;
TextView RowIDText;
Cursor c;
String name;
String category;
String description;
//final String SQL_STATEMENT = "SELECT Recipe_Name, Recipe_Category, Recipe_Description FROM RecipeData WHERE _id = " + RowIDText ;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.create); // sets the content view to main
EditRecipe = (EditText) findViewById(R.id.editText1);
EditRecipe2 = (EditText) findViewById(R.id.editText2);
EditRecipe3 = (EditText) findViewById(R.id.editText3);
RowIDText = (TextView) findViewById(R.id.RowID);
Rname = (Button) findViewById(R.id.RecipeName);
String RowID;
try{
Bundle extras = getIntent().getExtras();
if (extras != null) {
RowID = extras.getString("SELECTED");
RowIDText.setText(RowID);
}
if (RowIDText != null){
entry = new CBDataBaseHelper(this);
String s = RowIDText.getText().toString();
int ID = Integer.parseInt(s);
entry.open();
Cursor cursor = entry.fetchRow(ID);
if (cursor.moveToFirst()){ // data?
name = cursor.getString(cursor.getColumnIndex(CBDataBaseHelper.KEY_NAME));
}
entry.close();
EditRecipe.setText(name);
EditRecipe2.setText(category);
EditRecipe3.setText(description);
}
}catch (Exception e){
String error = e.toString();
Dialog d = new Dialog(this);
d.setTitle("darn");
TextView tv = new TextView(this);
tv.setText(name);
d.setContentView(tv);
d.show();
}
}
public void doIt(View view) {
String Name = EditRecipe.getText().toString();
String description = EditRecipe.getText().toString();
String category = EditRecipe.getText().toString();
entry = new CBDataBaseHelper(CBCreate.this);
entry.open();
entry.createEntry(Name, description, category);
entry.close();
EditRecipe.setText("");
EditRecipe2.setText("");
EditRecipe3.setText("");
}
public void goBack(View view){
Intent myIntent = new Intent(this, CBFilter.class);
startActivity(myIntent);
}
}
and then this is what i have within the database helper class... i think i want to call this method?
public Cursor fetchRow(long rowId) throws SQLException {
Cursor mCursor = mydatabase.query(true, DATABASE_TABLE, new String[] { KEY_ROWID,
KEY_CATEGORY, KEY_DESCRIPTION }, KEY_ROWID + "="
+ rowId, null, null, null, null, null);
if (mCursor != null) {
mCursor.moveToFirst();
}
return mCursor;
}

I would use mydatabase.rawquery(QUERY) instead of the cursors query method. Its easier for SQL developers I think. Anyways, once you have your values in the cursor, you can do this
EditRecipe.setText(cursor.getString(0));
EditRecipe2.setText(cursor.getString(1));
Where 0 represents the first column in your returned table. You would put that code after your mCursor.moveToFirst();

Related

Retrieve birthday of specific contacts

Contact list are retrieved from Contacts and displayed in listView. When a single contact is clicked from listview it starts a new activity i.e DetailActivity.java(code provided below). I need to show the clicked contact's birthday in DetailActivity's TextView field. How to do it?
MainActivity.java
public class MainActivity extends AppCompatActivity {
ListView listView1 ;
ArrayList<String> nameArray, phoneArray;
ArrayAdapter<String> arrayAdapter;
Cursor cursor, birthdayCur ;
String name, birthday ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main1);
listView1 = (ListView)findViewById(listView);
nameArray = new ArrayList<String>();
GetContactsIntoArrayList();
arrayAdapter = new ArrayAdapter<String>(
MainActivity.this,
R.layout.contact_items,
textView, nameArray
);
listView1.setAdapter(arrayAdapter);
listView1.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapter, View view, int position, long arg) {
String data = (String) adapter.getItemAtPosition(position);
Intent appInfo = new Intent(MainActivity.this, DetailActivity.class);
appInfo.putExtra("data", data);
startActivity(appInfo);
}
});
}
public void GetContactsIntoArrayList(){
cursor = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,null, null, null);
while (cursor.moveToNext()) {
name = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
nameArray.add(name);
}
cursor.close();
String where = ContactsContract.CommonDataKinds.Event.TYPE + "=" + ContactsContract.CommonDataKinds.Event.TYPE_BIRTHDAY;
birthdayCur = getContentResolver().query(ContactsContract.Data.CONTENT_URI, null, where, null, null);
if (birthdayCur.getCount() > 0) {
while (birthdayCur.moveToNext()) {
birthday = birthdayCur.getString(birthdayCur.getColumnIndex(ContactsContract.CommonDataKinds.Event.START_DATE));
phoneArray.add(birthday);
}
}
birthdayCur.close();
}
DetailActivity.java
public class DetailActivity extends AppCompatActivity {
TextView tv1, tv2;
String data;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_detail);
Intent i = getIntent();
data = i.getStringExtra("data");
tv1 = (TextView) findViewById(R.id.name);
tv1.setText(data);
}
you can get the birthday date of contacts, try this:
ContentResolver cr = getContentResolver();
Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null);
if (cur.getCount() > 0) {
while (cur.moveToNext()) {
String id = cur.getString(cur.getColumnIndex(ContactsContract.Contacts._ID));
String name = cur.getString(cur.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
ContentResolver bd = getContentResolver();
Cursor bdc = bd.query(android.provider.ContactsContract.Data.CONTENT_URI, new String[] { Event.DATA }, android.provider.ContactsContract.Data.CONTACT_ID+" = "+id+" AND "+Data.MIMETYPE+" = '"+Event.CONTENT_ITEM_TYPE+"' AND "+Event.TYPE+" = "+Event.TYPE_BIRTHDAY, null, android.provider.ContactsContract.Data.DISPLAY_NAME);
if (bdc.getCount() > 0) {
while (bdc.moveToNext()) {
String birthday = bdc.getString(0);
// now "id" is the user's unique ID, "name" is his full name and "birthday" is the date and time of his birth
}
}
}
}
cur.close();

Android - SQLite rawQuery Listview

I am trying to query all the users data that belong to him uniquely. through FK_ID of the user in the notes table.
// Listing all notes
public Cursor listNotes() {
SQLiteDatabase db = help.getReadableDatabase();
Cursor c = db.query(help.NOTE_TABLE, new String[]{help.COLUMN_TITLE,help.COLUMN_BODY, help.COLUMN_DATE}, null, null, null, null, null);
if (c != null) {
c.moveToFirst();
}
return c;
}
// Count how many Notes user has
public int NoteCount() {
String countQuery = "SELECT * FROM " + help.NOTE_TABLE;
Cursor cursor = db.rawQuery(countQuery, null);
cursor.close();
// return count
return cursor.getCount();
}
// Updating single contact
public void editNote(long id, String title, String body) {
ContentValues edit = new ContentValues();
edit.put(help.COLUMN_TITLE, title);
edit.put(help.COLUMN_BODY, body);
open();
db.update(help.NOTE_TABLE, edit, help.NOTES_ID + "=" + id, null);
close();
}
// Deleting single note
public void deleteNote(long id) {
open();
db.delete(help.NOTE_TABLE, help.NOTES_ID + "=" + id, null);
close();
}
}
I have a tab that will then return all the users data uniquely to him. This tab is a fragment.the Method populateList() will be called onCreateView
public void populateList(){
Cursor cursor = control.listNotes();
getActivity().startManagingCursor(cursor);
//Mapping the fields cursor to text views
String[] fields = new String[]{help.COLUMN_TITLE,help.COLUMN_BODY, help.COLUMN_DATE};
int [] text = new int[] {R.id.item_title,R.id.item_body, R.id.item_date};
adapter = new SimpleCursorAdapter(getActivity(),R.layout.list_layout,cursor, fields, text,0);
//Calling list object instance
listView = (ListView) getView().findViewById(android.R.id.list);
adapter.notifyDataSetChanged();
listView.setAdapter(adapter);
}
This is a null pointer. Am i passing the data wrong
Cursor cursor = control.listNotes();
Your listNotes method should look like :
public Cursor listNotes(long userId) {
Cursor c = getActivity().getContentResolver().query(yourTodoTableURI, new String[]{help.COLUMN_TITLE,help.COLUMN_BODY, help.COLUMN_DATE}, help.COLUMN_USER_ID + " = ?", new String[]{String.valueOf(userId)} , null);
return c;
}
try this:
public List<String> getAllTask(int userID){
String query = "Select * from tablename where ID =" + userID;
cursor = db.query(); //do your code here
int id = cursor.getInt(cursor.getColumnIndex(tablename.ID));
List<String> task = new ArrayList<String>();
String query = "Select * from tableTask where ID =" + id";
cursor = db.query(); //
if (cursor != null) {
cursor.movetofirst();
// do your code here
do{
String task = cursor.get......
task.add(task);
}while(cursor.movetonext);
}
return task;
}

Fetch data from SQLite only contains single data row

In my app i am storing data to SQLite, and now i am trying to fetch that data from SQLite to activity.
as per requirement i just have to store single data at a time and my table will contain only single data row not more than one row.
so I want if table has data row then fetch data and show in form in onCreate(..) of LoginActivity.java
Getting:
The method SelectData(String) in the type myDBClass is not applicable for the arguments ()
myDBClass.java:
// Select Data
public String[] SelectData(String strOperatorID) {
// TODO Auto-generated method stub
try {
String arrData[] = null;
SQLiteDatabase db;
db = this.getReadableDatabase(); // Read Data
Cursor cursor = db.query(TABLE_NAME, new String[] { "*" },
"OperatorID=?",
new String[] { String.valueOf(strOperatorID) }, null, null, null, null);
if(cursor != null)
{
if (cursor.moveToFirst()) {
arrData = new String[cursor.getColumnCount()];
arrData[0] = cursor.getString(0); // DeviceID
arrData[1] = cursor.getString(1); // EmailID
arrData[2] = cursor.getString(2); // Event
arrData[3] = cursor.getString(3); // Operator
arrData[4] = cursor.getString(4); // EventOperator
}
}
cursor.close();
db.close();
return arrData;
} catch (Exception e) {
return null;
}
}
LoginActivity.java:-
public class LoginActivity extends Activity {
.................
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
setContentView(R.layout.activity_login);
btnLogout = (Button) findViewById(R.id.btnLogout);
btnCamera = (Button) findViewById(R.id.btnCamera);
btnGallery = (Button) findViewById(R.id.btnGallery);
txtDeviceID = (TextView) findViewById(R.id.txtDeviceID);
txtEmailID = (TextView) findViewById(R.id.txtEmailID);
txtEvent = (TextView) findViewById(R.id.txtEvent);
txtOperative = (TextView) findViewById(R.id.txtOperative);
txtEventOperator = (TextView) findViewById(R.id.txtEventOperator);
Intent intent = getIntent();
deviceID = intent.getStringExtra("deviceID");
emailID = intent.getStringExtra("emailID");
event = intent.getStringExtra("name");
operative = intent.getStringExtra("firstName");
txtDeviceID.setText(deviceID);
txtEmailID.setText(emailID);
txtEvent.setText(event);
txtOperative.setText(operative);
txtEventOperator.setText(event + " " + operative);
strEvent = txtEvent.getText().toString();
strOperative = txtOperative.getText().toString();
// Dialog
final AlertDialog.Builder adb = new AlertDialog.Builder(this);
AlertDialog ad = adb.create();
// new Class DB
final myDBClass myDb = new myDBClass(this);
// Save Data
long saveStatus = myDb.InsertData(
txtDeviceID.getText().toString(),
txtEmailID.getText().toString(),
txtEvent.getText().toString(),
txtOperative.getText().toString(),
txtEventOperator.getText().toString()
);
if(saveStatus <= 0)
{
ad.setMessage("Error!! ");
ad.show();
return;
}
// Show Data
String arrData[] = myDb.SelectData();
if(arrData != null)
{
txtDeviceID.setText(arrData[1]);
txtEmailID.setText(arrData[2]);
txtEvent.setText(arrData[3]);
txtOperative.setText(arrData[4]);
txtEventOperator.setText(arrData[5]);
}
if(txtEvent.getText().toString().equals("") && txtOperative.getText().toString().equals(""))
{
Intent intentCall = new Intent(LoginActivity.this, LicenseListActivity.class);
startActivity(intentCall);
}
}
From the op requirement..
change your method like this..
public String[] SelectData() {
// TODO Auto-generated method stub
try {
String arrData[] = new String[5];
SQLiteDatabase db;
db = this.getReadableDatabase(); // Read Data
Cursor cursor = db.query(TABLE_NAME, null, null, null, null,
null, null);
if (cursor != null) {
if (cursor.moveToFirst()) {
arrData[0] = cursor.getString(0); // DeviceID
arrData[1] = cursor.getString(1); // EmailID
arrData[2] = cursor.getString(2); // Event
arrData[3] = cursor.getString(3); // Operator
arrData[4] = cursor.getString(4); // EventOperator
}
}
cursor.close();
db.close();
return arrData;
} catch (Exception e) {
return null;
}
}
Your SelectData method takes a String argument (strOperatorID) but you are calling it with no argument, so obviously it cannot be found.
By the way you should respect Java naming conventions for your methods (i.e. not starting with upper case character)
public String[] SelectData() {
// TODO Auto-generated method stub
try {
String arrData[] = new String[5];
SQLiteDatabase db;
db = this.getReadableDatabase(); // Read Data
Cursor cursor = db.query(TABLE_NAME, null, null, null, null,
null, null);
if (cursor != null) {
if (cursor.moveToFirst()) {
do{
arrData[0] = cursor.getString(0); // DeviceID
arrData[1] = cursor.getString(1); // EmailID
arrData[2] = cursor.getString(2); // Event
arrData[3] = cursor.getString(3); // Operator
arrData[4] = cursor.getString(4); // EventOperator
} while (cur.moveToNext());
}
}
return arrData;
} catch (Exception e) {
return null;
}finally{
cursor.close();
db.close();
}

Trying DATABSE.update showing errors

Brief of app: Add contacts / Edit Contacts
-Contato.java //Show a ListView of the contacts, when itemClicked shows a dialog of info(name/telephone) and 3Buttons (Ok/Alter/Delete) the Alter button sends the user to:
-Adicionarcontato.java with the info's to edit, but when I edit and hit the button "Salvar" (save) the error: The application Mensagem(process com.example.mensagem) has stopped unexpectedly. Please try again.
Here is the code of Contato.java of the ListView.
private void ListaContatos(){
ListView user = (ListView) findViewById(R.id.lvShowContatos);
//String = simple value ||| String[] = multiple values/columns
String[] campos = new String[] {"nome", "telefone"};
list = new ArrayList<String>();
c = db.query( "contatos", campos, null, null, null, null, null);
c.moveToFirst();
if(c.getCount() > 0) {
while(true) {
list.add(c.getString(c.getColumnIndex("nome")).toString());
if(!c.moveToNext()) break;
}
}
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, list);
user.setAdapter(adapter);
user.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
reg = position;
c.moveToPosition(reg);
String nome = c.getString(c.getColumnIndex("nome"));
String telefone = c.getString(c.getColumnIndex("telefone"));
ShowMessage(nome, telefone);
}
});
}
And here is the code in the Adicionarcontato.java:
public SQLiteDatabase db;
private String mIndex = "";
private String nomeant,foneant;
static final String userTable = "contatos";
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.adicionarcontato);
if(getIntent().getExtras() != null) {
if(getIntent().getExtras().containsKey("reg")) mIndex = getIntent().getExtras().getString("reg");
}
db = openOrCreateDatabase("banco.db", Context.MODE_WORLD_WRITEABLE, null);
if(!mIndex.equals("")) {
Cursor c = db.query(false, "contatos", (new String[] {"nome", "telefone"}), null, null, null, null, null, null);
c.moveToPosition(Integer.parseInt(mIndex));
nomeant = c.getString(0);
foneant = c.getString(1);
EditText nome1 = (EditText) findViewById(R.id.etNome);
EditText telefone1 = (EditText) findViewById(R.id.etTelefone);
nome1.setText(nomeant);
telefone1.setText(foneant);
}
AdicionarContato();
ResetarInfo();
}
And the code of the button "Salvar" when clicked:
public void AdicionarContato() {
// TODO Auto-generated method stub
final EditText nm = (EditText) findViewById(R.id.etNome);
final EditText tlf = (EditText) findViewById(R.id.etTelefone);
Button add = (Button) findViewById(R.id.bSalvarContato);
add.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
final String nome = nm.getText().toString();
final String telefone = tlf.getText().toString();
if(nome.length() != 0 && telefone.length() != 0){
if(mIndex.equals("")) {
ContentValues valor = new ContentValues();
valor.put("nome", nome);
valor.put("telefone", telefone);
db.insert("contatos", null, valor);
ShowMessage("Sucesso","O Contato " + nome + " foi salvo com sucesso");
}
else {
String[] whereArgs = {"nome", "telefone"};
ContentValues dataToInsert = new ContentValues();
dataToInsert.put("nome", nome);
dataToInsert.put("telefone", telefone);
db.update("contatos", dataToInsert, "nome='"+nomeant+" and telefone='"+foneant+"'", whereArgs);
ShowMessage("Sucesso","O Contato " + nome + " foi salvo com sucesso");
}
}
}
});
}
The LogCat error it shows that:
Failure 1 (table contatos already exists) on 0x2205b0 when preparing 'create table contatos(nome varchar(50),telefone varchar(20))'.
My POV: the result in the LogCat says that the table already exists but, in the code i cant see where i shows that im trying to create it, wrong, i try to connect to it and not create it.
You don't need the whereArgs here since you are attaching the arguments in the where clause itself. Just supply null to in place of whereArgs -
db.update("contatos", dataToInsert, "nome='"+nomeant+"' and telefone='"+foneant+"'", null);
But it is always better to use the arguments. It prevents sql injection and also takes care of escaping special characters. In your case -
db.update("contatos", dataToInsert, "nome=? and telefone=?", whereArgs);
Also, your whereArgs is wrong. It should be -
String[] whereArgs = new String[] {nomeant, foneant};
FONT from the user Mukesh Soni.
Also using the whereArgs allows for some SQLite optimizations,
another issue in your code is that you dont check for the return values of update and insert operations
db.update("contatos", dataToInsert, "nome='"+nomeant+"' and telefone='"+foneant+"'", null);
db.insert("contatos", null, valor);
ocurrs you have a success in your operation you should check for the returned values of update
and insert to check if the operations actually have had success.
You should also check this good tutorial on SQLite on Android as a good starting point.

setting view data on new activity

So I have a ListView on which I click to start new Activity called MerchantView.
Between the activities I am passing the uid which is a unique identifier of a merchant.
Im then extracting merchant data from DB and want to view this data in this view.
Everything works (while debugging i can see that data is taken from DB and passed properly to setText methods) but the data does not show, am I doing this right?
public class MerchantView extends Activity {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.merchant);
String desc = "";
String name = "";
Bundle extras = getIntent().getExtras();
String uid = "0";
if(extras !=null) {
uid = extras.getString("uid");
}
// get merchant from database
if(Integer.valueOf(uid) > 0){
Cursor c = Utilities.db.query(mydb.TABLE_MERCHANT,
null,
"uid=?", new String[] {uid}, null, null, null);
if(c.moveToFirst() != false){
name = c.getString(c.getColumnIndex(MerchantsColumns.COLname));
desc = c.getString(c.getColumnIndex(MerchantsColumns.COLdesc));
}
// set values to UI
TextView descUI = (TextView) findViewById(R.id.merchantDescription);
descUI.setText(desc);
TextView nameUI = (TextView) findViewById(R.id.merchantName);
nameUI.setText(name);
}
else{
}
Button buttonMerchants = (Button) findViewById(R.id.buttonMerchants);
buttonMerchants.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
finish();
}
});
}
}
Data was set properly. The problem was in layout. The header (LinearLayout) at the top had two buttons and it was set to android:layout_height="fill_parent" which was taking whole space. After fixing that, data is showing properly.
Try Below code hope it helps
SQLiteDatabase myDB = this.openOrCreateDatabase("databasename.db", SQLiteDatabase.OPEN_READWRITE, null);
try{
Cursor c = myDB.rawQuery("select name, desc from abctable where uid="+uid, null);
int Column1 = c.getColumnIndex("name");
int Column2 = c.getColumnIndex("desc");
// Check if our result was valid.
c.moveToFirst();
if (c != null) {
int i = 0;
// Loop through all Results
do {
i++;
String name = c.getString(Column1);
String desc = c.getString(Column2);
TextView descUI = (TextView) findViewById(R.id.merchantDescription);
descUI.setText(desc);
TextView nameUI = (TextView) findViewById(R.id.merchantName);
nameUI.setText(name);
} while (c.moveToNext());
}
} catch (SQLiteException e) {
e.printStackTrace();
} finally {
if (myDB != null)
myDB.close();
}

Categories

Resources