esmail jamshidiasl esmail jamshidiasl - 3 months ago 13
Java Question

URLConnection receive wrong text from php server

I have an app that has 4 activities.in first activity I want to request some text from my website (PHP file). For first time that I press button to get data it works fine but in next times that I press button, it returns a CORRECT text but concatenates it with previous text.see the example:

First press: returns: "abc"
Second press: returns: "abcabc" (must be return abc)
Third press: returns: "abcabcabc" (must be return abc)
.

1-I clear text view each time.
2-I close connection each time.
3-I close bufferedreader each time.
4-I close.

ACTIVITY1:

try{
URL u = new URL(uu);
HttpURLConnection con = (HttpURLConnection) u.openConnection(Proxy.NO_PROXY);
con.setDoOutput(true);
con.setUseCaches(false);
PrintStream pr = new PrintStream(con.getOutputStream());
pr.print("code=3&arg1=" + str);
BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream(),"UTF-8"));
String l;
while ((l=br.readLine())!=null){
z = z + "\n" + l;
}
br.close();
pr.close();
con.disconnect();
runOnUiThread(new Runnable() {
@Override
public void run() {
TextView tx = (TextView) findViewById(R.id.textView2);
tx.setMovementMethod(new ScrollingMovementMethod());
tx.setText("");
tx.setText(z);
}
});
}
catch (final Exception ex){
}

Answer

I don't see where you declared the z String, but you are obviously appending to it.

You should either clear it, or use a new String for each request.

And use a StringBuilder. You memory usage will be much lower.

Comments