2017-01-07 4 views
0

Я четырнадцать и новичок в java и студии android, и я делаю простую программу, которая собирает PIN-код для подзарядки пользователя в качестве входных данных, а затем набирает его на телефон в качестве USSD , но при каждом нажатии любой кнопки на MainActivity.xml приложение выходит из строя. Эти кодыAndroid-приложение падает при нажатии кнопки в Android-студии

//MainActivity.java 


package devchuks.com.rechargeyourcard; 

import android.content.Intent; 
import android.support.v7.app.AppCompatActivity; 
import android.os.Bundle; 
import android.view.View; 

public class MainActivity extends AppCompatActivity { 

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

     public void openEtisalat (View v) { 
      Intent intent = new Intent(this, Etisalat.class); 
      startActivity(intent); 
     } 

     public void openMTN (View v) { 
      Intent intent2 = new Intent(this, MTNactivity.class); 
      startActivity(intent2); 
     } 
     public void openAirtel (View v) { 
      Intent intent3 = new Intent(this, AirtelActivity.class); 
      startActivity(intent3); 
     } 
     public void openGlo (View v) { 
      Intent intent4 = new Intent(this, GloActivity.class); 
      startActivity(intent4); 
     } 
    } 

} 

Это XML из mainactivity

//activity_main.xml 
<?xml version="1.0" encoding="utf-8"?> 
<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" 
    tools:context="devchuks.com.rechargeyourcard.MainActivity"> 


    <LinearLayout 
     android:orientation="vertical" 
     android:layout_width="match_parent" 
     android:layout_height="match_parent" 
     android:layout_alignParentBottom="true" 
     android:layout_alignParentRight="true" 
     android:layout_alignParentEnd="true" 
     android:id="@+id/linearLayout"> 

     <Button 
      android:layout_width="fill_parent" 
      android:layout_height="wrap_content" 
      android:text="@string/Etisalat" 
      android:id="@+id/button" 
      android:onClick="openEtisalat"/> 

     <Button 
      android:layout_width="fill_parent" 
      android:layout_height="wrap_content" 
      android:text="@string/MTN" 
      android:id="@+id/button2" 
      android:onClick="openMTN"/> 

     <Button 
      android:layout_width="fill_parent" 
      android:layout_height="wrap_content" 
      android:text="@string/Airtel" 
      android:id="@+id/button3" 
      android:onClick="openAirtel"/> 

     <Button 
      android:layout_width="fill_parent" 
      android:layout_height="wrap_content" 
      android:text="Glo" 
      android:id="@+id/button4" 
      android:onClick="openGlo"/> 

     <TextView 
      android:layout_width="218dp" 
      android:layout_height="wrap_content" 
      android:text="@string/copyright" 
      android:id="@+id/textView" 
      android:layout_marginRight="255dp" 
      android:layout_marginEnd="255dp" /> 
    </LinearLayout> 

</RelativeLayout> 

это пример одного из мероприятий, которые будут открыты

//Etisalat.java 
package devchuks.com.rechargeyourcard; 

import android.net.Uri; 
import android.os.Bundle; 
import android.app.Activity; 
import android.content.Context; 
import android.content.Intent; 
import android.telephony.PhoneStateListener; 
import android.telephony.TelephonyManager; 
import android.view.View; 
import android.widget.Button; 
import android.widget.EditText; 
import android.widget.Toast; 
import android.view.View.OnClickListener; 

import devchuks.com.rechargeyourcard.R; 

public class Etisalat extends Activity { 

    private Button callBtn; 
    private Button dialBtn; 
    private EditText number; 

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

     number = (EditText) findViewById(R.id.phoneNumber); 
     callBtn = (Button) findViewById(R.id.call); 

     // add PhoneStateListener for monitoring 
     MyPhoneListener phoneListener = new MyPhoneListener(); 
     TelephonyManager telephonyManager = 
       (TelephonyManager) this.getSystemService(Context.TELEPHONY_SERVICE); 
     // receive notifications of telephony state changes 
     telephonyManager.listen(phoneListener,PhoneStateListener.LISTEN_CALL_STATE); 

     callBtn.setOnClickListener(new OnClickListener() { 

      @Override 
      public void onClick(View v) { 
       try { 
        // set the data 
        String uri = "tel:" + "*555*" + number.getText().toString() + "#"; 
        Intent callIntent = new Intent(Intent.ACTION_CALL, Uri.parse(uri)); 

        startActivity(callIntent); 
       } catch (Exception e) { 
        Toast.makeText(getApplicationContext(), "Your call has failed...", 
          Toast.LENGTH_LONG).show(); 
        e.printStackTrace(); 
       } 
      } 
     }); 

     dialBtn.setOnClickListener(new OnClickListener() { 

      @Override 
      public void onClick(View v) { 
       try { 
        String ussd = number.getText().toString(); 
        String uri = "tel:" + "*555*" + ussd + Uri.encode("#"); 
        Intent dialIntent = new Intent(Intent.ACTION_DIAL, Uri.parse(uri)); 

        startActivity(dialIntent); 
       } catch (Exception e) { 
        Toast.makeText(getApplicationContext(), "Your call has failed...", 
          Toast.LENGTH_LONG).show(); 
        e.printStackTrace(); 
       } 
      } 
     }); 
    } 

    private class MyPhoneListener extends PhoneStateListener { 

     private boolean onCall = false; 

     @Override 
     public void onCallStateChanged(int state, String incomingNumber) { 

      switch (state) { 
       case TelephonyManager.CALL_STATE_RINGING: 
        // phone ringing... 
        Toast.makeText(Etisalat.this, incomingNumber + " calls you", 
          Toast.LENGTH_LONG).show(); 
        break; 

       case TelephonyManager.CALL_STATE_OFFHOOK: 
        // one call exists that is dialing, active, or on hold 
        Toast.makeText(Etisalat.this, "on call...", 
          Toast.LENGTH_LONG).show(); 
        //because user answers the incoming call 
        onCall = true; 
        break; 

       case TelephonyManager.CALL_STATE_IDLE: 
        // in initialization of the class and at the end of phone call 

        // detect flag from CALL_STATE_OFFHOOK 
        if (onCall == true) { 
         Toast.makeText(Etisalat.this, "restart app after call", 
           Toast.LENGTH_LONG).show(); 

         // restart our application 
         Intent restart = getBaseContext().getPackageManager(). 
           getLaunchIntentForPackage(getBaseContext().getPackageName()); 
         restart.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); 
         startActivity(restart); 

         onCall = false; 
        } 
        break; 
       default: 
        break; 
      } 

     } 
    } 

} 

и это XML

//EtisalatActivity.xml 
<?xml version="1.0" encoding="utf-8"?> 
<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" 
    tools:context="devchuks.com.rechargeyourcard.Etisalat"> 
    <EditText 
     android:id="@+id/phoneNumber" 
     android:layout_width="fill_parent" 
     android:layout_height="wrap_content" 
     android:layout_alignParentLeft="true" 
     android:layout_alignParentTop="true" 
     android:hint="@string/pin" 
     android:ems="10" 
     android:inputType="phone" /> 

    <Button 
     android:id="@+id/call" 
     android:layout_width="fill_parent" 
     android:layout_height="wrap_content" 
     android:layout_below="@+id/phoneNumber" 
     android:layout_marginTop="20dp" 
     android:text="@string/Recharge" /> 

</RelativeLayout> 

Пожалуйста, помогите решить эту

Вот мой Manifest.xml

<?xml version="1.0" encoding="utf-8"?> 
<manifest xmlns:android="http://schemas.android.com/apk/res/android" 
    package="devchuks.com.rechargeyourcard"> 
    <uses-permission android:name="android.permission.CALL_PHONE" /> 
    <uses-permission android:name="android.permission.READ_PHONE_STATE" /> 
    <application 
     android:allowBackup="true" 
     android:icon="@mipmap/ic_launcher" 
     android:label="@string/app_name" 
     android:supportsRtl="true" 
     android:theme="@style/AppTheme"> 
     <activity android:name=".MainActivity"> 
      <intent-filter> 
       <action android:name="android.intent.action.MAIN" /> 

       <category android:name="android.intent.category.LAUNCHER" /> 
      </intent-filter> 
     </activity> 
     <activity android:name=".Etisalat" /> 
     <activity android:name=".MTNactivity" /> 
     <activity android:name=".AirtelActivity" /> 
     <activity android:name=".GloActivity" /> 
    </application> 

</manifest> 
+2

Использование неправильного расположения для деятельности Etisalat. изменить 'setContentView (R.layout.activity_main);' to' setContentView (R.layout.EtisalatActivity); ' –

+0

@ ρяσѕρєяK Вторично. Отправьте его как ответ. –

+0

Android Studio также показывает ошибку, где отображается «R.id.something» или «R.layout.something» –

ответ

0

Первый - Причиной аварии, вы сможете увидеть его на вкладке Log. Второй - (вы не разделили манифест) Вероятная причина сбоев в том, что вы не объявляли активности в манифесте.

+0

жаль, что я не вижу журналы, как я создаю apk и использую Bluestacks в качестве эмулятора. AVD по умолчанию слишком медленный на моем компьютере. также все действия объявлены в манифесте –

0

Прежде всего, вы должны изменить свой файл макета для Etisalat Activity, который является «R.layout.activity_main», чтобы изменить его «R.layout.EtisalatActivity», и посмотреть, что произойдет, и вы все равно получите крах, чем поделитесь своим LogCat.

+0

Он по-прежнему падает. Я не знаю, как генерировать логарифмы –

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