应用在从片段打开活动时在startActivity(intent)处崩溃。

huangapple 未分类评论42阅读模式
英文:

App crashes at startActivity(intent) while opening Activity from Fragment

问题

I was on my way of making a simple app that retrieves some list data from shared preferences and shows it on the screen. Long story short, the code to display the list is in a fragment 'InventoryFragment'. Inside that, I have a button, and I set an onClick so that an intent is sent to open another activity 'AddActivity'. That's where it crashes, at startActivity(intent).

It is a silly problem, but I can't find the solution. I tried with a simple 'TestActivity' (with just a textview showing up), and that gets shown, but not 'AddActivity'.

What is the error?

InventoryFragment:

package com.coffeetech.kittycatch;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.net.Uri;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentTransaction;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import java.lang.reflect.Type;
import java.util.ArrayList;


public class InventoryFragment extends Fragment {

    public InventoryFragment() {
    }

    // ... (Code omitted for brevity)

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // ... (Code omitted for brevity)

        floatingActionButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getActivity(), AddActivity.class);
                startActivity(intent);
            }
        });

        return rootView;
    }

    // ... (Code omitted for brevity)
}

AddActivity:

package com.coffeetech.kittycatch;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;

public class AddActivity extends AppCompatActivity {
    // ... (Code omitted for brevity)

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.add_activity);
        item_name = findViewById(R.id.name_add);
        quantity=findViewById(R.id.quantity_add);
        quantity_min=findViewById(R.id.min_quantity_add);
        save=findViewById(R.id.save_button);

        // Fix the initialization of radio_group
        radio_group = findViewById(R.id.radio_group);

        int id = radio_group.getCheckedRadioButtonId();
        if (id == R.id.discrete_button_add) {
            type = 0;
        } else {
            type = 1;
        }

        // ... (Code omitted for brevity)
    }
}

Layout for AddActivity:

<!-- ... (Layout code omitted for brevity) -->

<RadioGroup
    android:id="@+id/radio_group"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_weight="1">

    <RadioButton
        android:id="@+id/discrete_button_add"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Discrete" />

    <RadioButton
        android:id="@+id/cont_button_add"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Continuous" />
</RadioGroup>

<!-- ... (Layout code omitted for brevity) -->

Please note that I've provided the corrected parts of the code related to the error you mentioned. If you encounter any other issues or need further assistance, feel free to ask.

英文:

I was on my way of making a simple app that retrieves some list data from shared preferences and shows it on the screen. Long story short, the code to display the list is in a fragment 'InventoryFragment'. Inside that, I have a button, and I set an onClick so that an intent is sent to open another activity 'AddActivity'. That's where it crashes, at startActivity(intent).

It is a silly problem, but I can't find the solution. I tried with a simple 'TestActivity' (with just a textview showing up), and that gets shown, but not 'AddActivity'.

What is the error?

InventoryFragment:

package com.coffeetech.kittycatch;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.net.Uri;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentTransaction;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import java.lang.reflect.Type;
import java.util.ArrayList;


public class InventoryFragment extends Fragment {

    public InventoryFragment() {
    }

    //GLOBAL VARIABLES
    private ArrayList&lt;Food&gt; foods;
    private FoodAdapter foodAdapter;
    private ListView listView;
    private FloatingActionButton floatingActionButton;
    private View rootView;
    private Food food; //FOR BUNDLE




    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

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

        loadData(); //loading the data into arraylist

        if (getArguments()!=null){
            food.name = getArguments().getString(&quot;name&quot;);
            food.quantity=getArguments().getInt(&quot;quantity&quot;);
            food.min_quantity=getArguments().getInt(&quot;quantity_min&quot;);
            food.type=getArguments().getInt(&quot;type&quot;);
            foods.add(food);
            saveData();
        }

        //LOCATING THE FRAGMENT LAYOUT
        rootView = inflater.inflate(R.layout.inventory_fragment, container, false);

        //FOOD USAGE
        //foods.add(new Food(&quot;Tomatoes&quot;, 0, 10, 2));

        //SETTING ADAPTER FOR FOOD LIST
        foodAdapter = new FoodAdapter(getActivity(),foods);

        // SETTING LISTVIEW WITH ADAPTER
        listView = rootView.findViewById(R.id.list_view);
        listView.setAdapter(foodAdapter);

        //setting up the Add button
        floatingActionButton = rootView.findViewById(R.id.add_button);
        floatingActionButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //Go to ADD activity with no data, since new would be added
                //Intent intent = new Intent(getActivity(),AddActivity.class);
                //startActivity(intent);
                Intent intent = new Intent(getActivity(),AddActivity.class);
                startActivity(intent);
            }
        });

        return rootView;

    }

    private void saveData(){
        SharedPreferences sharedPreferences = getActivity().getSharedPreferences(&quot;shared preferences&quot;,Context.MODE_PRIVATE );
        Editor editor = sharedPreferences.edit();
        Gson gson = new Gson();
        String json = gson.toJson(foods);
        editor.putString(&quot;inventory&quot;,json);
        editor.apply();
    }


    private void loadData(){
        SharedPreferences sharedPreferences = getActivity().getSharedPreferences(&quot;shared preferences&quot;,Context.MODE_PRIVATE );
        Gson gson = new Gson();
        String json = sharedPreferences.getString(&quot;inventory&quot;,null);
        Type type = new TypeToken&lt;ArrayList&lt;Food&gt;&gt;(){}.getType();
        foods = gson.fromJson(json,type);

        if (foods==null){
            foods = new ArrayList&lt;Food&gt;();
        }

    }

    @Override
    public void onStop() {
        saveData();
        super.onStop();
    }
}


Layout for the above fragment:

&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;
&lt;FrameLayout xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;
    xmlns:app=&quot;http://schemas.android.com/apk/res-auto&quot;
    xmlns:tools=&quot;http://schemas.android.com/tools&quot;
    android:id=&quot;@+id/inventory&quot;
    android:layout_width=&quot;match_parent&quot;
    android:layout_height=&quot;match_parent&quot;
    tools:context=&quot;.InventoryFragment&quot;&gt;


    &lt;com.google.android.material.floatingactionbutton.FloatingActionButton
        android:id=&quot;@+id/add_button&quot;
        android:layout_width=&quot;wrap_content&quot;
        android:layout_height=&quot;wrap_content&quot;
        android:layout_gravity=&quot;bottom|right&quot;
        android:layout_margin=&quot;52dp&quot;
        android:background=&quot;#2196F3&quot;
        android:clickable=&quot;true&quot;
        android:src=&quot;@android:drawable/ic_menu_add&quot; /&gt;

    &lt;ListView
        android:id=&quot;@+id/list_view&quot;
        android:layout_width=&quot;match_parent&quot;
        android:layout_height=&quot;match_parent&quot;
        android:layout_marginLeft=&quot;12dp&quot;
        android:layout_marginRight=&quot;12dp&quot;&gt;

    &lt;/ListView&gt;

&lt;/FrameLayout&gt;

AddActivity:

package com.coffeetech.kittycatch;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;

public class AddActivity extends AppCompatActivity {
    //GLOBAL VARIABLES
    EditText item_name,quantity,quantity_min;
    RadioGroup radio_group;
    String name;
    Button save;
    int q,q_min,type;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.add_activity);
        item_name = findViewById(R.id.name_add);
        quantity=findViewById(R.id.quantity_add);
        quantity_min=findViewById(R.id.min_quantity_add);
        save=findViewById(R.id.save_button);

        int id = radio_group.getCheckedRadioButtonId();
        if (id == 1000008){
            type=0;
        }else{
            type=1;
        }

        save.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                name=item_name.getText().toString();
                q=Integer.parseInt(String.valueOf(quantity.getText()));
                q=Integer.parseInt(String.valueOf(quantity.getText()));
                q_min=Integer.parseInt(String.valueOf(quantity_min.getText()));
                //AT THIS POINT, name,q,q_min,type ARE READY TO BE BUNDLED
                InventoryFragment inventoryFragment = new InventoryFragment();
                Bundle args = new Bundle();
                args.putString(&quot;name&quot;,name);
                args.putInt(&quot;quantity_min&quot;,q_min);
                args.putInt(&quot;quantity&quot;,q);
                args.putInt(&quot;type&quot;,type);
                inventoryFragment.setArguments(args);
                getSupportFragmentManager().beginTransaction().replace(R.id.abcd,inventoryFragment).commit();
            }
        });
    }
}

Layout for above:

&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;
&lt;LinearLayout xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;
    xmlns:app=&quot;http://schemas.android.com/apk/res-auto&quot;
    xmlns:tools=&quot;http://schemas.android.com/tools&quot;
    android:id=&quot;@+id/abcd&quot;
    android:layout_width=&quot;match_parent&quot;
    android:layout_height=&quot;wrap_content&quot;
    android:layout_marginLeft=&quot;12sp&quot;
    android:layout_marginRight=&quot;12sp&quot;
    android:orientation=&quot;vertical&quot;
    tools:context=&quot;.AddActivity&quot;&gt;

    &lt;LinearLayout
        android:layout_width=&quot;match_parent&quot;
        android:layout_height=&quot;wrap_content&quot;
        android:orientation=&quot;horizontal&quot;&gt;

        &lt;TextView
            android:layout_width=&quot;wrap_content&quot;
            android:layout_height=&quot;wrap_content&quot;
            android:layout_weight=&quot;1&quot;
            android:text=&quot;Item name: &quot; /&gt;

        &lt;EditText
            android:id=&quot;@+id/name_add&quot;
            android:layout_width=&quot;wrap_content&quot;
            android:layout_height=&quot;wrap_content&quot;
            android:layout_weight=&quot;1&quot; /&gt;

    &lt;/LinearLayout&gt;

    &lt;LinearLayout
        android:layout_width=&quot;match_parent&quot;
        android:layout_height=&quot;wrap_content&quot;
        android:orientation=&quot;horizontal&quot;&gt;

        &lt;TextView
            android:layout_width=&quot;wrap_content&quot;
            android:layout_height=&quot;wrap_content&quot;
            android:layout_weight=&quot;1&quot;
            android:text=&quot;Minimum Quantity: &quot; /&gt;

        &lt;EditText
            android:id=&quot;@+id/min_quantity_add&quot;
            android:layout_width=&quot;wrap_content&quot;
            android:layout_height=&quot;wrap_content&quot;
            android:layout_weight=&quot;1&quot;
            android:ems=&quot;10&quot;
            android:inputType=&quot;numberDecimal&quot; /&gt;

    &lt;/LinearLayout&gt;

    &lt;LinearLayout
        android:layout_width=&quot;match_parent&quot;
        android:layout_height=&quot;wrap_content&quot;
        android:orientation=&quot;horizontal&quot;&gt;

        &lt;TextView
            android:layout_width=&quot;wrap_content&quot;
            android:layout_height=&quot;wrap_content&quot;
            android:layout_weight=&quot;1&quot;
            android:text=&quot;Quantity (now): &quot; /&gt;

        &lt;EditText
            android:id=&quot;@+id/quantity_add&quot;
            android:layout_width=&quot;wrap_content&quot;
            android:layout_height=&quot;wrap_content&quot;
            android:layout_weight=&quot;1&quot;
            android:ems=&quot;10&quot;
            android:inputType=&quot;numberDecimal&quot; /&gt;
    &lt;/LinearLayout&gt;

    &lt;LinearLayout
        android:layout_width=&quot;match_parent&quot;
        android:layout_height=&quot;match_parent&quot;
        android:orientation=&quot;horizontal&quot;&gt;

        &lt;TextView
            android:layout_width=&quot;wrap_content&quot;
            android:layout_height=&quot;wrap_content&quot;
            android:layout_weight=&quot;1&quot;
            android:text=&quot;Type: &quot; /&gt;

        &lt;RadioGroup
            android:layout_width=&quot;wrap_content&quot;
            android:layout_height=&quot;wrap_content&quot;
            android:layout_weight=&quot;1&quot;&gt;

            &lt;RadioButton
                android:id=&quot;@+id/discrete_button_add&quot;
                android:layout_width=&quot;match_parent&quot;
                android:layout_height=&quot;wrap_content&quot;
                android:text=&quot;Discrete&quot; /&gt;

            &lt;RadioButton
                android:id=&quot;@+id/cont_button_add&quot;
                android:layout_width=&quot;match_parent&quot;
                android:layout_height=&quot;wrap_content&quot;
                android:text=&quot;Continuous&quot; /&gt;
        &lt;/RadioGroup&gt;

    &lt;/LinearLayout&gt;

    &lt;Button
        android:id=&quot;@+id/save_button&quot;
        android:layout_width=&quot;wrap_content&quot;
        android:layout_height=&quot;wrap_content&quot;
        android:layout_gravity=&quot;right&quot;
        android:text=&quot;SAVE&quot; /&gt;

&lt;/LinearLayout&gt;

AndroidManifest.xml

&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;
&lt;manifest xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;
    package=&quot;com.coffeetech.kittycatch&quot;&gt;

    &lt;application
        android:allowBackup=&quot;true&quot;
        android:icon=&quot;@mipmap/ic_launcher&quot;
        android:label=&quot;@string/app_name&quot;
        android:roundIcon=&quot;@mipmap/ic_launcher_round&quot;
        android:supportsRtl=&quot;true&quot;
        android:theme=&quot;@style/AppTheme&quot;&gt;
        &lt;activity android:name=&quot;.AddActivity&quot; /&gt;
        &lt;activity android:name=&quot;.MainActivity&quot;&gt;
            &lt;intent-filter&gt;
                &lt;action android:name=&quot;android.intent.action.MAIN&quot; /&gt;

                &lt;category android:name=&quot;android.intent.category.LAUNCHER&quot; /&gt;
            &lt;/intent-filter&gt;
        &lt;/activity&gt;
    &lt;/application&gt;

&lt;/manifest&gt;

logcat:

2020-04-05 02:59:54.359 18534-18534/? E/tech.kittycatc: Unknown bits set in runtime_flags: 0x28000
2020-04-05 02:59:54.501 18534-18563/com.coffeetech.kittycatch E/Perf: Fail to get file list com.coffeetech.kittycatch
2020-04-05 02:59:54.502 18534-18563/com.coffeetech.kittycatch E/Perf: getFolderSize() : Exception_1 = java.lang.NullPointerException: Attempt to get length of null array
2020-04-05 02:59:54.502 18534-18563/com.coffeetech.kittycatch E/Perf: Fail to get file list com.coffeetech.kittycatch
2020-04-05 02:59:54.502 18534-18563/com.coffeetech.kittycatch E/Perf: getFolderSize() : Exception_1 = java.lang.NullPointerException: Attempt to get length of null array
2020-04-05 02:59:54.503 18534-18563/com.coffeetech.kittycatch E/Perf: Fail to get file list oat
2020-04-05 02:59:54.504 18534-18563/com.coffeetech.kittycatch E/Perf: getFolderSize() : Exception_1 = java.lang.NullPointerException: Attempt to get length of null array
2020-04-05 03:00:04.424 18534-18534/com.coffeetech.kittycatch E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.coffeetech.kittycatch, PID: 18534
    java.lang.RuntimeException: Unable to start activity ComponentInfo{com.coffeetech.kittycatch/com.coffeetech.kittycatch.AddActivity}: java.lang.NullPointerException: Attempt to invoke virtual method &#39;int android.widget.RadioGroup.getCheckedRadioButtonId()&#39; on a null object reference
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3497)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3636)
        at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:83)
        at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:140)
        at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:100)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2222)
        at android.os.Handler.dispatchMessage(Handler.java:107)
        at android.os.Looper.loop(Looper.java:228)
        at android.app.ActivityThread.main(ActivityThread.java:7782)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:981)
     Caused by: java.lang.NullPointerException: Attempt to invoke virtual method &#39;int android.widget.RadioGroup.getCheckedRadioButtonId()&#39; on a null object reference
        at com.coffeetech.kittycatch.AddActivity.onCreate(AddActivity.java:31)
        at android.app.Activity.performCreate(Activity.java:7964)
        at android.app.Activity.performCreate(Activity.java:7953)
        at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1307)
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3472)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3636)&#160;
        at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:83)&#160;
        at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:140)&#160;
        at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:100)&#160;
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2222)&#160;
        at android.os.Handler.dispatchMessage(Handler.java:107)&#160;
        at android.os.Looper.loop(Looper.java:228)&#160;
        at android.app.ActivityThread.main(ActivityThread.java:7782)&#160;
        at java.lang.reflect.Method.invoke(Native Method)&#160;
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492)&#160;
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:981)&#160;

Thanks in advance to anyone who replies 应用在从片段打开活动时在startActivity(intent)处崩溃。

huangapple
  • 本文由 发表于 2020年4月5日 05:05:33
  • 转载请务必保留本文链接:https://java.coder-hub.com/61034774.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定