我有这个错误
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中看到写作
答案 0 :(得分:1)
您已将此方法声明为静态。
您的代码行
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);
答案 1 :(得分:0)
如果你有静态方法,你不能调用非静态方法。静态方法“存在”没有类的实例。非静态方法是类实例的“部分”。
Pass View,您要在其中查找View作为静态方法的参数。
public static String send(String query, View view) {
....
view.findViewById(R.id.some_id);
....
}