Title: Android, Writing an app that takes a picture and then sends that picture in a post request
Tags: android
Question: I've gotten far enough that I can seemingly activate the camera and get the intent picture back, however the post request part seems to be a much larger issue. After constantly running into "NetworkOnMainThreadException"s and context errors, I sort of combined some things that I learned here into something...that still doesn't get rid of that exception. I'm sure that there are issues elsewhere too.
Edit: Here's the code.
public class MainActivity extends AppCompatActivity {
static final int REQUEST_IMAGE_CAPTURE =1;
//final IntentServiceActivity intentPost = new IntentServiceActivity();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final Button captureButton = findViewById(R.id.CaptureButton);
captureButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
dispatchTakePictureIntent();
}
});
private void dispatchTakePictureIntent() {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
protected  void  onActivityResult(int requestCode, int resultCode, Intent data){
if (requestCode == REQUEST_IMAGE_CAPTURE &amp;&amp; resultCode == RESULT_OK) {
Bundle extras = data.getExtras();
Bitmap imageBitmap = (Bitmap) extras.get("data");
IntentServiceActivity intentPost = new IntentServiceActivity();
intentPost.postRequest(imageBitmap);
public class IntentServiceActivity extends AppCompatActivity {
private TextView result;
@Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
result = (TextView) findViewById(R.id.resultText);
@Override
protected void onStop(){
super.onStop();
public void postRequest(Bitmap bmp){
HttpClient httpClient = new DefaultHttpClient();
HttpContext localContext = new BasicHttpContext();
HttpPost httpPost = new HttpPost("http://151.154.11.224:8000/trash/");
try {
File f = new File(myApp.getAppContext().getFilesDir(), "temp");
f.createNewFile();
//Convert bitmap to byte array
ByteArrayOutputStream bos = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.PNG, 0 /*ignored for PNG*/, bos);
byte[] bitmapdata = bos.toByteArray();
//write the bytes in file
FileOutputStream fos = new FileOutputStream(f);
fos.write(bitmapdata);
fos.flush();
fos.close();
MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
entity.addPart("image", new FileBody(f));
httpPost.setEntity(entity);
HttpResponse response = httpClient.execute(httpPost, localContext);
Log.d("response", EntityUtils.toString(response.getEntity()));
result.setText(EntityUtils.toString(response.getEntity()));
Log.d("Debug", "the end!");
} catch (IOException e) {
e.printStackTrace();
Finally:
public class myApp extends Application {
private static Context context;
public void onCreate() {
super.onCreate();
myApp.context = getApplicationContext();
public static Context getAppContext() {
return myApp.context;
I have added the uses-feature for camera and the uses-permission for internet as well as a name, if anyone was wondering.
Comment: Use AsyncTask to execute network in background thread. You can use Reftrofit kind of  library and it contain method to execute network in background

Here is the accepted answer: You may get NetworkOnMainThreadException when you try to execute a network a request on main UI thread. Such behavior makes application unresponsive. In order to handle such scenarios, you should always use a separate thread for network and heavy processing code logics. AsyncTask is one of the best ways to create a separate thread for heavy work.
Below is working code according to your request. Just change your IntentServiceActivity as follows
public class IntentServiceActivity extends AppCompatActivity {
private TextView result;
private Bitmap bitmap;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
result = (TextView) findViewById(R.id.resultText);
@Override
protected void onStop() {
super.onStop();
public void postRequest(Bitmap bmp) {
this.bitmap = bmp;
new UploadImageTask().execute();
private class UploadImageTask extends AsyncTask<String, Integer, String&gt; {
@Override
protected void onPreExecute() {
super.onPreExecute();
Toast.makeText(IntentServiceActivity.this, "Uploading Image", Toast.LENGTH_LONG).show();
}
@Override
protected String doInBackground(String... params) {
try {
HttpClient httpClient = new DefaultHttpClient();
HttpContext localContext = new BasicHttpContext();
HttpPost httpPost = new HttpPost("http://151.154.11.224:8000/trash/");
File f = new File(myApp.getAppContext().getFilesDir(), "temp");
f.createNewFile();
//Convert bitmap to byte array
ByteArrayOutputStream bos = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.PNG, 0 /*ignored for PNG*/, bos);
byte[] bitmapdata = bos.toByteArray();
//write the bytes in file
FileOutputStream fos = new FileOutputStream(f);
fos.write(bitmapdata);
fos.flush();
fos.close();
MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
entity.addPart("image", new FileBody(f));
httpPost.setEntity(entity);
HttpResponse response = httpClient.execute(httpPost, localContext);
String responseTxt = EntityUtils.toString(response.getEntity());
return responseTxt;
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(String resultTxt) {
super.onPostExecute(resultTxt);
Toast.makeText(IntentServiceActivity.this, "Image Uploaded", Toast.LENGTH_LONG).show();
Log.d("response", resultTxt);
if(result !== null) result.setText(resultTxt);
Log.d("Debug", "the end!");
}
Comment for this answer: Thank you! While other answers were proven to be correct in general, I chose this one because it was the neatest to me; thanks to the use of the subclass.

Here is another answer: As the exception suggests, you are not allowed to trigger network calls on the main thread in Android. What you need to use is an AsyncTask.
AsyncTask enables proper and easy use of the UI thread. This class
allows you to perform background operations and publish results on the
UI thread without having to manipulate threads and/or handlers
I really suggest you work through a few Android tutorials before starting developing Android apps because not every standard Java pattern is applicable in Android. I recommend this course because it is free and it teaches you the standard Android design patterns. It is also thaught by Google employees so I can assure you they know what they are talking about.

Here is another answer: NetworkOnMainThreadException this exception is thrown when your  application perform a networking operation(service call) on its main thread.
Use **AsyncTask ** for avoid this exception.
class UploadImageTask extends AsyncTask<String, Void, Void&gt; {
@Override
protected void onPreExecute() {
super.onPreExecute();
//here you can show progress dialog
protected void doInBackground(String... data) {
try {
postRequest(bitmap);
} catch (Exception e) {
protected void onPostExecute(void res) {
Then Change in IntentServiceActivity  class
@Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
result = (TextView) findViewById(R.id.resultText);
UploadImageTask task= new UploadImageTask ();
task.execute();
Hope this will help you.

{'source': 'StackExchangeDataset', 'subset': 'stackoverflow.com', 'metadata': {'AnswerCount': 3, 'CommentCount': 1, 'ContentLicense': 'CC BY-SA 3.0', 'CreationDate': '2018:00:05/01/18', 'FavoriteCount': None, 'PostTypeId': 1, 'Tags': '<android>', 'Title': 'Android, Writing an app that takes a picture and then sends that picture in a post request', 'ViewCount': 37, 'id': 50115558, 'user_AboutMe': None, 'user_AccountId': 13479381.0, 'user_DisplayName': 'Theodore Kallaus', 'user_Reputation': 13.0, 'user_Views': 2.0, 'user_id': 9725180.0}}