Android中Fragment的setUserVisibleHint中的NetworkOnMainThreadException

时间:2016-04-11 13:48:39

标签: php android android-fragments database-connection httpurlconnection

我在Android中有片段的 setUserVisibleHint(boolean isVisibleToUser),如果“True”使 HTTPURLConnection 到远程数据库并检索数据。但是我在 data = getJSONData(); (第14行)上收到错误。我没有任何编译错误,但在运行时它失败,任何人都可以帮我解决我正在制作的错误。

完整的代码是:

public class Cafeteria extends Fragment {

InputStream in = null;

public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View fragView = inflater.inflate(R.layout.commonlayout, container, false);
    return fragView;
}

@Override
public void setUserVisibleHint(boolean isVisibleToUser){
    super.setUserVisibleHint(isVisibleToUser);
    if(isVisibleToUser){
        MainActivity.googleMap.clear();
        String data= null;
        try {
            data = getJSONData();
        } catch (IOException e) {
            e.printStackTrace();
        }
        MarkerDisplay(data);
    }
    else{}

}

private String getJSONData() throws IOException{
    String myurl = "http://10.52.23.10/project/getCafeteriaData.php";

    URL url = new URL(myurl);
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();

    try{
    conn.setDoInput(true);
    conn.setRequestMethod("GET");

    if (conn.getResponseCode()==200){
        in= conn.getInputStream();
    }
    else{
        Log.d("DEBUG_TAG", "The Response Code Obtained is: " +conn.getResponseCode());
    }
    in = new BufferedInputStream(in); 
    InputStreamReader is = new InputStreamReader(in);
    BufferedReader br = new BufferedReader(is);
    String read = br.readLine();

    return read;
    }
    finally {
        conn= null;
    }
}

public void MarkerDisplay(String read) {
    String str1= read; // Odata is original Stream Data
    double slat, slng;
    String sdesc;
    try {
        String delimiters1 = " ";
        String[] str2 = str1.split(delimiters1);

        for (int i = 0; i < str2.length; i++){
            String delimiters2 = ",";
            String[] mappairs = str2[i].split(delimiters2);
            //Convert all the string to double and int
            slat = Double.parseDouble(mappairs[0].substring(8));
            slng = Double.parseDouble(mappairs[1].substring(9));
            sdesc=mappairs[2].substring(11);

            LatLng latLngob = new LatLng(slat, slng); 
            MainActivity.googleMap.addMarker(new MarkerOptions().position(new LatLng(slat, slng)).icon(BitmapDescriptorFactory.fromResource(R.drawable.cafeteriamarker)).title(sdesc));
            }//else completes
    }//try ends here
    catch (Exception e) {
e.printStackTrace();
    }
}

}

1 个答案:

答案 0 :(得分:1)

尝试这样:

public class MyAsync extends AsyncTask<Void, Void, String> {

  @Override
  protected String doInBackground(String... params) {
       String str = "";
       try{
         str = getJSONData();
       }catch(Exception e){}
       return str;
  }

  @Override
  protected void onPostExecute(String result) {
    // use result here
  }
}