如何仅在首次启动活动时设置变量

时间:2017-11-02 17:14:45

标签: java android api android-intent

我遇到了问题。这是一个String语言,我有MainActivity(A)和ChooseLanguageActivity(B)。从用户到B选择语言之后,他打算用A语言,语言从意图中获得价值。我需要为这个变量语言设置默认值。我试着在onCreate中使用它。但是每次创建活动时我都不需要使用默认值。我需要在app启动之后才使用它,此变量需要使用它从活动B intent获得的值。 那是代码

public class MainActivity extends AppCompatActivity {

    AppCompatButton chooseLanguageButton;
    AppCompatButton cleanButton;
    AppCompatEditText translatedTextOutput;
    AppCompatEditText translatedTextInput;
    String translatedInputString;
    RequestQueue requestQueue;
    SharedPreferences sPref;
    final String SAVED_TEXT = "saved_text";
    final String TAG = "myTag";
    String language;

    private ProgressBar progressBar;
    private Timer timer;

    private TextWatcher searchTextWatcher = new TextWatcher() {
        @Override
        public void afterTextChanged(Editable arg0) {
            timer = new Timer();
            timer.schedule(new TimerTask() {
                @Override
                public void run() {

                    if (translatedTextInput.getText().length() != 0){
                        try {
                            Thread.sleep(2000);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }

                        MainActivity.this.runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                requestQueue = Volley.newRequestQueue(MainActivity.this);
                                sendJsonRequest();
                            }
                        });
                    }
                     InputMethodManager in = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                     in.hideSoftInputFromWindow(translatedTextInput.getApplicationWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
                }
            }, 600);
        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            if (timer != null) {
                timer.cancel();
            }
        }
    };

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

        chooseLanguageButton = (AppCompatButton) findViewById(R.id.choose_language_button);
        cleanButton = (AppCompatButton) findViewById(R.id.clean_button);
        translatedTextOutput = (AppCompatEditText) findViewById(R.id.translated_text_field);
        translatedTextInput = (AppCompatEditText) findViewById(R.id.translation_input_edit);
        translatedTextInput.addTextChangedListener(searchTextWatcher);

        chooseLanguageButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                saveText();
                Intent intent = new Intent(MainActivity.this, ChooseLanguageList.class);
                startActivity(intent);
            }
        });

        cleanButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                translatedTextInput.setText("");
                translatedTextOutput.setText("");
            }
        });

        loadText();
    }

    @Override
    protected void onDestroy() {

        super.onDestroy();
        sPref = null;
    }

    void saveText() {
        sPref = getPreferences(MODE_PRIVATE);
        SharedPreferences.Editor ed = sPref.edit();
        ed.putString(SAVED_TEXT, translatedTextInput.getText().toString());
        ed.commit();
        Toast.makeText(this, "Text saved", Toast.LENGTH_SHORT).show();
    }

    void loadText() {
        sPref = getPreferences(MODE_PRIVATE);
        String savedText = sPref.getString(SAVED_TEXT, "");
        translatedTextInput.setText(savedText);
        Toast.makeText(this, "Text loaded", Toast.LENGTH_SHORT).show();
    }


    public void sendJsonRequest() {
        Intent myIntent = getIntent();
        language = myIntent.getStringExtra("short");
        Log.v(getClass().getSimpleName(), "language short = " + language);
        translatedInputString = translatedTextInput.getText().toString().replace(" ","+");
        String url = String.format(getApplicationContext().getResources().getString(R.string.request_template),
                String.format(getApplicationContext().getResources().getString(R.string.query_Template), translatedInputString, language ));
        JsonObjectRequest jsObjRequest = new JsonObjectRequest
        (Request.Method.GET, url, null, new Response.Listener<JSONObject>() {

            @Override
            public void onResponse(JSONObject response) {
                Log.v(TAG, "Inside OnResponse" + response.toString());
                JSONArray results = null;
                try {
                    results = response.getJSONObject("data").getJSONArray("translations");
                    for (int i=0,j=results.length();i<j;i++) {
                        String webTitle = results.getJSONObject(i).getString("translatedText");
                        translatedTextOutput.setText(webTitle);
                    }
                } catch (JSONException e) {
                    Log.e(TAG, "Error :" + e);
                    e.printStackTrace();
                }
            }
        }, new Response.ErrorListener() {

            @Override
            public void onErrorResponse(VolleyError error) {
                if (error instanceof NetworkError) {
                    Log.e(TAG, "NetworkError");
                } else if (error instanceof ServerError) {
                    Log.e(TAG, "The server could not be found. Please try again after some time!!");
                } else if (error instanceof AuthFailureError) {
                    Log.e(TAG, "AuthFailureError");
                } else if (error instanceof ParseError) {
                    Log.e(TAG, "Parsing error! Please try again after some time!!");
                } else if (error instanceof NoConnectionError) {
                    Log.e(TAG, "NoConnectionError!");
                } else if (error instanceof TimeoutError) {
                    Log.e(TAG, "Connection TimeOut! Please check your internet connection.");
                }
            }
        });
        requestQueue.add(jsObjRequest);
    }

}

嗯。我不明白-1。如果你至少写了-1评论什么是错误的问题,不要在下次重复这个错误。

3 个答案:

答案 0 :(得分:1)

简答:在SharedPreferences

上保存布尔活动

当应用启动时,始终将变量设为false。在活动的onCreate里面说的是真的,那么你可以使用:

if (activityWasLauched == false){
  //use the default
}
else{
  //use a bundle and get the value from an intent
}

尽可能简化SharedPreferences的使用: 要在共享首选项中存储值:

SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sp.edit();
if(score > high_score)
{
    editor.putInt("high_score", score);
    editor.apply();  /* Edit the value here*/
}

从共享首选项中检索值:

SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
String high_score= sp.getInt("high_score", "");

答案 1 :(得分:0)

请记住,变量存储在内存中,并在应用停止运行时销毁。要永久存储值,需要将其保存到磁盘。对于简单值,SharedPreferences是可行的方法。应用程序启动时,您应该从languages加载SharedPreferences的值。如果不存在此值,请保存默认值,以便下次启动应用程序时,它只读取值。如果应用中的某些内容更改了此变量的值(例如用户操作),请务必保存新值,以便下次应用启动时该值正确。

答案 2 :(得分:0)

希望我理解你......

<强>首先

启动你的&#34; ChooseLanguageList&#34;使用startActivityForResult()

的活动
Intent intent = new Intent(MainActivity.this, ChooseLanguageList.class);
startActivityForResult(intent, ANY_REQUEST_CODE);

<强>第二

在你的&#34; ChooseLanguageList&#34;将语言返回结果设置为&#34; MainActivity&#34;使用设置结果

    Intent returnIntent = new Intent();
    returnIntent.putExtra(MY_LANG_EXTRA, language);
    setResult(Activity.RESULT_OK, returnIntent);
    finish();

<强>第三

返回&#34; MainActivity&#34; ..使用onActivityResult捕获返回的结果

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == ANY_REQUEST_CODE && resultCode == Activity.RESULT_OK) {
    language = data.getStringExtra(MY_LANG_EXTRA);
    /* Save language in Shared Preferences */
}

<强>第四:

将检索到的语言保存在共享首选项

SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sp.edit();
editor.putInt(/*Key:*/"my_lang", /*value:*/language);
editor.apply();

<强>第五:

现在每次你想要使用语言时(例如在onCreate()中),只需从共享首选项中检索它,并在找不到默认值时

String language = sp.getString(/*Key:*/"my_lang", "en/*Default value*/");

现在每次&#34; MainActivity&#34;启动它将尝试使用密钥&#34; my_lang&#34;从共享首选项获取语言,但如果没有任何内容,它将回退到默认&#34; en&#34;直到从&#34; ChooseLanguageList&#34;中检索到新值。活性。

希望这能回答你的问题