简体   繁体   中英

New onClickListener with NullPointerException (Android)

I create a few textViews with onClickListeners at run time.

But I get a NullPointer.. . I think the reason is the View, he dosnt know where the textView should be.

How could I solve this?

The interesting lines of the class ShowSomething :

textView.setOnClickListener(new OnClickListener() {

    @Override
    public void onClick(View v) {

        Toast.makeText(ShowSomething.this, textView.getText().toString(), Toast.LENGTH_LONG).show();
        }
    });
    layout.addView(t);

Full class ShowSomething :

public class ShowSomething extends Activity {

    public void showData(final String[][] array, final int i, int j, LinearLayout layout, final TextView t, TextView t2, int color) {
        String Text = null;
        int size = 12;
        int top = 0;
        int bot = 0;

        if (j == 0) {
            size = 14;
            Text = array[j][i];
            top = 5;
            bot = 0;

        }
        if (j == 1) {
            size = 10;
            Text = "  " + array[j][i];
            top = 5;
            bot = 5;
        }
        t.setTextSize(TypedValue.COMPLEX_UNIT_DIP, size);
        t.setTextColor(color);
        t.setPadding(0, top, 0, bot);
        t.setClickable(false);
        t.setText(Text);
        t.setId(j + i);
        t.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {

                Toast.makeText(ShowSomething.this, t.getText().toString(), Toast.LENGTH_LONG).show();
            }
        });
        layout.addView(t);
    }
}

The interesting lines of the class ProjectsActivity :

    setContentView(R.layout.activity_projects);
    int j = 0;
    //result    
    for (i = 0; i < array[0].length; i++) {
        while (j <2) {
            LinearLayout layout = (LinearLayout) findViewById(R.id.mainLayout);
            final TextView t = new TextView(getApplicationContext());
            final TextView t2 = new TextView(getApplicationContext());
            ShowSomething.showData(array, i, j, layout, t, t2, color);

Full class ProjectsActivity :

public class ProjectsActivity extends Activity {
public String[][] array = null;
public int i = 0;
int color;
ShowSomething show = new ShowSomething();
@SuppressLint("NewApi")
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_projects);

    int j = 0;

    array = Connect.printJobList();

    for (i = 0; i < array[0].length; i++) {
        while (j < 2) {
            LinearLayout layout = (LinearLayout) findViewById(R.id.mainLayout);
            final TextView t = new TextView(getApplicationContext());
            final TextView t2 = new TextView(getApplicationContext());

            if (j == 0){    
                color = getResources().getColor(R.color.Project1);
            }
            if (j == 1){
                color = getResources().getColor(R.color.Project2);
            }

            show.showData(array, i, j, layout, t, t2, color);
            if (j == 1){
                t2.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, 1));
                t2.setBackgroundColor(getResources().getColor(R.color.Line));
                layout.addView(t2);
            }
            j++;
        }
        j = 0;
    }       
}

}

LogCat :

03-26 08:19:38.294: D/AndroidRuntime(1991): Shutting down VM
03-26 08:19:38.294: W/dalvikvm(1991):       threadid=1: thread exiting with uncaught exception (group=0x414c4700)
03-26 08:19:38.332: E/AndroidRuntime(1991): FATAL EXCEPTION: main
03-26 08:19:38.332: E/AndroidRuntime(1991): java.lang.NullPointerException
03-26 08:19:38.332: E/AndroidRuntime(1991):     at android.app.Activity.setContentView(Activity.java:1895)
03-26 08:19:38.332: E/AndroidRuntime(1991):     at de.xcom.mobilenav.ShowSomething$1.onClick(ShowSomething.java:47)
03-26 08:19:38.332: E/AndroidRuntime(1991):     at android.view.View.performClick(View.java:4240)
03-26 08:19:38.332: E/AndroidRuntime(1991):     at android.view.View$PerformClick.run(View.java:17721)
03-26 08:19:38.332: E/AndroidRuntime(1991):     at android.os.Handler.handleCallback(Handler.java:730)
03-26 08:19:38.332: E/AndroidRuntime(1991):     at android.os.Handler.dispatchMessage(Handler.java:92)
03-26 08:19:38.332: E/AndroidRuntime(1991):     at android.os.Looper.loop(Looper.java:137)
03-26 08:19:38.332: E/AndroidRuntime(1991):     at android.app.ActivityThread.main(ActivityThread.java:5103)
03-26 08:19:38.332: E/AndroidRuntime(1991):     at java.lang.reflect.Method.invokeNative(Native Method)
03-26 08:19:38.332: E/AndroidRuntime(1991):     at java.lang.reflect.Method.invoke(Method.java:525)
03-26 08:19:38.332: E/AndroidRuntime(1991):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
03-26 08:19:38.332: E/AndroidRuntime(1991):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
03-26 08:19:38.332: E/AndroidRuntime(1991):     at dalvik.system.NativeStart.main(Native Method)

Line 47 of ShowSomething : (ignore the comments)

43 public void onClick(View v) { 
44 //Intent intent = new Intent(ShowSomething.this, ProjectDetailActivity.class); 
45 //intent.putExtra("Project", array[0][i]); 
46   
47 //startActivity(intent); 
48 
49 Toast.makeText(ShowSomething.this, t.getText().toString(), Toast.LENGTH_LONG).show();

Changed the class ShowSomething :

public class ShowSomething {
.
.
.   t.setOnClickListener(new OnClickListener() {

    @Override
    public void onClick(View v) {
        Intent intent = new Intent(ShowSomething.this, ProjectDetailActivity.class);
        intent.putExtra("Project", array[0][i]);

        startActivity(intent);

        //Toast.makeText(getApplicationContext() , t.getText().toString(), Toast.LENGTH_LONG).show();
        }
    });

But now I get an error: The contructor Intent(ShowSomething, Class) is undefined...

ShowSomething show = new ShowSomething();

You cannot instantiate activities with new .

Looks like ShowSomething should not be an activity at all. You can pass a Context to it as a method argument, for example.

To pass data from an activity to another, use intents. See How do I pass data between Activities in Android application?

Maybe you have a problem with the context, first argument of the .makeText. You need to check in which line you have the NPE. Look at the LogCat window, you will see something like:

Caused by: java.lang.NullPointerException at yourpackagename.ShowSomething.showData(ShowSomething.java:123)

Then you will know where you have the NPE, or just ask further.

After Edit:

So you're trying to start an Intent now withou any context (ShowSomething isn't extendig activity right now)

You need to pass the Context to your ShowSomething class, maybe in constructor, and then use it:

public class ShowSomething {
...
Context mContext;

public ShowSomething(Context context){
   this.mContext=context;
}

calling: mContext.startActivity(intent); in the onClickListener

Creating your ShowSomething object then in your main activity:

ShowSomething myClass = new ShowSomething(getApplicationContext());

Toast.makeText(ShowSomething.this, t.getText().toString(), Toast.LENGTH_LONG).show();

Are you sure that t != null ?

首先,您必须像这样为textview创建对象:

TextView t=(TextView) findViewById(R.id.text);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM