简体   繁体   中英

connection to server database in Android

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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