XML Parsing With AsyncTask - java

I want to take currency from specific Url but AsyncTask is giving me runtime error: I couldn't find what I have to do.
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
WebServisXML xmlRead = new WebServisXML(this);
xmlRead.execute("http://www.tcmb.gov.tr/kurlar/today.xml");
}
public class WebServisXML extends AsyncTask<String, String, List<String>> {
private Context context;
private ListView listView;
private ProgressDialog dialogBar;
List<String> dovizListe = new ArrayList<String>();
HttpURLConnection baglanti = null;
public WebServisXML(Context context) {
this.context = context;
listView = (ListView) ((AppCompatActivity) context).findViewById(R.id.listView);}
protected void onPreExecute() {
super.onPreExecute();
dialogBar = ProgressDialog.show(context, "Lütfen bekleyiniz...", "İşlem yükleniyor...", true);
}
#Override
protected List<String> doInBackground(String... params) {
try {
URL adressOfLink = new URL(params[0]);
baglanti = (HttpURLConnection) adressOfLink.openConnection();
int responceCode = baglanti.getResponseCode();
if (responceCode == HttpURLConnection.HTTP_OK) {
BufferedInputStream stream = new BufferedInputStream(baglanti.getInputStream());
publishProgress("Döviz kurları okunuyor...");
DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
Document document = documentBuilder.parse(stream);
NodeList dovizNodeList = document.getElementsByTagName("Currency");
for (int i = 0; i < dovizNodeList.getLength(); i++) {
Element element = (Element) dovizNodeList.item(i);
NodeList nodeBirim = element.getElementsByTagName("Unit");
NodeList nodeIsim = element.getElementsByTagName("Isim");
NodeList nodeAlis = element.getElementsByTagName("ForexBuying");
NodeList nodeSatis = element.getElementsByTagName("ForexSelling");
String birim = nodeBirim.item(0).getFirstChild().getNodeValue();
String isim = nodeIsim.item(0).getFirstChild().getNodeValue();
String alis = nodeAlis.item(0).getFirstChild().getNodeValue();
String satis = nodeSatis.item(0).getFirstChild().getNodeValue();
dovizListe.add(birim + " " + isim + " Alış:" + alis + " Satış:" + satis);
}
publishProgress("Liste güncelleniyor...");
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ParserConfigurationException e) {
e.printStackTrace();
} catch (SAXException e) {
e.printStackTrace();
}finally {
if(baglanti!=null)
baglanti.disconnect();
}
return dovizListe;
}
#Override
protected void onProgressUpdate(String... values) {
super.onProgressUpdate(values);
dialogBar.setMessage(values[0]);
}
#Override
protected void onPostExecute(List<String> strings) {
super.onPostExecute(strings);
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(context,android.R.layout.simple_expandable_list_item_1,strings);
listView.setAdapter(arrayAdapter);
dialogBar.cancel();
}
}}
This is my error screen:

One of the nodes first child's is null. (Node has no children)
Without proper line numbers I cannot tell you which one. (Line 98 of MainActivity.java)
I suggest adding a check:
String birim = nodeBirim.item(0).getLength() > 0 ? nodeBirim.item(0).getFirstChild().getNodeValue() : "";
String isim = nodeIsim.item(0).getLength() > 0 ? nodeIsim.item(0).getFirstChild().getNodeValue() : "";
String alis = nodeAlis.item(0).getLength() > 0 ? nodeAlis.item(0).getFirstChild().getNodeValue() : "";
String satis = nodeSatis.item(0).getLength() > 0 ? nodeSatis.item(0).getFirstChild().getNodeValue() : "";

Related

How to update listview in for loop in asynk task

I'm reading some text from HttpUrlConnection request and putting it in ArrayList every iteration of a loop.
All works perfect, except items in ListView don't updating in UI after every iteration of a loop (only at the end).
I'm tried next 4 methods: arrayAdapter.notifyDataSetChanged(), listView.invalidateViews(), runOnUiThread(), onPostExecute() nothing helps.
Here is my code:
public class MainActivity extends AppCompatActivity {
ListView listView;
ArrayList<String> news = new ArrayList<>();
ArrayList<String> headers = new ArrayList<>();
ArrayAdapter<String> arrayAdapter;
static JSONArray array;
NewsUnpacker unpacker;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = findViewById(R.id.listView);
String link = "https://hacker-news.firebaseio.com/v0/topstories.json?print=pretty";
NewsLoader newsLoader = new NewsLoader();
array = null;
try {
array = newsLoader.execute(link).get();
} catch (Exception e) {
e.printStackTrace();
}
arrayAdapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, headers);
listView.setAdapter(arrayAdapter);
final int size = 15;
for (int i = 0; i < size; i++) {
try {
unpacker = new NewsUnpacker(this);
String info = unpacker.execute("https://hacker-news.firebaseio.com/v0/item/" + array.get(i) + ".json?print=pretty").get();
if (info == null) {
unpacker.cancel(true);
return;
}
news.add(info);
headers.add(info.split(System.lineSeparator())[0]);
arrayAdapter.notifyDataSetChanged();
listView.invalidateViews();
unpacker.cancel(true);
} catch (Exception e) {
e.printStackTrace();
}
}
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
}
});
}
static class NewsUnpacker extends AsyncTask<String, Void, String> {
MainActivity activity;
NewsUnpacker(MainActivity activity) {
this.activity = activity;
}
#Override
protected String doInBackground(String... urls) {
String info = null;
try {
URL url = new URL(urls[0]);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
InputStream is = connection.getInputStream();
InputStreamReader reader = new InputStreamReader(is);
StringBuilder builder = new StringBuilder();
int data;
while ((data = reader.read()) != -1)
builder.append((char) data);
String title, urlParam;
JSONObject object = new JSONObject(builder.toString());
title = object.get("title").toString();
urlParam = object.get("url").toString();
info = title + System.lineSeparator() + urlParam;
System.out.println(info);
} catch (Exception e) {
e.printStackTrace();
}
return info;
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
}
}
static class NewsLoader extends AsyncTask<String, Void, JSONArray> {
JSONArray array = null;
#Override
protected JSONArray doInBackground(String... urls) {
try {
URL url = new URL(urls[0]);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
InputStream is = connection.getInputStream();
InputStreamReader reader = new InputStreamReader(is);
StringBuilder builder = new StringBuilder();
int data;
while ((data = reader.read()) != -1)
builder.append((char) data);
array = new JSONArray(builder.toString());
} catch (Exception e) {
e.printStackTrace();
}
return array;
}
}
}

JSONParser: IOException: Unable to resolve host "my host address": No address associated with hostname

I am trying to get data from a JSON file that was written in a PHP file which was stored in my online hosting server(00webhost.com). When I run my program it says unknown host. However, the address will give JSON formatted file.
I have all the permissions along with the internet permission in my AndroidManifest.xml file.
Activity Class :
public class Recmain extends AppCompatActivity {
private String TAG = MainActivity.class.getSimpleName();
private ListView lv;
ArrayList<HashMap<String, String>> contactList;
TextView uid;
TextView name1;
TextView email1;
Button Btngetdata;
//URL to get JSON Array
private static String url = "http://tongue-tied-
papers.000webhostapp.com/data_fetch.php";
//JSON Node Names
private static final String TAG_USER = "user";
private static final String TAG_ID = "id";
private static final String TAG_NAME = "name";
private static final String TAG_EMAIL = "email";
JSONArray user = null;
private List<movie> movieList = new ArrayList<>();
private RecyclerView recyclerView;
private moviesadapter mAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.rmain);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
Intent intent=getIntent();
String m=intent.getStringExtra("data");
recyclerView = (RecyclerView) findViewById(R.id.recycler_view);
mAdapter = new moviesadapter(movieList);
RecyclerView.LayoutManager mLayoutManager = new
LinearLayoutManager(getApplicationContext());
recyclerView.setLayoutManager(mLayoutManager);
recyclerView.setItemAnimator(new DefaultItemAnimator());
recyclerView.setAdapter(mAdapter);
prepareMovieData();
}
private void prepareMovieData(){
movie movie = new movie("Mad Max: Fury Road", "Action & Adventure",
"2015");
movieList.add(movie);
mAdapter.notifyDataSetChanged();
new GetContacts().execute();
}
private class GetContacts extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
Toast.makeText(recmain.this,url,Toast.LENGTH_LONG).show();
}
#Override
protected Void doInBackground(Void... arg0) {
JSONParser sh = new JSONParser();
// Making a request to url and getting response
String url = "https://tongue-tied-
papers.000webhostapp.com/data_fetch.php";
String jsonStr = sh.makeServiceCall(url);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
JSONArray contacts = jsonObj.getJSONArray("id");
// looping through All Contacts
for (int i = 0; i < contacts.length(); i++) {
JSONObject c = contacts.getJSONObject(i);
String id = c.getString("id");
Toast.makeText(getApplicationContext(), id ,
Toast.LENGTH_LONG).show();
// tmp hash map for single contact
HashMap<String, String> contact = new HashMap<>();
// adding each child node to HashMap key => value
contact.put("id", id);
// adding contact to contact list
contactList.add(contact);
}
} catch (final JSONException e) {
Log.e(TAG, "Json parsing error: " + e.getMessage());
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"Json parsing error: " + e.getMessage(),
Toast.LENGTH_LONG).show();
}
});
}
} else {
Log.e(TAG, "Couldn't get json from server.");
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"Couldn't get json from server. Check LogCat
for possible errors!",
Toast.LENGTH_LONG).show();
}
});
}
return null;
}
#Override
protected void onPostExecute(Void result) {
}
}
}
Adapter class:
public class JSONParser {
private static final String TAG = JSONParser.class.getSimpleName();
public JSONParser() {
}
public String makeServiceCall(String reqUrl) {
String response = null;
try {
URL url = new URL(reqUrl);
HttpURLConnection conn = (HttpURLConnection)
url.openConnection();
conn.setRequestMethod("GET");
// read the response
InputStream in = new BufferedInputStream(conn.getInputStream());
response = convertStreamToString(in);
} catch (MalformedURLException e) {
Log.e(TAG, "MalformedURLException: " + e.getMessage());
} catch (ProtocolException e) {
Log.e(TAG, "ProtocolException: " + e.getMessage());
} catch (IOException e) {
Log.e(TAG, "IOException: " + e.getMessage());
} catch (Exception e) {
Log.e(TAG, "Exception: " + e.getMessage());
}
return response;
}
private String convertStreamToString(InputStream is) {
BufferedReader reader = new BufferedReader(new
InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line;
try {
while ((line = reader.readLine()) != null) {
sb.append(line).append('\n');
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}
}
It says, unknown host.
Looks like the URL is not formatted correctly. I think there is a space between the two parts of the URL.
private static String url = "http://tongue-tied-papers.000webhostapp.com/data_fetch.php"
Please try with the URL above without any space between the tied- and papers. You have two separate URL declaration, one at the beginning of the class and the other is in the doInBackground method. Please try changing both.

Unable to fetch images in Grid view

Main Activity:
public class MainActivity extends AppCompatActivity {
// ImageView iv;
public static StringBuffer finalparsedData;
public static GridView myGrid;
private static final String TAG = MainActivity.class.getSimpleName();
ArrayList<String> values = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myGrid=(GridView)findViewById(R.id.grid_view);
Button btnHit = (Button) findViewById(R.id.btnHit);
btnHit.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
new JSONTask().execute("https://api.flickr.com/services/rest/?method=flickr.photos.getRecent&" +
"api_key=46e71c8d2b35ba8c9c333a462ec8aea7&per_page=3&format=json&nojsoncallback=10");
}
});
values = new ArrayList<>();
}
/*static boolean isAirplaneModeOn(Context context) {
ContentResolver contentResolver = context.getContentResolver();
return Settings.System.getInt(contentResolver, AIRPLANE_MODE_ON, 0) != 0;
}*/
public class JSONTask extends AsyncTask<String, Void, String> {
String photoid;
int farm;
String server;
String secret;
#Override
protected String doInBackground(String... params) {
HttpURLConnection connection = null;
BufferedReader reader = null;
StringBuffer buffer = null;
JSONArray parentarray = null;
try {
URL url = new URL(params[0]);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
InputStream stream = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(stream));
buffer = new StringBuffer();
String line = "";
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
String finalJson = buffer.toString();
JSONObject parentObject = new JSONObject(finalJson);
//JSONObject initialObject = new JSONObject("photos");
JSONObject initialObject = parentObject.getJSONObject("photos");
parentarray = initialObject.getJSONArray("photo");
finalparsedData = new StringBuffer();
for (int i = 0; i < parentarray.length(); i++) {
JSONObject finalObject = parentarray.getJSONObject(i);
photoid = finalObject.optString("id");
farm = finalObject.optInt("farm");
server = finalObject.optString("server");
secret = finalObject.optString("secret");
finalparsedData.append("https://farm" + farm + ".staticflickr.com/" + server + "/" + photoid+ "_" + secret + ".jpg" +"\n\n");
values.add(String.valueOf((finalparsedData)));
}
return "done";
} catch (MalformedURLException e) {
e.printStackTrace();
return "error";
} catch (IOException e) {
e.printStackTrace();
return "error";
} catch (JSONException e) {
e.printStackTrace();
return "error";
} finally {
if (connection != null) {
connection.disconnect();
}
try {
if (reader != null) {
reader.close();
return "done";
}
} catch (IOException e) {
e.printStackTrace();
return "error";
}
}
}
#Override
protected void onPostExecute(String result) {
switch (result){
case "done":
MyImageAdapter adapter = new MyImageAdapter(MainActivity.this, values);
myGrid.setAdapter((ListAdapter) adapter);
break;
}
}
}
}
MyAdapterClass:
public class MyImageAdapter extends BaseAdapter {
ArrayList<String> values;
Context mContext;
public MyImageAdapter(Context mContext, ArrayList<String> values) {
this.values = values;
this.mContext = mContext;
}
#Override
public int getCount() {
return values.size();
}
#Override
public Object getItem(int position) {
return position;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
ViewHolder holder;
;
if (row == null){
LayoutInflater inflater = (LayoutInflater)mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = inflater.inflate(R.layout.grid,parent,false);
holder = new ViewHolder();
holder.imageView = (ImageView) row.findViewById(R.id.image_View);
row.setTag(holder);
} else {
holder = (ViewHolder) row.getTag();
}
String image = values.get(position);
Picasso.with(mContext).load(image).into(holder.imageView);
return row;
}
public class ViewHolder {
ImageView imageView;
}
}
I got a problem during images loading in gridview, out of 10 images only 1 image is shown and rest of them showing "this images is no longer available"
Hahaha, silly mistake. Just replace your for loop inside JSONTask with this,
.
.
.
for (int i = 0; i < parentarray.length(); i++) {
JSONObject finalObject = parentarray.getJSONObject(i);
photoid = finalObject.optString("id");
farm = finalObject.optInt("farm");
server = finalObject.optString("server");
secret = finalObject.optString("secret");
String fullPath = "https://farm" + farm + ".staticflickr.com/" + server + "/" + photoid+ "_" + secret + ".jpg";
values.add(fullPath);
}
.
.
.
No need to use StringBuffer. You should use normal String variable. :)

Looper in AsyncTask

I'm learning about HTML and parsing data with XML DOM. For this, I've created an App that reads the Wheater from Yahoo's wheater API.
When executing the app, shows an error in the logcat that says: java.lang.RuntimeException: Can't create handler inside thread that has not caller Looper.prepare().
I don't know what this means, or if the code is right.
This is the link to the XML file of Yahoo's wheater API:
http://weather.yahooapis.com/forecastrss?w=766273&u=c
And this is my code:
public class WeatherActivity extends Activity {
private static final String WEATHER_URL = "http://weather.yahooapis.com/forecastjson?w=";
private static final String MADRID_CODE = "766273";
private static final String LOCATION_NAME = "location";
private static final String CITY_NAME = "city";
private static final String CONDITION_NAME = "condition";
private static final String TEMPERATURE_NAME = "temperature";
private static final String FORECAST_NAME = "forecast";
private static final String DAY_NAME = "day";
private static final String HIGH_TEMPERATURE_NAME = "high_temperature";
private static final String LOW_TEMPERATURE_NAME = "low_temperature";
private static final String TODAY = "Today";
private static final String TOMORROW = "Tomorrow";
private Button mButton;
private TextView mCity;
private TextView mToday;
private TextView mTomorrow;
private class WeatherInfo {
String city;
int temperatureNow;
int lowTemperature;
int highTemperature;
int lowTemperatureTomorrow;
int highTemperatureTomorrow;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mCity = (TextView) findViewById(R.id.city);
mToday = (TextView) findViewById(R.id.today);
mTomorrow = (TextView) findViewById(R.id.tomorrow);
mButton = (Button) findViewById(R.id.button);
mButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
launch();
}
});
}
private void launch(){
try {
new WeatherAsyncTask().execute(MADRID_CODE);
} catch (IllegalArgumentException e) {
e.printStackTrace();
Toast.makeText(WeatherActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show();
}
}
private class WeatherAsyncTask extends AsyncTask<String, Void, WeatherInfo>{
#Override
protected WeatherInfo doInBackground(String... params) {
String code = params[0];
if (TextUtils.isEmpty(code))
throw new IllegalArgumentException("Code cannot be empty");
URL url = null;
HttpURLConnection connection = null;
try {
url = new URL(WEATHER_URL + code);
connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
InputStream is = connection.getInputStream();
WeatherInfo info = readWeatherInfo(is);
return info;
} catch (IOException e) {
e.printStackTrace();
Toast.makeText(WeatherActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show();
} finally {
if (connection != null)
connection.disconnect();
}
return null;
}
#Override
protected void onPostExecute(WeatherInfo result) {
super.onPostExecute(result);
showResult(result);
}
private WeatherInfo readWeatherInfo(InputStream is){
if (is == null)
return null;
WeatherInfo info = new WeatherInfo();
try {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document dom = builder.parse(is);
Element root = dom.getDocumentElement();
NodeList items = root.getElementsByTagName("item");
for (int i=0; i<items.getLength(); i++) {
Node item = items.item(i);
NodeList datos = item.getChildNodes();
for (int j=0; j<datos.getLength(); j++) {
Node dato = datos.item(j);
String etiqueta = dato.getNodeName();
if (etiqueta.equals(LOCATION_NAME)) {
String texto = obtenerTexto(dato);
if (texto.equals(TEMPERATURE_NAME)) {
info.city = texto;
}
}
else if (etiqueta.equals(CONDITION_NAME)) {
String texto = obtenerTexto(dato);
if (texto.equals(CITY_NAME)) {
info.temperatureNow = Integer.parseInt(texto);
}
}
else if (etiqueta.equals(FORECAST_NAME)) {
String texto = obtenerTexto(dato);
String day = null;
int high = -111;
int low = -111;
if (texto.equals(DAY_NAME)){
day = texto;
} else if (texto.equals(HIGH_TEMPERATURE_NAME)){
high = Integer.parseInt(texto);
} else if (texto.equals(LOW_TEMPERATURE_NAME)){
low = Integer.parseInt(texto);
}
if (day.equals(TODAY)){
info.highTemperature = high;
info.lowTemperature = low;
} else if (day.equals(TOMORROW)){
info.highTemperatureTomorrow = high;
info.lowTemperatureTomorrow = low;
}
}
}
}
}
catch (Exception ex)
{
throw new RuntimeException(ex);
}
return info;
}
private String obtenerTexto(Node dato) {
StringBuilder texto = new StringBuilder();
NodeList fragmentos = dato.getChildNodes();
for (int k=0;k<fragmentos.getLength();k++) {
texto.append(fragmentos.item(k).getNodeValue());
}
return texto.toString();
}
}
private void showResult(WeatherInfo info){
mCity.setText("Temperature in " + info.city);
mToday.setText("Today: " + info.temperatureNow + " F (min: " + info.lowTemperature + " F / max: " + info.highTemperature + " F).");
mTomorrow.setText("Tomorrow: min: " + info.lowTemperatureTomorrow + " F / max: " + info.highTemperatureTomorrow + " F.");
}
}
You cannot show a Toast in the doInBackground of an ASyncTask
Try wrapping it in a runOnUIThread() like:
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(WeatherActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show();
}
});
You can use preimplemented method onProgressUpdate() of AsyncTask which allows you to post Toasts. To do this, you have to change your AsyncTask declaration into
private class WeatherAsyncTask extends AsyncTask<String, String, WeatherInfo>
and add method
#Override
protected void onProgressUpdate(String... values)
{
super.onProgressUpdate(values);
Toast.makeText(WeatherActivity.this, values[0], Toast.LENGTH_SHORT).show();
}
and inside your AsyncTask you can catch your exception and do this
catch (IOException e)
{
e.printStackTrace();
publishProgress(e.getMessage());
}
All this is available by default in AsyncTask without the need of creating new runnables.

Android Get some data from XML to Layout

After much research, I can't manage to layout some XML data in my android app.
There is my MainActivity.java :
public class MainActivity extends Activity {
TextView textview1;
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
GetXmlTask task = new GetXmlTask(textview1 , "http://www.3pi.tf/test.xml"); // get the XML
Log.i("TAG", "test1");
task.execute(); // execute the task
Log.i("TAG","test2");
textview1 = (TextView) findViewById(R.id.textview1);
Log.i("TAG", "test4");
}
}
And there is my GetXmlTask.java :
public class GetXmlTask extends AsyncTask<Void, Void, String>{
public WeakReference<TextView> textViewReference;
public String url;
public GetXmlTask(TextView textview, String url) {
this.textViewReference = new WeakReference<TextView>(textview);
this.url = url;
}
public String THEXML = null;
public String doInBackground(Void... sUrl) {
try
{
HttpClient httpclient = new DefaultHttpClient();
httpclient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
HttpGet request = new HttpGet("http://3pi.tf/test.xml");
Log.i("TAG2",""+request);
HttpResponse response = httpclient.execute(request);
Log.i("TAG2",""+response);
HttpEntity resEntity = response.getEntity();
Log.i("TAG2",""+resEntity);
THEXML = EntityUtils.toString(resEntity);
Log.i("DONNEES XML",""+THEXML);
}
catch(Exception e){ e.printStackTrace(); }
return THEXML;
}
public Document getDomElement(String task) {
Log.i("TAG2","test01");
Document doc = null;
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
try{
DocumentBuilder db = dbf.newDocumentBuilder();
InputSource is = new InputSource();
is.setCharacterStream(new StringReader(task));
doc = db.parse(is);
}
catch (ParserConfigurationException e) {
Log.e("Error: ", e.getMessage());
return null;
}
catch (SAXException e) {
Log.e("Error: ", e.getMessage());
return null;
}
catch (IOException e) {
Log.e("Error: ", e.getMessage());
return null;
}
return doc;
}
public final String getElementValue( Node elem ) {
Node child;
if( elem != null){
if (elem.hasChildNodes()){
for( child = elem.getFirstChild(); child != null; child = child.getNextSibling() ){
if( child.getNodeType() == Node.TEXT_NODE ){
return child.getNodeValue();
}
}
}
}
return "";
}
//Retrieve each element child element value by using node name of element.
public String getValue(Element item, String str) {
NodeList n = item.getElementsByTagName(str);
return this.getElementValue(n.item(0));
}
}
As you can see, I put some logcat in to see how it passes through.
I can see all my XML in the logcat with the variable "THEXML" but I can't layout to my mobile app... I did all the method in an AsyncTask because that was highly recommended..
Please help me
Thank you
Use a interface as a callback to the activity
GetXmlTask task = new GetXmlTask(ActivityName.this, "http://www.3pi.tf/test.xml");
Then in GetXmlTask
ReturnData mCallback;
public GetXmlTask(Context context, String url) { // Constructor in asynctask
this.url = url;
mCallback = (ReturnData)context;
}
Then
public interface ReturnData
{
public void Returnxml(String xml);
}
In doInbackground you return THEXML
return THEXML;
In onPostExecute
#Override
public void onPostExecute(String result)
{
super.onPostExecute(result);
if(mCallback!=null)
{
mCallback.Returnxml(result);
}
}
In MainActivity implement the interface
public class MainActivity extends Activity implements ReturnData {
Then
public void Retunxml(String data)
{
textView1.setText(data);
}
You should overwrite the onPostExecute method of AsynckTask and handle there the operation over your downloaded file if it is different from null. In you case something like this:
protected void onPostExecute(Void result) {
if(THEXML !=null)
{
//do something
}
}

Categories