有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java RecycleServiceAdapter OnBindViewHolder具有空ID

我正在编写一个天气预报应用程序,我想尝试实现一个RecyclerView,这样我就可以拥有一个侧面滚动的ListView。但是,当我设置文本时,我的onBindViewHolder()会抛出NPE,因为视图ID为null,即使创建ViewHolder时ID不是null。如果能帮我找出差异,我将不胜感激。谢谢大家!

我的代码如下:

主要活动:

public class MainActivity extends AppCompatActivity {
EditText searchText;
Button searchButton;
Context context;
int count = 1; // default to one - potentially change later
RecyclerView recyclerView;

天气适配器; ArrayList天气表

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    context = this;

    recyclerView = (RecyclerView)findViewById(R.id.recyclerViewID);
    LinearLayoutManager manager = new LinearLayoutManager(context, LinearLayoutManager.HORIZONTAL, false);
    recyclerView.setLayoutManager(manager);
    adapter = new WeatherAdapter(context, weatherList);
    recyclerView.setAdapter(adapter);

    searchText = (EditText) findViewById(R.id.citySearchID);
    searchButton = (Button) findViewById(R.id.searchButtonID); 

    searchButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) { startSearch(view); }
    });
}

public void startSearch(View view) {
    JSONWeatherTask task = new JSONWeatherTask();
    String s = searchText.getText().toString();
    if (s.isEmpty()){
        Toast.makeText(this, R.string.searchError, Toast.LENGTH_SHORT).show();
        return;
    }
    try{ task.execute(s.replaceAll("\\s+", ""));
    } catch (Exception e) {
        Toast.makeText(this, R.string.searchError, Toast.LENGTH_SHORT).show();
    }
}
private class JSONWeatherTask extends AsyncTask<String, Void, ArrayList<Weather>> {
    @Override
    protected ArrayList<Weather> doInBackground(String... strings) {
        weatherList = new ArrayList<>();
        JSONObject jObj = ((new WeatherHttpClient()).getWeatherData(strings[0], count));
        try { weatherList = JSONWeatherParser.getWeather(jObj, count);
        } catch (JSONException e) { e.printStackTrace(); }
        return weatherList;
    }

    @Override
    protected void onPostExecute(ArrayList<Weather> weatherList) {
        super.onPostExecute(weatherList);
        LinearLayoutManager manager = new LinearLayoutManager(context, LinearLayoutManager.HORIZONTAL, false);
        recyclerView.setLayoutManager(manager);
        recyclerView.setItemAnimator(new DefaultItemAnimator());
        adapter = new WeatherAdapter(context, weatherList);
        recyclerView.setAdapter(adapter);
    }
}
}

适配器:

public class WeatherAdapter extends RecyclerView.Adapter<ViewHolder> {
private final Context context;
private final ArrayList<Weather> weatherList;

public WeatherAdapter(Context context, ArrayList<Weather> weatherList){
    this.context = context;
    this.weatherList = weatherList;
}
@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType){
    LayoutInflater infl = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    View v = infl.inflate(R.layout.weather_row, null);
    ViewHolder holder = new ViewHolder(v);
    return holder;
}

@Override
public void onBindViewHolder(ViewHolder holder, int pos){
    Weather weather = weatherList.get(pos);
    String[] Days = {"SUNDAY", "MONDAY", "TUESDAY", "WEDNESDAY", "THURSDAY", "FRIDAY", "SATURDAY"};
    long unixSeconds = weather.currentCondition.getDate();
    Date date = new Date(unixSeconds * 1000L);
    SimpleDateFormat dateFormat = new SimpleDateFormat("MMM dd");
    String formattedDate = dateFormat.format(date);
    Calendar cal = Calendar.getInstance();
    cal.setTimeInMillis(unixSeconds * 1000L);

    holder.dateText.setText(formattedDate);
    holder.dayText.setText(Days[cal.get(Calendar.DAY_OF_WEEK)-1]);

    // set other TextViews in the same way
}


@Override
public int getItemCount() {
    try{ return weatherList.size();
    } catch (NullPointerException e) { return 0; }
}
} 

持证人:

public class ViewHolder extends RecyclerView.ViewHolder{
TextView dateText;
TextView dayText;
// Other TextViews in the same vein

public ViewHolder (View view){
    super(view);
    TextView dateText = (TextView)view.findViewById(R.id.dateTextID);
    TextView dayText = (TextView)view.findViewById(R.id.dayTextID);
    // Other TextViews in the same vein
}

}

自定义行xml:

<LinearLayout xmlns:安卓="http://schemas.安卓.com/apk/res/安卓"
安卓:orientation="vertical"
安卓:layout_width="match_parent"
安卓:layout_height="match_parent">
<TextView
    安卓:id="@+id/dateTextID"
    安卓:layout_width="wrap_content"
    安卓:layout_height="wrap_content" />
<TextView
    安卓:id="@+id/dayTextID"
    安卓:layout_width="wrap_content"
    安卓:layout_height="wrap_content" />
<!-- Etc with more TextViews -->
</LinearLayout>

主要活动xml:

<LinearLayout
    安卓:layout_width="match_parent"
    安卓:layout_height="wrap_content"
    安卓:orientation="horizontal">
    <EditText
        安卓:id="@+id/citySearchID"
        安卓:layout_width="0dp"
        安卓:layout_height="wrap_content"
        安卓:layout_weight="3"
        安卓:inputType="text"
        安卓:hint="@string/cityHint"/>
    <Button
        安卓:id="@+id/searchButtonID"
        安卓:layout_width="0dp"
        安卓:layout_height="wrap_content"
        安卓:layout_gravity="end"
        安卓:layout_weight="1"
        安卓:text="@string/search"/>
</LinearLayout>

<安卓.support.v7.widget.RecyclerView
    安卓:id="@+id/recyclerViewID"
    安卓:layout_width="wrap_content"
    安卓:layout_height="wrap_content"/>
</LinearLayout>

日志:

java.lang.NullPointerException: Attempt to invoke virtual method 'void 安卓.widget.TextView.setText(java.lang.CharSequence)' on a null object reference
                                                                    at com.ak.niceweather.WeatherAdapter.onBindViewHolder(WeatherAdapter.java:48)
                                                                    at com.ak.niceweather.WeatherAdapter.onBindViewHolder(WeatherAdapter.java:17)
                                                                    at 安卓.support.v7.widget.RecyclerView$Adapter.onBindViewHolder(RecyclerView.java:5217)
                                                                    at 安卓.support.v7.widget.RecyclerView$Adapter.bindViewHolder(RecyclerView.java:5250)
                                                                    at 安卓.support.v7.widget.RecyclerView$Recycler.getViewForPosition(RecyclerView.java:4487)
                                                                    at 安卓.support.v7.widget.RecyclerView$Recycler.getViewForPosition(RecyclerView.java:4363)
                                                                    at 安卓.support.v7.widget.LinearLayoutManager$LayoutState.next(LinearLayoutManager.java:1961)
                                                                    at 安卓.support.v7.widget.LinearLayoutManager.layoutChunk(LinearLayoutManager.java:1370)
                                                                    at 安卓.support.v7.widget.LinearLayoutManager.fill(LinearLayoutManager.java:1333)
                                                                    at 安卓.support.v7.widget.LinearLayoutManager.onLayoutChildren(LinearLayoutManager.java:562)
                                                                    at 安卓.support.v7.widget.RecyclerView.dispatchLayout(RecyclerView.java:2900)
                                                                    at 安卓.support.v7.widget.RecyclerView.onLayout(RecyclerView.java:3071)
                                                                    at 安卓.view.View.layout(View.java:15596)
                                                                    at 安卓.view.ViewGroup.layout(ViewGroup.java:4966)
                                                                    at 安卓.widget.LinearLayout.setChildFrame(LinearLayout.java:1703)
                                                                    at 安卓.widget.LinearLayout.layoutVertical(LinearLayout.java:1557)
                                                                    at 安卓.widget.LinearLayout.onLayout(LinearLayout.java:1466)
                                                                    at 安卓.view.View.layout(View.java:15596)
                                                                    at 安卓.view.ViewGroup.layout(ViewGroup.java:4966)
                                                                    at 安卓.widget.FrameLayout.layoutChildren(FrameLayout.java:573)
                                                                    at 安卓.widget.FrameLayout.onLayout(FrameLayout.java:508)
                                                                    at 安卓.view.View.layout(View.java:15596)
                                                                    at 安卓.view.ViewGroup.layout(ViewGroup.java:4966)
                                                                    at 安卓.support.v7.widget.ActionBarOverlayLayout.onLayout(ActionBarOverlayLayout.java:435)
                                                                    at 安卓.view.View.layout(View.java:15596)
                                                                    at 安卓.view.ViewGroup.layout(ViewGroup.java:4966)
                                                                    at 安卓.widget.FrameLayout.layoutChildren(FrameLayout.java:573)
                                                                    at 安卓.widget.FrameLayout.onLayout(FrameLayout.java:508)
                                                                    at 安卓.view.View.layout(View.java:15596)
                                                                    at 安卓.view.ViewGroup.layout(ViewGroup.java:4966)
                                                                    at 安卓.widget.LinearLayout.setChildFrame(LinearLayout.java:1703)
                                                                    at 安卓.widget.LinearLayout.layoutVertical(LinearLayout.java:1557)
                                                                    at 安卓.widget.LinearLayout.onLayout(LinearLayout.java:1466)
                                                                    at 安卓.view.View.layout(View.java:15596)
                                                                    at 安卓.view.ViewGroup.layout(ViewGroup.java:4966)
                                                                    at 安卓.widget.FrameLayout.layoutChildren(FrameLayout.java:573)
                                                                    at 安卓.widget.FrameLayout.onLayout(FrameLayout.java:508)
                                                                    at 安卓.view.View.layout(View.java:15596)
                                                                    at 安卓.view.ViewGroup.layout(ViewGroup.java:4966)
                                                                    at 安卓.view.ViewRootImpl.performLayout(ViewRootImpl.java:2072)
                                                                    at 安卓.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1829)
                                                                    at 安卓.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1054)
                                                                    at 安卓.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:5779)
                                                                    at 安卓.view.Choreographer$CallbackRecord.run(Choreographer.java:767)
                                                                    at 安卓.view.Choreographer.doCallbacks(Choreographer.java:580)
                                                                    at 安卓.view.Choreographer.doFrame(Choreographer.java:550)
                                                                    at 安卓.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:753)
                                                                    at 安卓.os.Handler.handleCallback(Handler.java:739)
                                                                    at 安卓.os.Handler.dispatchMessage(Handler.java:95)
                                                                    at 安卓.os.Looper.loop(Looper.java:135)
                                                                    at 安卓.app.ActivityThread.main(ActivityThread.java:5221)
                                                                    at java.lang.reflect.Method.invoke(Native Method)
                                                                    at java.lang.reflect.Method.invoke(Method.java:372)
                                                                    at com.安卓.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
                                                                    at com.安卓.internal.os.ZygoteInit.main(ZygoteInit.java:694)

共 (1) 个答案

  1. # 1 楼答案

    您的问题在于ViewHolder.java类。在构造函数中定义和初始化新变量,而不是私有变量。因此,替换

    TextView dateText = (TextView)view.findViewById(R.id.dateTextID);
    TextView dayText = (TextView)view.findViewById(R.id.dayTextID);
    

    this.dateText = (TextView)view.findViewById(R.id.dateTextID);
    this.dayText = (TextView)view.findViewById(R.id.dayTextID);
    

    或者简单地说:

    dateText = (TextView)view.findViewById(R.id.dateTextID);
    dayText = (TextView)view.findViewById(R.id.dayTextID);