-3

我正在开发一个 android 项目,对于添加联系人之类的几个按钮或当我想开始一个新活动但当我尝试发送短信时它会强制关闭它自己。主要代码如下

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 和完成按钮导致强制关闭。为了使应用程序正确运行,我应该进行哪些更改。

第二个活动代码

 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可能为空。

完成按钮导致强制关闭

此行可能会引发 NullPointerException:

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

您不会检查 Intent 是否真的有额外内容,或者 Intent 是否存在。


我只看了你的代码,可能还有更多错误。LogCat 会告诉您错误发生的确切位置,这是您最好的调试工具。请阅读:如何解释 Logcat

于 2013-04-09T19:50:54.917 回答