I am trying to get some data from a server. User clicks search and another acitivity starts by startActivityForResult().when user clicks the data the data should be put inside intent and setResult() is done with that intent and finish() is called. Now i have tried debugg but when finish() is called the activity does no go back to the one which called this activity. instead the app closes down.
Here is the code;
public class SearchContactActivity extends AppCompatActivity {
ProgressBar pb;
CircleImageView profile_image_search;
TextView name_search,user_name_search;
EditText edit_search_contact;
Button btn_search_contact;
ConstraintLayout cl;
String profile_image,firstName,lastName;
RequestQueue myQueue;
String url = "working url";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_search_contact);
pb = findViewById(R.id.progressBar);
profile_image_search = findViewById(R.id.profile_image_search);
name_search = findViewById(R.id.name_search);
user_name_search = findViewById(R.id.user_name_search);
btn_search_contact = findViewById(R.id.btn_search_contact);
edit_search_contact = findViewById(R.id.edit_search_contact);
cl = findViewById(R.id.nested_layout);
cl.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
setResultForPreviousAcitvity();
}
});
btn_search_contact.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
search_contacts();
} catch (JSONException e) {
e.printStackTrace();
}
}
});
hideVisibility();
}
public void setResultForPreviousAcitvity()
{
Intent data = new Intent();
data.putExtra("first_name",firstName);
data.putExtra("last_name",lastName);
data.putExtra("user_name",user_name_search.getText().toString());
data.putExtra("profile", profile_image);
setResult(RESULT_OK,data);
finish(); // app closes down here
}
private void search_contacts() throws JSONException {
pb.setVisibility(View.VISIBLE);
//send php data in json array format
//JSONObject jsonbody = new JSONObject("{\"search_key\":\"jhonsanders \"}");
HashMap<String, String> params = new HashMap<String, String>();
params.put("search_key", edit_search_contact.getText().toString().trim());
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest( url,new JSONObject(params), new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONArray jsonArray = response.getJSONArray("result");
for(int i = 0; i < jsonArray.length(); i++)
{
JSONObject myobj = jsonArray.getJSONObject(i);
firstName = myobj.getString("first_name");
lastName = myobj.getString("last_name");
String userName = myobj.getString("user_name");
profile_image = myobj.getString("profile_image");
Bitmap image = NameAndImage.stringToImage(profile_image);
show_visibility();
profile_image_search.setImageBitmap(image);
user_name_search.setText(userName);
name_search.setText(firstName+" "+lastName);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
})/*{
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String,String> param = new HashMap<>();
param.put("search_key",edit_search_contact.getText().toString().trim());
return param;
}
}*/;
myQueue = VolleySingleton.getInstance(SearchContactActivity.this).getRequestQueue();
myQueue.add(jsonObjectRequest);
}
private void hideVisibility()
{
pb.setVisibility(View.INVISIBLE);
profile_image_search.setVisibility(View.INVISIBLE);
name_search.setVisibility(View.INVISIBLE);
user_name_search.setVisibility(View.INVISIBLE);
}
private void show_visibility()
{
profile_image_search.setVisibility(View.VISIBLE);
name_search.setVisibility(View.VISIBLE);
user_name_search.setVisibility(View.VISIBLE);
pb.setVisibility(View.INVISIBLE);
}
/* private Bitmap stringToImage(String s)
{
byte[] image = Base64.decode(s,Base64.DEFAULT);
Bitmap decodedImage = BitmapFactory.decodeByteArray(image,0,image.length);
return decodedImage;
}*/
}
The above activity is called by
Intent i = new Intent(ContactsActivity.this,SearchContactActivity.class);
startActivityForResult(i,REQUEST_CONTACT_SEARCH);
This is the manifest
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.privatechat">
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:usesCleartextTraffic="true"
android:theme="#style/Theme.PrivateChat">
<activity android:name=".SearchContactActivity"></activity>
<activity android:name=".ContactsActivity" />
<activity android:name=".NameAndImage" />
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<uses-library
android:name="org.apache.http.legacy"
android:required="false" />
</application>
<uses-permission android:name="android.permission.INTERNET" />
</manifest>
There is no logs that i can print.The log is cleared when onfinish() is called.
The app goes back to this other activity. This one also has onAcitivityResult but its not the one that called the other acitivity.
public class NameAndImage extends AppCompatActivity {
EditText editFirstName,editLastName;
ImageView profile_image;
Button uploadNameImage;
Bitmap image;
RequestQueue myQueue;
SaveSharedPreference sp = new SaveSharedPreference();
private String URL = "working url";
public static final int PICK_IMAGE_REQUEST = 1011;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_name_and_image);
editFirstName = findViewById(R.id.edit_first_name);
editLastName = findViewById(R.id.edit_last_name);
profile_image = findViewById(R.id.profile_image_search);
uploadNameImage = findViewById(R.id.upload_name_image);
Log.i("SharedPreference",sp.getUserName(NameAndImage.this).trim());
profile_image.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
pickPhoto();
}
});
uploadNameImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
uploadData();
}
});
}
private void pickPhoto()
{
Intent intent = new Intent();
intent.setAction(Intent.ACTION_PICK);
intent.setType("image/*");
startActivityForResult(intent,PICK_IMAGE_REQUEST);
}
private void uploadData()
{
StringRequest upload_data = new StringRequest(Request.Method.POST, URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
if(response.trim().equals("success_data_upload"))
{
Toast.makeText(NameAndImage.this, "upload success", Toast.LENGTH_SHORT).show();
Intent i = new Intent(NameAndImage.this,ContactsActivity.class);
startActivity(i);
}
if(response.trim().equals("Error"))
{
Toast.makeText(NameAndImage.this, "upload error", Toast.LENGTH_SHORT).show();
Log.i("server",response.toString());
}
else
{
Toast.makeText(NameAndImage.this, "Response dont match", Toast.LENGTH_SHORT).show();
Log.i("server",response);
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(NameAndImage.this, error.toString(), Toast.LENGTH_SHORT).show();
Log.i("server",error.toString());
}
}) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String,String> param = new HashMap<>();
param.put("image",imageToString(image));
param.put("first_name",editFirstName.getText().toString());
param.put("last_name",editLastName.getText().toString());
param.put("user_name",sp.getUserName(NameAndImage.this).trim());
return param;
}
};
upload_data.setRetryPolicy(new DefaultRetryPolicy(
3000,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT
));
myQueue = VolleySingleton.getInstance(NameAndImage.this).getRequestQueue();
myQueue.add(upload_data);
}
public static String imageToString(Bitmap pic)
{
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
pic.compress(Bitmap.CompressFormat.JPEG,100,byteArrayOutputStream);
byte[] imageByte = byteArrayOutputStream.toByteArray();
return Base64.encodeToString(imageByte,Base64.DEFAULT);
}
public static Bitmap stringToImage(String s)
{
byte[] image = Base64.decode(s,Base64.DEFAULT);
Bitmap decodedImage = BitmapFactory.decodeByteArray(image,0,image.length);
return decodedImage;
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK)
{
Uri uri = data.getData();
try {
image = MediaStore.Images.Media.getBitmap(getContentResolver(),uri);
profile_image.setImageBitmap(image);
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
Edit:
The app seems to close but after 2 sec the wrong activity is started.
When setting the result in setResult() i was putting a string profile which contained image as a String. I guess the string was really large but when i debugg the whole string seemed to be there. So when i made profile empty the app operated normally. Looks like i will have to split the string in 2 for more effectiveness.
Related
I have a page in my app with similar codes with different values and they send info to my PHP MySQL just fine. On the other hand, this page in my app cannot send the files and giving me an error message:
E/Volley: [258] BasicNetwork.performRequest: Unexpected response code 406
for http://applybpojobs.com/widevalueappfiles/server/api/addvehicle.php
I have already tried numerous solutions on web and this site to no avail. Can anyone help me figure this out?
Here is my java:
public class Addvehicle extends AppCompatActivity {
private static final String TAG = Addvehicle.class.getSimpleName();
private EditText plate_number, vin, car_make, car_model, car_year, displacement,
fuel_type, transmission, mileage, owner_name, address, phone_number,
email_adress, facebook;
private TextView btnCreate;
private TextView btnClose;
private ImageView upload_car, preview;
private int GALLERY = 1, CAMERA = 2;
private static String URL_ADD_VEHICLE = "http://abcde/server/api/addvehicle.php";
//private static String URL_VEHICLE_IMAGE = "http://abcde/server/api/addvehicle.php";
private Bitmap bitmap;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_addvehicle);
requestMultiplePermissions();
/*EditText Area*/
plate_number = findViewById(R.id.plate_number);
vin = findViewById(R.id.vin);
car_make = findViewById(R.id.car_make);
car_model = findViewById(R.id.car_model);
car_year = findViewById(R.id.car_year);
displacement = findViewById(R.id.displacement);
fuel_type = findViewById(R.id.fuel_type);
transmission = findViewById(R.id.transmission);
mileage = findViewById(R.id.mileage);
owner_name = findViewById(R.id.owner_name);
address = findViewById(R.id.address);
phone_number = findViewById(R.id.phone_number);
email_adress = findViewById(R.id.email_adress);
facebook = findViewById(R.id.facebook);
/*TextView Area*/
btnClose = findViewById(R.id.btnClose);
btnCreate = findViewById(R.id.btnCreate);
/*Button Area*/
upload_car = findViewById(R.id.iv);
preview = findViewById(R.id.iv);
upload_car.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
showPictureDialog();
}
});
btnClose.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(Addvehicle.this, Home.class));
}
});
btnCreate.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
showLoader();
addVehicle(getStringImage(bitmap));
}
});
}
private void showPictureDialog(){
AlertDialog.Builder pictureDialog = new AlertDialog.Builder(this);
pictureDialog.setTitle("Select Action");
String[] pictureDialogItems = {
"Select photo from gallery",
"Capture photo from camera" };
pictureDialog.setItems(pictureDialogItems,
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
switch (which) {
case 0:
choosePhotoFromGallary();
break;
case 1:
takePhotoFromCamera();
break;
}
}
});
pictureDialog.show();
}
public void choosePhotoFromGallary() {
Intent galleryIntent = new Intent(Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(galleryIntent, GALLERY);
}
private void takePhotoFromCamera() {
Intent intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, CAMERA);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == this.RESULT_CANCELED) {
return;
}
if (requestCode == GALLERY) {
if (data != null) {
Uri filePath = data.getData();
try {
bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), filePath);
String path = getStringImage(bitmap);
Toast.makeText(Addvehicle.this, "Image Saved!", Toast.LENGTH_SHORT).show();
preview.setImageBitmap(bitmap);
} catch (IOException e) {
e.printStackTrace();
Toast.makeText(Addvehicle.this, "Failed!", Toast.LENGTH_SHORT).show();
}
addVehicle(getStringImage(bitmap));
}
} else if (requestCode == CAMERA) {
Bitmap thumbnail = (Bitmap) data.getExtras().get("data");
preview.setImageBitmap(thumbnail);
getStringImage(thumbnail);
Toast.makeText(Addvehicle.this, "Image Saved!", Toast.LENGTH_SHORT).show();
}
addVehicle(getStringImage(bitmap));
}
private void addVehicle(final String stringImage) {
final String plate_number = this.plate_number.getText().toString().trim();
final String vin = this.vin.getText().toString().trim();
final String car_make = this.car_make.getText().toString().trim();
final String car_model = this.car_model.getText().toString().trim();
final String car_year = this.car_year.getText().toString().trim();
final String displacement = this.displacement.getText().toString().trim();
final String fuel_type = this.fuel_type.getText().toString().trim();
final String transmission = this.transmission.getText().toString().trim();
final String mileage = this.mileage.getText().toString().trim();
final String owner_name = this.owner_name.getText().toString().trim();
final String address = this.address.getText().toString().trim();
final String phone_number = this.phone_number.getText().toString().trim();
final String email_adress = this.email_adress.getText().toString().trim();
final String facebook = this.facebook.getText().toString().trim();
StringRequest stringRequest = new StringRequest(Request.Method.POST, URL_ADD_VEHICLE,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.i(TAG, response.toString());
try {
JSONObject jsonObject = new JSONObject(response);
String Success = jsonObject.getString("success");
if (Success.equals("1")){
hideLoader();
Toast.makeText(Addvehicle.this,"Vehicle Added Successfully",Toast.LENGTH_SHORT).show();
}else if (Success.equals("0")){
hideLoader();
Toast.makeText(Addvehicle.this,"Vehicle Already Exist",Toast.LENGTH_SHORT).show();
}
}catch (JSONException e){
e.printStackTrace();
hideLoader();
Toast.makeText(Addvehicle.this,"Vehicle Added Error"+e.toString(),Toast.LENGTH_SHORT).show();
}
}
},
new Response.ErrorListener(){
#Override
public void onErrorResponse(VolleyError error){
Toast.makeText(Addvehicle.this,"Vehicle Added Error"+error.toString(),Toast.LENGTH_SHORT).show();
hideLoader();
}
})
{
#Override
protected Map<String, String> getParams() throws AuthFailureError{
Map<String, String> params = new HashMap<>();
params.put("plate_number", plate_number);
params.put("vin", vin);
params.put("car_make", car_make);
params.put("car_model", car_model);
params.put("car_year", car_year);
params.put("displacement", displacement);
params.put("fuel_type", fuel_type);
params.put("transmission", transmission);
params.put("mileage", mileage);
params.put("owner_name", owner_name);
params.put("address", address);
params.put("phone_number", phone_number);
params.put("email_adress", email_adress);
params.put("facebook", facebook);
params.put("photo", stringImage);
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
public void showLoader(){
ProgressDialog progressDialog = new ProgressDialog(this);
progressDialog.setMessage("Adding Vehicle...");
progressDialog.show();
}
public void hideLoader(){
ProgressDialog progressDialog = new ProgressDialog(this);
progressDialog.hide();
}
public String getStringImage(Bitmap bitmap){
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, byteArrayOutputStream);
byte[] imageByteArray = byteArrayOutputStream.toByteArray();
String encodedImage = Base64.encodeToString(imageByteArray, Base64.DEFAULT);
return encodedImage;
}
private void requestMultiplePermissions(){
Dexter.withActivity(this)
.withPermissions(
Manifest.permission.CAMERA,
Manifest.permission.WRITE_EXTERNAL_STORAGE,
Manifest.permission.READ_EXTERNAL_STORAGE)
.withListener(new MultiplePermissionsListener() {
#Override
public void onPermissionsChecked(MultiplePermissionsReport report) {
// check if all permissions are granted
if (report.areAllPermissionsGranted()) {
Toast.makeText(getApplicationContext(), "All permissions are granted by user!", Toast.LENGTH_SHORT).show();
}
// check for permanent denial of any permission
if (report.isAnyPermissionPermanentlyDenied()) {
// show alert dialog navigating to Settings
//openSettingsDialog();
}
}
#Override
public void onPermissionRationaleShouldBeShown(List<PermissionRequest> permissions, PermissionToken token) {
token.continuePermissionRequest();
}
}).
withErrorListener(new PermissionRequestErrorListener() {
#Override
public void onError(DexterError error) {
Toast.makeText(getApplicationContext(), "Some Error! ", Toast.LENGTH_SHORT).show();
}
})
.onSameThread()
.check();
}
This is my server api file (mysqli) which is giving me the error response from logcat with this url : "http://abcde/server/api/addvehicle.php"
error_reporting(E_ALL); ini_set('display_errors', 1);
require '../core/connect.php';
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$plate_number=$_POST['plate_number'];
$vin=$_POST['vin'];
$car_make=$_POST['car_make'];
$car_model=$_POST['car_model'];
$car_year=$_POST['car_year'];
$displacement=$_POST['displacement'];
$fuel_type=$_POST['fuel_type'];
$transmission=$_POST['transmission'];
$mileage=$_POST['mileage'];
$owner_name=$_POST['owner_name'];
$address=$_POST['address'];
$phone_number=$_POST['phone_number'];
$email_adress=$_POST['email_adress'];
$facebook=$_POST['facebook'];
$adddate = date("d/m/Y");
$photo = $_POST['photo'];
$id=uniqid();
$path = "vehicle_upload/$id.jpeg";
$finalpath =
"http://abcde/server/api/addvehicle.php".$path;
$sql1=mysqli_query($connect,"SELECT * FROM _addvehicle WHERE
PlateNumber='$plate_number'");
if (mysqli_num_rows($sql1) > 0) {
$result['success'] = "0";
$result['message'] = "error";
echo json_encode($result);
}else{
$sql = mysqli_query($connect, "INSERT IGNORE INTO
_addvehicle(PlateNumber, Vin, Make, Model, Year, Displacement, FuelType,
Transmission, Mileage, OwnerorCompany, HomeorCompanyAddress, ContactNumber,
EmailAddress, FacebookID, AddDate, vehicleImage)VALUES('$plate_number','$vin','$car_make','$car_model','$car_year','$displacement','$fuel_type','$transmission','$mileage','$owner_name','$address','$phone_number','$email_adress','$facebook','$adddate','$finalpath')");
if ($sql) {
if (file_put_contents($path, base64_decode($photo))) {
$result['success'] = "1";
$result['message'] = "success";
echo json_encode($result);
//mysqli_close($connect);
}
}
}
I am having a hard time identifying what went wrong. Although I am seeing that logcat points me to the php file, it doesn't specifically tell me what to change. This page was working a couple of days ago.
When I put something wrong, I receive everything in onResponse but it does not go for the function resultado() and when I put all the data well, it goes to the function resultaod() but only until the time to assign the values to usuario and from the toast it is not executed.
Login Activity
public class LoginActivity extends AppCompatActivity {
private RelativeLayout parentLayout;
private EditText txtUsuario, txtContraseña;
private TextView txtVersion;
private CheckBox chxRecordar;
private Button btnEntrar;
private SharedPreferences myPreferences;
private Usuario usuario;
private String codes, status, token;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
iniciarComponentes();
btnEntrar.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
verificarInicio();
}
});
}
private void iniciarComponentes() {
parentLayout = findViewById(R.id.parent_layout);
txtUsuario = findViewById(R.id.txt_usuario);
txtContraseña = findViewById(R.id.txt_password);
chxRecordar = findViewById(R.id.chx_recordar);
btnEntrar = findViewById(R.id.btn_entrar);
txtVersion = findViewById(R.id.txt_version);
txtVersion.setText("Version " + BuildConfig.VERSION_NAME);
myPreferences = PreferenceManager.getDefaultSharedPreferences(this);
}
private void verificarInicio() {
String url = Common.BASE_URL + "usuario";
if (validarSesion()) {
Log.d("verificarInicio: ", url);
final String usuario = txtUsuario.getText().toString();
final String contraseña = txtContraseña.getText().toString();
final android.app.AlertDialog dialog = new SpotsDialog.Builder().setContext(this).setMessage("Cargando...").setCancelable(false).build();
dialog.show();
RequestQueue requestQueue = Volley.newRequestQueue(LoginActivity.this);
final StringRequest stringRequest = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonObject = new JSONObject(response);
codes = jsonObject.getString("code");
status = jsonObject.getString("status");
token = jsonObject.getString("token");
resultado(codes, status, jsonObject, token);
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Snackbar.make(parentLayout, error.getMessage(), Snackbar.LENGTH_LONG).show();
dialog.dismiss();
}
}) {
#Override
protected Map<String, String> getParams() {
HashMap<String, String> parametros = new HashMap<>();
parametros.put("dni", usuario);
parametros.put("password", contraseña);
return parametros;
}
};
requestQueue.add(stringRequest);
requestQueue.addRequestFinishedListener(new RequestQueue.RequestFinishedListener<String>() {
#Override
public void onRequestFinished(Request<String> request) {
if (dialog.isShowing())
dialog.dismiss();
}
});
}
}
private void resultado(String codes, String status, JSONObject jsonObject, String token) throws JSONException {
if (codes.equals("100")) {
JSONArray array = jsonObject.getJSONArray("result");
JSONObject dato = array.getJSONObject(0);
usuario = new Usuario(dato.getString("NombreCompleto"),
dato.getString("estado"),
dato.getString("foto"),
dato.getString("nombre_Aso"),
dato.getString("nombre_Red"),
dato.getString("sexo_Pro"),
dato.getInt("campana"));
Toast.makeText(LoginActivity.this, status, Toast.LENGTH_SHORT).show();
Common.USUARIO_DNI = txtUsuario.getText().toString();
guardarUsuario(token);
Intent intent = new Intent(LoginActivity.this, MainActivity.class);
intent.putExtra(Common.USUARIO, usuario);
startActivity(intent);
finish();
} else if (codes.equals("200")) {
Snackbar.make(parentLayout, status, Snackbar.LENGTH_LONG).show();
} else if (codes.equals("203")) {
Snackbar.make(parentLayout, status, Snackbar.LENGTH_LONG).show();
}
}
private boolean validarSesion() {
if (TextUtils.isEmpty(txtUsuario.getText()) || TextUtils.isEmpty(txtContraseña.getText())) {
Snackbar.make(parentLayout, "Ingrese su usuario y contraseña", Snackbar.LENGTH_SHORT).show();
return false;
}
return true;
}
private void guardarUsuario(String token) {
SharedPreferences.Editor myEditor = myPreferences.edit();
if (chxRecordar.isChecked()) {
if (!myPreferences.contains(Common.USUARIO)) {
myEditor.putString(Common.USUARIO, txtUsuario.getText().toString());
myEditor.putString(Common.CONTRASEÑA, txtContraseña.getText().toString());
myEditor.putBoolean(Common.CHECK_ESTADO, chxRecordar.isChecked());
myEditor.putString(Common.TOKEN, token);
myEditor.apply();
if (Common.USUARIO_DNI.isEmpty()) {
Common.USUARIO_DNI = myPreferences.getString(Common.USUARIO, "");
}
}
} else {
myEditor.clear();
myEditor.commit();
}
}
}
The whole code is not executed, only a part, I do not know why, I would be grateful if you helped me
check that recibe in a catch, the problem is when get the string for the jsonObject
#Override
public void onResponse(String response) {
try {
JSONObject jsonObject = new JSONObject(response);
codes = jsonObject.getString("code");
status = jsonObject.getString("status");
token = jsonObject.getString("token");
resultado(codes, status, jsonObject, token);
} catch (JSONException e) {
e.printStackTrace();
}
}
I have to upload a file and has three more parameters which is string.The file can be image or zip.How is it possible with volley to upload a file and submit string parameters along with it when button is clicked?
I have also tried this link-https://www.simplifiedcoding.net/upload-pdf-file-server-android/
Please help me.Thanks!!
My code is:
public class Tab1Fragment extends Fragment implements
AdapterView.OnItemSelectedListener {
EditText subj,desx;
private ImageView mAvatarImage;
Button choosefile,select,submt;
String uid, type;
String MY_PREFS_NAME = "value";
private int PICK_PDF_REQUEST = 1;
TextView filetext;
//storage permission code
private static final int STORAGE_PERMISSION_CODE = 123;
String uploadId;
//Uri to store the image uri
private Uri filePath;
Spinner spinner,spinner2;
public Tab1Fragment() {
// Required empty public constructor
}
public static Tab1Fragment newInstance() {
Tab1Fragment fragment = new Tab1Fragment();
return fragment;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootview= inflater.inflate(R.layout.fragment_tab1, container,
false);
subj=(EditText)rootview.findViewById(R.id.subj);
choosefile=(Button)rootview.findViewById(R.id.choosefile);
select=(Button)rootview.findViewById(R.id.select);
submt=(Button)rootview.findViewById(R.id.submt);
filetext=(TextView)rootview.findViewById(R.id.filetext);
mAvatarImage=(ImageView)rootview.findViewById(R.id.image);
desx=(EditText)rootview.findViewById(R.id.desx);
submt.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
saveProfileAccount();
}
});
select.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
showFileChooser();
}
});
choosefile.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
uploadMultipart();
}
});
requestStoragePermission();
SharedPreferences prefs =
this.getActivity().getSharedPreferences(MY_PREFS_NAME,
Context.MODE_PRIVATE);
uid = prefs.getString("uid", null);
spinner = (Spinner)rootview.findViewById(R.id.spinner);
spinner2 = (Spinner)rootview.findViewById(R.id.spinner2);
// Spinner click listener
spinner.setOnItemSelectedListener(this);
spinner2.setOnItemSelectedListener(this);
// Spinner Drop down elements
List<String> deparment= new ArrayList<String>();
deparment.add("Support");
deparment.add("Project");
deparment.add("Payment");
deparment.add("Service");
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this.getActivity(),android.R.layout.simple_spinner_item, deparment);
// Drop down layout style - list view with radio button
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// attaching data adapter to spinner
spinner.setAdapter(dataAdapter);
List<String> priority= new ArrayList<String>();
priority.add("low");
priority.add("Medium");
priority.add("High");
ArrayAdapter<String> dataAdapter2 = new ArrayAdapter<String>(this.getActivity(),android.R.layout.simple_spinner_item, priority);
// Drop down layout style - list view with radio button
dataAdapter2.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// attaching data adapter to spinner
spinner2.setAdapter(dataAdapter2);
return rootview;
}
private void saveProfileAccount() {
VolleyMultipartRequest multipartRequest = new VolleyMultipartRequest(Request.Method.POST, Constants.UPLOAD_SUPPORT, new Response.Listener<NetworkResponse>() {
#Override
public void onResponse(NetworkResponse response) {
String resultResponse = new String(response.data);
try {
JSONObject b = new JSONObject(resultResponse);
int status = b.getInt("status");
String data = b.getString("message");
Log.d("Response", data);
if (status ==100) {
/* Intent intent = new Intent(getActivity(),Skills.class);
startActivity(intent);*/
Toast.makeText(getActivity(), data, Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
NetworkResponse networkResponse = error.networkResponse;
String errorMessage = "Unknown error";
if (networkResponse == null) {
if (error.getClass().equals(TimeoutError.class)) {
errorMessage = "Request timeout";
} else if (error.getClass().equals(NoConnectionError.class)) {
errorMessage = "Failed to connect server";
}
} else {
String result = new String(networkResponse.data);
try {
JSONObject response = new JSONObject(result);
String status = response.getString("status");
String message = response.getString("message");
Log.e("Error Status", status);
Log.e("Error Message", message);
if (networkResponse.statusCode == 404) {
errorMessage = "Resource not found";
} else if (networkResponse.statusCode == 401) {
errorMessage = message+" Please login again";
} else if (networkResponse.statusCode == 400) {
errorMessage = message+ " Check your inputs";
} else if (networkResponse.statusCode == 500) {
errorMessage = message+" Something is getting wrong";
}
} catch (JSONException e) {
e.printStackTrace();
}
}
Log.i("Error", errorMessage);
error.printStackTrace();
}
}) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<>();
params.put("userid", uid);
params.put("department", spinner.getSelectedItem().toString());
params.put("priority",
spinner2.getSelectedItem().toString().trim());
params.put("subject", subj.getText().toString().trim());
params.put("description",desx.getText().toString().trim());
return params;
}
#Override
protected Map<String, DataPart> getByteData() {
Map<String, DataPart> params = new HashMap<>();
// file name could found file base or direct access from real path
// for now just get bitmap data from ImageView
params.put("avatar", new DataPart("file_avatar.jpg", AppHelper.getFileDataFromDrawable(getContext(), mAvatarImage.getDrawable()), "*/*"));
return params;
}
};
VolleySingleton.getInstance(getContext()).addToRequestQueue(multipartRequest);
}
try this
public void fileUploadFunction() {
// Getting file path using Filepath class.
Pdfuri = FilePath.getPath(this, uri);
Log.d("Pdfuri", Pdfuri);
// If file path object is null then showing toast message to move file into internal storage.
if (Pdfuri == null) {
Toast.makeText(this, "Please move your PDF file to internal storage & try again.", Toast.LENGTH_LONG).show();
}
// If file path is not null then PDF uploading file process will starts.
else {
try {
PdfID = UUID.randomUUID().toString();
new MultipartUploadRequest(this, PdfID, AppConstants.URL)
.addFileToUpload(Pdfuri, "pdf")
.addParameter("course", course.trim())
.addParameter("course_id", c_id.trim())
.addParameter("stream", stream.trim())
.setNotificationConfig(new UploadNotificationConfig())
.setMaxRetries(5)
.startUpload();
Toast.makeText(MainActivity.this,"Successfully Uploaded",Toast.LENGTH_SHORT).show();
} catch (Exception exception) {
Toast.makeText(this,
exception.getMessage(),Toast.LENGTH_SHORT).show();
}
}
}
VolleyMultipartRequest multipartRequest = new VolleyMultipartRequest(Request.Method.POST, url, new Response.Listener<NetworkResponse>() {
#Override
public void onResponse(NetworkResponse response) {
//Read response here
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
}) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<>();
//Add post values here
return params;
}
#Override
protected Map<String, DataPart> getByteData() {
Map<String, DataPart> params = new HashMap<>();
// Add you file here
return params;
}
};
VolleySingleton.getInstance(getBaseContext()).addToRequestQueue(multipartRequest);
You can use multipart for this. Here is a sample code
I'm developing an app and I'm blocked in one simple thing.
In my Activity, I show a dialog (AlertDialog.Builder) that ask a mail address and an activation. These two fields are checked with a Rest API.
If the activation code is wrong I restart the activity (with an Intent) and I show again the dialog.
I don't understand why, if I'm wrong the activation code the first time, the second time appears the dialog correctly, but when I click "submit", the app doesn't run the Rest call and return always "Invalid credentials", like if it would remind the old "state".
Instead, if I run the app and I put the correct credentials, all is ok.
Any idea?
Source code:
public class PinActivity extends Activity {
String mail;
String verification;
JSONObject responseServer;
BluetoothSocket bsocket;
ConnectedThreadBT cdbt;
SharedPreferences sharedPref;
SharedPreferences.Editor editor;
EditText mail_add;
EditText verification_code;
#Override
protected void onCreate (Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_check);
setup();
dialogActivation();
}
#Override
public void onDestroy() {
super.onDestroy();
}
private void setup(){
RestClientManager.initialize(getApplicationContext()).enableDebugLog(true);
bsocket = BluetoothApplication.getBSocket();
//salvo codice attivazione sul pacchetto
cdbt=new ConnectedThreadBT(bsocket,mHandler, "PinActivity");
cdbt.start();
}
private void dialogActivation(){
android.support.v7.app.AlertDialog.Builder builder = new android.support.v7.app.AlertDialog.Builder(new ContextThemeWrapper(this, R.style.myDialog));
LayoutInflater inflater = (LayoutInflater) getApplicationContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = inflater.inflate(R.layout.custom_dialog_verification, null);
mail_add = (EditText) view.findViewById(R.id.mailAddress);
verification_code = (EditText) view.findViewById(R.id.verification_code);
builder.setView(view).
setPositiveButton(getApplicationContext().getResources().getString(R.string.submit), new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
//prendo e salvo credenziali
mail = mail_add.getText().toString();
verification = verification_code.getText().toString();
//invio dati al server
activatePPS();
}
});
builder.setCancelable(false);
builder.show();
}
private void activatePPS(){
dialogCheck();
String url = "....";
RestClientManager.getInstance().makeJsonRequest(Request.Method.POST, url, new RequestHandler<>(new RequestCallbacks<JSONObject, Error>()
{
#Override
public void onRequestSuccess(JSONObject response)
{
responseServer = response;
int reply_code = 0;
try {
reply_code = response.getInt("reply_code");
checkReplyCode(reply_code);
} catch (JSONException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
public void onRequestError(Error error)
{
}
}, paramsList()));
}
private void dialogCheck(){
android.support.v7.app.AlertDialog.Builder builder = new android.support.v7.app.AlertDialog.Builder(new ContextThemeWrapper(this, R.style.myDialog));
LayoutInflater inflater = (LayoutInflater) getApplicationContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = inflater.inflate(R.layout.custom_dialog_load_check, null);
builder.setView(view);
builder.setCancelable(false);
builder.show();
}
private void checkReplyCode(int reply_code) throws JSONException, IOException {
switch(reply_code){
case 0:
successActivation();
break;
case 1001:
//credenziali invalide
Toast.makeText(getApplicationContext(), getResources().getString(R.string.wrong_credentials), Toast.LENGTH_LONG).show();
Intent intent = new Intent(PinActivity.this, PinActivity.class);
startActivity(intent);
break;
}
}
private void successActivation() throws JSONException {
String access_token = responseServer.get("access_token").toString();
String nickname = responseServer.get(".....
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
int value = sharedPref.getInt("step_conf",0);
if(value==0){
Intent intent = new Intent(getApplicationContext(), MethodCurveActivity.class);
intent.putExtra("style", 0);
startActivity(intent);
}
else{
Intent intent = new Intent(getApplicationContext(), MainActivity.class);
startActivity(intent);
}
}
},3000);
}
private ArrayMap<String, String> paramsList(){
ArrayMap<String, String> parameters=new ArrayMap<>();
parameters.put("user_mail", mail);
parameters.put(.....
return parameters;
}
private void resetMobileDevice(){
String url = "....";
RestClientManager.getInstance().makeJsonRequest(Request.Method.POST, url, new RequestHandler<>(new RequestCallbacks<JSONObject, Error>()
{
#Override
public void onRequestSuccess(JSONObject response)
{
System.out.println("Risposta:"+response);
responseServer = response;
int reply_code = 0;
try {
reply_code = response.getInt("reply_code");
} catch (JSONException e) {
e.printStackTrace();
}
try {
checkReplyCode(reply_code);
} catch (JSONException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
public void onRequestError(Error error)
{
}
}, paramsList()));
}
private final Handler mHandler = new Handler() {
#Override
public void handleMessage(Message msg) {
switch (msg.what) {
}
}
};
}
The important point is in the "case 1001", after error.
I have tried finish() and all the method to delete the old instance of the Activity...
Create Application class in your project and initialize RestClientManager in its onCreate Method like this:
public class MyApp extends Application {
private final static String LOG_TAG = Application.class.getSimpleName();
#Override
public void onCreate() {
Log.d(LOG_TAG, "Application.onCreate - Initializing application...");
super.onCreate();
initializeApplication();
Log.d(LOG_TAG, "Application.onCreate - Application initialized OK");
}
private void initializeApplication() {
RestClientManager.initialize(getApplicationContext()).enableDebugLog(true);
}
}
Add this line in your <Application> tag in androidmanifest.xml file:
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:name=".App"
android:theme="#style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
And Make sure your singleton structure should be something like this:
private static RestClientManager instance;
static void initInstance()
{
if (instance == null)
{
// Create the instance
instance = new RestClientManager();
}
}
public static RestClientManager getInstance()
{
// Return the instance
return instance;
}
Remember to remove
RestClientManager.initialize(getApplicationContext()).enableDebugLog(true);
from your main activity.
Please give it a try and let me know.
In my app, the user can upload the image to the server, but in some devices such as phones of version (4.4.4. 5.0.1 and 5.1.1) or even for all devices when selecting the image from "gallery" the app crashes. But when I choose the option "photos" and select photo and upload it, it works normally, so how can fix this problem and can select the photo from gallery or any album without crashing also upload it without any problem?
Given below is the full code of uploading the image:
public class send extends AppCompatActivity {
private Button buttonChoose;
private Button buttonUpload;
private ImageView imageView;
private EditText editTextName;
private EditText editTextPhone;
private EditText editTextText;
private Bitmap bitmap;
private int PICK_IMAGE_REQUEST = 1;
private static String host=PathConfig.hostName;
private String UPLOAD_URL ="http://"+host+"/upload.php";
private String KEY_IMAGE = "image";
private String KEY_NAME = "name";
private String KEY_PHONE = "phone";
private String KEY_TEXT = "text";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_send);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_send);
setSupportActionBar(toolbar);
getSupportActionBar().setHomeAsUpIndicator(R.drawable.arrowb);
getSupportActionBar().setDisplayHomeAsUpEnabled(true); // setting the back arrow in the toolbar
getSupportActionBar().setDisplayShowHomeEnabled(true);
setTitle("إرسال شكوى أو إقتراح");
buttonChoose = (Button) findViewById(R.id.chooseButton);
buttonUpload = (Button) findViewById(R.id.sendButton);
editTextName = (EditText) findViewById(R.id.name);
editTextPhone= (EditText) findViewById(R.id.phone);
editTextText= (EditText) findViewById(R.id.text);
imageView = (ImageView) findViewById(R.id.imageView4);
buttonChoose.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
showFileChooser();
}
});
buttonUpload.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
uploadImage();
}
});
}
public String getStringImage(Bitmap bmp){
ByteArrayOutputStream baos = new ByteArrayOutputStream();
if(bmp!=null){
bmp.compress(Bitmap.CompressFormat.JPEG, 100, baos);
}
byte[] imageBytes = baos.toByteArray();
String encodedImage = Base64.encodeToString(imageBytes, Base64.DEFAULT);
return encodedImage;
}
private void uploadImage() {
final String name = editTextName.getText().toString().trim();
final String phone = editTextPhone.getText().toString().trim();
final String text = editTextText.getText().toString().trim();
if (name.matches("") || phone.matches("") || text.matches("")) {
Toast.makeText(this, " عذرا, لا يمكن ترك حقول فارغة", Toast.LENGTH_SHORT).show();
} else {
//Showing the progress dialog
final ProgressDialog loading = ProgressDialog.show(this, "جاري الإرسال...", "الرجاء الإنتظار...", false, false);
StringRequest stringRequest = new StringRequest(Request.Method.POST, UPLOAD_URL,
new Response.Listener<String>() {
#Override
public void onResponse(String s) {
//Disimissing the progress dialog
loading.dismiss();
//Showing toast message of the response
Toast.makeText(send.this, s, Toast.LENGTH_LONG).show();
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError volleyError) {
//Dismissing the progress dialog
loading.dismiss();
//Showing toast
Toast.makeText(send.this, volleyError.getMessage().toString(), Toast.LENGTH_LONG).show();
}
}) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
//Converting Bitmap to String
String image = getStringImage(bitmap);
//Getting Image Name
//Creating parameters
Map<String, String> params = new HashMap<String, String>();
//Adding parameters
params.put(KEY_IMAGE, image);
params.put(KEY_NAME, name);
params.put(KEY_PHONE, phone);
params.put(KEY_TEXT, text);
//returning parameters
return params;
}
};
//Creating a Request Queue
RequestQueue requestQueue = Volley.newRequestQueue(this);
//Adding request to the queue
requestQueue.add(stringRequest);
}
}
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);
}
#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 {
//Getting the Bitmap from Gallery
bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), filePath);
//Setting the Bitmap to ImageView
imageView.setImageBitmap(bitmap);
} catch (IOException e) {
e.printStackTrace();
}
}
}
#Override
public boolean onSupportNavigateUp() {
onBackPressed();
return true;
}
}
I think you missing to ask permission.Can you check this is useful for you?
profile_img.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (Build.VERSION.SDK_INT >= 23) {
// Marshmallow+
if (!checkAccessFineLocationPermission() || !checkAccessCoarseLocationPermission() || !checkWriteExternalStoragePermission()) {
requestPermission();
} else {
selectImage();
}
}else{
selectImage();
}
}
});