-3

Androidプロジェクトに取り組んでいますが、連絡先の追加などのいくつかのボタンや、新しいアクティビティを開始したいときに正常に動作していますが、SMSを送信しようとすると強制終了します。主なコードは次のとおりです

package com.example.sms;
import java.util.Locale;
import java.util.StringTokenizer;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.provider.ContactsContract.CommonDataKinds.Phone;
import android.app.Activity;
 import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent; 
import android.content.IntentFilter;
import android.database.Cursor;
import android.speech.tts.TextToSpeech;
import android.speech.tts.TextToSpeech.OnInitListener;
import android.speech.tts.TextToSpeech.OnUtteranceCompletedListener;
import android.telephony.SmsManager;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity implements TextToSpeech.OnInitListener,      OnUtteranceCompletedListener, OnClickListener{
    Button btnSendSMS,record_sms,finish;
 EditText txtPhoneNo;
 EditText txtMessage;
 Button addcontact;
 EditText phonePhoneno;
 TextView enter_contact_no;
 private TextToSpeech tts;
 private static final int CONTACT_PICKER_RESULT = 1001;
 private static final String DEBUG_TAG = "";
 String phoneNo="";
 String phonenofromcontact="";
 String finallistofnumberstosendmsg ="";



 /** Called when the activity is first created. */
 @Override
 public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    enter_contact_no=(TextView) findViewById(R.id.txtPhoneNo1);
    btnSendSMS = (Button) findViewById(R.id.btnSendSMS);
  //  txtPhoneNo = (EditText) findViewById(R.id.txtPhoneNo);
    txtMessage = (EditText) findViewById(R.id.txtMessage);
    record_sms=(Button) findViewById(R.id.button1);
    finish=(Button) findViewById(R.id.complete);
    tts = new TextToSpeech(this, this);
    record_sms.setOnClickListener(this);
    finish.setOnClickListener(this);
//    String str;
   // Log.e("test4", "ram.......");

    //Log.e("test3", "mmmmmmmmmmm...");
    //tts.speak("enter contact number", TextToSpeech.QUEUE_FLUSH, null);
     //  str=getIntent().getExtras().getString("username");     
    //Log.e("message",str);
   /* record_sms.setOnClickListener(new View.OnClickListener() {


        public void onClick(View v) {
            // TODO Auto-generated method stub
            Intent intent=new Intent(MainActivity.this,     MainActivity1.class);
            startActivity(intent);  
                }
    });*/
    //Log.e("test2", "lllllllll...");
    addcontact =(Button) findViewById(R.id.addphonenofromcontact);


  /* Intent intent=new Intent(this,AndroidTextToSpeechActivity.class );
   startActivity(intent);*/
    speakOut("enter contact number");

    addcontact.setOnClickListener(new View.OnClickListener()
    {
        public void onClick(View V)
        {
            Intent ContactPickerIntent = new Intent(Intent.ACTION_PICK,ContactsContract.Contacts.CONTENT_URI);
            ContactPickerIntent.setType(ContactsContract.CommonDataKinds.Phone.CONTENT_TYPE);
            startActivityForResult(ContactPickerIntent, CONTACT_PICKER_RESULT);             
        }
    }
    );

    btnSendSMS.setOnClickListener(new View.OnClickListener() 
    {

        public void onClick(View v) 
        {  
        //  txtMessage.setText(getIntent().getExtras().getString("username"));
            String message = txtMessage.getText().toString();
            phoneNo = txtPhoneNo.getText().toString();
            String phoneNo1=  phonePhoneno.getText().toString(); 

            // Sending message to both the written and added contact...

            finallistofnumberstosendmsg +=phoneNo1 + phoneNo;
            String phoneFinal= phoneNo + finallistofnumberstosendmsg;

            //StringTokenizer st=new StringTokenizer(finallistofnumberstosendmsg,",");

            StringTokenizer st=new StringTokenizer(phoneFinal,",");
            while (st.hasMoreElements())
            {
                String tempMobileNumber = (String)st.nextElement();
                if(tempMobileNumber.length()>0 && message.trim().length()>0) {
                    sendSMS(tempMobileNumber, message);
                }
                else 
                {
                    Toast.makeText(getBaseContext(), 
                            "Please enter both phone number and message.", 
                            Toast.LENGTH_SHORT).show();
                }
            }
           }
    });  
    }

protected void onActivityResult(int requestCode, int resultCode, Intent data) {  
     if (resultCode == RESULT_OK)
     {  
         switch (requestCode) 
         {  
         case CONTACT_PICKER_RESULT:
             Cursor cursor=null;
             try
             {   
                 Uri result = data.getData();
                 Log.v(DEBUG_TAG, "Got a contact result: " + result.toString());

                 // get the contact id from the Uri     
                 String id = result.getLastPathSegment();

                 // query for everything contact number  
                 cursor = getContentResolver().query(  
                      Phone.CONTENT_URI, null,  
                      Phone._ID + "=?",  
                      new String[]{id}, null); 

                 cursor.moveToFirst();
                 int phoneIdx = cursor.getColumnIndex(Phone.NUMBER);  
                 if (cursor.moveToFirst())
                 {   
                     phonenofromcontact = cursor.getString(phoneIdx);
                     finallistofnumberstosendmsg +=","+phonenofromcontact;
                     Log.v(DEBUG_TAG, "Got phone no : " + phonenofromcontact);  
                 }
                 else 
                 {                                
                     Log.w(DEBUG_TAG, "No results"); 
                 }
             }
             catch(Exception e)
             {
                 Log.e(DEBUG_TAG, "Failed to get contact number", e);
             }
             finally
             {
                 if (cursor != null)
                 {  
                     cursor.close();
                 }
             }
             phonePhoneno= (EditText)findViewById(R.id.phonenofromcontact);
             phonePhoneno.setText(finallistofnumberstosendmsg);
             //phonePhoneno.setText(phonenofromcontact);
             if(phonenofromcontact.length()==0)
             {
                 Toast.makeText(this, "No contact number found for this contact",
                         Toast.LENGTH_LONG).show(); 
             }
            break;  
         }  
     } 
     else
     {  
         Log.w(DEBUG_TAG, "Warning: activity result not ok");
     }  
 } 

private void sendSMS(String phoneNumber, String message)
{
    String SENT = "SMS_SENT";
    String DELIVERED = "SMS_DELIVERED";

    PendingIntent sentPI = PendingIntent.getBroadcast(this, 0,
        new Intent(SENT), 0);

    PendingIntent deliveredPI = PendingIntent.getBroadcast(this, 0,
        new Intent(DELIVERED), 0);

  //---when the SMS has been sent---
    registerReceiver(new BroadcastReceiver(){
        public void onReceive(Context arg0, Intent arg1) {
            switch (getResultCode())
            {
                case Activity.RESULT_OK:
                    Toast.makeText(getBaseContext(), "SMS sent", 
                            Toast.LENGTH_SHORT).show();
                    break;
                case SmsManager.RESULT_ERROR_GENERIC_FAILURE:
                    Toast.makeText(getBaseContext(), "Generic failure", 
                            Toast.LENGTH_SHORT).show();
                    break;
                case SmsManager.RESULT_ERROR_NO_SERVICE:
                    Toast.makeText(getBaseContext(), "No service", 
                            Toast.LENGTH_SHORT).show();
                    break;
                case SmsManager.RESULT_ERROR_NULL_PDU:
                    Toast.makeText(getBaseContext(), "Null PDU", 
                            Toast.LENGTH_SHORT).show();
                    break;
                case SmsManager.RESULT_ERROR_RADIO_OFF:
                    Toast.makeText(getBaseContext(), "Radio off", 
                            Toast.LENGTH_SHORT).show();
                    break;
            }
        }
    },new IntentFilter(SENT));

    //---when the SMS has been delivered---
    registerReceiver(new BroadcastReceiver(){
        @Override
        public void onReceive(Context arg0, Intent arg1) {
            switch (getResultCode())
            {
                case Activity.RESULT_OK:
                    Toast.makeText(getBaseContext(), "SMS delivered", 
                            Toast.LENGTH_SHORT).show();
                    break;
                case Activity.RESULT_CANCELED:
                    Toast.makeText(getBaseContext(), "SMS not delivered", 
                            Toast.LENGTH_SHORT).show();
                    break;                        
            }
        }
    }, new IntentFilter(DELIVERED));        

    SmsManager sms = SmsManager.getDefault();
    sms.sendTextMessage(phoneNumber, null, message, sentPI, deliveredPI);       
}

@SuppressWarnings("deprecation")
public void onInit(int status) {
    // TODO Auto-generated method stub
    if (status == TextToSpeech.SUCCESS) {
                    int result = tts.setLanguage(Locale.US);
         // tts.setPitch(5); // set pitch level

        // tts.setSpeechRate(2); // set speech speed rate

        if (result == TextToSpeech.LANG_MISSING_DATA
                || result == TextToSpeech.LANG_NOT_SUPPORTED) {
            Log.e("TTS", "Language is not supported");
        } else {
            //btnSpeak.setEnabled(true);
            String text=enter_contact_no.getText().toString();
            //tts.speak("enter contact number", TextToSpeech.QUEUE_FLUSH, null);
            speakOut(text);
            Log.e("test", "hhhhhhhhhhhhhhhhh");
        /*  @Deprecated int listenerResult = tts.setOnUtteranceCompletedListener(new OnUtteranceCompletedListener()
            {
                public void onUtteranceCompleted(String utteranceId)
                {
                   // callWithResult.onDone(utteranceId);
                    Log.e("TAG2", "failed to add utterance completed listener");
                }
            });
            if (listenerResult != TextToSpeech.SUCCESS)
            {
                Log.e("TAG", "failed to add utterance completed listener");
            } */
            Intent ContactPickerIntent = new Intent(Intent.ACTION_PICK,ContactsContract.Contacts.CONTENT_URI);
            ContactPickerIntent.setType(ContactsContract.CommonDataKinds.Phone.CONTENT_TYPE);
            startActivityForResult(ContactPickerIntent, CONTACT_PICKER_RESULT);             

        }

    } else {
        Log.e("TTS", "Initilization Failed");
    }


}
private void speakOut(String text) {

    //String text = txtText.getText().toString();

    tts.speak(text, TextToSpeech.QUEUE_FLUSH, null);

}

public void onUtteranceCompleted(String utteranceId) {
    // TODO Auto-generated method stub

}

public void onClick(View v) {
    // TODO Auto-generated method stub
    if(v.getId()==R.id.button1)
    {
        Intent intent=new Intent(MainActivity.this, MainActivity1.class);
        String str=phonePhoneno.getText().toString();
        intent.putExtra("phoneno", str);
        startActivity(intent);  

    }
 if(v.getId()==R.id.complete)
    {
        Intent intent=getIntent();
        String str,str1;
        str=intent.getExtras().getString("phoneno");
        phonePhoneno.setText(str);
        //str1=intent.getStringExtra("username");
        //txtMessage.setText("str1");
    }   

}

/*public void onInit(int status) {
    // TODO Auto-generated method stub

}*/

}

上記のコードでは、sendms と終了ボタンが強制終了を引き起こしています。アプリを正しく実行するには、どのような変更を加える必要がありますか。

2 番目のアクティビティのコード

 package com.example.sms;
 import java.util.ArrayList;
 import android.app.Activity;
 import android.content.ActivityNotFoundException;
 import android.content.Intent;
 import android.os.Bundle;
 import android.speech.RecognizerIntent;
 import android.support.v4.view.ViewGroupCompat;
 import android.view.Menu;
 import android.view.View;
 import android.view.View.OnClickListener;
 import android.widget.Button;
 import android.widget.EditText;
 import android.widget.ImageButton;
 import android.widget.TextView;
 import android.widget.Toast;

 public class MainActivity1 extends Activity implements OnClickListener {
protected static final int RESULT_SPEECH = 1;
private ImageButton btnSpeak;
private TextView txtText;
//EditText msg;
Button b;
String phoneno;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main1);
    txtText = (TextView) findViewById(R.id.txtText);
    btnSpeak = (ImageButton) findViewById(R.id.btnSpeak);
  //  msg=(EditText) findViewById(R.id.txtMessage);
    //b=(Button) findViewById(R.id.main_act);
    b=(Button) findViewById(R.id.main_act);
    btnSpeak.setOnClickListener(this);
    b.setOnClickListener(this);
    Intent intent =getIntent();
    phoneno=intent.getExtras().getString("phoneno");


}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.activity_main, menu);
    return true;
}
public void onClick(View v) {
    // TODO Auto-generated method stub
    if(v.getId()==R.id.btnSpeak)
    {
        Intent intent = new Intent(
                RecognizerIntent.ACTION_RECOGNIZE_SPEECH);

        intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, "en-US");

        try {
            startActivityForResult(intent, RESULT_SPEECH);
            txtText.setText("");
        } catch (ActivityNotFoundException a) {
            Toast t = Toast.makeText(getApplicationContext(),
                    "Ops! Your device doesn't support Speech to Text",
                    Toast.LENGTH_SHORT);
            t.show();
        }

    }
if(v.getId()==R.id.main_act)
    {
       String str=txtText.getText().toString();
       Intent intent=new Intent(getApplicationContext(), MainActivity.class);
       intent.putExtra("username",str);
       intent.putExtra("phoneno", phoneno);
       startActivity(intent);
    } 
}


@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    switch (requestCode) {
    case RESULT_SPEECH: {
        if (resultCode == RESULT_OK && null != data) {

            ArrayList<String> text = data
                    .getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);

            String text1;
            text1=text.get(0);
            txtText.setText(text.get(0));
        /*  if(text1=="call"||text1=="cal"||text1=="phone")
            {
               txtText.setText("call module"+text1);    
            }
            else if(text1=="message"||text1=="massage"||text1=="sms")
            {
                 txtText.setText("message module"+text1);  
            }
           else  
            {
              txtText.setText("invalid word!! please try again"+text1);
            }   */
    //     msg.setText(text1);
          // Intent intent=new Intent(this, MainActivity.class);
          // startActivity(intent);

        }
        break;
    }

    }
}
}
4

1 に答える 1

1

sendms ...ボタンが原因で強制終了

btnSendSMSの OnClickListener では、初期化していないためtxtPhoneNo、NullPointerException がスローされます。

phoneNo = txtPhoneNo.getText().toString();

またphonePhoneno、null の場合もあります。

終了ボタンが原因で強制終了

この行はおそらく NullPointerException をスローします。

str=intent.getExtras().getString("phoneno");

インテントに実際にエクストラがあるかどうか、またはインテントが存在するかどうかは確認しません。


私はあなたのコードをちらりと見ただけで、おそらくもっと多くのエラーがあります。LogCat は、エラーが発生した正確な行を示します。これは最適なデバッグ ツールです。読んでください: Logcat の解釈方法

于 2013-04-09T19:50:54.917 に答える