0

I'm trying to connect my Android app to server but I get errors and I don't know what is wrong.

Here is my MainActivity class:

public class MainActivity extends AppCompatActivity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        try {
            JsonReader jsonReader=new JsonReader(new JsonReader.AsyncResponse() {
                @Override
                public void processfinish(JSONObject output) {
                    Gson gson=new Gson();
                    String message=gson.toJson(output);
                    Toast.makeText(getApplicationContext(),"this is "+message,Toast.LENGTH_LONG).show();
                }
            });
            jsonReader.execute();


        } catch (IOException e) {
            e.printStackTrace();
        }catch (Exception e){
            e.printStackTrace();

        }
    }
}    

and this is my JsonReader class:

public class JsonReader extends AsyncTask<String,String,JSONObject>{
    final static String myurl="http://example.com";
    public interface AsyncResponse{
        void processfinish(JSONObject output);
    }
    public AsyncResponse delegate = null;

    public JsonReader(AsyncResponse delegate){
        this.delegate = delegate;
    }
    public static JSONObject readJsonFromUrl(String url) throws IOException, JSONException {
        InputStream is = new URL(url).openStream();
        try {
            BufferedReader rd = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8")));
            String jsonText = readAll(rd);
            JSONObject json = new JSONObject(jsonText);
            return json;
        }
        finally {
            is.close();
        }
    }
    @Override
    protected JSONObject doInBackground(String... strings) {
        try {
            JSONObject s = readJsonFromUrl(myurl);
            return s;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        } catch (JSONException e) {
            e.printStackTrace();
            return null;
        }
    }

    @Override
    protected void onPostExecute(JSONObject jsonObject) {
        super.onPostExecute(jsonObject);
        delegate.processfinish(jsonObject);
    }
}

I created AsyncResponse using this guide: How to get the result of OnPostExecute() to main activity because AsyncTask is a separate class?

And my PHP server code:

<?php
$dbhost = "myhost";
$dbuser = "myuser";
$dbname = "myname";
$dbpass = "mypassword";

$connect_db = mysql_connect ($dbhost, $dbuser, $dbpass);
mysql_select_db($dbname,$connect_db);
if ($connect_db){
    $result= mysql_query("SELECT * FROM `ask` ",$connect_db)or die(mysql_error());
    while($row = mysql_fetch_array($result))
    {
        $qa=new StdClass();
        $qa->Question=$row['Question'];
        $qa->Answer=$row['Answer'];
        $qa->Answer2=$row['Answer2'];
        $qa->Answer3=$row['Answer3'];
        $qa->Answer4=$row['Answer4'];
        echo "<br />";

        $rses=json_encode($qa);
        echo $rses;

    }

}else{
    echo "error in connecting db";
}
?>

When I start my app it shows "this is null", but when I open my php code in browser it shows data correctly. What is the problem?

UPDATE:

i used another url and its worked. so the problem is in my php codes.i removed echo "<br />"; and opened it on browser.the result was {"Question":"question","Answer":"a","Answer2":"b","Answer3":"c","Answer4":"d"} im not professional on json format but i think its not correct format.how can i fix this?

Community
  • 1
  • 1
dnl.d
  • 1
  • 3
  • What errors do you get? – Christopher Schneider Aug 03 '16 at 20:09
  • the app compiles without crash and shows toast with text"this is null" but i expect it shows "this is "+json data from server.and in logcat it shows "E/Surface: getSlotFromBufferLocked: unknown buffer: 0xeb1cb8a0" i searched for it and it seems android 6.0.0 bug but i tested on android 4.4.2 and the result was same. – dnl.d Aug 03 '16 at 20:25
  • 1
    I'm assuming your myurl is not *literally* `http://example.com` but is in fact a real URL resolvable and reachable from the internet, or at least from the network the device is on? – alzee Aug 03 '16 at 20:51

1 Answers1

0

Your browser correctly renders HTML. And this will be hidden to your eye

 echo "<br />";

Android cares solely about the string content, so it is unable to parse that break tag.

You might inspect the logcat to see a JSONParseException is happening, though you catch it and return null, so the app doesn't crash

Only echo out the JSON in the PHP

And since you have a while loop, you want to build a JSONArray, and parse that instead of trying to parse a JsonObject line by line.

Additionally, this isn't necessary

String message=gson.toJson(output);

You have a JsonObject as output, so just toString that

OneCricketeer
  • 179,855
  • 19
  • 132
  • 245
  • i removed the php code and run app but it still shows this is null and when i try `toString` app crashs because output is null. – dnl.d Aug 04 '16 at 09:55
  • I can only guess why the app crashes without the **full** logcat. Plus, I also said, use an array, don't only remove that line. You do return null, though, when the json can't be parsed, so the NullPointerException is hiding the actual problem, it sounds like – OneCricketeer Aug 04 '16 at 11:37