Related
The code below is a portion of the registration page of an application. I've recently asked a question on the errors in my code, and I was told that the Handler was always calling onSignupSuccess. How do I ensure that according to the success or failure of the boolean emailsuccess, the Handler will run onSignupSuccess and onSignupFailed, or the code under the else statement, respectively?
link_login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent login = new Intent(SignUp.this, Login.class);
startActivity(login);
}
});
signupbutton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
signup();
}
});
}
public void signup() {
Log.d(TAG, "Signup");
if(!validate()) {
onSignupFailed();
return;
}
signupbutton.setEnabled(false);
final ProgressDialog progressDialog = new ProgressDialog(SignUp.this, R.style.Theme_AppCompat_DayNight_Dialog_Alert);
progressDialog.setIndeterminate(true);
progressDialog.setMessage("Creating Account");
progressDialog.show();
final String name = inputname.getText().toString();
final String email = inputemail.getText().toString();
final String password = inputpassword.getText().toString();
final int number = Integer.parseInt(inputnumber.getText().toString());
Response.Listener<String> responseListener = new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonResponse = new JSONObject(response);
boolean emailsuccess = jsonResponse.getBoolean("emailsuccess");
if (emailsuccess) {
onSignupSuccess();
return;
}
else {
onSignupFailed();
AlertDialog.Builder cancel = new AlertDialog.Builder(SignUp.this);
cancel.setTitle("Registration Failed");
cancel.setMessage("Email already in database.");
cancel.setNegativeButton("Retry", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
cancel.create();
cancel.show();
return;
}
} catch (JSONException e) {
e.printStackTrace();
}
}
};
RegisterRequest registerRequest = new RegisterRequest(name, email, password, number, responseListener);
RequestQueue queue = Volley.newRequestQueue(SignUp.this);
queue.add(registerRequest);
new android.os.Handler().postDelayed(
new Runnable() {
public void run() {
onSignupSuccess();
progressDialog.dismiss();
}
}, 3000);
}
public void onSignupSuccess() {
signupbutton.setEnabled(true);
setResult(RESULT_OK, null);
AlertDialog.Builder builder = new AlertDialog.Builder(SignUp.this);
builder.setTitle("Registration Successful!");
builder.setMessage("A confirmation code has been sent to your email.");
builder.setPositiveButton("Next", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(SignUp.this, Confirmation_Sign_Up.class);
startActivity(intent);
}
});
builder.create();
builder.show();;
}
public void onSignupFailed() {
Toast toast = Toast.makeText(this, "Registration failed", Toast.LENGTH_LONG);
TextView v = (TextView) toast.getView().findViewById(android.R.id.message);
v.setTextColor(Color.RED);
toast.show();
signupbutton.setEnabled(true);
}
public boolean validate() {
boolean valid = true;
String name = inputname.getText().toString();
String email = inputemail.getText().toString();
String password = inputpassword.getText().toString();
String number = inputnumber.getText().toString();
if (name.isEmpty() || name.length() < 2) {
inputname.setError("Store name must be at least 2 characters");
valid = false;
} else {
inputname.setError(null);
}
if (email.isEmpty() || !android.util.Patterns.EMAIL_ADDRESS.matcher(email).matches()) {
inputemail.setError("Enter a valid email address");
valid = false;
} else {
inputemail.setError(null);
}
if (password.isEmpty() || password.length() < 4 || password.length() > 10) {
inputpassword.setError("Password must have between 4 and 10 characters");
valid = false;
} else {
inputpassword.setError(null);
}
if (number.isEmpty() || number.length() != 8) {
inputnumber.setError("Enter a valid phone number");
valid = false;
} else {
inputnumber.setError(null);
}
return valid;
}
}
EDIT: I removed the Handler and placed the ProgressDialog under try but now the ProgressDialog does not dismiss itself.
try {
final ProgressDialog progressDialog = new ProgressDialog(SignUp.this, R.style.Theme_AppCompat_DayNight_Dialog_Alert);
progressDialog.setIndeterminate(true);
progressDialog.setMessage("Creating Account");
progressDialog.show();
JSONObject jsonResponse = new JSONObject(response);
boolean emailsuccess = jsonResponse.getBoolean("emailsuccess");
if (emailsuccess) {
progressDialog.dismiss();
onSignupSuccess();
}
else ........
This is my full code below. am coding an android app that can select image from gallery or any where and upload it to Mysql server through php but if image is not selected and the upload button is press the application crashes so i want to implement the function that it shows error dialog / warning dialog if image is not selected from gallery have already implemented it in EditText but cannot implement it in Image. below is my code
package com.app.markeet;
public class ActivityPost extends AppCompatActivity implements View.OnClickListener {
private Button buttonUpload;
private Button buttonChoose;
EditText editTitle, editTextPrice, editTextDescription, editTextStatus, editTextAuthorsname, editTextAuthorsphone;
private ImageView imageView,choiceItemImg,choiceItemImg2,choiceItemImg3,choiceItemImg4;
public static final String KEY_TITLE = "name";
public static final String KEY_IMAGE = "image";
public static final String KEY_PRICE = "price";
public static final String KEY_DESCRIPTION = "description";
public static final String KEY_STOCK = "stock";
public static final String KEY_AUTHORSNAME = "authorsname";
public static final String KEY_AUTHORSPHONE = "authorsphone";
public static final String KEY_STATUS = "status";
public static final String UPLOAD_URL = "http://192.168.0.199/config/upload.php";
private int PICK_IMAGE_REQUEST = 1;
public static final int CREATE_POST_IMG = 5;
private Bitmap bitmap;
private Uri outputFileUri;
public static final int SELECT_POST_IMG = 3;
public static final String APP_TEMP_FOLDER = "kobobay";
String[] categories = { "Animals and Pets", "Electronics and Video",
"Fashion and Beauty", "Home, Furniture and Garden", "Mobile Phone and Tablets", "PC, Laptop and Accessories",
"Jobs and Services", "Real Estate and Roommate", "Hobbles, Art and Sport", "Books and Tutorial",
"Vehicles", "Other"};
int[] catevalue = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12};
Spinner spinner1;
TextView textView1;
private Toolbar toolbar;
private ActionBar actionBar;
private String selectedPostImg = "";
ImageView mChoiceItemImg, mLocationDelete;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_post);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
actionBar = getSupportActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setHomeButtonEnabled(true);
actionBar.setTitle("");
buttonUpload = (Button) findViewById(R.id.buttonUpload);
buttonChoose = (Button) findViewById(R.id.buttonChooseImage);
editTitle = (EditText)findViewById(R.id.editTitle);
editTextPrice = (EditText)findViewById(R.id.editPrice);
editTextDescription = (EditText)findViewById(R.id.editDescription);
editTextStatus = (EditText)findViewById(R.id.editStatus);
editTextAuthorsname = (EditText)findViewById(R.id.editName);
editTextAuthorsphone = (EditText)findViewById(R.id.editPhone);
imageView = (ImageView) findViewById(R.id.imageView);
textView1 = (TextView)findViewById(R.id.text1);
spinner1 = (Spinner)findViewById(R.id.spinner1);
ArrayAdapter<String> adapter1 =
new ArrayAdapter<String>(ActivityPost.this,
android.R.layout.simple_spinner_item, categories);
adapter1.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner1.setAdapter(adapter1);
spinner1.setOnItemSelectedListener(onItemSelectedListener1);
buttonChoose.setOnClickListener(this);
buttonUpload.setOnClickListener(this);
choiceItemImg = (ImageView) findViewById(R.id.choiceItemImg);
choiceItemImg.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
showFileChooser();
}
});
mChoiceItemImg = (ImageView) findViewById(R.id.choiceItemImg2);
mChoiceItemImg.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (selectedPostImg.length() == 0) {
imageFromGallery();
} else {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(ActivityPost.this);
alertDialog.setTitle(getText(R.string.action_remove));
alertDialog.setMessage(getText(R.string.label_delete_img));
alertDialog.setCancelable(true);
alertDialog.setNeutralButton(getText(R.string.action_cancel), new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
alertDialog.setPositiveButton(getText(R.string.action_remove), new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
mChoiceItemImg.setImageResource(R.drawable.ic_camera);
selectedPostImg = "";
dialog.cancel();
}
});
alertDialog.show();
}
}
});
String URL = Constant.WEB_URL + "get/user_info.php";
StringRequest stringRequest = new StringRequest(Request.Method.POST, URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonResponse= new JSONObject(response);
//txtName.setText(jsonResponse.getString("fullname"));
editTextAuthorsname.setText(jsonResponse.getString("login"));
//txtEmail.setText(jsonResponse.getString("email"));
editTextAuthorsphone.setText(jsonResponse.getString("phone"));// you need to create this textView txtPoints.
} catch (Throwable t) {
Log.e("onResponse", "The response: " + response + " seems to not be json formatted.");
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(ActivityPost.this,error.toString(), Toast.LENGTH_SHORT).show();
}
}){
#Override
protected Map<String,String> getParams(){
Map<String,String> params = new HashMap<String, String>();
params.put("username",ThisApplication.getInstance().getUsername());
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
AdapterView.OnItemSelectedListener onItemSelectedListener1 =
new AdapterView.OnItemSelectedListener(){
#Override
public void onItemSelected(AdapterView<?> parent, View view,
int position, long id) {
String s1 = String.valueOf(catevalue[position]);
textView1.setText(s1);
}
#Override
public void onNothingSelected(AdapterView<?> parent) {}
};
private void showFileChooser() {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Picture"), PICK_IMAGE_REQUEST);
}
public void imageFromGallery() {
Intent intent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(Intent.createChooser(intent, getText(R.string.label_select_img)), SELECT_POST_IMG);
}
public void imageFromCamera() {
try {
File root = new File(Environment.getExternalStorageDirectory(), APP_TEMP_FOLDER);
if (!root.exists()) {
root.mkdirs();
}
File sdImageMainDirectory = new File(root, "post.jpg");
outputFileUri = Uri.fromFile(sdImageMainDirectory);
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);
startActivityForResult(cameraIntent, CREATE_POST_IMG);
} catch (Exception e) {
Toast.makeText(ActivityPost.this, "Error occured. Please try again later.", Toast.LENGTH_SHORT).show();
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null) {
Uri filePath = data.getData();
try {
bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), filePath);
choiceItemImg.setImageBitmap(bitmap);
} catch (IOException e) {
e.printStackTrace();
}
}
if (requestCode == SELECT_POST_IMG && resultCode == RESULT_OK && data != null && data.getData() != null) {
Uri filePath = data.getData();
try {
bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), filePath);
choiceItemImg2.setImageBitmap(bitmap);
} catch (IOException e) {
e.printStackTrace();
}
}
}
public String getStringImage(Bitmap bmp){
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.JPEG, 100, baos);
byte[] imageBytes = baos.toByteArray();
String encodedImage = Base64.encodeToString(imageBytes, Base64.DEFAULT);
return encodedImage;
}
public void uploadImage(){
final String GetAuthorsname = editTextAuthorsname.getText().toString();
final String GetAuthorsphone = editTextAuthorsphone.getText().toString();
final String GetTitle = editTitle.getText().toString().trim();
final String image = getStringImage(bitmap);
final String GetPrice = editTextPrice.getText().toString();
final String GetStock = textView1.getText().toString();
final String GetDescription = editTextDescription.getText().toString();
final String GetStatus = editTextStatus.getText().toString();
class UploadImage extends AsyncTask<Void,Void,String> {
ProgressDialog loading;
#Override
protected void onPreExecute() {
super.onPreExecute();
loading = ProgressDialog.show(ActivityPost.this,"Please wait...","uploading",false,false);
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
loading.dismiss();
Toast.makeText(ActivityPost.this,s, Toast.LENGTH_LONG).show();
}
#Override
protected String doInBackground(Void... params) {
RequestHandler rh = new RequestHandler();
HashMap<String,String> param = new HashMap<String,String>();
param.put(KEY_TITLE,GetTitle);
param.put(KEY_IMAGE,image);
param.put(KEY_PRICE,GetPrice);
param.put(KEY_STOCK,GetStock);
param.put(KEY_DESCRIPTION,GetDescription);
param.put(KEY_STATUS,GetStatus);
param.put(KEY_AUTHORSNAME,GetAuthorsname);
param.put(KEY_AUTHORSPHONE,GetAuthorsphone);
String result = rh.sendPostRequest(UPLOAD_URL, param);
return result;
}
}
UploadImage u = new UploadImage();
u.execute();
}
public Boolean checkPicture() {
String image = getStringImage(bitmap);
String GetPrice = editTextPrice.getText().toString();
String GetDescription = editTextDescription.getText().toString();
String GetStatus = editTextStatus.getText().toString();
editTitle.setError(null);
editTextPrice.setError(null);
editTextDescription.setError(null);
editTextStatus.setError(null);
if (image.length() == 0) {
editTitle.setError(getString(R.string.error_field_empty));
return false;
} if (GetPrice.length() == 0) {
editTextPrice.setError(getString(R.string.error_field_empty));
return false;
} if (GetDescription.length() == 0) {
editTextDescription.setError(getString(R.string.error_field_empty));
return false;
} if (GetStatus.length() == 0) {
editTextStatus.setError(getString(R.string.error_field_empty));
return false;
}
return true;
}
public Boolean checkDesc() {
String GetDescription = editTextDescription.getText().toString();
editTextDescription.setError(null);
if (GetDescription.length() == 0) {
editTextDescription.setError(getString(R.string.error_field_empty));
return false;
}
return true;
}
public Boolean checkProductName() {
String GetTitle = editTitle.getText().toString();
editTitle.setError(null);
if (GetTitle.length() == 0) {
editTitle.setError(getString(R.string.error_field_empty));
return false;
}
return true;
}
public Boolean checkCategory() {
String GetStock = textView1.getText().toString();
textView1.setError(null);
if (GetStock.length() == 0) {
editTitle.setError(getString(R.string.error_field_empty));
return false;
}
return true;
}
#Override
public void onClick(View v) {
if(v == buttonChoose){
showFileChooser();
//imageFromGallery();
}
if(v == buttonUpload){
// checkUsername();
if (!ThisApplication.getInstance().isConnected()) {
Toast.makeText(getApplicationContext(), R.string.msg_network_error, Toast.LENGTH_SHORT).show();
} else if (!checkProductName() || !checkDesc() || !checkCategory()) {
} else {
uploadImage();
}
}
}
#Override
public void onBackPressed(){
finish();
}
#Override
public void onDestroy() {
super.onDestroy();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_new_item, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.sync:
Intent intent = getIntent();
finish();
startActivity(intent);
return true;
case R.id.action_post:
uploadImage();
default:
return super.onOptionsItemSelected(item);
}
}
}
Just copy this code and paste
package com.app.markeet;
public class ActivityPost extends AppCompatActivity implements View.OnClickListener {
private Button buttonUpload;
private Button buttonChoose;
EditText editTitle, editTextPrice, editTextDescription, editTextStatus, editTextAuthorsname, editTextAuthorsphone;
private ImageView imageView,choiceItemImg,choiceItemImg2,choiceItemImg3,choiceItemImg4;
public static final String KEY_TITLE = "name";
public static final String KEY_IMAGE = "image";
public static final String KEY_PRICE = "price";
public static final String KEY_DESCRIPTION = "description";
public static final String KEY_STOCK = "stock";
public static final String KEY_AUTHORSNAME = "authorsname";
public static final String KEY_AUTHORSPHONE = "authorsphone";
public static final String KEY_STATUS = "status";
public static final String UPLOAD_URL = "http://192.168.0.199/config/upload.php";
private int PICK_IMAGE_REQUEST = 1;
public static final int CREATE_POST_IMG = 5;
private Bitmap bitmap;
private Uri outputFileUri;
public static final int SELECT_POST_IMG = 3;
public static final String APP_TEMP_FOLDER = "kobobay";
String[] categories = { "Animals and Pets", "Electronics and Video",
"Fashion and Beauty", "Home, Furniture and Garden", "Mobile Phone and Tablets", "PC, Laptop and Accessories",
"Jobs and Services", "Real Estate and Roommate", "Hobbles, Art and Sport", "Books and Tutorial",
"Vehicles", "Other"};
int[] catevalue = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12};
Spinner spinner1;
TextView textView1;
private Toolbar toolbar;
private ActionBar actionBar;
private String selectedPostImg = "";
ImageView mChoiceItemImg, mLocationDelete;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_post);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
actionBar = getSupportActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setHomeButtonEnabled(true);
actionBar.setTitle("");
buttonUpload = (Button) findViewById(R.id.buttonUpload);
buttonChoose = (Button) findViewById(R.id.buttonChooseImage);
editTitle = (EditText)findViewById(R.id.editTitle);
editTextPrice = (EditText)findViewById(R.id.editPrice);
editTextDescription = (EditText)findViewById(R.id.editDescription);
editTextStatus = (EditText)findViewById(R.id.editStatus);
editTextAuthorsname = (EditText)findViewById(R.id.editName);
editTextAuthorsphone = (EditText)findViewById(R.id.editPhone);
imageView = (ImageView) findViewById(R.id.imageView);
textView1 = (TextView)findViewById(R.id.text1);
spinner1 = (Spinner)findViewById(R.id.spinner1);
ArrayAdapter<String> adapter1 =
new ArrayAdapter<String>(ActivityPost.this,
android.R.layout.simple_spinner_item, categories);
adapter1.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner1.setAdapter(adapter1);
spinner1.setOnItemSelectedListener(onItemSelectedListener1);
buttonChoose.setOnClickListener(this);
buttonUpload.setOnClickListener(this);
choiceItemImg = (ImageView) findViewById(R.id.choiceItemImg);
choiceItemImg.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
showFileChooser();
}
});
mChoiceItemImg = (ImageView) findViewById(R.id.choiceItemImg2);
mChoiceItemImg.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (selectedPostImg.length() == 0) {
imageFromGallery();
} else {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(ActivityPost.this);
alertDialog.setTitle(getText(R.string.action_remove));
alertDialog.setMessage(getText(R.string.label_delete_img));
alertDialog.setCancelable(true);
alertDialog.setNeutralButton(getText(R.string.action_cancel), new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
alertDialog.setPositiveButton(getText(R.string.action_remove), new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
mChoiceItemImg.setImageResource(R.drawable.ic_camera);
selectedPostImg = "";
dialog.cancel();
}
});
alertDialog.show();
}
}
});
String URL = Constant.WEB_URL + "get/user_info.php";
StringRequest stringRequest = new StringRequest(Request.Method.POST, URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonResponse= new JSONObject(response);
//txtName.setText(jsonResponse.getString("fullname"));
editTextAuthorsname.setText(jsonResponse.getString("login"));
//txtEmail.setText(jsonResponse.getString("email"));
editTextAuthorsphone.setText(jsonResponse.getString("phone"));// you need to create this textView txtPoints.
} catch (Throwable t) {
Log.e("onResponse", "The response: " + response + " seems to not be json formatted.");
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(ActivityPost.this,error.toString(), Toast.LENGTH_SHORT).show();
}
}){
#Override
protected Map<String,String> getParams(){
Map<String,String> params = new HashMap<String, String>();
params.put("username",ThisApplication.getInstance().getUsername());
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
AdapterView.OnItemSelectedListener onItemSelectedListener1 =
new AdapterView.OnItemSelectedListener(){
#Override
public void onItemSelected(AdapterView<?> parent, View view,
int position, long id) {
String s1 = String.valueOf(catevalue[position]);
textView1.setText(s1);
}
#Override
public void onNothingSelected(AdapterView<?> parent) {}
};
private void showFileChooser() {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Picture"), PICK_IMAGE_REQUEST);
}
public void imageFromGallery() {
Intent intent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(Intent.createChooser(intent, getText(R.string.label_select_img)), SELECT_POST_IMG);
}
public void imageFromCamera() {
try {
File root = new File(Environment.getExternalStorageDirectory(), APP_TEMP_FOLDER);
if (!root.exists()) {
root.mkdirs();
}
File sdImageMainDirectory = new File(root, "post.jpg");
outputFileUri = Uri.fromFile(sdImageMainDirectory);
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);
startActivityForResult(cameraIntent, CREATE_POST_IMG);
} catch (Exception e) {
Toast.makeText(ActivityPost.this, "Error occured. Please try again later.", Toast.LENGTH_SHORT).show();
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null) {
Uri filePath = data.getData();
try {
bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), filePath);
choiceItemImg.setImageBitmap(bitmap);
} catch (IOException e) {
e.printStackTrace();
}
}
if (requestCode == SELECT_POST_IMG && resultCode == RESULT_OK && data != null && data.getData() != null) {
Uri filePath = data.getData();
try {
bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), filePath);
choiceItemImg2.setImageBitmap(bitmap);
} catch (IOException e) {
e.printStackTrace();
}
}
}
public String getStringImage(Bitmap bmp){
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.JPEG, 100, baos);
byte[] imageBytes = baos.toByteArray();
String encodedImage = Base64.encodeToString(imageBytes, Base64.DEFAULT);
return encodedImage;
}
public void uploadImage(){
final String GetAuthorsname = editTextAuthorsname.getText().toString();
final String GetAuthorsphone = editTextAuthorsphone.getText().toString();
final String GetTitle = editTitle.getText().toString().trim();
final String image = getStringImage(bitmap);
final String GetPrice = editTextPrice.getText().toString();
final String GetStock = textView1.getText().toString();
final String GetDescription = editTextDescription.getText().toString();
final String GetStatus = editTextStatus.getText().toString();
class UploadImage extends AsyncTask<Void,Void,String> {
ProgressDialog loading;
#Override
protected void onPreExecute() {
super.onPreExecute();
loading = ProgressDialog.show(ActivityPost.this,"Please wait...","uploading",false,false);
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
loading.dismiss();
Toast.makeText(ActivityPost.this,s, Toast.LENGTH_LONG).show();
}
#Override
protected String doInBackground(Void... params) {
RequestHandler rh = new RequestHandler();
HashMap<String,String> param = new HashMap<String,String>();
param.put(KEY_TITLE,GetTitle);
param.put(KEY_IMAGE,image);
param.put(KEY_PRICE,GetPrice);
param.put(KEY_STOCK,GetStock);
param.put(KEY_DESCRIPTION,GetDescription);
param.put(KEY_STATUS,GetStatus);
param.put(KEY_AUTHORSNAME,GetAuthorsname);
param.put(KEY_AUTHORSPHONE,GetAuthorsphone);
String result = rh.sendPostRequest(UPLOAD_URL, param);
return result;
}
}
UploadImage u = new UploadImage();
u.execute();
}
public Boolean checkPicture() {
String image = getStringImage(bitmap);
String GetPrice = editTextPrice.getText().toString();
String GetDescription = editTextDescription.getText().toString();
String GetStatus = editTextStatus.getText().toString();
editTitle.setError(null);
editTextPrice.setError(null);
editTextDescription.setError(null);
editTextStatus.setError(null);
if (image.length() == 0) {
editTitle.setError(getString(R.string.error_field_empty));
return false;
} if (GetPrice.length() == 0) {
editTextPrice.setError(getString(R.string.error_field_empty));
return false;
} if (GetDescription.length() == 0) {
editTextDescription.setError(getString(R.string.error_field_empty));
return false;
} if (GetStatus.length() == 0) {
editTextStatus.setError(getString(R.string.error_field_empty));
return false;
}
return true;
}
public Boolean checkDesc() {
String GetDescription = editTextDescription.getText().toString();
editTextDescription.setError(null);
if (GetDescription.length() == 0) {
editTextDescription.setError(getString(R.string.error_field_empty));
return false;
}
return true;
}
public Boolean checkProductName() {
String GetTitle = editTitle.getText().toString();
editTitle.setError(null);
if (GetTitle.length() == 0) {
editTitle.setError(getString(R.string.error_field_empty));
return false;
}
return true;
}
public Boolean checkCategory() {
String GetStock = textView1.getText().toString();
textView1.setError(null);
if (GetStock.length() == 0) {
editTitle.setError(getString(R.string.error_field_empty));
return false;
}
return true;
}
#Override
public void onClick(View v) {
if(v == buttonChoose){
showFileChooser();
//imageFromGallery();
}
if(v == buttonUpload){
// checkUsername();
if (!ThisApplication.getInstance().isConnected()) {
Toast.makeText(getApplicationContext(), R.string.msg_network_error, Toast.LENGTH_SHORT).show();
} else if (!checkProductName() || !checkDesc() || !checkCategory()) {
} else {
uploadImage();
}
}
}
#Override
public void onBackPressed(){
finish();
}
#Override
public void onDestroy() {
super.onDestroy();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_new_item, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.sync:
Intent intent = getIntent();
finish();
startActivity(intent);
return true;
case R.id.action_post:
uploadImage();
default:
return super.onOptionsItemSelected(item);
}
}
}
I twice get anr when i swipe the app from recent activities. And then the app works fine also I get an anr when I switch to landscape mode. The app works as expected as long as it is not oriented landscape or swiped from recent apps.
Can someone point out what I am doing wrong here.
Thanks
MyService.java:
public class MyService extends Service {
public static boolean started = false;
public static String TRANSACTION_DONE = "com.example.root.project";
private WebSocketClient client = null;
public static SQLiteDatabase myDataBase = null;
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public int onStartCommand(final Intent intent, int flags, int startId) {
if(started){
String message = intent.getStringExtra("message");
if(client != null){
client.send(message);
}
}
if (!started) {
myDataBase = openOrCreateDatabase("Messages.db", MODE_PRIVATE, null);
myDataBase.execSQL("CREATE TABLE IF NOT EXISTS messages " +
"(tag TEXT primary key, message TEXT);");
started = true;
URI uri = null;
try {
uri = new URI(intent.getStringExtra("ip"));
} catch (URISyntaxException e) {
e.printStackTrace();
}
client = new WebSocketClient(uri) {
#Override
public void onOpen(ServerHandshake serverHandshake) {
JSONObject jsonObject = null;
try {
jsonObject = new JSONObject();
jsonObject.accumulate("addme",intent.getStringExtra("name"));
} catch (JSONException e) {
e.printStackTrace();
}
client.send(jsonObject.toString());
}
#Override
public void onMessage(String message) {
JSONObject jsonObject = null;
try {
jsonObject = new JSONObject(message);
} catch (JSONException e) {
e.printStackTrace();
}
if (jsonObject.has("resolve")) {
PendingIntent notificIntent = PendingIntent.getActivity(getApplicationContext(), 0,
new Intent(getApplicationContext(), MainActivity.class), 0);
// Builds a notification
NotificationCompat.Builder mBuilder =
null;
try {
mBuilder = new NotificationCompat.Builder(getApplicationContext())
.setSmallIcon(R.drawable.add)
.setContentTitle(jsonObject.getString("name"))
.setTicker(jsonObject.getString("resolve"))
.setContentText(jsonObject.getString("destination"));
} catch (JSONException e) {
e.printStackTrace();
}
// Defines the Intent to fire when the notification is clicked
mBuilder.setContentIntent(notificIntent);
// Set the default notification option
// DEFAULT_SOUND : Make sound
// DEFAULT_VIBRATE : Vibrate
// DEFAULT_LIGHTS : Use the default light notification
mBuilder.setDefaults(Notification.DEFAULT_ALL);
// Auto cancels the notification when clicked on in the task bar
mBuilder.setAutoCancel(true);
// Gets a NotificationManager which is used to notify the user of the background event
NotificationManager mNotificationManager =
(NotificationManager) getApplicationContext().getSystemService(Context.NOTIFICATION_SERVICE);
// Post the notification
mNotificationManager.notify((int) System.currentTimeMillis(), mBuilder.build());
} else if (jsonObject.has("remove")) {
try {
String tag = jsonObject.getString("remove");
myDataBase.execSQL("DELETE FROM messages WHERE tag = " + tag + ";");
} catch (JSONException e) {
e.printStackTrace();
}
if (isForeground(TRANSACTION_DONE)) {
Intent broadcast = new Intent(TRANSACTION_DONE);
broadcast.putExtra("message", message);
sendBroadcast(broadcast);
}
} else {
try {
myDataBase.execSQL("INSERT INTO messages (tag, message) VALUES ('" +
jsonObject.getString("tag") + "', '" + message + "');");
} catch (JSONException e) {
e.printStackTrace();
}
if (isForeground(TRANSACTION_DONE)) {
Intent broadcast = new Intent(TRANSACTION_DONE);
broadcast.putExtra("message", message);
sendBroadcast(broadcast);
}
}
}
#Override
public void onClose(int i, String s, boolean b) {
Log.d("myTag", "onClose: websocket closing ");
Toast.makeText(getApplicationContext(),"closing websocket",Toast.LENGTH_LONG).show();
}
#Override
public void onError(Exception e) {
Log.i("Websocket", "Error " + e.getMessage());
}
};
client.connect();
}
return START_STICKY;
}
#Override
public void onTaskRemoved(Intent rootIntent) {
super.onTaskRemoved(rootIntent);
Toast.makeText(getApplicationContext(),"closing client",Toast.LENGTH_LONG).show();
client.close();
}
#Override
public void onDestroy() {
super.onDestroy();
Log.d("myTag", "onDestroy: service being destroyed ");
try {
client.closeBlocking();
} catch (InterruptedException e) {
e.printStackTrace();
}
Toast.makeText(this,"Service is closing on destroy called",Toast.LENGTH_LONG).show();
}
public boolean isForeground(String myPackage) {
ActivityManager manager = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
List<ActivityManager.RunningTaskInfo> runningTaskInfo = manager.getRunningTasks(1);
ComponentName componentInfo = runningTaskInfo.get(0).topActivity;
return componentInfo.getPackageName().equals(myPackage);
}
}
MainActivity.java:
public class MainActivity extends AppCompatActivity {
private CustomAdapter adapter;
private String name;
private String ip;
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.add) {
final AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Title");
final View viewInflated = getLayoutInflater().inflate(R.layout.custom_dialog_layout, null);
builder.setView(viewInflated);
// Set up the buttons
builder.setPositiveButton("Publish", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
EditText editText = (EditText) viewInflated.findViewById(R.id.dialogTitle);
EditText editText2 = (EditText) viewInflated.findViewById(R.id.dialogDesc);
String title = editText.getText().toString().trim();
String desc = editText2.getText().toString().trim();
JSONObject jsonObject = new JSONObject();
try {
jsonObject.accumulate("title", title);
jsonObject.accumulate("desc", desc);
jsonObject.accumulate("name",name);
} catch (JSONException e) {
e.printStackTrace();
}
Intent intent = new Intent(MainActivity.this,MyService.class);
intent.putExtra("message",jsonObject.toString());
startService(intent);
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
builder.show();
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if(MyPreferences.isFirst(this)) {
final AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Title");
final View viewInflated = getLayoutInflater().inflate(R.layout.login_dialog, null);
builder.setView(viewInflated);
// Set up the buttons
builder.setPositiveButton("Publish", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
EditText editText = (EditText) viewInflated.findViewById(R.id.dialogName);
EditText editText2 = (EditText) viewInflated.findViewById(R.id.dialogIp);
name = editText.getText().toString().trim();
ip = editText2.getText().toString().trim();
Intent intent = new Intent(MainActivity.this, MyService.class);
intent.putExtra("name", name);
intent.putExtra("ip", ip);
MainActivity.this.getSharedPreferences("my_preferences",MODE_PRIVATE).edit().putString("name",name).putString("ip",ip).commit();
startService(intent);
ListView listView = (ListView) findViewById(R.id.listView);
adapter = new CustomAdapter(MainActivity.this);
listView.setAdapter(adapter);
IntentFilter filter = new IntentFilter();
filter.addAction(MyService.TRANSACTION_DONE);
registerReceiver(myReceiver, filter);
new Handler().post(new Runnable() {
#Override
public void run() {
if (MyService.myDataBase == null) return;
Cursor cursor = MyService.myDataBase.rawQuery("SELECT * FROM messages", null);
int messageColumn = cursor.getColumnIndex("message");
cursor.moveToFirst();
if (cursor != null && (cursor.getCount() > 0)) {
do {
String message = cursor.getString(messageColumn);
try {
JSONObject jsonObject = new JSONObject(message);
adapter.add(jsonObject.getString("title"), jsonObject.getString("desc"), jsonObject.getString("tag"));
} catch (JSONException e) {
e.printStackTrace();
}
} while (cursor.moveToNext());
adapter.update();
}
}
});
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
builder.show();
}else {
Intent intent = new Intent(this, MyService.class);
name = this.getSharedPreferences("my_preferences",MODE_PRIVATE).getString("name","no_name");
ip = this.getSharedPreferences("my_preferences",MODE_PRIVATE).getString("ip","no_ip");
intent.putExtra("name",name);
intent.putExtra("ip",ip);
startService(intent);
ListView listView = (ListView) findViewById(R.id.listView);
adapter = new CustomAdapter(this);
listView.setAdapter(adapter);
IntentFilter filter = new IntentFilter();
filter.addAction(MyService.TRANSACTION_DONE);
registerReceiver(myReceiver, filter);
new Handler().post(new Runnable() {
#Override
public void run() {
if (MyService.myDataBase == null) return;
Cursor cursor = MyService.myDataBase.rawQuery("SELECT * FROM messages", null);
int messageColumn = cursor.getColumnIndex("message");
cursor.moveToFirst();
if (cursor != null && (cursor.getCount() > 0)) {
do {
String message = cursor.getString(messageColumn);
try {
JSONObject jsonObject = new JSONObject(message);
adapter.add(jsonObject.getString("title"), jsonObject.getString("desc"), jsonObject.getString("tag"));
} catch (JSONException e) {
e.printStackTrace();
}
} while (cursor.moveToNext());
adapter.update();
}
}
});
}
}
#Override
protected void onDestroy() {
if (myReceiver != null) {
unregisterReceiver(myReceiver);
myReceiver = null;
}
super.onDestroy();
}
private BroadcastReceiver myReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String message = intent.getStringExtra("message");
Toast.makeText(MainActivity.this,message,Toast.LENGTH_LONG).show();
JSONObject jsonObject = null;
try {
jsonObject = new JSONObject(message);
if(jsonObject.has("remove")){
adapter.remove(jsonObject.getString("remove"));
adapter.update();
}else {
adapter.add(jsonObject.getString("title"), jsonObject.getString("desc"), jsonObject.getString("tag"));
adapter.update();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
};
class CustomAdapter extends BaseAdapter {
private LayoutInflater inflater;
private ArrayList<ListViewData> objects;
public void add(String title, String desc, String tag) {
objects.add(new ListViewData(title, desc, tag));
}
public void remove(String tag){
for(ListViewData data : objects){
if(data.getTag().equals(tag)){
objects.remove(data);
break;
}
}
}
public void update(){
notifyDataSetChanged();
}
private class ViewHolder {
TextView title;
TextView description;
Button resolve;
Button subscribe;
Button unSubscribe;
}
public CustomAdapter(Context context) {
inflater = LayoutInflater.from(context);
objects = new ArrayList<>();
}
public int getCount() {
return objects.size();
}
public ListViewData getItem(int position) {
return objects.get(position);
}
public long getItemId(int position) {
return position;
}
public View getView(final int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
if (convertView == null) {
holder = new ViewHolder();
convertView = inflater.inflate(R.layout.custom_list_layout, null);
holder.title = (TextView) convertView.findViewById(R.id.title);
holder.description = (TextView) convertView.findViewById(R.id.desc);
holder.resolve = (Button) convertView.findViewById(R.id.resolve);
holder.subscribe = (Button) convertView.findViewById(R.id.subscribe);
holder.unSubscribe = (Button) convertView.findViewById(R.id.unsubscribe);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.title.setText(objects.get(position).getTitle());
holder.description.setText(objects.get(position).getDescription());
holder.resolve.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
final AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setTitle("Title");
final View viewInflated = getLayoutInflater().inflate(R.layout.custom_dialog2, null);
builder.setView(viewInflated);
// Set up the buttons
builder.setPositiveButton("Publish", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
EditText editText = (EditText) viewInflated.findViewById(R.id.name);
EditText editText2 = (EditText) viewInflated.findViewById(R.id.destination);
String name = editText.getText().toString().trim();
String destination = editText2.getText().toString().trim();
JSONObject jsonObject = new JSONObject();
try {
jsonObject.accumulate("name", name);
jsonObject.accumulate("destination", destination);
jsonObject.accumulate("resolve",objects.get(position).getTag());
} catch (JSONException e) {
e.printStackTrace();
}
Intent intent = new Intent(MainActivity.this,MyService.class);
intent.putExtra("message",jsonObject.toString());
startService(intent);
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
builder.show();
}
});
holder.subscribe.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String tag = objects.get(position).getTag();
try {
Intent intent = new Intent(MainActivity.this,MyService.class);
intent.putExtra("message",new JSONObject().accumulate("subscribe",tag).accumulate("name",name).toString());
startService(intent);
} catch (JSONException e) {
e.printStackTrace();
}
}
});
holder.unSubscribe.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String tag = objects.get(position).getTag();
try {
Intent intent = new Intent(MainActivity.this,MyService.class);
intent.putExtra("message",new JSONObject().accumulate("unsubscribe",tag).accumulate("name",name).toString());
startService(intent);
} catch (JSONException e) {
e.printStackTrace();
}
}
});
return convertView;
}
}
}
class MyPreferences {
private static final String MY_PREFERENCES = "my_preferences";
public static boolean isFirst(Context context){
final SharedPreferences reader = context.getSharedPreferences(MY_PREFERENCES, Context.MODE_PRIVATE);
final boolean first = reader.getBoolean("is_first", true);
if(first){
final SharedPreferences.Editor editor = reader.edit();
editor.putBoolean("is_first", false);
editor.commit();
}
return first;
}
}
I need to put a 30sec timer in my otp verfication page after 30secs timer should be gone and the keyboard should pop up. what needs to be done??
Below are my java files.
SignUpFragment.java
SignUpActivity activity;
/**
* Declaring Variables for Views
*/
TextView SignupAlreadyMember;
EditText SignUpName, SignUpEmail,referCode;
Button SignUpRegister;
VirtualApplication virtualApplication;
// Progress dialog
private ProgressDialog pDialog;
public SignUpFragment() {
}
#Override
public void onAttach(Activity activit) {
super.onAttach(activit);
this.activity = (SignUpActivity) activit;
virtualApplication = (VirtualApplication) activity.getApplicationContext();
}
int bodyId;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
bodyId = getArguments().getInt("output");
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_sign_up, container, false);
activity.setTempTitle("signup");
inItViews(view);
SignUpRegister.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
RegisterUser();
// showVerifyMobileScreen(123);
}
});
SignUpEmail.setOnEditorActionListener(new EditText.OnEditorActionListener() {
#Override
public boolean onEditorAction(TextView v, int actionId,
KeyEvent event) {
if (actionId == EditorInfo.IME_ACTION_DONE) {
RegisterUser();
}
return false;
}
});
SignupAlreadyMember.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
gotoLoginScreen();
}
});
return view;
}
private void gotoLoginScreen() {
Intent intent = new Intent(activity, LoginActivity.class);
startActivity(intent);
activity.finish();
}
public boolean validCellPhone(String number) {
return Patterns.PHONE.matcher(number).matches();
}
private void RegisterUser() {
String email = SignUpEmail.getText().toString().trim();
String name = SignUpName.getText().toString().trim();
String code=referCode.getText().toString().trim();
if (email.isEmpty() ||!SystemUtil.isValidMobile(email)) {
SignUpEmail.setError("Enter Mobile number here");
return;
}
JSONObject jsonObject = new JSONObject();
try {
jsonObject.put("name", name);
jsonObject.put("phone_number", email);
jsonObject.put("body_id", bodyId);
jsonObject.put("referral_code",code);//referral_code
TelephonyManager tm = (TelephonyManager) activity
.getSystemService(Context.TELEPHONY_SERVICE);
jsonObject.put("imei", SystemUtil.getIMEINumber(activity, tm)) ;
} catch (JSONException e) {
e.printStackTrace();
}
SignUpRegister.setEnabled(false);
requestForRegistration(jsonObject);
}
private void requestForRegistration(JSONObject jsonObject) {
showpDialog();
RequestQueue requestQueue = CustomVolleyRequestQueue.getInstance(activity).getRequestQueue();
final CustomJSONObjectRequest customJSONObjectRequest = new CustomJSONObjectRequest(Request.Method.POST, AppConstants.REGISTER_URL, jsonObject, this, this);
customJSONObjectRequest.setTag("Register");
customJSONObjectRequest.setRetryPolicy(new DefaultRetryPolicy(5000,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
customJSONObjectRequest.setShouldCache(true);
requestQueue.add(customJSONObjectRequest);
//
}
private void showVerifyMobileScreen(int userId) {
VerificationFragment verificationFragment = new VerificationFragment();
Bundle bundle = new Bundle();
bundle.putInt("userId", userId);
bundle.putString("mobile", SignUpEmail.getText().toString().trim());
verificationFragment.setArguments(bundle);
activity.getSupportFragmentManager().beginTransaction().replace(R.id.fragment, verificationFragment).commit();
}
private void inItViews(View view) {
TextView SignUPHeader = (TextView) view.findViewById(R.id.SignUPHeader);
TextView Signupmessage= (TextView) view.findViewById(R.id.Signupmessage);
Signupmessage.setTypeface(Typefaces.get(activity, AppConstants.FONT_ROBOT_REGULAR));
SignUPHeader.setTypeface(Typefaces.get(activity, AppConstants.FONT_ROBOT_REGULAR));
SignupAlreadyMember = (TextView) view.findViewById(R.id.SignupAlreadyMember);
SignupAlreadyMember.setTypeface(Typefaces.get(activity, AppConstants.FONT_ROBOT_REGULAR));
SignUpName = (EditText) view.findViewById(R.id.SignUpName);
SignUpName.setTypeface(Typefaces.get(activity, AppConstants.FONT_ROBOT_REGULAR));
SignUpEmail = (EditText) view.findViewById(R.id.SignUpEmail);
SignUpEmail.setTypeface(Typefaces.get(activity, AppConstants.FONT_ROBOT_REGULAR));
SignUpRegister = (Button) view.findViewById(R.id.SignUpRegister);
SignUpRegister.setTypeface(Typefaces.get(activity, AppConstants.FONT_ROBOT_REGULAR));
referCode = (EditText) view.findViewById(R.id.referCode);
referCode.setTypeface(Typefaces.get(activity, AppConstants.FONT_ROBOT_REGULAR));
}
private void showpDialog() {
pDialog = ProgressDialog.show(activity, null, null);
final Drawable d = new ColorDrawable(Color.TRANSPARENT);
pDialog.getWindow().setBackgroundDrawable(d);
pDialog.setContentView(R.layout.loader);
pDialog.show();
}
private void hidepDialog() {
if (pDialog != null && pDialog.isShowing())
pDialog.dismiss();
}
#Override
public void onErrorResponse(VolleyError volleyError) {
hidepDialog();
SignUpRegister.setEnabled(true);
}
#Override
public void onResponse(JSONObject jsonObject) {
hidepDialog();
SystemUtil.sysOut("register::::: " + jsonObject.toString());
if (JSONUtil.readBoolean(jsonObject, "status")) {
int userId = JSONUtil.readInt(jsonObject, "user_id");
showVerifyMobileScreen(userId);
}else{
SignUpRegister.setEnabled(true);
}
if (jsonObject.has("message"))
Toast.makeText(activity, JSONUtil.readString(jsonObject, "message"), Toast.LENGTH_LONG).show();
}
VerificationFragment.Java
SignUpActivity activity;
TextView verifyTitleOne, verifyTitleTwo, verifyChnageNumber, verificationResend;
EditText SignUpMobile, VerficationCode;
Button VerificationRegister;
int userId;
String mobile;
boolean isResend;
public VerificationFragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Bundle bundle = getArguments();
if (bundle != null) {
userId = bundle.getInt("userId");
mobile = bundle.getString("mobile");
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_verfication, container, false);
activity.setTempTitle("details");
inItViews(view);
SignUpMobile.setText("" + mobile);
VerificationRegister.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (!VerficationCode.getText().toString().trim().isEmpty()) {
Toast.makeText(activity, "Verifying", Toast.LENGTH_LONG).show();
showpDialog();
getDefaultData();
} else {
VerficationCode.setError("Enter Code");
}
}
});
verificationResend.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(!isResend) {
isResend = true;
JSONObject jsonObject = new JSONObject();
try {
jsonObject.put("phone_number", mobile);
} catch (JSONException e) {
e.printStackTrace();
}
requestServer(jsonObject, AppConstants.RESEND_OTP_URL);
}else
Toast.makeText(activity,"Please Wait",Toast.LENGTH_SHORT).show();
}
});
// setvalues();
return view;
}
private void setvalues() {
VerficationCode.setText("51692");
VerificationRegister.performClick();
}
private void getDefaultData() {
JSONObject jsonObject = new JSONObject();
try {
jsonObject.put("user_id", userId);
jsonObject.put("token", VerficationCode.getText().toString());
} catch (JSONException e) {
e.printStackTrace();
}
requestServer(jsonObject,AppConstants.VERIFY_NUMBER_URL);
}
private void requestServer(JSONObject jsonObject, String url) {
RequestQueue requestQueue = CustomVolleyRequestQueue.getInstance(activity).getRequestQueue();
final CustomJSONObjectRequest customJSONObjectRequest = new CustomJSONObjectRequest(Request.Method.POST, url, jsonObject, this, this);
customJSONObjectRequest.setTag("verify");
requestQueue.add(customJSONObjectRequest);
}
private void gotoSelectSizesPage(JSONObject jsonObject) {
Bundle bundle = new Bundle();
bundle.putString("output", jsonObject.toString());
DoneFragment homeKitFragment = new DoneFragment();
homeKitFragment.setArguments(bundle);
activity.setTempTitle("");
activity.getSupportFragmentManager().beginTransaction().replace(R.id.fragment, homeKitFragment).commit();
}
private void inItViews(View view) {
verifyTitleOne = (TextView) view.findViewById(R.id.verifyTitleOne);
verifyTitleOne.setTypeface(Typefaces.get(activity, AppConstants.FONT_ROBOT_REGULAR));
verifyTitleTwo = (TextView) view.findViewById(R.id.verifyTitleTwo);
verifyTitleTwo.setTypeface(Typefaces.get(activity, AppConstants.FONT_ROBOT_REGULAR));
verifyChnageNumber = (TextView) view.findViewById(R.id.verifyChnageNumber);
verifyChnageNumber.setTypeface(Typefaces.get(activity, AppConstants.FONT_ROBOT_REGULAR));
verificationResend = (TextView) view.findViewById(R.id.verificationResend);
verificationResend.setTypeface(Typefaces.get(activity, AppConstants.FONT_ROBOT_REGULAR));
SignUpMobile = (EditText) view.findViewById(R.id.SignUpMobile);
SignUpMobile.setTypeface(Typefaces.get(activity, AppConstants.FONT_ROBOT_REGULAR));
VerficationCode = (EditText) view.findViewById(R.id.VerficationCode);
VerficationCode.setTypeface(Typefaces.get(activity, AppConstants.FONT_ROBOT_REGULAR));
VerificationRegister = (Button) view.findViewById(R.id.VerificationRegister);
VerificationRegister.setTypeface(Typefaces.get(activity, AppConstants.FONT_ROBOT_REGULAR));
}
BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
Bundle intentExtras = intent.getExtras();
if (intentExtras != null) {
Object[] sms = (Object[]) intentExtras.get("pdus");
String smsMessageStr = "";
for (int i = 0; i < sms.length; ++i) {
SmsMessage smsMessage = SmsMessage.createFromPdu((byte[]) sms[i], "3gpp");
smsMessageStr = smsMessage.getMessageBody().toString();
// String address = smsMessage.getOriginatingAddress();
/*smsMessageStr += "SMS From: " + address + "\n";
smsMessageStr += smsBody + "\n";*/
}
VerficationCode.setText("" + stripNonDigits(smsMessageStr));
VerificationRegister.performClick();
}
}
};
private ProgressDialog pDialog;
private void showpDialog() {
pDialog = ProgressDialog.show(activity, null, null);
final Drawable d = new ColorDrawable(Color.TRANSPARENT);
pDialog.getWindow().setBackgroundDrawable(d);
pDialog.setContentView(R.layout.loader);
pDialog.show();
}
private void hidepDialog() {
if (pDialog != null && pDialog.isShowing())
pDialog.dismiss();
}
public static String stripNonDigits(
final CharSequence input) {
final StringBuilder sb = new StringBuilder(
input.length());
for (int i = 0; i < input.length(); i++) {
final char c = input.charAt(i);
if (c > 47 && c < 58) {
sb.append(c);
}
}
return sb.toString();
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
this.activity = (SignUpActivity) activity;
activity.registerReceiver(broadcastReceiver, new IntentFilter(
AppConstants.BROADCAST_ACTION_SMS));
}
#Override
public void onDetach() {
super.onDetach();
activity.unregisterReceiver(broadcastReceiver);
}
#Override
public void onErrorResponse(VolleyError volleyError) {
hidepDialog();
}
#Override
public void onResponse(JSONObject jsonObject) {
hidepDialog();
isResend=false;
if (jsonObject.has("message"))
Toast.makeText(activity, JSONUtil.readString(jsonObject, "message"), Toast.LENGTH_LONG).show();
if (JSONUtil.readBoolean(jsonObject, "status") &&jsonObject.has("user_data")) {
gotoSelectSizesPage(jsonObject);
}
}
}
I want to request from this webservice in my project. It contains some information and pictures. How do I get the JSON data from the linked webservice using Volley? How do I parse that data?
MainActivity.java
package.com.example.pr;
import java.*;
public class MainActivity extends Activity {
EditText adGiris, soyadGiris, telGiris, ismeGoreArat, TelefonNumarasi;
Button kaydet, guncelle, kisiAra, Ara;
Veritabani v1;
SQLiteDatabase db;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
v1 = new Veritabani(this); // veritabanımızdan bir nesne oluşturuldu
adGiris = (EditText) findViewById(R.id.editText1); // Layout'daki
// item'lerden nesne
// oluşturuldu
soyadGiris = (EditText) findViewById(R.id.editText2);
telGiris = (EditText) findViewById(R.id.editText3);
ismeGoreArat = (EditText) findViewById(R.id.editText4);
kaydet = (Button) findViewById(R.id.button1);
kaydet.setOnClickListener(new View.OnClickListener() // Kaydet butonunun
// click event'i
{
#Override
public void onClick(View v) // tıklandığında kaydet metoduna gidecek
// ve orada kayıt işlemi yapacak
{
kaydet(adGiris.getText().toString(), soyadGiris.getText()
.toString(), telGiris.getText().toString());
}
});
guncelle = (Button) findViewById(R.id.button3);
guncelle.setOnClickListener(new View.OnClickListener() // Kaydet
// butonunun
// click event'i
{
#Override
public void onClick(View v) // tıklandığında kaydet metoduna gidecek
// ve orada kayıt işlemi yapacak
{
guncelle();
}
});
kisiAra = (Button) findViewById(R.id.button2);
kisiAra.setOnClickListener(new View.OnClickListener() // kisiAra
// butonunun
// click event'i
{
#Override
public void onClick(View v) // ad'a göre bilgileri çekecek
{
bilgileriCek(ismeGoreArat.getText().toString()); // girilen isim
// alınıp
// metoda
// gönderiliyor
}
});
guncelle.setVisibility(View.INVISIBLE);
}
public void onClick(View v) {
String numara = TelefonNumarasi.getText().toString();
Intent intent = new Intent(Intent.ACTION_CALL);
intent.setData(Uri.parse("tel:" + numara + ""));
startActivity(intent);
}
public void kaydet(String ad, String soyad, String tel) {
try {
SQLiteDatabase db1 = v1.getWritableDatabase();
ContentValues cv1 = new ContentValues();
cv1.put("ad", ad);
cv1.put("soyad", soyad);
cv1.put("tel", tel);
db1.insertOrThrow("kisiler", null, cv1);
db1.close();
Toast.makeText(getApplicationContext(), "Kayıt işlemi tamamlandı",
Toast.LENGTH_SHORT).show();
} catch (Exception e) {
Toast.makeText(getApplicationContext(),
"Kayıt işleminde hata oluştu", Toast.LENGTH_SHORT).show();
}
}
public void guncelle() {
try {
SQLiteDatabase db1 = v1.getWritableDatabase();
ContentValues cv1 = new ContentValues();
cv1.put("id", Integer.valueOf(duzeltilecekVeri.getId().toString()));
cv1.put("ad", duzeltilecekVeri.getAd());
cv1.put("soyad", duzeltilecekVeri.getSoyad());
cv1.put("tel", duzeltilecekVeri.getTel());
String sql="UPDATE kisiler set ad='"+adGiris.getText()+"',soyad='"+soyadGiris.getText()+"',tel='"+telGiris.getText()+"'"
+ "WHERE id="+duzeltilecekVeri.getId();
db1.execSQL(sql);
db1.close();
Toast.makeText(getApplicationContext(), "Düzeltme işlemi tamamlandı",
Toast.LENGTH_SHORT).show();
guncelle.setVisibility(View.INVISIBLE);
kaydet.setVisibility(View.VISIBLE);
} catch (Exception e) {
Toast.makeText(getApplicationContext(),
"Düzeltme işleminde hata oluştu", Toast.LENGTH_SHORT)
.show();
}
}
class Veri{
private String id;
private String ad;
private String soyad;
private String tel;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getAd() {
return ad;
}
public void setAd(String ad) {
this.ad = ad;
}
public String getSoyad() {
return soyad;
}
public void setSoyad(String soyad) {
this.soyad = soyad;
}
public String getTel() {
return tel;
}
public void setTel(String tel) {
this.tel = tel;
}
}
public List<Veri>list=new ArrayList<Veri>();
public Veri duzeltilecekVeri;
public void bilgileriCek(String kisiAd) {
try {
ArrayAdapter<String> arrayAdapter2 = new ArrayAdapter<String>(
MainActivity.this,
android.R.layout.select_dialog_singlechoice);
String[] sutunlar = { "id","ad", "soyad", "tel" }; // veritabanındaki
// sütunlar
// gösterildi
SQLiteDatabase db = v1.getReadableDatabase();
Cursor okunanlar = db.query("kisiler", sutunlar, "ad like ?",
new String[] { "%"+kisiAd+"%" }, null, null, null);
// ad'a göre aratma yapıldı. DB.QUERY() metodunda 3. parametre WHERE
// ifadesidir.
// 4.parametre ise WHERE'de yerine koyacağımız parametredir.
list.clear();
Veri veri = new Veri();
while (okunanlar.moveToNext()) // Şarta uyan veriler okundu.
{
veri=new Veri();
veri.setId(okunanlar.getString(okunanlar.getColumnIndex("id")));
veri.setAd(okunanlar.getString(okunanlar.getColumnIndex("ad")));
veri.setSoyad(okunanlar.getString(okunanlar.getColumnIndex("soyad")));
veri.setTel(okunanlar.getString(okunanlar.getColumnIndex("tel")));
arrayAdapter2.add(veri.getAd() + "\n" + veri.getSoyad() + "\n" + veri.getTel()); // Okunan
// veriler
// adapter'e
// alt alta
// eklendi.
list.add(veri);
}
cekilenleriGoster(arrayAdapter2); // Çekilen veriler adapter'e
// dolduruldu ve ilgili metoda
// gönderildi
} catch (Exception e) {
Toast.makeText(getApplicationContext(),
"Bilgiler Getirilirken Hata Oluştu", Toast.LENGTH_SHORT)
.show();
}
}
public String strName;
public Integer index;
private void cekilenleriGoster(final ArrayAdapter<String> arrayAdapter2)
{
AlertDialog.Builder builderSingle = new AlertDialog.Builder(MainActivity.this);
builderSingle.setIcon(R.drawable.ic_launcher);
builderSingle.setTitle("Getirilen Kayıtlar");
builderSingle.setNegativeButton("Çıkış",new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
builderSingle.setAdapter(arrayAdapter2,new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
strName = (String) arrayAdapter2.getItem(which).toString();
index=which;
AlertDialog.Builder builderInner = new AlertDialog.Builder(MainActivity.this);
builderInner.setCancelable(false);
builderInner.setMessage(strName);
builderInner.setTitle("Kayıtlar");
builderInner.setPositiveButton("Değiştir",new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog,int which)
{
duzeltilecekVeri=list.get(index);
adGiris.setText(duzeltilecekVeri.getAd());
soyadGiris.setText(duzeltilecekVeri.getSoyad());
telGiris.setText(duzeltilecekVeri.getTel());
guncelle.setVisibility(View.VISIBLE);
kaydet.setVisibility(View.INVISIBLE);
}
});
builderInner.setNegativeButton("Ara",new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog,int which)
{
Intent callIntent = new Intent(Intent.ACTION_CALL);
callIntent.setData(Uri.parse("tel:"+list.get(index).getTel()));
startActivity(callIntent);
}
});
builderInner.show();
}
});
builderSingle.show();
}
public void dosyaIndir() throws IOException {
db=v1.getWritableDatabase();
org.apache.commons.httpclient.HttpClient hc = new HttpClient();
HttpMethod gm = new GetMethod("http://www.sinerjias.com.tr/jicra/data/android/13.sql");
hc.getHttpConnectionManager().getParams().setConnectionTimeout(5000);
hc.executeMethod(gm);
int status = gm.getStatusCode();
if (status != 200) {
throw new IOException("Dosya Bulunamadı !!!");
}
InputStream stream = gm.getResponseBodyAsStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(stream, "UTF-8"));
StringBuilder builder = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
db.execSQL(line);
Log.d("tamam", line);
}
//db.execSQL(builder.toString());
}
}
I assume you have already added volley to your project.
1) Create a RequestQueue using Activity (for example) as Context
RequestQueue queue = Volley.newRequestQueue(this);
String url ="https://app.petkim.com.tr/rapi/api/rehber";
2). Assuming the response will be a JSONArray (which it is in the given URL), set up a JSONArrayRequest:
JSONArrayRequest jRequest = new JSONArrayRequest
(Request.Method.GET, url, null, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d("onResponse()", "Response: " + response.toString());
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// error handling
}
});
3) Send the request:
queue.add(jRequest);
queue.start();
You will get your JSON in the onResponse() callback.