String string = editText.getText().toString() give me string = null - string

Im using an EditText and I need get a String from the input of the EditText.
but every time I use final EditText editText = (EditText) findViewByID(editText);
String string = editText.getText().toString() and put it in a Toast Toast.makeText(getApplicationContext(), string, Toast.LENGTH_SHORT).show(); I get an empty Toast (null). any help?

editText.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {}
#Override
public void beforeTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {}
#Override
public void afterTextChanged(Editable arg0) {
String string = editText.getText().toString();
Toast.makeText(getApplicationContext(), string, Toast.LENGTH_SHORT).show();
}
});

Related

How can I see all data with RecyclerView?

I cannot show all datas to RecyclerView.I keep getting this error:
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void androidx.recyclerview.widget.RecyclerView.setAdapter(androidx.recyclerview.widget.RecyclerView$Adapter)' on a null object reference
at com.cdirect.weatherapp.MyLocations.onCreate(MyLocations.java:50)
MyLocations.java: 50:
rcView.setAdapter(adapter);
MyLocations.java code:
public class MyLocations extends AppCompatActivity {
BottomNavigationView altNav;
RecyclerView rcView;
ArrayList<Locations> locationsList;
DatabaseReference dbRef;
Adapter adapter;
#Override
public void onBackPressed() {
super.onBackPressed();
startActivity(new Intent(MyLocations.this,MainActivity.class));
finish();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
dbRef = FirebaseDatabase.getInstance().getReference("Locations");
altNav = (BottomNavigationView) findViewById(R.id.altNav);
rcView = findViewById(R.id.rvLocations);
locationsList = new ArrayList<>();
adapter = new Adapter(MyLocations.this, locationsList);
rcView.setAdapter(adapter); //ERROR LINE
rcView.setLayoutManager(new LinearLayoutManager(this));
Adapter.java codes:
public class Adapter extends RecyclerView.Adapter<Adapter.MyViewHolder> {
ArrayList<Locations> locationsArrayList;
Context context;
public Adapter (Context context, ArrayList<Locations> locationsArrayList){
this.locationsArrayList=locationsArrayList;
this.context = context;
}
#NonNull
#Override
public MyViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(context).inflate(R.layout.recycler_view_row,parent,false);
return new MyViewHolder(v);
}
#Override
public void onBindViewHolder(#NonNull MyViewHolder holder, int position) {
Locations loc = locationsArrayList.get(position);
holder.location.setText(loc.getLocation());
holder.temperature.setText(loc.getTemp());
}
#Override
public int getItemCount() {
return locationsArrayList.size();
}
public static class MyViewHolder extends RecyclerView.ViewHolder{
TextView location, temperature;
public MyViewHolder(#NonNull View itemView) {
super(itemView);
location = itemView.findViewById(R.id.tvLocation);
temperature= itemView.findViewById(R.id.tvTemp);
}
}
}
Locations.java code:
public class Locations {
String location;
String temp;
String id;
public Locations(String location, String temp, String id) {
this.location = location;
this.temp = temp;
this.id = id;
}
public String getLocation() {
return location;
}
public void setLocation(String location) {
this.location = location;
}
public String getTemp() {
return temp;
}
public void setTemp(String temp) {
this.temp = temp;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
}
I cannot solve where is the problem. Can you help me?

How to display decimals on android studio

Hello I have a problem between the double and int
my code "works" when I put the variables in int but I do not have the numbers after the decimal point as soon as I put in duplicate it puts the result to me at 0 and I do not see why
MyCartAdpter
public class MyCartAdapter extends RecyclerView.Adapter<MyCartAdapter.ViewHolder> {
Context context;
List<MyCartModel> list;
double totalAmount =0;
...
}
#Override
public void onBindViewHolder(#NonNull ViewHolder holder, int position) {
...
holder.totalPrice.setText(String.valueOf(list.get(position).getTotalPrice()));
//total amount pass to cart activity
totalAmount = (totalAmount + list.get(position).getTotalPrice());
Intent intent = new Intent("MyTotalAmount");
intent.putExtra("totalAmount",totalAmount);
LocalBroadcastManager.getInstance(context).sendBroadcast(intent);
}
MyCartModel
public class MyCartModel {
...
double totalPrice;
...
}
public MyCartModel(..., double totalPrice, ...) {
...
this.totalPrice = totalPrice;
...
}
public double getTotalPrice() {
return totalPrice;
}
public void setTotalPrice(double totalPrice) {
this.totalPrice = totalPrice;
}
and my CartActivity
public BroadcastReceiver mMessageReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
double totalBill = intent.getIntExtra("totalAmount",0);
overAllAmount.setText("Montant Total :"+totalBill+"€");
}
};
thank you for your help because for 24 hours I have been looking
overAllAmount.setText(String.format("%.2f",totalBill));
Could also put the textviews input type to numberdecimal
android:inputType="numberDecimal"
Happy coding

CardView with RelativeLayout not updating properly after click

I am trying to change one of my textview(Status) when clicked but it just removes the current text and displays my original text's text.
The textview currently display either "Not Taken" or "Pending" depending on what data is retrieved from my db.
My pop up dialog fragment code that shows the card items in a recyclerview.
public class FragmentLocationPopup extends DialogFragment {
View mView;
TextView tvSelectedBranch;
RecyclerView mScheduleList;
ScheduleAdapter mAdapter;
RecyclerView.LayoutManager mLayoutManager;
String TAG = "DialogFragment";
ArrayList<Schedule> scheduleList;
VariablesHolder variablesHolder;
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
mView = inflater.inflate(R.layout.fragment_location_popup, container, false);
createScheduleList();
buildRecyclerView();
return mView;
}
public void createScheduleList(){
scheduleList = new ArrayList<>();
tvSelectedBranch = mView.findViewById(R.id.tvSelectedBranch);
variablesHolder = (VariablesHolder) getActivity().getApplicationContext();
String selectedBranch = variablesHolder.getSelectedBranch();
tvSelectedBranch.setText(selectedBranch);
Log.d(TAG, "Selected branch = "+selectedBranch);
Call<List<Schedule>> call = RetrofitClient.getInstance().getApiDate().getSchedule();
call.enqueue(new Callback<List<Schedule>>() {
#Override
public void onResponse(Call<List<Schedule>> call, Response<List<Schedule>> response) {
List<Schedule> schedules = response.body();
for (Schedule schedule : schedules) {
if(schedule.getBranchID().equals(variablesHolder.getBranchID())) {
scheduleList.add(new Schedule(schedule.getWorkScheduleFromDateTime(), schedule.getWorkScheduleToDateTime(),schedule.getWorkScheduleStatus()));
Log.d(TAG, "onResponse: " + schedule.getWorkScheduleFromDateTime() + " and " + schedule.getWorkScheduleToDateTime() + " and "+schedule.getWorkScheduleStatus());
}
}
}
#Override
public void onFailure(Call<List<Schedule>> call, Throwable t) {
}
});
String asd = ""+variablesHolder.getBranchIdList();
Log.d(TAG, "onCreateView: "+asd);
}
public void buildRecyclerView(){
mScheduleList = mView.findViewById(R.id.rvScheduleList);
mScheduleList.setHasFixedSize(true);
mLayoutManager = new LinearLayoutManager(mView.getContext());
mAdapter = new ScheduleAdapter(scheduleList);
mScheduleList.setLayoutManager(mLayoutManager);
mScheduleList.setAdapter(mAdapter);
mAdapter.setOnItemClickListener(new ScheduleAdapter.OnItemClickListener() {
#Override
public void onItemClick(int position) {
changeItem(position, "Clicked");
}
});
}
public void changeItem(int position, String text){
scheduleList.get(position).changeText1(text);
mAdapter.notifyItemChanged(position);
Log.d(TAG, "changeItem: "+position+" / "+text);
}
}
My schedule class (I only use 3 variables in it at the moment) workfromtime, worktotime, and workstatus
public class Schedule {
private String workScheduleID;
private Date workScheduleFromDateTime;
private Date workScheduleToDateTime;
private String workScheduleStatus;
private String workDescriptionID;
private String branchID;
private String staffID;
private String managerID;
private String workScheduleBidDateTime;
public Schedule(Date workScheduleFromDateTime, Date workScheduleToDateTime,String workScheduleStatus) {
this.workScheduleFromDateTime = workScheduleFromDateTime;
this.workScheduleToDateTime = workScheduleToDateTime;
this.workScheduleStatus = workScheduleStatus;
}
public void changeText1(String workScheduleStatus){
this.workScheduleStatus = workScheduleStatus;
}
public String getWorkScheduleID(){return workScheduleID;}
public Date getWorkScheduleFromDateTime(){return workScheduleFromDateTime;}
public Date getWorkScheduleToDateTime(){return workScheduleToDateTime;}
public String getWorkScheduleStatus(){return workScheduleStatus;}
public String getWorkDescriptionID(){return workDescriptionID;}
public String getBranchID(){return branchID;}
public String getStaffID(){return staffID;}
public String getManagerID(){return managerID;}
public String getWorkScheduleBidDateTime(){return workScheduleBidDateTime;}
}
Adapter class
public class ScheduleAdapter extends RecyclerView.Adapter<ScheduleAdapter.ScheduleViewHolder> {
private static final String TAG = "ScheduleAdapter";
private ArrayList<Schedule> mScheduleList;
private OnItemClickListener mListener;
public interface OnItemClickListener{
void onItemClick(int position);
}
public void setOnItemClickListener(OnItemClickListener listener){
mListener = listener;
}
public static class ScheduleViewHolder extends RecyclerView.ViewHolder{
public TextView FromTime,ToTime,ScheduleStatus,Tester;
public ScheduleViewHolder(#NonNull final View itemView, final OnItemClickListener listener) {
super(itemView);
FromTime = itemView.findViewById(R.id.tvFromTime);
ToTime = itemView.findViewById(R.id.tvToTime);
ScheduleStatus = itemView.findViewById(R.id.tvStatus);
Tester = itemView.findViewById(R.id.tvTest);
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(listener != null){
int position = getAdapterPosition();
if(position != RecyclerView.NO_POSITION){
listener.onItemClick(position);
}
}
}
});
}
}
public ScheduleAdapter(ArrayList<Schedule> scheduleList ){
mScheduleList = scheduleList;
}
#NonNull
#Override
public ScheduleViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View mView = LayoutInflater.from(parent.getContext()).inflate(R.layout.schedule_item,parent,false);
ScheduleViewHolder svh = new ScheduleViewHolder(mView, mListener);
return svh;
}
#Override
public void onBindViewHolder(#NonNull ScheduleViewHolder holder, int position) {
Schedule currentSchedule = mScheduleList.get(position);
Log.d(TAG, "onBindViewHolder: "+currentSchedule.getWorkScheduleFromDateTime() + " and "+currentSchedule.getWorkScheduleToDateTime());
String FromTimeRegion = currentSchedule.getWorkScheduleFromDateTime().toString().replace("GMT 2020","");
String ToTimeRegion = currentSchedule.getWorkScheduleToDateTime().toString().replace("GMT 2020","");
String status = currentSchedule.getWorkScheduleStatus();
Log.d(TAG, "onBindViewHolder: "+status);
if(status.toLowerCase().equals("pending")) {
holder.ScheduleStatus.setText("Pending");
holder.ScheduleStatus.setTextColor(Color.parseColor("#FFFF00"));
}
if(status.toLowerCase().equals("not taken")) {
holder.ScheduleStatus.setText("Not Taken");
holder.ScheduleStatus.setTextColor(Color.parseColor("#7FFF00"));
}
holder.FromTime.setText("From: "+FromTimeRegion);
holder.ToTime.setText("To: "+ToTimeRegion);
}
#Override
public int getItemCount() {
return mScheduleList.size();
}
}
Please advice.
I found out that it is caused by this part of my code.
if(status.toLowerCase().equals("pending")) {
holder.ScheduleStatus.setText("Pending");
holder.ScheduleStatus.setTextColor(Color.parseColor("#FFFF00"));
}
if(status.toLowerCase().equals("not taken")) {
holder.ScheduleStatus.setText("Not Taken");
holder.ScheduleStatus.setTextColor(Color.parseColor("#7FFF00"));
}
holder.FromTime.setText("From: "+FromTimeRegion);
holder.ToTime.setText("To: "+ToTimeRegion);
Just had to edit which comes first.

how to fix error 'int java.util.List.size()'

I am all time worked by one source! but now get error
int java.util.List.size()
now my adapter source its :
public class MessagesAdapter extends RecyclerView.Adapter<MessagesAdapter.msgsViewHoler> {
List<QueryMessages> queryMessages;
Context mtContext;
public MessagesAdapter(List<QueryMessages> queryMessages, MainActivity mainActivity){
this.queryMessages=queryMessages;
}
#NonNull
#Override
public msgsViewHoler onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view= LayoutInflater.from(parent.getContext()).inflate(R.layout.message_row,parent,false);
return new msgsViewHoler(view);
}
#Override
public void onBindViewHolder(#NonNull msgsViewHoler holder, int position) {
final QueryMessages queryMessageses=queryMessages.get(position);
Picasso.get()
.load(queryMessageses.getMpic())
.error(R.mipmap.ic_launcher)
.fit()
.into(holder.mpic);
holder.mname.setText(queryMessageses.getMname());
holder.message.setText(queryMessageses.getMessage());
holder.tarikh.setText(queryMessageses.getTarikh());
}
#Override
public int getItemCount() {
return queryMessages.size();
}
public class msgsViewHoler extends RecyclerView.ViewHolder{
int id;
CardView parent;
ImageView mpic;
TextView mname,message,tarikh;
public msgsViewHoler(View itemView) {
super(itemView);
parent=itemView.findViewById(R.id.message_row);
mpic=itemView.findViewById(iv_profile);
mname=itemView.findViewById(R.id.tv_mastername);
message=itemView.findViewById(R.id.tv_msg);
tarikh=itemView.findViewById(R.id.tv_date);
}
}
and give this error :
java.lang.NullPointerException: Attempt to invoke interface method 'int java.util.List.size()' on a null object reference
at ir.arvandit.channeleto.adapter.MessagesAdapter.getItemCount(MessagesAdapter.java:62)
thats line is :
return queryMessages.size();
my Activity Main its :
RecyclerView rvmsg;
CardView message_row;
List<QueryMessages> queryMessages;
MessagesAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
cast();
onClick();
ApiService service=ApiClient.getClient().create(ApiService.class);
Call<List<QueryMessages>> call=service.getQueryMessages();
call.enqueue(new Callback<List<QueryMessages>>() {
#Override
public void onResponse(Call<List<QueryMessages>> call, Response<List<QueryMessages>> response) {
pros.setVisibility(View.GONE);
queryMessages=response.body();
adapter=new MessagesAdapter(queryMessages,MainActivity.this);
rvmsg.setAdapter(adapter);
}
#Override
public void onFailure(Call<List<QueryMessages>> call, Throwable t) {
pros.setVisibility(View.GONE);
nonet.setVisibility(View.VISIBLE);
}
});
}
public void cast(){
rvmsg=findViewById(R.id.rv_message);
rvmsg.setLayoutManager(new LinearLayoutManager(this,LinearLayoutManager.VERTICAL,false));
}
now I need help for fix this error!
Issue is in bellow code
private static final String TAG = "CurrentActivity";
#Override
public void onResponse(Call<List<QueryMessages>> call,
Response<List<QueryMessages>> response) {
Log.v(TAG, "onResponse=" + response.body().toString());
}
check weather response.body() or response is the ArrayList of <List<QueryMessages>>
in new version retrofit if in your json have free parameter , get this error
for example i need id,name,number
but in my json have id,name,number,date ....
i give this error!
and some time if in ApiService have false url!
tanks for help all

Non-static edit() cannot be referenced from a static context

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));
}
});
}

Resources