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

Posted

技术标签:

【中文标题】从 MySQL 获取数据并使用 JSON 在 ListView 中显示【英文标题】:Get data from MySQL and show it in a ListView using JSON 【发布时间】:2014-04-12 22:48:59 【问题描述】:

我正在尝试从我的 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的main:

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();       
        

【问题讨论】:

【参考方案1】:

确保您的响应返回 != 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);

【讨论】:

现在,它显示了一条 Toast 消息,告诉我:“无效响应” 确保你的php文件回显正确的json格式字符串【参考方案2】:

我找到了解决办法!!!

从HERE!获取代码

【讨论】:

以上是关于从 MySQL 获取数据并使用 JSON 在 ListView 中显示的主要内容,如果未能解决你的问题,请参考以下文章

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

从 mysql 检索 json 数据并获取值作为对象

从 Laravel 中的 Mysql Pivot 表中获取列并返回 JSON 对象

Ajax获取到后台json数据,然后怎么取其中name的值赋值给li标签里面

使用 JSON 从 MYSql 获取数据到我的 iOS 应用程序

GET / POST方法无法使用json从mysql数据库获取数据到html