Unable to set notifyDataSetChanged in Android - android

I have a case where I load a set of 10 images via WebService and and on further scrolling, I call upon the second WebService which load the next 10 images. I am able to load all the images from WebService but I am doing something silly that removes the first 10 images and re-assigns it with the next 10 images while calling the 2nd web service. I have tried notifyDataSetChanged() but it has no effect. The code is as follows :
CODE :
MainActivty :
new WebServicesClass().generateSampleData(); -->1st WebService
mGridView.setOnScrollListener(this);
mGridView.setOnItemClickListener(this);
#Override
public void onScroll(final AbsListView view, final int firstVisibleItem, final int visibleItemCount, final int totalItemCount) {
Log.d(TAG, "onScroll firstVisibleItem:" + firstVisibleItem +
" visibleItemCount:" + visibleItemCount +
" totalItemCount:" + totalItemCount);
// our handling
if (!mHasRequestedMore) {
System.out.println("Inside the requested more");
int lastInScreen = firstVisibleItem + visibleItemCount;
if (lastInScreen >= totalItemCount) {
Log.d(TAG, "onScroll lastInScreen - so load more");
mHasRequestedMore = true;
new WebServicesClass().onLoadMoreItems(); --> 2nd WebServiceCall
mHasRequestedMore = false;
}
}
}
WebServicesClass :
1st WebService :
onDoInBackGround :
#Override
protected String doInBackground(Void... urls) {
// TODO Auto-generated method stub
try {
HttpClient httpclient = new DefaultHttpClient();
HttpContext localContext = new BasicHttpContext();
HttpGet httpGet = new HttpGet(
"http://demo.bsetec.com/fancyclone/android/users/products?user_id=2&limit=0");
HttpResponse response = httpclient.execute(httpGet,
localContext);
HttpEntity entity = response.getEntity();
is = entity.getContent();
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(
new InputStreamReader(is, "iso-8859-1"), 8);
System.out.println("Buffered Reader " + reader.toString());
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result = sb.toString();
} catch (Exception e) {
Log.e("log_tag",
"Error converting sms response result " + e.toString());
}
System.out.println("Result: " + result);
try {
limit_for = 0;
OpenHttpConnection(image_url);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return result;
}
OpenHttpConnection :
public InputStream OpenHttpConnection(String image_url)
throws IOException {
int response = -1;
JSONObject jsonresponse;
String first_image = null;
try {
jsonresponse = new JSONObject(result);
Log.i("Inside OpenHttp", result);
if (result != null) {
try {
JSONObject status = jsonresponse
.getJSONObject("status");
// looping through All Contacts
if (status != null) {
products = status.getJSONArray("products");
dreamt_product_list = status
.getJSONArray("dreamit_products");
System.out.println("Dreamt Products list are "
+ dreamt_product_list.getJSONObject(0)
.names());
System.out.println("The value of string limit is "
+ limit);
System.out.println("The limit_for value is "
+ limit_for);
for (int p = limit_for; p < load_limit; p++) {
System.out.println("Products names: "
+ products.getJSONObject(p).names());
System.out.println("Item Name "
+ products.getJSONObject(p).getString(
"name"));
product_name = products.getJSONObject(p)
.getString("name").toString();
cost = products.getJSONObject(p).getString("saleprice").toString();
product_id = products.getJSONObject(p)
.getString("id");
username = products.getJSONObject(p).getString("username").toString();
System.out.println("Getstring: "
+ products.getJSONObject(p).getString(
"images"));
String images_list = products.getJSONObject(p)
.getString("images");
images_list = images_list.replaceAll("\"", "");
String regex = images_list.replaceAll(
"\\[|\\]", "");
System.out
.println("The images without bracket are "
+ regex);
for (String comma_token : regex.split(",")) {
for (int i = 0; i < 1; i++) {
System.out
.println("First Image name is "
+ comma_token);
first_image = comma_token;
System.out
.println("Image in first image is "
+ first_image);
}
break;
}
System.out.println("I am here");
image_url = "http://demo.bsetec.com/fancyclone/uploads/approved_items/"
+ first_image;
URL url = new URL(image_url);
URLConnection conn = url.openConnection();
if (!(conn instanceof HttpURLConnection))
throw new IOException(
"Not an HTTP connection");
try {
HttpURLConnection httpConn = (HttpURLConnection) conn;
httpConn.setAllowUserInteraction(false);
httpConn.setInstanceFollowRedirects(true);
httpConn.setRequestMethod("GET");
httpConn.connect();
response = httpConn.getResponseCode();
if (response == HttpURLConnection.HTTP_OK) {
in = httpConn.getInputStream();
compressed_image = image;
BitmapFactory.Options options = new BitmapFactory.Options();
options.inPurgeable = true;
options.inJustDecodeBounds = true;
options.inSampleSize = 1;
options.inJustDecodeBounds = false;
image = BitmapFactory.decodeStream(in,
null, options);
// in.reset();
}
} catch (Exception ex) {
throw new IOException("Error connecting");
}
item = new RowItem(image, product_name, cost,
product_id, dream_status,username);
rowItems.add(item);
}
System.out.println("%%%%%%%%%%%%%%%%%%%%%%%%%%" + rowItems.size());
}
} catch (JSONException e) {
// TODO Auto-generated catch block
System.out
.println("Caught Exception in the 2nd try block");
e.printStackTrace();
}
}
} catch (Exception e) {
System.out.println("Caught exception");
}
System.out.println("Ending OpenHttpConnection");
return in;
}
onPostExecuteMethod :
mAdapter = newDynamicHeightAdapter(MainActivity.getContext(),R.layout.repeat_items,rowItems);
System.out.println("ADapter size: "+mAdapter.getCount());
MainActivity.mGridView.setAdapter(mAdapter);
2nd WebService :
onDoInBackGround :
The code is SAME as the first doInBackGround().OpenHttpConnection is also the same.
onPostExecuteMethod :
mAdapter.notifyDataSetChanged(); -->Not working
When I call the WebService initially, it retrieves the first 10 images as it is supposed to do. But when the 2nd WebService is called at onScroll, then it REPLACES the initial 10 images with the 10 images obtained FROM 2nd WEBSERVICE. All I want to know is, how do I UPDATE it WITHOUT REPLACING ? Any help will be much appreciated guys. I am happy to help you with any queries.
UPDATE :
rowItems.addAll(rowItems);
Is the above code valid ?
NOTE : I am using a external library named StaggeredGridView.

First get the adapter.
YourAdapter adapter=(YourAdapter) mGridView.getAdapter();
adapter.addAll(rowItems);
adapter.notifyDataSetChanged();
Hope this works fine

You pass a collection of objects to the adapter, in your case it is rowItems.
OnScroll you hit a Web service and receives and parse the contents. These new content should be put in separate new arraylist. Say it is newRowContents.
Now, you need to add newRowContent to original row content.
rowItems.addAll(newRowContent);
Your backing datasource is updated now, and your listview needs to be refresh now.
mAdapter.notifyDataSetChanged();

Related

Can Java's FutureTask be an alternative to AsyncTask?

The docs say AsyncTask is designed to handle short operations(few seconds maximum) and states that Java classes like FutureTask are better for operations that last long. So I tried to send my location updates to the server using FutureTask but I am getting NetworkOnMainThreadException. I don't want to use AsyncTask because I wanted to keep the http connection open until the updates are cancelled. Here is my code:
SendLocation updates = new SendLocation(idt, String.valueOf(location.getLatitude()), String.valueOf(location.getLongitude()));
FutureTask ft = new FutureTask<String>(updates);
boolean b = ft.cancel(false);
ft.run();
class SendLocation implements Callable<String> {
String t, la, lo;
public SendLocation(String a, String b, String c){
this.t = a;
this.la = b;
this.lo = c;
}
public String call() {
sendUpdates(token, la, lo);
return "Task Done";
}
public void sendUpdates(String a, String b, String c){
HttpURLConnection urlConn = null;
try {
try {
URL url;
//HttpURLConnection urlConn;
url = new URL(remote + "driver.php");
urlConn = (HttpURLConnection) url.openConnection();
System.setProperty("http.keepAlive", "true");
//urlConn.setDoInput(true); //this is for get request
urlConn.setDoOutput(true);
urlConn.setUseCaches(false);
urlConn.setRequestProperty("Content-Type", "application/json");
urlConn.setRequestProperty("Accept", "application/json");
urlConn.setRequestMethod("POST");
urlConn.connect();
try {
//Create JSONObject here
JSONObject json = new JSONObject();
json.put("drt", a);
json.put("drlat", b);
json.put("drlon", c);
String postData = json.toString();
// Send POST output.
OutputStreamWriter os = new OutputStreamWriter(urlConn.getOutputStream(), "UTF-8");
os.write(postData);
Log.i("NOTIFICATION", "Data Sent");
os.flush();
os.close();
BufferedReader reader = new BufferedReader(new InputStreamReader(urlConn.getInputStream()));
String msg = "";
String line = "";
while ((line = reader.readLine()) != null) {
msg += line;
}
Log.i("msg=", "" + msg);
} catch (JSONException jsonex) {
jsonex.printStackTrace();
Log.e("jsnExce", jsonex.toString());
}
} catch (MalformedURLException muex) {
// TODO Auto-generated catch block
muex.printStackTrace();
} catch (IOException ioex) {
ioex.printStackTrace();
try { //if there is IOException clean the connection and clear it for reuse(works if the stream is not too long)
int respCode = urlConn.getResponseCode();
InputStream es = urlConn.getErrorStream();
byte[] buffer = null;
int ret = 0;
// read the response body
while ((ret = es.read(buffer)) > 0) {
Log.e("streamingError", String.valueOf(respCode) + String.valueOf(ret));
}
// close the errorstream
es.close();
} catch(IOException ex) {
// deal with the exception
ex.printStackTrace();
}
}
} catch (Exception e) {
e.printStackTrace();
Log.e("ERROR", "There is error in this code " + String.valueOf(e));
}
}
}
Doesn't it get executed in a worker thread? If the answer is no why does the docs say that it is an alternative to AsyncTask?
Your code must not be in the void run() method. This is where the asynchronous code is ran.

Android HttpPost request to server

i want to send data from android SqLite database to my Codeigniter web App controller which take the post data and save it to MySql database
so i made buttn to make this sync task in android app and its code:
public void syncAttendance(View v) {
try
{
/** Retrieving data from database **/
//use cursor to keep all data
//cursor can keep data of any data type
Cursor c=db.rawQuery("select * from mytable", null);
int memNum = 1;
//move cursor to first position
c.moveToFirst();
//fetch all data one by one
do
{
//we can use c.getString(0) here
//or we can get data using column index
String memID = c.getString(c.getColumnIndex("memID"));
String currTime = c.getString(c.getColumnIndex("currTime"));
String dayName = c.getString(c.getColumnIndex("dayName"));
////////////////////////////////////////
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://mywebsite.com/index.php/admin/attendance/scan_qr");
JSONObject json = new JSONObject();
/** try {**/
// JSON data:
json.put("memID", memID);
json.put("currTime", currTime);
json.put("dayName", dayName);
JSONArray postjson=new JSONArray();
postjson.put(json);
// Post the data:
httppost.setHeader("json",json.toString());
httppost.getParams().setParameter("jsonpost",postjson);
// Execute HTTP Post Request
System.out.print(json);
HttpResponse response = httpclient.execute(httppost);
// for JSON:
if(response != null)
{
InputStream is = response.getEntity().getContent();
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) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
text = sb.toString();
}
//tv.setText(text);
/**
}catch (ClientProtocolException e) {
// TODO Auto-generated catch block
} catch (IOException e) {
// TODO Auto-generated catch block
}
**/
//////////////////////////////////////////
/** show confirmation toast **/
Toast toast = Toast.makeText(this, memNum + memID + currTime + dayName, Toast.LENGTH_LONG);
toast.show();
memNum ++;
//move next position until end of the data
}while(c.moveToNext());
/** show confirmation toast **/
Toast toast = Toast.makeText(this, "Synchronization Completed", Toast.LENGTH_LONG);
toast.show();
}
catch(Exception e)
{
e.printStackTrace();
}
}
and the php codeigniter controller code is:
public function scan_qr()
{
$json = $_SERVER['HTTP_JSON'];
var_dump($json);
$data = json_decode($json);
var_dump($data);
$memID = $data->memID;
$currTime = $data->currTime;
$dayName = $data->dayName;
$ma7abawy_year = 3;
$data= array(
'member_id' => $memID,
//'points' => $points,
'presence_time' => $currTime,
//'event' => $eventname,
'event_date' => $dayName,
'ma7abawy_year' => $ma7abawy_year
);
$this->db->insert('attendance',$data);
}
i have no exception but nothing is happened
any ideas would be appreciated
I would suggest to use retrofit (see API docs) library to consume the service. Afterwards, see what you get back in the response and it will be a simple matter of saving the data to the sqlite3 db. See example for saving data.

Trouble with setting the Nest field values via java/android code

I am writing android code to change the field in a Nest thermostat using the newly released API. Authentication and getting the field values is working just perfect, however I am haing problem with changing the field values. Based on the the API for changing the field values you need to use HTTP put, but once I am doing this, nothing happens in the device (the value (e.g. the value of target_temperature_f doesn't change!))
Here is my android code:
String url = "https://developer-api.nest.com/devices/thermostats/"
+ this.device_id + "?auth=" + this.access_token;
try{
HttpClient httpclient = new DefaultHttpClient();
/** set the proxy , not always needed */
HttpHost proxy = new HttpHost(proxy_ip,proxy_port);
httpclient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY,proxy);
// Set the new value
HttpPut httpPut = new HttpPut(url);
httpPut.setHeader("Content-Type", "application/json");
JSONObject jsonObj = new JSONObject("{\"target_temperature_f\":'60'}");
HttpEntity put_entity = new StringEntity(jsonObj.toString());
httpPut.setEntity(put_entity);
HttpResponse put_response = httpclient.execute(httpPut);
I can set the field in the device via "curl" command in linux though!! So the device is working fine.
Any help is highly appreciated!
I'm unsure of how to do it using the DefaultHttpClient and according to the documentation it has been deprecated in favor of HttpURLConnection.
Here's some code that uses HttpURLConnection that I've tested with Hue lights.
This will open a URL connection and perform a POST query with the given body. The readFromHttpConnection method expects a JSON response. It looks like Nest uses JSON so this may work for your needs.
private String synchronousPostMethod(String destination, String body)
{
Log.i(TAG, "Attempting HTTP POST method. Address=" + destination + "; Body=" + body);
String responseReturn;
try
{
HttpURLConnection httpConnection = openConnection(destination);
httpConnection.setDoOutput(true);
httpConnection.setRequestMethod("POST");
writeToHttpConnection(httpConnection, body);
responseReturn = readFromHttpConnection(httpConnection);
}
catch(Exception e)
{
responseReturn = RESPONSE_FAIL_MESSAGE + "; exception = " + e;
}
Log.i(TAG, "Result of HTTP POST method: " + responseReturn);
return responseReturn;
}
These are the helper methods.
private HttpURLConnection openConnection(String destination)
{
HttpURLConnection httpConnection = null;
try
{
URL connectionUrl = new URL(destination);
httpConnection = (HttpURLConnection) connectionUrl.openConnection();
}
catch(MalformedURLException malformedUrlException)
{
Log.w(TAG, "Failed to generate URL from malformed destination: " + destination);
Log.w(TAG, "MalformedURLException = " + malformedUrlException);
}
catch(IOException ioException)
{
Log.w(TAG, "Could not open HTTP connection. IOException = " + ioException);
}
return httpConnection;
}
private boolean writeToHttpConnection(HttpURLConnection httpConnection, String data)
{
// No data can be written if there is no connection or data
if(httpConnection == null || data == null)
{
return false;
}
try
{
OutputStreamWriter outputStream = new OutputStreamWriter(httpConnection.getOutputStream());
outputStream.write(data);
outputStream.close();
}
catch(IOException ioException)
{
Log.w(TAG, "Failed to get output stream from HttpUrlConnection. IOException = " + ioException);
return false;
}
return true;
}
private String readFromHttpConnection(HttpURLConnection httpConnection)
{
String responseReturn = "";
if(httpConnection != null)
{
try
{
InputStream response = httpConnection.getInputStream();
int size;
do
{
byte[] buffer = new byte[mResponseBufferSize];
size = response.read(buffer, 0, mResponseBufferSize);
// Convert the response to a string then add it to the end of the buffer
responseReturn += new String(buffer, 0, size);
}while(size < mResponseBufferSize || size <= 0);
// Cleanup
response.close();
}
catch (IOException ioException)
{
Log.w(TAG, "Failed to get input stream from HttpUrlConnection. IOException = " + ioException);
}
}
return responseReturn;
}

clientprotocolexception DefaultHttpClient.execute()

I am using the following code to request a response from a webserver. The server sends a malformed response without headers which causes a ClientProtocolException. I have tried to use inspectors but they are not called before the exception is fired. I cannot change the server (it is within an embedded device, ALFA router R36).
Any suggestions to deal with this problem (btw: the code works perfect if the server response is well-formed)
Thanks in advance, Ton
class httpRequestTask extends AsyncTask <Integer, Integer, Integer> {
StringBuffer respTxt = new StringBuffer("");
int reqCode = 0;
protected Integer doInBackground(Integer... requestCode) {
Integer reqStatus = 0;
String url = "http://192.168.2.1/";
String authString = ("admin:admin");
switch( reqCode = requestCode[0].intValue()){
case Constants.HTTP_GET_STATUS_INFO: url += "/adm/status_info.asp"; break;
case Constants.HTTP_SCAN: url += "/goform/getUsbStaBSSIDListForm"; break;
}
try {
DefaultHttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet();
HttpResponse response;
request.setURI( new URI( url));
request.addHeader("Authorization", "Basic " + Base64.encodeToString(authString.getBytes(),Base64.NO_WRAP));
response = client.execute(request);
reqStatus = response.getStatusLine().getStatusCode();
String line;
BufferedReader in = new BufferedReader( new InputStreamReader(response.getEntity().getContent()));
while((line = in.readLine()) != null) respTxt.append(line);
} catch ( ClientProtocolException e){
Log.e("ALFA", "HTTPReq:ClientProtocolException " + e.toString());
} catch ( IOException e){
Log.e("ALFA", "HTTPReq:IOException " + e.toString());
} catch ( Exception e){
Log.e("ALFA", "HTTPReq:Exception " + e.toString());
}
return reqStatus;
}
protected void onPostExecute(Integer reqStatus) {
Intent intent = new Intent(Constants.HTTP_RESPONSE);
intent.putExtra( "reqCode", reqCode);
intent.putExtra( "reqStatus", reqStatus);
intent.putExtra( "rspTxt", respTxt.toString());
getBaseContext().sendBroadcast(intent);
}
}
Looking further to find a solution to the problem I found a suggestion to use a socket to request the server. I used Fiddler in combination with a browser on my PC to examine the data send to and received from the buggy server and read an article on Wikipedia, explaining the HTTP protocol. With that info and by using a Socket, I wrote a very basic httpRequestHandler than deals with the miss formed response from the buggy web server.
class httpSocketRequest extends AsyncTask<Integer, Integer, Integer> {
StringBuffer respTxt = new StringBuffer("");
int reqCode = 0;
int reqStatus = 0;
protected Integer doInBackground(Integer... requestCode) {
String ip = "192.168.2.1";
String path = "";
String authString = ("admin:admin");
Socket socket = null;
switch( reqCode = requestCode[0].intValue()){
case Constants.HTTP_GET_STATUS_INFO: path = "adm/status_info.asp"; break;
case Constants.HTTP_SCAN: path = "goform/getUsbStaBSSIDListForm"; break;
}
try {
socket = new Socket( ip, 80);
PrintWriter out = new PrintWriter( socket.getOutputStream());
out.println( "GET http://" + ip + "/" + path + " HTTP/1.0");
out.println( "Authorization: Basic " + Base64.encodeToString(authString.getBytes(),Base64.NO_WRAP));
out.println( "");
out.flush();
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
String line;
int lineCnt = 0;
while((line = in.readLine()) != null){
if( lineCnt >= 0){
lineCnt++;
if(lineCnt == 1){ // first line should start with "HTTP/1.x " followed by a 3 digit status
if( line.length() > 12 && line.substring(0, 6).equals("HTTP/1")){
int p = line.indexOf(" ");
reqStatus = Integer.parseInt(line.substring(p+1, p+4));
continue;
} else { // not a well formed response
lineCnt = -1; // just put everything into respTxt
reqStatus = 200; // and assume everything went OK
}
} else if( lineCnt > 1){ // process rest of headers
if( line.length() == 0){
lineCnt = -1; // done with headers
} else {
// TODO insert code to process other headers
}
continue;
}
}
respTxt.append(line + "\n");
}
} catch (Exception e) {
Log.e("ALFA", "HTTPReq:Exception " + e.toString());
} finally {
try {
if( socket != null) socket.close();
} catch (IOException e) {
Log.e("ALFA", "HTTPReq:Exception closing socket" + e.toString());
}
}
return reqStatus;
}
protected void onPostExecute(Integer reqStatus) {
Intent intent = new Intent(Constants.HTTP_RESPONSE);
intent.putExtra( "reqCode", reqCode);
intent.putExtra( "reqStatus", reqStatus);
intent.putExtra( "rspTxt", respTxt.toString());
getBaseContext().sendBroadcast(intent);
}
}

Why does Android not send my second SSL request?

My Android app is talking to a webserver using SSL and GET requests. After switching to API 10 (Gingerbread) the SSL connection works - but only for the first time after the app starts...
The first request is sent by the main activity - after getting a response, another activity starts and sends multiple requests. And none of them is answered. In both cases the request is sent using a litte WebService class that is initiated in a new AsyncTask. After downsizing this alass, the only thing it actually contains is the URL(-String). Each activity starts its own instance of this class.
Here is the method that should do the GET request. As easily visible I included some code to avoid keep-alive - not that I don't like it, but it has been suggested in other answers to do so to avoid problems with multiple connections. Well, it did not work in my case.
public String webGet(String methodName, Map<String, String> params) {
String getUrl = webServiceUrl + methodName;
index++;
final int connectionID = index;
int i = 0;
for (Map.Entry<String, String> param : params.entrySet()) {
if (i == 0) {
getUrl += "?";
} else {
getUrl += "&";
}
try {
getUrl += param.getKey() + "=" + URLEncoder.encode(param.getValue(), "UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
i++;
}
String response;
Log.e("WebGetURL", "["+connectionID+"] " + getUrl);
URL url;
try {
url = new URL(getUrl);
} catch (MalformedURLException e) {
Log.e("WebService", "Malformed URL: " + getUrl);
return null;
}
HttpURLConnection urlConnection;
try {
Log.e("WebGetResponse", "["+connectionID+"] openConnection()");
System.setProperty("http.keepAlive", "false");
if (webServiceSsl) {
Log.e("WebService", "Using HTTPS");
urlConnection = (HttpsURLConnection) url.openConnection();
} else {
urlConnection = (HttpURLConnection) url.openConnection();
}
urlConnection.setUseCaches(false);
urlConnection.setRequestProperty("Connection","Keep-Alive");
urlConnection.setDoOutput(false);
urlConnection.setDoInput(true);
urlConnection.setRequestMethod("GET");
} catch (IOException e) {
Log.e("WebService", "I/O exception opening connection: " + e.getMessage());
e.printStackTrace();
return null;
}
urlConnection.setConnectTimeout(5000);
urlConnection.setReadTimeout(10000);
urlConnection.setRequestProperty("Connection", "close");
try {
urlConnection.connect();
Log.e("WebGetResponse", "["+connectionID+"] getInputStream()");
// This is the last thing I hear from my thread
BufferedInputStream bin = new BufferedInputStream(urlConnection.getInputStream());
Log.e("WebGetResponse", "["+connectionID+"] gotInputStream()");
byte[] contents = new byte[1024];
int bytesRead=0;
StringBuilder strFileContents = new StringBuilder();
Log.e("WebGetResponse", "["+connectionID+"] Waiting for data");
while((bytesRead = bin.read(contents)) != -1) {
String add = new String(contents, 0, bytesRead);
strFileContents.append(add);
}
bin.close();
response = strFileContents.toString();
} catch (IOException e) {
Log.e("WebService", "I/O exception reading stream: " + e.getMessage());
e.printStackTrace();
return null;
} finally {
urlConnection.disconnect();
}
Log.e("WebGetResponse", "["+connectionID+"] " + response);
return response;
}
I have been trying ans searching - I don't get the problem. Actually I cannot test the class on a non-https server currently, so I am unaware if the problem occurs in HTTP as well. However, the handshake seems to work, because the first request works well.
And here is the code that should start the request (final param is the GET content to send):
class ServerDataThread extends AsyncTask<Integer, Integer, String[]> {
#Override
protected String[] doInBackground(Integer... attempts) {
sendActive++;
int count = attempts.length;
String[] responses = new String[count];
for (int i = 0; i < count; i++) {
responses[i] = server.webGet("collector.php", params);
}
return responses;
}
protected void onPostExecute(String[] responses) {
sendActive--;
for (int i = 0; i < responses.length; i++) {
if (responses[i] == null) {
continue;
}
onResponseData(responses[i]);
}
}
}
new ServerDataThread().execute(0);
Could anyone please help me out with a hint what I am doing wrong? Thank you very much!
BurninLeo

Categories

Resources