How to get URL of web-service method in android? - android

I have to write XML to my SD card for that I want to get input-Stream but to establish this how can I get URL when I call any method from android?
For instance I want to download all login details containing 10,000 records when I call it from android that method is called but how to get URL so that I can establish connection and get Input Stream to write to file...Please help me on this below is my code
public void DownloadFiles(){
try {
URL url = new URL("http://192.168.0.10/INIFARM/fieldbook/webservice1.asmx?wsdl");
URLConnection conexion = url.openConnection();
conexion.connect();
int lenghtOfFile = conexion.getContentLength();
InputStream is = url.openStream();
File testDirectory = new File("/data/data/com.example.androidwebservice/");
if (!testDirectory.exists()) {
testDirectory.mkdir();
}
FileOutputStream fos = new FileOutputStream(testDirectory + "/response.xml");
byte data[] = new byte[1024];
int count = 0;
long total = 0;
int progress = 0;
while ((count = is.read(data)) != -1) {
total += count;
int progress_temp = (int) total * 100 / lenghtOfFile;
if (progress_temp % 10 == 0 && progress != progress_temp) {
progress = progress_temp;
}
fos.write(data, 0, count);
}
is.close();
fos.close();
Log.v(TAG, "File is Downloaded Successfully");
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

You mean the URL to call? Your web server admin needs to create a REST API for this and tell you the url so that your app can consume the data by querying this API.

Related

Using decodeByteArray to convert bitmap: Showing a black image and LogCat shows skimagedecoder factory returned null

I am trying to receive an image from a remote server which sends images every 5 seconds. Right now, on the Android side, I am using decodeByteArray() to convert it to a bitmap. When it is running, sometimes it shows an image on the screen, and sometimes it shows a black screen and the LogCat shows the skimagedecoder factory returning null. I don't know what the problem is.
Here is the code I have:
public class connection extends AsyncTask {
#Override
protected Object doInBackground(Object... arg0) {
int i = 0;
try {
clientSocket = new Socket("134.129.125.126", 8080);
input = clientSocket.getInputStream();
} catch (UnknownHostException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
while (true) {
data = new byte[2048 * 2048];
try {
read = input.read(data, 0, data.length);
System.out.println("getInputStream()");
bitmap = BitmapFactory.decodeByteArray(data, 0, read);
System.out.println("deco");
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
System.out.println(e);
}
runOnUiThread(new Runnable() {
public void run() {
image.setImageBitmap(bitmap);
System.out.println("setImage at less than 500");
}
});
}
}
}
Update
Right now, try to receive the size of image from server, and make became right size of byte array. then decodeByteArray(), it become Factory returned Null again. here is my revised code:
public class connection extends AsyncTask {
#Override
protected Object doInBackground(Object... arg0) {
try {
clientSocket = new Socket("134.129.125.126", 8080);
System.out.println("client connect to server");
input = clientSocket.getInputStream();
System.out.println("getinputstream");
} catch (UnknownHostException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
// while (true) {
int totalBytesRead = 0;
int chunkSize = 0;
int tempRead = 0;
String msg = null;
// byte[] data = null;
byte[] tempByte = new byte[1024 * 1024 * 4];
try {
tempRead = input.read(tempByte);
System.out.println("read:" + tempRead);
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
if (tempRead < 2000) {
String message = new String(tempByte, 0, tempRead);
msg = message.substring(0, 6);
System.out.println("message head:" + msg);
byteSize = Integer.parseInt(msg);
System.out.println("ByteSize:" + byteSize);
data = new byte[byteSize];
}
try {
while (chunkSize > -1) {
System.out.println("data length:" + data.length);
chunkSize = input.read(data, totalBytesRead, data.length
- totalBytesRead);
System.out.println("chunkSize is " + chunkSize);
totalBytesRead += chunkSize;
System.out.println("Total byte read " + totalBytesRead);
if (totalBytesRead == data.length) {
if (input.read() != -1) {
// error, the file is larger than our buffer
throw new RuntimeException("Buffer overflow error!");
}
}
}
} catch (Exception e) {
}
bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);
System.out.println("deco");
runOnUiThread(new Runnable() {
public void run() {
image.setImageBitmap(bitmap);
System.out.println("setImage at less than 500");
}
});
return null;
}
}
For one thing, there is no guarantee that your read command is reading the whole image. InputStreams tend to read the number of bytes currently available, which may or may not be until end of file, that is implementation dependent.
You should continue reading into your byte array until the value returned from input.read() is -1. This will obviously require a rework of some of the logic to loop until you get a -1 back and have a variable that tracks total bytes read as the summation of all the read calls.
For example, to read everything out of a stream
int totalBytesRead = 0;
int chunkSize = 0;
byte[] fileBuffer = new byte[4 * 1024 * 1024]; // 4MB buffer
while (chunkSize > -1) {
chunkSize = inputStream.read(fileBuffer, totalBytesRead, fileBuffer.length - totalBytesRead);
totalBytesRead += chunkSize;
if (totalBytesRead == fileBuffer.length) {
if (inputStream.read() != -1) {
// error, the file is larger than our buffer
throw new RuntimeException("Buffer overflow error!");
}
}
}

Does base64 decoding disable search in pdf files?

There is Arabic encoded pdf file that is received from a server via a web service in my Android application, then I decode it and save it to be cashed to open it anytime,this is the file I download_which also is encoded_ the problem is the file became not searchable anymore, this is the code I use to decode the file:
protected Void doInBackground(String... myLink) {
if (conDetector.isConnectingToInternet()) {
File myDir = getFilesDir();
String fileName = PDFCACHE;
File cachedFile = new File(myDir, fileName);
// to check if the cached file in the memory or not
if (cachedFile.exists()) {
try {
readPDFFile();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} else if (!cachedFile.exists()) {
try {
URL url = new URL(myLink[0]);
URLConnection urlConnection = url.openConnection();
urlConnection.connect();
file_size = urlConnection.getContentLength();
source = new BufferedInputStream(url.openStream(), 8192);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
buffer = new byte[1024];
long total = 0;
int count = 0;
// buffer=new
// Scanner(source).useDelimiter("\\A").next().getBytes();*/
// buffer = Base64.decode(buffer, 0);
for (int i; (i = source.read(buffer)) != -1;) {
total += i;
bos.write(buffer, 0, i); // no doubt here is 0
publishProgress(""
+ (int) ((total * 100) / file_size));
}
if (flag == false) {
bytes = bos.toByteArray();
bytes = Base64.decode(bytes, Base64.DEFAULT);
String decodedString = new String(bytes);
if (bytes != null) {
openBuffer(bytes);
if (manipulateCache())
try {
savePDFFile(bytes);
// source.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} else {
core = openFile(decodedString);
}
}
} catch (MalformedURLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
// when there is no internet connection "offline mode"
} else if (!(conDetector.isConnectingToInternet())) {
if (!PDFCACHE.equals(null)) {
try {
readPDFFile();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return null;
} }
The file you received is not searchable, the font objects contain ToUnicode maps claiming most of the glyphs used are numbers, symbols, or Latin characters which does not match their appearance as Arabic characters.
Thus, no standard PDF viewer can be used to search the files.

Android FTP Upload very slow when using BufferedOutputStream

I'm trying to build an Android app to perform upload speed tests using FTP, but with the following code, the upload speed doesn't go above 1 Mbps. While using an FTP client on the same device, I can get upload speeds of 15 Mbps. Can someone give me a help on this?
public class MultiUL extends Thread{
private String id="hhhhh0001";
private int bufferSize=32768;
public void run() {
FTPClient ftp = new FTPClient();
try {
ftp.connect(MPSharkVar.Server,21); // Using port no=21
ftp.login(MPSharkVar.FTPUser, MPSharkVar.FTPPwd);
ftp.setFileType(FTP.BINARY_FILE_TYPE);
ftp.enterLocalPassiveMode();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
uploadWork(ftp, id);
try {
ftp.disconnect();
}
catch (Exception ex)
{
}
}
private void uploadWork(FTPClient ftp, String id) {
byte[] buffer = new byte[bufferSize];
for (int i = 0; i < bufferSize; i++) {
buffer[i] = 'F';
}
OutputStream os = null;
BufferedOutputStream bos = null;
long start = System.currentTimeMillis();
long end = start;
try {
ftp.changeWorkingDirectory("/upload");
os = ftp.storeFileStream(id);
bos = new BufferedOutputStream(os);
start = System.currentTimeMillis();
end = start;
while (((end - start) <= MPSharkVar.TestDur)) {
bos.write(buffer, 0, buffer.length);
end = System.currentTimeMillis();
}
} catch (Exception ex) {
end = System.currentTimeMillis();
} finally {
try {
bos.flush();
bos.close();
os.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}

Android Sockets always timeout

I have this class which connects to a server through sockets, for some reason it is always timing out from here and I can't figure out why, I thought at first it had to do with it being with onCreate(), thats why doit() even exists. any help would be appreciated. here is my code...
public class Ads extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_ads);
doit();
};
public void doit(){
Socket socket = null;
FileOutputStream fos = null;
DataInputStream dis = null;
BufferedOutputStream buf = null;
DataOutputStream dos = null;
try {
socket = new Socket("192.168.1.106", 4447);
Bundle extras = getIntent().getExtras();
String value = extras.getString("keyName");
dos = new DataOutputStream(
new BufferedOutputStream(socket.getOutputStream()));
dis = new DataInputStream(new BufferedInputStream(
socket.getInputStream()));
//dos.writeChars(value);
int numFiles = dis.readInt();
File sdCard = Environment.getExternalStorageDirectory();
File dir = new File (sdCard.getAbsolutePath() +value);
dir.mkdirs();
if (dir.isDirectory()) {
String[] children = dir.list();
for (int i=0; i<children.length; i++) {
new File(dir, children[i]).delete();
}
}
int n = 0;
int fileLength = 0;
for (int i=0;i<numFiles;i++){
File file = new File(dir, String.valueOf(i)+".png");
Log.d("debug tag","created file "+file);
}
for (int i=0;i<numFiles;i++){
fileLength = dis.readInt();
byte[] temp = new byte[(int) fileLength];
String path = sdCard.getAbsolutePath()+value+"/"+i+".png";
buf = new BufferedOutputStream(new FileOutputStream(path));
while ((fileLength > 0) && (n = dis.read(temp, 0, (int) Math.min(temp.length, fileLength))) != -1) {
buf.write(temp,0,n);
buf.flush();
fileLength -= n;
}
//buf.close();
Log.d("debug tag","the file is "+temp.length+" bytes long");
}
// now read in text files
n = 0;
fileLength = 0;
for (int i=0;i<numFiles;i++){
File file = new File(dir, String.valueOf(i)+".txt");
Log.d("debug tag","created file "+file);
}
for (int i=0;i<numFiles;i++){
fileLength = dis.readInt();
byte[] temp = new byte[(int) fileLength];
String path = sdCard.getAbsolutePath()+value+"/"+i+".txt";
buf = new BufferedOutputStream(new FileOutputStream(path));
while ((fileLength > 0) && (n = dis.read(temp, 0, (int) Math.min(temp.length, fileLength))) != -1) {
buf.write(temp,0,n);
buf.flush();
fileLength -= n;
}
//buf.close();
Log.d("debug tag","the text file is "+temp.length+" bytes long");
}
generateListView(sdCard.getAbsoluteFile()+value+"/");
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally{
if (socket != null){
try {
socket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (fos != null){
try {
fos.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (dis != null){
try {
dis.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (dos != null){
try {
dos.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
;
I'm afraid the question lacks some important details (it timeouts when connecting, right?), but my blind guess is that your device is using cellular connection, while 192.168.1.106 is on your WiFi network - IPs in the 192.168.x.x pool are private IP addresses, and obviously you can't connect to any such IP address over Internet.
But there's another serious problem with your code - you're trying to make blocking I/O calls in onCreate() - which is executed in the main thread of the application. You should never do this (actually, as soon as you try it on Android 3.x or higher, you'll get NetworkOnMainThreadException). Network I/O should always happen in another thread, either explicitly, or perhaps using AsyncTask (which runs the background thread for you).
For a good introduction, see this post and Designing for Responsiveness guide.

Android Inputstream.read problem on Gingerbread (while downloading)

I didn't find any question like this here.
Yesterday I finally got Gingerbread 2.3.4 on my Nexus One. When I opened my application (basically loads an XML Feed into a ListView) again, it got stuck while downloading.
It seems that InputStream stream; -> stream.read(buffer); doesn't return -1 any more, when it's finished.
The Code ist nearly the same from here Download Progress
Here's my code:
public InputStream getInputStreamFromURL(String urlString, DownloadProgressCallback callback)
throws IOException, IllegalArgumentException
{
InputStream in = null;
conn = (HttpURLConnection) new URL(urlString).openConnection();
fileSize = conn.getContentLength();
out = new ByteArrayOutputStream((int) fileSize);
conn.connect();
stream = conn.getInputStream();
// loop with step 1kb
while (status == DOWNLOADING) {
byte buffer[];
if (fileSize - downloaded > MAX_BUFFER_SIZE) {
buffer = new byte[MAX_BUFFER_SIZE];
} else {
buffer = new byte[(int) (fileSize - downloaded)];
}
int read = stream.read(buffer);
if (read == -1) {
break;
}
// writing to buffer
out.write(buffer, 0, read);
downloaded += read;
// update progress bar
callback.progressUpdate((int) ((downloaded / fileSize) * 100));
}// end of while
if (status == DOWNLOADING) {
status = COMPLETE;
}
in= (InputStream) new ByteArrayInputStream(out.toByteArray());
// end of class DownloadImageTask()
return in;
}
The problem basically is that when the download finishes, stream.read(buffer) returns 0 instead of -1. When I change
if (read == -1) {
break;
}
to 0 or
if (fileSize == downloaded) {
break;
}
I get ParseExceptions (ExpatParser) on my MainActivity.
On 2.2 it runs really perfect.
I cleared the app cache and tried a few other things already, but I'm really stuck now.
I hope that someone can help me. :)
UPDATE:
That's awesome, you're the man, Guillaume. :)
Thank you very much, that saved my evening! :)
Your Code for my needs here:
public InputStream getStreamFromURL(String urlString, DownloadProgressCallback callback){
// initialize some timeouts
HttpParams httpParameters = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParameters,3000);
// create the connection
URL url;
try {
url = new URL(urlString);
URLConnection connection = url.openConnection();
HttpURLConnection httpConnection = (HttpURLConnection) connection;
// connection accepted
if(httpConnection.getResponseCode() == HttpURLConnection.HTTP_OK) {
int size = connection.getContentLength();
int index = 0;
int current = 0;
InputStream input = connection.getInputStream();
BufferedInputStream buffer = new BufferedInputStream(input);
byte[] bBuffer = new byte[1024];
out = new ByteArrayOutputStream((int) size);
while((current = buffer.read(bBuffer)) != -1) {
out.write(bBuffer, 0, current);
index += current;
callback.progressUpdate((index/size)*100);
}
out.close();
}
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return (InputStream) new ByteArrayInputStream(out.toByteArray());
}
This code work on my 2.3.4 Nexus One :
try {
// initialize some timeouts
HttpParams httpParameters = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParameters, 3000);
// create the connection
URL url = new URL(toDownload);
URLConnection connection = url.openConnection();
HttpURLConnection httpConnection = (HttpURLConnection) connection;
// connection accepted
if (httpConnection.getResponseCode() == HttpURLConnection.HTTP_OK) {
try {
file = new File(destination);
// delete the file if exists
file.delete();
} catch (Exception e) {
// nothing
}
int size = connection.getContentLength();
int index = 0;
int current = 0;
try {
file = new File(destination);
file.delete();
FileOutputStream output = new FileOutputStream(file);
InputStream input = connection.getInputStream();
BufferedInputStream buffer = new BufferedInputStream(input);
byte[] bBuffer = new byte[10240];
while ((current = buffer.read(bBuffer)) != -1) {
if (isCancelled()) {
file.delete();
break;
}
try {
output.write(bBuffer, 0, current);
} catch (IOException e) {
e.printStackTrace();
}
index += current;
publishProgress(index / (size / 100));
}
output.close();
} catch (SecurityException se) {
se.printStackTrace();
return 1;
} catch (FileNotFoundException e) {
e.printStackTrace();
return 1;
} catch (Exception e) {
e.printStackTrace();
return 2;
}
return 0;
}
// connection refused
return 2;
} catch (IOException e) {
return 2;
}

Categories

Resources