Android改造:在Recyclerview中显示JSON数据

Android改造:在Recyclerview中显示JSON数据,android,android-recyclerview,retrofit2,Android,Android Recyclerview,Retrofit2,我在如何向回收器视图显示json数据方面遇到了问题。这是我的JSON数据,我想在单个回收器视图中显示“匹配”和“替换”对象值。我已经使用了一些其他的json结构,但是这个对我来说有点复杂,所以我不知道该怎么做 { "software": { "name": "GrammarBot", "version": "4.3-SNAPSHOT", "apiVersion": 1, "premium": false, "premiumHint": "Yo

我在如何向回收器视图显示json数据方面遇到了问题。这是我的JSON数据,我想在单个回收器视图中显示“匹配”和“替换”对象值。我已经使用了一些其他的json结构,但是这个对我来说有点复杂,所以我不知道该怎么做

{
  "software": {
     "name": "GrammarBot",
     "version": "4.3-SNAPSHOT",
     "apiVersion": 1,
     "premium": false,
     "premiumHint": "You might be missing errors only the Premium version can find. Upgrade to see what you're missing.",
     "status": ""
      },
  "warnings": {
     "incompleteResults": false
     },
  "language": {
     "name": "English",
     "code": "en-US",
     "detectedLanguage": {
        "name": "English (US)",
        "code": "en-US"
        }
    },
  "matches": [
   {
     "message": "Statistics suggests that 'there' (as in 'Is there an answer?') might be the correct word here, not 'their' (as in 'It’s not their fault.'). Please check.",
     "shortMessage": "",
     "replacements": [
        {
        "value": "there"
        }
      ],
    "offset": 27,
    "length": 5,
    "context": {
       "text": "I can't remember how to go their.",
       "offset": 27,
       "length": 5
       },
    "sentence": "I can't remember how to go their.",
    "type": {
       "typeName": "Other"
        },
    "rule": {
       "id": "CONFUSION_RULE",
       "description": "Statistically detect wrong use of words that are easily confused",
       "issueType": "non-conformance",
       "category": {
           "id": "TYPOS",
            "name": "Possible Typo"
            }
        }
     }
   ]
}
我想要的RecyclerView将如下所示:

匹配1,
替换件1,
第二场,
第三场,
替换件2

这是我的密码:

服务(接口)

适配器

public class ResultAdapter extends RecyclerView.Adapter<ResultAdapter.ResultViewHolder>{

Context mContext;
ArrayList<Match> matchList = new ArrayList<>();
ArrayList<Replacement> replacementList = new ArrayList<>();

public ResultAdapter (Context mContext, ArrayList<Match> matchList){
    this.matchList = matchList;
    this.mContext = mContext;
}


@Override
public ResultViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
    View view = LayoutInflater.from(viewGroup.getContext())
            .inflate(R.layout.result_card, viewGroup, false);
    return new ResultViewHolder(view);
}

@Override
public void onBindViewHolder(ResultViewHolder resultViewHolder, int i) {

    Match match = matchList.get(i);
    resultViewHolder.mBadErrorTextView.setText(match.getSentence());
    resultViewHolder.mBetterErrorTextView.setText(match.getMessage());
}
 //viewholder and getcount
}
公共类ResultAdapter扩展了RecyclerView.Adapter{
语境;
ArrayList匹配列表=新的ArrayList();
ArrayList replacementList=新建ArrayList();
公共结果适配器(上下文mContext、ArrayList匹配列表){
this.matchList=匹配列表;
this.mContext=mContext;
}
@凌驾
public ResultViewHolder onCreateViewHolder(视图组视图组,int i){
View=LayoutFlater.from(viewGroup.getContext())
.充气(R.layout.result_卡、视图组、假);
返回新的ResultViewHolder(视图);
}
@凌驾
BindViewHolder上的公共无效(ResultViewHolder ResultViewHolder,int i){
Match=matchList.get(i);
resultViewHolder.mBadErrorTextView.setText(match.get句子());
resultViewHolder.mBetterErrorTextView.setText(match.getMessage());
}
//viewholder和getcount
}
片段类

public class Tab1Fragment_GrammarChecker extends Fragment {

@BindView(R.id.InputTextEditText)
EditText mInputGrammarEditText;

@BindView(R.id.ErrorsRecyclerView)
RecyclerView mErrorsRecyclerView;

public static String userInput;
public String apiKey = "";
public String language = "en-US";

@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.tab1_grammar_checker, container, false);

    ButterKnife.bind(this, view);
    RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getContext());
    mErrorsRecyclerView.setLayoutManager(layoutManager);
    mErrorsRecyclerView.setItemAnimator(new DefaultItemAnimator());

    return view;
}

//onClick

public void loadJson(){
    Retrofit.Builder builder = new Retrofit.Builder()
            .baseUrl("http://api.grammarbot.io")
            .addConverterFactory(GsonConverterFactory.create());

    Retrofit retrofit = builder.build();
    Service serviceAPI = retrofit.create(Service.class);
    Call<GrammarBotMain> loadErrorsCall = serviceAPI.readErrorsGrammar(apiKey, userInput, language);

    final ProgressDialog progressDialog;
    progressDialog = new ProgressDialog(getActivity());
    progressDialog.setMax(100);
    progressDialog.setMessage(getResources().getString(R.string.progressDialogLoadingResultMessage));
    progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
    progressDialog.show();

    loadErrorsCall.enqueue(new Callback<GrammarBotMain>() {
        @Override
        public void onResponse(Call<GrammarBotMain> call, Response<GrammarBotMain> response) {
            progressDialog.dismiss();
            GrammarBotMain grammarBotMain = response.body();

                ArrayList<Match> matches = grammarBotMain.getMatches();

                mErrorsRecyclerView.setAdapter(new ResultAdapter(getContext(), matches));
                Log.i("Fragment", "SUCCESS");
            }

        @Override
        public void onFailure(Call<GrammarBotMain> call, Throwable t) {
            progressDialog.dismiss();
            Log.e("Error: ", t.getMessage());
        }
    });
}

}
public类Tab1Fragment\u GrammarChecker扩展片段{
@BindView(R.id.InputExtEditText)
EditText-mInputGrammarEditText;
@BindView(R.id.ErrorsRecyclerView)
回收视图MERRORSRECELVIEW;
公共静态字符串用户输入;
公共字符串apiKey=“”;
公共字符串语言=“en US”;
@凌驾
创建视图时的公共视图(LayoutFlater充气机、@Nullable ViewGroup容器、@Nullable Bundle savedInstanceState){
视图=充气机。充气(R.layout.tab1\u语法检查器,容器,错误);
ButterKnife.bind(这个,视图);
RecyclerView.LayoutManager LayoutManager=新的LinearLayoutManager(getContext());
merrorserecyclerview.setLayoutManager(layoutManager);
setItemAnimator(新的DefaultItemAnimator());
返回视图;
}
//onClick
公共void loadJson(){
reformation.Builder=新的reformation.Builder()
.baseUrl(“http://api.grammarbot.io")
.addConverterFactory(GsonConverterFactory.create());
改装改装=builder.build();
Service serviceAPI=改装.create(Service.class);
调用loadErrorsCall=serviceAPI.readErrorsGrammar(apiKey,userInput,language);
最终进度对话;
progressDialog=新建progressDialog(getActivity());
progressDialog.setMax(100);
setMessage(getResources().getString(R.string.progressDialogLoadingResultMessage));
progressDialog.setProgressStyle(progressDialog.STYLE_微调器);
progressDialog.show();
loadErrorsCall.enqueue(新的回调(){
@凌驾
公共void onResponse(调用、响应){
progressDialog.disclose();
GrammarBotMain-GrammarBotMain=response.body();
ArrayList matches=grammarBotMain.getMatches();
setAdapter(新的ResultAdapter(getContext(),matches));
Log.i(“片段”、“成功”);
}
@凌驾
失败时公共无效(调用调用,可丢弃的t){
progressDialog.disclose();
Log.e(“错误:,t.getMessage());
}
});
}
}

我不知道您是如何决定维持列表顺序的。但如果要在同一个RecyclerView中混合两种类型的对象值,则可以执行以下步骤:

1) 在适配器中使用
对象
的数组列表,而不是
匹配
替换
数组列表。根据您所需的顺序,将您的
匹配对象
替换对象
添加到该对象列表中

ArrayList<Object> data = new ArrayList<>();
data.add(match1);
data.add(replacement1);
data.add(match2);

感谢您提供详细信息,但您的要求不明确。对于每个
match
对象,JSON结构似乎都有
match
对象数组和
replacement
对象数组。你能澄清一下吗?@sourav.bh嗨!没错,匹配是一个对象数组,其中该对象的一部分是替换数组。抱歉,如果它有点让人困惑,因为它已经是一个结构化的JSON,因为它来自我现在正在使用的API。这不是让我困惑的地方。我无法理解您的需求,比如是什么阻止您使用此JSON结构创建RecyclerView。请更具体地说明您的问题。@sourav.bh抱歉。我的意思是,我想在同一个recyclerview中同时显示一些匹配对象和替换对象,但我不知道如何执行或调用。好的,假设我们有一个recyclerview示例,其中行以逗号分隔的字符串表示。您想要哪一个:
match1+replacement1,match1+replacement2,match2+replacement2,…
match1,replacement1,match2,match3,replacement2,…
public class Replacement {

    @SerializedName("value")
    private String value;

    //--getter and setter
 }
public class ResultAdapter extends RecyclerView.Adapter<ResultAdapter.ResultViewHolder>{

Context mContext;
ArrayList<Match> matchList = new ArrayList<>();
ArrayList<Replacement> replacementList = new ArrayList<>();

public ResultAdapter (Context mContext, ArrayList<Match> matchList){
    this.matchList = matchList;
    this.mContext = mContext;
}


@Override
public ResultViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
    View view = LayoutInflater.from(viewGroup.getContext())
            .inflate(R.layout.result_card, viewGroup, false);
    return new ResultViewHolder(view);
}

@Override
public void onBindViewHolder(ResultViewHolder resultViewHolder, int i) {

    Match match = matchList.get(i);
    resultViewHolder.mBadErrorTextView.setText(match.getSentence());
    resultViewHolder.mBetterErrorTextView.setText(match.getMessage());
}
 //viewholder and getcount
}
public class Tab1Fragment_GrammarChecker extends Fragment {

@BindView(R.id.InputTextEditText)
EditText mInputGrammarEditText;

@BindView(R.id.ErrorsRecyclerView)
RecyclerView mErrorsRecyclerView;

public static String userInput;
public String apiKey = "";
public String language = "en-US";

@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.tab1_grammar_checker, container, false);

    ButterKnife.bind(this, view);
    RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getContext());
    mErrorsRecyclerView.setLayoutManager(layoutManager);
    mErrorsRecyclerView.setItemAnimator(new DefaultItemAnimator());

    return view;
}

//onClick

public void loadJson(){
    Retrofit.Builder builder = new Retrofit.Builder()
            .baseUrl("http://api.grammarbot.io")
            .addConverterFactory(GsonConverterFactory.create());

    Retrofit retrofit = builder.build();
    Service serviceAPI = retrofit.create(Service.class);
    Call<GrammarBotMain> loadErrorsCall = serviceAPI.readErrorsGrammar(apiKey, userInput, language);

    final ProgressDialog progressDialog;
    progressDialog = new ProgressDialog(getActivity());
    progressDialog.setMax(100);
    progressDialog.setMessage(getResources().getString(R.string.progressDialogLoadingResultMessage));
    progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
    progressDialog.show();

    loadErrorsCall.enqueue(new Callback<GrammarBotMain>() {
        @Override
        public void onResponse(Call<GrammarBotMain> call, Response<GrammarBotMain> response) {
            progressDialog.dismiss();
            GrammarBotMain grammarBotMain = response.body();

                ArrayList<Match> matches = grammarBotMain.getMatches();

                mErrorsRecyclerView.setAdapter(new ResultAdapter(getContext(), matches));
                Log.i("Fragment", "SUCCESS");
            }

        @Override
        public void onFailure(Call<GrammarBotMain> call, Throwable t) {
            progressDialog.dismiss();
            Log.e("Error: ", t.getMessage());
        }
    });
}

}
ArrayList<Object> data = new ArrayList<>();
data.add(match1);
data.add(replacement1);
data.add(match2);
int VIEW_TYPE_MATCH = 1;
int VIEW_TYPE_REPLQCEMENT = 2;

private int getViewType(int position) {
   Object value = data.get(position);
   if (value instanceof Match) return VIEW_TYPE_MATCH;
   else return VIEW_TYPE_REPLQCEMENT;
}