1

hey i have certain data on 000webhost which i want to send to my android studio app. I have checked the query by directly running on 000webhost , it is working.

But it is not sending data to android studio.I tried printing the value it prints null.Basically data i m sending trying to send an array.My fuction is performed on button click.I want a marker to appear on latitude longitude values being sent from php.BUt it send null with no error on logcat.

apiconnector i m using

package com.example.arpanagarwal.sba;

import android.util.Log;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.ParseException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;

 import java.io.IOException;

 public class Apiconnector2 {

 public JSONArray getUser() {
    //int i = 1;


    String url;
    //url = "http://10.0.0.2/uservalidate.php?BookName="+temp;
    HttpEntity httpEntity = null;
    //ArrayList<NameValuePair> nameValuePairs1 = new                     ArrayList<NameValuePair>();
    //nameValuePairs1.add(new BasicNameValuePair("search","sys"));
    try {
        System.out.println("step 3");
        url = "http://askamit2012.netne.net/callemptybin.php";
        DefaultHttpClient httpclient = new DefaultHttpClient();
        HttpGet httpGet = new HttpGet(url);
        //httpGet.setEntity(new UrlEncodedFormEntity(nameValuePairs1));

        HttpResponse httpResponse = httpclient.execute(httpGet);
        httpEntity = httpResponse.getEntity();

    } catch (ClientProtocolException e) {
        e.printStackTrace();

    } catch (IOException e) {
        e.printStackTrace();
    }
    JSONArray jsonArray = null;

    if (httpEntity != null) {
        try {
            String entityResponse = EntityUtils.toString(httpEntity);
            // String entityResponse = null;
            Log.e("Entity Response :", entityResponse);
            jsonArray = new JSONArray(entityResponse);
        } catch (JSONException e) {
            e.printStackTrace();
        } catch (ParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    return jsonArray;
}

}

/*****fuction where i m calling connector*****/

 public class callemptybin extends AsyncTask<Apiconnector2,Long,JSONArray>
{
    protected JSONArray doInBackground(Apiconnector2... params) {
        System.out.println("step1");
        return params[0].getUser();

    }
    @Override
    protected void onPreExecute()
    {
        System.out.println("step4");
        super.onPreExecute();
    }

    protected void onPostExecute(JSONArray jsonArray)
    {
        System.out.println("jsonarray=" + jsonArray);
        try{
            if(jsonArray==null)
            {
                System.out.println("null");
            }
            else {
                JSONObject json = jsonArray.getJSONObject(0);

                double lat1 = json.getDouble("latitude");
                double long1 = json.getDouble("longitude");

                LatLng jpnagar = new LatLng(lat1, long1);
                mMap.addMarker(new MarkerOptions().position(jpnagar).title("Bin Empty").icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_GREEN)));
            }
        }
        catch (JSONException e) {
            System.out.println("catch");
            e.printStackTrace();
        }
    }
}

/**** Function which is assingned to button ***/

public  void onthrow(View view)
{
    if(view.getId()==R.id.button3 )
    {
        //throwtrash();
        System.out.println("step 00");
        new callemptybin().execute(new Apiconnector2());
        tt=1;
    }
}

/***** Php script****/

<?php
if (isset($_SERVER['HTTP_ORIGIN'])) 
{
header("Access-Control-Allow-Origin: {$_SERVER['HTTP_ORIGIN']}");
header('Access-Control-Allow-Credentials: true');
header('Access-Control-Max-Age: 86400');    // cache for 1 day
}

// Access-Control headers are received during OPTIONS requests
if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') 
{

if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_METHOD']))
    header("Access-Control-Allow-Methods: GET, POST, OPTIONS");         

if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']))
    header("Access-Control-Allow-Headers:                 {$_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']}");

exit(0);
}


   $con = mysql_connect("mysql8.000webhost.com","********","*******");
    if(!$con)
    {
     die("Could not connect :".mysql_error());
    }
    mysql_select_db("*********",$con);


   //mysql_query($sql);
  mysql_query("set names 'utf8'"); 
   $result=mysql_query("select * from GPS where marker=1");
   while($row=mysql_fetch_assoc($result))
    {
     $output[]=$row;
    }
 print(json_encode($output));

   mysql_close($con);

?>      

logcat result.plz be careful with logcat since thr r multiple functions happening. i m checking only for one button click which has onthrow function as onclick intialized.check where json array prints as null in logcat.

04-14 21:16:51.387 1109-1109/? D/PhoneStatusBar: removeNotification      key=android.os.BinderProxy@42b5f3f0 keyCode=1119220720    old=StatusBarNotification(pkg=com.android.systemui user=UserHandle{0} id=252119    tag=null score=10: Notification(pri=1 contentView=com.android.systemui/0x1090064    vibrate=null sound=null defaults=0x0 flags=0x2 kind=[null]))
04-14 21:17:38.757 6128-6128/com.example.arpanagarwal.sba I/System.out:    **jsonarray=null**
 04-14 21:17:38.767 6128-6128/com.example.arpanagarwal.sba I/System.out: null
 04-14 21:18:56.327 6819-6835/? D/AlertSyncService: onHandleIntent action =   null
3
  • In PHP try replacing print with echo. Also, create the $output array outside your while loop. Currently it's scope is limited to the while block. Commented Apr 14, 2016 at 15:58
  • tried with echo still the same result Commented Apr 14, 2016 at 16:22
  • JSONObject json = jsonArray.getJSONObject(0); cn u tell me is thr ny prblm with this line in callemptybin Commented Apr 14, 2016 at 16:28

1 Answer 1

1

The post is too long, and stackoverflow does not like them. I have a few suggestions that you could try yourself.

  • Use Rest Console for testing out the expected response from the server. (Link for Google Chrome)

  • Forget DefaultHttpClient, use Volley, welcome to the modern world!

  • Keep it short. Nobody cares about what onthrow() does.

  • For parsing JSON to Java objects, use Gson.

Using Volley means that you will no longer be parsing JSON and you no longer need to create AsyncTasks and no longer writing codes for doInBackground(). I have made a GitHub gist to implement Volley in android codes.

Sign up to request clarification or add additional context in comments.

2 Comments

@arpanagarwal You mentioned that it was working fine on your browser. Your problem could be either on the connection: an unexpected response coming to your android application or your application not being able to parse it. First, try to locate whether the android application is receiving the data properly, by using Rest Console in the link provided above. After you pin point the error, I could help you.
Also, in android code, you can assert(condition) whenever you want to. Use them to track any unexpected code flow. And most of all, use android debugger.

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.