Android - NullPointerException hashCode() on a null object Reference [duplicate] - java

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 5 years ago.
Help Me, I have Error when i want to POST JSON from my register (frmDaftar) class to WebService, error code is : java.lang.NullPointerException: Attempt to invoke virtual method 'int java.lang.String.hashCode()' on a null object reference
at com.android.volley.Request.(Request.java:136)
public class frmDaftar extends AppCompatActivity {
Button btnDaftar, btnKembali;
EditText email, pass, nama;
AlertDialog alertDialog;
private static final String TAG = frmDaftar.class.getSimpleName();
SessionManager session;
private String EmailView;
private ProgressDialog pDialog;
private static final String Key_nama = "nama";
private static final String Key_email = "email";
private static final String Key_password = "password";
private static final String url = "Webservice_Controller.URL_DAFTAR";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_frm_daftar);
btnDaftar = (Button) findViewById(R.id.btnDaftar1);
btnKembali = (Button) findViewById(R.id.btnKembali);
email = (EditText) findViewById(R.id.txtEmailDaftar);
pass = (EditText) findViewById(R.id.txtPasswordDaftar);
nama = (EditText) findViewById(R.id.txtNamaDaftar);
session = new SessionManager(getApplicationContext());
btnDaftar.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
btnDaftar.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String emails = email.getText().toString().trim();
String passwords = pass.getText().toString().trim();
String namas = nama.getText().toString().trim();
registerUser(emails, passwords,namas);
//alertDialog.show();
}
});
}
});
btnKembali.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startActivity(new Intent(frmDaftar.this, frmLogin.class));
}
});
}
private void initCustomAlertDialog(String EmailView) {
View v = getLayoutInflater().inflate(R.layout.dialogverivikasi, null);
TextView txtEmail = (TextView) findViewById(R.id.lblemailDaftar);
//txtEmail.setText(EmailView);
alertDialog = new AlertDialog.Builder(this).create();
alertDialog.setView(v);
alertDialog.setTitle("Verifikasi Email");
}
private void registerUser(final String nama, final String email, final String pass){
String tag_string_req = "req_register";
pDialog.setMessage("Registering ...");
showDialog();
StringRequest stringRequest = new StringRequest(Request.Method.POST, Webservice_Controller.URL_DAFTAR,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try{
JSONObject jObj = new JSONObject(response);
boolean error = jObj.getBoolean("error");
Log.d(TAG, "Register Response: " + response.toString());
hideDialog();
}catch (JSONException e) {
e.printStackTrace();
} {
}
//Toast.makeText(DataSent.this, response, Toast.LENGTH_LONG).show();
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
//Toast.makeText(DataSent.this,error.toString(),Toast.LENGTH_LONG).show();
Log.e(TAG, "Registration Error: " + error.getMessage());
Toast.makeText(getApplicationContext(),
error.getMessage(), Toast.LENGTH_LONG).show();
hideDialog();
}
}){
#Override
protected Map<String,String> getParams(){
Map<String, String> params = new HashMap<String, String>();
params.put("name", nama);
params.put("email", email);
params.put("password", pass);;
return params;
}
};
AppController.getInstance().addToRequestQueue(stringRequest, tag_string_req);
}
Here is my AppController
public class AppController extends Application {
public static final String TAG = AppController.class.getSimpleName();
private RequestQueue mRequestQueue;
private static AppController mInstance;
#Override
public void onCreate() {
super.onCreate();
mInstance = this;
}
public static synchronized AppController getInstance() {
return mInstance;
}
public RequestQueue getRequestQueue() {
if (mRequestQueue == null) {
mRequestQueue = Volley.newRequestQueue(getApplicationContext());
}
return mRequestQueue;
}
public <T> void addToRequestQueue(Request<T> req, String tag) {
req.setTag(TextUtils.isEmpty(tag) ? TAG : tag);
getRequestQueue().add(req);
}
public <T> void addToRequestQueue(Request<T> req) {
req.setTag(TAG);
getRequestQueue().add(req);
}
public void cancelPendingRequests(Object tag) {
if (mRequestQueue != null) {
mRequestQueue.cancelAll(tag);
}
}
}
Help Me Please, This is my first android project :)

Double check that you added your app controller in your applicaiton tag. Hope it'll fix your crash.
<application
android:name="AppController"
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme">

Related

how to get twitter username with twitter4j

I am developing an app in java in the android studio IDE, the idea is that after logging in with my username and password, I can be redirected to a new view where a user profile is shown with the name, email and profile image. Currently I can log in and after that it redirects to the user profile but I don't know how to get the name, email and profile image.Then I leave you my code in case you have the time to help me, thank you very much for reading:
loggin.class
public class loggin extends AppCompatActivity {
//variable twitter
Button twitterButton;
//TwitterLoginButton login;
private static final String TAG = "Twitter4j";
private static Twitter twitter;
private static final String APIConsumerKey = "xxxx";
private static final String APIConsumerSecretKey = "xxxx";
private static final String CALLBACK_URL = "http://myurl";
private static RequestToken twitterRequestToken;
twitterButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
initializeTwitter(loggin.this);
}
});
}
private static void initializeTwitter(final Activity activity) {
ConfigurationBuilder configurationBuilder = new ConfigurationBuilder();
configurationBuilder.setOAuthConsumerKey(APIConsumerKey);
configurationBuilder.setOAuthConsumerSecret(APIConsumerSecretKey);
twitter = new TwitterFactory(configurationBuilder.build()).getInstance();
new Thread(new Runnable() {
#Override
public void run() {
User user;
try {
twitterRequestToken = twitter.getOAuthRequestToken(CALLBACK_URL);
Log.i("LoginActivity", String.valueOf(twitterRequestToken));
activity.runOnUiThread(new Runnable() {
#Override
public void run() {
//Open Dialog for authentication.
Intent intent = new Intent(activity, TwitterAuthActivity.class);
if (twitterRequestToken != null) {
intent.putExtra("TwitterReqTokenUrl", twitterRequestToken.getAuthenticationURL());
activity.startActivity(intent);
}
}
});
} catch (Exception e) {
Log.e(TAG, "Exception " + e.getMessage());
}
}
}).start();
}
}
twitterAuthActivity
public class TwitterAuthActivity extends AppCompatActivity {
private static final String TAG = "Twitter4j";
private static final String TWITTER_CALLBACK_URL = "http://www.stackoverflow.com"; //"x-oauthflow-twitter://twitterlogin";
private ProgressDialog progressDialog;
private String twitterRequesTokenUrl;
private WebView twitterWebView;
#SuppressLint("SetJavaScriptEnabled")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.dialog_twitter);
twitterWebView = findViewById(R.id.TwitterWebView);
Bundle extras = getIntent().getExtras();
if (extras != null) {
twitterRequesTokenUrl = extras.getString("TwitterReqTokenUrl");
}
progressDialog = new ProgressDialog(this);
progressDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
progressDialog.setMessage("Loading...");
//Setup WebView
CookieSyncManager.createInstance(this);
CookieManager cookieManager = CookieManager.getInstance();
cookieManager.removeAllCookie();
twitterWebView.setVerticalScrollBarEnabled(false);
twitterWebView.setHorizontalScrollBarEnabled(false);
twitterWebView.setWebViewClient(new TwitterWebViewClient());
WebSettings webSettings = twitterWebView.getSettings();
webSettings.setSupportZoom(true);
webSettings.setSaveFormData(true);
webSettings.setJavaScriptEnabled(true);
twitterWebView.loadUrl(twitterRequesTokenUrl);
}
#Override
public boolean dispatchTouchEvent(MotionEvent ev) {
if (ev.getAction() == MotionEvent.ACTION_DOWN) {
int[] l = new int[2];
twitterWebView.getLocationOnScreen(l);
Rect rect = new Rect(l[0], l[1], l[0] + twitterWebView.getWidth(), l[1] + twitterWebView.getHeight());
if (!rect.contains((int) ev.getRawX(), (int) ev.getRawY())) {
finish();
}
}
return super.dispatchTouchEvent(ev);
}
private class TwitterWebViewClient extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
boolean response = false;
if (url.contains(TWITTER_CALLBACK_URL)) {
Uri uri = Uri.parse(url);
//This uri could be saved as access token.
Log.i(TAG, "shouldOverrideUrlLoading() uri " + uri.getPath());
Intent intent=new Intent(TwitterAuthActivity.this,MainActivity.class);
startActivity(intent);
finish();
response = true;
}
return response;
}
#Override
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
super.onReceivedError(view, errorCode, description, failingUrl);
Toast.makeText(TwitterAuthActivity.this, "Upps! something happened, retry later!.", Toast.LENGTH_LONG).show();
finish();
}
#RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR1)
#Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
if(progressDialog.isShowing() && !isFinishing() && !isDestroyed()) {
progressDialog.dismiss();
}
twitterWebView.setVisibility(View.VISIBLE);
}
}
}

How to get response from server?

I'm writing a class with requests to rest API (Yandex disk). I use volley, but I do have some problems with getting a response from it. You can check the rest API here.
I use volley and I can get a response in the debugger, but not in my Activity.
Here is my Requests class
class Requests {
private String response_of_server, token;
private String url = "https://cloud-api.yandex.net/v1/disk";
private Context context;
Requests (String token, Context context) {
this.token = token;
this.context = context;
}
private void set_response_of_server(String response) {
this.response_of_server = response;
}
String get_response() {
return response_of_server;
}
void get_metadata_of_user() {
try {
/*Request*/
RequestQueue queue = Volley.newRequestQueue(this.context);
Response.ErrorListener error_listener = new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
};
Response.Listener<String> response_listener = new Response.Listener<String>()
{
#Override
public void onResponse(String response) {
set_response_of_server(response);
}
};
StringRequest getRequest = new StringRequest(Request.Method.GET, url+"?fields=user", response_listener, error_listener) {
#Override
public Map<String, String> getHeaders() {
Map<String, String> params = new HashMap<>();
params.put("Host", "cloud-api.yandex.net");
params.put("Authorization", token);
return params;
}
};
queue.add(getRequest);
/*Request end*/
} catch (Exception e) {
e.printStackTrace();
}
}
}
And the MainActivity where I want my response.
public class MainActivity extends AppCompatActivity {
private final String ID_OF_APP = "Your token of app";
private final String URL_FOR_CODE_QUERY = "https://oauth.yandex.com/authorize?response_type=token&client_id=" + ID_OF_APP;
private String SAVED_TOKEN = "";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button btn_get_code = findViewById(R.id.btn_get_code); // send to get code page (yandex)
btn_get_code.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse(URL_FOR_CODE_QUERY));
startActivity(i);
}
});
Button btn_sign_in = findViewById(R.id.btn_sign_in);
btn_sign_in.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
EditText code_field = findViewById(R.id.code_field);
String token = code_field.getText().toString();
save_token(token);
try {
if(check_token()) {
//Toast.makeText(MainActivity.this, "You are successfully signed in", Toast.LENGTH_SHORT).show();
// TODO change activity
}
else {}
} catch (InterruptedException e) {
e.printStackTrace();
}
//Toast.makeText(MainActivity.this, "Something went wrong. Please, check your connection and try again later", Toast.LENGTH_SHORT).show();
}
});
}
private void save_token(String token) {
SharedPreferences sPref = getPreferences(MODE_PRIVATE);
SharedPreferences.Editor ed = sPref.edit();
ed.putString(SAVED_TOKEN, token);
ed.apply();
}
private String load_token() {
SharedPreferences sPref = getPreferences(MODE_PRIVATE);
return sPref.getString(SAVED_TOKEN, "");
}
private boolean check_token() throws InterruptedException {
String token = load_token();
String result;
Requests request = new Requests(token, this);
request.get_metadata_of_user();
result = request.get_response();
Toast.makeText(MainActivity.this, result, Toast.LENGTH_SHORT).show();
return !(result.equals("-1"));
}
}
check_token() function at the moment should just make a toast with a response of the server. However, I cannot get the Toast or any response coming back from the server.
You have a Requests class which has the function to call the server API which is Asynchronous. Hence, you will not get the result immediately after calling the request.get_metadata_of_user(); in your check_token() function.
Hence I would like to suggest you modify your Request class like the following.
public class Requests {
private String response_of_server, token;
private String url = "https://cloud-api.yandex.net/v1/disk";
private Context context;
private HttpListener listener; // Add a listener to get the callback functionality
Requests (String token, Context context, HttpListener listener) {
this.token = token;
this.context = context;
this.listener = listener; // initialize the listener here
}
private void set_response_of_server(String response) {
this.response_of_server = response;
listener.onResponseReceived(response); // Send the response back to the calling class
}
String get_response() {
return response_of_server;
}
void get_metadata_of_user() {
try {
RequestQueue queue = Volley.newRequestQueue(this.context);
Response.ErrorListener error_listener = new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
};
Response.Listener<String> response_listener = new Response.Listener<String>()
{
#Override
public void onResponse(String response) {
set_response_of_server(response);
}
};
StringRequest getRequest = new StringRequest(Request.Method.GET, url+"?fields=user", response_listener, error_listener) {
#Override
public Map<String, String> getHeaders() {
Map<String, String> params = new HashMap<>();
params.put("Host", "cloud-api.yandex.net");
params.put("Authorization", token);
return params;
}
};
queue.add(getRequest);
} catch (Exception e) {
e.printStackTrace();
}
}
}
Now the HttpListener class might look like the following. Create HttpListener.java and add the following code to create this as an interface.
public interface HttpListener {
public void onResponseReceived();
}
Hence you need to implement this interface in your MainActivity like the following.
public class MainActivity extends AppCompatActivity implements HttpListener {
private final String ID_OF_APP = "Your token of app";
// I fixed this part too. Please change if that is not useful
private final String URL_FOR_CODE_QUERY = "https://oauth.yandex.com/authorize?response_type=" + SAVED_TOKEN + "&client_id=" + ID_OF_APP;
private String SAVED_TOKEN = "";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// ... I omitted some code
Button btn_sign_in = findViewById(R.id.btn_sign_in);
btn_sign_in.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
EditText code_field = findViewById(R.id.code_field);
String token = code_field.getText().toString();
save_token(token);
try {
// if(check_token()) {
// The check_token function call is Async. This will not return immediately. Hence you might consider removing this if part. Simply just call the function and listen to the callback function when the response is received
// }
check_token(); // Simply call the function here
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
}
private void save_token(String token) {
SharedPreferences sPref = getPreferences(MODE_PRIVATE);
SharedPreferences.Editor ed = sPref.edit();
ed.putString(SAVED_TOKEN, token);
ed.apply();
}
private String load_token() {
SharedPreferences sPref = getPreferences(MODE_PRIVATE);
return sPref.getString(SAVED_TOKEN, "");
}
// I changed the return type as this is not returning anything.
private void check_token() throws InterruptedException {
String token = load_token();
String result;
Requests request = new Requests(token, this);
request.get_metadata_of_user();
// You will not get the response immediately here. So omit these codes.
// result = request.get_response();
// Toast.makeText(MainActivity.this, result, Toast.LENGTH_SHORT).show();
// return !(result.equals("-1"));
}
#Override
public void onResponseReceived(String response) {
// Here is your response. Now you can use your response
// and can perform the next action here.
}
}
Please note that, the code is not tested. Please modify as per your requirement. I hope that helps you to understand the problem.

Unable to get a response from the backend as to my query. How can I fix this issue?

I am trying to create a register activity which uses volley and PHP to connect to mySQL. I have attached some of the code. The code works perfectly fine till i try to get the response back from the Database. While using StringRequest, the control is not entering this section of the code. How can i fix this problem? Please Help.
public class RegisterActivity extends AppCompatActivity {
String rurl = "http://102.160.2.104/register.php";
String message;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
final EditText etName = (EditText) findViewById(R.id.etName);
....
final EditText weig = (EditText) findViewById(R.id.weight);
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();
...
if(!(conpassword.equals(password))){
etPassword.setText("");
etconpas.setText("");
Toast.makeText(getApplicationContext(),"Passwords don't match",Toast.LENGTH_LONG).show();
}
//The problem arises over here as it does not enter the onResponse() method.
StringRequest stringRequest = new StringRequest(Request.Method.POST, rurl, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONArray jsonArray = new JSONArray(response);
JSONObject jsonObject = jsonArray.getJSONObject(0);
message = jsonObject.getString("message");
fin();
} catch (JSONException e) {
System.out.println("hhellooo");
e.printStackTrace();
}
}
private void fin() {
System.out.println(message);
if(message.equals("User already exists")){
etName.setText("");
etPassword.setText("");
contact.setText("");
etUsername.setText("");
age.setText("");
heig.setText("");
weig.setText("");
Toast.makeText(getApplicationContext(),"User already Exists",Toast.LENGTH_LONG).show();
}
else
{
Intent intent = new Intent(RegisterActivity.this,MainActivity.class);
startActivity(intent);
finish();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}){
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String,String> params = new HashMap<>();
params.put("name",name);
params.put("username",username);
params.put("password",password);
params.put("value", finalValue);
params.put("phone", String.valueOf(phone));
params.put("years", String.valueOf(years));
params.put("height", String.valueOf(height));
params.put("weight", String.valueOf(weight));
return params;
}
};
MySingleton.getInstance(RegisterActivity.this).addtoRQ(stringRequest);
}
});
}
The MySingleton class file to add the request into the queue.
class MySingleton {
private static MySingleton mInstance;
private static RequestQueue requestQueue;
private Context context;
private MySingleton(Context ctx) {
context = ctx;
requestQueue = getRequestQueue();
}
private RequestQueue getRequestQueue() {
if(requestQueue==null)
{
requestQueue = Volley.newRequestQueue(context.getApplicationContext());
}
return requestQueue;
}
static synchronized MySingleton getInstance(Context con){
if(mInstance==null)
{
mInstance = new MySingleton(con);
}
return mInstance;
}
<T>void addtoRQ(Request<T> request) {
requestQueue.add(request);
}
I think your request is not being sent because you haven't added it to a request queue.
RequestQueue mRequestQueue;
// Instantiate the cache
Cache cache = new DiskBasedCache(getCacheDir(), 1024 * 1024); // 1MB cap
// Set up the network to use HttpURLConnection as the HTTP client.
Network network = new BasicNetwork(new HurlStack());
// Instantiate the RequestQueue with the cache and network.
mRequestQueue = new RequestQueue(cache, network);
// Start the queue
mRequestQueue.start();
<Your request setup>
// Add the request to the RequestQueue.
mRequestQueue.add(stringRequest);
From: Android Developer

Fingerprint AuthenticationCallback in LoginActivity

How can I call the method "loginprep" of the LoginActivityClass from the FingerPrintClass?
See in the code...I wrote in where I want to call the loginprep with: "//Here I need the method loginprep() from the LoginActivity class"
FingerprintHandler.java
public class FingerprintHandler extends FingerprintManager.AuthenticationCallback {
private Context context;
// Constructor
public FingerprintHandler(Context mContext) {
context = mContext;
}
public void startAuth(FingerprintManager manager, FingerprintManager.CryptoObject cryptoObject) {
CancellationSignal cancellationSignal = new CancellationSignal();
if (ActivityCompat.checkSelfPermission(context, Manifest.permission.USE_FINGERPRINT) != PackageManager.PERMISSION_GRANTED) {
return;
}
manager.authenticate(cryptoObject, cancellationSignal, 0, this, null);
}
#Override
public void onAuthenticationError(int errMsgId, CharSequence errString) {
Toast.makeText((Activity)context, "Fingerprint Authentication error.", Toast.LENGTH_LONG).show();
}
#Override
public void onAuthenticationHelp(int helpMsgId, CharSequence helpString) {
Toast.makeText((Activity)context, "Fingerprint Authentication help.", Toast.LENGTH_LONG).show();
}
#Override
public void onAuthenticationFailed() {
Toast.makeText((Activity)context, "Fingerprint Authentication failed.", Toast.LENGTH_LONG).show();
}
#Override
public void onAuthenticationSucceeded(FingerprintManager.AuthenticationResult result) {
//Here I need the method loginprep() from the LoginActivity class
}
}
LoginActivity.java
public class LoginActivity extends AppCompatActivity {
public void loginprep() {
SharedPreferences sharedPreferencesF = getSharedPreferences("loginDatasFinger", Context.MODE_PRIVATE);
String urn = sharedPreferencesF.getString("username", "");
String pwd = sharedPreferencesF.getString("password", "");
loginUser(urn, pwd);
}
private void launchHomeScreen() {
Intent homeActivity = new Intent (LoginActivity.this,HomeActivity.class);
LoginActivity.this.startActivity(homeActivity);
finish();
}
public void loginUser(final String urn, final String pwd){
pd = ProgressDialog.show(LoginActivity.this, "", "Loading...");
StringRequest stringRequest = new StringRequest(Request.Method.POST, LOGIN_URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonResponse = new JSONObject(response);
System.out.println("JSON RESPONSE: " + jsonResponse.toString());
boolean success = jsonResponse.getBoolean("success");
if (success) {
launchHomeScreen();
pd.dismiss();
Toast.makeText(LoginActivity.this,"Welcome back " + urn,Toast.LENGTH_LONG).show();
SharedPreferences sharedPref = getSharedPreferences("loginDatas", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putString("username", urn);
editor.putString("password", pwd);
editor.apply();
}
else {
loginButton.setBackgroundColor(0x73000000);
Toast.makeText(LoginActivity.this,"Wrong Username or Password!",Toast.LENGTH_LONG).show();
pd.dismiss();
}
}
catch (JSONException e) {
loginButton.setBackgroundColor(0x73000000);
e.printStackTrace();
pd.dismiss();
Toast.makeText(LoginActivity.this,response,Toast.LENGTH_LONG).show();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
loginButton.setBackgroundColor(0x73000000);
pd.dismiss();
System.out.println("Error: " + error);
}
}){
#Override
protected Map<String,String> getParams(){
Map<String,String> params = new HashMap<>();
params.put(KEY_USERNAME,urn);
params.put(KEY_PASSWORD,pwd);
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
}
Following:
MainActivity mActivity = new MainActivity();
this is not the way Android is expecting you to create new instances of an activity, normally you wait the onCreate callback as described in the activity lifeCycle...
no following that approach you will need another way to communicate 2 different activities, what way must be taken depends on the specific arch of your application... the most commonly implemented could be using self defined interfaces and implement you custom callbacks...
You're writing a FingerPrint callback class, which means there is some onAuthenticationSucceeded method that is called when the "authentication succeeds."
How about you implement your own callback to pass back into the LoginActivity?
In other words, you'd
1) Write an interface
public interface LoginListener {
void onLoginSuccess();
void onLoginFailed();
}
2) Have the Activity implements LoginListener and have the Activity method of onLogin do your non-static stuff with the SharedPreferences,
public class LoginActivity extends AppCompatActivity
implements LoginListener {
public static final String KEY_USERNAME = "username";
public static final String KEY_PASS = "password";
private FingerprintHandler fingerprintHandler;
#Override
public void onLoginFailed() { }
#Override
public void onLoginSuccess() {
SharedPreferences sharedPrefs = getSharedPreferences("loginDatasFinger", Context.MODE_PRIVATE);
String urn = sharedPrefs.getString(KEY_USERNAME, "");
String pwd = sharedPrefs.getString(KEY_PASS, "");
loginUser(urn, pwd);
}
#Override
public void onCreate(Bundle b) {
super.onCreate(b);
setContentView(R.layout.activity_login);
fingerprintHandler = new FingerprintHandler(this);
}
// public void loginUser(final String urn, final String pwd){ }
}
3) Expect to pass in a LoginListener as a parameter to that separate class.
public class FingerprintHandler extends FingerprintManager.AuthenticationCallback {
private final Context mContext;
private LoginListener mListener;
// Constructor
public FingerprintHandler(Context context) {
mContext = context;
if (context instanceof LoginListener) {
this.mListener = (LoginListener) context;
} else {
throw new ClassCastException("FingerprintHandler: context must implement LoginListener!");
}
}
4) And you do then can use your callback from the other callback.
#Override
public void onAuthenticationSucceeded(FingerprintManager.AuthenticationResult result) {
if (mListener != null) {
mListener.onLoginSuccess();
}
}

how to check if a table has been updated or inserted then wanted to do it, otherwise it in android

i use volley library on android code
i want to know check if my table has been updated or inserted then wanted to do it(A), otherwise it(B)
for example if my table updated or inserted then send (A)sms otherwise (B)toast
its my activity code:
public class DeviceAddActivity extends AppCompatActivity implements View.OnClickListener {
private static final String REGISTER_URL = "http://192.168.43.190/entezam/addphone.php";
public static final String KEY_CUSTNAME = "Customer_non";
public static final String KEY_PHONENAME = "Phone_Name";
public static final String KEY_IMEI = "IMEI";
private EditText editTextName;
private EditText editTextPhoneName;
private EditText editTextIMEI;
private Button buttonRegister;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_device_add);
editTextName = (EditText) findViewById(R.id.editTextcustname);
editTextPhoneName = (EditText) findViewById(R.id.editTextphonename);
editTextIMEI= (EditText) findViewById(R.id.editTextimei);
buttonRegister = (Button) findViewById(R.id.buttonRegister);
buttonRegister.setOnClickListener(this);
}
private void registerUser(){
final String Customer_non = editTextName.getText().toString().trim();
final String Phone_Name = editTextPhoneName.getText().toString().trim();
final String IMEI = editTextIMEI.getText().toString().trim();
StringRequest stringRequest = new StringRequest(Request.Method.POST, REGISTER_URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Toast.makeText(DeviceAddActivity.this,response,Toast.LENGTH_LONG).show();
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(DeviceAddActivity.this,error.toString(),Toast.LENGTH_LONG).show();
}
}){
#Override
protected Map<String,String> getParams(){
Map<String,String> params = new HashMap<String, String>();
params.put(KEY_CUSTNAME,Customer_non);
params.put(KEY_PHONENAME,Phone_Name);
params.put(KEY_IMEI,IMEI);
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
#Override
public void onClick(View v) {
if(v == buttonRegister){
registerUser();
}
}
and its my php code:
<?php
if($_SERVER['REQUEST_METHOD']=='POST'){
$Phone_Name = $_POST['Phone_Name'];
$Customer = $_POST['Customer_non'];
$IMEI = $_POST['IMEI'];
require_once('dbConnect.php');
$sql = "INSERT INTO phone_in (Phone_Name,Customer_non,IMEI) VALUES ('$Phone_Name','$Customer','$IMEI')";
if(mysqli_query($con,$sql)){
echo "Successfully Registered";
}else{
echo "Could not register";
}
}else{echo 'error';}

Categories

Resources