This question already has answers here:
What is the reason behind “non-static method cannot be referenced from a static context”? [duplicate]
                                
                                    (13个回答)
                                
                        
                                4年前关闭。
            
                    
我正在调用php脚本,该脚本从android lass访问我的数据库。班级在下面;

public class pk_http {

    // Progress Dialog
    private ProgressDialog qDialog;

    // JSON parser class
    JSONParser jParser = new JSONParser();

    class phpCall extends AsyncTask<String, String, String> {
        @Override
        protected String doInBackground(String... args) {
            // Building Parameters
            String url = args[0];
            List<NameValuePair> params = new ArrayList<NameValuePair>();
            // getting JSON string from URL
            JSONObject json = jParser.makeHttpRequest(url, "GET",params);



            return null;
        }
   }


现在,当我从调用类(调用类不扩展Activity btw)中调用该方法时;

public static ArrayList<String> getLoginTileDataArray(Context c)
{
    //CODE STUB: HTTP GET RETURNS THE FOLLOWING STRING
    String result = pk_http.phpCall.execute("http://myUrl/phpFile.php");
.
.
.


我有一个错误预编译,说:


  非静态方法'execute(Params ...)不能从
  静态上下文。


如果我删除“ stst”没有变化。我是否正确调用异步方法?

最佳答案

您不能像这样调用execute,它不是静态方法。使用new

public static ArrayList<String> getLoginTileDataArray(Context c)
{
    //CODE STUB: HTTP GET RETURNS THE FOLLOWING STRING
    (new pk_http.phpCall()).execute("http://myUrl/phpFile.php");
.
.
.


更新

您的代码有错误,您错过了}中的一个pk_http。您需要搜索有关AsyncTask的更多信息,在doInBackground()中执行长期任务,并将结果从onPostExecute()处理到UI线程

这是简单的代码:

public class pk_http {

    public void execute(String s) {
        (new phpCall()).execute(s);
    }

    // Progress Dialog
    private ProgressDialog qDialog;

    // JSON parser class
    JSONParser jParser = new JSONParser();

    class phpCall extends AsyncTask<String, String, String> {
        @Override
        protected String doInBackground(String... args) {
            // Building Parameters
            String url = args[0];
            List<NameValuePair> params = new ArrayList<NameValuePair>();
            // getting JSON string from URL
            JSONObject json = jParser.makeHttpRequest(url, "GET", params);

            // TODO: return your result here, this will pass to onPostExecute(String)
            return null;
        }

        @Override
        protected void onPostExecute(String s) {
            // TODO: This is in UI thread, handle your result from doInBackground().
        }
    }
}


也许在MainActivity中:

public static ArrayList<String> getLoginTileDataArray(Context c)
{
    //CODE STUB: HTTP GET RETURNS THE FOLLOWING STRING
    (new pk_http()).execute("http://myUrl/phpFile.php");
.
.
.

10-07 16:14
查看更多