I have 2 EditText fields which are email and name. When the user clicks a button I get the value of those 2 fields in the AsyncTask onPreExecute() method. My question is how can I now pass that value to the doInBackground() method and insert it into the String Answers ? I have learned that you should not pass UI items into the doInBackground() . I have been searching on here and testing different variations of the code but keep getting Null values.
private class myprofile extends AsyncTask<String,Void,Boolean> {
#Override
protected void onPreExecute() {
super.onPreExecute();
Email= (EditText)findViewById(R.id.email);
String email= Email.getText().toString();
Name= (EditText)findViewById(R.id.name);
String name= Name.getText().toString();
}
#Override
protected Boolean doInBackground(String... params) {
String email = params[0];
String name = params[1];
String Answers="email="+email+"&name="+name;
return null;
}
// #Override
protected void onPostExecute(Boolean result) {
}
}
There are a lot of ways to do this. It looks like you're set up for passing them into execute().
1) Pass in to AsyncTask.execute()
String email= Email.getText().toString();
String name= Name.getText().toString();
new myprofile().execute(email, name);
2) Pass in to constructor
private class myprofile extends AsyncTask<Void,Void,Boolean> {
private String email;
private String name;
public myprofile(String email, String name){
this.email = email;
this.name = name;
}
...
}
String email= Email.getText().toString();
String name= Name.getText().toString();
new myprofile(email, name).execute();
3) Retrieve in onPreExecute()
private String email;
private String name;
protected void onPreExecute() {
super.onPreExecute();
email = Email.getText().toString();
name = Name.getText().toString();
}
Related
//1..i want to send pic from one activity and data from another activity into same database firebase having 1 same id instead of creating 2 different ids(one for pic and another for data(name,notice etc as mentioned below))
enter image description here here is an idea ..for storing different activities data into same id firebase..this isnot my example but i have same problem...but i dont want two ids ,i want one id for pic Uri and data as well.
//2..Here is my 1st activity..In this activity i have camera to capture image then send this Pic Uri to upload class(gettersetter class) for storing into database firebase. here i have sent pic Uri to gettersetter class.
popQuickActivity.java
if(imgUri!=null){
final ProgressDialog progressDialog=new ProgressDialog(this);
progressDialog.setTitle("Uploading.....");
progressDialog.show();
StorageReference fileReference=mStorageRef.child(System.currentTimeMillis()+"." +getFileExtension(imgUri));
fileReference.putFile(imgUri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Handler handler=new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
progressDialog.dismiss();
}
},500);
Toast.makeText(popQuickActivity.this, "Uploaded successfull", Toast.LENGTH_LONG).show();
String downloadUrl = taskSnapshot.getDownloadUrl().toString();
upload upload=new upload(downloadUrl);
String uploadId=mDatabaseRef.push().getKey();
mDatabaseRef.child(uploadId).setValue(upload);
}
// here is my upload(gettersetter class)...img uri is here
upload.java
public class upload {
private String mImageUri;
private String mNoticeNo;
private String mName;
private String mDate;
private String mCharge;
private String mDescription;
private String mCnic;
public upload(){
}
public upload(String name, String noticeNo, String date, String amountCharge, String des, String cnic, String description) {
if(description.trim().equals("")){
description="No Description";
}
mName=name;
mCharge=amountCharge;
mDate=date;
mCnic=cnic;
mNoticeNo=noticeNo;
mDescription=description;
}
public upload(String downloadUrl) {
mImageUri=downloadUrl;
}
public String getmImageUri() {
return mImageUri;
}
public void setmImageUri(String mImageUri) {
this.mImageUri = mImageUri;
}
public String getmNoticeNo() {
return mNoticeNo;
}
public void setmNoticeNo(String mNoticeNo) {
this.mNoticeNo = mNoticeNo;
}
public String getmName() {
return mName;
}
public void setmName(String mName) {
this.mName = mName;
}
public String getmDate() {
return mDate;
}
public void setmDate(String mDate) {
this.mDate = mDate;
}
public String getmCharge() {
return mCharge;
}
public void setmCharge(String mCharge) {
this.mCharge = mCharge;
}
public String getmDescription() {
return mDescription;
}
public void setmDescription(String mDescription) {
this.mDescription = mDescription;
}
public String getmCnic() {
return mCnic;
}
public void setmCnic(String mCnic) {
this.mCnic = mCnic;
}
}
//here is my another activity..here i am sending data(name,noticeNo,date etc) to gettersetter class(upload class) same place in firebase...but it is creating two different id instead of creating one id and storing both img and data in one same id.
QuickChallan.java
public void doIt(View view) {
String Name=name.getText().toString().trim();
String NoticeNo=noticeno.getText().toString().trim();
String Cnic=cnic.getText().toString().trim();
String AmountCharge=amountcharge.getText().toString().trim();
String Date=date.getText().toString().trim();
String Des=des.getText().toString().trim();
upload upload=new upload(Name,NoticeNo,Date,AmountCharge,Des,Cnic,Des);
String uploadId=mDatabaseRef.push().getKey();
mDatabaseRef.child(uploadId).setValue(upload);
}
It creates two random ID, because in the activity popQuickActivity.java you are creating an ID and storing it in the variable uploadId.
Then in the activity QuickChallan.java you also create another ID and store it in the variable uploadId but this time u add different data.
To only use one ID. In the first activity (popQuickActivity.java) after storing the image url under the id, you need to add it inside an intent:
Intent intent = new Intent(activity2.this, activity1.class);
intent.putExtra("id", uploadId);
startActivity(intent);
Then in the second activity :
Bundle bundle = getIntent().getExtras();
String id = bundle.getString("id");
mDatabaseRef.child(id).setValue(upload);
This way in the second activity you don't create another ID using the push(), therefore you ofcourse you have to remove uploadId=mDatabaseRef.push().getKey() since this line is creating another ID.
Im trying to get Geolocation JSON data with URL from this API http://ip-api.com/json/?fields=query,country,city and show IP Address, City, Country to my TextView layout
Response:
{"city":"Bandung","country":"Indonesia","query":"127.0.0.1"}
MainActivity.java:
public class MainActivity extends AppCompatActivity {
Button start;
TextView textView;
RequestQueue requestQueue;
public static TextView data;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
start = (Button) findViewById(R.id.lokasi);
textView = (TextView) findViewById(R.id.textViewLok);
requestQueue = Volley.newRequestQueue(this);
start.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View ){
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, "http://ip-api.com/json/?fields=query,country,city",
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
JSONObject jsonObject = new JSONObject(response);
String city = jsonObject.getString("city");
String country= jsonObject.getString("country");
String ip = jsonObject.getString("query");
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("VOLLEY","ERROR");
}
}
)
}
}
}
}
You need to put your response (that you get from the api) into a JSONObject.
JSONObject jsonObject = new JSONObject(myResponse);
After that you can parse the jsonObject.
String city = jsonObject.getString("city");
String country= jsonObject.getString("country");
String ip = jsonObject.getString("query");
Then just put the strings into your text view.
UPDATE:
Just change the onResponse to this.
#Override
public void onResponse(JSONObject response) {
String city = response.getString("city");
String country= response.getString("country");
String ip = response.getString("query");
}
Step 1. Make One POJO for your Response like Example.java
public class Example {
#SerializedName("city")
#Expose
private String city;
#SerializedName("country")
#Expose
private String country;
#SerializedName("query")
#Expose
private String query;
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
public String getQuery() {
return query;
}
public void setQuery(String query) {
this.query = query;
}
}
Step 2. parse a string response
Example ex = gson.fromJson(json, BoxSearch.class);
Step 3. Now get value from POJO
String city = ex.getCity();
String country= ex.getQuery();
String ip = ex.getCountry();
Step 4. Set value in Textview
txtCity.setText(city);
txtCountry.setText(country);
txtIp .setText(ip);
I am doing a Register login activities for my app and when I register all the info are going to my database except for the Email. I got a "0" as value in the database even if I entered a normal email address.
I checked everything in my code and my php files, but cannot find the problem.
public class createAccountActivity extends AppCompatActivity implements View.OnClickListener {
EditText etUsername,etEmail, etAge, etPassword;
Button register;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.createaccount);
etUsername = (EditText) findViewById(R.id.create_username);
etEmail = (EditText) findViewById(R.id.create_email);
etAge = (EditText) findViewById(R.id.create_age);
etPassword = (EditText) findViewById(R.id.create_password);
etConfirmPassword = (EditText) findViewById(R.id.confirm_password);
}
#Override
public void onClick (View v) {
switch (v.getId()){
case R.id.register:
String username = etUsername.getText().toString();
String email = etEmail.getText().toString();
int age = Integer.parseInt(etAge.getText().toString());
String password = etPassword.getText().toString();
User user = new User(username, email, age, password);
registerUser(user);
break;
}
}
private void registerUser(User user) {
ServerRequests serverRequest = new ServerRequests(this);
serverRequest.storeUserDataInBackground(user, new GetUserCallback() {
#Override
public void done(User returnedUser) {
Intent loginIntent = new Intent(createAccountActivity.this, Login.class);
startActivity(loginIntent);
}
});
}
}
In my UserLocalStore.java I got
public void storeUserData(User user) {
SharedPreferences.Editor userLocalDatabaseEditor = userLocalDatabase.edit();
userLocalDatabaseEditor.putString("username", user.username);
userLocalDatabaseEditor.putString("email", user.email);
userLocalDatabaseEditor.putString("password", user.password);
userLocalDatabaseEditor.putInt("age", user.age);
userLocalDatabaseEditor.commit();
}
My class User
public class User {
String username, email, password;
int age;
public User(String username,String email , int age, String password) {
this.username = username;
this.age = age;
this.email = email;
this.password = password;
}
public User(String username, String password) {
this(username,"", -1, password);
}
}
And my ServerRequests.class
if (jObject.length() != 0){
Log.v("happened", "2");
String username = jObject.getString("username");
int age = jObject.getInt("age");
String email = jObject.getString("email");
returnedUser = new User(username, user.username, age, user.password);
}
} catch (Exception e) {
e.printStackTrace();
}
return returnedUser;
}
Well it seems that returnedUser in ServerRequests.class puts user.username where the email should be, since you have declared it as
public User(String username,String email , int age, String password)
and it says
returnedUser = new User(username, user.username, age, user.password);
in the other file.
The Answer was simple, In my register.php it was writen "siss" and not "ssis" so it was seen as an int.
mysqli_stmt_bind_param($statement, "siss", $username, $email, $age, $password);
correct one :
mysqli_stmt_bind_param($statement, "ssis", $username, $email, $age, $password);
Sorry I should have provide it (php file), no wonder I didn't get a solution.
I'm trying to do field validation for an int in android studio. The code for the field is as follows;
public class Register extends ActionBarActivity implements View.OnClickListener {
EditText etName, etAge, etUsername, etPassword;
Button bRegister;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
etName = (EditText) findViewById(R.id.etName);
etAge = (EditText) findViewById(R.id.etAge);
etUsername = (EditText) findViewById(R.id.etUsername);
etPassword = (EditText) findViewById(R.id.etPassword);
bRegister = (Button) findViewById(R.id.bRegister);
bRegister.setOnClickListener(this);
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.bRegister:
String name = etName.getText().toString();
String username = etUsername.getText().toString();
String password = etPassword.getText().toString();
String ageText = etAge.getText().toString();
if(! TextUtils.isEmpty(ageText)) {
int age = Integer.parseInt(ageText);
}
if(name.length()==0)
{
etName.requestFocus();
etName.setError("Please don't leave the name field empty.");
}else if(username.length()==0)
{
etUsername.requestFocus();
etUsername.setError("Please don't leave the username field empty.");
}else if(password.length()==0)
{
etPassword.requestFocus();
etPassword.setError("Please don't leave the password field empty.");
}/*else if(age == null)
{
etAge.requestFocus();
etAge.setError("Please don't leave the age field empty.");
}*/
else if(!name.matches("[a-zA-Z]"))
{
etName.requestFocus();
etName.setError("Please only use alphabetic characters");
}else{
User user = new User(name, age, username, password);
registerUser(user);
}
break;
}
}
private void registerUser(User user) {
ServerRequest serverRequest = new ServerRequest(this);
serverRequest.storeUserDataInBackground(user, new GetUserCallback() {
#Override
public void done(User returnedUser) {
Intent loginIntent = new Intent(Register.this, Login.class);
startActivity(loginIntent);
}
});
}
}
But I can't get the int age validated, it keps giving me this error;
java.lang.NumberFormatException: Invalid int: ""
User class
public class User {
String name, username, password;
int age;
public User(String name, int age, String username, String password) {
this.name = name;
this.age = age;
this.username = username;
this.password = password;
}
Try this:
String ageText = etAge.getText().toString();
int age = 0;
if(! TextUtils.isEmpty(ageText)) // If EditText is not empty
age = Integer.parseInt(ageText); // parse its content to integer
// Continue validation...
instead of
int age = Integer.parseInt(etAge.getText().toString());
I believe you are looking for something like this:
String ageString = "25"; //age will be null if it is empty or not a number
Integer age = null;
try {
age = Integer.parseInt(ageString);
} catch (NumberFormatException e) {}
if (age == null) {
//enter age
}
I just made my first POJO Class, which takes two Strings and one String array and combines them into one (for lack of a better term) package. Everything seemed to be working well until the very last part. Here is my code:
class dataPOJO extends Phone_Save {
String fName;
String cName;
String[] cText;
public dataPOJO() {
fName = file_name;
cName = cname;
cText = ctext;
}
public String getName() {
return cName;
}
public void setName(String cName) {
this.cName = cName;
}
public String getFileName() {
return fName;
}
public void setFileName(String fName) {
this.fName = fName;
}
public String[] getRemainder() {
return cText;
}
public void getRemainder(String[] cText) {
this.cText = cText;
}
public String toString() {
String savePackage = "File Name: " + getFileName() + "\n";
savePackage += "CName: " + getName() + "\n";
savePackage += getRemainder() + "\n";
return savePackage;
}
public static void main(String[] args) {
dataPOJO combine = new dataPOJO();
combine.setName(cName);
combine.setFileName(fName);
combine.setRemainder(cText);
System.out.println(combine);
}
}
Unfortunately, I cannot setName as any of the strings I referenced above. To me, it seems like I should be able to. And I can't put a default name in there like:
combine.setName("default name");
because the name comes from user input and is different every time. My question is how can I set the value of the String array below to the strings like cName referenced above?
Thanks!
Added code
public class Phone_Save extends ActionBarActivity {
String[] ctext;
public int doc_id = 0;
String cname;
Button fileName;
Button loadText;
String file_name;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_phone_save);
Intent save_intent = getIntent();
Bundle bundle = save_intent.getExtras();
EditText file_name_edit = (EditText) findViewById(R.id.editText);
final TextView loaded_text = (TextView)findViewById(R.id.loaded_text);
file_name = file_name_edit.getText().toString();
fileName = (Button) findViewById(R.id.fName);
loadText = (Button) findViewById(R.id.loadText);
if (bundle != null) {
ctext = bundle.getStringArray("confirmed_text");
cname = bundle.getString("confirmed_name");
}
fileName.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
new dataPOJO();
}
});
}
First, dataPOJO should not be extending Phone_Save. There's nothing dataPOJO needs to do that depends on it being an Activity (at least based on what you've shown us). If you want to have that class to store those information in one place, that's fine; otherwise just store them in Phone_Save itself. Right now you appear to be trying to do both at once, which is confusing.
Second, calling new dataPOJO() in the OnClickListener allocates an object, then discards it since it is not being assigned to anything. It's also a completely different object and has no effect on this one.
Third, there's no use for that main method on Android, it will never be called (unless you call it yourself, which would be pointless anyway).
I would make dataPOJO its own class that doesn't extend anything and get rid of the no-arg constructor (or leave it but remove the code that's in there). In your Phone_Save's onCreate method, you can just make a dataPOJO and hang onto it.
public class DataPojo {
String fName;
String cName;
String[] cText;
public dataPOJO() {}
/* all the other stuff */
}
public class Phone_Save extends ActionBarActivity {
private DataPojo dataPojo;
// other members
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
dataPojo = new DataPojo();
Intent intent = getIntent();
dataPojo.setName(intent.getStringExtra("confirmed_name"));
dataPojo.setRemainder(intent.getStringExtra("confirmed_text"));
// other stuff...
}
}