After execution for 5 to 6 times i am not able to get response and the message is also not going to gateway and the application get struck.At InputStreamReader i am not able to get any response after execution for 5 times.When i checked the logs no error is coming but the Input Stream is not printing.
XMLFunctions.java
public static String getLocalCurtainControlResponse( String ipadress, String imvgid, String deviceid, String command, String value, int slidedValue) {
String result = null;
BufferedReader reader =null;
System.out.println("getLocalCurtainControlResponse : IN");
System.out.println("command : " + command);
System.out.println("value : " + value);
byte[] loginBytes = ("admin" + ":" + "admin").getBytes();
StringBuilder loginBuilder = new StringBuilder()
.append("Basic ")
.append(Base64.encodeToString(loginBytes, Base64.DEFAULT));
try {
URL url = new URL("http://" + ipadress + "/cgi-bin/WebInterface.cgi?ImvgId=" + imvgid + "%20&DeviceId=" + deviceid + "%20&Action=" + command + "%20&Value=" + value + "%20&Level=" + slidedValue + "%20&App=MID");
System.out.print("step0"+"http://" + ipadress + "/cgi-bin/WebInterface.cgi?ImvgId=" + imvgid + "%20&DeviceId=" + deviceid + "%20&Action=" + command + "%20&Value=" + value + "%20&Level=" + slidedValue + "%20&App=MID");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
// connection.setRequestMethod("GET");
connection.addRequestProperty("Authorization", loginBuilder.toString());
// connection.connect();
InputStream in = connection.getInputStream();
System.out.print("step1"+connection);
StringBuilder sb = new StringBuilder();
System.out.print("step2"+sb);
reader = new BufferedReader(new InputStreamReader(in));
System.out.print("step3"+reader);
String line;
while ((line = reader.readLine()) != null) {
sb.append(line);
sb.append("\n");
}
System.out.print("step4"+sb);
reader.close();
result = sb.toString();
System.out.print("step5"+result);
} catch (MalformedURLException e) {
e.printStackTrace();
System.out.print("Hiiiiiiiiiiiiiiiiiiii"+e.getMessage());
} catch (IOException e) {
e.printStackTrace();
System.out.print("Byeeeeeeeeee"+e.getMessage());
} finally {
if (null!=reader) {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
System.out.print("Hellllloooooooo"+e.getMessage());
}
}
}
return result;
}
Find the solution Post and Get using HttpUrlConnection
private Object doSendRequest(final int requestCode, String url, final Object params, final String sessionId, final String requestType, final Activity parentActivity) {
URL myurl;
Log.v("sessionId", sessionId + "");
HttpsURLConnection httpsURLConnection = null;
try {
if (requestType.equalsIgnoreCase("GET")) {
if (params.toString().length() >= 1) {
if (url.contains("?")) {
url = (url + params.toString());
} else {
url = (url + "?" + params.toString());
}
}
}
myurl = new URL(url);
Log.v("RequestCode, URL", requestCode + " : " + url);
httpsURLConnection = (HttpsURLConnection) myurl.openConnection();
httpsURLConnection.setRequestMethod(requestType);
httpsURLConnection.setUseCaches(true);
if (isOnline(parentActivity)) {
httpsURLConnection.addRequestProperty("Cache-Control", "max-age=0");
} else {
httpsURLConnection.setUseCaches(true);
httpsURLConnection.addRequestProperty("Cache-Control", "max-stale=" + CACHE_STALE_TIME_OUT);
httpsURLConnection.addRequestProperty("Cache-Control", "only-if-cached");
}
httpsURLConnection.setConnectTimeout(20 * ONE_SECOND);
httpsURLConnection.setReadTimeout(20 * ONE_SECOND);
httpsURLConnection.setInstanceFollowRedirects(true);
httpsURLConnection.setRequestProperty("Content-Type", CONTENT_TYPE_APPLICATION_JSON);
if (sessionId != null) {
httpsURLConnection.setRequestProperty("sessionId", sessionId);
}
httpsURLConnection.setDoInput(true);
if (!requestType.equalsIgnoreCase("GET")) {
Log.v("RequestData", "" + params.toString());
httpsURLConnection.setDoOutput(true);
BufferedWriter writer = null;
try {
writer = new BufferedWriter(new OutputStreamWriter(httpsURLConnection.getOutputStream(), "UTF-8"));
writer.write(params.toString());
writer.flush();
}catch (Exception e){
e.printStackTrace();
}finally {
if(writer != null){
try {
writer.close();
}catch (Exception e){
e.printStackTrace();
}
}
}
}
httpsURLConnection.connect();
} catch (Exception e) {
Log.v("Ex", "1");
e.printStackTrace();
handleException(requestCode, e, parentActivity);
return null;
}
//---------------------READING THE RESPONSE---------------------------//
BufferedReader bReader = null;
try {
final String newSessionId = httpsURLConnection.getHeaderField("sessionId");
final int httpResponseCode = httpsURLConnection.getResponseCode();
Log.v("Req, Response codes", requestCode+", "+httpResponseCode);
if(httpResponseCode == 504 && !LegionUtils.isOnline(parentActivity)){
parentActivity.runOnUiThread(new Runnable() {
#Override
public void run() {
hideProgressDialog();
showOfflineDialog(parentActivity);
}
});
return null;
}
if (httpResponseCode == 401) {
parentActivity.runOnUiThread(new Runnable() {
#Override
public void run() {
hideProgressDialog();
}
});
return null;
} else if ((httpResponseCode == 400 || (httpResponseCode >= 500 && httpResponseCode <= 599)) && !(parentActivity instanceof CreateAccountActivity)) {
parentActivity.runOnUiThread(new Runnable() {
#Override
public void run() {
hideProgressDialog();
networkCallback.onFailure(requestCode, null);
}
});
return null;
} else if ((httpResponseCode >= 500 && httpResponseCode <= 599) && (parentActivity instanceof CreateAccountActivity)) {
parentActivity.runOnUiThread(new Runnable() {
#Override
public void run() {
networkCallback.onFailure(requestCode, null);
}
});
return null;
}
InputStream inputStream;
try {
inputStream = httpsURLConnection.getInputStream();
}catch (FileNotFoundException e){
e.printStackTrace();
inputStream = httpsURLConnection.getErrorStream();
}
if (inputStream != null) {
bReader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
String inputLine;
final StringBuffer response = new StringBuffer();
while ((inputLine = bReader.readLine()) != null) {
response.append(inputLine);
}
bReader.close();
parentActivity.runOnUiThread(new Runnable() {
#Override
public void run() {
Log.v("RESPONSE " + requestCode, response.toString());
networkCallback.onSuccess(requestCode, response.toString(), newSessionId);
}
});
}
} catch (Exception e) {
Log.v("Ex", "2");
e.printStackTrace();
handleException(requestCode, e, parentActivity);
} finally {
try {
if (bReader != null) {
bReader.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
return null;
}
private void handleException(final int requestCode, Exception error, final Activity parentActivity) {
final String errorResponse;
if (error instanceof TimeoutException || error instanceof SocketTimeoutException || error instanceof UnknownHostException) {
errorResponse = "Your request has been timed out. Please try again later.";
} else if (error instanceof SSLException || error instanceof ConnectException) {
errorResponse = null;
parentActivity.runOnUiThread(new Runnable() {
#Override
public void run() {
hideProgressDialog();
showOfflineDialog(parentActivity);
}
});
} /*else if (error instanceof FileNotFoundException) {
errorResponse = "Invalid Request.\nPlease try again later.";
} */else if (error instanceof IOException) {
errorResponse = "Something went wrong. Please try again later.";
} else if (error instanceof JSONException) {
errorResponse = "Unexpected response.\nPlease try again later.";
} else {
errorResponse = null;
parentActivity.runOnUiThread(new Runnable() {
#Override
public void run() {
hideProgressDialog();
showOfflineDialog(parentActivity);
}
});
}
Log.v("FAILURE ERR RESPONSE " + requestCode, errorResponse + "");
parentActivity.runOnUiThread(new Runnable() {
#Override
public void run() {
networkCallback.onFailure(requestCode, errorResponse);
}
});
}
Related
My app crashes only on a smartphone with android 10 ... not on a smartphone with android 9 Why?
This is my error:
Thread[7,tid=8537,WaitingInMainSignalCatcherLoop,Thread*=0x70f8fa2c00,peer=0x131c0378,"Signal Catcher"]: reacting to signal 3
Wrote stack traces to tombstoned
onCreate method (NetActivity.java):
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
NetClient task = new NetClient();
payload = task.execute(ip, String.valueOf(Global.config_device), Global.uid, network.getSSID(), password, friendlyName).get();
}
}
});
My AsyncTask (NetClient.java):
public class NetClient extends AsyncTask<String, Void, String> {
Socket socket = null;
PrintWriter out = null;
BufferedReader buffer = null;
String ip;
int port = 8899;
String response = "";
int errors = 0;
private String[] conn_errors = {"", String.valueOf(R.string.error_provision), "Error: socket close...", "Error: receiving message...", "Unknown error...", "Error disconnecting socket..."};
protected Boolean connect() {
boolean res = false;
try {
if (socket == null) {
socket = new Socket(ip, port);
if (socket.isConnected()) {
res = true;
}
out = new PrintWriter(socket.getOutputStream());
buffer = new BufferedReader(new InputStreamReader(socket.getInputStream()));
}
} catch (IOException e) {
Log.e("ERROR connect", e.getMessage());
errors = 1;
}
return res;
}
protected void disConnect() {
if (socket != null) {
if (socket.isConnected()) {
try {
out.close();
socket.close();
} catch (IOException e) {
e.printStackTrace();
errors = 5;
}
}
}
}
protected void sendData(String message) {
if (message != null) {
out.write(message);
out.flush();
}
}
protected String receiveData() {
try {
String message = "";
message = buffer.readLine();
message += buffer.readLine();
message += buffer.readLine();
message += buffer.readLine();
message += buffer.readLine();
return message;
} catch (IOException e) {
errors = 3;
return "Error receiving response: " + e.getMessage();
}
}
#Override
protected String doInBackground(String... params) {
boolean conn;
ip = params[0];
String message = "Teste sample" ;
try {
conn = connect();
Log.w("NetClient", "" + conn);
if (conn) {
sendData(message);
} else {
errors = 2;
}
if (conn) {
response = receiveData();
} else {
errors = 2;
}
} catch (Exception e) {
Log.w("NetClient", "Exception");
e.printStackTrace();
errors = 4;
} finally {
disConnect();
Log.i("NetClient", "Finished");
return response;
}
return String.valueOf(errors);
}
protected void onProgressUpdate(Integer... progress) {
Log.w("onProgressUpdate", "Progress: " + progress[0]);
}
protected void onPostExecute(String result) {
if (errors == 0) {
Log.i("onPostExecute", "Payload [" + result.length() + "] : " + result);
}
if (errors > 0) {
Log.i("ERROR", conn_errors[errors]);
}
}
}
Hi i have a requirement of calling a web service when application goes to background and come back to foreground.I tried both Volley and HttpURLConnection but unfortunately both of them are not working for me. Some times it gives result but some times it is not.Below is my code
#Override
protected void onResume() {
try {
super.onResume();
// app.activityResumed();
// Toast.makeText(this, "QuizActivity Resumed", Toast.LENGTH_LONG).show();
/* if (session.getAreaName()!= null) {
if (GetGeoCodingTask.mAutoCompText != null)
autoCompView.setText(GetGeoCodingTask.mAutoCompText);
}*/
if (GetGeoCodingTask.mAutoCompText != null) {
autoCompView.setText(GetGeoCodingTask.mAutoCompText);
}
autoCompView.post(new Runnable() {
public void run() {
autoCompView.dismissDropDown();
}
});
LoadFoodListData();
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(this, e.getMessage(), Toast.LENGTH_LONG).show();
}
}
and my Method using HttpURLConnection is
private void LoadFoodListData() {
try {
StringBuffer chaine = new StringBuffer("");
URL url = new URL(myUrl);
connectionOpp = (HttpURLConnection) url.openConnection();
//connection.setReadTimeout(15000);
//connection.setConnectTimeout(15000);
connectionOpp.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
connectionOpp.setRequestMethod("POST");
connectionOpp.setDoInput(true);
connectionOpp.setDoOutput(true);
Log.d("Tag", "Webservice after connect");
OutputStream os = connectionOpp.getOutputStream();
BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(os, "UTF-8"));
writer.write(child.toString());
writer.flush();
writer.close();
os.close();
connectionOpp.connect();
int responseCode = connectionOpp.getResponseCode();
Log.d("Tag", String.valueOf(responseCode));
if (responseCode == HttpsURLConnection.HTTP_OK) {
// Toast.makeText(mContext, "Httpok",Toast.LENGTH_SHORT).show();
InputStream inputStream = connectionOpp.getInputStream();
Log.d("Tag", "Webservice httpok");
BufferedReader rd = new BufferedReader(new InputStreamReader(inputStream));
String line = "";
while ((line = rd.readLine()) != null) {
chaine.append(line);
}
}
String readJSON = chaine.toString();
} catch (Exception e) {
e.printStackTrace();
}
}
and Using Volley is
private void LoadFoodListData() {
final ProgressDialog ringProgressDialog = ProgressDialog.show(QuizActivity.this, "Please wait ...", "Fetching data nearby you ...", true);
ringProgressDialog.setCancelable(false);
JsonObjectRequest jsObjRequest = null;
try {
jsObjRequest = new JsonObjectRequest(Request.Method.POST, myurl, child,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
ongoing = response.getJSONArray("Listongoing");
if (ongoing != null) {
if (ongoing.length() != 0) {
runOnUiThread(new Runnable() {
#Override
public void run() {
livecount.setText("(" + ongoing.length() + ")");
}
});
}
}
upcoming = response.getJSONArray("ListUpcoming");
Expire = response.getJSONArray("ListExpire");
if (Expire != null) {
if (Expire.length() != 0) {
runOnUiThread(new Runnable() {
#Override
public void run() {
expiredcount.setText("(" + Expire.length() + ")");
}
});
}
}
}
catch (JSONException e) {
e.printStackTrace();
ringProgressDialog.dismiss();
}
// dialogPro.cancel();
ringProgressDialog.dismiss();
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
ringProgressDialog.dismiss();
}
});
} catch (Exception e) {
ringProgressDialog.dismiss();
}
if (jsObjRequest != null) {
jsObjRequest.setRetryPolicy(new DefaultRetryPolicy(0, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
}
AppController.getInstance().addToRequestQueue(jsObjRequest);
}
Any help would be very thankfull.
In here the code with BufferedReaderand line = reader.readLine() works
public class WeatherService extends AsyncTask<TaskParams, Void, String> {
private WeatherServiceCallback callback;
private Exception exception;
public WeatherService(WeatherServiceCallback callback) {
this.callback = callback;
}
#Override
protected String doInBackground(TaskParams... params) {
try {
URL url = new URL("http://api.openweathermap.org/data/2.5/weather?lat=" +
params[0].getLat() + "&lon=" + params[0].getLon() +
"&units=" + TaskParams.getUnits() +
"&type=" + TaskParams.getAccuracy() + "&lang=" + TaskParams.getLanguage() +
"&appid=10660a09a9fb335d72f576f7aa1bbe5b");
URLConnection connection = url.openConnection();
InputStream inputStream = connection.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
StringBuilder builder = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
builder.append(line);
}
return builder.toString();
} catch (MalformedURLException e) {
exception = e;
} catch (IOException e) {
exception = e;
}
return null;
}
#Override
protected void onPostExecute(String s)
{
if (s == null && exception != null)
{
callback.serviceFailure(exception);
return;
}
try
{
JSONObject data = new JSONObject(s);
Parameters parameters = new Parameters();
parameters.poopulate(data);
callback.serviceSuccess(parameters);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
I copy-pasted code to other class since it has very similar functionality and now for no reason I'm getting NullPointerException in while ((line = reader.readLine()) != null) and I have no idea why since as I said it's copy-pasted (I only changed URL and object returned if serivce succeeds)
public class PollutionService extends AsyncTask<TaskParams, Void, String>
{
private PollutionServiceCallback callback;
private Exception exception;
private URLConnection connection;
private InputStream inputStream;
private InputStreamReader streamReader;
private BufferedReader reader;
public PollutionService(PollutionServiceCallback callback) {
this.callback = callback;
}
#Override
protected String doInBackground(TaskParams... params) {
try
{
URL url = new URL("http://api.openweathermap.org/pollution/v1/co/" + params[0].getLat() +
"," + params[0].getLon() + "/current.json?&appid=10660a09a9fb335d72f576f7aa1bbe5b");
try
{
connection = url.openConnection();
}
catch (IOException e)
{
exception = new Exception("Connection error");
}
try
{
inputStream = connection.getInputStream();
}
catch (IOException e)
{
exception = new Exception("Input stream error");
}
try
{
streamReader = new InputStreamReader(inputStream);
}
catch (NullPointerException e)
{
exception = new Exception("Input stream reader error");
}
try
{
reader = new BufferedReader(streamReader);
}
catch (NullPointerException e)
{
exception = new Exception("Buffered reader error");
}
StringBuilder builder = new StringBuilder();
String line;
try
{
while ((line = reader.readLine()) != null)
{
builder.append(line);
}
}
catch (IOException e)
{
exception = e;
}
return builder.toString();
}
catch (MalformedURLException e)
{
exception = e;
}
return null;
}
#Override
protected void onPostExecute(String s)
{
if (s == null && exception != null)
{
callback.pollutionServiceFailure(exception);
return;
}
try
{
JSONObject data = new JSONObject(s);
PollutionParameters parameters = new PollutionParameters();
parameters.poopulate(data);
callback.pollutionServiceSuccess(parameters);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
Any clue?
EDIT
This is rewritten code for PollutionActivity. Callback function serviceFailure prints now the URL address on my phone's screen
public class PollutionService extends AsyncTask<TaskParams, Void, String>
{
private PollutionServiceCallback callback;
private Exception exception;
public PollutionService(PollutionServiceCallback callback) {
this.callback = callback;
}
#Override
protected String doInBackground(TaskParams... params) {
try
{
URL url = new URL("http://api.openweathermap.org/pollution/v1/co/" + params[0].getLat() +
"," + params[0].getLon() + "/current.json?&appid=10660a09a9fb335d72f576f7aa1bbe5b");
URLConnection connection = url.openConnection();
InputStream inputStream = connection.getInputStream();
InputStreamReader streamReader = new InputStreamReader(inputStream);
BufferedReader reader = new BufferedReader(streamReader);
StringBuilder builder = new StringBuilder();
String line;
try
{
while ((line = reader.readLine()) != null)
{
builder.append(line);
}
}
catch (IOException e)
{
exception = e;
}
return builder.toString();
}
catch (MalformedURLException e)
{
exception = e;
}
catch (IOException e)
{
exception = e;
}
return null;
}
#Override
protected void onPostExecute(String s)
{
if (s == null && exception != null)
{
callback.pollutionServiceFailure(exception);
return;
}
try
{
JSONObject data = new JSONObject(s);
PollutionParameters parameters = new PollutionParameters();
parameters.poopulate(data);
callback.pollutionServiceSuccess(parameters);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
Debugging showed me that code jumps to exception after
InputStream inputStream = connection.getInputStream();
If you are getting NPE for reader then it means that reader is not getting initialized and going null.Your code is getting crash at line 23 and 89. So I believe that the problem is right at the start somewhere and not at the point itself, may be some object is going null like connection.Since line number is not displayed here.Check null pointer for every object like if (connection!=null). Since the initial data is coming null,maybe input stream or some other data,hence your reader object is not getting initialized.Also check if you are getting value for every object in debug.
I am trying to parse some data from server and compare the data with the data in the database...
Everything seems working fine... except I am getting only same value even the comparing data change... I'll explain it with the code...
In the below code, there is textviews tv3 and tv4... even the comparing data ie, shopid changed, it shows the value from the first array of the json...
when i tried to debug, i found the the run() inside the runOnUithread is calling after 2-3 loops... i donno whats happening here... Please somone help ,e to sort out the issue...
Edit: while debugging when i skip to each line it not showing any error...
But when i try to skip to the breakpoints using F9 it shows the error...
Edit: 2: Since the code is litle bit long, i juz deleted som unwanted part...
private Bitmap downloadBitmap(String url) {
HttpURLConnection urlConnection = null;
try {
URL uri = new URL(url);
urlConnection = (HttpURLConnection) uri.openConnection();
int statusCode = urlConnection.getResponseCode();
if (statusCode != HttpStatus.SC_OK) {
return null;
}
InputStream inputStream = urlConnection.getInputStream();
if (inputStream != null) {
bitmap = BitmapFactory.decodeStream(inputStream);
return bitmap;
}
} catch (Exception e) {
urlConnection.disconnect();
Log.w("ImageDownloader", "Error downloading image from " + url);
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
}
return null;
}
#Override
public void onResume() {
mapView.onResume();
super.onResume();
}
#Override
public void onDestroy() {
super.onDestroy();
mapView.onDestroy();
}
#Override
public void onLowMemory() {
super.onLowMemory();
mapView.onLowMemory();
}
private class GetJsondata extends AsyncTask<Void, Void, String> {
#Override
protected void onPreExecute() {
dialog = ProgressDialog.show(getActivity(), "", getActivity().getResources().getString(R.string.pleasewait), true);
}
#Override
protected String doInBackground(Void... arg0) {
// Creating service handler class instance
ConnectivityManager conMgr = (ConnectivityManager) getActivity().getSystemService(Context.CONNECTIVITY_SERVICE);
activeNetwork = conMgr.getActiveNetworkInfo();
if (activeNetwork != null && activeNetwork.isConnected()) {
ServiceHandler sh = new ServiceHandler();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(url, ServiceHandler.GET);
Log.d("Response: ", "> " + jsonStr);
if (jsonStr != null) {
try {
jsonObj = new JSONObject(jsonStr);
ObjectOutput out = new ObjectOutputStream(new FileOutputStream
(new File(getActivity().getCacheDir(), "") + File.separator + "cacheFile.srl"));
out.writeObject(jsonObj.toString());
out.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
} else {
try {
ObjectInputStream in = new ObjectInputStream(new FileInputStream
(new File(getActivity().getCacheDir() + File.separator + "cacheFile.srl")));
jsonObj = new JSONObject((String) in.readObject());
in.close();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (OptionalDataException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (StreamCorruptedException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
}
if (jsonObj != null) {
try {
ofrList = new ArrayList<ArrayList<String>>();
// Getting JSON Array node
jsonArray = jsonObj.getJSONArray("offers");
shoplistarray = new ArrayList<ArrayList<String>>();
// looping through All Contacts
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject c = jsonArray.getJSONObject(i);
url1 = c.getString("url");
if (userPrefs.getString("locale", null) == null || userPrefs.getString("locale", null).equals("en")) {
desc = c.getString("desc");
} else {
desc = c.getString("desc_ar");
}
expdate = c.getString("expdate");
ofrdate = c.getString("date");
shopsarray = c.getJSONArray("shops");
for (int n = 0; n < shopsarray.length(); n++) {
JSONObject jobj = shopsarray.getJSONObject(n);
shopid = jobj.getString("shopid");
if (shopid.equals(id) && tv3.getText().toString().equals("") ) {
downloadBitmap(url1);
finalI = i;
getActivity().runOnUiThread(new Runnable() {
public void run() {
if (activeNetwork != null && activeNetwork.isConnected()) {
image.setImageBitmap(bitmap);
saveFileInCache(String.valueOf(finalI), bitmap);
} else {
getFileOutOfCache(String.valueOf(finalI));
image.setImageBitmap(bitmap);
}
tv3.setText(desc);
tv4.setText(getActivity().getResources().getString(R.string.validtill) + expdate);
}
});
}
}
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
getActivity().runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(getActivity(), getActivity().getResources().getString(R.string.urnotconnected), Toast.LENGTH_LONG).show();
}
});
}
return desc;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
dialog.dismiss();
}
}
private Bitmap getFileOutOfCache(String fileName) {
final String cachePath = getActivity().getCacheDir().getPath();
File myDiskCacheFilePath = new File(cachePath);
File myCachedFile = new File(myDiskCacheFilePath
+ File.separator + fileName);
if (myCachedFile.exists()) {
bitmap = BitmapFactory.decodeFile(myCachedFile.toString());
} else {
Toast.makeText(getActivity(), getActivity().getResources().getString(R.string.cachedfilenotexist), Toast.LENGTH_LONG).show();
}
return bitmap;
}
public void saveFileInCache(String aFileName, Bitmap myImage) {
final String cachePath = getActivity().getCacheDir().getPath();
File myDiscCacheFilePath;
myDiscCacheFilePath = new File(cachePath);
File myDiscCacheFile = new File(myDiscCacheFilePath + File.separator + aFileName);
try {
FileOutputStream out = new FileOutputStream(myDiscCacheFile);
myImage.compress(Bitmap.CompressFormat.JPEG, 80, out);
out.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
Toast.makeText(getActivity(), getActivity().getResources().getString(R.string.cachefailed), Toast.LENGTH_SHORT).show();
} catch (IOException e) {
e.printStackTrace();
}
}
}
private Bitmap downloadBitmap(String url) {
HttpURLConnection urlConnection = null;
try {
URL uri = new URL(url);
urlConnection = (HttpURLConnection) uri.openConnection();
int statusCode = urlConnection.getResponseCode();
if (statusCode != HttpStatus.SC_OK) {
return null;
}
InputStream inputStream = urlConnection.getInputStream();
if (inputStream != null) {
bitmap = BitmapFactory.decodeStream(inputStream);
return bitmap;
}
} catch (Exception e) {
urlConnection.disconnect();
Log.w("ImageDownloader", "Error downloading image from " + url);
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
}
return null;
}
#Override
public void onResume() {
mapView.onResume();
super.onResume();
}
#Override
public void onDestroy() {
super.onDestroy();
mapView.onDestroy();
}
#Override
public void onLowMemory() {
super.onLowMemory();
mapView.onLowMemory();
}
private class GetJsondata extends AsyncTask<Void, Void, String> {
boolean isIfCondition=false;
#Override
protected void onPreExecute() {
dialog = ProgressDialog.show(getActivity(), "", getActivity().getResources().getString(R.string.pleasewait), true);
}
#Override
protected String doInBackground(Void... arg0) {
// Creating service handler class instance
ConnectivityManager conMgr = (ConnectivityManager) getActivity().getSystemService(Context.CONNECTIVITY_SERVICE);
activeNetwork = conMgr.getActiveNetworkInfo();
if (activeNetwork != null && activeNetwork.isConnected()) {
ServiceHandler sh = new ServiceHandler();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(url, ServiceHandler.GET);
Log.d("Response: ", "> " + jsonStr);
if (jsonStr != null) {
try {
jsonObj = new JSONObject(jsonStr);
ObjectOutput out = new ObjectOutputStream(new FileOutputStream
(new File(getActivity().getCacheDir(), "") + File.separator + "cacheFile.srl"));
out.writeObject(jsonObj.toString());
out.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
} else {
try {
ObjectInputStream in = new ObjectInputStream(new FileInputStream
(new File(getActivity().getCacheDir() + File.separator + "cacheFile.srl")));
jsonObj = new JSONObject((String) in.readObject());
in.close();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (OptionalDataException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (StreamCorruptedException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
}
if (jsonObj != null) {
try {
ofrList = new ArrayList<ArrayList<String>>();
// Getting JSON Array node
jsonArray = jsonObj.getJSONArray("offers");
shoplistarray = new ArrayList<ArrayList<String>>();
// looping through All Contacts
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject c = jsonArray.getJSONObject(i);
url1 = c.getString("url");
if (userPrefs.getString("locale", null) == null || userPrefs.getString("locale", null).equals("en")) {
desc = c.getString("desc");
} else {
desc = c.getString("desc_ar");
}
expdate = c.getString("expdate");
ofrdate = c.getString("date");
shopsarray = c.getJSONArray("shops");
for (int n = 0; n < shopsarray.length(); n++) {
JSONObject jobj = shopsarray.getJSONObject(n);
shopid = jobj.getString("shopid");
if (shopid.equals(id) && tv3.getText().toString().equals("") ) {
downloadBitmap(url1);
finalI = i;
//no need to use runonuithread since post execute methods already runs on main ui thread ..rather set isIfCondition=true and do this job on postexecute method
isIfCondition=true;
desc1=desc;
expdate1=expdate;
/*getActivity().runOnUiThread(new Runnable() {
public void run() {
if (activeNetwork != null && activeNetwork.isConnected()) {
image.setImageBitmap(bitmap);
saveFileInCache(String.valueOf(finalI), bitmap);
} else {
getFileOutOfCache(String.valueOf(finalI));
image.setImageBitmap(bitmap);
}
tv3.setText(desc);
tv4.setText(getActivity().getResources().getString(R.string.validtill) + expdate);
}
});*/
}
}
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
//no need to use runonuithread since post execute methods already runs on main ui thread
/*getActivity().runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(getActivity(), getActivity().getResources().getString(R.string.urnotconnected), Toast.LENGTH_LONG).show();
}
});*/
}
return desc;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
dialog.dismiss();
if(isIfCondition=true)
{
if (activeNetwork != null && activeNetwork.isConnected()) {
image.setImageBitmap(bitmap);
saveFileInCache(String.valueOf(finalI), bitmap);
} else {
getFileOutOfCache(String.valueOf(finalI));
image.setImageBitmap(bitmap);
}
tv3.setText(desc1);
tv4.setText(getActivity().getResources().getString(R.string.validtill) + expdate1);
}
}
}
private Bitmap getFileOutOfCache(String fileName) {
final String cachePath = getActivity().getCacheDir().getPath();
File myDiskCacheFilePath = new File(cachePath);
File myCachedFile = new File(myDiskCacheFilePath
+ File.separator + fileName);
if (myCachedFile.exists()) {
bitmap = BitmapFactory.decodeFile(myCachedFile.toString());
} else {
Toast.makeText(getActivity(), getActivity().getResources().getString(R.string.cachedfilenotexist), Toast.LENGTH_LONG).show();
}
return bitmap;
}
public void saveFileInCache(String aFileName, Bitmap myImage) {
final String cachePath = getActivity().getCacheDir().getPath();
File myDiscCacheFilePath;
myDiscCacheFilePath = new File(cachePath);
File myDiscCacheFile = new File(myDiscCacheFilePath + File.separator + aFileName);
try {
FileOutputStream out = new FileOutputStream(myDiscCacheFile);
myImage.compress(Bitmap.CompressFormat.JPEG, 80, out);
out.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
Toast.makeText(getActivity(), getActivity().getResources().getString(R.string.cachefailed), Toast.LENGTH_SHORT).show();
} catch (IOException e) {
e.printStackTrace();
}
}
there is not need to use runonuithread or any other thread...because asynctask is already do this for you..doinbackground work run on bgthread and onpostexecute work on mainuithread..
Just check the code...i haven't check..but it will work for sure....
ConnectivityManager conMgr = (ConnectivityManager) getActivity().getSystemService(Context.CONNECTIVITY_SERVICE);
activeNetwork = conMgr.getActiveNetworkInfo();
if (activeNetwork != null && activeNetwork.isConnected()) {
new GetJsondata().execute()
}else{
//show toast
}
Write the above code in the place where you are calling the asynctask.Remove it from the asynctask itself.
I am using Thread for Webservice but i cant get the data from Thread because i cant return data from Thread.
This is my WebService.java :
public class Webservice {
static String result;
public static String readUrl(final String url) {
Thread thread = new Thread(new Runnable() {
#Override
public void run() {
try {
HttpClient client = new DefaultHttpClient();
HttpPost method = new HttpPost(url);
HttpResponse response = client.execute(method);
InputStream stream = response.getEntity().getContent();
result = ConvertInputStreamToString(stream);
Log.i("xxx","OK" + result);
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
});
thread.start();
return result;
}
private static String ConvertInputStreamToString(InputStream inputstteam) {
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
inputstteam));
StringBuilder builder = new StringBuilder();
String line = "";
while ((line = reader.readLine()) != null) {
builder.append(line);
}
return builder.toString();
}
catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
This is NotesActivity.java :
public class NotesActivity extends Activity {
private ArrayList<StructTask> nettasks = new ArrayList<StructTask>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Thread thread = new Thread(new Runnable() {
#Override
public void run() {
String result = Webservice.readUrl("http://192.168.200.101:8081/note-server/");
if (result != null) {
try {
JSONArray tasks = new JSONArray(result);
for (int i = 0; i < tasks.length(); i++) {
JSONObject object = tasks.getJSONObject(i);
//Log.i("LOG", "Task: " + object.getString("task_title"));
StructTask task = new StructTask();
task.id = object.getLong("task_id");
task.title = object.getString("task_title");
task.desc = object.getString("task_desc");
task.done = object.getBoolean("task_done");
nettasks.add(task);
for (StructTask taskes : nettasks) {
Log.i("LOG", "Taskes: " + taskes.id + "|" + taskes.title + "|" + taskes.desc + "|" + taskes.done);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
else
{
Log.i("OK", "TaskesOK: " + result);
Log.i("LOG", "Task: " + "NULL");
}
}
});
thread.start();
}
}
This is my StructTask.java :
public class StructTask {
public long id;
public String title;
public String desc;
public boolean done;
}
This code return for me NULL .
Just try this way
1) Webservice.java
public class Webservice {
public interface WebCallListener{
void onCallComplete(String result);
}
public static void readUrl(final String url,final WebCallListener callListener) {
Thread thread = new Thread(new Runnable() {
#Override
public void run() {
try {
HttpClient client = new DefaultHttpClient();
HttpPost method = new HttpPost(url);
HttpResponse response = client.execute(method);
InputStream stream = response.getEntity().getContent();
callListener.onCallComplete(ConvertInputStreamToString(stream));
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
});
thread.start();
}
private static String ConvertInputStreamToString(InputStream inputstteam) {
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
inputstteam));
StringBuilder builder = new StringBuilder();
String line = "";
while ((line = reader.readLine()) != null) {
builder.append(line);
}
return builder.toString();
}
catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
2) NotesActivity.java
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Webservice.readUrl("http://192.168.200.101:8081/note-server/",new WebCallListener() {
#Override
public void onCallComplete(String result) {
if (result != null) {
try {
JSONArray tasks = new JSONArray(result);
for (int i = 0; i < tasks.length(); i++) {
JSONObject object = tasks.getJSONObject(i);
//Log.i("LOG", "Task: " + object.getString("task_title"));
StructTask task = new StructTask();
task.id = object.getLong("task_id");
task.title = object.getString("task_title");
task.desc = object.getString("task_desc");
task.done = object.getBoolean("task_done");
nettasks.add(task);
}
for (StructTask taskes : nettasks) {
Log.i("LOG", "Taskes: " + taskes.id + "|" + taskes.title + "|" + taskes.desc + "|" + taskes.done);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
else
{
Log.i("OK", "TaskesOK: " + result);
Log.i("LOG", "Task: " + "NULL");
}
}
});
}
You may use your code some thing like this:
private class ImageDownloader extends AsyncTask {
#Override
protected Bitmap doInBackground(String... param) {
// TODO Auto-generated method stub
return myBackgroundImageDownloadFun(param[0]);
}
#Override
protected void onPreExecute() {
Log.i("Async-Example", "onPreExecute Called");
simpleWaitDialog = ProgressDialog.show(ImageDownladerActivity.this,
"Wait", "Downloading Image");
}
#Override
protected void onPostExecute(Bitmap result) {
Log.i("Async-Example", "onPostExecute Called");
MyImageView.setImageBitmap(result);
simpleWaitDialog.dismiss();
}
For this you can use AsyncTask i.e,
private class Webservice extends AsyncTask<Void, Void, ArrayList<StructTask>> {
private ArrayList<StructTask> nettasks = new ArrayList<StructTask>();
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected ArrayList<StructTask> doInBackground(Void... params) {
try {
String result = readUrl("http://192.168.200.101:8081/note-server/");
JSONArray tasks = new JSONArray(result);
for (int i = 0; i < tasks.length(); i++) {
JSONObject object = tasks.getJSONObject(i);
//Log.i("LOG", "Task: " + object.getString("task_title"));
StructTask task = new StructTask();
task.id = object.getLong("task_id");
task.title = object.getString("task_title");
task.desc = object.getString("task_desc");
task.done = object.getBoolean("task_done");
nettasks.add(task);
}
for (StructTask taskes : nettasks) {
Log.i("LOG", "Taskes: " + taskes.id + "|" + taskes.title + "|" + taskes.desc + "|" + taskes.done);
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return nettasks;
}
/* after parsing response this method will be called*/
#Override
protected void onPostExecute(ArrayList<StructTask> result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
}
private String readUrl(String url) throws Exception{
HttpClient client = new DefaultHttpClient();
HttpPost method = new HttpPost(url);
HttpResponse response = client.execute(method);
InputStream stream = response.getEntity().getContent();
String result = ConvertInputStreamToString(stream);
Log.i("xxx", "OK" + result);
return result;
}
private String ConvertInputStreamToString(InputStream inputstteam) {
try {
BufferedReader reader = new BufferedReader(
new InputStreamReader(inputstteam));
StringBuilder builder = new StringBuilder();
String line = "";
while ((line = reader.readLine()) != null) {
builder.append(line);
}
return builder.toString();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
In your activity class in onCreate method try to call like this
Webservice service=new Webservice();
service.excute();
so it will starts the excution of the above thread.
i think this will helps you