当我运行我的应用程序时,它总是给我“无效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();   
    ?>发布于 2015-10-14 13:47:37
据我所知,你有一个NetworkOnMainThreadException。当您试图在主线程上执行任何网络操作时,就会发生这种情况。
当应用程序试图在其主线程上执行网络操作时引发的异常。 只有针对蜂窝SDK或更高版本的应用程序才会抛出此选项。针对早期SDK版本的应用程序可以在它们的主要事件循环线程上进行联网,但这是非常不可取的。请参阅文档设计以获得响应性。
要解决这个问题,请看一下AsyncTask。
私有类DownloadFilesTask扩展了AsyncTask {受保护的长doInBackground(URL.urls) { int totalSize = urls.length;long totalSize = 0;for (int i= 0;i< count;i++) {totalSize += Downloader.downloadFile(urlsi);publishProgress((int) ((i /(浮计数)计数)*100);//如果cancel()被调用if (isCancelled()Downloader.downloadFile),则提前//逃逸;}返回totalSize;}受保护的无效onProgressUpdate(整数)){setProgressPercent(进度);}受保护的无效onPostExecute(长结果){showDialog(“下载”+结果+“字节”);} 一旦创建了任务,就会非常简单地执行任务:
new DownloadFilesTask().execute(url1, url2, url3);
PS:使用Log.e("Fail 1", e.toString());被认为是错误的做法。使用e.printStackTrace()代替。
https://stackoverflow.com/questions/33117211
复制相似问题