Robin
Robin

Reputation: 577

Button to launch app (Fragments)

So I am running into more problems with fragments, only if viewpager worked with Activity. :|

My issue comes upon implementing the code to launch the calendar application. Of course I have a button which is linked to the code, from there when clicking the button it launches the calendar application. I have used the code below to do so -

// Calendar Launch
Button calendar_launch = (Button) getView().findViewById(R.id.calendar_launch); 
date_launch.setOnClickListener(new View.OnClickListener() { 

 @Override
 public void onClick(View v) {
     PackageManager packageManager = getActivity().getPackageManager();
     Intent intent_calendar = new Intent(Intent.ACTION_MAIN).addCategory(Intent.CATEGORY_LAUNCHER);

     // Verify calendar implementation
     String clockImpls[][] = {
             {"Default", "com.android.calendar", "com.android.calendar.AllInOneActivity" },
             {"HTC", "com.htc.calendar", "com.htc.calendar.LaunchActivity"},
             {"GOOGLE", "com.google.android.calendar", "com.android.calendar.AllInOneActivity"},
             {"SAMSUNG", "ShiftCalendar.SamsungElectronics","ShiftCalendar.SamsungElectronics.main"}
     };

     boolean foundClockImpl = false;

     for(int i=0; i<clockImpls.length; i++) {
         String vendor = clockImpls[i][0];
         String packageName = clockImpls[i][1];
         String className = clockImpls[i][2];
         try {
             ComponentName cn = new ComponentName(packageName, className);
             ActivityInfo aInfo = packageManager.getActivityInfo(cn, PackageManager.GET_META_DATA);
             intent_calendar.setComponent(cn);
             //debug("Found " + vendor + " --> " + packageName + "/" + className);
             foundClockImpl = true;
         } catch (NameNotFoundException e) {
             //debug(vendor + " does not exists");
         }
     }

     if (foundClockImpl) {
         startActivity(intent_calendar);
     }
  }
});

But Upon launching of the application, it immediately closes, after checking the error log I surfed the web for an appropriate answer, but I didn't really know what I was to search on? Looking at the error log, it said the error (NullPointerException) exists within the following line - Button date_launch = (Button) getView().findViewById(R.id.calendar_launch);

How must I go about fixing this error, also what else do I need to know when implementing code fro man Activity to a Fragment?

Class (Fragment)

public class HomeFragment extends Fragment {  

  public static HomeFragment newInstance(String title) {

      HomeFragment homeFragment = new HomeFragment();
      Bundle bundle = new Bundle();
      bundle.putString("title", title);
      homeFragment.setArguments(bundle);
      return homeFragment;
  }

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

  @Override  
  public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {          
      View view = inflater.inflate(R.layout.fragment_activity_home, container, false);  

        // (Calendar) Date function - Displays dateview on Card
        final boolean keepRunning1 = true;
        Thread thread_two = new Thread(){
            @Override
            public void run(){

                while(keepRunning1){

                    // Make the thread wait half a second. If you want...
                    try {
                        Thread.sleep(500);
                    } catch (InterruptedException e) {
                        Toast.makeText(getActivity().getApplicationContext(), "Default Signature Fail", Toast.LENGTH_LONG).show();
                        e.printStackTrace();
                    }

                    getActivity().runOnUiThread(new Runnable(){
                        @Override
                        public void run(){
                            TextView date = (TextView) getView().findViewById(R.id.date);
                            date.setText(DateUtils.formatDateTime(getActivity().getBaseContext(), System.currentTimeMillis(),DateUtils.FORMAT_SHOW_WEEKDAY | DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_SHOW_YEAR));
                        }
                    });
                }
            }
        };

        thread_two.start();

        // Calendar Launch
        Button calendar_launch = (Button) getView().findViewById(R.id.calendar_launch); 
        date_launch.setOnClickListener(new View.OnClickListener() { 

         @Override
         public void onClick(View v) {
             PackageManager packageManager = getActivity().getPackageManager();
             Intent intent_calendar = new Intent(Intent.ACTION_MAIN).addCategory(Intent.CATEGORY_LAUNCHER);

             // Verify calendar implementation
             String clockImpls[][] = {
                     {"Default", "com.android.calendar", "com.android.calendar.AllInOneActivity" },
                     {"HTC", "com.htc.calendar", "com.htc.calendar.LaunchActivity"},
                     {"GOOGLE", "com.google.android.calendar", "com.android.calendar.AllInOneActivity"},
                     {"SAMSUNG", "ShiftCalendar.SamsungElectronics","ShiftCalendar.SamsungElectronics.main"}
             };

             boolean foundClockImpl = false;

             for(int i=0; i<clockImpls.length; i++) {
                 String vendor = clockImpls[i][0];
                 String packageName = clockImpls[i][1];
                 String className = clockImpls[i][2];
                 try {
                     ComponentName cn = new ComponentName(packageName, className);
                     ActivityInfo aInfo = packageManager.getActivityInfo(cn, PackageManager.GET_META_DATA);
                     intent_calendar.setComponent(cn);
                     //debug("Found " + vendor + " --> " + packageName + "/" + className);
                     foundClockImpl = true;
                 } catch (NameNotFoundException e) {
                     //debug(vendor + " does not exists");
                 }
             }

             if (foundClockImpl) {
                 startActivity(intent_calendar);
             }
          }
        });
      return view;  
    }
}

layout.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/blue"
    android:layoutAnimation="@anim/default_anim_parse"
    android:orientation="vertical" >

                    <!-- Header -->
                <LinearLayout
                    android:id="@+id/header_image"
                    android:layout_width="match_parent"
                    android:layout_height="120dp"
                    android:background="@drawable/header"
                    android:orientation="vertical" >

                    <RelativeLayout
                        android:id="@+id/google_search"
                        android:layout_width="match_parent"
                        android:layout_height="42dp"
                        android:layout_marginLeft="10dp"
                        android:layout_marginRight="10dp"
                        android:layout_marginTop="40dp"
                        android:background="@drawable/mybutton"
                        android:orientation="vertical" >

                        <com.activelauncher.MyTextView
                            android:id="@+id/search_text"
                            android:layout_width="100dp"
                            android:layout_height="42dp"
                            android:layout_alignParentLeft="true"
                            android:layout_alignParentTop="true"
                            android:layout_marginLeft="10dp"
                            android:gravity="center|left"
                            android:text="Google Search"
                            android:textColor="#6b6b6b"
                            android:textSize="15.5sp" />

                        <Button
                            android:id="@+id/search_button"
                            android:layout_width="35dp"
                            android:layout_height="35dp"
                            android:layout_alignParentRight="true"
                            android:layout_marginRight="4dp"
                            android:layout_marginTop="4dp"
                            android:gravity="center|left"
                            android:background="@drawable/google_search_button" />

                    </RelativeLayout>
                </LinearLayout>
                <!--  Header End -->

             <!-- Date View -->
                <LinearLayout
                    android:layout_width="match_parent"
                    android:layout_height="70dp"
                    android:layout_marginLeft="10dp"
                    android:layout_marginRight="10dp"
                    android:layout_marginTop="10dp"
                    android:background="@drawable/bg_card"
                    android:orientation="vertical" >

                    <com.activelauncher.MyTextView
                        android:id="@+id/date"
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:layout_gravity="center"
                        android:drawableRight="@drawable/ic_action_event_normal"
                        android:gravity="left"
                        android:text="@string/calendar"
                        android:textAppearance="?android:attr/textAppearanceLarge"
                        android:textColor="#6b6b6b"
                        android:textSize="20sp" />

                    <com.activelauncher.MyTextView
                        android:id="@+id/date_two"
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:layout_gravity="center"
                        android:gravity="left"
                        android:text="@string/calendar_summary"
                        android:textAppearance="?android:attr/textAppearanceLarge"
                        android:textColor="#6b6b6b"
                        android:textSize="15sp" />
                </LinearLayout>
                <!--  Date View End  -->
                <!-- Date Button -->
                <Button
                    android:id="@+id/calendar_launch"
                    android:layout_width="fill_parent"
                    android:layout_height="wrap_content"
                    android:layout_marginLeft="10dp"
                    android:layout_marginRight="10dp"
                    android:background="@drawable/mybutton"
                    android:drawableLeft="@drawable/ic_action_browse_normal"
                    android:gravity="left|center"
                    android:paddingLeft="5dp"
                    android:text="@string/calendar_button"
                    android:textColor="#4285F4" />
               <!-- Date Button End -->

               <!-- Time View -->
                <LinearLayout
                    android:layout_width="match_parent"
                    android:layout_height="70dp"
                    android:layout_marginLeft="10dp"
                    android:layout_marginRight="10dp"
                    android:layout_marginTop="10dp"
                    android:background="@drawable/bg_card"
                    android:orientation="vertical" >

                    <com.activelauncher.MyTextView
                        android:id="@+id/time"
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:layout_gravity="center"
                        android:drawableRight="@drawable/ic_action_alarm_normal"
                        android:gravity="left"
                        android:text="@string/time"
                        android:textAppearance="?android:attr/textAppearanceLarge"
                        android:textColor="#6b6b6b"
                        android:textSize="20sp" />

                    <com.activelauncher.MyTextView
                        android:id="@+id/time_two"
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:layout_gravity="center"
                        android:gravity="left"
                        android:text="@string/time_summary"
                        android:textAppearance="?android:attr/textAppearanceLarge"
                        android:textColor="#6b6b6b"
                        android:textSize="15sp" />
                </LinearLayout>
                <!-- Time Button -->

                <Button
                    android:id="@+id/time_launch"
                    android:layout_width="fill_parent"
                    android:layout_height="wrap_content"
                    android:layout_marginLeft="10dp"
                    android:layout_marginRight="10dp"
                    android:background="@drawable/mybutton"
                    android:drawableLeft="@drawable/ic_action_browse_normal"
                    android:gravity="left|center"
                    android:paddingLeft="5dp"
                    android:text="@string/time_button"
                    android:textColor="#4285F4" />
                <!-- Time View End -->


</LinearLayout>

Upvotes: 0

Views: 54

Answers (1)

M D
M D

Reputation: 47817

try this way

Button date_launch = (Button) view.findViewById(R.id.calendar_launch);

instead of

 Button calendar_launch = (Button) getView().findViewById(R.id.calendar_launch); 

You have to initialized your Button in onCreateView(....) in your Fragement with particular View that you've inflated.

Upvotes: 1

Related Questions