我必须从服务器上的MySQL数据库中获取一些数据。我有以下代码。但是当我运行它时应用程序崩溃了。即使我在Android Manifest中指定了Internet权限,我也会在Logcat中获得 Permission denied(缺少INTERNET权限?)。 知道这里可能有什么问题吗?
Java文件
import android.app.Activity;
import android.os.Bundle;
import android.os.StrictMode;
import android.util.Log;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends Activity {
TextView text;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
connect();
}
private void connect() {
String data;
List<String> r = new ArrayList<String>();
ArrayAdapter<String>adapter=new ArrayAdapter<String>(getApplicationContext(), android.R.layout.simple_list_item_1,r);
ListView list=(ListView)findViewById(R.id.listView1);
try {
DefaultHttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet("http://xxxxx/data.php");
HttpResponse response = client.execute(request);
HttpEntity entity=response.getEntity();
data=EntityUtils.toString(entity);
Log.e("STRING", data);
try {
JSONArray json=new JSONArray(data);
for(int i=0;i<json.length(); i++)
{
JSONObject obj=json.getJSONObject(i);
String name=obj.getString("name");
String desc=obj.getString("description");
// String lat=obj.getString("lat");
Log.e("STRING", name);
r.add(name);
r.add(desc);
// r.add(lat);
list.setAdapter(adapter);
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (ClientProtocolException e) {
Log.d("HTTPCLIENT", e.getLocalizedMessage());
} catch (IOException e) {
Log.d("HTTPCLIENT", e.getLocalizedMessage());
}
}
}
的AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.diana.menu" >
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<uses-permission android:name="android.permission.INTERNET"/>
<activity
android:name=".MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
data.php
<?php
$conn=mysql_connect('localhost', 'xxxx', 'xxxxx','u199776286_pois');
if(!$conn )
{
die('Could not connect: ' . mysql_error());
}
$sql = 'SELECT name, description FROM pois';
mysql_select_db('u199776286_pois');
$retval = mysql_query( $sql, $conn );
if(! $retval )
{
die('Could not get data: ' . mysql_error());
}
while($row = mysql_fetch_array($retval, MYSQL_ASSOC))
{
echo "NAME : {$row['name']} <br> ".
"DESCRIPTION : {$row['description']} <br> ".
"--------------------------------<br>";
}
echo "Fetched data successfully\n";
mysql_close($conn);
?>
我的logcat
答案 0 :(得分:2)
这是因为您从主UI线程连接到MySQL服务器。创建一个辅助线程(或异步任务)来连接并获得结果。
答案 1 :(得分:1)
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
编写上面的代码并不是摆脱NetworkOnMainThreadException的更好方法。您必须使用任何后台线程在api 11上面的android中进行网络操作,例如Asynch Task,Intent Service等。
How to fix android.os.NetworkOnMainThreadException?
您还可以将执行程序用于网络任务
Executors.newSingleThreadExecutor().submit(new Runnable() {
@Override
public void run() {
//You can performed your task here.
}
});
答案 2 :(得分:1)
使用Async Task从数据库中获取数据..
答案 3 :(得分:1)
在AndroidManifest.xml
<uses-permission android:name="android.permission.INTERNET" />
使用Asynck Task
List<String> r = new ArrayList<String>();
需要声明connect();
Oncreate
new LongOperation().execute("");
现在创建
private class LongOperation extends AsyncTask<String, Void, String> {
@Override
protected String doInBackground(String... params) {
connect();
return "Executed";
}
@Override
protected void onPostExecute(String result) {
ArrayAdapter<String>adapter=new ArrayAdapter<String>(getApplicationContext(), android.R.layout.simple_list_item_1,r);
ListView list=(ListView)findViewById(R.id.listView1);
list.setAdapter(adapter);
}
@Override
protected void onPreExecute() {}
@Override
protected void onProgressUpdate(Void... values) {}
}
//需要从connect();
中移除Ui控件并且需要值
在onPostExecute
答案 4 :(得分:1)
使用Async。如需更多帮助,请查看this