E/RecyclerView: No adapter attached; skipping layout (Help needed) [duplicate] - java

This question already has answers here:
recyclerview No adapter attached; skipping layout
(38 answers)
Closed 2 years ago.
i'm building an application that connects to my Drupal API. Somehow i'm not getting any data display within my application. I don't see any errors in the code and the debugging online gives the follow error: E/RecyclerView: No adapter attached; skipping layout
Here is my MainActivity code:
package com.example.eindopdrachtcmsapi;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.TextView;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonArrayRequest;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.security.PrivateKey;
import java.util.ArrayList;
import java.util.LinkedList;
public class MainActivity extends AppCompatActivity implements ExampleAdapter.onItemClickListener {
public static final String EXTRA_TITLE = "title";
public static final String EXTRA_BODY = "body";
public static final String EXTRA_LINK = "link";
private RecyclerView mRecyclerView;
private ExampleAdapter mExampleAdapter;
private ArrayList<ExampleItem> mExampleList;
private RequestQueue mRequestQueue;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mRecyclerView = findViewById(R.id.recycler_view);
mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
mRecyclerView.setHasFixedSize(true);
mRecyclerView.setAdapter(mExampleAdapter);
mExampleList = new ArrayList<>();
mRequestQueue = Volley.newRequestQueue(this);
parseJSON();
}
private void parseJSON() {
String url = "http://vistudio.be/api/portfolio";
JsonArrayRequest request = new JsonArrayRequest(Request.Method.GET, url, null,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
try {
for (int i = 0; i < response.length(); i++) {
JSONObject portfolio = response.getJSONObject(i);
String title = portfolio.getString("title");
String body = portfolio.getString("body");
String link = portfolio.getString("field_website_url");
mExampleList.add(new ExampleItem(title, body, link));
}
mExampleAdapter = new ExampleAdapter(MainActivity.this, mExampleList);
mRecyclerView.setAdapter(mExampleAdapter);
mExampleAdapter.setOnClickListener(MainActivity.this, new ExampleAdapter.onItemClickListener() {
#Override
public void onItemClick(int position) {
ExampleItem clickedItem = mExampleList.get(position);
String title = clickedItem.getTitle();
String Link = clickedItem.getLink();
Intent mSharingIntent = new Intent(Intent.ACTION_SEND);
mSharingIntent.setType("text/plain");
mSharingIntent.putExtra(Intent.EXTRA_SUBJECT, "Vistudio");
mSharingIntent.putExtra(Intent.EXTRA_TEXT, title + " - "+ Link);
startActivity(Intent.createChooser(mSharingIntent, "Share"));
}
});
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
});
mRequestQueue.add(request);
}
#Override
public void onItemClick(int position) {
Intent detailIntent = new Intent(this, DetailActivity.class);
ExampleItem clickedItem = mExampleList.get(position);
detailIntent.putExtra(EXTRA_TITLE, clickedItem.getTitle());
detailIntent.putExtra(EXTRA_BODY, clickedItem.getBody());
detailIntent.putExtra(EXTRA_LINK, clickedItem.getLink());
mExampleAdapter.setOnClickListener(MainActivity.this, new ExampleAdapter.onItemClickListener() {
#Override
public void onItemClick(int position) {
ExampleItem clickedItem = mExampleList.get(position);
String title = clickedItem.getTitle();
String Link = clickedItem.getLink();
Intent mSharingIntent = new Intent(Intent.ACTION_SEND);
mSharingIntent.setType("text/plain");
mSharingIntent.putExtra(Intent.EXTRA_SUBJECT, "Vistudio");
mSharingIntent.putExtra(Intent.EXTRA_TEXT, title + " - "+ Link);
startActivity(Intent.createChooser(mSharingIntent, "Share"));
}
});
startActivity(detailIntent);
}
}
My Adapter code:
package com.example.eindopdrachtcmsapi;
import android.content.Context;
import android.graphics.PorterDuffColorFilter;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import java.util.ArrayList;
public class ExampleAdapter extends RecyclerView.Adapter<ExampleAdapter.portfolioViewHolder>{
private Context mContext;
private ArrayList<ExampleItem> mExampleList;
private onItemClickListener mListener;
private onItemClickListener mListenerShare;
public interface onItemClickListener{
void onItemClick(int position);
}
public void setOnClickListener(onItemClickListener listener, onItemClickListener listenerShare){
mListener = listener;
mListenerShare = listenerShare;
}
public ExampleAdapter(Context context, ArrayList<ExampleItem> ExampleList) {
mContext = context;
mExampleList = ExampleList;
}
#Override
public portfolioViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(mContext).inflate(R.layout.exampleitem, parent, false);
return new portfolioViewHolder(v);
}
#Override
public void onBindViewHolder(portfolioViewHolder holder, int position) {
ExampleItem currentItem = mExampleList.get(position);
String title = currentItem.getTitle();
String body = currentItem.getBody();
String link = currentItem.getLink();
holder.mTextViewTitle.setText(title);
holder.mTextViewBody.setText(body);
holder.mTextViewLink.setText(link);
}
#Override
public int getItemCount() {
return mExampleList.size();
}
public class portfolioViewHolder extends RecyclerView.ViewHolder{
public TextView mTextViewTitle;
public TextView mTextViewBody;
public TextView mTextViewLink;
public Button mButton;
public portfolioViewHolder(View itemView) {
super(itemView);
mTextViewTitle = itemView.findViewById(R.id.text_view_title);
mTextViewBody = itemView.findViewById(R.id.text_view_body);
mTextViewLink = itemView.findViewById(R.id.text_view_link);
mButton = itemView.findViewById(R.id.share);
mButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mListenerShare != null){
int position = getAdapterPosition();
if (position != RecyclerView.NO_POSITION) {
mListenerShare.onItemClick(position);
}
}
}
});
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mListener != null){
int position = getAdapterPosition();
if (position != RecyclerView.NO_POSITION) {
mListener.onItemClick(position);
}
}
}
});
}
}
}

first remove inside oncreate()
mRecyclerView.setAdapter(mExampleAdapter);
after this code
mExampleAdapter = new ExampleAdapter(MainActivity.this, mExampleList);
mRecyclerView.setAdapter(mExampleAdapter);
add this:-
mExampleAdapter.notifyDataSetChanged();

Related

(Android) When Back pressed, Attempt to invoke virtual method 'int java.lang.String.hashCode()' on a null object reference

I've been working on a Android Project (A Basic College Information App), I have three main activities, the user goes in like, Goal/Course Select activity-> CollegeList activity-> College Details Activity. Now When I press back on College Details Activity it crashes with this Error:
Attempt to invoke virtual method 'int java.lang.String.hashCode()' on a null object reference
Below are the files/code which I think might be responsible for this.....
CollegeListActivity.java file
package com.anurag.college_information.activities;
import static com.anurag.college_information.activities.CareerGoalActivity.GOAL;
import static com.anurag.college_information.activities.CareerGoalActivity.SHARED_PREFS;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.anurag.college_information.R;
import com.anurag.college_information.adapters.RecyclerAdapter;
import com.anurag.college_information.models.ModelClass;
import java.util.ArrayList;
import java.util.List;
public class CollegeListActivity extends AppCompatActivity {
private RecyclerAdapter.RecyclerViewClickListener listener;
//ListView collegeList;
TextView collegeListTitle;
Button courseChange;
RecyclerView recyclerView;
LinearLayoutManager LayoutManager;
RecyclerAdapter recyclerAdapter;
List<ModelClass> cList;
String courseName;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_college_list);
collegeListTitle = findViewById(R.id.college_list_title);
courseChange = findViewById(R.id.btn_change_course);
//collegeListTitle.setText(goal + "Colleges");
collegeListTitle.setText(getIntent().getStringExtra("Title") + " Colleges");
initData();
initRecyclerView();
//collegeList = findViewById(R.id.lv_college_list);
courseChange.setTransformationMethod(null);
courseChange.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
SharedPreferences sharedPreferences = getSharedPreferences(SHARED_PREFS, MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.clear();
editor.apply();
Intent i = new Intent(CollegeListActivity.this, CareerGoalActivity.class);
startActivity(i);
//finish();
}
});
}
private void initData() {
cList = new ArrayList<>();
courseName = getIntent().getStringExtra("Title");
switch (courseName) {
case "BE/BTech":
cList.add(new ModelClass("https://images.static-collegedunia.com/public/college_data/images/campusimage/1479294300b-5.jpg", "A.P. Shah College of Engineering", "Thane", "8.0"));
break;
case "Pharmacy":
cList.add(new ModelClass("https://images.static-collegedunia.com/public/college_data/images/campusimage/14382400753.jpg", "Bombay College Of Pharmacy", "Mumbai", "9.0"));
break;
}
}
private void initRecyclerView() {
setOnClickListener();
recyclerView = findViewById(R.id.recycler_view);
LayoutManager = new LinearLayoutManager(this);
LayoutManager.setOrientation(RecyclerView.VERTICAL);
recyclerView.setLayoutManager(LayoutManager);
recyclerAdapter = new RecyclerAdapter(cList, listener);
recyclerView.setAdapter(recyclerAdapter);
}
private void setOnClickListener() {
listener = new RecyclerAdapter.RecyclerViewClickListener() {
#Override
public void onClick(View v, int position) {
Intent i = new Intent(CollegeListActivity.this, CollegeDetailsActivity.class);
startActivity(i);
}
};
}
#Override
public void onBackPressed() {
new AlertDialog.Builder(this)
.setMessage("Are you sure you want to exit?")
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
finish();
}
})
.setNegativeButton("No", null)
.show();
}
}
RecyclerAdapter.java
package com.anurag.college_information.adapters;
import android.content.Context;
import android.content.Intent;
import android.telecom.Call;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.anurag.college_information.activities.CollegeDetailsActivity;
import com.anurag.college_information.models.ModelClass;
import com.anurag.college_information.R;
import com.squareup.picasso.Picasso;
import java.util.List;
public class RecyclerAdapter extends RecyclerView.Adapter<RecyclerAdapter.ViewHolder> {
private List<ModelClass> collegeList ;
private RecyclerViewClickListener listener;
List<String> imageUrl, collegeName, collegeLocation, collegeRating;
public RecyclerAdapter(List<ModelClass> collegeList, RecyclerViewClickListener listener){
this.collegeList=collegeList;
this.listener = listener;
}
#NonNull
#Override
public RecyclerAdapter.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.college_list_single_row, parent, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull RecyclerAdapter.ViewHolder holder, int position) {
String imageLink = collegeList.get(position).getImageLink();
//int img = collegeList.get(position).getCollegeImage();
String cName = collegeList.get(position).getCollegeName();
String cRating = collegeList.get(position).getCollegeRating();
String cLocation = collegeList.get(position).getLocation();
Picasso.get().load(imageLink).into(holder.imageView);
//holder.setData(img, cName, cRating);
holder.setData(imageLink, cName, cLocation ,cRating);
}
#Override
public int getItemCount() {
return collegeList.size();
}
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
private ImageView imageView;
private TextView collegeName, collegeRating, collegeLocation;
public ViewHolder(#NonNull View itemView) {
super(itemView);
imageView = itemView.findViewById(R.id.college_image);
collegeName = itemView.findViewById(R.id.college_name);
collegeRating = itemView.findViewById(R.id.college_rating);
collegeLocation = itemView.findViewById(R.id.college_location);
itemView.setOnClickListener(this);
}
public void setData(String imageLink, String cName, String cLocation, String cRating) {
//imageView.setImageResource(img);
Picasso.get().load(imageLink).error(R.drawable.error).into(imageView);
collegeName.setText(cName);
collegeRating.setText(cRating);
collegeLocation.setText(cLocation);
}
#Override
public void onClick(View v) {
listener.onClick(v, getAdapterPosition());
Intent i = new Intent(v.getContext(), CollegeDetailsActivity.class);
i.putExtra("collegeImage", collegeList.get(getAdapterPosition()).getImageLink());
i.putExtra("collegeName", collegeList.get(getAdapterPosition()).getCollegeName());
i.putExtra("collegeRating", collegeList.get(getAdapterPosition()).getCollegeRating());
i.putExtra("collegeLocation", collegeList.get(getAdapterPosition()).getLocation());
v.getContext().startActivity(i);
}
}
public interface RecyclerViewClickListener{
void onClick(View v, int position);
}
}
CollegeDetailsActivity.java
package com.anurag.college_information.activities;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import com.anurag.college_information.R;
import com.squareup.picasso.Picasso;
public class CollegeDetailsActivity extends AppCompatActivity {
Button btnApply;
ImageView dCollegeImage;
TextView dCollegeName, dCollegeRating, dCollegeLocation;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_college_details);
dCollegeImage = findViewById(R.id.details_college_image);
dCollegeName = findViewById(R.id.details_college_name);
dCollegeRating = findViewById(R.id.details_college_rating);
dCollegeLocation = findViewById(R.id.details_college_location);
btnApply = findViewById(R.id.btn_apply);
Intent i = getIntent();
String cn = i.getStringExtra("collegeName");
String cr = i.getStringExtra("collegeRating");
String ci = i.getStringExtra("collegeImage");
String cl = i.getStringExtra("collegeLocation");
Picasso.get().load(ci).error(R.drawable.error).into(dCollegeImage);
dCollegeName.setText(cn);
dCollegeRating.setText(cr);
dCollegeLocation.setText(cl);
btnApply.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getApplicationContext(), "The institute will be notified, of your application", Toast.LENGTH_LONG).show();
Toast.makeText(getApplicationContext(), "The college will contact you, Thank you", Toast.LENGTH_LONG).show();
}
});
}
#Override
public void onBackPressed() {
Intent i = new Intent(CollegeDetailsActivity.this, CollegeListActivity.class);
startActivity(i);
}
}
This is the Error Screenshot:
I'm pretty new to android I've just worked on just 4 to 5 projects,
Any Assistance will be appreciated, Thank You
The commented Out code, is just a normal listview I implemented just In Case, I have to remove the recycler view.
This will probably go away if you don't override onBackPressed in CollegeDetailsActivity. Instead of going back to an activity that had a valid "Title" string extra, the code you posted will go to a new activity where "Title" isn't defined, then get a NullPointerException since courseName will be null in initData (which the error message tells you results in an error on line 81 in that method). Using a null string in a switch results in that type of error
Just remove your onBackPressed entirely in CollegeDetailsActivity.

ItemClickListener not working in Fragment RecyclerView with onclick

I've been following this tutorial: Tutorial
To make a json recyclerviewer with onclick, but i wanted to use Fragments instead of activities.
I've figured everything out until the point of the onClick.
My problem is the setOnItemClickListener is not taking my getActivity()
I've tried so much, but i just cant see the bright light.
If anyone could help me out that would be totally awesome!
Me only real problem is that the getActivity is giving a red line in the:
fNieuwsAdapter.setOnItemClickListener(getActivity());
NieuwsFragment.java
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
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.AdapterView;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.jsoup.Jsoup;
import java.util.ArrayList;
public class NieuwsFragment extends Fragment implements NieuwsAdapter.OnItemClickListener {
public static final String EXTRA_URL = "nieuwsImageUrl";
public static final String EXTRA_HEADING = "nieuwsHeading";
public static final String EXTRA_CONTENT = "nieuwsContent";
private RecyclerView fNieuwsRecyclerView;
private NieuwsAdapter fNieuwsAdapter;
private ArrayList<NieuwsItem> fNieuwsList;
private RequestQueue fNieuwsQueue;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_nieuws, container, false);
fNieuwsRecyclerView = view.findViewById(R.id.recycler_view);
fNieuwsRecyclerView.setHasFixedSize(true);
fNieuwsRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
fNieuwsList = new ArrayList<>();
fNieuwsQueue = Volley.newRequestQueue(getActivity());
parseJSON();
return view;
}
private void parseJSON() {
String url = "urlissecretsorry<3butthejsonparsingworks";
JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, null,
new Response.Listener<JSONObject>() {
public String nieuwsImageUrl;
#Override
public void onResponse(JSONObject response) {
try {
JSONArray jsonArray = response.getJSONArray("posts");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject hit = jsonArray.getJSONObject(i);
JSONArray attachArray = hit.getJSONArray("attachments");
for (int a = 0; a < attachArray.length(); a++) {
JSONObject attach = attachArray.getJSONObject(a);
nieuwsImageUrl = attach.getString("url");
}
String nieuwsHeading = hit.getString("title");
String nieuwsExcerpt = hit.getString("excerpt");
String nieuwsContent = hit.getString("content");
nieuwsExcerpt = html2text(nieuwsExcerpt);
fNieuwsList.add(new NieuwsItem(nieuwsImageUrl, nieuwsHeading, nieuwsExcerpt,nieuwsContent));
}
fNieuwsAdapter = new NieuwsAdapter(getActivity(), fNieuwsList);
fNieuwsAdapter.setOnItemClickListener(getActivity());
fNieuwsRecyclerView.setAdapter(fNieuwsAdapter);
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
});
fNieuwsQueue.add(request);
}
#Override
public void onItemClick(int position) {
Intent detailIntent = new Intent(getActivity(), DetailActivity.class);
NieuwsItem clickedItem = fNieuwsList.get(position);
detailIntent.putExtra(EXTRA_URL, clickedItem.getImageUrl());
detailIntent.putExtra(EXTRA_HEADING, clickedItem.getHeading());
detailIntent.putExtra(EXTRA_CONTENT, clickedItem.getContent());
startActivity(detailIntent);
}
public String html2text(String html) {
try {
return Jsoup.parse(html).text();
} catch (Exception ignored) {
return "";
}
}
}
NieuwsItem.java
public class NieuwsItem {
private String nieuwsImageUrl;
private String nieuwsHeading;
private String nieuwsExcerpt;
private String nieuwsContent;
public NieuwsItem(String imageUrl, String heading, String excerpt, String content){
nieuwsImageUrl = imageUrl;
nieuwsHeading = heading;
nieuwsExcerpt = excerpt;
nieuwsContent = content;
}
public String getImageUrl(){
return nieuwsImageUrl;
}
public String getHeading(){
return nieuwsHeading;
}
public String getExcerpt(){
return nieuwsExcerpt;
}
public String getContent(){
return nieuwsContent;
}
}
NieuwsAdapter.java
import android.content.Context;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.support.v4.app.FragmentActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import com.squareup.picasso.Picasso;
import java.util.ArrayList;
public class NieuwsAdapter extends RecyclerView.Adapter<NieuwsAdapter.NieuwsViewHolder> {
private Context NieuwsContext;
private ArrayList<NieuwsItem> NieuwsList;
private OnItemClickListener NieuwsListener;
public interface OnItemClickListener {
void onItemClick(int position);
}
public void setOnItemClickListener(OnItemClickListener listener) {
NieuwsListener = listener;
}
public NieuwsAdapter(Context context, ArrayList<NieuwsItem> nieuwslist) {
NieuwsContext = context;
NieuwsList = nieuwslist;
}
#NonNull
#Override
public NieuwsViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(NieuwsContext).inflate(R.layout.nieuws_item, parent, false);
return new NieuwsViewHolder(v);
}
#Override
public void onBindViewHolder(NieuwsViewHolder holder, int position) {
NieuwsItem currentitem = NieuwsList.get(position);
String ImageUrl = currentitem.getImageUrl();
String Heading = currentitem.getHeading();
String Excerpt = currentitem.getExcerpt();
holder.NieuwsTextViewHeading.setText(Heading);
holder.NieuwsTextViewExcerpt.setText(Excerpt);
Picasso.get().load(ImageUrl).fit().centerInside().into(holder.NieuwsImageView);
}
#Override
public int getItemCount() {
return NieuwsList.size();
}
public class NieuwsViewHolder extends RecyclerView.ViewHolder {
public ImageView NieuwsImageView;
public TextView NieuwsTextViewHeading;
public TextView NieuwsTextViewExcerpt;
public NieuwsViewHolder(#NonNull View itemView) {
super(itemView);
NieuwsImageView = itemView.findViewById(R.id.nieuws_image);
NieuwsTextViewHeading = itemView.findViewById(R.id.nieuws_heading);
NieuwsTextViewExcerpt = itemView.findViewById(R.id.nieuws_excerpt);
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (NieuwsListener != null) {
int position = getAdapterPosition();
if (position != RecyclerView.NO_POSITION) {
NieuwsListener.onItemClick(position);
}
}
}
});
}
}
}
DetailActivity.java
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.ImageView;
import android.widget.TextView;
import com.squareup.picasso.Picasso;
public class DetailActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_detail);
Intent intent = getIntent();
String imageUrl = intent.getStringExtra("EXTRA_URL");
String creatorName = intent.getStringExtra("EXTRA_HEADING");
String likeCount = intent.getStringExtra("EXTRA_CONTENT");
ImageView imageView = findViewById(R.id.nieuws_detail_image);
TextView textViewHeading = findViewById(R.id.nieuws_detail_heading);
TextView textViewContent = findViewById(R.id.nieuws_detail_content);
Picasso.get().load(imageUrl).fit().centerInside().into(imageView);
textViewHeading.setText(creatorName);
textViewContent.setText("Likes: " + likeCount);
}
}
You cant use NieuwsAdapter.setOnItemClickListener(getActivity()); , unless your activity implements OnItemClickListener interface, but im seeing that your fragment implements OnItemClickListener, so you can use the fragment instead like this :
fNieuwsAdapter.setOnItemClickListener(NieuwsFragment.this);
And by the way, you are sending the data via intent with :
detailIntent.putExtra(EXTRA_URL, clickedItem.getImageUrl());
detailIntent.putExtra(EXTRA_HEADING, clickedItem.getHeading());
detailIntent.putExtra(EXTRA_CONTENT, clickedItem.getContent());
You have to get them with the same parameters (remove the ""):
String imageUrl = intent.getStringExtra(EXTRA_URL);
String creatorName = intent.getStringExtra(EXTRA_HEADING);
String likeCount = intent.getStringExtra(EXTRA_CONTENT);
Hope this helps
change
public NieuwsAdapter(Context context, ArrayList<NieuwsItem> nieuwslist) {
NieuwsContext = context;
NieuwsList = nieuwslist;
}
to
public NieuwsAdapter(Context context, ArrayList<NieuwsItem> nieuwslist, OnItemClickListener mOnClickListener) {
this.NieuwsContext = context;
this.NieuwsList = nieuwslist;
this.NieuwsListener = mOnClickListener;
}
and this
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (NieuwsListener != null) {
int position = getAdapterPosition();
if (position != RecyclerView.NO_POSITION) {
NieuwsListener.onItemClick(position);
}
}
}
});
change to
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
NieuwsListener.onItemClick(int position);
}
});
and then in fragment You can do it like this
fNieuwsAdapter = new NieuwsAdapter(getActivity(), fNieuwsList,new NieuwsAdapter.OnItemClickListener() {
#Override
public void onItemClick(int position)
{
//DoSomethingHere
}
});

Attempt to invoke virtual method (null object reference)

Currently, I'm developing a media player, and I want hide a element when audio finishes. But when it happens, the app crash with this error: Attempt to invoke virtual method 'void android.widget.LinearLayout.setVisibility(int)' on a null object reference. Check my current code:
meplayer.java
package etes.xddda.music;
import android.app.Activity;
import android.content.Context;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.Toast;
public class meplayer extends Activity {
public static MediaPlayer mediaPlayer;
public LinearLayout menu_dialog;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
menu_dialog = findViewById(R.id.menu_dialog);
}
public void initAudio(final Context context, final String url) {
if (mediaPlayer == null) {
mediaPlayer = MediaPlayer.create(context, Uri.parse(url));
}
mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
public LinearLayout menu_dialog;
#Override
public void onCompletion(MediaPlayer mp) {
//Toast.makeText(context, "TEST", Toast.LENGTH_LONG).show();
killMediaPlayer();
menu_dialog.setVisibility(View.GONE);
}
});
mediaPlayer.start();
}
private void killMediaPlayer() {
if (mediaPlayer != null) {
try {
mediaPlayer.reset();
mediaPlayer.release();
mediaPlayer = null;
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
RecyclerViewAdapter
package etes.xddda.music;
import android.app.Dialog;
import android.content.Context;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.media.MediaPlayer;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import java.util.List;
public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.MyViewHolder> implements View.OnClickListener{
Context mContext;
List<mList> mData;
Dialog myDialog;
private MediaPlayer mediaPlayer;
private int playbackPosition=0;
meplayer media;
private LinearLayout menu_dialog;
public RecyclerViewAdapter(Context mContext, List<mList> mData) {
this.mContext = mContext;
this.mData = mData;
}
public void onClick(View view) {
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v;
v = LayoutInflater.from(mContext).inflate(R.layout.item_list, parent, false);
final MyViewHolder vHolder = new MyViewHolder(v);
// Dialog ini
myDialog = new Dialog(mContext);
myDialog.setContentView(R.layout.dialog);
myDialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
vHolder.item_play.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
TextView dialog_name_tv = (TextView) myDialog.findViewById(R.id.dialog_name_id);
TextView dialog_phone_tv = (TextView) myDialog.findViewById(R.id.dialog_author_id);
ImageView dialog_contact_img = (ImageView) myDialog.findViewById(R.id.dialog_img);
dialog_name_tv.setText(mData.get(vHolder.getAdapterPosition()).getName());
dialog_phone_tv.setText(mData.get(vHolder.getAdapterPosition()).getPhone());
dialog_contact_img.setImageResource(mData.get(vHolder.getAdapterPosition()).getPhoto());
//Toast.makeText(mContext, "Test click "+String.valueOf(vHolder.getAdapterPosition()), Toast.LENGTH_SHORT).show();
myDialog.show();
}
});
vHolder.menu_play.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
menu_dialog = v.getRootView().findViewById(R.id.menu_dialog);
menu_dialog.setVisibility(v.VISIBLE);
media = new meplayer();
media.initAudio(v.getContext(), mData.get(vHolder.getAdapterPosition()).getURL());
MainActivity.setMargins(v.getRootView().findViewById(R.id.viewpager_id), 0,0,0,100);
}
});
return vHolder;
}
#Override
public void onBindViewHolder(MyViewHolder holder, int position) {
holder.tv_name.setText(mData.get(position).getName());
holder.tv_author.setText(mData.get(position).getPhone());
holder.img.setImageResource(mData.get(position).getPhoto());
}
#Override
public int getItemCount() {
return mData.size();
}
public static class MyViewHolder extends RecyclerView.ViewHolder {
private ImageButton item_play;
private LinearLayout menu_play;
private TextView tv_name;
private TextView tv_author;
private TextView tv_url;
private ImageView img;
public MyViewHolder(View itemView) {
super(itemView);
item_play = itemView.findViewById(R.id.info_id);
menu_play = itemView.findViewById(R.id.list_item_id);
tv_name = (TextView) itemView.findViewById(R.id.name_list);
tv_author = (TextView) itemView.findViewById(R.id.author_list);
img = (ImageView) itemView.findViewById(R.id.img_contact);
}
}
}
fragmentList
package etes.xddda.music;
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.support.annotation.Nullable;
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.Toast;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonArrayRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
public class fragmentList extends Fragment {
View v;
private RecyclerView myrecyclerview;
private List<mList> lstContact;
private String URL_JSON = "https://pastebin.com/raw/fG3zd40U";
private JsonArrayRequest ArrayRequest;
private RequestQueue requestQueue ;
public fragmentList() {
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
v = inflater.inflate(R.layout.list_fragment,container,false);
myrecyclerview = (RecyclerView) v.findViewById(R.id.list_recyclerview);
RecyclerViewAdapter recyclerViewAdapter = new RecyclerViewAdapter(getContext(), lstContact);
myrecyclerview.setLayoutManager(new LinearLayoutManager(getActivity()));
myrecyclerview.setAdapter(recyclerViewAdapter);
return v;
}
#Override
public void onCreate(#Nullable Bundle savedInstaceState) {
super.onCreate(savedInstaceState);
_JSONcall();
}
public void _JSONcall() {
lstContact = new ArrayList<>();
ArrayRequest = new JsonArrayRequest(URL_JSON, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
JSONObject jsonObject = null;
for (int i = 0 ; i<response.length();i++) {
try {
jsonObject = response.getJSONObject(i);
lstContact.add(new mList(jsonObject.getString("name"), jsonObject.getString("description"), jsonObject.getString("link"), R.drawable.ic_play_circle_filled_black_24dp));
}
catch (JSONException e) {
e.printStackTrace();
Toast.makeText(getActivity(), "Error 1!",
Toast.LENGTH_LONG).show();
}
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getActivity(), "Error 3!",
Toast.LENGTH_LONG).show();
}
});
requestQueue = Volley.newRequestQueue(getActivity().getApplicationContext());
requestQueue.add(ArrayRequest);
}
}
MainActivity
package etes.xddda.music;
import android.annotation.SuppressLint;
import android.support.design.widget.TabLayout;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.LinearLayout;
public class MainActivity extends AppCompatActivity {
private DrawerLayout nDrawerLayout;
private ActionBarDrawerToggle mToggle;
private TabLayout tabLayout;
private ViewPager viewPager;
private viewPagerAdapter adapter;
public LinearLayout menu_dialog;
private String player_status = "playing";
private ImageButton player_img;
#SuppressLint("RestrictedApi")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
nDrawerLayout = findViewById(R.id.drawer);
menu_dialog = findViewById(R.id.menu_dialog);
menu_dialog.setVisibility(View.GONE);
player_img = findViewById(R.id.playorpause);
player_img.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//setMargins(viewPager, 0,0,0,110);
if (player_status == "playing") {
player_img.setImageResource(R.drawable.ic_play_arrow_black_24dp);
meplayer.pauseAudio();
player_status = "paused";
} else {
player_img.setImageResource(R.drawable.ic_pause_black_24dp);
meplayer.startAudio();
player_status = "playing";
}
}
});
//menu_dialog.setLayoutParams(new LinearLayout.LayoutParams(0, 0));
mToggle = new ActionBarDrawerToggle(this, nDrawerLayout, R.string.open, R.string.close);
nDrawerLayout.addDrawerListener(mToggle);
getSupportActionBar().setDefaultDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
tabLayout = findViewById(R.id.tablayout_id);
viewPager = findViewById(R.id.viewpager_id);
//viewPager.setLayoutParams(new ViewPager.LayoutParams(0, 0));
//setMarginBottom(viewPager, 0);
setMargins(viewPager, 0,0,0,0);
adapter = new viewPagerAdapter(getSupportFragmentManager());
//Add fragments here
adapter.addFragment(new fragmentList(), ""); //Lista de música
adapter.addFragment(new fragmentFrequent(), ""); //Frequentes
adapter.addFragment(new fragmentPlayList(), ""); //Playlist
viewPager.setAdapter(adapter);
tabLayout.setupWithViewPager(viewPager);
tabLayout.getTabAt(0).setIcon(R.drawable.ic_music_note_black_24dp); //Lista de música
tabLayout.getTabAt(1).setIcon(R.drawable.ic_filter_list_black_24dp); // Frequentes
tabLayout.getTabAt(2).setIcon(R.drawable.ic_queue_music_black_24dp); // Playlist
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (mToggle.onOptionsItemSelected(item)) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
// Sync the toggle state after onRestoreInstanceState has occurred.
mToggle.syncState();
}
public static void setMargins (View v, int l, int t, int r, int b) {
if (v.getLayoutParams() instanceof ViewGroup.MarginLayoutParams) {
ViewGroup.MarginLayoutParams p = (ViewGroup.MarginLayoutParams) v.getLayoutParams();
p.setMargins(l, t, r, b);
v.requestLayout();
}
}
}
mList
package etes.xddda.music;
public class mList {
private String Name;
private String Author;
private String URL;
private int Photo;
public mList() {
}
public mList(String name, String phone, String url, int photo) {
Name = name;
Author = phone;
URL = url;
Photo = photo;
}
//Get User
public String getName() {
return Name;
}
public String getPhone() {
return Author;
}
public String getURL() {
return URL;
}
public int getPhoto() {
return Photo;
}
//Setter
public void setName(String name) {
Name = name;
}
public void setPhone(String phone) {
Author = phone;
}
public void setURL(String url) {
URL = url;
}
public void setPhoto(int photo) {
Photo = photo;
}
}
There are no errors in this script, the app just crash when audio finishes. The problem is related to line menu_dialog.setVisibility(View.GONE); and I have already defined menu_dialog in onCreate. So, can you help me?
P.S.: menu_dialog belongs to activity_main.xml
Thank you!
Remove the local variable menu_dialog that you have defined inside the OnCompletionListener:
package etes.xddda.music;
import android.app.Activity;
import android.content.Context;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.Toast;
public class meplayer extends Activity {
public static MediaPlayer mediaPlayer;
public LinearLayout menu_dialog;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
menu_dialog = findViewById(R.id.menu_dialog);
}
public void initAudio(final Context context, final String url) {
if (mediaPlayer == null) {
mediaPlayer = MediaPlayer.create(context, Uri.parse(url));
}
mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
//public LinearLayout menu_dialog; REMOVE THIS
#Override
public void onCompletion(MediaPlayer mp) {
//Toast.makeText(context, "TEST", Toast.LENGTH_LONG).show();
killMediaPlayer();
menu_dialog.setVisibility(View.GONE);
}
});
mediaPlayer.start();
}
private void killMediaPlayer() {
if (mediaPlayer != null) {
try {
mediaPlayer.reset();
mediaPlayer.release();
mediaPlayer = null;
} catch (Exception e) {
e.printStackTrace();
}
}
}
}

Attempt to invoke virtual method [Null object reference] [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 4 years ago.
I'm spending the last 5 days trying solve this problem. I really do not have any idea about how to solve it. I'm getting Attempt to invoke virtual method 'android.view.Window$Callback android.view.Window.getCallback()' on a null object reference. Check my code:
RecyclerView.java
package etes.xdda.music;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.media.MediaPlayer;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import java.util.List;
public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.MyViewHolder> implements View.OnClickListener{
Context mContext;
List<mList> mData;
Dialog myDialog;
private MediaPlayer mediaPlayer;
private int playbackPosition=0;
private LinearLayout menu_dialog;
public RecyclerViewAdapter(Context mContext, List<mList> mData) {
this.mContext = mContext;
this.mData = mData;
}
public void onClick(View view) {
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v;
v = LayoutInflater.from(mContext).inflate(R.layout.item_list, parent, false);
final MyViewHolder vHolder = new MyViewHolder(v);
// Dialog ini
myDialog = new Dialog(mContext);
myDialog.setContentView(R.layout.dialog);
myDialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
vHolder.item_play.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
TextView dialog_name_tv = (TextView) myDialog.findViewById(R.id.dialog_name_id);
TextView dialog_phone_tv = (TextView) myDialog.findViewById(R.id.dialog_author_id);
ImageView dialog_contact_img = (ImageView) myDialog.findViewById(R.id.dialog_img);
dialog_name_tv.setText(mData.get(vHolder.getAdapterPosition()).getName());
dialog_phone_tv.setText(mData.get(vHolder.getAdapterPosition()).getPhone());
dialog_contact_img.setImageResource(mData.get(vHolder.getAdapterPosition()).getPhoto());
//Toast.makeText(mContext, "Test click "+String.valueOf(vHolder.getAdapterPosition()), Toast.LENGTH_SHORT).show();
myDialog.show();
}
});
vHolder.menu_play.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
menu_dialog = v.getRootView().findViewById(R.id.menu_dialog);
menu_dialog.setVisibility(v.VISIBLE);
MainActivity a = new MainActivity();
a.initAudio(v.getContext(), mData.get(vHolder.getAdapterPosition()).getURL());
MainActivity.setMargins(v.getRootView().findViewById(R.id.viewpager_id), 0,0,0,100);
}
});
return vHolder;
}
#Override
public void onBindViewHolder(MyViewHolder holder, int position) {
holder.tv_name.setText(mData.get(position).getName());
holder.tv_author.setText(mData.get(position).getPhone());
holder.img.setImageResource(mData.get(position).getPhoto());
}
#Override
public int getItemCount() {
return mData.size();
}
public static class MyViewHolder extends RecyclerView.ViewHolder {
private ImageButton item_play;
private LinearLayout menu_play;
private TextView tv_name;
private TextView tv_author;
private TextView tv_url;
private ImageView img;
public MyViewHolder(View itemView) {
super(itemView);
item_play = itemView.findViewById(R.id.info_id);
menu_play = itemView.findViewById(R.id.list_item_id);
tv_name = (TextView) itemView.findViewById(R.id.name_list);
tv_author = (TextView) itemView.findViewById(R.id.author_list);
img = (ImageView) itemView.findViewById(R.id.img_contact);
}
}
}
Note that I'm invoking MainActivity.java in this part:
vHolder.menu_play.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
menu_dialog = v.getRootView().findViewById(R.id.menu_dialog);
menu_dialog.setVisibility(v.VISIBLE);
MainActivity a = new MainActivity();
a.initAudio(v.getContext(), mData.get(vHolder.getAdapterPosition()).getURL());
MainActivity.setMargins(v.getRootView().findViewById(R.id.viewpager_id), 0,0,0,100);
}
});
And here's my MainActivity.java
package etes.xdda.music;
import android.annotation.SuppressLint;
import android.content.Context;
import android.media.MediaPlayer;
import android.net.Uri;
import android.support.design.widget.TabLayout;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.LinearLayout;
public class MainActivity extends AppCompatActivity {
private DrawerLayout nDrawerLayout;
private ActionBarDrawerToggle mToggle;
private TabLayout tabLayout;
private ViewPager viewPager;
private viewPagerAdapter adapter;
public LinearLayout menu_dialog;
private String player_status = "playing";
private ImageButton player_img;
private static MediaPlayer mediaPlayer;
#SuppressLint("RestrictedApi")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
nDrawerLayout = findViewById(R.id.drawer);
menu_dialog = findViewById(R.id.menu_dialog);
menu_dialog.setVisibility(View.GONE);
player_img = findViewById(R.id.playorpause);
player_img.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//setMargins(viewPager, 0,0,0,110);
if (player_status == "playing") {
player_img.setImageResource(R.drawable.ic_play_arrow_black_24dp);
meplayer.pauseAudio();
player_status = "paused";
} else {
player_img.setImageResource(R.drawable.ic_pause_black_24dp);
meplayer.startAudio();
player_status = "playing";
}
}
});
//menu_dialog.setLayoutParams(new LinearLayout.LayoutParams(0, 0));
mToggle = new ActionBarDrawerToggle(this, nDrawerLayout, R.string.open, R.string.close);
nDrawerLayout.addDrawerListener(mToggle);
getSupportActionBar().setDefaultDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
tabLayout = findViewById(R.id.tablayout_id);
viewPager = findViewById(R.id.viewpager_id);
//viewPager.setLayoutParams(new ViewPager.LayoutParams(0, 0));
//setMarginBottom(viewPager, 0);
setMargins(viewPager, 0,0,0,0);
adapter = new viewPagerAdapter(getSupportFragmentManager());
//Add fragments here
adapter.addFragment(new fragmentList(), ""); //Lista de música
adapter.addFragment(new fragmentFrequent(), ""); //Frequentes
adapter.addFragment(new fragmentPlayList(), ""); //Playlist
viewPager.setAdapter(adapter);
tabLayout.setupWithViewPager(viewPager);
tabLayout.getTabAt(0).setIcon(R.drawable.ic_music_note_black_24dp); //Lista de música
tabLayout.getTabAt(1).setIcon(R.drawable.ic_filter_list_black_24dp); // Frequentes
tabLayout.getTabAt(2).setIcon(R.drawable.ic_queue_music_black_24dp); // Playlist
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (mToggle.onOptionsItemSelected(item)) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
// Sync the toggle state after onRestoreInstanceState has occurred.
mToggle.syncState();
}
public static void setMargins (View v, int l, int t, int r, int b) {
if (v.getLayoutParams() instanceof ViewGroup.MarginLayoutParams) {
ViewGroup.MarginLayoutParams p = (ViewGroup.MarginLayoutParams) v.getLayoutParams();
p.setMargins(l, t, r, b);
v.requestLayout();
}
}
public void initAudio(final Context context, final String url) {
if (mediaPlayer == null) {
mediaPlayer = MediaPlayer.create(context, Uri.parse(url));
}
mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
//Toast.makeText(context, "TEST", Toast.LENGTH_LONG).show();
killMediaPlayer();
updateLayout();
}
});
mediaPlayer.start();
}
private static void killMediaPlayer() {
if (mediaPlayer != null) {
try {
mediaPlayer.reset();
mediaPlayer.release();
mediaPlayer = null;
} catch (Exception e) {
e.printStackTrace();
}
}
}
private void updateLayout() {
try {
menu_dialog = findViewById(R.id.menu_dialog);
menu_dialog.setVisibility(View.GONE);
} catch (Exception e) {
e.printStackTrace();
}
}
And the part of code that is giving crash is this:
private void updateLayout() {
try {
menu_dialog = findViewById(R.id.menu_dialog);
menu_dialog.setVisibility(View.GONE);
} catch (Exception e) {
e.printStackTrace();
}
}
#edit: I have added this piece of code, I don't know if can help
fragmentList.java
package etes.xdda.music;
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.support.annotation.Nullable;
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.Toast;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonArrayRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
public class fragmentList extends Fragment {
View v;
private RecyclerView myrecyclerview;
private List<mList> lstContact;
private String URL_JSON = "https://pastebin.com/raw/fG3zd40U";
private JsonArrayRequest ArrayRequest;
private RequestQueue requestQueue ;
MainActivity activity;
public fragmentList() {
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
v = inflater.inflate(R.layout.list_fragment,container,false);
myrecyclerview = (RecyclerView) v.findViewById(R.id.list_recyclerview);
RecyclerViewAdapter recyclerViewAdapter = new RecyclerViewAdapter(activity, lstContact);
myrecyclerview.setLayoutManager(new LinearLayoutManager(getActivity()));
myrecyclerview.setAdapter(recyclerViewAdapter);
return v;
}
#Override
public void onCreate(#Nullable Bundle savedInstaceState) {
super.onCreate(savedInstaceState);
_JSONcall();
}
public void _JSONcall() {
lstContact = new ArrayList<>();
ArrayRequest = new JsonArrayRequest(URL_JSON, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
JSONObject jsonObject = null;
for (int i = 0 ; i<response.length();i++) {
try {
jsonObject = response.getJSONObject(i);
lstContact.add(new mList(jsonObject.getString("name"), jsonObject.getString("description"), jsonObject.getString("link"), R.drawable.ic_play_circle_filled_black_24dp));
}
catch (JSONException e) {
e.printStackTrace();
Toast.makeText(getActivity(), "Error 1!",
Toast.LENGTH_LONG).show();
}
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getActivity(), "Error 3!",
Toast.LENGTH_LONG).show();
}
});
requestQueue = Volley.newRequestQueue(getActivity().getApplicationContext());
requestQueue.add(ArrayRequest);
}
}
Please, help me, I have no more ideas about what I should do. Thank you
Just taking a look at your code, it looks like you are doing many things wrong. Such as this line
MainActivity a = new MainActivity();
You can't instantiate lifecycle components like Services, Activities, Fragments etc this way. Android provides you these components when you call start methods etc. The activity that is created as a result of the above line doesn't go through the lifecycle calls that an activity that is started via using startActivity. As a result, the setContentView of the activity is never called and you get this error. You have to remove this line and implement this properly and the error will go away.
Also just to add, you are actually creating a new instance of the activity when one is already running when you need to call the methods on the old instance that was started.
Edit: Try like this.
MainActivity activity;
List<mList> mData;
Dialog myDialog;
private MediaPlayer mediaPlayer;
private int playbackPosition=0;
private LinearLayout menu_dialog;
public RecyclerViewAdapter(MainActivity activity, List<mList> mData) {
this.activity = activity;
this.mData = mData;
}
And then
vHolder.menu_play.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
menu_dialog = v.getRootView().findViewById(R.id.menu_dialog);
menu_dialog.setVisibility(v.VISIBLE);
activity.initAudio(v.getContext(), mData.get(vHolder.getAdapterPosition()).getURL());
activity.setMargins(v.getRootView().findViewById(R.id.viewpager_id), 0,0,0,100);
}
});
Also remove static from the main activity functions

Recycler view refreshing continuously

I had a single recycler view in MainActivity.I'm adding items to that recycler view from sqlite database. The problem is that it is refreshing continuously when we press back button from app and come back to app again.It is adding duplicates of existing items.
Here is my MainActivity.java file
package bk.acs;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Environment;
import android.support.v4.app.ActivityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.Toast;
import java.io.File;
import java.io.IOException;
import bk.acs.AddingToDatabase.MyDialog;
import bk.acs.RecyclerView.Data;
import bk.acs.RecyclerView.ListItem;
import bk.acs.RecyclerView.MyAdapter;
public class MainActivity extends AppCompatActivity {
private static final int CONTACTS_PERMISSION = 10;
RecyclerView recview;
MyAdapter adapter;
Data d;
Toolbar toolbar;
NavigationDrawer drawer;
String appName;
LinearLayout main;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toolbar = (Toolbar) findViewById(R.id.toolbar);
appName = getResources().getString(R.string.app_name);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayShowHomeEnabled(true);
recview = (RecyclerView) findViewById(R.id.recview);
drawer = (NavigationDrawer) getSupportFragmentManager().findFragmentById(R.id.navDrawer);
drawer.setUp((DrawerLayout) findViewById(R.id.drawer_layout), toolbar);
d = new Data(this);
adapter = new MyAdapter(d.getList(), this);
recview.setLayoutManager(new LinearLayoutManager(recview.getContext()));
recview.setAdapter(adapter);
main = (LinearLayout) findViewById(R.id.MainLayout);
try {
createFolders();
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int res_id = item.getItemId();
if (res_id == R.id.refresh) {
MyDialog dialog = new MyDialog();
dialog.show(getFragmentManager(), "myDialog");
}
return true;
}
public void updateRecView(long num, String subname) {
disableRecView();
adapter.listdata.add(new ListItem(subname, num + ""));
adapter.notifyItemInserted(adapter.listdata.size());
}
public void disableRecView() {
main = (LinearLayout) findViewById(R.id.MainLayout);
main.setVisibility(View.GONE);
}
public void createFolders() throws IOException {
File mainFolder = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS).getAbsolutePath(), appName);
File inputs = new File(mainFolder, "Inputs");
File outputs = new File(mainFolder, "Outputs");
if (mainFolder.exists()) {
Toast.makeText(this, "Welcome", Toast.LENGTH_SHORT).show();
File temp = new File(inputs, "temp.txt");
temp.createNewFile();
} else {
Toast.makeText(this, "Creating Folders", Toast.LENGTH_SHORT).show();
mainFolder.mkdir();
inputs.mkdir();
outputs.mkdir();
File temp = new File(inputs, "temp.txt");
temp.createNewFile();
}
}
public void fetchDataForSub(String s) {
Intent intent = new Intent(this, SubActivity1.class);
intent.putExtra("tv", s);
startActivity(intent);
}
}
Here is my Data.java file from where I'm getting items from database
package bk.acs.RecyclerView;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
import bk.acs.MainActivity;
import bk.acs.databases.Main;
/**
* Created by bk on 01-03-2017.
*/
public class Data {
public static ArrayList<String> sample = new ArrayList<>();
public static List<ListItem> list = new ArrayList<>();
String[] cols = {"SubjectName"};
SQLiteDatabase db;
Context ctx;
public Data(Context context) {
this.ctx = context;
Main main = new Main(context, "subjects_db", 1, 1);
db = main.getReadableDatabase();
Cursor cursor = db.query("SubjectsTable", cols, null, null, null, null, null);
while (cursor.moveToNext()) {
sample.add(cursor.getString(0));
}
if (sample.size() != 0) {
((MainActivity) context).disableRecView();
}
}
public List getList() {
for (int i = 0; i < sample.size(); i++) {
ListItem listItem = new ListItem(sample.get(i), (i + 1) + ""); //Fixed crash
list.add(listItem);
}
return list;
}
}
This is MyAdapter.java file
package bk.acs.RecyclerView;
import android.content.Context;
import android.content.Intent;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
import bk.acs.MainActivity;
import bk.acs.R;
import bk.acs.SubActivity1;
/**
* Created by bk on 01-03-2017.
*/
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.Holder> {
public List<ListItem> listdata;
LayoutInflater inflater;
Context c;
public MyAdapter(List<ListItem> list, Context c) {
this.inflater = LayoutInflater.from(c);
listdata = list;
this.c = c;
}
#Override
public Holder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = inflater.inflate(R.layout.subjects_li, parent, false);
return new Holder(view);
}
#Override
public void onBindViewHolder(Holder holder, int position) {
ListItem item = listdata.get(position);
holder.subjectName.setText(item.subName);
holder.serialNo.setText(item.sno);
}
#Override
public int getItemCount() {
return listdata.size();
}
class Holder extends RecyclerView.ViewHolder implements View.OnClickListener {
TextView subjectName;
TextView serialNo;
View container;
public Holder(View itemView) {
super(itemView);
subjectName = (TextView) itemView.findViewById(R.id.subjectTitle);
serialNo = (TextView) itemView.findViewById(R.id.sno);
container = itemView.findViewById(R.id.cont_root);
itemView.setOnClickListener(this);
}
#Override
public void onClick(View view) {
((MainActivity) c).fetchDataForSub(subjectName.getText().toString());
}
}
}
How can I prevent duplicates from getting added to this recycler view..Thanks in advance
Because public static List<ListItem> list = new ArrayList<>();,
is always added, so you need to clear the list before you add the items.
public List getList() {
list.clear();
for (int i = 0; i < sample.size(); i++) {
ListItem listItem = new ListItem(sample.get(i), (i + 1) + ""); //Fixed crash
list.add(listItem);
}
return list;
}

Categories