I am trying to save every output data in asynctask for each http call.But I am unable to see any data in a file.I really appreciate any help.Thanks in Advance.
final String[] ar={"1","2","3",.............,"25"}
filename="test_file";
myFile = new File("/sdcard/"+filename);
try {
myFile.createNewFile();
fOut = new FileOutputStream(myFile);
} catch (FileNotFoundException e1) {
e1.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
myOutWriter = new OutputStreamWriter(fOut);
for ( j = 0; j < ar.length; j++) {
u="http://www.example.com/"+ar[j];
JSONParser jParser=new JSONParser();
new MyAsyncTask().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR,u);
}
try {
myOutWriter.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
class MyAsyncTask extends AsyncTask<String, String, Void> {
private ProgressDialog progressDialog = new ProgressDialog(MainActivity.this);
InputStream inputStream = null;
String result = "";
protected void onPreExecute() {
progressDialog.setMessage("Downloading your data...");
progressDialog.show();
progressDialog.setOnCancelListener(new OnCancelListener() {
public void onCancel(DialogInterface arg0) {
MyAsyncTask.this.cancel(true);
}
});
}
#Override
protected Void doInBackground(String... params) {
String url_select = params[0];
try {
HttpClient httpclient = new DefaultHttpClient();
HttpResponse httpResponse = httpclient.execute(new HttpGet(url_select));
// receive response as inputStream
inputStream = httpResponse.getEntity().getContent();
//
// // Read content & Log
// inputStream = httpEntity.getContent();
} catch (UnsupportedEncodingException e1) {
Log.e("UnsupportedEncodingException", e1.toString());
e1.printStackTrace();
} catch (ClientProtocolException e2) {
Log.e("ClientProtocolException", e2.toString());
e2.printStackTrace();
} catch (IllegalStateException e3) {
Log.e("IllegalStateException", e3.toString());
e3.printStackTrace();
} catch (IOException e4) {
Log.e("IOException", e4.toString());
e4.printStackTrace();
}
// Convert response to string using String Builder
try {
BufferedReader bReader = new BufferedReader(new InputStreamReader(inputStream, "iso-8859-1"), 8);
StringBuilder sBuilder = new StringBuilder();
String line = null;
while ((line = bReader.readLine()) != null) {
sBuilder.append(line + "\n");
}
inputStream.close();
result = sBuilder.toString();
} catch (Exception e) {
Log.e("StringBuilding & BufferedReader", "Error converting result " + e.toString());
}
return null;
} // protected Void doInBackground(String... params)
protected void onPostExecute(Void v) {
//parse JSON data
try{
JSONObject jArray = new JSONObject(result);
String name = jArray.getString("name");
if (name!=null) {
Log.w("idname", name);
//
myOutWriter.append(name).append("\r\n");
//
Toast.makeText(getBaseContext(), name, 5).show();
}
// End Loop
this.progressDialog.dismiss();
} catch (JSONException e) {
Log.e("JSONException", "Error: " + e.toString());
} // catch (JSONException e)
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} // protected void onPostExecute(Void v)
} //class MyAsyncTask extends AsyncTask<String, String, Void>
for ( j = 0; j < ar.length; j++) {
u="http://www.example.com/"+ar[j];
JSONParser jParser=new JSONParser();
new MyAsyncTask().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR,u);
}
try {
myOutWriter.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
You close the myOutWriter after start MyAsyncTask. So when MyAsyncTask try to write data to file, it throw OutputStreamWriter is closed exception.
You need remove the code of close myOutWriter from here. Add add close code at the end of onPostExecute like below:
void onPostExecute(Void v) {
.....
} catch (JSONException e) {
Log.e("JSONException", "Error: " + e.toString());
} // catch (JSONException e)
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
int count = taskCount.decrementAndGet()
if(count == 0 ) {
try {
myOutWriter.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
} // protected void onPostExecute(Void v)
the definition of taskCount is like this:
AtomicInteger taskCount = new AtomicInteger(ar.length - 1);
At last, I think Thread and CountDownLatch is better option
check if entity not null then write to db
HttpEntity entity = response.getEntity();
if(entity!=null ){
inputStream = entity.getContent();
}
Related
I have this piece of code on android that reads data from Assets folder, so I need from this code to read data from external like dropbox. Ho to change and read data from dropbox. thanks
#Override
protected RadioDatas doInBackground(Void... params) {
BufferedReader reader = null;
ArrayList<RadioData> radioDatas = new ArrayList<>();
RadioDatas datas = new RadioDatas();
try {
reader = new BufferedReader(
new InputStreamReader(context.getAssets().open("url.txt"), "Unicode"));
String mLine;
while ((mLine = reader.readLine()) != null) {
RadioData radioData = new RadioData();
String[] meta = mLine.split(";");
radioData.setUrl(meta[0]);
radioData.setTitle(meta[1]);
radioData.setGenres(meta[2]);
radioDatas.add(radioData);
}
} catch (IOException e) {
//log the exception
return null;
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
//log the exception
}
}
}
datas.setRadioDatas(radioDatas);
return datas;
}
This would work....
public class Execute extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... arg0) {
HttpHandler handler = new HttpHandler();
String jsonString = handler.makeServiceCall(json);
if (jsonString != null) {
try {
//parse jsonString
} catch (JSONException e) {
Log.i("Error with parsing", e.getMessage());
}
}
return null;
}
protected void onPostExecute(Void result) {
super.onPostExecute(result);
}
}
You will need a HTTPHandler class...
public class HttpHandler {
private static final String TAG = HttpHandler.class.getSimpleName();
public HttpHandler() {
}
public String makeServiceCall(String reqUrl) {
String response = null;
try {
URL url = new URL(reqUrl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
// read the response
InputStream in = new BufferedInputStream(conn.getInputStream());
response = convertStreamToString(in);
in.close();
} catch (MalformedURLException e) {
Log.e(TAG, "MalformedURLException: " + e.getMessage());
} catch (ProtocolException e) {
Log.e(TAG, "ProtocolException: " + e.getMessage());
} catch (IOException e) {
Log.e(TAG, "IOException: " + e.getMessage());
} catch (Exception e) {
Log.e(TAG, "Exception: " + e.getMessage());
}
return response;
}
private String convertStreamToString(InputStream is) {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line;
try {
while ((line = reader.readLine()) != null) {
sb.append(line).append('\n');
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}
}
To run it.
new Execute().execute;
I am calling a url to fetch data and insert in my database. I have provided a no internet check. If I open the app without internet connection, it works fins, a pop up comes.. But if I connect to the url when I have internet and the internet goes in middle the process, my app crashes, How to fix it?
My code:
public class DoPOSTPen extends AsyncTask<String, Void, Boolean> implements OnCancelListener {
#SuppressWarnings("deprecation")
#Override
protected Boolean doInBackground(String... arg0) {
try {
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet("http://testapi.pharmeazy.in/api/MediEazy/GetAllInvoices");
request.addHeader("Authorization", " basic NDlyaWNva2pvaWQwM2ptZGlraWRES09qZGZpamRmNzY0dDA4NWp6MzcyOHdzMkpJS1M4MTA0c2NvcTJ1OTRkazphd0VEMzI3MkA4WWFzZEU3MjI3IUBeIypVSFMq");
request.setHeader(HTTP.CONTENT_TYPE, "application/json");
System.out.println("PRIINTING");
HttpResponse response = null;
try {
response = client.execute(request);
Log.d("Response of GET request", response.toString());
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
InputStream inputStream = response.getEntity().getContent();
String result = Utils.convertInputStreamToString(inputStream);
System.out.println("server response is :" + result + "\n" + inputStream);
try {
ja=new JSONArray(result);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
catch (Exception e) {
Log.e("ClientServerDemo", "Error:", e);
toastText2 = "Connection Error !";
}
return true;
}
protected void onPreExecute() {
//display the progress dialog
mProgressHUD2 = ProgressHUD.show(Med.this,"Getting Rejected Orders", true,false,this);
}
#Override
protected void onPostExecute(Boolean valid) {
mProgressHUD2.dismiss();
// if server response is successful
for(int i=0;i<ja.length();i++){
try {
jo=ja.getJSONObject(i);
db.insertLabel(jo.get("Id").toString(), jo.get("CustomerId").toString(), jo.get("PharmacyId").toString(),
jo.get("DeliveryAddress").toString(), jo.get("DeliveryName").toString(),
jo.get("OrderStatus").toString(),jo.get("PrescriptionAttached").toString(),jo.get("Discount").toString());
}
catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
new DoPOST3().execute();
}
Please help
why you don't go for httpurlconection
#Override
protected String doInBackground(String... params) {
String finalResult = null;
URL url = null;
HttpsURLConnection urlConnection = null;
try {
url=new URL(URL);
urlConnection = (HttpsURLConnection) url.openConnection();
urlConnection.setDoOutput(true);
urlConnection.setDoInput(true);
urlConnection.setRequestMethod("POST");
urlConnection.setUseCaches(false);
urlConnection.setConnectTimeout(5000);
urlConnection.setReadTimeout(5000);
urlConnection.setRequestProperty("Content-Type","application/json");
urlConnection.connect();
OutputStreamWriter out = new OutputStreamWriter(urlConnection.getOutputStream());
out.write(jsonObjSend.toString());
out.close();
starttime = System.currentTimeMillis();
try {
mResponseCode = urlConnection.getResponseCode();
totaltime = System.currentTimeMillis() - starttime;
Log.e("HTTP POST Response Code:", ""
+ mResponseCode);
} catch (SSLPeerUnverifiedException e) {
Log.e("Exception", Log.getStackTraceString(e));
} catch (IOException e) {
Log.e("Exception", Log.getStackTraceString(e));
Log.e("HTTP POST Response Code(2):", ""
+ mResponseCode);
}
}
check before calling asynctask
if(Util.haveNetworkConnection(this))
{
HttpPostData req=new HttpPostData(URL, createJsonObject(),this) ;
req.execute();
}
How to get response in put method with Authentication using four Headers.In ios it works fine but not in Android.
Authentication code is generated from the data HMAC-SHA256 with the secret key provided after validation as the key
HttpPut put = new HttpPut(xAuthurl);//url
Log.v("put", "" + put);
try {
put.setEntity(new StringEntity(data, "UTF-8"));
} catch (UnsupportedEncodingException e1) {
Log.e(TAG, "UnsupportedEncoding: ", e1);
}
//Here are the four headers......
put.addHeader("Content-type", "application/json");
put.addHeader("x-Auth-user", Validation.id);//id of the profile
put.addHeader("X-Auth-Hash", hexBytes);// Hexadecimal value
put.addHeader("X-Auth-Time", sdf.format(datetime));//date format in utc
HttpResponse response = null;
try {
response = http.execute(put);
Log.v("response", "" + response.getAllHeaders());
} catch (ClientProtocolException e1) { // TODO Auto-generated catch
// block
e1.printStackTrace();
} catch (IOException e1) { // TODO
// Auto-generated catch block
e1.printStackTrace();
}
Log.d(TAG, "This is what we get back:"
+ response.getStatusLine().toString() + ", "
+ response.getEntity().toString());
try {
inputStream = response.getEntity().getContent();
} catch (IllegalStateException e1) { // TODO Auto-generated catch
// block
e1.printStackTrace();
} catch (IOException e1) { // TODO Auto-generated catch block
e1.printStackTrace();
}
if (inputStream != null) {
try {
result = convertInputStreamToString(inputStream);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Log.v("result", "" + result);
} else {
result = "Did not work!";
}
return 1;
}
private String convertInputStreamToString(InputStream inputStream)
throws IOException {
BufferedReader bufferedReader = new BufferedReader(
new InputStreamReader(inputStream));
String line = "";
String result = "";
while ((line = bufferedReader.readLine()) != null)
result += line;
inputStream.close();
return result;
}
result i get is {"Message":"An error has occurred."}
here my code for fetching values from web api. in my code no error is there. but in emulator doesn't show the values. please tell me where i done a mistake. let me know what is the correct code for that.
public class MainActivity extends ActionBarActivity {
Spinner sp1;
String url1=" http://www.cartrade.com/testmobileapplication/GetTopCitiesList.php? app_id=<random number>&action=Get Cities";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Spinner sp1=(Spinner)findViewById(R.id.spinner1);
}
public class Mysync extends AsyncTask<List<String>, List<String>, List<String>>{
#Override
protected List<String> doInBackground(List<String>... arg0) {
// TODO Auto-generated method stub
HttpClient httpclient = new DefaultHttpClient();
// Prepare a request object
HttpGet httpget = new HttpGet(url1);
// Execute the request
HttpResponse response;
JSONArray arr = new JSONArray();
try {
response = httpclient.execute(httpget);
HttpEntity entity = response.getEntity();
if (entity != null && response.getStatusLine().getStatusCode() == 200) {
// A Simple JSON Response Read
InputStream instream = entity.getContent();
String result = convertStreamToString(instream);
arr=new JSONArray(result);
instream.close();
}
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
// Log.e(TAG,e.toString());
} catch (IOException e) {
// TODO Auto-generated catch block
// Log.e(TAG,e.toString());
} catch (JSONException e) {
// TODO Auto-generated catch block
//Log.e(TAG,e.toString());
}
List<String> list = new ArrayList<String>();
for(int i = 0; i < arr.length(); i++){
try {
list.add(arr.getJSONObject(i).getString("name"));
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return list;
}
protected void onPostExecute(List<String> result){
sp1=(Spinner)findViewById(R.id.spinner1);
ArrayAdapter<String> adapter=new ArrayAdapter<String>(getApplicationContext(), R.layout.support_simple_spinner_dropdown_item);
sp1.setAdapter(adapter);
}
}
public String convertStreamToString(InputStream is) {
// TODO Auto-generated method stub
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
} catch (IOException e) {
// Log.e(TAG + "ERROR",e.toString());
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
// Log.e(TAG + "ERRO",e.toString());
}
}
return sb.toString();
}
}
Define List under the line
String url1=" http://www.cartrade.com/testmobileapplication/GetTopCitiesList.php? app_id=&action=Get Cities";
like : List<String> list ;
And Try to Change the line
List list = new ArrayList();
Via
list = new ArrayList();
and Change
ArrayAdapter<String> adapter=new ArrayAdapter<String>(getApplicationContext(), R.layout.support_simple_spinner_dropdown_item);
Via
ArrayAdapter<String> adapter=new ArrayAdapter<String>(getApplicationContext(), R.layout.support_simple_spinner_dropdown_item,result);
Hope this may help you!
I am trying to read data continuously using the following code:
public class MyClientTask extends AsyncTask<Void, Void, Void> {
String dstAddress;
int dstPort;
String response = "";
MyClientTask(String addr, int port){
dstAddress = addr;
dstPort = port;
}
#Override
protected Void doInBackground(Void... arg0) {
Socket socket = null;
try {
socket = new Socket(dstAddress, dstPort);
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(1024);
byte[] buffer = new byte[1024];
int bytesRead;
InputStream inputStream = socket.getInputStream();
while ((bytesRead = inputStream.read(buffer)) != -1){
readInpt = inputStream.toString();
byteArrayOutputStream.write(buffer, 0, bytesRead);
response = byteArrayOutputStream.toString("UTF-8");
}
textResponse.setText(readInpt);
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
response = "UnknownHostException: " + e.toString();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
response = "IOException: " + e.toString();
}finally{
if(socket != null){
try {
socket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
return null;
}
#Override
protected void onPostExecute(Void result) {
textResponse.setText(response);
super.onPostExecute(result);
}
}
But for some reason, it doesn't show me any output in the textbox. any help would be appreciated.
There are at least two issues in your code.
Frist, I'm not sure the method toString() on the inputStream is going to work, because the documentation says it returns a description of the object (which would be different than the string recieved). You might be confusing this with the contents of buffer which might be what you really want.
readInpt = inputStream.toString(); // Probably wrong
Second. You're updating the User Interface from a background thread, inside doInBackground() , which is always forbidden.
textResponse.setText(readInpt); // Forbidden, move somewhere else, e.g. onPostExecute()
try {
socket = new Socket(dstAddress, dstPort);
BufferedReader stdIn = new BufferedReader(new InputStreamReader(socket.getInputStream()));
while (true) {
response = stdIn.readLine();
publishProgress(response);
Log.i("response", response);
}
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
response = "UnknownHostException: " + e.toString();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
response = "IOException: " + e.toString();
}
catch (Exception e) {
e.printStackTrace();
}
You cannot print it on text field because the socket will listen to the server socket.If server socket does not send any response it will listen to the socket continuously until the response is received.