I am writing an android app to interact with a user database on a live server. I'm currently working on a 'register user' activity, which is supposed to simply add a user to the database, based on information they enter in an edit text field.
I am Using Android's Volley Library to accomplish this, using a simple String Request. The request is then added to a request queue. I am able to connect and get a response from the server, but when I attempt to update the database (add a user) nothing happens.
I understand that while using method=POST (which my server does), one must override the getParams() method specifying Key/Value pairs (where KEY is the post data from the php script and the value is the new data.)
Ive tried implementing my request queue as a singleton class, creating a custom header, and even tried modifying volley's method from POST to 'DEPRECATED_GET_OR_POST' with no luck. If someone can tell me what i'm doing wrong or what's missing id greatly appreciate it.
Here's my code:
//url to the registration page (on the server)
private static final String Register_URL = "http://www.wupx.com/arcums/profile/register.php";
//key values (these are the values in the DB)
public static final String Key_Username = "username";
public static final String Key_Realname = "name";
public static final String Key_Password = "password2";
public static final String Key_Email = "email";
//declare the editText field & Button
private EditText editTextUsername;
private EditText editTextName;
private EditText editTextEmail;
private EditText editTextPassword;
private EditText editTextPassword2;
private Button buttonRegister;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
//reference editText fields and buttons
editTextUsername = (EditText) findViewById(R.id.editTextUserName);
editTextName = (EditText) findViewById(R.id.editTextRealName);
editTextEmail = (EditText) findViewById(R.id.editTextEmail);
editTextPassword = (EditText) findViewById(R.id.editTextPassword);
editTextPassword2 = (EditText) findViewById(R.id.editTextPasswordAgain);
buttonRegister = (Button) findViewById(R.id.registerButton);
buttonRegister.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
registerUser();//calls the registerUser method.
}
});
}
//method to add user to the arcums database
private void registerUser() {
//print textview contents to logcat (debugging)
Log.d("log message", "entering register User method");
//values passed in from the user
final String Username = editTextUsername.getText().toString().trim();
final String Name = editTextName.getText().toString().trim();
final String Password = editTextPassword.getText().toString().trim();
final String Password2 = editTextPassword2.getText().toString().trim();
final String Email = editTextEmail.getText().toString().trim();
StringRequest stringRequest = new StringRequest(Request.Method.POST, Register_URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
// put a toast here
Toast.makeText(register.this, R.string.register_response , Toast.LENGTH_SHORT).show();
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// error toast
Toast.makeText(register.this, R.string.register_error, Toast.LENGTH_SHORT).show();
}
}){
//returns a hashmap with key value pairs
#Override
protected Map<String,String> getParams(){
Map<String, String> params = new HashMap<String, String>();
params.put(Key_Username, Username);
params.put(Key_Realname, Name);
params.put(Key_Password, Password2);
params.put(Key_Email, Email);
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
}
and here's a screenshot of my DB values in php myadmin:
DB values
note that not all fields need to be filled out in order to be added to the database- just name, username, email, and password.
the server itself has no GUI so i'm unable to post the PHP code at the moment. I hope someone can help with the information given!
Related
this time i want to edit and update the new values in Firebase Database. I have read the firebase documentation and followed the steps. https://firebase.google.com/docs/database/android/read-and-write#update_specific_fields
i need a litte orientation, following the documentation's steps i have modifed my POJO class,
as proof just add the interno key in the public Map<>...
public class Cow implements Serializable {
String interno;
public Cow() {
}
public Cow(String interno) {
this.interno = interno;
}
public String getInterno() {
return interno;
}
public void setInterno(String interno) {
this.interno = interno;
}
#Exclude
public Map<String, Object> toMap() {
HashMap<String, Object> result = new HashMap<>();
result.put("inte", interno);
return result;
}
}
This is my database in firebase
I have a recyclerview and I send the values to another activity by an intent, where i show the details, in this detailcow i want to modify the values.
This is the code:
public class Cowdetail extends AppCompatActivity {
DatabaseReference reference;
EditText tvinterno, tvsiniiga, tvpadre, tvmadre, tvnacimiento, tvinseminacion, tvtoro, tvestatus, tvnotas;
AppCompatImageView tvimage;
Button tvbutton;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.detailcow);
tvinterno = (EditText) findViewById(R.id.tvinterno);
tvsiniiga = (EditText) findViewById(R.id.tvsiniiga);
tvpadre = (EditText) findViewById(R.id.tvpadre);
tvmadre = (EditText) findViewById(R.id.tvmadre);
tvnacimiento = (EditText) findViewById(R.id.tvnacimiento);
tvinseminacion = (EditText) findViewById(R.id.tvinsemincion);
tvtoro = (EditText) findViewById(R.id.tvtoro);
tvestatus = (EditText) findViewById(R.id.tvestatus);
tvnotas = (EditText) findViewById(R.id.tvnotas);
tvimage = (AppCompatImageView) findViewById(R.id.tvimage);
tvbutton = findViewById(R.id.actualizar);
String vpadre = "";
String vmadre = "";
String vinterno = "";
String vsiniiga = "";
String vnacimiento = "";
String vinseminacion = "";
String vtoro = "";
String vestatus = "";
String vnotas = "";
String vurl;
Bundle extras = getIntent().getExtras();
if (extras !=null);
vinterno = extras.getString("keyint");
vsiniiga = extras.getString("keysin");
vmadre = extras.getString("madre");
vpadre = extras.getString("padre");
vnacimiento = extras.getString("nacimiento");
vinseminacion = extras.getString("inseminacion");
vtoro = extras.getString("toro");
vestatus = extras.getString("estatus");
vnotas = extras.getString("notas");
String image = extras.getString("img");
if (image == null|| image.isEmpty()){
tvimage.setImageResource(R.drawable.ic_imageinf);
} else {
Picasso.get().load(image).fit().centerCrop().into(tvimage);
}
tvpadre.setText(vpadre);
tvinterno.setText(vinterno);
tvsiniiga.setText(vsiniiga);
tvmadre.setText(vmadre);
tvnacimiento.setText(vnacimiento);
tvinseminacion.setText(vinseminacion);
tvtoro.setText(vtoro);
tvestatus.setText(vestatus);
tvnotas.setText(vnotas);
tvbutton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Update();
}
});
}
private void Update() {
DatabaseReference ref = FirebaseDatabase.getInstance().getReference().child("Vacas");
Map<String, Object> updates = new HashMap<String, Object>();
updates.put("inte", tvinterno);
ref.updateChildren(updates);
}
}
I have added a button to the layout, it has to save the edited values to firebase with the public void Update, Im doing something wrong, but in my short (almost nil) experience i can't see the error. also, i'm looking for a asesor who can guide me in my project, if someone want to talk about it, send me an email to: pjcm97#outlook.com
Firebase Realtime Database stores JSON data. You're trying to write an EditText object to it, which is not JSON data. So your code is most likely crashing.
private void Update() {
DatabaseReference ref = FirebaseDatabase.getInstance().getReference().child("Vacas");
Map<String, Object> updates = new HashMap<String, Object>();
updates.put("inte", tvinterno.getText().toString());
ref.updateChildren(updates);
}
I also highly recommend always checking the result of a write operation, to see if it succeeded, as shown in the documentation on adding a completion listener.
I am doing a register form for an app I'm creating. It includes first name, last name, email, phone number, password, birth day and gender. The gender in a radio group, obviously using radio buttons. I am using Volley for networking data. How do I pass the checked radio button value using volley?
Here is my java code so far:
public class B_Register extends AppCompatActivity implements View.OnClickListener {
public static final String REGISTER_URL = "http://10.0.0.245/register_alex's_app.php";
public static final String FNAME_REGISTER = "first_name";
public static final String LNAME_REGISTER = "last_name";
public static final String EMAIL_REGISTER = "email_register";
public static final String USERNAME_REGISTER = "username_register";
public static final String PHONE_NUMBER_REGISTER = "phone_register";
public static final String PASSWORD_REGISTER = "password_register";
public static final String BDAY_REGISTER = "bday_register";
private EditText fname;
private EditText lname;
private EditText email;
private EditText phone_number;
private EditText new_username;
private EditText new_password;
private EditText bday;
private RadioGroup gender;
private Button register_btn;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.b_register);
fname = (EditText)findViewById(R.id.first_name_et);
lname = (EditText)findViewById(R.id.last_name_et);
email = (EditText)findViewById(R.id.email_et);
phone_number = (EditText)findViewById(R.id.phone_et);
new_username = (EditText)findViewById(R.id.username_et);
new_password = (EditText)findViewById(R.id.password_et);
bday = (EditText)findViewById(R.id.bday_et);
gender = (RadioGroup)findViewById(R.id.gender_register);
register_btn = (Button)findViewById(R.id.register_btn);
register_btn.setOnClickListener(this);
}
public void onTermsOfUseClick(View view) {
}
#Override
public void onClick(View view) {
final String firstName = fname.getText().toString().trim();
final String lastName = lname.getText().toString().trim();
final String new_email = email.getText().toString().trim();
final String newPhoneNumber = phone_number.getText().toString().trim();
final String userName = new_username.getText().toString().trim();
final String newPassword = new_password.getText().toString().trim();
final String bDay = bday.getText().toString().trim();
if(TextUtils.isEmpty(firstName)) {
fname.setError("Please enter your first name.");
return;
}else if(TextUtils.isEmpty(lastName)) {
lname.setError("Please enter your last name.");
return;
}else if(TextUtils.isEmpty(new_email)) {
email.setError("Please enter your email.");
return;
}else if(TextUtils.isEmpty(newPhoneNumber)) {
phone_number.setError("Please enter your phone number.");
return;
}else if(TextUtils.isEmpty(userName)) {
new_username.setError("Please enter a valid username, 5-25 characters.");
return;
}else if (TextUtils.isEmpty(newPassword)) {
new_password.setError("Please enter valid password, 5-15 characters.");
}else if (TextUtils.isEmpty(bDay)) {
bday.setError("Please enter your birth day.");
}
}
}
To know the selected RadioButton id check:
// get selected radio button from radioGroup
int selectedId = radioGroup.getCheckedRadioButtonId();
// find the radiobutton by returned id
radioButton = (RadioButton) findViewById(selectedId);
String radio_value = radioButton.getText(); //by this you will get the male or female text which will be used in sending to server.
To send the data using Volley, add dependencies:
compile 'com.android.volley:volley:1.0.0'
Volley method to send data to server:
try {
// initialize request to connect the server, via POST method and Server URl
StringRequest stringRequest = new StringRequest(Request.Method.POST, your_url,
new Response.Listener<String>() {
// catch JSON response from server
#Override
public void onResponse(final String response) {
// response from server
}
},
// catch error response from server
new Response.ErrorListener() {
#Override
public void onErrorResponse(final VolleyError error) {
// trace error message from server
}
}){
#Override
protected Map<String,String> getParams(){
Map<String,String> params = new HashMap<String, String>();
// map the string value, to send in server
params.put("name",string_value_of_name);
params.put("sex",string_value_of_sex);
.... //like more
return params;
}
};
// execute the request
RequestQueue requestQueue = Volley.newRequestQueue(your_activity_context.this);
requestQueue.add(stringRequest);
}catch (final Exception e){
//catch exception
}
Must visit link for more details Here
Note: This example is just for demonstration purpose and does not contains exact answer asked by user, must apply your idea using shown process/logic.
access the radio button directly, instead of the radiogroup.
RadioButton male = (RadioButton) findViewById(R.id.male);
boolean isMale = male.isChecked();
remember to label your radiobuttons.
<RadioGroup
android:id="#+id/gender_register"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<RadioButton
android:id="#+id/male"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/radio_male"
android:checked="true" />
<RadioButton
android:id="#+id/female"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/radio_female" />
</RadioGroup>
i need to find a way to request an url with an edit text and display the json of that url. i have tried to use this code :
// URL to get contacts JSON
private static String id = null;
private static String url = "http://api.ccapp.it/v1/student/" + id + "/schedule/11";
// JSON Node names
private static final String TAG_LESSON = "class";
private static final String TAG_ROOM = "room";
private static final String TAG_TEACHER = "teacher";
// contacts JSONArray
JSONArray contacts = null;
// Hashmap for ListView
ArrayList<HashMap<String, String>> contactList;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.roosteralluz);
//number input
final EditText input = (EditText) findViewById(R.id.editText2);
//search button
Button btnSearch = (Button) findViewById(R.id.button34);
btnSearch.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
id = input.getText().toString();
// Calling async task to get json
new GetContacts().execute();
}
});
But when i try that code it returns this error: org.json.JSONException: Value <html><head><title>Slim of type java.lang.String cannot be converted to JSONObject
It is able to parse a link if i change id (look at code) to my own id. but i need to find a user his own id with an edittext.
Instead of using JsonArray, try Gson library to convert from Json to String and vice versa.
I have code to show a toast:
public void checkchallenge(View v) {
String algo = null;
if(algo == "123")
{
Context context = getApplicationContext();
CharSequence text = "You have " + messages ;
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
...
the error in eclipse that I am getting is:
messages cannot be resolved to a variable
The variable "messages" is being called in some code above it:
String messages = c.getString(TAG_MESSAGES);
final TextView messages1 = (TextView)findViewById(R.id.envelope);
Maybe it's because I don't know Java too well but why isn't my string variable "messages" or "messages1" getting recognized in my code? I have a feeling it has to do with permissions of the code but when I remove the "final" part off of the messages 1 TextView I get the same error.
Confused!
Here is the entire code to the class:
public class Homepage extends Activity {
//URL to get JSON Arrays
public static String url = "http://10.0.2.2/android/SQL.php?username='";
public static String usernamefromlogin;
public static TextView errorchecking;
//JSON Node Names
private static final String TAG_USER = "users";
private static final String TAG_WINS = "wins";
private static final String TAG_MESSAGES = "messages";
private static final String TAG_NAME = "fullname";
private static final String TAG_DISPLAY = "displayname";
private static final String TAG_EMAIL = "email";
private static final String TAG_PW = "password";
private static final String TAG_CREATED = "created_at";
private static final String TAG_UPDATED = "updated_at";
JSONArray user = null;
//disable back button
#Override
public void onBackPressed() {
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.reshomepage);
//Get login name from EditText in login screen and concatenate it to PHP user-name for _GET command in 3 steps.
//Step 1: Get intent from previous activity
Intent intent = getIntent();
getIntent().getExtras();
//Step 2: convert intent (intent) to string called "usernamefromlogin" //error checking in log cat to see value of "usernamefromlogin"
usernamefromlogin = intent.getExtras().getString("username2"); Log.d("log of usernamefromlogin", usernamefromlogin);
//Step 3: take the string "url" and add string "usernamefromlogin" after it
String url5 = url.concat(usernamefromlogin);
String url6 = url5.concat("'");
//find TextView "errorchecking" and send the string "url6" to it so it can display in log cat
Log.d("log of URL6 in it's final state", url6);
// Creating new JSON Parser
JSONParser jParser = new JSONParser();
// Getting JSON from URL from the final string "url6"
JSONObject json = jParser.getJSONFromUrl(url6);
//Logcat check value for TAG_USER
try {
// Getting JSON Array
user = json.getJSONArray(TAG_USER);
JSONObject c = user.getJSONObject(0);
// Storing JSON item in a String Variable
String name = c.getString(TAG_NAME);
String messages = c.getString(TAG_MESSAGES);
String wins = c.getString(TAG_WINS);
String display = c.getString(TAG_DISPLAY);
String email = c.getString(TAG_EMAIL);
String pw = c.getString(TAG_PW);
String created = c.getString(TAG_CREATED);
String updated = c.getString(TAG_UPDATED);
//Importing TextView
final TextView name1 = (TextView)findViewById(R.id.tvfullname);
TextView messages1 = (TextView)findViewById(R.id.envelope);
final TextView wins1 = (TextView)findViewById(R.id.wins);
final TextView created1 = (TextView)findViewById(R.id.tvcreated_at);
final TextView updated1 = (TextView)findViewById(R.id.tvupdated_at);
//Set JSON Data in its respectable TextView
name1.setText("Hello " + name);
updated1.setText("Your last login was " + updated);
// print error if applicable.
} catch (JSONException e) {
e.printStackTrace();
}
}
public void checkchallenge(View v) {
String algo = null;
if(algo == "123")
{
// display pop up message (toast)
Context context = getApplicationContext();
CharSequence text = "You have " + messages1 ;
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
}else
{
// display pop up message (toast)
Context context = getApplicationContext();
CharSequence text = "You have no new Challenges";
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
}
}
}
I suspect the code is making the String messages and TextView local variables inside a method. If you want to access these objects within the entire class they should be declared as fields.
public SomeClass{
String messages;
final TextView messages1;
public void checkchallenge(View v) {
//Method implementation
}
public void someOtherMethod(){
this.messages = c.getString(TAG_MESSAGES);
this.messages1 = (TextView)findViewById(R.id.envelope);
}
}
If your messages variable is defined inside other method it won't be seen at the point you showed.
I'm trying to save user entries into a form, but for some reason I can not get it to work. When I kill the application and restart the data does not appear.
My aim is that if a user is halfway through completing the form and the application is killed, that when the application relaunches the entries will still remain. Any guidance would be much appreciated.
public class MainActivity extends Activity {
public final static String EXTRA_FROM = "com.example.assignment1.FROM";
public final static String EXTRA_TO = "com.example.assignment1.TO";
public final static String EXTRA_CC = "com.example.assignment1.CC";
public final static String EXTRA_BCC = "com.example.assignment1.BCC";
public final static String EXTRA_SUBJECT = "com.example.assignment1.SUBJECT";
public final static String EXTRA_COMPOSE = "com.example.assignment1.COMPOSE";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
#Override
protected void onSaveInstanceState(Bundle outState)
{
super.onSaveInstanceState(outState);
EditText emailFrom =(EditText) findViewById(R.id.editEmailFrom);
EditText emailTo =(EditText) findViewById(R.id.editEmailTo);
EditText emailCc =(EditText) findViewById(R.id.editEmailCc);
EditText emailBcc =(EditText) findViewById(R.id.editEmailBcc);
EditText emailSubject =(EditText) findViewById(R.id.editEmailSubject);
EditText emailCompose =(EditText) findViewById(R.id.editEmailCompose);
String from = emailFrom.getText().toString();
String to = emailTo.getText().toString();
String cc = emailCc.getText().toString();
String bcc = emailBcc.getText().toString();
String subject = emailSubject.getText().toString();
String compose = emailCompose.getText().toString();
outState.putString(EXTRA_FROM, from);
outState.putString(EXTRA_TO, to);
outState.putString(EXTRA_CC, cc);
outState.putString(EXTRA_BCC, bcc);
outState.putString(EXTRA_SUBJECT, subject);
outState.putString(EXTRA_COMPOSE, compose);
}
#Override
protected void onRestoreInstanceState(Bundle savedState)
{
EditText emailFrom =(EditText) findViewById(R.id.editEmailFrom);
EditText emailTo =(EditText) findViewById(R.id.editEmailTo);
EditText emailCc =(EditText) findViewById(R.id.editEmailCc);
EditText emailBcc =(EditText) findViewById(R.id.editEmailBcc);
EditText emailSubject =(EditText) findViewById(R.id.editEmailSubject);
EditText emailCompose =(EditText) findViewById(R.id.editEmailCompose);
String from = savedState.getString(EXTRA_FROM);
String to = savedState.getString(EXTRA_TO);
String cc = savedState.getString(EXTRA_CC);
String bcc = savedState.getString(EXTRA_BCC);
String subject = savedState.getString(EXTRA_SUBJECT);
String compose = savedState.getString(EXTRA_COMPOSE);
emailFrom.setText(from);
emailTo.setText(to);
emailCc.setText(cc);
emailBcc.setText(bcc);
emailSubject.setText(subject);
emailCompose.setText(compose);
}
public void emailSend (View sendButton)
{
Intent intent = new Intent(this,DisplayEmailActivity.class);
EditText emailFrom =(EditText) findViewById(R.id.editEmailFrom);
EditText emailTo =(EditText) findViewById(R.id.editEmailTo);
EditText emailCc =(EditText) findViewById(R.id.editEmailCc);
EditText emailBcc =(EditText) findViewById(R.id.editEmailBcc);
EditText emailSubject =(EditText) findViewById(R.id.editEmailSubject);
EditText emailCompose =(EditText) findViewById(R.id.editEmailCompose);
String from = emailFrom.getText().toString();
String to = emailTo.getText().toString();
String cc = emailCc.getText().toString();
String bcc = emailBcc.getText().toString();
String subject = emailSubject.getText().toString();
String compose = emailCompose.getText().toString();
intent.putExtra(EXTRA_FROM,from);
intent.putExtra(EXTRA_TO,to);
intent.putExtra(EXTRA_CC,cc);
intent.putExtra(EXTRA_BCC,bcc);
intent.putExtra(EXTRA_SUBJECT,subject);
intent.putExtra(EXTRA_COMPOSE,compose);
startActivity(intent);
}
}
To save a few items your best shot is to use SharedPreferences.
I've put an example some time ago on this post: SharedPreferences.
Good luck.
When I kill the application and restart the data does not appear.
Of course. If you kill the application (e.g., task killer), your saved instance state goes away. To handle this scenario, you need to persist your data to a file, database, etc.
To test whether or not onSaveInstanceState() works, rotate the screen or do some other type of configuration change.