I am trying to post an image to a server with Fast Android Networking and I can't figure out how.
The image gets uploaded from an emulator in Android Studio and put in an ImageView, how can I send that image to the server with a POST request?
The code under my starting point and is mostly from https://amitshekhar.me/Fast-Android-Networking/post_request.html if that helps.
AndroidNetworking.post("https://fierce-cove-29863.herokuapp.com/postFile")
.setContentType(file) // posting any type of file
.setTag("test")
.setPriority(Priority.MEDIUM)
.build()
.getAsJSONObject(new JSONObjectRequestListener() {
#Override
public void onResponse(JSONObject response) {
// do anything with response
}
#Override
public void onError(ANError error) {
// handle error
}
});
Related
How to attach PDF file to post API with two parameter? I am using Fast android networking library.
I am able to call API but I when user touched button my API called in my API have three parameters like this:
message = "Test"
receiver_Email = "#gmail.com"
File = text.PDF;
Sy API allows only PDF form met with message and email. I am using Fast android networking library. I try to call API but I am not able to do it.
I also looked at some examples but it couldn't help me out.
just call this method from your onCreate this is the easy way to call API with file and parameter I hope it helps you
//method used to call API to send email
enter code here
#RequiresApi(API = Build.VERSION_CODES.LOLLIPOP_MR1)
public void call_Api()
{
final String key = "file";
final File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath(), "/test.pdf");
AndroidNetworking.initialize(this);
AndroidNetworking.upload("your API")
.setPriority(Priority.HIGH)
.addMultipartParameter("message", "test")
.addMultipartParameter("receiverEmail","testrg0017#gmail.com")
.addMultipartFile(key, file)
.setPriority(Priority.HIGH)
.build()
.getAsJSONObject(new JSONObjectRequestListener()
{
#Override
public void onResponse(JSONObject response)
{
Log.d("res ",response.toString());
if(file.exists())
{
Toast.makeText(PdfGeneration.this, "API call successfully",
Toast.LENGTH_SHORT).show();
}
}
#Override
public void onError(ANError anError)
{
anError.printStackTrace();
Log.d("res12 ",anError.toString());
if(!file.exists())
{
Toast.makeText(PdfGeneration.this, "file not available",
Toast.LENGTH_SHORT).show();
}
}
});
}
So I'm starting with android studio, following tutorials and all.
I'm interested in making a request to a local server, so I google up and see this.
https://developer.android.com/training/volley/simple
I follow the instructions, get stuck in a couple of places being a very new user to java and android studio, but everything works in the end.
Then, knowing the app will work, just change the "http://www.google.com" string in the example with the ip of the server. And nothing happens.
It doesn't retrieve the index page.
I try with a php script. Nothing.
Phone and server are in the same LAN.
I have tried adding "http://" to the ip, nothing.
Server just work fine in any browser, pc and phone.
I am missing something?
If the code is needed I upload it, but it's exactly the same in the example.
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void sendRequest(){
final TextView textView = (TextView) findViewById(R.id.stringRequest);
RequestQueue queue = Volley.newRequestQueue(this);
String url ="http://192.168.1.36";
// Request a string response from the provided URL.
StringRequest stringRequest = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
// Display the first 500 characters of the response string.
textView.setText("Response is: "+ response.substring(0,500));
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
textView.setText("That didn't work!");
}
});
// Add the request to the RequestQueue.
queue.add(stringRequest);
}
public void onClick(View view){
sendRequest();
}
}
Logcat throws this error:
D/NetworkSecurityConfig: No Network Security Config specified, using platform default
I/System.out: (HTTPLog)-Static: isSBSettingEnabled false
Also, I tried to run it on a emulator and the result is the same.
I added every network related permission, too.
If the only thing you changed is https://www.google.com to http://1.2.3.4 (note switching https to http, and leaving the protocol in the string URL), and it works fine with google there but not with your IP, then it means where-ever you're running this code (on your phone directly, or on the emulator in your dev environment) cannot reach that IP. Note that if you wait a while, the code will error out with for example a Destination Unreachable error or something else enlightening.
I have an issue something like, I am downloading a image from web api and successfully set into imageview. I am unable to change the color of svg image that I downloaded.
I tried tintColor in xml and setFilterColor() from .java file but nothing is work for me.
Is there any solution please reply on this post.
public static void loadSvgWithColor(final Context context, String url, final int color, final ImageView target) {
if (httpClient == null) {
httpClient = new OkHttpClient.Builder()
.cache(new Cache(context.getCacheDir(), 5 * 1024 * 1014))
.build();
}
if (!url.equals("")) {
Request request = new Request.Builder().url(url).build();
httpClient.newCall(request).enqueue(new Callback() {
#Override
public void onFailure(Call call, IOException e) {
target.setImageResource(R.drawable.app_icon);
target.setColorFilter(color);
}
#Override
public void onResponse(Call call, Response response) throws IOException {
InputStream stream = response.body().byteStream();
Sharp.loadInputStream(stream).into(target);
stream.close();
target.setColorFilter(color);
}
});
} else {
target.setImageResource(R.drawable.app_icon);
target.setColorFilter(color);
}
}
Edit the stream of svg file when you received of api, and set into imageview
By this sample:
The Sharp library you are using generates a PictureDrawable and puts that in your ImageView. Last I checked, the android:tint and setColorFilter() methods don't work on PictureDrawables.
I can think of a couple of solutions:
Use Sharp's festure to change the colour when rendering. See their demo at: https://github.com/Pixplicity/sharp/blob/master/sample-imageview/src/main/java/com/pixplicity/sharp/imageviewdemo/SvgDemoActivity.java
Use a different library, such as my AndroidSVG, which let's you style the SVG with CSS when rendering.
I have an app that users can upload file. Right now it works.
They can upload files and it received in server side.
Now I want show upload percent to users while uploading.
I used below code to upload files on server.
here is my java code:
send.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try{
new MaterialFilePicker().
withActivity(AddActivity.this).
withRequestCode(10).
start();
}
catch (Exception e){
return;
}
}
});
and this is my method:
ProgressDialog progress;
#Override
protected void onActivityResult(int requestCode, int resultCode, final Intent data) {
if (requestCode==10 && resultCode==RESULT_OK){
progress = new ProgressDialog(AddActivity.this);
progress.setTitle("Uploading");
progress.setMessage("please wait...");
progress.show();
Thread t = new Thread(new Runnable() {
#Override
public void run() {
File f = new File(data.getStringExtra(FilePickerActivity.RESULT_FILE_PATH));
String content_type = getMimeType(f.getPath());
String file_path = f.getAbsolutePath();
file_size = String.valueOf(f.length()/1024);
OkHttpClient client = new OkHttpClient();
RequestBody file_body = RequestBody.create(MediaType.parse(content_type),f);
RequestBody request_body = new MultipartBody.Builder()
.setType(MultipartBody.FORM)
.addFormDataPart("type",content_type)
.addFormDataPart("upload_file",code+file_path.substring(file_path.lastIndexOf(".")),file_body)
.build();
code2 = code+file_path.substring(file_path.lastIndexOf("."));
Request request = new Request.Builder()
.url("http://api.mysite.com/api/uploadfile")
.post(request_body)
.build();
try {
Response response = client.newCall(request).execute();
Log.d("msg",request_body.toString());
Log.d("msg",f.getPath().toString());
Log.d("msg",getMimeType(f.getPath()));
Log.d("msg33",code+file_path.substring(file_path.lastIndexOf(".")));
if (!response.isSuccessful()){
throw new IOException(("Error:"+response));
}
progress.dismiss();
} catch (IOException e) {
e.printStackTrace();
}
}
});
t.start();
}
}
Please help me to add upload percentage.
Thank you
You are doing a lot of things wrong here:
Logic responsible for uploading file should not be located in onActivityResult()
You should seperate it into different method
Using thread like that is not a good idea
If you want to upload file or large file you should do it in IntentService class (You will have to create Your own class and extend IntentService), it is something that is meant for things like that. I suggest You to learn about Retrofit2 and OkHttp library cause it will make it a lot of easier.
An example where you can find a one of the ways how to do it is here: Is it possible to show progress bar when upload image via Retrofit 2?
Asking ppl at stackoverflow to write code completly for you is not a good way to improve your skills. Check this link which I gave You.
Good luck
EDIT:
Android Services: http://www.vogella.com/tutorials/AndroidServices/article.html and https://developer.android.com/training/run-background-service/create-service
Retrofit 2: http://www.vogella.com/tutorials/Retrofit/article.html
OkHttp: https://www.journaldev.com/13629/okhttp-android-example-tutorial
Sample: Is it possible to show progress bar when upload image via Retrofit 2?
These link provides all the information You need in order to write this functionality. I don't have videos on YouTube with things like this. I'm never using YouTube to get this kind of information.
I'm trying to upload an image, saved in the internal memory of my phone, clicked by an android app to a cloud service, and am using Kinvey to do so. But I'm facing some problems with it.
Every time I run the code that contains the upload part, I encounter an exception. I'm uploading an image of ".png" type. Any conversion to blob is not a necessary process that is required, unlike that in Google Cloud Platform.
Here is my .java code -
`Client mKinveyClient = new Client.Builder(APP_KEY, SECRET_KEY, this.getApplicationContext()).build();
mKinveyClient.enableDebugLogging();
mKinveyClient.ping(new KinveyPingCallback() {
public void onFailure(Throwable t) {
Log.e(TAG, "Kinvey Ping Failed", t);
}
public void onSuccess(Boolean b) {
Log.d(TAG, "Kinvey Ping Success");
}
});
java.io.File file = new java.io.File(Environment.getExternalStorageDirectory().getPath() + "/Camera/" + "IMG_20161115_193353.jpg");
mKinveyClient.file().upload(file, new UploaderProgressListener() {
public void onSuccess(Void result) {
Log.i(TAG, "successfully upload file");
}
#Override
public void onSuccess(FileMetaData fileMetaData) {
Log.i(TAG, "successfully uploaded file");
}
#Override
public void onFailure(Throwable error) {
Log.e(TAG, "failed to upload file.", error);
}
#Override
public void progressChanged(MediaHttpUploader uploader) throws IOException {
Log.i(TAG, "upload progress: " + uploader.getUploadState()); // all updates to UI widgets need to be done on the UI thread
}
});`
Now, although the ping call is giving me a successful response, the upload part is giving me an error.
E/Activity file: failed to upload file.
com.kinvey.java.KinveyException:
REASON: No user is currently logged in.
I've searched a lot on this topic, on kinvey's discussion platform and here too. But I'm still stuck. I don't know where I'm going wrong or what I might be missing.
If anyone is out there who has successfully managed to upload images through kinvey then please help me out.
Any kind of Kinvey operations must be provided via a logged user.
You must sign up (or login) before you start to i/o any information.
mKinveyClient.user().create("username", "password", new KinveyUserCallback()) {
#Override
public void onFailure(Throwable t) {
CharSequence text = "Could not sign up.";
Toast.makeText(getApplicationContext(), text, Toast.LENGTH_SHORT).show();
}
#Override
public void onSuccess(User u) {
//here we go on uploading file
}
});
You can find more info about users here
Sharmistha,
Yes, every app action needs an active user context.
So you will need to login in the app and then upload the file.
Please take a look at the following:
http://devcenter.kinvey.com/android/guides/users#ActiveUser
http://devcenter.kinvey.com/android/guides/files#Uploading
Thanks,
Pranav
Kinvey