I had some problem about get data from sqlite different database.One database that save user's name and phone and they can update as they like. While another is house information but also contain user's name and phone.
My problem is i just realize that the phone that had been update in user database is not same with phone that previous store in house database. So i wanna call the user's phone from user database and use for phone call function and message function. But it does not work.And i trying to match the fullname that in user database with house database to call the phone data but still cant.
here is my call and message function
public class HouseDetail extends AppCompatActivity {
EditText etAddress,etDetail,etPhone;
TextView txType,txProperty,txPrice,txState,txTitle,txOther,txSize,txFullname;
ImageButton bPhone,bMessage;
String type,property,price,state,address,title,other,size,detail,fullnames,fullname,phone;
HousesDB db = new HousesDB(this);
Houses houses;
DatabaseOperations Udb = new DatabaseOperations(this);
PersonalData profileInfo;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_house_detail);
txType = (TextView) findViewById(R.id.txTypes);
txProperty = (TextView) findViewById(R.id.txProperty);
txPrice = (TextView) findViewById(R.id.txPrice);
txState = (TextView) findViewById(R.id.txState);
etAddress = (EditText) findViewById(R.id.etAddress);
txTitle = (TextView) findViewById(R.id.txTitle);
txOther = (TextView) findViewById(R.id.txOther);
txSize = (TextView) findViewById(R.id.txSize);
txFullname = (TextView) findViewById(R.id.txFullname);
etPhone = (EditText) findViewById(R.id.etPhone);
etDetail = (EditText) findViewById(R.id.etDetail);
bPhone = (ImageButton) findViewById(R.id.bPhone);
bMessage = (ImageButton) findViewById(R.id.bMessage);
fullnames = txFullname.getText().toString();
type = txType.getText().toString();
property = txProperty.getText().toString();
price = txPrice.getText().toString();
state = txState.getText().toString();
address = etAddress.getText().toString();
title = txTitle.getText().toString();
other = txOther.getText().toString();
size = txSize.getText().toString();
detail = etDetail.getText().toString();
phone = etPhone.getText().toString();
Intent i = getIntent();
property = i.getStringExtra("house_property");
txProperty.setText(property);
houses = db.getInfo(property);
txType.setText(houses.getTypes());
txFullname.setText(houses.getFullname());
txPrice.setText(houses.getPrice());
txState.setText(houses.getState());
etAddress.setText(houses.getAddress());
txTitle.setText(houses.getTitle());
txOther.setText(houses.getOther());
txSize.setText(houses.getSize());
etDetail.setText(houses.getDetail());
this.fullnames = fullname;
profileInfo = Udb.getNumber(fullname);
etPhone.setText(profileInfo.get_phone());
bPhone.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent callIntent =new Intent(Intent.ACTION_CALL);
callIntent.setData(Uri.parse("tel:" + etPhone));
startActivity(callIntent);
}
});
bMessage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("sms:" + etPhone)));
}
});
}
Here is my user database that get the phone number
public PersonalData getNumber(String fullname)
{
SQLiteDatabase SQ = this.getWritableDatabase();
String query = "select FullName,Phone from "+ Table_NAME;
Cursor CR = SQ.rawQuery(query,null);
String a;
PersonalData info = new PersonalData();
if (CR.moveToFirst())
{
do {
a = CR.getString(0);
if (a.equals(fullname)) {
info._phone = CR.getString(1);
break;
}
}while (CR.moveToNext());
}
return info;
}
try this:
public PersonalData getNumber(String fullName) {
SQLiteDatabase database = this.getReadableDatabase();
String table = "YOUR TABLE NAME";
String[] columns = {
"FullName" ,
"Phone"
};
Cursor cursor = database.query(table , columns , null , null , null , null , null);
cursor.moveToPosition(-1);
PersonalData info = new PersonalData();
while (cursor.moveToNext()) {
String name = cursor.getString(0);
if (name.equals(fullName)) {
info._phone = cursor.getString(1);
break;
}
}
cursor.close();
return info;
}
Replace
a = CR.getString(0);
if (a.equals(fullname)) {
info._phone = CR.getString(1);
break;
}
with
a = CR.getString(CR.getColumnIndex("Fullname"));
if (a.equals("FullName")) {
info._phone = CR.getString(CR.getColumnIndex("Phone"));
break;
}
your data gotten by query maybe not be ordered as you want,in your case that is, the result maybe not in "Fullname,Phone",so you should use getColumnIndex() to get data for each column.
Related
I tried using query method in my login system.My logic is simple.Once a user has registered using Email and Password,then he can login if the email and password matches in the Database.For the starter code, i wanted to read the row from the database that matches the email ad password.And if the query method only returns 1 row,then the user is taken to the next page.
But the problem is that query method does not return any row.I have provided the code below.Thanks
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.login_signup);
demoText = (TextView) findViewById(R.id.demoText);
input_email = (EditText) findViewById(R.id.login_email);
input_password = (EditText) findViewById(R.id.login_password);
login = (Button) findViewById(R.id.login);
register = (Button) findViewById(R.id.register);
login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
login_email = input_email.getText().toString();
login_password = input_password.getText().toString();
Log.v("login_signup","Email= "+login_email+" Password"+login_password);
if(checkEntry(login_email,login_password)){
Intent i = new Intent(login_signup.this,anotherscreen.class);
startActivity(i);
Toast.makeText(login_signup.this,"Login Successful",Toast.LENGTH_SHORT).show();
}
else Toast.makeText(login_signup.this,"Login Failed",Toast.LENGTH_SHORT).show();
}
});
register.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(login_signup.this,Register.class);
startActivity(i);
}
});
toolbar= (Toolbar) findViewById(R.id.app_bar);
setSupportActionBar(toolbar);
getSupportActionBar().setIcon(R.drawable.text_icon);
dbHelper = new scannerDbHelper(this);
}
public boolean checkEntry(String email,String password){
db = dbHelper.getReadableDatabase();
String projection[] = {loginEntry.COLUMN_EMAIL_ID,loginEntry.COLUMN_PASSWORD};
String selection = loginEntry.COLUMN_EMAIL_ID + "= ?"+" AND "+loginEntry.COLUMN_PASSWORD + "= ?";
String selectionArgs[] = {email,password};
Cursor cursor = db.query(loginEntry.TABLE_NAME,projection,selection,selectionArgs,null,null,null);
demoText.setText("Rows returned "+ cursor.getCount());
if(cursor.getCount()== 1)
return true;
else
return false;
}
New to Android Studio so some help would go a long way!
Trying to do a search where the user inputs an email and if its in the database, then it shows up in a text view.
I think my select is correct but here's the method in my Database Handler class:
public String searchEmail(String email)
{
SQLiteDatabase db = this.getWritableDatabase();
String fName;
String sName;
String selectQuery = "SELECT FIRSTNAME, SURNAME FROM friends_table WHERE EMAIL=? ";
Cursor c = db.rawQuery(selectQuery, new String[] { email });
if (c.moveToFirst()) {
fName = c.getString(c.getColumnIndex("FIRSTNAME"));
sName = c.getString(c.getColumnIndex("SURNAME"));
}
c.close();
return email;
}
Then my search:
public void searchFriend(View v) {
EditText emailSearch = (EditText) findViewById(R.id.emailSearch);
String emailSearchString = emailSearch.getText().toString();
myDB.searchEmail(emailSearchString);
//I need to get the first name and surname from the db handler class
TextView firstName = (TextView)findViewById(R.id.firstname);
TextView surname = (TextView)findViewById(R.id.surname);
firstName.setText("");
surname.setText("");
}
I'm just finding to difficult to understand how I'll show the first name and surname if the email matches.
Thanks guys, I love you
Create a new class User (with getters, setters) and try this:
public User searchEmail(String email) {
SQLiteDatabase db = this.getWritableDatabase();
User u = null;
String selectQuery = "SELECT FIRSTNAME, SURNAME FROM friends_table WHERE EMAIL=? ";
Cursor c = db.rawQuery(selectQuery, new String[] { email });
if (c.moveToFirst()) {
u = new User();
u.setfName(c.getString(c.getColumnIndex("FIRSTNAME")));
u.setsName(c.getString(c.getColumnIndex("SURNAME")));
}
c.close();
return u;
}
Display results in activity:
public void searchFriend(View v) {
EditText emailSearch = (EditText) findViewById(R.id.emailSearch);
TextView firstName = (TextView)findViewById(R.id.firstname);
TextView surname = (TextView)findViewById(R.id.surname);
String emailSearchString = emailSearch.getText().toString();
User user = myDB.searchEmail(emailSearchString);
firstName.setText(user.getfName());
surname.setText(user.getsName());
}
Create a new class User and try this:
public User searchEmail(String email)
{
SQLiteDatabase db = this.getWritableDatabase();
User u = null;
String selectQuery = "SELECT FIRSTNAME, SURNAME FROM friends_table WHERE EMAIL=? ";
Cursor c = db.rawQuery(selectQuery, new String[] { email });
if (c.moveToFirst()) {
u = new User();
u.setfName(c.getString(c.getColumnIndex("FIRSTNAME")));
u.setsName(c.getString(c.getColumnIndex("SURNAME")));
}
c.close();
return u;
}
I created an app that shows a list of places and i created a search dialog wherein the user will type in edittext so he/she will find the desired place. First, search is working when its only place and I try to add spinner with values which are the region of the places and I got problem on the line which i will post below.
GetSearchPlace = dbhelper.getPlaceSearch(placeLocationEditText.getText().toString(),dbhelper.getPlaceSearch(placeRegion.getSelectedItem().toString()));
It says getPlaceSearch (String, string) in DatabaseHelper cannot be applied to (String)
This is my database helper
public List<PlaceModel> getPlaceSearch(String location, String region) {
List<PlaceModel> search = new ArrayList<PlaceModel>();
String selectQuery = "SELECT * FROM listing_place where province_name like '" + location + "' and region = '"+region+"'";
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
if (cursor.moveToFirst()) {
do {
PlaceModel pm = new PlaceModel();
pm.setlisting_title(cursor.getString(cursor.getColumnIndex(KEY_PLACE)));
search.add(pm);
}
while (cursor.moveToNext());
}
cursor.close();
return search;
}
This is my main activity
final Spinner placeRegion = (Spinner) dialog.findViewById(R.id.spinnerregion);
ArrayAdapter<String> RegionAdapter = new ArrayAdapter<String>(MainActivity.this,R.layout.spinner_layout, db.getAllRegion());
RegionAdapter.setDropDownViewResource(R.layout.spinner_layout);
placeRegion.setAdapter(RegionAdapter);
placeLocationEditText = (EditText)dialog.findViewById(R.id.placelocation);
Button button = (Button) dialog.findViewById(R.id.btnplacesearch);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dialog.dismiss();
PlaceListView = findViewById(R.id.placelayout);
ViewGroup parent = (ViewGroup) PlaceListView.getParent();
parent.removeView(PlaceListView);
PlaceSearchView = getLayoutInflater().inflate(R.layout.searchresult_place, parent, false);
parent.addView(PlaceSearchView);
GetSearchPlace = dbhelper.getPlaceSearch(placeLocationEditText.getText().toString(),dbhelper.getPlaceSearch(placeRegion.getSelectedItem().toString()));
lv2 = (ListView) findViewById(R.id.searchplace_list);
lv2.setAdapter(new ViewAdapterSearchPlace());
ok replace your code to below..
GetSearchPlace = dbhelper.getPlaceSearch(placeLocationEditText.getText().toString(),placeRegion.getSelectedItem().toString());
So I have a ListView on which I click to start new Activity called MerchantView.
Between the activities I am passing the uid which is a unique identifier of a merchant.
Im then extracting merchant data from DB and want to view this data in this view.
Everything works (while debugging i can see that data is taken from DB and passed properly to setText methods) but the data does not show, am I doing this right?
public class MerchantView extends Activity {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.merchant);
String desc = "";
String name = "";
Bundle extras = getIntent().getExtras();
String uid = "0";
if(extras !=null) {
uid = extras.getString("uid");
}
// get merchant from database
if(Integer.valueOf(uid) > 0){
Cursor c = Utilities.db.query(mydb.TABLE_MERCHANT,
null,
"uid=?", new String[] {uid}, null, null, null);
if(c.moveToFirst() != false){
name = c.getString(c.getColumnIndex(MerchantsColumns.COLname));
desc = c.getString(c.getColumnIndex(MerchantsColumns.COLdesc));
}
// set values to UI
TextView descUI = (TextView) findViewById(R.id.merchantDescription);
descUI.setText(desc);
TextView nameUI = (TextView) findViewById(R.id.merchantName);
nameUI.setText(name);
}
else{
}
Button buttonMerchants = (Button) findViewById(R.id.buttonMerchants);
buttonMerchants.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
finish();
}
});
}
}
Data was set properly. The problem was in layout. The header (LinearLayout) at the top had two buttons and it was set to android:layout_height="fill_parent" which was taking whole space. After fixing that, data is showing properly.
Try Below code hope it helps
SQLiteDatabase myDB = this.openOrCreateDatabase("databasename.db", SQLiteDatabase.OPEN_READWRITE, null);
try{
Cursor c = myDB.rawQuery("select name, desc from abctable where uid="+uid, null);
int Column1 = c.getColumnIndex("name");
int Column2 = c.getColumnIndex("desc");
// Check if our result was valid.
c.moveToFirst();
if (c != null) {
int i = 0;
// Loop through all Results
do {
i++;
String name = c.getString(Column1);
String desc = c.getString(Column2);
TextView descUI = (TextView) findViewById(R.id.merchantDescription);
descUI.setText(desc);
TextView nameUI = (TextView) findViewById(R.id.merchantName);
nameUI.setText(name);
} while (c.moveToNext());
}
} catch (SQLiteException e) {
e.printStackTrace();
} finally {
if (myDB != null)
myDB.close();
}
I have a page with a number edit texts, i want to populate these with columns of a raw with the row id equaling a textview value... this is what i have so far in the edit text page.
public class CBCreate extends Activity {
EditText EditRecipe,EditRecipe2,EditRecipe3;
Button Rname;
CBDataBaseHelper entry;
TextView RowIDText;
Cursor c;
String name;
String category;
String description;
//final String SQL_STATEMENT = "SELECT Recipe_Name, Recipe_Category, Recipe_Description FROM RecipeData WHERE _id = " + RowIDText ;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.create); // sets the content view to main
EditRecipe = (EditText) findViewById(R.id.editText1);
EditRecipe2 = (EditText) findViewById(R.id.editText2);
EditRecipe3 = (EditText) findViewById(R.id.editText3);
RowIDText = (TextView) findViewById(R.id.RowID);
Rname = (Button) findViewById(R.id.RecipeName);
String RowID;
try{
Bundle extras = getIntent().getExtras();
if (extras != null) {
RowID = extras.getString("SELECTED");
RowIDText.setText(RowID);
}
if (RowIDText != null){
entry = new CBDataBaseHelper(this);
String s = RowIDText.getText().toString();
int ID = Integer.parseInt(s);
entry.open();
Cursor cursor = entry.fetchRow(ID);
if (cursor.moveToFirst()){ // data?
name = cursor.getString(cursor.getColumnIndex(CBDataBaseHelper.KEY_NAME));
}
entry.close();
EditRecipe.setText(name);
EditRecipe2.setText(category);
EditRecipe3.setText(description);
}
}catch (Exception e){
String error = e.toString();
Dialog d = new Dialog(this);
d.setTitle("darn");
TextView tv = new TextView(this);
tv.setText(name);
d.setContentView(tv);
d.show();
}
}
public void doIt(View view) {
String Name = EditRecipe.getText().toString();
String description = EditRecipe.getText().toString();
String category = EditRecipe.getText().toString();
entry = new CBDataBaseHelper(CBCreate.this);
entry.open();
entry.createEntry(Name, description, category);
entry.close();
EditRecipe.setText("");
EditRecipe2.setText("");
EditRecipe3.setText("");
}
public void goBack(View view){
Intent myIntent = new Intent(this, CBFilter.class);
startActivity(myIntent);
}
}
and then this is what i have within the database helper class... i think i want to call this method?
public Cursor fetchRow(long rowId) throws SQLException {
Cursor mCursor = mydatabase.query(true, DATABASE_TABLE, new String[] { KEY_ROWID,
KEY_CATEGORY, KEY_DESCRIPTION }, KEY_ROWID + "="
+ rowId, null, null, null, null, null);
if (mCursor != null) {
mCursor.moveToFirst();
}
return mCursor;
}
I would use mydatabase.rawquery(QUERY) instead of the cursors query method. Its easier for SQL developers I think. Anyways, once you have your values in the cursor, you can do this
EditRecipe.setText(cursor.getString(0));
EditRecipe2.setText(cursor.getString(1));
Where 0 represents the first column in your returned table. You would put that code after your mCursor.moveToFirst();