I am trying to execute an Intent but it gives me an error when launching the Intent it shows me the following error:
Attempt to invoke virtual method 'java.lang.String android.content.Context.getPackageName()' on a null object reference
I don't know why this error happens when I call my intent, this is the method where I try to execute my intent:
public void vistaDetalle(String tituloNoticia, String subtituloNoticia, String imagenNoticia, String descripcionNoticia, Context context, Activity activity) {
Intent intent = new Intent(getContext(), DescripcionNoticias.class);
intent.putExtra("titulon",tituloNoticia);
intent.putExtra("descripcionn", descripcionNoticia);
intent.putExtra("imagen", imagenNoticia);
startActivity(intent);
getActivity().overridePendingTransition(R.anim.left_in, R.anim.left_out);
}
I have already tried to use getActivity() and other methods but none works for me, this is the complete class:
public class Inicio extends Fragment implements noticiasAdapter.OnEventMovieListener, Response.Listener<JSONObject>, Response.ErrorListener{
RecyclerView recyclerView;
private List<Noticias> noticias;
private noticiasAdapter noticiasadapter;
public static final String TAG = Noticias.class.getName();
RequestQueue request;
JsonObjectRequest jsonObjectRequest;
Context contextApp;
public Inicio(){
}
@Override
public void onAttach(Context context) {
super.onAttach(context);
this.contextApp = context;
}
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState){
View view = inflater.inflate(R.layout.inicio, container, false);
recyclerView = (RecyclerView)view.findViewById(R.id.recycler_view);
noticias = new ArrayList<>();
noticiasadapter = new noticiasAdapter(noticias);
noticiasadapter.setOnEventMovieListener(this);
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getContext());
recyclerView.setLayoutManager(layoutManager);
request = Volley.newRequestQueue(getActivity());
cargarWebService();
return view;
}
private void cargarWebService() {
String url = "http://192.168.1.81:80/webservicemgrex/listaNoticias.php";
jsonObjectRequest = new JsonObjectRequest(Request.Method.GET,url,null,this,this);
request.add(jsonObjectRequest);
}
@Override
public void onResponse(JSONObject response) {
Noticias news = null;
JSONArray json = response.optJSONArray("inicio");
try{
for (int i=0; i<json.length(); i++){
news = new Noticias();
JSONObject jsonObject = null;
jsonObject = json.getJSONObject(i);
news.setIdNoticia(jsonObject.optInt("idNoticia"));
news.setTituloNoticia(jsonObject.optString("tituloNoticia"));
news.setSubtituloNoticia(jsonObject.getString("subtituloNoticia"));
news.setImagenNoticia(jsonObject.getString("imagenNoticia"));
news.setDescripcionNoticia(jsonObject.getString("descripcionNoticia"));
noticias.add(news);
}
noticiasAdapter adapter = new noticiasAdapter(noticias);
recyclerView.setAdapter(adapter);
noticiasadapter.notifyDataSetChanged();
}catch (JSONException e){
Toast.makeText(getActivity(),"Error al cargar la informacion del servidor: "+e, Toast.LENGTH_LONG).show();
e.printStackTrace();
}
}
@Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getActivity(),"No se pudo consultar los registros: "+error.toString(), Toast.LENGTH_LONG).show();
Log.i("Error","No se pudo consultar el registro: "+error.toString());
}
public void vistaDetalle(String tituloNoticia, String subtituloNoticia, String imagenNoticia, String descripcionNoticia, Context context, Activity activity) {
Intent intent = new Intent(getContext(), DescripcionNoticias.class);
intent.putExtra("titulon",tituloNoticia);
intent.putExtra("descripcionn", descripcionNoticia);
intent.putExtra("imagen", imagenNoticia);
startActivity(intent);
getActivity().overridePendingTransition(R.anim.left_in, R.anim.left_out);
}
@Override
public void onStop() {
super.onStop();
}
@Override
public void onResume() {
super.onResume();
}
@Override
public void onPause() {
super.onPause();
}
@Override
public void onDestroy() {
super.onDestroy();
}
}
This is my class from where I call it, when the onclick is executed I try to call my ViewDetail method:
public class noticiasAdapter extends RecyclerView.Adapter<noticiasAdapter.NoticiasViewHolder> {
private List<Noticias> noticias;
private OnEventMovieListener onEventMovieListener;
private Context context;
public Activity activity;
public interface OnEventMovieListener{
}
public class NoticiasViewHolder extends RecyclerView.ViewHolder implements CompoundButton.OnCheckedChangeListener, View.OnClickListener {
TextView tituloNoticia;
TextView subtituloNoticia;
ImageView imagenNoticia;
TextView descripcionNoticia;
FloatingActionButton favoritos;
Button showMore;
private int contador = 0;
public NoticiasViewHolder(View itemView){
super(itemView);
tituloNoticia = (TextView)itemView.findViewById(R.id.tituloNoticia);
subtituloNoticia = (TextView)itemView.findViewById(R.id.subtituloNoticia);
imagenNoticia = (ImageView)itemView.findViewById(R.id.imagenNotica);
descripcionNoticia = (TextView)itemView.findViewById(R.id.descripcionNoticias);
favoritos = (FloatingActionButton)itemView.findViewById(R.id.floatingActionButton);
favoritos.setOnClickListener(this);
showMore = (Button)itemView.findViewById(R.id.showMore);
showMore.setOnClickListener(this);
}
@Override
public void onClick(View view) {
switch(view.getId()){
case R.id.floatingActionButton:
if (contador == 0){
favoritos.setImageResource(R.drawable.likedcolor);
contador = contador + 1;
Noticias fav = noticias.get(getAdapterPosition());
noticiasWebService noti = new noticiasWebService();
noti.update(fav.getTituloNoticia(), fav.getSubtituloNoticia(), fav.getImagenNoticia(), fav.getDescripcionNoticia(), context);
Toast.makeText(context, "Se añadio a tus favoritos ", Toast.LENGTH_LONG).show();
}else if (contador == 1){
favoritos.setImageResource(R.drawable.unliked);
contador = contador - 1;
Noticias fav = noticias.get(getAdapterPosition());
noticiasWebService noti = new noticiasWebService();
noti.deleteRegistro(fav.getTituloNoticia(), context);
Toast.makeText(context, "Se elimino de tus favoritos", Toast.LENGTH_LONG).show();
}
break;
case R.id.showMore:
Noticias news = noticias.get(getAdapterPosition());
Inicio inicio = new Inicio();
inicio.vistaDetalle(news.getTituloNoticia(), news.getSubtituloNoticia(), news.getImagenNoticia(), news.getDescripcionNoticia(),context, activity );
break;
default:
break;
}
}
@Override
public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
}
}
public noticiasAdapter(List<Noticias> noticias){
this.noticias = noticias;
}
@Override
public NoticiasViewHolder onCreateViewHolder(ViewGroup parent, int viewType){
View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_noticias, parent, false);
context = parent.getContext();
return new NoticiasViewHolder(itemView);
}
@Override
public void onBindViewHolder(NoticiasViewHolder holder, int position){
Noticias news = noticias.get(position);
holder.tituloNoticia.setText(news.getTituloNoticia());
holder.subtituloNoticia.setText(news.getSubtituloNoticia());
final String url = new String(news.getImagenNoticia());
if(url.isEmpty()){
Picasso.with(context).load(R.drawable.nofound).into(holder.imagenNoticia);
}else {
Picasso.with(context).load(url).into(holder.imagenNoticia);
}
holder.descripcionNoticia.setText(news.getDescripcionNoticia());
}
@Override
public int getItemCount(){
return noticias.size();
}
public OnEventMovieListener getOnEventMovieListener() {
return onEventMovieListener;
}
public void setOnEventMovieListener(OnEventMovieListener onEventMovieListener){
this.onEventMovieListener = onEventMovieListener;
}
}
and this is the method:
case R.id.showMore:
Noticias news = noticias.get(getAdapterPosition());
Inicio inicio = new Inicio();
inicio.vistaDetalle(news.getTituloNoticia(), news.getSubtituloNoticia(), news.getImagenNoticia(), news.getDescripcionNoticia(),context, activity );
break;
default:
break;
This is the class I am trying to call NewsDescription.class:
public class NewsDescription extends AppCompatActivity {
TextView tituloNoticiaDescripcion;
TextView noticiaCompleta;
ImageView imagenNoticiaCompleta;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_descripcion_noticias);
//Toolbar de la aplicacion en la vista principal
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
toolbar.setTitle("Sección 15");
toolbar.setSubtitle("Nota completa");
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
String tituloNoticia = getIntent().getExtras().getString("titulon");
String descripcionNoticia = getIntent().getExtras().getString("descripcionn");
String imagenNoticia = getIntent().getExtras().getString("imagen");
tituloNoticiaDescripcion = (TextView)findViewById(R.id.tituloDesNoticia);
noticiaCompleta = (TextView)findViewById(R.id.noticiaCompleta);
imagenNoticiaCompleta = (ImageView)findViewById(R.id.imagenNoticiaCompleta);
tituloNoticiaDescripcion.setText(tituloNoticia);
noticiaCompleta.setText(descripcionNoticia);
imagenNoticiaCompleta.setImageResource(R.drawable.noticiauno);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
overridePendingTransition(R.anim.left_out, R.anim.left_in);
onBackPressed();
return true;
}
return super.onOptionsItemSelected(item);
}
}
This is the full error:
Start Activity from Fragment.
If you want to make an Intent to open an Activity from a Fragment, you must use as context
getActivity()
, this way you get the context of the Activity that contains the Fragment.Example:
Obviously the one
Activity
to start must be registered in your fileAndroidManifest.xml
If you get an error using
getActivity()
it is probably caused by something else, you should review theLogCat
and add that information to your question.I already solved it, the only thing I did was change the method to the adapter and I pass the context in the following way:
I create a variable
private Context context;
and in the onCreateViewHolder method I assign the following value:
context = parent.getContext();
and in my method where I execute the intent I do it this way, I only pass the contex variable:
Try this if you cast it from a fragment:
If you launch it from an Activity it would be: