Android, displaying JSON data in application - java

I have this JSON data and I'm trying to display "measurements" part, but it doesn't work.
(I'm getting this: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was BEGIN_ARRAY at line 1 column 2 path $).
I'm beginner at Android developing, this is my first app and I just don't know how to fix this.
Here JSON:
[{
"id":1,
"type":"TEMPERATURE",
"measurements":[
{
"value":"22.58",
"time":"2017-01-11T12:20:44.701"
}]
},{
"id":2,
"type":"HUMIDITY",
"measurements":[
{
"value":"52.366",
"time":"2017-01-11T12:20:44.731"
}]
},{
"id":3,
"type":"LUMINOSITY",
"measurements":[
{
"value":"1.0",
"time":"2017-01-11T12:20:44.742"
}]
}]
Adapter:
public class SenzoriAdapter extends RecyclerView.Adapter < SenzoriAdapter.ViewHolder > {
private ArrayList < Measurement > mSenzori;
public SenzoriAdapter(ArrayList < Measurement > senzori) {
this.mSenzori = senzori;
}
#Override
public SenzoriAdapter.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.main_item, viewGroup, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(SenzoriAdapter.ViewHolder viewHolder, int i) {
String datum = mSenzori.get(i).getTime().replace("T", " ");
viewHolder.senzoriLastAlive.setText(datum);
String stringdouble = Double.toString(mSenzori.get(i).getValue());
viewHolder.senzoriMeasurement.setText(stringdouble);
}
#Override
public int getItemCount() {
return mSenzori.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
private TextView senzoriLastAlive, senzoriMeasurement;
public ViewHolder(View itemView) {
super(itemView);
senzoriLastAlive = (TextView) itemView.findViewById(R.id.senzoriLastAlive);
senzoriMeasurement = (TextView) itemView.findViewById(R.id.senzoriMeasurement);
}
}
}
Model Senzori:
public class Senzori {
#Expose
private Integer id;
#Expose
private String type;
#Expose
private Measurement[] measurements;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public Measurement[] getMeasurement() {
return measurements;
}
}
Model Measurement:
public class Measurement {
#Expose
private Double value;
#Expose
private String time;
public Double getValue() {
return value;
}
public void setValue(Double value) {
this.value = value;
}
public String getTime() {
return time;
}
public void setTime(String time) {
this.time = time;
}
}
and usage in Activity:
public void configViews() {
mRecyclerView = (RecyclerView) findViewById(recyclerView);
mRecyclerView.setHasFixedSize(true);
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getApplicationContext());
mRecyclerView.setLayoutManager(layoutManager);
loadJSON();
}
public void loadJSON() {
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(MainActivity.BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
SenzoriInterface request = retrofit.create(SenzoriInterface.class);
Call < Senzori > call = request.getAllSenzori(MainActivity.BASE_URL + "/sensors/");
call.enqueue(new Callback < Senzori > () {
#Override
public void onResponse(Call < Senzori > call, Response < Senzori > response) {
Senzori jsonResponse = response.body();
senzori = new ArrayList < > (Arrays.asList(jsonResponse.getMeasurement()));
senzoriAdapter = new SenzoriAdapter(senzori);
mRecyclerView.setAdapter(senzoriAdapter);
}
#Override
public void onFailure(Call < Senzori > call, Throwable t) {
Log.d("Error", t.getMessage());
}
});
}

You are expecting a single object, but response is giving you an array of objects.
Change
Call<Senzori> call = request.getAllSenzori(MainActivity.BASE_URL+"/sensors/");
To
Call<List<Senzori>> call = request.getAllSenzori(MainActivity.BASE_URL+"/sensors/");
And update your code accordingly.
call.enqueue(new Callback<List<Senzori>>() {
#Override
public void onResponse(Call<List<Senzori>> call, Response<List<Senzori>> response) {
senzori = response.body();
senzoriAdapter = new SenzoriAdapter(senzori.getMeasurement());
mRecyclerView.setAdapter(senzoriAdapter);
}
#Override
public void onFailure(Call<List<Senzori>> call, Throwable t) {
Log.d("Error",t.getMessage());
}
});

Related

How to consume an API call through Retrofit2?

API File
METHOD : GET
OUTPUT:
{
"status": true,
"message": "Subjects found.",
"data": {
"subjects": [
{
"subj_id": "2",
"name": "Maths",
"img": "Math.jpg"
},
{
"subj_id": "1",
"name": "Physics",
"img": "physics.png"
}
],
"total": 2
}
}
Model Class
public class SubjectTopics
{
#SerializedName("status")
#Expose
private Boolean status;
#SerializedName("message")
#Expose
private String message;
#SerializedName("data")
#Expose
private Data data;
public Boolean getStatus() {
return status;
}
public void setStatus(Boolean status) {
this.status = status;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public Data getData() {
return data;
}
public void setData(Data data) {
this.data = data;
}
}
public class Data {
#SerializedName("subjects")
#Expose
private List<Subjects> subjects = null;
#SerializedName("total")
#Expose
private Integer total;
public List<Subjects> getSubjects() {
return subjects;
}
public void setSubjects(List<Subjects> subjects) {
this.subjects = subjects;
}
public Integer getTotal() {
return total;
}
public void setTotal(Integer total) {
this.total = total;
}
}
public class Subjects {
#SerializedName("subj_id")
#Expose
private String subjId;
#SerializedName("name")
#Expose
private String name;
#SerializedName("img")
#Expose
private String img;
public String getSubjId() {
return subjId;
}
public void setSubjId(String subjId) {
this.subjId = subjId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getImg() {
return img;
}
public void setImg(String img) {
this.img = img;
}
}
My Adapter
public class MoviesAdapter extends RecyclerView.Adapter<MoviesAdapter.MovieViewHolder> {
private List<Subjects> movies;
private int rowLayout;
private Context context;
public static class MovieViewHolder extends RecyclerView.ViewHolder {
private TextView subjectName;
private TextView ID;
private ImageView ImageV;
private RelativeLayout relativeClick;
public MovieViewHolder(View v) {
super(v);
subjectName = (TextView) itemView.findViewById(R.id.textView);
relativeClick = (RelativeLayout) itemView.findViewById(R.id.relative_click);
ImageV = (ImageView) itemView.findViewById(R.id.imageView);
}
}
public MoviesAdapter(List<Subjects> movies, int rowLayout, Context context) {
this.movies = movies;
this.rowLayout = rowLayout;
this.context = context;
}
#Override
public MoviesAdapter.MovieViewHolder onCreateViewHolder(ViewGroup parent,
int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(rowLayout, parent, false);
return new MoviesAdapter.MovieViewHolder(view);
}
#Override
public void onBindViewHolder(MoviesAdapter.MovieViewHolder holder, final int position) {
holder.subjectName.setText(movies.get(position).getName());
holder.relativeClick.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(context, SubjectTopicList.class);
intent.putExtra("subject_id", movies.get(position).getSubjId());
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent);
}
});
Picasso.with(context)
.load(movies.get(position).getImg())
.placeholder(R.drawable.load)
.into(holder.ImageV);
}
#Override
public int getItemCount() {
return movies.size();
}
}
Activity
private void getSubjects() {
progressBar.setVisibility(View.VISIBLE);
Call<SubjectTopics> getProductsModelClassCall = webService.getSubjects();
getProductsModelClassCall.enqueue(new Callback<SubjectTopics>() {
#Override
public void onResponse(Call<SubjectTopics> call, Response<SubjectTopics> response) {
if (response.isSuccessful()) {
List<Subjects> movies = response.body().getData().getSubjects();
MoviesAdapter newAd=new MoviesAdapter(movies, R.layout.unit_test_row, getApplicationContext());
recyclerView.setAdapter(newAd);
} else {
APIError apiError = ErrorUtils.parseError(response);
Toast.makeText(UnitTestSubjects.this, ""+apiError, Toast.LENGTH_SHORT).show();
}
if (progressBar.isEnabled())
progressBar.setVisibility(View.INVISIBLE);
progressBar.setVisibility(View.GONE);
}
#Override
public void onFailure(Call<SubjectTopics> call, Throwable t) {
Toast.makeText(UnitTestSubjects.this, "Please Try Again", Toast.LENGTH_SHORT).show();
if (progressBar.isEnabled())
progressBar.setVisibility(View.INVISIBLE);
progressBar.setVisibility(View.GONE);
}
});
}
Retrofit Code
public class ServiceGenerator {
private final static String TAG = "ApiCall";
public static Retrofit getRetrofit(){
HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
// set your desired log level
logging.setLevel(HttpLoggingInterceptor.Level.BODY);
OkHttpClient.Builder httpClient = new OkHttpClient.Builder();
// add your other interceptors …
// add logging as last interceptor
httpClient.addInterceptor(logging); // <-- this is the important line!
httpClient.connectTimeout(10, TimeUnit.SECONDS).readTimeout(14, TimeUnit.SECONDS).writeTimeout(16, TimeUnit.SECONDS);
Gson gson = new GsonBuilder()
.setDateFormat("yyyy-MM-dd'T'HH:mm:ssZ")
.create();
return new Retrofit.Builder()
.baseUrl(WebServices.BASE_URL)
.client(httpClient.build())
.addConverterFactory(GsonConverterFactory.create(gson))
.build();
}
public static Api getApi(){
return getRetrofit().create(Api.class);
}
}
After calling API's using Retrofit 2.0, Unable to get any response and getting this error:
Failure:
retrofit2.ExecutorCallAdapterFactory$ExecutorCallbackCall#5321
every-time after callback it directly coming out from the method
I have tried all possible ways to solve but not able to find any solution regarding this.
I think this is internal retrofit error or in the pojo class I guess. Please help!

How to Load a Json data into dropdown Spinner Using Android Fragments

I need to Show Registration Form With Spinner Using Fragments and get the data using Json
This is kind of register form. At the bottom we have change language button which will reset the form and will be shown in arabic / english.
[
{
"Id":1,
"TitleEN":"Kuwait",
"TitleAR":"الكويت",
"CurrencyId":1,
"CurrencyEN":"Kuwaiti Dinar",
"CurrencyAR":"دينار كويتى",
"CodeEN":"KWD",
"CodeAR":"د.ك",
"Code":"965"
},
{
"Id":2,
"TitleEN":"Emirates",
"TitleAR":"الإمارات",
"CurrencyId":2,
"CurrencyEN":"Emirati Dirham",
"CurrencyAR":"درهم إماراتي",
"CodeEN":"AED",
"CodeAR":"درهم",
"Code":"971"
},
{
"Id":3,
"TitleEN":"Saudi Arabia",
"TitleAR":"السعودية",
"CurrencyId":3,
"CurrencyEN":"Saudi Riyal",
"CurrencyAR":"ريال سعودى",
"CodeEN":"SAR",
"CodeAR":"ر.س",
"Code":"966"
}
]
Note.I assume you have followed the first 3 steps from this [question][1]
and will start from the following
Step 1
Add spinner in xml
<Spinner
android:id="#+id/spinner"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:prompt="#string/spinner_title" />
Step 2
In ApiInterface Class add the following code
#GET("/app/app.asmx/GetCountries")
Call<List<Country>> getCountry();
Step 3
Create new model class by name Country
public class Country {
#SerializedName("Id")
#Expose
private Integer id;
#SerializedName("TitleEN")
#Expose
private String titleEN;
#SerializedName("TitleAR")
#Expose
private String titleAR;
#SerializedName("CurrencyId")
#Expose
private Integer currencyId;
#SerializedName("CurrencyEN")
#Expose
private String currencyEN;
#SerializedName("CurrencyAR")
#Expose
private String currencyAR;
#SerializedName("CodeEN")
#Expose
private String codeEN;
#SerializedName("CodeAR")
#Expose
private String codeAR;
#SerializedName("Code")
#Expose
private String code;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getTitleEN() {
return titleEN;
}
public void setTitleEN(String titleEN) {
this.titleEN = titleEN;
}
public String getTitleAR() {
return titleAR;
}
public void setTitleAR(String titleAR) {
this.titleAR = titleAR;
}
public Integer getCurrencyId() {
return currencyId;
}
public void setCurrencyId(Integer currencyId) {
this.currencyId = currencyId;
}
public String getCurrencyEN() {
return currencyEN;
}
public void setCurrencyEN(String currencyEN) {
this.currencyEN = currencyEN;
}
public String getCurrencyAR() {
return currencyAR;
}
public void setCurrencyAR(String currencyAR) {
this.currencyAR = currencyAR;
}
public String getCodeEN() {
return codeEN;
}
public void setCodeEN(String codeEN) {
this.codeEN = codeEN;
}
public String getCodeAR() {
return codeAR;
}
public void setCodeAR(String codeAR) {
this.codeAR = codeAR;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
}
Step 4
find view in activity or fragment and add call the request and get response and add the response in spinner adapter.Initialize a string list out side the onCreate method
List<String> codes = new ArrayList<String>();
APIInterface apiInterfacePages;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Spinner spinner = (Spinner) findViewById(R.id.spinner);
apiInterfacePages= PageApiClient.getRetrofit().create(APIInterface.class);
Call<List<Country>> getCountry = apiInterfacePages.getCountry();
getCountry.enqueue(new Callback<List<Country>>() {
#Override
public void onResponse(Call<List<Country>> call, Response<List<Country>> response) {
countryList = response.body();
for (int i = 0; i < countryList.size(); i++) {
codes.add(countryList.get(i).getCode());
}
ArrayAdapter<String> adapterTime = new ArrayAdapter<>(MainActivity.this, android.R.layout.simple_spinner_dropdown_item, codes);
spinner.setAdapter(adapterTime);
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
Toast.makeText(MainActivity.this, "" + countryList.get(i).getTitleEN(), Toast.LENGTH_SHORT).show();
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
}
#Override
public void onFailure(Call<List<Country>> call, Throwable t) {
}
});
}

Retrofit response success but null result

Interface:
public interface BabService {
#GET("bab.php")
Call<Respon> tampil(#Query("imam") String imam);
}
Respon:
public class Respon {
private String value;
private List<BabResult> resultBab;
public String getValue() {
return value;
}
public List<BabResult> getResultBab() { return resultBab; }
}
Result:
public class BabResult {
private String id_bab;
private String id_kitab;
private String bab;
public String getId_bab() { return id_bab; }
public String getId_kitab() {
return id_kitab;
}
public String getBab() {
return bab;
}
}
Adapter:
public class BabAdapter extends RecyclerView.Adapter<BabAdapter.ViewHolder>
{
private Context context;
private List<BabResult> results;
private String idBab, judulBab;
private int no;
public BabAdapter(Context context, List<BabResult> results) {
this.context = context;
this.results = results;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_bab, parent, false);
ViewHolder holder = new ViewHolder(v);
return holder;
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
if(position % 2 != 0){
holder.vBab.setBackgroundResource(R.color.ijo);
}else{
holder.vBab.setBackgroundResource(R.color.oren);
}
no = position + 1;
BabResult result = results.get(position);
idBab = result.getId_bab();
judulBab = result.getBab();
holder.tvNo.setText(no);
holder.tvBab.setText(judulBab);
}
#Override
public int getItemCount() {
if(results == null){
return 4;
}
return results.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
private View vBab;
private TextView tvBab, tvNo;
public ViewHolder(View itemView) {
super(itemView);
vBab = (View) itemView.findViewById(R.id.v_bab);
tvNo = (TextView) itemView.findViewById(R.id.tv_no);
tvBab = (TextView) itemView.findViewById(R.id.tv_bab);
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent i = new Intent(context, HadisList.class);
i.putExtra("id", idBab);
i.putExtra("bab", judulBab);
i.putExtra("no", no);
context.startActivity(i);
}
});
}
}
}
Activity:
public class MenuBab extends AppCompatActivity {
public static final String URL = "http://mi3bpolinema.000webhostapp.com/";
private List<BabResult> results = new ArrayList<>();
private BabAdapter babAdapter;
private ProgressBar pbLoading;
private RecyclerView rvBab;
private TextView tvImam;
private String imam, namaImam;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_menu_bab);
if(getSupportActionBar() != null){
getSupportActionBar().hide();
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
Intent intent = getIntent();
if(intent != null){
if(intent.getStringExtra("imam") != null){
imam = intent.getStringExtra("imam");
namaImam = intent.getStringExtra("nama");
}
}
pbLoading = (ProgressBar) findViewById(R.id.pb_loading);
rvBab = (RecyclerView) findViewById(R.id.rv_bab);
tvImam = (TextView) findViewById(R.id.tv_imam);
tvImam.setText(namaImam);
babAdapter = new BabAdapter(this, results);
RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getApplicationContext());
rvBab.setLayoutManager(mLayoutManager);
rvBab.setItemAnimator(new DefaultItemAnimator());
rvBab.setAdapter(babAdapter);
loadDataBab();
}
#Override
protected void onResume() {
super.onResume();
loadDataBab();
}
private void loadDataBab() {
Retrofit retrofit = new Retrofit
.Builder()
.baseUrl(URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
BabService api = retrofit.create(BabService.class);
Call<Respon> call = api.tampil(imam);
call.enqueue(new Callback<Respon>() {
#Override
public void onResponse(Call<Respon> call, Response<Respon> response) {
String value = response.body().getValue();
pbLoading.setVisibility(View.GONE);
if (value.equals("1")) {
results = response.body().getResultBab();
babAdapter = new BabAdapter(MenuBab.this, results);
rvBab.setAdapter(babAdapter);
}
}
#Override
public void onFailure(Call<Respon> call, Throwable t) {
}
});
}
}
On retrofit get result null, but when I run in website get result like this:
{"value":1,"result":[{"id_bab":"4","id_kitab":"1","bab":"Wudhu"},
{"id_bab":"8","id_kitab":"1","bab":"Shalat"},
{"id_bab":"15","id_kitab":"1","bab":"Puasa"}]}
using this link.
You need to use Model class in this way
now you can get API Result
Response Model Class
import com.google.gson.annotations.SerializedName;
import java.io.Serializable;
import java.util.ArrayList;
public class Response implements Serializable{
#SerializedName("value")
private String value;
#SerializedName("result")
private ArrayList<BabResult> resultBab;
public String getValue() {
return value;
}
public ArrayList<BabResult> getResultBab() {
return resultBab;
}
public void setValue(String value) {
this.value = value;
}
public void setResultBab(ArrayList<BabResult> resultBab) {
this.resultBab = resultBab;
}
public class BabResult {
#SerializedName("id_bab")
private String id_bab;
#SerializedName("id_kitab")
private String id_kitab;
#SerializedName("bab")
private String bab;
public String getId_bab() {
return id_bab;
}
public void setId_bab(String id_bab) {
this.id_bab = id_bab;
}
public String getId_kitab() {
return id_kitab;
}
public void setId_kitab(String id_kitab) {
this.id_kitab = id_kitab;
}
public String getBab() {
return bab;
}
public void setBab(String bab) {
this.bab = bab;
}
}
}
Respon class
public class Respon
{
private ArrayList<Result> result;
private String value;
public ArrayList<Result> getResult ()
{
return result;
}
public void setResult ( ArrayList<Result> result)
{
this.result = result;
}
public String getValue ()
{
return value;
}
public void setValue (String value)
{
this.value = value;
}
#Override
public String toString()
{
return "ClassPojo [result = "+result+", value = "+value+"]";
}
public class Result
{
private String id_kitab;
private String bab;
private String id_bab;
public String getId_kitab ()
{
return id_kitab;
}
public void setId_kitab (String id_kitab)
{
this.id_kitab = id_kitab;
}
public String getBab ()
{
return bab;
}
public void setBab (String bab)
{
this.bab = bab;
}
public String getId_bab ()
{
return id_bab;
}
public void setId_bab (String id_bab)
{
this.id_bab = id_bab;
}
#Override
public String toString()
{
return "ClassPojo [id_kitab = "+id_kitab+", bab = "+bab+", id_bab =
"+id_bab+"]";
}
}
}
Check this way data null or not and add arraylist
private void loadDataBab() {
Retrofit retrofit = new Retrofit
.Builder()
.baseUrl(URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
BabService api = retrofit.create(BabService.class);
Call<Respon> call = api.tampil(imam);
call.enqueue(new Callback<Respon>() {
#Override
public void onResponse(Call<Respon> call, Response<Respon> response) {
if (response.isSuccessful())
if (response.body() != null)
pbLoading.setVisibility(View.GONE);
if (response.body().getValue().equalsIgnoreCase("1")) {
results.addAll(response.body().getResult());
babAdapter = new BabAdapter(MenuBab.this, results);
rvBab.setAdapter(babAdapter);
}
}
#Override
public void onFailure(Call<Respon> call, Throwable t) {
}
});
}
Pass the array in your Respon class like this ..
public class Respon {
private String value;
private BabResult [] result;
public String getValue() {
return value;
}
public BabResult [] getResultBab() { return result; }
}
and in your loadDataBab method ..
private List<BabResult> results = new ArrayList<>();
private void loadDataBab() {
Retrofit retrofit = new Retrofit
.Builder()
.baseUrl(URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
RequestInterface api = retrofit.create(RequestInterface.class);
Call<Respon> call = api.tampil("1");
call.enqueue(new Callback<Respon>() {
#Override
public void onResponse(Call<Respon> call, Response<Respon> response) {
String value = response.body().getValue();
if (value.equals("1")) {
results = new ArrayList<>(Arrays.asList(response.body().getResultBab()));
}
}
#Override
public void onFailure(Call<Respon> call, Throwable t) {
}
});
}
I change Respon to :
public class Respon {
private String value;
private List<BabResult> result;
public String getValue() { return value; }
public List<BabResult> getResult() { return result; }
}
and it works. Thx :))

Retrofit2 HTTP Get Json to RecyclerView

I am trying to use Retrofit2 to retrieve data as JSON and then parsing it to my RecyclerView adapter, but whatever I do I can't figure out how to get this thing to work.
At the moment, I can load up one RecyclerView with local DBFlow data, but can't figure out how to do it for the JSON that I HTTP GET with Retrofit2 for my second RecyclerView. I have the code below so far, which loads the JSON in the Log. But can't parse it to the RecyclerView.
MainActivity.java:
onCreate() {
...
mGithubApi = ApiUtils.getApi();
mGithubRecyclerView = (RecyclerView)
findViewById(R.id.github_repository_recyclerview);
RecyclerView.LayoutManager mGithubLayoutManager = new
LinearLayoutManager(getApplicationContext());
mGithubRecyclerView.setLayoutManager(mGithubLayoutManager);
mGithubRecyclerView.setHasFixedSize(true);
...
loadGithubUserRepositoryJson();
}
// Load Github repo JSON
public void loadGithubUserRepositoryJson() {
Call<ResponseBody> result = api.getRepos("motivecodex");
result.enqueue(new Callback<ResponseBody>() {
#Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
try {
Log.e(LOG_TAG, response.body().string());
mGithubAdapter = new GithubRepositoriesAdapter((List<GithubRepository>) mGithubRepository);
mGithubRecyclerView.setAdapter(mGithubAdapter);
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
Log.e("MainActivity", "error loading from API");
}
});
}
GithubRepositoryAdapter.java
public class GithubRepositoriesAdapter extends RecyclerView.Adapter<GithubRepositoriesAdapter.RepositoryViewHolder> {
private List<GithubRepository> githubRepositoryList;
public class RepositoryViewHolder extends RecyclerView.ViewHolder {
public TextView repository, commits, stars, forks;
public RepositoryViewHolder(View view) {
super(view);
repository = (TextView) view.findViewById(R.id.listitem_repository);
commits = (TextView) view.findViewById(R.id.listitem_commits);
stars = (TextView) view.findViewById(R.id.listitem_stars);
forks = (TextView) view.findViewById(R.id.listitem_forked);
}
}
public GithubRepositoriesAdapter(List<GithubRepository> githubRepositoryList) {
this.githubRepositoryList = githubRepositoryList;
}
#Override
public RepositoryViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.listitem_repository, parent, false);
return new RepositoryViewHolder(itemView);
}
#Override
public void onBindViewHolder(RepositoryViewHolder holder, int position) {
GithubRepository githubRepository = githubRepositoryList.get(position);
holder.repository.setText(githubRepository.getName());
holder.commits.setText(githubRepository.getStargazersCount());
holder.stars.setText(githubRepository.getStargazersCount());
holder.forks.setText(githubRepository.getForks());
}
#Override
public int getItemCount() {
return githubRepositoryList.size();
}
}
interface Api.java:
#GET("users/{user}/repos")
Call<List<GithubRepository>> listRepos(#Path("user") String user);
model GithubRepository.java
public class GithubRepository {
#SerializedName("id")
#Expose
private Integer id;
#SerializedName("name")
#Expose
private String name;
#SerializedName("full_name")
#Expose
private String fullName;
#SerializedName("stargazers_count")
#Expose
private Integer stargazersCount;
#SerializedName("forks")
#Expose
private Integer forks;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getFullName() {
return fullName;
}
public void setFullName(String fullName) {
this.fullName = fullName;
}
public Integer getStargazersCount() {
return stargazersCount;
}
public void setStargazersCount(Integer stargazersCount) {
this.stargazersCount = stargazersCount;
}
public Integer getForks() {
return forks;
}
public void setForks(Integer forks) {
this.forks = forks;
}
}
ApiUtil.java
public static final String BASE_URL = "https://api.github.com/users/";
public static Api getApi() {
return RetrofitClient.getClient(BASE_URL).create(Api.class);
}
RetrofitClient.java
public class RetrofitClient {
private static Retrofit retrofit = null;
public static Retrofit getClient(String baseUrl) {
if (retrofit == null) {
retrofit = new Retrofit.Builder()
.baseUrl(baseUrl)
.addConverterFactory(GsonConverterFactory.create())
.build();
}
return retrofit;
}
}
Instead of Log (this approximately as I can't see your types):
localRepositoryList.addAll(response.body());
adapter.notifyDataSetChanged();
P.S: I assume you have in the code something like:
GithubRepositoriesAdapter adapter=new GithubRepositoriesAdapter(localRepositoryList);
mGithubRecyclerView.setAdapter(adapter);
Another option in log place:
mGithubRecyclerView.setAdapter(new GithubRepositoriesAdapter(response.body()));
UPDATE:
public void loadGithubUserRepositoryJson() {
api.listRepos("motivecodex").enqueue(new Callback<List<GithubRepository>>() {
#Override
public void onResponse(Call<List<GithubRepository>> call, Response<List<GithubRepository>> response) {
try {
Log.e(LOG_TAG, response.body().string());
mGithubAdapter = new GithubRepositoriesAdapter(response.body());
mGithubRecyclerView.setAdapter(mGithubAdapter);
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
public void onFailure(Call<List<GithubRepository>> call, Throwable t) {
Log.e("MainActivity", "error loading from API");
}
});
}

java.lang.NullPointerException: Attempt to invoke interface method 'java.util.Iterator java.util.List.iterator()' on a null object reference Retrofit

I'm trying to use blog id to get JSON object from server. At the moment I'm getting this error
java.lang.NullPointerException: Attempt to invoke interface method 'java.util.Iterator java.util.List.iterator()
on a null object reference`.How do I use the post Id to get the full content what am I doing wrong. Please help!!!
MyBlog Adapter:
public class MyBlogAdapter extends RecyclerView.Adapter<BlogViewHolder> {
List<BlogResponse> postsList;
Context context;
public static String blog_Id, blogID;
private LayoutInflater inflater;
public MyBlogAdapter(Context context, List<BlogResponse> postsList){
this.context = context;
this.inflater = LayoutInflater.from(context);
this.postsList = postsList;
}
#Override
public BlogViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = inflater.inflate(R.layout.custom_view,parent, false);
return new BlogViewHolder(view);
}
#Override
public void onBindViewHolder(BlogViewHolder holder, int position) {
final BlogResponse posts= postsList.get(position);
holder.summary.setText(posts.getBlogExcerpt().trim().toString());
holder.title.setText(posts.getBlogTitle().trim().toString());
// Glide.with(context).load(posts.getBlogThumbnail()).into(holder.cover);
holder.blogHolder.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(context, AnotherSingleView.class);
blog_Id = posts.getBlogId();
intent.putExtra(blogID,blog_Id);
Log.d("MyblogAdapter","Please check blog Id: "+blog_Id);
context.startActivity(intent);
}
});
}
#Override
public int getItemCount() {
Log.d("MyBlogAdapter,","getItemCount"+postsList.size());
return postsList == null ? (0) : postsList.size();
}
}
SecondActivity:
public class AnotherSingleView extends AppCompatActivity {
String postID;
int position;
public TextView blogTitle,blogSub,blogContent;
public ImageView blogPic;
List<SingleBlogPost> singleBlogPosts;
SingleBlogPost singleBlogPost;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_another_single_view);
Intent intent = getIntent();
Bundle showBlogId = intent.getExtras();
postID = showBlogId.getString(blogID);
Log.d("AnotherSingleView","Please check blog Id: "+postID);
singleBlogPosts = new ArrayList<>();
blogContent = (TextView)findViewById(R.id.blog_content);
blogSub = (TextView) findViewById(R.id.blog_subtitle);
blogTitle =(TextView) findViewById(R.id.blog_title);
blogPic =(ImageView) findViewById(R.id.blog_pix);
singlePostDisplay();
}
private void singlePostDisplay() {
BlogaPI api = ApiClient.getBlogInterface();
Call<List<SingleBlogPost>> call = api.postResponse(postID);
call.enqueue(new Callback<List<SingleBlogPost>>() {
#Override
public void onResponse(Call<List<SingleBlogPost>> call, Response<List<SingleBlogPost>> response) {
singleBlogPosts = response.body();
if (singleBlogPosts != null && !singleBlogPosts.isEmpty() ){
for (SingleBlogPost posts : singleBlogPosts){
Log.d("AnotherSingleView","Please check RESPONSE: "+response.body().toString());
blogTitle.setText(posts.getBlogTitle());
blogSub.setText(posts.getBlogSubtitle());
blogContent.setText(posts.getBlogContent());
// Glide.with(AnotherSingleView.this).load(singlepost.getBlogMedimg()).into(blogPic);
}
}
else{
Toast.makeText(AnotherSingleView.this, "Something is empty", Toast.LENGTH_SHORT).show();
} }
#Override
public void onFailure(Call<List<SingleBlogPost>> call, Throwable t) {
Toast.makeText(AnotherSingleView.this, "check again: "+t.toString(), Toast.LENGTH_SHORT).show();
}
});
}
}
Interface:
public interface BlogaPI {
#GET("blog")
Call<BlogList> response();
#GET("post/{blog_id}")
Call<List<SingleBlogPost>> postResponse(#Path("blog_id") String blog_id);
//Call<List<SingleBlogPost>> postResponse();
}
SingleBlogPost:
public class SingleBlogPost {
#SerializedName("blog_id")
#Expose
private String blogId;
#SerializedName("blog_title")
#Expose
private String blogTitle;
#SerializedName("blog_subtitle")
#Expose
private String blogSubtitle;
#SerializedName("blog_excerpt")
#Expose
private String blogExcerpt;
#SerializedName("blog_content")
#Expose
private String blogContent;
#SerializedName("blog_thumbnail")
#Expose
private String blogThumbnail;
#SerializedName("blog_medimg")
#Expose
private String blogMedimg;
#SerializedName("category_title")
#Expose
private String categoryTitle;
public SingleBlogPost(String blogId,String blogTitle, String blogSubtitle, String blogExcerpt,
String blogContent, String blogThumbnail, String blogMedimg, String categoryTitle){
this.blogId = blogId;
this.blogTitle = blogTitle;
this.blogSubtitle = blogSubtitle;
this.blogExcerpt = blogExcerpt;
this.blogContent = blogContent;
this.blogThumbnail = blogThumbnail;
this.blogMedimg = blogMedimg;
this.categoryTitle = categoryTitle;
}
public String getBlogId() {
return blogId;
}
public void setBlogId(String blogId) {
this.blogId = blogId;
}
public String getBlogTitle() {
return blogTitle;
}
public void setBlogTitle(String blogTitle) {
this.blogTitle = blogTitle;
}
public String getBlogSubtitle() {
return blogSubtitle;
}
public void setBlogSubtitle(String blogSubtitle) {
this.blogSubtitle = blogSubtitle;
}
public String getBlogExcerpt() {
return blogExcerpt;
}
public void setBlogExcerpt(String blogExcerpt) {
this.blogExcerpt = blogExcerpt;
}
public String getBlogContent() {
return blogContent;
}
public void setBlogContent(String blogContent) {
this.blogContent = blogContent;
}
public String getBlogThumbnail() {
return blogThumbnail;
}
public void setBlogThumbnail(String blogThumbnail) {
this.blogThumbnail = blogThumbnail;
}
public String getBlogMedimg() {
return blogMedimg;
}
public void setBlogMedimg(String blogMedimg) {
this.blogMedimg = blogMedimg;
}
public String getCategoryTitle() {
return categoryTitle;
}
public void setCategoryTitle(String categoryTitle) {
this.categoryTitle = categoryTitle;
}
}
Check if the server response is different then null before you do a enhanced for like this:
if(singleBlogPosts!= null) {
for (SingleBlogPosts posts : singleBlogPosts){
Log.d("AnotherSingleView","Please check RESPONSE: "+response.body().toString());
blogTitle.setText(posts.getBlogTitle());
blogSub.setText(posts.getBlogSubtitle());
blogContent.setText(posts.getBlogContent());
// Glide.with(AnotherSingleView.this).load(singlepost.getBlogMedimg()).into(blogPic);
}
}
you question was list iterator,but we can`t see you list use on anywhere,i guess you may be use recyclerView on you data has not get,because get data was asynchronous.try to use data if you can sure it is existing.

Categories