Boggy B
Boggy B

Reputation: 171

Android / Java - Converting DataInputStream into String

I currently have a connection established to some middleware, through which I send SQL queries to a database.

I'm having some trouble with converting the DataInputStream to a useable format (Whether or not that is a String). I looked at another StackOverflow question, however this did not resolve my problem since using

in.readLine();

is 'deprecated', whatever that means. I need to be able to read the response from my middleware.

private class NetworkTask extends AsyncTask<String, Void, Integer> 
{
    protected Integer doInBackground(String... params)
    {
        Message message = networkHandler.obtainMessage();

        String ip = "example ip";
        int port = 1234;

        try 
        {
            InetAddress serverAddr = InetAddress.getByName(ip);
            Log.d("EventBooker", "C: Connecting...");
            Socket socket = new Socket(serverAddr, port);               

            DataInputStream in = new DataInputStream(socket.getInputStream());


            try 
            {
                Log.d("EventBooker", "C: Connected. Sending command.");
                PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())), true);
                out.println(params[0]);
                networkHandler.sendMessage(message);
                Log.d("EventBooker", "C: Sent.");
            } 
            catch (Exception e) 
            {
                Log.e("EventBooker", "S: Error", e);
            }
            Log.d("EventBooker", "C: Reading...");



            Log.d("EventBooker", "C: Response read, closing.");
            socket.close();
            Log.d("Eventbooker", "C: Closed.");
        } 
        catch (Exception e)
        {
            Log.e("EventBooker", "C: Error", e);
        }
        return 1;
    }
}

Upvotes: 0

Views: 2415

Answers (1)

Johan S
Johan S

Reputation: 3591

Convert your DataInputStream to a BufferedReaderStream like this:

BufferedReader d = new BufferedReader(new InputStreamReader(in));

Then you want to get your actual String, to do this you do something like this:

StringBuffer sb = new StringBuffer();
String s = "";

while((s = d.readLine()) != null) {
    sb.append(s);
}

String data = sb.toString();

//Use data for w/e

Easy and simple!

The reason we don't just append it to a already existing string is that Java Strings are immutable so each time the String object is recreated, creating performance issues. Therefore the StringBuffer!

Upvotes: 2

Related Questions