我有像这样的JSON
{
"questions": [{
"Creator_User_ID": "140110",
"Advisor_User_ID": null,
"Question_Video_Title": "media",
"playing_time": null,
"Created": "2016-01-20T00:00:00",
"Modified": "2016-01-20T00:00:00",
"question_video_playingTime": "0:4",
"Answer_Video_Title": null,
"Answer_Video_Link": null,
"answer_video_playingtime": null,
"StatusName": "Approved",
"QuestionID": 182
},
{
"Creator_User_ID": "140110",
"Advisor_User_ID": null,
"Question_Video_Title": "media",
"playing_time": null,
"Created": "2016-01-20T00:00:00",
"Modified": "2016-01-20T00:00:00",
"question_video_playingTime": "0:4",
"Answer_Video_Title": null,
"Answer_Video_Link": null,
"answer_video_playingtime": null,
"StatusName": "Approved",
"QuestionID": 182
}
]
}
我添加了让我们假设的值" Answer_Video_Link"进入Arraylist例如arraylistAnswerLink,所以输出将像[null,null,.... so so] 在BaseAdapter中设置此arraylist时,要实现的功能是:
if(arraylistAnswerLink.get(position).contains(null)){
button.setVisibilty(View.Visible)}
else{
button.setVisibilty(View.Gone)
}
这是我的json解析代码
jsonInnerArray = jsonInnerObject.getJSONArray("questions");
for (int j = 0; j <= jsonInnerArray.length(); j++) {
jsonArrayObject = jsonInnerArray.getJSONObject(j);
Question_Video_Title = jsonArrayObject.getString("Question_Video_Title");
question_video_playingTime = jsonArrayObject.getString("question_video_playingTime");
String Designation1 = jsonArrayObject.getString("Designation");
full_name = jsonArrayObject.getString("User_name"); Question_Video_Link = jsonArrayObject.getString("Question_Video_Link");
Answer_Video_Link = jsonArrayObject.getString("Answer_Video_Link");
QuestionID = jsonArrayObject.getString("QuestionID");
video_thumbnail=jsonArrayObject.getString("video_thumbnail"); }
在列表的特定位置获取null时,数组索引的错误超出范围。
请检查我的代码
public class UnRepliedFragment_ extends Fragment {
private static final String ARG_PARAM1 = "param1";
private String mParam1;
View rootview;
private RecyclerView mRecyclerView;
private RecyclerView.Adapter mAdapter;
private RecyclerView.LayoutManager mLayoutManager;
// ArrayList<Integer> arrayListImage;
ArrayList<Integer> arrayListVideos;
File mediaFile, vPath;
String song_dur_str, st, vst, vst1, orginalName;
String timestamp, advisorID, token;
int VIDEO_CAPTURE = 1000;
ProgressDialog dlg;
SharedPreferences preferences;
ArrayList<String> arrayListName, videoName, singleVideoName, questionLink, arrquestion_video_playingTime, answerLinkEmpty;
String FirstName, durationofVideo, User_name, Question_Video_Title, Question_Video_Link, shorted, cmpsort, question_video_playingTime, path, QuestionID;
int advisor, pos;
private List<Modals> feedsList;
Uri mediaPath;
PutObjectRequest por;
String url = "https://s3-us-west-1.amazonaws.com/talentedge1";
private static AmazonS3Client sS3Client;
Uri fileUri;
static Object Answer_Video_Link;
ArrayList<Object> answerLink;
Object item;
JSONObject jsonObject,innerObject;
JSONArray innerArray;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
rootview = inflater.inflate(R.layout.fragment_unreplied, container, false);
dlg = new ProgressDialog(getActivity());
preferences = PreferenceManager.getDefaultSharedPreferences(getActivity());
token = preferences.getString(AppConstant.TOKEN, "");
advisorID = preferences.getString(AppConstant.USERID, "");
arrayListVideos = new ArrayList<>();
feedsList = new ArrayList<>();
arrayListName = new ArrayList<>();
videoName = new ArrayList<>();
questionLink = new ArrayList<>();
arrquestion_video_playingTime = new ArrayList<>();
answerLink = new ArrayList<>();
singleVideoName = new ArrayList<>();
/*
API hit
*/
new Proadvice().execute();
mRecyclerView = (RecyclerView) rootview.findViewById(R.id.recycler_view_unreplied);
mRecyclerView.setHasFixedSize(true);
mLayoutManager = new LinearLayoutManager(getActivity());
mRecyclerView.setLayoutManager(mLayoutManager);
return rootview;
}
/*
Adapter class
*/
class MyRecyclerViewAdapter extends RecyclerView.Adapter<MyRecyclerViewAdapter.ViewHolder> {
private Context mContext;
private LayoutInflater inflater;
ArrayList<String> videoName;
ArrayList<String> questionLink;
ArrayList<String> arrquestion_video_playingTime;
ArrayList<Object> answerLink;
public MyRecyclerViewAdapter(ArrayList<String> videoName, ArrayList<String> questionLink, ArrayList<Object> answerLink, ArrayList<String> arrquestion_video_playingTime) {
this.videoName = videoName;
this.questionLink = questionLink;
this.answerLink = answerLink;
this.arrquestion_video_playingTime = arrquestion_video_playingTime;
}
@Override
public MyRecyclerViewAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.unreplied_list_row, parent, false);
ViewHolder viewHolder = new ViewHolder(view);
return viewHolder;
}
@Override
public void onBindViewHolder(MyRecyclerViewAdapter.ViewHolder holder, int position) {
holder.txt_it_author.setText(arrayListName.get(position));
holder.textView.setText(arrquestion_video_playingTime.get(position));
holder.txt_it_Title.setText(videoName.get(position));
for (Object value : answerLink) {
if (value != null) {
System.out.println("Not Null" + value);
} else {
System.out.println("Null" + value);
}
}
}
@Override
public int getItemCount() {
return videoName.size();
}
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
ImageView imageView;
TextView textView, txt_it_author, txt_it_Title, share;
RippleView relativeLayout;
LinearLayout imageButtonAnswer;
FrameLayout frameLayout;
public ViewHolder(View itemView) {
super(itemView);
relativeLayout = (RippleView) itemView.findViewById(R.id.relative_video_it);
relativeLayout.setOnClickListener(this);
imageView = (ImageView) itemView.findViewById(R.id.img_it_Video);
textView = (TextView) itemView.findViewById(R.id.txt_it_duration);
txt_it_author = (TextView) itemView.findViewById(R.id.txt_it_author);
txt_it_Title = (TextView) itemView.findViewById(R.id.txt_it_Title);
imageButtonAnswer = (LinearLayout) itemView.findViewById(R.id.img_answers);
frameLayout = (FrameLayout) itemView.findViewById(R.id.relative_play_img);
imageButtonAnswer.setOnClickListener(this);
}
@Override
public void onClick(View v) {
int position = getLayoutPosition();
int id = v.getId();
switch (id) {
case R.id.relative_play_img:
Intent i = new Intent(getActivity(), Video_ViewAct.class);
i.putExtra("position", "" + position);
i.putExtra("Question_Video_Link", questionLink.get(position));
// i.putExtra("Answer_Video_Link", answerLink.get(position));
startActivity(i);
break;
}
}
}
}
class Proadvice extends AsyncTask<String, Integer, String> {
@Override
protected String doInBackground(String... params) {
return doInLoginProadvice();
}
@Override
protected void onPreExecute() {
super.onPreExecute();
dlg.setMessage("Loading.....");
dlg.setCancelable(false);
dlg.show();
}
@Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
dlg.dismiss();
if (result.contains("true")) {
updateUIProadvice(result);
}
}
}
private void updateUIProadvice(String result) {
try {
jsonObject = new JSONObject(result);
String message = jsonObject.getString("message");
innerObject = jsonObject.getJSONObject("Object");
innerArray = innerObject.getJSONArray("details");
// Log.e("arr", " " + arr);
for (int i = 0; i <= innerArray.length(); i++) {
JSONObject obj = innerArray.getJSONObject(i);
String advisorID = obj.getString("AdvisorID");
FirstName = obj.getString("FirstName");
String LastName = obj.getString("LastName");
String Email = obj.getString("Email");
String Password = obj.getString("Password");
String Designation = obj.getString("Designation");
String Company = obj.getString("Company");
String Location = obj.getString("Location");
String Description = obj.getString("Description");
String Profile_Pic_Small = obj.getString("Profile_Pic_Small");
String Profile_Pic_Original = obj.getString("Profile_Pic_Original");
String No_Questions = obj.getString("No_Questions");
String No_Answers = obj.getString("No_Answers");
String No_Up_Votes = obj.getString("No_Up_Votes");
String No_Followers = obj.getString("No_Followers");
String IsActive = obj.getString("IsActive");
String Created = obj.getString("Created");
String Modified = obj.getString("Modified");
JSONArray arr1 = innerObject.getJSONArray("questions");
for (int j = 0; j <= arr1.length(); j++) {
JSONObject obj1 = arr1.getJSONObject(j);
Question_Video_Title = obj1.getString("Question_Video_Title");
question_video_playingTime = obj1.getString("question_video_playingTime");
String Designation1 = obj1.getString("Designation");
User_name = obj1.getString("User_name");
Question_Video_Link = obj1.getString("Question_Video_Link");
shorted = Question_Video_Title.replace("=", " ");
cmpsort = shorted.replace("-", " ");
Answer_Video_Link = obj1.get("Answer_Video_Link");
QuestionID = obj1.getString("QuestionID");
videoName.add((cmpsort));
questionLink.add(Question_Video_Link);
answerLink.add(Answer_Video_Link);
arrayListName.add(User_name);
arrquestion_video_playingTime.add(question_video_playingTime);
mAdapter = new MyRecyclerViewAdapter(videoName, questionLink, answerLink, arrquestion_video_playingTime);
mRecyclerView.setAdapter(mAdapter);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
private String doInLoginProadvice() {
String responseString = null;
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(AppConstant.getAdvivisorDetail);
httppost.addHeader("APIKEY", "123ABC890567");
httppost.addHeader("Token", token);
List<NameValuePair> pairs = new ArrayList<NameValuePair>();
pairs.add(new BasicNameValuePair("AdvisorID", advisorID));
try {
httppost.setEntity(new UrlEncodedFormEntity(pairs));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
try {
HttpResponse response = httpclient.execute(httppost);
HttpEntity r_entity = response.getEntity();
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode == 200) {
responseString = EntityUtils.toString(r_entity);
} else {
responseString = "Error occurred! Http Status Code: "
+ statusCode;
}
} catch (ClientProtocolException e) {
e.printStackTrace();
responseString = e.toString();
} catch (IOException e) {
responseString = e.toString();
}
return responseString;
}
}
答案 0 :(得分:1)
以下是Parse JSON array
的简单方法,轻松获取Null
以及值对。重要事项不要使用变量名作为大写字母,它必须以小写字母开头。
请找到程序,您可以根据您的要求进行修改
import java.io.File;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
public class UnRepliedFragment_ {
//Define this as a global varraible
static Object Advisor_User_ID;
static Object Creator_User_ID;
static Object Question_Video_Title;
static Object playing_time;
static Object Created;
static Object Modified;
static Object question_video_playingTime;
static Object Answer_Video_Title;
static Object Answer_Video_Link;
static Object answer_video_playingtime;
static Object StatusName;
static Object QuestionID;
static ArrayList al;
public void onBindViewHolder() {
for (Object value : al) {
if (value != null) {
System.out.println("Not Null" + value);
} else {
System.out.println("Null" + value);
}
}
}
private void updateUIProadvice(String result) {
//Since i have an limited JSON so Accroding to that i did parsing . Dont try with getString just try with Get();//method
try {
JSONParser jsonParser = new JSONParser();
org.json.simple.JSONObject jsonObject = (org.json.simple.JSONObject) jsonParser.parse(result);
org.json.simple.JSONArray lang = (org.json.simple.JSONArray) jsonObject.get("questions");
for (int i = 0; i < lang.size(); i++) {
}
Iterator i = lang.iterator();
while (i.hasNext()) {
org.json.simple.JSONObject innerObj = (org.json.simple.JSONObject) i.next();
Creator_User_ID = innerObj.get("Creator_User_ID").toString();
Advisor_User_ID = innerObj.get("Advisor_User_ID");
Question_Video_Title = innerObj.get("Question_Video_Title");
playing_time = innerObj.get("playing_time");
Created = innerObj.get("Created");
Modified = innerObj.get("Modified");
question_video_playingTime = innerObj.get("question_video_playingTime");
Answer_Video_Title = innerObj.get("Answer_Video_Title");
question_video_playingTime = innerObj.get("question_video_playingTime");
Answer_Video_Title = innerObj.get("Answer_Video_Title");
Answer_Video_Link = innerObj.get("Answer_Video_Link");
answer_video_playingtime = innerObj.get("answer_video_playingtime");
StatusName = innerObj.get("StatusName");
QuestionID = innerObj.get("QuestionID");
// Storing data into arrayList
al = new ArrayList();
al.add(Creator_User_ID);
al.add(Advisor_User_ID);
al.add(Question_Video_Title);
al.add(playing_time);
al.add(Created);
al.add(Modified);
al.add(question_video_playingTime);
al.add(Answer_Video_Link);
al.add(Answer_Video_Title);
al.add(answer_video_playingtime);
al.add(QuestionID);
al.add(StatusName);
// First Way to get element one by one
for (Object value : al) {
if (value != null) {
System.out.println("Not Null:" + value);
} else {
System.out.println("Null:" + value);
}
}
//or Second Way
Object valuenext=al.get(0); // Get First Index Value
System.out.println(valuenext);
}
} catch (ParseException ex) {
ex.printStackTrace();
} catch (NullPointerException ex) {
ex.printStackTrace();
}
}
}