Autoclick saveButton in every change of string in editText - java

Receive SMS then set EditText to msgBody
public class SmsBroadcastReceiver extends BroadcastReceiver {
//.....
((EditText)MainActivity.mThis.findViewById(R.id.editTextName)).setText(msgBody);}
The error is this in View cannot be applied to android.view.View.Onclicklistiner
//onCreate
buttonSave.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
buttonSave.performClick(this);
}
});
the message will automatically save to SQLite and sync to Mysql when buttonSave is click
private void saveNameToServer() {
final ProgressDialog progressDialog = new ProgressDialog(this);
progressDialog.setMessage("Saving Name...");
progressDialog.show();
final String name = editTextName.getText().toString().trim();
StringRequest stringRequest = new StringRequest(Request.Method.POST, URL_SAVE_NAME,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
progressDialog.dismiss();
try {
JSONObject obj = new JSONObject(response);
if (!obj.getBoolean("error")) {
//if there is a success
//storing the name to sqlite with status synced
saveNameToLocalStorage(name, NAME_SYNCED_WITH_SERVER);
} else {
//if there is some error
//saving the name to sqlite with status unsynced
saveNameToLocalStorage(name, NAME_NOT_SYNCED_WITH_SERVER);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
progressDialog.dismiss();
//on error storing the name to sqlite with status unsynced
saveNameToLocalStorage(name, NAME_NOT_SYNCED_WITH_SERVER);
}
}) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
params.put("name", name);
return params;
}
};
VolleySingleton.getInstance(this).addToRequestQueue(stringRequest);
}
#Override
public void onClick(View view) {
saveNameToServer();
}
Are there other ways to auto click button when EditText value changes?

Instead of invoking the click buttonSave.performClick(this); just simply invoke saveNameToServer(); method to save your data.
buttonSave.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
//buttonSave.performClick(this); // remove, not required
saveNameToServer(); // save your data
}
});

Related

how to display image without onclick button

help guys how to display image without using a button, I tried to put it on create but not working and I tried to make it as a function but still not working,but when in button (on click) it show image. I want to show the image without clicking the button.
I want to load the image without clicking the button, so when the user come the image automatically load without push of a button.
public class MainActivity extends AppCompatActivity {
TextView textViewdatashow;
EditText editTextvalue;
ImageView imageView;
Button buttonfetch;
String url ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textViewdatashow = (TextView) findViewById(R.id.tvshowdata);
editTextvalue = (EditText) findViewById(R.id.etvalue);
imageView = (ImageView) findViewById(R.id.image);
buttonfetch = (Button) findViewById(R.id.buttonfetchdata);
buttonfetch.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String id = editTextvalue.getText().toString();
url = "https://PASTE_YOUR_IMAGE_URL"+id+".jpg";
getData();
}
});
}
private void getData() {
String id = editTextvalue.getText().toString().trim();
if (id.equals("")) {
Toast.makeText(this, "Check Detail!", Toast.LENGTH_LONG).show();
return;
}
String url = Config.DATA_URL + editTextvalue.getText().toString().trim();
StringRequest stringRequest = new StringRequest(url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
showJSONS(response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(MainActivity.this, error.getMessage().toString(), Toast.LENGTH_LONG).show();
}
});
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
private void showJSONS(String response) {
String name = "";
try {
JSONObject jsonObject = new JSONObject(response);
JSONArray result = jsonObject.getJSONArray(Config.JSON_ARRAY);
JSONObject collegeData = result.getJSONObject(0);
name = collegeData.getString(Config.KEY_NAME);
} catch (JSONException e) {
e.printStackTrace();
}
textViewdatashow.setText("" + name);
ImageRetriveWithPicasso();
}
private void ImageRetriveWithPicasso() {
Picasso.get()
.load(url)
.placeholder(R.drawable.imageholder)
.into(imageView);
}
}
Put this code inside on create view
final Handler myHandler = new
Handler(Looper.getMainLooper());
new Thread(new Runnable() {
#Override
public void run() {
myHandler.post(new Runnable() {
#Override
public void run() {
getData()
}
});
}
})).start();
}

Android Studio SharedPrerefernces is not working another activity

I have created two activities SignUp and Login.
Also, I have SharedPreferences which get edittext value. When I call SharedPreferences(getNomre) inside onCreate It works but doesn't work as global variable. I want to declare a variable named mobileNomre for using put to Constant.mobile. How can I send Shared Preference value to Constant.mobile?
p.s: Acitivity code is too large. I noted some parts of them.
Thanks
SignUpActivity:
public void SignUpWithEmail(View view) {
if (!validateForm()) {
return;
}
showProgressDialog();
final String email = edtEmail.getText().toString();
final String password = edtPassword.getText().toString();
final String name = edtName.getText().toString();
final String mobile = edtMobile.getText().toString();
Session.setNomre(getApplicationContext(),"nomreler",mobile);
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
UserProfileChangeRequest profileUpdates = new UserProfileChangeRequest.Builder()
.setDisplayName(name).build();
assert user != null;
user.updateProfile(profileUpdates)
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()) {
}
}
});
sendEmailVerification();
} else {
hideProgressDialog();
try {
throw Objects.requireNonNull(task.getException());
} catch (FirebaseAuthInvalidCredentialsException | FirebaseAuthInvalidUserException | FirebaseAuthUserCollisionException invalidEmail) {
inputEmail.setError(invalidEmail.getMessage());
} catch (Exception e) {
e.printStackTrace();
inputEmail.setError(e.getMessage());
}
}
}
});
}
LoginActivity:
public class LoginActivity extends AppCompatActivity {
String TAG = "LoginActivity";
int RC_SIGN_IN = 9001;
CallbackManager mCallbackManager;
String token;
String mobileNomre = Session.getNomre(getApplicationContext(),"nomreler","");
public static FirebaseAuth mAuth;
GoogleSignInClient mGoogleSignInClient;
TextView tvPrivacy, tvTest;
ProgressDialog mProgressDialog;
public TextInputEditText edtEmail, edtPassword;
public TextInputLayout inputEmail, inputPass;
public void UserSignUpWithSocialMedia( final String mobileNomre,
final String fCode,
final String referCode,
final String name,
final String email,
final String profile,
final String type) {
StringRequest strReq = new StringRequest(Request.Method.POST, Constant.QUIZ_URL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject obj = new JSONObject(response);
if (obj.getString("error").equals("false")) {
JSONObject jsonobj = obj.getJSONObject("data");
if (!jsonobj.getString(Constant.status).equals(Constant.DE_ACTIVE)) {
Session.saveUserDetail(getApplicationContext(),
jsonobj.getString(Constant.userId),
jsonobj.getString(Constant.name),
jsonobj.getString(Constant.email),
jsonobj.getString(Constant.mobile),
jsonobj.getString(Constant.PROFILE), referCode);
User user = new User(
jsonobj.getString(Constant.mobile),
jsonobj.getString(Constant.name),
jsonobj.getString(Constant.email),
"0",
false,
jsonobj.getString(Constant.PROFILE),
"0",
token,
jsonobj.getString(Constant.userId));
FirebaseDatabase.getInstance().getReference("user").child(FirebaseAuth.getInstance().
getCurrentUser().getUid()).setValue(user).
addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task1) {
Intent i = new Intent(getApplicationContext(), MainActivity.class);
i.putExtra("type", "default");
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(i);
finish();
}
});
hideProgressDialog();
} else
setSnackBarStatus();
} else {
LoginManager.getInstance().logOut();
Toast.makeText(getApplicationContext(), obj.getString("message"), Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put(Constant.accessKey, Constant.accessKeyValue);
params.put(Constant.userSignUp, "1");
params.put(Constant.email, email);
params.put(Constant.name, name);
params.put(Constant.PROFILE, profile);
params.put(Constant.fcmId, token);
params.put(Constant.type, type);
params.put(Constant.mobile, mobileNomre );
params.put(Constant.REFER_CODE, referCode);
params.put(Constant.FRIENDS_CODE, fCode);
WifiManager wm = (WifiManager) getApplicationContext().getSystemService(WIFI_SERVICE);
String ip = Formatter.formatIpAddress(wm.getConnectionInfo().getIpAddress());
params.put(Constant.ipAddress, ip);
System.out.println("---params social " + params.toString());
return params;
}
};
// AppController.getInstance().getRequestQueue().getCache().clear();
AppController.getInstance().addToRequestQueue(strReq);
}
SharedPrereferences:
public class Session {
public static void setNomre(Context mContext, String key, String objString) {
SharedPreferences.Editor editor =
mContext.getSharedPreferences(mContext.getString(R.string.app_name),
Context.MODE_PRIVATE).edit();
editor.putString(key, objString);
editor.commit();
}
public static String getNomre(Context mContext, final String key, final String defaultStr) {
SharedPreferences pref = mContext.getSharedPreferences(mContext.getString(R.string.app_name),
Context.MODE_PRIVATE);
return pref.getString(key, defaultStr);
}}
Make your String public static to access it globally;
public static String mobileNomre = Session.getNomre(getApplicationContext(),"nomreler","");
Haven't tried but working around with below code can give you an idea,
We uses this method if we want to access any function of Activity1 in Activity2..
AnotherActivity anotheractivity = (AnotherActivity) this.getActivity();

Retrieve a String property from a class instance

I have class A and B.
"A" makes an instance of "B" and call a method that modify a String property. However, after the calling the property checked in "A" is null.
Can anyone help me?
Class B
private String Retro;
....
public boolean Login(final String user, final String pass){
stringRequest = new StringRequest(Request.Method.POST, Url + strLogin,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
// Display the first 500 characters of the response string.
Retro = "Done";
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
**Retro = error.getMessage();**
Toast.makeText(context, "Error de acceso: "+Retro, Toast.LENGTH_LONG).show(); //error.getMessage()
}
}) {
#Override
protected Map<String, String> getParams(){
Map<String, String> parameters = new HashMap<>();
parameters.put("identifier", user);
parameters.put("password", pass);
return parameters;
}
};
// Add the request to the RequestQueue.
requestQueue.add(stringRequest);
return Retro == "Done";
}
Class A
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = 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();
}
});
accessDB = new StrapiDBAccess(this);
signIn();
}
private void handleSignInResult(Task<GoogleSignInAccount> completedTask) {
try {
...
if (acct != null) {
....
boolean result = accessDB.Login(parcelAccess.personEmail, "*******");
tvAuth.setText(tvAuth.getText()+" "+**accessDB.getRetro()**); //
}
} catch (ApiException e) {
// The ApiException status code indicates the detailed failure reason.
// Please refer to the GoogleSignInStatusCodes class reference for more information.
parcelAccess.signedIn = false;
parcelAccess.personName = "Anónimo";
Toast.makeText(this, "Error de autenticación con Google. Chequee que tiene internet e inténtelo de nuevo.", Toast.LENGTH_SHORT).show();
}
}
I found the answer to my doubt. It is impossible to do by a field, or getter or any direct way. It is neccesary to implement an interface for success or error. It would be this way:
Class B
public void Login(final String user, final String pass, final VolleyCallback callback){
Retro = "";
stringRequest = new StringRequest(Request.Method.POST, Url + strLogin,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
// Display the first 500 characters of the response string.
***callback.onSuccess("Done");***
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Retro = Retro + String.copyValueOf(error.getMessage().toCharArray());
***callback.onError(Retro);***
//error.getMessage()
}
}) {
#Override
protected Map<String, String> getParams(){
Map<String, String> parameters = new HashMap<>();
parameters.put("identifier", user);
parameters.put("password", pass);
return parameters;
}
};
// Add the request to the RequestQueue.
requestQueue.add(stringRequest);
Toast.makeText(context, "Error de acceso: "+ErrorCode, Toast.LENGTH_LONG).show();
}
Class A
accessDB.Login(parcelAccess.personEmail, "************", new StrapiDBAccess.VolleyCallback(){
#Override
public void onSuccess(String result) {
}
#Override
public void onError(String error)
//no pudo ingresar
}
}
});
Well, I hope to help anyone who has this kind of trouble

Return Volley Result to a different class

how can I get the result of a StringRequest or JsonObjectRequest back to the class where I called the method.
In my MainActivty I have a Login Button. When I press it, it Calls the function checkLogin with a StingRequest from my Backgroundworker.class. How can I get the response back to my MainActivity to process it or Display it?
I can’t use a return at the end of the method because its asynchrony. I tried calling a method in my MainActivity but I always get an error when reaching the Intent
2019-05-16 16:43:52.794 3158-3158/com.test.Test E/Error: Attempt to invoke virtual method 'java.lang.String android.content.Context.getPackageName()' on a null object reference
What’s the proper way to do a login function like this?
-MainActivity
package com.test.Test;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import com.test.Test.tools.BackgroundWorker;
public class MainActivity extends AppCompatActivity {
private EditText txtEditUser;
private EditText txtEditPw;
private Button btnLogin;
private Button btnRegister;
private TextView txtViewLoginfailed;
private String user;
private String password;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
txtEditUser = findViewById(R.id.txtEditUser);
txtEditPw = findViewById(R.id.txtEditPw);
btnLogin = findViewById(R.id.btnLogin);
btnRegister = findViewById(R.id.btnRegister);
txtViewLoginfailed = findViewById(R.id.txtViewLoginfailed);
btnLogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
user = txtEditUser.getText().toString();
password = txtEditPw.getText().toString();
new BackgroundWorker().checkLogin(user, password, getApplicationContext());
}
});
btnRegister.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent register = new Intent(getApplicationContext(), Register.class);
startActivity(register);
}
});
}
public void Login(Boolean LoginOK,Context context) {
if (LoginOK) {
Intent menu = new Intent(context, Menu.class);
startActivity(menu);
} else {
txtViewLoginfailed.setText("Login failed");
}
}
}
-Backgroundworker
public class BackgroundWorker {
private Boolean LoginOK;
public void checkLogin(final String user, final String password, final Context context) {
String url = "http://192.168.0.2:80/webapp/login.php";
RequestQueue queue = Volley.newRequestQueue(context);
StringRequest sr = new StringRequest(Request.Method.POST, url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
Log.d("testLogin", "3");
if (response.equals("login success")) {
LoginOK = true;
new MainActivity().Login(LoginOK, context);
} else {
Log.d("testLogin", "5");
}
} catch (Exception exc) {
exc.printStackTrace();
Log.e("Error", exc.getMessage());
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("Error", error.getMessage());
}
}
) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("user_name", user);
params.put("password", password);
return params;
}
};
queue.add(sr);
}
}
What you need is Callback interface.
Create new interface e.g. LoginRequestCallback:
public interface LoginRequestCallback {
void onLoginRequestSuccess();
void onLoginRequestError(String errorMessage);
}
In your checkLogin method add new parameter LoginRequestCallback callback:
public void checkLogin(final String user, final String password, final Context context, LoginRequestCallback callback) { ... }
And then call method corresponding to either success of login or to the error:
public void checkLogin(final String user, final String password, final Context context) {
String url = "http://192.168.0.2:80/webapp/login.php";
RequestQueue queue = Volley.newRequestQueue(context);
StringRequest sr = new StringRequest(Request.Method.POST, url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
Log.d("testLogin", "3");
if (response.equals("login success")) {
callback.onLoginRequestSuccess();
} else {
callback.onLoginRequestError("Invalid credentials");
}
} catch (Exception exc) {
exc.printStackTrace();
Log.e("Error", exc.getMessage());
callback.onLoginRequestError(exc.getMessage());
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("Error", error.getMessage());
callback.onLoginRequestError(exc.getMessage());
}
}
) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("user_name", user);
params.put("password", password);
return params;
}
};
queue.add(sr);
}
When calling from MainActivity, make MainActivity class implement this interface:
public class MainActivity extends Activity implements LoginRequestCallback {
//...
#Override
public void onLoginRequestSuccess() {
}
#Override
public void onLoginRequestError(String errorMessage) {
}
}
And when you call this method, pass this as callback:
void onLoginButtonClicked(View v) {
String user = "Asd";
String password = "asdasd";
this.backgroundWorker.checkLogin(user, password, this, this);
}
#Override
public void onLoginRequestSuccess() {
this.Login(true, this);
}
#Override
public void onLoginRequestError(String errorMessage) {
Toast.makeText(this, errorMessage, Toast.SHORT).show();
}

how do I make the data I input in the EditText inserted into the database and appear on the recyclerview without refreshing it like ajax?

I tried using adapter.notifyDataSetChanged() but failed, maybe someone could tell me where the code was placed.
This is my MainActivity:
private RecyclerView mList;
private LinearLayoutManager linearLayoutManager;
private DividerItemDecoration dividerItemDecoration;
private Adapter mExampleAdapter;
private ArrayList<Model> mExampleList;
private RecyclerView.Adapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
modelList = new ArrayList<>();
pesan= (EditText) findViewById(R.id.pesan);
user= 1;
admin= 1;
save = (ImageButton) findViewById(R.id.btn_submit);
mList = findViewById(R.id.main_list);
modelList = new ArrayList<>();
adapter = new Adapter(getApplicationContext(),modelList);
linearLayoutManager = new LinearLayoutManager(this);
linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
dividerItemDecoration = new DividerItemDecoration(mList.getContext(), linearLayoutManager.getOrientation());
mList.setHasFixedSize(true);
mList.setLayoutManager(linearLayoutManager);
mList.setAdapter(adapter);
save.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final String isi_pesan = pesan.getText().toString();
final String id_admin = admin.toString();
final String id_user = user.toString();
RequestQueue queue = Volley.newRequestQueue(MainActivity.this);
StringRequest request = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
pesan.setText("");
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(MainActivity.this, "my error :"+error, Toast.LENGTH_LONG).show();
Log.i("My error",""+error);
}
}){
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String,String> map = new HashMap<String, String>();
map.put("message",isi_pesan);
map.put("id_admin",id_admin);
map.put("id_user",id_user);
return map;
}
};
queue.add(request);
}
});
getData();
}
private void getData() {
final ProgressDialog progressDialog = new ProgressDialog(this);
progressDialog.setMessage("Loading...");
progressDialog.show();
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(url, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
for (int i = 0; i < response.length(); i++) {
try {
JSONObject jsonObject = response.getJSONObject(i);
Model model = new Model();
model.setPesan(jsonObject.getString("isi_pesan"));
model.setAdmin(jsonObject.getString("sender"));
modelList.add(model);
adapter.notifyDataSetChanged();
mExampleAdapter = new Adapter(MainActivity.this, modelList);
mList.setAdapter(mExampleAdapter);
} catch (JSONException e) {
e.printStackTrace();
progressDialog.dismiss();
}
}
progressDialog.dismiss();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("Volley", error.toString());
progressDialog.dismiss();
}
});
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(jsonArrayRequest);
}
}
I want the data I post to appear in real time like whatsapp
First you told recyclerveiw that the number of items are fixed
mList.setHasFixedSize(true);
but in getData method you added an item to it.
second, don't call adapter.notifyDataSetChanged(); when you just added an item, instead call notifyItemInserted(position);
third, you replaced adapter after calling adapter.notifyDataSetChanged();, first replace adapter then call adapter.notifyDataSetChanged();

Categories