Good evening. Or whatever time you're reading this in. In Android Studio when I was developing the first stages of my app I ran into a problem and I can't seem to find the answer. I am trying to use SharedPrefereces to save user input, but when I try to edit the prefereces [editor = SharedPreferences.edit();] it says that edit() is a non-static method and connot be refereced from a static context.
Here is the code.
public class TheButton extends AppCompatActivity {
EditText ed1, ed2, ed3, ed4;
/*EditText nameInput;
EditText ageInput;
EditText occupationInput;
EditText genderInput;
Button startButtonFinish;*/
protected static final String MyPREFERENCES = "";
public static final String nameInput = "";
public static final int ageInput = 0;
public static final String occupationInput = "";
public static final String genderInput = "";
SharedPreferences sharedpreferences;
SharedPreferences.Editor editor;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_the_button);
ed1 = (EditText) findViewById(R.id.nameInput);
ed2 = (EditText) findViewById(R.id.ageInput);
ed3 = (EditText) findViewById(R.id.occupationInput);
ed4 = (EditText) findViewById(R.id.genderInput);
sharedpreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
Button startButtonFinish = (Button) findViewById(R.id.startButtonFinish);
startButtonFinish.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String nL = ed1.getText().toString();
String oI = ed3.getText().toString();
String gI = ed4.getText().toString();
//Gives me an error on edit() saying that it edit() is a non-static
// class and they cannot be referenced from a static context
editor = SharedPreferences.edit();
editor.putString(nameInput,nL);
editor.putString(occupationInput, oI);
editor.putString(genderInput, gI);
editor.commit();
startActivity(new Intent(TheButton.this, thebutton2.class));
}
});
}
I will appreciate any help. Thank you!
Instead of this line editor = SharedPreferences.edit();
you should call edit method by sharedpreferences object which is initialized in your code.
You should call the .edit() method by creating object of SharedPreferences. Change SharedPreferences in line, from editor = SharedPreferences.edit(); to editor = sharedPreferences.edit();
EditText ed1, ed2, ed3, ed4;
/*EditText nameInput;
EditText ageInput;
EditText occupationInput;
EditText genderInput;
Button startButtonFinish;*/
protected static final String MyPREFERENCES = "";
public static final String nameInput = "";
public static final int ageInput = 0;
public static final String occupationInput = "";
public static final String genderInput = "";
SharedPreferences sharedpreferences;
SharedPreferences.Editor editor;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_the_button);
ed1 = (EditText) findViewById(R.id.nameInput);
ed2 = (EditText) findViewById(R.id.ageInput);
ed3 = (EditText) findViewById(R.id.occupationInput);
ed4 = (EditText) findViewById(R.id.genderInput);
sharedpreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
Button startButtonFinish = (Button) findViewById(R.id.startButtonFinish);
startButtonFinish.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String nL = ed1.getText().toString();
String oI = ed3.getText().toString();
String gI = ed4.getText().toString();
//Gives me an error on edit() saying that it edit() is a non-static
// class and they cannot be referenced from a static context
editor = sharedPreferences.edit();
editor.putString(nameInput,nL);
editor.putString(occupationInput, oI);
editor.putString(genderInput, gI);
editor.commit();
startActivity(new Intent(TheButton.this, thebutton2.class));
}
});
}
Related
i want to pass some data from activity to a java class i use intent to pass data from activity to a java class .
// Activity
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_workspace);
worklink = findViewById(R.id.workspace);
button = findViewById(R.id.continu);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String work_link = worklink.getText().toString().trim();
SharedPreferences sharedPref = getSharedPreferences("myKey", MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putString("value", work_link);
editor.apply();
Intent intent = new Intent(workspace.this,BaseURL.class);
startActivity(intent);
}
});
// java class
import android.content.Intent;
public class BaseURL {
String value = getIntent.getExtra("worklink");
}
Create a Global class and create getter setter then set the data you want to pass
public class GlobalData {
public static String status;
public static int getStatus() {
return status;
}
public static void setStatus(String status) {
GlobalData.status = status;
}
}
I am making a listView and in each item, there is a TextView identifying the field, and an EditText for the user to fill out the value. When I input the text into the EditText, the text just reverts back to what it was before. How do I make it so that it saves the new input? I read an article on StackOverflow of someone with a similar problem and they suggested using a TextOnChanged listener, so I added that as well. When I ran my app, the app just froze. I think I am doing it wrong so it would be great if someone helped me. Thanks.
Here is my code for my custom adapter:
public class DataListAdapter extends ArrayAdapter<DataObject> {
private Context mContext;
int mResource;
public DataListAdapter(Context context, int resource, List<DataObject> objects) {
super(context, resource, objects);
mResource = resource;
mContext = context;
}
#NonNull
#Override
public View getView(int position, #Nullable View convertView, #NonNull ViewGroup parent) {
String field = getItem(position).getField();
String value = getItem(position).getValue();
String unit = getItem(position).getUnit();
DataObject dataObject = new DataObject(field, value, unit);
LayoutInflater layoutInflater = LayoutInflater.from(mContext);
convertView = layoutInflater.inflate(mResource, parent, false);
TextView tvField = (TextView) convertView.findViewById(R.id.Field);
final EditText tvValue = (EditText) convertView.findViewById(R.id.Value);
tvField.setText(field);
tvValue.setText(value);
//the code I attempted to use to save the changed text
tvValue.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
String edit = s.toString();
tvValue.setText(edit);
}
#Override
public void afterTextChanged(Editable s) {
}
});
return convertView;
}
}
Here is my code for the main activity for now if needed:
public class MainActivity extends AppCompatActivity {
ListView list;
ArrayList<DataObject> data = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
list =(ListView) findViewById(R.id.list);
data.add(new DataObject("Vitamin A", "14", ""));
data.add(new DataObject("Vitamin B", "15", ""));
data.add(new DataObject("Vitamin C", "16", ""));
DataListAdapter dataAdapter = new DataListAdapter(this, R.layout.row, data);
list.setAdapter(dataAdapter);
}
}
I'm trying to make a program in android studio that when sellected a higher education it automatically adds 200$ to the pay that was previously entered. But instead of getting 500+200=700, I get 500200. I ran trough the code numerous times and just can't seem to find the error. I'm still new on Java. This is the second window that appears when submitting the information, It shows all the info entered in the first window, but for some reason it can't 200 to the entered pay
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_rezultatas);
Intent duom = getIntent();
String pavarde = duom.getStringExtra("pavarde");
String issilavinimas = duom.getStringExtra("issilavinimas");
int pay = duom.getIntExtra("atlyginimas", 0);
String laikas = duom.getStringExtra("laikas");
TextView rez = findViewById(R.id.rezultatas);
rez.setText("Pavardė: "+pavarde+"\n");
rez.append("Išsilavinimas: "+issilavinimas+"\n");
if(issilavinimas.equals("Aukštasis")){
rez.append("Gaunamas atlyginimas: " +pay+ 200 + "\n");
} else{
rez.append("Gaunamas atlyginimas: "+pay+ "\n");
}
rez.append("Keliasi: "+laikas+"\n");
}
This is the first window where all the information is entered:
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void saugoti(View v){
EditText txt = findViewById(R.id.lastName);
String pavarde = txt.getText().toString();
Spinner issilavinimas = findViewById(R.id.issilavinimas);
String issilav = issilavinimas.getSelectedItem().toString();
EditText atl = findViewById(R.id.pay);
int pay = Integer.parseInt(atl.getText().toString());
TextView txt2 = findViewById(R.id.time);
String laikas = txt2.getText().toString();
Intent duom = new Intent(this, rezultatas.class);
duom.putExtra("pavarde", pavarde);
duom.putExtra("issilavinimas", issilav);
duom.putExtra("laikas", laikas);
duom.putExtra("atlyginimas", pay);
startActivity(duom);
}
public void showTimePickerDialog(View v) {
DialogFragment newFragment = new TimePickerFragment();
newFragment.show(getSupportFragmentManager(), "timePicker");
}
Try this
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_rezultatas);
Intent duom = getIntent();
String pavarde = duom.getStringExtra("pavarde");
String issilavinimas = duom.getStringExtra("issilavinimas");
int pay = duom.getIntExtra("atlyginimas", 0);
int total=pay+ 200;
String laikas = duom.getStringExtra("laikas");
TextView rez = findViewById(R.id.rezultatas);
rez.setText("Pavardė: "+pavarde+"\n");
rez.append("Išsilavinimas: "+issilavinimas+"\n");
if(issilavinimas.equals("Aukštasis")){
rez.append("Gaunamas atlyginimas: " + total + "\n");
} else{
rez.append("Gaunamas atlyginimas: "+pay+ "\n");
}
rez.append("Keliasi: "+laikas+"\n");
}
when you + with String concatination is actually working there instead of addition
I'm loading an Image into an ImageView using a link, and I'm trying to pass this link from one activity to display on another activity by an Intent. However, the Image just seems to come up blank.
Below I have listed the code associated with the two activities, as well as the adapter of the RecyclerView that the information is being passed from in the first activity
ActivityOne.java
private ArrayList<String> mImageUrls = new ArrayList<>();
...
mImageUrls.add("https://data.oireachtas.ie/ie/oireachtas/member/id/Se%C3%A1n-Haughey.S.1987-04-25/image/large");
...
#Override
public void onNoteClick(int position) {
Intent intent = new Intent(this, ActivityTwo.class);
intent.putExtra("EXTRA_KEY_NAME", mNames.get(position));
intent.putExtra("EXTRA_KEY_IMAGE", mImageUrls.get(position));
startActivity(intent);
}
ActivityTwo.java
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_members_map_detailed);
tvMemberName = findViewById(R.id.tvClareMemberNameDetailed);
tvMemberParty = findViewById(R.id.tvClareMemberPartyDetailed);
tvMemberConstituency = findViewById(R.id.tvClareMemberConstituencyDetailed);
tvMemberAddress = findViewById(R.id.tvClareMemberAddressDetailed);
tvMemberEmail = findViewById(R.id.tvClareMemberEmailDetailed);
tvMemberPhone = findViewById(R.id.tvClareMemberPhoneDetailed);
tvMemberContributions = findViewById(R.id.tvClareMemberContributionsDetailed);
imgMember = findViewById(R.id.imgClareMemberImageDetailed);
Intent intent = getIntent();
String mName = intent.getStringExtra("EXTRA_KEY_NAME");
String mParty = intent.getStringExtra("EXTRA_KEY_PARTY");
String mConstituency = intent.getStringExtra("EXTRA_KEY_CONSTITUENCY");
String mAddress = intent.getStringExtra("EXTRA_KEY_ADDRESS");
Uri myUri = Uri.parse(intent.getStringExtra("EXTRA_KEY_IMAGE"));
String mEmail = intent.getStringExtra("EXTRA_KEY_EMAIL");
String mPhone = intent.getStringExtra("EXTRA_KEY_PHONE");
String mContributions = intent.getStringExtra("EXTRA_KEY_CONTRIBUTIONS");
tvMemberName.setText(mName);
tvMemberParty.setText(mParty);
tvMemberConstituency.setText(mConstituency);
tvMemberAddress.setText(mAddress);
tvMemberEmail.setText(mEmail);
tvMemberPhone.setText(mPhone);
tvMemberContributions.setText(mContributions);
imgMember.setImageURI(myUri);
Adapter information associated with Image
#Override
public void onBindViewHolder(#NonNull ViewHolder holder, int position) {
Glide.with(mContext)
.asBitmap()
.load(mImageUrls.get(position))
.into(holder.image);
holder.name.setText(mNames.get(position));
holder.party.setText(mParties.get(position));
I have a class with the name of SharePrefManager. Here is the code
package com.example.lms02;
public class SharedPrefManager {
private static final String SHARED_PREF_NAME = "volleyregisterlogin";
private static final String KEY_USERNAME = "keyusername";
private static final String KEY_EMAIL = "keyemail";
private static final String KEY_GENDER = "keygender";
private static final String KEY_ID = "keyid";
private static final String KEY_STDID = "keystdid";
private static final String KEY_USER_STATUS = "keyuserstatus";
private static SharedPrefManager mInstance;
private static Context ctx;
private SharedPrefManager(Context context) {
ctx = context;
}
public static synchronized SharedPrefManager getInstance(Context context) {
if (mInstance == null) {
mInstance = new SharedPrefManager(context);
}
return mInstance;
}
//this method will store the user data in shared preferences
public void userLogin(User user) {
SharedPreferences sharedPreferences = ctx.getSharedPreferences(SHARED_PREF_NAME, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putInt(KEY_ID, user.getId());
editor.putString(KEY_STDID,user.getStdid());
editor.putString(KEY_USERNAME, user.getName());
editor.putString(KEY_EMAIL, user.getEmail());
editor.putString(KEY_GENDER, user.getGender());
editor.putString(KEY_USER_STATUS, user.getStatus());
editor.apply();
}
//this method will checker whether user is already logged in or not
public boolean isLoggedIn() {
SharedPreferences sharedPreferences = ctx.getSharedPreferences(SHARED_PREF_NAME, Context.MODE_PRIVATE);
return sharedPreferences.getString(KEY_USERNAME, null) != null;
}
//this method will give the logged in user
public User getUser() {
SharedPreferences sharedPreferences = ctx.getSharedPreferences(SHARED_PREF_NAME, Context.MODE_PRIVATE);
return new User(
sharedPreferences.getInt(KEY_ID, -1),
sharedPreferences.getString(KEY_STDID, null),
sharedPreferences.getString(KEY_USERNAME, null),
sharedPreferences.getString(KEY_EMAIL, null),
sharedPreferences.getString(KEY_GENDER, null),
sharedPreferences.getString(KEY_USER_STATUS, null)
);
}
//this method will logout the user
public void logout() {
SharedPreferences sharedPreferences = ctx.getSharedPreferences(SHARED_PREF_NAME, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.clear();
editor.apply();
ctx.startActivity(new Intent(ctx, LoginActivity.class));
}
}
I am using Fragments. Here is the code of my Fragment
public class HomeFragment extends Fragment {
TextView txtvwuserid;
User user = SharedPrefManager.getInstance(getContext()).getUser();
public HomeFragment() {
// Required empty public constructor
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_home, container, false);
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
txtvwuserid = getActivity().findViewById(R.id.txtvwstdid);
txtvwuserid.setText("Hy");
}
}
The problem occurs in HomeFragment here
User user = SharedPrefManager.getInstance(getContext()).getUser();
The Error shown is:
java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.SharedPreferences
android.content.Context.getSharedPreferences(java.lang.String, int)' on a null object reference
My Problem is how can i access the values of SharedPrefManager and what does the error means
Problem Solved:
According to the Fragment Life Cycle. we have to place all of our code after the creation of Fragment. What I was doing wrong is Declaring the User object before creation of fragment. Placing it like
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
user = SharedPrefManager.getInstance(getActivity()).getUser(); //Placing here
}
It Worked For me. Cheers...!!!