Failed to get location using opencellid.org Android

im using opencellid.org to get Mobile location from cell id, Mnc and Mmcc and other information, im getting CellId, MNC, MCC and LAC, but could not get location from this information. Error showing " android.os.NetworkOnMainThreadException "

Here is the code

public class OpenCellID {
		  String mcc;  //Mobile Country Code
		  String mnc;  //mobile network code
		  String cellid; //Cell ID
		  String lac;  //Location Area Code
		   
		  Boolean error;
		  String strURLSent;;
		  String GetOpenCellID_fullresult;;
		   
		  String latitude;
		  String longitude;
		   
		  public Boolean isError(){
		   return error;
		  }
		   
		  public void setMcc(String value){
		   mcc = value;
		  }
		   
		  public void setMnc(String value){
		   mnc = value;
		  }
		   
		  public void setCallID(int value){
		   cellid = String.valueOf(value);
		  }
		   
		  public void setCallLac(int value){
		   lac = String.valueOf(value);
		  }
		   
		  public String getLocation(){
		   return(latitude + " : " + longitude);
		  }
		   
		  public void groupURLSent(){
		   strURLSent =
		    "http://www.opencellid.org/cell/get?mcc=" + mcc
		    +"&mnc=" + mnc
		    +"&cellid=" + cellid
		    +"&lac=" + lac
		    +"&fmt=txt";
		  }
		   
		  public String getstrURLSent(){
		   return strURLSent;
		  }
		   
		  public String getGetOpenCellID_fullresult(){
		   return GetOpenCellID_fullresult;
		  }
		   
		  public void GetOpenCellID() throws Exception {
		   groupURLSent();
		   HttpClient client = new DefaultHttpClient();
		   HttpGet request = new HttpGet(strURLSent);
		   HttpResponse response = client.execute(request);
		   GetOpenCellID_fullresult = EntityUtils.toString(response.getEntity()); 
		   spliteResult();
		  }
		   
		  private void spliteResult(){
		   if(GetOpenCellID_fullresult.equalsIgnoreCase("err")){
		    error = true;
		   }else{
		    error = false;
		    String[] tResult = GetOpenCellID_fullresult.split(",");
		    latitude = tResult[0];
		    longitude = tResult[1];
		   }
		     
		    
		  }
		 }
		 
		 int myLatitude, myLongitude;
		 OpenCellID openCellID;
		 
		  
		   /** Called when the activity is first created. */
		   @Override
		   public void onCreate(Bundle savedInstanceState) {
		       super.onCreate(savedInstanceState);
		       setContentView(R.layout.activity_main);
		        
		       TextView textGsmCellLocation = (TextView)findViewById(R.id.gsmcelllocation);
		       TextView textMCC = (TextView)findViewById(R.id.mcc);
		       TextView textMNC = (TextView)findViewById(R.id.mnc);
		       TextView textCID = (TextView)findViewById(R.id.cid);
		       TextView textLAC = (TextView)findViewById(R.id.lac);
		       TextView textGeo = (TextView)findViewById(R.id.geo);
		       TextView textRemark = (TextView)findViewById(R.id.remark);;
		       
		       
		       //retrieve a reference to an instance of TelephonyManager
		       TelephonyManager telephonyManager = (TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);
		       GsmCellLocation cellLocation = (GsmCellLocation)telephonyManager.getCellLocation();
		       
		       String networkOperator = telephonyManager.getNetworkOperator();
		       String mcc = networkOperator.substring(0, 3);
		       String mnc = networkOperator.substring(3);
		       textMCC.setText("mcc: " + mcc);
		       textMNC.setText("mnc: " + mnc);
		       
		       int cid = cellLocation.getCid();
		       int lac = cellLocation.getLac();
		       textGsmCellLocation.setText(cellLocation.toString());
		       textCID.setText("gsm cell id: " + String.valueOf(cid));
		       textLAC.setText("gsm location area code: " + String.valueOf(lac));
		       
		       openCellID = new OpenCellID();
		       
		       openCellID.setMcc(mcc);
		       openCellID.setMnc(mnc);
		       openCellID.setCallID(cid);
		       openCellID.setCallLac(lac);
		       try {
		   openCellID.GetOpenCellID();
		    
		   if(!openCellID.isError()){
		    textGeo.setText(openCellID.getLocation());
		    textRemark.setText( "\n\n"
		      + "URL sent: \n" + openCellID.getstrURLSent() + "\n\n"
		      + "response: \n" + openCellID.GetOpenCellID_fullresult);
		   }else{
		    textGeo.setText("Error");
		   }
		  } catch (Exception e) {
		   // TODO Auto-generated catch block
		   e.printStackTrace();
		   textGeo.setText("Exception: " + e.toString());
		   Log.d("location is not valid",e.toString());
		  }
		   }   
		}

	
      

Run codeHide result


Log code that does not display errors

  : Flushing caches (mode 0)
   received file descriptor 48 from ADB
 D/ActivityThread(27520): BIND_APPLICATION handled : 0 / AppBindData{appInfo=ApplicationInfo{4180ddd8 com.example.cellid_areacode}}
   processIncoming
   processIncoming
   handlePacket : cmd=0x1, cmdSet=0xC7, len=0x13, id=0x4000010A, flags=0x0, dataLen=0x8
   REQ: DDM.Chunk (cmd=199/1 dataLen=8 id=0x4000010a)
   reply: dataLen=9 err=NONE(0)
   processIncoming
   handlePacket : cmd=0x1, cmdSet=0xC7, len=0x17, id=0x4000010B, flags=0x0, dataLen=0xC
   REQ: DDM.Chunk (cmd=199/1 dataLen=12 id=0x4000010b)
   reply: dataLen=104 err=NONE(0)
   processIncoming
   handlePacket : cmd=0x1, cmdSet=0xC7, len=0x13, id=0x4000010C, flags=0x0, dataLen=0x8
   REQ: DDM.Chunk (cmd=199/1 dataLen=8 id=0x4000010c)
   reply: dataLen=216 err=NONE(0)
   processIncoming
   handlePacket : cmd=0x1, cmdSet=0xC7, len=0x13, id=0x4000010D, flags=0x0, dataLen=0x8
   REQ: DDM.Chunk (cmd=199/1 dataLen=8 id=0x4000010d)
   reply: dataLen=9 err=NONE(0)
   processIncoming
   handlePacket : cmd=0x1, cmdSet=0xC7, len=0x14, id=0x4000010E, flags=0x0, dataLen=0x9
   REQ: DDM.Chunk (cmd=199/1 dataLen=9 id=0x4000010e)
   reply: dataLen=0 err=NONE(0)
 getDefaultSim is sim1
  create GsmCellLocation
  getDefaultSim is sim1
  getaddrinfo: www.opencellid.org  return error = 0x8 >>
   android.os.NetworkOnMainThreadException
   	at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1099)
   	at java.net.InetAddress.lookupHostByName(InetAddress.java:392)
   	at java.net.InetAddress.getAllByNameImpl(InetAddress.java:243)
   	at java.net.InetAddress.getAllByName(InetAddress.java:221)
   	at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:137)
   	at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164)
   	at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119)
   	at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:363)
   	at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555)
   	at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
   	at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465)
   	at com.example.cellid_areacode.MainActivity$OpenCellID.GetOpenCellID(MainActivity.java:80)
   	at com.example.cellid_areacode.MainActivity.onCreate(MainActivity.java:141)
   	at android.app.Activity.performCreate(Activity.java:4479)
   	at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1050)
   	at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2041)
   	at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2104)
   	at android.app.ActivityThread.access$600(ActivityThread.java:134)
   	at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1247)
   	at android.os.Handler.dispatchMessage(Handler.java:99)
   	at android.os.Looper.loop(Looper.java:154)
   	at android.app.ActivityThread.main(ActivityThread.java:4624)
   	at java.lang.reflect.Method.invokeNative(Native Method)
   	at java.lang.reflect.Method.invoke(Method.java:511)
   	at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:809)
   	at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:576)
   	at dalvik.system.NativeStart.main(Native Method)
    location is not valid(27520): android.os.NetworkOnMainThreadException
    ActivityThread(27520): ACT-AM_ON_RESUME_CALLED ActivityRecord{4180f378 token=android.os.BinderProxy@4180eb00 {com.example.cellid_areacode/com.example.cellid_areacode.MainActivity}}
    ACT-LAUNCH_ACTIVITY handled : 0 / ActivityRecord{4180f378 token=android.os.BinderProxy@4180eb00 {com.example.cellid_areacode/com.example.cellid_areacode.MainActivity}}
    GC_CONCURRENT freed 194K, 4% free 9425K/9719K, paused 1ms+1ms
    loaded /system/lib/egl/libGLES_android.so
    loaded /vendor/lib/egl/libEGL_mtk.so
    loaded /vendor/lib/egl/libGLESv1_CM_mtk.so
    loaded /vendor/lib/egl/libGLESv2_mtk.so
    Enabling debug mode 0
    threadid=11: interp stack at 0x4d174000
    showStatusIcon on inactive InputConnection
      

  
      

Run codeHide result


If I'm not mistaken, I need to write an AsyncTask class, but I don't know what function or code should be written in the DoinBackground function in the AsyncTask class. Help would be appreciated
thanks in Advance

+3


source to share


2 answers


My class with async task looks like below

public class MainActivity extends AppCompatActivity {
private  OpenCellID openCellID;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        TelephonyManager tm = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);
        GsmCellLocation loc = (GsmCellLocation) tm.getCellLocation();
        String networkOperator = tm.getNetworkOperator();
        String mcc = networkOperator.substring(0, 3);
        String mnc = networkOperator.substring(3);
        int cellid = loc.getCid();
        int lac = loc.getLac();
        openCellID = new OpenCellID();
        openCellID.setMcc(mcc);
        openCellID.setMnc(mnc);
        openCellID.setCallID(cellid);
        openCellID.setCallLac(lac);
        new GetLocation().execute();
    }
    class GetLocation extends AsyncTask<String, Void, Void> {
        private Exception exception;
        protected Void doInBackground(String... urls) {
            try {
                try {
                    openCellID.GetOpenCellID();
                    if(!openCellID.isError()) {
                        Toast.makeText(getApplicationContext(), openCellID.getLocation(), Toast.LENGTH_LONG).show();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                return null;
            } catch (Exception e) {
                this.exception = e;
                return null;
            }
        }
        protected void onPostExecute(Void feed) {
            // TODO: check this.exception
            // TODO: do something with the feed
        }
    }
    public class OpenCellID {
        String mcc; //Mobile Country Code
        String mnc; //mobile network code
        String cellid; //Cell ID
        String lac; //Location Area Code
        Boolean error;
        String strURLSent;
        String GetOpenCellID_fullresult;
        String latitude;
        String longitude;

        public Boolean isError(){
            return error;
        }

        public void setMcc(String value){
            mcc = value;
        }

        public void setMnc(String value){
            mnc = value;
        }

        public void setCallID(int value){
            cellid = String.valueOf(value);
        }

        public void setCallLac(int value){
            lac = String.valueOf(value);
        }

        public String getLocation(){
            return(latitude + " : " + longitude);
        }
        public void groupURLSent(){
            strURLSent =
                    "http://www.opencellid.org/cell/get?key=15e7c7be-4d6c-42bc-a79c-23be75abcc87&mcc=" + mcc
                            +"&mnc=" + mnc
                            +"&cellid=" + cellid
                            +"&lac=" + lac
                            +"&fmt=txt";
        }

        public String getstrURLSent(){
            return strURLSent;
        }

        public String getGetOpenCellID_fullresult(){
            return GetOpenCellID_fullresult;
        }

        public void GetOpenCellID() throws Exception {
            groupURLSent();
            HttpClient client = new DefaultHttpClient();
            HttpGet request = new HttpGet(strURLSent);
            HttpResponse response = client.execute(request);
            GetOpenCellID_fullresult = EntityUtils.toString(response.getEntity());
            spliteResult();
        }
        private void spliteResult(){
            if(GetOpenCellID_fullresult.equalsIgnoreCase("err")){
                error = true;
            }else{
                error = false;
                String[] tResult = GetOpenCellID_fullresult.split(",");
                latitude = "23.028431";
                longitude = "72.491422";
            }
        }
    }
}

      

Another suggestion will add the api key to your url, otherwise it won't give you any result.



You can create api key from this link

Your url should be like this http://opencellid.org/cell/get?key=15e7c7be-4d6c-42bc-a79c-23be75abcc87&mcc=405&mnc=030&cellid=19757464&lac=30001&fmt=txt

+1


source


opencellid changed the api structure, they use XML output, so you need to adapt your code to read data from xml file or url. I hope I can help you with something.



-2


source







All Articles