繁体   English   中英

使用JSON将Android中的字符串发送到PHP

[英]Send String from Android to PHP using JSON

在我的练习中,我必须将一个字符串从我的App Android发送到位于localhost的.PHP文件。 在此.PHP文件中,服务器将以JSON形式重新发送到我的APP。

这是.PHP文件:

<?php
include_once '../database/ConnessioneDb.php';
include_once 'SchedaRepertoInterface.php';

$schedaInterface = new SchedaRepertoInterface(); 

$schedaReperto = $schedaInterface->readById($_POST['idScheda']); //oppure id_scheda

 if($schedaReperto->getPubblica()==1){

 $titolo=$schedaReperto->getNome();
 $descriziones=$schedaReperto->getDescrizioneShort();
 $descrizionee=$schedaReperto->getDescrizioneEstesa();

 $a = array($titolo, $descriziones, $descrizionee);
 print(json_encode($a));


 echo '{ \"titolo\" : \"$titolo\" ,  \"descriziones\" : \"$descriziones\" ,  \"descrizionee\" : \"$descrizionee\"}';


 else{
     $titolo='Spiacente Scheda Reperto non Pubblica';
     print(json_encode($titolo));
 }

?>

这是活动:

public class SchedeActivity extends Activity implements TextToSpeech.OnInitListener {

private String url = "http://192.168.1.5/wordpress/wp-content/plugins/wp-schedeReperto/interaction.php";
private String idSchedaReceived;
TextView titoloView;
TextView descrizionesView;
TextView descrizioneeView;
private TextView myAwesomeTextView;
private TextToSpeech tts;
private FloatingActionButton btnSpeak;

boolean riproduzione_in_corso = false;

/**
 * Called when the activity is first created.
 */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_schede);

    tts = new TextToSpeech(this, this);
    btnSpeak = (FloatingActionButton) findViewById(R.id.fab);
    Intent intent = getIntent();
    idSchedaReceived = intent.getExtras().getString("idScheda");
    riproduzione_in_corso = false;

    titoloView = (TextView) findViewById(R.id.titolo);
    descrizionesView = (TextView) findViewById(R.id.descShort);
    descrizioneeView = (TextView) findViewById(R.id.descExt);


    HttpGetTask task = new HttpGetTask();
    task.execute();

    myAwesomeTextView = (TextView)findViewById(R.id.myAwesomeTextView);
    myAwesomeTextView.setVisibility(TextView.INVISIBLE);

    FloatingActionButton fab = btnSpeak;
    fab.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(final View view) {

            if(riproduzione_in_corso==false) {
                final AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(SchedeActivity.this);
                alertDialogBuilder.setMessage("Attivare riproduzione Audio?");
                alertDialogBuilder.setPositiveButton("YES", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int id) {
                        myAwesomeTextView.setText(titoloView.getText().toString() + descrizionesView.getText().toString() + descrizioneeView.getText().toString());
                        //speakOut();
                        riproduzione_in_corso = true;
                    }
                })
                        .setNegativeButton("NO", new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int id) {
                                riproduzione_in_corso = false;
                            }
                        });
                alertDialogBuilder.create();
                alertDialogBuilder.show();
            }

            else {
                final AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(SchedeActivity.this);
                alertDialogBuilder.setMessage("Disattivare Audio?");
                alertDialogBuilder.setPositiveButton("YES", new DialogInterface.OnClickListener(){
                    public void onClick(DialogInterface dialog, int id) {
                        tts.stop();
                        riproduzione_in_corso = false;
                    }
                })

                        .setNegativeButton("NO", new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int id) {
                                riproduzione_in_corso = true;
                            }
                        });

                alertDialogBuilder.create();
                alertDialogBuilder.show();
            }
        }
    });

}
private class HttpGetTask extends AsyncTask<String, String, String> {

    @Override
    protected String doInBackground(String... params) {
        String result = "";
        String stringaFinale = "";
        ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
        nameValuePairs.add(new BasicNameValuePair("idScheda", idSchedaReceived));
        InputStream is = null;

        //http post
        try{
            HttpClient httpclient = new DefaultHttpClient();
            HttpPost httppost = new HttpPost("http://192.168.1.5:80/wordpress/wp-content/plugins/wp-schedeReperto/interaction.php");
            httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
            HttpResponse response = httpclient.execute(httppost);
            HttpEntity entity = response.getEntity();
            is = entity.getContent();
        }catch(Exception e){
            Log.e("TEST", "Errore nella connessione http "+e.toString());
        }

        if (is != null) {
            //converto la risposta in stringa
            try {
                BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8);
                StringBuilder sb = new StringBuilder();
                String line = null;
                while ((line = reader.readLine()) != null) {
                    sb.append(line + "\n");
                }
                is.close();

                result = sb.toString();
            } catch (Exception e) {
                Log.e("TEST", "Errore nel convertire il risultato " + e.toString());
            }


            //parsing dei dati arrivati in formato json
            try{
                JSONArray jArray = new JSONArray(result);
                for(int i=0;i<jArray.length();i++){
                    JSONObject json_data = jArray.getJSONObject(i);

                    stringaFinale = json_data.getString("titolo") + " " + json_data.getString("descriziones") + " " + json_data.getString("descrizionee") + "\n\n";
                }
            }
            catch(JSONException e){
                Log.e("log_tag", "Error parsing data "+e.toString());
            }

        }else{}


        return stringaFinale;

    }

    @Override
    protected void onProgressUpdate(String... values) {

    }

    @Override
    protected void onPostExecute(String result) {
        myAwesomeTextView.setText(result);
    }
}

}

最后是日志:

E/log_tag: Error parsing data org.json.JSONException: End of input at character 0 of

我怎么了 是在我的.PHP文件中还是在Android中?

你的问题是

org.json.JSONException:输入的结尾(字符为0)

因此,您应该检查JSONArray jArray = new JSONArray(result); 首先在您的代码中。 result可能在您的代码中为""

你可以试试看。

if(!TextUtils.isEmpty(result)){
    JSONArray jArray = new JSONArray(result);
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM