当前位置: 代码迷 >> Android >> 无法静态引用非静态方法findviewbyid(int)TextView
  详细解决方案

无法静态引用非静态方法findviewbyid(int)TextView

热度:88   发布时间:2023-08-04 12:44:10.0

我有这个错误
Cannot make a static reference to the non-static method findViewById(int) from the type Activity" in a second activity

第二次活动代码:

public class sendQuery extends main  {
/////////// Public method to send Query ///////////
public static String send(String query,Activity main) {
    String result = "0";
    InputStream is = null;
    String weekDayVal=null;
    //the query to send
    ArrayList<NameValuePair> querySend = new ArrayList<NameValuePair>();

    querySend.add(new BasicNameValuePair("querySend",query));

    //http post
    try{
        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost("http://locali.altervista.org/php/locali.php");
        httppost.setEntity(new UrlEncodedFormEntity(querySend));
        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);
        StringBuilder sb = new StringBuilder();
        String line = null;
        while ((line = reader.readLine()) != null) {
            sb.append(line + "\n");
        }
        is.close();
        result=sb.toString();
        try{
            JSONArray weekDetails = new JSONArray ( result); // Your response string
            for(int index=0;index < weekDetails.length();index++)
            {
            JSONObject tempWeekDetail = weekDetails.getJSONObject(index);
            weekDayVal = tempWeekDetail.getString("Lunedi");// Value for Monday
            //added this Log which you can view from LogCat. also changed above variable name
            Log.i("Resp Value","Moday Value "+weekDayVal);
            }
            }catch(Exception e)
            {

                TextView text = (TextView) main.findViewById(R.id.textView10);
                text.setText(weekDayVal);
            }
    }catch(Exception e){
        Log.e("log_tag", "Error converting result: "+e.toString());
    }

    Log.i("SendQUERY", result);
    return result;
}
  }

我是否首先将值传递给主要活动?
为什么我会收到此错误?
请帮我! 谢谢

编辑

我有修改代码,现在正确吗? 因为我看不到TextView中的文字

您已将此方法声明为静态的。

您的代码行

 TextView text = (TextView) findViewById(R.id.textView10);

和这个

findViewById(int id)

来自Activity类,该类需要一个此类的实例才能使用。

解决方案

您可以做的是在方法中添加一个参数,例如:

public static String send(String query,Activity yourActivity)

然后使用

 TextView text = (TextView) yourActivity.findViewById(R.id.textView10);

如果您有静态方法,则不能调用非静态方法。 没有类实例的静态方法“存在”。 非静态方法是类实例的“一部分”。

传递视图,您要在其中查找视图作为静态方法的参数。

public static String send(String query, View view) {
   ....

   view.findViewById(R.id.some_id);
   ....
}
  相关解决方案