将Retrofit2与包含不同数量项目的适配器中的JSON结合使用

huangapple go评论89阅读模式
英文:

Combining Retrofit2 with JSON inside an Adapter with a Different Number of Items

问题

以下是您提供的代码的翻译部分:

我正尝试从一个 REST API 获取一些数据但我遇到了一个问题因为我有一些包含不同数量项的对象

例如

    [{7 项}, {7 项}, {6 项}...{1 项}]

它们有相同的键但问题在于在某些对象中一个或多个参数可能会丢失

我的应用程序开始运行但当我尝试向下滚动时它会崩溃我收到了以下错误

    尝试从空对象引用中读取字段 'android.widget.TextView com.example.covidapp.covidAdapter$ViewHolder.tv_activeCases'。

这是我的 `MainActivity``ListView`:

    public class MainActivity extends AppCompatActivity {
        private static final String TAG = "MainActivity";
        private ListView listView;
        private covidAdapter covidAdapter;
        private CovidApi covidApi;
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
    
            listView = (ListView) findViewById(R.id.list_view_main);
    
            Gson gson = new GsonBuilder().serializeNulls().create();
    
            Retrofit retrofit = new Retrofit.Builder().baseUrl("https://covid-19-tracking.p.rapidapi.com/")
                    .addConverterFactory(GsonConverterFactory.create(gson)).build();
    
            covidApi = retrofit.create(CovidApi.class);
    
            Call<List<covid>> call = covidApi.getInfo();
    
                call.enqueue(new Callback<List<covid>>() {
    
                @Override
                public void onResponse(Call<List<covid>> call, Response<List<covid>> response) {
    
                    if (!response.isSuccessful()){
                        return;
                    }
    
                    List<covid> covids = response.body();
    
    
                    covidAdapter = new covidAdapter((ArrayList<covid>) covids, getApplicationContext());
                    listView.setAdapter(covidAdapter);
    
                }
    
                @Override
                public void onFailure(Call<List<covid>> call, Throwable t) {
                    Toast.makeText(MainActivity.this,t.getMessage(),Toast.LENGTH_LONG).show();
                }
            });
        }
    }

这是 `Adapter`

    public class covidAdapter extends BaseAdapter {
    
        private ArrayList<covid> covidList;
        private Context context;
    
        public covidAdapter(ArrayList<covid> covidList, Context context){
            this.covidList = covidList;
            this.context = context;
        }
    
        @Override
        public int getCount() {
            return this.covidList.size();
        }
    
        @Override
        public Object getItem(int i) {
            return this.covidList.get(i);
        }
    
        @Override
        public long getItemId(int i) {
            return i;
        }
    
        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
    
            ViewHolder holder = null;
    
            if (convertView == null) {
    
                LayoutInflater inf = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                convertView = inf.inflate(R.layout.template, null);
    
                holder = new ViewHolder();
    
                holder.tv_activeCases =(TextView)convertView.findViewById(R.id.textview_active_cases);
                holder.tv_country =(TextView)convertView.findViewById(R.id.textview_country);
                //holder.tv_lastUpdate =(TextView)convertView.findViewById(R.id.textview_last_update);
                holder.tv_newCases =(TextView)convertView.findViewById(R.id.textview_new_cases);
                holder.tv_newDeaths =(TextView)convertView.findViewById(R.id.textview_new_deaths);
                holder.tv_totalCases =(TextView)convertView.findViewById(R.id.textview_total_cases);
                holder.tv_totalDeaths =(TextView)convertView.findViewById(R.id.textview_total_deaths);
                holder.tv_totalRecovered =(TextView)convertView.findViewById(R.id.textview_total_recovered);
    
    
            } else {
                holder = (ViewHolder) convertView.getTag();
            }
    
            covid covid = covidList.get(position);
    
            if ( covidList.size() < 0){
                System.out.println("No dps key");
    
            }else {
    
                holder.tv_activeCases.setText("Active Cases: " + covid.getActive());
                holder.tv_country.setText("Country: " + covid.getCountry());
                // holder.tv_lastUpdate.setText("Last Update: " + covid.getLastUpdate());
                holder.tv_newDeaths.setText("New Deaths: " + covid.getNewDeaths());
                holder.tv_newCases.setText("New Cases: " + covid.getNewCases());
                holder.tv_totalRecovered.setText("Recovered: " + covid.getRecovered());
                holder.tv_totalDeaths.setText("Deaths: " + covid.getTotalDeaths());
                holder.tv_totalCases.setText("Total Cases: " + covid.getTotalCases());
            }
            return convertView;
    
        }
    
    
        private static class ViewHolder{
            public TextView tv_country, tv_activeCases,  tv_newCases, tv_newDeaths, tv_totalCases, tv_totalDeaths, tv_totalRecovered;
        }
    }

我将不胜感激任何帮助
英文:

I am trying to get some data from a rest API, but I have a problem because I have some objects with a different numbers of items.

For example:

[{7 items}, {7 items}, {6 items}...{1 item}]

They have the same key, but the problem is in some objects, one or more arguments can be missing.

My app starts running, but when I try to scroll down it crashes. I have am receiving this error:

Attempt to read from field &#39;android.widget.TextView com.example.covidapp.covidAdapter$ViewHolder.tv_activeCases&#39; on a null object reference. 

Here is my MainActivity and ListView:

public class MainActivity extends AppCompatActivity {
private static final String TAG = &quot;MainActivity&quot;;
private ListView listView;
private covidAdapter covidAdapter;
private CovidApi covidApi;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = (ListView) findViewById(R.id.list_view_main);
Gson gson = new GsonBuilder().serializeNulls().create();
Retrofit retrofit = new Retrofit.Builder().baseUrl(&quot;https://covid-19-tracking.p.rapidapi.com/&quot;)
.addConverterFactory(GsonConverterFactory.create(gson)).build();
covidApi = retrofit.create(CovidApi.class);
Call&lt;List&lt;covid&gt;&gt; call = covidApi.getInfo();
call.enqueue(new Callback&lt;List&lt;covid&gt;&gt;() {
@Override
public void onResponse(Call&lt;List&lt;covid&gt;&gt; call, Response&lt;List&lt;covid&gt;&gt; response) {
if (!response.isSuccessful()){
return;
}
List&lt;covid&gt; covids = response.body();
covidAdapter = new covidAdapter((ArrayList&lt;covid&gt;) covids, getApplicationContext());
listView.setAdapter(covidAdapter);
}
@Override
public void onFailure(Call&lt;List&lt;covid&gt;&gt; call, Throwable t) {
Toast.makeText(MainActivity.this,t.getMessage(),Toast.LENGTH_LONG).show();
}
});
}
}

This is the Adapter class:

public class covidAdapter extends BaseAdapter {
private ArrayList&lt;covid&gt; covidList;
private Context context;
public covidAdapter(ArrayList&lt;covid&gt; covidList, Context context){
this.covidList = covidList;
this.context = context;
}
@Override
public int getCount() {
return this.covidList.size();
}
@Override
public Object getItem(int i) {
return this.covidList.get(i);
}
@Override
public long getItemId(int i) {
return i;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
if (convertView == null) {
LayoutInflater inf = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inf.inflate(R.layout.template, null);
holder = new ViewHolder();
holder.tv_activeCases =(TextView)convertView.findViewById(R.id.textview_active_cases);
holder.tv_country =(TextView)convertView.findViewById(R.id.textview_country);
//holder.tv_lastUpdate =(TextView)convertView.findViewById(R.id.textview_last_update);
holder.tv_newCases =(TextView)convertView.findViewById(R.id.textview_new_cases);
holder.tv_newDeaths =(TextView)convertView.findViewById(R.id.textview_new_deaths);
holder.tv_totalCases =(TextView)convertView.findViewById(R.id.textview_total_cases);
holder.tv_totalDeaths =(TextView)convertView.findViewById(R.id.textview_total_deaths);
holder.tv_totalRecovered =(TextView)convertView.findViewById(R.id.textview_total_recovered);
} else {
holder = (ViewHolder) convertView.getTag();
}
covid covid = covidList.get(position);
if ( covidList.size() &lt; 0){
System.out.println(&quot;No dps key&quot;);
}else {
holder.tv_activeCases.setText(&quot;Active Cases: &quot; + covid.getActive());
holder.tv_country.setText(&quot;Country: &quot; + covid.getCountry());
// holder.tv_lastUpdate.setText(&quot;Last Update: &quot; + covid.getLastUpdate());
holder.tv_newDeaths.setText(&quot;New Deaths: &quot; + covid.getNewDeaths());
holder.tv_newCases.setText(&quot;New Cases: &quot; + covid.getNewCases());
holder.tv_totalRecovered.setText(&quot;Recovered: &quot; + covid.getRecovered());
holder.tv_totalDeaths.setText(&quot;Deaths: &quot; + covid.getTotalDeaths());
holder.tv_totalCases.setText(&quot;Total Cases: &quot; + covid.getTotalCases());
}
return convertView;
}
private static class ViewHolder{
public TextView tv_country, tv_activeCases,  tv_newCases, tv_newDeaths, tv_totalCases, tv_totalDeaths, tv_totalRecovered;
}
}

I would appreciate any help.

答案1

得分: 1

为了在下次调用getView()时能够检索到持有者,请进行以下存储:

convertView.setTag(holder)
英文:

To store the holder so that it can be retrieved when getView() is called again:

convertView.setTag(holder) 

huangapple
  • 本文由 发表于 2020年7月29日 00:31:45
  • 转载请务必保留本文链接:https://go.coder-hub.com/63138754.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定