0

Here is my MainActivity (only activity) in my project (FSM, I know)

public class MainActivity extends Activity {
    private static final String DEBUG_TAG = "HttpExample";
    private static final String MYURL = "http://www.myserver.com/myapp/usertable.php";
    private TextView textView;

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

        textView = (TextView) findViewById(R.id.hello_world);

        if (savedInstanceState == null) {
            getFragmentManager().beginTransaction()
                    .add(R.id.container, new PlaceholderFragment())
                    .commit();
        }

        //Check connectivity
        ConnectivityManager connMgr = (ConnectivityManager)
                getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
        if (networkInfo != null && networkInfo.isConnected()) {
            //fetch data
            new DownloadWebpageTask().execute(MYURL);
            textView.setText("Fetching data");


        } else {
            //show error
            textView.setText("No network connection available.");
        }
    }

    private class DownloadWebpageTask extends AsyncTask<String, Void, String> {
        @Override
        protected String doInBackground(String... urls) {

            // params comes from the execute() call: params[0] is the url.
            try {
                return downloadUrl(urls[0]);
            } catch (IOException e) {
                return "Unable to retrieve web page. URL may be invalid.";
            }
        }
        // onPostExecute displays the results of the AsyncTask.
        @Override
        protected void onPostExecute(String result) {
            textView.setText(result);
            textView.setMovementMethod(new ScrollingMovementMethod());
        }
    }

    //Method to convert url to url object
    private String downloadUrl(String myurl) throws IOException {
        InputStream is = null;
        // Only display the first 500 characters of the retrieved
        // web page content.
        int len = 16*1024; //Try 16*1024
        String username;
        String password;
        String email;

        try {
            URL url = new URL(myurl);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setReadTimeout(10000 /* milliseconds */);
            conn.setConnectTimeout(15000 /* milliseconds */);
            conn.setRequestMethod("GET");
            conn.setDoInput(true);
            // Starts the query
            conn.connect();
            int response = conn.getResponseCode();
            Log.d(DEBUG_TAG, "The response is: " + response);
            is = conn.getInputStream();

            // Convert the InputStream into a string
            String contentAsString = readIt(is, len);
            Log.d(DEBUG_TAG, "The data is: " + contentAsString);

            try {
                //Get master array of locations
                Log.d(DEBUG_TAG, "BEFORE JSONArray: " + contentAsString);

                JSONArray jsonArray = new JSONArray(contentAsString);
                Log.d(DEBUG_TAG, "AFTER JSONArray: " + contentAsString);

                //Loop through each dictionary in array
                for (int i = 0; i < jsonArray.length(); i++) {
                    //test array contents
                    //String strToPrint = "jsonArray[" + i + "]=" + jsonArray[i];

                    //Get the lat&long for
                    JSONObject someData  = jsonArray.getJSONObject(i);
                    System.out.println(i + " id : " + someData.getString("id"));
                    System.out.println(i + " user : " + someData.getString("username"));
                    System.out.println(i + " email : " + someData.getString("email"));
                    //username = sys.getString("username");
                    //email = sys.getString("email");
                    //password = sys.getString("password");

                    //Create location object

                    // Use Location.distanceTo() - creates list of distances to users current location

                    //add distance to array?
                }

                //Sort and get nearest 5 locations


                //better use Mirror API
            } catch (Exception e) {
                // TODO Auto-generated catch block
                System.out.println("trycatch" );

                e.printStackTrace();
            }


            return contentAsString;

            // Makes sure that the InputStream is closed after the app is
            // finished using it.
        } finally {
            if (is != null) {
                is.close();
            }
        }
    }

    //Get distances
    public float distanceTo (Location dest) {

        //Compare distance passed to user location

        //return distance float
        return 1;
    }


    //Convert input stream to string
    // Reads an InputStream and converts it to a String.
    public String readIt(InputStream stream, int len) throws IOException, UnsupportedEncodingException {
        Reader reader = null;
        reader = new InputStreamReader(stream, "UTF-8");
        char[] buffer = new char[len];
        reader.read(buffer);
        return new String(buffer);
    }

Here is the end of whats printed as data is: at the end of a long string of the correct characters:

,"email":"Jo������������

where the server response is actually:

,"email":"[email protected]"

Here is a sample of the server result:

[{"id":"36","username":"Simulor","password":"0457e576192406775e574c2555e2edc6","password_hint":"","last name":"","first name":"","email":"[email protected]","phone":"","address1":"","address2":"","city":"","state":"","zip":"","country":"","url":"","permissions":"1","udid":"9","userCreated":"2013-06-29 17:51:40","time_queued":null,"time_sent":null},
{"id":"35","username":"zlitsami ","password":"932d1c42a4e4880e57037994fd3584b1","password_hint":"","last name":"","first name":"","email":"[email protected]","phone":"","address1":"","address2":"","city":"","state":"","zip":"","country":"","url":"","permissions":"1","idid":"9","userCreated":"2013-01-01 14:27:22","time_queued":null,"time_sent":null},{"id":"34","username":"Probate","password":"5fbba4aa93a00a9d75b19a3b7f9249bd","password_hint":"","last name":"","first name":"","email":"[email protected]","phone":"","address1":"","address2":"","city":"","state":"","zip":"","country":"","url":"","permissions":"1","udid":"9","userCreated":"2012-06-15 12:17:53","time_queued":null,"time_sent":null},{"id":"4","username":"carSim","password":"2d157441e6f311d0a5c8a5cbe2fd6f06","password_hint":"","lastname":"","firstname":"","email":"[email protected]","phone":"","address1":"","address2":"","city":"","state":"","zip":"","country":"","url":"","permissions":"1","udid":"F6869FB4-2EBE-5D43-A62D-5D4007646764","userCreated":"0000-00-00 00:00:00","time_queued":null,"time_sent":"2011-06-24 11:59:23"},{"id":"33","username":"Test","password":"68eacb97d86f0c4621fa2b0e17cabd8c","password_hint":"","lastname":"","firstname":"","email":"[email protected]","phone":"","address1":"","address2":"","city":"","state":"","zip":"","country":"","url":"","permissions":"1","udid":"9","userCreated":"2012-06-15 12:03:49","time_queued":null,"time_sent":null},{"id":"6","username":"danni","password":"6d1ab84bf937dde5ef7d738f97b44314","password_hint":"","lastname":"","firstname":"","email":"[email protected]","phone":"","address1":"","address2":"","city":"","state":"","zip":"","country":"","url":"","permissions":"1","udid":"36e83a379985ce9e485fdbd2d94d2c835f869b1c","userCreated":"0000-00-00 00:00:00","time_queued":null,"time_sent":"2011-06-24 11:59:23"},{"id":"7","username":"janevm","password":"da80a7e5f20f7dd56370dba9305155ef","password_hint":"","lastname":"","firstname":"","email":"[email protected]","phone":"","address1":"","address2":"","city":"","state":"","zip":"","country":"","url":"","permissions":"1","udid":"adead80b9f8426ff4c20b38f4aa8cca9ab75e383","userCreated":"0000-00-00 00:00:00","time_queued":null,"time_sent":"2011-06-24 11:59:23"},{"id":"8","username":"JohnFranks","password":"3cc5f0b88d4cf16008ed8f63c88ddcb0","password_hint":"","lastname":"","firstname":"","email":"[email protected]","phone":"","address1":"","address2":"","city":"","state":"","zip":"","country":"","url":"","permissions":"1","idid":"9950b4a6189f338eb68b38bd76745ef6a6d932f1","userCreated":"0000-00-00 00:00:00","time_queued":null,"time_sent":"2011-06-24 11:59:23"}
]

What could be causing those strange characters? They only occur when I make the Stream's int len this size (16*1024). Originally it was only 500. But why would I even need to specify an amount of characters to return?

Why does the app never get past the JSONArray jsonArray = new JSONArray(contentAsString); line?

Can I take that which is a JSON encoded array, and put it straight into an array in java?

3 Answers 3

1

Why are you calling someData.getInt() / sameData.getDouble() when the values for id, username, and email are strings ? You should be calling someData.getString() instead.

Sign up to request clarification or add additional context in comments.

3 Comments

I changed them to string. Ok but I still get the strange data characters after Jo.....Any ideas why?
That looks like more of an encoding problem. Is it possible that the string is not being loaded with the right encoding? Or, possibly (if you are using eclipse), the IDE is not set up with the right encoding. See stackoverflow.com/questions/17174624/…
Im not using Eclipse, Im using Android Studio. How should I encode it such that it will work?
0

Is it possible you can provide your web-service url so that I can test with my code?

Can you please change both getDouble for user & getBoolean for email to getString like below:

System.out.println(i + " user : " + someData.getString("username"));
System.out.println(i + " email : " + someData.getString("email"));

2 Comments

Well here is a complete response of just a few results.
Thanks, I was testing 2 different service while debugging. I forgot to change them.
0

I replaced the method for reading the InputStream to this:

public String readIt(InputStream stream, int len) throws IOException, UnsupportedEncodingException {

        StringBuilder builder = new StringBuilder();
        BufferedReader reader = new BufferedReader(new InputStreamReader(stream));

        //New code to convert InputStream to String
        String line;
        while ((line = reader.readLine()) != null) {
        builder.append(line);
        }
        return builder.toString();
    }

and it works now.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.