Can a StringRequest be created inside a doInBackground() method? - java

I am creating a button which when clicked calls the checkUserName method which searches the database and tells whether the username is available or not. The URL_CHECK_USERNAME responds "Username Available" or "Username not available".
public void checkUserName(View v){
String username = inputUserName.getText().toString().trim();
new CheckUsername().execute(username);
}
class CheckUsername extends AsyncTask<String, String, String>{
String r = null;
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(RegisterActivity.this);
pDialog.setMessage("Checking Availability of this Username...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected String doInBackground(String... params) {
//String r = null;
final String username = params[0];
StringRequest strReq = new StringRequest(Method.POST,
AppConfig.URL_CHECK_USERNAME, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
r = response;
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError volleyError) {
Log.e(TAG, "Error in checking username." + volleyError.getMessage());
Toast.makeText(getApplicationContext(), volleyError.getMessage(), Toast.LENGTH_SHORT).show();
hideDialog();
}
}){
#Override
protected Map<String, String> getParams() {
Map<String, String> param = new HashMap<>();
//param.put("username", params[0]);
param.put("username", username);
return param;
}
};
AppController.getInstance().addToRequestQueue(strReq);
return r;
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
pDialog.dismiss();
Toast.makeText(RegisterActivity.this, s, Toast.LENGTH_SHORT).show();
}
}
This program displays an empty Toast everytime. What can be the problem?

From the code you posted I suppose you are using Volley as your network library.
If that's the case you should be aware that there's no need for that Asynctask of yours because Volley takes care of the threading for you.
The request will be executed in the background and the callback will be called asynchronously. That 's why your toasts are empty.
Create your StringRequest in your checkUsername(View) method and have the toast shown in the onResponse callback.

Related

How can add a delay to Progress Dialog - Java - Android - Android Studio

I want to make a progress dialog appear for 2 or 3 seconds.
It won't actually do anything other than say progress.
I want to add a delay in progress bar. How can succeed this?
It appears at first but for a very short time.
My code is below:
private void registerNewAccount(String username,String email, String password, String mobile, String gender){
final ProgressDialog progressDialog = new ProgressDialog( RegisterActivity.this);
progressDialog.setCancelable(false);
progressDialog.setIndeterminate(false);
progressDialog.setTitle("Registering New Account");
progressDialog.show();
String uRl = "http://192.168.1.6/Projects/LoginRegisterAndroid/register.php";
StringRequest request = new StringRequest(Request.Method.POST, uRl, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
if (response.equals("Successfull")){
progressDialog.dismiss();
Toast.makeText(RegisterActivity.this, response, Toast.LENGTH_SHORT).show();
startActivity(new Intent(RegisterActivity.this, LoginActivity.class));
finish();
}
else{
progressDialog.dismiss();
Toast.makeText(RegisterActivity.this, response, Toast.LENGTH_SHORT).show();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
progressDialog.dismiss();
Toast.makeText(RegisterActivity.this, error.toString(), Toast.LENGTH_SHORT).show();
}
}){
#Override
protected Map<String, String> getParams() throws AuthFailureError {
HashMap<String,String> param = new HashMap<>();
param.put("username", username);
param.put("email", email);
param.put("psw", password);
param.put("mobile", mobile);
param.put("gender", gender);
return param;
}
};
request.setRetryPolicy(new DefaultRetryPolicy(30000, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
MySingleton.getmInstance(RegisterActivity.this).addToRequestQueue(request);
}
}
I'd suggest using a Handler perhaps:
new Handler(Looper.getMainLooper()).postDelayed(new Runnable() {
#Override
public void run() {
// dismiss progress dialog here
}
}, 3000)
This can be done inside the onRepsonse method in your Volley request

Android Studio / JAVA: How to trace error at android studio using "log"

Currently, I have a problem with my code. An error displayed as follows
Value br of type java.lang.String cannot be converted to JSONObject
I try to find if there a problem at my PHP side, but I also dunno how to trace the problem.
Thus, can I know how to use the log and where I need to put the log in my code?
I hope anyone can help me with this. Thanks
Below is my current code
public class MainActivity extends AppCompatActivity {
EditText etBadgeid, etPassword;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
etBadgeid = findViewById(R.id.etBadgeid);
etPassword = findViewById(R.id.etPassword);
findViewById(R.id.btnLogin).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
userLogin();
}
});
}
private void userLogin() {
final String badgeid = etBadgeid.getText().toString();
final String pwd = etPassword.getText().toString();
class UserLogin extends AsyncTask<Void, Void, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
try {
//converting response to json object
JSONObject obj = new JSONObject(s);
//if no error in response
if (!obj.getBoolean("error")) {
Toast.makeText(getApplicationContext(), obj.getString("message"), Toast.LENGTH_SHORT).show();
//getting the user from the response
JSONObject userJson = obj.getJSONObject("user");
//creating a new user object
User user = new User(
userJson.getString("badgeid"),
userJson.getString("email"),
userJson.getString("fullname"),
userJson.getInt("roles_id"),
userJson.getInt("team_id")
);
//storing the user in shared preferences
SharedPrefManager.getInstance(getApplicationContext()).userLogin(user);
//starting the profile activity
finish();
startActivity(new Intent(getApplicationContext(), Home.class));
} else {
Toast.makeText(getApplicationContext(), "Invalid username or password", Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
#Override
protected String doInBackground(Void... voids) {
//creating request handler object
RequestHandler requestHandler = new RequestHandler();
//creating request parameters
HashMap<String, String> params = new HashMap<>();
params.put("badgeid", badgeid);
params.put("pwd", pwd);
//returing the response
return requestHandler.sendPostRequest(URLs.URL_LOGIN, params);
}
}
UserLogin ul = new UserLogin();
ul.execute();
}
#Override
public void onBackPressed() {
finish();
System.exit(0);
}
}
In android you can log with Log.d(tag,message), and you can view the debug message in the logcat
You should print log before parsing the response string,
...
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
Log.d("onPostExecute","response is: "+s);
try {
//converting response to json object
JSONObject obj = new JSONObject(s);
....
Your response is probably a non json formatted plain text.
for more info
https://developer.android.com/reference/android/util/Log.html#d(java.lang.String,%20java.lang.String)

Show function data without blinking with Volley in Android Studio

Recently I am working on Android project with Volley for registration and for further operation, I can make function for insertion and other one is for retrieval data. When insert button click 'Insert' function called and data has been inserted to database through volley, and at the same time retrieval function also called. But when USER clicked the button and function called then data showed(database inserted data) with blinking effect, look like loading.
I want to get rid of that effect. I want to show data smoothly without any blinking effect. I do searching but can not find any solution. Please suggest me solution I'am newbie so kindly short and efficient required.
package com.darkcoderz.parsejson;
public class MainActivity extends AppCompatActivity {
private Context mContext;
private Activity mActivity;
//private CoordinatorLayout mCLayout;
private TextView mTextView;
private String mJSONURLString = "http://192.168.10.4/volley/api.php";
String url = "http://192.168.10.4/volley/register.php";
private EditText sms;
private Button sendsms;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Get the application context
//mContext = getApplicationContext();
//mActivity = MainActivity.this;
// Get the widget reference from XML layout
//mCLayout = (CoordinatorLayout) findViewById(R.id.coordinator_layout);
mTextView = (TextView) findViewById(R.id.tv);
sms = (EditText) findViewById(R.id.sms);
sendsms = (Button) findViewById(R.id.sendsms);
final Handler firesms = new Handler();
firesms.post(new Runnable() {
#Override
public void run() {
getdata();
firesms.postDelayed(this, 100);
}
});
sendsms.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
reg();
}
});
getdata();
}
// insert
public void reg()
{
final String msg = sms.getText().toString();
StringRequest stringreq = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
if (response.equals("success"))
{
Toast.makeText(MainActivity.this, "Registration Successfull!", Toast.LENGTH_SHORT).show();
}
else
{
Toast.makeText(MainActivity.this, "Username Already Exist!", Toast.LENGTH_SHORT).show();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(MainActivity.this, "Great Error "+error.toString(), Toast.LENGTH_LONG).show();
}
})
{
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String,String> params = new HashMap<>();
params.put("sms",msg);
return params;
}
};
RequestQueue reqest = Volley.newRequestQueue(MainActivity.this);
reqest.add(stringreq);
}
private void getdata() {
// Empty the TextView
mTextView.setText("");
// Initialize a new RequestQueue instance
RequestQueue requestQueue = Volley.newRequestQueue(MainActivity.this);
// Initialize a new JsonArrayRequest instance
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(Request.Method.GET, mJSONURLString, null, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
// Do something with response
//mTextView.setText(response.toString());
// Process the JSON
try{
// Loop through the array elements
for(int i=0;i<response.length();i++){
// Get current json object
JSONObject student = response.getJSONObject(i);
// Get the current student (json object) data
// String firstName = student.getString("fname");
// String lastName = student.getString("lname");
String age = student.getString("email");
// Display the formatted json data in text view
mTextView.append("SMS : " + age);
mTextView.append("\n\n");
}
}catch (JSONException e){
e.printStackTrace();
}
}
},
new Response.ErrorListener(){
#Override
public void onErrorResponse(VolleyError error){
// Do something when error occurred
Toast.makeText(mContext, "Something Went Wrong", Toast.LENGTH_SHORT).show();
}
}
);
// Add JsonArrayRequest to the RequestQueue
requestQueue.add(jsonArrayRequest);
}
}
private void getdata() {
// Empty the TextView
mTextView.setText("");
// Initialize a new RequestQueue instance
RequestQueue requestQueue = Volley.newRequestQueue(MainActivity.this);
// Initialize a new JsonArrayRequest instance
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(Request.Method.GET, mJSONURLString, null, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
//before parsing check your response is in JSONArray Format or JSONObject format
// Process the JSON
try{
}catch (JSONException e){
e.printStackTrace();
//print here to know JSONException if exists
Toast.makeText(mContext, "Exception"+e.toString(), Toast.LENGTH_SHORT).show();
}
}
}
},
new Response.ErrorListener(){
#Override
public void onErrorResponse(VolleyError error){
// Do something when error occurred
Toast.makeText(mContext, "Something Went Wrong", Toast.LENGTH_SHORT).show();
}
}
);
// Add JsonArrayRequest to the RequestQueue
requestQueue.add(jsonArrayRequest);
}

What would be the simplest way of posting data using Volley?

I am trying to use Volley to send 3 strings to a php script that sends it to a localhost server. I have this so far;
RegisterRequest;
public class RegisterRequest extends StringRequest {
private static final String REGISTER_REQUEST_URL = "http://192.168.*.*:80/phptesting/Register.php";
private Map<String, String> params;
public RegisterRequest(String username, String password,String isAdmin,
Response.Listener<String> listener,
Response.ErrorListener errListener){
super(Method.POST, REGISTER_REQUEST_URL,listener,errListener);
params = new HashMap<>();
params.put("username",username);
params.put("password",password);
params.put("isAdmin",isAdmin+"");
}
public Map<String, String> getparams() {
return params;
}
}
This is CreateUser;
public class CreateUser extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_create_user);
this.setTitle("Create User");
final EditText username1 = findViewById(R.id.Createusername);
final EditText password1 = findViewById(R.id.CreatePassword);
final Switch isAdmin = findViewById(R.id.isadmin);
final Button createuser = findViewById(R.id.createuserbtn);
if (getIntent().hasExtra("com.example.northlandcaps.crisis_response")){
isAdmin.setVisibility(View.GONE);
}
createuser.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final String username = username1.getText().toString();
final String password = password1.getText().toString();
final String isadmin = isAdmin.getText().toString();
Response.Listener<String> responseListener = new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d("Response Value: ", response);
if (response.equals("success")){
Intent intent = new Intent(CreateUser.this, MainActivity.class);
CreateUser.this.startActivity(intent);
}else{
AlertDialog.Builder builder = new AlertDialog.Builder(CreateUser.this);
builder.setMessage("Register Failed")
.setNegativeButton("Retry",null)
.create()
.show();
}
}
};Response.ErrorListener errorListener = new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(), String.valueOf(error), Toast.LENGTH_SHORT).show();
}
};
RegisterRequest registerRequest = new RegisterRequest(username,password,isadmin,responseListener,errorListener);
RequestQueue queue = Volley.newRequestQueue(CreateUser.this);
queue.add(registerRequest);
}
});
}
Now, the only error im getting is an Undefined index. And thats because Volley isnt sending data to the php script. The php script does work properly when data is sent to it, so my question is this; what changes do i have to make to my script for it to send the 3 strings over?
Never mess with code or else it will be confusing for you to handle things properly.
So just make another class and use it in your activity.
Have a look at this class I have written, you can use it anywhere and for any type of data request.
public class SendData {
private Context context;
private String url;
private HashMap<String, String> data;
private OnDataSent onDataSent;
public void setOnDataSent(OnDataSent onDataSent) {
this.onDataSent = onDataSent;
}
public SendData(Context context, String url, HashMap<String, String> data) {
this.context = context;
this.url = url;
this.data = data;
}
public void send(){
StringRequest stringRequest = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
if(onDataSent != null){
onDataSent.onSuccess(response);
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
if(onDataSent != null){
onDataSent.onFailed(error.toString());
}
}
}){
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> map = new HashMap<>();
map.putAll(data);
return map;
}
};
stringRequest.setRetryPolicy(new DefaultRetryPolicy(0, 0, 0));
RequestQueue requestQueue = Volley.newRequestQueue(context);
requestQueue.add(stringRequest);
}
public interface OnDataSent{
void onSuccess(String response);
void onFailed(String error);
}
}
And now you can easily use it from any activity. Just give data in the constructor and use the interface to track the events this way
HashMap<String, String> data = new HashMap<>();
data.put("username", "");//define the value
data.put("password", "");//define the value
data.put("is_admin", "");//define the value
SendData sendData = new SendData(this, "", data); //defie the context and url properly
sendData.setOnDataSent(new SendData.OnDataSent() {
#Override
public void onSuccess(String response) {
//parse the response
}
#Override
public void onFailed(String error) {
//something went wrong check the error
}
});
sendData.send();

Android Volley- How to send raw text and get json response

I am new to android and using volley to communicate with web services.
Postman details
I found sending a raw text to the web service will only work on postman.I try using grant_type=password&username=myusername&password=mypassowrd getting myusername and mypassword from two editText from my mainActivity, .
Is there any better way to achieve this?
public class MainActivity extends AppCompatActivity {
Button btnLogin,btnFetch,btnExit;
EditText editTxtUsr,editTxtPass;
TextView txtView;
String uRL ="****";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnLogin=findViewById(R.id.buttonLogin);
btnFetch=findViewById(R.id.buttonFetch);
btnExit=findViewById(R.id.buttonExit);
editTxtUsr=findViewById(R.id.editTextUsrname);
editTxtPass=findViewById(R.id.editTextPassword);
txtView=findViewById(R.id.textViewData);
btnLogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String wsURL = uRL + "/authtoken";
//final String appData = "grant_type=password&username=" + editTxtUsr + "&password=" + editTxtPass;
StringRequest request = new StringRequest(Request.Method.POST, wsURL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
if (response.equals("true")) {
Toast.makeText(MainActivity.this, "Login Successful", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(MainActivity.this, "Incorrect ", Toast.LENGTH_SHORT).show();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError volleyError) {
Toast.makeText(MainActivity.this, "Some error occured" + volleyError, Toast.LENGTH_SHORT).show();
}
}) {
#Override
public Map<String,String> getHeaders() throws AuthFailureError {
Map<String, String> headers = new HashMap<>();
headers.put("Content-Type", "application/text");
headers.put("charset", "TYPE_UTF8_CHARSET");
return headers;
}
#Override
protected Map<String,String> getParams() throws AuthFailureError {
Map<String, String> parameters = new HashMap<>();
parameters.put("grand_type", "SET_VALUE");
parameters.put("Username", editTxtUsr.getText().toString());
parameters.put("Password", editTxtPass.getText().toString());
return parameters;
}
};
RequestQueue rQueue= Volley.newRequestQueue(MainActivity.this);
rQueue.add(request);
}
});
btnExit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
finish();
}
});
}
}
I have tried various ways to achieve this, but with no luck. That's a sample of my code that I use to try to connect to the web service.
I get [253] BasicNetwork.performRequest: Unexpected response code 400 for...
I searched thoroughly through StackOverflow but I can't seem to find the correct answer to my question.
Any help would be appreciated.
Its been days I have been working on this but after I posted my question, I found the solution after some tries.
The answer is simpler than I have thought.
What you need to do is make an objectrequest and override the body with the text you want to post. Nothing had to change in headers or parameters.
I still can't find an answer using Stringrequest.
#Override
public byte[] getBody() {
try {
return requestBody.getBytes("utf-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
return null;
}
}
Where requestBody is the raw text you want to send as a string.

Categories

Resources