2016-02-19 4 views
1

Я имитирую код в этом thread, чтобы создать событие многократного нажатия, которое запускает браузер. Я хочу передать целевой URL-адрес при создании экземпляра класса. Пример не имеет никакой очевидной ошибки в затмении, но сбой при запуске:Повторное использование прослушивателя onclick со строковым параметром в Android Java

FATAL EXCEPTION: main 02-19 12:45:57.416: E/AndroidRuntime(12465): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.app/com.app.ItemActivity}: java.lang.NullPointerException

ошибка должна исходить от этой линии btn.setOnClickListener(new ButtonInternetAccess("http://google.com"));

, потому что он работает нормально без этой линии. Не возвращает класс ButtonInternetAccess onClickListener, который приводит к нулевому значению? Как я могу это исправить?

Основная деятельность:

public class ItemActivity extends ActionBarActivity{ 
    private static final View View = null; 
    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_item); 
     Bundle b = i.getExtras(); 
     Button btn = (Button) findViewById(R.id.button_internet_access); 
     btn.setOnClickListener(new ButtonInternetAccess("http://google.com"));  
    } 
} 

Кнопка Класс:

public class ButtonInternetAccess extends Activity implements OnClickListener { 
    String url; 
    public ButtonInternetAccess(String url) { 
     this.url = url; 
    } 

    public void onClick(View v) { 
     try { 
      Intent callIntent = new Intent(Intent.ACTION_CALL); 
      callIntent.setData(Uri.parse(url)); 
      startActivity(callIntent); // No Error here 

      System.out.println(url); 
     } catch (ActivityNotFoundException activityException) { 
      Log.e("Calling a Phone Number", "Call failed", activityException); 
     } 
    } 

} 

макет/activity_item

<TextView 
    android:id="@+id/response" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:text="" /> 

<include android:id="@+id/header" layout="@layout/button_internet_access"> 

макет/button_internet_access:

<Button xmlns:android="http://schemas.android.com/apk/res/android" 
    android:id="@+id/button_internet_access" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:text="go out" /> 

Ошибка:

02-19 12:45:57.416: E/AndroidRuntime(12465): FATAL EXCEPTION: main 
02-19 12:45:57.416: E/AndroidRuntime(12465): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.app/com.app.ItemActivity}: java.lang.NullPointerException 
02-19 12:45:57.416: E/AndroidRuntime(12465): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2059) 
02-19 12:45:57.416: E/AndroidRuntime(12465): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2084) 
02-19 12:45:57.416: E/AndroidRuntime(12465): at android.app.ActivityThread.access$600(ActivityThread.java:130) 
02-19 12:45:57.416: E/AndroidRuntime(12465): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1195) 
02-19 12:45:57.416: E/AndroidRuntime(12465): at android.os.Handler.dispatchMessage(Handler.java:99) 
02-19 12:45:57.416: E/AndroidRuntime(12465): at android.os.Looper.loop(Looper.java:137) 
02-19 12:45:57.416: E/AndroidRuntime(12465): at android.app.ActivityThread.main(ActivityThread.java:4745) 
02-19 12:45:57.416: E/AndroidRuntime(12465): at java.lang.reflect.Method.invokeNative(Native Method) 
02-19 12:45:57.416: E/AndroidRuntime(12465): at java.lang.reflect.Method.invoke(Method.java:511) 
02-19 12:45:57.416: E/AndroidRuntime(12465): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786) 
02-19 12:45:57.416: E/AndroidRuntime(12465): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553) 
02-19 12:45:57.416: E/AndroidRuntime(12465): at dalvik.system.NativeStart.main(Native Method) 
02-19 12:45:57.416: E/AndroidRuntime(12465): Caused by: java.lang.NullPointerException 
02-19 12:45:57.416: E/AndroidRuntime(12465): at com.app.ItemActivity.onCreate(ItemActivity.java:29) 
02-19 12:45:57.416: E/AndroidRuntime(12465): at android.app.Activity.performCreate(Activity.java:5008) 
02-19 12:45:57.416: E/AndroidRuntime(12465): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1079) 
02-19 12:45:57.416: E/AndroidRuntime(12465): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2023) 

Обновлено:

мне удалось сделать плагин после этого link.

Выпускная работа:

Класс Интернет:

public class Internet implements OnClickListener { 

    private String url; 
    private Context context; 

    public Internet(Context context, String url) { 
     this.context = context; 
     this.url = url; 
    } 

    @Override 
    public void onClick(View v) { 

     if (!url.contains("http://")){ 
      url = "http://"+url; 
     } 
     Intent callIntent = new Intent(Intent.ACTION_VIEW); 
     callIntent.setData(Uri.parse(url)); 
     context.startActivity(callIntent); 
    } 
} 

Класс StyleButton:

public class StyleButton extends Button{ 

    public StyleButton(Context context) { 
     super(context); 
    } 

    public StyleButton(Context context, AttributeSet attrs) { 
     super(context, attrs); 
     initStyleButton(attrs); 
    } 

    public StyleButton(Context context, AttributeSet attrs, int defStyle,String url) { 
     super(context, attrs, defStyle); 
     initStyleButton(attrs); 
    } 

    private void initStyleButton(AttributeSet attrs){ 
     TypedArray a = getContext().obtainStyledAttributes(attrs,R.styleable.style_Button); 
     String Text1 = a.getString(R.styleable.style_Button_myText_1); 
     String Text2 = a.getString(R.styleable.style_Button_myText_2); 
     setText(Text1 + "\n" + Text2); 
     String url = a.getString(R.styleable.style_Button_url); 
     System.out.println(url); 
     setOnClickListener(new Internet(getContext(),url)); 
     a.recycle(); 
    } 
} 

/макет/item_activity

<?xml version="1.0" encoding="utf-8"?> 
<LinearLayout 
    xmlns:android="http://schemas.android.com/apk/res/android" 
    xmlns:stylebutton= "http://schemas.android.com/apk/res-auto" 
    android:orientation="vertical" 
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent" 
    > 
<TextView 
    android:id="@+id/response" 
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:text=""/> 
<com.button.StyleButton 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    stylebutton:myText_1="My Text 1" 
    stylebutton:myText_2="My Text 2" 
    stylebutton:url="www.google.com" 
    /> 
<com.button.StyleButton 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    stylebutton:myText_1="Hello!" 
    stylebutton:myText_2="It's a Style Button:)" 
    stylebutton:url="www.yahoo.com" 
    /> 

/value/attr.xml

<?xml version="1.0" encoding="utf-8"?> 
<resources> 
    <declare-styleable name="style_Button"> 
     <attr name="myText_1" format="string" /> 
     <attr name="myText_2" format="string" /> 
     <attr name="url" format="string" /> 
    </declare-styleable> 
</resources> 
+0

это не способ инициализации деятельности – KDeogharkar

+0

вы говорите, что класс кнопки, но расширяется активность. Зачем? – KDeogharkar

+0

Очевидно, что вы получаете NPE, потому что вы видите (button_internet_access), нет в макете 'activity_item' его в' button_internet_access' change 'setContentView (R.layout.button_internet_access);' – Bharatesh

ответ

1

Создать свой custom button и использовать его в вашем проекте, как это можно использовать в глобальном масштабе.

public class ButtonInternetAccess extends UIButton implements OnClickListener { 
     String url; 
    Context mContext; 
    public ButtonInternetAccess(Context context, AttributeSet attrs,String url) { 
      super(context, attrs); 
     this.url = url; 
     this.mContext=mContext; 
      // TODO Auto-generated constructor stub 
     } 
     // initialize button and add click listener here. 

}

Вы можете добавить эту кнопку на XML также как

<yourpackagename.ButtonInternetAccess 
height="" 
width = "" 
other properties to include 
/> 

надеюсь, что это поможет.

+0

Ваша ссылка очень полезна. Я изменил учебник, чтобы заставить его работать. – RedGiant

+0

welcome @RedGiant – KDeogharkar

1

Изменение Кнопка класса для;

public class ButtonInternetAccess implements View.OnClickListener { 

    private String url; 
    private Context context; 

    public ButtonInternetAccess(Context context, String url) { 
     this.context = context; 
     this.url = url; 
    } 

    public void onClick(View v) { 

     System.out.println(url); 

     Intent callIntent = new Intent(Intent.ACTION_VIEW); 
     callIntent.setData(Uri.parse(url)); 

     try { 
      context.startActivity(callIntent); 
     } catch (ActivityNotFoundException activityException) { 
      Log.e("ONCLICK", "No Activity found", activityException); 
     } 
    } 
} 
+0

Но без расширения от Activity eclipse выдаст ошибку 'Метод startActivity (Intent) не определен для типа ButtonInternetAccess' – RedGiant

+0

См. Edit ... для добавления' Context' –

1

ваш setOnClickListener должен быть ниже способом:

btn.setOnClickListener(new View.OnClickListener() { 
      @Override 
      public void onClick(View view) { 
       try { 
        Intent callIntent = new Intent(Intent.ACTION_CALL); 
        callIntent.setData(Uri.parse("http://google.com")); 
        startActivity(callIntent); // No Error here 
        System.out.println(url); 
       } catch (ActivityNotFoundException activityException) { 
        Log.e("Calling a Phone Number", "Call failed", activityException); 
       } 
      } 
     }); 

Кажется, вам не нужно, чтобы отправить URL в другой класс, как вы можете сделать то же самое ItemActivity сама.

Отредактировано: В случае, если хочет geralize один класс, пожалуйста, обновите ButtonInternetAccess ниже образом:

public class ButtonInternetAccess implements OnClickListener { 
    String url; 
    Context mContext; 
    public ButtonInternetAccess(Context mContext,String url) { 
     this.url = url; 
     this.mContext=mContext; 
    } 

    public void onClick(View v) { 
     try { 
      Intent callIntent = new Intent(Intent.ACTION_CALL); 
      callIntent.setData(Uri.parse(url)); 
      mContext.startActivity(callIntent); 

      System.out.println(url); 
     } catch (ActivityNotFoundException activityException) { 
      Log.e("Calling a Phone Number", "Call failed", activityException); 
     } 
    } 

} 
+0

Но я искал способ не повторять кода при создании похожих кнопок, но только с разными URL-адресами. – RedGiant

+0

В этом случае пройдите объект Context и попробуйте startActivity в этом классе. Надеюсь, вы получите это. –

+0

См. Мой отредактированный ответ. –

Смежные вопросы