I'm currently developing an app. What it does, the user would input some sentences and then the app will get the ambiguous word and then display it meaning. In my table I have fields like _id, word, meaning, definition_number.
Sample data:
_id word meaning definition_number
1 Break to pause from something 1
2 Break to cut into pieces 2
If the user would input: My break was very fast.
The intended output would be:
Ambiguous word: Break
Meaning: To pause from something
I want to display the it randomly. This is a snippet of code from my DBHelper.class:
public Cursor getAllWords()
{
Cursor localCursor =
//this.myDataBase.query(DB_TABLE, new String[] {
// KEY_ID, KEY_WORD, KEY_MEANING }, null, null, null, null, null);//"RANDOM()");
//this.myDataBase.query(DB_TABLE, new String[] {
// KEY_ID, KEY_WORD, KEY_MEANING }, null, null, null, null, "RANDOM()", " 1");
this.myDataBase.query(DB_TABLE, new String[] {
KEY_ID, KEY_WORD, KEY_MEANING },
null, null, null, null, "RANDOM()");
if (localCursor != null){
localCursor.moveToFirst();
}
return localCursor;
}
MainActivity.class:
ArrayList<String> colWords = new ArrayList<String>();
ArrayList<String> colMeanings = new ArrayList<String>();
String[] words;
String[] meanings;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initControls();
}
private void initControls() {
// TODO Auto-generated method stub
text = (EditText) findViewById (R.id.editText1);
view = (TextView) findViewById (R.id.textView1);
clear = (Button) findViewById (R.id.button2);
clear.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
text.setText("");
view.setText("");
}
});
connectDB();
ok = (Button) findViewById (R.id.button1);
ok.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
//Log.d(strWord, strWord);
strWord = text.getText().toString();
if(strWord.isEmpty()){
Toast.makeText(MainActivity.this, "Please input some data", Toast.LENGTH_SHORT).show();
} else {
checkAmbiguousWord();
}
}
});
}
private void connectDB(){
dbHelper = new DBHelper(MainActivity.this);
try {
dbHelper.createDataBase();
} catch (IOException ioe) {
throw new Error("Unable to create database");
}
try {
dbHelper.openDataBase();
} catch (SQLException sqle) {
throw sqle;
}
cursor = dbHelper.getAllWords();
/*strWord = cursor.getString(cursor.getColumnIndex(DBHelper.KEY_WORD))
+ cursor.getString(cursor.getColumnIndex(DBHelper.KEY_MEANING)); */
colWords.clear();///added code
colMeanings.clear();///added code
/*
for(cursor.moveToFirst(); cursor.moveToNext(); cursor.isAfterLast()) {
colWords.add(cursor.getString(1));
colMeanings.add(cursor.getString(2));
String records = cursor.getString(0);
Log.d("Records", records);
} */
if (cursor != null) {
if (cursor.moveToFirst()) {
do {
colWords.add(cursor.getString(1));
colMeanings.add(cursor.getString(2));
String records = cursor.getString(0);
Log.d("Records", records);
} while (cursor.moveToNext());
}
}
}
private void checkAmbiguousWord(){
final String textToCheck = text.getText().toString();
List<Integer> ambiguousIndexes = findAmbiguousWordIndexes(textToCheck);
view.setText(!ambiguousIndexes.isEmpty() ?
ambigousIndexesToMessage(ambiguousIndexes) : "No ambiguous word/s found.");
}
/**
* #param text checked for ambiguous words
* #return the list of indexes of the ambiguous words in the {#code words} array
*/
private List<Integer> findAmbiguousWordIndexes(String text) {
final String lowerCasedText = text.toLowerCase();
final List<Integer> ambiguousWordIndexList = new ArrayList<Integer>();
words = (String[]) colWords.toArray(new String[colWords.size()]);
meanings = (String[]) colMeanings.toArray(new String[colMeanings.size()]);
for (int i = 0; i < words.length; i++) {
if (lowerCasedText.contains(words[i].toLowerCase())) {
ambiguousWordIndexList.add(i);
}
}
return ambiguousWordIndexList;
}
public String ambigousIndexesToMessage(List<Integer> ambiguousIndexes) {
// create the text using the indexes
// this is an example implementation
StringBuilder sb = new StringBuilder();
for (Integer index : ambiguousIndexes) {
sb.append("Ambiguous words: ");
sb.append(words[index] + "\nMeaning: " + meanings[index] + "\n");
sb.append("");
}
return sb.toString();
}
But all it does is displaying the two records. Both id 1 and id 2. I just want to display only one record randomly. I really need help regarding this. Any ideas? I would gladly appreciate it.
You have RANDOM() ordering but you also need to add a LIMIT 1 to only return one result row. There's an overload of SQLiteDatabase.query() that takes in a limit parameter:
this.myDataBase.query(DB_TABLE, new String[] {
KEY_ID, KEY_WORD, KEY_MEANING },
null, null, null, null, "RANDOM()", "1");
Related
I have created a database that stores all the correct values. I need for each row stored in the database to be displayed on a new line in one TextView.
Current Output
Current Output
After adding to database it adds on and updates current values instead of going to new line.
Required Output
Required Output
Each row from the database displayed on a new line in TextView
Insert data to database
public static void InsertOrUpdateRatingPoints(Context context, int point, SelfToSelfActivity.Rating activity) {
DBHelper dbHelper = new DBHelper(context);
SQLiteDatabase db = dbHelper.getWritableDatabase();
String[] projection = {ID, TIME, TYPE,};
String where = TYPE + " = ?";
String[] whereArgs = {String.valueOf(activity)};
String orderBy = TIME + " DESC";
Cursor cursor = db.query(TABLE_NAME, projection, where, whereArgs, null, null, orderBy);
boolean sameDay = false;
Date currentTime = Calendar.getInstance().getTime();
int StoredPoint = 0;
long lastStored = 0;
if (cursor != null) {
if (cursor.moveToFirst()) {
lastStored = cursor.getLong(cursor.getColumnIndex(TIME));
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
sameDay = (sdf.format(new Date(lastStored))).equals(sdf.format(currentTime));
if (sameDay) StoredPoint = cursor.getInt(cursor.getColumnIndex(POINT));
}
cursor.close();
}
ContentValues cv = new ContentValues();
cv.put(POINT, point + StoredPoint);
if (sameDay) {
db.update(TABLE_NAME, cv, TIME + " = ?", new String[]{String.valueOf(lastStored)});
} else {
cv.put(TYPE, activity.ordinal());
cv.put(TIME, currentTime.getTime());
cv.put(POINT, point);
db.insert(TABLE_NAME, null, cv);
}
}
Execute
public void execute() {
AsyncTask.execute(new Runnable() {
#Override
public void run() {
Cursor c = TrackerDb.getStoredItems(getApplicationContext());
if (c != null) {
if (c.moveToFirst()) {
WorkoutDetails details = null;
do {
WorkoutDetails temp = getWorkoutFromCursor(c);
if (details == null) {
details = temp;
continue;
}
if (isSameDay(details.getWorkoutDate(), temp.getWorkoutDate())) {
if (DBG) Log.d(LOG_TAG, "isSameDay().. true");
details.add(temp);
} else {
mWorkoutDetailsList.add(details);
details = temp;
}
} while (c.moveToNext());
if (details != null) mWorkoutDetailsList.add(details);
if (DBG)
Log.d(LOG_TAG, "AsyncTask: list size " + mWorkoutDetailsList.size());
runOnUiThread(new Runnable() {
#Override
public void run() {
mWorkoutsAdapter.updateList(mWorkoutDetailsList);
//AVG_THIRTY.setText(String.valueOf(EmotionListAdapter.thirtyday));
//Today_Score.setText(String.valueOf(EmotionListAdapter.day));
}
});
}
c.close();
}
}
});
}
Display Data
#Override
public void onBindViewHolder(RatingListViewHolder holder, int position)
{
WorkoutDetails details = mWorkoutsList.get(position);
holder.textSTS.setText(String.valueOf(totalSTS));
holder.textLoss.setText(String.valueOf(details.getPoints(SelfToSelfActivity.Rating.LOSS)));
holder.textRateLoss.setText(String.valueOf(details.getPoints(SelfToSelfActivity.Rating.RATELOSS)));
}
I assume you want to display every item of ArrayList in separate lines.
Try this, hope this help.
TextView conciergeServicesTv = (TextView) findViewById(R.id.activity_get_quote_final_concierge_services_tv);
if (arrayListConciergeServices.size() != 0) { //ArrayList you are receiving\\
StringBuilder stringBuilder = new StringBuilder();
for (int i = 0; i < arrayListConciergeServices.size(); i++) {
if (i == arrayListConciergeServices.size() - 1) {
stringBuilder.append(arrayListConciergeServices.get(i));
} else {
stringBuilder.append(arrayListConciergeServices.get(i)).append("\n");
}
}
conciergeServicesTv.setText(stringBuilder);
} else {
conciergeServicesTv.setText("No concierge services selected");
}
I want user to select a number from calllog and that number get selected and come in the activity. So I created custom calllog list. I used this code but it is not showing the call log list in right order
first thing it is showing the callhistory of the first number fully that it gets in the calllog list
second I wnt to show the name also, I tried a lot but I am not able to do
Can anyone tell what amendments i make in this code to make it right
The code I used is:
String[] callLogFields = { android.provider.CallLog.Calls._ID,
android.provider.CallLog.Calls.NUMBER,
android.provider.CallLog.Calls.CACHED_NAME };
String viaOrder = android.provider.CallLog.Calls.DATE + " DESC";
String WHERE = android.provider.CallLog.Calls.NUMBER + " >0"; /*filter out private/unknown numbers */
final Cursor callLog_cursor = this.getContentResolver().query(
android.provider.CallLog.Calls.CONTENT_URI, callLogFields,
WHERE, null, viaOrder);
AlertDialog.Builder myversionOfCallLog = new AlertDialog.Builder(this);
android.content.DialogInterface.OnClickListener listener = new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialogInterface, int item) {
callLog_cursor.moveToPosition(item);
Log.v("number", callLog_cursor.getString(callLog_cursor
.getColumnIndex(android.provider.CallLog.Calls.NUMBER)));
callLog_cursor.close();
}
};
myversionOfCallLog.setCursor(callLog_cursor, listener,
android.provider.CallLog.Calls.NUMBER);
myversionOfCallLog.setTitle("Choose from Call Log");
myversionOfCallLog.create().show();
You can add the Contact Numbers in a Set, which will prevent adding duplicate contact numbers. Then add the Set's data to listview as you want.
Set<String> setNumbers = new HashSet<String>();
String callNumber = cursor.getString(cursor.getColumnIndex(
android.provider.CallLog.Calls.NUMBER));
setNumbers.add(callNumber);
Hope this helps.
For saving numbers without duplicates, as MysticMagic suggested, use 'Set' as per the link given in the comment.
For getting the contact name from the phone number, use code :
(Reference)
private String getContactName(Context context, String number) {
String name = null;
// define the columns I want the query to return
String[] projection = new String[] {
ContactsContract.PhoneLookup.DISPLAY_NAME,
ContactsContract.PhoneLookup._ID};
// encode the phone number and build the filter URI
Uri contactUri = Uri.withAppendedPath(ContactsContract.PhoneLookup.CONTENT_FILTER_URI, Uri.encode(number));
// query time
Cursor cursor = context.getContentResolver().query(contactUri, projection, null, null, null);
if(cursor != null) {
if (cursor.moveToFirst()) {
name = cursor.getString(cursor.getColumnIndex(ContactsContract.PhoneLookup.DISPLAY_NAME));
Log.v(TAG, "Started uploadcontactphoto: Contact Found # " + number);
Log.v(TAG, "Started uploadcontactphoto: Contact name = " + name);
} else {
Log.v(TAG, "Contact Not Found # " + number);
}
cursor.close();
}
return name;
}
Also refer here for another method to fetch name in phone call history
Uri allCalls = Uri.parse("content://call_log/calls");
Cursor c = managedQuery(allCalls, null, null, null, null);
String num= c.getString(c.getColumnIndex(CallLog.Calls.NUMBER));// for number
String name= c.getString(c.getColumnIndex(CallLog.Calls.CACHED_NAME));// for name
String duration = c.getString(c.getColumnIndex(CallLog.Calls.DURATION));// for duration
int type = Integer.parseInt(c.getString(c.getColumnIndex(CallLog.Calls.TYPE)));// for call type, Incoming or out going
Finally this is the code that worked with the help of MysticMagic and Nishanthi Grashia
Set setA;
setA = new HashSet();
public void getCallLog() {
try {
final String[] projection = null;
final String selection = null;
final String[] selectionArgs = null;
final String sortOrder = "DATE DESC";
final Cursor cursor = this.getContentResolver().query(
Uri.parse("content://call_log/calls"), projection,
selection, selectionArgs, sortOrder);
if (cursor != null) {
// Loop through the call log.
while (cursor.moveToNext()) {
// Common Call Log Items
String callNumber = cursor
.getString(cursor
.getColumnIndex(android.provider.CallLog.Calls.NUMBER));
setA.add(callNumber);
}
generateList();
}
} catch (Exception e) {
}
}
#SuppressLint("NewApi")
private void generateList() {
// TODO Auto-generated method stub
try {
Object[] calllist = new String[setA.size()];
calllist = setA.toArray();
String scalllist[] = Arrays.copyOf(calllist, calllist.length,
String[].class);
for (int i = 0; i < scalllist.length; i++) {
scalllist[i] = scalllist[i] + " "
+ getContactName(this, scalllist[i]);
}
final Dialog d = new Dialog(this);
d.setContentView(R.layout.dialog1);
d.setTitle("Choose from Call Log...");
final ListView lv1 = (ListView) d.findViewById(R.id.listView1);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, android.R.id.text1,
scalllist);
lv1.setAdapter(adapter);
lv1.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
// TODO Auto-generated method stub
String clickednumber[] = (lv1.getItemAtPosition(arg2)
.toString()).split(" ");
usernumber.setText(clickednumber[0]);
try {
username.setText(clickednumber[1]);
} catch (ArrayIndexOutOfBoundsException e) {
username.setText(" ");
}
d.dismiss();
}
});
d.show();
} catch (Exception e) {
}
}
private String getContactName(Context context, String number) {
String name = null;
try {
// define the columns I want the query to return
String[] projection = new String[] {
ContactsContract.PhoneLookup.DISPLAY_NAME,
ContactsContract.PhoneLookup._ID };
// encode the phone number and build the filter URI
Uri contactUri = Uri.withAppendedPath(
ContactsContract.PhoneLookup.CONTENT_FILTER_URI,
Uri.encode(number));
// query time
Cursor cursor = context.getContentResolver().query(contactUri,
projection, null, null, null);
if (cursor != null) {
if (cursor.moveToFirst()) {
name = cursor
.getString(cursor
.getColumnIndex(ContactsContract.PhoneLookup.DISPLAY_NAME));
} else {
name = " ";
}
cursor.close();
}
} catch (Exception e) {
e.printStackTrace();
}
return name;
}
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();
}
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.
I have two buttons inside of my application, one for next and one for prev. I want the next button to get the next record inside of my database and display it inside of my view, and the prev button to get the previous record and display it inside of my view. How would I call the next or previous record? I have looked for tutorials and stuff but didn't find any. I anyone has a tutorial please share with me. Thanks for any help. I wish I had some code to provide but I really don't know where to start.
I use an int to pull the record from the dbase.
From my ContactView class
static long record = 1;
public void getData() {
DBase db = new DBase(this);
db.open();
lastRecord = db.lRec();
firstRecord = db.fRec();
rRec = db.getRec(record);
db.close();
}
then my query is from my Dbase class
public String[] getRec(long record) {
record = ContactView.record;
String[] columns = new String[] { KEY_ROWID, KEY_ONE, KEY_TWO,
KEY_THREE, KEY_FOUR, KEY_FIVE, KEY_SIX };
Cursor c = ourDatabase.query(DATABASE_TABLE, columns, KEY_ROWID + "="
+ record, null, null, null, null);
if (c != null && c.moveToFirst()) {
String rRec = c.getString(0);
String rOne = c.getString(1);
String rTwo = c.getString(2);
String rThree = c.getString(3);
String rFour = c.getString(4);
String rFive = c.getString(5);
String rSix = c.getString(6);
String[] rData = { rRec, rOne, rTwo, rThree, rFour,
rFive, rSix };
return rData;
}
return null;
}
and the next few are from my ContactView class
my buttons
#Override
public void onClick(View arg0) {
switch (arg0.getId()) {
case R.id.bSQLvPrev:
recordMinus();
display();
break;
case R.id.bSQLvNext:
recordPlus();
display();
break;
}
}
and the methods they call
public void display() {
etSQLvRec.setText(rRec[0]);
etSQLvOne.setText(rRec[1]);
etSQLvTwo.setText(rRec[2]);
etSQLvThree.setText(rRec[3]);
etSQLvFour.setText(rRec[4]);
etSQLvFive.setText(rRec[5]);
etSQLvSix.setText(rRec[6]);
}
public void recordPlus() {
record++;
}
public void recordMinus() {
record--;
}
That will get the record from the database based on the "record" variable, and the buttons increment it, or decrement it, it also skips any "empty" records.
EDIT OK, I had changed some stuff around since I lasted used my db, so use the next recordPlus() and recordMinus() code instead
public void recordPlus() {
if (record < lastRecord) {
record++;
} else {
record = firstRecord;
}
getData();
do {
if (record < lastRecord) {
record++;
} else {
record = firstRecord;
}
getData();
} while (rRec == null);
}
public void recordMinus() {
if (record == 1) {
record = lastRecord;
} else {
record--;
}
getData();
do {
if (record == 1) {
record = lastRecord;
} else {
record--;
}
getData();
} while (rRec == null);
}
And you'll need my fRec() and lRec() which find the first and last records in the DB
public long fRec() {
Cursor c = ourDatabase.query(DATABASE_TABLE, new String[] { "min(" +
KEY_ROWID
+ ")" }, null, null, null, null, null);
c.moveToFirst();
long rowID = c.getInt(0);
return rowID;
}
}
public long lRec() {
long lastRec = 0;
String query = "SELECT ROWID from Table order by ROWID DESC limit 1";
Cursor c = ourDatabase.rawQuery(query, null);
if (c != null && c.moveToFirst()) {
lastRec = c.getLong(0);
}
return lastRec;
}