0

I want to upload a video (chosen from gallery) to a server (localhost-Wampserver is running Apache 2.4.4 on my computer). From the exception and searching about it, I found out that the network operation should not take place in the thread on which the UI is running. but how should I do this? My code is given below:

PostFile:

public final class PostFile 
{
  public static final MediaType MEDIA_TYPE_MARKDOWN
      = MediaType.parse("vide/mp4");

  private final OkHttpClient client = new OkHttpClient();

  public void run(String path) throws Exception 
  {
    File file = new File(path);

    Request request = new Request.Builder()
        .url("http://192.168.1.7")
        .post(RequestBody.create(MEDIA_TYPE_MARKDOWN, file))
        .build();

    Response response = client.newCall(request).execute();
    if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);

        System.out.println(response.body().string());
  }

}

MainActivity.java:

public class MainActivity extends Activity 
{
    private static int RESULT_LOAD_IMG = 1;
    String decodableString;

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

    public void loadImagefromGallery(View view) 
    {
        // Create intent to Open Image applications like Gallery, Google Photos
        Intent galleryIntent = new Intent(Intent.ACTION_PICK,
                android.provider.MediaStore.Video.Media.EXTERNAL_CONTENT_URI);
        // Start the Intent
        startActivityForResult(galleryIntent, RESULT_LOAD_IMG);
    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) 
    {
        super.onActivityResult(requestCode, resultCode, data);
        try {
            // When a video is picked
            if (requestCode == RESULT_LOAD_IMG && resultCode == RESULT_OK
                    && null != data) 
            {
                // Get the video from data
                Uri selectedVideo = data.getData();
                String[] filePathColumn = { MediaStore.Video.Media.DATA };
                Cursor cursor = getContentResolver().query(selectedVideo,
                        filePathColumn, null, null, null);
                cursor.moveToFirst();
                int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
                decodableString = cursor.getString(columnIndex);
                Log.i("mok",decodableString);
                cursor.close();
                new PostFile().run(decodableString);
                Log.i("mok","done");
            } else 
            {
                Toast.makeText(this, "You haven't picked any video",
                        Toast.LENGTH_LONG).show();
            }
        } catch (Exception e) 
        {
            e.printStackTrace();
            Toast.makeText(this, "Something went wrong", Toast.LENGTH_LONG)
                        .show();
            }
        }
}

Stack trace: enter image description here

Mohsen Kamrani
  • 7,177
  • 5
  • 42
  • 66

3 Answers3

3

AsyncTask provides doInBackground method.

http://developer.android.com/reference/android/os/AsyncTask.html

Damian Kozlak
  • 7,065
  • 10
  • 45
  • 51
2

All you need to do it is knowledge about using Retrofit. Here is explanation how file uploading work with Retrofit and how to do it.

https://futurestud.io/blog/retrofit-how-to-upload-files/

Executing query in background should be done with callbacks mechanism. Query goes in background and callback is executed on mainthread.

How to implement an async Callback using Square's Retrofit networking library

using-squares-retrofit-networking-library Here you can find good example of defining retrofit rest methods with callbacks.

It is everything that you need. Do not even try to change threading policy, it is strongly not recommended.

Sebastian Pakieła
  • 2,970
  • 1
  • 16
  • 24
  • Upvoted. I forgot that @mok is using Retrofit, so it's much better solution using methods from Retrofit instead of `AsyncTask`. – Damian Kozlak Nov 12 '15 at 16:57
  • @DamianKozlak exactly. I got confused really because I thought using Retrofit I don't need to use AsyncTask. – Mohsen Kamrani Nov 12 '15 at 17:08
  • Thank you for references and especially the last paragraph. But, both of them seems too advanced. I mean I have no prior knowledge about using these APIs. Would you please mention a working example (no matter how simple it is, just it works, then I'll understand the other things). – Mohsen Kamrani Nov 12 '15 at 17:17
  • https://stackoverflow.com/questions/26500036/using-retrofit-in-android Here you can find a nice example of adapter, interface and using them. The most voted answer – Sebastian Pakieła Nov 12 '15 at 18:15
1

You'll need to execute it with an AsyncTask

jonk
  • 1,494
  • 11
  • 13