任何人都可以帮我解决这个错误吗,当我运行应用程序并搜索 ID 时,从 MySQL 数据库中选择值到 Android,它总是说(无效的 IP 地址)...
我的 Web 服务器上有一个 PHP 文件,该文件连接到 WampServer 数据库并检索返回到 Android 应用程序的值。
String id
String name;
InputStream is=null;
String result=null;
String line;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final EditText e_id=(EditText) findViewById(R.id.editText1);
Button select=(Button) findViewById(R.id.button1);
select.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
id=e_id.getText().toString();
select();
}
});
}
public void select()
{
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("id",id));
try
{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://10.0.2.2/test/select.php");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
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
{
JSONObject json_data = new JSONObject(result);
name=(json_data.getString("name"));
Toast.makeText(getBaseContext(), "Name : "+name,
Toast.LENGTH_SHORT).show();
}
catch(Exception e)
{
Log.e("Fail 3", e.toString());
}
}
LogCat 错误:
11-17 02:40:58.059: E/Fail 1(1073): android.os.NetworkOnMainThreadException
11-17 02:40:58.079: E/Fail 2(1073): java.lang.NullPointerException: lock == null
11-17 02:40:58.079: E/Fail 3(1073): java.lang.NullPointerException
感谢任何帮助...
最佳答案
E/Fail 1(1073): android.os.NetworkOnMainThreadException
出现此错误是因为您在主 Activity 的线程上运行网络连接调用(例如 httpclient
)。要摆脱这个问题,您需要使用另一个线程来进行这些调用。最简单的方法是使用 Async Task
关于java - 错误空指针异常 : lock == null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20028714/