I'm trying to develop a simple app that gets data from web service and displays it
It throws exception exactly when he calls response.execute(client)
package com.example.webbasedapp;
import java.io.BufferedReader;
import java.io.InputStream;
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.util.Log;
public class GETMethods {
public String getInternetData() throws Exception{
BufferedReader in=null;
String Data=null;
try{
HttpClient client=new DefaultHttpClient();
URI web=new URI("http://www.mybringback.com/");
HttpGet request = new HttpGet();
request.setURI(web);
HttpResponse reponse=client.execute(request);
Log.v("response code", reponse.getStatusLine()
.getStatusCode() + "");
InputStream inp=reponse.getEntity().getContent();
in=new BufferedReader(new InputStreamReader(inp));
StringBuffer buf=new StringBuffer();
String l="";
String nl=System.getProperty("line.separator");
while((l=in.readLine())!=null){
buf.append(l+nl);
}
in.close();
Data=buf.toString();
return Data;
}finally{
if(in!=null){
try{
in.close();
return Data;
}catch (Exception e){
Log.d("error",e.toString());
}
}
}
}
}
And this is my main activity
package com.example.webbasedapp;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.widget.TextView;
import android.widget.Toast;
public class Home extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
TextView test = (TextView) findViewById(R.id.data);
GETMethods data = new GETMethods();
String d = null;
try {
d = data.getInternetData();
// test.setText(d);
} catch (Exception e) {
// TODO Auto-generated catch block
d = "bla";
Toast.makeText(this, e.getMessage(), Toast.LENGTH_SHORT).show();
// Log.d("testW",e.getMessage());
}
test.setText(d);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.home, menu);
return true;
}
}
You are attempting to access the network on the UI thread which is not allowed due to potential hangup issues. Look into AysncTask and implement GETMethods as one of them. It will look something like this:
public class GETMethods extends AsyncTask<String, Void, String>{
protected void doInBackground(String... params){
YourNetworkCode
}
}
Related
I've this condition to write the server call that executes every 50ms.
The server call must be from volley.
But the difficulty i am facing is every server call has different urls and how to pass these different urls in thread so to call server every 50ms.?
I am not an expert in android, but this is what I could think of if you want to call different urls after 50ms. Please correct me if I am wrong :)
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
public class MainActivity extends AppCompatActivity {
private static final ScheduledExecutorService worker = Executors.newSingleThreadScheduledExecutor();
int i=0;
final String[] urlArray = new String[]{"http://google.com","http://fb.com"};//your url array here
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Runnable task = new Runnable() {
public void run() {
String currentURL= MainActivity.this.getNextURL();
new HitWebService().execute(currentURL);
}
};
worker.schedule(task, 50, TimeUnit.SECONDS);
}
private String getNextURL(){
String currentURL= urlArray[i];
if(i == urlArray.length){
i=0;
}
else{
i++;
}
return currentURL;
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
private class HitWebService extends AsyncTask<String,Void,String> {
protected void onPreExecute(){
//do whatever you want with respect to ui
}
#Override
protected String doInBackground(String... params){
HttpURLConnection connection=null;
String stringUrl= params[0];
try {
URL url= new URL(stringUrl);
connection=(HttpURLConnection)url.openConnection();
connection.setRequestMethod("POST");
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
DataOutputStream outputStream=new DataOutputStream(connection.getOutputStream());
String parameters = "initialise your parameters here, pass parameters also in params and access it like params[1]";
outputStream.writeBytes(parameters);
outputStream.flush();
outputStream.close();
InputStream inputStream=connection.getInputStream();
BufferedReader bufferedReader=new BufferedReader(new InputStreamReader(inputStream));
StringBuffer response = new StringBuffer();
String line;
while((line=bufferedReader.readLine())!=null){
response.append(line);
}
bufferedReader.close();
return response.toString();
}
catch (MalformedURLException malformedException){
return malformedException.toString();
}
catch (IOException ioException){
return ioException.toString();
}
finally {
if(connection !=null){
connection.disconnect();
}
}
}
#Override
protected void onPostExecute(String response){
//do whatever you want here
}
}
}
I was trying to load a web page on the emulator. I was trying the following code.
package com.test.scraptest;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity {
private TextView textView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = (TextView) findViewById(R.id.TextView01);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
private class DownloadWebPageTask extends AsyncTask<String, Void, String> {
#Override
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();
Log.e("MYAPP", "exception", e);
}
}
return response;
}
#Override
protected void onPostExecute(String result) {
textView.setText(result);
}
}
public void onClick(View view) {
DownloadWebPageTask task = new DownloadWebPageTask();
// new Toast(getApplicationContext());
Toast ts=Toast.makeText(this, "this is a message",Toast.LENGTH_SHORT) ;
ts.show();
task.execute(new String[] { "http://www.google.com" });
}
}
Problem is, when I run the application I get the following error.
Issue: I have two URLs that I need to call simultaneous to validate my session and directly enter to my Home (or other) pages. I am trying to call my first URL through HTTPClient execute and validate the session (Can call Login). Now second call is directly through WebView so that I can reach to my HomePage, instead of Login Page.
Below is my code. I refered lot of links and blogs but non of worked for me. I am putting my code here. Please provide your inputs if any.
package com.example.samplewebview;
import java.io.IOException;
import java.net.URL;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.cookie.Cookie;
import org.apache.http.impl.client.DefaultHttpClient;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.SystemClock;
import android.app.Activity;
import android.graphics.Bitmap;
import android.view.Menu;
import android.webkit.CookieManager;
import android.webkit.CookieSyncManager;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Toast;
public class MainActivity extends Activity {
WebView myWebView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
CookieSyncManager.createInstance(MainActivity.this);
myWebView = (WebView)findViewById(R.id.webView1);
new WebViewTask().execute();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
private class WebViewTask extends AsyncTask<Void, Void, Boolean> {
String sessionCookie;
CookieManager cookieManager;
String url1 = "http://domain.com/validateURL=sessionid";
String url2 = "http://domain.com/WebViewURLToLoad";
#Override
protected void onPreExecute() {
super.onPreExecute();
}
protected Boolean doInBackground(Void... param) {
DefaultHttpClient httpClient = new DefaultHttpClient();
//HttpGet httpGet = new HttpGet(url1);
HttpUriRequest request = new HttpGet(url1);
try {
HttpResponse response = httpClient.execute(request);
List<Cookie> cookies = httpClient.getCookieStore().getCookies();
for (int i = 0; i < cookies.size(); i++) {
Cookie cookie = cookies.get(i);
System.out.println("Name : "+cookie.getName()+" --- Value"+cookie.getValue());
}
cookieManager = CookieManager.getInstance();
//cookieManager.acceptCookie();
sessionCookie = cookieManager.getCookie(url1);
//sessionCookie = new PersistentConfig(getApplicationContext()).getCookieString();
//sessionCookie = new String("test");
if (sessionCookie != null) {
cookieManager.removeSessionCookie();
}
CookieSyncManager.createInstance(getApplicationContext()).sync();
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
SystemClock.sleep(1000);
return false;
}
#Override
protected void onPostExecute(Boolean result) {
myWebView.setWebViewClient(new WebViewClient() {
#Override
public void onPageStarted(WebView view, String url,
Bitmap favicon) {
if (sessionCookie != null) {
cookieManager.setCookie(url2, sessionCookie);
CookieSyncManager.getInstance().sync();
Toast.makeText(getApplicationContext(), url2, Toast.LENGTH_LONG).show();
}
//super.onPageStarted(view, url, favicon);
}
});
myWebView.loadUrl(url2);
}
}
}
I am currently trying to DL some twitter information and for some reason the code that I am using will not return the data.
When I use the URL manually in Explorer I do get data. but when I try to get Android to do it I get an exception.
I have found two ways of trying to get at the data. The first is as shown. The second is commenting out the three lines above the comments and uncommenting the other lines.
I will be using JSON simple afterwards in order to parse the string.
I hope I have explained my issue sufficiently. Any comments would be welcome.
import java.io.InputStream;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
String searchUrl = "http://search.twitter.com/search.json?q=#aplusk&rpp=100&page=1";
HttpClient client = new DefaultHttpClient();
HttpGet get = new HttpGet(searchUrl);
ResponseHandler<String> responseHandler = new BasicResponseHandler();
String responseBody = null;
Log.d("log", "test"+responseBody);
try{
responseBody = client.execute(get, responseHandler);
HttpResponse response = client.execute(get);
responseBody = response.toString();
// HttpResponse response = client.execute(get);
// InputStream inputStream = response.getEntity().getContent();
// responseBody = inputStream.toString();
Log.d("log", "test2"+responseBody);
}catch(Exception ex) {
Log.d("log", "nope");
ex.printStackTrace();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
I'm not sure what your exception is, but your first problem is probably that you're doing network activity on the main thread. You'll have to spin up a new thread or use an Async Task.
Your second problem is you're improperly converting the response to a string. To get the actual content string you'll have to iterate over an InputStream. This is my preferred method.
Also, make sure <uses-permission android:name="android.permission.INTERNET" /> is in your AndroidManifest.xml file.
Try this out:
import java.io.InputStream;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
(new Thread(new Runnable() {
#Override
public void run() {
String searchUrl = "http://search.twitter.com/search.json?q=#aplusk&rpp=100&page=1";
HttpClient client = new DefaultHttpClient();
HttpGet get = new HttpGet(searchUrl);
String responseBody = null;
Log.d("log", "test" + responseBody);
try {
HttpResponse response = client.execute(get);
InputStream inputStream = response.getEntity().getContent();
// responseBody = inputStream.toString();
responseBody = streamToString(inputStream);
Log.d("log", "test2" + responseBody);
} catch (Exception ex) {
Log.d("log", "nope");
ex.printStackTrace();
}
}
})).start();
}
public static String streamToString(InputStream is) {
java.util.Scanner s = new java.util.Scanner(is).useDelimiter("\\A");
return s.hasNext() ? s.next() : "";
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
So I am trying to create an Android app which basically reads out the twitter feed according to the search query inside a UI. The feed that I need to display form the parsed JSON is the user name, handle, profile picture and the tweet.
Now I have created the whole thing and my code compiles but as soon as I run it the app opens and I write something in the search feed and hit enter - " Unfortunately, AppName has stopped working " I am attaching my logcat and my source code for reference.
*Solved the issue by removing set text from DoInBackground and then giving adequate permission for Android to access internet. The issue now is that as I try and display the profile picture, the URL gets displayed, not the image.
Source code :
package com.example.twittersearchactivity;
import java.io.BufferedInputStream;
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 java.net.URLConnection;
import java.net.URLEncoder;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONObject;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
public class TwitterSearchActivity extends Activity {
private TextView tweetDisplay;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_twitter_search);
tweetDisplay = (TextView)findViewById(R.id.tweet_txt);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.twitter_search, menu);
return true;
}
public void searchTwitter(View view){
EditText searchTxt = (EditText)findViewById(R.id.search_edit);
String searchTerm = searchTxt.getText().toString();
if(searchTerm.length()>0){
try{
String encodedSearch = URLEncoder.encode(searchTerm, "UTF-8");
String searchURL = "http://search.twitter.com/search.json?q="+encodedSearch;
new GetTweets().execute(searchURL);
Log.i("1", "entered the searchterm");
}
catch(Exception e){
tweetDisplay.setText("Whoops - something went wrong!");
e.printStackTrace();
}
}
else
tweetDisplay.setText("Enter a search query!");
}
private class GetTweets extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... twitterURL) {
StringBuilder tweetFeedBuilder = new StringBuilder();
for (String searchURL : twitterURL) {
HttpClient tweetClient = new DefaultHttpClient();
try {
HttpGet tweetGet = new HttpGet(searchURL);
HttpResponse tweetResponse = tweetClient.execute(tweetGet);
StatusLine searchStatus = tweetResponse.getStatusLine();
if (searchStatus.getStatusCode() == 200) {
HttpEntity tweetEntity = tweetResponse.getEntity();
Log.i("2", "entered gettweets");
InputStream tweetContent = tweetEntity.getContent();
InputStreamReader tweetInput = new InputStreamReader(tweetContent);
BufferedReader tweetReader = new BufferedReader(tweetInput);
String lineIn;
while ((lineIn = tweetReader.readLine()) != null) {
tweetFeedBuilder.append(lineIn);
Log.i("3", "entered while in dobackground");
}
}
else {Log.i("error", "error");}
//tweetDisplay.setText("Whoops - something went wrong!");
}
catch(Exception e) {
Log.e("DEBUGTAG", "Remote Image Exception", e);
//tweetDisplay.setText("Whoops - something went wrong!");
e.printStackTrace();
}}
return tweetFeedBuilder.toString();
}
protected void onPostExecute(String result) {
StringBuilder y;
StringBuilder tweetResultBuilder = new StringBuilder();
try {
Log.i("tag", "entered try block");
JSONObject resultObject = new JSONObject(result);
JSONArray tweetArray = resultObject.getJSONArray("results");
for (int t=0; t<tweetArray.length(); t++) {
Log.i("tag", "entered the json stream");
JSONObject tweetObject = tweetArray.getJSONObject(t);
tweetResultBuilder.append(tweetObject.getString("from_user")+": ");
tweetResultBuilder.append(tweetObject.getString("from_user_name")+": ");
tweetResultBuilder.append(tweetObject.get("text")+"\n\n");
String imageURL = (String) tweetObject.get(("profile_image_url")+": ");
Bitmap bitmap = BitmapFactory.decodeStream((InputStream)new URL(imageURL).getContent());
#SuppressWarnings("deprecation")
Drawable d =new BitmapDrawable(bitmap);
d.setAlpha(255);
TextView.setCompoundDrawablesWithIntrinsicBounds(0,0,1,0);
}
}
catch (Exception e) {
tweetDisplay.setText("Whoops - something went wrong!");
e.printStackTrace();}
if(tweetResultBuilder.length()>0)
tweetDisplay.setText(tweetResultBuilder.toString());
else
tweetDisplay.setText("Sorry - no tweets found for your search!");
}
}}
You can't call view functions like setText on another thread like an AsyncTask doInBackground function. You need to do it in onPostExecute.