Domanda

My problem is the imageView will be null in showPicture(). I call this method from an other thread. If I remove the if (imageView != null)... condition, I will get a NullPointerException. Can you tell my Why? Thanks.

Activity java file:

public class ClientActivity extends Activity {

private ImageView imageView;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    requestWindowFeature(Window.FEATURE_NO_TITLE);
    getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
        WindowManager.LayoutParams.FLAG_FULLSCREEN);
    setContentView(R.layout.client);

    imageView = (ImageView) findViewById(R.id.image);
    imageView.setImageResource(R.drawable.p1);         //IT WORKS
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.client, menu);
    return true;
}

public void showPicture(final int ID) {
    if (imageView != null) {
        imageView.post(new Runnable() {

            @Override
            public void run() {
                imageView.setImageResource(ID);

            }
        });
    } else {        // It will be executed.
        System.out.println("WHY imageView IS NULL?!");
    }
}

Layout xml file:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <ImageView
        android:id="@+id/image"
        android:contentDescription="@string/content"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:src="@drawable/bg" />

</LinearLayout>

in strings.xml:

<string name="content">image</string>
È stato utile?

Soluzione

My program manage a socket based communication. When the client connect to the server socket this ClientActivity will be started: clientActivity = new ClientActivity(); Intent intent = new Intent(mainActivity, clientActivity.getClass());

Never instantiate activities with new. Either the classes should not be activities in the first place, or you should invoke them with an Intent.

The reason for the NPE is that onCreate() was not called on the activity you created yourself.

Altri suggerimenti

Try below code:-

    setContentView(R.layout.client);
    imageView = (ImageView) findViewById(R.id.image);
    imageView.setImageResource(R.drawable.p1);

    //after this use function show picture
    showPicture(id);

you have to call your function after setContentView because after setContentView layout content initialize.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top