简体   繁体   中英

Moving java from MainActivity.java to HomeFragment.java causing errors thought the same code

I have recently created a new application with a bottom navigation template. I put my code in the activity_main.xml and the MainActivity.java files. But I realized, I wanted to put them in the fragment_home.xml file and the java in the HomeFragment.java. All the XML was only a button and a textView, so I copied and pasted those in the fragment_home.xml file but it wasn't so easy to copy th java from the MainActivity.java to the HomeFragment.java. This is the first time using a bottom navigation template and I'm not sure where to put the code, code that worked in the MainAtivity.java, show red lines in the HomeFragment.java file. Since I have no experience with using fragments and their specialized syntax, I looked for help here. I wanted someone more experienced to possibly help me move code from the MainAcitivity to the HomeFragment with no errors. So here is the code.

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/container"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingTop="?attr/actionBarSize"

    >

    <com.google.android.material.bottomnavigation.BottomNavigationView
        android:id="@+id/nav_view"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginStart="0dp"
        android:layout_marginEnd="0dp"
        android:background="?android:attr/windowBackground"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:menu="@menu/bottom_nav_menu" />

    <fragment
        android:id="@+id/nav_host_fragment"
        android:name="androidx.navigation.fragment.NavHostFragment"
        android:layout_width="408dp"
        android:layout_height="742dp"
        app:defaultNavHost="true"
        app:layout_constraintBottom_toTopOf="@id/nav_view"
        app:layout_constraintHorizontal_bias="0.333"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.0"
        app:navGraph="@navigation/mobile_navigation" />

    <TextView
        android:id="@+id/text_view_result"
        android:layout_width="194dp"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:textColor="#0A0A0A"
        app:layout_constraintBottom_toTopOf="@+id/nav_view"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.497"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.287" />

    <Button
        android:id="@+id/button_parse"
        android:layout_width="194dp"
        android:layout_height="71dp"
        android:text="Parse"
        app:layout_constraintBottom_toTopOf="@+id/nav_view"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.497"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="@+id/nav_host_fragment"
        app:layout_constraintVertical_bias="0.419" />

</androidx.constraintlayout.widget.ConstraintLayout>

MainActivity.java:

package com.example.spoonacular;

import android.app.VoiceInteractor;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.VolleyLog;
import com.android.volley.toolbox.JsonArrayRequest;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.google.android.material.bottomnavigation.BottomNavigationView;

import androidx.appcompat.app.AppCompatActivity;
import androidx.navigation.NavController;
import androidx.navigation.Navigation;
import androidx.navigation.ui.AppBarConfiguration;
import androidx.navigation.ui.NavigationUI;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.lang.reflect.Array;
import java.net.URL;

public class MainActivity extends AppCompatActivity {
    private TextView mTextViewResult;
    private RequestQueue mQueue;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        BottomNavigationView navView = findViewById(R.id.nav_view);
        // Passing each menu ID as a set of Ids because each
        // menu should be considered as top level destinations.
        AppBarConfiguration appBarConfiguration = new AppBarConfiguration.Builder(
                R.id.navigation_home, R.id.navigation_dashboard, R.id.navigation_notifications)
                .build();
        NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment);
        NavigationUI.setupActionBarWithNavController(this, navController, appBarConfiguration);
        NavigationUI.setupWithNavController(navView, navController);
        mTextViewResult = findViewById(R.id.text_view_result);
        Button buttonParse = findViewById(R.id.button_parse);

        mQueue = Volley.newRequestQueue(this);

        buttonParse.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                jsonParse();
            }
        });
    }

    private void jsonParse() {
        String url = "https://api.spoonacular.com/recipes/random?number=1&tags=vegetarian,dessert&apiKey=86912d6bb1474577a76513e236a8a58e";
        JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, null,
                new Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject response) {
                        try {
                            JSONArray jsonArray = response.getJSONArray("recipes");
                            for (int i = 0; i < jsonArray.length(); i++) {
                                JSONObject recipes = jsonArray.getJSONObject(i);

                                Boolean vegetarian = recipes.getBoolean("vegetarian");
                                Boolean vegan = recipes.getBoolean("vegan");
                                Boolean glutenFree = recipes.getBoolean("glutenFree");
                                Boolean dairyFree = recipes.getBoolean("dairyFree");
                                Boolean veryHealthy = recipes.getBoolean("veryHealthy");
                                Boolean cheap = recipes.getBoolean("cheap");
                                Boolean veryPopular = recipes.getBoolean("veryPopular");
                                Boolean sustainable = recipes.getBoolean("sustainable");
                                Boolean lowFodmap = recipes.getBoolean("lowFodmap");
                                int weightWatcherSmartPoints = recipes.getInt("weightWatcherSmartPoints");
                                int spoonacularScore = recipes.getInt("spoonacularScore");
                                int healthScore = recipes.getInt("healthScore");
                                int pricePerServing = recipes.getInt("pricePerServing");
                                int likes = recipes.getInt("aggregateLikes");
                                String gaps = recipes.getString("gaps");
                                String source = recipes.getString("sourceName");
                                mTextViewResult.setText("Vegetarian: " + vegetarian + "\n\n"+ "Vegan: " + vegan + "\n\n" + "Gluten Free: " + glutenFree + "\n\n" + "Dairy Free: "  + dairyFree + "\n\n" + "Very Healthy: " + veryHealthy + "\n\n"+ "Cheap: " + cheap + "\n\n" + "Very Popular: " + veryPopular + "\n\n" + "Sustainable: "  + sustainable + "\n\n" + "Low Fod Map: " + lowFodmap + "\n\n" + "Weight Watcher Points: "  +  String.valueOf(weightWatcherSmartPoints) + "\n\n" + "Spoonacular Score: "  + String.valueOf(spoonacularScore) + "\n\n" + "Health Score: "  + String.valueOf(healthScore) + "\n\n" + "Price Per Serving: "  + String.valueOf(pricePerServing) + "\n\n" + "Likes: " + String.valueOf(likes) + "\n\n");
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                error.printStackTrace();
            }
        });
        mQueue.add(request);
    }
}

Move to fragment_home.xml and the homefragment java file.

fragment_home.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".ui.home.HomeFragment">

    <TextView
        android:id="@+id/text_home"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginStart="8dp"
        android:layout_marginTop="8dp"
        android:layout_marginEnd="8dp"
        android:textAlignment="center"
        android:textSize="20sp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>

the HomeFragment.java file,

package com.example.spoonacular.ui.home;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;

import com.example.spoonacular.R;

public class HomeFragment extends Fragment {

    private HomeViewModel homeViewModel;

    public View onCreateView(@NonNull LayoutInflater inflater,
                             ViewGroup container, Bundle savedInstanceState) {
        homeViewModel =
                new ViewModelProvider(this).get(HomeViewModel.class);
        View root = inflater.inflate(R.layout.fragment_home, container, false);
        final TextView textView = root.findViewById(R.id.text_home);
        homeViewModel.getText().observe(getViewLifecycleOwner(), new Observer<String>() {
            @Override
            public void onChanged(@Nullable String s) {
                textView.setText(s);
            }
        });
        return root;
    }
}

And since it might be useful to show the HomeViewModel file as well, (although it would be appreciated if someone could explain to me the difference between the HomeViewModel.java and the HomeFragment.java)

HomeViewModel.java

package com.example.spoonacular.ui.home;

import androidx.lifecycle.LiveData;
import androidx.lifecycle.MutableLiveData;
import androidx.lifecycle.ViewModel;

public class HomeViewModel extends ViewModel {

    private MutableLiveData<String> mText;

    public HomeViewModel() {
        mText = new MutableLiveData<>();
        mText.setValue("This is home fragment");
    }

    public LiveData<String> getText() {
        return mText;
    }
}

I know this a long question and might not be worth answering, but I have not been able to find a solution and this is my last hope. I'm ready to answer any question (and upvote and accept working solutions) Thank you for any help!

EDIT
MainActivity.java

package com.example.spoonacular;

import android.os.Bundle;

import com.google.android.material.bottomnavigation.BottomNavigationView;

import androidx.appcompat.app.AppCompatActivity;
import androidx.navigation.NavController;
import androidx.navigation.Navigation;
import androidx.navigation.ui.AppBarConfiguration;
import androidx.navigation.ui.NavigationUI;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        BottomNavigationView navView = findViewById(R.id.nav_view);
        // Passing each menu ID as a set of Ids because each
        // menu should be considered as top level destinations.
        AppBarConfiguration appBarConfiguration = new AppBarConfiguration.Builder(
                R.id.navigation_home, R.id.navigation_dashboard, R.id.navigation_notifications)
                .build();
        NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment);
        NavigationUI.setupActionBarWithNavController(this, navController, appBarConfiguration);
        NavigationUI.setupWithNavController(navView, navController);
    }
}

HomeFragment.java

package com.example.spoonacular.ui.home;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import com.example.spoonacular.R;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

public class HomeFragment extends Fragment {

    private TextView mTextViewResult;
    private Button buttonParse;
    private HomeViewModel homeViewModel;
    private RequestQueue mQueue;

    public View onCreateView(@NonNull LayoutInflater inflater,
                             ViewGroup container, Bundle savedInstanceState) {
        homeViewModel =
                new ViewModelProvider(this).get(HomeViewModel.class);
        View root = inflater.inflate(R.layout.fragment_home, container, false);

        mTextViewResult = root.findViewById(R.id.text_view_result);
        buttonParse = root.findViewById(R.id.button_parse);

        mQueue = Volley.newRequestQueue(this);

        buttonParse.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                jsonParse();
            }
        });


        homeViewModel.getText().observe(getViewLifecycleOwner(), new Observer<String>() {
            @Override
            public void onChanged(@Nullable String s) {
                mTextViewResult.setText(s);
            }
        });
        return root;
    }

    private void jsonParse() {
        String url = "https://api.spoonacular.com/recipes/random?number=1&tags=vegetarian,dessert&apiKey=86912d6bb1474577a76513e236a8a58e";
        JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, null,
                new Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject response) {
                        try {
                            JSONArray jsonArray = response.getJSONArray("recipes");
                            for (int i = 0; i < jsonArray.length(); i++) {
                                JSONObject recipes = jsonArray.getJSONObject(i);

                                Boolean vegetarian = recipes.getBoolean("vegetarian");
                                Boolean vegan = recipes.getBoolean("vegan");
                                Boolean glutenFree = recipes.getBoolean("glutenFree");
                                Boolean dairyFree = recipes.getBoolean("dairyFree");
                                Boolean veryHealthy = recipes.getBoolean("veryHealthy");
                                Boolean cheap = recipes.getBoolean("cheap");
                                Boolean veryPopular = recipes.getBoolean("veryPopular");
                                Boolean sustainable = recipes.getBoolean("sustainable");
                                Boolean lowFodmap = recipes.getBoolean("lowFodmap");
                                int weightWatcherSmartPoints = recipes.getInt("weightWatcherSmartPoints");
                                int spoonacularScore = recipes.getInt("spoonacularScore");
                                int healthScore = recipes.getInt("healthScore");
                                int pricePerServing = recipes.getInt("pricePerServing");
                                int likes = recipes.getInt("aggregateLikes");
                                String gaps = recipes.getString("gaps");
                                String source = recipes.getString("sourceName");
                                mTextViewResult.setText("Vegetarian: " + vegetarian + "\n\n" + "Vegan: " + vegan + "\n\n" + "Gluten Free: " + glutenFree + "\n\n" + "Dairy Free: " + dairyFree + "\n\n" + "Very Healthy: " + veryHealthy + "\n\n" + "Cheap: " + cheap + "\n\n" + "Very Popular: " + veryPopular + "\n\n" + "Sustainable: " + sustainable + "\n\n" + "Low Fod Map: " + lowFodmap + "\n\n" + "Weight Watcher Points: " + String.valueOf(weightWatcherSmartPoints) + "\n\n" + "Spoonacular Score: " + String.valueOf(spoonacularScore) + "\n\n" + "Health Score: " + String.valueOf(healthScore) + "\n\n" + "Price Per Serving: " + String.valueOf(pricePerServing) + "\n\n" + "Likes: " + String.valueOf(likes) + "\n\n");
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                error.printStackTrace();
            }
        });
        mQueue.add(request);
    }
}

fragment_home.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".ui.home.HomeFragment">

    <TextView
        android:id="@+id/text_home"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginStart="8dp"
        android:layout_marginTop="8dp"
        android:layout_marginEnd="8dp"
        android:textAlignment="center"
        android:textSize="20sp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />
    <TextView
        android:id="@+id/text_view_result"
        android:layout_width="194dp"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:textColor="#0A0A0A"
        app:layout_constraintBottom_toTopOf="@+id/nav_view"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.497"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.287" />

    <Button
        android:id="@+id/button_parse"
        android:layout_width="194dp"
        android:layout_height="71dp"
        android:text="Parse"
        app:layout_constraintBottom_toTopOf="@+id/nav_view"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.497"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="@+id/nav_host_fragment"
        app:layout_constraintVertical_bias="0.419" />
</androidx.constraintlayout.widget.ConstraintLayout>

Activity_Main.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/container"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingTop="?attr/actionBarSize"

    >

    <com.google.android.material.bottomnavigation.BottomNavigationView
        android:id="@+id/nav_view"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginStart="0dp"
        android:layout_marginEnd="0dp"
        android:background="?android:attr/windowBackground"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:menu="@menu/bottom_nav_menu" />

    <fragment
        android:id="@+id/nav_host_fragment"
        android:name="androidx.navigation.fragment.NavHostFragment"
        android:layout_width="408dp"
        android:layout_height="742dp"
        app:defaultNavHost="true"
        app:layout_constraintBottom_toTopOf="@id/nav_view"
        app:layout_constraintHorizontal_bias="0.333"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.0"
        app:navGraph="@navigation/mobile_navigation" />



</androidx.constraintlayout.widget.ConstraintLayout>

Still have error in HomeFragment.java
line 44

        mQueue = Volley.newRequestQueue(this);

在此处输入图像描述

I don't know, I just copied some text from MainActivity to HomeFragment .

MainActivity

package com.example.spoonacular;

import android.os.Bundle;

import com.google.android.material.bottomnavigation.BottomNavigationView;

import androidx.appcompat.app.AppCompatActivity;
import androidx.navigation.NavController;
import androidx.navigation.Navigation;
import androidx.navigation.ui.AppBarConfiguration;
import androidx.navigation.ui.NavigationUI;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        BottomNavigationView navView = findViewById(R.id.nav_view);
        // Passing each menu ID as a set of Ids because each
        // menu should be considered as top level destinations.
        AppBarConfiguration appBarConfiguration = new AppBarConfiguration.Builder(
                R.id.navigation_home, R.id.navigation_dashboard, R.id.navigation_notifications)
                .build();
        NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment);
        NavigationUI.setupActionBarWithNavController(this, navController, appBarConfiguration);
        NavigationUI.setupWithNavController(navView, navController);
    }
}

HomeFragment

package com.example.spoonacular.ui.home;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;

import com.example.spoonacular.R;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;

public class HomeFragment extends Fragment {

    private TextView mTextViewResult;
    private Button buttonParse;
    private HomeViewModel homeViewModel;
    private RequestQueue mQueue;

    public View onCreateView(@NonNull LayoutInflater inflater,
                             ViewGroup container, Bundle savedInstanceState) {
        homeViewModel =
                new ViewModelProvider(this).get(HomeViewModel.class);
        View root = inflater.inflate(R.layout.fragment_home, container, false);

        mTextViewResult = root.findViewById(R.id.text_view_result);
        buttonParse = root.findViewById(R.id.button_parse);

        mQueue = Volley.newRequestQueue(this);

        buttonParse.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                jsonParse();
            }
        });


        homeViewModel.getText().observe(getViewLifecycleOwner(), new Observer<String>() {
            @Override
            public void onChanged(@Nullable String s) {
                mTextViewResult.setText(s);
            }
        });
        return root;
    }

    private void jsonParse() {
        String url = "https://api.spoonacular.com/recipes/random?number=1&tags=vegetarian,dessert&apiKey=86912d6bb1474577a76513e236a8a58e";
        JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, null,
                new Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject response) {
                        try {
                            JSONArray jsonArray = response.getJSONArray("recipes");
                            for (int i = 0; i < jsonArray.length(); i++) {
                                JSONObject recipes = jsonArray.getJSONObject(i);

                                Boolean vegetarian = recipes.getBoolean("vegetarian");
                                Boolean vegan = recipes.getBoolean("vegan");
                                Boolean glutenFree = recipes.getBoolean("glutenFree");
                                Boolean dairyFree = recipes.getBoolean("dairyFree");
                                Boolean veryHealthy = recipes.getBoolean("veryHealthy");
                                Boolean cheap = recipes.getBoolean("cheap");
                                Boolean veryPopular = recipes.getBoolean("veryPopular");
                                Boolean sustainable = recipes.getBoolean("sustainable");
                                Boolean lowFodmap = recipes.getBoolean("lowFodmap");
                                int weightWatcherSmartPoints = recipes.getInt("weightWatcherSmartPoints");
                                int spoonacularScore = recipes.getInt("spoonacularScore");
                                int healthScore = recipes.getInt("healthScore");
                                int pricePerServing = recipes.getInt("pricePerServing");
                                int likes = recipes.getInt("aggregateLikes");
                                String gaps = recipes.getString("gaps");
                                String source = recipes.getString("sourceName");
                                mTextViewResult.setText("Vegetarian: " + vegetarian + "\n\n" + "Vegan: " + vegan + "\n\n" + "Gluten Free: " + glutenFree + "\n\n" + "Dairy Free: " + dairyFree + "\n\n" + "Very Healthy: " + veryHealthy + "\n\n" + "Cheap: " + cheap + "\n\n" + "Very Popular: " + veryPopular + "\n\n" + "Sustainable: " + sustainable + "\n\n" + "Low Fod Map: " + lowFodmap + "\n\n" + "Weight Watcher Points: " + String.valueOf(weightWatcherSmartPoints) + "\n\n" + "Spoonacular Score: " + String.valueOf(spoonacularScore) + "\n\n" + "Health Score: " + String.valueOf(healthScore) + "\n\n" + "Price Per Serving: " + String.valueOf(pricePerServing) + "\n\n" + "Likes: " + String.valueOf(likes) + "\n\n");
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                error.printStackTrace();
            }
        });
        mQueue.add(request);
    }
}

activity_main

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/container"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingTop="?attr/actionBarSize"
    >

    <com.google.android.material.bottomnavigation.BottomNavigationView
        android:id="@+id/nav_view"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginStart="0dp"
        android:layout_marginEnd="0dp"
        android:background="?android:attr/windowBackground"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:menu="@menu/bottom_nav_menu" />

    <fragment
        android:id="@+id/nav_host_fragment"
        android:name="androidx.navigation.fragment.NavHostFragment"
        android:layout_width="408dp"
        android:layout_height="742dp"
        app:defaultNavHost="true"
        app:layout_constraintBottom_toTopOf="@id/nav_view"
        app:layout_constraintHorizontal_bias="0.333"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.0"
        app:navGraph="@navigation/mobile_navigation" />

</androidx.constraintlayout.widget.ConstraintLayout>

fragment_home

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    >

    <TextView
        android:id="@+id/text_view_result"
        android:layout_width="194dp"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:textColor="#0A0A0A"
        app:layout_constraintBottom_toTopOf="@+id/nav_view"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.497"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.287"
        tools:text="dfgdfsgdfgdfgd"
        />

    <Button
        android:id="@+id/button_parse"
        android:layout_width="194dp"
        android:layout_height="71dp"
        android:text="Parse"
        app:layout_constraintBottom_toTopOf="@+id/nav_view"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.497"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="@+id/nav_host_fragment"
        app:layout_constraintVertical_bias="0.419"
        />

</LinearLayout>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM