Using Retrofits2 upload file to server in android - android

Why can not I upload files to the server? When I used Log.d to print to the log screen, it reported an error can not connect to 192.168.10.2:8080 although I have asked for permission to the Internet and read the internal memory of the device.
APIUtils.java
import android.provider.ContactsContract;
public class APIUtils {
public static final String Base_Url = "http://192.168.10.2:8080/Quanlysinhvien/";
public static DataClient getData(){
return RetrofitClient.getClient(Base_Url).create(DataClient.class);
}
}
DataClient.java
import okhttp3.MultipartBody;
import retrofit2.Call;
import retrofit2.http.Multipart;
import retrofit2.http.POST;
import retrofit2.http.Part;
public interface DataClient {
#Multipart
#POST("uploadhinhanh.php")
Call<String> UploadPhot(#Part MultipartBody.Part phto);
}
RetrofitClient.java
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import java.util.concurrent.TimeUnit;
import okhttp3.OkHttpClient;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
public class RetrofitClient {
private static Retrofit retrofit = null;
public static Retrofit getClient(String baseurl){
OkHttpClient builder = new OkHttpClient.Builder()
.readTimeout(5000, TimeUnit.MILLISECONDS)
.writeTimeout(5000, TimeUnit.MILLISECONDS)
.connectTimeout(10000, TimeUnit.MILLISECONDS)
.retryOnConnectionFailure(true)
.build();
Gson gson = new GsonBuilder().setLenient().create();
retrofit = new Retrofit.Builder()
.baseUrl(baseurl)
.client(builder)
.addConverterFactory(GsonConverterFactory.create())
.build();
return retrofit;
}
}
DangKyActivity.java
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import com.example.nhutkhanh.demoretrofit2.Retrofit2.APIUtils;
import com.example.nhutkhanh.demoretrofit2.Retrofit2.DataClient;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.InputStream;
import okhttp3.Call;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import retrofit2.Callback;
import retrofit2.Response;
public class DangKyActivity extends AppCompatActivity {
ImageView imgdangky;
EditText edtUsername, edtPassword;
Button btnhuy, btnxacnhan;
int Request_Code_Image = 123;
String realpath = "";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_dang_ky);
anhxa();
imgdangky.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(Intent.ACTION_PICK);
intent.setType("image/*");
startActivityForResult(intent, Request_Code_Image);
}
});
btnxacnhan.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
File file = new File(realpath);
String file_path = file.getAbsolutePath();
String[] mangtenfile = file_path.split("\\.");
file_path = mangtenfile[0] + System.currentTimeMillis() + "." + mangtenfile[1];
RequestBody requestBody = RequestBody.create(MediaType.parse("multipart/from-data"), file);
MultipartBody.Part body = MultipartBody.Part.createFormData("uploaded_file", file_path, requestBody);
DataClient dataClient = APIUtils.getData();
retrofit2.Call<String> callback = dataClient.UploadPhot(body);
callback.enqueue(new Callback<String>() {
#Override
public void onResponse(retrofit2.Call<String> call, Response<String> response) {
if(response != null){
String message = response.body();
Log.d("AAA", message);
}
}
#Override
public void onFailure(retrofit2.Call<String> call, Throwable t) {
Log.d("BBB", "Lỗi " + t.getMessage());
}
});
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if(requestCode == Request_Code_Image && resultCode == RESULT_OK && data != null){
Uri uri = data.getData();
realpath = getRealPathFromURI(uri);
try {
InputStream inputStream = getContentResolver().openInputStream(uri);
Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
imgdangky.setImageBitmap(bitmap);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
super.onActivityResult(requestCode, resultCode, data);
}
public String getRealPathFromURI (Uri contentUri) {
String path = null;
String[] proj = { MediaStore.MediaColumns.DATA };
Cursor cursor = getContentResolver().query(contentUri, proj, null, null, null);
if (cursor.moveToFirst()) {
int column_index = cursor.getColumnIndexOrThrow(MediaStore.MediaColumns.DATA);
path = cursor.getString(column_index);
}
cursor.close();
return path;
}
private void anhxa() {
imgdangky = (ImageView)findViewById(R.id.imageViewDK);
edtPassword = (EditText)findViewById(R.id.editTextDKMK);
edtUsername = (EditText)findViewById(R.id.editTextDKTK);
btnhuy = (Button)findViewById(R.id.buttonHuy);
btnxacnhan = (Button)findViewById(R.id.buttonXacNhan);
}
}
MainActivity.java
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}

Related

Attempt to invoke virtual method 'int java.lang.String.length()' on a null object reference, iven that object is not null and initialize

i know that quastion has asked lot of times, but im realy dont found solution.
i know the error come couse the object intent is null, but how? if i choose a picture from a gallery?
this is the the error i get
E/Volley: [497] NetworkDispatcher.processRequest: Unhandled exception java.lang.NullPointerException: Attempt to invoke virtual method 'int java.lang.String.length()' on a null object reference
java.lang.NullPointerException: Attempt to invoke virtual method 'int java.lang.String.length()' on a null object reference
at java.net.URLEncoder.encode(URLEncoder.java:205)
at com.android.volley.Request.encodeParameters(Request.java:491)
at com.android.volley.Request.getBody(Request.java:477)
at com.android.volley.toolbox.HurlStack.addBodyIfExists(HurlStack.java:245)
at com.android.volley.toolbox.HurlStack.setConnectionParametersForRequest(HurlStack.java:219)
at com.android.volley.toolbox.HurlStack.executeRequest(HurlStack.java:97)
at com.android.volley.toolbox.BasicNetwork.performRequest(BasicNetwork.java:131)
at com.android.volley.NetworkDispatcher.processRequest(NetworkDispatcher.java:120)
at com.android.volley.NetworkDispatcher.run(NetworkDispatcher.java:87)
D/EGL_emulation: eglMakeCurrent: 0xa7685060: ver 3 1 (tinfo 0xa7683280)
D/EGL_emulation: eglMakeCurrent: 0xa7685060: ver 3 1 (tinfo 0xa7683280)
this is my intent object part:
btnSelectImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Dexter.withActivity(uploadimage.this).withPermission(Manifest.permission.READ_EXTERNAL_STORAGE)
.withListener(new PermissionListener() {
#Override
public void onPermissionGranted(PermissionGrantedResponse response) {
Intent intent = new Intent(Intent.ACTION_PICK);
intent.setType("image/*");
startActivityForResult(Intent.createChooser(intent,"Select image"),1);
}
when i came to this part of the code, its fall, couse intent is null? but why is like that?
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
if(requestCode==1 && requestCode==RESULT_OK && data!= null){
Uri filePath = data.getData();
try {
InputStream inputStream = getContentResolver().openInputStream(filePath);
bitmap = BitmapFactory.decodeStream(inputStream);
imageView.setImageBitmap(bitmap);
imageStore(bitmap);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
super.onActivityResult(requestCode, resultCode, data);
}
what can be the problem?
i add to manifest the permission of READ_EXTERNAL_STORAGE .
this is all my code, if its relevant.
package com.example.yacovapp;
import android.Manifest;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import com.android.volley.toolbox.StringRequest;
import android.widget.Toast;
import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.Volley;
import com.karumi.dexter.Dexter;
import com.karumi.dexter.PermissionToken;
import com.karumi.dexter.listener.PermissionDeniedResponse;
import com.karumi.dexter.listener.PermissionGrantedResponse;
import com.karumi.dexter.listener.PermissionRequest;
import com.karumi.dexter.listener.single.PermissionListener;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.Map;
import java.io.ByteArrayOutputStream;
import java.util.HashMap;
import android.util.Base64;
public class uploadimage extends AppCompatActivity {
Button btnSelectImage, btnUploadImage;
ImageView imageView;
Bitmap bitmap;
String encodedImage;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_uploadimage);
btnSelectImage = (Button) findViewById(R.id.btnSelectImage);
btnUploadImage = (Button) findViewById(R.id.buttonUploadImage);
imageView = findViewById(R.id.imView);
btnSelectImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Dexter.withActivity(uploadimage.this).withPermission(Manifest.permission.READ_EXTERNAL_STORAGE)
.withListener(new PermissionListener() {
#Override
public void onPermissionGranted(PermissionGrantedResponse response) {
Intent intent = new Intent(Intent.ACTION_PICK);
intent.setType("image/*");
startActivityForResult(Intent.createChooser(intent,"Select image"),1);
}
#Override
public void onPermissionDenied(PermissionDeniedResponse response) { }
#Override
public void onPermissionRationaleShouldBeShown(PermissionRequest permission, PermissionToken token) { }
}).check();
}
});
btnUploadImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
StringRequest request = new StringRequest(Request.Method.POST, "https://kerron.xyz/htdocs/images.php"
, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Toast.makeText(uploadimage.this, response, Toast.LENGTH_SHORT).show();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(uploadimage.this, error.getMessage(), Toast.LENGTH_SHORT).show();
}
}){
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map <String, String> param = new HashMap<>();
param.put("image", encodedImage);
return param;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(uploadimage.this);
requestQueue.add(request);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
if(requestCode==1 && requestCode==RESULT_OK && data!= null){
Uri filePath = data.getData();
try {
InputStream inputStream = getContentResolver().openInputStream(filePath);
bitmap = BitmapFactory.decodeStream(inputStream);
imageView.setImageBitmap(bitmap);
imageStore(bitmap);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
super.onActivityResult(requestCode, resultCode, data);
}
private void imageStore(Bitmap bitmap) {
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream);
byte [] imageBytes = stream.toByteArray();
encodedImage = android.util.Base64.encodeToString(imageBytes,Base64.DEFAULT);
}
}
php file: (on server in the folder of public_html i create a folder htdocs and in this folder i have all my php files of the project)
<?php
$conn = mysqli_connect("78.140.191.36","kerronxy_yacov", "]k2oIl?WBRPh", "kerronxy_users");
if(isset($_POST['image'])) {
$target_dir = "htdocs/";
$image = $_POST['image'];
$imageStore = rand()."_".time()."jpeg";
$target_dir = $target_dir."/".$imageStore;
file_put_contents($target_dir, base64_decode($image));
$select = "INSERT INTO images (image) VALUES ($imageStore)";
$responce = mysqli_query($conn, $select);
if($responce) {
echo "Image Uploaded";
mysqli_close($conn);
}
}
The Logcat error indicates Nullpointer exception means that some of the variable are null at runtime.
You might have put some null value or key in your post parameters.Please make sure your postParams in your case
encodedImage is notnull before calling the request,because the keys or values that is returned from these methods should not be null.
Hope this helps..

how can I send an image using an http request

I am working on an application that would send an image with 2 strings but I am not as experienced in this field so i was lost for the last day or two trying to figure this out as i started with a script but didn't work for me
here is the part of script that i worked on which has a bit PHP behind and just show an image in my activity once it's chosen form the gallery with a bit of logic that i understood but didn't really work for me
that's my java code :
package com.example.tuteur;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.AsyncTask;
import android.provider.MediaStore;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Base64;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import java.io.ByteArrayOutputStream;
import java.util.ArrayList;
public class ajouter_photo extends AppCompatActivity implements View.OnClickListener {
ImageView upload_img;
EditText img_text;
EditText img_titre;
Button img_but;
private static final int result_load_img = 1;
private static final String server = "http://192.168.1.3/pfe/saveImg.php";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_ajouter_photo);
upload_img=findViewById(R.id.photo_upload);
img_but=findViewById(R.id.upload_button);
img_text=findViewById(R.id.upload_text_corps);
img_titre=findViewById(R.id.upload_text_title);
upload_img.setOnClickListener(this);
img_but.setOnClickListener(this);
}
#Override
public void onClick(View v) {
switch (v.getId())
{
case(R.id.photo_upload):
Intent galleryIntent = new Intent(Intent.ACTION_PICK,MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(galleryIntent,result_load_img);
break;
case(R.id.upload_button):
Bitmap image =((BitmapDrawable) upload_img.getDrawable()).getBitmap();
new uploadimg(img_text.getText().toString(),image,img_titre.getText().toString());
break;
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if( requestCode==result_load_img && resultCode==RESULT_OK && data != null){
Uri selectedimg = data.getData();
upload_img.setImageURI(selectedimg);
}
}
private class uploadimg extends AsyncTask<Void , Void , Void> {
String text;
Bitmap image;
String titre;
public uploadimg(String text, Bitmap image,String titre) {
this.text = text;
this.image = image;
this.titre=titre;
}
#Override
protected Void doInBackground(Void ... params) {
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
image.compress(Bitmap.CompressFormat.JPEG, 100,byteArrayOutputStream);
String encodedImage = Base64.encodeToString(byteArrayOutputStream.toByteArray(),Base64.DEFAULT);
ArrayList<NameValuePair> dataToSend = new ArrayList<>();
dataToSend.add(new BasicNameValuePair("text",text));
dataToSend.add(new BasicNameValuePair("image",encodedImage));
dataToSend.add(new BasicNameValuePair("titre",titre));
HttpParams httpRequest = getHttpRequestParams();
HttpClient client = new DefaultHttpClient(httpRequest);
HttpPost post =new HttpPost(server);
try {
post.setEntity(new UrlEncodedFormEntity(dataToSend));
client.execute(post);
}
catch(Exception e)
{
Toast.makeText(getApplicationContext(),"erreur" , Toast.LENGTH_SHORT).show();
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
Toast.makeText(getApplicationContext(),"L'image est envoyé",Toast.LENGTH_SHORT).show();
}
}
private HttpParams getHttpRequestParams()
{
HttpParams httpRequestParams = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpRequestParams,1000*30);
HttpConnectionParams.setSoTimeout(httpRequestParams,1000*30);
return httpRequestParams;
}
}
and this is my PHP which just store my image in the server not a data base it was test before I would try with blob
<?php
$name = $_POST["text"];
$image=$_POST["image"];
$decodedImage = base64_decode("$image");
file_put_contents("pictures". $name . ".PNG" , $decodedImage);
?>

Run a piece of code only once in background whenever user login

Ia trying to get user locations whenever its login the application.I made a class and its working perfect seperately but when I embed it in my main project it didnt submit the location values in database.I want that whenever user login that class run for only once and submits its coordinates in database.
Here Is the code of my location class :
I want that when user login this class class run for once only all I want is to get user location when its loged in.
import android.Manifest;
import android.content.Context;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationManager;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import java.util.HashMap;
import java.util.Map;
public class getposition extends AppCompatActivity {
String URL_LOGIN = "api"
Button btn;
TextView tv1,tv2;
LocationManager locationManager;
static final int REQUEST_LOCATION = 1;
String lg, lt , chk;
String lat_long;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_getposition);
btn = findViewById(R.id.send);
tv1 = findViewById(R.id.lang);
tv2 = findViewById(R.id.lat);
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
chk = getLocation();
loadlocation();
if(chk != "false"){
String foo = chk;
String[] split = foo.split("_");
lt = split[0];
lg = split[1];
Toast.makeText(getApplicationContext(),chk,Toast.LENGTH_LONG).show();
}
}
private void loadlocation() {
final RequestQueue requestQueue = Volley.newRequestQueue(getposition.this);
StringRequest stringRequest = new StringRequest(Request.Method.POST, URL_LOGIN, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
tv1.setText(response);
tv2.setText(response);
requestQueue.stop();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
tv1.setText("Something went wrong///");
error.printStackTrace();
requestQueue.stop();
}
})
{
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
params.put("user_id","12" );
params.put("user_lat", lt);
params.put("user_lng", lg);
return params;
}
};
VolleySingleton.getInstance(getposition.this).addToRequestQueue(stringRequest);
}
public String getLocation() {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION)
!= PackageManager.PERMISSION_GRANTED)
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, REQUEST_LOCATION);
else {
Location location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (location != null) {
double latt = location.getLatitude();
double lng = location.getLongitude();
lat_long = latt + "_" + lng;
tv1.setText("Latitude: " + latt);
tv2.setText("Longitude: " + lng);
} else {
lat_long = "false";
tv1.setText("Unable to find correct location.");
tv2.setText("Unable to find correct location. ");
}
}
return lat_long;
}
}
This is my login class:
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.Toast;
import com.vshine.neuron.riseshine.VolleySingleton;
import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.vshine.neuron.riseshine.MainActivity;
import com.vshine.neuron.riseshine.R;
import com.vshine.neuron.riseshine.getregistered;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.HashMap;
import java.util.Map;
public class login extends AppCompatActivity {
Button login_button;
ImageButton GetRegistered;
EditText userName_edt, password_edt;
String user_name, password;
Context mctx;
String json_response;
String URL_LOGIN = "api"
public static final String PREFS_NAME = "MyPreferenceFiles";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
mctx = this;
initBasic();
initLogin();
}
private void initBasic() {
login_button = (Button) findViewById(R.id.login_button);
GetRegistered = (ImageButton) findViewById(R.id.register);
userName_edt = (EditText) findViewById(R.id.user_name);
password_edt = (EditText) findViewById(R.id.password);
}
private void initLogin() {
GetRegistered.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent= new Intent(login.this,getregistered.class);
startActivity(intent);
}
});
login_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
user_name = userName_edt.getText().toString();
password = password_edt.getText().toString();
if (user_name.trim().equals("") || password.trim().equals("")) {
ShowToastMessage("Please enter the credentials properly");
}
else {
StringRequest stringRequest = new StringRequest(Request.Method.POST, URL_LOGIN,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
//converting response to json object
JSONObject obj = new JSONObject(response);
//if no error in response
// json_response = j_obj.getString("message");
if (response!= null) {
// Toast.makeText(getApplicationContext(), obj.getString("message"), Toast.LENGTH_SHORT).show();
json_response = obj.getString("message");
// ShowToastMessage(json_response);
//getting the user from the response
JSONObject userJson = obj.getJSONObject("response");
//creating a new user object
String u_id = String.valueOf(userJson.getInt("id"));
// ShowToastMessage(u_id);
//storing the user in shared preferences
SharedPreferences.Editor editor = getSharedPreferences(PREFS_NAME, MODE_PRIVATE).edit();
editor.putString("User_id", u_id);
editor.commit();
finish();
startActivity(new Intent(getApplicationContext(), MainActivity.class));
} else {
Toast.makeText(getApplicationContext(), obj.getString("message"), Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_SHORT).show();
}
})
{
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
params.put("user_name", user_name);
params.put("password", password);
return params;
}
};
VolleySingleton.getInstance(login.this).addToRequestQueue(stringRequest);
}
}
});
}
private void ShowToastMessage(String message) {
Toast.makeText(this, message, Toast.LENGTH_LONG).show();
}
}

Getting Error in onResponse in Retrofit

I am a newbie to the android world. I am trying to develop an app for my school project and stumble upon this issue. please someone help me.
My fragment code is bellow. Where I want to fill up a form with Image and upload to PHP, Mysql server for registration. But the app is crashing.
package com.dgdev.mtmicds;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.provider.MediaStore.Images.Media;
import android.support.v4.app.Fragment;
import android.support.v7.widget.AppCompatButton;
import android.support.v7.widget.AppCompatEditText;
import android.support.v7.widget.AppCompatImageView;
import android.util.Base64;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;
import com.dgdev.mtmicds.DbAccess.Remote.APIClient;
import com.dgdev.mtmicds.DbAccess.Remote.ApiInterface;
import com.dgdev.mtmicds.DbAccess.Remote.UserRegistrationModel;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import static android.app.Activity.RESULT_OK;
import static android.provider.MediaStore.Images.Media.*;
import static android.support.v4.content.PermissionChecker.checkSelfPermission;
/**
* A simple {#link Fragment} subclass.
*/
public class ProfileFragment extends Fragment {
View view;
AppCompatImageView imageView;
AppCompatEditText etFullname, etEmail, etDob, etMobile, etPsw, etRePsw, etAddr;
AppCompatButton btnRegister, btnCancel;
private static final int IMAGE_REQUEST = 7777;
Bitmap bitmap;
public ProfileFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
view = inflater.inflate(R.layout.fragment_profile, container, false);
imageView = (AppCompatImageView) view.findViewById(R.id.ProfileDP);
etFullname = (AppCompatEditText) view.findViewById(R.id.tvfullanme);
etEmail = (AppCompatEditText) view.findViewById(R.id.tvemail);
etDob = (AppCompatEditText) view.findViewById(R.id.tvdob);
etPsw = (AppCompatEditText) view.findViewById(R.id.tvpsw);
etRePsw = (AppCompatEditText) view.findViewById(R.id.tvpsw_re);
etAddr = (AppCompatEditText) view.findViewById(R.id.tvaddr);
etMobile = (AppCompatEditText) view.findViewById(R.id.tvmobile);
btnRegister = (AppCompatButton) view.findViewById(R.id.btnRegister);
btnCancel = (AppCompatButton) view.findViewById(R.id.btnCancel);
/*-----------------------------------------------------------------------------*/
/* this onClickListener will be responsible for getting image URI from gallery */
/*-----------------------------------------------------------------------------*/
imageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
selectImageFromGallery();
}
});
btnRegister.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
uploadData();
}
});
return view;
}
private void uploadData() {
String fullname = etFullname.getText().toString();
String dob = convertTOMysqlDate(etDob.getText().toString());
String mobile = etMobile.getText().toString();
String addr = etAddr.getText().toString();
String psw = etPsw.getText().toString();
String prof_pic = imageToString();
Toast.makeText(view.getContext(), dob, Toast.LENGTH_LONG).show();
ApiInterface apiInterface = APIClient.GetClient().create(ApiInterface.class);
Call<UserRegistrationModel> call = apiInterface.RegisterUser(fullname, dob, mobile, addr, psw, prof_pic);
call.enqueue(new Callback<UserRegistrationModel>() {
#Override
public void onResponse(Call<UserRegistrationModel> call, Response<UserRegistrationModel> response) {
UserRegistrationModel res = response.body();
Toast.makeText(view.getContext(), res.getStatus(), Toast.LENGTH_LONG).show();
}
#Override
public void onFailure(Call<UserRegistrationModel> call, Throwable t) {
Toast.makeText(view.getContext(), "You are not able to talk to server!", Toast.LENGTH_LONG).show();
}
});
}
private String convertTOMysqlDate(String s) {
String $MysqlDateString;
String[] DateParts = s.split("/");
$MysqlDateString = DateParts[2] + "-" + DateParts[1] + "-" + DateParts[0];
return $MysqlDateString;
}
private void selectImageFromGallery() {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(intent, IMAGE_REQUEST);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == IMAGE_REQUEST && resultCode == RESULT_OK && data != null) {
Uri path = data.getData();
try {
bitmap = getBitmap(getActivity().getApplicationContext().getContentResolver(), path);
imageView.setImageBitmap(bitmap);
} catch (IOException e) {
e.printStackTrace();
}
}
}
private String imageToString() {
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 40, outputStream);
byte[] ImageBytes = outputStream.toByteArray();
return Base64.encodeToString(ImageBytes, Base64.DEFAULT);
}
}
And I am getting bellow message in logcat
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String com.dgdev.mtmicds.DbAccess.Remote.UserRegistrationModel.getStatus()' on a null object reference
at com.dgdev.mtmicds.ProfileFragment$3.onResponse(ProfileFragment.java:105)
Please Help me...I am a newbie...
Try this
#Override
public void onResponse(Call<UserRegistrationModel> call, Response<UserRegistrationModel> response) {
if(response.isSuccessful()) {
UserRegistrationModel res = response.body();
if(res!=null) {
Toast.makeText(view.getContext(), res.getStatus(), Toast.LENGTH_LONG).show();
} else {
Toast.makeText(view.getContext(), "Didn't get response", Toast.LENGTH_LONG).show();
}
}
}
Your com.dgdev.mtmicds.DbAccess.Remote.UserRegistrationModel is null. Check whether it is being alloted any value by getting in debug mode. Run the code step by step in debug mode and check how it is getting initialized.
Hint: Check this line of your code in debugger:
UserRegistrationModel res = response.body();

Error : method gettext() must be call from UI thread is worker

While working on a project I'm getting this error
Error : method gettext() must be call from UI thread is worker
on the following line :
String url = Util.send_chat_url+"?email_id="+editText_mail_id.getText().toString()+"&message="+editText_chat_message.getText().toString();
Please Help
This is my entire code for the class ChatActivity.java
package com.example.ankit.myapplication;
import android.app.Activity;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.support.annotation.NonNull;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;
import com.example.ankit.myapplication.XmppService;
import com.squareup.okhttp.OkHttpClient;
import org.jivesoftware.smack.packet.Message;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
import java.util.Scanner;
//import services.XmppService;
public class ChatActivity extends Activity {
EditText editText_mail_id;
EditText editText_chat_message;
ListView listView_chat_messages;
Button button_send_chat;
List<ChatObject> chat_list;
BroadcastReceiver recieve_chat;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_chat);
Scanner in = new Scanner(System.in);
XmppService xm= new XmppService();
Log.d("pavan","in chat "+getIntent().getStringExtra("user_id"));
Log.d("pavan","in chat server "+Util.SERVER);
XmppService.setupAndConnect(ChatActivity.this, Util.SERVER, "",
getIntent().getStringExtra("user_id"), Util.XMPP_PASSWORD);
editText_mail_id= (EditText) findViewById(R.id.editText_mail_id);
editText_chat_message= (EditText) findViewById(R.id.editText_chat_message);
listView_chat_messages= (ListView) findViewById(R.id.listView_chat_messages);
button_send_chat= (Button) findViewById(R.id.button_send_chat);
button_send_chat.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// send chat message to server
String message=editText_chat_message.getText().toString();
showChat("sent",message);
// new SendMessage().execute();
XmppService.sendMessage(ChatActivity.this, editText_mail_id.getText().toString() + Util.SUFFIX_CHAT, Message.Type.chat, message);
editText_chat_message.setText("");
}
});
recieve_chat=new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String message=intent.getStringExtra("message");
Log.d("pavan","in local braod "+message);
showChat("recieve",message);
}
};
LocalBroadcastManager.getInstance(this).registerReceiver(recieve_chat, new IntentFilter("message_recieved"));
}
private void showChat(String type, String message){
if(chat_list==null || chat_list.size()==0){
chat_list= new ArrayList<ChatObject>();
}
chat_list.add(new ChatObject(message,type));
ChatAdabter chatAdabter=new ChatAdabter(ChatActivity.this,R.layout.chat_view,chat_list);
listView_chat_messages.setAdapter(chatAdabter);
//chatAdabter.notifyDataSetChanged();
}
#Override
protected void onDestroy() {
super.onDestroy();
}
private class SendMessage extends AsyncTask<String, Void, String> {
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
}
#Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
String url = Util.send_chat_url+"?email_id="+editText_mail_id.getText().toString()+"&message="+editText_chat_message.getText().toString();
Log.i("pavan", "url" + url);
OkHttpClient client_for_getMyFriends = new OkHttpClient();
String response = null;
// String response=Utility.callhttpRequest(url);
try {
url = url.replace(" ", "%20");
response = callOkHttpRequest(new URL(url),
client_for_getMyFriends);
for (String subString : response.split("<script", 2)) {
response = subString;
break;
}
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return response;
}
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
//Toast.makeText(context,"response "+result,Toast.LENGTH_LONG).show();
}
}
// Http request using OkHttpClient
String callOkHttpRequest(URL url, OkHttpClient tempClient)
throws IOException {
HttpURLConnection connection = tempClient.open(url);
connection.setConnectTimeout(40000);
InputStream in = null;
try {
// Read the response.
in = connection.getInputStream();
byte[] response = readFully(in);
return new String(response, "UTF-8");
} finally {
if (in != null)
in.close();
}
}
byte[] readFully(InputStream in) throws IOException {
ByteArrayOutputStream out = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
for (int count; (count = in.read(buffer)) != -1;) {
out.write(buffer, 0, count);
}
return out.toByteArray();
}
}
Do not access the Android UI toolkit from outside the UI thread
Pass editText_mail_id.getText() and editText_chat_message.getText() as parameters to your async task or set it in onPreExecute to some variable
Like :
private class SendMessage extends AsyncTask<String, Void, String> {
private String mailId;
private String msgText;
#Override
protected void onPreExecute() {
super.onPreExecute();
mailId = editText_mail_id.getText().toString();
msgText = editText_chat_message.getText().toString();
}
Change url in doInBackground as :
String url = Util.send_chat_url+"?email_id="+mailId+"&message="+msgText;
you can create class for storing your parameter like i do,
Just create one class
example :
public class MyTaskParams
{
String mailId;
String message;
public MyTaskParams(String mailId, String message)
{
this.mailId = mailId;
this.message = message;
}
}
public class SendMessage extends AsyncTask<MyTaskParams, Void, String {
#Override
protected String doInBackground(MyTaskParams... params) {
String mailId = params[0].mailId;
String message = params[0].message;
String url = Util.send_chat_url+"?email_id="+ mailId +"&message="+ message;
}
}
so you can just call like this
MyTaskParams params = new MyTaskParams(editText_mail_id.getText().toString(),editText_chat_message.getText().toString());
SendMessage myTask = new SendMessage();
myTask.execute(params);
with this code you can call SendMessage Class from any activity, dont bind your asynctask with get text because if you do that you just can use SendMessage only in that activity
Hope this can help you.

Categories

Resources