错误NullPointerException:lock == null

时间:2013-11-17 08:25:02

标签: java android

任何人都可以帮我解决这个错误,当我运行应用程序并搜索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

任何帮助表示赞赏......

1 个答案:

答案 0 :(得分:2)

E/Fail 1(1073): android.os.NetworkOnMainThreadException

引发此错误的原因是您在主Activity的主题上运行了网络连接调用(如httpclient)。要摆脱这种情况,你需要使用另一个线程进行这些调用。这样做的简单方法是使用Async Task