I am uploading audio on soundcloud server but when i click upload button it throws FileNotFoundException.After uploading a response from server has to be generated.plss help me guys. please correct me if i am making mistake somewhere.
There are 2 situation in which upload function is performed.
1.Recording of only one page story audio and uloding it.(in this case the audio is being uploade).
2. Recording of more than one page story in which after uploading of 1st page audio the 2nd page will come as response from my server.(In this case its throwing FileNotFound Exception).
upload.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String tag_string_req = "req_login";
StringRequest postStringRequest = new StringRequest(Request.Method.POST, SC_LOGIN_LINK,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d(TAG,"Reponse Check for sound upload login :"+response);
// Log.d(TAG,"Object Check :"+json);
try {
JSONObject json = new JSONObject(response);
access_token = json.getString("access_token");
expires_in = json.getString("expires_in");
refresh_token = json.getString("refresh_token");
// doFileUpload();
new AsyncTaskRunner().execute();
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
//Toast.makeText(AccessToken.this, error.toString(), Toast.LENGTH_LONG).show();
Log.e(TAG, "Error Response Check :" + error);
}
}){
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("client_id", client_id);
params.put("client_secret",client_secret);
params.put("grant_type",grant_type);
params.put("username",username);
params.put("password",user_password);
Log.d(TAG, "Params :" + params);
return params;
}
}; AppController.getInstance().addToRequestQueue(postStringRequest, tag_string_req);
}
});
}
private void mergeAudioFiles(){
try {
File tempFolder = new File(mRawAudioFolder.getPath());
Movie[] movies = new Movie[tempFolder.listFiles().length];
int i = 0;
for (File saveTempFile : tempFolder.listFiles()) {
try {
movies[i] = MovieCreator.build(new FileDataSourceImpl(saveTempFile));
} catch (IOException e) {
e.printStackTrace();
}
i++;
}
final Movie finalMovie = new Movie();
List<Track> audioTracks = new ArrayList<>();
for (Movie movie : movies) {
for (Track track : movie.getTracks()) {
}
}
finalMovie.addTrack(new AppendTrack(audioTracks.toArray(new Track[audioTracks.size()])));
final Container container = new DefaultMp4Builder().build(finalMovie);
mergedFile = new File(mAudioFolder.getPath()+"/merged.3gp");
final FileOutputStream fos = new FileOutputStream(mergedFile);
FileChannel fc = new RandomAccessFile(mergedFile, "rw").getChannel();
container.writeContainer(fc);
fc.close();
} catch (Exception e) {
e.printStackTrace();
}
}
public static void createAudioFolder() {
File movieFile = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MOVIES);
mRawAudioFolder = new File(movieFile, "Temp");
mAudioFolder = new File(movieFile, "The Tagore Project");
if (!mAudioFolder.exists()) {
mAudioFolder.mkdirs();
}
if (!mRawAudioFolder.exists()) {
mRawAudioFolder.mkdirs();
}
}
public byte[] toByteArray(InputStream in) throws IOException {
ByteArrayOutputStream out = new ByteArrayOutputStream();
int read = 0;
byte[] buffer = new byte[1024];
while (read != -1) {
read = in.read(buffer);
if (read != -1)
out.write(buffer,0,read);
}
out.close();
return out.toByteArray();
}
public void forwardtoOurServer() {
String tag_string_req = "req_login";
StringRequest postStringRequest = new StringRequest(Request.Method.POST, RECORD_COMPOSITION_API,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d(TAG, "Audio Upload Response Check :" + response);
Log.d(TAG,"Object Check :"+response);
try {
JSONObject json = new JSONObject(response);
String code = json.getString("code");
if (String.valueOf(code).equals("200")) {
JSONObject upload = json.getJSONObject("upload");
JSONObject Booking = json.getJSONObject("upload").getJSONObject("Booking");
JSONObject Composition = json.getJSONObject("upload").getJSONObject("Composition");
JSONObject TableofContents = json.getJSONObject("upload").getJSONObject("TableOfContent");
String content = Composition.getString("content");
String pageno = Composition.getString("pageno");
String tocid = Composition.getString("table_of_content_id");
String wrd_count = Composition.getString("wordcount");
String tocName = TableofContents.getString("name");
} else {
String errorMsg = json.getString("error_msg");
Toast.makeText(getApplicationContext(),
errorMsg, Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, "Error Response Check :" + error);
}
}) {
#RequiresApi(api = Build.VERSION_CODES.N)
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("data[Booking][id]",bookingId);
params.put("data[Booking][contributor_id]",contributor_id);
params.put("data[Booking][table_of_content_id]",tocId);
params.put("data[Booking][cdn_id]",vs_cdn_id);
params.put("data[Booking][secret_token]",secret_token);
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
sdf.setTimeZone(TimeZone.getTimeZone("GMT"));
Date now = new Date();
String strDate = sdf.format(now);
params.put("data[Booking][uploaded_on]",strDate);
Log.d(TAG, "Params :" + params);
return params;
}
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> headers = new HashMap<String, String>();
headers.put("Content-Type", "application/x-www-form-urlencoded");
headers.put("UUID", device_uuid);
headers.put("APPID", "2A192A0C22");
headers.put("USERID", "1");
headers.put("PLATFORM", "Andriod");
headers.put("APP_REQUEST", "1");
headers.put("PLATFORMVERSION",androidOS);
return headers;
}
};
AppController.getInstance().addToRequestQueue(postStringRequest, tag_string_req);
}
public void MediaRecorderReady(){
mediaRecorder=new MediaRecorder();
mediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
mediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
mediaRecorder.setAudioEncoder(MediaRecorder.OutputFormat.AMR_NB);
mediaRecorder.setOutputFile(AudioSavePathInDevice);
}
public String CreateRandomAudioFileName(int string){
StringBuilder stringBuilder = new StringBuilder( string );
int i = 0 ;
while(i < string ) {
stringBuilder.append(RandomAudioFileName.
charAt(random.nextInt(RandomAudioFileName.length())));
i++ ;
}
return stringBuilder.toString();
}
private void requestPermission() {
ActivityCompat.requestPermissions(RecordComposition.this, new
String[]{WRITE_EXTERNAL_STORAGE, RECORD_AUDIO}, RequestPermissionCode);
}
#Override
public void onRequestPermissionsResult(int requestCode,
String permissions[], int[] grantResults) {
switch (requestCode) {
case RequestPermissionCode:
if (grantResults.length> 0) {
boolean StoragePermission = grantResults[0] ==
PackageManager.PERMISSION_GRANTED;
boolean RecordPermission = grantResults[1] ==
PackageManager.PERMISSION_GRANTED;
if (StoragePermission && RecordPermission) {
Toast.makeText(RecordComposition.this, "Permission Granted",
Toast.LENGTH_LONG).show();
} else {
Toast.makeText(RecordComposition.this,"Permission Denied",Toast.LENGTH_LONG).show();
}
}
break;
}
}
public boolean checkPermission() {
int result = ContextCompat.checkSelfPermission(getApplicationContext(),
WRITE_EXTERNAL_STORAGE);
int result1 = ContextCompat.checkSelfPermission(getApplicationContext(),
RECORD_AUDIO);
return result == PackageManager.PERMISSION_GRANTED &&
result1 == PackageManager.PERMISSION_GRANTED;
}
private class AsyncTaskRunner extends AsyncTask<String,Void,String> {
#Override
protected String doInBackground(String... params) {
doFileUpload();
return null;
}
}
private void doFileUpload(){
HttpURLConnection conn = null;
//DataOutputStream dos = null;
//DataInputStream inStream = null;
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 1*1024*1024;
String responseFromServer = "";
String urlString = "https://api.soundcloud.com/tracks";
try
{
//------------------ CLIENT REQUEST
FileInputStream fileInputStream = new FileInputStream(mergedFile);
// open a URL connection to the Servlet
URL url = new URL (urlString);
// Open a HTTP connection to the URL
conn = (HttpURLConnection) url.openConnection();
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setUseCaches(false);
conn.setRequestMethod("POST");
conn.setRequestProperty("Connection", "Keep-Alive");
conn.setRequestProperty("Content-Type", "multipart/form-data;boundary="+boundary);
DataOutputStream dos = new DataOutputStream( conn.getOutputStream() );
//Adding oauth token
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"oauth_token\""+lineEnd+lineEnd+access_token+lineEnd);
// dos.writeBytes(lineEnd);
//Adding Track title
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"track[title]\""+lineEnd+lineEnd+tocName+"by Contributor"+":"+" "+contributorName+lineEnd);
//Track taglist
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"track[tag_list]\""+lineEnd+lineEnd+"Tagore Project"+lineEnd);
//Add sharing
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"track[sharing]\""+lineEnd+lineEnd+"private"+lineEnd);
dos.writeBytes(lineEnd);
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"track[asset_data]\";filename=\"" + mergedFile + "\"" + lineEnd);
dos.writeBytes("Content-Type: audio/mpeg"+lineEnd+lineEnd);
// create a buffer of maximum size
bytesAvailable = fileInputStream.available();
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);
}
dos.writeBytes(lineEnd+twoHyphens + boundary + twoHyphens + lineEnd);
fileInputStream.close();
dos.flush();
dos.close();
Log.e("Debug","File is written - "+mergedFile+" - "+conn.getResponseCode());
}
catch (MalformedURLException ex)
{
Log.e("Debug", "error: " + ex.getMessage(), ex);
Toast.makeText(this, ex.getMessage(), Toast.LENGTH_SHORT).show();
}
catch (IOException ioe)
{
Log.e("Debug", "error: " + ioe.getMessage(), ioe);
Toast.makeText(this, ioe.getMessage(), Toast.LENGTH_SHORT).show();
}
try {
BufferedReader inStream = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String str;
Log.e("Debug","Before while");
while (( str = inStream.readLine() ) != null)
{
Log.e("Debug","Server Response "+str);
JSONObject response = new JSONObject(str);
vs_cdn_id = response.getString("id");
secret_token = response.getString("secret_token");
forwardtoOurServer();
}
inStream.close();
}
catch (IOException ioex){
Log.e("Debug", "error: " + ioex.getMessage(), ioex);
} catch (JSONException e) {
e.printStackTrace();
} catch (Exception ex){
ex.printStackTrace();
}
}
Log:
File is written - /storage/emulated/0/Movies/The Tagore Project/merged.3gp - 500
error: https://api.soundcloud.com/tracks
java.io.FileNotFoundException: https://api.soundcloud.com/tracks
at com.android.okhttp.internal.huc.HttpURLConnectionImpl.getInputStream(HttpURLConnectionImpl.java:238)
at com.android.okhttp.internal.huc.DelegatingHttpsURLConnection.getInputStream(DelegatingHttpsURLConnection.java:210)
at com.android.okhttp.internal.huc.HttpsURLConnectionImpl.getInputStream(HttpsURLConnectionImpl.java)
at com.showhow2.www.thetagoreproject.RecordComposition.doFileUpload(RecordComposition.java:923)
at com.showhow2.www.thetagoreproject.RecordComposition.access$2400(RecordComposition.java:73)
at com.showhow2.www.thetagoreproject.RecordComposition$AsyncTaskRunner.doInBackground(RecordComposition.java:829)
at com.showhow2.www.thetagoreproject.RecordComposition$AsyncTaskRunner.doInBackground(RecordComposition.java:824)
at android.os.AsyncTask$2.call(AsyncTask.java:295)
at java.util.concurrent.FutureTask.run(FutureTask.java:237)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:234)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588)
at java.lang.Thread.run(Thread.java:818)
Give permission in menifest...
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
Add this on your code in your Activity class
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
ArrayList<String> names = new ArrayList<>();
ArrayList<Integer> types = new ArrayList<>();
//add item to manes and types array
ListViewAdapter customList = new ListViewAdapter(this, names, types);
list = (ListView) findViewById(R.id.lv);
list.setAdapter(customList);
}
This is ListViewAdapter class
public class ListViewAdapter extends ArrayAdapter<String> {
private ArrayList<String> names;
ArrayList<Integer> types;
private Activity context;
public ListViewAdapter(Activity context, ArrayList<String> names, ArrayList<Integer> types) {
super(context, R.layout.item_rating_rows, names);
this.context = context;
this.names = names;
this.types = types;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = context.getLayoutInflater();
View listViewItem = inflater.inflate(R.layout.item_rating_rows, null, true);
Button btn = (Button) listViewItem.findViewById(R.id.btn);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Log.d("__onclick", "" + view.getId());
}
});
return listViewItem;
}
}
Related
I'm having a hard time with calling a function when I select on the files.
When I select on a file, it start to take like 10 seconds before it start to call the UploadFile function and then connect to the server, so when I select more files to add, it will take like a minute or so before it start to call the UploadFile function and connect to the server which is wrong. It should have start to call the UploadFile function instantly and connect to the server when I am adding more than one files.
Below is the full code:
public class ComposeActivity extends AppCompatActivity implements AdapterView.OnItemSelectedListener {
private static final int CHOOSE_FILE_REQUESTCODE = 1;
private RecyclerView mFilesDetailRecyclerView;
private ArrayList<String> mSelectedFilesList = new ArrayList<>();
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK && requestCode == CHOOSE_FILE_REQUESTCODE) {
try {
Uri uri = data.getData();
Cursor cursor = getContentResolver().query(uri, null, null, null, null);
int index = cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME);
Context context = getApplicationContext();
FilePath = RealPathUtil.getRealPath(context, uri);
cursor.moveToFirst();
//mSelectedFilesList.add(cursor.getString(index));
mSelectedFilesList.add(FilePath);
mAdapter.notifyItemInserted(mSelectedFilesList.size());
Log.e("message.......", "caught this.....");
upload_File = new File(FilePath);
FileName = upload_File.getName();
new UploadFile().execute();
} catch (Exception e) {
Toast.makeText(ComposeActivity.this, "Choose any other file", Toast.LENGTH_SHORT).show();
}
}
}
#SuppressLint("StaticFieldLeak")
private class UploadFile extends AsyncTask<Void, Void, Void> {
#RequiresApi(api = Build.VERSION_CODES.O)
#Override
protected Void doInBackground(Void... params) {
HttpURLConnection urlConnection = null;
try {
String twoHyphens = "--";
String boundary = "*****" + System.currentTimeMillis() + "*****";
String lineEnd = "\r\n";
Log.e("message.......", "FileName...." + FileName);
URL url = new URL("https://www.example.com/fileupload1.php");
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setUseCaches(false);
urlConnection.setDoOutput(true);
urlConnection.setDoInput(true);
urlConnection.setRequestMethod("POST");
urlConnection.setConnectTimeout(200);
urlConnection.setReadTimeout(200);
urlConnection.setRequestProperty("Connection", "Keep-Alive");
urlConnection.setRequestProperty("ENCTYPE", "multipart/form-data");
urlConnection.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
urlConnection.setRequestProperty("uploaded_file", FileName);
FileInputStream fileInputStream = new FileInputStream(upload_File);
DataOutputStream dataOutputStream = new DataOutputStream(urlConnection.getOutputStream());
dataOutputStream.writeBytes(twoHyphens + boundary + lineEnd);
dataOutputStream.writeBytes("Content-Disposition: form-data; name=\"uploaded_file" +
"\"; filename=\"" + FileName + "\"" + lineEnd);
dataOutputStream.writeBytes(lineEnd);
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 1 * 1024 * 1024;
Log.e("message.......", "FileName...." + FileName);
//returns no. of bytes present in fileInputStream
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
buffer = new byte[bufferSize];
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
//Thread.sleep(5000);
while (bytesRead > 0) {
//int percentage = (int) ((bytesRead / (float) size) * 100);
dataOutputStream.write(buffer, 0, bufferSize);
//dataOutputStream.flush(); //doesn't help
bytesAvailable = fileInputStream.available();
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
}
dataOutputStream.writeBytes(lineEnd);
dataOutputStream.writeBytes(twoHyphens + boundary + twoHyphens
+ lineEnd);
int code = urlConnection.getResponseCode();
StringBuilder result = new StringBuilder();
if (code == 200) {
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
String line;
while ((line = reader.readLine()) != null) {
result.append(line);
}
upload_success = result.toString();
}
} catch(SocketTimeoutException e) {
//e.printStackTrace();
if (urlConnection != null) {
urlConnection.disconnect();
cancel(true);
}
}
catch (UnsupportedEncodingException e) {
e.printStackTrace();
Log.e("message.......", "here....5");
} catch (ClientProtocolException e) {
e.printStackTrace();
Log.e("message.......", "here....6");
} catch (ConnectTimeoutException e) {
e.printStackTrace();
Log.e("message.......", "here....7");
}
catch (IOException ioException) {
ioException.printStackTrace();
Log.e("message.......", "here....2");
}
catch (Exception e) {
e.printStackTrace();
Log.e("message.......", "here....5");
if (failtoupload == false) {
failtoupload = true;
}
if (sendMail == true) {
sendMail = false;
}
if (UpdateDraft == true) {
UpdateDraft = false;
}
if (saveDraft == true) {
saveDraft = false;
}
Date dt = new Date();
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String savedDate = dateFormat.format(dt);
draftDB = new DraftDB(mContext);
if (mSelectedFilesList.size() == 1) {
attachments = join("", mSelectedFilesList);
if (attachments.equals("")) {
attachments = null;
}
}
else
{
attachments = join(", ", mSelectedFilesList);
}
if (attachments == null) {
if (mSelectedFilesList.size() == 1) {
attachments = join("", mSelectedFilesList);
}
else
{
attachments = join(", ", mSelectedFilesList);
}
}
String isImportant = "true";
String isRead = "unread";
String UpdateDB = null;
String draftID = null;
if (to == null) {
to = "";
}
if (bcc == null) {
bcc = "";
}
if (cc == null) {
cc = "";
}
if (subject == null) {
subject = "";
}
if (message == null) {
message = "";
}
if (draft_id != null) {
draftID = draft_id;
UpdateDB = "yes";
}
else
{
draftID = "";
UpdateDB = "no";
}
if (draftDB_id == 0) {
draftDB.insertDraft(from, to, cc, bcc, subject, message, attachments, isImportant, isRead, UpdateDB, draftID, savedDate);
draftDB_id = draftDB.getID();
}
else
{
int id = draftDB_id;
draftDB.updateDraft(id, from, to, cc, bcc, subject, message, attachments, isImportant, isRead, UpdateDB, draftID, savedDate);
}
else
{
int id = draftDB_id;
draftDB.updateDraft(id, from, to, cc, bcc, subject, message, attachments, isImportant, isRead, UpdateDB, draftID, savedDate);
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
}
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
Log.e("message.......", "here....6");
if (upload_success != null) {
if (upload_success.equals("success")) {
if (mSelectedFilesList.size() > 0) {
mSelectedFilesList.remove(0);
if (draft_id == null) {
new SaveDraft().execute();
}
else if (draft_id != null) {
if (attachment != null) {
if (mSelectedFilesList.size() >= 1) {
attid++;
for (int i = 0; i < mSelectedFilesList.size(); i++) {
String path = mSelectedFilesList.get(0);
FileName = path.substring(path.lastIndexOf("/") + 1);
attachment += " attid: " + String.valueOf(attid) + " filename: " + FileName;
}
}
}
Log.e("message........", "attachment......" + attachment);
new UpdateDrafts().execute();
}
if (mSelectedFilesList.size() >= 1) {
FilePath = mSelectedFilesList.get(0);
upload_File = new File(FilePath);
FileName = upload_File.getName();
new UploadFile().execute();
}
}
//Now time to check the upload_File
if (mSelectedFilesList.size() == 0) {
if (upload_File != null) {
upload_File = null;
}
if (FilePath != null) {
FilePath = null;
}
Log.e("message.......", "sendMail........." + sendMail);
}
if (upload_success != null) {
upload_success = null;
}
}
}
}
#Override
protected void onCancelled() {
super.onCancelled();
this.cancel(true);
}
}
What I am trying to do is when I select on the file and add more files on my mobile app, I want to call the UploadFile function instantly and connect to my server to upload the file in each time when I select on the file. If the server do not response for 10 seconds and the server is offline, I want to store the data in the sqlite database.
I have been told that I should use multi thread and I should also use retrofit. I am not sure if it would be possible to use HttpUrlConnection method with multi thread to connect to the server and upload the files.
Can you please show me an example of what is the best way I could use to get instantly call to a function and connect to the server using with HttpUrlConnection if that is possible??
You start already wrong with trying to get a real path for an uri.
Remove that code.
Then instead of opening a FileInputStream open an InputStream for the uri
InputStream is = getContentResolvet().openInputStream(uri);
I am making app in which user can attach Image from gallery, capture from camera or attach PDF file so i want to send File using volley. I wrote MultipartRequest class in which i can pass bitmap by using ByArrayOutputStream. But now i want to send File. There is an sendLeave() in fragment which Fragment which sending file with other params. Only MultipartRequest class and SendLeave() is only related code for this question but other code for how file is created.
MultipartRequest Class
public class MultipartRequest extends Request<NetworkResponse> {
private final String twoHyphens = "--";
private final String lineEnd = "\r\n";
private final String boundary = "apiclient-" + System.currentTimeMillis();
private Response.Listener<NetworkResponse> mListener;
private Response.ErrorListener mErrorListener;
private Map<String, String> mHeaders;
public MultipartRequest(int method, String url,
Response.Listener<NetworkResponse> listener,
Response.ErrorListener errorListener) {
super(method, url, errorListener);
this.mListener = listener;
this.mErrorListener = errorListener;
}
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
return (mHeaders != null) ? mHeaders : super.getHeaders();
}
#Override
public String getBodyContentType() {
return "multipart/form-data;boundary=" + boundary;
}
#Override
public byte[] getBody() throws AuthFailureError {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
DataOutputStream dos = new DataOutputStream(bos);
try {
// populate text payload
Map<String, String> params = getParams();
if (params != null && params.size() > 0) {
textParse(dos, params, getParamsEncoding());
}
// populate data byte payload
Map<String, DataPart> data = getByteData();
if (data != null && data.size() > 0) {
dataParse(dos, data);
}
// close multipart form data after text and file data
dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
return bos.toByteArray();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
/**
* Custom method handle data payload.
*
* #return Map data part label with data byte
* #throws AuthFailureError
*/
protected Map<String, DataPart> getByteData() throws AuthFailureError {
return null;
}
#Override
protected Response<NetworkResponse> parseNetworkResponse(NetworkResponse response) {
try {
return Response.success(
response,
HttpHeaderParser.parseCacheHeaders(response));
} catch (Exception e) {
return Response.error(new ParseError(e));
}
}
#Override
protected void deliverResponse(NetworkResponse response) {
mListener.onResponse(response);
}
#Override
public void deliverError(VolleyError error) {
mErrorListener.onErrorResponse(error);
}
/**
* Parse string map into data output stream by key and value.
*
* #param dataOutputStream data output stream handle string parsing
* #param params string inputs collection
* #param encoding encode the inputs, default UTF-8
* #throws IOException
*/
private void textParse(DataOutputStream dataOutputStream, Map<String, String> params, String encoding) throws IOException {
try {
for (Map.Entry<String, String> entry : params.entrySet()) {
buildTextPart(dataOutputStream, entry.getKey(), entry.getValue());
}
} catch (UnsupportedEncodingException uee) {
throw new RuntimeException("Encoding not supported: " + encoding, uee);
}
}
/**
* Parse data into data output stream.
*
* #param dataOutputStream data output stream handle file attachment
* #param data loop through data
* #throws IOException
*/
private void dataParse(DataOutputStream dataOutputStream, Map<String, DataPart> data) throws IOException {
for (Map.Entry<String, DataPart> entry : data.entrySet()) {
buildDataPart(dataOutputStream, entry.getValue(), entry.getKey());
}
}
/**
* Write string data into header and data output stream.
*
* #param dataOutputStream data output stream handle string parsing
* #param parameterName name of input
* #param parameterValue value of input
* #throws IOException
*/
private void buildTextPart(DataOutputStream dataOutputStream, String parameterName, String parameterValue) throws IOException {
dataOutputStream.writeBytes(twoHyphens + boundary + lineEnd);
dataOutputStream.writeBytes("Content-Disposition: form-data; name=\"" + parameterName + "\"" + lineEnd);
dataOutputStream.writeBytes(lineEnd);
dataOutputStream.writeBytes(parameterValue + lineEnd);
}
/**
* Write data file into header and data output stream.
*
* #param dataOutputStream data output stream handle data parsing
* #param dataFile data byte as DataPart from collection
* #param inputName name of data input
* #throws IOException
*/
private void buildDataPart(DataOutputStream dataOutputStream, DataPart dataFile, String inputName) throws IOException {
dataOutputStream.writeBytes(twoHyphens + boundary + lineEnd);
dataOutputStream.writeBytes("Content-Disposition: form-data; name=\"" +
inputName + "\"; filename=\"" + dataFile.getFileName() + "\"" + lineEnd);
if (dataFile.getType() != null && !dataFile.getType().trim().isEmpty()) {
dataOutputStream.writeBytes("Content-Type: " + dataFile.getType() + lineEnd);
}
dataOutputStream.writeBytes(lineEnd);
ByteArrayInputStream fileInputStream = new ByteArrayInputStream(dataFile.getContent());
int bytesAvailable = fileInputStream.available();
int maxBufferSize = 1024 * 1024;
int bufferSize = Math.min(bytesAvailable, maxBufferSize);
byte[] buffer = new byte[bufferSize];
int bytesRead = fileInputStream.read(buffer, 0, bufferSize);
while (bytesRead > 0) {
dataOutputStream.write(buffer, 0, bufferSize);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
}
dataOutputStream.writeBytes(lineEnd);
}
class DataPart {
private String fileName;
private byte[] content;
private String type;
public DataPart() {
}
DataPart(String name, byte[] data) {
fileName = name;
content = data;
}
String getFileName() {
return fileName;
}
byte[] getContent() {
return content;
}
String getType() {
return type;
}
}
}
AttachDocument Fragment
public class LeaveCreate extends Fragment {
File files;
#Override
public View onCreateView(final LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
btnAttach.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
final Dialog dialog = new Dialog(getActivity());
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setContentView(R.layout.dialog_layout);
dialog.show();
Button btnGallery = (Button) dialog.findViewById(R.id.btnGallery);
Button btnFile = (Button) dialog.findViewById(R.id.btnFile);
Button btnCamera = (Button) dialog.findViewById(R.id.btnCamera);
btnGallery.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
dialog.dismiss();
Intent pickIntent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
pickIntent.setType("image/*");
startActivityForResult(pickIntent,1);
}
});
btnFile.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
dialog.dismiss();
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("application/pdf");
intent.addCategory(Intent.CATEGORY_OPENABLE);
try {
startActivityForResult(Intent.createChooser(intent,"Select a File to Upload"),2);
}catch (android.content.ActivityNotFoundException ex){
Toast.makeText(getActivity(), "Please Install a File Manager",Toast.LENGTH_SHORT).show();
}
}
});
btnCamera.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
dialog.dismiss();
String filename = "digimTemp.jpg";
ContentValues contentValues = new ContentValues();
contentValues.put(MediaStore.Images.Media.TITLE,filename);
mCapturedImageURI = getActivity().getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,contentValues);
Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT,mCapturedImageURI);
startActivityForResult(cameraIntent,3);
}
});
}
});
btnSend.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
SendLeave();
}
});
return view;
}
#RequiresApi(api = Build.VERSION_CODES.KITKAT)
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == Activity.RESULT_OK) {
if (requestCode == 1) {
if (resultCode == Activity.RESULT_OK) {
Uri selectedImageUri = data.getData();
String path = getRealPathFromURI(getActivity(),selectedImageUri);
// Toast.makeText(getBaseContext(),path,
// Toast.LENGTH_LONG).show();
files = new File(path.substring(0,path.lastIndexOf("/")),path.substring(path.lastIndexOf("/"),path.length()));
btnAttach.setText("Gallery");
Bitmap b = null;
try {
b = MediaStore.Images.Media.getBitmap(getActivity().getContentResolver(), selectedImageUri);
} catch (IOException e) {
e.printStackTrace();
}
Drawable d = new BitmapDrawable(getResources(), b);
d.setBounds(0, 0, 60, 60);
btnAttach.setCompoundDrawables(d, null, null, null);
btnAttach.setCompoundDrawablePadding(20);
}
}
else if (requestCode == 2) {
if (resultCode == Activity.RESULT_OK) {
Uri selectedImageUri = data.getData();
String path = null;
path = getPath(getActivity(),selectedImageUri);
Toast.makeText(getActivity().getBaseContext(),path,
Toast.LENGTH_LONG).show();
files = new File(path.substring(0,path.lastIndexOf("/")),path.substring(path.lastIndexOf("/"),path.length()));
btnAttach.setText(path.substring(path.lastIndexOf("/")+1,path.length()));
}
}
else if(requestCode == 3)
{
if (resultCode == Activity.RESULT_OK) {
String[] projection = { MediaStore.Images.Media.DATA };
Cursor cursor = getActivity().managedQuery(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
projection, null, null, null);
int column_index_data = cursor
.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToLast();
String path = cursor.getString(column_index_data);
Bitmap photo = BitmapFactory.decodeFile(path);
// CALL THIS METHOD TO GET THE URI FROM THE BITMAP
// Uri tempUri = getImageUri(getApplicationContext(), bitmap);
files = new File(path.substring(0,path.lastIndexOf("/")),path.substring(path.lastIndexOf("/"),path.length()));
if (Integer.parseInt(String.valueOf(files.length() / 1024)) > 100) {
// filesize=String.valueOf(files.length()/1048576)+" MB";
}
btnAttach.setText("Camera");
// attachment.setDrawableLe
Drawable d = new BitmapDrawable(getResources(), photo);
d.setBounds(0, 0, 60, 60);
btnAttach.setCompoundDrawables(d, null, null, null);
btnAttach.setCompoundDrawablePadding(20);
}
}
}
}
public void SendLeave(){
progressDialog.show();
MultipartRequest multipartRequest = new MultipartRequest(Request.Method.POST, SEND_LEAVE_URL, new Response.Listener<NetworkResponse>() {
#Override
public void onResponse(NetworkResponse response) {
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}){
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String,String> params = new HashMap<>();
params.put("parent_id", SharedPreferenceManager.getmInstance(getActivity()).getID());
params.put("student_id",studentid);
params.put("reason",txtReason.getText().toString());
params.put("start_date",txtFromDate.getText().toString());
params.put("end_date",txtToDate.getText().toString());
int i=0;
for (String temp: teacherid){
params.put("teacher_id["+(i++)+"]", temp);
}
return params;
}
#Override
protected Map<String, MultipartRequest.DataPart> getByteData() {
Map<String, MultipartRequest.DataPart> params = new HashMap<>();
params.put("file", new MultipartRequest.DataPart());
return params;
}
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String,String> headers = super.getHeaders();
if (headers == null || headers.equals(Collections.<String, String>emptyMap())){
headers = new HashMap<String, String>();
}
MyApp.get().addSessionCookie(headers);
return headers;
}
};
RequestQueue queue = Volley.newRequestQueue(getContext());
queue.add(multipartRequest);
}
Volley doesn’t support multi part file
But there’s a customized library of volley called Volley Plus which supports multi part file
Or use http url connection to send file.
Follow this.
Using http url connection u can also show the upload progress easily
This is what I used to upload a PDF, but you can use it to any file. I used the same VolleyMultipartRequest, you just have to get the data from the file to upload it. Hope it helps you!
private void uploadPDF() {
VolleyMultipartRequest volleyMultipartRequest = new VolleyMultipartRequest(
Request.Method.POST,
url,
new Response.Listener<NetworkResponse>() {
#Override
public void onResponse(NetworkResponse response) {
//Handle response
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
//Handle error
}
}
) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
//Params
return params;
}
#Override
protected Map<String, DataPart> getByteData() {
Map<String, DataPart> params = new HashMap<>();
String pdfName = String.valueOf(System.currentTimeMillis() + ".pdf");
params.put("pdf", new DataPart(pdfName, getFileData()));
return params;
}
};
//I used this because it was sending the file twice to the server
volleyMultipartRequest.setRetryPolicy(
new DefaultRetryPolicy(
0,
-1,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT
)
);
requestQueue.add(volleyMultipartRequest);
}
private byte[] getFileData() {
int size = (int) pdf.length();
byte[] bytes = new byte[size];
byte[] tmpBuff = new byte[size];
try (FileInputStream inputStream = new FileInputStream(pdf)) {
int read = inputStream.read(bytes, 0, size);
if (read < size) {
int remain = size - read;
while (remain > 0) {
read = inputStream.read(tmpBuff, 0, remain);
System.arraycopy(tmpBuff, 0, bytes, size - remain, read);
remain -= read;
}
}
} catch (IOException e) {
e.printStackTrace();
}
return bytes;
}
I want to access html from the server using API for that i want to make a method in the response, that method i want to use it in main class.I am using webview to show the output result in webview.Following code I am using.
public class Dashboard_Description__page extends AppCompatActivity {
ImageButton reader_back;
ArrayList<Reader_Model> actorsList;
String addCat;
ActorAdapter adapter;
WebView webView;
String alternate_id;
String bookmarkid;
String bookmarkfile;
private String webData;
String mimeType = "text/html";
String encoding = "utf-8";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_dashboard__description__page);
WebView webView = (WebView) findViewById(R.id.webview);
// String summary = "<html><body>You scored <b>192</b> points.</body></html>";
webView.loadData(getWebData(), "text/html", null);
if (savedInstanceState == null) {
Bundle extras = getIntent().getExtras();
if(extras == null) {
alternate_id= null;
bookmarkid= null;
bookmarkfile = null;
} else {
alternate_id= extras.getString("alternateid");
bookmarkid= extras.getString("bookmarkid");
bookmarkfile = extras.getString("bookmarkfile");
}
} else {
alternate_id= (String) savedInstanceState.getSerializable("alternateid");
bookmarkid= (String) savedInstanceState.getSerializable("bookmarkid");
bookmarkfile= (String) savedInstanceState.getSerializable("bookmarkfile");
}
webView.setWebViewClient(new WebViewClient() {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
});
// System.out.println(stringCameFromFirstAcvitity);
// actorsList = new ArrayList<Actors>();
new JSONReaderAsyncTask().execute("https://www.webo.com/secure-mobile/get_article_detail?", " access_token","bookmark_file","alternate_id","bookmarkId");
reader_back=(ImageButton)
findViewById(R.id.reader_back_btn);
reader_back.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick (View v) {
Intent dash_back = new Intent(getApplicationContext(),Dashboard.class);
startActivity(dash_back);
}
});
}
public String getWebData() {
return webData;
}
public void setWebData(String data) {
this.webData = data;
}
class JSONReaderAsyncTask extends AsyncTask<String, Void, Boolean> {
ProgressDialog dialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
dialog = new ProgressDialog(Dashboard_Description__page.this);
dialog.setMessage("Loading, please wait");
dialog.setTitle("Connecting server");
dialog.show();
dialog.setCancelable(false);
}
#Override
protected Boolean doInBackground(String... params)
{
HttpParams httpParameters = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParameters, 5000);
HttpConnectionParams.setSoTimeout(httpParameters, 5000);
HttpClient httpClient = new DefaultHttpClient(httpParameters);
HttpPost httpPost = new HttpPost(params[0]);
String jsonResult = "";
try {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(4);
nameValuePairs.add(new BasicNameValuePair("access_token", "94529e5dbc6234fc3bbfce7406b8dde9"));
nameValuePairs.add(new BasicNameValuePair("bookmark_file", bookmarkfile));
nameValuePairs.add(new BasicNameValuePair("alternate_id", alternate_id));
nameValuePairs.add(new BasicNameValuePair("bookmarkId", bookmarkid));
// System.out.println(alternate_id);
//System.out.println(bookmarkfile);
// System.out.println(bookmarkid);
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpClient.execute(httpPost);
// System.out.println("hello Hitu");
// jsonResult = inputStreamToString(response.getEntity().getContent()).toString();
// System.out.println(jsonResult);
// StatusLine stat = response.getStatusLine();
int status = 200;
if (status == 200) {
HttpEntity entity = response.getEntity();
String data = EntityUtils.toString(entity);
// ArrayList<String> mylist = new ArrayList<String>();
// mylist.add(data);
// System.out.println(first);
System.out.println(data);
System.out.println("fffff");
//here result is coming from the server. I want here a method which can be used in main class.I want to view this result in html form using webview.
// JSONObject jsono = new JSONObject(data);
// JSONArray jarray = jsono.getJSONArray("content");
}
return true;
//------------------>>
} catch (ParseException e1) {
e1.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return false;
}
protected void onPostExecute(Boolean result) {
dialog.cancel();
// adapter.notifyDataSetChanged();
if(result == false)
Toast.makeText(getApplicationContext(), "Unable to fetch data from server", Toast.LENGTH_LONG).show();
}
}
}
public class HttpClientWrapper {
public static String post(String requestUrl,String postValues) {
URL url;
String response = "";
try {
url = new URL(requestUrl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(15000);
conn.setConnectTimeout(15000);
conn.setRequestMethod("POST");
conn.setDoInput(true);// Specifies whether this URLConnection allows receiving data.
conn.setDoOutput(true);// Specifies whether this URLConnection allows sending data.
conn.setRequestProperty("Content-Type", "application/json; charset=utf-8");
conn.setRequestProperty("Accept", "application/json; charset=utf-8");
OutputStream os = conn.getOutputStream();
BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(os, "UTF-8"));
writer.write(postValues);
writer.flush();
writer.close();
os.close();
int responseCode=conn.getResponseCode();
if (responseCode == HttpsURLConnection.HTTP_OK) {
String line="";
BufferedReader br=new BufferedReader(new InputStreamReader(conn.getInputStream(),"UTF-8"));
StringBuilder sb = new StringBuilder();
while ((line=br.readLine()) != null) {
sb.append(line+"\n");
response = sb.toString().substring(0, sb.toString().length() - 1);
}
}
else {
response="";
}
} catch (Exception e) {
e.printStackTrace();
}
return response;
}
public static String getResponseGET(String url) {
String response = "";
HttpURLConnection c = null;
try {
URL u = new URL(url);
c = (HttpURLConnection) u.openConnection();
c.setRequestMethod("GET");
c.setConnectTimeout(15000);
c.setReadTimeout(15000);
c.connect();
int status = c.getResponseCode();
switch (status) {
case 200:
case 201:
BufferedReader br = new BufferedReader(new InputStreamReader(c.getInputStream()));
StringBuilder sb = new StringBuilder();
String line;
while ((line = br.readLine()) != null) {
sb.append(line+"\n");
response = sb.toString().substring(0, sb.toString().length() - 1);
}
br.close();
return response;
}
} catch (IOException ex) {
if (c != null) {
c.disconnect();
}
} finally {
if (c != null) {
try {
c.disconnect();
} catch (Exception ex) {
}
}
}
return null;
}
}
private class RegistrationAsyncTask extends AsyncTask<Void, Void, String> {
ProgressDialog dialog;
Context mContext;
String error;
String response;
String mData;
public RegistrationAsyncTask(Context context,String data) {
this.mContext = context;
this.error = "";
this.mData = data;
}
#Override
protected void onPreExecute() {
dialog = new ProgressDialog(mContext);
dialog.setTitle("Registration");
dialog.setMessage("Registration in process...");
dialog.setCancelable(false);
dialog.show();
}
#Override
protected String doInBackground(Void... params) {
try {
response = HttpClientWrapper.post(URL.URL_REGISTRATION, mData);
Log.e(TAG, "Response: " + response);
} catch (Exception e) {
e.printStackTrace();
this.error = e.getMessage();
}
return response;
}
#Override
protected void onPostExecute(String result) {
Log.e(TAG, "result: " + response);
if (dialog.isShowing()) {
dialog.dismiss();
}
if (response.isEmpty()){
Utils.message(getActivity(), getResources().getString(R.string.error_server));
return;
}
try {
JSONObject jsonObject = new JSONObject(result);
if (jsonObject.has("error")) {
String error = jsonObject.getString("error");
JSONObject jsonObject1 = new JSONObject(error);
String message = jsonObject1.getString("message");
Utils.showDialog(mContext, alert, alertDialog, getResources().getString(R.string.text_title_reg),message);
return;
} else {
String error = jsonObject.getString("success");
JSONObject jsonObject1 = new JSONObject(error);
String message = jsonObject1.getString("message");
alert = new AlertDialog.Builder(getActivity());
alert.setTitle(R.string.text_title_reg);
alert.setMessage(message);
alert.setCancelable(false);
alert.setPositiveButton("OK",
new DialogInterface.OnClickListener() {
public void onClick(
DialogInterface dialog,
int whichButton) {
clearForm();
dialog.dismiss();
}
});
alertDialog = alert.create();
alertDialog.show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
I am trying to upload images from android to php server The server is working all good for ios using objective c but in android I did not not know how to upload the images. I have tried the below code but the server returns message that (images are not in proper format or missing image file
ArrayList<File> imageFiles= new ArrayList<File>();
for(int i=0;i<mCameraDataList.size();i++) {
File f = new File(getFilesDir(),"image"+i+".jpg");
f.createNewFile();
Bitmap bitmap = Bitmap.createScaledBitmap(
BitmapFactory.decodeByteArray(mCameraDataList.get(i), 0, mCameraDataList.get(i).length),CommonMethods.getDeviceWidth(this), CommonMethods.getDeviceHeight(this), true);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 90, stream);
byte[] bitmapdata = stream.toByteArray();
FileOutputStream fos = new FileOutputStream(f);
fos.write(bitmapdata);
fos.flush();
fos.close();
imageFiles.add(f);
}
public static void postProduct(ArrayList<File> nImages) throws UnsupportedEncodingException {
MultipartEntityBuilder entity=MultipartEntityBuilder.create();
entity.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
entity.addPart("authenticity",new StringBody("1"));
entity.addPart("brand_id",new StringBody("1"));
entity.addPart("cat_id",new StringBody("2"));
entity.addPart("color_id1",new StringBody("2"));
entity.addPart("color_id2",new StringBody("3"));
entity.addPart("condition_id",new StringBody("3"));
entity.addPart("description",new StringBody("Bgvv"));
entity.addPart(Constants.KeyValues.DEVICE_ID,new StringBody(Constants.DEVICE_ID));
entity.addPart("images",new StringBody("images"));
entity.addPart("lon",new StringBody("74.344630"));
entity.addPart("lat",new StringBody("31.516762"));
entity.addPart("name_brand",new StringBody("2 puffs"));
entity.addPart("package_size",new StringBody("0"));
entity.addPart("selling_price", new StringBody("20"));
entity.addPart("title",new StringBody("My test"));
entity.addPart(Constants.KeyValues.UID,new StringBody(String.valueOf(CommonObjects.getUserProfile().getUid())));
for(int i=0;i<nImages.size();i++)
{
File f=new File(nImages.get(i).getAbsolutePath());
if(f.exists()){
entity.addPart(Constants.KeyValues.IMAGES, new FileBody(f, "image/jpeg"));
}
}
new SetDataToServer(Constants.NetworkServiceMethods.Product.POST_PRODUCT, entity, new SetDataToServer.SetDataNotifier() {
#Override
public void onDataReceived(boolean isError, String message, JSONObject jsonObj) {
ArrayList<String> postProductResult =new ArrayList<String>();
try {
Log.e("JSON",jsonObj.toString());
if (!jsonObj.isNull(Constants.KeyValues.DATA)) {
JSONObject jsonObjectData = jsonObj.getJSONObject(Constants.KeyValues.DATA);
// postProductResult.add(jsonObjectData.getString(Constants.KeyValues.CON_ID));
// postProductResult.add(jsonObjectData.getString(Constants.KeyValues.ORDER_ID));
}
} catch (JSONException e) {
isError = true;
message = "Sorry! Error occurred in data parsing";
}
productHandlerMethods.onPostProductResult(isError, message, postProductResult);
}
}).callServerToSetData();
}
Can any body tell what I am doing wrong.
Server side code
public function postproduct_post() {
$brand_id = $this->post('brand_id');
if ($brand_id == '') {
$brand_name = $this->post('name_brand');
if ($brand_name == '')
$this->create_error(-1);
$brand_id = $this->Mproduct->insertBrandName($brand_name);
} else {
if (!$this->Mproduct->_checkBrandId($brand_id))
$this->create_error(-15, 'brand_id');
}
$time = time();
$uid = $this->post('uid');
$cat_id = $this->post('cat_id');
$title = $this->post('title');
$description = $this->post('description');
$condition_id = $this->post('condition_id');
$authenticity = $this->post('authenticity');
$color_id1 = $this->post('color_id1', 0);
$color_id2 = $this->post('color_id2', 0);
$selling_price = $this->post('selling_price');
$package_size = $this->post('package_size');
$lat = $this->post('lat');
$lon = $this->post('lon');
if ($uid == '' || $cat_id == '' || $title == '' || $description == ''
|| $color_id1 == '' || $condition_id == '' || $authenticity == '') {
$this->create_error(-1);
}
if (!$this->Muser->_checkUid($uid))
$this->create_error(-10);
if (!$this->Mproduct->_checkCatId($cat_id))
$this->create_error(-15, 'cat_id');
if ($color_id1 > 0 && !$this->Mproduct->_checkColorId($color_id1)) {
$this->create_error(-15, 'color_id1');
}
if ($color_id2 > 0 && !$this->Mproduct->_checkColorId($color_id2)) {
$this->create_error(-15, 'color_id2');
}
$images = isset($_FILES['images']) ? $_FILES['images'] : null;
if ($images == null || count($images['name']) <= 0) {
$this->create_error(-21);
}
$this->load->model('Mfile');
if (!$this->Mfile->checkArrayImage($images)) {
$this->create_error(-13);
}
if (!$this->Mproduct->_checkConditionId($condition_id)) {
$this->create_error(-15, 'condition_id');
}
$params = array();
$params['owner_id'] = $uid;
$params['cat_id'] = $cat_id;
$params['title'] = $title;
$params['added'] = $time;
$params['brand_id'] = $brand_id;
$params['description'] = $description;
$params['is_sell'] = 1;
$params['size_id'] = 101;
$params['is_swap'] = 0;
$params['is_give'] = 0;
$params['color_id1'] = $color_id1;
$params['color_id2'] = $color_id2;
$params['condition_id'] = $condition_id;
$params['authenticity'] = $authenticity;
$params['lat'] = $lat;
$params['lon'] = $lon;
$params['last_activity'] = $time;
$params['last_comment'] = '';
$params['status'] = 1;
if ($selling_price != '')
$params['selling_price'] = $selling_price;
if ($package_size != '')
$params['package_size'] = $package_size;
$product_id = $this->Mproduct->insertProduct($params);
if ($product_id == -1) {
$this->create_error(-16);
}
$paths = $this->Mfile->saveArrayImage($images, $product_id, $time);
if (count($paths) <= 0) {
$this->create_error(-13);
}
$params = array();
$params['image'] = $this->Mfile->createThumbProduct($paths[0]);
$params['status'] = 1;
$this->Mproduct->updateAfterInsertProduct($product_id, $params);
$this->Mproduct->upItemInCat($cat_id);
$this->Mproduct->upItemInBrand($brand_id);
$this->Muser->upItemOfUser($uid);
$this->Mproduct->insertProductImage($product_id, $paths);
//$this->Mfeed->insertNotifyNewProduct($time, $uid, $product_id);
//$this->Mpush->createNotiAddProduct($uid, $product_id);
$uids = $this->Mproduct->getUidsFollowUser($uid);
$this->load->model('Mnotify');
$this->Mnotify->createNotifyMany($uids, $product_id, $uid, 7, array('product_id' => $product_id, 'uid' => $uid));
$this->Mfeed->insertFeedWhenSell($time, $product_id);
$data = array();
$data['product_id'] = $product_id;
$this->create_success($data, 'Add success');
}
Try to upload the image via below service written in android, make sure that image path is correct in below code, place the image in sdcard :
public class MyService extends Service {
SharedPreferences sharedPref;
SharedPreferences.Editor editor;
int serverResponseCode = 0;
String upLoadServerUri = null;
private static final String TAG = "com.example.ServiceExample";
#Override
public void onCreate() {
Log.i(TAG, "Service onCreate");
sharedPref = getSharedPreferences("myfiles", MODE_PRIVATE);
/************* Php script path ****************/
upLoadServerUri = "http://myserver/uploadimage.php";
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.i(TAG, "Service onStartCommand " + startId);
final int currentId = startId;
Runnable r = new Runnable() {
public void run() {
for (int i = 0; i < 3; i++) {
// long endTime = System.currentTimeMillis() + 10*1000;
// while (System.currentTimeMillis() < endTime) {
synchronized (this) {
try {
uploadFile(sharedPref.getString(i + "", ""));
} catch (Exception e) {
}
}
// }
Log.i(TAG, "Service running " + currentId);
}
stopSelf();
}
};
Thread t = new Thread(r);
t.start();
return Service.START_STICKY;
}
#Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
Log.i(TAG, "Service onBind");
return null;
}
#Override
public void onDestroy() {
Log.i(TAG, "Service onDestroy");
}
public int uploadFile(String sourceFileUri) {
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(Environment.getExternalStorageDirectory(),sourceFileUri);
File sourceFile = new File(Environment.getExternalStorageDirectory()
.getAbsolutePath() + "/" + fileName);
if (!sourceFile.isFile()) {
return 0;
} else {
try {
// open a URL connection to the Servlet
FileInputStream fileInputStream = new FileInputStream(
sourceFile);
URL url = new URL(upLoadServerUri);
// Open a HTTP connection to the URL
conn = (HttpURLConnection) url.openConnection();
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("Content-Disposition: form-data; name=\"uploaded_file\";filename=\""
+ fileName + "\"" + lineEnd);
dos.writeBytes(lineEnd);
// create a buffer of maximum size
bytesAvailable = fileInputStream.available();
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) {
}
// close the streams //
fileInputStream.close();
dos.flush();
dos.close();
} catch (MalformedURLException ex) {
ex.printStackTrace();
Log.e("Upload file to server", "error: " + ex.getMessage(), ex);
} catch (Exception e) {
e.printStackTrace();
Log.e("Upload file to server Exception",
"Exception : " + e.getMessage(), e);
}
return serverResponseCode;
} // End else block
}
}
I definitely need some help on this one! My problem is that I can't find out how to get the Uri of the last taken photo. I can upload a photo when I choose it from the gallery, but the other feature is missing. The camera starts and after the photo is taken it is saved in the gallery, but somehow I can't find out the URI of the last taken photo. Please help!
Regards,
Habib
public class MainActivity extends Activity {
private final int SELECT_FILE = 1;
private final int REQUEST_CAMERA = 0;
private ImageView ivImage;
private Button btnSetImage;
TextView tv;
int serverResponseCode = 0;
ProgressDialog dialog = null;
File f = new File(Environment.getExternalStorageDirectory().toString());
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ivImage = (ImageView) findViewById(R.id.ivImage);
btnSetImage = (Button) findViewById(R.id.btnSelectPhoto);
btnSetImage.setOnClickListener(onClickListener);
tv = (TextView) findViewById(R.id.tv);
}
private OnClickListener onClickListener = new OnClickListener() {
#Override
public void onClick(View v) {
selectImage();
}
};
public int uploadFile(String sourceFileUri) {
String upLoadServerUri = "...upload.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 Server
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(MainActivity.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(MainActivity.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(MainActivity.this, "Exception : " + e.getMessage(),
Toast.LENGTH_SHORT).show();
Log.e("Upload file to server Exception",
"Exception : " + e.getMessage(), e);
}
dialog.dismiss();
return serverResponseCode;
}
private void selectImage() {
final CharSequence[] items = { "Take Photo", "Choose from Library",
"Cancel" };
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setTitle("Add Photo!");
builder.setItems(items, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int item) {
if (items[item].equals("Take Photo")) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File f = new File(android.os.Environment
.getExternalStorageDirectory(), "temp.jpg");
intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(f));
startActivityForResult(intent, REQUEST_CAMERA);
} else if (items[item].equals("Choose from Library")) {
Intent intent = new Intent(
Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
intent.setType("image/*");
startActivityForResult(
Intent.createChooser(intent, "Select File"),
SELECT_FILE);
} else if (items[item].equals("Cancel")) {
dialog.dismiss();
}
}
});
builder.show();
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
if (requestCode == REQUEST_CAMERA) {
File f = new File(Environment.getExternalStorageDirectory()
.toString());
for (File temp : f.listFiles()) {
if (temp.getName().equals("temp.jpg")) {
f = temp;
break;
}
}
try {
Bitmap bm;
BitmapFactory.Options btmapOptions = new BitmapFactory.Options();
bm = BitmapFactory.decodeFile(f.getAbsolutePath(),
btmapOptions);
// bm = Bitmap.createScaledBitmap(bm, 70, 70, true);
ivImage.setImageBitmap(bm);
String path = android.os.Environment
.getExternalStorageDirectory()
+ File.separator
+ "Phoenix" + File.separator + "default";
f.delete();
OutputStream fOut = null;
final File file = new File(path, String.valueOf(System
.currentTimeMillis()) + ".jpg");
try {
fOut = new FileOutputStream(file);
bm.compress(Bitmap.CompressFormat.JPEG, 85, fOut);
fOut.flush();
fOut.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
} catch (Exception e) {
e.printStackTrace();
}
} else if (requestCode == SELECT_FILE) {
Uri selectedImageUri = data.getData();
final String tempPath = getPath(selectedImageUri,
MainActivity.this);
Bitmap bm;
BitmapFactory.Options btmapOptions = new BitmapFactory.Options();
bm = BitmapFactory.decodeFile(tempPath, btmapOptions);
ivImage.setImageBitmap(bm);
dialog = ProgressDialog.show(MainActivity.this, "",
"Uploading file...", true);
new Thread(new Runnable() {
public void run() {
runOnUiThread(new Runnable() {
public void run() {
tv.setText("uploading started.....");
}
});
int response = uploadFile(tempPath);
System.out.println("RES : " + response);
}
}).start();
}
}
}
public String getPath(Uri uri, Activity activity) {
String[] projection = { MediaColumns.DATA };
Cursor cursor = activity
.managedQuery(uri, projection, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(MediaColumns.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
}
You can use this as the path/file where camera stores the photo instead of looking for latest photo.
Uri.fromFile(f)
Camera intent stores the image to the location which you pass it. So may be store the path of the image a global in the activity since it's a temp path that you are passing. And use it the on activity result method to access the file.