I want to pass info as shown in this picture screen description
I know that my code is working, becuase with one Intent it works perfectley. However, when I try to put two or more Intents it seems to get messed up. I also checked here to find a sutibale solution, but I don't think I can use it the same way. Thanks in advance
--update--
still dosen't work
i did this on my saving side
Intent saveIntent = new Intent(this, MainActivity.class);
SharedPreferences.Editor editor = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE).edit();
editor.putString("time", displayTime.getText().toString());
editor.commit();
startActivity(saveIntent);
and this on my reciving side
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
String time = preferences.getString("time",null);
if (time != null)
getTime.setText(time);
Main Activity:
private Button createNewEvent;
private Button showMyEvents;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
createNewEvent = (Button) findViewById(R.id.bCreateNewEvent);
showMyEvents = (Button) findViewById(R.id.bShowMyEvents);
}
public void buttonOnClick(View v) {
switch (v.getId()) {
case R.id.bCreateNewEvent:
Intent createNewEventIntent = new Intent(this, CreateNewEventActivity.class);
startActivity(createNewEventIntent);
break;
case R.id.bShowMyEvents:
Intent myEventsIntent = new Intent(this,MyEventsActivity.class);
startActivity(myEventsIntent);
break;
}
}
}
screen 1 save button:
case R.id.bSaveNewEvent:
Intent putIntent = new Intent(getApplicationContext(),MyEventsActivity.class);
// String text = displayTime.getText().toString();
putIntent.putExtra("time",displayTime.getText().toString());
Intent saveIntent = new Intent(this, MainActivity.class);
startActivity(saveIntent);
startActivity(putIntent);
screen 2 getExtras
public class MyEventsActivity extends AppCompatActivity {
TextView getTime;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my_events);
getTime = (TextView) findViewById(R.id.tvGetTime);
Intent in = getIntent();
String name = in.getStringExtra("time");
getTime.setText(name);
/* Bundle extras = getIntent().getExtras();
if (extras != null){
getTime.setText(extras.getString("time"));
}*/
If you are trying to save data that will be need to be used in multiple other activities, SharedPreferences will be the easiest solution.
https://developer.android.com/training/basics/data-storage/shared-preferences.html
When you want to save a value, you would use:
SharedPreferences.Editor editor = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE).edit();
editor.putString("time", displayTime.getText().toString());
editor.commit();
Then when you want to get the preference later on you would use:
SharedPreferences preferences = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE);
String time = preferences.getString("time", "");
Related
I am creating a social app with a login/Registration system and I am having trouble logging the user out.
When I click the logout button I want to unset the username and clear the entire session of the user so that they go back to the LoginActivity class. Right now when I go to the profile activity and click logout I go straight back to the Home Activity which is only suppose to be for user who are logged in. I've been trying since yesterday and still nothing. Can someone help me ?
Login activity:
//SharedPreferences preferences;
private ProgressDialog loadingBar;
private Button LoginButton;
private EditText LoginUsername, LoginPassword;
private TextView NeedNewAccountLink;
private static final String PREF_LOGIN = "LOGIN_PREF";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
//SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(PREF_LOGIN, MODE_PRIVATE);
SharedPreferences sharedPreferences = getSharedPreferences(PREF_LOGIN, MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
}
LoginButton = (Button) findViewById(R.id.login_button);
LoginUsername = (EditText) findViewById(R.id.login_username);
LoginPassword = (EditText) findViewById(R.id.login_password);
NeedNewAccountLink = (TextView) findViewById(R.id.need_new_account_link);
loadingBar = new ProgressDialog(this);
editor.putString("username", String.valueOf(LoginUsername));
editor.putString("pw", String.valueOf(LoginPassword));
editor.apply();
if (LoginUsername != null) {
editor.remove("username");
editor.remove(String.valueOf(sharedPreferences));
editor.remove("pw");
editor.clear();
editor.apply();
SendUserToHomeActivity();
}
private void SendUserToHomeActivity() {
Intent mainIntent = new Intent(LoginActivity.this, HomeActivity.class);
mainIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(mainIntent);
finish();
}
public void OnLogin(View view) {
String username = LoginUsername.getText().toString();
String pw = LoginPassword.getText().toString();
String type = "login";
BackgroundWorker backgroundWorker = new BackgroundWorker(this);
backgroundWorker.execute(type, username, pw);
}
profile activity:
LogoutButton.setOnClickListener(view -> {
PreferenceManager.getDefaultSharedPreferences(getBaseContext()).edit().clear().apply();
sharedPreferences.edit().remove("username").apply();
sharedPreferences.edit().remove("pw").apply();
editor.remove("username");
editor.remove("pw");
editor.clear();
editor.apply();
finish();
Intent intent = new Intent(ProfileActivity.this, LoginActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
});
LogoutButton.setOnClickListener(view -> {
PreferenceManager.getDefaultSharedPreferences(getBaseContext()).edit().clear().apply();
sharedPreferences.edit().remove("username").apply();
sharedPreferences.edit().remove("pw").apply();
editor.remove("username");
editor.remove("pw");
editor.clear();
editor.apply();
Intent intent = new Intent(ProfileActivity.this, LoginActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
});
Remove the Intent.FLAG_ACTIVITY_CLEAR_TOP flag will solve your problem. Please refer to this link.
I believe to get text from edit text you need
LoginUsername.getText().toString()
and Checking EditText "LoginUsername" against If condition will never yield null unless
it points to wrong ID
Try proceeding with appropriate changes in below code block
LoginUsername = (EditText) findViewById(R.id.login_username);
LoginPassword = (EditText) findViewById(R.id.login_password);
NeedNewAccountLink = (TextView) findViewById(R.id.need_new_account_link);
loadingBar = new ProgressDialog(this);
editor.putString("username", String.valueOf(LoginUsername));
editor.putString("pw", String.valueOf(LoginPassword));
editor.apply();
if (LoginUsername != null) {
editor.remove("username");
editor.remove(String.valueOf(sharedPreferences));
editor.remove("pw");
editor.clear();
editor.apply();
SendUserToHomeActivity();
}
In my app urls are getting from the firebase database . I want to send these url to the another activity. how can i pass the url (Uri webpage) to the
viewer class.Please tell me how to do it.
Use intent in first activity like this:
Intent intent = new Intent(CurrentActivity.this, NextActivity.class);
intent.putExtra("key", value);
CurrentActivity.this.startActivity(intent);
And retrieve it on the second activity:
#Override
protected void onCreate(Bundle savedInstanceState) {
Intent intent = getIntent();
String value = intent.getStringExtra("key");
}
you can use this SharedPreferences
SharedPreferences sharedPref = getSharedPreferences("key",Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putString("key1","your uri");
editor.apply();
if you want get value in new ativity
SharedPreferences sharedPref = getSharedPreferences("key",Context.MODE_PRIVATE);
String uri=sharedPref.getString("key1","default value if value is null");
keys values must be same
You can also send String Array via intent from one activity to another.
In sender's activity, you can add URL string array into intent.
Intent intent = new Intent(this, MainActivity.class);
String[] urls = new String[] {
"https://google.com",
"https://stackoverflow.com"
};
intent.putExtra("urls", urls);
startActivity(intent);
In MainActivity (Receiver), you can get String array from intent.
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
String[] urls = getIntent().getStringArrayExtra("urls");
}
}
Hope it will be helpful.
I am writing a code which should return NFC tag value on the next activity ( page ) when NFC get detected during scan. What happens here is that when I launch the app for the first time it the first page shows for a fraction of a second and moves to second page directly ( activity ).
Here is the piece of code for the first activity ( which is just for asking user to tap to scan )
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
askPermissions();
mtxtViewNfcContent = (TextView) findViewById(R.id.text);
nfcAdapter = NfcAdapter.getDefaultAdapter(this);
if (nfcAdapter == null) {
Toast.makeText(this, "No NFC", Toast.LENGTH_SHORT).show();
finish();
return;
}
else {
Intent in = new Intent(Main2Activity.this, MainActivity.class);
startActivity(in);
}
What I want is the the to show the first page at launch and when user tap to nfc scan, show the output on the next page ( MainActivity).
PS : I am new to android, please excuse with my codes.
what are you doing until now is to exit the app when the device doesnot support nfc or to start another activity when the device supports nfc.
you are actually not listening at all to any tag.
here you have two possibilities:
first : read an nfc tag in the first activity and then creat a new intent with and put the result of tag reading as extra bundel.
two : listen to tag existance in the first activity and then send the tag to second one and read it in the second activity.
I would prefer the first secinario.
on firstActivity:
public class MainActivity extends AppCompatActivity {
private PendingIntent pendingIntent;
private IntentFilter[] writeTagFilters;
private NfcAdapter nfcAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setTheme(R.style.AppTheme);
setContentView(R.layout.activity_main);
nfcAdapter = NfcAdapter.getDefaultAdapter(this);
if (nfcAdapter == null) {
Toast.makeText(this, "No NFC", Toast.LENGTH_SHORT).show();
finish();
return;
}
setForeground();
}
private void setForeground() {
pendingIntent = PendingIntent.getActivity(this, 0, new Intent(this, getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0);
IntentFilter tagDetected = new IntentFilter(NfcAdapter.ACTION_TAG_DISCOVERED);
tagDetected.addCategory(Intent.CATEGORY_DEFAULT);
writeTagFilters = new IntentFilter[]{tagDetected};
}
#Override
protected void onResume() {
super.onResume();
if (nfcAdapter != null) {
nfcAdapter.enableForegroundDispatch(this, pendingIntent, null, null);
}
processNfcTag(getIntent());
}
#Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
setIntent(intent);
}
#Override
protected void onPause() {
super.onPause();
if (nfcAdapter != null) {
nfcAdapter.disableForegroundDispatch(this);
}
}
private void processNfcTag(Intent intent) {
//TODO: here you should to check if this intent is an NFC Intent, in case it is an nfc intent you could read it according of tag tech you have
// for example MifareUltralight.
MifareUltralight mfu = MifareUltralight.get(intent.getParcelableExtra(NfcAdapter.EXTRA_TAG));
try {
mfu.connect();
byte [] bytes = mfu.readPages(pageNumber);
mfu.close();
} catch (IOException e) {
e.printStackTrace();
}
// then you could get this bytes and send it to the other activity
}
please check this link to know how to send data between activities.
p.s: you should to check the code I have wrote it quickly.
You can use intent.putExtra (key,value) while calling the intent and use bundle on the result activity to fetch the variable data
use this while calling the intent
`Intent intent = new Intent(FirstActivity.this, SecondActivity.class);
intent.putExtra("some_key", value);
intent.putExtra("some_other_key", "a value");
startActivity(intent);`
use this on result activity
`Bundle bundle = getIntent().getExtras();
int valueText = bundle.getInt("some_key");
String valueString = bundle.getString("some_other_key");
TextView textone =(TextView)findVeiwById(R.id.textone);
textone.setText(valueText);
TextView stringTextView = (TextView)FindViewById(R.id.stringTextView)
stringTextView.setText(valueString)`
in my project I have static member as User.current.
If I run the app after it terminates in background, User.current will be null. I get user from server on splash screen.
I want to start splash screen when I run terminated application.
How I can solve this problem?
If you call a server, you probably use an Async task. In Async task
...
#Override
protected Boolean doInBackground(Void... params) {
...
value = jsonObj.getString("value");
return true;
}
protected void onPostExecute(Boolean iHaveValue) {
if(iHaveValue){
// use case 1 or 2
// 1
Intent i = new Intent(getApplicationContext(), MainActivity.class);
i.putExtra("value", value);
startActivity(i);
// 2
SharedPreferences sharedpreferences = getSharedPreferences("user", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putString("value", value);
editor.commit();
Intent i = new Intent(getApplicationContext(), MainActivity.class);
startActivity(i);
}
}
You get the user on the doInBackground(Void... params). And in the onPostExecute(Boolean iHaveValue) method you simply go to the MainActivity.
You can use the intent to put the value and receive on MainActivity (1) or use a shared preference (2)
(1)
in SplashScreen
Intent i = new Intent(getApplicationContext(), MainActivity.class);
i.putExtra("value", value);
startActivity(i);
in MainActivity
Intent editIntent = new Intent(getApplicationContext(), Splashscreen.class);
(2)
in SplashScreen
SharedPreferences sharedpreferences = getSharedPreferences("user", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putString("value", value);
editor.commit();
in MainActivity
SharedPreferences prefs = getSharedPreferences("user", MODE_PRIVATE);
value = prefs.getString("value", "null");
If you need use this value for multiple locations, sharedPreferences helps a lot (case 2). If not, use putExtra to send info to MainActivity (case 1).
I've created a widget which displays a simple textview, which is editable as an Edittext in a configuration activity. I save the inputted text with shared preferences, so the user can tap the widget to edit the text, and the already inputted text appears in the edittextfield.
My problem is this. I would like the user to be able to add multiple widgets, but when a seccond widget is added, the same text as in the other widget is loaded from shared preferences. And, when on widget is edited so is the other one. Hope i'm being clear. I kinda have an idea it has something to do with appWidgetIds but i cannot figure it out.
Here's my code, a bit simplified.
public class WidgetConfig extends Activity implements OnClickListener, OnItemSelectedListener {
AppWidgetManager awm;
int awID;
Context c;
EditText info;
Button b;
String note;
int styleStart = -1, cursorLoc = 0;
SharedPreferences sp;
Spinner spinner;
String[] paths = { "10", "20", "30" };
File path = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.widgetconfig);
c = WidgetConfig.this;
info = (EditText)findViewById(R.id.etwidgetconfig);
...
b = (Button)findViewById(R.id.bwidgetconfig);
loadPrefs();
b.setOnClickListener(this);
//Getting Info about the widget that launched this activity
Intent i = getIntent();
Bundle extras = i.getExtras();
if (extras != null){
awID = extras.getInt(AppWidgetManager.EXTRA_APPWIDGET_ID,
AppWidgetManager.INVALID_APPWIDGET_ID );
}
awm = AppWidgetManager.getInstance(c);
}
...
private void loadPrefs(){
sp = PreferenceManager.getDefaultSharedPreferences(this);
note = sp.getString("NOTE", "DEFAULT");
info.setText(note);
}
private void savePrefs(String key, String value){
sp = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sp.edit();
editor.putString(key, value); // value to store
editor.commit();
}
public void onClick(View v) {
// TODO Auto-generated method stub
savePrefs("NOTE", info.getText().toString());
RemoteViews views = new RemoteViews(c.getPackageName(), R.layout.widget);
views.setTextViewText(R.id.tvConfigInput, info.getText());
ComponentName thisWidget = new ComponentName(this, Widget.class);
AppWidgetManager manager = AppWidgetManager.getInstance(this);
manager.updateAppWidget(thisWidget, views);
Intent in = new Intent(c, WidgetConfig.class);
PendingIntent pi = PendingIntent.getActivity(c, 0, in, PendingIntent.FLAG_UPDATE_CURRENT);
views.setOnClickPendingIntent(R.id.B_EditAgain, pi);
awm.updateAppWidget(awID, views);
Intent result = new Intent();
result.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, awID);
setResult(RESULT_OK, result);
finish();
}
}
UPDATE:
So i tried this, but nothings different, still doesn't work.
private void loadPrefs(){
sp = context.getSharedPreferences("widget" + String.valueOf(appWidgetId)
, Context.MODE_PRIVATE);
note = sp.getString("Note", "");
info.setText(note);
}
private void savePrefs(String key, String value){
sp = context.getSharedPreferences("widget" + String.valueOf(appWidgetId)
, Context.MODE_PRIVATE);
Editor editor = sp.edit();
editor.clear();
editor.putString("Note", info.getText().toString());
editor.putString(key, value); // value to store
editor.commit();
}
You probably don't want to use getDefaultSharedPreferences here. All widgets share the same default shared preferences, so they will be constantly overwriting each other.
I had the same situation in my own app, so I used a custom preference file for each widget. You can name the preference file with the widgetID, and then each widget will always get it's own unique set of preferences.
In the configuration PreferenceActivity:
this.getPreferenceManager().setSharedPreferencesName(
"widget" + String.valueOf(mAppWidgetId)
);
This will store all of the PreferenceActivity settings into a preference file named after the widget id.
Then in the widget itself, just retrieve the file corresponding to its id:
preferences = context.getSharedPreferences(
"widget" + String.valueOf(appWidgetId)
, Context.MODE_PRIVATE);
And retrieve preferences like normal.