2015-06-19 5 views
0

Я - новичок в программировании из Германии. Я хотел создать программу, в которой вы можете рассчитать стоимость газа во время езды. Поэтому мне нужна «стартовая страница», «расчетная страница» и тост, который дает результат. У меня есть два вида деятельности. Я не уверен, почему моя программа не работает! Я надеюсь, что кто-то может мне помочь, потому что это будет мой экзамен, и для меня очень важно работать.Первая программа не работает, и я понятия не имею, почему

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

 package de.vivian.calci; 

    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.view.View.OnClickListener; 
    import android.widget.Button; 



    public class MainActivity extends ActionBarActivity 
    implements View.OnClickListener{ 


    private Button beginnen; 

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


    //Der Button für den Beginn der Berechnun 
    beginnen= (Button) findViewById(R.id.buttonbeginnen); 
     beginnen.setOnClickListener(this); 

    } 

    @Override 
    public void onClick(View v) { 
     // TODO Auto-generated method stub 

     Intent intent = new Intent(this, Berechnungsactivity.class); 
     startActivity(intent); 
     //Bei Drücken des Buttons soll die Berechnungsactivity über ein Intent aufgerufen werden 
    } 



    @Override 
    public boolean onCreateOptionsMenu(Menu menu) { 
     getMenuInflater().inflate(R.menu.main, 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); 
    } 
} 

activity_main.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 
xmlns:tools="http://schemas.android.com/tools" 
android:layout_width="match_parent" 
android:layout_height="match_parent" 
android:background="#CBD0D0" 
android:paddingBottom="@dimen/activity_vertical_margin" 
android:paddingLeft="@dimen/activity_horizontal_margin" 
android:paddingRight="@dimen/activity_horizontal_margin" 
android:paddingTop="@dimen/activity_vertical_margin" 
tools:context="de.vivian.calci.MainActivity" > 

<Button 
    android:id="@+id/buttonbeginnen" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:layout_alignParentBottom="true" 
    android:layout_centerHorizontal="true" 
    android:layout_marginBottom="100dp" 
    android:text="@string/beginnen" 
    android:textColor="#FA5882" /> 

<ImageView 
    android:id="@+id/imageView1" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:layout_alignParentBottom="true" 
    android:layout_centerHorizontal="true" 
    android:layout_marginBottom="350dp" 
    android:contentDescription="@string/description" 
    android:src="@drawable/auto" /> 

<TextView 
    android:id="@+id/textView1" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:layout_alignTop="@+id/imageView1" 
    android:layout_centerHorizontal="true" 
    android:layout_marginTop="138dp" 
    android:gravity="center_horizontal" 
    android:text="@string/begruessung" 
    android:textColor="#000000" 
    android:textSize="@dimen/textview_schriftgroesse" /> 

</RelativeLayout> 

Вторая деятельность по имени Berechnungsactivity (calculatingactivity)

package de.vivian.calci; 

import android.support.v7.app.ActionBarActivity; 

import android.os.Bundle; 
import android.view.Menu; 
import android.view.MenuItem; 
import android.view.View.OnClickListener; 
import android.widget.Button; 
import android.widget.TextView; 
import android.widget.Toast; 
import android.view.View; 

public class Berechnungsactivity extends ActionBarActivity{ 
private Button buttonspritkosten; 
private Button buttonabbrechen; 
//Die möglichen Buttons in dieser Activity 

private OnClickListener listi= new OnClickListener(){ 
    //Hier konnte ich mit dem OnClickListener nur über ein Objekt Arbeiten, da es mir sonst einen Fehler angezeigt hat 
    @Override 
    public void onClick(View v) { 
     if (v == buttonspritkosten) { 

      TextView textViewPersonenzahl; 
      TextView textViewStrecke; 
      TextView textViewVerbrauch; 
      TextView textViewPreis; 
      double berechnung; 
      String Personenzahl; 
      String Strecke; 
      String Verbrauch; 
      String Preis; 



      // Eingabefelder auslesen  
      textViewPersonenzahl = (TextView) findViewById(R.id.editpersonen); 
      textViewStrecke = (TextView) findViewById(R.id.editstrecke); 
      textViewVerbrauch = (TextView) findViewById(R.id.editverbrauch); 
      textViewPreis = (TextView) findViewById(R.id.editpreis); 

      Personenzahl=textViewPersonenzahl.getText().toString(); 
      Strecke=textViewStrecke.getText().toString(); 
      Verbrauch=textViewVerbrauch.getText().toString(); 
      Preis=textViewPreis.getText().toString(); 

      berechnung= (((((Double.parseDouble(Strecke))/100)*(Double.parseDouble(Verbrauch)))*(Double.parseDouble(Preis)))/(Double.parseDouble(Personenzahl))); 

      Toast einToast = Toast.makeText(v.getContext(), "Die Kosten pro Person betragen:" + String.valueOf(berechnung), Toast.LENGTH_SHORT); 
      einToast.show(); 
      ; 
      //Wenn also hier der Button berechnen gedrückt wird, sollen die Kosten berechnet werden und ein Toast mit dem ergebnis ausgegeben werden 
     } else if (v == buttonabbrechen) { 
      finish(); 

      // sollte der User Abbrechen drücken, soll die App beendet werden 
     } 
     // TODO Auto-generated method stub 

    } 
}; 


    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_berechnungsactivity); 
     buttonspritkosten= (Button) findViewById(R.id.buttonspritkosten); 
     buttonspritkosten.setOnClickListener(listi); 
     buttonabbrechen= (Button) findViewById(R.id.buttonabbrechen); 
     buttonabbrechen.setOnClickListener(listi); 

    } 






    @Override 
    public boolean onCreateOptionsMenu(Menu menu) { 
     // Inflate the menu; this adds items to the action bar if it is present. 
     getMenuInflater().inflate(R.menu.berechnungsactivity, 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); 
    } 


} 

Файл XML в berechnungsactivity второй активности (расчетная активность)

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 
xmlns:tools="http://schemas.android.com/tools" 
android:layout_width="match_parent" 
android:layout_height="match_parent" 
android:paddingBottom="@dimen/activity_vertical_margin" 
android:paddingLeft="@dimen/activity_horizontal_margin" 
android:paddingRight="@dimen/activity_horizontal_margin" 
android:paddingTop="@dimen/activity_vertical_margin" 
android:background="#CBD0D0" 
tools:context="de.vivian.calci.Berechnungsactivity" > 

<TextView 
    android:id="@+id/textView1" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:layout_alignParentTop="true" 
    android:layout_centerHorizontal="true" 
    android:text="Bitte fülle folgende Felder aus:" 
    android:textSize="@dimen/textview_schriftgroesse" 
    android:textColor="#FA5882" /> 

<TextView 
    android:id="@+id/textView2" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:layout_alignLeft="@+id/textView1" 
    android:layout_below="@+id/textView1" 
    android:layout_marginTop="50dp" 
    android:text="Personenzahl" 
    android:textAppearance="?android:attr/textAppearanceSmall" 
    android:textColor="@color/black" /> 

<TextView 
    android:id="@+id/textView3" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:layout_alignLeft="@+id/textView2" 
    android:layout_below="@+id/textView2" 
    android:layout_marginTop="50dp" 
    android:text="Strecke in km" 
    android:textAppearance="?android:attr/textAppearanceSmall" 
    android:textColor="@color/black"/> 

<TextView 
    android:id="@+id/textView4" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:layout_alignLeft="@+id/textView3" 
    android:layout_below="@+id/textView3" 
    android:layout_marginTop="50dp" 
    android:text="Verbrauch in l" 
    android:textAppearance="?android:attr/textAppearanceSmall" 
    android:textColor="@color/black" /> 

<TextView 
    android:id="@+id/textView5" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:layout_alignLeft="@+id/textView4" 
    android:layout_below="@+id/textView4" 
    android:layout_marginTop="50dp" 
    android:text="Literpreis in €" 
    android:textAppearance="?android:attr/textAppearanceSmall" 
    android:textColor="@color/black" /> <!-- Länge des Eingabefeldes --> 


<Button 
    android:id="@+id/buttonspritkosten" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:layout_alignParentBottom="true" 
    android:layout_centerHorizontal="true" 
    android:layout_marginBottom="110dp" 
    android:text="@string/buttonspritkosten" 
    android:textColor="#FA5882" /> 

<EditText 
    android:id="@+id/editpersonen" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:layout_alignBottom="@+id/textView2" 
    android:layout_alignRight="@+id/textView1" 
    android:ems="6" 
    android:inputType="numberDecimal" /> 

<EditText 
    android:id="@+id/editstrecke" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:layout_alignBottom="@+id/textView3" 
    android:layout_alignLeft="@+id/editpersonen" 
    android:ems="6" 
    android:inputType="numberDecimal" > 

    <requestFocus /> 
</EditText> 

<EditText 
    android:id="@+id/editverbrauch" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:layout_alignBottom="@+id/textView4" 
    android:layout_alignLeft="@+id/editstrecke" 
    android:ems="6" 
    android:inputType="numberDecimal" /> 

<EditText 
    android:id="@+id/editpreis" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:layout_alignBottom="@+id/textView5" 
    android:layout_alignLeft="@+id/editverbrauch" 
    android:ems="6" 
    android:inputType="numberDecimal" /> 

<Button 
    android:id="@+id/buttonabbrechen" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:layout_alignTop="@+id/buttonspritkosten" 
    android:layout_centerHorizontal="true" 
    android:layout_marginTop="50dp" 
    android:text="@string/buttonabbrechen" 
    android:textColor="#FA5882" /> 

</RelativeLayout> 

manifest.xml

<?xml version="1.0" encoding="utf-8"?> 
<manifest xmlns:android="http://schemas.android.com/apk/res/android" 
    package="de.vivian.calci" 
    android:versionCode="1" 
    android:versionName="1.0" > 

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

    <application 
     android:allowBackup="true" 
     android:icon="@drawable/ic_launcher" 
     android:label="@string/app_name" 
     android:theme="@android:style/Theme.Light"> > 
     <activity 
      android:name=".MainActivity" 
      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=".Berechnungsactivity" 
      android:label="@string/title_activity_berechnungsactivity" > 
     </activity> 
    </application> 

</manifest> 

Logcat говорит:

06-19 07:22:10.393: E/AndroidRuntime(775): FATAL EXCEPTION: main 
06-19 07:22:10.393: E/AndroidRuntime(775): java.lang.RuntimeException: Unable to start activity ComponentInfo{de.vivian.calci/de.vivian.calci.MainActivity}: java.lang.IllegalStateException: You need to use a Theme.AppCompat theme (or descendant) with this activity. 
06-19 07:22:10.393: E/AndroidRuntime(775): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2180) 
06-19 07:22:10.393: E/AndroidRuntime(775): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230) 
06-19 07:22:10.393: E/AndroidRuntime(775): at android.app.ActivityThread.access$600(ActivityThread.java:141) 
06-19 07:22:10.393: E/AndroidRuntime(775): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234) 
06-19 07:22:10.393: E/AndroidRuntime(775): at android.os.Handler.dispatchMessage(Handler.java:99) 
06-19 07:22:10.393: E/AndroidRuntime(775): at android.os.Looper.loop(Looper.java:137) 
06-19 07:22:10.393: E/AndroidRuntime(775): at android.app.ActivityThread.main(ActivityThread.java:5041) 
06-19 07:22:10.393: E/AndroidRuntime(775): at java.lang.reflect.Method.invokeNative(Native Method) 
06-19 07:22:10.393: E/AndroidRuntime(775): at java.lang.reflect.Method.invoke(Method.java:511) 
06-19 07:22:10.393: E/AndroidRuntime(775): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793) 
06-19 07:22:10.393: E/AndroidRuntime(775): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560) 
06-19 07:22:10.393: E/AndroidRuntime(775): at dalvik.system.NativeStart.main(Native Method) 
06-19 07:22:10.393: E/AndroidRuntime(775): Caused by: java.lang.IllegalStateException: You need to use a Theme.AppCompat theme (or descendant) with this activity. 
06-19 07:22:10.393: E/AndroidRuntime(775): at android.support.v7.app.AppCompatDelegateImplBase.onCreate(AppCompatDelegateImplBase.java:113) 
06-19 07:22:10.393: E/AndroidRuntime(775): at android.support.v7.app.AppCompatDelegateImplV7.onCreate(AppCompatDelegateImplV7.java:146) 
06-19 07:22:10.393: E/AndroidRuntime(775): at android.support.v7.app.AppCompatActivity.onCreate(AppCompatActivity.java:59) 
06-19 07:22:10.393: E/AndroidRuntime(775): at de.vivian.calci.MainActivity.onCreate(MainActivity.java:25) 
06-19 07:22:10.393: E/AndroidRuntime(775): at android.app.Activity.performCreate(Activity.java:5104) 
06-19 07:22:10.393: E/AndroidRuntime(775): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1080) 
06-19 07:22:10.393: E/AndroidRuntime(775): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2144) 
06-19 07:22:10.393: E/AndroidRuntime(775): ... 11 more 

styles.xml

<?xml version="1.0" encoding="UTF-8"?> 
<resources> 

    <!-- Base application theme, dependent on API level. This theme is replaced 
     by AppBaseTheme from res/values-vXX/styles.xml on newer devices. --> 
    <style name="AppBaseTheme" parent="Theme.AppCompat.Light"> 
     <!-- Theme customizations available in newer API levels can go in res/values-vXX/styles.xml, 
      while customizations related to backward-compatibility can go here. --> 
    </style> 

    <!-- Application theme. --> 
    <style name="AppTheme" parent="AppBaseTheme"> 
     <!-- All customizations that are NOT specific to a particular API-level 
      can go here. --> 



     <item name="android:windowNoTitle">true</item> <!-- Hides the Action Bar test --> 
     <item name="android:windowFullscreen">true</item> <!-- Hides the status bar test --> 




    </style> 

</resources> 
+1

Пожалуйста, определите, 'моя программа не работает!' –

+0

какая ошибка вы получаете? или что не происходит, как должно? –

+0

@vivian вывести вывод Logcat вместе с вопросом – Sushrita

ответ

1

Вы используете

android:theme="@android:style/Theme.Light" 

в качестве темы вашего приложения. Так как у ваших styles.xml есть

Вы должны использовать AppBaseTheme как свою тему в своем манифесте.

android:theme="@android:style/AppBaseTheme 
+0

Если это разрешило ваш запрос, отметьте этот ответ как правильный @OP –

+0

Спасибо, очень, мое приложение работает сейчас! Мне нужно исправить многие вещи, но я доволен, что это больше не останавливается! – Vivian

1

По ошибке вы получаете, вы должны изменить эту строку:

public class Berechnungsactivity extends ActionBarActivity{ 

с этим одним:

public class Berechnungsactivity extends Activity{ 

и всего остальное будет таким же, как это

0

В вашем manifest.xml файл для <application> изменений тега theme атрибута, как этого

android:theme="@style/AppTheme" 
1

причина, по которой у вас возникает эта проблема, заключается в том, что деятельность, которую вы пытаетесь применить к теме, расширяет ActionBarActivity wh ich требует применения темы AppCompat.

Измените наследование Java с ActionBarActivity на Activity и оставьте тему в манифесте как есть.

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