My question is how can i clear the editText field after i have saved what i have written to it to the database? I currently can input text using the nameEditText field but when i click the InsertButton, it does not clear the for. I just want to clear the form not the value or string in the Database...This is the insert button i want to also use as a clear method:
class InsertButtonListener implements OnClickListener, android.view.View.OnClickListener
{
public void onClick(View v)
{
if("".equals(nameEditText.getText().toString()))
{
Toast toast = Toast.makeText(Entername.this, "Sorry, you must input both the name and the address!", Toast.LENGTH_LONG);
toast.show();
}
else
{
long flag = 0;
int id = 1;
SQLiteDatabase db = dbHelper.getWritableDatabase();
Cursor cursor = db.query("user_name", new String[]{"count(*) ID"}, null, null, null, null, null);
while(cursor.moveToNext())
{
int idFromDatabase = cursor.getInt(cursor.getColumnIndex("ID"));
if(idFromDatabase != 0)
{
id = 1 + idFromDatabase;
}
}
ContentValues values = new ContentValues();
values.put("ID", id);
values.put("name", nameEditText.getText().toString().trim());
//values.put("address", addressEditText.getText().toString().trim());
flag = db.insert("user_name", null, values);
if(flag != -1)
{
Toast toast = Toast.makeText(Entername.this, "You have successful inserted this record into database! ", Toast.LENGTH_LONG);
toast.show();
db.close();
return;
}
else
{
Toast toast = Toast.makeText(Entername.this, "An error occured when insert this record into database!", Toast.LENGTH_LONG);
toast.show();
db.close();
return;
}
}
}
public void onClick(DialogInterface dialog, int which)
{
// TODO Auto-generated method stub
}
}
You need to call:
nameEditText.setText("");
addressEditText.setText("");
So, do the following change in your if condition when adding to database is successful:
if(flag != -1)
{
Toast toast = Toast.makeText(Entername.this,
"You have successful inserted this record into database! ",
Toast.LENGTH_LONG);
toast.show();
db.close();
//clearing edittexts
nameEditText.setText("");
addressEditText.setText("");
return;
}
you last insert after editText in to set null values
EditText text;
text.setText("");
Related
I'm new in this programming in Android Studio.I have a problem with this code that I write from a tutorial.
public void onClick(View v){
if (editusername.getText().toString().trim().length() == 0 || editpassword.getText().toString().trim().length() ==0) {
Toast.makeText(getApplicationContext(), "Semua Kolom harus Diisi", Toast.LENGTH_SHORT).show();}
else try{ String username = editusername.getText().toString().trim();
String password = editpassword.getText().toString().trim();
String query = "Select * From User where username = '"+username+"'";
if(DbManager.fetch().getCount()>0){
Toast.makeText(getApplicationContext(), "Already Exist!", Toast.LENGTH_SHORT).show();
}else{
DbManager.insert(username, password);
Toast.makeText(getApplicationContext(), "Added successfully!", Toast.LENGTH_SHORT).show();
}
}catch (Exception e) {
e.printStackTrace();
}
In the 'fetch' and 'insert' Method there was an error of 'cannot be referenced as static method'.
This is the code in the corresponding class DbManager
public void insert(String usn, String pwd) {
ContentValues contentValue = new ContentValues();
contentValue.put(SQLiteHelper.USERNAME, usn);
contentValue.put(SQLiteHelper.PASSWORD, pwd);
this.database.insert(SQLiteHelper.TABLE_NAME_USER, null, contentValue);
}
public Cursor fetch() {
Cursor cursor = this.database.query(SQLiteHelper.TABLE_NAME_USER, new String[]{SQLiteHelper._ID, SQLiteHelper.USERNAME, SQLiteHelper.PASSWORD}, null, null, null, null, null);
if (cursor != null) {
cursor.moveToFirst();
}
return cursor;
}
You never created an instance of the DbManager class.
Adding an DbManager manager = new DbManager(); and then using manager.fetch() and manager.insert(params...) should solve your problem.
Doing Class.Method() is only possible if Method() was declares as public static void Method(). If it wasn't, you need to first create an object, then call the method on that object like I showed you above.
I have an sqlite database that collects data from the user and can delete it as well.
Here is it being created:
db.execSQL("CREATE TABLE " + TABLE_NAME + " (ID INTEGER PRIMARY KEY AUTOINCREMENT, DATA TEXT UNIQUE) ");
Here's the code for the adding data and removing data
public boolean insertData(String data) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues cValues = new ContentValues();
cValues.put(Col_2, data);
long result = db.insert(TABLE_NAME, null, cValues);
if (result == -1)
return false;
else
return true;
}
public boolean deleteData(String data){
SQLiteDatabase db = this.getWritableDatabase();
long result = db.delete(TABLE_NAME, "DATA = ?", new String[]{data});
ContentValues cValues = new ContentValues();
if (result == 0)
return false;
else
return true;
}
Here is the java button im trying to use
public void changeData(){
favBtn.setOnClickListener(
new View.OnClickListener(){
#Override
public void onClick(View v){
boolean isInserted = myDB.insertData(textView.getText().toString());
if(isInserted == true)
Toast.makeText(randomApp.this, "Added Data", Toast.LENGTH_LONG).show();
else
Toast.makeText(randomApp.this, "Data was deleted", Toast.LENGTH_LONG).show();
myDB.deleteData(textView.getText().toString());
}
}
);
}
The issue is that when this button is clicked it adds data but then will not remove said data. It will just continue playing the "added data" toast and add said data to the database- there is a unique constraint with the data
column but I'm not really sure what I'm doing wrong or missing as I understand it should not be added twice. It should remove the data if that is already added and vice versa.
According to your code the delete data code will always execute. And the data you are inserting will immediately deleted, hence the unique constraint won't break ever. You didn't put any {} in your else case and it contains two statements; first one considered as the statement inside else and second one will be considered as a statement outside the if and else case. So for fixing this issue you need to put {} properly. (Personal opinion : Try to put {} in if and else cases even if there is only one statement)
You should change that to:
if(isInserted == true)
{
Toast.makeText(randomApp.this, "Added Data", Toast.LENGTH_LONG).show();
}
else
{
Toast.makeText(randomApp.this, "Data was deleted", Toast.LENGTH_LONG).show();
myDB.deleteData(textView.getText().toString());
}
You are calling myDB.insertData on every click first, for every insert it will return true, so isInserted will be true always, thats why do you add multiple times the same data. Try this:
private isInserted = false;
public void changeData(){
favBtn.setOnClickListener(
new View.OnClickListener(){
#Override
public void onClick(View v){
if(!isInserted){
Toast.makeText(randomApp.this, "Added Data", Toast.LENGTH_LONG).show();
myDB.insertData(textView.getText().toString());
}
else{
Toast.makeText(randomApp.this, "Data was deleted", Toast.LENGTH_LONG).show();
myDB.deleteData(textView.getText().toString());
}
isInserted = !isInserted;
}
}
);
}
I want my Onclick method that is used used to insert data into a database to first check if data exist. If there is data, a toast message appears. how can I accomplish this. My OnClick is below. I just it to verify there is a username and password. If there is, the user receives a toast.
#Override
public void onClick (View v) {
rUsername = rName.getText().toString();
rPasscode = rCode.getText().toString();
RegDetails regDetails = new RegDetails();
regDetails.setrName(bundleRegName);
regDetails.setpCode(bundleRegCode);
if(v.getId()==R.id.rtn_button){
finish();
}else if(v.getId()==R.id.reg_button){
insertCredentials(regDetails);
}
}
private void insertCredentials(RegDetails regDetails){
LoginDB androidOpenDBHelper = new LoginDB(this);
SQLiteDatabase sqliteDB = androidOpenDBHelper.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(LoginDB.COLUMN_NAME_USERNAME, rUsername);
contentValues.put(LoginDB.COLUMN_NAME_PASSWORD, rPasscode);
long affectedColumnid = sqliteDB.insert(LoginDB.TABLE_NAME_CREDENTIALS, null, contentValues);
Toast.makeText(getApplicationContext(), "Credentials Saved! Please login" + affectedColumnid, Toast.LENGTH_SHORT).show();
sqliteDB.close();
finish();
}
}
The sqliteDB.insert return long value on success and -1 on error. The long value indicates the row number for newly inserted row in db. You can check this return value and display toast accordingly.
Please look at the detailed explanation here, http://developer.android.com/reference/android/database/sqlite/SQLiteDatabase.html#insert(java.lang.String, java.lang.String, android.content.ContentValues)
In short, modify your code to be like this,
private void insertCredentials(RegDetails regDetails){
LoginDB androidOpenDBHelper = new LoginDB(this);
SQLiteDatabase sqliteDB = androidOpenDBHelper.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(LoginDB.COLUMN_NAME_USERNAME, rUsername);
contentValues.put(LoginDB.COLUMN_NAME_PASSWORD, rPasscode);
long affectedColumnid = sqliteDB.insert(LoginDB.TABLE_NAME_CREDENTIALS, null, contentValues);
if(affectedColumnid != -1){
Toast.makeText(getApplicationContext(), "Credentials Saved! Please login" + affectedColumnid, Toast.LENGTH_SHORT).show();
}else{
// Display error dialog or smthg
}
sqliteDB.close();
finish();
}
Read your database . If cursor.getCount() >0 thats mean data exists.
Cursor cursor = getDbEntries();
if( cursor.getCount() > 0 ){
// data exists
}
else{
// data doesnt exist
}
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);
this is my code
`I have created one table, but i want to create two and when i hit the "show" button, i want to be able to select contents from both tables and show them...this is my code...am having problems creating two tables and showing them:
public class Entername extends Activity {
private Button showButton;
private Button insertButton;
private TextView nameEditText;
private TextView addTextView;
private Button doneButton;
public DatabaseHelper dbHelper = new DatabaseHelper(Entername.this,"pubgolfdatabase",2);
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.entername);
addTextView = (TextView)findViewById(R.id.textView1);
doneButton= (Button)findViewById(R.id.doneButton);
insertButton = (Button)findViewById(R.id.addButton);
nameEditText = (EditText)findViewById(R.id.name);
showButton =(Button)findViewById(R.id.button1);
showButton.setOnClickListener(new showButtonListener());
insertButton.setOnClickListener(new InsertButtonListener());
doneButton.setOnClickListener(new DoneButtonListener());
/** create the database if it dosen't exist **/
SQLiteDatabase db = dbHelper.getWritableDatabase();
try
{
db.execSQL("create table user_name(ID integer, name varchar(90));");
}
catch(Exception e)
{
e.printStackTrace();
}
}
class InsertButtonListener implements OnClickListener, android.view.View.OnClickListener
{
public void onClick(View v)
{
if("".equals(nameEditText.getText().toString()))
{
Toast toast = Toast.makeText(Entername.this, "Sorry, you must input both the name and the address!", Toast.LENGTH_LONG);
toast.show();
}
else
{
long flag = 0;
int id = 1;
SQLiteDatabase db = dbHelper.getWritableDatabase();
Cursor cursor = db.query("user_name", new String[]{"count(*) ID"}, null, null, null, null, null);
while(cursor.moveToNext())
{
int idFromDatabase = cursor.getInt(cursor.getColumnIndex("ID"));
if(idFromDatabase != 0)
{
id = 1 + idFromDatabase;
}
}
ContentValues values = new ContentValues();
values.put("ID", id);
values.put("name", nameEditText.getText().toString().trim());
flag = db.insert("user_name", null, values);
if(flag != -1)
{
Toast toast = Toast.makeText(Entername.this, "You have successful inserted this record into database! ", Toast.LENGTH_LONG);
toast.show();
db.close();
//clear fields //clearing edittexts
nameEditText.setText("");
return;
}
else
{
Toast toast = Toast.makeText(Entername.this, "An error occured when insert this record into database!", Toast.LENGTH_LONG);
toast.show();
db.close();
//clear fields
//clearing edittexts
nameEditText.setText("");
return;
}
}
}
public void onClick(DialogInterface dialog, int which)
{
// TODO Auto-generated method stub
}
}
class DoneButtonListener implements OnClickListener, android.view.View.OnClickListener
{
public void onClick(View v)
{
Intent myIntent = new Intent(v.getContext(), Pickholespubs.class);
startActivityForResult(myIntent, 0);
}
public void onClick(DialogInterface dialog, int which)
{
// TODO Auto-generated method stub
}
}
class showButtonListener implements OnClickListener, android.view.View.OnClickListener
{
public void onClick(View v)
{
String display = "";
SQLiteDatabase db = dbHelper.getWritableDatabase();
/** the result will be loaded in cursor **/
Cursor cursor = db.query("user_name", new String[]{"ID","name"}, null, null, null, null, null);
/** check if the table is empty **/
if (!cursor.moveToNext())
{
addTextView.setText("No data to display, please make sure you have already inserted data!");
db.close();
return;
}
cursor.moveToPrevious();
/** if the table is not empty, read the result into a string named display **/
while(cursor.moveToNext())
{
int ID = cursor.getInt(cursor.getColumnIndex("ID"));
String name = cursor.getString(cursor.getColumnIndex("name"));
display = display + "\n"+"Player"+ID+", Name: "+name;
}
/** display the result on the phone **/
addTextView.setText(display);
db.close();
}
public void onClick(DialogInterface dialog, int which)
{
// TODO Auto-generated method stub
}
}
}`
A Simple Answer would be No you can not do it. As Create Table Syntax doesn't allow two DML operations at a same time.
But the alternet way is like as follows,
Create Table table1 ( column list ); Create Table table2 ( column list );
This could be possible. Moral is there must be a ; (semicolon) after each Create Table syntax is completed).