尝试在带有片段的底部导航视图布局中实现JSON

时间:2020-05-19 16:27:59

标签: android json android-fragments

我正在尝试创建一个项目,该项目在主要活动和4个片段中具有底部导航视图。我希望解析JSON并更新应该显示信息的片段之一中的数据。我的代码解析了主要活动中的数据,但出现错误。我不断收到

主要活动代码

strdup()

片段页面XML

public class MainActivity extends AppCompatActivity {
TextView infectedCaseCount;
TextView deceasedCaseCount;
TextView recoveredCaseCount;
RequestQueue requestQueue;
Button parseBtn;

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

    BottomNavigationView bottomNavigationView = findViewById(R.id.bottom_navigation);
    bottomNavigationView.setOnNavigationItemSelectedListener(navListener);
    getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,new CasesFragment()).commit();

    infectedCaseCount = findViewById(R.id.infectedCaseCount);
    deceasedCaseCount = findViewById(R.id.deceasedCaseCount);
    recoveredCaseCount = findViewById(R.id.recoveredCaseCount);
    parseBtn = (Button) findViewById(R.id.parseBtn);
    requestQueue = Volley.newRequestQueue(this);

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





}

public void jsonParse() {
        String url="https://api.covid19api.com/summary";
         JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET,url,null, new Response.Listener<JSONObject>() {
             @Override
             public void onResponse(JSONObject response) {
                 try {
                     JSONArray jsonArray = response.getJSONArray("Global");

                     for(int i=0;i< jsonArray.length();i++)
                     {
                         JSONObject global = jsonArray.getJSONObject(i);
                         String TotalConfirmed = global.getString("TotalConfirmed");
                         String TotalDeaths = global.getString("TotalDeaths");
                         String TotalRecovered = global.getString("TotalRecovered");

                         infectedCaseCount.setText(TotalConfirmed);
                         deceasedCaseCount.setText(TotalDeaths);
                         recoveredCaseCount.setText(TotalRecovered);

                     }
                 } catch (JSONException e) {
                     e.printStackTrace();
                 }
             }
         }, new Response.ErrorListener() {
             @Override
             public void onErrorResponse(VolleyError error) {
                 error.printStackTrace();
             }
         });
         requestQueue.add(request);
}

private BottomNavigationView.OnNavigationItemSelectedListener navListener =
        new BottomNavigationView.OnNavigationItemSelectedListener() {
            @Override
            public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) {
               Fragment selectedFragment = null;

               switch(menuItem.getItemId()){
                   case R.id.updates:
                       selectedFragment = new CasesFragment();
                       break;
                   case R.id.symptoms:
                       selectedFragment = new SymptomsFragment();
                       break;
                   case R.id.safety:
                       selectedFragment = new SafetyFragment();
                       break;
                   case R.id.contact:
                       selectedFragment = new FragmentContact();
                       break;
               }
               getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,selectedFragment).commit();
               return true;
            }
        };


}

Fragment.java

<androidx.core.widget.NestedScrollView 
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/scrollView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingTop="10dp">

<RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="500dp"

    android:background="@color/colorPrimaryDark">

    <Button
        android:id="@+id/parseBtn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@id/linearAboveButton"
        android:layout_centerInParent="true"
        android:layout_marginTop="20dp"
        android:background="@drawable/button"
        android:text="Get Info!"
        android:textAllCaps="false"
        android:textColor="@color/White" />

    <TextView
        android:id="@+id/globalSituation"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="20dp"
        android:layout_marginTop="10dp"
        android:fontFamily="@font/medium"
        android:text="Global Situation"
        android:textColor="@color/colorDescription"
        android:textSize="30sp" />


    <androidx.appcompat.widget.LinearLayoutCompat
        android:id="@+id/linearAboveButton"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_below="@id/totCase"
        android:orientation="horizontal"
        android:weightSum="2">

        <androidx.cardview.widget.CardView
            android:id="@+id/deceasedData"
            android:layout_width="0dp"
            android:layout_height="80dp"
            android:layout_margin="20dp"
            android:layout_weight="1"
            android:background="#E7F8FA"
            android:padding="5dp"
            app:cardCornerRadius="16dp"
            app:cardElevation="10dp">

            <androidx.appcompat.widget.LinearLayoutCompat
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:orientation="vertical"
                android:paddingTop="5dp">


                <TextView
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:fontFamily="@font/regular"
                    android:text="Recovered"
                    android:textAlignment="center"
                    android:textSize="25sp" />

                <TextView
                    android:id="@+id/recoveredCaseCount"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:fontFamily="@font/medium"
                    android:text="4345677"
                    android:textAlignment="center"
                    android:textColor="@color/actCases"
                    android:textSize="25sp" />


            </androidx.appcompat.widget.LinearLayoutCompat>


        </androidx.cardview.widget.CardView>

        <androidx.cardview.widget.CardView
            android:id="@+id/activeData"
            android:layout_width="0dp"
            android:layout_height="80dp"
            android:layout_margin="20dp"
            android:layout_weight="1"
            android:background="#E7F8FA"
            app:cardCornerRadius="16dp"

            app:cardElevation="10dp">

            <androidx.appcompat.widget.LinearLayoutCompat
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:orientation="vertical"
                android:paddingTop="5dp">

                <TextView
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:fontFamily="@font/regular"
                    android:text="Deceased"
                    android:textAlignment="center"
                    android:textSize="25sp" />

                <TextView
                    android:id="@+id/deceasedCaseCount"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:fontFamily="@font/medium"
                    android:text="4345677"
                    android:textAlignment="center"
                    android:textColor="@color/decCases"
                    android:textSize="25sp" />

            </androidx.appcompat.widget.LinearLayoutCompat>

        </androidx.cardview.widget.CardView>


    </androidx.appcompat.widget.LinearLayoutCompat>


    <androidx.cardview.widget.CardView
        android:id="@+id/totCase"
        android:layout_width="match_parent"
        android:layout_height="80dp"
        android:layout_below="@id/globalSituation"
        android:layout_marginLeft="10dp"
        android:layout_marginTop="10dp"
        android:layout_marginRight="10dp"
        android:background="#E7F8FA"
        android:paddingTop="5dp"
        app:cardCornerRadius="16dp"
        app:cardElevation="10dp">

        <androidx.appcompat.widget.LinearLayoutCompat
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="vertical"
            android:paddingTop="5dp">

            <TextView
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:fontFamily="@font/regular"
                android:text="Infected"
                android:textAlignment="center"
                android:textSize="25sp" />

            <TextView
                android:id="@+id/infectedCaseCount"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:fontFamily="@font/medium"
                android:text="4345677"
                android:textAlignment="center"
                android:textColor="@color/totCases"
                android:textSize="25sp" />

        </androidx.appcompat.widget.LinearLayoutCompat>

    </androidx.cardview.widget.CardView>


</RelativeLayout>

错误

public class CasesFragment extends Fragment {


@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

    return inflater.inflate(R.layout.fragment_cases,container,false);


}
}

CasesFragment

E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.coronavirustracker, PID: 28827
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.coronavirustracker/com.example.coronavirustracker.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2913)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3048)
    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:1808)
    at android.os.Handler.dispatchMessage(Handler.java:106)
    at android.os.Looper.loop(Looper.java:193)
    at android.app.ActivityThread.main(ActivityThread.java:6669)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)
 Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
    at com.example.coronavirustracker.MainActivity.onCreate(MainActivity.java:51)
    at android.app.Activity.performCreate(Activity.java:7136)
    at android.app.Activity.performCreate(Activity.java:7127)
    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1271)
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2893)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3048) 
    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:1808) 
    at android.os.Handler.dispatchMessage(Handler.java:106) 
    at android.os.Looper.loop(Looper.java:193) 
    at android.app.ActivityThread.main(ActivityThread.java:6669) 
    at java.lang.reflect.Method.invoke(Native Method) 
    at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493) 
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858) 

新错误

public class CasesFragment extends Fragment {

TextView infectedCaseCount;
TextView deceasedCaseCount;
TextView recoveredCaseCount;
RequestQueue requestQueue;
Button parseBtn;


@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

    parseBtn = getActivity().findViewById(R.id.parseBtn);
    infectedCaseCount = getActivity().findViewById(R.id.infectedCaseCount);
    deceasedCaseCount = getActivity().findViewById(R.id.deceasedCaseCount);
    recoveredCaseCount = getActivity().findViewById(R.id.recoveredCaseCount);
    requestQueue = Volley.newRequestQueue(getContext());

    parseBtn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            jsonParse();
        }
    });
    return inflater.inflate(R.layout.fragment_cases,container,false);


}
public void jsonParse() {
    String url="https://api.covid19api.com/summary";
    JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET,url,null, new Response.Listener<JSONObject>() {
        @Override
        public void onResponse(JSONObject response) {
            try {
                JSONArray jsonArray = response.getJSONArray("Global");

                for(int i=0;i< jsonArray.length();i++)
                {
                    JSONObject global = jsonArray.getJSONObject(i);

                    String TotalConfirmed = global.getString("TotalConfirmed");
                    String TotalDeaths = global.getString("TotalDeaths");
                    String TotalRecovered = global.getString("TotalRecovered");

                    infectedCaseCount.setText(TotalConfirmed);
                    deceasedCaseCount.setText(TotalDeaths);
                    recoveredCaseCount.setText(TotalRecovered);

                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            error.printStackTrace();
        }
    });
    requestQueue.add(request);
}
}

1 个答案:

答案 0 :(得分:0)

您正在使用主类初始化Fragment中存在的View。然后应在Fragment类而不是主类中进行初始化。

案件内部片段

button =getActivity().findViewById(R.id.text_paresbt);

实际上,您应该将整个代码移到片段上

infectedCaseCount = findViewById(R.id.infectedCaseCount);
deceasedCaseCount = findViewById(R.id.deceasedCaseCount);
recoveredCaseCount = findViewById(R.id.recoveredCaseCount);
parseBtn = (Button) findViewById(R.id.parseBtn);


parseBtn.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        jsonParse();
    }
});
}
相关问题