0

I am trying to uplaoad an image on django restapi but i am getting same error again and again .This is my first question on stackoverflow,if some mistake happens plz forgive.

ERROR :

I/Adreno: PFP: 0x005ff113, ME: 0x005ff066
I/ConfigStore: android::hardware::configstore::V1_0::ISurfaceFlingerConfigs::hasWideColorDisplay retrieved: 0
    android::hardware::configstore::V1_0::ISurfaceFlingerConfigs::hasHDRDisplay retrieved: 0
I/OpenGLRenderer: Initialized EGL, version 1.4
D/OpenGLRenderer: Swap behavior 2

D/path to file: /storage/emulated/0/Pictures/20210318_1302565478385964844159819.jpg

I/Timeline: Timeline: Activity_launch_request time:81856604 intent:Intent { act=android.media.action.IMAGE_CAPTURE flg=0x3 clip={text/uri-list U:content://com.example.captureImage.fileprovider/myImages/20210318_1302565478385964844159819.jpg} (has extras) }

W/Activity: Slow Operation: Activity com.example.captureimage/.MainActivity onActivityResult took 367ms

W/Looper: Slow Looper main: doFrame is 379ms late because of 2 msg, msg 2 took 377ms (late=14ms h=android.app.ActivityThread$H w=159)

D/NetworkSecurityConfig: No Network Security Config specified, using platform default

W/le.captureimag: Accessing hidden method Ldalvik/system/CloseGuard;->get()Ldalvik/system/CloseGuard; (light greylist, reflection)

    Accessing hidden method Ldalvik/system/CloseGuard;->open(Ljava/lang/String;)V (light greylist, reflection)

    Accessing hidden method Ldalvik/system/CloseGuard;->warnIfOpen()V (light greylist, reflection)
I/le.captureimag: ProcessProfilingInfo new_methods=1973 is saved saved_to_disk=1 resolve_classes_delay=8000

D/failed !!!!!!: java.net.SocketTimeoutException: failed to connect to /10.0.2.2 (port 8000) from /192.168.43.2 (port 40471) after 10000ms

Build.gradle file:

   dependencies {
    
        implementation 'androidx.appcompat:appcompat:1.2.0'
        implementation 'com.google.android.material:material:1.3.0'
        implementation 'androidx.constraintlayout:constraintlayout:2.0.4'
        testImplementation 'junit:junit:4.+'
        androidTestImplementation 'androidx.test.ext:junit:1.1.2'
        androidTestImplementation 'androidx.test.espresso:espresso-core:3.3.0'
        implementation 'com.squareup.retrofit2:retrofit:2.5.0'
        implementation 'com.squareup.retrofit2:converter-gson:2.5.0'
        implementation 'com.google.code.gson:gson:2.6.2'
    
       
    }

fileUploadserviceprovider.java

public interface FileUploadService {
    @Multipart
    @POST("upload")

  
    Call<RequestBody> upload(
            @Part("description") RequestBody description,
            @Part MultipartBody.Part file);


}

NETWORKCLIENT.JAVA

public class NetworkClient {

private static Retrofit retrofit;
private static final String BASE_URL = "http://10.0.2.2:8000/";

public  static Retrofit getRetrofit()
{
    OkHttpClient okHttpClient = new OkHttpClient.Builder().build();

    if(retrofit == null)
        retrofit = new Retrofit.Builder().baseUrl(BASE_URL).addConverterFactory(GsonConverterFactory.create()).client(okHttpClient).build();

    return retrofit;
}

}

MAINACTIVITY.JAVA

public class MainActivity extends AppCompatActivity {

    String pathToFile;
    Button capture_Picture;
    Button saveImage;
    ImageView photo_Box;
    String filepath ="";
    private Object ServiceGenerator;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        if(Build.VERSION.SDK_INT >=23)
        {
            requestPermissions(new String[]{Manifest.permission.CAMERA,Manifest.permission.WRITE_EXTERNAL_STORAGE},2);
        }



        capture_Picture = findViewById(R.id.click_Picture);
        saveImage = findViewById(R.id.save_Picture);
        photo_Box = findViewById(R.id.image);

        saveImage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                uploadImage();

            }
        });



        capture_Picture.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dispatchPictureTakeAction();
            }
        });

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if(resultCode == RESULT_OK)
        {
            if(requestCode == 1)
            {
                Bitmap bitmap = BitmapFactory.decodeFile(pathToFile);
                photo_Box.setImageBitmap(bitmap);
            }
        }

    }

    private void dispatchPictureTakeAction()
    {
        Intent takePic = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        if(takePic.resolveActivity(getPackageManager() )!= null)
        {
            File photoFile = null;

            photoFile = createPhotoFile();


            if(photoFile != null)
            {
                pathToFile = photoFile.getAbsolutePath();
                Log.d("path to file",pathToFile);
                Uri photoURI = FileProvider.getUriForFile(MainActivity.this,"com.example.captureImage.fileprovider",photoFile);
                takePic.putExtra(MediaStore.EXTRA_OUTPUT,photoURI);
                startActivityForResult(takePic,1);
            }

        }


    }

    private File createPhotoFile()
    {
        String name = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
        File storageDir = getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
        File image = null;
        try {
            image = File.createTempFile(name,".jpg",storageDir);
        } catch (IOException e) {
            Log.d("mylog","Excep : " + e.toString());
        }

        return image;

    }

    private void uploadImage()
    {


        File file = new File(pathToFile);
        Retrofit retrofit = NetworkClient.getRetrofit();

        RequestBody requestBody = RequestBody.create(MediaType.parse("image/*"),file);
        MultipartBody.Part parts = MultipartBody.Part.createFormData("file",file.getName(),requestBody);

        RequestBody somedata = RequestBody.create(MediaType.parse("description"),"this is a new Image");


        FileUploadService uploadApis = retrofit.create(FileUploadService.class);

        Call call = uploadApis.upload(somedata,parts);

        call.enqueue(new Callback() {
            @Override
            public void onResponse(Call call, Response response) {



            }

            @Override
            public void onFailure(Call call, Throwable t) {

                Log.d("failed !!!!!!  ", ""+t);
            }
        });

    }



}

**Models class in django**

class myimage(models.Model):
    my_name=models.CharField(max_length=50)
    my_image= models.ImageField(upload_to='Images/',default='Images/None/No-img.jpg')

    def __str__(self):
        return self.my_name

thanks in advance,i have tried everything available on stackoverflow regarding this problem.

ARmk
  • 1
  • testing on emulator? unlikely problem with your code but configuration of your network. try to open that address http://10.0.2.2:8000/ inside your browser check if server responds – ProblemSlover Mar 18 '21 at 09:34
  • i have tried both device as well as emulator.I have used 10.0.2.2 for emualtior and my pc's IP address for device,my api end point is **127.0.0.1/myimage** and i have used **10.0.2.2:8000** also both are not working.I have changed **@POST(myimage)**,but still it is not working,while i checked with postman API is working.I AM USING DJANGO server on the same laptop on which my studio is working. Latest error which i am getting is ** D/failed !!!!!!: java.net.SocketTimeoutException: failed to connect to /192.168.43.187 (port 8000) from /192.168.43.2 (port 42202) after 10000ms ** – ARmk Mar 19 '21 at 06:29
  • you checked if api endpoint accessible in browser of your device and emulator right? – ProblemSlover Mar 19 '21 at 06:42
  • yes i can access api endpoint by using **127.0.0.1/myimage ** – ARmk Mar 19 '21 at 06:55
  • can you download sample project offered by retrofit and reproduce problem. for example this project https://github.com/SiGMobileUIUC/RetrofitTutorial pull it and open in android studio – ProblemSlover Mar 19 '21 at 07:30
  • https://github.com/Nsikaktopdown/AndelaChallengeProject This one also should work – ProblemSlover Mar 19 '21 at 07:31
  • Generally problem is that the permission INTERNET access in Android manifest is missing https://stackoverflow.com/questions/2378607/what-permission-do-i-need-to-access-internet-from-an-android-application – ProblemSlover Mar 19 '21 at 07:32
  • I have already added internet permission in manifest file. – ARmk Mar 19 '21 at 08:14

0 Answers0