2015-07-18 3 views
0

Я создаю приложение, и мне нужно активировать действие, когда одна из кнопок нажата. Все они открывают ту же деятельность. Я проверил, все они имеют правильные имена файлов, и все они в манифесте, но когда я пытаюсь нажать кнопку, чтобы открыть эту активность, она говорит мне: «К сожалению ... остановился». Пожалуйста, помогите мне. Вот Manifest:Деятельность, не открывающая с использованием намерения

<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.apps.testp"> 

<uses-sdk 
    android:minSdkVersion="8" 
    android:targetSdkVersion="8" /> 

<application 
    android:allowBackup="true" 
    android:icon="@drawable/ic_launcher" 
    android:label="@string/app_name" 
    android:theme="@style/AppTheme" > 

    <activity 
     android:name="com.apps.testp.MainActivityWithButtons" 
     android:label="@string/app_name" > 
     <intent-filter> 
      <action android:name="android.intent.action.MAIN" /> 

      <category android:name="android.intent.category.LAUNCHER" /> 
     </intent-filter> 
    </activity> 

    <activity 
     android:name="com.apps.testp.LocationSelectFromAlertButtons" 
     android:label="@string/title_activity_location_select_from_alert_buttons" > 
    </activity> 

</application> 

Вот это MainActivityWithButtons.java:

package com.apps.testp; 

import android.support.v7.app.ActionBarActivity; 
import android.content.Intent; 
import android.os.Bundle; 
import android.view.Menu; 
import android.view.MenuItem; 
import android.view.View; 
import android.widget.Button; 


@SuppressWarnings("deprecation") 
public class MainActivityWithButtons extends ActionBarActivity { 
@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main_activity_with_buttons); 

    Button breakIn=(Button)findViewById(R.id.houseBreakIn); 
    Button robbery=(Button)findViewById(R.id.storeRobbery); 
    Button car=(Button)findViewById(R.id.carTheft); 
    Button assaulting=(Button)findViewById(R.id.assault); 
    Button shots=(Button)findViewById(R.id.shotsFired); 
    Button fight=(Button)findViewById(R.id.fighting); 
    Button address=(Button)findViewById(R.id.setOrChangeAddress); 


    address.setOnClickListener(new View.OnClickListener() { 

     @Override 
     public void onClick(View v) { 
      Intent i = new Intent(MainActivityWithButtons.this, LocationSelectFromAlertButtons.class); 
      startActivity(i); 

     } 
    }); 



    breakIn.setOnClickListener(new View.OnClickListener() { 

     @Override 
     public void onClick(View v) { 
      Intent i = new Intent(MainActivityWithButtons.this, LocationSelectFromAlertButtons.class); 
      startActivity(i); 
     } 
    }); 



    robbery.setOnClickListener(new View.OnClickListener() { 

      @Override 
      public void onClick(View v) { 
       Intent i = new Intent(MainActivityWithButtons.this, LocationSelectFromAlertButtons.class); 
       startActivity(i); 
       } 
      }); 



    car.setOnClickListener(new View.OnClickListener() { 

     @Override 
     public void onClick(View v) { 
      Intent i = new Intent(MainActivityWithButtons.this, LocationSelectFromAlertButtons.class); 
      startActivity(i); 
     } 
    }); 


    assaulting.setOnClickListener(new View.OnClickListener() { 

     @Override 
     public void onClick(View v) { 
      Intent i = new Intent(MainActivityWithButtons.this, LocationSelectFromAlertButtons.class); 
      startActivity(i); 
     } 
    }); 


    shots.setOnClickListener(new View.OnClickListener() { 

     @Override 
     public void onClick(View v) { 
      Intent i = new Intent(MainActivityWithButtons.this, LocationSelectFromAlertButtons.class); 
      startActivity(i); 
     } 
    }); 


    fight.setOnClickListener(new View.OnClickListener() { 

     @Override 
     public void onClick(View v) { 
      Intent i = new Intent(MainActivityWithButtons.this, LocationSelectFromAlertButtons.class); 
      startActivity(i); 
     } 
    }); 



    //Next Listener Goes Here 
} 


@Override 
public boolean onCreateOptionsMenu(Menu menu) { 
    // Inflate the menu; this adds items to the action bar if it is present. 
    getMenuInflater().inflate(R.menu.main_activity_with_buttons, menu); 
    return true; 
} 

@Override 
public boolean onOptionsItemSelected(MenuItem item) { 
    // Handle action bar item clicks here. The action bar will 
    // automatically handle clicks on the Home/Up button, so long 
    // as you specify a parent activity in AndroidManifest.xml. 
    int id = item.getItemId(); 
    if (id == R.id.action_settings) { 
     return true; 
    } 
    return super.onOptionsItemSelected(item); 
} 

}

Вот Активности я пытаюсь открыть:

package com.apps.testp; 

    import android.support.v7.app.ActionBarActivity; 
    import android.os.Bundle; 
    import android.view.Menu; 
    import android.view.MenuItem; 
    import android.view.View; 
    import android.widget.Button; 
    import android.widget.EditText; 
    import android.widget.TextView; 

    @SuppressWarnings("deprecation") 
    public class LocationSelectFromAlertButtons extends ActionBarActivity { 

DBAdapter myDB; 

Button save=(Button)findViewById(R.id.saveBtn); 
TextView currentAddress=(TextView)findViewById(R.id.CurrAddress); 
EditText addressNew=(EditText)findViewById(R.id.tbNewAddress); 

@Override 
protected void onCreate(Bundle savedInstanceState) { 

    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_location_select_from_alert_buttons); 

    openDB(); 



} 
private void openDB() { 
    myDB = new DBAdapter(this); 
    myDB.open(); 
} 

@Override 
protected void onDestroy() { 
    super.onDestroy(); 
    closeDB(); 
} 

private void closeDB() { 

    myDB.close(); 
} 
public void saveButtonClicked(){ 
    long newId =myDB.insertRow(LocationSelectFromAlertButtons.this.addressNew.getText().toString()); 


} 








@Override 
public boolean onCreateOptionsMenu(Menu menu) { 
    // Inflate the menu; this adds items to the action bar if it is present. 
    getMenuInflater().inflate(R.menu.location_select_from_alert_buttons, 
      menu); 
    return true; 
} 

@Override 
public boolean onOptionsItemSelected(MenuItem item) { 
    // Handle action bar item clicks here. The action bar will 
    // automatically handle clicks on the Home/Up button, so long 
    // as you specify a parent activity in AndroidManifest.xml. 
    int id = item.getItemId(); 
    if (id == R.id.action_settings) { 
     return true; 
    } 
    return super.onOptionsItemSelected(item); 
} 

}

вся помощь будет принята с благодарностью! Спасибо ребята

Edit:

LogCat:

07-18 20:01:55.572 21821-21821/com.apps.testp D/dalvikvm? Late-enabling CheckJNI 
07-18 20:01:55.572 21821-21821/com.apps.testp D/dalvikvm? Try to disable coredump for pid 21821 
07-18 20:01:55.903 21821-21821/com.apps.testp I/dalvikvm? Could not find method android.content.res.TypedArray.getChangingConfigurations, referenced from method android.support.v7.internal.widget.TintTypedArray.getChangingConfigurations 
07-18 20:01:55.903 21821-21821/com.apps.testp W/dalvikvm? VFY: unable to resolve virtual method 411: Landroid/content/res/TypedArray;.getChangingConfigurations()I 
07-18 20:01:55.903 21821-21821/com.apps.testp D/dalvikvm? VFY: replacing opcode 0x6e at 0x0002 
07-18 20:01:55.903 21821-21821/com.apps.testp I/dalvikvm? Could not find method android.content.res.TypedArray.getType, referenced from method android.support.v7.internal.widget.TintTypedArray.getType 
07-18 20:01:55.903 21821-21821/com.apps.testp W/dalvikvm? VFY: unable to resolve virtual method 433: Landroid/content/res/TypedArray;.getType (I)I 
07-18 20:01:55.903 21821-21821/com.apps.testp D/dalvikvm? VFY: replacing opcode 0x6e at 0x0002 
07-18 20:01:56.112 21821-21821/com.apps.testp D/libEGL? loaded /vendor/lib/egl/libEGL_POWERVR_SGX544_115.so 
07-18 20:01:56.143 21821-21821/com.apps.testp D/libEGL? loaded /vendor/lib/egl/libGLESv1_CM_POWERVR_SGX544_115.so 
07-18 20:01:56.153 21821-21821/com.apps.testp D/libEGL? loaded /vendor/lib/egl/libGLESv2_POWERVR_SGX544_115.so 
07-18 20:01:56.233 21821-21821/com.apps.testp D/OpenGLRenderer? Enabling debug mode 0 
07-18 20:01:58.432 21821-21821/com.apps.testp D/AndroidRuntime? Shutting down VM 
07-18 20:01:58.432 21821-21821/com.apps.testp W/dalvikvm? threadid=1: thread exiting with uncaught exception (group=0x41abae10) 
07-18 20:01:58.432 21821-21821/com.apps.testp E/AndroidRuntime? FATAL EXCEPTION: main 
      java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.apps.testp/com.apps.testp.LocationSelectFromAlertButtons}: java.lang.NullPointerException 
      at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2171) 
      at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2295) 
      at android.app.ActivityThread.access$700(ActivityThread.java:150) 
      at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1280) 
      at android.os.Handler.dispatchMessage(Handler.java:99) 
      at android.os.Looper.loop(Looper.java:137) 
      at android.app.ActivityThread.main(ActivityThread.java:5279) 
      at java.lang.reflect.Method.invokeNative(Native Method) 
      at java.lang.reflect.Method.invoke(Method.java:511) 
      at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1102) 
      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:869) 
      at dalvik.system.NativeStart.main(Native Method) 
      Caused by: java.lang.NullPointerException 
      at android.app.Activity.findViewById(Activity.java:1886) 
      at com.apps.testp.LocationSelectFromAlertButtons.<init>(LocationSelectFromAlertButtons.java:17) 
      at java.lang.Class.newInstanceImpl(Native Method) 
      at java.lang.Class.newInstance(Class.java:1319) 
      at android.app.Instrumentation.newActivity(Instrumentation.java:1071) 
      at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2162) 
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2295) 
            at android.app.ActivityThread.access$700(ActivityThread.java:150) 
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1280) 
            at android.os.Handler.dispatchMessage(Handler.java:99) 
            at android.os.Looper.loop(Looper.java:137) 
            at android.app.ActivityThread.main(ActivityThread.java:5279) 
            at java.lang.reflect.Method.invokeNative(Native Method) 
            at java.lang.reflect.Method.invoke(Method.java:511) 
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1102) 
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:869) 
            at dalvik.system.NativeStart.main(Native Method) 
+0

пожалуйста, напишите следы журнала в журнале кошки ! – Mahfa

+0

Mahfa прав, мы должны знать, что вызывает ошибку, пожалуйста, также разместите следующие строки. Тем не менее save, currentAddress, addressNew будет null, если вы вызове findViewById() в этот момент. findViewByID должен вызываться после setContentView(). – FlanschiFox

+0

Я только что закрыл все, дайте мне несколько секунд, я отредактирую их в –

ответ

0

Проблема здесь:

Caused by: java.lang.NullPointerException 
      at android.app.Activity.findViewById(Activity.java:1886) 

, которое вызывается с помощью вызова findViewById(), прежде чем иметь действительный контекст в вашей деятельности.

Когда вы звоните findViewById(), на самом деле это не так для this.findViewById(), и в вашем случае this имеет значение null, отсюда исключение NullPointerException.

Обратите внимание, что для того, чтобы найти кнопки, правильное расположение должно быть накачаны в окно, так что вам нужно поместить эти вызовы после setContentView(), а также:

Button save; 
TextView currentAddress; 
EditText addressNew; 

@Override 
protected void onCreate(Bundle savedInstanceState) { 

    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_location_select_from_alert_buttons); 

    save = (Button)findViewById(R.id.saveBtn); 
    currentAddress = (TextView)findViewById(R.id.CurrAddress); 
    addressNew = (EditText)findViewById(R.id.tbNewAddress); 

    openDB(); 

} 
+0

Спасибо! Я обязательно попробую и дам вам знать результат! –

+0

Я только что понял, что это не кнопка, которую я использую, я использую: Button breakIn = (Button) findViewById (R.id.houseBreakIn); Кнопка robbery = (кнопка) findViewById (R.id.storeRobbery); Кнопка автомобиля = (кнопка) findViewById (R.id.carTheft); Кнопка нападения = (кнопка) findViewById (R.id.assault); Кнопка выстрелов = (кнопка) findViewById (R.id.shotsFired); Button fight = (кнопка) findViewById (R.id.fighting); Кнопка адрес = (кнопка) findViewById (R.id.setOrChangeAddress); –

+0

Извините, я не знаю, как прокомментировать код –

0

Расположить это:

Button save=(Button)findViewById(R.id.saveBtn); 
TextView currentAddress=(TextView)findViewById(R.id.CurrAddress); 
EditText addressNew=(EditText)findViewById(R.id.tbNewAddress); 

После вашего setContentView.

0

Я думаю, что проблема может быть в вашем манифесте. Вы не установили

android:parentActivityName="com.apps.testp.MainActivityWithButtons" 

Система использует это, чтобы включить навигацию поведения (которые пользователи ожидают), и я не знаю, если вы можете перемещаться, как вы собираетесь без включения этого в манифесте.

Для поддержки старых устройств, также включают в себя:

<meta-data android:name="android.support.PARENT_ACTIVITY" 
android:value="com.apps.testp.MainActivityWithButtons" /> 

в теле вашей декларации деятельности.

Для получения дополнительной информации см. http://developer.android.com/training/basics/firstapp/starting-activity.html.

Я ранее следовал руководству на developer.android.com для реализации такой функции без проблем.

+0

Видите ли, я согласен с вами, я знаю, что мой код довольно точный, дело в том, что они не разговаривают друг с другом, поэтому Я предполагаю, что проблема в манифесте. Где я должен добавить: android: parentActivityName = "com.apps.testp.MainActivityWithButtons" –

+0

Извините, должен был правильно прочитать, вы сказали, что он должен быть в объявлении активности, но какой? Основной или тот, на который он должен перейти? –

+0

Он должен быть частью следующего тега: Как упоминалось ранее, метаданные поступают в тело, а не открывающий тег. – user3704140

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