Android: checking database with volley library constantly - android

I started learning Android and Java a week ago and now I am trying to make an login application. I am using Volley libary to communicate with my server. I have done the login part. Now, what I want to do is to check the database every minute to see if the password or the username somehow changed. If the information in the database is changed, app will automaticly logout the user.
If you can explain which tools(Services,BroadcastReceivers) I can use and how can I achieve it, as I am not very experienced.
This is what I tried and failed:
loginChecker.class
public class loginChecker extends Service {
public loginChecker() {
}
public static String username;
public static String password;
private loginChecker mInstance = this;
public static boolean loginCheck= true;
public static String responseG = "failed";
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Bundle b=intent.getExtras();
username = b.getString("username");
password = b.getString("password");
final String URL = ".........";
final RequestQueue requestQueue = Volley.newRequestQueue(mInstance);
new Thread(new Runnable(){
public void run() {
do{
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
e.printStackTrace();
}
StringRequest request = new StringRequest(Request.Method.POST, URL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
responseG = response;
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
responseG = "error";
}
}) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
HashMap<String, String> hashMap = new HashMap<String, String>();
hashMap.put("username", username);
hashMap.put("password", password);
return hashMap;
}
};
requestQueue.add(request);
switch(responseG){
case "successful" :
loginCheck = true;
break;
case "failed" :
loginCheck= false;
break;
case "error" :
loginCheck = false;
break;
}
}
while(loginCheck == true || responseG == "successful");
}
}).start();
Toast.makeText(getApplicationContext(), "LOOP ENDED", Toast.LENGTH_SHORT).show();
return START_REDELIVER_INTENT;
}
#Override
public void onDestroy() {
final Intent mainActivity = new Intent(mInstance, MainActivity.class);
mainActivity.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(mainActivity);
}
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
}
MainActivity.class
public class MainActivity extends AppCompatActivity {
private RequestQueue requestQueue;
private static final String URL = "........";
private StringRequest request;
private TextView text;
private EditText userName, passWord;
private Button loginButton;
public MainActivity mInstance = this;
#Override
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
text = (TextView) findViewById(R.id.textView);
userName = (EditText) findViewById(R.id.userName);
passWord = (EditText) findViewById(R.id.passWord);
loginButton = (Button) findViewById(R.id.loginButton);
requestQueue = Volley.newRequestQueue(this);
final Intent profilePage = new Intent(this, Profile.class);
loginButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick (View v){
loginButton.setEnabled(false);
request = new StringRequest(Request.Method.POST, URL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
text.setText(response);
switch(response){
case "successful" :
Intent loginCheckerService = new Intent(mInstance, com.erenyenigul.apps.starter.services.loginChecker.class);
Bundle b = new Bundle();
b.putString("username", String.valueOf(userName.getText()));
b.putString("password", String.valueOf(passWord.getText()));
loginCheckerService.putExtras(b);
startService(loginCheckerService);
startActivity(profilePage);
finish();
break;
case "failed" :
Toast.makeText(getApplicationContext(), "Username or Password you entered is wrong!", Toast.LENGTH_LONG).show();
loginButton.setEnabled(true);
break;
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(), "There is a problem with our servers or you don't have internet connection!", Toast.LENGTH_LONG).show();
}
}) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
HashMap<String, String> hashMap = new HashMap<String, String>();
hashMap.put("username", userName.getText().toString());
hashMap.put("password", passWord.getText().toString());
return hashMap;
}
};
requestQueue.add(request);
}
}
);
}
}
There is also a file called Profile.class but it is empty. I tried this but the loop lasted one tour. It stopped even though the connection was ok and the data wasn't changed.

Related

Volley give me only: onErrorResponse

I start to work with volley and when i try to make a post request it give me only errore.
Can you guys tell me when im wrong?
Im working on the Android side of the project with VolleyLibrary.
public class MainActivity extends AppCompatActivity {
private EditText etUsername;
private EditText etPassword;
private Button btnLogin;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
etUsername = findViewById(R.id.etUsername);
etPassword = findViewById(R.id.etPassword);
btnLogin = findViewById(R.id.btnLogin);
btnLogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Login();
}
});
}
private void Login(){
String url = "http://myapies.youcantwatch.it/loginuser_module";
RequestQueue requestQueue = Volley.newRequestQueue(this);
StringRequest stringRequest = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
if(!response.trim().equals("errors")){
Intent intent = new Intent(MainActivity.this, LoggedActivity.class);
startActivity(intent);
} else {
Toast.makeText(MainActivity.this, "Login Fallito", Toast.LENGTH_SHORT).show();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(MainActivity.this, "La chiamata non รจ andata a buon fine", Toast.LENGTH_SHORT).show();
}
}) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
params.put("firstName","adkdmadm");
params.put("password","asdasdjn");
params.put("secretKey","dlwdmkemd3d455");
params.put("username", etUsername.getText().toString().trim());
params.put("passwordasdad", etPassword.getText().toString().trim());
return super.getParams();
}
};
requestQueue.add(stringRequest);
}
}
Replace StringRequest->JSONObjectRequest and check.
Pass request parameters in JSONObject, not in the header,
only pass Content-Type->application/json in header.
change volley to another libs like retrofit volley long time not updated

posting data to mysql database using rest api which is done in magento 2 from my android app?

facing problem in posting data to mysql database using rest api which is done in magento 2 from my android app.
RegisterActivity extends AppCompatActivity {
private static final String TAG = "RegisterActivity";
private static final String URL_FOR_REGISTRATION = "https://xyz/restapi/registration";
ProgressDialog progressDialog;
private EditText signupInputName, signupInputEmail, signupInputPassword, signupInputCnfPassword, signupInputAge;
private Button btnSignUp;
private Button btnLinkLogin;
private RadioGroup genderRadioGroup;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
// Progress dialog
progressDialog = new ProgressDialog(this);
progressDialog.setCancelable(false);
signupInputName = (EditText) findViewById(R.id.signup_input_name);
signupInputEmail = (EditText) findViewById(R.id.signup_input_email);
signupInputPassword = (EditText) findViewById(R.id.signup_input_password);
signupInputCnfPassword = (EditText) findViewById(R.id.signup_input_passwords);
signupInputAge = (EditText) findViewById(R.id.signup_input_age);
btnSignUp = (Button) findViewById(R.id.btn_signup);
btnLinkLogin = (Button) findViewById(R.id.btn_link_login);
btnSignUp.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
submitForm();
}
});
btnLinkLogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent i = new Intent(getApplicationContext(),LoginActivity.class);
startActivity(i);
}
});
}
private void submitForm() {
registerUser(signupInputName.getText().toString(),
signupInputEmail.getText().toString(),
signupInputPassword.getText().toString(),
signupInputCnfPassword.getText().toString(),
signupInputAge.getText().toString());
}
private void registerUser(final String name, final String email, final String password, final String cnfpassword, final String dob) {
// Tag used to cancel the request
String cancel_req_tag = "register";
progressDialog.setMessage("Adding you ...");
showDialog();
StringRequest strReq = new StringRequest(Request.Method.POST,
URL_FOR_REGISTRATION, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d(TAG, "Register Response: " + response.toString());
hideDialog();
try {
JSONObject jObj = new JSONObject(response);
boolean error = jObj.getBoolean("error");
if (!error) {
String user = jObj.getJSONObject("user").getString("name");
Toast.makeText(getApplicationContext(), "Hi " + user +", You are successfully Added!", Toast.LENGTH_SHORT).show();
// Launch login activity
Intent intent = new Intent(
RegisterActivity.this,
LoginActivity.class);
startActivity(intent);
finish();
} else {
String errorMsg = jObj.getString("error_msg");
Toast.makeText(getApplicationContext(),
errorMsg, Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, "Registration Error: " + error.getMessage());
Toast.makeText(getApplicationContext(),
error.getMessage(), Toast.LENGTH_LONG).show();
hideDialog();
}
}) {
#Override
protected Map<String, String> getParams() {
// Posting params to register url
Map<String, String> params = new HashMap<String, String>();
params.put("cust_username", name);
params.put("cust_firstname", email);
params.put("cust_pass", password);
params.put("cust_confirmpass", cnfpassword);
params.put("cust_phoneno", dob);
return params;
}
};
// Adding request to request queue
AppSingleton.getInstance(getApplicationContext()).addToRequestQueue(strReq, cancel_req_tag);
}
private void showDialog() {
if (!progressDialog.isShowing())
progressDialog.show();
}
private void hideDialog() {
if (progressDialog.isShowing())
progressDialog.dismiss();
}
}
I am using Volley library for request.
I am getting this error
BasicNetwork.performRequest: Unexpected response code 503 for
https://xyz/restapi/registration.
My question is am I missing any thing or will there be constrain that should be checked in mysql to post the data.

refresh current page without blinking android

My app has a list and a button to add element to the list and reload it in the same activity, when pressing the button I need to reload the activity without blinking or time of reloading Like when you send message in messenger.I try the following code:
recreate()
tvSender.setText("");
And this code :
Intent intent = getIntent();
finish();
intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
startActivity(intent);
This works but it's still not what i want exact any help pls
the full code :
public class ChatRoom extends AppCompatActivity {
String username;
String username1;
TextView userroom;
String image1;
Message_adapter adapter;
ListView L_MESSAGES;
ArrayList<Messages> messages= new ArrayList<Messages>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_chat_room);
Intent intent = getIntent();
username = intent.getStringExtra("username");
username1 = intent.getStringExtra("username1");
userroom =(TextView) findViewById(R.id.userroom);
final EditText tvSender =(EditText) findViewById(R.id.Sender);
final ImageButton btSender=(ImageButton)findViewById(R.id.btSender);
final ImageButton btBack=(ImageButton)findViewById(R.id.back);
btBack.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(ChatRoom.this, ChatActivity.class);
intent.putExtra("username", username);
intent.putExtra("username1", username1);
ChatRoom.this.startActivity(intent);
}
});
btSender.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final String message=tvSender.getText().toString();
Response.Listener<String> responselistener = new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonObject = new JSONObject(response);
boolean success = jsonObject.getBoolean("success");
if (success) {
recreate();
tvSender.setText("");
}
} catch (JSONException e) {
e.printStackTrace();
}
}
};
MessageSender loginrequest = new MessageSender(message, username,username1, responselistener);
RequestQueue queue = Volley.newRequestQueue(ChatRoom.this);
queue.add(loginrequest);
}
});
getsendMessages();
}
private void getsendMessages(){
String url =config_message.DATA_URL1+username+"&username1="+username1;
userroom.setText(username1);
StringRequest stringRequest = new StringRequest(url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
showJsonFriend(response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError volleyError) {
Toast.makeText(ChatRoom.this,volleyError.getMessage().toString(), Toast.LENGTH_LONG).show();
}
}
);
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
private void showJsonFriend(String response) {
try {
JSONObject jsonObject = new JSONObject(response);
JSONArray result = jsonObject.getJSONArray(config_message.JSON_ARRAY);
JSONObject collegeData =null;
messages.clear();
for(int i=0;i<result.length();i++) {
collegeData = result.getJSONObject(i);
String friend = collegeData.getString(config_message.KEY_SENDER);
image1 = collegeData.getString(config_message.KEY_IMAGE);
String time = collegeData.getString(config_message.KEY_Time);
String sender = collegeData.getString(config_message.KEY_Sender);
messages.add(new Messages(friend,image1,time,sender));
}
} catch (JSONException e) {
e.printStackTrace();
}
L_MESSAGES=(ListView) findViewById(R.id.chatRoomsList);
adapter = new Message_adapter(this,messages);
L_MESSAGES.setAdapter(adapter);
L_MESSAGES.setSelection(L_MESSAGES.getAdapter().getCount()-1);
}
}
this the button to refresh list:
public void onClick(View v) {
final String message=tvSender.getText().toString();
Response.Listener<String> responselistener = new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonObject = new JSONObject(response);
boolean success = jsonObject.getBoolean("success");
if (success) {
recreate();
tvSender.setText("");
}
} catch (JSONException e) {
e.printStackTrace();
}
}
};
MessageSender loginrequest = new MessageSender(message, username,username1, responselistener);
RequestQueue queue = Volley.newRequestQueue(ChatRoom.this);
queue.add(loginrequest);
}
});
There is no need to restart whole Activity. Instead you can insert an element in your list dataset(ArrayList<> or something) and call adapter.notifyDataSetChanged() to make the changes in listview.

App stops working on S6 only

I have no idea whats going on here. My app works perfectly fine on the J5 and J6, but it stops working on the S6 (same android version on all phones)
And it only stops when I have the following code:
When I publish, android studio says 0 errors and 0 warnings
I'm still pretty new to android studio, and I've tried it with Thread myThread and without thread
public class IntroPage extends AppCompatActivity {
private ImageButton btnSkip;
private ImageButton btnUpdate;
// need this for post
RequestQueue requestQueue;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// full screen
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.intro_page);
requestQueue = Volley.newRequestQueue(getApplicationContext());
// outlets
btnSkip = (ImageButton) findViewById(R.id.btnSkip);
btnUpdate = (ImageButton) findViewById(R.id.btnUpdate);
// hide both on default
btnSkip.setVisibility(View.VISIBLE);
btnUpdate.setVisibility(View.GONE);
// when submit is clicked
btnSkip.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent startMainScreen = new Intent(getApplicationContext(), MainActivity.class);
startActivity(startMainScreen);
finish();
}
});
// update
btnUpdate.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);
intent.addCategory(Intent.CATEGORY_BROWSABLE);
intent.setData(Uri.parse("https://play.google.com/store/apps/details?id=ddddddddd"));
startActivity(intent);
}
});
// get app version
PackageInfo pInfo = null;
try {
pInfo = getPackageManager().getPackageInfo(getPackageName(), 0);
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
}
String version = pInfo.versionName;
final Integer versionCode = pInfo.versionCode;
// conn
Thread myThread = new Thread() {
#Override
public void run() {
StringRequest jsonObjectRequest = new StringRequest(Request.Method.POST,
"https://www.domain.com/appVersion.php", new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject responseJson = new JSONObject(response);
Log.i("JSON RESPONSE", responseJson.toString());
// check if we are up to date
if (responseJson.getInt("version") > versionCode) {
btnSkip.setVisibility(View.GONE);
btnUpdate.setVisibility(View.VISIBLE);
} else {
btnSkip.setVisibility(View.VISIBLE);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}) {
// This whole section can be deleted if we dont post vars
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> parameters = new HashMap<>();
parameters.put("club", "Murmur");
parameters.put("device", "Android");
return parameters;
}
};
jsonObjectRequest.setShouldCache(false);
// requestQueue.getCache().remove("https://www.domain.com/appVersion.php");
requestQueue.add(jsonObjectRequest);
}
};
myThread.start();
}
}

HTTP Post Request using Volley

I code to send some message and email using HTTP post using Volley.
when i run the emulator using Genymotion.Everything luking fine but i click the click button it show HTTP has been stopped. I am giving logcat picture Please click this Logcat picture to see Please help me what is wrong and how to resolve this problem
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
public static final String URL_CLICK = "http://www.careoservice.goyalsoftwares.com/feedback/add.php";
public static final String KEY_MESSAGE = "message";
public static final String KEY_EMAIL = "email";
private EditText editTextMessages;
private EditText editTextEmail;
private Button buttonSend;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editTextEmail = (EditText) findViewById(R.id.editmsg);
editTextEmail = (EditText) findViewById(R.id.editmail);
buttonSend = (Button) findViewById(R.id.btnclk);
buttonSend.setOnClickListener(this);
}
public void sendView() throws JSONException {
final String message = editTextMessages.getText().toString().trim();
final String email = editTextEmail.getText().toString().trim();
StringRequest stringRequest = new StringRequest(Request.Method.POST, URL_CLICK, new Response.Listener<String>() {
#Override
public void onResponse(String s) {
Toast.makeText(MainActivity.this,s, Toast.LENGTH_LONG).show();
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(MainActivity.this, error.toString(), Toast.LENGTH_LONG).show();
}
}) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put(KEY_MESSAGE, message);
params.put(KEY_EMAIL, email);
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
#Override
public void onClick(View v) {
if (v == buttonSend) {
try {
sendView();
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}
You are not initialazing the "editTextMessages", this is your null pointer exception.

Categories

Resources