2015-10-14 71 views
0

當我運行我的應用程序時,它總是給我「無效的IP」,無法從數據庫中獲取數據。 我是一個新手,所以我不知道有關android。 我從谷歌獲得此代碼無法從數據庫中獲取數據?

以下是我的代碼段代碼,請幫助我。

public class EnterGeneralDetails extends Activity { 

    InputStream is=null; 
    String result=null; 
    String line=null; 

    @Override 
    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_general_details); 

     try 
     { 
      HttpClient httpclient = new DefaultHttpClient(); 
      HttpPost httppost = new HttpPost("http://thecapitalcitychurch.16mb.com/new/CohortName.php"); 
      HttpResponse response = httpclient.execute(httppost); 
      HttpEntity entity = response.getEntity(); 
      is = entity.getContent(); 
      Log.e("Pass 1", "connection success "); 
     } 
     catch(Exception e) 
     { 
      Log.e("Fail 1", e.toString()); 
      Toast.makeText(getApplicationContext(), "Invalid IP Address", 
        Toast.LENGTH_LONG).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"); 
      } 

      is.close(); 
      result = sb.toString(); 
      Log.e("Pass 2", "connection success "); 
     } 
     catch(Exception e) 
     { 
      Log.e("Fail 2", e.toString()); 
     } 

     try 
     { 
      JSONArray JA=new JSONArray(result); 
      JSONObject json= null; 
      final String[] str1 = new String[JA.length()]; 
      final String[] str2 = new String[JA.length()]; 

      for(int i=0;i<JA.length();i++) 
      { 
       json=JA.getJSONObject(i); 
       str1[i] = json.getString("ID"); 
       str2[i]=json.getString("Cohort_Name"); 
      } 

      final Spinner sp = (Spinner) findViewById(R.id.spinner22); 
      List<String> list = new ArrayList<String>(); 

      for(int i=0;i<str2.length;i++) 
      { 
       list.add(str2[i]); 
      } 


      Collections.sort(list); 

      ArrayAdapter<String> dataAdapter = new ArrayAdapter<String> 
        (getApplicationContext(), android.R.layout.simple_spinner_item, list); 
      dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); 
      sp.setAdapter(dataAdapter); 

      sp.setOnItemSelectedListener(new OnItemSelectedListener() 
      { 
       public void onItemSelected(AdapterView<?> arg0, View arg1,int position, long id) 
       { 
        // TODO Auto-generated method stub 

        String item=sp.getSelectedItem().toString(); 

        Toast.makeText(getApplicationContext(), item, 
          Toast.LENGTH_LONG).show(); 

        Log.e("Item",item); 
       } 

       public void onNothingSelected(AdapterView<?> arg0) 
       { 
        // TODO Auto-generated method stub 
       } 
      }); 
     } 
     catch(Exception e) 
     { 
      Log.e("Fail 3", e.toString()); 
     } 
    } 

} 

PHP代碼

<?php 
    $DB_USER='u868549735_rj'; 
    $DB_PASS='myself00'; 
    $DB_HOST='mysql.hostinger.in'; 
    $DB_NAME='u868549735_db'; 
    $mysqli = new mysqli($DB_HOST, $DB_USER, $DB_PASS, $DB_NAME); 
    /* check connection */ 
    if (mysqli_connect_errno()) { 
    printf("Connect failed: %s\n", mysqli_connect_error()); 
    exit(); 
    }  

    $mysqli->query("SET NAMES 'utf8'"); 
    $sql="SELECT ID, Cohort_Name FROM Cohorts"; 
    $result=$mysqli->query($sql); 
    while($e=mysqli_fetch_array($result)){ 
    $output[]=$e; 
    } 

    print(json_encode($output)); 
    $mysqli->close(); 

    ?> 
+0

你在日誌上得到了這個輸出連接成功嗎? –

+0

沒有......謝謝 – RBrb

+0

我曾訪問過該網站 http://thecapitalcitychurch.16mb.com/new/CohortName.php 它表明它已阻止我的IP,去一些驗證。那個過程也沒有反應。所以問題在於你的服務器。改變你的主機,你把你的'CohortName.php' –

回答

0

至於我可以看到你已經有了一個NetworkOnMainThreadException。當您嘗試在主線程上執行任何網絡操作時,會發生這種情況。

當應用程序嘗試在其主線程上執行聯網操作時引發的異常。

這僅適用於定位到Honeycomb SDK或更高版本的應用程序。針對早期SDK版本的應用程序允許在其主要事件循環線程上進行聯網,但非常不鼓勵。請參閱文檔Designing for Responsiveness。

要解決這個問題,看看AsyncTask

private class DownloadFilesTask extends AsyncTask<URL, Integer, Long> { 
    protected Long doInBackground(URL... urls) { 
     int count = urls.length; 
     long totalSize = 0; 
     for (int i = 0; i < count; i++) { 
      totalSize += Downloader.downloadFile(urls[i]); 
      publishProgress((int) ((i/(float) count) * 100)); 
      // Escape early if cancel() is called 
      if (isCancelled()) break; 
     } 
     return totalSize; 
    } 

    protected void onProgressUpdate(Integer... progress) { 
     setProgressPercent(progress[0]); 
    } 

    protected void onPostExecute(Long result) { 
     showDialog("Downloaded " + result + " bytes"); 
    } 
} 

一旦建立,任務是非常簡單的執行:

new DownloadFilesTask().execute(url1, url2, url3);

PS: 使用Log.e("Fail 1", e.toString());被認爲是不好的做法。改用e.printStackTrace()。