简体   繁体   中英

Android | JAVA | Cannot Access Variable returned by a method

I have a system of arduino which sends back "1" when browsing "10.0.0.1/connection". I am storing that "1" into a variable called 'value' and accessing it in another method. While accessing value in another method it gives null pointer exception.

Description:

This is the method which loads url and store's whatever source code i receive into a variable.

public String getConnection()
    {
        String []value = new String[1];
        String con = "http://10.0.0.1/connection";
        Ion.with(getApplicationContext()).load(con).asString().setCallback(new FutureCallback<String>() {

            @Override
            public void onCompleted(Exception e, String result) {
                int i = Integer.parseInt(result);
                conFlag = i;
                tv.setText(result);
                tv.setVisibility(View.VISIBLE);
                if(i == 1){
                    value[0] = result;
                Log.d("vol ",value[0]);
              }
            }
        });
    return value[0];
    }

Here as you can see I printed log which will print value[0] if i==1 . And I set conFlag = i .

Here I am getting the value which is returned by getConnection()

@Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults)
    {
        Log.d("onRequestPermissionsResult() ->", " called");
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == 1) {
            Log.d("onRequestPermissionsResult() ->", " requestCode = 1");
            if (grantResults.length >0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                //do your thing
                info = wifiManager.getConnectionInfo();
                if (info.getSSID().trim().equals(ssid)){
                    String conct = getConnection();
                    Log.d("vol conct", conct);
                    if (conFlag == 1){
                        startActivity(new Intent(SplashScreen.this,MainActivity.class));
                    }
                }
                else {
                    Log.d("Value","Not found");
          
                }
                Log.d("onRequestPermissionsResult() ->", " Permissions Granted");

            }
        }

    }

Here I am getting exception of nullPointer on "Log.d("vol conct", conct);". Logs

E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.ims_temp_1, PID: 6670
    java.lang.RuntimeException: Failure delivering result ResultInfo{who=@android:requestPermissions:, request=1, result=-1, data=Intent { act=android.content.pm.action.REQUEST_PERMISSIONS (has extras) }} to activity {com.example.ims_temp_1/com.example.ims_temp_1.SplashScreen}: java.lang.NullPointerException: println needs a message
        at android.app.ActivityThread.deliverResults(ActivityThread.java:5143)
        at android.app.ActivityThread.handleSendResult(ActivityThread.java:5184)
        at android.app.servertransaction.ActivityResultItem.execute(ActivityResultItem.java:51)
        at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:140)
        at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:100)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2222)
        at android.os.Handler.dispatchMessage(Handler.java:107)
        at android.os.Looper.loop(Looper.java:228)
        at android.app.ActivityThread.main(ActivityThread.java:7782)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:981)
     Caused by: java.lang.NullPointerException: println needs a message
        at android.util.Log.println_native(Native Method)
        at android.util.Log.d(Log.java:155)
        at com.example.ims_temp_1.SplashScreen.onRequestPermissionsResult(SplashScreen.java:88)
        at android.app.Activity.dispatchRequestPermissionsResult(Activity.java:8458)
        at android.app.Activity.dispatchActivityResult(Activity.java:8308)

If I don't call the method getConnection() and do not use it's returned value then it is printing Log of value[0] as 1 . Which means whatever string i received is parsed as int and compared with int 1 . I am not able to use that i or conFlag in onRequestPermissionsResult() method.

Create an interface for Result like this:

public interface ResultCallback {
    public void result(String value);
}

update your getConnection method like this:

public void getConnection(ResultCallback callback)
    {
        String []value = new String[1];
        String con = "http://10.0.0.1/connection";
        Ion.with(getApplicationContext()).load(con).asString().setCallback(new FutureCallback<String>() {
            @Override
            public void onCompleted(Exception e, String result) {
                int i = Integer.parseInt(result);
                conFlag = i;
                tv.setText(result);
                tv.setVisibility(View.VISIBLE);
                if(i == 1){
                    value[0] = result;
                    Log.d("vol ",value[0]);
                    callback.result(value[0]);
                }
            }
        });
    }

and your onRequestPermissionsResult like this:

@Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults)
    {
        Log.d("onRequestPermissionsResult() ->", " called");
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == 1) {
            Log.d("onRequestPermissionsResult() ->", " requestCode = 1");
            if (grantResults.length >0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                //do your thing
                info = wifiManager.getConnectionInfo();
                if (info.getSSID().trim().equals(ssid)){
                    getConnection(new ResultCallback() {
                        @Override
                        public void result(String value) {
                            Log.d("vol conct", value);
                            if (conFlag == 1){
                                startActivity(new Intent(SplashScreen.this,MainActivity.class));
                            }
                        }
                    });
                }
                else {
                    Log.d("Value","Not found");

                }
                Log.d("onRequestPermissionsResult() ->", " Permissions Granted");

            }
        }

    }

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