模拟器无法启动,因为在我的mainactivity中发现错误。当我调试代码时,行发生异常:
HttpResponse response = httpclient.execute(httppost);
任何人都可以帮助我吗?这是我第一次尝试将android模拟器连接到localhost mysql数据库。以下是mainactivity类中的onCreate方法。
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
JSONArray jArray = null;
String result = null;
StringBuilder sb = null;
InputStream is = null;
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
//http post
try{
HttpClient httpclient = new DefaultHttpClient();
//Why to use 10.0.2.2
HttpPost httppost = new HttpPost("http://10.0.2.2/Appli/androidAccess.php");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
}catch(Exception e){
Log.e("log_tag", "Error in http connection"+e.toString());
}
//convert response to string
try{
BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
sb = new StringBuilder();
sb.append(reader.readLine() + "\n");
String line="0";
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result=sb.toString();
}catch(Exception e){
Log.e("log_tag", "Error converting result "+e.toString());
}
String name;
try{
jArray = new JSONArray(result);
JSONObject json_data=null;
for(int i=0;i<jArray.length();i++){
json_data = jArray.getJSONObject(i);
name=json_data.getString("NAME");//here "Name" is the column name in database
}
}
catch(JSONException e1){
Toast.makeText(getBaseContext(), "No Data Found" ,Toast.LENGTH_LONG).show();
} catch (ParseException e1) {
e1.printStackTrace();
}
}
这是我在htdocs中的php文件
<?php mysql_connect("localhost","root",""); mysql_select_db("appli"); $sql=mysql_query("select fName from userTest where id = 1"); while($row=mysql_fetch_assoc($sql)) $output[]=$row; print(json_encode($output));// this will print the output in json mysql_close(); ?>
12-29 20:02:54.850:E / log_tag(845):http connectionandroid.os.NetworkOnMainThreadException出错 12-29 20:02:54.850:E / log_tag(845):转换结果时出错java.lang.NullPointerException:lock == null 12-29 20:02:54.860:D / AndroidRuntime(845):关闭VM 12-29 20:02:54.860:W / dalvikvm(845):threadid = 1:线程退出未捕获的异常(group = 0xb3aecba8) 12-29 20:02:54.890:E / AndroidRuntime(845):致命异常:主要 12-29 20:02:54.890:E / AndroidRuntime(845):进程:com.example.loginapp,PID:845 12-29 20:02:54.890:E / AndroidRuntime(845):java.lang.RuntimeException:无法启动活动ComponentInfo {com.example.loginapp / com.example.loginapp.MainActivity}:java.lang.NullPointerException
答案 0 :(得分:1)
问题在于您的HTTP请求...检查您的清单中是否添加了正确的权限。
<uses-permission android:name="android.permission.INTERNET" />
并从您的模拟器或设备中检查您的网址...如果您无法访问它,请找到正确的网址....
打开命令提示符 - >输入ipconfig-&gt;获取IPV4地址....类似于192.xx ......
因此,您的网址为“http://192.xx.xx.xx/Appli/androidAccess.php”
从Android模拟器访问本地主机使用ipconfig中提供的ip地址。