Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/cocoa/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Android 在活动之间传递数据会导致强制关闭_Android - Fatal编程技术网

Android 在活动之间传递数据会导致强制关闭

Android 在活动之间传递数据会导致强制关闭,android,Android,我正在做一个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; impo

我正在做一个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

}*/
}

在上述代码中,sendsms和finish按钮导致强制关闭。为了使应用程序正确运行,我应该做哪些更改

第二项活动代码

 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;
    }

    }
}
}
package com.example.sms;
导入java.util.ArrayList;
导入android.app.Activity;
导入android.content.ActivityNotFoundException;
导入android.content.Intent;
导入android.os.Bundle;
导入android.speech.RecognizerIntent;
导入android.support.v4.view.ViewGroupCompat;
导入android.view.Menu;
导入android.view.view;
导入android.view.view.OnClickListener;
导入android.widget.Button;
导入android.widget.EditText;
导入android.widget.ImageButton;
导入android.widget.TextView;
导入android.widget.Toast;
公共类MainActivity1扩展活动实现OnClickListener{
受保护的静态最终整数结果\u SPEECH=1;
专用图像按钮btnSpeak;
私有文本视图txtText;
//编辑文本消息;
按钮b;
字符串phoneno;
@凌驾
创建时的公共void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main1);
txtText=(TextView)findViewById(R.id.txtText);
btnSpeak=(图像按钮)findViewById(R.id.btnSpeak);
//msg=(EditText)findViewById(R.id.txtMessage);
//b=(按钮)findViewById(R.id.main\u act);
b=(按钮)findViewById(R.id.main\u act);
btnSpeak.setOnClickListener(此);
b、 setOnClickListener(此);
Intent=getIntent();
phoneno=intent.getExtras().getString(“phoneno”);
}
@凌驾
公共布尔onCreateOptions菜单(菜单){
getMenuInflater().充气(R.menu.activity\u主菜单);
返回true;
}
公共void onClick(视图v){
//TODO自动生成的方法存根
if(v.getId()==R.id.btnSpeak)
{
意图=新意图(
识别者(意图、行动、识别、言语);
intent.putExtra(RecognizerIntent.EXTRA_语言_模型,“en-US”);
试一试{
startActivityForResult(意图、结果和演讲);
txtText.setText(“”);
}捕获(ActivityNotFoundException a){
Toast t=Toast.makeText(getApplicationContext(),
“操作!您的设备不支持语音转换为文本”,
烤面包片(长/短);
t、 show();
}
}
如果(v.getId()==R.id.main\u act)
{
字符串str=txtText.getText().toString();
Intent Intent=新的Intent(getApplicationContext(),MainActivity.class);
intent.putExtra(“用户名”,str);
intent.putExtra(“电话号码”,电话号码);
星触觉(意向);
} 
}
@凌驾
受保护的void onActivityResult(int请求代码、int结果代码、意图数据){
super.onActivityResult(请求代码、结果代码、数据);
开关(请求代码){
个案结果(演讲):{
if(resultCode==RESULT\u OK&&null!=数据){
ArrayList文本=数据
.getStringArrayListExtra(识别器意图.额外结果);
字符串text1;
text1=text.get(0);
setText(text.get(0));
/*如果(text1==“呼叫”| | text1==“校准”| | text1==“电话”)
{
setText(“调用模块”+text1);
}
else if(text1==“消息”| | text1==“按摩”| | text1==“短信”)
{
setText(“消息模块”+text1);
}
其他的
{
setText(“无效单词!!请重试”+text1);
}   */
//msg.setText(text1);
//意向意向=新意向(此,MainActivity.class);
//星触觉(意向);
}
打破
}
}
}
}
发送短信。。。按钮导致强制关闭

btnSendSMS
的OnClickListener中,您尚未初始化
txtPhoneNo
,因此这将引发NullPointerException:

phoneNo = txtPhoneNo.getText().toString();
str=intent.getExtras().getString("phoneno");
phoneno
也可能为空

“完成”按钮导致强制关闭

此行可能会引发NullPointerException:

phoneNo = txtPhoneNo.getText().toString();
str=intent.getExtras().getString("phoneno");
您不会检查该意图是否确实有额外的内容,或者该意图是否存在



我只是浏览了一下你的代码,可能还有更多的错误。LogCat告诉您错误发生的确切位置,这是您最好的调试工具。请阅读:

显示崩溃堆栈跟踪!清理代码,只显示相关内容。然后按照@WebnetMobile的建议显示LogCat中的堆栈跟踪。我发现错误是由于intent返回的空指针异常造成的。应该如何处理它。由于初始化变量不正确,send sms被强制关闭。我已更正了该部分。您能否为我提供处理intent返回的空指针异常的解决方案。那么为什么send sms也导致强制关闭?是的,您的右应用程序因空指针异常而崩溃。我应该如何处理空指针异常。