获取editText标记时出现空指针异常

时间:2013-03-21 12:24:29

标签: android nullpointerexception

我在以下if循环中得到空指针异常:

...
if (tmp_tag.getName().equals("Tags")) {
            e.setText(stringBuilder.toString());
        }
...

我甚至检查过标签是否正确设置为editTexts但仍然得到“空指针异常”。不知道我在代码中缺少什么。事实上,我甚至不知道如何调试应用程序来查找错误。请帮帮我......

这是我的活动的java代码:

package com.walletapp;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.ContentValues;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

public class AddRecords extends Activity {

Spinner spinner, spinner_tags;
SQLiteDatabase database;
ArrayList<String> spinner_list, tags_list, cat_field_list;
String[] tags;
ArrayList<CharSequence> selectedTags = new ArrayList<CharSequence>();
TextView tv_1, tv_2, tv_3, tv_4, tv_5, tv_6, tv_7, tv_8, tv_9, tv_10,
        tv_11, tv_12, tv_13;
EditText et_1, et_2, et_3, et_4, et_5, et_6, et_7, et_8, et_9, et_10,
        et_11, et_12, et_13;
TextView[] tv;
EditText[] et;
Button btn_save;
int cat_id;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_add_records);

    this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);

    tv_1 = (TextView) findViewById(R.id.textView1);
    tv_2 = (TextView) findViewById(R.id.textView2);
    tv_3 = (TextView) findViewById(R.id.textView3);
    tv_4 = (TextView) findViewById(R.id.textView4);
    tv_5 = (TextView) findViewById(R.id.textView5);
    tv_6 = (TextView) findViewById(R.id.textView6);
    tv_7 = (TextView) findViewById(R.id.textView7);
    tv_8 = (TextView) findViewById(R.id.textView8);
    tv_9 = (TextView) findViewById(R.id.textView9);
    tv_10 = (TextView) findViewById(R.id.textView10);
    tv_11 = (TextView) findViewById(R.id.textView11);
    tv_12 = (TextView) findViewById(R.id.textView12);
    tv_13 = (TextView) findViewById(R.id.textView13);

    tv = new TextView[] { tv_1, tv_2, tv_3, tv_4, tv_5, tv_6, tv_7, tv_8,
            tv_9, tv_10, tv_11, tv_12, tv_13 };

    et_1 = (EditText) findViewById(R.id.editText1);
    et_2 = (EditText) findViewById(R.id.editText2);
    et_3 = (EditText) findViewById(R.id.editText3);
    et_4 = (EditText) findViewById(R.id.editText4);
    et_5 = (EditText) findViewById(R.id.editText5);
    et_6 = (EditText) findViewById(R.id.editText6);
    et_7 = (EditText) findViewById(R.id.editText7);
    et_8 = (EditText) findViewById(R.id.editText8);
    et_9 = (EditText) findViewById(R.id.editText9);
    et_10 = (EditText) findViewById(R.id.editText10);
    et_11 = (EditText) findViewById(R.id.editText11);
    et_12 = (EditText) findViewById(R.id.editText12);
    et_13 = (EditText) findViewById(R.id.editText13);

    et = new EditText[] { et_1, et_2, et_3, et_4, et_5, et_6, et_7, et_8,
            et_9, et_10, et_11, et_12, et_13 };

    selectedTags = new ArrayList<CharSequence>();
    build_tags_list();

    btn_save = (Button) findViewById(R.id.buttonAddRecordsSave);
    btn_save.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {

            loadDatabase();
            String currentDate = new SimpleDateFormat("yyyy/MM/dd")
                    .format(Calendar.getInstance().getTime());

            // ----------first insert into records_data table------------

            Tag tmp_tag = (Tag) et_1.getTag();
            ContentValues values = new ContentValues();

            values.put("cat_id", tmp_tag.getCat_id());
            values.put("tag_id", "0");
            values.put("is_favourite", "0");
            values.put("rec_name", et_1.getText() + "");
            values.put("is_delete", "0");
            values.put("create_date", currentDate);
            values.put("update_date", "0");

            database.insert("records_data", null, values);
            values.clear();

            // --------now insert the rest of the entries except "Tags" into
            // records_fields_data table---------

            // ----------------first we fetch rec_id from records_data

            int rec_id = 0;
            Cursor cursor = database.query("records_data",
                    new String[] { "rec_id" }, "rec_name=?",
                    new String[] { et_1.getText() + "" }, null, null, null);
            while (cursor.moveToNext()) {
                rec_id = cursor.getInt(0);
            }
            cursor.close();

            // ---------------use rec_id to insert into records_fields_data

            for (EditText e : et) {
                Tag tmp = (Tag) e.getTag();

                if (tmp.getName().equals("Tags")) {
                    continue;
                } else {
                    values.put("rec_id", rec_id);
                    values.put("cat_field_id", "0");
                    values.put("field_value", e.getText() + "");
                    values.put("is_delete", "0");
                    values.put("create_date", currentDate);
                    values.put("update_date", "0");

                    database.insert("records_fields_data", null, values);
                    values.clear();
                }
            }

            // --------now insert into record_tag_relation table

            if (selectedTags.size() != 0)
                for (CharSequence s : selectedTags) {
                    values.put("cat_id", cat_id);
                    values.put("tag_id", get_tag_id(s));
                    database.insert("record_tag_relation", null, values);
                    values.clear();
                }
        }
    });

    spinner = (Spinner) findViewById(R.id.spinnerAddRecords);
    cat_field_list = new ArrayList<String>();
    build_spinner_list();
    spinner.setOnItemSelectedListener(new OnItemSelectedListener() {

        @Override
        public void onItemSelected(AdapterView<?> arg0, View arg1,
                int arg2, long arg3) {

            cat_id = getId(arg0.getItemAtPosition(arg2) + "");
            generateUI(arg0.getItemAtPosition(arg2) + "");
        }

        @Override
        public void onNothingSelected(AdapterView<?> arg0) {

        }
    });
}

public int get_tag_id(CharSequence s) {

    int tag_id = 0;
    Cursor cursor = database.query("tags", new String[] { "tag_id" },
            "tag_name=?", new String[] { s + "" }, null, null, null);
    while (cursor.moveToNext()) {
        tag_id = cursor.getInt(0);
    }

    return tag_id;
}

protected void showSelectTagsDialog() {

    boolean[] checkedTags = new boolean[tags.length];
    int count = tags.length;

    for (int i = 0; i < count; i++)
        checkedTags[i] = selectedTags.contains(tags[i]);

    DialogInterface.OnMultiChoiceClickListener tagsDialogListener = new DialogInterface.OnMultiChoiceClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which,
                boolean isChecked) {
            if (isChecked)
                selectedTags.add(tags[which]);
            else
                selectedTags.remove(tags[which]);

            onChangeSelectedTags();
        }
    };

    AlertDialog.Builder builder = new AlertDialog.Builder(this);
    builder.setTitle("Select Tag(s)");
    builder.setMultiChoiceItems(tags, checkedTags, tagsDialogListener);
    builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int id) {
            dialog.dismiss();
        }
    });

    AlertDialog dialog = builder.create();
    dialog.show();
}

public void onChangeSelectedTags() {

    StringBuilder stringBuilder = new StringBuilder();

    for (CharSequence tag : selectedTags)
        stringBuilder.append(tag + ",");

    Tag tmp_tag = null;
    for (EditText e : et) {

        tmp_tag = (Tag) e.getTag();
        // Toast.makeText(getBaseContext(), e.getText()+"",
        // Toast.LENGTH_SHORT).show();
        if (tmp_tag.getName().equals("Tags")) {
            e.setText(stringBuilder.toString());
        }
    }
}

private void build_tags_list() {

    loadDatabase();

    tags_list = new ArrayList<String>();
    Cursor cursor = database.query("tags", new String[] { "tag_name" },
            null, null, null, null, null);
    while (cursor.moveToNext())
        tags_list.add(cursor.getString(0));
    cursor.close();
    database.close();

    tags = tags_list.toArray(new String[tags_list.size()]);
}

private void build_spinner_list() {
    loadDatabase();

    spinner_list = new ArrayList<String>();
    spinner_list.add("Category");
    Cursor cursor = database.query("category",
            new String[] { "cat_description" }, null, null, null, null,
            null);
    while (cursor.moveToNext())
        spinner_list.add(cursor.getString(0));
    cursor.close();
    ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this,
            android.R.layout.simple_list_item_1, spinner_list);
    dataAdapter
            .setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    spinner.setAdapter(dataAdapter);
    database.close();
}

protected int getId(String string) {

    loadDatabase();

    int tmp_cat_id = 0;
    Cursor cursor = database.query("category", new String[] { "cat_id" },
            "cat_description=?", new String[] { string }, null, null, null);
    while (cursor.moveToNext())
        tmp_cat_id = cursor.getInt(0);
    cursor.close();
    database.close();

    return tmp_cat_id;
}

protected void generateUI(String string) {

    if (string.equals("Category")) {
        Toast.makeText(getBaseContext(),
                "Select the category to proceed further.",
                Toast.LENGTH_SHORT).show();
        for (EditText e : et)
            e.setVisibility(View.GONE);
        for (TextView t : tv)
            t.setVisibility(View.GONE);
        btn_save.setVisibility(View.GONE);
    }

    else {
        loadDatabase();
        cat_field_list.clear();

        // ----------------fetch id of item selected in spinner

        // int cat_id = 0;
        // Cursor cursor = database.query("category",
        // new String[] { "cat_id" }, "cat_description=?",
        // new String[] { string }, null, null, null);
        // while (cursor.moveToNext())
        // cat_id = cursor.getInt(0);
        // cursor.close();

        // ----------------fetch cat_fields of the selected item in the
        // spinner

        Cursor cursor = database.query("category_fields",
                new String[] { "field_name" }, "cat_id=?",
                new String[] { cat_id + "" }, null, null, null);
        while (cursor.moveToNext())
            cat_field_list.add(cursor.getString(0));
        cursor.close();

        // -------------sort list in the format "Description",.....Rest of
        // the fields.....,"Notes","Tags"

        ArrayList<String> al_new_cat_field_id_list = new ArrayList<String>();
        al_new_cat_field_id_list = sort_list(cat_field_list);

        for (int i = 0; i < al_new_cat_field_id_list.size(); i++) {
            tv[i].setVisibility(View.VISIBLE);
            tv[i].setText(al_new_cat_field_id_list.get(i));
            et[i].setVisibility(View.VISIBLE);
            et[i].setTag(new Tag(cat_id,
                    get_cat_field_id(al_new_cat_field_id_list.get(i)),
                    al_new_cat_field_id_list.get(i)));

            if (al_new_cat_field_id_list.get(i).equals("Tags")) {
                et[i].setFocusable(false);
                et[i].setFocusableInTouchMode(false);
                et[i].setOnClickListener(new OnClickListener() {

                    @Override
                    public void onClick(View v) {

                        showSelectTagsDialog();
                    }
                });
            }

            Tag tmp = (Tag) et[i].getTag();
            Toast.makeText(
                    getBaseContext(),
                    "cat_id: " + tmp.getCat_id() + ", cat_field_id: "
                            + tmp.getCat_field_id() + ", name: "
                            + tmp.getName(), Toast.LENGTH_SHORT).show();
        }

        btn_save.setVisibility(View.VISIBLE);
        database.close();
    }
}

private ArrayList<String> sort_list(ArrayList<String> cat_field_list2) {

    int count = 0;
    ArrayList<String> al_tmp = new ArrayList<String>();
    for (String s : cat_field_list2) {
        if (s.equals("Description")) {
            if (al_tmp.contains(s)) {
                // ----do nothing
            } else {
                al_tmp.add(s);
            }
        } else if (s.equals("Notes")) {
            continue;
        } else if (s.equals("Tags")) {
            continue;
        } else {
            if (al_tmp.contains(s)) {
                // ----do nothing
            } else {
                al_tmp.add(s);
            }
        }
        count++;
        if (count == cat_field_list.size() - 2) {
            al_tmp.add("Notes");
            al_tmp.add("Tags");
        }
    }
    return al_tmp;
}

private int get_cat_field_id(String string) {

    loadDatabase();

    int tmp_cat_field_id = 0;
    Cursor cursor = database.query("category_fields",
            new String[] { "cat_field_id" }, "field_name=?",
            new String[] { string }, null, null, null);
    while (cursor.moveToNext())
        tmp_cat_field_id = cursor.getInt(0);
    cursor.close();
    database.close();

    return tmp_cat_field_id;
}

private void loadDatabase() {
    database = openOrCreateDatabase("WalletAppDatabase.db",
            SQLiteDatabase.OPEN_READWRITE, null);
}

public class Tag {
    int cat_id;
    int cat_field_id;
    String name;

    public Tag(int tmp_cat_id, int tmp_cat_field_id) {

        cat_id = tmp_cat_id;
        cat_field_id = tmp_cat_field_id;
    }

    public Tag(int tmp_cat_id, int tmp_cat_field_id, String tmp_name) {

        name = tmp_name;
        cat_id = tmp_cat_id;
        cat_field_id = tmp_cat_field_id;
    }

    int getCat_id() {
        return cat_id;
    }

    int getCat_field_id() {
        return cat_field_id;
    }

    String getName() {
        return name;
    }

}

@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
    if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
        finish();
        startActivity(new Intent(AddRecords.this, AllRecords.class));
        return true;
    }
    return super.onKeyDown(keyCode, event);
}
}

这是我的logcat输出:

    03-21 18:27:09.790: D/AndroidRuntime(32189): Shutting down VM
03-21 18:27:09.790: W/dalvikvm(32189): threadid=1: thread exiting with uncaught exception (group=0x4001d800)
03-21 18:27:09.821: E/AndroidRuntime(32189): FATAL EXCEPTION: main
03-21 18:27:09.821: E/AndroidRuntime(32189): java.lang.NullPointerException
03-21 18:27:09.821: E/AndroidRuntime(32189):    at com.walletapp.AddRecords.onChangeSelectedTags(AddRecords.java:241)
03-21 18:27:09.821: E/AndroidRuntime(32189):    at com.walletapp.AddRecords$3.onClick(AddRecords.java:211)
03-21 18:27:09.821: E/AndroidRuntime(32189):    at com.android.internal.app.AlertController$AlertParams$4.onItemClick(AlertController.java:886)
03-21 18:27:09.821: E/AndroidRuntime(32189):    at android.widget.AdapterView.performItemClick(AdapterView.java:284)
03-21 18:27:09.821: E/AndroidRuntime(32189):    at android.widget.ListView.performItemClick(ListView.java:3382)
03-21 18:27:09.821: E/AndroidRuntime(32189):    at android.widget.AbsListView$PerformClick.run(AbsListView.java:1696)
03-21 18:27:09.821: E/AndroidRuntime(32189):    at android.os.Handler.handleCallback(Handler.java:587)
03-21 18:27:09.821: E/AndroidRuntime(32189):    at android.os.Handler.dispatchMessage(Handler.java:92)
03-21 18:27:09.821: E/AndroidRuntime(32189):    at android.os.Looper.loop(Looper.java:123)
03-21 18:27:09.821: E/AndroidRuntime(32189):    at android.app.ActivityThread.main(ActivityThread.java:4627)
03-21 18:27:09.821: E/AndroidRuntime(32189):    at java.lang.reflect.Method.invokeNative(Native Method)
03-21 18:27:09.821: E/AndroidRuntime(32189):    at java.lang.reflect.Method.invoke(Method.java:521)
03-21 18:27:09.821: E/AndroidRuntime(32189):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
03-21 18:27:09.821: E/AndroidRuntime(32189):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
03-21 18:27:09.821: E/AndroidRuntime(32189):    at dalvik.system.NativeStart.main(Native Method)
03-21 18:27:11.730: I/Process(32189): Sending signal. PID: 32189 SIG: 9

2 个答案:

答案 0 :(得分:0)

我真的不知道,但你可以尝试以下方法:不要使用增强的for循环,尝试通常的for循环:

    public void onChangeSelectedTags() {

StringBuilder stringBuilder = new StringBuilder();

for (CharSequence tag : selectedTags)
    stringBuilder.append(tag + ",");

Tag tmp_tag = null;
for (int i=0;i<et.length;i++) {

    tmp_tag = (Tag) et[i].getTag();
    // Toast.makeText(getBaseContext(), e.getText()+"",
    // Toast.LENGTH_SHORT).show();
    if (tmp_tag.getName().equals("Tags")) {
        e.setText(stringBuilder.toString());
    }
}
 }

错误是否仍然存在?

答案 1 :(得分:0)

我得到了答案,,,这里是如何...... 我正在通过“setTag()”将标签设置为前5个EditTexts和我的增强型for循环 ,我试图获得第6个(依此类推)EditText的标签,当我从未设置那些标签时,我将如何获得这些标签。 我唯一的错误是,我忘了在我的if循环中插入“break”...感谢你们的支持......