发送短信时发生Android NullPointerException

时间:2014-09-19 13:38:00

标签: android nullpointerexception sms

编辑: 当我尝试调用sendTextMessage时,我经常得到空指针异常,而且我不能'找出原因...... 有趣的是,它并不总是发生,但确实经常发生。

以下是代码:

package com.prolink.rute;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.telephony.SmsManager;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;


public class SendActivity extends ActionBarActivity {
    Button tourInput;
    Button tourInputWithout;
    EditText editNote;
    ListView list;

    TextView labelDate;
    TextView labelaOdredista;

    Bundle extras;

    String startName;
    String finishName;
    String strDate;
    String strNote="";
    String name;

    int option;
    int nDrivers;

    NetworkClass net;
    DBHelper db;
    DateClass dat;
    DriverClass[] drivers;


    // ----------------  Activiti OnCreate()  ----------------
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        Intent intent = getIntent();
        extras = intent.getExtras();

        option = extras.getInt("option");
        startName = extras.getString("start");
        finishName = extras.getString("finish");

        net = new NetworkClass(this);
        db = new DBHelper(this);
        dat = new DateClass(this);

        if(option == 2)
            strDate = dat.tommorowDate();
        else if(option == 10)
            strDate = extras.getString("_datue");
        else
            strDate = dat.danasnjiDatum();


        new SetTheContent().execute();
    }// end void onCreate()




    // ------------------ onBackPressed()  ------------------
    @Override
    public void onBackPressed() {
        // TODO Auto-generated method stub
    }






    // ------------------  Creating the ActionBar  ------------------
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // TODO Auto-generated method stub
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.action_bar_2, menu);
        return super.onCreateOptionsMenu(menu);
    }// end boolean onCreateOptionsMenu()





    // ------------------  Selecting the ActionBar option  ------------------
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // TODO Auto-generated method stub
        int id = item.getItemId();

        switch(id){
            case R.id.option_back:
                finish();
                break;

        case R.id.option_home: 
                Intent intent = new Intent(SendActivity.this, StartActivity.class);
                startActivity(intent);
                break;
        }

        return super.onOptionsItemSelected(item);
    }// end boolean onOptionsItemsSelected()









    // ------------------  Setting the content  ------------------
    private class SetTheContent extends AsyncTask<Void, Void, Void>{
        private ProgressDialog pd;

        @Override
        protected void onPreExecute(){
            super.onPreExecute();
            pd = new ProgressDialog(SendActivity.this);
            pd.setMessage("Setting the content...");
            pd.setCancelable(false);
            pd.show();
        }// end void onPreExecute()

        @Override
        protected Void doInBackground(Void... params) {
            // TODO Auto-generated method stub
            int[] ids = extras.getIntArray("selected_drivers");
            nDrivers = ids.length;

            drivers = new DriverClass[nDrivers];
            for(int i=0; i<nDrivers; i++){
                drivers[i] = new DriverClass();
                drivers[i] = db.returnDriver(ids[i]);
            }

            return null;
        }// end void doInBackground()

        protected void onPostExecute(Void Result){
            super.onPostExecute(Result);
            if (pd.isShowing())
                pd.dismiss();
            setMyContent();
            DriversAdapter adapter = new DriversAdapter(SendActivity.this, drivers,     nDrivers, strDate);
            list.setAdapter(adapter);
        }
    }// end class SetTheContent






    // ------------------  Sending tour to server, sending SMS  ------------------
    private class TourInput extends AsyncTask<Boolean, Void, Boolean>{

        private ProgressDialog pd;
        Boolean _sms;


        @Override
        protected void onPreExecute(){
            super.onPreExecute();
            pd = new ProgressDialog(SendActivity.this);
            pd.setMessage("Unos ture ...");
            pd.setCancelable(false);
            pd.show();
        }// end void onPreExecute()



        @Override
        protected Boolean doInBackground(Boolean... params) {
            // TODO Auto-generated method stub
            _sms = params[0];
            boolean success = net.potvrdiVezu();
            if(option == 10){
                String _start = extras.getString("_start");
                String _finish = extras.getString("_finish");
                if(net.deleteTour(Integer.parseInt(drivers[0].returnID()), _start, _finish, strDate) == 0)
                    success = false;
                if(net.tourInput(Integer.parseInt(drivers[0].returnID()), startName, finishName, strDate, strNote) == 0)
                    success = false;
            }//if
            else{
                if(success){
                    for(int i=0; i<nDrivers; i++){
                        if(net.tourInput(Integer.parseInt(drivers[i].returnID()), startName, 
                                finishName, strDate, strNote) == 0){
                            success = false;
                            break;
                        }
                    }// for
                }
            }// else
            return success;
        }// end Void doInBackGround()



        protected void onPostExecute(Boolean Result){
            super.onPostExecute(Result);

            if (pd.isShowing())
                pd.dismiss();

            if(Result){
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        // TODO Auto-generated method stub
                        if(option == 10){
                            int tour_id = extras.getInt("tour_id");
                            db.deleteTure(tour_id);
                            db.tourInsert(Integer.parseInt(drivers[0].returnID()), startName, finishName, datum);
                            if(_sms){
                                String smsTour = "Change: " + startName + " - " + finishName +  
                                                 ", date: " + strDate;
                                String smsNote = " Note: " + strNote;
                                String smsText = smsTour + smsNote;

                                Log.e("smsText", smsText);
                                smsSend(drivers[0].returnNumber(), smsTour, drivers[0].returnName());
                                smsSend(drivers[0].returnNumber(), smsNote, drivers[0].returnName());


                                db.smsInsert(Integer.parseInt(drivers[0].returnID()), dat.strDateTime(), smsText);
                                net.smsInsert(DBHelper.SMS_ID, Integer.parseInt(drivers[0].returnID()), dat.dateTime(), smsText);
                            }
                       }// if(option..)

                       else{
                           for(int i=0; i<nDrivers; i++){
                                db.tourInsert(Integer.parseInt(drivers[i].returnID()), startName, finishName, strDate);
                                if(_sms){
                                    String smsTour = "Tour: " + startName + " - " + finishName + 
                                                      ", date: " + strDate;
                                    String smsNote = " Note: " + strNote; 

                                    String smsDrivers = "";
                                    for(int k=0; k<nDrivers-1; k++)
                                        smsDrivers += drivers[k].returnName() + ", ";
                                    smsDrivers += drivers[nDrivers - 1].returnName();

                                    String smsText = smsTour + smsNote + " " + smsDrivers;

                                    Log.e("smsText", smsText);

                                    smsSend(drivers[i].returnNumber(), smsTour, drivers[i].returnName());
                                    smsSend(drivers[i].returnNumber(), smsNote, drivers[i].returnName());
                                    if(nDrivers > 1)
                                        smsSend(drivers[i].returnNumber(), smsDrivers, drivers[i].returnName());

                                    db.smsInsert(Integer.parseInt(drivers[i].returnID()), dat.dateTime(), smsText);
                                    net.smsInsert(DBHelper.SMS_ID, Integer.parseInt(drivers[i].returnID()), dat.datumVrijeme(), smsText);
                                }
                            }

                        }// else(option..)

                        Intent intent = new Intent(SendActivity.this, StartActivity.class);
                        startActivity(intent);
                    }// run()
                }).start();
            }

            else
                Toast.makeText(SendActivity.this, "Failed input", Toast.LENGTH_SHORT).show();           
        }// end void onPostExecute()

    }// end class TourInput







    // ------------------  Set the content  ------------------
    private void setMyContent(){
        setContentView(R.layout.activity_send);

        tourInput = (Button) findViewById(R.id.button_tourInput);
        tourInputWithout = (Button) findViewById(R.id.button_tourInput2);
        editNote = (EditText) findViewById(R.id.edit_note);
        list = (ListView) findViewById(R.id.list_send_drivers);
        labelDate = (TextView) findViewById(R.id.label_send_datum);
        labelaOdredista = (TextView) findViewById(R.id.label_send_destinations);

        labelDate.setText(DateClass.formatDate(strDate));
        labelaOdredista.setText(startName + "\t\t-\t\t" + finishName);


        tourInput.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub

                strNote = editNote.getText().toString();
                if(strNote.isEmpty())
                    strNote = "-";
                Log.e("Note:", strNote);

                if(net.hasNet())
                    new TourInput().execute(true);
                else
                    Toast.makeText(SendActivity.this, "No Network", Toast.LENGTH_SHORT).show();
            }// end onClick()
        });// end setOnClickListener()



        tourInputWithout.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                strNote = editNote.getText().toString();
                if(strNote.isEmpty())
                    strNote = "-";
                if(net.hasNet())
                    new TourInput().execute(false);
                else
                    Toast.makeText(SendActivity.this, "No Network", Toast.LENGTH_SHORT).show();
            }
        });

    }// end void setMyContent()




    // ------------------ Sending SMS  ------------------
    private void smsSend(String number, String message, String name_){
        SmsManager sms = SmsManager.getDefault();
        name= name_;

        try{
            sms.sendTextMessage(number, null, message, null, null);
        }
        catch(IllegalArgumentException e){
            Log.e("SMS error", e.getMessage().toString());
        }
        catch(Exception e){
            Log.e("SMS Exception", e.getMessage().toString());
        }
    }// end void smsSend()
}

我发现有时候因为变量而引发了异常&#34; strDate&#34;并且&#34; strNote&#34;,但是在logcat中它们的内容是存在的并且打印出来......

logcat的:

09-20 13:31:25.310: D/dalvikvm(14101): GC_FOR_ALLOC freed 163K, 4% free 6469K/6727K, paused 57ms
09-20 13:31:25.340: I/dalvikvm-heap(14101): Grow heap (frag case) to 6.856MB for 513744-byte allocation
09-20 13:31:25.440: D/dalvikvm(14101): GC_CONCURRENT freed 0K, 4% free 6970K/7239K, paused 2ms+3ms
09-20 13:31:25.980: I/dalvikvm(14101): Could not find method android.widget.LinearLayout$LayoutParams.<init>, referenced from method android.support.v7.internal.view.menu.ActionMenuView$LayoutParams.<init>
09-20 13:31:25.980: W/dalvikvm(14101): VFY: unable to resolve direct method 8268: Landroid/widget/LinearLayout$LayoutParams;.<init> (Landroid/widget/LinearLayout$LayoutParams;)V
09-20 13:31:25.980: D/dalvikvm(14101): VFY: replacing opcode 0x70 at 0x0000
09-20 13:31:26.590: D/dalvikvm(14101): GC_CONCURRENT freed 69K, 3% free 7317K/7495K, paused 4ms+4ms
09-20 13:31:26.780: D/CLIPBOARD(14101): Hide Clipboard dialog at Starting input: finished by someone else... !
09-20 13:31:32.060: D/dalvikvm(14101): GC_CONCURRENT freed 121K, 3% free 7587K/7815K, paused 3ms+5ms
09-20 13:31:32.680: D/dalvikvm(14101): GC_CONCURRENT freed 307K, 5% free 7748K/8135K, paused 26ms+19ms
09-20 13:31:34.600: D/dalvikvm(14101): GC_CONCURRENT freed 461K, 7% free 7741K/8263K, paused 5ms+6ms
09-20 13:31:37.460: D/dalvikvm(14101): GC_CONCURRENT freed 170K, 4% free 8044K/8327K, paused 5ms+3ms
09-20 13:31:43.680: E/Note:(14101): fffffffff
09-20 13:31:43.740: E/smsText(14101): Tour: ŠUMARIJA BRINJE - CEDAR d.o.o. - NAŠICE, date: 2014-09-21 Note: fffffffff BREZARIĆ MLADEN
09-20 13:31:43.800: W/dalvikvm(14101): threadid=14: thread exiting with uncaught exception (group=0x401be760)
09-20 13:31:43.810: E/AndroidRuntime(14101): FATAL EXCEPTION: Thread-17
09-20 13:31:43.810: E/AndroidRuntime(14101): java.lang.NullPointerException
09-20 13:31:43.810: E/AndroidRuntime(14101):    at com.prolink.rute.SendActivity.smsSend(SendActivity.java:412)
09-20 13:31:43.810: E/AndroidRuntime(14101):    at com.prolink.rute.SendActivity.access$1(SendActivity.java:399)
09-20 13:31:43.810: E/AndroidRuntime(14101):    at com.prolink.rute.SendActivity$UnosTure$1.run(SendActivity.java:312)
09-20 13:31:43.810: E/AndroidRuntime(14101):    at java.lang.Thread.run(Thread.java:1020)
09-20 13:31:45.840: I/dalvikvm(14101): threadid=4: reacting to signal 3
09-20 13:31:45.860: I/dalvikvm(14101): Wrote stack traces to '/data/anr/traces.txt'

LogCat始终指向与空指针异常关联的两行代码: smsSend(drivers[i].returnNumber(), smsTour, drivers[i].returnName())  和catch(Exception e){ Log.e(...); }

它类似于String变量,它是smsSend方法的第二个参数,为null。当我将随机String作为第二个参数传递时,它可以工作。但是当我传递变量smsTour时,smsNote有时会抛出异常,有时候不会抛出异常。当我将smsText作为参数传递时,它总是抛出异常。

我总是在调用smsSend之前在LogCat中打印这些String变量的值,并且它很好..但由于某种原因,抛出异常..

我认为这可能是因为弦乐的长度,但长度远小于160个字符.. 无论如何,我认为问题与作为sendSMS的参数传递的String变量有关,但不知道是什么以及为什么......

对此有何帮助?

1 个答案:

答案 0 :(得分:0)

似乎方法sendTextMessage()无法正常工作...... 我用方法sendMultiPartTextMessage()替换它并且它工作正常:=)