3

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: 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.

AnuragK
  • 61
  • 1
  • 8

1 Answers1

2

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.

Tyler V
  • 9,694
  • 3
  • 26
  • 52
  • So, Now the App is not crashing, but , presing _back_ once displays the same `CollegeDetailsActivty`, Without any data, just a blank layout , with all views, but has no data. is there a solution ? Edit: it goes on the previous screen, when back is pressed twice – AnuragK Nov 27 '21 at 01:34
  • You have two places where you launch the details activity - once in the RecyclerAdapter and again in the click listener. You are launching the details activity twice, so pressing "back" goes back to the first one of those. You'll want to fix that so it is only launched once. Remove the one set in CollegeListActivity - it doesn't pass any parameters to the new activity, or fix that one and don't launch the intent in the RecyclerAdapter (either way - just don't do it twice) – Tyler V Nov 27 '21 at 01:52