Advertisement
If you have a new account but are having problems posting or verifying your account, please email us on hello@boards.ie for help. Thanks :)
Hello all! Please ensure that you are posting a new thread or question in the appropriate forum. The Feedback forum is overwhelmed with questions that are having to be moved elsewhere. If you need help to verify your account contact hello@boards.ie

ANDROID QUERY

Options
  • 26-02-2014 10:25am
    #1
    Registered Users Posts: 72 ✭✭


    Hi Folks,

    Can anyone assist me with the following please and let me know why this is not working properly - i am doing this to try and learn how to get the internet on the app(it is only a test app so do not mind the layout / graphics etc) - and the toasts are there just to see where the problem lies.....which seems to be around the BufferedReader??

    [code]

    import java.io.BufferedReader;
    import java.io.InputStreamReader;
    import java.net.URL;
    import java.net.URLConnection;
    import android.os.Bundle;
    import android.app.Activity;
    import android.view.Menu;
    import android.view.View;
    import android.view.View.OnClickListener;
    import android.widget.Button;
    import android.widget.EditText;
    import android.widget.TextView;
    import android.widget.Toast;

    public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    final EditText et = (EditText) findViewById(R.id.search_box);
    final Button b = (Button) findViewById(R.id.Search_button);
    final TextView tv = (TextView) findViewById(R.id.Search_results);

    b.setOnClickListener(new OnClickListener() {


    public void onClick(View v){
    // Toast.makeText(getApplicationContext(), "Test1",
    // Toast.LENGTH_LONG).show();
    try{
    URL url = new URL(et.getText().toString());

    URLConnection conn = url.openConnection();
    Toast.makeText(getApplicationContext(), "Test - URL TEST",
    Toast.LENGTH_LONG).show();
    BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
    Toast.makeText(getApplicationContext(), "Test - URL1 TEST",
    Toast.LENGTH_LONG).show();

    String line = "";
    while((line = reader.readLine())!=null) {
    tv.append(line);
    }
    } catch(Exception e) {
    Toast.makeText(getApplicationContext(), e.toString(),
    Toast.LENGTH_LONG).show();

    }
    }
    });


    }



    @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;
    }

    }
    [end of code]

    thanks


Comments

  • Closed Accounts Posts: 19,777 ✭✭✭✭The Corinthian


    1. Firstly, have you remembered to give the app permission to connect to the Internet in the Manifest?
    android.permission.INTERNET
    
    2. What exception message are you getting anyway? Would make finding what's wrong a lot easier.

    3. Instead of BufferedReader, have you instead tried use:
    InputStream is = con.getInputStream();
    StringBuffer out = new StringBuffer();
    byte[] b = new byte[4096];
    for (int i; (i = is.read(b)) != -1;) {
        out.append(new String(b, 0, i));
    }
    System.out.println(out.toString());
    
    And use the [code] tags please, when posting code.


  • Registered Users Posts: 72 ✭✭shanard


    Will try that thanks - i have permissions set ok - it as giving me an error "NetworkOnMainThreadException"???


  • Registered Users Posts: 18,272 ✭✭✭✭Atomic Pineapple


    shanard wrote: »
    Will try that thanks - i have permissions set ok - it as giving me an error "NetworkOnMainThreadException"???

    You can't perform network operations on the main thread(I think the restriction was introduced in later versions of Android), look into using an AsyncTask to off load the operation onto an asynchronous thread.

    http://developer.android.com/reference/android/os/AsyncTask.html


  • Registered Users Posts: 72 ✭✭shanard


    Thanks AP!


  • Closed Accounts Posts: 19,777 ✭✭✭✭The Corinthian


    You can't perform network operations on the main thread(I think the restriction was introduced in later versions of Android)
    3.0+ I think.

    http://www.androiddesignpatterns.com/2012/06/app-force-close-honeycomb-ics.html


  • Advertisement
  • Registered Users Posts: 750 ✭✭✭smackyB


    Have you considered using a library to manage your network stuff? Takes a lot of the hassle and boilerplate out of your app. This one is nice: http://arnab.ch/blog/2013/08/asynchronous-http-requests-in-android-using-volley/


  • Closed Accounts Posts: 19,777 ✭✭✭✭The Corinthian


    smackyB wrote: »
    Have you considered using a library to manage your network stuff? Takes a lot of the hassle and boilerplate out of your app. This one is nice: http://arnab.ch/blog/2013/08/asynchronous-http-requests-in-android-using-volley/
    That might defeat the purpose of "doing this to try and learn how", I suspect.


  • Registered Users Posts: 750 ✭✭✭smackyB


    That might defeat the purpose of "doing this to try and learn how", I suspect.

    Ah, I missed that bit ;)


  • Registered Users Posts: 72 ✭✭shanard


    Hi Folks,

    Can anyone please have a look at the following please and guide me where i am going wrong or where i could improve this code. I am basically just trying to learn how to access the internet on android(for the first time) so its only a basic app just so i can try to get the code and functionality right. I have the permissions set in the manifest for internet and network state etc, so the problem lies somewhere below???

    The toasts are there just so i can follow the flow as they pop up on screen - and this is the second java/activity files within the same package.

    Thanks in advance!
    import java.io.BufferedReader;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.InputStreamReader;
    import java.net.HttpURLConnection;
    import java.net.URL;
    import java.net.URLConnection;
    
    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.impl.client.DefaultHttpClient;
    
    import android.net.ConnectivityManager;
    import android.net.NetworkInfo;
    import android.os.AsyncTask;
    import android.os.Bundle;
    import android.app.Activity;
    import android.content.Context;
    import android.content.Intent;
    import android.util.Log;
    import android.view.Menu;
    import android.view.View;
    import android.view.View.OnClickListener;
    import android.widget.Button;
    import android.widget.EditText;
    import android.widget.TextView;
    import android.widget.Toast;
    
    public class Sample extends Activity  {
    
    	protected void onCreate(Bundle savedInstanceState) {
    		super.onCreate(savedInstanceState);
    		setContentView(R.layout.activity_main);
    		
    		if(isNetworkAvailable()) Toast.makeText(getApplicationContext(), "Network is Available", Toast.LENGTH_LONG).show();
    		
    		
    	}
    	
    		public void run(){
    		
    				Toast.makeText(getApplicationContext(), "OnClick Test", Toast.LENGTH_LONG).show();
    			
    				Toast.makeText(getApplicationContext(), "Post String Test", Toast.LENGTH_LONG).show();
    			try {
    				 URL url = new URL("http://www.google.com");
    				  HttpURLConnection con = (HttpURLConnection) url
    				    .openConnection();
    				 StringBuilder builder = new StringBuilder();
    				 		HttpClient client = new DefaultHttpClient();
    				 		HttpGet httpGet = new HttpGet("http://www.google.com");
    				
    				 		HttpResponse response = client.execute(httpGet);
    				 		StatusLine statusLine = response.getStatusLine();
    				      int statusCode = statusLine.getStatusCode();
    				      if (statusCode == 200) {
    				        HttpEntity entity = response.getEntity();
    				        InputStream content = entity.getContent();
    				        BufferedReader reader = new BufferedReader(new InputStreamReader(content));
    				        String line;
    				        while ((line = reader.readLine()) != null) {
    				          builder.append(line);
    				        }
    				      } else {
    				        Log.e("getPageFromUrl()", "Failed to download file");
    				      }
    				  
    				   		 Toast.makeText(getApplicationContext(), "URL TEST",  Toast.LENGTH_SHORT).show();
    			}catch(Exception e) {
    				 		Toast.makeText(getApplicationContext(), e.toString(),  Toast.LENGTH_SHORT).show();
    							
    			}
    		}
    	
    	public boolean isNetworkAvailable() {
    	    ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    	    NetworkInfo networkInfo = cm.getActiveNetworkInfo();
    	    // if no network is available networkInfo will be null
    	    // otherwise check if we are connected
    	    if (networkInfo != null && networkInfo.isConnected()) {
    	        return true;
    	    }
    	    return false;
    	} 
    	
    	@Override
    	public boolean onCreateOptionsMenu(Menu menu) {
    		// Inflate the menu; this adds items to the action bar if it is present.
    		getMenuInflater().inflate(R.menu.sample, menu);
    		return true;
    	}
    
    }
    
    


  • Registered Users Posts: 7,868 ✭✭✭The_B_Man


    What errors are you getting?

    Where are you calling the "run()" method? Are you running it somewhere else in a thread?

    For web stuff, definitely look at AsyncTasks.


  • Advertisement
  • Registered Users Posts: 1,586 ✭✭✭Gaz


    You seem to be still trying network operations on the main thread, you need to use async ... something like this



    public class NetCheck extends AsyncTask<String,String,Boolean>
    {
    private ProgressDialog nDialog;

    @Override
    protected void onPreExecute(){
    super.onPreExecute();
    nDialog = new ProgressDialog(LockNowActivity.this);
    nDialog.setTitle("Checking Network");
    nDialog.setMessage("Loading..");
    nDialog.setIndeterminate(false);
    nDialog.setCancelable(true);
    nDialog.show();
    }

    //Gets current device state and checks for working internet connection by trying Google.

    @Override
    protected Boolean doInBackground(String... args){



    ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo netInfo = cm.getActiveNetworkInfo();
    if (netInfo != null && netInfo.isConnected()) {
    try {
    URL url = new URL("http://www.google.com");
    HttpURLConnection urlc = (HttpURLConnection) url.openConnection();
    urlc.setConnectTimeout(3000);
    urlc.connect();
    if (urlc.getResponseCode() == 200) {
    return true;
    }
    } catch (MalformedURLException e1) {
    // TODO Auto-generated catch block
    e1.printStackTrace();
    } catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    }
    }
    return false;

    }
    @Override
    protected void onPostExecute(Boolean th){

    if(th == true){
    nDialog.dismiss();
    new ProcessLogin().execute();
    }
    else{
    nDialog.dismiss();
    Toast.makeText(getBaseContext(),"No internet connection detected",
    Toast.LENGTH_SHORT).show();
    }
    }
    }




    private class ProcessLogin extends AsyncTask<String, String, JSONObject> {


    private ProgressDialog pDialog;


    @Override
    protected void onPreExecute() {


    pDialog = new ProgressDialog(LockNowActivity.this);
    pDialog.setTitle("Contacting Server");
    pDialog.setMessage("Loggin in ...");
    pDialog.setIndeterminate(false);
    pDialog.setCancelable(true);
    pDialog.show();
    }

    @Override
    protected JSONObject doInBackground(String... args) {

    }

    @Override
    protected void onPostExecute(JSONObject json) {
    try {


    ....do something

    }
    else {

    do something else

    }
    }
    } catch (JSONException e) {
    e.printStackTrace();
    }
    }
    }
    public void NetAsync(View view){
    new NetCheck().execute();
    }



    public void onBackPressed() {

    }

    }


  • Registered Users Posts: 72 ✭✭shanard


    HI - i transcribed your code into my test app to see if i can enter a URL at the top of the screen and under this press a button to search URL and below the button and taking up the rest of the screen, i have a textview which is where i want to display the URL - also instead of hardcoding in Google or any other website, i looking for the user to type in the URL of their choice - i hope this explains what i am looking for.... thanks in advance....

    Here is the code i took from you, which is containing some errors, if you wouldnt mind helping me with, thanks again...
    import java.io.IOException;
    import java.net.HttpURLConnection;
    import java.net.MalformedURLException;
    import java.net.URL;
    
    import org.json.JSONObject;
    
    import android.net.ConnectivityManager;
    import android.net.NetworkInfo;
    import android.os.AsyncTask;
    import android.os.Bundle;
    import android.app.Activity;
    import android.app.ProgressDialog;
    import android.content.Context;
    import android.view.Menu;
    import android.view.View;
    import android.widget.Toast;
    
    public class TestScreenActivity extends AsyncTask<String, String, Boolean> {
    	
    	private ProgressDialog nDialog;
    
    	@Override
    	protected void onPreExecute(){
    	super.onPreExecute();
    	nDialog = new ProgressDialog(LockNowActivity.this);
    	nDialog.setTitle("Checking Network");
    	nDialog.setMessage("Loading..");
    	nDialog.setIndeterminate(false);
    	nDialog.setCancelable(true);
    	nDialog.show();
    	}
    
    	//Gets current device state and checks for working internet connection by trying Google.
    	@Override
    	protected Boolean doInBackground(String... args) {
    		ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    		NetworkInfo netInfo = cm.getActiveNetworkInfo();
    		if (netInfo != null && netInfo.isConnected()) {
    		try {
    		URL url = new URL("http://www.google.com");
    		HttpURLConnection urlc = (HttpURLConnection) url.openConnection();
    		urlc.setConnectTimeout(3000);
    		urlc.connect();
    		if (urlc.getResponseCode() == 200) {
    		return true;
    		}
    		} catch (MalformedURLException e1) {
    		// TODO Auto-generated catch block
    		e1.printStackTrace();
    		} catch (IOException e) {
    		// TODO Auto-generated catch block
    		e.printStackTrace();
    			}
    		}
    		return false;
    	}
    		
    		@Override
    		protected void onPostExecute(Boolean th){
    
    		if(th == true){
    		nDialog.dismiss();
    		new ProcessLogin().execute();
    		}
    		else{
    		nDialog.dismiss();
    		Toast.makeText(getBaseContext(),"No internet connection detected",
    		Toast.LENGTH_SHORT).show();	
    		}
    		}
    
    		private Context getBaseContext() {
    			// TODO Auto-generated method stub
    			return null;
    		}
    		}
    	
    	 class ProcessLogin extends AsyncTask<String, String, JSONObject> {
    
    		private ProgressDialog pDialog;
    
    
    		public ProcessLogin() {
    			// TODO Auto-generated constructor stub
    		}
    
    		@Override
    		protected void onPreExecute() {
    
    
    		pDialog = new ProgressDialog(LockNowActivity.this);
    		pDialog.setTitle("Contacting Server");
    		pDialog.setMessage("Loggin in ...");
    		pDialog.setIndeterminate(false);
    		pDialog.setCancelable(true);
    		pDialog.show();
    		}
    
    		@Override
    		protected JSONObject doInBackground(String... args) {
    
    		}
    
    		@Override
    		protected void onPostExecute(JSONObject json) {
    		try {
    
    
    	//	....do something
    
    		}
    		else {
    
    		//do something else
    
    		}
    		}
    		} catch (JSONException e) {
    			e.printStackTrace();
    		}
    		}
    		}
    		public void NetAsync(View view){
    		new NetCheck().execute();
    		} 
    
    
    
    		public void onBackPressed() {
    
    		}
    
    		}
    	
    	
    
    

    The errors showing are as follows: -
    1) - LockNowActivity.this (on line 28) - error asks me to create a class/interface etc???
    2) - getSystemService (on line 39) - error asks me to create a method getSystemService()
    3) - LockNowActivity.this (on line 94) - error asks me to create a class/interface etc???
    4) - new NetCheck() (on line 121) - asks me to create class for this too???

    Thanks again folks


  • Registered Users Posts: 7,868 ✭✭✭The_B_Man


    For 4, if you definitely have a class called NetCheck, then maybe import the correct package for it, or make the ".execute()" method public.

    1-3 are to do with application context. You're doing it wrong, basically.
    I've run into this a lot of times and its very common (to me anyway).

    When I use AsyncTasks, I actually use them as inner classes, so I can get access to the current classes context (eg I can call LockNowActivity.this).

    The getSystemService is called through a context as well, so it should be "this.getSystemService()", or possibly "LockNowActivity.this.getSystemService()"


  • Registered Users Posts: 72 ✭✭shanard


    Thanks B_Man - however since i am a beginner to this android thing - any chance you could guide me through what you described above please??

    Thanks

    K


  • Registered Users Posts: 1,586 ✭✭✭Gaz


    LockNowActivity was my activity , you need to create your own ... this is just as an example. I think you need to study this a bit more, not much point in us giving you the code ... try this http://www.vogella.com/tutorials/AndroidBackgroundProcessing/article.html


  • Registered Users Posts: 7,868 ✭✭✭The_B_Man


    Here's some untested code you can try. I've taken it from one of my apps, and stripped all my app-specific stuff using notepad, so I might have missed something.
    This should have everything in it that you need to know. If you can understand this, you should be good to go.

    It uses a nested class for the AsyncTask. I'm sure you can edit it to be in a standalone reusable class if need be.

    To use it, in your calling class do this:
    NetworkManager nm = new NetworkManager(this);
    nm.downloadData("www.google.com");
    

    It assumes you don't need to have the returned data in your calling class, and that you handle it in your AsyncTask.doInBackground() method.

    This is actually how I use it in my apps, so I'd be curious to see what other devs think. Maybe someone can provide optimisations.
    public class NetworkManager {
    	private Activity activity;
    
    	private NetworkManager() { }
    	public NetworkManager(Activity activity) {
    		this();
    		this.activity = activity;
    	}
    
    	public void downloadData(String url) {
    		new DownloadDataFromURL(url).execute();
    	}
    
    	private class DownloadDataFromURL extends AsyncTask<Void, Void, Void> {
    		private String url;
    		private String downloadedData;
    		private ProgressDialog dialog;
    
    		public DownloadDataFromURL(String url) {
    			this.url = url;
    		}
    
    		@Override
    		protected void onPreExecute() {
    			dialog = new ProgressDialog(activity);
    			dialog.setTitle("Downloading data");
    			dialog.setMessage("Connecting to server");
    			if(!dialog.isShowing()) {
    				dialog.show();
    			}
    		}
    		
    		@Override
    		protected Void doInBackground(Void... params) {
    			StringBuilder sb = doCodeToDownloadData(url);
    			downloadedData = sb.toString();
    			//Now do whatever you want with the data
    			return null;
    		}
    		
    		@Override
    		protected void onPostExecute(Void result) {
    			//Add code to handle any other tasks
    			if(dialog.isShowing()) {
    				dialog.dismiss();
    			}
    		}
    	}
    	
    	private StringBuilder doCodeToDownloadData(String url) {
    		//Do work to download data
    	}
    }
    


  • Registered Users Posts: 72 ✭✭shanard


    Will try that and will let you know my feedback thereafter - cheers for your assistance B-Man....


  • Closed Accounts Posts: 19,777 ✭✭✭✭The Corinthian


    Here's a nice little series of examples that demonstrate different ways to make HTTP calls using Java on Android:

    http://blog.dahanne.net/2009/08/16/how-to-access-http-resources-from-android/


Advertisement