okhttpclient在尝试从SharedReferences加载数据时引发错误

jljoyd4f  于 2021-08-20  发布在  Java
关注(0)|答案(1)|浏览(422)

我正在制作一个控制esp模块的应用程序,我正在使用okhttpclient发出post web请求。您可以在设置选项卡中设置esp模块的ip(例如,如果您的esp ip为123.456.789,则web请求的url为http://123.456.789),我正在使用SharedReferences将设置活动中的数据保存、加载并获取到主活动中,但当我打开应用程序时,它会崩溃,错误url==null。
我让它工作的唯一方法是加载如下内容:

public String ip = SettingsActivity.ipEsp;

但是,每次我重新打开应用程序时,我都必须打开要加载数据的设置活动。(尝试使用SharedReferences保存此值,但它似乎不起作用,没有崩溃或任何不起作用的东西)
我想让它以某种方式保存,这样每当我重新打开应用程序时,它就会记住我在设置中设置的ip地址。
以下是主要活动代码:

public class MainActivity extends AppCompatActivity {

    Button settings;
    Button send;
    TextView view;
    TextView see;
    public String urlS;

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

        settings = (Button) findViewById(R.id.button);
        send = (Button) findViewById(R.id.button2);
        view = (TextView) findViewById(R.id.textView);
        see = (TextView) findViewById(R.id.see);

        SharedPreferences urls = getSharedPreferences("sPrefs", MODE_PRIVATE);

        urlS = urls.getString("url", "http://0.0.0.0:8888");

        send.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {

            client.newCall(requestlL).enqueue(new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {

                }

                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    if (response.isSuccessful()){
                        String myR = response.body().string();

                        MainActivity.this.runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                see.setText(myR);
                            }
                        });
                    }
                }
            });

                view.setText(urlS);
            }

        }
        );

        settings.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
            setting();
            }
        });

    }

    OkHttpClient client = new OkHttpClient();

    String urllL = urlS;

    Request requestlL = new Request.Builder()
            .url(urllL)
            .build();

    public void setting() {
        Intent intent = new Intent(this, MainActivity2.class);
        startActivity(intent);
    }

}

这是设置活动代码:

public class MainActivity2 extends AppCompatActivity {

private Handler sHand = new Handler();
public static final String S_PREFS = "sPrefs";
public static final String URL = "url";

Button back;
Button save;
EditText url;

public String urlS;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main3);
    back = (Button) findViewById(R.id.button3);
    save = (Button) findViewById(R.id.button4);
    url = (EditText) findViewById(R.id.edit);

    back.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            back();
        }
    });

    save.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            urlS = url.getText().toString();
            save();

        }
    });

    load();
    view();

}

public void back()
{
    Intent intent = new Intent(this, MainActivity.class);
    startActivity(intent);
}

public void saveDataRunS()
{
    sHand.post(saveDs);
}

private Runnable saveDs= new Runnable() {
    @Override
    public void run() {
        save();
        load();

        sHand.postDelayed(this, 1);

    }

};

public void save()
{
    SharedPreferences sharedPreferences = getSharedPreferences("sPrefs", MODE_PRIVATE);
    SharedPreferences.Editor edit = sharedPreferences.edit();

    edit.putString(URL, url.getText().toString());

    edit.apply();
}

public void load()
{
    SharedPreferences sharedPreferences = getSharedPreferences(S_PREFS, MODE_PRIVATE);
    urlS = sharedPreferences.getString(URL, "http://0.0.0.0:8888");

}

public void view()
{
    url.setText(urlS);

}

}
这就是我得到的错误:

E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.test, PID: 18146
java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.test/com.example.test.MainActivity}: java.lang.NullPointerException: url == null
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3222)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3437)
    at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:83)
    at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
    at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2041)
    at android.os.Handler.dispatchMessage(Handler.java:107)
    at android.os.Looper.loop(Looper.java:214)
    at android.app.ActivityThread.main(ActivityThread.java:7386)
    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:980)
 Caused by: java.lang.NullPointerException: url == null
    at okhttp3.Request$Builder.url(Request.java:132)
    at com.example.test.MainActivity.<init>(MainActivity.java:99)
    at java.lang.Class.newInstance(Native Method)
    at android.app.AppComponentFactory.instantiateActivity(AppComponentFactory.java:95)
    at androidx.core.app.CoreComponentFactory.instantiateActivity(CoreComponentFactory.java:45)
    at android.app.Instrumentation.newActivity(Instrumentation.java:1250)
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3210)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3437) 
    at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:83) 
    at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135) 
    at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95) 
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2041) 
    at android.os.Handler.dispatchMessage(Handler.java:107) 
    at android.os.Looper.loop(Looper.java:214) 
    at android.app.ActivityThread.main(ActivityThread.java:7386) 
    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:980) 
gopyfrb3

gopyfrb31#

@leeo6002在mainactivity2中,save()方法的调用方式如下。oncreate->savedataruns->shand.post(saveds)->save->edit.putstring(url,url.gettext().tostring());
基本上,只要触发活动的oncreate,就可以从url edittext获取值。这意味着您没有等待用户在edittext中输入值。至少,这是问题之一。
老实说,你需要清理你的代码,它现在是一个很大的混乱。

相关问题