0

I can't figure out whats wrong with this code , it's supposed to get data from php page that i created. I'm using Eclipse with android SDK.

    package com.myproject.myproject2;


import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.ParseException;
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.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
public class EntList extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.entlist);

        JSONArray jsonArray = null;

        String jsonString = null;

        StringBuilder stringBuilder = null;

        InputStream inStream = null;

        TextView tv = (TextView) findViewById(R.id.listtitle);



        ArrayList<NameValuePair> nVPArray = new ArrayList<NameValuePair>(); //This is empty because you're asking for data
        try{
            //Connect to your script, and save get an object to read the data (inStream)
             HttpClient client = new DefaultHttpClient();
             HttpPost post = new HttpPost("http://sawtaljabal.com/ar/android_connect/test.php"); // Be sure to replace with your actual script
             post.setEntity(new UrlEncodedFormEntity(nVPArray)); 
             HttpResponse postResponse = client.execute(post); 
             HttpEntity responseEntity = postResponse.getEntity();
             inStream = responseEntity.getContent();
             }catch(Exception e){
                 Log.e("Error connecting", e.getLocalizedMessage());
            }

        try{
            //read the stream to a single JSON string
              BufferedReader reader = new BufferedReader(new InputStreamReader(inStream,"iso-8859-1"), 10); // iso-8859-1 is the character converter
               stringBuilder = new StringBuilder();
               stringBuilder.append(reader.readLine() + "\n");

               String line="0";
               while ((line = reader.readLine()) != null) {
                              stringBuilder.append(line + "\n");
                }
                inStream.close();
                jsonString = stringBuilder.toString();
                }catch(Exception e){
                      Log.e("Error creating JSON string", e.getLocalizedMessage());
                }


        try{ 
              //Turn the JSON string into an array of JSON objects
              jsonArray = new JSONArray(jsonString);
              JSONObject jsonObject = null;
              for(int i=0;i< jsonArray.length();i++){
                     jsonObject = jsonArray.getJSONObject(i);
                     //do something with the object, like String data = jsonObject.getString("KEY");
                     String data = jsonObject.getString("n_t");
                     tv.setText(data);
                 }
              }
              catch(JSONException e){
               e.printStackTrace();
              } catch (ParseException e) {
           e.printStackTrace();
         }

    }
}

I don't even know what to try , can u help me please, this is my first Application.

Havelock
  • 6,913
  • 4
  • 34
  • 42
xyzdev
  • 23
  • 7
  • what is response in logcat? – KOTIOS Apr 14 '14 at 04:38
  • May be you will get `Networkonmainthreadexception`.Because you are performaing network operation inside `OnCreate`. You should use Async task. http://stackoverflow.com/questions/6343166/android-os-networkonmainthreadexception – Hariharan Apr 14 '14 at 04:40
  • You want me to show you all the errors in the LogCat ? – xyzdev Apr 14 '14 at 04:42
  • yes you need to past the logcat response – Simmant Apr 14 '14 at 04:47
  • Android apps have a main thread called the UI thread. It is an error to perform long-running and/or blocking operations (like HTTP calls) on the UI thread. Please read this document which explores at least one alternative approach using AsyncTask: https://developer.android.com/guide/components/processes-and-threads.html#Threads – Karakuri Apr 14 '14 at 04:48
  • 1
    its better to do the network tasks inside an AsyncTask. Try putting all the code from onCreate into another AsyncTask class and rather invoke the class inside onCreate – Atish Agrawal Apr 14 '14 at 04:48
  • agree with @AtishAgrawal its better to use asynctask for all network work.. – Simmant Apr 14 '14 at 04:51

3 Answers3

0

If this is your first android app you may want to try cloning this project and learn with code there:

https://github.com/jgilfelt/android-jsonarrayadapter?files=1

Hope it helps.

Pedro Lobito
  • 94,083
  • 31
  • 258
  • 268
0

Are you sure, the String you are getting in the response is a JSON Array. I think it should be a JSON object by which you can get the further JSON Array .

which means

 // try parse the string to a JSON object
    try {
        jObj = new JSONObject(jsonString);          
    } catch (JSONException e) {
    }

and then parse the JSON array from JSON Object.

Check Out this link, it might be helpful.

Also do all networking call in AsynTask or in a different thread.

Jagdeep Singh
  • 1,200
  • 1
  • 16
  • 34
0

To connect php using Android first your have to call a web service (which may be a php page returning json), call to this page should be in AsynTask class. Then you need to parse json in right way.

You can try any good tutorial for this. Try this

Mobi
  • 645
  • 3
  • 6
  • 14
  • Welcome, right way to say thanks in http://stackoverflow.com/, is accept the answer and vote up to the answer. – Mobi Apr 14 '14 at 09:10