I'm new to Android and I want to copy a big file (approx. 2GB) chosen by the user(so I guess it should have permissions by default) to the internal memory. I already have the permissions added in AndroidManifest but I don't know how (and if I need to) use the Android FileProivder. I would also like to know how this process can happen on another thread such that the app is not blocked during the process and it can show the progress.
You could use a foreground service to do this and make sure the process doesn't get interrupted.
Build the service:
public class CopyService extends Service {
#Override
public void onCreate() {
}
#Override
public int onStartCommand(final Intent intent, int flags, int startId) {
// Run the moving code here
return START_NOT_STICKY;
}
}
It's important that you launch it as a foreground service (add permission in manifest), so it doesn't get destroyed after some time. You'll be required to add a notification then, which you can use for progress.
Read further on services: https://developer.android.com/guide/components/services
As #blackapps pointed out it would be wise decision to check the permission and only start the service if it's granted. I usually check if the permission is granted, if not I request it, if it is I follow. Then I check for it once again so I can see if the user granted it or not.
Google has a great article on how to request permissions:
https://developer.android.com/training/permissions/requesting
How to move the file though? Here is the code I use in my own app:
private static void moveFile(File from, File to) {
InputStream inputStream;
OutputStream outputStream;
try {
inputStream = new FileInputStream(from);
outputStream = new FileOutputStream(to);
byte[] buffer = new byte[1024];
while (inputStream.read(buffer) > 0) {
outputStream.write(buffer);
}
inputStream.close();
outputStream.close();
// You may wish not to do this if you want to keep the original file
from.delete();
Log.i(LOG_TAG, "File copied successfully");
} catch (IOException e) {
e.printStackTrace();
}
// Stop service here
}
The code you'd like to run inside the service should be placed inside onStartCommand()
I have tried so many way but i can't succeed. I haven't found any source code examples for Android(about rekognition)
there's a source code in JAVA in the Developer Guide but i cannot implement that even though I tried TT
I try to detect faces by sending an image file from an external storage(from the emulator)
I don't know what i did wrong(I'm not good at coding)
Here is my code
AmazonRekognitionClient amazonRekognitionClient;
Image getAmazonRekognitionImage;
DetectFacesRequest detectFaceRequest;
DetectFacesResult detectFaceResult;
File file = new File(Environment.getExternalStorageDirectory(),"sungyeol.jpg.jpg");
public void test_00(View view) {
ByteBuffer imageBytes;
try{
InputStream inputStream = new FileInputStream(file.getAbsolutePath().toString());
imageBytes = ByteBuffer.wrap(IOUtils.toByteArray(inputStream));
Log.e("InputStream: ",""+inputStream);
Log.e("imageBytes: ","");
getAmazonRekognitionImage.withBytes(imageBytes);
// Initialize the Amazon Cognito credentials provider
CognitoCachingCredentialsProvider credentialsProvider = new CognitoCachingCredentialsProvider(
getApplicationContext(),
"us-east-2:.......", // Identity Pool ID
Regions.US_EAST_2 // Region
);
//I want "ALL" attributes
amazonRekognitionClient = new AmazonRekognitionClient(credentialsProvider);
detectFaceRequest = new DetectFacesRequest()
.withAttributes(Attribute.ALL.toString())
.withImage(getAmazonRekognitionImage);
detectFaceResult = amazonRekognitionClient.detectFaces(detectFaceRequest);
detectFaceResult.getFaceDetails();
}
catch(Exception ex){
Log.e("Error on something:","Message:"+ex.getMessage());
}
and here is my errors
02-04 09:30:07.268 29405-29405/? E/InputStream:: java.io.FileInputStream#a9b23e7
02-04 09:30:07.271 29405-29405/? E/Error on something:: Message:Attempt to invoke virtual method 'com.amazonaws.services.rekognition.model.Image com.amazonaws.services.rekognition.model.Image.withBytes(java.nio.ByteBuffer)' on a null object reference
what is a null object reference?
i try to change the file path but he said no such file ... and when I change to this path, there's errors above.
by the way I've already asked a user for a permission to access a folder from Emulator in Android
please help me
PS. sorry for my bad English
Thank you in advance.
Now I am ok with the issues. I have been through many many things <3 <3 <3.
Thank you
I'm Thai and I had to try harder to find the solutions because there's lack of information in the particular language. Here are my solutions.
My solutions are:
0.There is an endpoint for setting for the Rekognition-->
http://docs.aws.amazon.com/general/latest/gr/rande.html#rekognition_region
1.On a "null object reference issue" I found that I have to create a new object first such as "Image image = new Image();" <-- The "new" command creates an object instance in that class
2.After the above error, there are more errors (Errors on NetworkOnMainThreadException), so I tried everything until I found this page -->
https://docs.aws.amazon.com/cognito/latest/developerguide/getting-credentials.html the page said that ...
Consequently, I looked up for more information about the AsyncTask and after that I created an AsyncTask class and then I move all my code about the initialize, the request, the response to the AsyncTask class. ตอนรันตอนท้ายๆน้ำตาจิไหล my code worked... TT and by the conclusion the sungyeol.jpg.jpg file worked
for example
private void testTask(){
.... all code in the main thread particularly on the requests and responses
from the services
//print the response or the result
//Log.e() makes the message in the android monitor red like an error
Log.e("Response:", [responseparameter.toString()]);
}
//create the inherited class from the AsyncTask Class
//(you can create within your activity class)
class AsyncTaskRunner extends AsyncTask<String,String,String>{
#Override
public String doInBackground(String ... input){
testTask(); // call the testTask() method that i have created
return null; // this override method must return String
}
}
//I've created a button for running the task
public void buttonTask(View view){
AsyncTaskRunner runner = new AsyncTaskRunner();
runner.execute();
}
for more information about the AsyncTask:
https://developer.android.com/training/basics/network-ops/connecting.html#AsyncTask
http://www.compiletimeerror.com/2013/01/why-and-how-to-use-asynctask.html#.WJdkqVOLTIU
I hope these help :)
I get some JSON data which contains some food menu items
Please note: this is just a sample, there are more than 2 images sometimes and many more menu items in the array!
{
"menu": [
{
"url": "/api/v1/menu/1",
"name": "Best Food",
"description": "really nice food",
"opening_time": "every day from 9am to 6pm",
"contact_email": "info#food.com",
"tel_number": "+54 911 3429 5762",
"website": "http://bestfood.com",
"images": [
{
"url": "https://blahblah/image1.jpg"
},
{
"url": "https://blahblah/image2.jpg"
}
]
},
]
}
Each item has some info and an array of image URLs.
I am using the Glide image library to process these images and Retrofit 2.0 to download the JSON data from the endpoint. All is well at this point.
However, I need to store this downloaded data for offline access.
Currently, I am using ORM Lite on my existing models to store all the JSON data in a database. This part is OK.
However, in my database I only store the image URLs as I was told that it is not good approach to store images (as blob) in the database.
So there is a section in my app to view the saved menu's with an option to download it for offline access if the user chooses to.
It is worth mentioning at this point, that I already have the raw menu information in the database because the user would have to view the menu in the first place to get it in DB.
But the problem is the images.
This is where I do not know how to proceed, but I list the solutions and problems that I am thinking about and was hoping people could advise me on what is the best course of action is.
Use a service to download the images. This I feel is mandatory because I do not know how many images there will be, and I want the download to proceed even if user exits the app
Glide has a download only option for images and you can configure where its cache is located (internal private or external public) as I read here and here. Problem is I do not feel comfortable with setting the cache size as I do not know what is required. I would like to set unlimited.
I need to be able to delete the saved menu data especially if its saved on the external public directory as this is not removed when the app is deleted etc. or if the user chooses to delete a saved menu from within the app. I was thinking I could store the file image URIs or location of the entire saved menu in database for this but not sure if this is a good way
I read in different sources and answers that in this use case for just caching images to SD card etc. that I should specifically use a network library to do so to avoid the allocation of a bitmap to heap memory. I am using OK HTTP in my app at the moment.
I'm using ormlite to store objects with urls too, I have a synchronization after the "sign in" screen on my app, on my experience I really recommend this library https://github.com/thest1/LazyList
It's very simple:
ImageLoader imageLoader=new ImageLoader(context);
imageLoader.DisplayImage(url, imageView);
This library saves the image using the url on the external sd with basic and simple configuration about the memory issues, so if you actually have two or more items with the same url this library works perfectly, the url and imageView are the parameters, if the image is not on the phone begins a new task and put the image in the view when the download is finish, and btw this library also saves the images encoded, so these pictures don't appear on the gallery.
Actually you only need these files to implement the library:https://github.com/thest1/LazyList/tree/master/src/com/fedorvlasov/lazylist
If you wanna manipulate some files, you can change the folder name in the FileCache class:
public FileCache(Context context){
//Find the dir to save cached images
...
cacheDir=new File(android.os.Environment.getExternalStorageDirectory(),"LazyList");
...
}
Where "LazyList" is the folder name, and them you can delete, move, etc.
Delete sample:
/**
* This method delete a file if exist
*/
public static void deleteFile(File file){
if(file!=null && file.exists()) {
file.delete();
}
}
Now I learned more about memory cache and the allocation of a bitmap to heap memory, for the first time manipulating images online and offline, I recommend this library, also when you learn more about it, you can implement and edit the library to your needs.
1: Use an IntentService to do your downloads.
http://developer.android.com/reference/android/app/IntentService.html
2: Set up your IntentService using AlarmManager so that it runs even if the
application is not running. You register with the AlarmManager
http://developer.android.com/reference/android/app/AlarmManager.html
There are a variety of ways you can have the AlarmManager start your
intent.
For Example:
// Register first run and then interval for repeated cycles.
alarmManager.setInexactRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP,
SystemClock.elapsedRealtime() + DEFAULT_INITIAL_RUN,
DEFAULT_RUN_INTERVAL, pi);
3: Storing Data
There are several options here depending on how public you want your
pictures/data to be.
http://developer.android.com/reference/android/os/Environment.html
Example: External Public Storage
File dirBackup = Environment.getExternalStoragePublicDirectory(
"YourDirectory" );
4: Downloading
Your option here. You can using anything from your current API to a
basic URLConnection.
You may want to look at:
http://developer.android.com/reference/android/app/DownloadManager.html
Also, watch your permissions you will need to add
and
Hope this points you in a useful direction.
Try out this library to manage images loading.
Use a service to download the images. This I feel is mandatory because
I do not know how many images there will be, and I want the download
to proceed even if user exits the app
All downloading done in worker threads so it's alive while application process is alive. There may a problem appear: application dies while loading is in progress. To workaround this I suggest to use AlarmManager in combination with Service. Set it up to start by timer, check you database or UIL cache for image files being not loaded and start their loading again.
Glide has a download only option for images and you can configure
where its cache is located (internal private or external public) as I
read here and here. Problem is I do not feel comfortable with setting
the cache size as I do not know what is required. I would like to set
unlimited.
UIL has several disc cache implementations out of the box including unlimited one. It also provides you cache interface so you can implement your own.
I need to be able to delete the saved menu data especially if its
saved on the external public directory as this is not removed when the
app is deleted etc. or if the user chooses to delete a saved menu from
within the app. I was thinking I could store the file image URIs or
location of the entire saved menu in database for this but not sure if
this is a good way
UIL generates unique filename for each loaded file using provided file link. You can delete any loaded image or cancel any download using link from your JSON.
I read in different sources and answers that in this use case for just
caching images to SD card etc. that I should specifically use a
network library to do so to avoid the allocation of a bitmap to heap
memory. I am using OK HTTP in my app at the moment.
UIL does it OK. It manages memory very accurately also provide you several options for memory management configuration. For example you can choose between several memory cache implementations out of the box.
In conclusion I suggest you to the visit the link above and read library documentation/description by yourself. It's very flexible and contatins lots of useful features.
Using a service can be a good option if you want the downloads to continue even if the user exits. Images that are stored in directories created using getExternalStorageDirectory() are automatically deleted when your app is uninstalled. Moreover you can check if the internal memory is large enough to store images. If you use this methods these images will be deleted upon the uninstallion of the app.
I use this class when downloading images, it caches the images, next time you will be downloading them it will just load from external memory, it manages the cache for you as well so you wont have to worry about setting cache to limited or unlimited, pretty efficient and fast.
public class ImageLoader {
MemoryCache memoryCache = new MemoryCache();
FileCache fileCache;
private Map<ImageView, String> imageViews = Collections
.synchronizedMap(new WeakHashMap<ImageView, String>());
ExecutorService executorService;
// Handler to display images in UI thread
Handler handler = new Handler();
public ImageLoader(Context context) {
fileCache = new FileCache(context);
executorService = Executors.newFixedThreadPool(5);
}
final int stub_id = R.drawable.placeholder;
public void DisplayImage(String url, ImageView imageView) {
imageViews.put(imageView, url);
Bitmap bitmap = memoryCache.get(url);
if (bitmap != null)
imageView.setImageBitmap(bitmap);
else {
queuePhoto(url, imageView);
imageView.setImageResource(stub_id);
}
}
private void queuePhoto(String url, ImageView imageView) {
PhotoToLoad p = new PhotoToLoad(url, imageView);
executorService.submit(new PhotosLoader(p));
}
private Bitmap getBitmap(String url) {
File f = fileCache.getFile(url);
Bitmap b = decodeFile(f);
if (b != null)
return b;
// Download Images from the Internet
try {
Bitmap bitmap = null;
URL imageUrl = new URL(url);
HttpURLConnection conn = (HttpURLConnection) imageUrl
.openConnection();
conn.setConnectTimeout(30000);
conn.setReadTimeout(30000);
conn.setInstanceFollowRedirects(true);
InputStream is = conn.getInputStream();
OutputStream os = new FileOutputStream(f);
Utils.CopyStream(is, os);
os.close();
conn.disconnect();
bitmap = decodeFile(f);
return bitmap;
} catch (Throwable ex) {
ex.printStackTrace();
if (ex instanceof OutOfMemoryError)
memoryCache.clear();
return null;
}
}
// Decodes image and scales it to reduce memory consumption
private Bitmap decodeFile(File f) {
try {
// Decode image size
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
FileInputStream stream1 = new FileInputStream(f);
BitmapFactory.decodeStream(stream1, null, o);
stream1.close();
// Find the correct scale value. It should be the power of 2.
// Recommended Size 512
final int REQUIRED_SIZE = 70;
int width_tmp = o.outWidth, height_tmp = o.outHeight;
int scale = 1;
while (true) {
if (width_tmp / 2 < REQUIRED_SIZE
|| height_tmp / 2 < REQUIRED_SIZE)
break;
width_tmp /= 2;
height_tmp /= 2;
scale *= 2;
}
// Decode with inSampleSize
BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inSampleSize = scale;
FileInputStream stream2 = new FileInputStream(f);
Bitmap bitmap = BitmapFactory.decodeStream(stream2, null, o2);
stream2.close();
return bitmap;
} catch (FileNotFoundException e) {
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
// Task for the queue
private class PhotoToLoad {
public String url;
public ImageView imageView;
public PhotoToLoad(String u, ImageView i) {
url = u;
imageView = i;
}
}
class PhotosLoader implements Runnable {
PhotoToLoad photoToLoad;
PhotosLoader(PhotoToLoad photoToLoad) {
this.photoToLoad = photoToLoad;
}
#Override
public void run() {
try {
if (imageViewReused(photoToLoad))
return;
Bitmap bmp = getBitmap(photoToLoad.url);
memoryCache.put(photoToLoad.url, bmp);
if (imageViewReused(photoToLoad))
return;
BitmapDisplayer bd = new BitmapDisplayer(bmp, photoToLoad);
handler.post(bd);
} catch (Throwable th) {
th.printStackTrace();
}
}
}
boolean imageViewReused(PhotoToLoad photoToLoad) {
String tag = imageViews.get(photoToLoad.imageView);
if (tag == null || !tag.equals(photoToLoad.url))
return true;
return false;
}
// Used to display bitmap in the UI thread
class BitmapDisplayer implements Runnable {
Bitmap bitmap;
PhotoToLoad photoToLoad;
public BitmapDisplayer(Bitmap b, PhotoToLoad p) {
bitmap = b;
photoToLoad = p;
}
public void run() {
if (imageViewReused(photoToLoad))
return;
if (bitmap != null)
photoToLoad.imageView.setImageBitmap(bitmap);
else
photoToLoad.imageView.setImageResource(stub_id);
}
}
public void clearCache() {
memoryCache.clear();
fileCache.clear();
}
}
To use it Just create an instance of it like
ImageLoader Imageloaer = new ImageLoader(getBaseContext());
Imageloaer.DisplayImage(imageUrl, imageView);
You should try downloading with this,
class DownloadFile extends AsyncTask<String,Integer,Long> {
ProgressDialog mProgressDialog = new ProgressDialog(MainActivity.this);// Change Mainactivity.this with your activity name.
String strFolderName;
#Override
protected void onPreExecute() {
super.onPreExecute();
mProgressDialog.setMessage("Downloading Image ...");
mProgressDialog.setIndeterminate(false);
mProgressDialog.setMax(100);
mProgressDialog.setCancelable(false);
mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
mProgressDialog.show();
}
#Override
protected Long doInBackground(String... aurl) {
int count;
try {
URL url = new URL((String) aurl[0]);
URLConnection conexion = url.openConnection();
conexion.connect();
String targetFileName="downloadedimage.jpg";//Change name and subname
int lenghtOfFile = conexion.getContentLength();
String PATH = Environment.getExternalStorageDirectory()+"/myImage/";
File folder = new File(PATH);
if(!folder.exists()){
folder.mkdir();//If there is no folder it will be created.
}
InputStream input = new BufferedInputStream(url.openStream());
OutputStream output = new FileOutputStream(PATH+targetFileName);
byte data[] = new byte[1024];
long total = 0;
while ((count = input.read(data)) != -1) {
total += count;
publishProgress ((int)(total*100/lenghtOfFile));
output.write(data, 0, count);
}
output.flush();
output.close();
input.close();
} catch (Exception e) {}
return null;
}
protected void onProgressUpdate(Integer... progress) {
mProgressDialog.setProgress(progress[0]);
if(mProgressDialog.getProgress()==mProgressDialog.getMax()){
mProgressDialog.dismiss();
Toast.makeText(getApplicationContext(), "Download Completed !", Toast.LENGTH_LONG).show();
}
}
protected void onPostExecute(String result) {
}
}
This code will let you to download all the url of images,
new DownloadFile().execute("https://i.stack.imgur.com/w4kCo.jpg");
.....
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
Change Folder Name as you desired and try to set this images to app bitmap and also avoiding rotate error of images by using this.
The important things to think about here is
Thread , Service ,File , Json, Context,Receiver & if else & for
maybe i did not understand your question but this is not a big deal sir,
your programm your app to work in way where your app starts when the os broadcast onBootCompleted, then create a Thread where you are going to do a lot of code - getting your json file-(when you need it), since its an array you get your jsonObject images, whether its a thousand or million you just iterate it and use any approach to download it, i'd say use the traditional way of downloading your images so as you better control it.
With the help of File class you save it alongside Context you can get your app's cache's directory, which is an internal memory save it there and create a column in your database where you can save the path to the file in your database as String.
When your app start in onPrepareOptionsMenu() check if your app's cache's directory is empty-if not you have some files, now since you have every file and its respective path you can check if it exists with File.exist() if it does no need to download.
if you need pace you can always create new Threads. The Reciever was to be the guy who gets notified when your device boots, if else for a lot of logic checking, for for your loopings, Service to be able to do long running work and have a way to communicate between the UI and background thread.
sorry for the last paragraph i was just trying to buy space :)
I'm trying to connect to .NET 4.0 webservice I created for receiving SOAP-calls from Android-devices, now hosted on local IIS for testing purposes.
I found out that ksoap2 would be an excellent class library for doing what i want to do. Downloaded the .jar package from https://code.google.com/p/ksoap2-android/ and started pounding the keyboard in ecstacy... with my fingers.
The amount of information being sent is from few kilobytes to few megabytes.
What is working
HttpTransportSE.call(String, SoapSerializationEnvelope)-method works perfectly while still in Eclipse's Android emulator, sending the call to webservice hosted in local IIS. Even tested that the webservice receives empty calls from trying to open the service address from a web browser in the same local area network.
What doesn't work
When I copy the .apk-file to an Android device, install it, start it and trying to make the call, the whole program freezes without making the call.
As you can see from a code block presented some lines after that possible errors are being taken into account: In emulated environment a successful call returns a SoapPrimitive-object or flows into the correct catch block generating an error message for the user according to the current situation.
Then on live Android device, program loses it's responsivity forever and has to be terminated from application menu.
What have i tried
I removed the call from the asynchronous method, and tried calling it straight from an anonymous inner function assigned for a button click-event.
Tried not trying to get a response, just making the call.
Tried getting a logcat-program for the device to see what's happening behind the UI, found two, they needed root access, which i don't have in the device. This is why i don't have any logcats to show you, and showing the emulator logcat would probably(?) be useless because it works fine there.
Not trying to connect to localhost.
Tried installing the program on older Lenovo-tablet running Android 4.2.2 and on brand new Samsung Galaxy Tab, both would have the same problem while otherwise working well.
The code
Here's the asynchronous method for making the call in device/emulator, where variables str_URL and soapRequest are a correct service address (checked) and a well formed SoapObject respectively:
#Override
protected WebServiceResult doInBackground(Void... v) {
WebServiceResult _ret;
SoapSerializationEnvelope soapEnvelope= new SoapSerializationEnvelope(SoapEnvelope.VER11);
soapEnvelope.dotNet=true;
soapEnvelope.setAddAdornments(false);
soapEnvelope.setOutputSoapObject(soapRequest);
HttpTransportSE conn = new HttpTransportSE(str_URL);
conn.setXmlVersionTag("<?xml version=\"1.0\" encoding=\"utf-8\"?>");
conn.debug = true;
try {
conn.call(str_ACTION, soapEnvelope);
SoapObject o = (SoapObject)soapEnvelope.getResponse();
_ret = new WebServiceResult(o, WebServiceResultEnum.ok);
} catch (NetworkOnMainThreadException e) {
_ret = new WebServiceResult(null, WebServiceResultEnum.keskeytys);
} catch (HttpResponseException e) {
_ret = new WebServiceResult(null, WebServiceResultEnum.httpVirhe);
} catch (XmlPullParserException e) {
_ret = new WebServiceResult(null, WebServiceResultEnum.vaara_muoto);
} catch (SocketTimeoutException e) {
_ret = new WebServiceResult(null, WebServiceResultEnum.aikakatkaisu);
} catch (Exception e) {
_ret = new WebServiceResult(null, WebServiceResultEnum.keskeytys);
}
return _ret;
}
Thank you in advance!
Is it possible you are doing something like this:
YourAsyncTask task = new YourAsyncTask();
WebServiceResult result = task.doInBackground();
Because that would be wrong, completely wrong. If you call doInBackground() directly it will run in the same Thread and not in a new one. You need to start the AsyncTask with execute() like this:
YourAsyncTask task = new YourAsyncTask();
task.execute();
You need to implement the AsyncTask like this:
public class ExampleTask extends AsyncTask<Void, Void, WebServiceResult> {
public interface FinishedListener {
public void onFinished(WebServiceResult result);
}
private final FinishedListener finishedListener;
public ExampleTask(FinishedListener listener) {
this.finishedListener = listener;
}
#Override
protected WebServiceResult doInBackground(Void... params) {
WebServiceResult result = ...;
return result;
}
#Override
protected void onPostExecute(WebServiceResult result) {
super.onPostExecute(result);
if(this.finishedListener != null) {
this.finishedListener.onFinished(result);
}
}
}
And if you implemented it that way you can use it like this:
ExampleTask task = new ExampleTask(new ExampleTask.FinishedListener() {
#Override
public void onFinished(WebServiceResult result) {
// This will be called if the task has finished
}
});
task.execute();
It seems that I had declared the minimum SDK as 14 and target SDK as 17 in AndroidManifest.xml. I didn't use any fancy things in newer sdk's so i lowered the target SDK to the same level as minimum SDK, 14. I also had an Avast! Antivirus service running on the tablet which i removed.
This solved my problem. It could be that probably the Avast! antivirus-program wanted to block all communications from applications not downloaded from Play-store. I don't know if changing the target SDK had much effect really.
Well, I had the same question as you. When it goes to the method transport.call, it pauses, and for a while, it throws a timeout problem. At first, I thought maybe the network was poor, but the server logcat shows it is not the problem. The request was fine and the response was good. My business process is like below:
First, I get a list from the server through ksoap inner a child thread, then cycle the list, send a ksoap request based on every item of the list. It means it will send another list.size() request. When debugging in a real device the above problems occured. I solved it by starting a new child thread after getting the list and making all the list.size requests in the new child thread. So, ksoap use in android may cause thread block which leads to ioexception. So when you put it in a new thread, it escapes from the parent catch exception and works fine.
I am trying to send information to my company's server. Basically when I enter a URL pointing to it and connect to it in a browser, it takes parameters contained in the URL and puts them in a database. Again when done in a browser, it works. However, I would like to be able to send this information every time an event of importance (like scanning a qr code in our app) happens, and I want it to be done in the background (without the user knowing.)
We have tried ConnectionFactory, HTTPRequests etc etc, nothing has worked for us so far.
I am sure there is a simple way to go about this.
Can anyone provide us with the few elusive lines of code to help us do what we want to do??
Thanks alot!
Edit:
Okay here is some code we tried using (one of many code snippets) but it did not work:
public class ConnectionThread extends Thread{
String URL;
public ConnectionThread(String URL) {
this.URL = URL;
}
public void run() {
ServerCalls sc = new ServerCalls(); // This is for generating the URL
ConnectionFactory connFact = new ConnectionFactory();
ConnectionDescriptor connDesc;
connDesc = connFact.getConnection(sc.fillParameters(URL));
if (connDesc != null)
{
HttpConnection httpConn;
httpConn = (HttpConnection)connDesc.getConnection();
}
}
}
and we call
new ConnectionThread(barcode).start()
when we need it to send the info to the server.
For opening the url you can use
javax.microedition.io.HttpConnection Package.
And here is the code how to go about that....
HttpConnection connection=(HttpConnection) Connector.open(your url+";deviceside=true");
if(connection.getResponseCode()==HttpConnection.HTTP_OK) {
write your code, Which you want to get from url or any thing you want
}else{
UiApplication.getUiApplication().invokeLater(new Runnable() {
public void run() {
Dialog.inform("connection error");
}
});
}
This may help you :)