从onClick项目获取详细信息

时间:2013-07-18 11:15:46

标签: java php android mysql

首先,如果这个问题已经存在,我想道歉,但我找不到正确答案。 我将数据从MySQL传输到List,这工作正常,但现在我想从列表中点击这个项目。当我从列表中选择一个人时,Dialog会弹出他的名字和一个按钮来给他打电话。我的问题是如何在点击时获得该名称和电话号码。请查看代码,因为我没有像其他示例那样制作任何特定的字符串。 以下是代码:

应用程序适配器

package com.sj.jsondemo;

import java.util.List;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;

public class ApplicationAdapter extends ArrayAdapter<Application>{
    private List<Application> items;

    public ApplicationAdapter(Context context, List<Application> items) {
        super(context, R.layout.app_custom_list, 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.app_custom_list, null);            
        }

        Application app = items.get(position);

        if(app != null) {

            TextView imeText = (TextView)v.findViewById(R.id.titleTxt);
            TextView telText = (TextView)v.findViewById(R.id.tel);
            TextView gradText = (TextView)v.findViewById(R.id.dlTxt);

            if(imeText != null) imeText.setText(app.getIme());
            if(gradText != null) gradText.setText(app.getGrad());                       
            if(telText != null) telText.setText(app.getTelefon());   

        }

        return v;
    }
}

FetchDataTask

package com.sj.jsondemo;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List; 
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.os.AsyncTask;

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<Application> apps = new ArrayList<Application>();

            for(int i=0; i<aJson.length(); i++) {
                JSONObject json = aJson.getJSONObject(i);
                Application app = new Application();
                app.setIme(json.getString("Ime"));
                app.setGrad(json.getString("Grad"));
                app.setTelefon(json.getString("Broj"));  


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

主要

package com.sj.jsondemo;

import java.util.List;
import android.app.AlertDialog;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;

public class MainActivity extends ListActivity implements FetchDataListener{
    private ProgressDialog dialog;
    private static final String TAG_PID = "pid";

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

        setListAdapter(new ArrayAdapter<String>(this, R.layout.activity_main));

        ListView listView = getListView();
        listView.setTextFilterEnabled(true);

        listView.setOnItemClickListener(new OnItemClickListener() {
            public void onItemClick(AdapterView<?> parent, View view,
                    final int position, long id) {


                AlertDialog.Builder adb=new AlertDialog.Builder(MainActivity.this);
                adb.setTitle("Odabir");
                adb.setMessage("Izabrali ste profesora "+ ??? ); //how to get name of selected person

                adb.setPositiveButton("Call",new DialogInterface.OnClickListener() {
                    public void onClick (DialogInterface dialog, int which) {
                    Intent i=new Intent(android.content.Intent.ACTION_DIAL,
                        Uri.parse("tel:+"+ ???);  //how to get number of selected person
                    startActivity(i);
                    }
                });
                adb.show(); 
            }
        });
    }

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

        String url = "http://192.168.1.12/test/apps.php";
        FetchDataTask task = new FetchDataTask(this);
        task.execute(url);
    }

    @Override
    public void onFetchComplete(List<Application> data) {
        // dismiss the progress dialog
        if(dialog != null)  dialog.dismiss();
        // create new adapter
        ApplicationAdapter adapter = new ApplicationAdapter(this, data);
        // 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();        
    }




}

和PHP

<?php
$host = "localhost"; // host of MySQL server
$user = "root"; // MySQL user
$pwd = "aleksa"; // MySQL user's password
$db = "spisak"; // database name

// Create connection
$con = mysqli_connect($host, $user, $pwd, $db);

// Check connection
if(mysqli_connect_errno($con)) {
    die("Failed to connect to MySQL: " . mysqli_connect_error());
} 

// query the application data
$sql = "SELECT * FROM lista ORDER By id";
$result = mysqli_query($con, $sql);



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

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

}


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

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

提前谢谢。

RGDS,

亚历

编辑:我编辑了代码,缩短了代码,因此您可以更轻松地帮助我。

0 个答案:

没有答案