Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

bufferedReader for URL throws IOException

Tags:

android

I got my code to connect to my computers php file and output the correct text in a java program. When I tried to add it to my android project inorder to display high scores It always throws an IOException and I can't figure out why. Here is my code. Any help would be appreciated.


package com.enophz.spacetrash;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

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 Scores extends Activity {

 //private TextView HscoreText;

 /** Called when the activity is first created. */
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.scores);

        Button next = (Button) findViewById(R.id.Button01);
        next.setOnClickListener(new View.OnClickListener() {
            public void onClick(View view) {
                Intent myIntent = new Intent(view.getContext(), Menu.class);
                startActivity(myIntent);
            }

        });

        TextView HscoreText = (TextView) findViewById(R.id.text);

        try
        {
         URL page = new URL("http://192.168.1.108/score.php");
         URLConnection pageconnection = page.openConnection();
         BufferedReader in = new BufferedReader(
                    new InputStreamReader(
                    pageconnection.getInputStream()));

         in.close();


            HscoreText.setText("It Worked!");
        }
        catch(MalformedURLException e)
        {
         HscoreText.setText("MalformedURL");
        }
        catch (IOException e)
        {
         HscoreText.setText("IOException");
  }

    }

}
like image 289
drewsmug Avatar asked Jan 18 '11 05:01

drewsmug


Video Answer


1 Answers

I don't know what type of content you are expecting from the php page.. but following may help you to get the content from web server:

HttpClient httpClient = new DefaultHttpClient();
HttpContext localContext = new BasicHttpContext();
HttpGet httpGet = new HttpGet(myUrl);

HttpResponse response = httpClient.execute(httpGet, localContext);
BufferedReader reader = new BufferedReader(new InputStreamReader(
    response.getEntity().getContent(), "UTF-8"));

Now JSON will be single line so you can use:

String sResponse = reader.readLine();
JSONObject JResponse = new JSONObject(sResponse);

Otherwise to get the whole content as a string:

String sResponse;
StringBuilder s = new StringBuilder();

while ((sResponse = reader.readLine()) != null) {
s = s.append(sResponse);
}
like image 106
Vikas Avatar answered Sep 27 '22 18:09

Vikas