This is the code that I use
dbhelper mydb;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profile);
final Intent profile = getIntent();
final String user = profile.getExtras().getString("tete");
final EditText username = (EditText) findViewById(R.id.Pusername);
final EditText password = (EditText) findViewById(R.id.Ppassword);
username.setText(user);
username.setInputType(InputType.TYPE_NULL); //Supaya username tidak dapat diganti
Button update = (Button) findViewById(R.id.btupdate);
update.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String newpassword = password.getText().toString();
String newusername = username.getText().toString();
if (password.getText().toString().trim().length() < 6) {
Toast.makeText(getApplicationContext(), "Password Baru Harus diisi minimal 6 karakter", Toast.LENGTH_SHORT).show();
} else {
mydb.editData(newusername, newpassword);
Toast.makeText(getApplicationContext(), "berhasil!", Toast.LENGTH_SHORT).show();
}
}
});
This is my code for the dbhelper class
public void editData(String username,String password){
SQLiteDatabase db= this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(COL_1,username);
contentValues.put(COL_2,password);
db.update(TABLE_NAME,contentValues,"USERNAME = ?", new String[]{username});
//String query="UPDATE " + TABLE_NAME + " SET " + COL_2 + " = '" + password + "' Where " + COL_1 + " = '" + username + "'";
//db.execSQL(query);
}
The logcat gave this error
java.lang.NullPointerException: Attempt to invoke virtual method 'void
com.example.charlie.gate.dbhelper.editData(java.lang.String,
java.lang.String)' on a null object reference
I tried to toast the newusername and the newpassword string to test if it were null and the result were both contain the value as intended, but somehow everytime I click the button the app forced close, Please help
You do not initialize mydb correctly so it is null when you try to use it.
Inside onCreate() add this line:
mydb = new dbhelper(this, ...);
usually you pass this and other parameters for this initialization.
Related
I have written code using JDBC to create registration page in Android Studio. I create database in SQL Server 2019. In addition I tried to connect from the code to MSSQL database and insert values, but while I run the app I'm getting the error:
login failed for user.
I have examined many options that can cause this error and I fixed them. For example: The server authentication is SQL Server authentication,the TCP option at the server is enabled, I have the relevant permissions of the user, also I check the if the firewall is the cause for this error. However, I continue to receive the error.
The connection class:
public class ConnectionClass {
public static String ip= "***.***.*.*:1433"; //
public static String user_name ="****";
public static String password = "****";
public static String database = "tests";
}
The Registeration class:
EditText email;
EditText password;
EditText confirmPassword;
Button sign_up;
EditText name;
Connection connection1;
Statement statement;
TextView status;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.sign_up_parent);
email = (EditText) findViewById(R.id.editTextTextEmailAddress2);
password = (EditText) findViewById(R.id.editTextTextPassword);
confirmPassword = (EditText) findViewById(R.id.editTextTextPassword2);
sign_up = (Button) findViewById(R.id.button);
name = (EditText) findViewById(R.id.editTextTextPassword3);
status = (TextView) findViewById(R.id.status);
sign_up.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
new ParentSignUp.registerUser().execute("");
}
});
}
public class registerUser extends AsyncTask<String, String, String>{
String z ="";
Boolean isSuccess = false;
public registerUser() {
super();
}
#Override
protected void onPreExecute() {
status.setText("Sending Data to Database");
}
#Override
protected void onPostExecute(String s) {
name.setText("");
email.setText("");
password.setText("");
confirmPassword.setText("");
}
#Override
protected String doInBackground(String... strings) {
try {
connection1 = connection_class(ConnectionClass.user_name.toString(), ConnectionClass.password.toString(),
ConnectionClass.database.toString(), ConnectionClass.ip.toString());
if (connection1 == null) {
z = "Check Internet Connection";
}
else {
String sql = "INSERT INTO test (name,password, email) VALUES ('example', 'example', 'example')";
statement = connection1.createStatement();
statement.executeUpdate(sql);
}
}
catch (Exception e) {
isSuccess = false;
z = e.getMessage();
}
return null;
}
}
#SuppressLint("NewApi")
public Connection connection_class (String user, String password, String database, String server) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
Connection connection = null;
String connectionUrl = null;
try{
Class.forName("net.sourceforge.jtds.jdbc.Driver");
connectionUrl = "jdbc:jtds:sqlserver://" + server + "/" + database + ";user=" + user + ";"+"password=" + password + ";";
connection = DriverManager.getConnection(connectionUrl);
}catch (Exception e){
Log.e("SQL Connection Error : ", e.getMessage());
}
return connection;
}
The problem is alertdialogue box not at all working and it crashes everytime
I checked each and every line with youtube,
but it cant be helped
here's the code:
public void showupdatedialogue(String id , String name){
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
LayoutInflater inflater = getLayoutInflater();
View dialog = inflater.inflate(R.layout.update,null);
builder.setView(dialog);
EditText naame = findViewById(R.id.name);
EditText rollno = findViewById(R.id.roll);
EditText cla = findViewById(R.id.clas);
EditText date = findViewById(R.id.dob);
EditText teacher = findViewById(R.id.teacher);
Button up = findViewById(R.id.update);
builder.setTitle("Updating" + " " + name + " " + "record");
builder.show();
up.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String n = naame.getText().toString();
String r = rollno.getText().toString();
String c = cla.getText().toString();
String d = date.getText().toString();
String t = teacher.getText().toString();
updatestudents(id,n,r,d,c,t);
Toast.makeText(MainActivity.this,"record updated",Toast.LENGTH_LONG).show();
}
});
}```
In the findViewById() you should add dialog.findViewById()
public void showupdatedialogue(String id , String name){
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
LayoutInflater inflater = getLayoutInflater();
View dialog = inflater.inflate(R.layout.update,null);
builder.setView(dialog);
EditText naame = dialog.findViewById(R.id.name);
EditText rollno = dialog.findViewById(R.id.roll);
EditText cla = dialog.findViewById(R.id.clas);
EditText date = dialog.findViewById(R.id.dob);
EditText teacher = dialog.findViewById(R.id.teacher);
Button up = dialog.findViewById(R.id.update);
builder.setTitle("Updating" + " " + name + " " + "record");
builder.show();
up.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String n = naame.getText().toString();
String r = rollno.getText().toString();
String c = cla.getText().toString();
String d = date.getText().toString();
String t = teacher.getText().toString();
updatestudents(id,n,r,d,c,t);
Toast.makeText(MainActivity.this,"record updated",Toast.LENGTH_LONG).show();
}
});
}
I'm trying to make a program in android studio that when sellected a higher education it automatically adds 200$ to the pay that was previously entered. But instead of getting 500+200=700, I get 500200. I ran trough the code numerous times and just can't seem to find the error. I'm still new on Java. This is the second window that appears when submitting the information, It shows all the info entered in the first window, but for some reason it can't 200 to the entered pay
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_rezultatas);
Intent duom = getIntent();
String pavarde = duom.getStringExtra("pavarde");
String issilavinimas = duom.getStringExtra("issilavinimas");
int pay = duom.getIntExtra("atlyginimas", 0);
String laikas = duom.getStringExtra("laikas");
TextView rez = findViewById(R.id.rezultatas);
rez.setText("Pavardė: "+pavarde+"\n");
rez.append("Išsilavinimas: "+issilavinimas+"\n");
if(issilavinimas.equals("Aukštasis")){
rez.append("Gaunamas atlyginimas: " +pay+ 200 + "\n");
} else{
rez.append("Gaunamas atlyginimas: "+pay+ "\n");
}
rez.append("Keliasi: "+laikas+"\n");
}
This is the first window where all the information is entered:
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void saugoti(View v){
EditText txt = findViewById(R.id.lastName);
String pavarde = txt.getText().toString();
Spinner issilavinimas = findViewById(R.id.issilavinimas);
String issilav = issilavinimas.getSelectedItem().toString();
EditText atl = findViewById(R.id.pay);
int pay = Integer.parseInt(atl.getText().toString());
TextView txt2 = findViewById(R.id.time);
String laikas = txt2.getText().toString();
Intent duom = new Intent(this, rezultatas.class);
duom.putExtra("pavarde", pavarde);
duom.putExtra("issilavinimas", issilav);
duom.putExtra("laikas", laikas);
duom.putExtra("atlyginimas", pay);
startActivity(duom);
}
public void showTimePickerDialog(View v) {
DialogFragment newFragment = new TimePickerFragment();
newFragment.show(getSupportFragmentManager(), "timePicker");
}
Try this
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_rezultatas);
Intent duom = getIntent();
String pavarde = duom.getStringExtra("pavarde");
String issilavinimas = duom.getStringExtra("issilavinimas");
int pay = duom.getIntExtra("atlyginimas", 0);
int total=pay+ 200;
String laikas = duom.getStringExtra("laikas");
TextView rez = findViewById(R.id.rezultatas);
rez.setText("Pavardė: "+pavarde+"\n");
rez.append("Išsilavinimas: "+issilavinimas+"\n");
if(issilavinimas.equals("Aukštasis")){
rez.append("Gaunamas atlyginimas: " + total + "\n");
} else{
rez.append("Gaunamas atlyginimas: "+pay+ "\n");
}
rez.append("Keliasi: "+laikas+"\n");
}
when you + with String concatination is actually working there instead of addition
I connected my android studio program to a database with a login and register function.
Everytime I register my profile the username value is always "0" in the database.
Here's the code:
Register Activity
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
final EditText etAge = (EditText) findViewById(R.id.etAge);
final EditText etName = (EditText) findViewById(R.id.etName);
final EditText etUsername = (EditText) findViewById(R.id.etUsername);
final EditText etPassword = (EditText) findViewById(R.id.etPassword);
final Button bRegister = (Button) findViewById(R.id.bRegister);
bRegister.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final String name = etName.getText().toString();
final String username = etUsername.getText().toString();
final String password = etPassword.getText().toString();
final int age = Integer.parseInt(etAge.getText().toString());
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) {
Intent intent = new Intent(RegisterActivity.this, MainActivity.class);
RegisterActivity.this.startActivity(intent);
} else {
AlertDialog.Builder builder = new AlertDialog.Builder(RegisterActivity.this);
builder.setMessage("Register Failed")
.setNegativeButton("Retry", null)
.create()
.show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
};
RegisterRequest registerRequest = new RegisterRequest(name, username, age, password, responseListener);
RequestQueue queue = Volley.newRequestQueue(RegisterActivity.this);
queue.add(registerRequest);
}
});
}
}
Register Request
public class RegisterRequest extends StringRequest{
private static final String REGISTER_REQUEST_URL = "http://animotradings.000webhostapp.com/Register.php";
private Map<String, String> params;
public RegisterRequest(String name, String username, int age, String password, Response.Listener<String> listener){
super(Method.POST, REGISTER_REQUEST_URL, listener, null);
params = new HashMap<>();
params.put("name", name);
params.put("username", username);
params.put("password", password);
params.put("age", age + "");
}
#Override
public Map<String, String> getParams() {
return params;
}
}
Register.php File
<?php
$con = mysqli_connect("localhost", "id52837_animotradings", "password", "id52837_animotradings");
$name = $_POST["name"];
$username = $_POST["username"];
$age = $_POST["age"];
$password = $_POST["password"];
$statement = mysqli_prepare($con, "INSERT INTO user (name, username, age, password) VALUES (?, ?, ?, ?)");
mysqli_stmt_bind_param($statement, "siss", $name, $username, $age, $password);
mysqli_stmt_execute($statement);
$response = array();
$response["success"] = true;
echo json_encode($response);?>
I need help to filter empty edittext in login activity before trying to call method and execute query in mysql.. I am new in android development and getting really lost.. I followed a tutorial that works well in registration and login but no filtering or validation. Sad to say, I was not able to fully understand the steps on how each function / method are running.. I will appreciate if you can give me a link to a better page for a good tutorial which is not obsolete or have deprecated libraries.. I am using android 1.5.
I've been searching google and threads here but I could not find solution that is understandable by a newbie in android..
Here is the code of my Main.java which handles log in
public class Main extends AppCompatActivity implements View.OnClickListener {
EditText name, password;
String Name, Password;
Context ctx=this;
String NAME=null, PASSWORD=null, EMAIL=null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
name = (EditText) findViewById(R.id.main_name);
password = (EditText) findViewById(R.id.main_password);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
}
public void main_register(View v){
startActivity(new Intent(this,Register.class));
}
public void main_login(View v){
Name = name.getText().toString();
Password = password.getText().toString();
BackGround b = new BackGround();
b.execute(Name, Password);
}
#Override
public void onClick(View v) {
switch (v.getId()){
case R.id.main_login:
break;
}
}
class BackGround extends AsyncTask<String, String, String> {
#Override
protected String doInBackground(String... params) {
String name = params[0];
String password = params[1];
String data="";
int tmp;
try {
URL url = new URL("http://10.0.2.2/BirdBreedingManagement/scripts/login.php");
String urlParams = "name="+name+"&password="+password;
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setDoOutput(true);
OutputStream os = httpURLConnection.getOutputStream();
os.write(urlParams.getBytes());
os.flush();
os.close();
InputStream is = httpURLConnection.getInputStream();
while((tmp=is.read())!=-1){
data+= (char)tmp;
}
is.close();
httpURLConnection.disconnect();
return data;
} catch (MalformedURLException e) {
e.printStackTrace();
return "Exception: "+e.getMessage();
} catch (IOException e) {
e.printStackTrace();
return "Exception: "+e.getMessage();
}
}
#Override
protected void onPostExecute(String s) {
String err=null;
try {
JSONObject root = new JSONObject(s);
JSONObject user_data = root.getJSONObject("user_data");
NAME = user_data.getString("name");
PASSWORD = user_data.getString("password");
EMAIL = user_data.getString("email");
} catch (JSONException e) {
e.printStackTrace();
err = "Exception: "+e.getMessage();
}
Intent i = new Intent(ctx, Home.class);
i.putExtra("name", NAME);
i.putExtra("password", PASSWORD);
i.putExtra("email", EMAIL);
i.putExtra("err", err);
startActivity(i);
}
}
And here is the php script
try{
//$username = "jeel";
//$pssword = "23456";
$username = filter_input(INPUT_POST, 'name');
$pssword = filter_input(INPUT_POST, 'password');
if($username == "" ){
$results = "Invalid Entry";
echo json_encode(array("user_data"=>$results));
}else{
$stmt = $db->prepare('SELECT * '
. 'FROM users1 '
. 'WHERE name = :uname AND password = :password ');
$stmt->bindParam(':uname', $username);
$stmt->bindParam(':password', $pssword);
$stmt->execute();
$results = $stmt->fetch(PDO::FETCH_ASSOC);
if($results > 0 ){
$response = array();
echo json_encode(array("user_data"=>$results));
} else{
$results = "No Record Found";
echo json_encode(array("user_data"=>$results));
}
}
}catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
Thanks in advance.
Since you need to check the username and password fields empty or not before running the AsyncTask to get data from php. Modify the main_login(View v) method as below
public void main_login(View v){
Name = name.getText().toString();
Password = password.getText().toString();
if(Name==null || Password==null){
// can alert the user that either one of username or the password is empty by
Toast.makeText(getActivity(), "Username or the Password is empty",Toast.LENGTH_LONG).show();
// in here you can restart the current activity
startActivity(this,Main.class);
finish(); // to destroy the current activity
}
else{
BackGround b = new BackGround();
b.execute(Name, Password);
}
}
The answer of Kasun Siyambalapitiya lead me to make the code perform as expected with some adjustment made.. I am posting it here to share to others who's also looking for a code which they can try if the answer of Kasun didn't fit in their requirement..
`public void main_login(View v){
Name = name.getText().toString();
Password = password.getText().toString();
if(name.getText().length()==0){
Toast.makeText(getApplicationContext(),
"Please Enter your name", Toast.LENGTH_LONG).show();
Intent intent = getIntent();
startActivity(intent);
}else{
Intent intent = getIntent();
startActivity(intent);
BackGround b = new BackGround();
b.execute(Name, Password);
}
}`
I remove the finish command to avoid the application from closing and reopening.