"无效的IP地址" android-JSON-MySQL中发现错误

时间:2015-03-26 17:14:18

标签: php android mysql json

我正在尝试创建一个连接到MySQL数据库并查询数据的应用程序。我不想插入任何数据,只是在给定的条目中搜索关键字。我在Google上找到了几个教程,这个教程对我有用。

布局看起来很好,应用程序启动良好(我在我的实际Nexus 5上测试了应用程序)。但是每次单击按钮时,无论文本框中是否有数据,它都会在toast中显示“Invalid IP address”,我假设是错误捕获的。我的PHP看起来像这样:

$host='*****';
$uname='*****';
$pwd='*****';
$db="*****";
$con = mysql_connect($host,$uname,$pwd) or die("connection failed");
mysql_select_db($db,$con) or die("db selection failed");
$id=$_REQUEST['id'];
$r=mysql_query("select * from ***** where id='$id'",$con);
while($row=mysql_fetch_array($r))
{
$flag[name]=$row[name];
}
print(json_encode($flag));
mysql_close($con);

为什么我收到此错误?我该如何让它发挥作用?可以提供所需的任何其他数据。

修改

Android代码

public class MainActivity extends Activity {  
    String id;  
    String name;  
    InputStream is=null;  
    String result=null;  
    String line=null;  
    @Override  
    public void onCreate(Bundle savedInstanceState) {  
        super.onCreate(savedInstanceState);  
        setContentView(R.layout.activity_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://kanurajb.co.nf/php/search.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());    
        }   
    }  
    @Override  
    public boolean onCreateOptionsMenu(Menu menu) {  
        getMenuInflater().inflate(R.menu.main, menu);  
        return true;  
    }  
}

1 个答案:

答案 0 :(得分:0)

查看答案here ..它正确告诉您如何处理异常。它说..

  

当应用程序尝试执行a时,抛出此异常   主线程上的网络操作。运行你的代码   AsyncTask

改变你的代码,如下所示..我已经更改了你的select(),如下所示。这只是为了让你更好地理解AsyncTask

class RetrieveFeedTask extends AsyncTask<Void, Void, Boolean> {

  private Exception exception;

  protected Boolean doInBackground(String... urls) {
      try {
        Boolean failedflag=false;
        ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();  
        nameValuePairs.add(new BasicNameValuePair("id",id));  
        try  
        {  
            HttpClient httpclient = new DefaultHttpClient();  
            HttpPost httppost = new   HttpPost("http://kanurajb.co.nf/php/search.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) 
        {  
            failedflag=true;
            Log.e("Fail 1", e.toString());           
        }  
        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)  
        {  
            failedflag=true;
            Log.e("Fail 2", e.toString());   
        }  
        try  
        {  
            JSONObject json_data = new JSONObject(result);  
            name=(json_data.getString("name"));   
        }    
        catch(Exception e)   
        {  
            failedflag=true;
            Log.e("Fail 3", e.toString());    
        }   
        return failedflag;
  }

  protected void onPostExecute(Boolean flag) { 
      // TODO: do something with the flag
      if(!flag){
          Toast.makeText(getApplicationContext(), "Failed",  
        Toast.LENGTH_LONG).show();
      }
  }
}
     

如何执行任务:在MainActivity.java文件中,您可以添加此项   你的oncreate()方法中的行

new RetrieveFeedTask().execute();
     

不要忘记将其添加到AndroidManifest.xml文件:

<uses-permission android:name="android.permission.INTERNET"/>