0

I am trying to get xml from Web Services and I am storing it in string. I need to print this xml in Log cat but it is not coming in proper way. code is :

MainActivity.java

public class MainActivity extends Activity {
    static final String URL = myUrlOfLocalHost;

    // XML node keys
    static final String KEY_ITEM = "item"; // parent node
    static final String KEY_ID = "id";
    static final String KEY_NAME = "name";
    static final String KEY_COST = "cost";
    static final String KEY_DESC = "description";
    private String xml;

    @SuppressLint("NewApi")
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        AsyncTaskRunner runner = new AsyncTaskRunner();
        runner.execute();

    }

    class AsyncTaskRunner extends AsyncTask<String, String, String> {

        @SuppressLint("NewApi")
        @Override
        protected String doInBackground(String... params) {

            publishProgress("Sleeping..."); // Calls onProgressUpdate()
            ArrayList<HashMap<String, String>> menuItems = new ArrayList<HashMap<String, String>>();

            XMLParser parser = new XMLParser();

            xml = parser.getXmlFromUrl(URL); // getting XML
            //Document doc = parser.getDomElement(xml); // getting DOM element



            Log.e("String Data : " , xml);
return null;
}

XMLParser.java

public class XMLParser {


    private StringBuffer result ;

    //Method to get XML from reuested URL
    public String getXmlFromUrl(String url) {

        try {
            // defaultHttpClient
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost(url);

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

            InputStream in = httpEntity.getContent();
            BufferedReader reader = new BufferedReader(new InputStreamReader(in, "UTF-8"),8);
            StringBuffer sb = new StringBuffer();
            String line = null;
            while ((line = reader.readLine()) != null)
            {
                // sb.append(line);
                result =  sb.append(line);;
            }

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        // return XML complete
        return result.toString();
    }

please suggest any solution as output in logcat is coming like below :

<pre class="cake-error"><a href="javascript:void(0);" onclick="document.getElementById('cakeErr5265202999359-trace').style.display = (document.getElementById('cakeErr5265202999359-trace').style.display == 'none' ? '' : 'none');"><b>Notice</b> (8)</a>: Undefined variable: school [<b>APP\View\Schools\xml\get_school_details.ctp</b>, line <b>1</b>]<div id="cakeErr5265202999359-trace" class="cake-stack-trace" style="display: none;"><a href="javascript:void(0);" onclick="document.getElementById('cakeErr5265202999359-code').style.display = (document.getElementById('cakeErr5265202999359-code').style.display == 'none' ? '' : 'none')">Code</a> <a href="javascript:void(0);" onclick="document.getElementById('cakeErr5265202999359-context').style.display = (document.getElementById('cakeErr5265202999359-context').style.display == 'none' ? '' : 'none')">Context</a><pre id="cakeErr5265202999359-code" class="cake-code-dump" style="display: none;"><span class="code-highlight"><code><span style="color: #000000"><span style="color: #0000BB">&lt;?php&nbsp;$xml&nbsp;</span><span style="color: #007700">=&nbsp;</span><span style="color: #0000BB">Xml</span><span style="color: #007700">::</span><span style="color: #0000BB">fromArray</span><span style="color: #007700">(array(</span><span style="color: #0000BB">$school</span><span style="color: #007700">));</span></span></code></span></pre><pre id="cakeErr5265202999359-context" class="cake-context" style="display: none;">$viewFile = &#039;C:\wamp\www\School App\app\View\Schools\xml\get_school_details.ctp&#039;$dataForView = array()</pre><pre class="stack-trace">include - APP\View\Schools\xml\get_school_details.ctp, line 1View::_evaluate() - CORE\Cake\View\View.php, line 931View::_render() - CORE\Cake\View\View.php, line 893View::render() - CORE\Cake\View\View.php, line 462XmlView::render() - CORE\Cake\View\XmlView.php, line 104Controller::render() - CORE\Cake\Controller\Controller.php, line 952Dispatcher::_invoke() - CORE\Cake\Routing\Dispatcher.php, line 194Dispatcher::dispatch() - CORE\Cake\Routing\Dispatcher.php, line 162[main] - APP\webroot\index.php, line 110</pre></div></pre><?xml version="1.0" encoding="UTF-8"?><response>  <code>500</code>  <url>/School%20App/schools/getSchoolDetails.xml?school_id=1</url>  <name>The key of input must be alphanumeric</name></response>

On Server Side method (code) used is :

public function getSchoolDetails() {
    if ($this->RequestHandler->isXml() && $this->request->is('get')) {
        $this->School->unBindModel(array('hasMany' => array('Admin', 'Announcement', 'Batch', 'Class1', 'Event', 'Lunchmenu', 'Student', 'Timetable', 'SpecialInstruction'),                                         'hasAndBelongsToMany' => array('Subject')));
        $fields = array('School.id, School.school_name, School.logo, School.phone');
        $school = $this->School->find('first', array('fields' => $fields, 'conditions' => array('School.id' => $_GET['school_id'])));
        $this->set(array(
            'school' => $school,
        '_serialize' => array('school')
        ));
    }
}

2 Answers2

0

If this is in logcat then it looks like a php problem on the serversize...

....CORE\Cake\Routing\Dispatcher.php....
  • Web Service is working in browser. But, while integrating in android code, it is giving above mentioned data in stacktrace.. please guide me sir if you know any solution... thank you – user2890202 Oct 21 '13 at 13:43
  • I still have a suspicion about a serverside problem: php seems to be outputting the error to the stream as well as the XML. There is a snippet of XML at the bottom of your trace: ` 500 /School%20App/schools/getSchoolDetails.xml?school_id=1 The key of input must be alphanumeric`. I'm assuming this is the bit that needs parsing? –  Oct 21 '13 at 13:49
  • I think so - I would image that an error occuring on the serverside needs to be caught and dumped to `error_log`. It looks as though the error is also being reported as part of the XML response which I imagine is the correct bit ... –  Oct 21 '13 at 13:56
  • Not without seeing the serverside code. The quick (and, may I add, extermely dirty) hack would be to look for the `` tag in the returned string. This would get the Android side working, but it's just a hack and won't address the serverside issue which is more important. –  Oct 21 '13 at 14:01
  • means, this can help only to work on android side, but problem on server side will remain same... any way sir.. please do suggest or add if you can do this.. i will thankful of you.. – user2890202 Oct 21 '13 at 14:04
  • What about this bit: `Undefined variable: school [APP\View\Schools\xml\get_school_details.ctp, line 1]` –  Oct 21 '13 at 14:21
  • I think in the serverside code you have a undefined variable - 'school' - have you posted the file `get_school_details.ctp`? –  Oct 21 '13 at 14:24
  • asXML(); ?> – user2890202 Oct 21 '13 at 14:29
  • I'd double check that $school is being correctly initialised. Look at http://stackoverflow.com/questions/4261133/php-notice-undefined-variable-and-notice-undefined-index for more info –  Oct 21 '13 at 14:29
  • But Sir, If $school is not initialised, then How it work on browser? actually, it is working in browser fine.. so, I am not getting Sir... – user2890202 Oct 21 '13 at 14:40
0

You are using a POST request, while your controller action only works with a GET request:

if ($this->RequestHandler->isXml() && $this->request->is('get')) {

This causes the variables not to be set in case of non XML/POST requests, resulting in the error your are receiving.

Quick fix, allow POST requests too or use a GET request instead. Also I'd suggest to change your controller action so that it triggers proper exceptions in case the request doesn't fit the requirements. Here's an (untested) example how could look like:

public function getSchoolDetails() {
    // NOTE you don't necessarily need this, you could also force the type
    // of response using $this->RequestHandler->renderAs($this, 'xml');
    if (!$this->RequestHandler->isXml()) {
        throw new BadRequestException();
    }

    // NOTE as of CakePHP 2.3 you could use $this->request->onlyAllow('get');
    // instead
    if (!$this->request->is('get')) {
        throw new MethodNotAllowedException();
    }

    // NOTE use the request object instead of $_GET, it will safely return
    // null on non-existent parameters
    $id = $this->request->query('school_id');

    // NOTE skip this in case you want to retrieve empty results instead
    if (!$this->School->exists($id)) {
        throw new NotFoundException();
    }

    // NOTE you should use the containable behavior instead of this
    // unbinding orgy
    $this->School->unbindModel(array(
        'hasMany' => array(
            'Admin', 'Announcement', 'Batch', 'Class1',
            'Event', 'Lunchmenu', 'Student', 'Timetable',
            'SpecialInstruction'
        ),
        'hasAndBelongsToMany' => array(
            'Subject'
        )
    ));

    $fields = array(
        'School.id, School.school_name, School.logo, School.phone'
    );
    $school = $this->School->find('first', array(
        'fields' => $fields,
        'conditions' => array(
            'School.id' => $id
        )
    ));

    $this->set(array(
        'school' => $school,
        '_serialize' => array('school')
    ));
}
ndm
  • 59,784
  • 9
  • 71
  • 110