0% found this document useful (0 votes)
5 views2 pages

Shared Preference

Uploaded by

abhinandpcdance
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views2 pages

Shared Preference

Uploaded by

abhinandpcdance
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 2

java

package com.example.sharedpreference;
import androidx.appcompat.app.AppCompatActivity;
import android.content.*;
import android.os.Bundle;
import android.view.View;
import android.widget.*;
public class MainActivity extends AppCompatActivity {
EditText rollNo, name, branch;
SharedPreferences pref;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
rollNo = findViewById(R.id.rollno);
name = findViewById(R.id.name);
branch = findViewById(R.id.branch);
Button save = findViewById(R.id.save);
Button newData = findViewById(R.id.newData);
pref = getSharedPreferences("MyPrefs", MODE_PRIVATE);
save.setOnClickListener(v -> {
String r = rollNo.getText().toString();
String n = name.getText().toString();
String b = branch.getText().toString();
if (r.isEmpty()) rollNo.setError("Required");
else if (n.isEmpty()) name.setError("Required");
else if (b.isEmpty()) branch.setError("Required");
else {
pref.edit().putString("rollno", r)
.putString("name", n)
.putString("branch", b)
.apply();
startActivity(new Intent(this, view.class)); } });
newData.setOnClickListener(v -> {
pref.edit().clear().apply();
rollNo.setText("");
name.setText("");
branch.setText("");
}); }}
view

package com.example.sharedpreference;
import androidx.appcompat.app.AppCompatActivity;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.widget.TextView;
public class view extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view);
SharedPreferences pref = getSharedPreferences("MyPrefs",
MODE_PRIVATE);
String data = "Roll No: " + pref.getString("rollno", "N/A") +
"\nName: " + pref.getString("name", "N/A") +
"\nBranch: " + pref.getString("branch", "N/A");
((TextView) findViewById(R.id.display)).setText(data);}}

You might also like