简体   繁体   中英

How do I refer to any object in MainActivity from other class? and how do I avoid NullPointerException for referencing to any object

onPostExecute()-NullPointerException: Attempt to invoke v.method'android.view.Window$Callback android.view.Window.getCallback()'on a null object ref.

Null pointer Exception(onPostExecute()-NullPointerException: Attempt to invoke v.method'android.view.Window$Callback) on set method(MainActivity) or on postExecute methode(img load) appears.

I was trying to load an image and set it to the imageview in mainactivity. but I cant refer to that imageview.

I can't refer to that imageview from imageload class but I can refer to that from any method in mainactivity.

Here is MainActivity :

public class MainActivity extends AppCompatActivity {

ImageView imageView;
Context context;

TextView textView;

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

    imageView = (ImageView) findViewById(R.id.imageView);

    textView = (TextView) findViewById(R.id.textView);
}

    public void network(View view) {
        ConnectivityManager connMgr = (ConnectivityManager)
                getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
        if (networkInfo != null && networkInfo.isConnected()) {
            // fetch data
            Toast.makeText(this, "Network detected", Toast.LENGTH_SHORT).show();

            String stringUrl = "http://www.lorempixel.com/420/240/";
            new imgLoad().execute(stringUrl);

        } else {
            // display error

            Toast.makeText(this, "No network detected", Toast.LENGTH_SHORT).show();
//            textView.setText("No network connection available.");

        }


    }
public void set(Bitmap bitmap) {
    textView = (TextView) findViewById(R.id.textView);
    if (textView != null) {
        textView.setText("setting image..");
    }
    Toast.makeText(this, "setting..,", Toast.LENGTH_SHORT).show();

    if (imageView != null) {
        Toast.makeText(this, "good", Toast.LENGTH_SHORT).show();
        textView.setText("image not null..");

        imageView.setImageBitmap(bitmap);
    }else {
        textView.setText("null");
    }
}

Here references on set method are null and cant get reference on below class for ImageView.

Here is Imageloader class:

public class imgLoad extends AsyncTask<String, Void, Bitmap> {


@Override
protected Bitmap doInBackground(String... params) {
    return load(params[0]);


}

@Override
protected void onPostExecute(Bitmap bitmap) {
    super.onPostExecute(bitmap);
    MainActivity m = new MainActivity();
//        ImageView c = m.x();
            m.set(bitmap);
//        Toast.makeText(MainActivity.getContext(), "downloaded", Toast.LENGTH_SHORT).show();
//        if (c!=null) {
//            c.setImageBitmap(bitmap);
//        }

}

private Bitmap load(String param) {
    Bitmap bitmap = null;
        InputStream inputStream;
        try {
            URL url = new URL(param);
            HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
            httpURLConnection.setRequestMethod("Get");
            httpURLConnection.setConnectTimeout(4000);
            httpURLConnection.setReadTimeout(2000);
            httpURLConnection.setDoInput(true);
            httpURLConnection.connect();
            inputStream = httpURLConnection.getInputStream();
            bitmap = BitmapFactory.decodeStream(inputStream);


        } catch (MalformedURLException e) {

            Log.e("error", "wrong url : " + e.getMessage());

//            e.printStackTrace();
            } catch (IOException e) {
//            e.printStackTrace();
            Log.e("error", "failed : " + e.getMessage());
        }
    return bitmap;
}
}

Here is the Logcat:

12-13 10:15:53.234 28054-28127/com.facebook.mahmud.r.pixels E/error: failed : Expected one of [OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, PATCH] but was Get
12-13 10:15:53.347 28054-28054/com.facebook.mahmud.r.pixels D/AndroidRuntime: Shutting down VM
12-13 10:15:53.364 28054-28054/com.facebook.mahmud.r.pixels E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.facebook.mahmud.r.pixels, PID: 28054
java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.Window$Callback android.view.Window.getCallback()' on a null object reference
at android.support.v7.app.AppCompatDelegateImplBase.<init>(AppCompatDelegateImplBase.java:68)
at android.support.v7.app.AppCompatDelegateImplV7.<init>(AppCompatDelegateImplV7.java:145)
at android.support.v7.app.AppCompatDelegateImplV11.<init>(AppCompatDelegateImplV11.java:28)
at android.support.v7.app.AppCompatDelegateImplV14.<init>(AppCompatDelegateImplV14.java:41)
at android.support.v7.app.AppCompatDelegateImplV23.<init>(AppCompatDelegateImplV23.java:29)
at android.support.v7.app.AppCompatDelegate.create(AppCompatDelegate.java:186)
at android.support.v7.app.AppCompatDelegate.create(AppCompatDelegate.java:170)
at android.support.v7.app.AppCompatActivity.getDelegate(AppCompatActivity.java:502)
at android.support.v7.app.AppCompatActivity.findViewById(AppCompatActivity.java:174)
at com.facebook.mahmud.r.pixels.MainActivity.set(MainActivity.java:151)
at com.facebook.mahmud.r.pixels.imgLoad.onPostExecute(imgLoad.java:35)
at com.facebook.mahmud.r.pixels.imgLoad.onPostExecute(imgLoad.java:20)
at android.os.AsyncTask.finish(AsyncTask.java:651)
at android.os.AsyncTask.-wrap1(AsyncTask.java)
at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:668)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
12-13 10:15:56.700 28054-28054/com.facebook.mahmud.r.pixels I/Process: Sending signal. PID: 28054 SIG: 9

TIA.

Let's put your problem in proper format. When you ran your application you created an object for MainActivity . Let us call that mainActivityObject1 . From mainActivityObject1 you created an object for imgLoad class. In that after downloading the image you created yet another object for MainActivity (let's call it mainActivityObject2 ). Now you are trying to call the method mainActivityObject2.set(bitmap); where you should be calling mainActivityObject1.set(bitmap); .

You can solve this problem couple of ways. But the most basic one is by passing the activity context.

Create a constructor in imgLoad class and change your onPostExecute method like this:

private MainActivity mainActivityContext;
public imgLoad(MainActivity passedActivityContext){
    this.mainActivityContext = passedActivityContext;
}
@Override
protected Bitmap doInBackground(String... params) {
    return load(params[0]);
}
@Override
protected void onPostExecute(Bitmap bitmap) {
    super.onPostExecute(bitmap);
    mainActivityContext.set(bitmap);
}

From your MainActivity class when you do instantiate imgLoad pass your activity context like this:

new imgLoad(MainActivity.this).execute(stringUrl);

Now you when you call set(Bitmap bitmap) from imgLoad class it should call the original MainActivity object that created the imgLoad object.

Note:

I also noticed you are not calling network method in your MainActivity class that you posted in here. Do call it to test properly.

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