This url is executed when a button is clicked
new HttpAsyncTasks().execute("http://www.demo.com/xyz");
this is the asynctask for the above execution
private class HttpAsyncTasks extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... urls) {
return POSTS(urls[0]);
}
// onPostExecute displays the results of the AsyncTask.
#Override
protected void onPostExecute(String result) {
Toast.makeText(getBaseContext(), "successfull!", Toast.LENGTH_LONG).show();
//call main activity activity upon successful registration
Intent callMain = new Intent(getApplicationContext(),
MainActivity.class);
startActivity(callMain);
}
}
The doInbackground of the above never gets executed but the onPostExecute method does.
this is the POSTS method called in doInbackground
public String POSTS(String url){
InputStream inputStream = null;
String result = "";
try {
// 1. create HttpClient
HttpClient httpclient = new DefaultHttpClient();
// 2. make POST request to the given URL
HttpPost httpPost = new HttpPost(url);
String json = "";
// 3. build jsonObject
JSONObject jsonObject = new JSONObject();
jsonObject.accumulate("xyz", "xyz");
jsonObject.accumulate("amount", "800");
jsonObject.accumulate("demo", "demo");
jsonObject.accumulate("demo2", demo2);
// 4. convert JSONObject to JSON to String
json = jsonObject.toString();
// ** Alternative way to convert Person object to JSON string usin Jackson Lib
// ObjectMapper mapper = new ObjectMapper();
// json = mapper.writeValueAsString(person);
// 5. set json to StringEntity
StringEntity se = new StringEntity(json);
// 6. set httpPost Entity
httpPost.setEntity(se);
// 7. Set some headers to inform server about the type of the content
httpPost.setHeader("Accept", "application/json");
httpPost.setHeader("Content-type", "application/json");
// 8. Execute POST request to the given URL
HttpResponse httpResponse = httpclient.execute(httpPost);
// 9. receive response as inputStream
inputStream = httpResponse.getEntity().getContent();
// 10. convert inputstream to string
if(inputStream != null)
result = convertInputStreamToString(inputStream);
else
result = "Did not work!";
} catch (Exception e) {
Log.d("InputStream", e.getLocalizedMessage());
}
// 11. return result
return result;
}
Please what could be wrong?
Can you try this with way. It's checking your POSTS method.
If toast show empty line, your error in POSTS method on WebProcess.
private class HttpAsyncTasks extends AsyncTask<String, Void, String> {
private String myResult="check";
#Override
protected String doInBackground(String... urls) {
try
{
myResult = POSTS(urls[0]);
}
catch(Exception e)
{
return e;
}
return myResult;
}
#Override
protected void onPostExecute(String result) {
Toast.makeText(getBaseContext(), result, Toast.LENGTH_LONG).show();
/* other codes */
}
}
Your POSTS(urls[0]) call must be giving an exception and when it does the rest of the code is skipped and it bypasses your toast. Try removing exception you can find it in logcat.
Related
I am trying to create a function to make a request, but it is giving some error, I already put permission to the internet, but still
This is my code:
public String request(String Url,JSONObject Data){
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(Url);
InputStream inputstream;
String content = "";
try {
httppost.setEntity(new StringEntity(Data.toString()));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
while(true){
if(entity != null){
inputstream = entity.getContent();
content = inputstream.toString();
break;
}
}
} catch (Exception ex) {
return ex.toString();
}
return content;
}
Input:
JSONObject data = new JSONObject();
data.put("teste","teste");
String response = request('urlExample',data);
Toast.makeText(getApplicationContext(),response,Toast.LENGTH_SHORT).show();
Output:
android.os.NetworkOnMainThreadExecption
I suggest you to use AsyncTask as I mentioned in the comment :
private class LongOperation extends AsyncTask<Void, Void, String> {
private String mUrl;
private JSONObject mData;
public LongOperation(String url, JSONObject data) {
mUrl = url;
mData = data;
}
#Override
protected String doInBackground(Void... params) {
return request(mUrl, mData);
}
#Override
protected void onPostExecute(String response) {
Toast.makeText(getApplicationContext(),response,
Toast.LENGTH_SHORT).show();
}
#Override
protected void onPreExecute() {}
#Override
protected void onProgressUpdate(Void... values) {}
}
You can start your AsyncTask as follow:
JSONObject data = new JSONObject();
data.put("teste","teste");
new LongOperation('urlExample', data).execute();
Network operation does not be launched on Main Thread. You can create another Thread for running it.
Thread thread = new Thread(new Runnable(){
#Override public void run(){
// Run request here !!!!
}
});
thread.start();
I recomend you to use **Volley**, it's a side client library which helps you with the Http-Request.
Search for StringRequest.
Im trying to do a GET request to a server and return the response. Here is my code.
#Override
protected String doInBackground(String... params) {
String url = getBaseUrl() + params[0] + "?" + params[1] + "=" + params[2];
String response = "";
try {
HttpClient client = new DefaultHttpClient();
String getURL = url;
HttpGet get = new HttpGet(getURL);
HttpResponse responseGet = client.execute(get);
HttpEntity resEntityGet = responseGet.getEntity();
if (resEntityGet != null) {
// do something with the response
response = EntityUtils.toString(resEntityGet);
return response;
}
} catch (Exception e) {
e.printStackTrace();
}
return response;
}
When debugging response has the right value but when I call the method the response becomes something else. I call it like this:
HTTPConnector connector = new HTTPConnector("http://www.thetvdb.com/api/");
try {
AsyncTask<String, Void, String> result = connector.execute("GetSeries.php", "seriesname", "Arrow");
String result2 = result.toString();
System.out.println(result2);
} catch (Exception e) {
e.printStackTrace();
}
The result here is something else than the response in the doInBackground method. How is this possible and how can I fix this?
As see doc AsyncTask.execute task returns itself (this) so that the caller can keep a reference to it which we will use to check the status of AsyncTask like is task is running,pending or finished instead of return result of doInBackground.
onPostExecute method is called when doInBackground method execution done to deliver result to UI Thread:
#Override
protected void onPostExecute(String result) {
// update UI here
}
You use AsyncTask in a wrong way. You should get the response String in its onPostExecute() method, code like this:
#Override
protected void onPostExecute(String result) {
// The result is the response String you want.
}
public String POST(String url){
InputStream inputStream = null;
String result = "";
try {
// 1. create HttpClient
HttpClient httpclient = new DefaultHttpClient();
// 2. make POST request to the given URL
HttpPost httpPost = new HttpPost(url);
String json = "";
// 3. build jsonObject
JSONObject jsonObject = new JSONObject();
jsonObject.accumulate("UserName","example#gmail.com");
jsonObject.accumulate("Password","123456!");
// 4. convert JSONObject to JSON to String
json = jsonObject.toString();
// ** Alternative way to convert Person object to JSON string usin Jackson Lib
// ObjectMapper mapper = new ObjectMapper();
// json = mapper.writeValueAsString(person);
// 5. set json to StringEntity
StringEntity se = new StringEntity(json);
// 6. set httpPost Entity
httpPost.setEntity(se);
// 7. Set some headers to inform server about the type of the content
httpPost.setHeader("Accept", "application/json");
httpPost.setHeader("Content-type", "application/json");
// 8. Execute POST request to the given URL
HttpResponse httpResponse = httpclient.execute(httpPost);
Toast.makeText(getBaseContext()," text",Toast.LENGTH_SHORT).show();
// 9. receive response as inputStream
inputStream = httpResponse.getEntity().getContent();
// 10. convert inputstream to string
if(inputStream != null)
result = convertInputStreamToString(inputStream);
else
result = "Did not work!";
} catch (Exception e) {
Log.d("InputStream", e.getLocalizedMessage());
}
// 11. return result
return result;
}
private class HttpAsyncTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... urls) {
// Toast.makeText(getBaseContext(), "post invoked", Toast.LENGTH_SHORT).show();
return POST(urls[0]);
}
// onPostExecute displays the results of the AsyncTask.
#Override
protected void onPostExecute(String result) {
Toast.makeText(getBaseContext(), "Data Sent!"+result+" don", Toast.LENGTH_LONG).show();
}
}
I tried to invoke this POST method from an object of HTTPAsyncTask class, with targeted url passed. But the Toast execeuted in OnPostExecute() popping up with the message "Data sent!Done", which tells that value of 'result' variable is null. And in log cat it is showing"I'm getting feedback from logcat that "Request time failed,Java.net.socketException:Addres family not supported by protocol". What would the fault? Could anyone please fix this***
The URL is lacking the protocol part. Try
http://devcare.dyndns.info:85/WCFServices/UserAuthServices.svc/Login
otherwise devcare.dyndns.info will be mistaken as the protocol.
Try adding this to AndroidManifest.xml
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
And please catch this exception:
catch(SocketException se)
{
Log.e("Exception ---- : " , "Error on execute??" + se.getMessage());
se.printStackTrace();
}
I have an android code which i am sharing below. in the ninth step i.e step 9 can the input stream be converted into json before the result is displayed in the last step. If yes how? . please help i just want the result should be what i get from the url. i am getting result as an Xml till now
public class MainActivity extends Activity implements OnClickListener {
TextView tvIsConnected;
EditText etName,etCountry,etTwitter;
Button btnPost;
Person person;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// get reference to the views
tvIsConnected = (TextView) findViewById(R.id.tvIsConnected);
etName = (EditText) findViewById(R.id.etName);
etCountry = (EditText) findViewById(R.id.etCountry);
//etTwitter = (EditText) findViewById(R.id.etTwitter);
btnPost = (Button) findViewById(R.id.btnPost);
// check if you are connected or not
if(isConnected()){
tvIsConnected.setBackgroundColor(0xFF00CC00);
tvIsConnected.setText("You are conncted");
}
else{
tvIsConnected.setText("You are NOT conncted");
}
// add click listener to Button "POST"
btnPost.setOnClickListener(this);
}
public static String POST(String url, Person person){
InputStream inputStream = null;
String result = "";
try {
// 1. create HttpClient
HttpClient httpclient = new DefaultHttpClient();
// 2. make POST request to the given URL
HttpPost httpPost = new HttpPost(url);
String json = "";
// 3. build jsonObject
JSONObject jsonObject = new JSONObject();
jsonObject.accumulate("Email", person.getName());
jsonObject.accumulate("pass", person.getCountry());
//jsonObject.accumulate("twitter", person.getTwitter());
// 4. convert JSONObject to JSON to String
json = jsonObject.toString();
// ** Alternative way to convert Person object to JSON string usin Jackson Lib
// ObjectMapper mapper = new ObjectMapper();
// json = mapper.writeValueAsString(person);
// 5. set json to StringEntity
StringEntity se = new StringEntity(json);
// 6. set httpPost Entity
httpPost.setEntity(se);
// 7. Set some headers to inform server about the type of the content
httpPost.setHeader("Accept", "application/json");
httpPost.setHeader("Content-type", "application/json");
// 8. Execute POST request to the given URL
HttpResponse httpResponse = httpclient.execute(httpPost);
// 9. receive response as inputStream
inputStream = httpResponse.getEntity().getContent();
// 10. convert inputstream to string
if(inputStream != null)
result = convertInputStreamToString(inputStream);
else
result = "Did not work!";
} catch (Exception e) {
Log.d("InputStream", e.getLocalizedMessage());
}
// 11. return result
return result;
}
public boolean isConnected(){
ConnectivityManager connMgr = (ConnectivityManager) getSystemService(Activity.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
if (networkInfo != null && networkInfo.isConnected())
return true;
else
return false;
}
#Override
public void onClick(View view) {
switch(view.getId()){
case R.id.btnPost:
if(!validate())
Toast.makeText(getBaseContext(), "Enter some data!", Toast.LENGTH_LONG).show();
// call AsynTask to perform network operation on separate thread
new HttpAsyncTask().execute("http://dev.myurl");
break;
}
}
private class HttpAsyncTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... urls) {
person = new Person();
person.setName(etName.getText().toString());
person.setCountry(etCountry.getText().toString());
//person.setTwitter(etTwitter.getText().toString());
return POST(urls[0],person);
}
// onPostExecute displays the results of the AsyncTask.
#Override
protected void onPostExecute(String result) {
Toast.makeText(getBaseContext(), result, Toast.LENGTH_LONG).show();
}
}
private boolean validate(){
if(etName.getText().toString().trim().equals(""))
return false;
else if(etCountry.getText().toString().trim().equals(""))
return false;
//else if(etTwitter.getText().toString().trim().equals(""))
//return false;
else
return true;
}
private static String convertInputStreamToString(InputStream inputStream) throws IOException{
BufferedReader bufferedReader = new BufferedReader( new InputStreamReader(inputStream));
String line = "";
String result = "";
while((line = bufferedReader.readLine()) != null)
result += line;
inputStream.close();
return result;
}
}
/*Try using Gson library to prepare Json string from your service, sample code is given below
JsonObject myObj = new JsonObject(); //Create Json Object
myObj.addProperty("Email", person.getName()); //Add properties to your Json object
myObj.addProperty("pass", person.getCountry());
return new Gson().toJson(myObj); //Convert Json Object to String and return from your service*/
HttpResponse response = httpClient.execute(httpPost);
HttpEntity entity = response.getEntity();
String resp = null;
JsonObject myObj = null;
if (entity != null) {
resp = EntityUtils.toString(entity);
Gson gson = new Gson();
myObj = gson.fromJson(resp, JsonElement.class).getAsJsonObject();
}
My app doesn't seem to pull the JSON data from PHP webservice properly.
Visiting the webservice's function to get all data records from database produces JSON properly, but my app can't grab that data and seems to end up with NullPointerException.
LogCat issues me this:
Update:
Noticed this error in yellow that happens before the below errors:
W/System.err(835): org.apache.http.conn.HttpHostConnectException:
Connection to http:// localhost refused
If I can't connect to the webservice on my localhost then I'm not getting the JSON to my app. But why would it refuse connection to localhost?
W/System.err(1159): at
com.example.myfirstapp.MainActivity$LoadAllCars.doInBackground(MainActivity.java:113)
W/System.err(1159): at
com.example.myfirstapp.MainActivity$LoadAllCars.doInBackground(MainActivity.java:1)
E/AndroidRuntime(1159): at
com.example.myfirstapp.MainActivity$LoadAllCars.doInBackground(MainActivity.java:116)
E/AndroidRuntime(1159): at
com.example.myfirstapp.MainActivity$LoadAllCars.doInBackground(MainActivity.java:1)
E/WindowManager(1159): at
com.example.myfirstapp.MainActivity$LoadAllCars.onPreExecute(MainActivity.java:103)
Line 113: JSONObject json = jParser.makeHttpRequest(url_all_cars, "GET", params);
Line 116: Log.d("All Cars: ", json.toString());
MainActivity
package com.example.myfirstproject;
//imports
public class MainActivity extends ListActivity implements OnItemClickListener {
// Progress Dialog
private ProgressDialog pDialog;
// Creating JSON Parser object
JSONParser jParser = new JSONParser();
ArrayList<HashMap<String, String>> carsList;
// url to get all products list
private static String url_all_cars = "http://localhost/webservice/get_all_cars.php";
// JSON Node names
private static final String TAG_SUCCESS = "success";
private static final String TAG_CARS = "cars";
private static final String TAG_NAME = "name";
// products JSONArray
JSONArray cars = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Hashmap for ListView
carsList = new ArrayList<HashMap<String, String>>();
// Loading products in Background Thread
new LoadAllcars().execute();
// Get listview
ListView lv = getListView();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
/**
* Background Async Task to Load all product by making HTTP Request
* */
class LoadAllcars extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Loading cars. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
/**
* getting All products from url
* */
protected String doInBackground(String... args) {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
// getting JSON string from URL
JSONObject json = jParser.makeHttpRequest(url_all_cars, "GET", params);
// Check your log cat for JSON reponse
Log.d("All cars: ", json.toString());
try {
// Checking for SUCCESS TAG
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// products found
// Getting Array of Products
cars = json.getJSONArray(TAG_CARS);
// looping through All Products
for (int i = 0; i < cars.length(); i++) {
JSONObject c = cars.getJSONObject(i);
// Storing each json item in variable
String title = c.getString(TAG_NAME);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_NAME, name);
// adding HashList to ArrayList
carsList.add(map);
}
} else {
// no products found
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("No cars found");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
// dismiss the dialog after getting all products
pDialog.dismiss();
// updating UI from Background Thread
runOnUiThread(new Runnable() {
public void run() {
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(
MainActivity.this, carsList,
android.R.id.list, new String[] {TAG_NAME},
new int[] { R.id.title });
// updating listview
setListAdapter(adapter);
}
});
}
}
}
EDIT
JSONParser:
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
// function get json from url
// by making HTTP POST or GET method
public JSONObject makeHttpRequest(String url, String method,
List<NameValuePair> params) {
// Making HTTP request
try {
// check for request method
if(method == "POST"){
// request method is POST
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(params));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}else if(method == "GET"){
// request method is GET
DefaultHttpClient httpClient = new DefaultHttpClient();
String paramString = URLEncodedUtils.format(params, "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());
}
// 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());
}
// return JSON String
return jObj;
}
}
I think your problem may be that you never put anything in params. It's just an empty List.
Well if you are getting a null pointer exception on this line
JSONObject json = jParser.makeHttpRequest(url_all_cars, "GET", params);
then 1 or more of them things must be null. The jParser is instantiated, the url string is also, the params is as a list however there is nothing in the list. Have a look inside the jParser and see what is happening with that list of params. Do you need them? Does it need them?
EDIT
So the jParser is converting your list(which is empty) to a string with string builder. Which is returning an empty sting.
so your url when it is sent to your server looks like this
http://localhost/webservice/get_all_cars.php?
So the normal url but with a question mark on it. Is that correct?
It would make sense to log the statuscode and status reason from your httpresponse so you can see what the server is responsing you would do that like so...
Log.d("Class Name", "Status code: " + httpResponse.getStatusLine().getStatusCode() + " Status Phrase: " + httpResponse.getStatusLine().getReasonPhrase());
EDIT
The url is set to "localhost" so I presume it is looking within the device rather than at your server. Put in the ip of your server instead
Problem was here:
private static String url_all_cars = "http://localhost/webservice/get_all_cars.php";
Can't use localhost because the emulated phone itself is localhost/127.0.0.1
You need to change localhost to 10.0.2.2:
private static String url_all_cars = "http://10.0.2.2/webservice/get_all_cars.php";