Ir al contenido


Foto

Problema coneccion XML y Android


  • Por favor identifícate para responder
6 respuestas en este tema

#1 enecumene

enecumene

    Webmaster

  • Administrador
  • 7.419 mensajes
  • LocationRepública Dominicana

Escrito 13 abril 2012 - 04:58

Pues eso, haciendo pruebas para mostrar una lista desde internet en Android, he usado como ejemplo las categorias del foro para mostrarla en una lista en el mobile, este es el estilo del XML:

<listcategory status="success" count="9"><category>
<id>7</id>
<name>COMUNIDAD</name>
</category><category>
<id>3</id>
<name>PROGRAMACIÓN</name>
</category><category>

<id>13</id>
<name>PROGRAMACIÓN WEB</name>
</category><category>
<id>1</id>
<name>BASES DE DATOS</name>
</category><category>
<id>6</id>

<name>COLABORACIÓN</name>
</category><category>
<id>4</id>
<name>OTROS TEMAS</name>
</category><category>
<id>5</id>
<name>DIVERSIÓN</name>

</category><category>
<id>8</id>
<name>FOROS ESPECIALES</name>
</category><category>
<id>2</id>
<name>ADMINISTRACIÓN</name>
</category></listcategory>


Esta disponible en los siguientes link:

http://www.delphiacc...ion=xmlcategory
http://www.delphiacc.../categorias.php

Pues bien tengo los siguientes archivos en Android:

XMLfunctions.java

[java]package com.pxr.tutorial.xmltest;

import java.io.IOException;
import java.io.StringReader;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;


public class XMLfunctions {

public final static Document XMLfromString(String xml){

Document doc = null;

DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        try {
       
DocumentBuilder db = dbf.newDocumentBuilder();

InputSource is = new InputSource();
        is.setCharacterStream(new StringReader(xml));
        doc = db.parse(is);
       
} catch (ParserConfigurationException e) {
System.out.println("XML parse error: " + e.getMessage());
return null;
} catch (SAXException e) {
System.out.println("Wrong XML file structure: " + e.getMessage());
            return null;
} catch (IOException e) {
System.out.println("I/O exeption: " + e.getMessage());
return null;
}
     
        return doc;
       
}

/** Returns element value
  * @param elem element (it is XML tag)
  * @return Element value otherwise empty String
  */
public final static String getElementValue( Node elem ) {
    Node kid;
    if( elem != null){
        if (elem.hasChildNodes()){
            for( kid = elem.getFirstChild(); kid != null; kid = kid.getNextSibling() ){
                if( kid.getNodeType() == Node.TEXT_NODE  ){
                    return kid.getNodeValue();
                }
            }
        }
    }
    return "";
}

public static String getXML(){
String line = null;

try {

DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("http://www.delphiacc...categorias.php");

HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
line = EntityUtils.toString(httpEntity);

} catch (UnsupportedEncodingException e) {
line = "<listcategory status=\"error\"><msg>Can't connect to server</msg></listcategory>";
} catch (MalformedURLException e) {
line = "<listcategory status=\"error\"><msg>Can't connect to server</msg></listcategory>";
} catch (IOException e) {
line = "<listcategory status=\"error\"><msg>Can't connect to server</msg></listcategory>";
}

return line;

}

public static int numResults(Document doc){
Node results = doc.getDocumentElement();
int res = -1;

try{
res = Integer.valueOf(results.getAttributes().getNamedItem("count").getNodeValue());
}catch(Exception e ){
res = -1;
}

return res;
}

public static String getValue(Element item, String str) {
NodeList n = item.getElementsByTagName(str);
return XMLfunctions.getElementValue(n.item(0));
}
}[/java]

Main.java

[java]package com.pxr.tutorial.xmltest;

import java.util.ArrayList;
import java.util.HashMap;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;

import android.app.ListActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;

public class Main extends ListActivity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.listplaceholder);
       
        ArrayList<HashMap<String, String>> mylist = new ArrayList<HashMap<String, String>>();
     
     
        String xml = XMLfunctions.getXML();
        Document doc = XMLfunctions.XMLfromString(xml);
               
        int numResults = XMLfunctions.numResults(doc);
       
        if((numResults <= 0)){
        Toast.makeText(Main.this, "Geen resultaten gevonden", Toast.LENGTH_LONG).show(); 
        finish();
        }
               
NodeList nodes = doc.getElementsByTagName("category");

for (int i = 0; i < nodes.getLength(); i++) {
HashMap<String, String> map = new HashMap<String, String>();

Element e = (Element)nodes.item(i);
map.put("id", XMLfunctions.getValue(e, "id"));
        map.put("name", XMLfunctions.getValue(e, "name"));
        mylist.add(map);
}
     
        ListAdapter adapter = new SimpleAdapter(this, mylist , R.layout.main,
                        new String[] { "name" },
                        new int[] { R.id.item_title });
       
        setListAdapter(adapter);
       
        final ListView lv = getListView();
        lv.setTextFilterEnabled(true);
        lv.setOnItemClickListener(new OnItemClickListener() {
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {       
        @SuppressWarnings("unchecked")
HashMap<String, String> o = (HashMap<String, String>) lv.getItemAtPosition(position);        
        Toast.makeText(Main.this, "ID '" + o.get("id") + "' was clicked.", Toast.LENGTH_LONG).show();

}
});
    }
}[/java]

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="com.pxr.tutorial.xmltest"
      android:versionCode="1"
      android:versionName="1.0">
    <uses-sdk android:minSdkVersion="14" />

    <application android:icon="@drawable/icon" android:label="@string/app_name">
        <activity android:name=".Main"
                  android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

    </application>

<uses-permission android:name="android.permission.INTERNET" />

</manifest>


main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:padding="7dp"
    >
<TextView 
android:id="@+id/item_title"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:textAppearance="?android:attr/textAppearanceMedium"
    android:padding="2dp"
    android:textSize="20dp" />
    <TextView 
android:id="@+id/item_subtitle"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:padding="2dp"
    android:textSize="13dp" />
</LinearLayout>


listplaceholder.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">

    <ListView
android:id="@id/android:list"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_weight="1"
android:drawSelectorOnTop="false" />

    <TextView
        android:id="@id/android:empty"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="No data"/>

</LinearLayout>


Y no me esta funcionando, a ver algun alma que se apiade de mi, ya llevo dos dias en esto  :

  • 0

#2 cHackAll

cHackAll

    Advanced Member

  • Administrador
  • 599 mensajes

Escrito 14 abril 2012 - 09:00

Fernando,
el ejemplo no tiene errores, qué error te da?

P.D. Ojo que si lo estas probando en tu celular, debe tener una conexión 2G/3G/WiFi activa.
  • 0

#3 enecumene

enecumene

    Webmaster

  • Administrador
  • 7.419 mensajes
  • LocationRepública Dominicana

Escrito 14 abril 2012 - 09:04

Fernando,
el ejemplo no tiene errores, qué error te da?

P.D. Ojo que si lo estas probando en tu celular, debe tener una conexión 2G/3G/WiFi activa.


No lo estoy ejecutando en el celular, sino en el emulador, el caso es que no arranca, me indica que la aplicacion fue detenida desafortunamente.
  • 0

#4 enecumene

enecumene

    Webmaster

  • Administrador
  • 7.419 mensajes
  • LocationRepública Dominicana

Escrito 14 abril 2012 - 09:39

Bueno, hice una prueba usando JSON y pude acceder a la lista de catehorias de este foro, el codigo que use fueron los siguientes:

Main.java

[java]package com.enesoft.smf.json;

import java.util.ArrayList;
import java.util.HashMap;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;

import com.enesoft.smf.json.R;

import android.app.ListActivity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;

public class Main extends ListActivity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.listplaceholder);
       
        ArrayList<HashMap<String, String>> mylist = new ArrayList<HashMap<String, String>>();
     
        //Por razones obvias el archivo php lo he suprimido por seguridad pues :)
        JSONObject json = JSONfunctions.getJSONfromURL("http://delphiaccess....orum/xxxxx.php");
               
        try{
       
        JSONArray  categorias = json.getJSONArray("categorias");
       
        for(int i=0;i<categorias.length();i++){
HashMap<String, String> map = new HashMap<String, String>();
JSONObject e = categorias.getJSONObject(i);

map.put("id",  String.valueOf(i));
        map.put("name", e.getString("name"));        
        mylist.add(map);
}
        }catch(JSONException e)        {
        Log.e("log_tag", "Error parsing data "+e.toString());
        }
       
        ListAdapter adapter = new SimpleAdapter(this, mylist , R.layout.main,
                        new String[] { "id", "name" },
                        new int[] { R.id.item_title, R.id.item_subtitle });
       
        setListAdapter(adapter);
       
        final ListView lv = getListView();
        lv.setTextFilterEnabled(true);
        lv.setOnItemClickListener(new OnItemClickListener() {
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {       
        @SuppressWarnings("unchecked")
HashMap<String, String> o = (HashMap<String, String>) lv.getItemAtPosition(position);        
        Toast.makeText(Main.this, "ID '" + o.get("id") + "' was clicked.", Toast.LENGTH_SHORT).show();

}
});
    }
}[/java]

JSONfunctions.java

[java]package com.enesoft.smf.json;



import java.io.BufferedReader;

import java.io.InputStream;

import java.io.InputStreamReader;

import java.util.HashMap;



import org.apache.http.HttpEntity;

import org.apache.http.HttpResponse;

import org.apache.http.client.HttpClient;

import org.apache.http.client.entity.UrlEncodedFormEntity;

import org.apache.http.client.methods.HttpPost;

import org.apache.http.impl.client.DefaultHttpClient;

import org.json.JSONArray;

import org.json.JSONException;

import org.json.JSONObject;



import android.util.Log;



public class JSONfunctions {



public static JSONObject getJSONfromURL(String url){

InputStream is = null;

String result = "";

JSONObject jArray = null;



//http post

    try{

            HttpClient httpclient = new DefaultHttpClient();

            HttpPost httppost = new HttpPost(url);

            HttpResponse response = httpclient.execute(httppost);

            HttpEntity entity = response.getEntity();

            is = entity.getContent();



    }catch(Exception e){

            Log.e("log_tag", "Error in http connection "+e.toString());

    }

   

  //convierte la respuesta en string

    try{

            BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);

            StringBuilder sb = new StringBuilder();

            String line = null;

            while ((line = reader.readLine()) != null) {

                    sb.append(line + "\n");

            }

            is.close();

            result=sb.toString();

    }catch(Exception e){

            Log.e("log_tag", "Error converting result "+e.toString());

    }

   

    try{

   

            jArray = new JSONObject(result);           

    }catch(JSONException e){

            Log.e("log_tag", "Error parsing data "+e.toString());

    }

   

    return jArray;

}

}
[/java]

Lo demas viene siendo lo mismo, ahora, ya esto es otro tema, pero en JSON todos los string con acentos me aparecen nulos, a que se debera?

Archivos adjuntos


  • 0

#5 enecumene

enecumene

    Webmaster

  • Administrador
  • 7.419 mensajes
  • LocationRepública Dominicana

Escrito 14 abril 2012 - 02:03

Doy el tema como resuelto, la solucion a los acentos y caracteres especiales era sencillo, solo habia que poner el charset como utf8 en todos los documentos que lo requiera.

Saludos.

Archivos adjuntos


  • 0

#6 egostar

egostar

    missing my father, I love my mother.

  • Administrador
  • 14.448 mensajes
  • LocationMéxico

Escrito 14 abril 2012 - 02:39

Caramba!!!, que bien master (y)

Ahora solo hay que tener en cuenta la parte de privilegios ;)

Saludos
  • 0

#7 enecumene

enecumene

    Webmaster

  • Administrador
  • 7.419 mensajes
  • LocationRepública Dominicana

Escrito 14 abril 2012 - 02:53

Uff y eso que falta bro jeje, este sera mi primera aplicacion, asi que ando cuchicheando java y android :)

Saludos.
  • 0




IP.Board spam blocked by CleanTalk.