douzhi9635 2017-11-09 23:46
浏览 75

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

In my exercise i have to send a String from my App Android to a .PHP file located in localhost. In this .PHP file there is the answer that Server re-send to my APP in form of JSON.

This is the .PHP file:

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

?>

This is the Activity:

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 + "
");
                }
                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") + "

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

}

And finally the Log:

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

What is my problem? Is it on my .PHP file or in Android?

  • 写回答

1条回答 默认 最新

  • douyu7210 2017-11-10 00:31
    关注

    Your problem is

    org.json.JSONException: End of input at character 0 of

    So you should check the JSONArray jArray = new JSONArray(result); first in your code . The result may be "" in your code .

    You can try this .

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

报告相同问题?

悬赏问题

  • ¥15 ogg dd trandata 报错
  • ¥15 高缺失率数据如何选择填充方式
  • ¥50 potsgresql15备份问题
  • ¥15 Mac系统vs code使用phpstudy如何配置debug来调试php
  • ¥15 目前主流的音乐软件,像网易云音乐,QQ音乐他们的前端和后台部分是用的什么技术实现的?求解!
  • ¥60 pb数据库修改与连接
  • ¥15 spss统计中二分类变量和有序变量的相关性分析可以用kendall相关分析吗?
  • ¥15 拟通过pc下指令到安卓系统,如果追求响应速度,尽可能无延迟,是不是用安卓模拟器会优于实体的安卓手机?如果是,可以快多少毫秒?
  • ¥20 神经网络Sequential name=sequential, built=False
  • ¥16 Qphython 用xlrd读取excel报错