java.lang.NullPointerException: Uzyskiwanie wartości z klasy Java

głosy
-1

Wciąż otrzymuję błąd NullPointer wyjątek, gdy uruchomię mój kod.

  • Próbuję uzyskać wartość (DailyCalorieAmount), który jest przechowywany w Firebase Realtime Database.
  • Wartość ta jest również zapisana w klasie User.java i to jest, gdy próbuję uzyskać dostęp do tej wartości z.
  • Raz uzyskać wartość staram się umieścić go w równaniu podzielić wartość przez 3 (To ma być oddany do zmiennej o nazwie maxCalories).
  • Wartość ta (maxCalories) jest następnie wchodząc url uzyskać plik JSON.

Wziąłem to samo podejście do strony profilu i wszystko działało w porządku! Każda pomoc będzie bardzo mile widziana!

Zarejestruj kodzie strony:

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);
    }

}

Klasa 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;
    }

}

Błąd w dziennikach jest następujący:

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
Utwórz 19/03/2020 o 22:03
źródło użytkownik
W innych językach...                            

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