Why does Android not send my second SSL request? - android

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

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.

SocketTimeoutException in HttpURLConnection randomly in getResponseCode

I am getting following error in con.getResponseCode()
java.net.SocketTimeoutException: failed to connect to example.com (port 80) after 3000ms
at libcore.io.IoBridge.connectErrno(IoBridge.java:223)
at libcore.io.IoBridge.connect(IoBridge.java:127)
at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:192)
at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:475)
at java.net.Socket.connect(Socket.java:861)
at com.android.okhttp.internal.Platform.connectSocket(Platform.java:152)
at com.android.okhttp.Connection.connect(Connection.java:101)
at com.android.okhttp.internal.http.HttpEngine.connect(HttpEngine.java:294)
at com.android.okhttp.internal.http.HttpEngine.sendSocketRequest(HttpEngine.java:255)
at com.android.okhttp.internal.http.HttpEngine.sendRequest(HttpEngine.java:206)
at com.android.okhttp.internal.http.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:345)
at com.android.okhttp.internal.http.HttpURLConnectionImpl.getResponse(HttpURLConnectionImpl.java:296)
at com.android.okhttp.internal.http.HttpURLConnectionImpl.getResponseCode(HttpURLConnectionImpl.java:503)
First time when it gets called it works perfectly.
But it stops working after it and it may start working randomly after some time.
public class HTTPLoader {
public static String loadContentFromURLGET(String urlString,List<String[]> getVars,Context context){
int retry = 0;
HttpURLConnection con=null;
BufferedReader in = null;
StringBuffer response=null;
if (!isConnectingToInternet(context)){
return "{'error':'No Internet connection!'}";
}
while (retry++<=RETRY_CNT) {
try {
String urlParameters = "";
for (String[] var : getVars) {
urlParameters += var[0] + "=" + URLEncoder.encode(var[1], "UTF-8") + "&";
}
if (urlParameters.length() > 1) {
urlParameters = urlParameters.substring(0, urlParameters.length() - 1);
}
if (urlString.charAt(urlString.length() - 1) != '?') {
urlString += "&";
}
URL url = new URL(urlString + urlParameters);
con = (HttpURLConnection) url.openConnection();
con.setConnectTimeout(3000);
con.setRequestMethod("GET");
con.setRequestProperty("User-Agent", USER_AGENT);
con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");
con.setDoInput(true);
con.setDoOutput(true);
int responseCode = con.getResponseCode();
in = new BufferedReader(
new InputStreamReader(con.getInputStream()));
String inputLine;
response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
retry = RETRY_CNT+1;
break;
} catch (IOException e) {
e.printStackTrace();
Log.e(TAG, e.getMessage());
}finally {
if (in!=null){
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (con!=null) {
con.disconnect();
}
in = null;
con = null;
}
}
if (response!=null)
return new String(response);
return "{'error':'No Internet connection!'}";
}
}
This loadContentFromURLGET is getting called from IntentService
public class ChatUtil extends IntentService{
protected String loadAllChats(String date){
String response = "";
try {
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
String email = sharedPreferences.getString(QuickstartPreferences.EMAIL, "");
List<String[]> postVars = new ArrayList<>();
postVars.add(new String[]{"getconversation", "yes"});
postVars.add(new String[]{"user_id", email});
postVars.add(new String[]{"last_date", date});
String urlString = getString(R.string.get_conversation_url);
response = HTTPLoader.loadContentFromURLGET(urlString, postVars,getApplicationContext());
Log.i(TAG, response.toString());
JSONObject jsonObject = new JSONObject(response);
if (jsonObject.has("error")) {
//Toast.makeText(getApplicationContext(), jsonObject.getString("error"), Toast.LENGTH_SHORT).show();
return jsonObject.getString("error");
}
}catch (JSONException e) {
}
}
protected void onHandleIntent(Intent intent) {
String task = intent.getStringExtra(QuickstartPreferences.CURRENT_TASK);
Intent nintent;
String date = "";
String[] arr3 = new NewsDBUtil(getApplicationContext()).getLastChatEntry(null);
if (arr3!=null)
date = arr3[1];
loadAllChats(date);
nintent = new Intent(QuickstartPreferences.LOADING_ALL_CHAT);
LocalBroadcastManager.getInstance(getApplicationContext()).sendBroadcast(nintent);
}
}
Tried closing and disconnecting stream in finally block.
But no Success.
you can put con.getResponseCode(); between try ...catch block if it throw SocketTimeoutException Exception make another try , but make sure you extend your timeout
if (responseCode != 200) {
....
...
} catch (final java.net.SocketTimeoutException e) {
// connection timed out...let's try again
}
may this help
Without specific ContentLength via setFixedLengthStreamingMode
I found some devices generated incomplete http request
cause the server has to wait until either server or client timed out
you can use wireshark to analyze the problem

How to get a working HttpsUrlConnection with Steam Web API?

im currently trying to implement the Steam Web API using the given code in the following repository -> https://github.com/Overv/SteamWebAPI/blob/master/SteamAPISession.cs into my Android app and im getting different exceptions dependend on using the given wep api ip ( 63.228.223.110 ) or the adress ( https://api.steampowered.com/ ) itself.
my code actually looks like this in the given method when building up a connection to the web api:
private String steamRequest( String get, String post ) {
final int MAX_RETRIES = 3;
int numberOfTries = 0;
HttpsURLConnection request = null;
while(numberOfTries < MAX_RETRIES) {
if (numberOfTries != 0) {
Log.d(TAG, "Retry -> " + numberOfTries);
}
try {
request = (HttpsURLConnection) new URL("https://api.steampowered.com/" + get).openConnection(); //or 63.228.223.110/ ???
SSLSocketFactory socketFactory = (SSLSocketFactory) SSLSocketFactory.getDefault();
String host = "api.steampowered.com";
int port = 443;
int header = 0;
socketFactory.createSocket(new Socket(host, port), host, port, false);
request.setHostnameVerifier(new HostnameVerifier() {
#Override
public boolean verify(String s, SSLSession sslSession) {
return true;
}
});
request.setSSLSocketFactory(socketFactory);
request.setDoOutput(false);
// request.setRequestProperty("Host", "api.steampowered.com:443");
// request.setRequestProperty("Protocol-Version", "httpVersion");
request.setRequestProperty("Accept", "*/*");
request.setRequestProperty("Accept-Encoding", "gzip, deflate");
request.setRequestProperty("Accept-Language", "en-us");
request.setRequestProperty("User-Agent", "Steam 1291812 / iPhone");
request.setRequestProperty("Connection", "close");
if (post != null) {
byte[] postBytes;
try {
request.setRequestMethod("POST");
postBytes = post.getBytes("US-ASCII");
// request.setRequestProperty("Content-Length", Integer.toString(postBytes.length));
request.setFixedLengthStreamingMode(postBytes.length);
request.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
PrintWriter out = new PrintWriter(request.getOutputStream());
out.print(post);
out.close();
// DataOutputStream requestStream = new DataOutputStream(request.getOutputStream());
//// OutputStreamWriter stream = new OutputStreamWriter(request.getOutputStream());
//// stream.write(postBytes, 0, postBytes.length);
// requestStream.write(postBytes, 0, postBytes.length);
// requestStream.close();
message++;
} catch (ProtocolException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
try {
int statusCode = request.getResponseCode();
InputStream is;
Log.d(TAG, "The response code of the status code is" + statusCode);
if (statusCode != 200) {
is = request.getErrorStream();
Log.d(TAG, String.valueOf(is));
}
// String src = null;
// OutputStreamWriter out = new OutputStreamWriter(request.getOutputStream());
// out.write(src);
// out.close();
Scanner inStream = new Scanner(request.getInputStream());
String response = "";
while (inStream.hasNextLine()) {
response += (inStream.nextLine());
}
// String src;
// BufferedReader in = new BufferedReader(new InputStreamReader(request.getInputStream()));
// StringBuilder builder = new StringBuilder();
// while ((src = in.readLine()) != null) {
// builder.append(src);
// }
// String jsonData = builder.toString();
Log.d(TAG, response); //jsonData
// in.close();
return response; //jsonData
} catch (MalformedURLException ex) {
Toast.makeText(getActivity(), ex.toString(), Toast.LENGTH_LONG).show();
ex.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (request != null) {
request.disconnect();
}
}
numberOfTries++;
}
Log.d(TAG, "Max retries reached. Giving up on connecting to Steam Web API...");
return null;
}
following exception occurs when using https://api.steampowered.com/ as url:
W/System.err﹕ java.io.FileNotFoundException: https://api.steampowered.com/ISteamOAuth2/GetTokenWithCredentials/v0001
D/OptionsFragment﹕ Failed to log in!
i've really tried and researched on those issues, but i just can't get a solution. If someone got a good hint on helping to solve these exceptions please let me know!
EDIT:
I've researched some more!
Looking up on https://partner.steamgames.com/documentation/webapi#creating the direct ip adress shouldn't be used and therefore only the DNS name itself (for further clarification look on the given link). Hence, looking up on the API interface list itself -> http://api.steampowered.com/ISteamWebAPIUtil/GetSupportedAPIList/v0001/?format=json there doesn't seem to be a given Interface with a method called ISteamOAuth2/GetTokenWithCredentials.(Or not anymore!) Only ISteamUserAuth and ISteamUserOAuth which seem to handle Authentication stuff.
I will update this post again if i should get a working connection and handling with the steam web api.
Cheers!

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;
}

Unable to set notifyDataSetChanged in 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();

Categories

Resources