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();
}
}
Related
I have a database where i have Unique id, Email id and Password. Im storing using SQlite database. I've to get the cursor which stores the result of the query, i have got the cloumn index of each cloumn, appended it using StringBuffer, but i dont know how to get those values in the other class? please help.
here is my code for Adapter class:
public String getData(String email,String pwd)
{
StringBuffer buffer=new StringBuffer();
SQLiteDatabase db =sciHelper.getWritableDatabase();
Cursor cursor = db.rawQuery("SELECT _id FROM " + SciHelper.TABLE_NAME + " WHERE email=? AND password=?", new String[]{email, pwd});
while(cursor.moveToNext())
{
int index1=cursor.getColumnIndex(SciHelper.UID);
int index2=cursor.getColumnIndex(SciHelper.EMAIL);
int index3=cursor.getColumnIndex(SciHelper.PASSWORD);
String cid=cursor.getString(index1);
String mail=cursor.getString(index2);
String mailpass=cursor.getString(index3);
buffer.append(cid +" "+mail+" "+mailpass+"\n");
}
return buffer.toString();
}
code at login class:
public void checkTable(View view) {
email2 = emaillog.getText().toString();
pass2 = passlog.getText().toString();
String data = sciDataBaseAdapter.getData(email2, pass2);
String[] values=data.split("\\");
String cid=values(0);
if (TextUtils.isEmpty(email2)) {
emaillog.setError("Enter Email Id");
passlog.setError("Enter Password");
}
// if (email1 != null) {
Intent intent=new Intent(this,ResultActivity.class);
startActivity(intent);
Message.message(this, "Login succesful");
} else {
Message.message(this, "Invalid username/ or register");
}
}
}
When calling the ResultAcitvity
Intent intent=new Intent(this,ResultActivity.class);
intent.putExtra("key","value");
startActivity(intent);
and on ResultActivity, inside onCreate() method write
Intent intent=getIntent();
String value=intent.getStringExtra("key");
String[] values = value.split(" ");
String cid=values[0];
String mail=values[1];
String mailpass=values[2];
public void checkTable(View view) {
email2 = emaillog.getText().toString();
pass2 = passlog.getText().toString();
String data = sciDataBaseAdapter.getData(email2, pass2);
String[] values=data.split("\\");
String cid=values(0);
if (TextUtils.isEmpty(email2)) {
emaillog.setError("Enter Email Id");
passlog.setError("Enter Password");
}
// if (email1 != null) {
Bundle bundle=new Bundle();
b.putStringArray(some_key, values);
Intent intent=new Intent(this,ResultActivity.class);
intent.putExtra(bundle);
startActivity(intent);
Message.message(this, "Login succesful");
} else {
Message.message(this, "Invalid username/ or register");
}
}
and in your next activity get that using.
Bundle extras = getIntent().getExtras();
String[] some_variable= extras.getString("some_key");
I couldn't get corresponds data from list view's item.
here i am using sms and email templates. when i click on sms or any email listviews item then it will open in edit text form db and then could update data and then store. corresponding with email or sms .i create fields into db for email and sms template such as
id, template_name, message, template_code(0,1) i.e. specifies which on i'm using either sms or email.
here is three activity ManageEmailTemplate, ManageSmsTemplate that intents to next activity i.e. SMSTemplateEdit
ManageEmailTemplate.java
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.manage_email_template);
//-------------------------
dba = new MyDB(this);
dba.open();
mQuery = "Select " +
Constants.KEY_ID_GREET + "," +
Constants.GREETING_NAME + "," +
Constants.GREETING_MESSAGE+ "," +
Constants.KEY_ID_SETUP_GREET +
" from " + Constants.TABLE_NAME_GREETINGS +
" where " + Constants.KEY_ID_SETUP_GREET + " = " + Constants.EMAIL_CODE;
c = dba.getResults( mQuery );
startManagingCursor(c);
String[] resultColumns;
if( c != null && c.moveToFirst()){
}
int[] textviews = new int[] {android.R.id.text1};
resultColumns = new String[] { Constants.GREETING_NAME};
mAdapter = new SimpleCursorAdapter(this, android.R.layout.simple_list_item_1, c, resultColumns, textviews);
this.setListAdapter(mAdapter);
getListView().setTextFilterEnabled(true);
//dba.close();
//-------------------------
// Create Email Templates
//setup Create Email Templates Listener
Button createEmailTemplatesButton = (Button) findViewById(R.id.create_email_template_button);
createEmailTemplatesButton.setOnClickListener(new OnClickListener(){
public void onClick(View view){
showCreateEmailTemplate();
}
});
}
private void showCreateEmailTemplate(){
Intent i = new Intent(this, CreateNewTemplate.class);
i.putExtra("template_type","email");
//startActivity(i);
startActivityForResult(i, mRequestCode);
}
#Override
public void onItemClick(AdapterView<?> parent, View v,
int position, long id)
{
super.onItemClick(parent, v, position, id);
final Cursor c = (Cursor) mAdapter.getItem(position);
String name = c.getString(c.getColumnIndex( Constants.GREETING_NAME ));
final int template_id = c.getInt(c.getColumnIndex( Constants.KEY_ID_GREET ));
temp_id=String.valueOf(template_id);
goForEdit();
//confirm
Toast.makeText(this,
"Name :"+name+" id : " +template_id , Toast.LENGTH_LONG)
.show();
}
public void goForEdit(){
Intent launchSMSTempEdit = new Intent(
ManageEmailTemplate.this,
EmailSMSTempEdit.class);
launchSMSTempEdit.getExtras().get("selection"));
// startActivity(launchSMSTempEdit);
// Toast.makeText(this, temp_id, Toast.LENGTH_LONG).show();
// startActivity(launchSMSTempEdit);
SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(this);
//now get Editor
SharedPreferences.Editor editor = sharedPref.edit();
//put your value
editor.putString("Temp_id", temp_id);
editor.putString("template_type", "email");
//commits your edits
editor.commit();
startActivity(launchSMSTempEdit);
}
}
ManageSMSTemplate.java
public class ManageSMSTemplate extends
ActionBarListActivity {
private MyDB dba;
private Cursor c;
String temp_id;
private SimpleCursorAdapter mAdapter;
private int mRequestCode = 0000;
ListView lst;
private String mQuery;
/** Called when the activity is first created. */
#SuppressWarnings("deprecation")
#Override
public void onCreate(Bundle savedInstanceState)
{
lst =(ListView)findViewById(android.R.id.list);
super.onCreate(savedInstanceState);
setContentView(R.layout.manage_sms_template);
// -------------------------
dba = new MyDB(this);
dba.open();
mQuery = "Select " + Constants.KEY_ID_GREET + ","
+ Constants.GREETING_NAME + ","
+ Constants.GREETING_MESSAGE + ","
+ Constants.KEY_ID_SETUP_GREET + " from "
+ Constants.TABLE_NAME_GREETINGS
+ " where " + Constants.KEY_ID_SETUP_GREET
+ " = " + Constants.SMS_CODE;
c = dba.getResults(mQuery);
startManagingCursor(c);
String[] resultColumns;
if (c != null && c.moveToFirst()) {
}
int[] textviews = new int[] { android.R.id.text1 };
resultColumns = new String[] { Constants.GREETING_NAME };
mAdapter = new SimpleCursorAdapter(this,
android.R.layout.simple_list_item_1, c,
resultColumns, textviews);
this.setListAdapter(mAdapter);
getListView().setTextFilterEnabled(true);
// -------------------------
// Create sms Templates
// setup Create SMS Templates Listener
Button createSMSTemplatesButton = (Button) findViewById(R.id.create_sms_template_button);
createSMSTemplatesButton
.setOnClickListener(new OnClickListener() {
public void onClick(View view)
{
showCreateSMSTemplate();
}
});
}
private void showCreateSMSTemplate()
{
Intent i = new Intent(this, CreateNewTemplate.class);
i.putExtra("template_type", "sms");
startActivityForResult(i, mRequestCode);
}
#Override
protected void onActivityResult(int requestCode,
int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode,
data);
Log.v("Crash",
"Returned from template creation in SMStemplate Manager");
if (mAdapter == null)
Log.d("Crash", "SMS-Manager - mAdapter is NULL");
else
Log.d("Crash",
"SMS-Manager - mAdapter is NOT Null");
if (requestCode == mRequestCode) {
if (resultCode == RESULT_OK) {
if (mAdapter.getCursor() != null)
mAdapter.getCursor().requery();
mAdapter.notifyDataSetChanged();
}
}
}
#Override
protected void onDestroy()
{
dba.close();
super.onDestroy();
}
#Override
public void onItemClick(AdapterView<?> parent, View v,
int position, long id)
{
super.onItemClick(parent, v, position, id);
final Cursor c = (Cursor) mAdapter
.getItem(position);
String name = c.getString(c
.getColumnIndex(Constants.GREETING_NAME));
final int template_id = c.getInt(c
.getColumnIndex(Constants.KEY_ID_GREET));
temp_id=String.valueOf(template_id);
goForEdit();
// confirm
Toast.makeText(this,
"Name :"+name+" id : " +template_id , Toast.LENGTH_LONG)
.show();
}
public void goForEdit(){
Intent launchSMSTempEdit = new Intent(
ManageSMSTemplate.this,
EmailSMSTempEdit.class);
// Intent i = new Intent(ManageSMSTemplate.this, SMSTempEdit.class);
//i.putExtra("KeyId", temp_id.toString());
// startActivity(i);
// launchSMSTempEdit.putExtra("selection", temp_id.toString());
// Log.d("*** OUTBOUND INTENT: ", "" + launchSMSTempEdit.getExtras().get("selection"));
// startActivity(launchSMSTempEdit);
// Toast.makeText(this, temp_id, Toast.LENGTH_LONG).show();
// startActivity(launchSMSTempEdit);
SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(this);
//now get Editor
SharedPreferences.Editor editor = sharedPref.edit();
//put your value
editor.putString("userName", temp_id);
editor.putString("template_type", "sms");
//commits your edits
editor.commit();
startActivity(launchSMSTempEdit);
}
}
EmailSMSTempEdit.java
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.create_template);
// sms_key_id=getIntent().getStringExtra("id");
// String sms_key_id;
// if (savedInstanceState == null) {
// Bundle extras = getIntent().getExtras();
// if(extras == null) {
// sms_key_id= null;
// } else {
// sms_key_id= extras.getString("STRING_I_NEED");
// }
// } else {
// sms_key_id= (String) savedInstanceState.getSerializable("STRING_I_NEED");
// }
SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(this);
sms_key_id = sharedPref.getString("userName", "Not Available");
mTemplateType=sharedPref.getString("template_type", "Not Available");
Toast.makeText(this, mTemplateType, Toast.LENGTH_LONG).show();
dba = new MyDB(this);
dba.open() ;
//array to hold values to show in spinner
nameTypeArr = new String[]{getString(R.string.insert_name_prompt),
getString(R.string.first_name),
getString(R.string.last_name)};
//get views from xml
mNameBox = (EditText) findViewById(R.id.template_name_box);
mSubjectBox = (EditText) findViewById(R.id.template_subject_box);
mMessageBox = (EditText) findViewById(R.id.template_message_box);
mInsertNameSpinner = (Spinner) findViewById(R.id.insert_name_here_spinner);
//create adapter for the spinner and set it
ArrayAdapter<String> mAdapter1=
new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, nameTypeArr);
mAdapter1.setDropDownViewResource(android.R.layout.simple_dropdown_item_1line);
mInsertNameSpinner.setAdapter(mAdapter1);
//listener for the spinner
mInsertNameSpinner.setOnItemSelectedListener(new OnItemSelectedListener()
{
#Override
public void onItemSelected(AdapterView<?> parent,
View view, int pos, long id) {
//if the spinner has just been created, ignore this call to onItemSelected
if(spinnerBeingCreated == true){
spinnerBeingCreated = false;
return;
}
//what item did the user click in spinner
String typeOfName = parent.getItemAtPosition(pos).toString();
//based on user choice, insert corresponding placeholder in text
if(typeOfName.equals( getString(R.string.first_name) )){
insertAtCurrentLocation( getString(R.string.first_name_placeholder) );
}else if(typeOfName.equals( getString(R.string.last_name) )){
insertAtCurrentLocation( getString(R.string.last_name_placeholder) );
}
//reset the spinner item selection back to first one
mInsertNameSpinner.setSelection(0);
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {}
});
//if its a template for sms, hide the subject line
LinearLayout subjectarea = (LinearLayout) findViewById(R.id.template_subject_box_container);
if(mTemplateType.equals("sms")){
subjectarea.setVisibility(View.GONE);
} else if(mTemplateType.equals("email")){
subjectarea.setVisibility(View.VISIBLE);
}
fillData(sms_key_id);
//Save the template
//setup Save Template Listener
Button saveTemplateButton = (Button) findViewById(R.id.save_template_button);
saveTemplateButton.setOnClickListener(new OnClickListener(){
public void onClick(View view){
// saveTemplate();
updateTemplate(sms_key_id);
}
});
//Cancel
//Cancel Listener
Button cancelTemplateButton = (Button) findViewById(R.id.cancel_template_button);
cancelTemplateButton.setOnClickListener(new OnClickListener(){
public void onClick(View view){
finish();
}
});
}
public void fillData(String sms_key_id) {
Toast.makeText(EmailSMSTempEdit.this, sms_key_id, Toast.LENGTH_LONG).show();
dba.open();
String queryStr =
"Select " +
"*" + " from " +
Constants.TABLE_NAME_GREETINGS +
" where "+ Constants.KEY_ID_GREET+"=" + sms_key_id ;
//Toast.makeText(this, queryStr, Toast.LENGTH_SHORT).show();
c = dba.getResults(queryStr);
startManagingCursor(c);
if(c.moveToFirst()){
do{
mNameBox.setText(c.getString(c.getColumnIndex(Constants.GREETING_NAME)));
mMessageBox.setText(c.getString(c.getColumnIndex(Constants.GREETING_MESSAGE)));
// System.out.println(c.getString(c.getColumnIndex(Constants.KEY_ID_GREET)));
// System.out.println(c.getString(c.getColumnIndex(Constants.GREETING_NAME)));
// System.out.println(c.getString(c.getColumnIndex(Constants.GREETING_MESSAGE)));
// System.out.println(c.getString(c.getColumnIndex(Constants.KEY_ID_SETUP_GREET)));
} while(c.moveToNext());
}
}
public void updateTemplate(String sms_key_id){
String subject = mSubjectBox.getText().toString();
String name = mNameBox.getText().toString();
String message = mMessageBox.getText().toString();
dba.open();
//if name is null or empty, don't save
if(name == null || name.equals("")){
Toast.makeText(this, R.string.empty_template_name_error, Toast.LENGTH_LONG).show();
return;
}
//whether its sms or email, requied fro db query
int messageTypeCode = -1; //for sms, it is 0. For email it is 1
if(mTemplateType.equals("email")){
message = subject + subjectMessageDelimiter + message; //|~| is the delimiter
messageTypeCode = Constants.EMAIL_CODE;
} else if(mTemplateType.equals("sms")){
messageTypeCode = Constants.SMS_CODE;
}
String Stmt = "update " +
Constants.TABLE_NAME_GREETINGS +
" set "+
Constants.GREETING_NAME+"='"+name + "',"+
Constants.GREETING_MESSAGE+"='"+message + "'," +
Constants.KEY_ID_SETUP_GREET+"='"+messageTypeCode +"'" +
" where "+ Constants.KEY_ID_GREET+"=" + sms_key_id ;
dba.execute(Stmt);
dba.close();
Toast.makeText(this, "Successfully updated Template: " + name, Toast.LENGTH_LONG).show();
//finish the activity
// setResult(RESULT_OK, null);
finish();
}
#Override
protected void onDestroy(){
//dba.close();
super.onDestroy();
}
//insert at currnet cursor location in subject or message field
private void insertAtCurrentLocation(String str){
int start, end;
if(mMessageBox.hasFocus()){
start = mMessageBox.getSelectionStart();
end = mMessageBox.getSelectionEnd();
mMessageBox.getText().replace(Math.min(start, end), Math.max(start, end),
str, 0, str.length());
} else if(mSubjectBox.hasFocus()){
start = mSubjectBox.getSelectionStart();
end = mSubjectBox.getSelectionEnd();
mSubjectBox.getText().replace(Math.min(start, end), Math.max(start, end),
str, 0, str.length());
}
}
private boolean alreadyExists(String templateName){
int type_code = -1;
if(mTemplateType.equals("sms")){
type_code = Constants.SMS_CODE;
} else if(mTemplateType.equals("email")){
type_code = Constants.EMAIL_CODE;
}
String query = "Select * from " + Constants.TABLE_NAME_GREETINGS
+ " where " + Constants.GREETING_NAME + " = '" + templateName
+ "' AND " + Constants.KEY_ID_SETUP_GREET + "=" + type_code;
Cursor c = null;
Boolean exists = false;
dba.open();
try {
c = dba.getResults( query );
if (c != null) {
if (c.moveToFirst()) {
exists = (c.getCount() > 0);
} else {
exists = false;
}
}
} catch (Exception e) {
Log.e("CreateNewTemplate", "Error while checking if name already exists. Details: "+e.getMessage(), e);
e.printStackTrace();
} finally {
if (c != null)
c.close();
dba.close();
}
return exists;
}
}
move your cursor to the position of the list view item that you have clicked and then fetch the data from db using that cursor. Below is a small snippet:
yourListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
if(cursor!=null){
cursor.moveToPosition(position);
//do your stuff here....
cursor.close();
}
}
});
i want to search in database in my android application. when i get a select query if its been or not been in database its show nothing.
this is my code:
final String havy = edtSearch.getText().toString();
btnSearch.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
Cursor cursor = G.dataBase.rawQuery("SELECT * FROM db WHERE info_title=" + "'" + havy + "'", null);
if (cursor.moveToNext()) {
Intent intent = new Intent(SearchActivity.this, DetailActivity.class);
intent.putExtra(G.selectedItem.face, true);
SearchActivity.this.finish();
} else {
Toast.makeText(SearchActivity.this, "shows something", Toast.LENGTH_SHORT).show();
}
}
});
Check if your cursor is not null and size is greater that zero, then iterate over the cursor.
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);
In my application i've one AutoComplete TextView and EditText In this AutoComplete TextView provides all the contact names from Contacts.
I want to get the primary email id which contact was selected in my AutoComplete Textview to the editText. How can i achieve this? Anyone guide me?
public class Contact extends Activity {
/** Called when the activity is first created. */
private static final int CONTACT_PICKER_RESULT = 10;
private static final String DEBUG_TAG = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
public void doLaunchContactPicker(View view) {
Intent contactPickerIntent = new Intent(Intent.ACTION_PICK,Contacts.CONTENT_URI);
startActivityForResult(contactPickerIntent, CONTACT_PICKER_RESULT);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
switch (requestCode) {
case CONTACT_PICKER_RESULT:
Cursor cursor = null;
String email = "";
try {
Uri result = data.getData();
Log.v(DEBUG_TAG, "Got a contact result: "
+ result.toString());
// get the contact id from the Uri
String id = result.getLastPathSegment();
// query for everything email
cursor = getContentResolver().query(Email.CONTENT_URI, null, Email.CONTACT_ID + "=?", new String[] { id }, null);
int emailIdx = cursor.getColumnIndex(Email.DATA);
// let's just get the first email
if (cursor.moveToFirst()) {
email = cursor.getString(emailIdx);
Log.v(DEBUG_TAG, "Got email: " + email);
} else {
Log.w(DEBUG_TAG, "No results");
}
} catch (Exception e) {
Log.e(DEBUG_TAG, "Failed to get email data", e);
} finally {
if (cursor != null) {
cursor.close();
}
EditText emailEntry = (EditText) findViewById(R.id.invite_email);
emailEntry.setText(email);
if (email.length() == 0) {
Toast.makeText(this, "No email found for contact.",
Toast.LENGTH_LONG).show();
}
}
break;
}
} else {
Log.w(DEBUG_TAG, "Warning: activity result not ok");
}
}
}
Make sure you have READ_CONTACTS permission for your App.
AutoCompleteTextView autoCompleteTextView = (AutoCompleteTextView)findViewById(R.id.autoCompleteTextView1);
Cursor emailCursor = getContentResolver().query(ContactsContract.CommonDataKinds.Email.CONTENT_URI, null, null, null, null);
startManagingCursor(emailCursor);
autoCompleteTextView.setAdapter(new SimpleCursorAdapter(this, android.R.layout.simple_dropdown_item_1line, emailCursor, new String[] {Email.DATA1}, new int[] {android.R.id.text1}));
autoCompleteTextView.setThreshold(0);
Please Note AutoCompleteTextView is Case Sensitive.