2016-12-02 7 views
0

画面がロックされていないときにトーストを表示しようとしています。しかし、(EditTextにテキストを入力しても)空のトーストが表示されます。私は何をすべきか?そのうちトーストにテキストを表示しなかったためToastにテキストがありません

package com.example.hpi5.myapplication; 

import android.support.v7.app.AppCompatActivity; 
import android.os.Bundle; 
import android.widget.Button; 
import android.widget.EditText; 
import android.content.Intent; 
import android.content.IntentFilter; 
import android.view.View; 
import android.content.BroadcastReceiver; 
import android.content.Context; 
import android.widget.Toast; 

public class MainActivity extends AppCompatActivity { 

    Button button = null; 
    MyReceiver receiver = null; 
    EditText editText = null; 
    String text; 

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

     receiver = new MyReceiver(); 

     editText = (EditText) findViewById(R.id.editText); 
     text = editText.getText().toString(); 

     button = (Button) findViewById(R.id.button); 
     button.setOnClickListener(new View.OnClickListener() 
     { 
      @Override 
      public void onClick(View v) 
      { 
       Intent intent = new Intent(); 
       intent.setAction("my.action.string"); 
       intent.putExtra("str",text); 
       sendBroadcast(intent); 
      } 
     }); 

     IntentFilter filter = new IntentFilter(); 
     filter.addAction(Intent.ACTION_USER_PRESENT); 
     filter.addAction("my.action.string"); 
     this.registerReceiver(receiver, filter); 
    } 

    public class MyReceiver extends BroadcastReceiver 
    { 
     private String te ; 
     @Override 
     public void onReceive(Context context, Intent intent) 
     { 
      if (intent.getAction().equals("my.action.string")) { 
       te = intent.getExtras().getString("str"); 
      } 

      if (intent.getAction().equals(Intent.ACTION_USER_PRESENT)) { 
       Toast.makeText(context,te , Toast.LENGTH_LONG).show(); 
      } 

     } 
    } 

    @Override 
    protected void onDestroy() 
    { 
     if(receiver!=null) 
      this.unregisterReceiver(receiver); 
    } 
} 
+0

コメントは議論の対象外です。この会話は[チャットに移動]されています(http://chat.stackoverflow.com/rooms/129751/discussion-on-question-by-rayan-i-am-trying-to-display-a-toast-whenever- the-scre)。 –

+0

私はプロセスが終了する可能性があることを理解していますが、記事によると、アプリケーションは以前と同じように再開します。 – rayan

答えて

1

は、私はいくつかのミスを犯した。(私はその時点でのAndroidのプログラミングに新しいだった)私が作った何の過ち

  • データを保存するのにShared Preferencesを使用しませんでした。
  • 私の受信機は動的に登録されています。トーストは、アプリの実行中またはバックグラウンドでのみ表示されました。
  • EditTextの中にテキストを入力した後、私はアプリケーションを閉じて最近のアプリから削除しました。その後、私は再びのアプリケーションを開いて、それの新しいインスタンスを作成しました。そこにあると思ったデータは実際にはであり、トーストにはテキストがありませんでした。

私は彼の辛抱強さと助けに感謝します。

関連する問題