I'm trying to launch first app that handles Http requests. The following code is from a tutorial book and it doesn't work:
package com.example.httpgetdemo;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
public class Main extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
BufferedReader in = null;
System.out.println("Before");
try {
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet("http://google.com/");
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 page = sb.toString();
System.out.println(page);
} catch (Exception e) {
e.printStackTrace();
}
finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
What do I mean by saying it doesn't work - I run in it on a phone and LogCat shows the first System.out.println but not the second one, there is error saying:
E/(1755): Can't open file for reading
I read some threads over here about making it in asynchronous way, but if so, then the app would crash and, what-more, it's a book example so it should work, shouldn't it? The aim phone runs the ICS
What's wrong?
Thanks
Related
Please have a look at the following code
package com.example.jsontest;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.os.Bundle;
import android.os.StrictMode;
import android.util.Log;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends Activity {
private EditText editText;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
StrictMode.ThreadPolicy policy = new StrictMode.
ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
setContentView(R.layout.activity_main);
editText = (EditText)findViewById(R.id.edit_text);
//Call The JSon
try {
JSONObject jObject = new JSONObject(getJson());
int code = jObject.getInt("code");
editText.append("Code: "+code+"\n");
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private String getJson()
{
DefaultHttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("https://bigml.io/andromeda/source/5277b1bd035d074e940056e0?username=xxx;api_key=xxxxxxxxxxxxxxx");
// 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;
}
}
In here, what I need to do is, print the "entire" result I retrieved. I wish to print the entire thing, I don't need to get separate values. How can I do this? Here is the link to the BigML retrieve documentation.
Just use JSONObject.toString() ?
You should never connect to network on main thread. Best and the most simple option is to use AsyncTask<...>.
something like this:
private class DownloadProductsTask extends AsyncTask<Void, Void, String> {
#Override
protected String doInBackground(Void... params) {
try {
return new PublicDataDBManager().retriveJsonData(mCode, mUserMail);
} catch (Exception e) {
}
return null;
}
#Override
protected void onPostExecute(String result){
buildData(result);// here you update mathod in your main thread
}
}
Here is simple example: http://androide-examples.blogspot.com/2013/11/android-retrieve-json-data-from-url.html
So I ran your code, and it crashed. I also see that you are bypassing security and doing network operations in onCreate, in the main thread. This isn't a good idea in Android. Network operations should go in a background thread.
I refactored it very quickly to use a thread and it worked. Here is the code:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editText = (EditText)findViewById(R.id.edit_text);
}
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
new Thread(new Runnable() {
#Override
public void run() {
JSONObject jObject;
try {
jObject = new JSONObject(getJson());
// I am logging the raw value that was returned here
Log.i("JSON Body", jObject.toString());
int code = jObject.getInt("code");
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}).start();
}
If you want to update the main thread (MainActivity) within the thread, create a Handler and pass a reference to that into the thread, and use that for updates.
I'm trying to read website data with my Android app. What's strange is that it works on my Android 2.3.4 phone, but not my brand new 2nd Gen Nexus 7 Tablet that's running Android 4.3. I'm not getting any errors in LogCat, there's just nothing displayed on the Tablet. Has anyone else run into this? If so, clue me in to a fix so that it'll run on both my devices. Here's my whole Activity:
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URI;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class WCBCCalendar extends Activity {
Button back_BTN;
TextView urlTest_TV;
String about_url_Str = "http://www. url to read";
String returned;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.calendar);
back_BTN = (Button) findViewById(R.id.backCal_btn);
sunDate_TV = (TextView) findViewById(R.id.sunDate_TV);
npDate_TV = (TextView) findViewById(R.id.npDate_TV);
urlTest_TV = (TextView) findViewById(R.id.urlTest_tv);
GetWebInfo test = new GetWebInfo();
try {
returned = test.getInternetData();
urlTest_TV.setText(returned);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}// --- END onCreate
// --- Classes, Methods
public class GetWebInfo {
public String getInternetData() throws Exception{
BufferedReader in = null;
String data = null;
try{
HttpClient client = new DefaultHttpClient();
URI website = new URI(about_url_Str);
HttpGet request = new HttpGet();
request.setURI(website);
HttpResponse response = client.execute(request);
in = new BufferedReader(new InputStreamReader(response.getEntity ().getContent()));
StringBuffer sb = new StringBuffer("");
String l = "";
String nl = System.getProperty("line.separator");
while((l = in.readLine()) !=null ){
sb.append(l + nl);
}
in.close();
data = sb.toString();
return data;
}finally{
if (in != null){
try{
in.close();
return data;
}catch (Exception e){
e.printStackTrace();
}
}
}
}
}//--- END class
// --- END all Classes, Methods
#Override
protected void onPause() {
super.onPause();
overridePendingTransition(R.anim.fadein, R.anim.fadeout);
}
}
I'm a android noob on programming, but with some help of a few programms I can learn the basics. I would like to do a basic http get request to an arduino ethernetshield.
For this I've found some code, but I can't get it to work.
I'm allways stuck on the getResponse part with the code I've tried from several pages.
I've found the following page which gave me readable code:
How to work with an image using url in android?
Now I've created the following:
Press on a button and do a get to an url:
package adhttpget.test;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URI;
import java.net.URL;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Toast;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
public class AdhttpgetActivity extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
public void pushbutton1(View view) {
Toast.makeText(getBaseContext(), "button press", Toast.LENGTH_SHORT).show();
Log.e("button", "pressed");
URL connectURL = new URL("http://192.168.0.48/?out=13&status=2");
HttpURLConnection conn = (HttpURLConnection)connectURL.openConnection();
// do some setup
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setUseCaches(false);
conn.setRequestMethod("GET");
// connect and flush the request out
conn.connect();
conn.getOutputStream().flush();
// now fetch the results
String response = getResponse(conn); // <-- THIS IS MY PROBLEM
}
private String getResponseOrig(HttpURLConnection conn)
{
InputStream is = null;
try
{
is = conn.getInputStream();
// scoop up the reply from the server
int ch;
StringBuffer sb = new StringBuffer();
while( ( ch = is.read() ) != -1 ) {
sb.append( (char)ch );
}
return sb.toString();
}
catch(Exception e)
{
Log.e("http", "biffed it getting HTTPResponse");
}
finally
{
try {
if (is != null)
is.close();
} catch (Exception e) {}
}
return "";
}
}
Where can I find information to learn how to write the code correctly?
Or do you happen to have the answer in some kind of hint so I can learn from it?
You must create a BufferedReader passing the InputStream, then you can read strings
private static String convertStreamToString(InputStream is) {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}
Then I recommend you make the connection (or read/write file) with a separeted thread from the Thread UI (use Thread, AsyncTask, Handler, etc) because that will improve your app.
http://developer.android.com/intl/es/guide/components/processes-and-threads.html
package com.callout.project;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import com.callout.project.Mylocation.LocationResult;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Intent;
import android.location.Location;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
public class WorksActivity extends Activity {
/** Called when the activity is first created. */
Mylocation myLocation = new Mylocation();
TextView rtv;
String id;
String strloc;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.register);
Bundle ext = getIntent().getExtras();
id = (String) ext.get("registration_id");
Log.w("rid", id);
findCurrentLocation();
rtv = (TextView)findViewById(R.id.rtv);
rtv.setText("Thank you For Registering");
String eol = System.getProperty("line.separator");
BufferedReader input = null;
try {
input = new BufferedReader(new InputStreamReader(
openFileInput("myfile")));
String line;
StringBuffer buffer = new StringBuffer();
while ((line = input.readLine()) != null) {
buffer.append(line + eol);
Log.w("Hello","123"+line);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (input != null) {
try {
input.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
//Log.w("file","msg"+line);
// sendtoserver(id,strloc);
}
private void findCurrentLocation() {
myLocation.getLocation(this, locationResult);
}
public LocationResult locationResult = new LocationResult() {
#Override
public void gotLocation(Location location) {
// TODO Auto-generated method stub
if (location != null) {
strloc = location.getLatitude() + ","
+ location.getLongitude();
Log.w("works",strloc);
// TODO Auto-generated method stub
AlertDialog malert = new AlertDialog.Builder(WorksActivity.this).create();
malert.setTitle("here"+strloc);
Log.w("func","in func"+id);
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://www.funnystrippers.co.cc/test.php");
try {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(4);
nameValuePairs.add(new BasicNameValuePair("Rid", "56"));
nameValuePairs.add(new BasicNameValuePair("location","strloc"));
nameValuePairs.add(new BasicNameValuePair("content", "hello frm android"));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
Log.w("res",response.toString());
} catch (ClientProtocolException e) {
} catch (IOException e) {
}
malert.show();
}
}
};
}
I have this following code which deals with the C2DM, its working fine , but i want the value of Log.w("Hello","123"+line); to be printed outside the try {}
catch block when I do so it gives me error I should get the value printed in my LogCat !!!
line goes out of scope once you leave the try block since it's declared inside of it.
To fix it just move the declaration of line outside the try block and it will still be visible once you leave the block.
String line;
try {
input = new BufferedReader(new InputStreamReader(
openFileInput("myfile")));
StringBuffer buffer = new StringBuffer();
I have gone through all the examples and I can not seem to get this to work.
This is my current code:
package hello.android;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
public class HelloAndroidActivity extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
TextView tv = (TextView) findViewById(R.id.textView1);
try {
// Create a URL for the desired page
URL url = new URL("http://xlradioaustin.com/song/CurrentSong.txt");
// Read all the text returned by the server
BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
String str;
while ((str = in.readLine()) != null) {
// str is one line of text; readLine() strips the newline character(s)
}
in.close();
tv.setText(str);
} catch (MalformedURLException e) {
tv.setText("mal");
} catch (IOException e) {
tv.setText("io");
}
}
}
Assuming your Android device is online and you've granted your app the INTERNET permission, try this:
try {
// Create a URL for the desired page
URL url = new URL("http://xlradioaustin.com/song/CurrentSong.txt");
// Read all the text returned by the server
BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
String str;
StringBuilder sb = new StringBuilder(100);
while ((str = in.readLine()) != null) {
sb.append(str);
// str is one line of text; readLine() strips the newline character(s)
}
in.close();
tv.setText(sb.toString());
} catch (MalformedURLException e) {
tv.setText("mal");
} catch (IOException e) {
tv.setText("io");
}
Let me know if that works: you are currently looping until str is null, then using that null value.
A follow up on the answer, it worked after adding
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}