2

I have been trying to connect my mobile phone from android studio to mysql database at wamp server. However my database and the web page itself has not go live and just stay at localhost at my pc. However both my pc and smartphone is connected to the same internet. Therefore, i would like to know if i can use json and urlconnection to retrieve and sent data to and from database at local host?

 private class RetrieveTask extends AsyncTask<Void, Void, Void>{

    @Override
    protected Void doInBackground(Void... params) {
        ContentValues nameValuePairList = new ContentValues();

        try{
            URL url = new  
   URL("http://10.211.66.88/test2/register_user.php");

            HttpURLConnection conn = (HttpURLConnection) 
  url.openConnection();
            conn.setReadTimeout(10000);
            conn.setConnectTimeout(15000);
            conn.setRequestMethod("POST");
            conn.setDoInput(true);
            conn.setDoOutput(true);

            System.out.println("Response Code: " + conn.getResponseCode());
            InputStream in = new BufferedInputStream(conn.getInputStream());
            String response = nameValuePairList.toString();
            System.out.println(response);
        }catch (Exception e){
            Toast.makeText(getApplicationContext(), exceptionMessage+", 
  Ex1", Toast.LENGTH_SHORT).show();
        }try{
            BufferedReader reader = new BufferedReader(new 
  InputStreamReader(is, "iso-8859-1"), 8);
            StringBuilder sb = new StringBuilder();
            while((line=reader.readLine())!=null){
                sb.append(line+"\n");
            }
            result = sb.toString();
            System.out.println("-----JSON Data-----");
            System.out.println(result);
            is.close();
        }catch(Exception e){
            Toast.makeText(getApplicationContext(), exceptionMessage+",
   Ex2", Toast.LENGTH_SHORT).show();
        }try{
            JSONArray jsonArray = new JSONArray(result);
            int totalCount = jsonArray.length();
            for(int i=0; i<totalCount; i++){
                JSONObject jsonObject = jsonArray.getJSONObject(i);
                names += jsonObject.getString("name")+":";
                emails += jsonObject.getString("email")+":";
                passwords += jsonObject.getString("password")+":";
                fullnames += jsonObject.getString("fullname")+":";
                combinedText += (i+1)+". Name 
   '"+jsonObject.getString("name")+"', "+
                        "Email '"+jsonObject.getString("email")+"', "+
                        "password '"+jsonObject.getString("password")+"', "+
                        "fullname '"+jsonObject.getString("fullname")+"':";
            }

        }catch (Exception e){
            Toast.makeText(getApplicationContext(), exceptionMessage+", 
   Ex3", Toast.LENGTH_SHORT).show();
        }

        return null;
    }
Cheong Charlene
  • 275
  • 1
  • 2
  • 12

0 Answers0