harsh thakur harsh thakur - 4 months ago 30
Android Question

i am getting these king of error java.lang.NullPointerException: Attempt to invoke virtual method at bindview holder method Recyclerview

hi i am new on android project,i am getting error evove like this.
in my project i have used recycler view used.so when parsed json data i am getting two kinds of error..so i need help
1.recycler view data only showing in api 21 to above version.means below 21 data is not showing .
2.when i scrolled down in above version ..app crashed

my code :- here is Adapter class

public class ContactAdapter extends RecyclerView.Adapter<ContactAdapter.ContactViewHolder> {

private List<Model_joblist> contactList;
private Context context;
public ContactAdapter(List<Model_joblist> contactList)
{
this.contactList = contactList;
}
@Override
public int getItemCount() {
if (contactList != null) {
return contactList.size();
}
return 0;
}

@Override
public void onAttachedToRecyclerView(RecyclerView recyclerView) {
super.onAttachedToRecyclerView(recyclerView);
}
@Override
public void onBindViewHolder(ContactViewHolder contactViewHolder, int positionforitem) {
Model_joblist ci = contactList.get(positionforitem);

contactViewHolder.des1.setText(ci.getDescreption());//error line : java.lang.NullPointerException: Attempt to invoke virtual method
contactViewHolder.contra1.setText("ConTract Manager_id"+ci.getContract());
contactViewHolder.jobno1.setText(ci.getJobno());
contactViewHolder.hours1.setText(String.valueOf(ci.getTime()));


}

@Override
public ContactViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View itemView = LayoutInflater.
from(viewGroup.getContext()).
inflate(R.layout.row_jobs, viewGroup, false);

return new ContactViewHolder(itemView);
}

public static class ContactViewHolder extends RecyclerView.ViewHolder {

protected TextView jobno1;
// protected TextView date1;
protected TextView des1;
protected TextView contra1;
protected TextView hours1;

public ContactViewHolder(View v) {
super(v);
jobno1 = (TextView) v.findViewById(R.id.text1);
des1 = (TextView) v.findViewById(R.id.text3);
contra1 = (TextView) v.findViewById(R.id.text44);
hours1=(TextView)v.findViewById(R.id.text4);

}
}


}

this is home Actcivity class

public class Assigned extends AppCompatActivity {
private DrawerLayout mDrawerLayout;
private RecyclerView recyclerView;

private ContactAdapter ca;
private Model_joblist model_joblist;
private RecyclerView.LayoutManager layoutManager;
//private JSONObject obj;
public static final String KEY_TOKEN = "token";
public static final String KEY_ROLE = "role";
public static final String KEY_ID = "user_id";

public List<Model_joblist> model_joblists;
private static final String TAG = Assigned.class.getName();

protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.assign);
session = new SessionManager(getApplicationContext());
TextView textView = (TextView) findViewById(R.id.user_name);
HashMap<String, String> user = session.getUserDetails();
String name = user.get(SessionManager.KEY_NAME);
textView.setText(name);


recyclerView = (RecyclerView) findViewById(R.id.cardList);
final LinearLayoutManager layoutManager = new LinearLayoutManager(context);
layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
recyclerView.setLayoutManager(layoutManager);
recyclerView.setHasFixedSize(true);



model_joblists = new ArrayList<>();
recyclerView.addOnItemTouchListener(
new RecyclerItemClickListener(context, new RecyclerItemClickListener.OnItemClickListener() {
@Override
public void onItemClick(View view, int position) {
switch (position) {
case 0: {
Intent intent = new Intent(getApplicationContext(), JobSubmission.class);
startActivity(intent);
break;
}
default: {
Intent intent = new Intent(getApplicationContext(), JobSubmission.class);
startActivity(intent);
}
}

}
})
);

ContactAdapter adapter2 = new ContactAdapter(model_joblists);
recyclerView.setAdapter(adapter2);


getDataNew();
}
private void getDataNew()
{
String tag_json_obj = "json_obj_req";
String url = "http://103.54.103.8:4067/evivaservices/Webservices/joblisting";
HashMap<String, String> user = session.getUserDetails();
String token = user.get(SessionManager.KEY_TOKEN);
Log.e("token check kro", token);
final String role = user.get(SessionManager.KEY_ROLE);
Log.e("role", role);
String user_id = user.get(SessionManager.KEY_USERID);
Log.e("user_id", String.valueOf(user_id));
Map<String, String> params = new HashMap();
params.put(KEY_TOKEN, token);
params.put(KEY_ROLE, role);
params.put(KEY_ID, user_id);

JSONObject parameters = new JSONObject(params);
final ProgressDialog loading = ProgressDialog.show(this, "Loading Data", "Please wait...", false, false);
JsonObjectRequest jsonRequest = new JsonObjectRequest(Request.Method.POST, url, parameters, new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
Log.e("response mila", response.toString());
ParseData(response);
loading.dismiss();

}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
});
jsonRequest.setRetryPolicy(new DefaultRetryPolicy(
5000,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
Volley.newRequestQueue(this).add(jsonRequest);
}

private void ParseData(JSONObject Object)
{

try {
//JSONObject jsonObject=new JSONObject(Object);
JSONArray jsonArray = Object.getJSONArray("job_details");
List<Model_joblist> jobListArray=new ArrayList<Model_joblist>();
for (int m = 0; m < jsonArray.length(); m++) {
Model_joblist model_joblist= new Model_joblist();

JSONObject jsonObject = jsonArray.getJSONObject(m);
String job=jsonObject.getString("job_no");
model_joblist.setJobno(jsonObject.getString(JobList.JOB_NO));
model_joblist.setJobid(jsonObject.getInt(JobList.JOB_ID));
model_joblist.setDescreption(jsonObject.getString(JobList.JOB_DESCRIPTION));
model_joblist.setTime(jsonObject.getDouble(JobList.TIME_SPENT));
model_joblist.setContract(jsonObject.getInt(JobList.CONTRACT_MANAGER));
model_joblist.setCompanyname(jsonObject.getString(JobList.COMPANY_NAME));

model_joblists.add(model_joblist);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
model_joblists.add(model_joblist);
}


}
error line
FATAL EXCEPTION: main
Process: evivaservices.com.dikona, PID: 3379
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String evivaservices.com.dikona.Model.Model_joblist.getDescreption()' on a null object reference
at evivaservices.com.dikona.ContactAdapter.onBindViewHolder(ContactAdapter.java:47)
at evivaservices.com.dikona.ContactAdapter.onBindViewHolder(ContactAdapter.java:18)
at android.support.v7.widget.RecyclerView$Adapter.onBindViewHolder(RecyclerView.java:5768)
at android.support.v7.widget.RecyclerView$Adapter.bindViewHolder(RecyclerView.java:5801)
at android.support.v7.widget.RecyclerView$Recycler.getViewForPosition(RecyclerView.java:5037)
at android.support.v7.widget.RecyclerView$Recycler.getViewForPosition(RecyclerView.java:4913)
at android.support.v7.widget.LinearLayoutManager$LayoutState.next(LinearLayoutManager.java:2029)
at android.support.v7.widget.LinearLayoutManager.layoutChunk(LinearLayoutManager.java:1414)
at android.support.v7.widget.LinearLayoutManager.fill(LinearLayoutManager.java:1377)
at android.support.v7.widget.LinearLayoutManager.scrollBy(LinearLayoutManager.java:1193)
at android.support.v7.widget.LinearLayoutManager.scrollVerticallyBy(LinearLayoutManager.java:1043)
at android.support.v7.widget.RecyclerView$ViewFlinger.run(RecyclerView.java:4357)
at android.view.Choreographer$CallbackRecord.run(Choreographer.java:767)
at android.view.Choreographer.doCallbacks(Choreographer.java:580)
at android.view.Choreographer.doFrame(Choreographer.java:549)
at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:753)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5254)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)

Answer

Read the comments and set adapter when your data is ready?

 private void ParseData(JSONObject Object) {

        try {
            //JSONObject jsonObject=new JSONObject(Object);
            JSONArray jsonArray = Object.getJSONArray("job_details");
            List<Model_joblist> jobListArray = new ArrayList<Model_joblist>();
            for (int m = 0; m < jsonArray.length(); m++) {
                Model_joblist model_joblist = new Model_joblist();

                JSONObject jsonObject = jsonArray.getJSONObject(m);
                String job = jsonObject.getString("job_no");
                model_joblist.setJobno(jsonObject.getString(JobList.JOB_NO));
                model_joblist.setJobid(jsonObject.getInt(JobList.JOB_ID));
                model_joblist.setDescreption(jsonObject.getString(JobList.JOB_DESCRIPTION));
                model_joblist.setTime(jsonObject.getDouble(JobList.TIME_SPENT));
                model_joblist.setContract(jsonObject.getInt(JobList.CONTRACT_MANAGER));
                model_joblist.setCompanyname(jsonObject.getString(JobList.COMPANY_NAME));

                model_joblists.add(model_joblist);
            }
        } catch (JSONException e){
            e.printStackTrace();
        }
        // comment this line
        //model_joblists.add(model_joblist);
        // and then set adapter her when ready not in oncreate()
        ContactAdapter adapter2 = new ContactAdapter(model_joblists);
        recyclerView.setAdapter(adapter2);
    }