close previous Activity and open new activity on Item click - android

Hi everyone,
I have created a listview which is available on left side. On each item click opens new activity opens but when I traverse among listitems the new activity does not open after first attempt. I have closed the present activity in each case with finish() method. but it does not seems to work. here is code snippet ..let me know if anybody could help..appreciated
if (listname.equalsIgnoreCase("Time Table")) {
intent = new Intent(getApplicationContext(), TimeTable.class);
startActivity(intent);
Attendance.this.finish();
} else if (listname.equalsIgnoreCase("Announcements")) {
intent = new Intent(getApplicationContext(), Announcement.class);
startActivity(intent);
Attendance.this.finish();
}

I found the solution for my own problem, the issue was that I was not forwarding the some needed values to next activity such as userid, password etc. So I used SharedPreferences to pass the needed values on other activities. Here is example ..I hope it can be useful for others.
This is now created and committed shared preference
SharedPreferences prefs = getSharedPreferences("ABCPreferences",MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
editor.putString("UserId", login);
editor.putString("password", password);
editor.putString("IsInside", Inside);
editor.putString("UserType", "S");
editor.commit();
To access values through shared preference, It is simple
String listname = ((TextView)view).getText().toString();
String userid = getSharedPreferences("UMSPreferences",MODE_PRIVATE).getString("UserId", login);
String paswrd = getSharedPreferences("UMSPreferences",MODE_PRIVATE).getString("password", password);

Related

How to get the current userID on fragments, after you logged in

userLogin.class
try {
JSONObject obj = new JSONObject(response);
if(!obj.getBoolean("error")){
SharedPrefManager.getInstance(getApplicationContext())
.userLogin(
obj.getInt("id"),
obj.getString("firstname"),
obj.getString("lastname"),
obj.getString("s_id")
);
startActivity(new Intent(getApplicationContext(), MainActivity.class));
finish();
}else{
}
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(),"ERROR",Toast.LENGTH_LONG).show();
}
This is the code when you are trying to login.
How to put the current s_id to other activity like "FragmentActivity".
It should be like this. after you logged in, it will go to FragmentActivity also its should get the current user which the s_id.
I already put the code
Intent intentMainActivity = new Intent(LoginActivity.this, MainActivity.class);
intentMainActivity.putExtra("s_id", username);
startActivity(intentMainActivity);
But I don't know how to get in FragmentActivity, I tried
final String userID = getActivity().getIntent().getStringExtra("s_id");
I put in below the
private void fetchNewsFeedData() {
but still it doesn't work.
please help me solve this problem.
thank you.
In the login activity before going to main save the userid to shared pref
SharedPreferences prefs = this.getSharedPreferences("MyPrefs", Context.MODE_PRIVATE);
//set value to pref
preferences.edit().putString("s_id", username.toString()).apply();
and get the data whenever you want
SharedPreferences preferences = this.getActivity().getSharedPreferences("MyPrefs", MODE_PRIVATE);
String id = preferences.getString("s_id", "default value");

How to pass data from a Fragment to Fragment to Activity

So basically I'm trying to pass an EditText String to another fragment which is in the same Activity. Then pass that data to another Activity, depending on which button the pressed. My problem is the application works fine but I just don't see the string being created. I've tried to use a textview just to check if it works when I pass it through the first data, but nothing shows.
I just want to pass the string to another fragment then depending on the button they press pass it on the whichever Activity.
This is my code
Passing my Data to the next Fragment and going to the fragment.
mNextBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(getActivity(), ItemStorageFragment.class);
intent.putExtra("itemName", addName.getText().toString());
((AddInventoryActivity)getActivity()).ToExpiration(null);
}
});
Grabbing the data from my First Fragment
Intent intent = getActivity().getIntent();
value = intent.getStringExtra("itemName");
Then Sending it to the Activity
mToFreezer.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent in = new Intent(getActivity(), FreezerActivity.class);
in.putExtra("itemNameToFreezer", value);
startActivity(in);
}
});
Then Adding it to my RecyclerView
Intent i = getIntent();
String string = i.getStringExtra("itemNameToFreezer");
mDataset.add(string);
mAdapter.notifyDataSetChanged();
Intent extras are fine to share data between Activities, but you cannot use them for Fragments directly, as you did in your code. I assume, you are a beginner, so I recommend you read in depth about Intents here: Android - Intents and Filters
There are several ways of passing data between Activities and Fragments, most common of which is passing arguments. Yet, in your situation I'd recommend using SharedPreferences. You can store String data at any point inside your Fragment or Activity and then easily take it out with these simple steps:
Input data into SharedPreferences:
SharedPreferences.Editor editor = getSharedPreferences("YourPrefsFile", MODE_PRIVATE).edit();
editor.putString("name", "Elena");
editor.putInt("idName", 12);
editor.apply();
Get data from SharedPreferences:
SharedPreferences prefs = getSharedPreferences("YourPrefsFile", MODE_PRIVATE);
String restoredText = prefs.getString("text", null);
if (restoredText != null) {
String name = prefs.getString("name", "");
int idName = prefs.getInt("idName", 0);
}

Saving a string from first run to later start an activity

I have 4 activities in my android app.
1) Splash Activity - To decide if the app is being launched for the first time and to decide which activity to open
2)Main Activity - Button to open camera and start scanning i.e go to QR activity
2) QR Activity - Scan a QR code
3) Web Activity - On successful scanning, open a web page in the app. Use the data from the QR code to make a URL for the web page
In my splash activity, I check if it is the first run. If it is, I got to the main activity and if not, I want to go to the web activity. In my QR activity, I scan QR code and get a number from it. I use this number in the next activity, i.e, web activity to make a url using the scanned number and open the web page, But now, since I want to start different activity depending on the app run number, I want to save the scanned number from the first activity for all future runs of the app. Much like Facebook, which stores our login credentials for all future runs.
I am trying to do something like this, but the scanned value is not passed to my web activity
ScannerActivity.java
public static final String PREFS_NAME = "myPrefs";
if (barcodes.size() != 0) {
Intent intent = new Intent(getApplication(), WebActivity.class);
//intent.putExtra("result",barcodes.valueAt(0));
SharedPreferences.Editor editor=settings.edit();
editor.putString("result", barcodes.valueAt(0).displayValue);
editor.commit();
startActivity(intent);
finish();
}
WebActivity.java
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_web);
SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(this);
String result = settings.getString("result", "");
/*Barcode barcode = (Barcode) getIntent().getParcelableExtra("result");
Toast.makeText(WebActivity.this, barcode.displayValue, Toast.LENGTH_LONG).show();*/
Toast.makeText(WebActivity.this, result, Toast.LENGTH_SHORT).show();
webView = (WebView) findViewById(R.id.webview);
webView.setWebViewClient(new myWebClient());
webView.getSettings().setJavaScriptEnabled(true);
webView.loadUrl(" http://url?u="+result);
}
You're recommended to visit Android Studio Storage Option to have an enlarged perception of the mechanism and functionality
that being said, allow me to provide you with a snippet of how I store values in my application
Note you need to make minor adjustments, since I am applying Sharedpreferences inside a fragment
first
addusername = (EditText) oView.findViewById(R.id.addnewUsername);
second
//adjustment and reattachment
String bonsiour = addusername.getText().toString().trim();
SharedPreferences sPref = getActivity().getPreferences(0);
SharedPreferences.Editor edt = sPref.edit();
edt.putString("key1", bonsiour);
edt.commit();
//toast to confirm value has been saved
String buzo = sPref.getString("key1", "empty");
Toast.makeText(getActivity(), "You're " + buzo + "!!", Toast.LENGTH_LONG).show();
This is how to extract/read from it
SharedPreferences prefs = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE);
String name = prefs.getString("key1", "No name defined");
if(name.equals("PDF_FOUND")){
Toast.makeText(Controller.this,"IT WORKED !", Toast.LENGTH_SHORT).show();
//skip the splash screen and move to another activity asap
} else{
Toast.makeText(Controller.this,"BAD NEWS !", Toast.LENGTH_SHORT).show();
//display Splash screen
}
}
You can use SharedPreferences to store your String and re-use it later
If you want to store a String for example, first create keys to get your values
public static final String sharedPreferencesKey = "shareKey";
public static final String stringKey = "stringKey";
To store your value
SharedPreferences sharedpreferences =
context.getSharedPreferences(sharedPreferencesKey, Context.MODE_PRIVATE);
SharedPreferences.Editor ed = sharedpreferences.edit();
ed.putString(stringKey, "");
ed.apply();
To get your value
if (sharedpreferences.contains(stringKey))
sharedPreferences.getString(stringKey, "")
To store your String in shared preferences, you can do the following in a one liner:
String QRCode = "code";
PreferenceManager.getDefaultSharedPreferences(this).edit().putString("QRCode", QRCode).commit();
To retrieve the value of your stored String, use this:
//The second parameter for getString() is the default value to return if QRCode is not set
String QRCode = PreferenceManager.getDefaultSharedPreferences(this).getString("QRCode", "NOT_FOUND");
if(QRCode.equals("NOT_FOUND")){
//open MainActivity
Intent intent = new Intent(this, MainActivity.class);
startActivity(intent);
} else {
//open WebActivity
Intent intent = new Intent(this, WebActivity.class);
//you can pass code to webactivity or retrieve it from shared prefs
intent.putExtra("QRCode", QRCode);
startActivity(intent);
}

How to ensure the data remain in an activity after clicking a button to another page then return to current page?

I've an application where a user creates events. The user need to retrieve a certain name from an activity which is a ListView of names list.
I'm having an issue with making sure that a name should remain in an activity after clicking a date button which links to another activity(calendar activity), then return back to the current activity.
My codes of the 3 pages:
Create_Events.java - codes for getting a certain name from ListView activity and the btnDate onClickListener which links to the another activity(calendar activity)
Bundle bundle = getIntent().getExtras();
if(bundle != null)
{
String date = bundle.getString("date");
txtDate.setText(date);
}
Bundle b = getIntent().getExtras();
if(b != null)
{
String name = bundle.getString("name");
txtName.setText("Create an event for:" +name);
}
buttonDate = (Button) findViewById(R.id.btnDate);
buttonDate.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
Intent calIntent = new Intent(Create_Events.this, Calendar_Event.class);
startActivity(calIntent);
}
});
ContactsList.java -- the ListView of the names which is passed to the Create_Events page.
Cursor cursor = null;
cursor = (Cursor) l.getItemAtPosition(position);
Intent intent = new Intent(ContactsList.this, Create_Events.class);
intent.putExtra("name", cursor.getString(cursor.getColumnIndex(buddyDB.KEY_NAME)));
startActivity(intent);
I need help with this. Any help provided will be greatly appreciated. Thanks in advance! =)
you can get this behavior by saving you current screen state,
you can either use shared preferences or other ways (xml,data base, ..),
this way before you leave the activity (onPause) you save any information you need..
and on (onResume) if the information exists (its not the first time the activity loads),
collect the data and put it on screen..
if this is too much for you and you only need the name string to save,
try doing this :
How to declare global variables in Android?
hope it helps...
okay what i understand from your question is you want to retain your data on screen after coming back from another activity.
like Activity A--> Activity B--> Activity A
so, set in menifest file for activity A
android:launchmode="singletop"
and, when you are coming back from Activity B to Activity A
set
Intent intent=new Intent(ActivtyB.this, ActivityA.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
you can use SharedPreferences to store the name while use bundle to store the date.
From contactLists.java add these codes
private void SavePreferences(String key, String value)
{
SharedPreferences sharedPref = getSharedPreferences("MY_SHARED_PREF", MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putString(key, value);
editor.commit();
}
private void LoadPreferences()
{
SharedPreferences sharedPref = getSharedPreferences("MY_SHARED_PREF", MODE_PRIVATE);
String name = sharedPref.getString("name", "");
}
Then set the name to the textView which will show on the listView. And then load the preference in the create_events page and the name will be shown even when you go to another activity.
Do inform me if you still have any questions. (:

getting data from first activity to fourth activity in android

i want to get text written in the EditText first activity and set that text to the another EditText which is fourth activity.
Use this code in your first activity
Intent intent = new Intent(context,Viewnotification.class);
intent.putExtra("Value1", youredittextvalue.getText().toString());
startActiviy(intent);
And in your fourth Activity
Bundle extras = getIntent().getExtras();
String value1 = extras.getString("Value1");
yourfourthactivityedittext.setText(value1);
1- use SharedPreferences
2- set in apllication class
3- pass to using intent from 1-> 2 ->3 ->4
Simple way to do is,
You can assign one static variable which is public inside first activity like,
public static String myEditTextContent;
Set this after you set the value from your edit text like,
myEditTextContent = editText.getText().toString();
Use the same in fourth activity like
FirstActivityClass.myEditTextContent and set it in this(fourth) activity.
Later on you can use intent's putExtra,SQLLite Database,Shared Preference also, as suggested by others
You can do it in two ways
First Use SharedPreferences like
// declare
SharedPreferences pref;
SharedPreferences.Editor edit;
in On create
//initialize
pref = this.getSharedPreferences("myPrefs", MODE_PRIVATE);
edit = pref.edit();
// add data in it
edit.putString("USERNAME", EditText1.getText().toString());
edit.putString("PASSWORD", EditText1.getText().toString());
edit.putString("USERID", Text1.getText().toString());
// save data in it
edit.commit();
to get data
// access it
String passwrd = pref.getString("PASSWORD", "");
String userid = pref.getString("USERID", "");
And the second way
Send data from 1 to 2 and 2 to 3 and 3 to 4 activity
with intents like
Intent i = new Intent(First.this, Secondclass.class);
i.putExtra("userid", EditText1.getText().toString());
i.putExtra("username",EditText2.getText().toString());
startActivity(i);
and recieve in each activity like
Intent i = getIntent();
String ursid = i.getStringExtra("userid");
String ursername = i.getStringExtra("username");

Categories

Resources