Reputation: 448
I am new to Android and don't know much. I need help to change this code - I want to download some text from a website.
If I use the code: new DownloadTextTask().execute("http://www.test.com/file.xml");
It doesn't show the downloaded text in TextView
, but if I reopen the app I can see the text. I think its because it's asynchronous, and it has delay to download text.
How can I fix this, or just use this code instead:
(I mean using DownloadText()
function directly! It didnt work when I tried!)
TextView txt = (TextView)findViewById(R.id.textTest);
txt.setText(DownloadText("http://www.test.com/"));
All the code:
public class MainActivity extends AppCompatActivity {
public InputStream OpenHttpConnection(String urlString) throws IOException{
InputStream in = null;
int response = -1;
URL url = new URL(urlString);
URLConnection conn = url.openConnection();
if (!(conn instanceof HttpURLConnection))
throw new IOException("Not an HTTP connection");
try{
HttpURLConnection httpConn = (HttpURLConnection) conn;
httpConn.setAllowUserInteraction(false);
httpConn.setInstanceFollowRedirects(true);
httpConn.setRequestMethod("GET");
httpConn.connect();
response = httpConn.getResponseCode();
if (response == HttpURLConnection.HTTP_OK) {
in = httpConn.getInputStream();
}
}
catch (Exception ex)
{
Log.d("MainActivity", ex.getLocalizedMessage());
throw new IOException("Error connecting");
}
return in;
}
public String DownloadText(String URL)
{
int BUFFER_SIZE = 2000;
InputStream in = null;
try {
in = OpenHttpConnection(URL);
} catch (IOException e) {
Log.d("MainActivity", e.getLocalizedMessage());
return "";
}
InputStreamReader isr = new InputStreamReader(in);
int charRead;
String str = "";
char[] inputBuffer = new char[BUFFER_SIZE];
try {
while ((charRead = isr.read(inputBuffer))>0) {
//---convert the chars to a String---
String readString =
String.copyValueOf(inputBuffer, 0, charRead);
str += readString;
inputBuffer = new char[BUFFER_SIZE];
}
in.close();
} catch (IOException e) {
Log.d("MainActivity", e.getLocalizedMessage());
return "";
}
return str;
}
private class DownloadTextTask extends AsyncTask<String, Void, String> {
protected String doInBackground(String... urls) {
return DownloadText(urls[0]);
}
@Override
protected void onPostExecute(String result) {
Toast.makeText(getBaseContext(), result, Toast.LENGTH_LONG).show();
}
}
public static class xmlClass
{
public static String xml ="";
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//new DownloadTextTask().execute("http://www.test.com/file.xml");
TextView txt = (TextView)findViewById(R.id.textTest);
txt.setText(DownloadText("http://www.test.com/file.xml"));
}
}
Upvotes: 0
Views: 914
Reputation: 1796
It will be better to use and XML Parser to retrieve data from your XML file to your textView , look at this example
public class XMLParser {
public static List<Object> parseFeed(String content) {
try {
boolean inDataItemTag = false;
String currentTagName = "";
Object xyz = null;
List<Object> xyzList = new ArrayList<>();
XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
XmlPullParser parser = factory.newPullParser();
parser.setInput(new StringReader(content));
int eventType = parser.getEventType();
while (eventType != XmlPullParser.END_DOCUMENT) {
switch (eventType) {
case XmlPullParser.START_TAG:
currentTagName = parser.getName();
if (currentTagName.equals("product")) {
inDataItemTag = true;
xyz = new Object();
xyzList.add(xyz);
}
break;
case XmlPullParser.END_TAG:
if (parser.getName().equals("product")) {
inDataItemTag = false;
}
currentTagName = "";
break;
case XmlPullParser.TEXT:
if (inDataItemTag && xyz != null) {
switch (currentTagName) {
case "productId":
xyz.setProductId(Integer.parseInt(parser.getText()));
break;
case "name":
xyz.setName(parser.getText());
break;
case "instructions":
xyz.setInstructions(parser.getText());
break;
case "category":
xyz.setCategory(parser.getText());
break;
case "price" :
xyz.setPrice(Double.parseDouble(parser.getText()));
break;
case "photo" :
xyz.setPhoto(parser.getText());
default:
break;
}
}
break;
}
eventType = parser.next();
}
return xyzList;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
}
this is an example of a XML parser , from a XML File that have ProductId,Name,Instructions,Price and Photo.
Upvotes: 0
Reputation: 1032
Make a callback from AsyncTask as follows
private class DownloadTextTask extends AsyncTask {
MainActivity instance=null;
public DownloadTextTask(MainActivity instance){
this.instance=instance;
}
protected String doInBackground(String... urls) {
return DownloadText(urls[0]);
}
@Override
protected void onPostExecute(String result) {
Toast.makeText(getBaseContext(), result, Toast.LENGTH_LONG).show();
if(instance!=null){
instance.callback(result);
}
}
}
and add a method named callback in MainActivity
public class MainActivity extends AppCompatActivity {
.... your code......
public void callback(String result){
txt.setText(Parse your response);
}
}
You need to make a call as follows from mainactivity
new DownloadTextTask(this).execute("http://www.test.com/file.xml");
Upvotes: 3
Reputation: 809
set text here in your code
if (response == HttpURLConnection.HTTP_OK) {
in = httpConn.getInputStream();
txt.setText(Parse your response);
}
Upvotes: 0