从MySQL获取数据并使用JSON在ListView中显示它

时间:2014-03-09 23:59:08

标签: php android mysql json listview

我正在尝试从MySQL外部数据库中获取数据并将其显示在ListView中。要做..我使用JSONObject和JSONArray ..不能让它给我看任何东西..你能告诉我我做错了吗?

php文件:

 <?php

$host = ""; // host of MySQL server
$user = ""; // MySQL user
$pwd = ""; // MySQL user's password
$db = ""; // database name


$con = mysql_connect($host, $user, $pwd, $db);

// query the application data
$sql = "SELECT nombre FROM usuarios ORDER BY id";
$result = mysql_query($con, $sql);

// an array to save the application data
$rows = array();

// iterate to query result and add every rows into array
while($row = mysql_fetch_array($result)) {
    $rows[] = $row; 
}

// close the database connection
mysql_close($con);

// echo the application data in json format
echo json_encode($rows);

?>

Asyntask java:

public class FetchDataTask extends AsyncTask<String, Void, String>{
    private final FetchDataListener listener;
    private String msg;

public FetchDataTask(FetchDataListener listener) {
    this.listener = listener;
}

@Override
protected String doInBackground(String... params) {
    if(params == null) return null;

    // get url from params
    String url = params[0];

    try {
        // create http connection
        HttpClient client = new DefaultHttpClient();
        HttpGet httpget = new HttpGet(url);

        // connect
        HttpResponse response = client.execute(httpget);

        // get response
        HttpEntity entity = response.getEntity();

        if(entity == null) {
            msg = "No response from server";
            return null;        
        }

        // get response content and convert it to json string
        InputStream is = entity.getContent();
        return streamToString(is);
    }
    catch(IOException e){
        msg = "No Network Connection";
    }

    return null;
}

@Override
protected void onPostExecute(String sJson) {
    if(sJson == null) {
        if(listener != null) listener.onFetchFailure(msg);
        return;
    }        

    try {
        // convert json string to json array
        JSONArray aJson = new JSONArray(sJson);
        // create apps list
        List<Usuari> apps = new ArrayList<Usuari>();

        for(int i=0; i<aJson.length(); i++) {
            JSONObject json = aJson.getJSONObject(i);
            Usuari app = new Usuari();
            app.setTitle(json.getString("app_title"));


            // add the app to apps list
            apps.add(app);
        }

        //notify the activity that fetch data has been complete
        if(listener != null) listener.onFetchComplete(apps);
    } catch (JSONException e) {
        msg = "Invalid response";
        if(listener != null) listener.onFetchFailure(msg);
        return;
    }        
}

/**
 * This function will convert response stream into json string
 * @param is respons string
 * @return json string
 * @throws IOException
 */
public String streamToString(final InputStream is) throws IOException{
    BufferedReader reader = new BufferedReader(new InputStreamReader(is));
    StringBuilder sb = new StringBuilder(); 
    String line = null;

    try {
        while ((line = reader.readLine()) != null) {
            sb.append(line + "\n");
        }
    } 
    catch (IOException e) {
        throw e;
    } 
    finally {           
        try {
            is.close();
        } 
        catch (IOException e) {
            throw e;
        }
    }



        return sb.toString();
    }
}

列表适配器:

public class UsuariAdapter extends ArrayAdapter<Usuari>{
    private List<Usuari> items;

    public UsuariAdapter(Context context, List<Usuari> items) {
        super(context, R.layout.row, items);
        this.items = items;
    }

    @Override
    public int getCount() {
        return items.size();
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        View v = convertView;

        if(v == null) {
            LayoutInflater li = LayoutInflater.from(getContext());
            v = li.inflate(R.layout.row, null);            
        }

        Usuari app = items.get(position);

        if(app != null) {

            TextView titleText = (TextView)v.findViewById(R.id.titleTxt);



            if(titleText != null){ titleText.setText(app.getTitle());}


        }

        return v;
    }
}

调用FetchDataTask的主要部分:

public class BuscarAmics extends ListActivity implements FetchDataListener{
        private ProgressDialog dialog;
        //Button boto_buscar;
       // TextView camp_buscar;
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);       
            setContentView(R.layout.buscar_amics);  
         // get the action bar
            ActionBar actionBar = getActionBar();
            actionBar.setDisplayHomeAsUpEnabled(true);
           // boto_buscar=(Button)findViewById(R.id.boto_buscar);
           // camp_buscar=(EditText)findViewById(R.id.camp_buscar);
           // boto_buscar.setOnClickListener(this);
            String url="http://www.myurl.com/buscar_amics.php";
            initView(url);  

        }


        private void initView(String url) {
            // show progress dialog
            dialog = ProgressDialog.show(this, "", "Loading...");



            FetchDataTask task = new FetchDataTask(this);
            task.execute(url);
        }


        @Override
        public void onFetchComplete(List<Usuari> usuaris) {
            // dismiss the progress dialog
            if(dialog != null)  dialog.dismiss();
            // create new adapter
            UsuariAdapter adapter = new UsuariAdapter(BuscarAmics.this, usuaris);
            // set the adapter to list
            setListAdapter(adapter);    
                  }

        @Override
        public void onFetchFailure(String msg) {
            // dismiss the progress dialog
            if(dialog != null) { dialog.dismiss();
            // show failure message
            Toast.makeText(this, msg, Toast.LENGTH_LONG).show(); }      
        }

2 个答案:

答案 0 :(得分:0)

确保您的响应返回!= null,此代码正常工作。

    HttpClient client = new DefaultHttpClient();
    HttpGet httpget = new HttpGet(url);

    // connect
    HttpResponse response = client.execute(httpget);

    // get response
    HttpEntity entity = response.getEntity();
    String state = EntityUtils.toString(entity);
    return streamToString(state);

答案 1 :(得分:0)

我找到了解决方案!!!

HERE!

获取代码