0

我在该行收到 NullPointerException:

mAssistInstrButton.setOnClickListener(this);

但是我看不出它应该发生的任何原因。

非常感谢任何输入。

日志猫:

08-15 15:19:25.090: E/AndroidRuntime(24692): FATAL EXCEPTION: main
08-15 15:19:25.090: E/AndroidRuntime(24692): java.lang.NullPointerException
08-15 15:19:25.090: E/AndroidRuntime(24692):    at com.project.new.datasettings.ConfigFinalActivity.onClick(ConfigFinalActivity.java:182)
08-15 15:19:25.090: E/AndroidRuntime(24692):    at android.view.View.performClick(View.java:3511)
08-15 15:19:25.090: E/AndroidRuntime(24692):    at android.view.View$PerformClick.run(View.java:14111)
08-15 15:19:25.090: E/AndroidRuntime(24692):    at android.os.Handler.handleCallback(Handler.java:605)
08-15 15:19:25.090: E/AndroidRuntime(24692):    at android.os.Handler.dispatchMessage(Handler.java:92)
08-15 15:19:25.090: E/AndroidRuntime(24692):    at android.os.Looper.loop(Looper.java:137)
08-15 15:19:25.090: E/AndroidRuntime(24692):    at android.app.ActivityThread.main(ActivityThread.java:4429)
08-15 15:19:25.090: E/AndroidRuntime(24692):    at java.lang.reflect.Method.invokeNative(Native Method)
08-15 15:19:25.090: E/AndroidRuntime(24692):    at java.lang.reflect.Method.invoke(Method.java:511)
08-15 15:19:25.090: E/AndroidRuntime(24692):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:791)
08-15 15:19:25.090: E/AndroidRuntime(24692):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:558)
08-15 15:19:25.090: E/AndroidRuntime(24692):    at dalvik.system.NativeStart.main(Native Method)

资源:

project com.project.new.datasettings;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import javax.xml.parsers.ParserConfigurationException;

import org.xml.sax.SAXException;

import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.database.SQLException;
import android.net.Uri;
import android.os.Build;
import android.os.Build.VERSION_CODES;
import android.os.Bundle;
import android.provider.Settings;
import android.telephony.TelephonyManager;
import android.text.Html;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
public class ConfigFinalActivity extends Activity implements OnClickListener {
    private static final String TAG = "ConfigActivity";
    TelephonyManager tm;
    AlertDialog mErrorAlert = null;
    private Notification mNotification = null;
    private Button mXButton = null;
    private Button mAssistUpdateButton = null;
    private Button mAssistInstrButton = null;
    private Button mReadAgainButton = null;
    private int mInstructionNumber = 0;
    public static ArrayList<String> NameArr = new ArrayList<String>();
    public static ArrayList<String> ValueArr = new ArrayList<String>();
    public static ArrayList<String> nameArr = new ArrayList<String>();
    public static ArrayList<String> ApnArr = new ArrayList<String>();
    public static ArrayList<String> mmscArr = new ArrayList<String>();
    public static ArrayList<String> mmsportArr = new ArrayList<String>();
    public static ArrayList<String> mmsproxyArr = new ArrayList<String>();
    public static ArrayList<String> portArr = new ArrayList<String>();
    public static ArrayList<String> proxyArr = new ArrayList<String>();
    public static int count;
    public static int TotalSteps = 8;
    int i, g = 0, result = 0;
    String Result = "";
    public static ContentValues Values = new ContentValues();
    XmlParserHandlerFinal handler;

    public static final Uri APN_TABLE_URI = Uri
            .parse("content://telephony/carriers");
    public static String Base_URL = "https://www.mysettings.com/";
    public static InputStream stream = null;
    UpdateActivity update;
    public static String status;

    /** Called when the activity is first created. */
    @SuppressLint("NewApi")
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        int version = android.os.Build.VERSION.SDK_INT;
        tm = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);
        update = new UpdateActivity();
        nameArr = update.getnameArr();
        ApnArr = update.getApnArr();
        mmscArr = update.getMMSCArr();
        mmsproxyArr = update.getMmscProxyArr();
        mmsportArr = update.getMmsPortArr();
        proxyArr = update.getMmscProxyArr();
        portArr = update.getMmsPortArr();
        count = update.getCount();
        if (ApnArr.isEmpty() || mmscArr.isEmpty() || mmsportArr.isEmpty()
                || mmsproxyArr.isEmpty() || proxyArr.isEmpty()
                || portArr.isEmpty()) {
            tryagain();
        } else if (version < VERSION_CODES.ICE_CREAM_SANDWICH) {

            // Update APN table
            try {
                result = updateTable();
            } catch (IOException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }// Settings updated with this atomic call
            catch (SAXException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (ParserConfigurationException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

            if (result != -1) {
                status = "success";

            } else {
                status = "failure";
            }

            if (status.equals("success")) {
                completeUpdate();
            } else if (status.equals("failure")) {
                tryagain();
                // showAlert(getString(R.string.unchanged_net10_dialog));
            }

        } else {// ICS and later versions

            // Reduce number of steps to 6
            TotalSteps = 6;
            setContentView(R.layout.assist_update);
    //      String assistUpdate = getString(R.string.instructions_1);
    //      CharSequence styledText = Html.fromHtml(assistUpdate);
            TextView assistText = (TextView) findViewById(R.id.apn_app_text_cta2);
    //      assistText.setText(styledText);
            mAssistUpdateButton = (Button) findViewById(R.id.assist_update_btn);
            mAssistUpdateButton.setOnClickListener(this);

        }
    }

    public void onClick(View v) {
        switch(v.getId()) {
        case R.id.assist_update_btn:

            // Update button for ICS and up is selected
            // Get the TextView in the Assist Update UI

            TextView tv = (TextView) findViewById(R.id.apn_app_text_cta2);
            String text = "";
            CharSequence styledText = text;
            switch (mInstructionNumber) {

            case 0:
                // Retrieve the instruction string resource corresponding the
                // 2nd set of instructions
                text = String.format(getString(R.string.apn_app_text_instr),
                        TotalSteps);
                styledText = Html.fromHtml(text);
                // Update the TextView with the correct set of instructions
                tv.setText(styledText);
                // Increment instruction number so the correct instructions
                // string resource can be retrieve the next time the update
                // button is pressed
                mInstructionNumber++;
                break;
            case 1:
                text = getString(R.string.apn_app_text_instr2);
                styledText = Html.fromHtml(text);
                tv.setText(styledText);
                // Increment instruction number so the correct instructions
                // string resource can be retrieve the next time the update
                // button is pressed
                mInstructionNumber++;
                break;

            case 2:
                // Final set of instructions-Change to the corresponding layout

                setContentView(R.layout.assist_instructions);
                String assistUpdateInstr = String.format(
                        getString(R.string.apn_app_text_instr3), TotalSteps);
                styledText = Html.fromHtml(assistUpdateInstr);
                TextView assistInstrText = (TextView) findViewById(R.id.updated_text);
                assistInstrText.setText(styledText);
                mAssistInstrButton = (Button) findViewById(R.id.assist_update_btn);
                //mReadAgainButton = (Button) findViewById(R.id.read_again_btn);
                mAssistInstrButton.setOnClickListener(this);
                // mReadAgainButton.setOnClickListener(this);

                // "LET'S DO THIS" Button in final instructions screen for ICS
                // and
                // up is selected
                // Create ConfigActivity Intent
                // Intent i = new Intent(this,
                // NotificationActivityForMultiProf.class);
                // Invoke ConfigActivity Intent to start the assisted update
                // startActivity(i);
                // finish();

                // startActivity(new Intent(Settings.ACTION_APN_SETTINGS));
            }
        }  if (v == mAssistInstrButton) {

            // mAssistUpdateButton = (Button)
            // findViewById(R.id.assist_update_btn);
            // mAssistUpdateButton.setOnClickListener(this);
            startActivity(new Intent(Settings.ACTION_APN_SETTINGS));

            try {
                showNotification();
            } catch (SAXException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (ParserConfigurationException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            finish();// } else if (v == mReadAgainButton) {




            // go back to set of instructions if read again is selected
        //  mInstructionNumber = 2;

    //      setContentView(R.layout.screen5);
////            String one_text = String
////                    .format(getString(R.string.one), TotalSteps);
////            CharSequence styledText_one = Html.fromHtml(one_text);
//          TextView one = (TextView) findViewById(R.id.text_one);
//          one.setTextSize(18);
//          one.setText(styledText_one);
//          String two_text = String
//                  .format(getString(R.string.two), TotalSteps);
//          CharSequence styledText_two = Html.fromHtml(two_text);
//          TextView two = (TextView) findViewById(R.id.text_two);
//          two.setTextSize(18);
//          two.setText(styledText_two);
//          String three_text = String.format(getString(R.string.three),
//                  TotalSteps);
//          CharSequence styledText_three = Html.fromHtml(three_text);
//          TextView three = (TextView) findViewById(R.id.text_three);
//          three.setTextSize(18);
//          three.setText(styledText_three);
    //      mAssistUpdateButton = (Button) findViewById(R.id.assist_instr_btn);
        //  mAssistUpdateButton.setOnClickListener(this);

        }
    }



    /*
     * Insert a new APN entry into the system APN table Require an apn name, and
     * the apn address. More can be added. Return an id (_id) that is
     * automatically generated for the new apn entry.
     */
    public int InsertAPN() throws SecurityException {

        int id = -1;
        for (i = 0; i < count; i++) {
            ContentValues values2 = new ContentValues();
            // values2 = values1;
            values2 = getValues();
            ContentResolver resolver = getContentResolver();
            Cursor c = null;
            try {
                Uri newRow = resolver.insert(APN_TABLE_URI, values2);
                // System.out.println("values in insertAPN" + values1);
                if (newRow != null) {
                    c = resolver.query(newRow, null, null, null, null);
                    Log.d(TAG, "Newly added APN:");
                    // TF Settings have been inserted
                    // Obtain the apn id
                    int idindex = c.getColumnIndex("_id");
                    c.moveToFirst();
                    id = c.getShort(idindex);

                    Log.d(TAG, "New ID: " + id
                            + ": Inserting new APN succeeded!");
                }
            } catch (SQLException e) {
                Log.d(TAG, e.getMessage());
            }
            if (c != null)
                c.close();
        }
        return id;

    }

    public ContentValues getValues() {
        ContentValues values = new ContentValues();

        values.put("name", nameArr.get(i));
        values.put("apn", ApnArr.get(i));
        values.put("mmsc", mmscArr.get(i));
        values.put("mmsproxy", mmsproxyArr.get(i));
        values.put("mmsport", mmsportArr.get(i));
        values.put("proxy", proxyArr.get(i));
        values.put("port", portArr.get(i));
        values.put("mcc", (getString(R.string.mcc)));
        if ((tm.getSimOperator()).equals(getString(R.string.numeric_tmo))) {
            values.put("numeric", getString(R.string.numeric_tmo));
            values.put("mnc", (getString(R.string.mnc_tmo)));
        } else if ((tm.getSimOperator())
                .equals(getString(R.string.numeric_att))) {
            values.put("numeric", getString(R.string.numeric_att));
            values.put("mnc", (getString(R.string.mnc_att)));
        }
        return values;
    }

    /*
     * Delete APN data where the indicated field has the values Entire table is
     * deleted if both field and value are null
     */
    private void DeleteAPNs(String field, String[] values)
            throws SecurityException {
        int c = 0;
        c = getContentResolver().delete(APN_TABLE_URI, null, null);
        if (c != 0) {
            String s = "APNs Deleted:\n";
            Log.d(TAG, s);

        }

    }

    /*
     * Return all column names stored in the string array
     */
    private String getAllColumnNames(String[] columnNames) {
        String s = "Column Names:\n";
        for (String t : columnNames) {
            s += t + ":\t";
        }
        return s + "\n";
    }

    /*
     * Copy all data associated with the 1st record Cursor c. Return a
     * ContentValues that contains all record data.
     */
    private ContentValues copyRecordFields(Cursor c) {
        if (c == null)
            return null;
        int row_cnt = c.getCount();
        Log.d(TAG, "Total # of records: " + row_cnt);
        ContentValues values = new ContentValues();//
        if (c.moveToFirst()) {
            String[] columnNames = c.getColumnNames();
            Log.d(TAG, getAllColumnNames(columnNames));
            String row = "";
            for (String columnIndex : columnNames) {
                int i = c.getColumnIndex(columnIndex);
                row += c.getString(i) + ":\t";
                // if (i>0)//Avoid copying the id field
                // id to be auto-generated upon record insertion
                values.put(columnIndex, c.getString(i));
            }
            row += "\n";
            Log.d(TAG, row);
            Log.d(TAG, "End Of Records");
        }
        return values;
    }

    // showAlert displays the text contained in message as an alert
    public void showAlert(String message) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setMessage(message).setPositiveButton("OK",
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int id) {
                        ConfigFinalActivity.this.finish();
                    }
                });
        mErrorAlert = builder.create();
        mErrorAlert.show();
    }

    // showErrorAlert displays an alert with layout and a title
        private void showErrorAlert(int layoutRes, String title) {
            AlertDialog.Builder builder = new AlertDialog.Builder(this);
            // Get the layout inflater
            LayoutInflater inflater = ConfigFinalActivity.this.getLayoutInflater();

            // Inflate and set the layout for the dialog
            // Pass null as the parent view because its going in the dialog layout
            builder.setTitle(title)
                    .setView(inflater.inflate(layoutRes, null))
                    .setPositiveButton(getString(R.string.assisted_button),
                            new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface dialog, int id) {
                                    startActivity(new Intent(
                                            Settings.ACTION_APN_SETTINGS));
                                    try {
                                        showNotification();
                                    } catch (SAXException e) {
                                        // TODO Auto-generated catch block
                                        e.printStackTrace();
                                    } catch (ParserConfigurationException e) {
                                        // TODO Auto-generated catch block
                                        e.printStackTrace();
                                    }
                                }
                            });
            mErrorAlert = builder.create();
            mErrorAlert.show();
        }

    // showNotification starts the process of sending notifications to the bar
    // to assist the user in updating the data settings on ICS and later
    // versions of Android
    @SuppressWarnings("deprecation")
    @TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
    void showNotification() throws SAXException, ParserConfigurationException {

        String field = getString(R.string.config_name_label);

        String value = Values.get("name").toString();
        int mId = 1;
        String title = "1 of " + TotalSteps + " (Update " + field + ":)";
        Notification.Builder mBuilder = new Notification.Builder(this)
                .setSmallIcon(R.drawable.ic_launcher)
                .setContentTitle(title).setContentText(value);
        Intent resultIntent = new Intent(this, NotificationActivityForMultiProf.class);
        resultIntent.putExtra(field, value);
        PendingIntent resultPendingIntent = PendingIntent.getActivity(
                getApplicationContext(), 0, resultIntent,
                PendingIntent.FLAG_UPDATE_CURRENT);
        mBuilder.setContentIntent(resultPendingIntent);
        NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        // mId allows you to update the notification later on.
        mNotification = mBuilder.getNotification();
        mNotification.flags |= Notification.FLAG_AUTO_CANCEL;
        mNotificationManager.notify(mId, mNotification);
        finish();
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        // TODO Auto-generated method stub
        super.onSaveInstanceState(outState);
        if (mNotification != null) {
            outState.putString("NOTIFICATIONB", mNotification.toString());
        }
    }

    @Override
    protected void onRestart() {
        super.onRestart();
        if (mErrorAlert != null)
            mErrorAlert.dismiss();
    }

    private int updateTable() throws IOException, SAXException,
            ParserConfigurationException {
        int insertResult = -1;
        // returned value if table is not properly updated

        try {

            ContentValues values = new ContentValues();
            // Query the carrier table for the current data settings
            Cursor c = getContentResolver().query(APN_TABLE_URI, null,
                    "current=?", new String[] { "1" }, null);
            values = copyRecordFields(c);
            // Copy the NET10 settings into values

            // Replace T-Mo/ATT Data settings if there is no SIM or
            // NET10/T-Mo/ATT SIM is
            // present
            if (tm.getSimState() == TelephonyManager.SIM_STATE_ABSENT
                    || (tm.getSimOperator())
                            .equals(getString(R.string.numeric_tmo))) {

                // delete all APNs before adding new APNs
                DeleteAPNs("numeric=?",
                        new String[] { getString(R.string.numeric_tmo) });
                // Insert NET10 Data Settings into Carrier table

                insertResult = InsertAPN();

            } else if (tm.getSimState() == TelephonyManager.SIM_STATE_ABSENT
                    || (tm.getSimOperator())
                            .equals(getString(R.string.numeric_att))) {
                // Delete all APNs before adding new APNs
                DeleteAPNs("numeric=?",
                        new String[] { getString(R.string.numeric_att) });
                // Insert NET10 Data Settings into Carrier table

                insertResult = InsertAPN();

    //      } else
                // non NET10/ non T-Mo SIM/non ATT SIM
        //      showAlert(getString(R.string.insert_net10_dialog));
            }   } catch (SecurityException e) {
        //  showErrorAlert(R.layout.assisted_settings,
        //          getString(R.string.assited_title));
            Log.d(TAG, e.getMessage());
        }
        return insertResult;
    }

    private void completeUpdate() {
        // Displaying final layout after pre-ICS automatic settings update
        setContentView(R.layout.completion);
    //  TextView mCompleted = (TextView) findViewById(R.id.done_text1);
    //  String mDoneText = String.format(getString(R.string.done_text1));
    //  CharSequence styledText = Html.fromHtml(mDoneText);

    //  mCompleted.setText(styledText);
        mAssistUpdateButton = (Button) findViewById(R.id.assist_update_btn);
        mAssistUpdateButton.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                finish();
            }
        });
    }

    public void tryagain() {
        // Displaying final layout after failure of pre-ICS automatic settings
        // update
        //setContentView(R.layout.tryagain);
        String tryAgainText = "";
        CharSequence styledTryAgainText;
//
//      tryAgainText = String.format(getString(R.string.tryagain_text1),
//              TotalSteps);
//      styledTryAgainText = Html.fromHtml(tryAgainText);
//      TextView tryAgain1 = (TextView) findViewById(R.id.tryagain_text1);
//      tryAgain1.setText(styledTryAgainText);
//
//      tryAgainText = String.format(getString(R.string.tryagain_text2),
//              TotalSteps);
//      styledTryAgainText = Html.fromHtml(tryAgainText);
//      TextView tryAgain2 = (TextView) findViewById(R.id.tryagain_text2);
//      tryAgain2.setText(styledTryAgainText);
//
//      tryAgainText = String.format(getString(R.string.tryagain_text3),
//              TotalSteps);
//      styledTryAgainText = Html.fromHtml(tryAgainText);
//      TextView tryAgain3 = (TextView) findViewById(R.id.tryagain_text3);
//      tryAgain3.setText(styledTryAgainText);

    }

    // This function return a cursor to the table holding the
    // the APN configurations (Carrier table)
    public Cursor getConfigTableCursor() {
        return getContentResolver()
                .query(APN_TABLE_URI, null, null, null, null);
    }

    public ArrayList<String> getnameArr() {

        return nameArr;
    }

    public ArrayList<String> getApnArr() {

        return ApnArr;
    }

    public ArrayList<String> getMMSCArr() {

        return mmscArr;
    }

    public ArrayList<String> getMmscProxyArr() {

        return mmsproxyArr;
    }

    public ArrayList<String> getMmsPortArr() {

        return mmsportArr;
    }

    public int getCount() {
        return count;
    }

    public ArrayList<String> getProxyArr() {

        return proxyArr;
    }

    public ArrayList<String> getPortArr() {

        return portArr;
    }

}
4

5 回答 5

2

你打电话:

mAssistInstrButton = (Button) findViewById(R.id.assist_update_btn);

从文档中:

public View findViewById (int id)

从在 onCreate(Bundle) 中处理的 XML 中查找由 id 属性标识的视图。退货

如果找到则为视图,否则为 null。

所以,assist_update_btn存在R.id. 检查拼写/位置assist_update_btn

于 2013-08-15T19:35:49.943 回答
1

正如 Nobu 的评论所说,用代码摘录和没有行号来确定负责的确切行有点困难,但我在您的代码中发现这三行接近第 182 行,第三行与您询问的行匹配:

 mAssistInstrButton = (Button) findViewById(R.id.assist_update_btn);
 //mReadAgainButton = (Button) findViewById(R.id.read_again_btn);
 mAssistInstrButton.setOnClickListener(this);

如果 mAssistInstrButton 为 null,我希望这里会出现 NullPointerException,因此我建议检查(通过添加日志记录或使用调试器)以确保findViewById(R.id.assist_update_btn)方法调用返回的不是 null。您确定传递R.id.assist_update_btn给该方法将是一个 Button 实例而不是 null 吗?

于 2013-08-15T19:46:51.693 回答
0

logcat 指向您分配侦听器的视图不存在的事实,即;他们没有 ID 视图assist_update_btn,这就是为什么当您尝试分配clickListener给布局中不存在的按钮时会收到 NullPointerException 的原因。

于 2013-08-15T19:37:46.293 回答
0

findViewById显然是返回一个null值。您可以将其包装在 if 条件中以检查该情况,或者您可以编辑findViewById函数本身。

您发布的摘录很难更具体。

于 2013-08-15T19:33:39.000 回答
0

正如其他人所说:findViewById 可能会返回 null,因为无法找到视图。

但这也可能是构建过程中罕见的故障,我在 Android 应用程序开发期间也发生过几次。过去一直工作的代码部分突然因 NullPointerExceptions 而崩溃。

构建过程有时会有点不稳定,资源没有得到正确处理或更新。如果您确定视图存在并且 id 是正确的(如果它以前一直为您工作)那么清理您的工作区并从头开始构建新的应用程序项目。

这有时甚至会发生在可绘制和字符串资源中,它们可能会被切换和弄乱。

于 2013-08-15T19:41:50.697 回答