发送值到json php webservice android

时间:2015-09-12 07:09:13

标签: android json web-services

我正在尝试使用json和PHP webservice将edittext值插入到mysql表中。我找到了这样做的代码;它应该在webservice工作时传递“success”消息。但是当单击提交按钮时它强制关闭。这是代码:

    protected void onCreate(Bundle savedInstanceState) {
                super.onCreate(savedInstanceState);
                setContentView(R.layout.activity_main);
mhost=(EditText) findViewById(R.id.field_host);
        mdb=(EditText) findViewById(R.id.field_db);
        muser=(EditText) findViewById(R.id.field_user);
        mpassword=(EditText) findViewById(R.id.field_password);

        mConnection=(Button) findViewById(R.id.insert);
        mConnection.setOnClickListener(new OnClickListener() {

                    @Override
                    public void onClick(View v) {
                        // TODO Auto-generated method stub
                        new Connect().execute();

                    }
                });
        } 
    class Connect extends AsyncTask<String, String, String>{

            @Override
            protected String doInBackground(String... args) {
                // TODO Auto-generated method stub
                String HOST=mhost.getText().toString();
                String USER=muser.getText().toString();
                String DB=mdb.getText().toString();
                String PASSWORD=mpassword.getText().toString();

                List<NameValuePair> params=new ArrayList<NameValuePair>();
                params.add(new BasicNameValuePair("nfc_tag", HOST));
                params.add(new BasicNameValuePair("meter_reading", USER));
                params.add(new BasicNameValuePair("reading_datetime", DB));
                params.add(new BasicNameValuePair("image_name", PASSWORD));


                JSONObject json=jp.makeHttpRequest(connection_url, "POST", params);

                try {

                    int success=json.getInt(Tag_success);
                    if(success==1){

                        Toast.makeText(getApplicationContext(), "Connected :-)", Toast.LENGTH_LONG);
                    }else{

                        Toast.makeText(getApplicationContext(), "Not Connected :(", Toast.LENGTH_LONG);
                    }

                } catch (JSONException e) {
                    // TODO: handle exception
                    e.printStackTrace();
                }
                return null;
            }

        }

JsonParser类

public class JsonParser {

    static InputStream IS=null;
    static JSONObject JB=null;
    static String json="";

    public JsonParser(){


    }
    public JSONObject makeHttpRequest(String url,String method,List<NameValuePair> params){
        try {

            if(method=="POST"){

                DefaultHttpClient httpClient=new DefaultHttpClient();
                HttpPost httpPost=new HttpPost(url);
                httpPost.setEntity(new UrlEncodedFormEntity(params));

            }else if(method=="GET"){
                 DefaultHttpClient httpClient=new DefaultHttpClient();
                 String paramaString =URLEncodedUtils.format(params, "utf-8");
                 url +="?"+paramaString;
                 HttpGet httpGet=new HttpGet(url);

                 HttpResponse httpresponse=httpClient.execute(httpGet);
                 HttpEntity httpEntity=httpresponse.getEntity();
                 IS=httpEntity.getContent();

            }

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }catch (ClientProtocolException e) {
            // TODO: handle exception
        }catch (IOException e) {
            // TODO: handle exception
            e.printStackTrace();
        }

        try {

            BufferedReader reader=new BufferedReader(new InputStreamReader(IS,"iso-8859"),8);
            StringBuilder sb=new StringBuilder();
            String line=null;
            while((line=reader.readLine())!=null){
                sb.append(line+"\n");
            }
            IS.close();
            json=sb.toString();

        } catch (Exception e) {
            // TODO: handle exception
            Log.e("Buffer Error","Connection Error"+e.toString());
        }
        try {
            JB=new JSONObject(json);
        } catch (JSONException e) {
            // TODO: handle exception
            Log.e("JSON Parser", e.toString());
        }

        return JB;
    }

PHP脚本

<?php
$host=$_POST['nfc_tag'];
$user=$_POST['meter_reading'];
$db=$_POST['reading_datetime'];
$password=$_POST['image_name'];

$response=array();
$connect=mysql_connect($host,$user,$password);

if(mysql_select_db($db,$connect)){

$response['success']=1;
}else{
$response['success']=2;
}
echo json_encode($response);
?>

2 个答案:

答案 0 :(得分:0)

你初始化了你的EditText吗? 认为这是因为你没有初始化EditText“mhost”和“muser”并直接读取值。 例如。 mhost=(EditText)findViewById(R.id.mhost);

答案 1 :(得分:0)

初始化 mConnection 。它看起来像 Button 所以在调用 setOnClickListener 方法之前这样做

mConnection = (Button) findViewById(R.id.**YouButtonId**);
mhost = (EditText) findViewById(R.id.**YouEditTextId**); //if its a edittext
mConnection.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View v) {
                    // TODO Auto-generated method stub
                    new Connect().execute();

                }
            });