Quantcast
Channel: Active questions tagged listview - Stack Overflow
Viewing all articles
Browse latest Browse all 618

Get data from MySQL and show it in a ListView using JSON

$
0
0

I'm trying to get data from my MySQL external database and display it in a ListView. To do .. I use JSONObject and JSONArray .. can not get it to show me anything .. can you tell me what I do wrong?

The php file:

<?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 arraywhile($row = mysql_fetch_array($result)) {    $rows[] = $row; }// close the database connectionmysql_close($con);// echo the application data in json formatecho json_encode($rows);?>

The Asyntask java:

public class FetchDataTask extends AsyncTask<String, Void, String>{    private final FetchDataListener listener;    private String msg;public FetchDataTask(FetchDataListener listener) {    this.listener = listener;}@Overrideprotected 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;}@Overrideprotected 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();    }}

The List Adapter:

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;    }}

The main that calls the 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(); }              }

Viewing all articles
Browse latest Browse all 618

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>