Saving Values to a database - java

I am trying to make an app for a restaurant. I have set up a local database and have a prepared statement to save a users username and password to enable them to log into the system, but it does not seem to work. The username and passwords are not saving. Below is my code, if anyone has any solutions, i would greatly appreciate it.
public class register extends AppCompatActivity {
EditText username, password;
Button registartion;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
}
private Connection getConnection()
{
String host = "jdbc:mysql://jdbc.fmc.me.uk:3306/db_ben";
String u = "user_ben";
String p = "******";
try
{
Connection con = DriverManager.getConnection(host, u, p);
return con;
} catch (SQLException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
private boolean registerUser(){
//Get username
EditText regUsernameBox = (EditText) findViewById(R.id.RegUsername);
String regUsernameStr = regUsernameBox.getText().toString();
//Get password
EditText regPasswordBox = (EditText) findViewById(R.id.RegPassword);
String regPasswordStr = regPasswordBox.getText().toString();
System.out.println(regUsernameStr);
System.out.println(regPasswordStr);
int i = 0;
Connection con = getConnection();
try {
PreparedStatement pst = con.prepareStatement("insert into users values(?,?)");
pst.setString(1, regUsernameStr);
pst.setString(2,regPasswordStr);
i = pst.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
}
if(i>0)
return true;
return false;
}
public void buttonClick() {
final Button registerUsers = (Button) findViewById(R.id.bRegister);
registerUsers.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
registerUser();
}
});
}
}

None of your methods are being called. Your oncreate sets the view for the activity and then does nothing. Hence, you get no errors as there are technically none. You have to set the button click instructions for the button in the create. Your onCreate should look like this:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
final Button registerUsers = (Button) findViewById(R.id.bRegister);
registerUsers.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
registerUser();
}
});
}
Now here the button is assigned a variable and then the clicklistener is set to it onCreate. Now when you click the button it would do something.

iQuote the android references http://developer.android.com/intl/es/reference/android/app/Activity.html#onCreate(android.os.Bundle)
i also think that you should use asynctask to do database work to keep your app responsive
onCreate(Bundle) is where you initialize your activity. Most importantly, here you will usually call setContentView(int) with a layout resource defining your UI, and using findViewById(int) to retrieve the widgets in that UI that you need to interact with programmatically.
so it must look like this:
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
EditText regUsernameBox = (EditText) findViewById(R.id.RegUsername);
EditText regPasswordBox = (EditText) findViewById(R.id.RegPassword);
Button registerUsers = (Button) findViewById(R.id.bRegister);
registerUsers.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
registerUser();
}
});
}

Related

nullpointerexception error I do now know how to fix

where is error? how can I fix it? layout is true error in 24th line that
kaleciKayit.setOnClickListener(new View.OnClickListener() {
here is my all codes
public class oyuncuAdlariActivity extends AppCompatActivity {
Button kaleciKayit;
Button oyuncuKayit;
EditText isimGiris;
String isimGirisString;
int kaleciSayisi = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_oyuncu_adlari);
kaleciKayit = (Button) findViewById(R.id.kaleciButton);
oyuncuKayit = (Button) findViewById(R.id.oyuncuButton);
isimGiris = (EditText) findViewById(R.id.isimGir);
kaleciKayit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
kaleciSayisi++;
isimGirisString = isimGiris.getText().toString();
if (isimGirisString.isEmpty()){
Toast toast1 = Toast.makeText(getApplicationContext(),getApplicationContext().getString(R.string.isimBos), Toast.LENGTH_SHORT);
toast1.show();
}
else if (kaleciSayisi >2)
kaleciKayit.setEnabled(false);
}
});
}
}
First of all, I will recommend setting the objects in a class to private. I think the problem is that maybe you are assigning the id of the wrong widget? check the FindViewByID again.
The other 3 possibilities that I can think about are-
The problem is in the first activity(In this case I ask you to post here the content of the first activity)
The setContentView method points at a wrong XML file.
Your AVD ran out of memory and you need to add more to it in the AVD Manager tool.
Change MainActivity to this,
public class MainActivity extends AppCompatActivity {
Button devamButton;
EditText takim1, takim2;
String takimTextA;
String takimTextB;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
devamButton = findViewById(R.id.devamButton);
takim1 = findViewById(R.id.takimB);
takim2 = findViewById(R.id.takimA);
devamButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
takimTextA = takim1.getText().toString();
takimTextB = takim2.getText().toString();
if (takimTextA.equals(takimTextB)) {
Toast toast1 = Toast.makeText(getApplicationContext(),getApplicationContext().getString(takimAyniOlmaz), Toast.LENGTH_SHORT);
toast1.show();
} else if (takimTextA.isEmpty() || takimTextB.isEmpty()) {
Toast toast2 = Toast.makeText(getApplicationContext(), getApplicationContext().getString(R.string.takimBosBirakma), Toast.LENGTH_SHORT);
toast2.show();
} else {
activityGecis1(v);
}
}
});
}
private void activityGecis1(View v) {
Intent gecis1 = new Intent(v.getContext(), oyuncuAdlariActivity.class);
startActivity(gecis1);
}
Since you are calling inside onclicklistener maybe this in intent may point to that functions class.

Passing database value to variable

I'm rarely ask on here, so first of all I'm sorry if my question is readable or not allowed here. So what I'm trying to do here is passing the username from LoginActivity into the player1 variable at HomeActivity . here's the code for the HomeActivity.java class
public class HomeActivity extends Activity {
TextView NameTxt;
TextView CoinTxt;
TextView GemTxt;
String p1name = player1.getName();
int p1coin = player1.getCoins();
int p1gem = player1.getGems();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_screen);
//////TV declare///////
NameTxt = (TextView)findViewById(R.id.playerName);
CoinTxt = (TextView)findViewById(R.id.cointxt);
GemTxt = (TextView)findViewById(R.id.gemtxt);
NameTxt.setText(p1name);
CoinTxt.setText("Coin: " +p1coin);
GemTxt.setText("Gem: " +p1gem);
}
}
And this is LoginActivity.class
public class LoginActivity extends Activity {
EditText edit1;
EditText edit2;
EditText edit3;
Button registerBtn;
Button loginBtn;
DatabaseHelper myDb;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//Set fullscreen and no title//////////
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
///////////////////////////////////////
setContentView(R.layout.login_screen);
edit1 = (EditText)findViewById(R.id.editpname);
edit2 = (EditText)findViewById(R.id.editpemail);
edit3 = (EditText)findViewById(R.id.editppw);
registerBtn = (Button)findViewById(R.id.registerbtn);
loginBtn = (Button)findViewById(R.id.loginbtn);
myDb = new DatabaseHelper(this);
loginBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (validate()) {
String Email = edit2.getText().toString();
String Password = edit3.getText().toString();
User currentUser = myDb.Authenticate(new User(null, null, Email, Password));
if (currentUser != null) {
System.out.println("Successfull");
Intent intent = new Intent(getApplicationContext(),HomeActivity.class);
startActivity(intent);
finish();
} else {
System.out.println("Unsuccessfull");
}
}
}
});
registerBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (validate()) {
String UserName = edit1.getText().toString();
String Email = edit2.getText().toString();
String Password = edit3.getText().toString();
if (!myDb.isEmailExists(Email)) {
myDb.addUser(player1);
public User player1 = new User(null, UserName, Email, Password);
}
}
}
});
}
public boolean validate() {
boolean valid = false;
String Email = edit2.getText().toString();
String Password = edit3.getText().toString();
if (!android.util.Patterns.EMAIL_ADDRESS.matcher(Email).matches()) {
valid = false;
edit2.setError("Please enter valid email!");
} else {
valid = true;
edit2.setError(null);
}
if (Password.isEmpty()) {
valid = false;
edit3.setError("Please enter valid password!");
} else {
if (Password.length() > 5) {
valid = true;
edit3.setError(null);
} else {
valid = false;
edit3.setError("Password is to short!");
}
}
return valid;
}
}
And I also have simple User.java class
String id;
String userName;
String email;
String password;
int coins;
int gems;
public User(String id, String userName, String email, String password) {
this.id = id;
this.email = email;
//And so on. Don't mind this
}
public String getName() {
return this.userName;
}
public int getCoins() {
return this.coins;
}
public int getGems() {
return this.gems;
}
And I write the short code , for the sake of readability.
I get an error on
myDb.addUser(player1);
And the one below it.
I'm just trying to make so that the player name equals to the value of Username on the database . and also the coins and gems too. Can you guys help me to get the idea how to pass the value? It tooks me whole 3days to figure a way to fix this. And it just blew my brain. So maybe you guys can help me
Ignoring the database stuff and assuming that LoginActivity is started from another activity (MainActivity) then you could adapt the following which passes the Username and UserId (ample to then get any additional data in the HomeActivity from the database).
So this when it starts immediately invokes the LoginActivity.
Clicking Login (mimics getting user and id from db) starts the HomeActivity passing the Username and userid via Intent Extras.
The HomeActivity displays the username and userid, and additionally a DONE button.
Clicking the DONE button returns back through the stack (skippng LoginActivity as that was finished) to the MainActivity which changes the TextView from Hello World to Welcome Back (not that you'd ever see Hello World).
MainActivity.java :-
public class MainActivity extends AppCompatActivity {
TextView mMessage;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mMessage = this.findViewById(R.id.message);
// Immediately start Login Activity
Intent i = new Intent(MainActivity.this,LoginActivity.class);
startActivity(i);
}
#Override
protected void onResume() {
super.onResume();
mMessage.setText("Welcome back");
}
}
LoginActivity.java :-
public class LoginActivity extends AppCompatActivity {
public static final String INTENTKEY_USERNAME = "IK_USERNAME";
public static final String INTENTKEY_USERID = "IK_USERID";
Button mloginbtn;
Context mContext;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
mContext = this;
mloginbtn = this.findViewById(R.id.loginbtn);
mloginbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent i = new Intent(mContext,HomeActivity.class);
i.putExtra(INTENTKEY_USERNAME,"Fred");
i.putExtra(INTENTKEY_USERID,99L);
startActivity(i);
finish();
}
});
}
}
HomeActivity.java
public class HomeActivity extends AppCompatActivity {
TextView mUsername, muserid;
Button mDone;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
mUsername = this.findViewById(R.id.username);
muserid = this.findViewById(R.id.userid);
mDone = this.findViewById(R.id.done);
mDone.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
finish();
}
});
Intent i = this.getIntent();
mUsername.setText(i.getStringExtra(LoginActivity.INTENTKEY_USERNAME));
muserid.setText(String.valueOf(i.getLongExtra(LoginActivity.INTENTKEY_USERID,0)));
}
}
I'd do the following:
...
Intent intent = new Intent(getApplicationContext(),HomeActivity.class);
intent.putExtra("username", Bob)
startActivity(intent);
finish();
...
and then in home have:
Intent intent = getIntent();
String easyPuzzle = intent.getExtras().getString("username");

Retrieve data from database to my app (NOT WORKING)

so i am trying to retrieve data stored in my database.
basically the user inputs a car registration number and a rating (between 1-5)and click button. once the button is clicked my code will execute. which gets text from both editext and send to my server. i have php file saved, which will check if the carregistration number matches the value in the databse. if it matches retrieve the current rating stored in the database. the value is then showed on another acitivity. The php file works fine. i tried by inserting value manually. the problem i have is that when the button is clicked nothign happens. i have used this code to retrieve user name and other details on another app.
dataretrieve.java
public class DataRetrieve extends StringRequest {
private static final String REGISTER_REQUEST_URL = "https://dipteran-thin.000webhostapp.com/Login1.php";
private Map<String, String> params;
public DataRetrieve (String carreg, int rating, Response.Listener<String> listener) {
super(Method.POST, REGISTER_REQUEST_URL, listener, null);
params = new HashMap<>();
params.put("carreg", carreg);
params.put("rating", rating + "");
}
#Override
public Map<String, String> getParams() {
return params;
}
}
Profile.java (where the user inputs carreg and rating)
public class Profile extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.profile);
final EditText editText = (EditText) findViewById(R.id.carreg);
final EditText editText1 = (EditText) findViewById(R.id.editText3);
Button button = (Button) findViewById(R.id.button2);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final String carreg = editText.getText().toString();
final int rating = Integer.parseInt(editText1.getText().toString());
// Response received from the server
Response.Listener<String> responseListener = new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonResponse = new JSONObject(response);
boolean success = jsonResponse.getBoolean("success");
if (success) {
int rating = jsonResponse.getInt("rating");
Intent intent = new Intent(Profile.this, UserAreaActivity.class);
intent.putExtra("rating", rating);
Profile.this.startActivity(intent);
} else {
AlertDialog.Builder builder = new AlertDialog.Builder(Profile.this);
builder.setMessage("Login Failed")
.setNegativeButton("Retry", null)
.create()
.show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
};
DataRetrieve loginRequest = new DataRetrieve(carreg, rating, responseListener);
RequestQueue queue = Volley.newRequestQueue(Profile.this);
queue.add(loginRequest);
}});
}
}
userareaactivity.java (where value is shown when retrieved)
public class UserAreaActivity extends AppCompatActivity {
#Override
protected void onCreate (Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_user_area);
final TextView etusername = (TextView) findViewById(R.id.textView2);
final TextView etwelcome = (TextView) findViewById(R.id.textView);
final TextView etuname = (TextView) findViewById(R.id.textView3);
final Button Logout = (Button) findViewById(R.id.logout);
//String Name = SharedPreferenceUtils.getName(this);
//etwelcome.setText(Name);
Intent intent = getIntent();
username = intent.getIntExtra("rating", -1);
etusername.setText(username + "");
//Intent in = new Intent(getApplicationContext(), Messages.class);
//in.putExtra("username", username);
//UserAreaActivity.this.startActivity(in);
}
#Override
public void onBackPressed(){
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if ((keyCode == KeyEvent.KEYCODE_VOLUME_DOWN)) {
Intent intent = new Intent(UserAreaActivity.this, Messages.class);
UserAreaActivity.this.startActivity(intent);
}
return true;
}
I'm getting an error from your php page:
<b>Parse error</b>: syntax error, unexpected ']' in <b>/storage/ssd1/526/2972526/public_html/Login1.php</b> on line <b>8</b><br />
You can see the output of your response in the log by using this line above your JSON parsing (before it throws the exception)
Log.d("Response", response.toString());
I copied your success block into the exception block and it works as expected, so that code is valid. I would also put some kind of alert in the catch to let you know the failure happened when you're done testing.
Side note, change your parameter line to this...it's cleaner:
params.put("rating", String.valueOf(rating));

Checking if a username and email are found in Parse database

In my application I have an activity called AddPatient this activity allows the user to enter either a username or a email and the if found the text view will display a text "Found" else "not found" and the button will allow the user to continue to the next activity just if the users found the mail and username already in database. This is my code but it's giving me found all the time and the button is not working....Any help please.
Note this activity extends AppCompatActivity:
EditText UserNameEt;
EditText EmailEt;
String email;
String username;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_patient);
UserNameEt = (EditText) findViewById(R.id.et1);
EmailEt = (EditText) findViewById(R.id.et2);
username = UserNameEt.getText().toString();
email = EmailEt.getText().toString();
final TextView tv = (TextView) findViewById(R.id.tv);
ParseQuery<ParseObject> lotsOfWins = ParseQuery.getQuery("User");
lotsOfWins.whereEqualTo("email",email);
ParseQuery<ParseObject> fewWins = ParseQuery.getQuery("User");
fewWins.whereEqualTo("username", username);
List<ParseQuery<ParseObject>> queries = new ArrayList<ParseQuery<ParseObject>>();
queries.add(lotsOfWins);
queries.add(fewWins);
ParseQuery<ParseObject> query = ParseQuery.or(queries);
query.findInBackground(new FindCallback<ParseObject>() {
#Override
public void done(List<ParseObject> objects, ParseException e) {
if (true) {
tv.setText("Patient found");
} else {
tv.setText("Patient Not found");
}
}
});
String Result = tv.getText().toString();
if (Result=="Patient found"){
Button fill = (Button) findViewById(R.id.button);
fill.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(AddPatient.this,Patients.class);
startActivity(i);
}
});
}
}
}
You're setting whether the patient has been found or not using if (true), which is obviously always going to be true. You need to replace that with something that checks whether the entered value actually exists.
i would like to try on this way.
first set this method.
1st Method.
ParseQuery<ParseObject> lotsOfWins =new ParseQuery<ParseObject>("User");
lotsOfWins.whereEqualTo("email", email);
ParseQuery<ParseObject> fewWins = new ParseQuery<ParseObject>("User");
fewWins.whereEqualTo("username", username);
List<ParseQuery<ParseObject>> queries = new ArrayList<ParseQuery<ParseObject>>();
queries.add(lotsOfWins);
queries.add(fewWins);
ParseQuery<ParseObject> query = ParseQuery.or(queries);
query.findInBackground(new FindCallback<ParseObject>() {
#Override
public void done(List<ParseObject> objects, ParseException e) {
if (e == null) {
if (objects.size() > 0) {
tv.setText("Patient found");
} else {
tv.setText("Patient Not found");
}
getPatientInfo(tv.getText().toString());
} else {
// error
}
}
});
2nd this method.
protected void getPatientInfo(String Result) {
// TODO Auto-generated method stub
if (Result == "Patient found") {
Button fill = (Button) findViewById(R.id.button);
fill.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(AddPatient.this, Patients.class);
startActivity(i);
}
});
}
}
this type do for findInBackGround is one type of thread.

How to implement onClick in my activity

I have list of passwords (strings) in a database.
In my activity i put EditText (the user will write there his/her password) and a button.
How i can implement onClick for the button that will check if the password are in the system (in the list)?
Define a method called onClick() in your activity - this will get called when the button is clicked (as you specified in your XML). You can then retrieve the EditText text, and check it against the passwords in your DB.
public void onClick(View v) {
EditText myEditText = (EditText) findViewById(R.id.password);
CharSequence enteredPassword = myEditText.getText();
// TODO check if input matches a string in the DB
}
Implement OnClickListener to the control you want the user to click on:
Button mLoginButton = (Button) findViewById(R.id.login);
mLoginButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
Login();
}
});
Create the listener event "Login":
private void attemptLogin() {
//check login is valid
}
Add this to the button
btn.addActionListener( this );
and then do this
public void actionPerformed( ActionEvent event )
{
if( event.getSource() == btn )
{
}
}
You can do like this:
Button loginButton = (Button) findViewById(R.id.login);
loginButton .setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String pwd = password.getText().toString();
checkLogin(pwd)
}
})
private void checkLogin(String password) {
//db is your db instance.this is dummy query.You may have a user name editText as well
Cursor c = db.rawQuery("SELECT * FROM tbl1 WHERE TRIM(password) = '"+password.trim()+"'", null);
//check if cursor returns data
if (!(c .moveToFirst()) || c .getCount() ==0){
//cursor is empty
}
else
{
`//cursor is not empty`
}
}

Categories

Resources