java.lang.NullPointerException: जावा वर्ग से कोई मान रही

वोट
-1

जब मैं अपने कोड को चलाने मैं एक NullPointer अपवाद त्रुटि प्राप्त हो रही।

  • मैं एक मूल्य (DailyCalorieAmount) कि Firebase रीयलटाइम डाटाबेस में संग्रहित है पाने के लिए कोशिश कर रहा हूँ।
  • यह मान भी एक User.java कक्षा में संग्रहीत किया जाता है और यह वह जगह है जहाँ मैं इस मूल्य का उपयोग करने की कोशिश कर रहा हूँ।
  • एक बार मैं मूल्य मैं इसे एक समीकरण में डाल करने के लिए 3 से मूल्य को विभाजित करने की कोशिश कर रहा हूँ मिल (यह एक चर कहा maxCalories में डाल दिया जा रहा है)।
  • यह मान (maxCalories) फिर एक 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
20/03/2020 को 00:03
का स्रोत उपयोगकर्ता
अन्य भाषाओं में...                            

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