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.
Related
I'm trying to learn the android and need your help!
Problem 1:
I store my data with ".push()" . How do I update the data on the random number that I declared with ".push()".
Once I update that only create new data but not a data update
Problem 2
Once I delete the data will delete whole data but not only the specific data.
This is my timetable.java.
public class Timetable extends AppCompatActivity{
//View
RecyclerView timeTable;
RecyclerView.LayoutManager layoutManager;
DatabaseReference counterRef,currentRef;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_ttable);
timeTable = (RecyclerView)findViewById(R.id.timeTable);
timeTable.setHasFixedSize(true);
layoutManager = new LinearLayoutManager(this);
timeTable.setLayoutManager(layoutManager);
Toolbar toolbar = (Toolbar)findViewById(R.id.toolBar);
toolbar.setTitle("Time Table");
setSupportActionBar(toolbar);
counterRef = FirebaseDatabase.getInstance().getReference("Time");
currentRef = counterRef.child(FirebaseAuth.getInstance().getCurrentUser().getUid());
//online list here
updateList();
}
private void updateList() {
FirebaseRecyclerAdapter<Time, ListTimeViewHolder> adapter = new FirebaseRecyclerAdapter<Time, ListTimeViewHolder>(
Time.class,
R.layout.time_table,
ListTimeViewHolder.class,
currentRef
) {
#Override
protected void populateViewHolder(final ListTimeViewHolder viewHolder, final Time model, int position) {
viewHolder.txtEmail.setText("Time (" +model.getTime()+ ")");
viewHolder.itemClickListenener1 = new ItemClickListenener1() {
#Override
public void onClick(View view, int position) {
showUpdateDeleteLog(model.getEmail(),model.getTime());
//alert dialog
// AlertDialog alertDialog = new AlertDialog.Builder(Timetable.this).create();
//
// // Setting Dialog Title
// alertDialog.setTitle("Message");
//
// // Setting Dialog Message
// alertDialog.setMessage("Unable to click");
//
// alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
// public void onClick(DialogInterface dialog, int which) {
// // Write your code here to execute after dialog closed
// Toast.makeText(getApplicationContext(), "OK", Toast.LENGTH_SHORT).show();
// }
// });
//
// // Showing Alert Message
// alertDialog.show();
}
private void showUpdateDeleteLog(String email, String time) {
AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(Timetable.this);
LayoutInflater inflater = getLayoutInflater();
final View dialogView = inflater.inflate(R.layout.update_dialog, null);
dialogBuilder.setView(dialogView);
final EditText editTextName = (EditText) dialogView.findViewById(R.id.editTextName);
final Button buttonUpdate = (Button) dialogView.findViewById(R.id.buttonUpdateArtist);
final Button buttonDelete = (Button) dialogView.findViewById(R.id.buttonDeleteArtist);
dialogBuilder.setTitle(email);
final AlertDialog b = dialogBuilder.create();
b.show();
buttonUpdate.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String name = editTextName.getText().toString().trim();
if (!TextUtils.isEmpty(name)) {
updateArtist(model.getEmail(),name);
b.dismiss();
}
}
});
buttonDelete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
deleteArtist(model.getEmail(),model.getTime());
b.dismiss();
}
});
}
private boolean deleteArtist(String email, String time) {
//getting the specified artist reference
DatabaseReference dR = FirebaseDatabase.getInstance().getReference("Time").child(FirebaseAuth.getInstance().getCurrentUser().getUid());
//removing artist
dR.removeValue();
Toast.makeText(getApplicationContext(), "Time is deleted", Toast.LENGTH_LONG).show();
return true;
}
private boolean updateArtist(String email, String time) {
//getting the specified artist reference
DatabaseReference dR = FirebaseDatabase.getInstance().getReference("Time").child(FirebaseAuth.getInstance().getCurrentUser().getUid());
//updating artist
Time artist = new Time(email,time);
dR.push().setValue(artist);
Toast.makeText(getApplicationContext(), "Time is updated", Toast.LENGTH_LONG).show();
return true;
}
};
}
};
adapter.notifyDataSetChanged();
timeTable.setAdapter(adapter);
}
}
Thanks for help! I'm newbie in Android need pro to help me up! Thanks guys and this platform!
First of all, why do you need to push() after Uid? As Uid is always unique, you can remove that to easily access the child node like below:
-Time
-UID
-email
-time
Problem 1: I store my data with ".push()" . How do I update the data on the random number that I declared with ".push()".
You need to get the reference of that particular node to update. For that, you can store the push Id along with email and time. Also, you don't need to push while updating.
private boolean updateArtist(String email, String time) {
//getting the specified artist reference
DatabaseReference dR = FirebaseDatabase.getInstance().getReference("Time").child(FirebaseAuth.getInstance().getCurrentUser().getUid()).child(timeModel.getPushId());
//updating artist
Time artist = new Time(email,time);
dR.updateChildren(artist); // instead use updateChildren
Toast.makeText(getApplicationContext(), "Time is updated", Toast.LENGTH_LONG).show();
return true;
}
Once I delete the data will delete whole data but not only the specific data
Same goes for problem 2, you need that particular node to delete,
private boolean deleteArtist(String email, String time) {
//getting the specified artist reference
DatabaseReference dR = FirebaseDatabase.getInstance().getReference("Time").child(FirebaseAuth.getInstance().getCurrentUser().getUid()).child(timeModel.getPushId());
//removing artist
dR.getRef().removeValue();
Toast.makeText(getApplicationContext(), "Time is deleted", Toast.LENGTH_LONG).show();
return true;
}
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));
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();
}
});
}
I'm trying to produce a password check before submitting my form, but I'm not getting the desired behavior. Basically no matter what the user inputs for either field, it will submit the new password from mConfirmPasswordField. What I want to have happen is that if the passwords do not match, hence if (!(mNewPassword.equals(mConfirmPassword)), then an alert dialog is displayed and nothing more. Based on the code below, this seems like it should be the case but it simply saves the new password to the user either way. What am I doing wrong here?
mNewPasswordField = (EditText)findViewById(R.id.newPassword);
mConfirmPasswordField = (EditText)findViewById(R.id.newPasswordAgain);
final String mNewPassword = mNewPasswordField.getText().toString();
final String mConfirmPassword = mConfirmPasswordField.getText().toString();
mNewPasswordField.setText(mNewPassword);
mConfirmPasswordField.setText(mConfirmPassword);
Button mButton = (Button) findViewById(R.id.submitPasswordChanges);
mButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (!(mNewPassword.equals(mConfirmPassword))) {
AlertDialog.Builder builder = new AlertDialog.Builder(ChangePasswordActivity.this);
builder.setMessage("Please check that you've entered and confirmed your new password!")
.setTitle("Error:")
.setPositiveButton(android.R.string.ok, null);
AlertDialog dialog = builder.create();
dialog.show();
} else {
setProgressBarIndeterminateVisibility(true);
//Update user
ParseUser user = ParseUser.getCurrentUser();
user.setPassword(mConfirmPasswordField.getText().toString());
user.saveInBackground(new SaveCallback() {
public void done(com.parse.ParseException e) {
// TODO Auto-generated method stub
LaunchPersonalGalleryIntent();
}
});
}
}
final String mNewPassword = mNewPasswordField.getText().toString();
final String mConfirmPassword = mConfirmPasswordField.getText().toString();
This will be executed when the EditText are still empty, so mNewPassword equals mConfirmPassword equals "".
The two String should be retrieved within the onClick:
..
mButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final String mNewPassword = mNewPasswordField.getText().toString();
final String mConfirmPassword = mConfirmPasswordField.getText().toString();
if (!(mNewPassword.equals(mConfirmPassword))) {
..
I believe what's wrong is that you are not updating your fields: you should check for new values right when the user clicks the button, like:
mButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mNewPassword = mNewPasswordField.getText().toString();
mConfirmPassword = mConfirmPasswordField.getText().toString();
if (!(mNewPassword.equals(mConfirmPassword))) {
....
} else {
....
}
}
});
I should mention for others passing through, that you will also need to include the following fields, along with the password strings, within the onClick method.
..
mButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mNewPasswordField = (EditText)findViewById(R.id.newPassword);
mConfirmPasswordField = (EditText)findViewById(R.id.newPasswordAgain);
final String mNewPassword = mNewPasswordField.getText().toString();
final String mConfirmPassword = mConfirmPasswordField.getText().toString();
mConfirmPasswordField.setText(mConfirmPassword);
if (!(mNewPassword.equals(mConfirmPassword))) {
..
I am trying to retrieve information from parse. In particular, I have added a condition where it would only return the list of users that have selected the same activity. In doing so, I unexpectedly receive the following error:
userActivitySelectionName cannot be resolved to a variable
It would essentially see which users have selected that particular activity name and return I randomly added this variable because I would like to retrieve the list of usersname who have selected that activity with the exception of the currentuser. I did not want to specificly point out a username since the list changes all the time, so was thinking of having a generic variable name such as userActivitySelectionName
Below is the entire code
public class MatchingActivity extends Activity {
private String currentUserId;
private ArrayAdapter<String> namesArrayAdapter;
private ArrayList<String> names;
private ListView usersListView;
private Button logoutButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.matching);
logoutButton = (Button) findViewById(R.id.logoutButton);
logoutButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
ParseUser.logOut();
Intent intent = new Intent(getApplicationContext(), LoginActivity.class);
startActivity(intent);
}
});
setConversationsList();
}
private void setConversationsList() {
currentUserId = ParseUser.getCurrentUser().getObjectId();
names = new ArrayList<String>();
ParseQuery<ParseUser> query = ParseUser.getQuery();
query.whereNotEqualTo("objectId", currentUserId);
query.whereEqualTo("ActivityName",userActivitySelectionName);
query.findInBackground(new FindCallback<ParseUser>() {
public void done(List<ParseUser> userList, ParseException e) {
if (e == null) {
for (int i=0; i<userList.size(); i++) {
names.add(userList.get(i).getUsername().toString());
}
usersListView = (ListView)findViewById(R.id.usersListView);
namesArrayAdapter =
new ArrayAdapter<String>(getApplicationContext(),
R.layout.user_list_item, names);
usersListView.setAdapter(namesArrayAdapter);
usersListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> a, View v, int i, long l) {
openConversation(names, i);
}
});
} else {
Toast.makeText(getApplicationContext(),
"Error loading user list",
Toast.LENGTH_LONG).show();
}
}
});
}
public void openConversation(ArrayList<String> names, int pos) {
ParseQuery<ParseUser> query = ParseUser.getQuery();
query.whereEqualTo("username", names.get(pos));
query.findInBackground(new FindCallback<ParseUser>() {
public void done(List<ParseUser> user, ParseException e) {
if (e == null) {
Intent intent = new Intent(getApplicationContext(), MessagingActivity.class);
intent.putExtra("RECIPIENT_ID", user.get(0).getObjectId());
startActivity(intent);
} else {
Toast.makeText(getApplicationContext(),
"Error finding that user",
Toast.LENGTH_SHORT).show();
}
}
});
}
}
Thanks in advance.
You have missed to declare this variable userActivitySelectionName. You need to declare this variable and assign the datatype, which is going to store.
say
String userActivitySelectionName = null;
As #Suresh said, You need to make a check of null value before you make any operations on it like
if(userActivitySelectionName!=null)
query.whereEqualTo("ActivityName",userActivitySelectionName);
Otherwise, you will get NullPointerException when you invoke methods or access properties of a null value.
If the value is null, you can set a meaningful value instead of null say empty string "" for a String variable