First name is not displaying in android using arraylist - android

Hi in the below first name is not passing correctly to another activity.Can any one help me.
I am comparing my username with user_name if both are equal then I am sending my first name to another activity.
Support my username is admin and user_name is admin then I am able to pass the first name from the api. If it is second list item it is not working.
private void fetchUserJSON(final String sessionId, final String username){
handler.postDelayed(new Runnable() {
#Override
public void run() {
// Write code for your refresh logic
// progressDialog = new ProgressDialog(getActivity());
// progressDialog.setIndeterminate(true);
// progressDialog.setMessage("Loading...");
// progressDialog.setCanceledOnTouchOutside(false);
// progressDialog.setCancelable(false);
// progressDialog.show();
// sessionId = getIntent().getStringExtra("sessionId");
//username = getIntent().getStringExtra("username");
String operation = "query";
String query = "select * from Users";
final GetNoticeDataService service = RetrofitInstance.getRetrofitInstance().create(GetNoticeDataService.class);
/** Call the method with parameter in the interface to get the notice data*/
Call<UserModule> call = service.UserRecordDetails(operation, sessionId, query);
/**Log the URL called*/
Log.i("URL Called", call.request().url() + "");
call.enqueue(new Callback<UserModule>() {
#Override
public void onResponse(Call<UserModule> call, Response<UserModule> response) {
Log.e("response", new Gson().toJson(response.body()));
if (response.isSuccessful()) {
Log.e("response", new Gson().toJson(response.body()));
UserModule userModule = response.body();
String success = userModule.getSuccess();
if (success.equals("true")) {
Results_Users results = userModule.getResult();
records = results.getRecords();
for (Records records1 : records) {
String user_name = records1.getUser_name();
String id = records1.getId();
Log.d("id",id);
String first_name = records1.getFirst_name();
String last_name = records1.getLast_name();
String email1=records1.getEmail1();
String title=records1.getTitle();
Records records=new Records(user_name,title,first_name,last_name,email1,id);
recordsList.add(records);
}
if(username.equals(recordsList.get(0).getUser_name()))
i = new Intent(LoginActivity.this, MainActivity.class);
i.putExtra("first_name", recordsList.get(2).getFirst_name());
startActivity(i);
finish();
}
}
}
#Override
public void onFailure(Call<UserModule> call, Throwable t) {
}
// progressDialog.dismiss();
});
}
}, 0);
return ;
}

Remove final from for loop
for (Records records1 : records) {

I don't know the logic of your whole code. But you can edit your loop like this:
String first_name = null;
for (Records records1 : records) {
if (username.equals(records1.getUser_name())) {
first_name = records1.getFirst_name();
break;
}
}
i = new Intent(LoginActivity.this, MainActivity.class);
i.putExtra("first_name", first_name);
startActivity(i);
finish();

Related

Android Retrofit get response before cursor next loop

#OnClick(R.id.btnCheckStockId) void callCheck() {
MyDatabaseHelper dbHelper = new MyDatabaseHelper(ScanBarcodeActivity.this);
final SQLiteDatabase sql = dbHelper.getWritableDatabase();
String query = "SELECT barcode FROM stockopname where lokasi_item = ?";
cursor = sql.rawQuery(query, new String[]{lokasiItem});
try {
while (cursor.moveToNext()) {
final String stockId = cursor.getString(cursor.getColumnIndex("barcode"));
//API RETROFIT
ApiService api_check = ApiClient.getClient().create(ApiService.class);
Call<String> call = api_check.check_barcode(stockId);
call.enqueue(new Callback<String>() {
#Override
public void onResponse(Call<String> call, Response<String> response) {
//get result
String sync_result = response.body();
String set_sync = "";
if (sync_result == "true") {
set_sync = "true";
} else {
set_sync = "false";
}
//update data on sqlite
ContentValues updatecolumn = new ContentValues();
updatecolumn.put("is_sync", set_sync);
sql.update("stockopname", updatecolumn, "barcode = ?", new String[]{stockId});
}
#Override
public void onFailure(Call<String> call, Throwable t) {
Toast.makeText(getApplicationContext(), t.getMessage(), Toast.LENGTH_LONG).show();
}
});
}
}
catch (Exception ex)
{
ex.printStackTrace();
}
}
So the logic is, get a list from stock_id from the local database then check the server with API, if true the stock_id already exists on the server, if false the stock_id data does not yet exist. and the results of the responses need to be updated back to the local database with the column is_sync = true/false
when debugging, the pointer does not enter into onResponse but enters the next loop
I want to ask and need advice on how to get a response from the server immediately before the next loop in the cursor (using sqlite database), is there a solution?
Update, My Solution after reconstruct the code :
#OnClick(R.id.btnCheckStockId) void callCheck() {
MyDatabaseHelper dbHelper = new MyDatabaseHelper(ScanBarcodeActivity.this);
SQLiteDatabase sql = dbHelper.getWritableDatabase();
String query = "SELECT barcode FROM stockopname where lokasi_item = ?";
cursor_checksync = sql.rawQuery(query, new String[]{lokasiItem});
if (cursor_checksync != null) {
//more to the first row
cursor_checksync.moveToFirst();
//iterate over rows
for (int i = 0; i < cursor_checksync.getCount(); i++) {
callCheckSync(cursor_checksync);
cursor_checksync.moveToNext();
}
//close the cursor
cursor.close();
}
}
public void callCheckSync(Cursor csr_checksync)
{
final String stockId = csr_checksync.getString(csr_checksync.getColumnIndex("barcode"));
//API RETROFIT
ApiService api_check = ApiClient.getClient().create(ApiService.class);
Call<String> call = api_check.check_barcode(stockId);
call.enqueue(new Callback<String>() {
#Override
public void onResponse(Call<String> call, Response<String> response) {
//get result
if(response.isSuccessful())
{
String sync_result = response.body();
String set_sync = "";
if (sync_result == "true") {
set_sync = "true";
} else {
set_sync = "false";
}
//update data on sqlite
update(stockId, set_sync);
}
}
#Override
public void onFailure(Call<String> call, Throwable t) {
Toast.makeText(getApplicationContext(), t.getMessage(), Toast.LENGTH_LONG).show();
}
});
}
public void update(String Barcode, String value)
{
MyDatabaseHelper dbHelper = new MyDatabaseHelper(ScanBarcodeActivity.this);
SQLiteDatabase sql = dbHelper.getWritableDatabase();
ContentValues updatecolumn = new ContentValues();
updatecolumn.put("is_sync", value);
sql.update("stockopname", updatecolumn, "barcode = ?", new String[]{Barcode});
}
I don't know if this is the best approach, but it solves my problem.
Call this method on onClick after defining initial cursor. Sorry for syntax I dont have IDE.
public void callMethod(Cursor cursor){
if (cursor.moveToNext()) {
//Retrofit
onResponse: () -> {
callMethod(cursor);
}
}else {
cursor.close();
}
}

Error on Logging in Still prompts but still Logs in

I am developing a mobile application that has 2 types of users.
In my php code, I separated the boolean for each user. success for the client and success1 for the stylist.
When I press log in, the error prompts first following is the fast intent for the successful menu profile.
This is my line of codes from LoginRegister.java
private ProgressBar loading;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
final EditText userLoginUsername = (EditText) findViewById(R.id.loginUser);
final EditText userLoginPassword = (EditText) findViewById(R.id.loginPass);
final Button Login = (Button) findViewById(R.id.buttonLogin);
final Button Register = (Button) findViewById(R.id.buttonRegister);
loading = findViewById(R.id.loadinglogin);
//login
Login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final String username = userLoginUsername.getText().toString();
final String password = userLoginPassword.getText().toString();
if(!username.isEmpty() && !password.isEmpty()) {
Login.setVisibility(View.GONE);
loading.setVisibility(View.VISIBLE);
Response.Listener<String> responseListener = new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonResponse = new JSONObject(response);
boolean success = jsonResponse.getBoolean("success");
boolean success1 = jsonResponse.getBoolean("success1");
//Client's Log in
if (success) {
//gikan sa php (green ones) to strings sa android
String username = jsonResponse.getString("username");
String name = jsonResponse.getString("name");
String number = jsonResponse.getString("number");
String gender = jsonResponse.getString("gender");
String address = jsonResponse.getString("address");
String occupation = jsonResponse.getString("occupation");
String birth_date = jsonResponse.getString("birth_date");
String user_type = jsonResponse.getString("user_type");
Intent intent = new Intent(LoginRegister.this, ProfileActivity.class);
//from strings to pass sa lain intents.
intent.putExtra("username",username);
intent.putExtra("number",number);
intent.putExtra("name", name);
intent.putExtra("gender", gender);
intent.putExtra("address", address);
intent.putExtra("occupation", occupation);
intent.putExtra("birthDate", birth_date);
intent.putExtra("userType", user_type);
LoginRegister.this.startActivity(intent);
finish();
} else {
AlertDialog.Builder builder = new AlertDialog.Builder(LoginRegister.this);
builder.setMessage("Login Failed! Please provide valid username and password or connect to internet.")
.setNegativeButton("Retry", null)
.create()
.show();
Login.setVisibility(View.VISIBLE);
loading.setVisibility(View.GONE);
}
//Stylist's Log in
if(success1) {
String user_type = jsonResponse.getString("user_type");
Intent intent = new Intent(LoginRegister.this, ProfileActivity.class);
intent.putExtra("userType", user_type);
LoginRegister.this.startActivity(intent);
finish();
} else {
AlertDialog.Builder builder = new AlertDialog.Builder(LoginRegister.this);
builder.setMessage("Login Failed! Please provide valid username and password or connect to internet.")
.setNegativeButton("Retry", null)
.create()
.show();
Login.setVisibility(View.VISIBLE);
loading.setVisibility(View.GONE);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
};
LoginRequest loginRequest = new LoginRequest(username, password, responseListener);
RequestQueue queue = Volley.newRequestQueue(LoginRegister.this);
queue.add(loginRequest);
}else if(username.isEmpty() ){
userLoginUsername.setError("Please insert a username");
}else if(password.isEmpty()){
userLoginPassword.setError("Please put your password");
}
}
});
//register
Register.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent Register = new Intent(LoginRegister.this, RegisterCustomerOrStylist.class);
LoginRegister.this.startActivity(Register);
}
});
}
PS they have different datas from different tables. What I did is that I have an if condition that if the boolean of success (client) is true, it passes the data and its else is the alertdialog for error login. After it is another if statement for the success1 (stylist) which has the same logic with client.
If simplified, your code looks like this.
//Client's Log in
if (success) {
} else {
AlertDialog.Builder builder = ...
}
//Stylist's Log in
if(success1) {
} else {
AlertDialog.Builder builder
}
This means if a stylist tries to log in, client's log in block alert dialog will be shown, and vice versa.
So, a flag may be needed to check any success exists.
boolean successAny = success || suucess1;
//Client's Log in
if (success) {
} else {
if (!successAny) {
AlertDialog.Builder builder = ...
}
}
...
NB. A person is a client and also be a stylist case is not intended for this sample.

Window Leaked in Async task while showing progress dialog

I have one AsyncTask I am showing progress dialog in preExecute() method of an async task and dismissing it in postExecute() method of an async task.
I am also checking if the dialog is null or not. Also set setCancelable as false to progress dialog. Tried every solution given on SO but still window is getting leaked.
Async Task :
public class RegisterUserAsyncTask extends AsyncTask<String, Void, JSONObject> {
String api;
JSONObject jsonParams;
String muserName;
String mfullName;
String mpassword;
String mmobileNo;
String memailId;
String mdeviceId;
File mprofileImage;
private ProgressDialog progressDialog = null;
private static String KEY_SUCCESS = "Success";
private Context mContext;
public RegisterUserAsyncTask(Context context, String fullName, String userName, String password, String mobileNo, String emailId, String deviceId, File profileImage) {
this.mContext = context;
this.muserName = userName;
this.mpassword = password;
this.mfullName = fullName;
this.mmobileNo = mobileNo;
this.memailId = emailId;
this.mdeviceId = deviceId;
this.mprofileImage = profileImage;
}
#Override
protected void onPreExecute(){
super.onPreExecute();
if(progressDialog == null) {
progressDialog = new ProgressDialog(mContext);
progressDialog.setMessage("Creating Account...");
progressDialog.setIndeterminate(true);
progressDialog.setCancelable(false);
progressDialog.show();
}
else {
progressDialog.dismiss();
}
}
#Override
protected JSONObject doInBackground(String... params) {
try {
//Url
api = ServiceUrl.getBaseUrl() + ServiceUrl.getregister();
//Build JsonObject
jsonParams = new JSONObject();
String userName = this.muserName; // params[0] is username
String fullName = this.mfullName; // params[1] is fullname
String password = this.mpassword; // params[2] is password
String mobileNo = this.mmobileNo; // params[3] is mobile
String emailId = this.memailId; // params[4] is emailid
String deviceId = this.mdeviceId; // params[5] is deviceid
jsonParams.put("full_name", fullName);
jsonParams.put("user_name", userName);
jsonParams.put("password", password);
jsonParams.put("mobile_no", mobileNo);
jsonParams.put("email_id", emailId);
jsonParams.put("device_id", deviceId);
try {
if(convertFileToString(this.mprofileImage)!=null) {
jsonParams.put("profile_image", convertFileToString(this.mprofileImage));
System.out.println("convertFileToString(profile_image)" + convertFileToString(this.mprofileImage));
}
else
{ jsonParams.put("profile_image", " null");}
} catch (Exception e) {
System.out.println("convertFileToString(profile_image)");
}
ServerRequest request = new ServerRequest(api, jsonParams);
return request.sendRequest();
} catch (JSONException je) {
return Excpetion2JSON.getJSON(je);
}
} //end of doInBackground
#Override
protected void onPostExecute(JSONObject response) {
super.onPostExecute(response);
if (response.has("message")) {
String message = null;
try {
if (response.getString("message").equalsIgnoreCase(KEY_SUCCESS)) {
Toast.makeText(mContext, "success", Toast.LENGTH_LONG).show();
progressDialog.dismiss();
progressDialog = null;
} else {
Toast.makeText(mContext, "Could not Register ", Toast.LENGTH_LONG).show();
Intent intent = new Intent(mContext, RegisterActivity.class).setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
progressDialog.dismiss();
progressDialog = null;
mContext.startActivity(intent);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}
In activity calling RegisterAsyncTask in onClicked method of a button in onCreate() method of an activity.
b1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
if (checkValidation()) {
registerUser();
} else
Toast.makeText(RegisterActivity.this, "Form contains error", Toast.LENGTH_LONG).show();
}
});
}
private void registerUser() {
String userName = edtuserName.getText().toString();
String fullName = edtfullName.getText().toString();
String password = edtPassword.getText().toString();
String confirm = edtconfirmPassword.getText().toString();
String mobileNo = edtmobile.getText().toString();
String emailId = edtemail.getText().toString();
String deviceId = "233";
new RegisterUserAsyncTask(RegisterActivity.this, fullName, userName, password, mobileNo, emailId, deviceId,mProfileImage).execute();
}
What to do for this?
Please help. Thank you..
This problem may occurs due to "context". Progress dialog have a context of an activity but you may doing finish activity before complete the async task. So please check it once.

How to return Object which is inside anonymous inner class?

I've created this code to access user from my database for Login purpose. I can access the object 'st' when I'm inside OnResponse method but when I try to return return the object, it gives me null. Also when I try to access this st object before returning, it gives NullPointerException. What is the exact problem?
public class ServerRequests {
ProgressDialog progressDialog;
public static user_Student st;
public static final int CONNECTION_TIMEOUT = 1000 * 15;
public static final String SERVER_ADDRESS = "http://prem-pc:8989/";
Context ct;
public ServerRequests(Context context) {
ct = context;
progressDialog = new ProgressDialog(context);
progressDialog.setCancelable(false);
progressDialog.setTitle("Processing");
progressDialog.setMessage("Please Wait....");
}
public ServerRequests() {
}
public user_Student fetchUserDataInBackground(user_Student user) {
progressDialog.show();
Toast.makeText(ct, "Data in background: ", Toast.LENGTH_SHORT).show();
user_Student ust = doInBackground(user);
progressDialog.dismiss();
return ust;
}
public user_Student doInBackground(user_Student user) {
String URL = SERVER_ADDRESS + "connect.php?prn=" + user.prn + "&password=" + user.password;
RequestQueue req = Volley.newRequestQueue(ct);
Toast.makeText(ct, "Do in Background", Toast.LENGTH_SHORT).show();
JsonObjectRequest jsonObjReq = new JsonObjectRequest(Request.Method.GET, URL, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject jObject) {
try {
// Parsing json object response
// response will be a json object
if (jObject.length() == 0) {
st = null;
Toast.makeText(ct, "Null JSON Object", Toast.LENGTH_SHORT).show();
} else {
String prn = jObject.getString("prn");
String fname = jObject.getString("fname");
String mname = jObject.getString("mname");
String lname = jObject.getString("lname");
String clas = jObject.getString("clas");
String dept = jObject.getString("dept");
String batch = jObject.getString("batch");
String scontact = jObject.getString("scontact");
String pcontact = jObject.getString("pcontact");
String email = jObject.getString("email");
String password = jObject.getString("password");
String dob = jObject.getString("dob");
st = new user_Student(prn, fname, mname, lname, clas, dept, batch, scontact, pcontact, email, password, dob);
Toast.makeText(ct, "JSON Object:" + st.fname, Toast.LENGTH_SHORT).show();
}
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(ct, "Error: " + e.getMessage(), Toast.LENGTH_LONG).show();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(ct, error.getMessage(), Toast.LENGTH_SHORT).show(); // hide the progress dialog
}
});
req.add(jsonObjReq);
//Toast.makeText(ct,"DO in back End"+st.fname,Toast.LENGTH_SHORT).show();
return st;
}
}
You can't return from anonymous inner classes, but you could create a method inside ServerRequests that takes a user_Student as a parameter and call that method from within onResponse. This method could then do whatever you need.
You must use AsyncTask to do funtion doInBackground(user_Student user)
You can view this post to understand AsyncTask:
How to use AsyncTask correctly in Android

HTTPAsyncClient skipping the first time

I am using HTTPAsyncClient to send a post request to the server , and it is activated with a button press (named checkbox) the problem is now when I press the first time It skips going into the TextHttpResponseHandler() and so it doesn't send anything to the server , but on the second press It gets into the function normally and calls the server , also when I switch to another activity it does the same thing and skips going into the response
handler.
EDIT: I was debugging the program and I realized it does not skip the part as much as for the first run , it does not call the server at all , and returns the server_response=null but on the second call it calls the server and everything goes right
Edit2: Looking further into my code with debugging , I realized that the real problem is that the AsyncHttpClient client = new AsyncHttpClient(); takes time to get initialized that's why the response doesn't come out at first because there was not actual server call sent , but on the second time the AsyncHttpClient client = new AsyncHttpClient(); is initialized and the connection established that is why it gives out a response and acts normally , the question is now how do I fix this to make it work seamlessly
Here is the code :
public class RegisterFragment extends Fragment {
ProgressBar progressBar;
ImageView checkbutton;
EditText first_name_ET;
EditText last_name_ET;
EditText email_ET;
EditText password_ET;
EditText confirm_password_ET;
EditText phone_ET;
EditText username_ET;
String first_name;
String last_name;
String email;
String password;
String confirm_password;
String phone;
String username;
Pattern pattern;
Matcher matcher;
String URL = "http://198.58.109.238/engezni/public/android/register";
String USER_PREF = "User Pref";
String server_response = null;
String response_function_result = null;
public RegisterFragment() {
// Required empty public constructor
}
#TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1)
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final View view = inflater.inflate(R.layout.fragment_register, container, false);
progressBar = (ProgressBar) view.findViewById(R.id.progressbar);
getView();
progressBar.setVisibility(View.GONE);
if (view != null) {
first_name_ET = (EditText) view.findViewById(R.id.first_name_ET);
last_name_ET = (EditText) view.findViewById(R.id.last_name_ET);
email_ET = (EditText) view.findViewById(R.id.email_ET);
password_ET = (EditText) view.findViewById(R.id.password_ET);
confirm_password_ET = (EditText) view.findViewById(R.id.confirm_password_ET);
phone_ET = (EditText) view.findViewById(R.id.phone_ET);
username_ET = (EditText) view.findViewById(R.id.username_ET);
checkbutton = (ImageView) view.findViewById(R.id.check_button);
}
first_name = first_name_ET.getText().toString().trim();
last_name = last_name_ET.getText().toString().trim();
email = email_ET.getText().toString().trim();
password = password_ET.getText().toString().trim();
confirm_password = confirm_password_ET.getText().toString().trim();
phone = phone_ET.getText().toString().trim();
username = username_ET.getText().toString().trim();
checkbutton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (Validate()) {
response_function_result = null;
response_function_result = SendToServer(first_name, last_name, email, password, phone, username);
if (response_function_result != null) {
if (ServerErrorHandler(response_function_result)) {
/*Saving the fields in shared prefs and going to another activity*/
SharedPreferences.Editor save = getActivity().getSharedPreferences(USER_PREF, 0).edit();
save.putString("User Name", first_name + " " + last_name);
save.putString("Email", email);
save.putString("Password", password);
save.putString("Phone", phone);
save.putString("Name", username);
save.commit();
Intent intent = new Intent(getActivity(), SignInScreen.class);
startActivity(intent);
}
}
}
}
});
return view;
}
public boolean Validate() {
first_name = first_name_ET.getText().toString().trim();
last_name = last_name_ET.getText().toString().trim();
email = email_ET.getText().toString().trim();
password = password_ET.getText().toString().trim();
confirm_password = confirm_password_ET.getText().toString().trim();
phone = phone_ET.getText().toString().trim();
username = username_ET.getText().toString().trim();
final String EMAIL_PATTERN = "^[_A-Za-z0-9-]+(\\.[_A-Za-z0-9-]+)*#[A-Za-z0-9]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";
pattern = Pattern.compile(EMAIL_PATTERN);
matcher = pattern.matcher(email);
if (first_name.length() < 4 || first_name.length() > 30) {
first_name_ET.setError("First name should be 4 chartacters or more");
return false;
} else {
first_name_ET.setError(null);
}
if (last_name.length() < 4 || last_name.length() > 30) {
last_name_ET.setError("First name should be 4 chartacters or more");
return false;
} else {
last_name_ET.setError(null);
}
if (!matcher.matches()) {
email_ET.setError("Invalid Email ex:example#domain.com");
return false;
} else {
email_ET.setError(null);
}
if (password.length() < 6) {
password_ET.setError("Password has to be 6 characters or more");
return false;
} else {
password_ET.setError(null);
}
if (!confirm_password.equals(password)) {
confirm_password_ET.setError("Password does not match");
return false;
} else {
confirm_password_ET.setError(null);
}
if (phone.length() < 11) {
phone_ET.setError("Phone number invalid");
return false;
} else {
phone_ET.setError(null);
}
return true;
}
public String SendToServer(String first_name, String last_name, String email, String password, String phone, String username) {
AsyncHttpClient client = new AsyncHttpClient();
StringEntity stringEntity = null;
JsonArray jsonArray = new JsonArray();
JsonObject jsonObject = new JsonObject();
try {
jsonObject.addProperty("username", first_name + last_name);
jsonObject.addProperty("email", email);
jsonObject.addProperty("password", password);
jsonObject.addProperty("name", username);
jsonObject.addProperty("phone", phone);
jsonObject.addProperty("dop", "dummy DOP");
jsonArray.add(jsonObject);
stringEntity = new StringEntity(jsonArray.toString());
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
client.post(getActivity().getApplicationContext(), URL, stringEntity, "application/json", new TextHttpResponseHandler() {
#Override
public void onStart() {
super.onStart();
progressBar.setVisibility(View.VISIBLE);
}
#Override
public void onFinish() {
super.onFinish();
progressBar.setVisibility(View.GONE);
}
#Override
public void onFailure(int i, Header[] headers, String s, Throwable throwable) {
Toast.makeText(getActivity(), "onfaaail", Toast.LENGTH_LONG).show();
}
#Override
public void onSuccess(int i, Header[] headers, String s) {
server_response = s;
SharedPreferences.Editor save = getActivity().getSharedPreferences(USER_PREF, 0).edit();
save.putString("Server Response", server_response);
save.commit();
}
});
return server_response;
}
public boolean ServerErrorHandler(String response) {
String error_message = "Error Message: ";
// Checks for errors.
if (response.contains("INVALID") || response.contains("EXISTS")) {
// error occured.
if (response.contains("EMAIL_INVALID")) {
error_message = error_message + " Invalid Email";
}
if (response.contains("PASSWORD_INVALID")) {
error_message = error_message + " Invalid Password";
}
if (response.contains("PHONE_INVALID")) {
error_message = error_message + " Invalid Phone";
}
if (response.contains("NAME_INVALID")) {
error_message = error_message + " Invalid Name";
}
if (response.contains("DOP_INVALID")) {
error_message = error_message + " Invalid DoP";
}
if (response.contains("USERNAME_INVALID")) {
error_message = error_message + " Invalid Username";
}
if (response.contains("USERNAME_EXIST")) {
error_message = error_message + " Name Exists";
}
if (response.contains("EMAIL_EXIST")) {
error_message = error_message + " Email Exists";
}
if (response.contains("PHONE_EXIST")) {
error_message = error_message + " Phone Exists";
}
Toast.makeText(getActivity().getApplicationContext(), error_message, Toast.LENGTH_LONG).show();
return false;
} else {
/*No error*/
Toast.makeText(getActivity().getApplicationContext(), "Registered", Toast.LENGTH_LONG).show();
return true;
}
}
}
When you do this: response_function_result = SendToServer(first_name, last_name, email, password, phone, username);
An Asynchronous request is made to your validation server. This basically means that there's a background thread on which the whole request is made and your main thread does not wait for the results. So while the validation request is going on in the background, this line executes straightaway return server_response; which is null and hence it returns null.

Categories

Resources