1

I can't convert a string to an array!

String text = "";
String[] textsplit = {};

//Stuff

The app set the content of an online txt file in a string:

The online txt file contain: hello,my,name,is,simone

[...] //Downloading code
text = bo.toString(); //Set the content of the online file to the string

Now the string text is like this:

text = "hello,my,name,is,simone"

Now i have to convert the string to an array that must be like this:

textsplit = {"hello","my","name","is","simone"}

so the code that i use is:

textsplit = text.split(",");

But when i try to use the array the app crash! :( For example:

textview.setText(textsplit[0]); //The text of the textview is empity
textview.setText(textsplit[1]); //The app crash
textview.setText(textsplit[2]); //The app crash 

etc... where am I wrong? thanks!

EDIT: This is the code:

new Thread() {
        @Override
        public void run() {
            String path ="http://www.luconisimone.altervista.org/ciao.txt";
            URL u = null;
            try {
                u = new URL(path);
                HttpURLConnection c = (HttpURLConnection) u.openConnection();
                c.setRequestMethod("GET");
                c.connect();
                InputStream in = c.getInputStream();
                final ByteArrayOutputStream bo = new ByteArrayOutputStream();
                byte[] buffer = new byte[1024];
                in.read(buffer); // Read from Buffer.
                bo.write(buffer); // Write Into Buffer.

                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        text = bo.toString();
                        testo.setText("(" + text + ")");
                        try {
                            bo.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                });

            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (ProtocolException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
    }.start();

// Here all variables became empity


    textsplit = text.split(",");
    datisplittati.setText(textsplit[0]);
8
  • 1
    I do not see anything wrong. Are you absolutely sure text is the String you provided? The fact that the first element of the array is empty would suggest that the String is empty since "".split(","); would be an array with a single empty String object Commented Jul 4, 2015 at 12:53
  • You need to print the text that is received from the file and ensure that its contents is as expected. Also, Arrays.toString(textsplit) will return a readable String representation of the array contents, which you can use to print for debugging. Commented Jul 4, 2015 at 12:58
  • Your string is like "hello,my,name,is,simone" or "hello, my, name, is, simone"? Please paste string here same like you pass Commented Jul 4, 2015 at 13:03
  • @SamTebbs33 or better would be to learn how to use the debugger. Commented Jul 4, 2015 at 13:04
  • You can trim string before splitting. And then try I think your problem will solved Commented Jul 4, 2015 at 13:06

3 Answers 3

1

Try :

String text = "hello,my,name,is,simone";
String[] textArr = text.split(Pattern.quote(","));
Sign up to request clarification or add additional context in comments.

Comments

0

You can get string using AsyncTask

private class GetStringFromUrl extends AsyncTask<String, Void, String> {

    ProgressDialog dialog ;

    @Override
    protected void onPreExecute() {
        super.onPreExecute();

        // show progress dialog when downloading 
        dialog = ProgressDialog.show(MainActivity.this, null, "Downloading...");
    }

    @Override
    protected String doInBackground(String... params) {

        // @BadSkillz codes with same changes
        try {
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpGet httpGet = new HttpGet(params[0]);
            HttpResponse response = httpClient.execute(httpGet);
            HttpEntity entity = response.getEntity();

            BufferedHttpEntity buf = new BufferedHttpEntity(entity);

            InputStream is = buf.getContent();

            BufferedReader r = new BufferedReader(new InputStreamReader(is));

            StringBuilder total = new StringBuilder();
            String line;
            while ((line = r.readLine()) != null) {
                total.append(line + "\n");
            }
            String result = total.toString();
            Log.i("Get URL", "Downloaded string: " + result);
            return result;
        } catch (Exception e) {
            Log.e("Get Url", "Error in downloading: " + e.toString());
        }
        return null;
    }

    @Override
    protected void onPostExecute(String result) {
        super.onPostExecute(result);

        // TODO change text view id for yourself
        TextView textView = (TextView) findViewById(R.id.textView1);

        // show result in textView
        if (result == null) {
            textView.setText("Error in downloading. Please try again.");
        } else {
            textView.setText(result);
        }

        // close progresses dialog
        dialog.dismiss();
    }
}

and use blow line every time that you want:

new GetStringFromUrl().execute("http://www.luconisimone.altervista.org/ciao.txt");

Comments

0

You're using new thread to get data from an url. So in runtime, data will be asynchronous.
So when you access text variable (split it), it's still not get full value (example reason: network delay).
Try to move the function split after text = bo.toString(); , I think it will work well.

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.