I suspect I’m running into some issues borne out of threading in my simple Android app.
I have a Activity which does the following:
- runs a dialog on main thread
- spins a background thread and hits a PHP script for retreiving data using
DefaultHttpClientand close this connection. This successfully returns a URL to a picture on the internet - open
HttpUrlConnectioncalledconnand try conn.connect - app freezes at this point with no error
Not sure what code to put here, I could paste it all but that would be too much so let me know if any more info is needed:
/**
* Background Async Task to Load all Question by making HTTP Request
*/
class LoadAllImages extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
@Override
protected void onPreExecute() {
super.onPreExecute();
// dialog init'd here
}
@Override
protected String doInBackground(String... args) {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
// getting JSON string from URL
JSONObject json = jParser.makeHttpRequest(url_question_details, "GET", params);
// Check your log cat for JSON response
Log.d("All Questions: ", json.toString());
try {
// images found
// Getting Array of questions
images = json.getJSONArray(TAG_IMAGES);
// looping through All questions
for (int i = 0; i < images.length(); i++) {
JSONObject c = images.getJSONObject(i);
// Storing each json item in variable
String id = c.getString(TAG_IMAGEID);
String location = c.getString(TAG_IMAGELOCATION);
URL myFileUrl = null;
try {
myFileUrl = new URL(location);
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
HttpURLConnection conn = (HttpURLConnection) myFileUrl.openConnection();
conn.setDoInput(true);
conn.connect(); // freezes here
int length = conn.getContentLength();
int[] bitmapData = new int[length];
byte[] bitmapData2 = new byte[length];
InputStream is = conn.getInputStream();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Remove these 2 lines:
When you do this:
You are already connected. Calling
conn.getContentLength()causesHttpURLConnectionto make the connection, sends the request and fetches the response. You don’t need to explicitly connect. You also don’t need to callsetDoInput(true)since that is the default setting.