I'm having an issue trying to compare the result of an HttpResponse with an simple string.
What the code below do, is just get the response of an Http request.
In this case the result of the request is a simple "ok", but when I try to compare it with another string the conditional doesn't work.
I'm able to show the response via toast message...to debug it and to confirm that it is what I'm expecting, but I don't know why the conditional is not working.
Thank's in advance.
imports go here...
public class HttpTest extends Activity {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
DownloadWebPageTask task = new DownloadWebPageTask();
task.execute(new String[] { "http://www.ecoeficiencia-ambiental.com/test/" });
}
private class DownloadWebPageTask extends AsyncTask<String, Void, String> {
protected String doInBackground(String... urls) {
String response = "";
for (String url : urls) {
DefaultHttpClient client = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
try {
HttpResponse execute = client.execute(httpGet);
InputStream content = execute.getEntity().getContent();
BufferedReader buffer = new BufferedReader(new InputStreamReader(content));
String s = "";
while ((s = buffer.readLine()) != null) {
response += s;
}
} catch (Exception e) {
e.printStackTrace();
}
}
return response;
}
protected void onPostExecute(String result) {
if(result == "ok"){
Toast.makeText(HttpTest.this, result, Toast.LENGTH_LONG).show();
}else{
Toast.makeText(HttpTest.this, "the conditional fails, the result is: "+result, Toast.LENGTH_LONG).show();
}
}
}
}
Note: the manifest has the permission to use internet.
both the code and the URL are functional.
You should not use the equality operator to compare strings like that
Try
result.equals("ok");
Oh, interesting! I guess that the string you get from reponse Entity including these things as well:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
Not just a single string 'ok' as you think. That's why comparison fails.
You can confirm reponse by:
string response = EntityUtils.toString(execute.getEntity());
Have fun :)
Related
I have recently made an application in android studio 2.3 to show data from a server the link that I use is working properly in a browser and data is shown successfully in json format. But in my application I can't retrieve these data, I add avolley lib in my app gradle file like this :
compile 'com.mcxiaoke.volley:library:1.0.18'
The code I use in MainActivity is :
public class MainActivity extends AppCompatActivity {
RequestQueue rq;
String url = "http://abdulwahid.esy.es/show.php";
TextView txtshow;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
txtshow = (TextView) findViewById(R.id.txtshow);
rq = Volley.newRequestQueue(this);
JsonObjectRequest jor = new JsonObjectRequest(Request.Method.GET, url,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONArray jarr = response.getJSONArray("allstudents");
for (int i = 0; i < jarr.length(); i++) {
JSONObject res = jarr.getJSONObject(i);
String id = res.getString("id");
String name = res.getString("name");
String info = res.getString("info");
txtshow.append("\n" + id + " - " + name + "\n" + info + "\n" + "------------------" + "\n");
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("VOLLEY", "ERROR");
}
});
rq.add(jor);
}
The link of php file that I use is executed successfully in a web browser.
How to show data in my application or is there another code or library to use for retrieving data form online ?
you can use StringRequest instead of jsonObject with the new library of volley
compile 'com.android.volley:volley:1.0.0'
Use this code to retrieve data, in string line your data will be appended as a complete string as shown in browser
public void getData(){
class GetDataJSON extends AsyncTask<String, Void, String>{
#Override
protected String doInBackground(String... params) {
DefaultHttpClient httpclient = new DefaultHttpClient(new BasicHttpParams());
HttpPost httppost = new HttpPost("http://abdulwahid.esy.es/show.php");
// Depends on your web service
httppost.setHeader("Content-type", "application/json");
InputStream inputStream = null;
String result = null;
try {
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
inputStream = entity.getContent();
// json is UTF-8 by default
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
result = sb.toString();
} catch (Exception e) {
// Oops
}
finally {
try{if(inputStream != null)inputStream.close();}catch(Exception squish){}
}
return result;
}
#Override
protected void onPostExecute(String result){
myJSON=result;
showList();
}
}
GetDataJSON g = new GetDataJSON();
g.execute();
}
The problem is that the Content-Type header is not set in the response of your server. For Volley to be able to parse it, you will need that header set to application/json.
Add the following line in your show.php:
header('Content-Type: application/json');
Edit
After the above change, the response seems strange...
I can see strange characters in the response, that might be causing parsing issues on the client side.
I have an app that should send a the phone number and retrieve a value from the database, now I change the query and my code should retrieve values of multiple columns, So where changes should be in my code.
public class JSONTransmitter extends AsyncTask<JSONObject, Void, String>
{
HttpResponse response;
String url = "http://192.168.1.97:89/Derdeery/bankOsman.php";
private AsyncCallback asyncCallback;
public JSONTransmitter(Context context) {
// attach the callback to any context
asyncCallback = (AsyncCallback) context;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
asyncCallback.onResponse(result);
}
protected String doInBackground(JSONObject... data)
{
JSONObject json = data[0];
HttpClient client = new DefaultHttpClient();
HttpConnectionParams.setConnectionTimeout(client.getParams(), 100000);
StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder().permitNetwork().build());
JSONObject jsonResponse = null;
HttpPost post = new HttpPost(url);
String resFromServer = "";
try {
StringEntity se = new StringEntity("json=" + json.toString());
post.addHeader("content-type", "application/x-www-form-urlencoded");
post.setEntity(se);
HttpResponse response;
response = client.execute(post);
resFromServer = org.apache.http.util.EntityUtils.toString(response.getEntity());
Log.i("Response from server", resFromServer);
} catch (Exception e) {
e.printStackTrace();
}
return resFromServer;
}
public static interface AsyncCallback {
void onResponse(String res);
}
}
Here is something to consider:
First, in your php code (server-side), query your data perhaps separately. So for instance, you can get those that match column A and then query for those that match column B.
Generate Json for each (A and B accordingly)
Then create a single JSON object that contains the two sets of data like this:
{
"DataFromColumnA" : {},
"DataFromColumnB" : {}
}
Once you have made your HTTP request in your android code, you can get the specific data by getting "DataFromColumnA" json Object and B respectively.
I hope this helps you get your problem solved!
I'm trying to get a daily quote from
http://quotesondesign.com/api/3.0/api-3.0.json?callback=json
I call this method in my onCreate
But when i try to execute the httpclient.execute();
it escapes to the catch statement...
What am I doing wrong?
I did include the <uses-permission android:name="android.permission.INTERNET" />
in my manifest file.
public String getJson(){
String quoteUrl = "http://quotesondesign.com/api/3.0/api-3.0.json?callback=?";
DefaultHttpClient httpclient = new DefaultHttpClient();
HttpGet httpget = new HttpGet(quoteUrl);
httpget.setHeader("Content-type", "application/json");
InputStream inputStream = null;
String result = null;
String aJsonString = null;
try {
HttpResponse response = httpclient.execute(httpget);
Toast.makeText(this, "It works", Toast.LENGTH_LONG).show();
HttpEntity entity = response.getEntity();
inputStream = entity.getContent();
// json is UTF-8 by default
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
result = sb.toString();
JSONObject jObject = new JSONObject(result);
aJsonString = jObject.getString("quote");
} catch (Exception e) {
//Toast.makeText(this, "can't execute http request", Toast.LENGTH_LONG).show();
}
finally {
try{if(inputStream != null)inputStream.close();}catch(Exception squish){}
}
return aJsonString;
}
EDIT: here is the onCreate()
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//verbergt notificatiebalk
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.splash);
jsonstring = getJson();
Log.d(jsonstring, "The jsonstring contains: " + jsonstring);
//Toast.makeText(this, jsonstring, Toast.LENGTH_LONG).show();
//tot hier testen
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
Intent i = new Intent(SplashScreen.this, MainActivity.class);
startActivity(i);
finish();
}
}, SPLASH_TIME_OUT);
}
Thank you in advance!
Update: Actual answer with code now vailable:
private class AsyncQuoteDownload extends AsyncTask<Void, Void, String>{
#Override
protected String doInBackground(Void... params) {
String jsonData = getJson(); //or, if the jsonData var is available from everywhere, just put myR.run(); here, return null, and append the data directly in onPostExecute
return jsonData;
}
#Override
protected void onPostExecute(String result) {
(TextView)findViewById(R.id.Quote).append(result).append("\"");
} // \" makes it put an actual " inside a string
}
Old answer:
I bet your stacktrace (which isn't as an error because oyu catch it, but it's in the log) reads something like "Network on Main Thread"?
Because that's something you're trying to do, and that's something you aren't allowed to do. Instead, put it in an AsyncTask:
onCreate(){ //beware pseudo code because it doesn't matter
//do stuff
setContentView(...); //Above here, everything stays as is.
//below here, only that:
new GetQuoteTask.execute();
}
class GetQuoteTask extends AsyncTask<Void, Void, String>{
String doInBackground(...){ //<- pseudo code, code completion is your friend
String result = getJson();
Log.d(jsonstring, "The jsonstring contains: " + jsonstring);
return result;
}
onPostExecute(String result){
maybePutYourStringSomewhereAKAUpdateUI();
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
Intent i = new Intent(SplashScreen.this, MainActivity.class);
startActivity(i);
finish();
}
}, SPLASH_TIME_OUT);
}
}
In your code you have
String quoteUrl = "http://quotesondesign.com/api/3.0/api-3.0.json?callback=?";
While the URL you want to fetch is
http://quotesondesign.com/api/3.0/api-3.0.json?callback=json
Notice how in your code you have callback=? while the URL has callback=json.
After Android 4.2, you can't make Http Request on the UI-Thread (the "main" thread). You need to do it in a seperate thread.
You can find an example on this website or in this stackoverflow post: HttpClient.execute(HttpPost) on Android 4.2 error
I'm trying to see how works an Asynctask class in android. In particular i want reveal in real time the status of the class for see when it is running and when it has finished. For do this, i have created a class that extend the main activity and another class that is the asynctaks class.
This is my main class:
public class PhotoManagement extends Activity{
private String numberOfSelectedPhotos;
private Bitmap currentImage;
private String initConfiguration = "http://www.something.com";
private String response;
private ArrayList<String> formatPhotoList = new ArrayList<String>(); //create a list that will contains the available format of the photos downloaded from the server
private ArrayList<String> pricePhotoList = new ArrayList<String>(); //create a list that will contains the available price for each format of the photos
DownloadWebPageTask webPage = new DownloadWebPageTask();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
protected void onResume(){
super.onResume();
webPage.execute(initConfiguration);
if(webPage.getStatus() == AsyncTask.Status.PENDING){
Log.i("STATUS","PENDING");
}
if(webPage.getStatus() == AsyncTask.Status.RUNNING){
Log.i("","RUNNING");
}
if(webPage.getStatus() == AsyncTask.Status.FINISHED){
Log.i("","FINISHED");
}
}
}
As you can see i want only see the passages of the status with a simple log.
And here there is the asynctask class.
private class DownloadWebPageTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... urls) {
for (String url : urls) {
DefaultHttpClient client = new DefaultHttpClient(); //create a new http client
HttpGet httpGet = new HttpGet(url); //create a new http request passing a valid url
try {
HttpResponse execute = client.execute(httpGet); //try to execute the http get request
InputStream content = execute.getEntity().getContent(); //prepare the input stream to read the bytes of the request
BufferedReader buffer = new BufferedReader(
new InputStreamReader(content));
String s = "";
while ((s = buffer.readLine()) != null) {
response += s; //until is present a line to read, the response variable store the value of the lines
}
} catch (Exception e) {
Log.i("MyApp", "Download Exception : " + e.toString()); //Print the error if something goes wrong
}
}
return response; //return the response
}
#Override
protected void onPostExecute(String result) {
result = doInBackground(initConfiguration); //take the result from the DownloadWebPageTask class
result = result.replace("null", "");
Log.i("RESULT",""+result);
//find the price and format value from the result using XmlPullParser
try {
XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
factory.setNamespaceAware(true);
XmlPullParser xpp = factory.newPullParser();
xpp.setInput( new StringReader ( result ) );
int attributeNumber = xpp.getAttributeCount();
int eventType = xpp.getEventType();
String currentTag = null;
while(eventType != XmlPullParser.END_DOCUMENT){
if(eventType == XmlPullParser.START_TAG) {
currentTag = xpp.getName();
if (currentTag.equals("product")){
xpp.getAttributeValue(null, "name");
formatPhotoList.add(xpp.getAttributeValue(null, "name"));
Log.i("FORMAT PHOTO",""+xpp.getAttributeValue(null, "name"));
}
}
eventType = xpp.next();
}
} catch (XmlPullParserException e) {
e.printStackTrace();
Log.i("","ERROR XML PULL PARSER");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Log.i("","ERROR IOEXCEPTION");
}
}
}
}
As you can see i have implemented also the method onPostExecute that should be called when the asynctask method has finished to execute the instructions right?
So at this point i don't understand why my log RUNNING and my log FINISHED never appear on the log cat.
What i'm doing wrong?
I'm tried to follow this topic Android, AsyncTask, check status? but in my case it isn't working.
Thanks
Problem :
You are creating object like
DownloadWebPageTask webPage = new DownloadWebPageTask();
But you are calling asynctask on different object,
new DownloadWebPageTask().execute(initConfiguration);
Solution :
It should be like
webPage.execute(initConfiguration);
#Override
protected void onResume(){
super.onResume();
new DownloadWebPageTask().execute(initConfiguration);
here do like this
#Override
protected void onResume(){
super.onResume();
webPage.execute(initConfiguration);
You didn't implement webPage.execute(), add it
Most probably the task hasn't finished or even started yet. As you probably know the AsyncTask is doing it's (background) work on a different thread, so your onResume is running in parallel with it. You can either use the task's get() method to wait for it to finish and get the result of the doInBackground() method and then query for it's status or notify your activity from the task's onPostExecute() method to let it know (and log) that it has finished. I don't recommend you the first option because it will actually block the UI thread and will make your usage of AsyncTask pointless.
this code is for getting details from a php server by posting two data num,db and getting a response.
public class MainActivity extends Activity {
Button b;
TextView num;
TextView dob;
String db;
String x;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
b=(Button) findViewById(R.id.button1);
num=(TextView) findViewById(R.id.editText1);
dob=(TextView) findViewById(R.id.editText2);
x=(String) num.getText();
db=(String) dob.getText();
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
submit();
}
});
}
submit fn is for posting two values num,db into the server to get a response.
public String submit(){
ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
postParameters.add(new BasicNameValuePair("registerno", x ));
postParameters.add(new BasicNameValuePair("dob", db ));
String response = "";
DefaultHttpClient client = new DefaultHttpClient();
HttpGet httpGet = new HttpGet("http://www.pnrinbox.com/premfin.php");
try
{
HttpResponse execute = client.execute(httpGet);
InputStream content = execute.getEntity().getContent();
BufferedReader buffer = new BufferedReader(
new InputStreamReader(content));
String s = "";
while ((s = buffer.readLine()) != null)
{
response += s;
}
Log.d( "After call, response: " , " " + response);
}
catch (Exception e)
{
System.out.println(e.toString());
}
return response;
}
posting two data items into a php server and getting data back.
Ill bet you are getting a NetworkOnMainThreadException. All networking operations must be done on a non-UI thread. I would recommend looking up the AsyncTask class in the android documentaion: http://developer.android.com/reference/android/os/AsyncTask.html.
You will probably find that you need to move the body of your submit() function into the doInBackground() function of an asyncTask.
I think you'll have to use AsyncTask for network access, and then call the AsyncTask from the UI thread to return the desired value. Also, you'll have to put <uses-permission android:name="android.permission.INTERNET"></uses-permission> after the </application> in the manifest.xml file.