java.lang.NullPointerException: Να πάρει μια τιμή από Java Class

ψήφοι
-1

Παίρνω ένα λάθος NullPointer Εξαίρεση όταν τρέχω τον κωδικό μου.

  • Είμαι προσπαθεί να πάρει μια τιμή (DailyCalorieAmount) που είναι αποθηκευμένα σε firebase Realtime βάση δεδομένων.
  • Αυτή η τιμή είναι αποθηκευμένο σε μια τάξη User.java και αυτό είναι που προσπαθώ να αποκτήσετε πρόσβαση σε αυτήν την τιμή από το.
  • Μόλις πάρει την αξία που προσπαθώ να το βάλετε σε μια εξίσωση για να διαιρέσει την αξία του 3 (Αυτό πρόκειται να τεθεί σε μια μεταβλητή που ονομάζεται maxCalories).
  • Αυτή η τιμή (maxCalories) στη συνέχεια πηγαίνει σε ένα url για να πάρετε ένα αρχείο JSON.

Πήρα την ίδια προσέγγιση για την Σελίδα Προφίλ και όλα πήγαν καλά! Οποιαδήποτε βοήθεια θα ήταν πραγματικά εκτιμηθεί!

Εγγραφή Κωδικός Σελίδα:

public class BreakfastPage extends AppCompatActivity {

    //initialise RecyclerView
    private RecyclerView recyclerView;

    private LinearLayoutManager linearLayoutManager;
    private DividerItemDecoration dividerItemDecoration;
    private RecyclerView.Adapter adapter;

    private Double maxCalories;
    private String CalorieAmount;

    private List<Meal> meals;

    //reference to the database
    private FirebaseAuth myAuth;
    private FirebaseDatabase database;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.breakfast_activity);

        recyclerView = (RecyclerView) findViewById(R.id.RecyclerViewBreakfast);

        meals = new ArrayList<>();

        adapter = new MealAdapter(meals,this);

        linearLayoutManager = new LinearLayoutManager(this);
        linearLayoutManager.setOrientation(RecyclerView.VERTICAL);
        dividerItemDecoration = new DividerItemDecoration(recyclerView.getContext(), linearLayoutManager.getOrientation());

        recyclerView.setHasFixedSize(true);
        recyclerView.setLayoutManager(linearLayoutManager);
        recyclerView.addItemDecoration(dividerItemDecoration);
        recyclerView.setAdapter(adapter);

        //create instance to the database
        myAuth = FirebaseAuth.getInstance();
        database = FirebaseDatabase.getInstance();

        DatabaseReference databaseReference = database.getReference(myAuth.getUid());

        databaseReference.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot dataSnapshot) {

                User user = dataSnapshot.getValue(User.class);
                String username = user.getUsername();
                CalorieAmount = user.getCalorieIntake();
            }

            @Override
            public void onCancelled(@NonNull DatabaseError databaseError) {

                Toast.makeText(BreakfastPage.this, databaseError.getCode(), Toast.LENGTH_SHORT).show();
            }
        });


        getData();
    }

    private class GetMealTask extends AsyncTask<String, Void, String> {
        @Override
        protected String doInBackground(String... params) {
            try {
                URL url = new URL(params[0]);
                HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
                urlConnection.connect();

                InputStream stream = urlConnection.getInputStream();
                InputStreamReader reader = new InputStreamReader(stream);

                int data = reader.read();
                String apiDetails = ;
                char current;

                while (data != -1) {
                    current = (char) data;
                    apiDetails += current;
                    data = reader.read();
                }

                return apiDetails;
            } catch (Exception e) {
                e.printStackTrace();
            }
            return null;
        }
    }

    private void getData() {
        final ProgressDialog progressDialog = new ProgressDialog(this);
        progressDialog.setMessage(Loading...);
        progressDialog.show();

        maxCalories = (Double.parseDouble(CalorieAmount) / 3);

        String URL_MEAL = https://api.spoonacular.com/recipes/complexSearch?&apiKey=da7dd16a704f4552b70a96c1e9641b08&type=breakfast&maxCalories= + maxCalories + &number=10&sort=random&addRecipeInformation=true;

        RequestQueue requestQueue = Volley.newRequestQueue(this);

        JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, URL_MEAL, null, new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject response) {
                try {
                    JSONArray array = response.getJSONArray(results);
                    for (int i = 0; i < array.length(); i++) {
                        JSONObject results = array.getJSONObject(i);

                        Meal meal = new Meal();

                        meal.setMealTitle(results.getString(title));
                        meal.setImage(results.getString(image));
                        meal.setMealId(results.getString(id));

                        meal.setCalorieAmount(results.getJSONArray(nutrition).getJSONObject(0).getString(amount));

                        meals.add(meal);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                    progressDialog.dismiss();
                }
                progressDialog.dismiss();
                adapter.notifyDataSetChanged();
            }
        },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        Log.e(Volley, error.toString());
                        progressDialog.dismiss();
                    }
                });
        requestQueue.add(jsonObjectRequest);
    }

}

User.java κατηγορία

//modal class
public class User {
    public String username;
    public String email;
    public String dob;
    public String weight;
    public String height;
    public String gender;
    public String calorieIntake;


    //default constructor
    public User() {
    }

    public User(String username, String email, String dob, String weight, String height, String gender, String calorieIntake ) {
        this.username = username;
        this.email = email;
        this.dob = dob;
        this.weight = weight;
        this.height = height;
        this.gender = gender;
        this.calorieIntake = calorieIntake;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public String getdob() {
        return dob;
    }

    public void setdob(String dob) {
        this.dob = dob;
    }

    public String getWeight() {
        return weight;
    }

    public void setWeight(String weight) {
        this.weight = weight;
    }

    public String getHeight() {
        return height;
    }

    public void setHeight(String height) {
        this.height = height;
    }

    public String getGender() {
        return gender;
    }

    public void setGender(String gender) {
        this.gender = gender;
    }

    public String getCalorieIntake() {
        if(this.getGender().equals(Male)){
            calorieIntake = String.valueOf(((((Double.parseDouble(this.getWeight()) * 10) + (6.25 * Double.parseDouble(this.getHeight()))) - (5 * 21)) + 5));
        } else if (this.getGender().equals(Female)){
            calorieIntake = String.valueOf(((((Double.parseDouble(this.getWeight()) * 10) + (6.25 * Double.parseDouble(this.getHeight()))) - (5 * 21)) - 161));
        }
        return  calorieIntake;
    }

}

Το λάθος στα αρχεία καταγραφής είναι η εξής:

E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.calorie2food, PID: 19905
    java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.calorie2food/com.example.calorie2food.Pages.BreakfastPage}: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String java.lang.String.trim()' on a null object reference
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3121)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3264)
        at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:78)
        at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:108)
        at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:68)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1955)
        at android.os.Handler.dispatchMessage(Handler.java:106)
        at android.os.Looper.loop(Looper.java:214)
        at android.app.ActivityThread.main(ActivityThread.java:7078)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:494)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:964)
     Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String java.lang.String.trim()' on a null object reference
        at sun.misc.FloatingDecimal.readJavaFormatString(FloatingDecimal.java:1838)
        at sun.misc.FloatingDecimal.parseDouble(FloatingDecimal.java:110)
        at java.lang.Double.parseDouble(Double.java:538)
        at com.example.calorie2food.Pages.BreakfastPage.getData(BreakfastPage.java:152)
        at com.example.calorie2food.Pages.BreakfastPage.onCreate(BreakfastPage.java:115)
        at android.app.Activity.performCreate(Activity.java:7327)
        at android.app.Activity.performCreate(Activity.java:7318)
        at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1275)
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3101)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3264) 
        at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:78) 
        at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:108) 
        at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:68) 
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1955) 
        at android.os.Handler.dispatchMessage(Handler.java:106) 
        at android.os.Looper.loop(Looper.java:214) 
        at android.app.ActivityThread.main(ActivityThread.java:7078) 
        at java.lang.reflect.Method.invoke(Native Method) 
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:494) 
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:964) 
I/Process: Sending signal. PID: 19905 SIG: 9
Δημοσιεύθηκε 19/03/2020 στις 22:03
πηγή χρήστη
Σε άλλες γλώσσες...                            

Cookies help us deliver our services. By using our services, you agree to our use of cookies. Learn more