-1

I have made a String replace method in android which is not working. It displays the same output as input(no change).

The Replacement method is at the last lines of the code.I have tried here to replace like "mon" to "MONDAY","tue" to "TUESDAY"....etc,...My code as below:

Main.java

public class MainActivity extends Activity {
    String temperature, date, condition, humidity, wind, link;
    Bitmap icon = null;
    TextView title, tempText, dateText, conditionText, windText, humidityText,
            weatherLink, day1, day2, day3, day4, day5, day6, day7;
    ImageView image;
    TextView temp1, temp2, temp3, temp4, temp5, txt1, txt2, txt3, txt4, txt5;
    ArrayList<String> weather = new ArrayList<String>();
    ProgressDialog dialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        image = (ImageView) findViewById(R.id.icon);
        title = (TextView) findViewById(R.id.weather_title);
        dateText = (TextView) findViewById(R.id.dateText);
        tempText = (TextView) findViewById(R.id.tempText);
        conditionText = (TextView) findViewById(R.id.conditionText);
        humidityText = (TextView) findViewById(R.id.humidityText);
        windText = (TextView) findViewById(R.id.windText);
        day1 = (TextView) findViewById(R.id.day1);
        day2 = (TextView) findViewById(R.id.day2);
        day3 = (TextView) findViewById(R.id.day3);
        day4 = (TextView) findViewById(R.id.day4);
        temp1 = (TextView) findViewById(R.id.temp1);
        temp2 = (TextView) findViewById(R.id.temp2);
        temp3 = (TextView) findViewById(R.id.temp3);
        temp4 = (TextView) findViewById(R.id.temp4);
        temp5 = (TextView) findViewById(R.id.temp5);
        txt1 = (TextView) findViewById(R.id.txt1);
        txt2 = (TextView) findViewById(R.id.txt2);
        txt3 = (TextView) findViewById(R.id.txt3);
        txt3 = (TextView) findViewById(R.id.txt4);
        txt3 = (TextView) findViewById(R.id.txt5);

        weatherLink = (TextView) findViewById(R.id.weatherLink);
        /*
         * Typeface tf = Typeface.createFromAsset(getAssets(),
         * “Fonts/Roboto-Condensed.ttf”);
         */
        title.setText("My Weather Report");
        /*
         * tempText.setTypeface(tf); conditionText.setTypeface(tf);
         * dateText.setTypeface(tf); humidityText.setTypeface(tf);
         * windText.setTypeface(tf); title.setTypeface(tf);
         * day1.setTypeface(tf); day2.setTypeface(tf); day3.setTypeface(tf);
         * day4.setTypeface(tf);
         */
        ImageButton backBtn = (ImageButton) findViewById(R.id.backBtn);
        ImageButton report = (ImageButton) findViewById(R.id.reportBtn);

        new retrieve_weatherTask().execute();
    }

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

    protected class retrieve_weatherTask extends
            AsyncTask<Void, String, String> {

        @Override
        protected void onPreExecute() {
            // TODO Auto-generated method stub
            super.onPreExecute();

            dialog = new ProgressDialog(MainActivity.this);
            dialog.setTitle("Please wait...");
            dialog.show();
        }

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

            // TODO Auto-generated method stub
            String qResult = "";
            HttpClient httpClient = new DefaultHttpClient();
            HttpContext localContext = new BasicHttpContext();
            HttpGet httpGet = new HttpGet(
                    "http://weather.yahooapis.com/forecastrss?w=2295425&u=c&#8221");

            try {
                HttpResponse response = httpClient.execute(httpGet,
                        localContext);
                HttpEntity entity = response.getEntity();

                if (entity != null) {
                    InputStream inputStream = entity.getContent();
                    Reader in = new InputStreamReader(inputStream);
                    BufferedReader bufferedreader = new BufferedReader(in);
                    StringBuilder stringBuilder = new StringBuilder();
                    String stringReadLine = null;
                    while ((stringReadLine = bufferedreader.readLine()) != null) {
                        stringBuilder.append(stringReadLine + "\n");

                    }
                    qResult = stringBuilder.toString();
                }

            } catch (ClientProtocolException e) {
                e.printStackTrace();
                Toast.makeText(MainActivity.this, e.toString(),
                        Toast.LENGTH_LONG).show();
            } catch (IOException e) {
                e.printStackTrace();
                Toast.makeText(MainActivity.this, e.toString(),
                        Toast.LENGTH_LONG).show();
            }

            Document dest = null;
            DocumentBuilderFactory dbFactory = DocumentBuilderFactory
                    .newInstance();
            DocumentBuilder parser;
            try {
                parser = dbFactory.newDocumentBuilder();
                dest = parser
                        .parse(new ByteArrayInputStream(qResult.getBytes()));
            } catch (ParserConfigurationException e1) {
                e1.printStackTrace();
                Toast.makeText(MainActivity.this, e1.toString(),
                        Toast.LENGTH_LONG).show();
            } catch (SAXException e) {
                e.printStackTrace();
                Toast.makeText(MainActivity.this, e.toString(),
                        Toast.LENGTH_LONG).show();
            } catch (IOException e) {
                e.printStackTrace();
                Toast.makeText(MainActivity.this, e.toString(),
                        Toast.LENGTH_LONG).show();
            }

            Node temperatureNode = dest.getElementsByTagName(
                    "yweather:condition").item(0);
            temperature = temperatureNode.getAttributes().getNamedItem("temp")
                    .getNodeValue().toString();
            Node tempUnitNode = dest.getElementsByTagName("yweather:units")
                    .item(0);
            temperature = temperature
                    + "°"
                    + tempUnitNode.getAttributes().getNamedItem("temperature")
                            .getNodeValue().toString();

            Node dateNode = dest.getElementsByTagName("yweather:forecast")
                    .item(0);
            date = dateNode.getAttributes().getNamedItem("date").getNodeValue()
                    .toString();

            Node conditionNode = dest
                    .getElementsByTagName("yweather:condition").item(0);
            condition = conditionNode.getAttributes().getNamedItem("text")
                    .getNodeValue().toString();

            Node humidityNode = dest
                    .getElementsByTagName("yweather:atmosphere").item(0);
            humidity = humidityNode.getAttributes().getNamedItem("humidity")
                    .getNodeValue().toString();
            humidity = humidity + "%";

            Node windNode = dest.getElementsByTagName("yweather:wind").item(0);
            wind = windNode.getAttributes().getNamedItem("speed")
                    .getNodeValue().toString();
            Node windUnitNode = dest.getElementsByTagName("yweather:units")
                    .item(0);
            wind = wind
                    + " "
                    + windUnitNode.getAttributes().getNamedItem("speed")
                            .getNodeValue().toString();

            String desc = dest.getElementsByTagName("item").item(0)
                    .getChildNodes().item(13).getTextContent().toString();
            StringTokenizer str = new StringTokenizer(desc, "<=>");
            System.out.println("Tokens: " + str.nextToken("=>"));
            String src = str.nextToken();
            System.out.println("src: " + src);
            String url1 = src.substring(1, src.length() - 2);
            Pattern TAG_REGEX = Pattern.compile("(.+?)<br />");
            Matcher matcher = TAG_REGEX.matcher(desc);
            while (matcher.find()) {
                weather.add(matcher.group(1));
            }

            Pattern links = Pattern.compile("(.+?)<BR/>");
            matcher = links.matcher(desc);
            while (matcher.find()) {
                System.out.println("Match Links: " + (matcher.group(1)));
                link = matcher.group(1);
            }

            /*
             * String test = (Html.fromHtml(desc)).toString();
             * System.out.println(“test: “+ test); StringTokenizer tkn = new
             * StringTokenizer(test); for(int i=0; i < tkn.countTokens(); i++){
             * System.out.println(“Remaining: “+tkn.nextToken()); }
             */

            InputStream in = null;
            try {
                // in = OpenHttpConnection(url1);
                int response = -1;
                URL url = new URL(url1);
                URLConnection conn = url.openConnection();

                if (!(conn instanceof HttpURLConnection))
                    throw new IOException("Not an HTTP connection");
                HttpURLConnection httpConn = (HttpURLConnection) conn;
                httpConn.setAllowUserInteraction(false);
                httpConn.setInstanceFollowRedirects(true);
                httpConn.setRequestMethod("GET");
                httpConn.connect();

                response = httpConn.getResponseCode();
                if (response == HttpURLConnection.HTTP_OK) {
                    System.out.println("*********************");
                    in = httpConn.getInputStream();
                }
                icon = BitmapFactory.decodeStream(in);
                in.close();
            } catch (IOException e1) {
                e1.printStackTrace();
            }
            return qResult;

        }

        protected void onPostExecute(String result) {
            System.out.println("POST EXECUTE");

            if (dialog.isShowing() && dialog != null)
                dialog.dismiss();
            tempText.setText("Temperature:" + temperature);
            conditionText.setText("Condition: " + condition);
            dateText.setText("Date: " + date);
            humidityText.setText("Humidity: " + humidity);
            windText.setText("Wind: " + wind);
            // image.setImageBitmap(icon);
            String three = weather.get(3);
            String four = weather.get(4);
            String five = weather.get(5);
            String six = weather.get(6);

            System.out.println(":::::::thusday:::::" + weather.get(3));
            System.out.println(":::::::friday:::::" + weather.get(4));
            System.out.println(":::::::satrday:::::" + weather.get(5));
            System.out.println(":::::::sunday:::::" + weather.get(6));

            // DAY1
            String[] parts1 = three.split("-");
            String th1 = parts1[0]; // 004
            String th22 = parts1[1];
            String[] sub1 = th22.split(". H");
            String t1 = sub1[0];
            String t2 = sub1[1];
            System.out.println(":::::::;Part 1:::::::::" + t1);
            System.out.println(":::::::;Part 1:::::::::" + t2);

            day1.setText(weekdaygen(th1.trim()));
            System.out.println("::::::::::::::::REPLACE:::::::" + th1);
            temp1.setText("H" + t2);

            txt1.setText(t1);

            /*
             * // DAY2 String[] parts2 = four.split("-"); String th2 =
             * parts2[0]; // 004 String th23 = parts2[1]; String[] sub2 =
             * th23.split(". "); String t3 = sub2[0]; String t4 = sub2[1];
             * 
             * day2.setText(th2); temp2.setText(t4); txt2.setText(t3);
             * 
             * // DAY4 String[] parts4 = five.split("-"); String th4 =
             * parts4[0]; // 004 String th25 = parts4[1]; String[] sub4 =
             * th25.split(". "); String t7 = sub4[0]; String t8 = sub4[1];
             * 
             * day3.setText(th4); temp3.setText(t8); txt3.setText(t7);
             * 
             * // DAY5 String[] parts5 = five.split("-"); String th5 =
             * parts5[0]; // 004 String th26 = parts5[1]; String[] sub5 =
             * th26.split(". "); String t9 = sub5[0]; String t10 = sub5[1];
             * 
             * day4.setText(th5); temp4.setText(t10); txt4.setText(t9);
             * 
             * day1.setText(weather.get(3)); day2.setText(weather.get(4));
             * day3.setText(weather.get(5)); day4.setText(weather.get(6));
             * 
             * 
             * 
             * day5.setText(weather.get(1)); day6.setText(weather.get(2));
             */

            weatherLink.setText(Html.fromHtml(link));

        }
    }

    String weekdaygen(String s) {
        if (s.equals("Mon")) {
            s.replace("mon", "MONDAY");
        }
        if (s.equals("Tue")) {
            s.replace("Tue", "TUESDAY");
        }
        if (s.equals("Wed")) {
            s.replace("Wed", "WEDNESDAY");
        }
        if (s.equals("Thu")) {
            s.replace("Thu", "THURSDAY");
        }
        if (s.equals("Fri")) {
            s.replace("Fri", "FRIDAY");
        }
        if (s.equals("Sat")) {
            s.replace("Sat", "SATURDAY");
        }
        if (s.equals("Sun")) {
            s.replace("Sun", "SUNDAY");
        }
        return s;

    }

}
ApproachingDarknessFish
  • 14,133
  • 7
  • 40
  • 79
jigar jims
  • 41
  • 1
  • 7

2 Answers2

2
String weekdaygen(String s) {
        if (s.equals("Mon")) {
            s=s.replace("mon", "MONDAY");
        }
        if (s.equals("Tue")) {
           s= s.replace("Tue", "TUESDAY");
        }
        if (s.equals("Wed")) {
            s=s.replace("Wed", "WEDNESDAY");
        }
        if (s.equals("Thu")) {
            s=s.replace("Thu", "THURSDAY");
        }
        if (s.equals("Fri")) {
            s=s.replace("Fri", "FRIDAY");
        }
        if (s.equals("Sat")) {
            s=s.replace("Sat", "SATURDAY");
        }
        if (s.equals("Sun")) {
            s=s.replace("Sun", "SUNDAY");
        }
        return s;

    }

Use this code

Strings in Java are immutable - when you call replace, it doesn't change the contents of the existing string - it returns a new string with the modifications. So you want: s=s.replace("mon", "MONDAY");

Renjith Krishnan
  • 2,446
  • 5
  • 29
  • 53
  • 1
    I think it is overkill to use `replace` here. If it is already known that `s.equals("Tue")` it is enough to write `s = "TUESDAY"` – Henry Jan 01 '14 at 08:17
1

As string is immutable replace function creates a new string after replacement and returns it.

Change your function to folling:

 String weekdaygen(String s) {
        if (s.equals("Mon")) {
            s=s.replace("mon", "MONDAY");
        }
        //same for rest of them

        return s;

    }
vipul mittal
  • 17,343
  • 3
  • 41
  • 44