1

I am trying to upload images taken from phone camera to the server. Since I am new to uploading images in android I do not know much about this. I followed one tutorial on internet after googling which does work as a separat app but when I use that same class in my app it does not work anymore. I get errors in my logcat(which I will post at the end of this post). I do not know what does this error mean and how can I solve this. Please help me how can I make this work?

Here is my code for Camera activity

public class Camera extends Activity { ImageView ivUserImage; Button bUpload; Intent i; int CameraResult = 0; Bitmap bmp; FileUpload fu; @Override protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); setContentView(R.layout.camera); ivUserImage = (ImageView)findViewById(R.id.ivUserImage); bUpload = (Button)findViewById(R.id.bUpload); openCamera(); } private void openCamera() { i = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE); startActivityForResult(i, CameraResult); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if(resultCode == RESULT_OK) { Bundle extras = data.getExtras(); //Log.e("Image: ", data.toString()); bmp = (Bitmap) extras.get("data"); ivUserImage.setImageBitmap(bmp); bUpload.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { // TODO Auto-generated method stub //Toast.makeText(getApplicationContext(), bmp.toString(), Toast.LENGTH_SHORT).show(); fu = new FileUpload(bmp.toString()); } }); } } } 

Here is my FileUpload class

public class FileUpload extends Activity { TextView tv; Button b; int serverResponseCode = 0; ProgressDialog dialog = null; public FileUpload(final String bmp) { dialog = ProgressDialog.show(FileUpload.this, "", "Uploading file...", true); new Thread(new Runnable() { public void run() { runOnUiThread(new Runnable() { public void run() { tv.setText("uploading started....."); } }); int response= uploadFile(bmp); //Log.e("Response: ", response); System.out.println("RES : " + response); } }).start(); } public int uploadFile(String sourceFileUri) { String upLoadServerUri = "http://www.example.info/androidfileupload/index.php"; String fileName = sourceFileUri; HttpURLConnection conn = null; DataOutputStream dos = null; String lineEnd = "\r\n"; String twoHyphens = "--"; String boundary = "*****"; int bytesRead, bytesAvailable, bufferSize; byte[] buffer; int maxBufferSize = 1 * 1024 * 1024; File sourceFile = new File(sourceFileUri); if (!sourceFile.isFile()) { Log.e("uploadFile", "Source File Does not exist"); return 0; } try { // open a URL connection to the Servlet FileInputStream fileInputStream = new FileInputStream(sourceFile); URL url = new URL(upLoadServerUri); conn = (HttpURLConnection) url.openConnection(); // Open a HTTP connection to the URL conn.setDoInput(true); // Allow Inputs conn.setDoOutput(true); // Allow Outputs conn.setUseCaches(false); // Don't use a Cached Copy conn.setRequestMethod("POST"); conn.setRequestProperty("Connection", "Keep-Alive"); conn.setRequestProperty("ENCTYPE", "multipart/form-data"); conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary); conn.setRequestProperty("uploaded_file", fileName); dos = new DataOutputStream(conn.getOutputStream()); dos.writeBytes(twoHyphens + boundary + lineEnd); dos.writeBytes("Content-Disposition: form-data; name=\"uploaded_file\";filename=\""+ fileName + "\"" + lineEnd); dos.writeBytes(lineEnd); bytesAvailable = fileInputStream.available(); // create a buffer of maximum size bufferSize = Math.min(bytesAvailable, maxBufferSize); buffer = new byte[bufferSize]; // read file and write it into form... bytesRead = fileInputStream.read(buffer, 0, bufferSize); while (bytesRead > 0) { dos.write(buffer, 0, bufferSize); bytesAvailable = fileInputStream.available(); bufferSize = Math.min(bytesAvailable, maxBufferSize); bytesRead = fileInputStream.read(buffer, 0, bufferSize); } // send multipart form data necesssary after file data... dos.writeBytes(lineEnd); dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd); // Responses from the server (code and message) serverResponseCode = conn.getResponseCode(); String serverResponseMessage = conn.getResponseMessage(); Log.i("uploadFile", "HTTP Response is : " + serverResponseMessage + ": " + serverResponseCode); if(serverResponseCode == 200){ runOnUiThread(new Runnable() { public void run() { tv.setText("File Upload Completed."); Toast.makeText(FileUpload.this, "File Upload Complete.", Toast.LENGTH_SHORT).show(); } }); } //close the streams // fileInputStream.close(); dos.flush(); dos.close(); } catch (MalformedURLException ex) { dialog.dismiss(); ex.printStackTrace(); Toast.makeText(FileUpload.this, "MalformedURLException", Toast.LENGTH_SHORT).show(); Log.e("Upload file to server", "error: " + ex.getMessage(), ex); } catch (Exception e) { dialog.dismiss(); e.printStackTrace(); Toast.makeText(FileUpload.this, "Exception : " + e.getMessage(), Toast.LENGTH_SHORT).show(); Log.e("Upload file to server Exception", "Exception : " + e.getMessage(), e); } dialog.dismiss(); return serverResponseCode; 

} }

and here is what I get in my logcat

06-10 14:26:55.320: W/IInputConnectionWrapper(23770): showStatusIcon on inactive InputConnection 06-10 14:27:03.765: D/AndroidRuntime(23770): Shutting down VM 06-10 14:27:03.765: W/dalvikvm(23770): threadid=1: thread exiting with uncaught exception (group=0x4001e578) 06-10 14:27:03.775: E/AndroidRuntime(23770): FATAL EXCEPTION: main 06-10 14:27:03.775: E/AndroidRuntime(23770): java.lang.IllegalStateException: System services not available to Activities before onCreate() 06-10 14:27:03.775: E/AndroidRuntime(23770): at android.app.Activity.getSystemService(Activity.java:3562) 06-10 14:27:03.775: E/AndroidRuntime(23770): at android.app.Dialog.<init>(Dialog.java:141) 06-10 14:27:03.775: E/AndroidRuntime(23770): at android.app.AlertDialog.<init>(AlertDialog.java:63) 06-10 14:27:03.775: E/AndroidRuntime(23770): at android.app.ProgressDialog.<init>(ProgressDialog.java:80) 06-10 14:27:03.775: E/AndroidRuntime(23770): at android.app.ProgressDialog.<init>(ProgressDialog.java:76) 06-10 14:27:03.775: E/AndroidRuntime(23770): at android.app.ProgressDialog.show(ProgressDialog.java:101) 06-10 14:27:03.775: E/AndroidRuntime(23770): at android.app.ProgressDialog.show(ProgressDialog.java:90) 06-10 14:27:03.775: E/AndroidRuntime(23770): at com.zafar.login.FileUpload.<init>(FileUpload.java:25) 06-10 14:27:03.775: E/AndroidRuntime(23770): at com.zafar.login.Camera$1.onClick(Camera.java:52) 06-10 14:27:03.775: E/AndroidRuntime(23770): at android.view.View.performClick(View.java:2538) 06-10 14:27:03.775: E/AndroidRuntime(23770): at android.view.View$PerformClick.run(View.java:9152) 06-10 14:27:03.775: E/AndroidRuntime(23770): at android.os.Handler.handleCallback(Handler.java:587) 06-10 14:27:03.775: E/AndroidRuntime(23770): at android.os.Handler.dispatchMessage(Handler.java:92) 06-10 14:27:03.775: E/AndroidRuntime(23770): at android.os.Looper.loop(Looper.java:130) 06-10 14:27:03.775: E/AndroidRuntime(23770): at android.app.ActivityThread.main(ActivityThread.java:3691) 06-10 14:27:03.775: E/AndroidRuntime(23770): at java.lang.reflect.Method.invokeNative(Native Method) 06-10 14:27:03.775: E/AndroidRuntime(23770): at java.lang.reflect.Method.invoke(Method.java:507) 06-10 14:27:03.775: E/AndroidRuntime(23770): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:907) 06-10 14:27:03.775: E/AndroidRuntime(23770): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:665) 06-10 14:27:03.775: E/AndroidRuntime(23770): at dalvik.system.NativeStart.main(Native Method) 
3
  • Have you set all the required permissions in your Android Mainifest? Commented Jun 10, 2012 at 11:52
  • I think it requires '<uses-permission android:name="android.permission.INTERNET"/> ' internet permission which I did Commented Jun 10, 2012 at 11:54
  • you pass Context from your main Activity to this Upload class. Commented Jun 10, 2012 at 11:59

2 Answers 2

1

You create Object FileUpload activity using new. In Android, an activity is suggested to be designed as a standalone module, and the activity is created by Android. If you want to communicate to other activities, you should use Intent to do this.

fu = new FileUpload(bmp.toString()); // here make error. 

In android it is not possible to create object of another activity.

Sign up to request clarification or add additional context in comments.

3 Comments

Yeah I do not want this class to be an activity. I wanted to make a complete new class i.e. class FileUpload { }. But when I changed it showed tons of errors. I mean there were so many line red underline.
public FileUpload(Context context, final String bmp) { dialog = ProgressDialog.show(context, "", "Uploading file...", true); new Thread(new Runnable() { public void run() { runOnUiThread(new Runnable() { public void run() { tv.setText("uploading started....."); } }); int response= uploadFile(bmp); //Log.e("Response: ", response); System.out.println("RES : " + response); } }).start(); } and fu = new FileUpload(this, bmp.toString());
I am not getting your comment. What does this mean? could you please elaborate this?
0

I recommend you to create a FTP server and use ftp for Uploading your files. the following code is a method for getting file from FTP server. customize it for uploading:

public static boolean getFile(String serverName, String userName, String password, String serverFilePath, String localFilePath) throws Exception { FTPClient ftp = new FTPClient(); try { // ftp.setCopyStreamListener(); ftp.connect(serverName); int reply = ftp.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { ftp.disconnect(); return false; } } catch (IOException e) { if (ftp.isConnected()) { try { ftp.disconnect(); } catch (IOException f) { throw e; } } throw e; } catch (Exception e) { throw e; } try { // String filePath = "system/mswin.98/SETUP0.WAV"; if (!ftp.login(userName, password)) { ftp.logout(); } // if (binaryTransfer) ftp.setFileType(FTPClient.BINARY_FILE_TYPE); // ftp.enterLocalPassiveMode(); ftp.enterLocalActiveMode(); OutputStream output; if (checkAndCreateDirectories(localFilePath)) { output = new FileOutputStream(localFilePath); ftp.retrieveFile(serverFilePath, output); output.close(); } ftp.noop(); // check that control connection is working OK ftp.logout(); return true; } catch (FTPConnectionClosedException e) { throw e; } catch (IOException e) { throw e; } catch (Exception e) { throw e; } finally { if (ftp.isConnected()) { try { ftp.disconnect(); } catch (IOException f) { throw f; } } } } 

2 Comments

Is ftp better than the one I am currently using?
But search to find if FTP is better or not

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.