0

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

}

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?

2
  • did you try JsonObject(result) instead of JsonArray(result)? Commented Nov 9, 2017 at 23:55
  • what is the value of result? Also why create a BufferedReader with a size of 8? Commented Nov 10, 2017 at 0:07

1 Answer 1

1

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);
}
Sign up to request clarification or add additional context in comments.

1 Comment

Could you check my answer ?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.