sending data to server from text file using a service - android

I am sending data from text file to server using service code given below. It sends data line by line to server. I want the service to run in background continuously.For this I have written asyncTask. But it sends all data once and then stops.
public class BackgroundService extends Service
{
private static final String TAG = "BackgroundService";
String line=null;
Context mContext = null;
File file;RandomAccessFile in = null;
StringEntity se ;
HttpEntity entity=null;
final static int SERVICE_NAME = 1;
int WORK_TYPE;
public BackgroundService()
{
//super(TAG);
}
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(),"in BackgroundService", Toast.LENGTH_LONG).show();
mContext = getBaseContext();
WORK_TYPE = 2;
new BackgroundTask(mContext).execute();
return super.onStartCommand(intent, flags, startId);
}
public class BackgroundTask extends AsyncTask<String, String, Void>
{
Context mContext = null;String response;
public BackgroundTask(Context context)
{
mContext = context;
}
protected void onPreExecute()
{
Toast.makeText(getApplicationContext(),"1", Toast.LENGTH_LONG).show();
}
protected Void doInBackground(final String... args)
{
switch (WORK_TYPE)
{
case 2:
File file = new File(Environment.getExternalStorageDirectory(),"/BPCLTracker/gpsdata.txt");
int i=0;
RandomAccessFile in = null;
try {
in = new RandomAccessFile(file, "rw");
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
while ((line = in.readLine()) != null)
{
String input = line.toString();
response = sendDataToServer(input);
// JsonUtils.parseServerData(response, hashMapObj);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
break;
}//switch
return null;
}//doInBackground
protected void onPostExecute(final Void unused)
{
Toast.makeText(getApplicationContext(),"3", Toast.LENGTH_LONG).show();
switch (WORK_TYPE)
{
case 2:
if (!"".equalsIgnoreCase(response) && response != null)
{
//DeviceUtils.deviceRegistration(hashMapObj, mContext);
callService(1);
}
try {
if((line = in.readLine()) == null && entity!=null)
{
file.delete();
new BackgroundTask(mContext).execute();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
break;
}
}
}
public void callService(int work)
{
WORK_TYPE = work;
new BackgroundTask(mContext).execute();
}
public String sendDataToServer(String data)
{
StringBuffer sb = new StringBuffer("");
String serverUrl = "http://67.23.166.35:80/android/insert.php" ;
try
{
URL url = new URL(serverUrl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setConnectTimeout(6 * 10 * 1000);
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
conn.setRequestMethod("POST");
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
wr.write(data);
wr.flush();
// Get the response
BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line = "";
while ((line = rd.readLine()) != null)
{
// Process line...
sb.append(line);
}
wr.close();
rd.close();
return sb.toString();
}
catch (Exception e)
{
Log.d("Exception : ", e.getStackTrace().toString());
}
return sb.toString();
}
}
Thank you

I have Modify your code:
Check my all code this ll give you idea about send line one by one. Please do rest of logic this way. i have also remove some method.
This is not all code but it ll give you IDEA.
package com.example.getjson;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.RandomAccessFile;
import java.net.HttpURLConnection;
import java.net.URL;
import org.apache.http.HttpEntity;
import org.apache.http.entity.StringEntity;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Environment;
import android.os.IBinder;
import android.util.Log;
import android.widget.Toast;
public class backservice extends Service {
private static final String TAG = "BackgroundService";
String line = null;
Context mContext = null;
File file;
RandomAccessFile in = null;
StringEntity se;
HttpEntity entity = null;
final static int SERVICE_NAME = 1;
int WORK_TYPE;
String response;
String input = "";
public backservice() {
// super(TAG);
}
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(), "in BackgroundService",
Toast.LENGTH_LONG).show();
mContext = getBaseContext();
WORK_TYPE = 2;
// new BackgroundTask(mContext).execute();
switch (WORK_TYPE) {
case 2:
File file = new File(Environment.getExternalStorageDirectory(),
"/BPCLTracker/gpsdata.txt");
int i = 0;
RandomAccessFile in = null;
try {
in = new RandomAccessFile(file, "rw");
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
while ((line = in.readLine()) != null) {
input = line.toString();
// response = sendDataToServer(input);
new BackgroundTask(mContext).execute();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
break;
}
return super.onStartCommand(intent, flags, startId);
}
public class BackgroundTask extends AsyncTask<String, String, Void> {
Context mContext = null;
public BackgroundTask(Context context) {
mContext = context;
}
protected void onPreExecute() {
Toast.makeText(getApplicationContext(), "1", Toast.LENGTH_LONG)
.show();
}
protected Void doInBackground(final String... args) {
response = sendDataToServer(input);
return null;
}
protected void onPostExecute(final Void unused) {
}
}
public void callService(int work) {
WORK_TYPE = work;
new BackgroundTask(mContext).execute();
}
public String sendDataToServer(String data) {
StringBuffer sb = new StringBuffer("");
String serverUrl = "http://67.23.166.35:80/android/insert.php";
try {
URL url = new URL(serverUrl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setConnectTimeout(6 * 10 * 1000);
conn.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded;charset=UTF-8");
conn.setRequestMethod("POST");
OutputStreamWriter wr = new OutputStreamWriter(
conn.getOutputStream());
wr.write(data);
wr.flush();
// Get the response
BufferedReader rd = new BufferedReader(new InputStreamReader(
conn.getInputStream()));
String line = "";
while ((line = rd.readLine()) != null) {
// Process line...
sb.append(line);
}
wr.close();
rd.close();
return sb.toString();
} catch (Exception e) {
Log.d("Exception : ", e.getStackTrace().toString());
}
return sb.toString();
}
}

Related

Android - Call Thread synchronized on UI thread

I try to create synchronized threads, but I always get the following error: android.os.NetworkOnMainThreadException.
I've read more posts, but they don't work for me.
Below I write the code blocks that do not work for me:
1.
final SyncApp syncJob = new SyncApp();
Thread t = new Thread (new Runnable () {
                         #Override
                         public void run () {
                             synchronized (syncJob) {
                                 String s = syncJob.insert (newJobs, GlobalVariables.URL_LOCALHOST + "jobs");
                                 txtState.setText (s);
                             }}});
                         }
                     });
                     t.Start ();
// t.run ();
2.
myClass.runOnUiThread(new Runnable() {
public void run() {...}
})
3.
Running code in main thread from another thread
SyncApp:
public class SyncApp {
synchronized public String insert(List<Jobs> job, String... params) {
URL url = null;
HttpURLConnection conn = null;
try {
url = new URL(params[0]);
conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/json");
conn.setDoInput(true);
conn.setDoOutput(true);
String str = new Gson().toJson(job);
byte[] outputInBytes = str.getBytes();
OutputStream os = conn.getOutputStream();
os.write( outputInBytes );
os.flush();
int responseCode=conn.getResponseCode();
String response = null;
if (responseCode == HttpsURLConnection.HTTP_OK) {
String line;
BufferedReader br=new BufferedReader(new InputStreamReader(conn.getInputStream()));
while ((line=br.readLine()) != null) {
response+=line;
}
}
else {
response=conn.getResponseMessage();
}
return response;
} catch (Exception e) {
e.printStackTrace();
} finally {
conn.disconnect();
}
return null;
}
}
I need to call a thread, wait for the answer and call another thread. Their answers I must use them in the activity
I need to call a thread, wait for the answer and call another thread.
Their answers I must use them in the activity
Example using async tasks to accomplish objective.
In this code, let A be your activity which needs to call a thread,
wait for the answer and call another thread. Customize as needed.
Since you never wait in UI threads, callbacks are used to accomplish synchronization.
Let A be your activity class:
public class A extends Activity {
// some method in activity where you launch a background thread (B)
// which then completes and invokes callback which then creates and launches
// a background thread (C) which then completes and invokes a callback.
//
// In callback C, you are on the UI thread.
protected void someMethod() {
new B(new B.CallbackB() {
public void result(Object o) {
new C(new C.CallbackC() {
public void result(Object o, Object answerFromB) {
// OK - C is now done and we are on UI thread!
// 'o' is answer from C
// 'answerFromB' also provided
}
}, o).execute(new Object());
}
).execute(new Object());
}
}
Define a class B:
public class B extends AsyncTask<Object, Void, Object> {
public static interface CallbackB {
void result(Object o);
}
private CallbackB cb;
public B (CallbackB cb) {
this.cb = cb;
}
protected Object doInBackground(Object... params) {
// do work and return an answer.
return new Object();
}
protected void onPostExecute(Object result) {
if (cb != null) {
cb.result(result);
}
}
}
Define a class C:
public class C extends AsyncTask<Object, Void, Object> {
public static interface CallbackC {
void result(Object o, Object answerFromB);
}
private CallbackC cb;
private Object answerFromB;
public C (CallbackC cb, Object answerFromB) {
this.cb = cb;
this.answerFromB = answerFromB;
}
protected Object doInBackground(Object... params) {
// do work and return an answer.
return new Object();
}
protected void onPostExecute(Object result) {
if (cb != null) {
cb.result(result, answerFromB);
}
}
}
For reference:
https://stackoverflow.com/a/9963705/2711811
My solution is:
public class Sync extends AppCompatActivity {
...
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sync_server);
dao = new DAO(this);
txtState = findViewById(R.id.txt_log);
btnSincro = findViewById(R.id.btn_sincro);
btnSincro.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
countCall = 0;
callFlow();
}
});
btnHome = findViewById(R.id.btn_home);
btnHome.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(SyncServerActivity.this, MainActivity.class);
startActivity(intent);
}
});
}
private void callFlow() {
switch (countCall) {
case 0:
templates = toTemplate("url");
break;
case 1:
jobs = toJobs("url");
break;
case 2:
job = ... //select item
res = sendJobs(jobs, "url");
break;
default:
runOnUiThread(new Runnable() {
#Override
public void run() {
btnSincro.setEnabled(true);
txtState.append("\n\nEND");
}
});
}
}
private void nextStep() {
setText(txtState, "\nSync \n" + countCall + "/3");
countCall++;
callFlow();
}
private void setText(final TextView text, final String value) {
runOnUiThread(new Runnable() {
#Override
public void run() {
text.setText(value);
}
});
}
public List<Templates> toTemplate(final String... params) {
final List<Templates> list = new ArrayList<>();
Thread t = new Thread(new Runnable() {
#Override
public void run() {
URL url = null;
BufferedReader reader = null;
HttpURLConnection connection = null;
try {
url = new URL(params[0]);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
InputStream stream = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(stream));
int responseCode = connection.getResponseCode();
String response = null;
if (responseCode == HttpsURLConnection.HTTP_OK) {
StringBuffer buffer = new StringBuffer();
String line = "";
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
String finalJson = buffer.toString();
JSONObject parentObject = new JSONObject(finalJson);
JSONArray parentArray = parentObject.getJSONArray("data");
for (int i = 0; i < parentArray.length(); i++) {
Templates item = new Gson().fromJson(parentArray.get(i).toString(), Templates.class);
list.add(item);
}
} else {
response = connection.getResponseMessage();
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
} finally {
if (connection != null)
connection.disconnect();
try {
if (reader != null)
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
nextStep(); //call next Thread
}
}
});
t.start();
return list;
}
public List<Jobs> toJobs(final String... params) {
final List<Jobs> list = new ArrayList<>();
Thread t = new Thread(new Runnable() {
#Override
public void run() {
URL url = null;
BufferedReader reader = null;
HttpURLConnection connection = null;
try {
url = new URL(params[0]);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
InputStream stream = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(stream));
int responseCode = connection.getResponseCode();
String response = null;
if (responseCode == HttpsURLConnection.HTTP_OK) {
StringBuffer buffer = new StringBuffer();
String line = "";
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
String finalJson = buffer.toString();
JSONObject parentObject = new JSONObject(finalJson);
JSONArray parentArray = parentObject.getJSONArray("data");
for (int i = 0; i < parentArray.length(); i++) {
Jobs item = new Gson().fromJson(parentArray.get(i).toString(), Jobs.class);
list.add(item);
}
} else {
response = connection.getResponseMessage();
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
} finally {
if (connection != null)
connection.disconnect();
try {
if (reader != null)
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
nextStep();
}
}
});
t.start();
return list;
}
public Boolean sendJobs(final List<Jobs> job, final String... params) {
final Boolean[] result = {false};
Thread t = new Thread(new Runnable() {
#Override
public void run() {
URL url = null;
HttpURLConnection conn = null;
try {
url = new URL(params[0]);
conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/json");
conn.setDoInput(true);
conn.setDoOutput(true);
String str = new Gson().toJson(job);
Log.d(TAG, str);
byte[] outputInBytes = str.getBytes();
OutputStream os = conn.getOutputStream();
os.write(outputInBytes);
os.flush();
int responseCode = conn.getResponseCode();
String response = null;
if (responseCode == HttpsURLConnection.HTTP_OK) {
String line;
BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
while ((line = br.readLine()) != null) {
response += line;
}
result[0] = true;
} else {
response = conn.getResponseMessage();
}
} catch (Exception e) {
e.printStackTrace();
} finally {
conn.disconnect();
nextStep();
}
}
});
t.start();
return result[0];
}
}
Whenever a thread ends, it calls the nextStep() method, which starts the next trhead.

Sending Variables to a REST api to be saved on server

I am really struggling with this for some time now and I am really lost in terms of how this works.
I have written a REST service in netbeans and I have passed through Json data and tested that it works using Postman and it is successfully saving to the database.
Now, I want the variables in my mobile application to be sent to that REST api so that they can then be saved to the database.
I have looked at many answers on this but can get none which fully explain to me how to do this.. Ideally I am trying to POST or PUT data from my mobile app into my database.
Here is what I have tried so far:
submit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
details = editTextDetails.getText().toString();
getCurrentDateandTime();
String url = "http://localhost:8080/engAppApi/webservices/engineerTable/";
HttpClient client = new DefaultHttpClient();
HttpPost request = new HttpPost(url);
JSONObject params = new JSONObject();
try {
params.put("machinetype", machineType);
} catch (JSONException e) {
e.printStackTrace();
}
try {
params.put("workordernumber", workOrderNumber);
} catch (JSONException e) {
e.printStackTrace();
}
try {
params.put("employeename", employee);
} catch (JSONException e) {
e.printStackTrace();
}
try {
params.put("activity", activity);
} catch (JSONException e) {
e.printStackTrace();
}
try {
params.put("durationhours", durationHours);
} catch (JSONException e) {
e.printStackTrace();
}
try {
params.put("durationmins", durationMins);
} catch (JSONException e) {
e.printStackTrace();
}
try {
params.put("downtimehours", downTimeHours);
} catch (JSONException e) {
e.printStackTrace();
}
try {
params.put("downtimemins", downTimeMins);
} catch (JSONException e) {
e.printStackTrace();
}
try {
params.put("details", details);
} catch (JSONException e) {
e.printStackTrace();
}
try {
params.put("currentdateandtime", currentDateandTime);
} catch (JSONException e) {
e.printStackTrace();
}
StringEntity jsonEntity = null;
try {
jsonEntity = new StringEntity(params.toString());
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
request = new HttpPost(url);
request.addHeader("Content-Type", "application/json");
request.setEntity(jsonEntity);
try {
HttpResponse response = client.execute(request);
} catch (IOException e) {
e.printStackTrace();
}
}
});
}
can someone please point me in the right direction
Thanks in advance!
just use retrofit 2 for connect to server.
see this link
You have an idea in how to do the post petition, but you have a couple of problems. The first and more important problem is that if you want to retrieve information from a server, you must put your code in an async task. You can't do it in UI Thread. So, i'm gonna share with you a class that implements all the logic you need and you just have to use it. First you need to use gson, look how to use it here
https://github.com/google/gson
and the code is here. It have two methods, one for GET and other for POST.
import android.os.AsyncTask;
import android.util.Log;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
/**
* Created by Administrador on 4/27/2017.
*/
public class JsonReaderFromUrl {
public static final int SUCCESS = 0;
public static final int FAILED = 1;
public static final int PROGRESS = 2;
public interface OnJesonInterface{
void OnJsonReceive(int status, JSONObject jsonObject, int key);
}
public JsonReaderFromUrl() {
}
public void getJsonFromUrlPost(final String url, final OnJesonInterface onJesonInterface, final String body, final int key){
new AsyncTask<Void, String, String>() {
#Override
protected void onPreExecute() {
super.onPreExecute();
onJesonInterface.OnJsonReceive(PROGRESS,null,0);
}
#Override
protected String doInBackground(Void... params) {
if(android.os.Debug.isDebuggerConnected())
android.os.Debug.waitForDebugger();
try {
URL urlJson = new URL(url);
HttpURLConnection connection = (HttpURLConnection) urlJson.openConnection();
connection.setDoInput(true);
connection.setRequestProperty("Content-Type","application/json");
connection.setRequestMethod("POST");
OutputStream outputStream = connection.getOutputStream();
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
writer.write(body);
writer.flush();
writer.close();
outputStream.close();
connection.connect();
StringBuilder stringBuilder = new StringBuilder();
int httpStatus = connection.getResponseCode();
if (httpStatus == HttpURLConnection.HTTP_CREATED){
BufferedReader br = new BufferedReader(
new InputStreamReader(connection.getInputStream(),"utf-8")
);
String line = "";
while ((line = br.readLine()) != null){
stringBuilder.append(line + "\n");
}
br.close();
return stringBuilder.toString();
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
if (s != null){
try {
JSONObject jsonObject = new JSONObject(s);
onJesonInterface.OnJsonReceive(SUCCESS,jsonObject,key);
} catch (JSONException e) {
e.printStackTrace();
}
}
else {
onJesonInterface.OnJsonReceive(FAILED,null,0);
}
}
}.execute();
}
public void getJsonFromUrl(final String url, final OnJesonInterface onJesonInterface){
AsyncTask<Void,String,String> asyncTask = new AsyncTask<Void, String, String>() {
#Override
protected void onPreExecute() {
super.onPreExecute();
onJesonInterface.OnJsonReceive(PROGRESS,null,0);
}
#Override
protected String doInBackground(Void... params) {
try {
URL urlJson = new URL(url);
HttpURLConnection connection = (HttpURLConnection) urlJson.openConnection();
connection.connect();
InputStream stream = connection.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(stream));
StringBuffer stringBuffer = new StringBuffer();
String line = "";
while ((line = reader.readLine()) != null){
stringBuffer.append(line + "\n");
Log.d("RESPONDE JSON: ",">" + line);
}
return stringBuffer.toString();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
if (s != null){
try {
JSONObject jsonObject = new JSONObject(s);
onJesonInterface.OnJsonReceive(SUCCESS,jsonObject,0);
} catch (JSONException e) {
e.printStackTrace();
}
}
else {
onJesonInterface.OnJsonReceive(FAILED,null,0);
}
}
}.execute();
}
}
import this class where you need and use it PD: The key value is an int that can be used to retrieve what response correspond to each petition, this in case you use this class with a lot of petitions.

Android HttpUrlConnection simple Website connection

I want to check if a local website from my apache-server is up and reachable.
If read through countless threads about HttpUrlconnection and came up with the following code. Manifest Internet Persmission is set. The website is currently running and I can access it via my smartphones webbrowser. I´ve also read about Input and Outputstreams, do I need them for my task?
public class MainActivity extends AppCompatActivity {
boolean value;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
state(value);
}
public boolean state(boolean value){
try {
URL url = new URL("http://192.168.178.59:8090/");
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setRequestMethod("HEAD");
httpURLConnection.setConnectTimeout(3000);
httpURLConnection.setReadTimeout(3000);
value = true;
Toast.makeText(MainActivity.this,"true",Toast.LENGTH_SHORT).show();
return value;
} catch (MalformedURLException e) {
e.printStackTrace();
value = false;
Toast.makeText(MainActivity.this,"false",Toast.LENGTH_SHORT).show();
return value;
} catch (IOException e) {
e.printStackTrace();
value = false;
Toast.makeText(MainActivity.this,"false",Toast.LENGTH_SHORT).show();
return value;
}
}
}
EDIT: Solution from Exception
import java.net.HttpURLConnection;
import android.os.AsyncTask;
public class MainActivity extends AppCompatActivity {
boolean value;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new HttpTask().execute(value);
}
private class HttpTask extends AsyncTask<Boolean, Void, Boolean>
{
#Override
protected Boolean doInBackground(Boolean... params) {
// TODO Auto-generated method stub
boolean value=params[0];
try {
URL url = new URL("http://192.168.178.59:8090/");
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setRequestMethod("HEAD");
httpURLConnection.setConnectTimeout(3000);
httpURLConnection.setReadTimeout(3000);
httpURLConnection.connect();
value = true;
//Toast.makeText(MainActivity.this,"true",Toast.LENGTH_SHORT).show();
return value;
} catch (MalformedURLException e) {
e.printStackTrace();
value = false;
//Toast.makeText(MainActivity.this,"false",Toast.LENGTH_SHORT).show();
return value;
} catch (IOException e) {
e.printStackTrace();
value = false;
//Toast.makeText(MainActivity.this,"false",Toast.LENGTH_SHORT).show();
return value;
}
}
#Override
protected void onPostExecute(Boolean result) {
if(result){
Toast.makeText(MainActivity.this,"true",Toast.LENGTH_SHORT).show();
}
else{
Toast.makeText(MainActivity.this,"false",Toast.LENGTH_SHORT).show();
}
}
}
}
EDIT: Service Solution
#Override
protected void onPostExecute(Boolean result) {
if(result){
Toast.makeText(NotifiyService.this,"true",Toast.LENGTH_SHORT).show();
//Notification in Status Bar
NotificationCompat.Builder builder = new NotificationCompat.Builder(NotifiyService.this);
builder.setSmallIcon(R.drawable.dummy);
Intent intent = new Intent(NotifiyService.this, Main22Activity.class);
intent.setAction(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_LAUNCHER);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
PendingIntent pendingIntent = PendingIntent.getActivity(NotifiyService.this,0,intent,0);
builder.setContentIntent(pendingIntent);
builder.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.dummy));
builder.setContentTitle(getResources().getString(R.string.newNotify));
builder.setContentText(getResources().getString(R.string.newNotify2));
NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
notificationManager.notify(1,builder.build());
}
else{
Toast.makeText(NotifiyService.this,"false",Toast.LENGTH_SHORT).show();
}
Replace your code with below given code.
import java.net.HttpURLConnection;
import android.os.AsyncTask;
public class MainActivity extends AppCompatActivity {
boolean value;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new HttpTask().execute(value);
}
private class HttpTask extends AsyncTask<Boolean, Void, Boolean>
{
#Override
protected Boolean doInBackground(Boolean... params) {
// TODO Auto-generated method stub
boolean value=params[0];
try {
URL url = new URL("http://192.168.178.59:8090/");
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setRequestMethod("HEAD");
httpURLConnection.setConnectTimeout(3000);
httpURLConnection.setReadTimeout(3000);
httpURLConnection.connect();
value = true;
//Toast.makeText(MainActivity.this,"true",Toast.LENGTH_SHORT).show();
return value;
} catch (MalformedURLException e) {
e.printStackTrace();
value = false;
//Toast.makeText(MainActivity.this,"false",Toast.LENGTH_SHORT).show();
return value;
} catch (IOException e) {
e.printStackTrace();
value = false;
//Toast.makeText(MainActivity.this,"false",Toast.LENGTH_SHORT).show();
return value;
}
}
#Override
protected void onPostExecute(Boolean result) {
if(result){
Toast.makeText(MainActivity.this,"true",Toast.LENGTH_SHORT).show();
}
else{
Toast.makeText(MainActivity.this,"false",Toast.LENGTH_SHORT).show();
}
}
}
}
EDIT:
To launch new activity on notification click, add these lines after Intent intent = new Intent(NotifiyService.this, Main22Activity.class);:
intent .setAction(Intent.ACTION_MAIN);
intent .addCategory(Intent.CATEGORY_LAUNCHER);
intent .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
Simply run this code:-
public boolean state(boolean value){
URL url;
String response = "";
try {
url = new URL("http://192.168.178.59:8090/");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(15000);
conn.setConnectTimeout(15000);
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.setDoOutput(true);
OutputStream os = conn.getOutputStream();
BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(os, "UTF-8"));
//writer.write(getPostDataString(postDataParams));
writer.write(value);
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()));
while ((line = br.readLine()) != null) {
response += line;
System.out.println(response);
}
} else {
response = "";
}
} catch (Exception e) {
e.printStackTrace();
}
}

android socket jelly bean

i want to ask some question for android socket. I create a sample app to send data to wifly module. But when i receive data from module i get socket timeout exception. Without setSoTimeout app freeze to inputStream.read. Here is my code:
package com.socket.wiflysocket;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends Activity {
protected static final String TAG = "WIflySocket";
EditText textOut;
TextView textIn;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textOut = (EditText)findViewById(R.id.textout);
Button buttonSend = (Button)findViewById(R.id.send);
textIn = (TextView)findViewById(R.id.textin);
buttonSend.setOnClickListener(buttonSendOnClickListener);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
Button.OnClickListener buttonSendOnClickListener
= new Button.OnClickListener(){
#Override
public void onClick(View arg0) {
ConnectivityManager connMgr = (ConnectivityManager)
getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
if (networkInfo == null || networkInfo.isConnected() == false) {
try {
throw new Exception("Network is not connected");
} catch (Exception e) {
e.printStackTrace();
}
}
else {
new SocketThread(textOut.getText().toString()).execute();
textOut.setText("");
}
}};
}
and asynkTask:
package com.socket.wiflysocket;
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;
import android.os.AsyncTask;
import android.util.Log;
public class SocketThread extends AsyncTask<String, Void, String>{
private static final String TAG = "SocketAsyncTask";
private static final int BUFFER_SIZE = 8;
private String textViewIn;
private String output;
private Socket socket = null;
private PrintWriter outputStream;
private InputStreamReader inputStream;
public SocketThread(String paramTextViewIn)
{
this.textViewIn = paramTextViewIn;
}
#Override
protected String doInBackground(String ...views) {
Log.d(TAG, "Execute");
DataOutputStream dataOutputStream = null;
DataInputStream dataInputStream = null;
try {
socket = new Socket("1.2.3.4", 2000);
socket.setSoTimeout(2000);
outputStream = new PrintWriter(new OutputStreamWriter(socket.getOutputStream()));
inputStream = new InputStreamReader(socket.getInputStream());
if(socket.isConnected()) {
this.sendDataWithString(textViewIn);
output = this.receiveDataFromServer();
}
this.closeSocket();
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
finally{
if (socket != null){
try {
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (dataOutputStream != null){
try {
dataOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (dataInputStream != null){
try {
dataInputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return output;
}
/*
// onPostExecute displays the results of the AsyncTask.
#Override
protected void onPostExecute(String result) {
return textViewOut;
}
*/
private void closeSocket() {
if (socket != null) {
if (socket.isConnected()) {
try {
inputStream.close();
outputStream.close();
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
private void sendDataWithString(String message) {
if (message != null) {
outputStream.write(message);
outputStream.flush();
}
}
private String receiveDataFromServer() {
String message = "";
try {
int charsRead = 0;
char[] buffer = new char[BUFFER_SIZE];
while ((charsRead = inputStream.read(buffer)) != -1) {
message += new String(buffer).substring(0, charsRead);
}
closeSocket();
return message;
} catch (IOException e) {
//TODO work around
return message;
//return "Error receiving response: " + e.getMessage();
}
}
}
Permission that I add are :
android.permission.INTERNET;
android.permission.ACCESS_NETWORK_STATE
Can you suggest me, what is wrong, and how to fix this issue.
Thanks
Try this -
BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in));
String userInput;
while ((userInput = stdIn.readLine()) != null) {
out.println(userInput);
System.out.println("echo: " + in.readLine());
}
or this -
Reader r = new InputStreamReader(conn.getInputStream());
String line;
StringBuilder sb = new StringBuilder();
char[] chars = new char[4*1024];
int len;
while((len = r.read(chars))>=0) {
sb.append(chars, 0, len);
}
or this one -
byte[] resultBuff = new byte[0];
byte[] buff = new byte[1024];
int k = -1;
while((k = sock.getInputStream().read(buff, 0, buff.length)) > -1) {
byte[] tbuff = new byte[resultBuff.length + k];
System.arraycopy(resultBuff, 0, tbuff, 0, resultBuff.length); bytes
System.arraycopy(buff, 0, tbuff, resultBuff.length, k);
resultBuff = tbuff;
}
SocketFactory creates socket for you
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import javax.net.SocketFactory;
...
private Socket socket = null;
public Reader reader = null;
public Writer writer = null;
protected void init(String host, int port) throws ClientException {
try {
socket = SocketFactory.getDefault().createSocket(host, port);
} catch (UnknownHostException e) {
throw new ClientException(e);
} catch (IOException e) {
throw new ClientException(e);
}
initDataManagers();
}
protected void initDataManagers() throws ClientException {
try {
reader = new BufferedReader(new InputStreamReader(socket.getInputStream(), "UTF-8"));
writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream(), "UTF-8"));
} catch (UnsupportedEncodingException e) {
throw new ClientException(e);
} catch (IOException e) {
throw new ClientException(e);
}
}

Can someone help me with some file download code

Hi I am making a app that fetches a xml file and displays the results with a button labeled get it. I need help with when the button is clicked it will take the .pkg file url in the xml file and download it with some sort of progress reporting. Any help would be awesome thanks in advance. Here is what I have so far it has a error in the download code I tried maybe someone can fix this for me. I am stumped also the links are to .pkg files
package com.mypackagename;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.List;
import javax.net.ssl.HttpsURLConnection;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.params.ClientPNames;
import org.apache.http.client.params.CookiePolicy;
import org.apache.http.entity.StringEntity;
import org.apache.http.protocol.HttpContext;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import android.app.Activity;
import android.app.ListActivity;
import android.content.Context;
import android.content.Intent;
import android.content.DialogInterface.OnClickListener;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import org.apache.http.util.ByteArrayBuffer;
import android.util.Log;
public class MainActivity extends ListActivity {
String XML_URL = "http://www.mysite.com/book.xml";
private DocumentBuilder docBuilder;
private Document doc;
private DocumentBuilderFactory docBuilderFactory;
private String bookImageUrl;
private int nodeListbooksLength;
private String bookId;
private String bookUrl;
private String bookDescription;
private String bookTitle;
ButtonListMenuAdapter notes;
ArrayList<Book> list;
TextView tv_title;
ImageView iv_logo;
private String Title;
Drawable booksImagesList[];
/** Called when the activity is first created. 1 */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
tv_title = (TextView) findViewById(R.id.TextView01);
iv_logo = (ImageView) findViewById(R.id.ImageView01);
list = new ArrayList<Book>();
parseXML();
notes = new ButtonListMenuAdapter(
this,
R.layout.book_row,
list );
setListAdapter( notes );
}
private void parseXML()
{
try{
Log.d("MainActivity", "Connecting Server");
InputStream inStream =openHttpConnection(XML_URL);
Log.d("MainActivity", "Fetching Data Completed");
if(inStream!=null){
docBuilderFactory = DocumentBuilderFactory.newInstance();
docBuilderFactory.setCoalescing(true);
docBuilder = docBuilderFactory.newDocumentBuilder();
docBuilder.isValidating();
doc = docBuilder.parse(inStream);
NodeList nodeListbookTitle = doc.getDocumentElement().getElementsByTagName("Title1");
if(nodeListbookTitle.getLength()>0){
Element elementbooktitile = (Element) nodeListbookTitle.item(0);
NodeList nodeListElementbooktitle = elementbooktitile.getChildNodes();
if(nodeListElementbooktitle.getLength()>0)
{
Title = ((Node) nodeListElementbooktitle.item(0)).getNodeValue();
Log.d("MainActivity", "Title:"+Title);
tv_title.setText(Title);
}
}
NodeList nodeListbookBanner = doc.getDocumentElement().getElementsByTagName("logo");
if(nodeListbookBanner.getLength()>0){
Element elementTeamBanner = (Element) nodeListbookBanner.item(0);
NodeList nodeListElementTeamBanner = elementTeamBanner.getChildNodes();
if(nodeListElementTeamBanner.getLength()>0)
{
bookImageUrl = ((Node) nodeListElementTeamBanner.item(0)).getNodeValue();
try {
DownloadFilesTask d = new DownloadFilesTask();
d.execute(new URL(bookImageUrl));
d.sendObjectImageView(iv_logo);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
Log.d("ERROR getView", "EX::"+e);
}
Log.d("MainActivity", "bookImageUrl:"+bookImageUrl);
Log.d("MainActivity", "");
}
}
NodeList nodeListbook = doc.getDocumentElement().getElementsByTagName("Book");
Log.d("MainActivity","nodeListbook Length--"+nodeListbook.getLength());
nodeListbooksLength=nodeListbook.getLength();
booksImagesList = new Drawable[nodeListbooksLength+1];
if(nodeListbooksLength>0){
for(int v=0;v<nodeListbooksLength;v++){
Node nodebook = nodeListbook.item(v);
if (nodebook.getNodeType() == Node.ELEMENT_NODE){
Element elementbookResult = (Element) nodebook;
bookId=elementbookResult.getAttribute("bid");
Log.d("MainActivity","----in bookId- ->"+v+" "+bookId);
bookImageUrl=elementbookResult.getAttribute("bimg");
Log.d("MainActivity","--bookImageUrl--->"+bookImageUrl);
bookTitle=elementbookResult.getAttribute("bte");
Log.d("MainActivity","--bookTitle--->"+bookTitle);
bookDescription=elementbookResult.getAttribute("bsd");
Log.d("MainActivity","--bookDescription--->"+bookDescription);
bookUrl=elementbookResult.getAttribute("bph");
Log.d("MainActivity","--bookUrl:--->"+bookUrl);
list.add( new Book( bookId, bookImageUrl,bookTitle,bookDescription,bookUrl) );
}
}
}
}
}catch(Exception e){
Log.d("MainActivity", "parseXML:"+e);
}
}
private InputStream openHttpConnection(String urlStr) {
InputStream in = null;
int resCode = -1;
try {
Log.d("openHttpConnection", "URL:"+urlStr);
URL url = new URL(urlStr);
URLConnection urlConn = url.openConnection();
if (!(urlConn instanceof HttpURLConnection)) {
throw new IOException ("URL is not an Http URL");
}
Log.d("openHttpConnection", "httpConn:1");
HttpURLConnection httpConn = (HttpURLConnection)urlConn;
httpConn.setAllowUserInteraction(false);
httpConn.setInstanceFollowRedirects(true);
httpConn.setRequestMethod("GET");
httpConn.setRequestProperty("User-Agent", "Mozilla/5.0 (X11; U; Linux "+"i686; en-US; rv:1.8.1.6) Gecko/20061201 Firefox/2.0.0.6 (Ubuntu-feisty)");
httpConn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
Log.d("openHttpConnection", "setting requests and properties");
httpConn.connect();
Log.d("openHttpConnection", "Connected successfully");
resCode = httpConn.getResponseCode();
Log.d("openHttpConnection", "resCode"+resCode);
if (resCode == HttpURLConnection.HTTP_OK) {
in = httpConn.getInputStream();
Log.d("openHttpConnection", "Fetchinf data done");
}
} catch (MalformedURLException e) {
e.printStackTrace();
Log.d("openHttpConnection", "1"+e);
} catch (IOException e) {
e.printStackTrace();
Log.d("openHttpConnection", ""+e);
}
return in;
}
private HttpClient httpClient;
private HttpPost httpPost;
private HttpResponse response;
private HttpContext localContext;
private String ret;
private InputStream postPage(String url, String data) {
InputStream is = null;
ret = null;
httpClient.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.RFC_2109);
httpPost = new HttpPost(url);
response = null;
StringEntity tmp = null;
httpPost.setHeader("User-Agent", "Mozilla/5.0 (X11; U; Linux " +
"i686; en-US; rv:1.8.1.6) Gecko/20061201 Firefox/2.0.0.6 (Ubuntu-feisty)");
httpPost.setHeader("Accept", "text/html,application/xml," +
"application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5");
httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded");
try {
tmp = new StringEntity(data,"UTF-8");
} catch (UnsupportedEncodingException e) {
System.out.println("HTTPHelp : UnsupportedEncodingException : "+e);
}
httpPost.setEntity(tmp);
try {
response = httpClient.execute(httpPost,localContext);
} catch (ClientProtocolException e) {
System.out.println("HTTPHelp : ClientProtocolException : "+e);
} catch (IOException e) {
System.out.println("HTTPHelp : IOException : "+e);
}
ret = response.getStatusLine().toString();
HttpEntity he = response.getEntity();
try {
InputStream inStream = he.getContent();
is = inStream;
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return is;
}
class Book
{
public String getBookId() {
return bookId;
}
public String getBookImageUrl() {
return bookImageUrl;
}
public String getBookTitle() {
return bookTitle;
}
public String getBookDescription() {
return bookDescription;
}
public String getBookUrl() {
return bookUrl;
}
private String bookId;
private String bookImageUrl;
private String bookTitle;
private String bookDescription;
private String bookUrl;
public Book(String bookId, String bookImageUrl, String bookTitle,String bookDescription, String bookUrl) {
this.bookId = bookId;
this.bookImageUrl = bookImageUrl;
this.bookTitle = bookTitle;
this.bookDescription = bookDescription;
this.bookUrl = bookUrl;
}
}
public class ButtonListMenuAdapter extends BaseAdapter {
public static final String LOG_TAG = "ButtonListAdapter";
private Context context;
private List<Book> menuList;
private int rowResID;
public ButtonListMenuAdapter(MainActivity context, int rowResID,
ArrayList<Book> menuList) {
// TODO Auto-generated constructor stub
this.context = context;
this.rowResID = rowResID;
this.menuList = menuList;
}
public int getCount() {
return menuList.size();
}
public Object getItem(int position) {
return menuList.get(position);
}
public long getItemId(int position) {
return position;
}
public View getView(final int position, View convertView, ViewGroup parent) {
final Book row = menuList.get(position);
LayoutInflater inflater = LayoutInflater.from( context );
View v = inflater.inflate( rowResID, parent, false );
TextView tv_title = (TextView)v.findViewById(R.id.Text_book_title);
tv_title.setText(row.getBookTitle());
TextView tv_desc = (TextView)v.findViewById(R.id.Text_Book_Desc);
tv_desc.setText(row.getBookDescription());
ImageView iv_book_img = (ImageView)v.findViewById(R.id.Image_book);
if(booksImagesList[position]==null)
{
try {
DownloadFilesTask d = new DownloadFilesTask();
d.execute(new URL(row.getBookImageUrl()));
d.sendObjectImageView(iv_book_img,position);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
Log.d("ERROR getView", "EX::"+e);
}
}
else
{
iv_book_img.setImageDrawable(booksImagesList[position]);
Log.d("Not","Reloaded");
}
Button b_get_book = (Button)v.findViewById(R.id.Button01);
b_get_book.setOnClickListener(
new View.OnClickListener()
{
public void onClick(View v) {
private final String PATH = "/mnt/sdcard/"; //put the downloaded file here
public void DownloadFromUrl(String bookUrl, String fileName) { //this is the downloader method
try {
URL url = new URL("http://mysite.com/" + bookUrl); //you can write here any link
File file = new File(fileName);
long startTime = System.currentTimeMillis();
Log.d("ImageManager", "download begining");
Log.d("ImageManager", "download url:" + url);
Log.d("ImageManager", "downloaded file name:" + fileName);
/* Open a connection to that URL. */
URLConnection ucon = url.openConnection();
/*
* Define InputStreams to read from the URLConnection.
*/
InputStream is = ucon.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is);
/*
* Read bytes to the Buffer until there is nothing more to read(-1).
*/
ByteArrayBuffer baf = new ByteArrayBuffer(50);
int current = 0;
while ((current = bis.read()) != -1) {
baf.append((byte) current);
}
/* Convert the Bytes read to a String. */
FileOutputStream fos = new FileOutputStream(PATH+file);
fos.write(baf.toByteArray());
fos.close();
Log.d("ImageManager", "download ready in"
+ ((System.currentTimeMillis() - startTime) / 1000)
+ " sec");
} catch (IOException e) {
Log.d("ImageManager", "Error: " + e);
}
}
}
});
return v;
}
}
private class DownloadFilesTask extends AsyncTask<URL, Integer, Long> {
ImageView iv;
int id;
protected Long doInBackground(URL... urls) {
int count = urls.length;
long totalSize = 0;
downloadDrawable(urls[0].toString());
return totalSize;
}
public void sendObjectImageView(ImageView ivLogo) {
// TODO Auto-generated method stub
this.iv = ivLogo;
id = -1;
}
public void sendObjectImageView(ImageView iv,int id) {
// TODO Auto-generated method stub
this.iv = iv;
this.id = id;
}
protected void onProgressUpdate(Integer... progress) {
Log.d("DownloadFilesTask", "onProgressUpdate"+progress[0]);
}
protected void onPostExecute(Long result) {
Log.d("DownloadFilesTask", "onPostExecute"+result);
if(d!=null && iv!=null)
{
iv.setImageDrawable(d);
if(id!=-1)
booksImagesList[id] = d;
}
}
private Drawable d;
public Drawable downloadDrawable(String imageUrl) {
try {
Log.d("downloadDrawable", "Starting Connection");
URL url = new URL(imageUrl);
URLConnection conn = url.openConnection();
conn.connect();
Log.d("downloadDrawable", "Connection Created Successfully");
InputStream is = conn.getInputStream();
Log.d("downloadDrawable", "InputStream created Successfully");
d = Drawable.createFromStream(is, url.toString());
Log.d("downloadDrawable", "Drawable created Successfully");
is.close();
} catch (IOException e) {
Log.d("ERROR3", "Ex::"+e);
}
return d;
}
}
}
this is a typical http connection.
URL url = new URL(strUrl);
HttpURLConnection urlConn = (HttpURLConnection) url
.openConnection();
InputStream is = urlConn.getInputStream();
final int MAX_LENGTH = 10000;
byte[] buf = new byte[MAX_LENGTH];
int total = 0;
while (total < MAX_LENGTH) {
int count = is.read(buf, total, MAX_LENGTH - total);
if (count < 0) {
break;
}
total += count;
}
is.close();
String result = new String(buf, 0, total);
urlConn.disconnect();

Categories

Resources