2013-04-09 2 views
-3

안드로이드 프로젝트에서 연락처를 추가하거나 새로운 활동을 시작하려고 할 때 버튼이 제대로 작동하지만 SMS를 보내려고하면 강제 종료됩니다. 위의 코드에서 sendsms활동간에 데이터를 전달하면 강제로 닫기가 발생합니다.

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 

}*/ 

}

다음과 종료 버튼 강제 확대를 일으키는 같이 주 코드이다. 앱을 올바르게 실행하기 위해 어떤 변경을해야합니까? 두 번째 활동

코드

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

    } 
} 
} 
+1

show crash stacktrace! –

+0

코드를 지우고 관련된 내용 만 표시하십시오. 그런 다음 @WebnetMobile이 제안한대로 LogCat에서 스택 추적을 표시합니다. – coder

+0

의도적으로 반환 된 널 포인터 예외로 인해 오류가 발생했습니다. 처리해야합니다. send sms는 ininitialised 변수 때문에 강제 종료되었습니다. 나는 그 부분을 바로 잡았습니다. – sid

답변

1
가까운

btnSendSMS의 OnClickListener를에서

sendsms ... 버튼을 일으키는 힘, 당신은 그래서 이것은 NullPointerException이 발생합니다 txtPhoneNo를 초기화하지 않은 :

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

phonePhoneno도 null 일 수 있습니다. 텐트도 존재하는 경우는 의도가 실제로 엑스트라가 있는지 여부를 확인하지 않거나

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

:

종료 버튼을

가까운 힘을 일으키는이 줄은 아마 NullPointerException이 발생합니다.


난 단지 코드를 훑어 보았을 때 더 많은 오류가있을 수 있습니다. LogCat은 오류가 발생한 정확한 행을 알려주며, 이것은 가장 좋은 디버깅 도구입니다. 읽으십시오 : How to interpret Logcat

+0

그런 다음 SMS를 보내면 강제 종료가 발생하는 이유는 무엇입니까 ?? – sid

+0

내 대답 – Sam

+0

맞아요 응용 프로그램이 null 포인터 예외로 인해 응용 프로그램이 충돌합니다. null 포인터 예외를 처리해야합니다. – sid

관련 문제