从另一个类调用的findViewById有时会返回null

时间:2017-01-23 01:31:37

标签: java android findviewbyid

我的应用中遇到了一个奇怪的问题。我试图从另一个类(不是Activity)更新TextViews。我可以通过调用重载的//Page stuff... at the very bottom of my MVC Razor view //.. //Append my custom CSS styles @section stylesSection { <styles> // is this not correct, why does the browser not load this?? <link href="@Url.Action("GetDynamicCssBlock", "DynamicCssCtlr")" rel="stylesheet" type="text/css" /> //updated with type type="text/css" </styles> } 方法以两种方式完成它:

这就是我从MainActivity中调用它们的方式: 这种方式很好。

Controller which serves the raw CSS content

这个没有:

public class DynamicCssCtlr: Controller
{
    public ContentResult GetDynamicCssBlock()
    {
        //string cssBlock = GetCssBodyFromDb(); 
        //simplified...
        string cssBlock = @".pDiv { background-color: yellow; }";
        return Content(cssBlock , "text/css");
    }
}
从SearchView收到

getUpdate()

public boolean onOptionsItemSelected(MenuItem item) { int id = item.getItemId(); switch (id) { case R.id.menu_location_button: if (this.cwu == null) this.cwu = new CurrentWeatherUpdater(this); this.cwu.getUpdate(lf.getLongitude(), lf.getLatitude()); break; . . . } return super.onOptionsItemSelected(item); } private void handleIntent(Intent intent) { if (Intent.ACTION_SEARCH.equals(intent.getAction())) { String query = intent.getStringExtra(SearchManager.QUERY); if (this.cwu == null) this.cwu = new CurrentWeatherUpdater(this); this.cwu.getUpdate(query); } }

中声明

这是我的CurrentWeatherUpdater类:

query

}

CurrentWeatherUpdater cwu;MainActivity.java

中声明

基本上,当我从public class CurrentWeatherUpdater extends Updater{ private TextView city; private TextView temp; private TextView desc; private TextView humidity; private TextView pressure; private TextView wind; public CurrentWeatherUpdater(Context context) { super(context); this.city = (TextView) ((Activity)context).findViewById(R.id.city_name); this.temp = (TextView) ((Activity)context).findViewById(R.id.current_temperature); this.desc = (TextView) ((Activity)context).findViewById(R.id.current_weather_desc); this.humidity = (TextView) ((Activity)context).findViewById(R.id.humidity); this.pressure = (TextView) ((Activity)context).findViewById(R.id.pressure); this.wind = (TextView) ((Activity)context).findViewById(R.id.wind); } public void getUpdate(String cityName) { updateView(super.getUpdate(Updater.REQUEST_WEATHER, cityName)); } public void getUpdate(double longitude, double latitude) { updateView(super.getUpdate(Updater.REQUEST_WEATHER, longitude, latitude)); } private void updateView(JSONObject result) { try { if (result.getInt("cod") == 200) { this.city.setText(result.getString("name")); JSONObject main = result.getJSONObject("main"); temp.setText(Integer.toString((int) Math.round(Double.parseDouble(main.getString("temp")))) + "\u00b0"); pressure.setText(main.getString("pressure") + "hPa"); humidity.setText(main.getString("humidity") + "%"); JSONObject windInfo = result.getJSONObject("wind"); wind.setText(windInfo.getString("speed") + "m/s"); JSONArray weatherArray = result.getJSONArray("weather"); JSONObject weather = weatherArray.getJSONObject(0); desc.setText(weather.getString("main")); } if (result.getInt("cod") == 404) { Toast.makeText(mContext, "Location not found", Toast.LENGTH_SHORT).show(); } } catch (JSONException e) { e.printStackTrace(); } } 调用CurrentWeatherUpdater cwu;构造函数时,它运行正常。但是当我从MainActivity.java调用它时,即使CurrentWeatherUpdater(this)指向onOptionsItemSelected就像在另一个中一样,但没有一个字段(doSearchcontext,等号被分配了一个值,而MainActivity方法在city

temp下火了
updateView

即使首次从NullPointerException调用并且this.city.setText(result.getString("name"))对象已经创建,java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference 也会评估为onOptionsItemSelected,并且会创建新对象。

1 个答案:

答案 0 :(得分:0)

您可以使用LocalBroadcastManager将您的数据广播到另一个类

您可以通过

将数据设置为LocalBroadcastManager
Intent intent = new Intent("myFunction");
                // add data
                intent.putExtra("variable1", "Data1");
                intent.putExtra("variable2", "Data2");
                intent.putExtra("variable3", "Data3");
                LocalBroadcastManager.getInstance(this).sendBroadcast(intent);

现在,在定义更新视图的类中,输入以下代码:

private BroadcastReceiver mMessageReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            // Extract data included in the Intent
            String t = intent.getStringExtra("variable1");
            String t1 = intent.getStringExtra("variable2");
            String t2 = intent.getStringExtra("variable3");
            //Updating textview function
            updateTheTextView(t, t1, t2);
        }
    };
    @Override
    public void onResume() {
        super.onResume();
        LocalBroadcastManager.getInstance(this.getActivity()).registerReceiver(mMessageReceiver,
                new IntentFilter("myFunction"));
    }

    @Override
    public void onPause() {
        super.onPause();
        LocalBroadcastManager.getInstance(this.getActivity()).unregisterReceiver(mMessageReceiver);
    }

我不确定这对你有帮助!但这就是我设法将数据发送到另一个类中定义的texviews的方法。