I wanna compare 2 ArrayList from LatestFragment and ApplyFragment. ApplyFragment contains ArrayList from the user. But, when I compare it, the following error appears. How to getUserId() from SharedPref when im comparing this 2 ArrayList?
this is the comparison in JobAdapter.java
for (ItemJob itemJob : LatestFragment.mListItem){
boolean found = false;
for (ItemJob itemJob2 : ApplyFragment.mListItem) {
if (itemJob2.id == itemJob.id)
btnApplyJob.setText(R.string.applied);
found = true;
}
if(!found){
btnApplyJob.setText(R.string.apply_now);
}
}
ApplyFragment.java
package com.data.fragment;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import com.app.hero.MyApplication;
import com.app.hero.R;
import com.data.adapter.JobAdapter;
import com.data.adapter.JobProviderAdapter;
import com.data.item.ItemJob;
import com.data.util.Constant;
import com.data.util.ItemOffsetDecoration;
import com.data.util.JsonUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
/**
* Created by laxmi.
*/
public class ApplyFragment extends Fragment {
public static ArrayList<ItemJob> mListItem;
public RecyclerView recyclerView;
JobAdapter adapter;
private ProgressBar progressBar;
private LinearLayout lyt_not_found;
MyApplication MyApp;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.row_recyclerview, container, false);
MyApp = MyApplication.getInstance();
mListItem = new ArrayList<>();
lyt_not_found = rootView.findViewById(R.id.lyt_not_found);
progressBar = rootView.findViewById(R.id.progressBar);
recyclerView = rootView.findViewById(R.id.vertical_courses_list);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false));
ItemOffsetDecoration itemDecoration = new ItemOffsetDecoration(getActivity(), R.dimen.item_offset);
recyclerView.addItemDecoration(itemDecoration);
if (JsonUtils.isNetworkAvailable(getActivity())) {
new getLatest().execute(Constant.USERS_JOB_APPLIED_LIST + MyApp.getUserId());
}
return rootView;
}
private class getLatest extends AsyncTask<String, Void, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
showProgress(true);
}
#Override
protected String doInBackground(String... params) {
return JsonUtils.getJSONString(params[0]);
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
showProgress(false);
if (null == result || result.length() == 0) {
lyt_not_found.setVisibility(View.VISIBLE);
} else {
try {
JSONObject mainJson = new JSONObject(result);
JSONArray jsonArray = mainJson.getJSONArray(Constant.ARRAY_NAME);
JSONObject objJson;
for (int i = 0; i < jsonArray.length(); i++) {
objJson = jsonArray.getJSONObject(i);
ItemJob objItem = new ItemJob();
objItem.setId(objJson.getString(Constant.JOB_ID));
objItem.setJobName(objJson.getString(Constant.JOB_NAME));
objItem.setJobCompanyName(objJson.getString(Constant.JOB_COMPANY_NAME));
objItem.setJobDate(objJson.getString(Constant.JOB_DATE));
objItem.setJobDateFrom(objJson.getString(Constant.JOB_DATEFROM));
objItem.setJobDateTo(objJson.getString(Constant.JOB_DATETO));
objItem.setJobDesignation(objJson.getString(Constant.JOB_DESIGNATION));
objItem.setJobAddress(objJson.getString(Constant.JOB_ADDRESS));
objItem.setJobImage(objJson.getString(Constant.JOB_IMAGE));
mListItem.add(objItem);
}
} catch (JSONException e) {
e.printStackTrace();
}
displayData();
}
}
}
private void displayData() {
adapter = new JobAdapter(getActivity(), mListItem);
recyclerView.setAdapter(adapter);
if (adapter.getItemCount() == 0) {
lyt_not_found.setVisibility(View.VISIBLE);
} else {
lyt_not_found.setVisibility(View.GONE);
}
}
private void showProgress(boolean show) {
if (show) {
progressBar.setVisibility(View.VISIBLE);
recyclerView.setVisibility(View.GONE);
lyt_not_found.setVisibility(View.GONE);
} else {
progressBar.setVisibility(View.GONE);
recyclerView.setVisibility(View.VISIBLE);
}
}
}
And This is the error
Process: com.app.hero, PID: 25830
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String com.app.hero.MyApplication.getUserId()' on a null object reference
at com.data.fragment.ApplyFragment.onCreateView(ApplyFragment.java:55)
at android.support.v4.app.Fragment.performCreateView(Fragment.java:2354)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1419)
at android.support.v4.app.FragmentManagerImpl.moveFragmentToExpectedState(FragmentManager.java:1740)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1809)
at android.support.v4.app.BackStackRecord.executeOps(BackStackRecord.java:799)
at android.support.v4.app.FragmentManagerImpl.executeOps(FragmentManager.java:2580)
at android.support.v4.app.FragmentManagerImpl.executeOpsTogether(FragmentManager.java:2367)
at android.support.v4.app.FragmentManagerImpl.removeRedundantOperationsAndExecute(FragmentManager.java:2322)
at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:2229)
at android.support.v4.app.FragmentManagerImpl$1.run(FragmentManager.java:700)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5451)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
'java.lang.String com.app.hero.MyApplication.getUserId()' on a null object reference
you got this error because your UserId() is not set properly and you try to getUserId().
I guess everything is perfect just check your sharedPreference have all your UserData.
Related
I have a recycler view, that is picking the data from an URL and it stores it, but I want to set an OnClickListener so I can click on a specific field and show some extra data.
I tried to implement a ClickListener but it gives me an error.
if this way I tried is not good feel free to suggest a better way for my code.
Adapter Class:
package com.example.zlatnakopackajson1;
import android.content.Context;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import java.util.ArrayList;
public class PonudiAdapter extends RecyclerView.Adapter<PonudiViewHolder> {
private Context context;
ArrayList<Ponudi> ponudis;
public PonudiAdapter() {
ponudis = new ArrayList<>();
}
public void setData(ArrayList<Ponudi> ponudis) {
this.ponudis = ponudis;
}
#NonNull
#Override
public PonudiViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
Context context = parent.getContext();
LayoutInflater layoutInflater = LayoutInflater.from(context);
View ponudiView = layoutInflater.inflate(R.layout.adapter_view_layout,parent,false);
return new PonudiViewHolder(ponudiView);
}
#Override
public void onBindViewHolder(#NonNull PonudiViewHolder holder, int position) {
final Ponudi ponudi = ponudis.get(position);
// holder.sh_sport_id.setText(ponudi.sh_sport_id);
if ( ponudi.sh_sport_id.equals("1")) {
holder.sh_sport_id.setText("Фудбал");
holder.imgSport.setImageResource(R.drawable.fudbal);
}
else if (ponudi.sh_sport_id.equals("2") ) {
holder.sh_sport_id.setText("Хокеј");
holder.imgSport.setImageResource(R.drawable.hokej);
}
else if (ponudi.sh_sport_id.equals("3") ) {
holder.sh_sport_id.setText("Кошарка");
holder.imgSport.setImageResource(R.drawable.basketball);
}
else if (ponudi.sh_sport_id.equals("4") ) {
holder.sh_sport_id.setText("Тенис");
holder.imgSport.setImageResource(R.drawable.tenis);
}
else if (ponudi.sh_sport_id.equals("5") ) {
holder.sh_sport_id.setText("Ракомет");
// holder.imgSport.setImageResource(R.drawable.handball);
}
else if (ponudi.sh_sport_id.equals("6") ) {
holder.sh_sport_id.setText("MLB");
// holder.imgSport.setImageResource(R.drawable.mlb);
}
else if (ponudi.sh_sport_id.equals("7") ) {
holder.sh_sport_id.setText("Одбојка");
holder.imgSport.setImageResource(R.drawable.odbojka);
}
else if (ponudi.sh_sport_id.equals("8") ) {
holder.sh_sport_id.setText("Рагби");
holder.imgSport.setImageResource(R.drawable.ragbi);
}
else if (ponudi.sh_sport_id.equals("9") ) {
holder.sh_sport_id.setText("Формула");
// holder.imgSport.setImageResource(R.drawable.formula);
}
else if (ponudi.sh_sport_id.equals("10") ) {
holder.sh_sport_id.setText("Мото Спорт");
// holder.imgSport.setImageResource(R.drawable.moto);
}
else if (ponudi.sh_sport_id.equals("11") ) {
holder.sh_sport_id.setText("Ватерполо");
holder.imgSport.setImageResource(R.drawable.vaterpolo);
}
else if (ponudi.sh_sport_id.equals("12") ) {
holder.sh_sport_id.setText("Бокс");
// holder.imgSport.setImageResource(R.drawable.boks);
}
else if (ponudi.sh_sport_id.equals("13") ) {
holder.sh_sport_id.setText("Футсал");
holder.imgSport.setImageResource(R.drawable.futsal);
}
else if (ponudi.sh_sport_id.equals("14") ) {
holder.sh_sport_id.setText("Пинг Понг");
// holder.imgSport.setImageResource(R.drawable.tenis);
}
else {
holder.sh_sport_id.setText("Останато");
holder.imgSport.setImageAlpha(0);
}
holder.tim1.setText(ponudi.tim1);
holder.tim2.setText(ponudi.tim2);
holder.liga_header.setText(ponudi.liga_header);
holder.parent_layout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(context,MatchActivity.class);
context.startActivity(intent);
}
});
}
#Override
public int getItemCount() {
return ponudis.size();
}
}
ViewHolder Class:
package com.example.zlatnakopackajson1;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
public class PonudiViewHolder extends RecyclerView.ViewHolder {
TextView sh_sport_id;
TextView tim1;
TextView tim2;
TextView liga_header;
ImageView imgSport;
LinearLayout parent_layout;
public PonudiViewHolder(#NonNull View itemView) {
super(itemView);
sh_sport_id = itemView.findViewById(R.id.textView1);
tim1 = itemView.findViewById(R.id.textView2);
tim2 = itemView.findViewById(R.id.textView3);
liga_header = itemView.findViewById(R.id.textView4);
imgSport = itemView.findViewById(R.id.imgSport);
parent_layout = itemView.findViewById(R.id.parent_layout);
}
}
Error Logcat:
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.content.Context.getPackageName()' on a null object reference
at android.content.ComponentName.<init>(ComponentName.java:131)
at android.content.Intent.<init>(Intent.java:6510)
at com.example.zlatnakopackajson1.PonudiAdapter$1.onClick(PonudiAdapter.java:114)
at android.view.View.performClick(View.java:7125)
at android.view.View.performClickInternal(View.java:7102)
at android.view.View.access$3500(View.java:801)
at android.view.View$PerformClick.run(View.java:27336)
at android.os.Handler.handleCallback(Handler.java:883)
at android.os.Handler.dispatchMessage(Handler.java:100)
at android.os.Looper.loop(Looper.java:214)
at android.app.ActivityThread.main(ActivityThread.java:7356)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:930)
New Activity:
package com.example.zlatnakopackajson1;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
public class MatchActivity extends AppCompatActivity {
private static final String TAG = "MatchActivity";
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_match);
Log.d(TAG, "OnCrate: started");
getIncomingIntent();
}
private void getIncomingIntent() {
Log.d(TAG, "getIncomingIntent: checking for incoming intent");
if (getIntent().hasExtra("tim1") && getIntent().hasExtra("tim2")) {
Log.d(TAG, "getIncomingIntetnt: found intent extras.");
String tim1 = getIntent().getStringExtra("tim1");
String tim2 = getIntent().getStringExtra("tim2");
setItems(tim1,tim2);
}
}
private void setItems (String tim1, String tim2) {
Log.d(TAG,"setItems: setting the tims to widgets.");
TextView Tim1 = findViewById(R.id.txtMatchT1);
Tim1.setText(tim1);
TextView Tim2 = findViewById(R.id.txtMatchT2);
Tim2.setText(tim2);
}
}
Here in your PonudiAdapter class you have a private member Context.
But you are not setting the value for the context in your class constructor.
Change your class constructor to pass a context object
public class PonudiAdapter extends RecyclerView.Adapter<PonudiViewHolder> {
private Context context;
ArrayList<Ponudi> ponudis;
public PonudiAdapter(Context context) {
ponudis = new ArrayList<>();
this.context = context;
}
...
}
Then in your class where you initialize the PonudiAdapter, pass the application context.
PonudiAdapter adapter = new PonudiAdapter(getApplicationContext());
Hope this answers your question. Please feel free to comment in case you run into any other issues.
I will encode user input into a single URL, I use Uri.encode but error response remains 400. how to make the encode work?
the result is that "space" is replaced with "%20" but the response still fails
And this is my code.,
public void OnQuerySubmit() {
searchView.setOnQueryTextListener(new MaterialSearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
String UrlEncode = AppConfig.URL_GETJOBS + Uri.encode(query);
progressDialog.setMessage("Mencari...");
showDialog();
jobList.clear();
getJobs(UrlEncode);
homeRecyclerViewAdapter.notifyDataSetChanged();
hideDialog();
return false;
}
});
}
public List<Job> getJobs(String urlGetjobs) {
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, urlGetjobs, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d(TAG, "onResponse: " + response.toString());
try {
boolean error = response.getBoolean("error");
if(!error) {
JSONArray transaksiArray = response.getJSONArray("transaksi");
for(int i = 0; i < transaksiArray.length(); i++) {
JSONObject seluruhTrans = transaksiArray.getJSONObject(i);
Job job = new Job();
job.setTitle(seluruhTrans.getString("title"));
job.setNamaPerusahaan(seluruhTrans.getString("nama_perusahaan"));
job.setLokasi(seluruhTrans.getString("lokasi"));
job.setKriteria_1(seluruhTrans.getString("kriteria_1"));
job.setKriteria_2(seluruhTrans.getString("kriteria_2"));
job.setKriteria_3(seluruhTrans.getString("kriteria_3"));
job.setGaji(seluruhTrans.getString("gaji"));
job.setImg_logo(seluruhTrans.getString("img_logo"));
job.setTanggal(seluruhTrans.getString("tanggal"));
job.setId_post(seluruhTrans.getString("id_post"));
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("title", job.getTitle());
editor.putString("nama_perusahaan", job.getNamaPerusahaan());
editor.putString("lokasi", job.getLokasi());
editor.putString("kriteria_1", job.getKriteria_1());
editor.putString("kriteria_2", job.getKriteria_2());
editor.putString("kriteria_3", job.getKriteria_3());
editor.putString("gaji", job.getGaji());
editor.putString("img_logo", job.getImg_logo());
editor.putString("tanggal", job.getTanggal());
editor.putString("id_post", job.getId_post());
editor.commit();
jobList.add(job);
}
}
homeRecyclerViewAdapter.notifyDataSetChanged();
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(getActivity(), e.getMessage(), Toast.LENGTH_SHORT).show();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
if (error instanceof NoConnectionError || error instanceof TimeoutError || error instanceof NoConnectionError){
Toast.makeText(getActivity(), "Please Check your Connection!", Toast.LENGTH_SHORT).show();
}
}
});
AppController.getInstance().addToRequestQueue(jsonObjectRequest);
return jobList;
}
Any help would be appreciated.
Modify your code like this
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_home, container, false);
queue = Volley.newRequestQueue(getActivity());
searchView = view.findViewById(R.id.search_view);
recyclerView = view.findViewById(R.id.recyclerview);
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
jobList = new ArrayList<>();
homeRecyclerViewAdapter = new HomeRecyclerViewAdapter(getActivity(), jobList);
recyclerView.setAdapter(homeRecyclerViewAdapter);
getJobs(""); //get your data as it is
OnQuerySubmit();
return view;
}
public void OnQuerySubmit() {
searchView.setOnQueryTextListener(new MaterialSearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
getJobs(query);
return false;
}
});
}
public void getJobs(final String query) {
StringRequest jsonObjectRequest = new StringRequest(Request.Method.GET, AppConfig.URL_GETJOBS, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d(TAG, "onResponse: " + response);
try {
JSONObject jsonObject=new JSONObject(response);
boolean error = jsonObject.getBoolean("error");
if (!error) {
jobList.clear();
JSONArray transaksiArray = jsonObject.JSONArray("transaksi");
....
....
....
jobList.add(job);
adapter.notifyDataSetChanged();
}
} catch (JSONException e) {
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e(Tag, error.toString());
}
}) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> map = new HashMap<>();
if(!TextUtils.isEmpty(query){
map.put("title", query);
}else{}
return map;
}
};
AppController.getInstance().addToRequestQueue(jsonObjectRequest);
}
package com.mimdudin.carekkerje.Activities;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;
import com.android.volley.NoConnectionError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.TimeoutError;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.miguelcatalan.materialsearchview.MaterialSearchView;
import com.mimdudin.carekkerje.Adapter.HomeRecyclerViewAdapter;
import com.mimdudin.carekkerje.Helper.AppController;
import com.mimdudin.carekkerje.Model.Job;
import com.mimdudin.carekkerje.R;
import com.mimdudin.carekkerje.Util.AppConfig;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import static com.android.volley.VolleyLog.TAG;
/**
* A simple {#link Fragment} subclass.
*/
public class HomeFragment extends Fragment {
private RecyclerView recyclerView;
private HomeRecyclerViewAdapter homeRecyclerViewAdapter;
private List<Job> jobList;
private RequestQueue queue;
private MaterialSearchView searchView;
private ProgressDialog progressDialog;
private SharedPreferences sharedPreferences;
public HomeFragment() {
// Required empty public constructor
}
public static HomeFragment newInstance() {
HomeFragment homeFragment = new HomeFragment();
return homeFragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_home, container, false);
queue = Volley.newRequestQueue(getActivity());
searchView = view.findViewById(R.id.search_view);
recyclerView = view.findViewById(R.id.recyclerview);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
jobList = new ArrayList<>();
jobList = getJobs(AppConfig.URL_GETJOBS);
homeRecyclerViewAdapter = new HomeRecyclerViewAdapter(getActivity(), jobList);
recyclerView.setAdapter(homeRecyclerViewAdapter);
homeRecyclerViewAdapter.notifyDataSetChanged();
sharedPreferences = getActivity().getSharedPreferences("data", Context.MODE_PRIVATE);
progressDialog = new ProgressDialog(getContext());
progressDialog.setCancelable(false);
OnQuerySubmit();
return view;
}
public void OnQuerySubmit(){
searchView.setOnQueryTextListener(new MaterialSearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
String UrlEncode = AppConfig.URL_GETJOBS + Uri.encode(query);
progressDialog.setMessage("Mencari...");
showDialog();
jobList.clear();
getJobs(UrlEncode);
homeRecyclerViewAdapter.notifyDataSetChanged();
hideDialog();
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
return false;
}
});
}
public List<Job> getJobs(String urlGetjobs) {
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, urlGetjobs, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d(TAG, "onResponse: " + response.toString());
try {
boolean error = response.getBoolean("error");
if(!error) {
JSONArray transaksiArray = response.getJSONArray("transaksi");
for(int i = 0; i < transaksiArray.length(); i++) {
JSONObject seluruhTrans = transaksiArray.getJSONObject(i);
Job job = new Job();
job.setTitle(seluruhTrans.getString("title"));
job.setNamaPerusahaan(seluruhTrans.getString("nama_perusahaan"));
job.setLokasi(seluruhTrans.getString("lokasi"));
job.setKriteria_1(seluruhTrans.getString("kriteria_1"));
job.setKriteria_2(seluruhTrans.getString("kriteria_2"));
job.setKriteria_3(seluruhTrans.getString("kriteria_3"));
job.setGaji(seluruhTrans.getString("gaji"));
job.setImg_logo(seluruhTrans.getString("img_logo"));
job.setTanggal(seluruhTrans.getString("tanggal"));
job.setId_post(seluruhTrans.getString("id_post"));
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("title", job.getTitle());
editor.putString("nama_perusahaan", job.getNamaPerusahaan());
editor.putString("lokasi", job.getLokasi());
editor.putString("kriteria_1", job.getKriteria_1());
editor.putString("kriteria_2", job.getKriteria_2());
editor.putString("kriteria_3", job.getKriteria_3());
editor.putString("gaji", job.getGaji());
editor.putString("img_logo", job.getImg_logo());
editor.putString("tanggal", job.getTanggal());
editor.putString("id_post", job.getId_post());
editor.commit();
jobList.add(job);
}
}
homeRecyclerViewAdapter.notifyDataSetChanged();
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(getActivity(), e.getMessage(), Toast.LENGTH_SHORT).show();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
if (error instanceof NoConnectionError || error instanceof TimeoutError || error instanceof NoConnectionError){
Toast.makeText(getActivity(), "Please Check your Connection!", Toast.LENGTH_SHORT).show();
}
}
});
AppController.getInstance().addToRequestQueue(jsonObjectRequest);
return jobList;
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.menu_main, menu);
MenuItem item = menu.findItem(R.id.action_search);
searchView.setMenuItem(item);
super.onCreateOptionsMenu(menu, inflater);
}
public void showDialog() {
if (!progressDialog.isShowing()) {
progressDialog.show();
}
}
public void hideDialog(){
if (progressDialog.isShowing()) {
progressDialog.dismiss();
}
}
}
HomeRecyclerviewAdapter.java
package com.mimdudin.carekkerje.Adapter;
import android.app.FragmentManager;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.mimdudin.carekkerje.Activities.HomeFragment;
import com.mimdudin.carekkerje.Activities.HomeFragmentDetail;
import com.mimdudin.carekkerje.Model.Job;
import com.mimdudin.carekkerje.R;
import java.util.List;
/**
* Created by master on 12/12/17.
*/
public class HomeRecyclerViewAdapter extends RecyclerView.Adapter<HomeRecyclerViewAdapter.ViewHolder> {
private Context context;
private List<Job> jobList;
public HomeRecyclerViewAdapter(Context context, List<Job> jobs){
this.context = context;
jobList = jobs;
}
#Override
public HomeRecyclerViewAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.home_row, parent, false);
return new ViewHolder(view, context);
}
#Override
public void onBindViewHolder(HomeRecyclerViewAdapter.ViewHolder holder, int position) {
Job job = jobList.get(position);
holder.title.setText(job.getTitle());
holder.namaPerusahaan.setText(job.getNamaPerusahaan());
holder.kriteria_1.setText(job.getKriteria_1());
holder.kriteria_2.setText(job.getKriteria_2());
holder.kriteria_3.setText(job.getKriteria_3());
holder.gaji.setText(job.getGaji());
holder.lokasi.setText(job.getLokasi());
holder.tanggal.setText(job.getTanggal());
String img_logoLink = job.getImg_logo();
Glide.with(context)
.load(img_logoLink) // URL
.apply(new RequestOptions().placeholder(android.R.drawable.ic_dialog_info)
.error(android.R.drawable.ic_dialog_alert).centerCrop().dontAnimate()
// .centerCrop(), .crossFade(), .thumbnail(), .dontAnimate(), .dontTransform() BitmapTransformation(.circleCrop())
)
.into(holder.img_logo); //TARGET GAMBAR YANG NAK DIUBAH
}
#Override
public int getItemCount() {
return jobList.size();
}
public class ViewHolder extends RecyclerView.ViewHolder{
TextView title;
TextView namaPerusahaan;
TextView lokasi;
TextView kriteria_1;
TextView kriteria_2;
TextView kriteria_3;
TextView gaji;
ImageView img_logo;
TextView tanggal;
public ViewHolder(final View itemView, final Context ctx) {
super(itemView);
context = ctx;
title = itemView.findViewById(R.id.titleID);
namaPerusahaan = itemView.findViewById(R.id.namaPerusahaanID);
kriteria_1 = itemView.findViewById(R.id.satuTv);
kriteria_2 = itemView.findViewById(R.id.duaTv);
kriteria_3 = itemView.findViewById(R.id.tigaTv);
gaji = itemView.findViewById(R.id.gajiID);
lokasi = itemView.findViewById(R.id.lokasiID);
img_logo = itemView.findViewById(R.id.img_logoID);
tanggal = itemView.findViewById(R.id.tanggalID);
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
HomeFragmentDetail fragmentDetail = new HomeFragmentDetail();
Bundle bundle = new Bundle();
Job job = jobList.get(getAdapterPosition());
bundle.putSerializable("job", job);
fragmentDetail.setArguments(bundle);
AppCompatActivity activity = (AppCompatActivity) itemView.getContext();
android.support.v4.app.FragmentManager fragmentManager = activity.getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction().addToBackStack(null);
fragmentTransaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
fragmentTransaction.replace(R.id.frame_fragmenthome, fragmentDetail);
fragmentTransaction.commit();
//// Intent intent = new Intent(context, HomeDetailActivity.class);
//// intent.putExtra("job", job);
//// ctx.startActivity(intent);
}
});
}
}
}
HomeFragmentDetail.java
package com.mimdudin.carekkerje.Activities;
import android.content.Context;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.mimdudin.carekkerje.Model.Job;
import com.mimdudin.carekkerje.R;
/**
* A simple {#link Fragment} subclass.
* Activities that contain this fragment must implement the
* to handle interaction events.
*/
public class HomeFragmentDetail extends Fragment {
private TextView tvDeskripsi;
private TextView tvIndustri;
public HomeFragmentDetail() {
// Required empty public constructor
}
public static HomeFragmentDetail newInstance(){
HomeFragmentDetail homeFragmentDetail = new HomeFragmentDetail();
return homeFragmentDetail;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_home_fragment_detail, container, false);
tvDeskripsi = view.findViewById(R.id.tvDeskripsi);
tvIndustri = view.findViewById(R.id.tvIndustri);
Bundle bundle = getArguments();
Job job = (Job) bundle.getSerializable("job");
String PostID = job.getId_post();
String titleID = job.getTitle();
tvDeskripsi.setText(PostID);
tvIndustri.setText(titleID);
return view;
// DataHolder dataholder=new DataHolder("1","TestName");
// Bundle bundle=new Bundle();
// bundle.putSerializable("obj",dataholder);
// Fragment fragment=new FragmentB();
// fragment.setArguments(bundle);
// fragmentManager = getActivity(). getSupportFragmentManager();
// fragmentTransaction = fragmentManager .beginTransaction();
// fragmentTransaction.add(R.id.container, fragment);
// fragmentTransaction.commit();
//Job job = (Job) getIntent.getSerializableExtra("job");
// Bundle bundle = getArguments();
// Job job = (Job) bundle.getSerializable("job");
// String jobID = job.getId_post();
// String titleID = job.getTitle();
}
}
AppConfig.java
package com.mimdudin.carekkerje.Util;
/**
* Created by master on 10/12/17.
*/
public class AppConfig {
public static final String URL = "http://192.168.43.142/Carekkerje/v1";
public static final String URL_REGISTER = URL + "/daftarUser";
public static final String URL_LOGIN = URL + "/loginUser";
public static final String URL_GETJOBS = URL + "/seluruhLowongan/";
public static final String URL_GETJOBSS = URL + "/seluruhLowongan/:title";
}
I run my App on my phone. Everything works perfectly.. But after i check in my logcat for the debug.
It's show me this error.
E/HAL: hw_get_module_by_class: module name gralloc
E/HAL: hw_get_module_by_class: module name gralloc
It's show when user run the app for the first time. It's show just in time the app show splash screen. I'm not sure which code that make this thing happen.
So i'll show you my splash code and my fragment home code.
so this is my splasactivity code :
package com.apps.mathar;
import android.content.Intent;
import android.content.res.Resources;
import android.os.Build;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.TypedValue;
import android.view.Window;
import android.view.WindowManager;
import com.apps.utils.Constant;
import com.apps.utils.JsonUtils;
public class SplashActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_splash);
// hideStatusBar();
setStatusColor();
try {
Constant.isFromPush = getIntent().getExtras().getBoolean("ispushnoti", false);
Constant.pushID = getIntent().getExtras().getString("noti_nid");
} catch (Exception e) {
Constant.isFromPush = false;
}
try {
Constant.isFromNoti = getIntent().getExtras().getBoolean("isnoti", false);
} catch (Exception e) {
Constant.isFromNoti = false;
}
JsonUtils jsonUtils = new JsonUtils(SplashActivity.this);
Resources r = getResources();
float padding = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, Constant.GRID_PADDING, r.getDisplayMetrics());
Constant.columnWidth = (int) ((jsonUtils.getScreenWidth() - ((Constant.NUM_OF_COLUMNS + 1) * padding)) / Constant.NUM_OF_COLUMNS);
if(!Constant.isFromNoti) {
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
openMainActivity();
}
}, 2000);
} else {
openMainActivity();
}
}
private void openMainActivity() {
Intent intent = new Intent(SplashActivity.this,MainActivity.class);
startActivity(intent);
finish();
}
public void setStatusColor()
{
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP)
{
Window window = getWindow();
window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
window.setStatusBarColor(getResources().getColor(R.color.statusBar));
}
}
}
And this is my fragmenthome code
package com.apps.mathar;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.apps.adapter.AdapterRecent;
import com.apps.item.ItemSong;
import com.apps.utils.Constant;
import com.apps.utils.DBHelper;
import com.apps.utils.JsonUtils;
import com.apps.utils.RecyclerItemClickListener;
import com.apps.utils.ZProgressHUD;
import com.google.android.gms.ads.AdListener;
import com.squareup.picasso.Callback;
import com.squareup.picasso.Picasso;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
public class FragmentHome extends Fragment {
DBHelper dbHelper;
RecyclerView recyclerView;
ArrayList<ItemSong> arrayList;
ArrayList<ItemSong> arrayList_recent;
AdapterRecent adapterRecent;
ZProgressHUD progressHUD;
LinearLayoutManager linearLayoutManager;
public ViewPager viewpager;
ImagePagerAdapter adapter;
TextView textView_empty;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
View rootView = inflater.inflate(R.layout.fragment_home, container, false);
setHasOptionsMenu(true);
dbHelper = new DBHelper(getActivity());
progressHUD = ZProgressHUD.getInstance(getActivity());
progressHUD.setMessage(getActivity().getResources().getString(R.string.loading));
progressHUD.setSpinnerType(ZProgressHUD.FADED_ROUND_SPINNER);
textView_empty = (TextView)rootView.findViewById(R.id.textView_recent_empty);
adapter = new ImagePagerAdapter();
viewpager = (ViewPager)rootView.findViewById(R.id.viewPager_home);
viewpager.setPadding(80,20,80,20);
viewpager.setClipToPadding(false);
viewpager.setPageMargin(40);
viewpager.setClipChildren(false);
// viewpager.setPageTransformer(true,new BackgroundToForegroundTransformer());
arrayList = new ArrayList<ItemSong>();
arrayList_recent = new ArrayList<ItemSong>();
recyclerView = (RecyclerView)rootView.findViewById(R.id.recyclerView_home_recent);
linearLayoutManager = new LinearLayoutManager(getActivity(),LinearLayoutManager.HORIZONTAL,false);
recyclerView.setLayoutManager(linearLayoutManager);
recyclerView.setItemAnimator(new DefaultItemAnimator());
recyclerView.setHasFixedSize(true);
if (JsonUtils.isNetworkAvailable(getActivity())) {
new LoadLatestNews().execute(Constant.URL_LATEST);
} else {
Toast.makeText(getActivity(), getResources().getString(R.string.internet_not_conn), Toast.LENGTH_SHORT).show();
}
recyclerView.addOnItemTouchListener(new RecyclerItemClickListener(getActivity(), new RecyclerItemClickListener.OnItemClickListener() {
#Override
public void onItemClick(View view, int position) {
if(JsonUtils.isNetworkAvailable(getActivity())) {
Constant.isOnline = true;
Constant.arrayList_play.clear();
Constant.arrayList_play.addAll(arrayList_recent);
Constant.playPos = position;
((MainActivity)getActivity()).changeText(arrayList_recent.get(position).getMp3Name(),arrayList_recent.get(position).getCategoryName(),position+1,arrayList_recent.size(),arrayList_recent.get(position).getDuration(),arrayList_recent.get(position).getImageBig(),"home");
Constant.context = getActivity();
if(position == 0) {
Intent intent = new Intent(getActivity(), PlayerService.class);
intent.setAction(PlayerService.ACTION_FIRST_PLAY);
getActivity().startService(intent);
}
} else {
Toast.makeText(getActivity(), getResources().getString(R.string.internet_not_conn), Toast.LENGTH_SHORT).show();
}
}
}));
return rootView;
}
private class LoadLatestNews extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
progressHUD.show();
arrayList.clear();
super.onPreExecute();
}
#Override
protected String doInBackground(String... strings) {
try {
String json = JsonUtils.getJSONString(strings[0]);
JSONObject mainJson = new JSONObject(json);
JSONArray jsonArray = mainJson.getJSONArray(Constant.TAG_ROOT);
JSONObject objJson = null;
for (int i = 0; i < jsonArray.length(); i++) {
objJson = jsonArray.getJSONObject(i);
String id = objJson.getString(Constant.TAG_ID);
String cid = objJson.getString(Constant.TAG_CAT_ID);
String cname = objJson.getString(Constant.TAG_CAT_NAME);
String artist = objJson.getString(Constant.TAG_ARTIST);
String name = objJson.getString(Constant.TAG_SONG_NAME);
String url = objJson.getString(Constant.TAG_MP3_URL);
String desc = objJson.getString(Constant.TAG_DESC);
String duration = objJson.getString(Constant.TAG_DURATION);
String image = objJson.getString(Constant.TAG_THUMB_B).replace(" ","%20");
String image_small = objJson.getString(Constant.TAG_THUMB_S).replace(" ","%20");
ItemSong objItem = new ItemSong(id,cid,cname,artist,url,image,image_small,name,duration,desc);
arrayList.add(objItem);
}
return "1";
} catch (JSONException e) {
e.printStackTrace();
return "0";
} catch (Exception ee) {
ee.printStackTrace();
return "0";
}
}
#Override
protected void onPostExecute(String s) {
recyclerView.setAdapter(adapterRecent);
if(s.equals("1")) {
progressHUD.dismissWithSuccess(getResources().getString(R.string.success));
// setLatestVariables(0);
if(Constant.isAppFirst) {
if(arrayList.size()>0) {
Constant.isAppFirst = false;
Constant.arrayList_play.addAll(arrayList);
((MainActivity)getActivity()).changeText(arrayList.get(0).getMp3Name(),arrayList.get(0).getCategoryName(),1,arrayList.size(),arrayList.get(0).getDuration(),arrayList.get(0).getImageBig(),"home");
Constant.context = getActivity();
}
}
viewpager.setAdapter(adapter);
loadRecent();
// adapterPagerTrending = new AdapterPagerTrending(getActivity(),Constant.arrayList_trending);
// viewPager_trending.setAdapter(adapterPagerTrending);
// adapterTopStories = new AdapterTopStories(getActivity(),Constant.arrayList_topstories);
// listView_topstories.setAdapter(adapterTopStories);
// setListViewHeightBasedOnChildren(listView_topstories);
adapterRecent.notifyDataSetChanged();
} else {
progressHUD.dismissWithFailure(getResources().getString(R.string.error));
Toast.makeText(getActivity(), getResources().getString(R.string.server_no_conn), Toast.LENGTH_SHORT).show();
}
super.onPostExecute(s);
recyclerView.setAdapter(adapterRecent);
}
}
private void loadRecent() {
arrayList_recent = dbHelper.loadDataRecent();
adapterRecent = new AdapterRecent(getActivity(),arrayList_recent);
recyclerView.setAdapter(adapterRecent);
if(arrayList_recent.size() == 0) {
recyclerView.setVisibility(View.GONE);
textView_empty.setVisibility(View.VISIBLE);
} else {
recyclerView.setVisibility(View.VISIBLE);
textView_empty.setVisibility(View.GONE);
}
}
private class ImagePagerAdapter extends PagerAdapter {
private LayoutInflater inflater;
public ImagePagerAdapter() {
// TODO Auto-generated constructor stub
inflater = (LayoutInflater) getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
return arrayList.size();
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view.equals(object);
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
View imageLayout = inflater.inflate(R.layout.viewpager_home, container, false);
assert imageLayout != null;
ImageView imageView = (ImageView) imageLayout.findViewById(R.id.imageView_pager_home);
final ProgressBar spinner = (ProgressBar) imageLayout.findViewById(R.id.loading_home);
TextView title = (TextView) imageLayout.findViewById(R.id.textView_pager_home_title);
TextView cat = (TextView) imageLayout.findViewById(R.id.textView_pager_home_cat);
RelativeLayout rl = (RelativeLayout)imageLayout.findViewById(R.id.rl_homepager);
title.setText(arrayList.get(position).getMp3Name());
cat.setText(arrayList.get(position).getCategoryName());
Picasso.with(getActivity())
.load(arrayList.get(position).getImageBig())
.placeholder(R.mipmap.app_icon)
.into(imageView, new Callback() {
#Override
public void onSuccess() {
spinner.setVisibility(View.GONE);
}
#Override
public void onError() {
spinner.setVisibility(View.GONE);
}
});
rl.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(JsonUtils.isNetworkAvailable(getActivity())) {
//showInter();
playIntent();
} else {
Toast.makeText(getActivity(), getResources().getString(R.string.internet_not_conn), Toast.LENGTH_SHORT).show();
}
}
});
container.addView(imageLayout, 0);
return imageLayout;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
container.removeView((View) object);
}
}
/* private void showInter() {
Constant.adCount = Constant.adCount + 1;
if(Constant.adCount % Constant.adDisplay == 0) {
((MainActivity)getActivity()).mInterstitial.setAdListener(new AdListener() {
#Override
public void onAdClosed() {
playIntent();
super.onAdClosed();
}
});
if(((MainActivity)getActivity()).mInterstitial.isLoaded()) {
((MainActivity)getActivity()).mInterstitial.show();
((MainActivity)getActivity()).loadInter();
} else {
playIntent();
}
} else {
playIntent();
}
}
*/
private void playIntent() {
Constant.isOnline = true;
int pos = viewpager.getCurrentItem();
Constant.arrayList_play.clear();
Constant.arrayList_play.addAll(arrayList);
Constant.playPos = pos;
((MainActivity)getActivity()).changeText(arrayList.get(pos).getMp3Name(),arrayList.get(pos).getCategoryName(),pos+1,arrayList.size(),arrayList.get(pos).getDuration(),arrayList.get(pos).getImageBig(),"home");
Constant.context = getActivity();
if(pos == 0) {
Intent intent = new Intent(getActivity(), PlayerService.class);
intent.setAction(PlayerService.ACTION_FIRST_PLAY);
getActivity().startService(intent);
}
}
}
Once more, i'm sure what's going on here.
I'm looking this error since 3 days ago but i have checked my code, i dont know what is wrong with this code.
This kind of error occurs when you have a loop that doesn't terminate.I also faced the similar kind of situation and It took me literally two days to find out the root cause of problem.
My problem was:
When I run the above code, I used to get this kind of error
hw_get module_by class _gralloc... .
I was really frustrated because I was not able to find out the root cause and luckily I found out that the above section of the code was the main cause because the loop never goes to terminate in the above section and when I found about the problem main cause I replaced it by:
Then, the problem was solved..
So maybe your problem lies within the loop or similar kind of situations..
I have been reading the different answers here on stackoverflow and on this blog post and tried to implement their solutions but I am still getting the error: No adapter attached; skipping layout.
RecyclerAdapter:
package vn.jupviec.frontend.android.monitor.app.ui.candidate;
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.w3c.dom.Text;
import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import butterknife.BindView;
import vn.jupviec.frontend.android.monitor.app.R;
import vn.jupviec.frontend.android.monitor.app.domain.candidate.TrainingDTO;
import vn.jupviec.frontend.android.monitor.app.util.Utils;
/**
* Created by Windows 10 Gamer on 16/12/2016.
*/
public class RecyclerAdapter extends RecyclerView.Adapter<RecyclerAdapter.RecyclerViewHolder> {
private static final String TAG = "RecyclerView";
private List<TrainingDTO> mTrainingDTOs;
private Context mContext;
private LayoutInflater mLayoutInflater;
private String today;
private static final DateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
AdapterInterface buttonListener;
public RecyclerAdapter(Context context, List<TrainingDTO> datas, AdapterInterface buttonListener) {
mContext = context;
mTrainingDTOs = datas;
this.mLayoutInflater = LayoutInflater.from(mContext);
this.buttonListener = buttonListener;
}
#Override
public RecyclerViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.candidate_item, parent, false);
// View itemView = mLayoutInflater.inflate(R.layout.candidate_item, parent, false);
return new RecyclerViewHolder(itemView);
}
#Override
public void onBindViewHolder(RecyclerViewHolder holder, int position) {
final ObjectMapper mapper = new ObjectMapper();
final TrainingDTO trainingDTO = mapper.convertValue(mTrainingDTOs.get(position), TrainingDTO.class);
holder.tvName.setText(trainingDTO.getMaidName());
holder.status.setVisibility(View.GONE);
Date date = new Date();
String currentDate = sdf.format(date);
for (TrainingDTO.TrainingDetailDto td : trainingDTO.getListTrain()) {
today = Utils.formatDate((long) td.getTrainingDate(),"dd/MM/yyyy");
break;
}
if(currentDate.equals(today)) {
holder.status.setVisibility(View.VISIBLE);
holder.status.setText("(Mới)");
}
holder.btnHistory.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(mContext,R.string.msg_no_candidate_history,Toast.LENGTH_SHORT).show();
}
});
holder.btnTest.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
buttonListener.showComment(trainingDTO);
}
});
}
#Override
public int getItemCount() {
int size ;
if(mTrainingDTOs != null && !mTrainingDTOs.isEmpty()) {
size = mTrainingDTOs.size();
}
else {
size = 0;
}
return size;
}
class RecyclerViewHolder extends RecyclerView.ViewHolder {
private TextView tvName;
private Button btnTest;
private Button btnHistory;
private TextView status;
public RecyclerViewHolder(View itemView) {
super(itemView);
tvName = (TextView) itemView.findViewById(R.id.txtName);
btnTest = (Button) itemView.findViewById(R.id.btnTest);
btnHistory = (Button) itemView.findViewById(R.id.btnHistory);
status = (TextView)itemView.findViewById(R.id.status);
}
}
public boolean removeItem(int position) {
if (mTrainingDTOs.size() >= position + 1) {
mTrainingDTOs.remove(position);
return true;
}
return false;
}
public interface AdapterInterface {
void showComment(TrainingDTO trainingDTO);
void showHistory(TrainingDTO trainingDTO);
}
}
FragmentTapNew:
package vn.jupviec.frontend.android.monitor.app.ui.candidate;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ClipDrawable;
import android.graphics.drawable.ShapeDrawable;
import android.graphics.drawable.shapes.RoundRectShape;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;
import retrofit.Callback;
import retrofit.RetrofitError;
import retrofit.client.Response;
import vn.jupviec.frontend.android.monitor.app.R;
import vn.jupviec.frontend.android.monitor.app.domain.ResultDTO;
import vn.jupviec.frontend.android.monitor.app.domain.candidate.TrainingDTO;
import vn.jupviec.frontend.android.monitor.app.domain.training.CandidateService;
import vn.jupviec.frontend.android.monitor.app.util.Constants;
import vn.jupviec.frontend.android.monitor.app.util.Utils;
/**
* Created by Windows 10 Gamer on 09/12/2016.
*/
public class FragmentTapNew extends Fragment implements RecyclerAdapter.AdapterInterface {
private static final String TAG = FragmentTapNew.class.getSimpleName();
Activity myContext = null;
private OnItemSelectedListener listener;
ShapeDrawable shapeDrawable;
#BindView(R.id.lvToday)
RecyclerView lvToday;
#BindView(R.id.textView)
TextView textView;
#BindView(R.id.pb_loading)
ProgressBar pbLoading;
private Unbinder unbinder;
private boolean loading = true;
int pastVisiblesItems, visibleItemCount, totalItemCount;
ArrayList<TrainingDTO> mTrainingDTO ;
RecyclerAdapter mTrainingDTOAdapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.activity_candidate_training, container, false);
unbinder = ButterKnife.bind(this, v);
initViews();
return v;
}
private void initViews() {
LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity().getApplicationContext());
layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
lvToday.setHasFixedSize(true);
lvToday.setNestedScrollingEnabled(false);
Thread t = new Thread(new Runnable() {
#Override
public void run() {
today();
}
});
t.start();
}
private boolean isNetworkConnected() {
ConnectivityManager cm = (ConnectivityManager) getActivity().getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo ni = cm.getActiveNetworkInfo();
if (ni == null) {
Toast.makeText(getActivity(), R.string.err_cannot_establish_connection, Toast.LENGTH_SHORT).show();
return false;
} else
return true;
}
private void today() {
if(isNetworkConnected()){
String token = "a";
Integer date = 0;
setLoadingVisible(true);
CandidateService.getApiDummyClient(getContext()).getCandidate(
token,
date,
Constants.TRAINING,
Arrays.asList(Constants.TRAINING_DAY_NEW),
new Callback<ResultDTO>() {
#Override
public void success(ResultDTO resultDTO, Response response) {
setLoadingVisible(false);
mTrainingDTO = (ArrayList<TrainingDTO>) resultDTO.getData();
if (mTrainingDTO.size() == 0) {
if(textView!=null) {
textView.setVisibility(View.VISIBLE);
textView.setTextColor(Color.RED);
textView.setGravity(Gravity.CENTER | Gravity.BOTTOM);
}
} else {
if(textView!=null) {
textView.setVisibility(View.GONE);
}
if(null==mTrainingDTOAdapter) {
mTrainingDTOAdapter = new RecyclerAdapter(getActivity(), mTrainingDTO, FragmentTapNew.this);
lvToday.setAdapter(mTrainingDTOAdapter);
} else {
lvToday.setAdapter(mTrainingDTOAdapter);
mTrainingDTOAdapter.notifyDataSetChanged();
}
lvToday.invalidate();
}
}
#Override
public void failure(RetrofitError error) {
Log.e(TAG, "JV-ERROR: " + error.getMessage());
Log.e(TAG, "JV-ERROR: " + error.getSuccessType());
}
});
}
}
#Override
public void onResume() {
setLoadingVisible(false);
initViews();
lvToday.setAdapter(mTrainingDTOAdapter);
super.onResume();
}
#Override
public void onDestroyView() {
super.onDestroyView();
unbinder.unbind();
}
private void setLoadingVisible(boolean visible) {
// pbLoading.getIndeterminateDrawable().setColorFilter(0xFFFF0000, android.graphics.PorterDuff.Mode.MULTIPLY);
if(pbLoading!=null) {
pbLoading.setVisibility(visible ? View.VISIBLE : View.GONE);
lvToday.setVisibility(visible ? View.GONE : View.VISIBLE);
}
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
if (activity instanceof OnItemSelectedListener) {
listener = (OnItemSelectedListener) activity;
} else {
throw new ClassCastException(activity.toString()
+ " phải implemenet MyListFragment.OnItemSelectedListener");
}
}
#Override
public void onDetach() {
super.onDetach();
listener = null;
}
#Override
public void showComment(TrainingDTO trainingDTO) {
Intent intent = new Intent(getContext(), CommentActivity.class);
intent.putExtra(Constants.ARG_NAME_DETAIL, trainingDTO);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
getContext().startActivity(intent);
}
#Override
public void showHistory(TrainingDTO trainingDTO) {
Intent intent = new Intent(getContext(), HistoryActivity.class);
intent.putExtra(Constants.ARG_CANDIDATE_HISTORY_DETAIL, trainingDTO);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
getContext().startActivity(intent);
}
public interface OnItemSelectedListener {
void showComment(TrainingDTO trainingDTO);
void showHistory(TrainingDTO trainingDTO);
}
}
The first, you don't need to set adapter multiple time, only set adapter at the first time in your method initView().
LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity().getApplicationContext());
layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
lvToday.setHasFixedSize(true);
lvToday.setNestedScrollingEnabled(false);
if(mTrainingDTO == null) {
mTrainingDTO = new ArrayList<>();
}
if(null == mTrainingDTOAdapter ) {
mTrainingDTOAdapter = new RecyclerAdapter(getActivity(), mTrainingDTO, FragmentTapNew.this);
}
lvToday.setAdapter(mTrainingDTOAdapter);
Thread t = new Thread(new Runnable() {
#Override
public void run() {
today();
}
});
t.start();
After that, you don't need to call lvToday.setAdapter(mTrainingDTOAdapter);
many times. Just call mTrainingDTOAdapter.notifyDataSetChanged(); if having any changes in your data mTrainingDTO.
The errorlog - error:No adapter attached; skipping layout indicates that you've attached LayoutManager but you haven't attached an adapter yet, so recyclerview will skip layout. I'm not sure but, in other words recyclerView will skip layout measuring at the moment.
to prevent this errorLog Try to set an adapter with an empty dataSet i.e. ArrayList or
Attach LayoutManager just before you are setting your adapter.
Try this,
private void initViews() {
LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity().getApplicationContext());
layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
LinearLayoutManager mLinearLayoutManager = new LinearLayoutManager(getActivity());
lvToday.setLayoutManager(mLinearLayoutManager);
lvToday.setHasFixedSize(true);
lvToday.setNestedScrollingEnabled(false);
Thread t = new Thread(new Runnable() {
#Override
public void run() {
today();
}
});
t.start();
}
I am trying to get youtube id from databse to playing the video. Then using a recyclerview in my layout I want to display it on my device. This I do by using an string array. I just want to play the video of the youtube in a recyclerview. But I keep getting error
"java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String java.lang.Object.toString()' on a null object reference".
My code is as follows:
package com.echessa.videotube;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.google.android.youtube.player.YouTubeInitializationResult;
import com.google.android.youtube.player.YouTubeStandalonePlayer;
import com.google.android.youtube.player.YouTubeThumbnailLoader;
import com.google.android.youtube.player.YouTubeThumbnailView;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
/**
* Created by ofaroque on 8/13/15.
*/
public class RecyclerAdapter extends RecyclerView.Adapter<RecyclerAdapter.VideoInfoHolder> {
ConnectionClass connectionClass;
//these ids are the unique id for each video
String[] VideoID;
// String[] VideoID = {"zlQMI01A3gg","zlQMI01A3gg"};
{
connectionClass = new ConnectionClass();
ResultSet Video = null;
String data = "";
String msg = "";
Connection con = connectionClass.CONN();
{
String command = "SELECT TOP 1 videoData FROM tab1";
try
{
Statement stmt = con.createStatement();
Video = stmt.executeQuery(command);
if(Video != null)
{
//while (Video.next())
int size = VideoID.length;
for (int i=0; i<size; i++)
{
data = Video.getString(1);
VideoID[1] = data;
// Toast.makeText(ctx.getApplicationContext(), data , Toast.LENGTH_SHORT).show();
}
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
#Override
public int getItemCount() {
return VideoID.length;
/* try {
return VideoID.length;
} catch (Exception e) {
return 0;
}*/
}
and my mainactivity class is belw
package com.echessa.videotube;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
public class MainActivity extends AppCompatActivity {
private static String TAG = MainActivity.class.getSimpleName();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.manisha);
RecyclerView recyclerView = (RecyclerView) findViewById(R.id.list);
recyclerView.setHasFixedSize(true);
//to use RecycleView, you need a layout manager. default is LinearLayoutManager
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
recyclerView.setLayoutManager(linearLayoutManager);
RecyclerAdapter adapter = new RecyclerAdapter(this);
recyclerView.setAdapter(adapter);
}
}
when play the video through String[] VideoID = {"zlQMI01A3gg","zlQMI01A3gg"}; this the video is successfully playing but when adding this video in loop getting error
i use YouTubePlayerSupportFragment play on recyclerview and it works.
#Override
public void onBindViewHolder(final ViewHolder holder, final int position) {
Log.i("state", "work");
/* if (liststate.get(position)!=0) {*/
final YoutubeVideoViewHolder holder1 = (YoutubeVideoViewHolder) holder;
YoutubeVideo youtubeVideo = mYoutubeVideos.get(position);
YouTubeThumbnailView videoThumb = holder1.youTubeThumbnailView;
YouTubeThumbnailLoader loader = mThumbnailViewToLoaderMap.get(videoThumb);
if (loader == null) {
videoThumb.setTag(youtubeVideo.getVideoId());
videoThumb.initialize(mContext.getString(R.string.YOUTUBE_DEVELOPER_KEY), mThumbnailListener);
} else {
videoThumb.setImageResource(R.drawable.loading_thumbnail);
loader.setVideo(youtubeVideo.getVideoId());
}
int newid = (int) System.currentTimeMillis();
((YoutubeVideoViewHolder) holder).frameLayout.setId(newid);
holder1.youtubeVideoPlayBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
holder1.youTubeThumbnailView.setVisibility(View.GONE);
holder1.youtubeVideoPlayBtn.setVisibility(View.GONE);
if (oldid != 0) {
fragmentManager.findFragmentById(oldid);
fragmentManager.beginTransaction().remove(fragmentManager.findFragmentById(oldid)).commit();
v1.setVisibility(View.VISIBLE);
v2.setVisibility(View.VISIBLE);
}
YouTubePlayerSupportFragment youTubePlayerFragment = YouTubePlayerSupportFragment.newInstance();
fragmentManager.beginTransaction().add(((YoutubeVideoViewHolder) holder).frameLayout.getId(), youTubePlayerFragment).commit();
initializedListener = new OnInitializedListener(position);
youTubePlayerFragment.initialize(mContext.getString(R.string.YOUTUBE_DEVELOPER_KEY), initializedListener);
oldid = ((YoutubeVideoViewHolder) holder).frameLayout.getId();
v1 = holder1.youTubeThumbnailView;
v2 = holder1.youtubeVideoPlayBtn;
}
});
if (!holder1.frameLayout.isShown() && liststate.get(position) != 0) {
Log.i("state", "showbtn");
holder1.youTubeThumbnailView.setVisibility(View.VISIBLE);
holder1.youtubeVideoPlayBtn.setVisibility(View.VISIBLE);
}
if (liststate.get(position) == 1 && !statefull) {
Log.i("state", "truescreen");
youTubePlayer.setFullscreen(true);
} else if (liststate.get(position) == 0 && statefull) {
Log.i("state", "falsescreen");
Log.i("state",Constant.fullscreenposition+"");
youTubePlayer.setFullscreen(false);
}
}
You have declared VideoID String[] VideoID; but you are using another local variable in onCreateViewHolder()
String[] VideoID = {"zlQMI01A3gg", "zlQMI01A3gg"};
don't declare another variable there, just use
VideoID = {"zlQMI01A3gg", "zlQMI01A3gg"};