I've been having a weird issue lately regarding my database-driven android app. I use the code UPDATE before with no problem but now it won't allow me to update changes to my records.
I did try to log if it's saving the changes I've made but it doesn't.
Here's the code I'm using:
private void initControls() {
userInput = (EditText) findViewById (R.id.editTextDialogUserInput);
save = (Button) findViewById (R.id.btSave);
cancel = (Button) findViewById (R.id.btCancel);
save.setOnClickListener(this);
cancel.setOnClickListener(this);
Bundle extras = getIntent().getExtras();
if (extras != null) {
stID = extras.getString("dog_id");
dog_name = extras.getString("dog_name");
cursor = dbHelper.fetchbBreedByName(dog_name);
strDesc = cursor.getString(cursor.getColumnIndexOrThrow("description"));
Log.d("Animal ID", "Animal ID is " + stID + " and breed is " + dog_name);
userInput.setText(strDesc);
}
}
private void checkDatabaseConnection() {
// TODO Auto-generated method stub
dbHelper = new DBHelper(this);
try {
dbHelper.createDataBase();
} catch (IOException ioe) {
throw new Error("Unable to create database");
}
try {
dbHelper.openDataBase();
} catch (SQLException sqle) {
throw sqle;
}
}
#Override
public void onClick(View v) {
switch(v.getId()){
case R.id.btSave:
if(userInput.equals("")){
Toast.makeText(this, "No input", Toast.LENGTH_SHORT).show();
}
else {
id = Long.valueOf(stID);
dbHelper.updateDescription( id, userInput.getText().toString() );
Toast.makeText(this, "Description has been updated successfully!",
Toast.LENGTH_SHORT).show();
strDesc = cursor.getString(cursor.getColumnIndexOrThrow("description"));
Log.d("Updated", dog_name + " " + strDesc);
Intent i = new Intent(this, DogClass.class);
startActivity(i);
finish();
}
break;
case R.id.btCancel:
userInput.setText("");
break;
}
}
#Override
protected void onDestroy() {
dbHelper.close(); // close DB
cursor.close(); // close cursor
super.onDestroy();
}
Whole code can be viewed here
I really don't know what's wrong, anybody here has experienced this before? Might as well help me figure out what I'm missing in my code. Help is pretty much appreciated. Thanks.
Try to use update method like this..
SQLiteDatabase database = dbHelper.getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put(IConstants.FOLDER_LOCKED, isSelected);
database.update(FOLDER_TABLE, cv, IConstants.FOLDER_NAME + "= ?",
new String[] { foldername });
Related
I am trying to delete files from a list view, I am able to delete the original file but not to delete the name from the list, I think its because I need to delete it from the database, problem is I don't know how, could somebody help?
// the adapter
listAdapter = new ArrayAdapter<String>(RecordsActivity.this, R.layout.support_simple_spinner_dropdown_item, MainActivity.listRecord);
recordList.setAdapter(listAdapter);
//deleting the file (which goes well, the name is not deleted from the database I guess)
delete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
try {
datadelete(filePath);
listAdapter.remove(recordToPlay);
listAdapter.notifyDataSetChanged();
delete.setVisibility(View.INVISIBLE);
share.setVisibility(View.INVISIBLE);
Toast.makeText(getApplicationContext(), "File deleted successfully", Toast.LENGTH_SHORT).show();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
});
// The dataDelete method
public void dataDelete(String inputPath) throws FileNotFoundException {
try {
// delete the original file
new File(inputPath).delete();
} catch (Exception e) {
Log.e("tag", e.getMessage());
}
}
//Main Activity
File directory = new File(Environment.getExternalStorageDirectory() + File.separator + "/Recordings");
directory.mkdirs();
//outPutFile = Environment.getExternalStorageDirectory().toString() + "/recording.3gp";
String dateTime = new SimpleDateFormat("dd.MM.yyyy hh-mm-ss aa", Locale.getDefault()).format(new Date());
//Date date = new Date();
//String dateTime = DateFormat.getDateTimeInstance().format(date);
outPutFile = Environment.getExternalStorageDirectory().getAbsolutePath() + "/Recordings/"+dateTime +".m4a";
final String DIR_DATABASE = Environment.getExternalStorageDirectory().getAbsolutePath() + "/Recordings";
String sqliteQuery = "CREATE TABLE IF NOT EXISTS Recordings (ID INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL UNIQUE , fileName VARCHAR)";
database = SQLiteDatabase.openOrCreateDatabase(DIR_DATABASE + "db.sqlite", null);
database.execSQL(sqliteQuery);
getNames();
// The getNames method for retrieving the names of the files
public static void getNames(){
Cursor cursor = database.rawQuery("SELECT fileName FROM Recordings", null);
ArrayList<String> fileNames = new ArrayList<>();
while (cursor.moveToNext()) {
String fileName = cursor.getString(0);
fileNames.add(fileName);
}
cursor.close();
database.close();
listRecord.addAll(fileNames);
}
// And this is where I save the files
stop.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
mediaRecorder.stop();
mediaRecorder.release();
mediaRecorder = null;
stop.setEnabled(false);
pauseBtn.setEnabled(false);
SQLiteDatabase database = SQLiteDatabase.openDatabase(DIR_DATABASE + "db.sqlite", null, 0);
values = new ContentValues();
values.put("fileName", outPutFile.substring(31));
database.insert("Recordings", "", values);
Toast.makeText(getApplicationContext(), "Audio recorded", Toast.LENGTH_LONG).show();
Activity mActivity = MainActivity.this;
restartActivity(mActivity);
}
});
You should add a delete query to delete data from the database. Change your code in to
delete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
try {
datadelete(filePath);
database = this.getWritableDatabase();
database.execSQL("DELETE FROM Recordings WHERE fileName = '"+your file name Here+"'");
database.close();
listAdapter.remove(recordToPlay);
listAdapter.notifyDataSetChanged();
delete.setVisibility(View.INVISIBLE);
share.setVisibility(View.INVISIBLE);
Toast.makeText(getApplicationContext(), "File deleted successfully", Toast.LENGTH_SHORT).show();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
});
You should write the filename which you want to delete in the sqlite query. Hope this will work.
I need to enter username & password in edittext & store them into a database on clicking a button. They shoud be stored only if the any other record doesn't have same username. This one causes app to crash
public void updateDB(){
username = editTextUser.getText().toString();
password = editTextPassword.getText().toString();
cursor = db.rawQuery("select * from " +UserDatabase.TABLE1+" where"+UserDatabase.USERNAME+" ='" +username+ "'",null);
if (cursor.getCount()==0) {
values.put(UserDatabase.USERNAME,username);
values.put(UserDatabase.PASSWORD,password);
try {
db.insert(UserDatabase.TABLE1, null, values);
Toast.makeText(this,"Registered", Toast.LENGTH_SHORT).show();
Log.d("SignUpActivity", username + " " + password);
} catch (SQLiteException e) {
e.printStackTrace();
}
} else {
Toast.makeText(this,"Username NA", Toast.LENGTH_SHORT).show();
}
}
you can use insertOrThrow() method instead,just put an UNIQUE keyword before username in table and introduce an new
catch with(SQLException e){}
in this you can toast you messsage
Use this Method for Checking User Already Exist's or Not.
// For UserName[Person] Already Exist
public String ExistsValidation(String PersonName) {
String PName = "";
SQLiteDatabase db = this.getReadableDatabase();
try {
Cursor cursor = db.query(TABLE_NAME, null, PERSON_NAME + "=?", new String[]{String.valueOf(PersonName).trim()}, null, null, null);
if (cursor == null) {
return PName;
} else {
cursor.moveToFirst();
PName = cursor.getString(cursor.getColumnIndex("PersonName"));
}
cursor.close();
} catch (Exception ex) {
ex.printStackTrace();
}
db.close();
return PName;
}
Use above Method Like :
String PersonName = etPersonName.getText().toString().trim();
String storedPersonName = db.ExistsValidation(PersonName);
// if PersonName Exists
if (PersonName.equals(storedPersonName)) {
ShowAlertDialog("Error..!", "PersonName Already Exists,Enter Another Name");
return false;
}
By using assets folder, we are reading data i.e,address details based on search keyword:
Here is my code
private SQLiteDatabase db;
private Cursor c;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
et_search = (EditText) findViewById(R.id.et_search);
img = (ImageView) findViewById(R.id.img_search);
list = (ListView) findViewById(R.id.list_search);
db = openOrCreateDatabase("sample", Context.MODE_PRIVATE, null);
img.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
search_keyword = et_search.getText().toString();
arr_data = new ArrayList<ListItems>();
if (isValid()) {
SELECT_SQL = "SELECT ROWID AS _id,* FROM Addresses where Type LIKE '%" + search_keyword + "%'";
Log.d("daatt",SELECT_SQL);
try {
c = db.rawQuery(SELECT_SQL, null);
c.moveToFirst();
showRecords();
} catch (SQLiteException e) {
Toast.makeText(getApplicationContext(), "No Data", Toast.LENGTH_LONG).show();
}
}
}
});
}
private void showRecords() {
String ugName = c.getString(c.getColumnIndex("Name"));
String ugaddress = c.getString(c.getColumnIndex("Address"));
String ugtype = c.getString(c.getColumnIndex("Type"));
ListItems items = new ListItems();
// Finish reading one raw, now we have to pass them to the POJO
items.setName(ugName);
items.setAddress(ugaddress);
items.setType(ugtype);
// Lets pass that POJO to our ArrayList which contains undergraduates as type
arr_data.add(items);
}
ListDataAdapter adapter = new ListDataAdapter(arr_data);
list.setAdapter(adapter);
if (c != null && !c.isClosed()) {
int count = c.getCount();
c.close();
}
Log.d("ListData", "" + arr_data);
}
private boolean isValid() {
if (search_keyword.length() == 0) {
Toast.makeText(getApplicationContext(), "please enter valid key word", Toast.LENGTH_LONG).show();
return false;
}
return true;
}
For 1st build we got successful data loaded using list adapter
But after clean project, & Rebuild project showing a no such table expection
Please guide us wr we r going wrong
Advance Thanks
As far as I can see from your print, the table you're referring to is called ListOfAddress, ain't it? your SQL is:
SELECT_SQL = "SELECT ROWID AS _id,* FROM Addresses where Type LIKE '%" + search_keyword + "%'";
I might be wrong, but I would double check the query.
I am creating a database within my android application that allows users to enter assignment information. At the moment the information is stored but not listed as I would like. I am looking to add function to the View Assignments button so that it returns to the AssignmentsManager page and lists the entered assignments.
I believe I will have to use something like;
listView=(ListView)findViewById(R.id.listView1); //initialise the listview
listAdapter= new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,0); //initialise an ArrayAdapter
listView.setAdapter(listAdapter); //set the adapter to the listview
And to add assignments to list;
listAdapter.add(c.getString(0)+c.getString(1)+c.getString(2)+c.getString(3)+c.getString(4));
I am unsure how to implement this though. Below is my class to add the assignments;
public class addassignment extends Activity {
DBAdapter db = new DBAdapter(this);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.add);
}
public void addAssignment(View v) {
Log.d("test", "adding");
// get data from form
EditText nameTxt = (EditText) findViewById(R.id.editTitle);
EditText dateTxt = (EditText) findViewById(R.id.editDuedate);
EditText courseTxt = (EditText) findViewById(R.id.editCourse);
EditText notesTxt = (EditText) findViewById(R.id.editNotes);
db.open();
long id = db.insertRecord(nameTxt.getText().toString(), dateTxt
.getText().toString(), courseTxt.getText().toString(), notesTxt
.getText().toString());
db.close();
nameTxt.setText("");
dateTxt.setText("");
courseTxt.setText("");
notesTxt.setText("");
Toast.makeText(addassignment.this, "Assignment Added",
Toast.LENGTH_LONG).show();
}
public void viewAssignments(View v) {
Intent i = new Intent(this, AssignmentManager.class);
startActivity(i);
}
}
Here is the Assignments Class where the list should be displayed;
public class AssignmentManager extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.assignmentmanager);
Button addBtn = (Button) findViewById(R.id.add);
addBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(AssignmentManager.this,
addassignment.class);
startActivity(i);
}
});
try {
String destPath = "/data/data/" + getPackageName()
+ "/databases/AssignmentDB";
File f = new File(destPath);
if (!f.exists()) {
CopyDB(getBaseContext().getAssets().open("mydb"),
new FileOutputStream(destPath));
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
DBAdapter db = new DBAdapter(this);
// ---add an assignment---
db.open();
long id = db.insertRecord("Android App", "14/02/2015", "Networks",
"First Android Project");
id = db.insertRecord("Java Development", "5/02/2015", "Java",
"Complete Assignment");
db.close();
// ---get all Records---
db.open();
Cursor c = db.getAllRecords();
if (c.moveToFirst()) {
do {
DisplayRecord(c);
} while (c.moveToNext());
}
db.close();
/*
* //---get a Record--- db.open(); Cursor c = db.getRecord(2); if
* (c.moveToFirst()) DisplayRecord(c); else Toast.makeText(this,
* "No Assignments found", Toast.LENGTH_LONG).show(); db.close();
*/
// ---update Record---
/*
* db.open(); if (db.updateRecord(1, "Android App", "29/02/2015",
* "Networks", "First Android Project")) Toast.makeText(this,
* "Update successful.", Toast.LENGTH_LONG).show(); else
* Toast.makeText(this, "Update failed.", Toast.LENGTH_LONG).show();
* db.close();
*/
/*
* //---delete a Record--- db.open(); if (db.deleteRecord(1))
* Toast.makeText(this, "Delete successful.", Toast.LENGTH_LONG).show();
* else Toast.makeText(this, "Delete failed.",
* Toast.LENGTH_LONG).show(); db.close();
*/
}
public void CopyDB(InputStream inputStream, OutputStream outputStream)
throws IOException {
// ---copy 1K bytes at a time---
byte[] buffer = new byte[1024];
int length;
while ((length = inputStream.read(buffer)) > 0) {
outputStream.write(buffer, 0, length);
}
inputStream.close();
outputStream.close();
}
public void DisplayRecord(Cursor c) {
Toast.makeText(
this,
"id: " + c.getString(0) + "\n" + "Title: " + c.getString(1)
+ "\n" + "Due Date: " + c.getString(2),
Toast.LENGTH_SHORT).show();
}
public void addAssignment(View view) {
Intent i = new Intent("addassignment");
startActivity(i);
Log.d("TAG", "Clicked");
}
}
Can anyone show me where I should implement the lists to add the functionality?
You're on the right track. I'd simplify the process if I were you, instead of initially adding assignments individually, add an ArrayList of assignments when you're creating your adapter:
listAdapter= new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, assignmentArrayList);
// now set the adapter to the ListView
listView.setAdapter(listAdapter); //set the adapter to the listview
Once your adapter is set and you make any changes to it (add, remove, etc) make sure you call .notifyDataSetChanged() so it knows to refresh the list.
listAdapter.notifyDataSetChanged(); // notify the list adapter
here i tried to take name and password from database if the user have already an account, or sign up him by enter his data.
This is the first activity which has force close by clicking on first button to log into the data base
public class SelesMeter2Activity extends Activity implements OnClickListener {
EditText ed1;
EditText ed2;
Button b1;
Button b2;
SQLiteDatabase sql;
Cursor c;
Intent in;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ed1 = (EditText) findViewById(R.id.ed1);
ed2 = (EditText) findViewById(R.id.ed2);
b1 = (Button) findViewById(R.id.bt1);
b2 = (Button) findViewById(R.id.bt2);
b1.setOnClickListener(this);
b2.setOnClickListener(this);
sql = openOrCreateDatabase("db", 0, null);
sql.execSQL("CREATE TABLE if not exists "
+ "Employee2 (password integer NOT NULL PRIMARY KEY,name text NOT NULL)");
}
#Override
public void onClick(View arg0) {
// log in
if (arg0.getId() == R.id.bt1) {
int p = 0;
String name = ed1.getText().toString();
String sp = ed2.getText().toString();
try {
// Attempt to parse the number as an integer
p = Integer.parseInt(sp);
} catch (NumberFormatException nfe) {
// parseInt failed, so tell the user it's not a number
Toast.makeText(this,
"Sorry, " + sp + " is not a number. Please try again.",
Toast.LENGTH_LONG).show();
}
if (c.getCount() != 0) {
c = sql.rawQuery("select * from Employee", null);
while (c.moveToNext()) {
if (name.equals("c.getString(1)") && p == c.getInt(0)) {
in = new Intent(this, secondview.class);
startActivity(in);
break;
}
}
}
else {
Toast.makeText(this,
"please sign up first or enter " + "correct data", 2000)
.show();
}
} else if (arg0.getId() == R.id.bt2) {
// sign up
Intent in2 = new Intent(this, signup.class);
startActivity(in2);
}
}
}
the second class that enter the new user which is not working as expected,
the toast does not work :
public class signup extends Activity implements OnClickListener {
EditText e1;
EditText e2;
SQLiteDatabase sql;
Button b;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.singupx);
Intent in = getIntent();
e1 = (EditText) findViewById(R.id.ed1s);
e2 = (EditText) findViewById(R.id.ed2s);
b = (Button) findViewById(R.id.bt1s);
b.setOnClickListener(this);
}
#Override
public void onClick(View v) {
String n = e1.getText().toString();
String sp = e2.getText().toString();
try {
// Attempt to parse the number as an integer
int p = Integer.parseInt(sp);
// This insertion will *only* execute if the parseInt was successful
// sql.execSQL("insert into Employee2(password,name)values('"+n+"',"+p+")");
ContentValues values = new ContentValues();
values.put("password", p);
values.put("name", n);
sql.insert("Employee2", null, values);
Toast.makeText(this, "Data inserted", Toast.LENGTH_LONG).show();
Intent in2 = new Intent(this, secondview.class);
startActivity(in2);
} catch (NumberFormatException nfe) {
// parseInt failed, so tell the user it's not a number
Toast.makeText(this,
"Sorry, " + sp + " is not a number. Please try again.",
Toast.LENGTH_LONG).show();
}
}
}
In the SelesMeter2Activity you'll have a NullPointerException at the line:
if (c.getCount() != 0) {
as you don't initialize the Cursor before that line. Move the query before the above line:
c = sql.rawQuery("select * from Employee", null);
if (c.getCount() != 0) {
// ...
You should post the exception you get from the logcat.
Also regarding your signup activity please don't instantiate the first activity to access fields from it. Open the database again in the second activity and insert the values.
This is why you are getting error
// you are calling the `c.getCount();` before you are assigning
// It will throw null pointer exception
if (c.getCount() != 0) {
c = sql.rawQuery("select * from Employee", null);
while (c.moveToNext()) {
if (name.equals(c.getString(1)) && p == c.getInt(0)) {
in = new Intent(this, secondview.class);
startActivity(in);
break;
}
}
}
Change the logic like
c = sql.rawQuery("select * from Employee", null);
c.moveToFirst();
if(!c.isAfterLast()) {
do {
if (name.equals(c.getString(1)) && p == c.getInt(0)) {
in = new Intent(this, secondview.class);
startActivity(in);
break;
}
} while (c.moveToNext());
}
and name.equals("c.getString(1)") should be name.equals(c.getString(1))
EDIT
Example of insert method
ContentValues values = new ContentValues();
values.put("password", n);
values.put("name", p);
database.insert("Employee2", null, values);