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.
Related
I have two AppCompatActivitys, both should have an onItemClickListener, but one of them doesn't do anything on click. I've just added a Toast for test reason, later on it should call a function to delete an item from list (with an ajax request)
What am I doing wrong?
I have made custom list and custom adapter for this - I know, I am new to Android Studio, but the other Activity works fine, and I cant find any differences.
public class ActivityListofProducts extends AppCompatActivity {
ProgressDialog pd;
SharedPreferences preferences;
String userid;
String session;
String list_id = "-1"; // or other values
String appVersion = "";
private ArrayList<listProductItem> myProducts = new ArrayList<listProductItem>();
private ArrayList<listProductItem> groceryFilterProducts = new ArrayList<listProductItem>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
handleIntent(getIntent());
setContentView(R.layout.activity_list_of_products);
this.setTitle(getString(R.string.grocery_list));
Bundle b = getIntent().getExtras();
SwipeRefreshLayout swipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.refreshLayout);
if (b != null)
list_id = b.getString("list_id");
Toast.makeText(this, "List to open " + " " + list_id, Toast.LENGTH_SHORT).show();
preferences =
getSharedPreferences(this.getPackageName(), this.MODE_PRIVATE);
userid = preferences.getString("userid", "");
session = preferences.getString("session", "");
appVersion = preferences.getString("appVersion", "");
getData();
swipeRefreshLayout.setOnRefreshListener(
new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
getData();
swipeRefreshLayout.setRefreshing(false);
}
}
);
}
public void getData() {
AsyncTask<String, String, String> Task_GetListofProducts = new Task_GetListofProducts();
Task_GetListofProducts.execute("https://get-some-json.com");
}
public void initListofProducts(String jsonString) {
Log.i("jsonString",jsonString);
try {
JSONObject jsonResponse = new JSONObject(jsonString);
JSONObject jsonListMode = jsonResponse.getJSONObject("list");
String ListName = jsonListMode.optString("name");
this.setTitle(ListName);
JSONArray jsonMainNode = jsonResponse.optJSONArray("data");
for (int i = 0; i < jsonMainNode.length(); i++) {
JSONObject jsonChildNode = jsonMainNode.getJSONObject(i);
int item_amount = jsonChildNode.optInt("item_amount");
int id = jsonChildNode.optInt("id");
String item_name = jsonChildNode.optString("item_name",">Name<");
int done = jsonChildNode.optInt("done", 0);
String timestamp = jsonChildNode.optString("timestamp", "");
String item_scale = jsonChildNode.optString("item_scale", "x");
String img = jsonChildNode.optString("img", "x");
double bestprice = jsonChildNode.optDouble("bestprice");
//int oitems = jsonChildNode.optInt("oitems", 0);
//int shared = jsonChildNode.optInt("shared", 0);
String outPut = "item_amount:"+ item_amount +" id:"+ id +" item_name:"+ item_name +" done:"+ done +" timestamp:"+ timestamp +" item_scale:"+ item_scale +" img:"+ img;
Log.i("outPut",outPut);
myProducts.add(new listProductItem(id, item_name, item_amount, item_scale, img, done, timestamp, bestprice));
}
final ListView lv = findViewById(R.id.grocery_list_of_products);
lv.setAdapter(new listofProductsAdapter(this, myProducts));
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> a, View v, int position, long id) {
/*
!! HERE is my problem. This Code seems not to be executed !!
*/
Toast.makeText(ActivityListofProducts.this, "Should handle click now.", Toast.LENGTH_SHORT).show();
}
});
} catch (JSONException e) {
Toast.makeText(getApplicationContext(), "Error" + e.toString(), Toast.LENGTH_SHORT).show();
}
}
public void setProductDone(int pid, int done) {
String url = "put-some-json.com";
new ActivityListofProducts.Task_SetProductDone().execute(url);
}
private class Task_SetProductDone extends AsyncTask<String, String, String> {
protected void onPreExecute() {
super.onPreExecute();
pd = new ProgressDialog(ActivityListofProducts.this);
pd.setMessage("Please wait");
pd.setCancelable(false);
pd.show();
}
protected String doInBackground(String... params) {
HttpURLConnection connection = null;
BufferedReader reader = null;
Log.i("doInBackground",params.toString());
try {
URL url = new URL(params[0]);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
InputStream stream = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(stream));
StringBuffer buffer = new StringBuffer();
String line = "";
while ((line = reader.readLine()) != null) {
buffer.append(line + "\n");
Log.d("Response: ", "> " + line); //here you will get whole response...... :-)
}
return buffer.toString();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (UnknownHostException e) {
Toast.makeText(ActivityListofProducts.this, "No Internet?", Toast.LENGTH_SHORT).show();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (connection != null) {
connection.disconnect();
}
try {
if (reader != null) {
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
if (pd.isShowing()) {
pd.dismiss();
}
Log.i("onPostExecute", result);
}
}
private class Task_GetListofProducts extends AsyncTask<String, String, String> {
protected void onPreExecute() {
super.onPreExecute();
pd = new ProgressDialog(ActivityListofProducts.this);
pd.setMessage("Please wait");
pd.setCancelable(false);
pd.show();
myProducts = new ArrayList<listProductItem>(); //empty list
}
protected String doInBackground(String... params) {
HttpURLConnection connection = null;
BufferedReader reader = null;
Log.i("doInBackground",params.toString());
try {
URL url = new URL(params[0]);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
InputStream stream = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(stream));
StringBuffer buffer = new StringBuffer();
String line = "";
while ((line = reader.readLine()) != null) {
buffer.append(line + "\n");
Log.d("Response: ", "> " + line); //here you will get whole response...... :-)
}
return buffer.toString();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (connection != null) {
connection.disconnect();
}
try {
if (reader != null) {
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
if (pd.isShowing()) {
pd.dismiss();
}
initListofProducts(result);
}
}
private class Task_FindProducts extends AsyncTask<String, String, String> {
protected void onPreExecute() {
super.onPreExecute();
pd = new ProgressDialog(ActivityListofProducts.this);
pd.setMessage("Please wait");
pd.setCancelable(false);
pd.show();
myProducts = new ArrayList<listProductItem>(); //empty list
}
protected String doInBackground(String... params) {
HttpURLConnection connection = null;
BufferedReader reader = null;
Log.i("doInBackground",params.toString());
try {
URL url = new URL(params[0]);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
InputStream stream = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(stream));
StringBuffer buffer = new StringBuffer();
String line = "";
while ((line = reader.readLine()) != null) {
buffer.append(line + "\n");
Log.d("Response: ", "> " + line); //here you will get whole response...... :-)
}
return buffer.toString();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (connection != null) {
connection.disconnect();
}
try {
if (reader != null) {
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
if (pd.isShowing()) {
pd.dismiss();
}
setFilterProducts(result);
}
}
}
I try to create synchronized threads, but I always get the following error: android.os.NetworkOnMainThreadException.
I've read more posts, but they don't work for me.
Below I write the code blocks that do not work for me:
1.
final SyncApp syncJob = new SyncApp();
Thread t = new Thread (new Runnable () {
#Override
public void run () {
synchronized (syncJob) {
String s = syncJob.insert (newJobs, GlobalVariables.URL_LOCALHOST + "jobs");
txtState.setText (s);
}}});
}
});
t.Start ();
// t.run ();
2.
myClass.runOnUiThread(new Runnable() {
public void run() {...}
})
3.
Running code in main thread from another thread
SyncApp:
public class SyncApp {
synchronized public String insert(List<Jobs> job, String... params) {
URL url = null;
HttpURLConnection conn = null;
try {
url = new URL(params[0]);
conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/json");
conn.setDoInput(true);
conn.setDoOutput(true);
String str = new Gson().toJson(job);
byte[] outputInBytes = str.getBytes();
OutputStream os = conn.getOutputStream();
os.write( outputInBytes );
os.flush();
int responseCode=conn.getResponseCode();
String response = null;
if (responseCode == HttpsURLConnection.HTTP_OK) {
String line;
BufferedReader br=new BufferedReader(new InputStreamReader(conn.getInputStream()));
while ((line=br.readLine()) != null) {
response+=line;
}
}
else {
response=conn.getResponseMessage();
}
return response;
} catch (Exception e) {
e.printStackTrace();
} finally {
conn.disconnect();
}
return null;
}
}
I need to call a thread, wait for the answer and call another thread. Their answers I must use them in the activity
I need to call a thread, wait for the answer and call another thread.
Their answers I must use them in the activity
Example using async tasks to accomplish objective.
In this code, let A be your activity which needs to call a thread,
wait for the answer and call another thread. Customize as needed.
Since you never wait in UI threads, callbacks are used to accomplish synchronization.
Let A be your activity class:
public class A extends Activity {
// some method in activity where you launch a background thread (B)
// which then completes and invokes callback which then creates and launches
// a background thread (C) which then completes and invokes a callback.
//
// In callback C, you are on the UI thread.
protected void someMethod() {
new B(new B.CallbackB() {
public void result(Object o) {
new C(new C.CallbackC() {
public void result(Object o, Object answerFromB) {
// OK - C is now done and we are on UI thread!
// 'o' is answer from C
// 'answerFromB' also provided
}
}, o).execute(new Object());
}
).execute(new Object());
}
}
Define a class B:
public class B extends AsyncTask<Object, Void, Object> {
public static interface CallbackB {
void result(Object o);
}
private CallbackB cb;
public B (CallbackB cb) {
this.cb = cb;
}
protected Object doInBackground(Object... params) {
// do work and return an answer.
return new Object();
}
protected void onPostExecute(Object result) {
if (cb != null) {
cb.result(result);
}
}
}
Define a class C:
public class C extends AsyncTask<Object, Void, Object> {
public static interface CallbackC {
void result(Object o, Object answerFromB);
}
private CallbackC cb;
private Object answerFromB;
public C (CallbackC cb, Object answerFromB) {
this.cb = cb;
this.answerFromB = answerFromB;
}
protected Object doInBackground(Object... params) {
// do work and return an answer.
return new Object();
}
protected void onPostExecute(Object result) {
if (cb != null) {
cb.result(result, answerFromB);
}
}
}
For reference:
https://stackoverflow.com/a/9963705/2711811
My solution is:
public class Sync extends AppCompatActivity {
...
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sync_server);
dao = new DAO(this);
txtState = findViewById(R.id.txt_log);
btnSincro = findViewById(R.id.btn_sincro);
btnSincro.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
countCall = 0;
callFlow();
}
});
btnHome = findViewById(R.id.btn_home);
btnHome.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(SyncServerActivity.this, MainActivity.class);
startActivity(intent);
}
});
}
private void callFlow() {
switch (countCall) {
case 0:
templates = toTemplate("url");
break;
case 1:
jobs = toJobs("url");
break;
case 2:
job = ... //select item
res = sendJobs(jobs, "url");
break;
default:
runOnUiThread(new Runnable() {
#Override
public void run() {
btnSincro.setEnabled(true);
txtState.append("\n\nEND");
}
});
}
}
private void nextStep() {
setText(txtState, "\nSync \n" + countCall + "/3");
countCall++;
callFlow();
}
private void setText(final TextView text, final String value) {
runOnUiThread(new Runnable() {
#Override
public void run() {
text.setText(value);
}
});
}
public List<Templates> toTemplate(final String... params) {
final List<Templates> list = new ArrayList<>();
Thread t = new Thread(new Runnable() {
#Override
public void run() {
URL url = null;
BufferedReader reader = null;
HttpURLConnection connection = null;
try {
url = new URL(params[0]);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
InputStream stream = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(stream));
int responseCode = connection.getResponseCode();
String response = null;
if (responseCode == HttpsURLConnection.HTTP_OK) {
StringBuffer buffer = new StringBuffer();
String line = "";
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
String finalJson = buffer.toString();
JSONObject parentObject = new JSONObject(finalJson);
JSONArray parentArray = parentObject.getJSONArray("data");
for (int i = 0; i < parentArray.length(); i++) {
Templates item = new Gson().fromJson(parentArray.get(i).toString(), Templates.class);
list.add(item);
}
} else {
response = connection.getResponseMessage();
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
} finally {
if (connection != null)
connection.disconnect();
try {
if (reader != null)
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
nextStep(); //call next Thread
}
}
});
t.start();
return list;
}
public List<Jobs> toJobs(final String... params) {
final List<Jobs> list = new ArrayList<>();
Thread t = new Thread(new Runnable() {
#Override
public void run() {
URL url = null;
BufferedReader reader = null;
HttpURLConnection connection = null;
try {
url = new URL(params[0]);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
InputStream stream = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(stream));
int responseCode = connection.getResponseCode();
String response = null;
if (responseCode == HttpsURLConnection.HTTP_OK) {
StringBuffer buffer = new StringBuffer();
String line = "";
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
String finalJson = buffer.toString();
JSONObject parentObject = new JSONObject(finalJson);
JSONArray parentArray = parentObject.getJSONArray("data");
for (int i = 0; i < parentArray.length(); i++) {
Jobs item = new Gson().fromJson(parentArray.get(i).toString(), Jobs.class);
list.add(item);
}
} else {
response = connection.getResponseMessage();
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
} finally {
if (connection != null)
connection.disconnect();
try {
if (reader != null)
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
nextStep();
}
}
});
t.start();
return list;
}
public Boolean sendJobs(final List<Jobs> job, final String... params) {
final Boolean[] result = {false};
Thread t = new Thread(new Runnable() {
#Override
public void run() {
URL url = null;
HttpURLConnection conn = null;
try {
url = new URL(params[0]);
conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/json");
conn.setDoInput(true);
conn.setDoOutput(true);
String str = new Gson().toJson(job);
Log.d(TAG, str);
byte[] outputInBytes = str.getBytes();
OutputStream os = conn.getOutputStream();
os.write(outputInBytes);
os.flush();
int responseCode = conn.getResponseCode();
String response = null;
if (responseCode == HttpsURLConnection.HTTP_OK) {
String line;
BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
while ((line = br.readLine()) != null) {
response += line;
}
result[0] = true;
} else {
response = conn.getResponseMessage();
}
} catch (Exception e) {
e.printStackTrace();
} finally {
conn.disconnect();
nextStep();
}
}
});
t.start();
return result[0];
}
}
Whenever a thread ends, it calls the nextStep() method, which starts the next trhead.
its my json file
{"VisitorsList":[{"VisitorID":"09005451","VisitorName":" xxxx","VisitorPhon":"","VisitorAddr":"xxxx","GeoCode":"","AutoKey":1},{"VisitorID":"09005468","VisitorName":"xxxxxx","VisitorPhon":"09005468","VisitorAddr":"xxxx","GeoCode":"","AutoKey":2}]}
and i wanna read and show information from this file to a ListView
my VisitorsListActivity is:
public class VisitorsListActivity extends AppCompatActivity {
public ListView lstVisitors;
static VisitorsList visitorsList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.visitor_list);
try {
//********************************** COMELETE THIS SECTION *********************************************
new JsonHelper.GetJsonData(new JsonHelper.GetJsonData.AsyncResponse() {
#Override
public void processFinish(String output) {
try {
if (output == null) output = "";
if (output.equals("")) {
Toast.makeText(getApplicationContext(),
"No Visitor Founded",
Toast.LENGTH_LONG)
.show();
return;
}
//960105--------------------
else if (output.equals("401")) {
Toast.makeText(getApplicationContext(),
"Error 401",
Toast.LENGTH_LONG)
.show();
return;
}
//--------------------------------------
Log.i("LOG", "output" + output);
Gson gson = new Gson();
output = output.substring(1, output.length() - 1);
/*Toast.makeText(getApplicationContext(),
output,
Toast.LENGTH_LONG)
.show();*/
visitorsList = new VisitorsList();
visitorsList = gson.fromJson(output, VisitorsList.class);
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(),
"exception",
Toast.LENGTH_LONG)
.show();
}
}
}).execute("http://192.168.1.162:8014/api/Visitors");
//************************************ visitor list is null :| *******************************************
/*if( visitorsList == null) {
Toast.makeText(getApplicationContext(),
"data is nul",
Toast.LENGTH_LONG)
.show();
}*/
AdapterVisitor customAdapter = new AdapterVisitor(this, R.layout.visitor_list, visitorsList.VisitorsList);
customAdapter.notifyDataSetChanged();
lstVisitors.setAdapter(customAdapter);
lstVisitors.requestFocus();
final ViewGroup layoutClear = (ViewGroup) findViewById(R.id.layoutClear);
layoutClear.setVisibility(View.GONE);
} catch (Exception e) {
e.getMessage();
}
} }
and VisitorsList:
public class VisitorsList {
public VisitorsList() {}
public ArrayList<Visitors> VisitorsList;}
Visitors:
public class Visitors {
public String VisitorID;
public String VisitorName;
public String VisitorPhon;
public String VisitorAddr;
public String GeoCode;
public int AutoKey;}
and always visitor list which created by Gson is null. i dont know maybe my problem is in reading from json or maybe visitors class ...
jsonhelper :
public class JsonHelper {
public static class GetJsonData extends AsyncTask<String, Void, String> {
public interface AsyncResponse {
void processFinish(String output);
}
public AsyncResponse delegate = null;
public GetJsonData(AsyncResponse delegate) {
this.delegate = delegate;
}
#Override
protected String doInBackground(String... strUrl) {
String str = strUrl[0];
URLConnection urlConn = null;
BufferedReader bufferedReader = null;
try {
URL url = new URL(str);
urlConn = url.openConnection();
urlConn.setReadTimeout(300000);
urlConn.setConnectTimeout(5000);
bufferedReader = new BufferedReader(new InputStreamReader(urlConn.getInputStream(), "utf-8"), 8);
StringBuffer stringBuffer = new StringBuffer();
String line;
while ((line = bufferedReader.readLine()) != null) {
stringBuffer.append(line);
}
String tmpJson = stringBuffer.toString().replace("\\", "");
return tmpJson;
} catch (Exception ex) {
ex.getMessage();
return null;
} finally {
if (bufferedReader != null) {
try {
bufferedReader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
#Override
protected void onPostExecute(String response) {
delegate.processFinish(response);
}
}
public static class SetJsonData extends AsyncTask<String, Void, String> {
String responseServer;
public interface AsyncResponse {
void processFinish(String output);
}
public AsyncResponse delegate = null;
public SetJsonData(AsyncResponse delegate) {
this.delegate = delegate;
}
#Override
protected String doInBackground(String... param) {
URL url;
String response = null;
try {
url = new URL(param[0]);
HttpURLConnection conn = null;
conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(20000);
conn.setConnectTimeout(10000);//950718
conn.setRequestMethod("GET");
conn.setDoInput(true);
conn.setDoOutput(true);
OutputStream os = conn.getOutputStream();
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
writer.write(param[1]);
writer.flush();
writer.close();
os.close();
int responseCode = conn.getResponseCode();
if (responseCode == HttpsURLConnection.HTTP_OK) {
String line;
BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
while ((line = br.readLine()) != null) {
response += line;
}
} else {
response = (String.valueOf(responseCode));
String line;
BufferedReader br = new BufferedReader(new InputStreamReader(conn.getErrorStream()));//950427
while ((line = br.readLine()) != null) {
}
}
return response;
} catch (IOException e1) {
e1.getMessage();
return null;
} catch (Exception e) {
e.getMessage();
return null;
}
}
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
try {
super.onPostExecute(result);
delegate.processFinish(result);
} catch (Exception e) {
e.getMessage();
}
}
}}
your visitors class is missing annotations.
use this to convert it properly:
http://www.jsonschema2pojo.org/
Check this https://kylewbanks.com/blog/Tutorial-Android-Parsing-JSON-with-GSON
to read the JSON with GSON.
well at first read AsyncResponse so you are using asynchronous request is that what are doing ?
An asynchronous request doesn't block the client so it continue executing the code when the response is back it will execute what is inside the callback.
But you are calling the customAdapter.notifyDataSetChanged(); outside processFinish() you need to call it inside or call the Adapter work inside the processFinish method.
public class VisitorsList {
public VisitorsList() {}
public ArrayList VisitorsList= new ArrayList<>();}
Should be like this... Intialization is missing.
VisitorsList class :
public class VisitorsList {
#SerializedName("VisitorsList")
public List<VisitorsList> VisitorsList;
public static class VisitorsList {
#SerializedName("VisitorID")
public String VisitorID;
#SerializedName("VisitorName")
public String VisitorName;
#SerializedName("VisitorPhon")
public String VisitorPhon;
#SerializedName("VisitorAddr")
public String VisitorAddr;
#SerializedName("GeoCode")
public String GeoCode;
#SerializedName("AutoKey")
public int AutoKey;
}
}
delete this line
output = output.substring(1, output.length() - 1);
and get your result:
Gson gson = new Gson();
visitorsList=gson.fromJson(output), new TypeToken<VisitorsList>() { }.getType());
i change VisitorsListActivity same as below . and set a condition before call adapter to be sure reading information from json has been finished, this worked correctly :
new JsonHelper.GetJsonData(new JsonHelper.GetJsonData.AsyncResponse() {
#Override
public void processFinish(String output) {
try {
if (output == null) output = "";
if (output.equals("")) {
Toast.makeText(getApplicationContext(),
"No Visitor Founded",
Toast.LENGTH_LONG)
.show();
return;
}
else if (output.equals("401")) {
Toast.makeText(getApplicationContext(),
"Error 401",
Toast.LENGTH_LONG)
.show();
return;
}
Log.i("LOG", "output" + output);
Gson gson = new Gson();
output = output.substring(1, output.length() - 1);
try {
visitorsList = new VisitorsList();
visitorsList = gson.fromJson(output, VisitorsList.class);
if(visitorsList != null) {
d.cancel();
adapter = new AdapterVisitor(visitorsList.VisitorsList);
adapter.notifyDataSetChanged();
lstVisitors.setAdapter(adapter);
lstVisitors.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// ******
Object o = lstVisitors.getItemAtPosition(position);
Intent i = new Intent(getApplicationContext(),DateSelectorActivity.class);
Visitors v = (Visitors) o;
i.putExtra("VisitorID", v.VisitorID);
startActivity(i);
}
});
}
}catch (Exception e) {
Log.i("LOG", getAssets().toString() + "exception" + e);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}).execute(url);
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);
}
});
}
I have an AsyncTask which acts as a client and get a string from a server and puts it in a String. After the task I use the response from the server but the data haven't changed yet - it's null.
connectBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
...
Client myClient = new Client(responseTV);
myClient.execute();
if (responseStr.charAt(0) == '1') { <----- responseStr is null
changeBrightness(Integer.parseInt(responseStr.substring(1)));
}
}
});
I assume the code keeps going after .execute() which is not very good in my situation.
Update: Added code for Client class.
public class Client extends AsyncTask<Void, Void, Void> {
String response = "";
TextView responseTV;
public Client(TextView responseTV) {
this.responseTV = responseTV;
}
#Override
protected Void doInBackground(Void... params) {
Socket socket = null;
try {
socket = new Socket(IP, PORT);
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(BUFFER_SIZE);
byte[] buffer = new byte[BUFFER_SIZE];
int bytesRead;
InputStream inputStream = socket.getInputStream();
while ((bytesRead = inputStream.read(buffer)) != -1) {
byteArrayOutputStream.write(buffer, 0, bytesRead);
response += byteArrayOutputStream.toString("UTF-8");
}
} catch (UnknownHostException e) {
e.printStackTrace();
response = "UnknownHostException: " + e.toString();
} catch (IOException e) {
e.printStackTrace();
response = "IOException: " + e.toString();
} finally {
if (socket != null) {
try {
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
//Toast.makeText(MainActivity.this, response, Toast.LENGTH_LONG).show();
responseTV.setText(response);
responseStr = response;
super.onPostExecute(aVoid);
}
}
if (responseStr.charAt(0) == '1') { <----- responseStr is null
changeBrightness(Integer.parseInt(responseStr.substring(1)));
}
Use this code in onPostExecute() method of AsyncTask. It runs on the UI thread and is exactly the method you need after finishing work in doInBackground().