2016-02-28 41 views
1

正如在標題中所述,我運行我的簡單應用程序時出現問題,該應用程序會在我的手機上發出http請求。在模擬器上它可以很好地工作,但在手機上它不能下載所需的字符串。http請求在模擬器中運行,但不在電話上運行

public class MainActivity extends AppCompatActivity { 
Button btn; 

public String uzmiLokacije() 
{ 
    String url_all_products = "http://www.parkingpmf.co.nf/db_get_all.php"; 
    HttpURLConnection urlConnection = null; 
    String res = ""; 

    try { 
     URL url = new URL(url_all_products); 
     urlConnection = (HttpURLConnection) url.openConnection(); 

     InputStream in = new BufferedInputStream(urlConnection.getInputStream()); 
     BufferedReader reader = new BufferedReader(new InputStreamReader(in)); 
     String line; 
     //String res = ""; 

     while((line=reader.readLine()) != null) 
     { 
      res = res + line; 
     } 
    } 
    catch(Exception e) 
    { 
     System.out.println(e.getMessage()); 
    } 
    finally{ 
     urlConnection.disconnect(); 
     return res; 
    } 
} 

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 

    btn = (Button) findViewById(R.id.button); 

    btn.setOnClickListener(new View.OnClickListener(
    ){ 
     @Override 
     public void onClick(View v) { 
      String ans = uzmiLokacije(); 
      Toast.makeText(getApplicationContext(), ans, Toast.LENGTH_LONG).show(); 
     } 
    }); 
} 

}

任何提示,爲什麼會出現這種情況? 我在清單中加入了這個:

<uses-permission android:name="android.permission.INTERNET" /> 

P.我正在使用Android Studio

+0

您是否嘗試過在此設備上的Web瀏覽器中訪問該頁面?此外,您需要將此網絡I/O移至後臺線程,因爲您可能正在使用「NetworkOnMainThreadException」崩潰。 – CommonsWare

+0

我已經嘗試在瀏覽器中打開,是的它的工作原理。你能解釋一下如何去做,因爲到現在爲止我還沒有做任何有關後臺線程的事情? 我會嘗試捕捉異常現在 –

+0

請提供一些更多的信息,以幫助我們,如你的手機,它的Android版本等... –

回答

0

Android禁止在主線程中從互聯網加載數據,因爲它會使應用程序在連接速度緩慢時出現滯後現象。您可以編寫自己的工作線程,也可以使用android自己提供的線程。

final TextView mTextView = (TextView) findViewById(R.id.text); 
... 

// Instantiate the RequestQueue. 
RequestQueue queue = Volley.newRequestQueue(this); 
String url ="http://www.google.com"; 

// Request a string response from the provided URL. 
StringRequest stringRequest = new StringRequest(Request.Method.GET, url, 
      new Response.Listener<String>() { 
    @Override 
    public void onResponse(String response) { 
     // Display the first 500 characters of the response string. 
     mTextView.setText("Response is: "+ response.substring(0,500)); 
    } 
}, new Response.ErrorListener() { 
    @Override 
    public void onErrorResponse(VolleyError error) { 
     mTextView.setText("That didn't work!"); 
    } 
}); 
// Add the request to the RequestQueue. 
queue.add(stringRequest); 

(從here拍攝的實施例)

正如你可以看到,本實施例中設置一個TextView的從互聯網上加載的文本的文本。您必須更改方法onResponseonErrorResponse中的代碼以實現您自己的邏輯。

相關問題