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
Related
Here i am facing a problem with password validation which is when i entering correct password but it is saying the password is incorrect. Here i am using rest web services below is my code please help me.
EditText password;
String Passwordstr;
Button btn_go;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
password = (EditText) findViewById(R.id.passET);
btn_go = (Button) findViewById(R.id.btn_go);
btn_go.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Passwordstr = password.getText().toString();
if (Passwordstr.isEmpty()) {
Toast.makeText(Main2Activity.this, "Please, Enter Your Password.", Toast.LENGTH_SHORT).show();
} else {
new MyAsyncTask().execute(Passwordstr);
}
}
});
}
private class MyAsyncTask extends AsyncTask<String, Integer, String> {
#Override
protected String doInBackground(String... params) {
String res = PostData(params);
return res;
}
public String PostData(String[] args) {
String s = "";
try {
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("http://localhost:82/demo/login.php");
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
s = readResponse(httpResponse);
} catch (Exception exception) {
}
return s;
}
protected void onPostExecute(String result) {
if (result.equals("true")) {
Intent intent = new Intent(Main2Activity.this, Main3Activity.class);
intent.putExtra("Password", Passwordstr);
startActivity(intent);
} else {
Toast.makeText(getApplicationContext(), "Password incorrect", Toast.LENGTH_LONG).show();
}
}
public String readResponse(HttpResponse res) {
InputStream is = null;
String return_text = "";
try {
is = res.getEntity().getContent();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(is));
String line = "";
StringBuffer sb = new StringBuffer();
while ((line = bufferedReader.readLine()) != null) {
sb.append(line);
}
return_text = sb.toString();
} catch (Exception e) {
}
return return_text;
}
}
}
I am developing an android app in this my aim is to connect to a web page through web-server, here i am using Rest call and java code.Please help me any one.
In your post execute you have to check the null value not the true value like this
protected void onPostExecute(String result) {
if (result!=null) {
Intent intent = new Intent(Main2Activity.this, Main3Activity.class);
intent.putExtra("Password", Passwordstr);
//No Full Name
//MyHomeActivity.putExtra("GetDisplayName",user.getDisplayName());
// MyHomeActivity.putExtra("GetPhotoUrl",user.getPhotoUrl());
startActivity(intent);
} else {
Toast.makeText(getApplicationContext(), "Password incorrect", Toast.LENGTH_LONG).show();
// Hide the progress bar
// progressBar.setVisibility(View.GONE);
}
}
try this as you are not create post parameters pair with key and value.
List nameValuePair = new ArrayList(1);
nameValuePair.add(new BasicNameValuePair("password", "password"));
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePair));
HttpResponse response = httpClient.execute(httpPost);
Also hit rest api from postman or hurl.it with same password and check the response.
you can use android-async-http simple , fast
and u can access UI thread an Views on respond methods
RestClient.get("statuses/public_timeline.json", null, new JsonHttpResponseHandler() {
#Override
public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
// If the response is JSONObject instead of expected JSONArray
}
#Override
public void onSuccess(int statusCode, Header[] headers, JSONArray timeline) {
// Pull out the first event on the public timeline
JSONObject firstEvent = timeline.get(0);
String Text = firstEvent.getString("text");
textview.setText(Text);
// Do something with the response
System.out.println(tweetText);
}
});
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 AsyncTask in my activity class and when I check some data in doInBackground(), I just want to change/set an instance variable of my activity class, but somehow there is nothing what is changing! :(
And if the variable is changed another AsyncTask should start.
Now here is the code:
public class LogIn extends Activity {
private boolean emailNotAvalaible;
private void setemailNotAvalaible(boolean emailNotAvalaible) {
this.emailNotAvalaible= emailNotAvalaible;
}
private Button loginBtn;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.login_activity);
loginBtn = (Button) findViewById(R.id.login_btn);
loginBtn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
new Register().execute("");
if (emailNotAvalaible== true) {
new Installation().execute("");
}
}// end of onClick()
});// end of setOnClickListener
}// end of onCreate();
public class Register extends AsyncTask<String,Integer,String>{
#Override
protected void onPreExecute() {
...
}//end of onPreExecute()
#Override
protected String doInBackground(String... params) {
ArrayList<NameValuePair> postParamsEmail = new ArrayList<NameValuePair>();
postParamsEmail.add(new BasicNameValuePair("email", email));
try {
String emailCheck = executeHttpPost("http://.../doubleEmail.php", postParamsEmail);
try {
JSONArray jsonarr = new JSONArray( emailCheck );
String emailAvalaible = jsonarr.getString(0);
if( emailAvalaible.equals("no") ){ doubleEmail = "no"; }else{ doubleEmail = "yes"; }
} catch (JSONException e) {
e.printStackTrace();
}
} catch (Exception e1) {
e1.printStackTrace();
}
}
return "String";
}// end of doInBackground()
#Override
protected void onPostExecute(String result){
super.onPostExecute(result);
if (doubleEmail.equals("no")){
LogIn.this.setEmailNotAvalaible(true);
}
}
}//end of AsyncTask class
private static HttpClient getHttpClient() {
if (mHttpClient == null) {
mHttpClient = new DefaultHttpClient();
final HttpParams params = mHttpClient.getParams();
HttpConnectionParams.setConnectionTimeout(params, HTTP_TIMEOUT);
HttpConnectionParams.setSoTimeout(params, HTTP_TIMEOUT);
ConnManagerParams.setTimeout(params, HTTP_TIMEOUT);
}
return mHttpClient;
}//end of getHttpClient()
public static String executeHttpPost(String url, ArrayList<NameValuePair> postParameters) throws Exception {
BufferedReader in = null;
try {
HttpClient client = getHttpClient();
HttpPost request = new HttpPost(url);
UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(postParameters);
request.setEntity(formEntity);
HttpResponse response = client.execute(request);
in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
StringBuffer sb = new StringBuffer("");
String line = "";
String NL = System.getProperty("line.separator");
while ((line = in.readLine()) != null) {
sb.append(line + NL);
}
in.close();
String result = sb.toString();
return result;
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}//end of executeHttpPost()
}//end of activity class
Some code is not shown, but this code isn't important for the solution.
The php-file just checks if the entered email does exist in the database.
So, the major question is how can I easily change the variable 'emailNotAvalaible' in doInBackground or in onPostExecute?
Thanks for your help!!!
EDIT:
Hello again, thanks for everybodys help, to change the variable works fine, but I guess my problem is, that before my Register AsyncTask is allready finished, the new AsyncTask proofs the variable and wants to start, but just a second after that the variable is set. So, How can I ensure that the second AsyncTask only starts when the first AsyncTask is Allready finished? thanks for your help guys!!!
There are several ways but the postExecute method can solve your problem look this: how to pass the result of asynctask onpostexecute method into the parent activity android
this should not be an issue. here is an example that works fine:
public class Register extends AsyncTask<String,Integer,String>{
#Override
protected void onPreExecute() {
Log.d("", "on pre bool: " + bool);
}//end of onPreExecute()
#Override
protected String doInBackground(String... params) {
bool = true;
return "";
}
#Override
protected void onPostExecute(String result){
super.onPostExecute(result);
Log.d("", "on post, bool: " + bool);
}
}
where bool = private boolean in your main activity. here is the logcat:
07-19 11:57:25.943: D/(21843): on pre bool: false
07-19 11:57:29.736: D/(21843): on post, bool: true
my guess is that your variable, doubleEmail, is not getting set to "no".
So, I think I have found at least one solution for my problem, this is maybe not the best one, but it works fine.
Now, for those who are interested in my solution.
I have found it here : multithreading , thanks to Boris Strandjev
I have chosen the 'get' - option : new Register().execute("").get(2000, TimeUnit.MILLISECONDS);
If there is any better solution, please tell me, otherwise thanks for trying to help me!
I have an AsynTask which retrieve data from a web service and with this data to be viewed on the UI. So, in my MainActivity, I have a textView.
This is the data I received from the webservice:
{"name":"ezio","country":"italy"}{"name":"fufu","country":"tutu"}{"name":"chikaka","country":"aceVentura"}
The problem is, I do not know how to set the textView with the value of 'result' from the ClientConnection class. When I run the application, the textView is empty.
public class ClientConnection extends AsyncTask {
public static final String URL = "http://192.168.0.15/test.php";
static JSONObject jObj = null;
public static String result = "";
#Override
protected String doInBackground(Void... voids) {
// public JSONObject connect(){
try{
HttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(URL);
HttpResponse response = httpClient.execute(httpGet);
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode != HttpStatus.SC_OK) {
Log.e("HTTPStatus error:","Status not okay");
}
InputStream in = response.getEntity().getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(in, "iso-8859-1"), 8);
StringBuilder str = new StringBuilder();
String line = null;
while((line = reader.readLine()) != null){
str.append(line + "\n");
}
in.close();
result = str.toString();
JSONObject jsonObject = convertToJson(result);
// jsonObject.get()
//result = jsonObject.getString("name");
//JSONArray google = jsonObject.getJSONArray("");
} catch (Exception e) {
//Toast toast = Toast.makeText(null, e.getMessage(), Toast.LENGTH_LONG);
Log.e("Error","don't know what exception though");
}
return result;
}
private JSONObject convertToJson(String test){
JSONArray clients = new JSONArray();
try{
jObj = new JSONObject(test);
}catch (JSONException e){
Log.e("JSON Parser", "Error parsing data" + e.toString());
}
return jObj;
}
public String getResult(){
return result;
}
public JSONObject getjObj(){
return jObj;
}
}
And this is the Main Activity
public class MyActivity extends Activity {
/**
* Called when the activity is first created.
*/
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final TextView textView = (TextView) findViewById(R.id.textViewTest);
ListView listView = (ListView) findViewById(R.id.listView);
Button buttonConnect = (Button) findViewById(R.id.buttonConnect);
final ClientJSONParsingActivity clientJSONParsingActivity = new ClientJSONParsingActivity();
buttonConnect.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
new ClientConnection().execute();
textView.setText(new ClientConnection().getResult());
}
});
}
}
Thank you for your help
You can display the result in the onPostExecute in the AsyncTask.
You should update textview in your asynctask. onPostExecute() method runs on UI thread
protected void onPostExecute(String result) {
textView.setText(result);
}
Pass the text view as an argument to the asynctask and set it in onPostExecute. On my mobile so no code, sorry ;-)
add this code under your doinbackground;
protected void onPostExecute(Long result) {
(find your text view here from the context where textview it is)
textView.setText(result);
}
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 :)