I want to send a URL such as "http://192.168.1.1/key_on" to an HTML form and then receive a number 1 or 0 as response, if it can changes correctly, then do something in my app. I send my request by AsyncTask, and it works correctly! But I don't know how to get response ?
Here is my some code in Activities:
Button btn= (Button)convertView.findViewById(R.id.two);
btn.setWidth(500);
new RequestTask().execute("http://192.168.1.1/key_on");
btn.setBackgroundColor(Color.parseColor("#FF11AC06"));
btn.setText(childText);
btn.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
int color = Color.TRANSPARENT;
Drawable background = view.getBackground();
if (background instanceof ColorDrawable)
color = ((ColorDrawable) background).getColor();
if (color == Color.parseColor("#FF11AC06")) {
new RequestTask().execute("http://192.168.1.1/key_off");
view.setBackgroundColor(Color.parseColor("#FF41403F"));
} else {
view.setBackgroundColor(Color.parseColor("#FF11AC06"));
new RequestTask().execute("http://192.168.1.1/key_on");
}
}
});
return convertView;
And in RequestTask.java:
class RequestTask extends AsyncTask<String, String, String> {
#Override
protected String doInBackground(String... uri) {
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response;
String responseString = null;
try {
response = httpclient.execute(new HttpGet(uri[0]));
StatusLine statusLine = response.getStatusLine();
if(statusLine.getStatusCode() == HttpStatus.SC_OK){
ByteArrayOutputStream out = new ByteArrayOutputStream();
response.getEntity().writeTo(out);
responseString = out.toString();
out.close();
} else{
//Closes the connection.
response.getEntity().getContent().close();
throw new IOException(statusLine.getReasonPhrase());
}
} catch (ClientProtocolException e) {
//TODO Handle problems..
} catch (IOException e) {
//TODO Handle problems..
}
return responseString;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
//Do anything with response..
}
}
please check your request url(http://192.168.1.1/key_off) getting 404 error code.please fire your url in web.
Related
BackgorundTask.java (How to get the result of OnPostExecute() to main activity because AsyncTask is a separate class?)
public class BackgroundTask extends AsyncTask<String,Void,String> {
public interface AsyncResponse {
void processFinish(String output);
}
public AsyncResponse delegate = null;
public BackgorundTask(AsyncResponse delegate){
this.delegate = delegate;
}
protected String doInBackground(String... uri) {
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response;
String responseString = null;
try {
response = httpclient.execute(new HttpGet(uri[0]));
StatusLine statusLine = response.getStatusLine();
if(statusLine.getStatusCode() == HttpStatus.SC_OK){
ByteArrayOutputStream out = new ByteArrayOutputStream();
response.getEntity().writeTo(out);
responseString = out.toString();
out.close();
} else{
//Closes the connection.
response.getEntity().getContent().close();
throw new IOException(statusLine.getReasonPhrase());
}
} catch (ClientProtocolException e) {
//TODO Handle problems..
} catch (IOException e) {
//TODO Handle problems..
}
return responseString;
}
protected void onProgressUpdate(Integer... progress) {
}
#Override
protected void onPostExecute(String result) {
delegate.processFinish(result);
}
}
ListActivity.java
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list);
BackgorundTask asyncTask = (BackgorundTask) new BackgorundTask(new BackgorundTask.AsyncResponse(){
#Override
public void processFinish(String output){
listAdapter.add(output);
}
}).execute("some url");
adapter = new MyCustomAdapter(listAdapter, this);
final ListView mainListView = (ListView)findViewById(R.id.listView);
mainListView.setAdapter(adapter);
The variable is returned correctly. But I can not add to the ListView (listAdapter) of each item. What could be the reason? I suppose that I have to somehow pull the string variable output from asyncTask to my function onCreate in which it is placed.
your code is fine. you just need to call this line after adding data
listAdapter.add(output); // after this line add below line
listAdapter.notifyDataSetChanged();
The code to get the data back to the activity and to your listadapter seems okay to me. I think you just need to add a listAdapter.notifyDataSetChanged(); after listAdapter.add(output); so the listview knows it has to render itself anew.
You have to set the adapter again when you receive output string as below :
BackgorundTask asyncTask = (BackgorundTask) new BackgorundTask(new BackgorundTask.AsyncResponse(){
#Override
public void processFinish(String output){
listAdapter.add(output);
adapter = new MyCustomAdapter(listAdapter, this);
final ListView mainListView = (ListView)findViewById(R.id.listView);
mainListView.setAdapter(adapter);
}
}).execute("some url");
Unable to fetch data from server even i have value in textview as per my condition in onCreate() and when i remove this condition this works just fine for me (my mean, in that case i am able to fetch JSON data from Server).
and i tried many things but still no success for me, always getting "Unable to fetch data from server" because i used this as Toast in onPostExecute() method of AsyncTask
I am getting value for TextView and that's for sure its calling execute method of AsyncTask as well, but always getting Unable to fetch data from server
Do you have Questions in your mind :
1) Why I am using such condition in onCreate(), then check my this question
2) Why I am setting adapter in onPostExecute(), then check my this question
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_video_category);
etTextToSave = (TextView) findViewById(R.id.textView2);
sharedprefs = getSharedPreferences("MyPrefs", MODE_PRIVATE);
etTextToSave.setText(sharedprefs.getString("SharedPrefsData",""));
actorsList = new ArrayList<VideoCategory>();
if(etTextToSave.getText().toString().length()>0)
{
new JSONAsyncTask().execute("http://microblogging.wingnity.com/JSONParsingTutorial/jsonActors");
}
centerLockHorizontalScrollview = (HSVActivity) findViewById(R.id.scrollView);
}
class JSONAsyncTask extends AsyncTask<String, Void, Boolean> {
ProgressDialog dialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
dialog = new ProgressDialog(MainActivity.this);
dialog.setMessage("Loading, please wait");
dialog.setTitle("Connecting server");
dialog.show();
dialog.setCancelable(false);
}
#Override
protected Boolean doInBackground(String... urls) {
try {
//------------------>>
HttpGet httppost = new HttpGet(urls[0]);
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response = httpclient.execute(httppost);
// StatusLine stat = response.getStatusLine();
int status = response.getStatusLine().getStatusCode();
if (status == 200) {
HttpEntity entity = response.getEntity();
String data = EntityUtils.toString(entity);
JSONObject jsono = new JSONObject(data);
JSONArray jarray = jsono.getJSONArray("actors");
for (int i = 0; i < jarray.length(); i++) {
JSONObject object = jarray.getJSONObject(i);
Actors actor = new Actors();
actor.setName(object.getString("name"));
Log.d("Name:", object.getString("name"));
actor.setImage(object.getString("image"));
Log.d("Image:", object.getString("image"));
actorsList.add(actor);
}
return true;
}
//------------------>>
} catch (ParseException e1) {
e1.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return false;
}
protected void onPostExecute(Boolean result) {
dialog.cancel();
if(result == false)
Toast.makeText(getApplicationContext(), "Unable to fetch data from server", Toast.LENGTH_LONG).show();
if(actorsList != null) {
adapter = new VideoCategoryAdapter(getApplicationContext(), R.layout.adapter_video_category, actorsList);
centerLockHorizontalScrollview.setAdapter(HomeActivity.this, adapter);
}
}
}
I am not getting any exception or toast message.
Check the Json response.
As per your posted question , you get data form the server still you get Toast that "Unable to fetch data from server" . I done the small change in your code please try it and let me known .
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_video_category);
etTextToSave = (TextView) findViewById(R.id.textView2);
sharedprefs = getSharedPreferences("MyPrefs", MODE_PRIVATE);
etTextToSave.setText(sharedprefs.getString("SharedPrefsData",""));
actorsList = new ArrayList<VideoCategory>();
if(etTextToSave.getText().toString().length()>0)
{
new JSONAsyncTask().execute("http://microblogging.wingnity.com/JSONParsingTutorial/jsonActors");
}
centerLockHorizontalScrollview = (HSVActivity) findViewById(R.id.scrollView);
}
class JSONAsyncTask extends AsyncTask<String, Void, Boolean> {
ProgressDialog dialog;
JSONObject jObj;
#Override
protected void onPreExecute() {
super.onPreExecute();
dialog = new ProgressDialog(MainActivity.this);
dialog.setMessage("Loading, please wait");
dialog.setTitle("Connecting server");
dialog.show();
dialog.setCancelable(false);
}
#Override
protected Boolean doInBackground(String... urls) {
try {
//------------------>>
HttpGet httppost = new HttpGet(urls[0]);
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response = httpclient.execute(httppost);
// StatusLine stat = response.getStatusLine();
int status = response.getStatusLine().getStatusCode();
if (status == 200) {
HttpEntity entity = response.getEntity();
String data = EntityUtils.toString(entity);
jObj = new JSONObject(data);
if(!(jObj.equals(null)))
{
JSONArray jarray = jsono.getJSONArray("actors");
for (int i = 0; i < jarray.length(); i++) {
JSONObject object = jarray.getJSONObject(i);
Actors actor = new Actors();
actor.setName(object.getString("name"));
Log.d("Name:", object.getString("name"));
actor.setImage(object.getString("image"));
Log.d("Image:", object.getString("image"));
actorsList.add(actor);
}
}
return true;
}
//------------------>>
} catch (ParseException e1) {
e1.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return false;
}
protected void onPostExecute(Boolean result) {
dialog.cancel();
if(jObj== null)
Toast.makeText(getApplicationContext(), "Unable to fetch data from server", Toast.LENGTH_LONG).show();
if(actorsList != null) {
adapter = new VideoCategoryAdapter(getApplicationContext(), R.layout.adapter_video_category, actorsList);
centerLockHorizontalScrollview.setAdapter(HomeActivity.this, adapter);
}
}
}
When I go back to the previous activity by pressing the back button the progress dialog is appearing and not disappearing. When I minimize they the app the progress dialog disappears.
Here is the code for the async class
public class BackGroundTask extends AsyncTask<String, String, JSONObject> {
List<NameValuePair> postparams = new ArrayList<NameValuePair>();
private ProgressDialog pd;
String url = null;
String method = null;
Context context;
public BackGroundTask(String url, String method,
List<NameValuePair> params, Context context) {
this.url = url;
postparams = params;
this.method = method;
this.context = context;
//pd = new ProgressDialog(context);
//pd.setTitle("Processing...");
//pd.setMessage("Please wait.");
//pd.setCancelable(false);
//pd.setIndeterminate(true);
}
#Override
protected void onPreExecute() {
super.onPreExecute();
pd = new ProgressDialog(context);
pd = ProgressDialog.show(context, "Processing...", "Please wait.", true, false);
}
#Override
protected void onPostExecute(JSONObject result) {
super.onPostExecute(result);
pd.dismiss();
}
#Override
protected JSONObject doInBackground(String... params) {
// TODO Auto-generated method stub
// Making HTTP request
try {
// Making HTTP request
// check for request method
if (method.equals("POST")) {
// request method is POST
// defaultHttpClient
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(postparams));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
} else if (method == "GET") {
// request method is GET
HttpClient httpClient = new DefaultHttpClient();
String paramString = URLEncodedUtils.format(postparams,
"utf-8");
url += "?" + paramString;
HttpGet httpGet = new HttpGet(url);
HttpResponse httpResponse = httpClient.execute(httpGet);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(
new InputStreamReader(is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
System.out.println(json);
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
//pd.dismiss();
// return JSON String
return jObj;
}
}
You aren't dismissing it when you finish the Activity and the task must not be done. Override finish() and dismiss it if needed
#Override
public void finish()
{
if (pd.isShowing()
{
pd.dismiss();
}
super.finish();
}
You could also Override onBackPressed() and put this code there but since pressing the back button calls finish() its probably safer just to do it there.
Also, you are comparing Strings correctly in one place
if (method.equals("POST")) // correct
but not others
else if (method == "GET") // incorrect
Here is my code:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button1 = (Button) findViewById(R.id.button1);
button1.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
MainActivity.this.runOnUiThread(new Runnable() {
public void run() {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(
"http://shopstable.turkcell.com.tr/timmenu/getPerosConfig.do");
try {
HttpResponse response = httpclient
.execute(httppost);
} catch (ClientProtocolException e) {
} catch (IOException e) {
}
}
});
}
});
}
i'am getting NetworkOnMainThreadException. I think the problem is in the httppost, but i couldn't figure it out.
This exception is thrown when an application attempts to perform a networking operation on its main thread.This is only thrown for applications targeting the Honeycomb SDK or higher. Applications targeting earlier SDK versions are allowed to do networking on their main event loop threads, but it's heavily discouraged. Run your code in AsyncTask:
// use async task like this .this will solve ur problem
Class A{
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button1 = (Button) findViewById(R.id.button1);
button1.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
MainActivity.this.runOnUiThread(new Runnable() {
public void run() {
new RequestLogInFromServer().execute();
}
});
}
});
}
public class RequestLogInFromServer extends AsyncTask<Object, Object, Object>
{
#Override
protected Object doInBackground(Object... params)
{
String responsearray[] = new String[2];
//JSONObject jsonResponse = null;
// Create a new HttpClient and Post Header
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("http://shopstable.turkcell.com.tr/timme/getPerosConfig.do");
httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded");
try {
// Add your data
in case if u want to pass any data to server else leave it
List<NameValuePair> signinDetails = new ArrayList<NameValuePair>();
signinDetails.add(new BasicNameValuePair("name",uname));
signinDetails.add(new BasicNameValuePair("pass",pwd));
httpPost.setEntity(new UrlEncodedFormEntity(signinDetails));
// Execute HTTP Post Request
HttpResponse httpResponse = httpClient.execute(httpPost);
Log.v("Post Status", "Code: "
+ httpResponse.getStatusLine().getStatusCode());
responseCode = httpResponse.getStatusLine().getStatusCode();
Log.e("responseBody", String.valueOf(responseCode));
responsearray[0]=String.valueOf(responseCode);
switch(responseCode){
case 200:
Log.e("responseCode", String.valueOf(responseCode));
HttpEntity entity = httpResponse.getEntity();
Log.e("entity", String.valueOf(entity));
if (entity != null) {
responsearray[1] = EntityUtils.toString(entity);
Log.e("responsearray", String.valueOf(responsearray));
/* Log.e("responseBody", String.valueOf(responseBody));
JSONTokener jsonTokener = new JSONTokener(responseBody);
jsonResponse = new JSONObject(jsonTokener);
Log.e("finalResult", String.valueOf(jsonResponse));
JSONObject response = jsonResponse.getJSONObject("response");
// Getting String inside response object
String status = response.getString("status");
String message = response.getString("message");
Log.e("status", String.valueOf(status));
Log.e("message", String.valueOf(message));
*/
} // if (entity != null) end
break;
case 503:
responsearray[1]="";
break;
default:
responsearray[1]="";
break;
}//switch end
} catch (ClientProtocolException cpeExp) {
// TODO Auto-generated catch block
} catch (Exception allExp) {
// TODO Auto-generated catch block
}
return responsearray;
}
#Override
protected void onPostExecute(Object result)
{
super.onPostExecute(result);
}
#Override
protected void onPreExecute() {
progressDialog = ProgressDialog.show(SignInActivity.this, "", "Please wait");
super.onPreExecute();
}
}
} //close class A
you have simply use this so get solution:
Here SDK version is your app's minimum sdk version ..so you have to set your minimum sdk version here. And put this code after onCreate() method:
if (android.os.Build.VERSION.SDK_INT > 8) {
StrictMode.ThreadPolicy stp = new StrictMode.ThreadPolicy.Builder()
.permitAll().build();
StrictMode.setThreadPolicy(stp);
}
And also add this permission to your manifest file:
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
I have a thread that sends GPS coordinates to a database every six seconds and I have a check that verifies that the user is within a defined area. If the user is not within the location, I want an alert dialog that notifies them that they are out of range, and if they are within the area I want a dialog that tells them they are within range. I have the checks working properly, but I have tried and I'm pretty sure that I can't add the dialog on the background thread. I have read a bit about using handlers but I'm not sure how to implement one. If you have any suggestions I would appreciate it! Thanks.
This is how I call FindLocation.java from my main activity (MainActivity.java):
new FindLocation(getBaseContext()).start(usr_id1); //sends a user id with it
Below is FindLocation.java
public class FindLocation extends Thread {
public boolean inJurisdiction;
public boolean AlertNotice = false;
private LocationManager locManager;
private LocationListener locListener;
Context ctx;
public String userId;
public FindLocation(Context ctx) {
this.ctx = ctx;
}
public void start(String userId) {
this.userId = userId;
super.start();
}
#Override
public void run() {
Looper.prepare();
final String usr = userId;
//get a reference to the LocationManager
locManager = (LocationManager) ctx.getSystemService(Context.LOCATION_SERVICE);
//checked to receive updates from the position
locListener = new LocationListener() {
public void onLocationChanged(Location loc) {
String lat = String.valueOf(loc.getLatitude());
String lon = String.valueOf(loc.getLongitude());
Double latitude = loc.getLatitude();
Double longitude = loc.getLongitude();
if (latitude >= 39.15296 && longitude >= -86.547546 && latitude <= 39.184901 && longitude <= -86.504288 || inArea != false) {
Log.i("Test", "Yes");
inArea = true;
JSONArray jArray;
String result = null;
InputStream is = null;
StringBuilder sb = null;
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("id", usr));
//http post
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://www.example.com/test/example.php");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
}catch(Exception e){
Log.e("log_tag", "Error in http connection"+e.toString());
}
//convert response to string
try{
BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
sb = new StringBuilder();
sb.append(reader.readLine() + "\n");
String line="0";
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result=sb.toString();
}
catch(Exception e){
Log.e("log_tag", "Error converting result "+e.toString());
}
try{
jArray = new JSONArray(result);
JSONObject json_data=null;
for(int i=0;i<jArray.length();i++){
json_data = jArray.getJSONObject(i);
String ct_name = json_data.getString("phoneID");
Log.i("User ID", ct_name);
if(ct_name == usr) {
locManager.removeUpdates(locListener);
}
else{
locManager.removeUpdates(locListener);
Log.i("User ID", "NONE");
}
}
}
catch(Exception e){
//Log.e("log_tag", "Error converting result "+e.toString());
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://example.com/test/example.php");
try {
List<NameValuePair> nameValuePairs1 = new ArrayList<NameValuePair>(2);
nameValuePairs1.add(new BasicNameValuePair("lat", lat));
nameValuePairs1.add(new BasicNameValuePair("lon", lon));
nameValuePairs1.add(new BasicNameValuePair("id", usr));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs1));
httpclient.execute(httppost);
Log.i("SendLocation", "Yes");
}
catch (ClientProtocolException g) {
// TODO Auto-generated catch block
} catch (IOException f) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
else {
Log.i("Test", "No");
inArea = false;
}
}
public void onProviderDisabled(String provider){
}
public void onProviderEnabled(String provider){
}
public void onStatusChanged(String provider, int status, Bundle extras){
}
};
locManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 6000, 0, locListener);
Looper.loop();
}
}
It is a little difficult to read the entire code, but I will show you how to display an AlertDialog from a background Thread:
Create a handler inside onCreate(), or onResume()... something that runs on the UI-Thread:
...onCreate(){
//...
mHandler=new Handler();
}
Then inside your Thread() just use:
mHandler.post(new Runnable() {
public void run(){
//Be sure to pass your Activity class, not the Thread
AlertDialog.Builder builder = new AlertDialog.Builder(MyActivity.this);
//... setup dialog and show
}
});
runOnUiThread(new Runnable() {
public void run() {
//your alert dialog here..
}
});
new Handler().post(new Runnable{
public void run(){
//create your AlertDialog here..
}
});
see more here