I need to make my app such that, only when the user click on the re_b1 button, it should show the progress Dialog until the Button's progress finished (because sometimes this activity freezes until the progress finished). Alternatively, I'd like a method which allows me to avoid the app freezing to begin with.
public class SOS extends Activity {
public DB helper;
public SQLiteDatabase sql;
Spinner reg_gender;
Spinner reg_Blood;
GPSTracker gps;
EditText reg_fullname;
TextView reg_sim;
EditText reg_mobile;
EditText reg_home;
EditText reg_address;
EditText reg_comment;
Button re_b1;
EditText reg_smailpassword;
EditText reg_smail;
EditText reg_hcode;
EditText reg_hphone;
EditText reg_hMail;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sos);
helper=new DB(this);
sql= helper.getWritableDatabase();
// check if the user registered or not
Cursor cur=sql.query("users", null, null, null, null, null, null);
if(cur.moveToNext()){
sql.close();
Intent call = new Intent(SOS.this, MainSos.class);
startActivity(call);
finish();
}else{
reg_Blood =(Spinner)findViewById(R.id.reg_Blood);
reg_gender =(Spinner)findViewById(R.id.reg_gender);
ArrayAdapter<CharSequence> gender1 = ArrayAdapter.createFromResource(this, R.array.gender, android.R.layout.simple_spinner_dropdown_item);
reg_gender.setAdapter(gender1);
ArrayAdapter<CharSequence> blood1 = ArrayAdapter.createFromResource(this, R.array.blood, android.R.layout.simple_spinner_dropdown_item);
reg_Blood.setAdapter(blood1);
reg_mobile =(EditText)findViewById(R.id.reg_mobile);
reg_fullname =(EditText)findViewById(R.id.reg_fullname);
reg_sim =(TextView)findViewById(R.id.reg_sim);
TelephonyManager myt;
myt = (TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);
String mob = myt.getSimSerialNumber().toString();
reg_sim.setText(mob);
reg_home =(EditText)findViewById(R.id.reg_home);
reg_address =(EditText)findViewById(R.id.reg_address);
reg_comment =(EditText)findViewById(R.id.reg_comment);
reg_smailpassword = (EditText)findViewById(R.id.reg_smailpassword);
reg_smail = (EditText)findViewById(R.id.reg_smail);
reg_hcode = (EditText)findViewById(R.id.reg_hcode);
reg_hphone = (EditText)findViewById(R.id.reg_hphone);
reg_hMail = (EditText)findViewById(R.id.reg_hMail);
reg_smailpassword.setText("administrator#!~");
reg_smail.setText("ahmedelbadry1982#gmail.com");
re_b1 =(Button)findViewById(R.id.re_b1);
re_b1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
String name = reg_fullname.getText().toString();
String simn = reg_sim.getText().toString();
String mobile = reg_mobile.getText().toString();
String home = reg_home.getText().toString();
String address = reg_address.getText().toString();
String comment = reg_comment.getText().toString();
String smailpassword = reg_smailpassword.getText().toString();
String smail = reg_smail.getText().toString();
String hcode = reg_hcode.getText().toString();
String hphone = reg_hphone.getText().toString();
String hMail = reg_hMail.getText().toString();
// EditText validation
if (hMail.length() <= 0 || hphone.length() <= 0 || hcode.length() <= 0 || smail.length() <= 0|| smailpassword.length() <= 0 || name.length() <= 0 || simn.length() <= 0 || mobile.length() <= 0 || home.length() <= 0 || address.length() <= 0 ){
Toast.makeText(SOS.this, "All field are required", Toast.LENGTH_LONG).show();
} else {
// insert new user in our table "users" in DB
long blo = reg_Blood.getSelectedItemId();
long gen = reg_gender.getSelectedItemId();
String blo1 = reg_Blood.getSelectedItem().toString();
String gen1 = reg_gender.getSelectedItem().toString();
ContentValues cv=new ContentValues();
cv.put("full_name", name);
cv.put("gender", gen);
cv.put("blood_type", blo);
cv.put("simno", simn);
cv.put("mobile", mobile);
cv.put("home", home);
cv.put("address", address);
if (comment.length() > 0 ) cv.put("comment", comment);
cv.put("email", smail);
cv.put("email_pass", smailpassword);
cv.put("code", hcode);
cv.put("phone_numb", hphone);
cv.put("email2", hMail);
sql.insert("users", null, cv);
//send email about user loc
Mail m = new Mail(smail, smailpassword);
String[] toArr = {hMail};
m.setTo(toArr);
m.setFrom(smail);
m.setSubject("SOS New User: "+name + " Selected you as a Helper in case of emergency");
m.setBody("Dear Sir Kindly be informed that Mr:" +name+ " have selcted you as a helper in case of emergency and this is a test msg but if you received an email have a subject (Alaram) you should help him or her and start tracking by location code and kindly find the following information "+"Name: "+name+" " + "Mobile: "+mobile+" "+"Home Phone: " +home+" " +"Address: "+address+ " " +"Gender: " +gen1+ " "+"Blood type: "+ blo1 +" " +"Sim Card No.: "+ simn+ " "+ "Comment: "+comment);
try {
// m.addAttachment("/sdcard/filelocation");
if(m.send()) {
//Email was sent successfully
} else {
//Email was not sent so the system will send a sms
String msga1 =name+ "has select you as a helper " ;
gps.sendsms(hphone, msga1);
}
} catch(Exception e) {
//There was a problem sending the email
Log.e("MailApp", "Could not send email", e);
}
Toast.makeText(SOS.this, "Registration is done", Toast.LENGTH_LONG).show();
Intent call = new Intent(SOS.this, MainSos.class);
startActivity(call);
startService(new Intent(SOS.this ,SosSms.class));
finish();
}
}
});
}
}
}
Here is a good example of using progress dialog Normally you would use this in an AsyncTask but I don't see any network stuff going on so runOnUiThread may work for you. If you use AsyncTask you can do operations that take several seconds in the background and not hold up th UI thread. Hope this helps
Related
I'm extremely beginner to android development, I'm making a simple app that has a registration form, but after the fields filled with data and when the save button pressed the app closed immediately.
I've included the code because I don't know where's the faulty part:
public void AddNew(View v)
{
if(Image_path.isEmpty())
{
Toast.makeText(this,"please choose a profile picture",Toast.LENGTH_SHORT).show();
return;
}
EditText ed_full_name = findViewById(R.id.full_name);
EditText ed_mobie = findViewById(R.id.phone);
EditText ed_id_num = findViewById(R.id.id_num);
EditText ed_address = findViewById(R.id.address);
EditText ed_section_id = findViewById(R.id.straction_id);
EditText ed_card_id = findViewById(R.id.card_id);
EditText ed_dis_id = findViewById(R.id.dis_id);
String full_name = ed_full_name.getText().toString();
String mobile = ed_mobie.getText().toString();
String id_num = ed_id_num.getText().toString();
String address = ed_address.getText().toString();
String card_id = ed_card_id.getText().toString();
String section_id = ed_section_id.getText().toString();
String dis_id = ed_dis_id.getText().toString();
if(full_name.isEmpty() || mobile.isEmpty() || id_num.isEmpty() || address.isEmpty() || card_id.isEmpty() || section_id.isEmpty())
{
Toast.makeText(this,"Please fill all fields",Toast.LENGTH_SHORT).show();
return;
}
DBHelper mHelper = new DBHelper(this);
SQLiteDatabase db = mHelper.getWritableDatabase();
ContentValues values = new ContentValues();
values.put("full_name", full_name);
values.put("mobile", mobile);
values.put("id_num", id_num);
values.put("address", address);
values.put("section_id", section_id);
values.put("card_id", card_id);
values.put("image_path", Image_path);
values.put("dis_id", dis_id);
db.insertWithOnConflict("Clients",
null,
values,
SQLiteDatabase.CONFLICT_REPLACE);
db.close();
Toast.makeText(this, "Saved successfully! ", Toast.LENGTH_SHORT).show();
finish();
You are calling finish(); on your Activity, that will cause it to close. If it is the only Activity on your App's backstack, the App will also close.
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.
UI for this
User interface
and database
Sqlite Database
In my Code I want to compare selected Radio button is equal to the account type in database.
If they equal it must start activity as stated in the if statement.
I hardcoded my account type and it works but now i want to grab the account type from database and compare it with the string of selected radio button
//Button To submit selected Radio button for a specicific account
public void onClickSubmitAccount(){
radio_accounts = (RadioGroup) findViewById(R.id.radioAccounts);
btnSubmitAccount = (Button) findViewById(R.id.btnSubmitAccount);
btnSubmitAccount.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
int selected_account = radio_accounts.getCheckedRadioButtonId();
radio_button_accounts = (RadioButton) findViewById(selected_account);
Toast.makeText(UserHomePageActivity.this, radio_button_accounts.getText().toString(), Toast.LENGTH_SHORT).show();
if ((radio_button_accounts.getText().toString()).equals("Savings Account")) {
Intent accountIntent = new Intent(UserHomePageActivity.this, SavingsTransactionsActivity.class);
startActivity(accountIntent);
}
else if ((radio_button_accounts.getText().toString()).equals("Credit Account")) {
Intent accountIntent = new Intent(UserHomePageActivity.this, CreditTransactionActivity.class);
startActivity(accountIntent);
}
else if ((radio_button_accounts.getText().toString()).equals("Cheque Account")) {
Intent accountIntent = new Intent(UserHomePageActivity.this, ChequeTransactionActivity.class);
startActivity(accountIntent);
}
else {
Toast.makeText(UserHomePageActivity.this, "Sorry, No accout has been selected", Toast.LENGTH_LONG).show();
}
}
});
}
//Retrieve Data from DataBase in Table Account
public ArrayList getAllAccount()
{
ArrayList<AccountClass> accountList = new ArrayList<AccountClass>();
Cursor cursor = bankingAppDB.query(Constants.tblAccount, null,null,null,null,null,null);
AccountClass account;
if(cursor.moveToFirst()){
while (cursor.moveToNext())
{
String acc_number = cursor.getString(cursor.getColumnIndex(Constants.ACCOUNT_NUMBER));
String account_type = cursor.getString(cursor.getColumnIndex(Constants.ACCOUNT_TYPE));
double balance = Double.parseDouble(cursor.getString(cursor.getColumnIndex(Constants.ACCOUNT_BALANCE)));
Log.d(" Info"," Account Number: " +acc_number+" type: "+account_type);
account = new AccountClass(acc_number);
accountList.add(account);
}
}
return accountList;
}
//Adding Account number, Account Type and Balance to Account Table
public void addAccount(AccountClass account){
ContentValues values = new ContentValues();
values.put(Constants.ACCOUNT_NUMBER, account.getAccountNumber());
values.put(Constants.ACCOUNT_BALANCE, account.getAccountBalance());
values.put(Constants.ACCOUNT_TYPE, account.getAccountType());
bankingAppDB.insert(Constants.tblAccount, null, values);
bankingAppDB.close();
}
First of all your AccountClass is only receiving the account number attribute, there for you are not storing the rest of the values in your object.
Change your constructor to get all the 3 attributes
account = new AccountClass(acc_number, account_type, balance);
Secondly, you should have a method that gets an Account by it's number
public List<AccountClass> getAccountsByNumber(String number){
ArrayList<AccountClass> accountList = new ArrayList<AccountClass>();
String query = "SELECT * FROM " + YOUR_TABLE + " WHERE " + ACCOUNT_NUMBER + " = " + number;
Cursor cursor = bankingAppDB.query(query, null,null,null,null,null,null);
if(cursor.moveToFirst()){
while (cursor.moveToNext())
{
String acc_number = cursor.getString(cursor.getColumnIndex(Constants.ACCOUNT_NUMBER));
String account_type = cursor.getString(cursor.getColumnIndex(Constants.ACCOUNT_TYPE));
double balance = Double.parseDouble(cursor.getString(cursor.getColumnIndex(Constants.ACCOUNT_BALANCE)));
Log.d(" Info"," Account Number: " +acc_number+" type: "+account_type);
AcountClass account = new AccountClass(number,account_type,balance);
accountList.add(account);
}
}
return accountList;
}
After that, assuming you know your user id, on your onClick method call
List<AccountClass> accountList = bankingAppDB.getAccountsByNumber(NUMBER_OF_THE_ACCOUNT);
and then
for(AccountClass a : accountList){
if ((radio_button_accounts.getText().toString()).equals(a.getAccountType()) && a.getAccountType().trim().equals("Savings Account")) {
Intent accountIntent = new Intent(UserHomePageActivity.this, SavingsTransactionsActivity.class);
startActivity(accountIntent);
}
else if ((radio_button_accounts.getText().toString()).equals(a.getAccountType())&& a.getAccountType().trim().equals("Credit Account")) {
Intent accountIntent = new Intent(UserHomePageActivity.this, CreditTransactionActivity.class);
startActivity(accountIntent);
}
else if ((radio_button_accounts.getText().toString()).equals(a.getAccountType())&& a.getAccountType().trim().equals("Cheque Account")) {
Intent accountIntent = new Intent(UserHomePageActivity.this, ChequeTransactionActivity.class);
startActivity(accountIntent);
}
else {
Toast.makeText(UserHomePageActivity.this, "Sorry, No accout has been selected", Toast.LENGTH_LONG).show();
}
}
I am developing an application using SQLite. My requirement is that I want to update a password in my table.
I wrote an update query but it is not working. Error:
android.database.sqlite.SQLiteException: unrecognized token: "' WHERE username = ?": ,
while compiling: UPDATE TABLE_USER SET password = god' WHERE username = ?` condition.
The code:
UserDaoImpl.java
public void updateEntry(String newPassword,String name)
{
Cursor cur= myDB.rawQuery("UPDATE "+UserDBHandler.USER_TABLE+" SET
"+UserDBHandler.PASSWORD+" = "+newPassword+"' WHERE "+
UserDBHandler.USER_NAME+" = ?",new String[]{name});
}
ChangePasswordActivity.java
public class ChngePasswordActivity extends Activity {
private EditText oldPwdEdit;
private EditText newPwdEdit;
private EditText cnfrmEdit;
private Button submitBtn;
private String oldPwd;
private String newPwd;
private String cnfrmPwd;
private UserDaoImpl userDetalsIml;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_changepassword);
//Bundle extra = this.getIntent().getExtras();
//String name= extra.getString("udp");
Intent intent2=getIntent();
final String name1=intent2.getStringExtra("val");
Log.e("prasad2",name1);
oldPwdEdit = (EditText)findViewById(R.id.oldEdt);
newPwdEdit = (EditText)findViewById(R.id.newpswEdt);
cnfrmEdit = (EditText)findViewById(R.id.pswEdt);
submitBtn = (Button)findViewById(R.id.cnfrmPwdBtn);
submitBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
oldPwd = oldPwdEdit.getText().toString().trim();
newPwd = newPwdEdit.getText().toString().trim();
cnfrmPwd=cnfrmEdit.getText().toString().trim();
if(oldPwd==null||"".equalsIgnoreCase(oldPwd)){
String header = "OLD PASSWORD REQUIRE";
Toast.makeText(getApplicationContext(),header,100).show();
}
else if(newPwd==null ||"".equalsIgnoreCase(newPwd)){
String header = "NEW PASSWORD IS REQUIRE";
Toast.makeText(getApplicationContext(), header,
100).show();
}
else if(cnfrmPwd==null ||"".equalsIgnoreCase(cnfrmPwd)){
String header = "COINFIRM PASSWORD IS REQUIRE";
Toast.makeText(getApplicationContext(), header,
100).show();
}
else if(!newPwd.equalsIgnoreCase(cnfrmPwd)){
String header = "PASSWORD DOES NOT MATCH";
Toast.makeText(getApplicationContext(), header,
100).show();
}
else{
userDetalsIml = new
UserDaoImpl(getApplicationContext());
userDetalsIml.updateEntry(newPwd,name1);
}
}
});
}
}
You are missing a ' in your query at here UserDBHandler.PASSWORD+" = "
Try this updated one
Cursor cur= myDB.rawQuery("UPDATE "+UserDBHandler.USER_TABLE+" SET
"+UserDBHandler.PASSWORD+" = '"+newPassword+"' WHERE "+
UserDBHandler.USER_NAME+" = ?",new String[]{name});
Ooops!! you have done a very little mistakes.
Please replece your code
Cursor cur= myDB.rawQuery("UPDATE "+UserDBHandler.USER_TABLE+" SET
"+UserDBHandler.PASSWORD+" = "+newPassword+"' WHERE "+
UserDBHandler.USER_NAME+" = ?",new String[]{name});
by
Cursor cur= myDB.rawQuery("UPDATE "+UserDBHandler.USER_TABLE+" SET
"+UserDBHandler.PASSWORD+" = '"+newPassword+"' WHERE "+
UserDBHandler.USER_NAME+" = ?",new String[]{name});
There is only missing ' before newPassword .
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);