Add numbers from EditTexts - android

I've created an Activity where I've got an "Add subject" button. When I press it, it creates an item in a ListView, which is formed by an EditText where the user enters a number.
What I want to do is to add the numbers inside the EditTexts of each item created, depending if the user has created 3, 4, 5, etc. items in the ListView, via button.
Here is the code of the Activity:
public class PersActivity extends Activity {
Button start, calcaverage1;
private SubjectAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.subject_list_view);
setupListViewAdapter();
setupAddMarkButton();
// Accept button
Button acceptbn= (Button)findViewById(R.id.start1);
acceptbn.setOnClickListener(new OnClickListener()
{ public void onClick(View v)
{
Intent intent = new Intent(PersActivity.this, MainActivity.class);
startActivity(intent);
finish();
}
});
}
public void removeClick(View v) {
Mark itemToRemove = (Mark)v.getTag();
adapter.remove(itemToRemove);
}
private void setupListViewAdapter() {
adapter = new SubjectAdapter(PersActivity.this, R.layout.subject_list_item, new ArrayList<Mark>());
ListView atomPaysListView = (ListView)findViewById(R.id.subject_list_item);
atomPaysListView.setAdapter(adapter);
}
private void setupAddMarkButton() {
findViewById(R.id.addsubject).setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
adapter.insert(new Mark("", 0), 0);
}
});
}
}
Here is the code of the adapter:
public class SubjectAdapter extends ArrayAdapter<Mark> {
protected static final String LOG_TAG = SubjectAdapter.class.getSimpleName();
private List<Mark> items;
private int layoutResourceId;
private Context context;
public SubjectAdapter(Context context, int layoutResourceId, List<Mark> items) {
super(context, layoutResourceId, items);
this.layoutResourceId = layoutResourceId;
this.context = context;
this.items = items;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
MarkHolder holder = null;
LayoutInflater inflater = ((Activity) context).getLayoutInflater();
row = inflater.inflate(layoutResourceId, parent, false);
holder = new MarkHolder();
holder.Mark = items.get(position);
holder.removePaymentButton = (ImageButton)row.findViewById(R.id.remove);
holder.removePaymentButton.setTag(holder.Mark);
holder.name = (TextView)row.findViewById(R.id.subjectname);
setNameTextChangeListener(holder);
holder.value = (TextView)row.findViewById(R.id.subjectmark);
setValueTextListeners(holder);
row.setTag(holder);
setupItem(holder);
return row;
}
private void setupItem(MarkHolder holder) {
holder.name.setText(holder.Mark.getName());
holder.value.setText(String.valueOf(holder.Mark.getValue()));
}
public static class MarkHolder {
Mark Mark;
TextView name;
TextView value;
ImageButton removePaymentButton;
}
private void setNameTextChangeListener(final MarkHolder holder) {
holder.name.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
holder.Mark.setName(s.toString());
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) { }
#Override
public void afterTextChanged(Editable s) { }
});
}
private void setValueTextListeners(final MarkHolder holder) {
holder.value.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
try{
holder.Mark.setValue(Double.parseDouble(s.toString()));
}catch (NumberFormatException e) {
Log.e(LOG_TAG, "error reading double value: " + s.toString());
}
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) { }
#Override
public void afterTextChanged(Editable s) { }
});
}
}
I've implemented serializable to pass data through the adapter:
public class Mark implements Serializable {
private static final long serialVersionUID = -5435670920302756945L;
private String name = "";
private double value = 0;
public Mark(String name, double value) {
this.setName(name);
this.setValue(value);
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getValue() {
return value;
}
public void setValue(double value) {
this.value = value;
}
}
Hope there's a solution. Thanks!

Here is how you would do it
addNumberFromText()
{
int total=0;
for(int i=0;i<listView.getChildCount();i++)
{
View wantedView = listView.getChildAt(i);
EditText edtText=view.findViewById(R.id.specificEditTextId);
//not checking wheter integer valid or not, Please do so
int value=Integer.parseInt(edtText.toString());
total+=value;
}
Log.d(TAG,"total sum is "+total);
}
update your activity from following code
public class PersActivity extends Activity
{
Button start, calcaverage1;
private SubjectAdapter adapter;
ListView atomPaysListView;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.subject_list_view);
atomPaysListView = (ListView)findViewById(R.id.subject_list_item);
setupListViewAdapter();
setupAddMarkButton();
// Accept button
Button acceptbn= (Button)findViewById(R.id.start1);
acceptbn.setOnClickListener(new OnClickListener()
{ public void onClick(View v)
{
Intent intent = new Intent(PersActivity.this, MainActivity.class);
startActivity(intent);
finish();
}
});
}
public void removeClick(View v) {
Mark itemToRemove = (Mark)v.getTag();
adapter.remove(itemToRemove);
}
private void setupListViewAdapter() {
adapter = new SubjectAdapter(PersActivity.this, R.layout.subject_list_item, new ArrayList<Mark>());
atomPaysListView.setAdapter(adapter);
}
private void setupAddMarkButton() {
findViewById(R.id.addsubject).setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
adapter.insert(new Mark("", 0), 0);
}
});
}
addNumberFromText()
{
double total=0;
for(int i=0;i<atomPaysListView.getChildCount();i++)
{
View wantedView = atomPaysListView.getChildAt(i);
/*
// if edit text
EditText edt=(EditText)view.findViewById(R.id.editText);
//not checking wheter valid or not, Please do so
double value=Double.parseDouble(edt.toString());
*/
//you say edittext, but its a textview or so it seems
TextView txv=(TextView)view.findViewById(R.id.subjectmark);
//not checking wheter valid or not, Please do so
double value=Double.parseDouble(txv.toString());
total+=value;
}
Log.d(TAG,"total sum is "+total);
}
}

Related

RecyclerView EditText value erase after scrolling

EditText input value erase after scrolling down and scrolling up.
I followed many tutorials but nothing worked for me, I tried to implement Textwatcher but I can't perfectly implement it.
Someone please help, I'm stuck with this problem. Please give me a solution if it had multiple edittext too.
here is my adapter code.
public class ClassTestMarkAdapter extends RecyclerView.Adapter<ClassTestMarkAdapter.NviewHolder> {
private Context mCtx;
private List<ClassTestMarkModel> marklist;
public ClassTestMarkAdapter(Context mCtx, List<ClassTestMarkModel> marklist) {
this.mCtx = mCtx;
this.marklist = marklist;
}
#NonNull
#Override
public NviewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int position) {
LayoutInflater inflater =LayoutInflater.from(mCtx);
View v = inflater.inflate(R.layout.class_test_mark_list,null);
NviewHolder holder =new NviewHolder(v,new MyCustomEditTextListener());
return holder;
}
#Override
public void onBindViewHolder(#NonNull final NviewHolder nviewHolder, int position) {
ClassTestMarkModel markModel =marklist.get(position);
nviewHolder.myCustomEditTextListener.updatePosition(nviewHolder.getAdapterPosition());
nviewHolder.wrText.setText(marklist[nviewHolder.getAdapterPosition()]);
nviewHolder.stname.setText(markModel.getUserName());
nviewHolder.stroll.setText(markModel.getRoll());
nviewHolder.wrText.setText(markModel.getMarks());
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(mCtx);
Long instituteID = prefs.getLong("InstituteID",0);
final String inssid=String.valueOf(instituteID);
final String subId = prefs.getString("subId", "");
final String examids = prefs.getString("examidforct", "");
final String sessionId = prefs.getString("sesId", "");
final String cTMarkID=markModel.getcTMarkID();
final String insCTID=markModel.getInsCTID();
final String userID=markModel.getUserID();
nviewHolder.btnMark.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
RequestQueue myRequestQueue = Volley.newRequestQueue(mCtx);
String url = mCtx.getResources().getString(R.string.baseUrlLocal)+"setExamCTMarks";
final String xNon=nviewHolder.wrText.getText().toString();
Double wrsum= Double.valueOf(xNon);
if (wrsum>0){
nviewHolder.btnMark.setText("Success!");
nviewHolder.btnMark.setBackgroundColor(Color.parseColor("#009000"));
}
StringRequest myStringRequest = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Toast.makeText(mCtx,"Success! Data Posted Sucessfully",Toast.LENGTH_SHORT).show();
}
}, new Response.ErrorListener() { //Create an error listener to handle errors appropriately.
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(mCtx,"Error: Something Wrong...",Toast.LENGTH_SHORT).show();
}
}) {
protected Map<String, String> getParams() {
Map<String, String> MyData = new HashMap<String, String>();
MyData.put("CTMarkID", cTMarkID);
MyData.put("InsCTID", insCTID);
MyData.put("UserID",userID);
MyData.put("SessionID", sessionId);
MyData.put("SubjectID", subId);
MyData.put("ExamID", examids);
MyData.put("ObtainMarks",xNon);
MyData.put("InstituteID",inssid);
MyData.put("IsAbsent", "");
MyData.put("LoggedUserID", "123");
MyData.put("IP", "123");
return MyData;
}
};
myRequestQueue.add(myStringRequest);
}
});
}
#Override
public int getItemCount() {
return marklist.size();
}
class NviewHolder extends RecyclerView.ViewHolder{
TextView stname, stroll;
LinearLayout parentLayout;
Button btnMark;
EditText wrText;
//String wrMark;
public MyCustomEditTextListener myCustomEditTextListener;
public NviewHolder(#NonNull View itemView, MyCustomEditTextListener myCustomEditTextListener) {
super(itemView);
stname =itemView.findViewById(R.id.clsmarkName);
stroll =itemView.findViewById(R.id.clsmkRoll);
parentLayout = itemView.findViewById(R.id.ctMarkList);
btnMark =itemView.findViewById(R.id.clsmarkBtn);
this.wrText = itemView.findViewById(R.id.editText);
this.myCustomEditTextListener = myCustomEditTextListener;
this.wrText.addTextChangedListener(myCustomEditTextListener);
}
}
private class MyCustomEditTextListener implements TextWatcher {
private int position;
public void updatePosition(int position) {
this.position = position;
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
marklist[position] = s.toString();
}
#Override
public void afterTextChanged(Editable s) {
}
}
}
Update your list item on text change using text watcher after setText to edit text.
Or Alternatively, For best practices use two way data binding to overcome this issue.

Implementing Search filter Causing problem when pressed backspace

I am trying to implement a search filter on complex object data in recyclerview when I type in the Edit text first-time it works properly, but whenever I try to delete characters by pressing back-space in order to modify our search- I am repeatedly failing in this regard.
I can only search once !!
etSearch = (EditText) findViewById(R.id.edittext);
etSearch.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) {
myAdapter.filter(s);
}
#Override
public void afterTextChanged(Editable s) {
}
});
now the filter code
public void filter(CharSequence sequence) {
ArrayList<user> temp = new ArrayList<>();
if (!TextUtils.isEmpty(sequence)) {
for (user s : arr) {
Log.d("users ",s.getName());
if (s.getName().toLowerCase().contains(sequence)) {
temp.add(s);
}
}
} else {
temp.addAll(arrcopy);
}
arr.clear();
arr.addAll(temp);
notifyDataSetChanged();
temp.clear();
}
Whats the issue, I cannot search more than once-any help is appreciated
Here is my Adapter class
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.MyHolder>
{
Context cxt;
ArrayList<user> arr;
ArrayList<user> arrcopy;
DatabaseReference dref;
MyAdapter myAdapter;
public MyAdapter(Context context, ArrayList<user> arrayList)
{
cxt = context;
arr = arrayList;
arrcopy=new ArrayList<>(arr);
Log.d("Very start arr",arr.toString());
notifyDataSetChanged();
dref = FirebaseDatabase.getInstance().getReference("users");
}
#NonNull
#Override
public MyHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(cxt).inflate(R.layout.item_chatroom,viewGroup,false);
myAdapter = new MyAdapter(cxt, arr);
Log.d("Inside MyHolder arr",arr.toString());
return new MyHolder(view);
}
#Override
public void onBindViewHolder(#NonNull final MyHolder myHolder,final int i) {
final String name = arr.get(i).getUsername();
String pic=arr.get(i).getPic();
final String mail=arr.get(i).getEmail();
myHolder.name.setText(name);
Glide.with(myHolder.profile.getContext())
.load(pic)
.into(myHolder.profile);
myHolder.name.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(cxt,MainActivity.class);
intent.putExtra("Id",arr.get(i).getId());
intent.putExtra("Name",arr.get(i).getUsername());
cxt.startActivity(intent);
}
});
myHolder.info.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final SweetAlertDialog pDialog = new SweetAlertDialog(cxt, SweetAlertDialog.SUCCESS_TYPE);
pDialog.setTitleText("User Information e-mail ID");
pDialog.setContentText("Name: "+name+"\n\n E-mail: "+mail);
pDialog.setConfirmText("Ok");
pDialog.show();
}
});
}
#Override
public int getItemCount() {
return arr.size();
}
class MyHolder extends RecyclerView.ViewHolder
{
TextView name;
ImageView profile,info;
public MyHolder(#NonNull View itemView) {
super(itemView);
name = itemView.findViewById(R.id.txv);
profile=itemView.findViewById(R.id.profile);
info=itemView.findViewById(R.id.profileinfo);
}
}
public void filter(CharSequence sequence) {
ArrayList<user> temp = new ArrayList<>();
if (!TextUtils.isEmpty(sequence)) {
for (user s : arr) {
if (s.getName().toLowerCase().contains(sequence)) {
temp.add(s);
}
}
} else {
temp.addAll(arrcopy);
}
arr.clear();
arr.addAll(temp);
notifyDataSetChanged();
temp.clear();
}
}
I assume the arrcopy is the copy of arr like:
ArrayList<User> arrcopy = new ArrayList<>(arr);
If you modify arr, it also change the content of arrcopy. And when no result matches, the arr is empty, so is the arrcopy.
else {
temp.addAll(arrcopy);
}
arr.clear();
arr.addAll(temp);
Now temp is empty, the arr data you set for adapter is empty, so issues happens.
Please try:
In MyAdapter:
Context cxt;
ArrayList<user> arr;
public MyAdapter(Context context) {
cxt = context;
dref = FirebaseDatabase.getInstance().getReference("users");
}
public void setData(ArrayList<User> arrayList) {
arr = arrayList;
notifyDataSetChanged();
}
Also put the filter() in your activity/fragment:
protected void onCreate(final Bundle savedInstanceState) {
etSearch = (EditText) findViewById(R.id.edittext);
etSearch.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
etSearch.requestFocus();
}
});
etSearch.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) {
filter(etSearch.getText().toString());
}
#Override
public void afterTextChanged(Editable s) {
}
});
etSearch.clearFocus();
mAdapter = new MyAdapter(this);
mAdapter.setData(arrayList);
mRecyclerView.setAdapter(mAdapter);
...
}
public void filter(String input) {
if (!TextUtils.isEmpty(input)) {
ArrayList<User> temp = new ArrayList<>();
for (user s : arr) {
if (s.getName().toLowerCase().contains(input)) {
temp.add(s);
}
}
mAdapter.setData(temp);
} else {
mAdapter.setData(arr);
}
mAdapter.notifyDataSetChanged();
}
Implement Filterable in your MyAdapter
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.MyHolder>
implements Filterable {
// change MyObject to user class
//replace myObjects with arr and reservedList with arrcopy
Context cxt;
ArrayList<MyObject> myObjects;
ArrayList<MyObject> reservedList;
DatabaseReference dref;
public MyAdapter(Context context, ArrayList<MyObject> arrayList){
cxt = context;
myObjects = arrayList;
reservedList = arrayList
Log.d("Very start arr",myObjects.toString());
// notifyDataSetChanged();
dref = FirebaseDatabase.getInstance().getReference("users");
}
//...
#Override
public Filter getFilter() {
return new Filter() {
#Override
protected FilterResults performFiltering(CharSequence charSequence) {
String charString = charSequence.toString().toLowerCase();
if (!charString.isEmpty()) {
List<MyObject> filteredList = new ArrayList<>();
for (MyObject row : reservedList) {
if (row.getName().toLowerCase().contains(charString)){
filteredList.add(row);
}
}
myObjects = filteredList;
} else {
myObjects = reservedList;
}
FilterResults filterResults = new FilterResults();
filterResults.values = myObjects;
return filterResults;
}
#Override
protected void publishResults(CharSequence charSequence, FilterResults filterResults) {
myObjects = (ArrayList<MyObject>) filterResults.values;
notifyDataSetChanged();
}
};
}
and from your activity
etSearch = (EditText) findViewById(R.id.edittext);
etSearch.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) {
myAdapter.getFilter().filter(s);
}
#Override
public void afterTextChanged(Editable s) {
}
});

Firebase database my data is not pushing. And getting DatabaseException error when I add a child Manually

Hello I'm using a custom adapter to assign how I handle my firebase objects and then using a dialog to to assign the variables on my fragment. I need help concerning the fact that the data's I'm assigning to is not pushing into my firebase. Can I ask why?
*EDIT ADDDED INFO CLASS AND DATABASE SCHEMA
Codes of my Adapter
public class UserTransactionAdapter extends RecyclerView.Adapter<UserTransactionAdapter.ViewHolder> {
private List<Info> mInfo;
private Callback mCallback;
private DatabaseReference userref;
public UserTransactionAdapter(Callback callback) {
mCallback = callback;
mInfo = new ArrayList<>();
userref = FirebaseDatabase.getInstance().getReference().child("Transactions");
userref.addChildEventListener(new UserChildEventListener());
}
class UserChildEventListener implements ChildEventListener{
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
Info info = dataSnapshot.getValue(Info.class);
info.setKey(dataSnapshot.getKey());
mInfo.add(0,info);
notifyDataSetChanged();
}
#Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
String key = dataSnapshot.getKey();
Info updatedInfo = dataSnapshot.getValue(Info.class);
for (Info info : mInfo){
if (info.getKey().equals(key)){
info.setValues(updatedInfo);
notifyDataSetChanged();
return;
}
}
}
#Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
String key = dataSnapshot.getKey();
for(Info info: mInfo){
if (info.getKey().equals(key)){
mInfo.remove(info);
break;
}
}
notifyDataSetChanged();
}
#Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.modelinfo, parent, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(ViewHolder holder, final int position) {
final Info info = mInfo.get(position);
holder.mNameTextView.setText(info.getName());
holder.mMonthTextView.setText(info.getMonth());
holder.mPayTextView.setText(info.getPay());
holder.mUntilTextView.setText(info.getUntil());
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mCallback.onEdit(info);
}
});
}
public void remove(Info info) {
//TODO: Remove the next line(s) and use Firebase instead
userref.child(info.getKey()).removeValue();
}
#Override
public int getItemCount() {
return mInfo.size();
}
public void add(Info info) {
//TODO: Remove the next line(s) and use Firebase instead
userref.push().setValue(info);
}
public void update(Info info, String newName,String newMonth,String newPay, String newUntil) {
//TODO: Remove the next line(s) and use Firebase instead
info.setName(newName);
info.setMonth(newMonth);
info.setPay(newPay);
info.setUntil(newUntil);
userref.child(info.getKey()).setValue(info);
}
public interface Callback {
public void onEdit(Info info);
}
class ViewHolder extends RecyclerView.ViewHolder {
private TextView mNameTextView;
private TextView mMonthTextView;
private TextView mPayTextView;
private TextView mUntilTextView;
public ViewHolder(View itemView) {
super(itemView);
mNameTextView = (TextView) itemView.findViewById(R.id.nameTxt);
mMonthTextView = (TextView) itemView.findViewById(R.id.monthTxt);
mPayTextView = (TextView) itemView.findViewById(R.id.payTxt);
mUntilTextView = (TextView) itemView.findViewById(R.id.untilTxt);
}
}
And codes of my Fragment
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
final View view = inflater.inflate(R.layout.fragment_transaction, container, false);
FloatingActionButton fab = (FloatingActionButton) view.findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
showAddEditDialog(null);
}
});
mAdapter = new com.google.firebase.ikuzou.database.UserTransactionAdapter(this);
RecyclerView view1 = (RecyclerView) view.findViewById(R.id.recycler_view);
view1.setLayoutManager(new LinearLayoutManager(getContext()));
view1.setHasFixedSize(true);
view1.setAdapter(mAdapter);
return view;
}
private void showAddEditDialog(final Info info) {
AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
builder.setTitle(getString(info == null ? R.string.dialog_add_title2 : R.string.dialog_edit_title2));
View view = getLayoutInflater().inflate(R.layout.dialog_info, null, false);
builder.setView(view);
final EditText nameEditText = (EditText) view.findViewById(R.id.nameEditText);
final EditText monthEditText = (EditText) view.findViewById(R.id.monthEditText);
final EditText payEditText = (EditText) view.findViewById(R.id.payEditText);
final EditText untilEditText = (EditText) view.findViewById(R.id.untilEditText);
if (info != null) {
// pre-populate
nameEditText.setText(info.getName());
monthEditText.setText(info.getMonth());
payEditText.setText(info.getPay());
untilEditText.setText(info.getUntil());
TextWatcher textWatcher = new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
// empty
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
// empty
}
#Override
public void afterTextChanged(Editable s) {
String name = nameEditText.getText().toString();
String month = monthEditText.getText().toString();
String pay = payEditText.getText().toString();
String until = untilEditText.getText().toString();
mAdapter.update(info, name,month,pay,until );
}
};
nameEditText.addTextChangedListener(textWatcher);
monthEditText.addTextChangedListener(textWatcher);
payEditText.addTextChangedListener(textWatcher);
untilEditText.addTextChangedListener(textWatcher);
}
builder.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
if (info == null) {
String name = nameEditText.getText().toString();
String month = monthEditText.getText().toString();
String pay = payEditText.getText().toString();
String until = untilEditText.getText().toString();
mAdapter.add(new Info(name, month,pay,until));
}
}
});
builder.setNegativeButton(android.R.string.cancel, null);
builder.create().show();
Can I know the errors on my codes so that I can know why this is happening? Or perhaps is it because I still haven't created a transaction node yet that's why this is happening?
EDIT
I tried to add child nodes manually and now I'm getting
DatabaseException: Can't convert object of type java.lang.String to
type error
Here is my info class codes
public class Info {
private String name,month,pay,until,key;
public Info (){
}
public Info(String name, String month, String pay, String expire) {
this.name= this.name;
this.month= this.month;
this.pay= this.pay;
this.until= this.until;
}
public String getName(){
return name;
}
public void setName(String name){
this.name=name;
}
public String getMonth(){
return month;
}
public void setMonth(String month){
this.month=month;
}
public String getPay(){
return pay;
}
public void setPay(String pay){
this.pay=pay;
}
public String getUntil(){
return until;
}
public void setUntil(String until){
this.until=until;
}
#Exclude
public String getKey(){
return key;
}
public void setKey(String key){
this.key = key;
}
public void setValues(Info updatedInfo) {
this.name=updatedInfo.name;
this.month=updatedInfo.month;
this.pay=updatedInfo.pay;
this.until=updatedInfo.until;
}
My Database
You have added a childEventListner and all of these functions will only run when a child is added,removed or changed under the node "Transactions". So try adding a child to the node "Transactions".
According to the docs, child_added is triggered once for each existing child and then again every time a new child is added to the specified path.
Ref: https://firebase.google.com/docs/database/admin/retrieve-data
userref.child(info.getKey()).setValue(info);
this line should be like this.
userref.child(info.getKey()).push().setValue(info);
FIXED IT. It was a stupid mistake by me from my Info.class
Added a this.
public Info(String name, String month, String pay, String expire) {
this.name= this.name;
this.month= this.month;
this.pay= this.pay;
this.until= this.until;
Instead of
this.name= name;
this.month= month;
this.pay= pay;
this.until= until;
So solution was removing the this and simply put month,pay,until
Problem is fixed now by removing this

how to refresh my custom listview

I'm updating the database to other classes and I want the custom listview to be updated when I get to the main activity. My customListview is still standing
I have searched for this problem, but I could not solve it myself. Where should I add the code to solve this problem? Please help me 3 days did not solve my problem.
public class MainActivity extends AppCompatActivity {
veritabani vtabani; //database
List<Yukleclas> yuklele =new ArrayList<Yukleclas>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
vtabani=new veritabani(this);
OzelAdaptor adaptor=new OzelAdaptor(this,yuklele);
ListView listView=(ListView) findViewById(R.id.listview);
String[] sutunlar =
{"id","bilgi","simdikiyil","simdikiay","simdikigun","alarmsaat",
"alarmdakika","gsonrayil","gsonraay","gsonragun","hsonrayil","hsonraay",
"hsonragun","asonrayil","asonraay","asonragun","seviye","durum"};
SQLiteDatabase dboku =vtabani.getReadableDatabase();
Cursorcursor=dboku.query("tablo_adi",sutunlar,null,null,null,null,null);
while (cursor.moveToNext()) {
if (cursor.getInt(17)==1) {
yuklele.add(new Yukleclas(cursor.getString(1), cursor.getInt(2),
cursor.getInt(3), cursor.getInt(4),
cursor.getInt(7),cursor.getInt(8),cursor.getInt(9),cursor.getInt(10),
cursor.getInt(11),cursor.getInt(12),cursor.getInt(13),cursor.getInt(14),
cursor.getInt(15),cursor.getInt(16)));
}
}
cursor.close();
dboku.close();
listView.setAdapter(adaptor);
adaptor.notifyDataSetChanged();
}
public void ekleyegit(View view) {
Intent intent =new Intent(this,ekleactivity.class);
startActivity(intent);
finish();
}}
and this is myAdapter:
public class OzelAdaptor extends BaseAdapter {
LayoutInflater layoutInflater;
List<Yukleclas> list;
public OzelAdaptor(Activity activity,List<Yukleclas> mList){
layoutInflater= (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
list=mList;
}
#Override
public int getCount() {
return list.size();
}
#Override
public Object getItem(int position) {
return list.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View satirView;
satirView=layoutInflater.inflate(R.layout.satir,null);
TextView tv_tarih = (TextView) satirView.findViewById(R.id.text_tarih);
TextView tv_bilgi= (TextView) satirView.findViewById(R.id.text_bilgi);
ImageView imageView= (ImageView) satirView.findViewById(R.id.imageView);
Yukleclas yukleclas =list.get(position);
tv_bilgi.setText(yukleclas.getBilgi());
if(yukleclas.getSeviye()==1){
tv_tarih.setText("Sonraki tekrar:" +yukleclas.getGun() +"/" +yukleclas.getAy() + "/" +yukleclas.getYil() );
}else if(yukleclas.getSeviye()==2){
tv_tarih.setText("Sonraki tekrar:" +yukleclas.getGsgun() +"/" +yukleclas.getGsay() + "/" +yukleclas.getGsyil() );
}else if (yukleclas.getSeviye()==3){
tv_tarih.setText("Sonraki tekrar:" +yukleclas.getHsgun() +"/" +yukleclas.getHsay() + "/" +yukleclas.getHsyil() );
}else if (yukleclas.getSeviye()==4){
tv_tarih.setText("Sonraki tekrar:" +yukleclas.getAsgun() +"/" +yukleclas.getAsay() + "/" +yukleclas.getAsyil() );
}
if(yukleclas.getSeviye()==1){
imageView.setImageResource(bir); // eğer 1. seviyede ise bir isimli ikonu göster
}else if(yukleclas.getSeviye()==2){
imageView.setImageResource(iki);
}else if(yukleclas.getSeviye()==3){
imageView.setImageResource(uc);
}else if(yukleclas.getSeviye()==4){
imageView.setImageResource(ic_launcher);
}
return satirView;
}
}
and this is my class to get-set:
public class Yukleclas {
private String bilgi;
private int yil;
private int ay;
private int gun;
private int seviye;
private int gsyil;
private int gsay;
private int gsgun;
private int hsyil;
private int hsay;
private int hsgun;
private int asyil;
private int asay;
private int asgun;
public Yukleclas(String mBilgi,int mYil,int mAy,int mGun,int mGsyil,int
mGsay,int mGsgun,int mHsyil,int mHsay,int mHsgun,int mAsyil,int mAsay,int
mAsgun,int mSeviye){
yil=mYil;
bilgi=mBilgi;
ay=mAy;
gun=mGun;
gsyil=mGsyil;
gsay=mGsay;
gsgun=mGsgun;
hsyil=mHsyil;
hsay=mHsay;
hsgun=mHsgun;
asyil=mAsyil;
asay=mAsay;
asgun=mAsgun;
seviye=mSeviye;
}
public int getYil() {
return yil;
}
public void setYil(int yil) {
this.yil = yil;
}
public int getSeviye() {
return seviye;
}
public void setSeviye(int yil) {
this.seviye = seviye;
}
public String getBilgi() {
return bilgi;
}
public void setBilgi(String bilgi) {
this.bilgi = bilgi;
}
public int getAy() {
return ay;
}
public void setAy(int ay) {
this.ay = ay;
}
public int getGun() {
return gun;
}
public void setGun(int gun) {
this.gun = gun;
}
public int getGsyil() {return gsyil;
}
public void setGsyil(int gsyil) {this.gsyil = gsyil;
}
public int getGsay() {return gsay;
}
public void setGsay(int gsay) {this.gsay = gsay;
}
public int getGsgun() {return gsgun;
}
public void setGsgun(int gsgun) {this.gsgun = gsgun;
}
public int getHsyil() {return hsyil;
}
public void setHsyil(int hsyil) {this.hsyil = hsyil;
}
public int getHsay() {return hsay;
}
public void setHsay(int hsay) {this.hsay = hsay;
}
public int getHsgun() {return hsgun;
}
public void setHsgun(int hsgun) {this.hsgun = hsgun;
}
public int getAsyil() {return asyil;
}
public void setAsyil(int asyil) {this.asyil = asyil;
}
public int getAsay() {return asay;
}
public void setAsay(int asay) {this.asay = asay;
}
public int getAsgun() {return asgun;
}
public void setAsgun(int asgun) {this.asgun = asgun;
}
}
I know it is very complex but How to replace my customlistview ?
Easy way is to call adapter.notifyDataSetChanged() in your onResume function.
But I would suggest you check if your list has been updated then only you call adapter.notifyDataSetChanged(). You can do this in multiple ways, but for a cleaner approach use EventBus which allows you to fire events and listen to them, So you can fire an event every time you update your dataBaseand on listening to this event, simply call adapter.notifyDataSetChanged

Setting text to a custom dialog class

I am setting text to a custom dialog box. I am getting a NullPointerException. The dialog is called when a listItem is clicked. EDIT, Scroll to the bottom to see updated code. Or See here:
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
HomeItem homeItem = (HomeItem) adapter.getItem(position);
DialogClass dialogClass = new DialogClass(databaseFightCard.this);
dialogClass.setDialog(homeItem.getHomeItemRedName(), homeItem.getHomeItemRedAge(), homeItem.getHomeItemRedRecord(),
homeItem.getHomeItemRedHeight(), homeItem.getHomeItemRedWeight(), homeItem.getHomeItemRedCity(), homeItem.getHomeItemRedExp(),
homeItem.getHomeItemBlueName(), homeItem.getHomeItemBlueAge(), homeItem.getHomeItemBlueRecord(), homeItem.getHomeItemBlueHeight(),
homeItem.getHomeItemBlueWeight(), homeItem.getHomeItemBlueCity(), homeItem.getHomeItemBlueExp());
dialogClass.show();
}
});
DialogClass
public class DialogClass extends Dialog implements View.OnClickListener {
public Activity c;
public Dialog d;
public Button yes, no;
public TextView rn, ra, rr, rh, rw, rc, re, bn, ba, br, bh, bw, bc, be;
public void setDialog(String redName, String redAge, String redRecord, String redHeight,
String redWeight, String redCity, String redExp,String blueName, String blueAge,
String blueRecord, String blueHeight,
String blueWeight, String blueCity, String blueExp){
rn = (TextView) findViewById(R.id.tvRName);
ra = (TextView) findViewById(R.id.tvRAge);
rr = (TextView) findViewById(R.id.tvRRecord);
rh = (TextView) findViewById(R.id.tvRHeight);
rw = (TextView) findViewById(R.id.tvRWeight);
rc = (TextView) findViewById(R.id.tvRCity);
re = (TextView) findViewById(R.id.tvRExp);
bn = (TextView) findViewById(R.id.tvBName);
ba = (TextView) findViewById(R.id.tvBAge);
br = (TextView) findViewById(R.id.tvBRecord);
bh = (TextView) findViewById(R.id.tvBHeight);
bw = (TextView) findViewById(R.id.tvBWeight);
bc = (TextView) findViewById(R.id.tvBCity);
be = (TextView) findViewById(R.id.tvBExp);
<----------Where the NullPointer is being thrown----------->
rn.setText(redName);
ra.setText(redAge);
rr.setText(redRecord);
rh.setText(redHeight);
rw.setText(redWeight);
rc.setText(redCity);
re.setText(redExp);
bn.setText(blueName);
ba.setText(blueAge);
br.setText(blueRecord);
bh.setText(blueHeight);
bw.setText(blueWeight);
bc.setText(blueCity);
be.setText(blueExp);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.custom_dialog);
yes = (Button) findViewById(R.id.bPlay);
no = (Button) findViewById(R.id.bDone);
yes.setOnClickListener(this);
no.setOnClickListener(this);
}
public DialogClass(Activity a) {
super(a);
this.c = a;
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.bPlay:
dismiss();
break;
case R.id.bDone:
dismiss();
break;
default:
break;
}
dismiss();
}
}
LogCat
10-05 18:48:01.843 994-994/com.codealchemist.clashmma E/AndroidRuntime﹕ FATAL EXCEPTION: main
java.lang.NullPointerException
at com.codealchemist.clashmma.DialogClass.setDialog(DialogClass.java:43)
at com.codealchemist.clashmma.databaseFightCard$1.onItemClick(databaseFightCard.java:71)
at android.widget.AdapterView.performItemClick(AdapterView.java:298)
at android.widget.AbsListView.performItemClick(AbsListView.java:1100)
at android.widget.AbsListView$PerformClick.run(AbsListView.java:2749)
at android.widget.AbsListView$1.run(AbsListView.java:3423)
at android.os.Handler.handleCallback(Handler.java:725)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:5041)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
at dalvik.system.NativeStart.main(Native Method)
The LogCat is point to my DialogClass on the line
rn.setText(redName);
I have never set the text to a custom built dialog, so please explain what I am doing wrong.
EDIT DUE TO blackbelt This is how I tried to do a class member. If it is not obvious by my reputation, I am a beginner so please explain a better way to do this:
Changed this in my activity that calls for the dialog
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
HomeItem homeItem = (HomeItem) adapter.getItem(position);
DialogClass dialogClass = new DialogClass(homeItem);
dialogClass.show();
}
});
Changed this in my DialogClass
public DialogClass(HomeItem context) {
super(context);
this.hi = context;
}
Then in my onCreate of my DialogClass:
rn.setText(hi.getHomeItemRedName());
bn.setText(hi.getHomeItemBlueName());
Because I had to use Context of HomeItem, or whatever I did I have to make my HomeItem class extend Context. I had to #Override about 80 methods:
public class HomeItem extends Context {
private int HomeItemID;
private String HomeItemRedName, HomeItemRedAge, HomeItemRedRecord, HomeItemRedHeight, HomeItemRedWeight,
HomeItemRedCity, HomeItemRedExp;
private String HomeItemBlueName, HomeItemBlueAge, HomeItemBlueRecord, HomeItemBlueHeight, HomeItemBlueWeight,
HomeItemBlueCity, HomeItemBlueExp;
public int getHomeItemID() {
return HomeItemID;
}
public void setHomeItemID(int ID) {
this.HomeItemID = ID;
}
public String getHomeItemRedName() {
return HomeItemRedName;
}
public void setHomeItemRedName(String Name) {
this.HomeItemRedName = Name;
}
public String getHomeItemRedAge(){
return HomeItemRedAge;
}
public void setHomeItemRedAge(String Age){
if (Age == null)
this.HomeItemRedAge = "Unknown";
this.HomeItemRedAge = Age;
}
public String getHomeItemRedRecord(){
return HomeItemRedRecord;
}
public void setHomeItemRedRecord(String Record){
if (Record == null)
this.HomeItemRedRecord = "Unknown";
this.HomeItemRedRecord = Record;
}
public String getHomeItemRedHeight(){
return HomeItemRedHeight;
}
public void setHomeItemRedHeight(String Height){
if (Height == null)
this.HomeItemRedHeight = "Unknown";
this.HomeItemRedHeight = Height;
}
public String getHomeItemRedWeight(){
return HomeItemRedWeight;
}
public void setHomeItemRedWeight(String Weight){
if (Weight == null)
this.HomeItemRedWeight = "Unknown";
this.HomeItemRedWeight = Weight;
}
public String getHomeItemRedCity(){
return HomeItemRedCity;
}
public void setHomeItemRedCity(String City){
if (City == null)
this.HomeItemRedCity = "Unknown";
this.HomeItemRedCity = City;
}
public String getHomeItemRedExp(){
return HomeItemRedExp;
}
public void setHomeItemRedExp(String Exp){
if (Exp == null)
this.HomeItemRedExp = "Unknown";
this.HomeItemRedExp = Exp;
}
//Blue side
public String getHomeItemBlueName(){
return HomeItemBlueName;
}
public void setHomeItemBlueName(String Name){
this.HomeItemBlueName = Name;
}
public String getHomeItemBlueAge(){
return HomeItemBlueAge;
}
public void setHomeItemBlueAge(String Age){
if (Age == null)
this.HomeItemBlueAge = "Unknown";
this.HomeItemBlueAge = Age;
}
public String getHomeItemBlueRecord(){
return HomeItemBlueRecord;
}
public void setHomeItemBlueRecord(String Record){
if (Record == null)
this.HomeItemBlueRecord = "Unknown";
this.HomeItemBlueRecord = Record;
}
public String getHomeItemBlueHeight(){
return HomeItemBlueHeight;
}
public void setHomeItemBlueHeight(String Height){
if (Height == null)
this.HomeItemBlueHeight = "Unknown";
this.HomeItemBlueHeight = Height;
}
public String getHomeItemBlueWeight(){
return HomeItemBlueWeight;
}
public void setHomeItemBlueWeight(String Weight){
if (Weight == null)
this.HomeItemBlueWeight = "Unknown";
this.HomeItemBlueWeight = Weight;
}
public String getHomeItemBlueCity(){
return HomeItemBlueCity;
}
public void setHomeItemBlueCity(String City){
if (City == null)
this.HomeItemBlueCity = "Unknown";
this.HomeItemBlueCity= City;
}
public String getHomeItemBlueExp(){
return HomeItemBlueExp;
}
public void setHomeItemBlueExp(String Exp){
if (Exp == null)
this.HomeItemBlueExp = "Unknown";
this.HomeItemBlueExp = Exp;
}
#Override
public AssetManager getAssets() {
return null;
}
#Override
public Resources getResources() {
return null;
}
#Override
public PackageManager getPackageManager() {
return null;
}
#Override
public ContentResolver getContentResolver() {
return null;
}
#Override
public Looper getMainLooper() {
return null;
}
#Override
public Context getApplicationContext() {
return null;
}
#Override
public void setTheme(int i) {
}
#Override
public Resources.Theme getTheme() {
return null;
}
#Override
public ClassLoader getClassLoader() {
return null;
}
#Override
public String getPackageName() {
return null;
}
#Override
public ApplicationInfo getApplicationInfo() {
return null;
}
#Override
public String getPackageResourcePath() {
return null;
}
#Override
public String getPackageCodePath() {
return null;
}
#Override
public SharedPreferences getSharedPreferences(String s, int i) {
return null;
}
#Override
public FileInputStream openFileInput(String s) throws FileNotFoundException {
return null;
}
#Override
public FileOutputStream openFileOutput(String s, int i) throws FileNotFoundException {
return null;
}
#Override
public boolean deleteFile(String s) {
return false;
}
#Override
public File getFileStreamPath(String s) {
return null;
}
#Override
public File getFilesDir() {
return null;
}
#Override
public File getExternalFilesDir(String s) {
return null;
}
#Override
public File getObbDir() {
return null;
}
#Override
public File getCacheDir() {
return null;
}
#Override
public File getExternalCacheDir() {
return null;
}
#Override
public String[] fileList() {
return new String[0];
}
#Override
public File getDir(String s, int i) {
return null;
}
#Override
public SQLiteDatabase openOrCreateDatabase(String s, int i, SQLiteDatabase.CursorFactory cursorFactory) {
return null;
}
#Override
public SQLiteDatabase openOrCreateDatabase(String s, int i, SQLiteDatabase.CursorFactory cursorFactory, DatabaseErrorHandler databaseErrorHandler) {
return null;
}
#Override
public boolean deleteDatabase(String s) {
return false;
}
#Override
public File getDatabasePath(String s) {
return null;
}
#Override
public String[] databaseList() {
return new String[0];
}
#Override
public Drawable getWallpaper() {
return null;
}
#Override
public Drawable peekWallpaper() {
return null;
}
#Override
public int getWallpaperDesiredMinimumWidth() {
return 0;
}
#Override
public int getWallpaperDesiredMinimumHeight() {
return 0;
}
#Override
public void setWallpaper(Bitmap bitmap) throws IOException {
}
#Override
public void setWallpaper(InputStream inputStream) throws IOException {
}
#Override
public void clearWallpaper() throws IOException {
}
#Override
public void startActivity(Intent intent) {
}
#Override
public void startActivity(Intent intent, Bundle bundle) {
}
#Override
public void startActivities(Intent[] intents) {
}
#Override
public void startActivities(Intent[] intents, Bundle bundle) {
}
#Override
public void startIntentSender(IntentSender intentSender, Intent intent, int i, int i2, int i3) throws IntentSender.SendIntentException {
}
#Override
public void startIntentSender(IntentSender intentSender, Intent intent, int i, int i2, int i3, Bundle bundle) throws IntentSender.SendIntentException {
}
#Override
public void sendBroadcast(Intent intent) {
}
#Override
public void sendBroadcast(Intent intent, String s) {
}
#Override
public void sendOrderedBroadcast(Intent intent, String s) {
}
#Override
public void sendOrderedBroadcast(Intent intent, String s, BroadcastReceiver broadcastReceiver, Handler handler, int i, String s2, Bundle bundle) {
}
#Override
public void sendBroadcastAsUser(Intent intent, UserHandle userHandle) {
}
#Override
public void sendBroadcastAsUser(Intent intent, UserHandle userHandle, String s) {
}
#Override
public void sendOrderedBroadcastAsUser(Intent intent, UserHandle userHandle, String s, BroadcastReceiver broadcastReceiver, Handler handler, int i, String s2, Bundle bundle) {
}
#Override
public void sendStickyBroadcast(Intent intent) {
}
#Override
public void sendStickyOrderedBroadcast(Intent intent, BroadcastReceiver broadcastReceiver, Handler handler, int i, String s, Bundle bundle) {
}
#Override
public void removeStickyBroadcast(Intent intent) {
}
#Override
public void sendStickyBroadcastAsUser(Intent intent, UserHandle userHandle) {
}
#Override
public void sendStickyOrderedBroadcastAsUser(Intent intent, UserHandle userHandle, BroadcastReceiver broadcastReceiver, Handler handler, int i, String s, Bundle bundle) {
}
#Override
public void removeStickyBroadcastAsUser(Intent intent, UserHandle userHandle) {
}
#Override
public Intent registerReceiver(BroadcastReceiver broadcastReceiver, IntentFilter intentFilter) {
return null;
}
#Override
public Intent registerReceiver(BroadcastReceiver broadcastReceiver, IntentFilter intentFilter, String s, Handler handler) {
return null;
}
#Override
public void unregisterReceiver(BroadcastReceiver broadcastReceiver) {
}
#Override
public ComponentName startService(Intent intent) {
return null;
}
#Override
public boolean stopService(Intent intent) {
return false;
}
#Override
public boolean bindService(Intent intent, ServiceConnection serviceConnection, int i) {
return false;
}
#Override
public void unbindService(ServiceConnection serviceConnection) {
}
#Override
public boolean startInstrumentation(ComponentName componentName, String s, Bundle bundle) {
return false;
}
#Override
public Object getSystemService(String s) {
return null;
}
#Override
public int checkPermission(String s, int i, int i2) {
return 0;
}
#Override
public int checkCallingPermission(String s) {
return 0;
}
#Override
public int checkCallingOrSelfPermission(String s) {
return 0;
}
#Override
public void enforcePermission(String s, int i, int i2, String s2) {
}
#Override
public void enforceCallingPermission(String s, String s2) {
}
#Override
public void enforceCallingOrSelfPermission(String s, String s2) {
}
#Override
public void grantUriPermission(String s, Uri uri, int i) {
}
#Override
public void revokeUriPermission(Uri uri, int i) {
}
#Override
public int checkUriPermission(Uri uri, int i, int i2, int i3) {
return 0;
}
#Override
public int checkCallingUriPermission(Uri uri, int i) {
return 0;
}
#Override
public int checkCallingOrSelfUriPermission(Uri uri, int i) {
return 0;
}
#Override
public int checkUriPermission(Uri uri, String s, String s2, int i, int i2, int i3) {
return 0;
}
#Override
public void enforceUriPermission(Uri uri, int i, int i2, int i3, String s) {
}
#Override
public void enforceCallingUriPermission(Uri uri, int i, String s) {
}
#Override
public void enforceCallingOrSelfUriPermission(Uri uri, int i, String s) {
}
#Override
public void enforceUriPermission(Uri uri, String s, String s2, int i, int i2, int i3, String s3) {
}
#Override
public Context createPackageContext(String s, int i) throws PackageManager.NameNotFoundException {
return null;
}
#Override
public Context createConfigurationContext(Configuration configuration) {
return null;
}
#Override
public Context createDisplayContext(Display display) {
return null;
}
Compiling this, in my LogCat, I receive this error:
10-06 18:42:59.465 785-785/com.codealchemist.clashmma E/AndroidRuntime﹕ FATAL EXCEPTION: main
java.lang.NullPointerException
at android.app.Dialog.<init>(Dialog.java:154)
at android.app.Dialog.<init>(Dialog.java:131)
at com.codealchemist.clashmma.DialogClass.<init>(DialogClass.java:83)
at com.codealchemist.clashmma.databaseFightCard$1.onItemClick(databaseFightCard.java:70)
at android.widget.AdapterView.performItemClick(AdapterView.java:298)
at android.widget.AbsListView.performItemClick(AbsListView.java:1100)
at android.widget.AbsListView$PerformClick.run(AbsListView.java:2749)
at android.widget.AbsListView$1.run(AbsListView.java:3423)
at android.os.Handler.handleCallback(Handler.java:725)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:5041)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
at dalvik.system.NativeStart.main(Native Method)
I ALSO TRIED THIS
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
HomeItem homeItem = (HomeItem) adapter.getItem(position);
final Dialog dialog = new Dialog(databaseFightCard.this, android.R.style.Theme_Black_NoTitleBar_Fullscreen);
WindowManager.LayoutParams lp = (dialog.getWindow().getAttributes());
lp.dimAmount = 0.5f;
dialog.getWindow().addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
Window window = dialog.getWindow();
window.setGravity(Gravity.CENTER);
dialog.setContentView(R.layout.custom_dialog);
Button play = (Button) findViewById(R.id.bPlay);
Button done = (Button) findViewById(R.id.bDone);
TextView rn = (TextView) findViewById(R.id.tvRName);
TextView ra = (TextView) findViewById(R.id.tvRAge);
TextView rr = (TextView) findViewById(R.id.tvRRecord);
TextView rh = (TextView) findViewById(R.id.tvRHeight);
TextView rw = (TextView) findViewById(R.id.tvRWeight);
TextView rc = (TextView) findViewById(R.id.tvRCity);
TextView re = (TextView) findViewById(R.id.tvRExp);
TextView bn = (TextView) findViewById(R.id.tvBName);
TextView ba = (TextView) findViewById(R.id.tvBAge);
TextView br = (TextView) findViewById(R.id.tvBRecord);
TextView bh = (TextView) findViewById(R.id.tvBHeight);
TextView bw = (TextView) findViewById(R.id.tvBWeight);
TextView bc = (TextView) findViewById(R.id.tvBCity);
TextView be = (TextView) findViewById(R.id.tvBExp);
rn.setText(homeItem.getHomeItemRedName()+"");
ra.setText(homeItem.getHomeItemRedAge()+"");
rr.setText(homeItem.getHomeItemRedRecord()+"");
rh.setText(homeItem.getHomeItemRedHeight()+"");
rw.setText(homeItem.getHomeItemRedWeight()+"");
rc.setText(homeItem.getHomeItemRedCity()+"");
re.setText(homeItem.getHomeItemRedExp()+"");
bn.setText(homeItem.getHomeItemBlueName()+"");
ba.setText(homeItem.getHomeItemBlueAge()+"");
br.setText(homeItem.getHomeItemBlueRecord()+"");
bh.setText(homeItem.getHomeItemBlueHeight()+"");
bw.setText(homeItem.getHomeItemBlueWeight()+"");
bc.setText(homeItem.getHomeItemBlueCity()+"");
be.setText(homeItem.getHomeItemBlueExp()+"");
play.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
dialog.dismiss();
}
});
done.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
dialog.dismiss();
}
});
dialog.show();
}
});
Still getting NullPointerException on
rn.setText(homeItem.getHomeItemRedName()+"");
setDialog is called before the Dialog's onCreate . Instead of passing all the Strings to setDialog you can pass a HomeItem reference and you can keep it as class member. Inside the onCreate, after setContentView you can perform all the findViewById and set the text accordingly
Edit
public class DialogClass extends Dialog implements View.OnClickListener {
public Activity c;
public Dialog d;
public Button yes, no;
public TextView rn, ra, rr, rh, rw, rc, re, bn, ba, br, bh, bw, bc, be;
private HomeItem homeItem;
public void setDialog(HomeItem homeItem){
this.homeItem = homeItem;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.custom_dialog);
yes = (Button) findViewById(R.id.bPlay);
no = (Button) findViewById(R.id.bDone);
yes.setOnClickListener(this);
no.setOnClickListener(this);
rn = (TextView) findViewById(R.id.tvRName);
ra = (TextView) findViewById(R.id.tvRAge);
rr = (TextView) findViewById(R.id.tvRRecord);
rh = (TextView) findViewById(R.id.tvRHeight);
rw = (TextView) findViewById(R.id.tvRWeight);
rc = (TextView) findViewById(R.id.tvRCity);
re = (TextView) findViewById(R.id.tvRExp);
bn = (TextView) findViewById(R.id.tvBName);
ba = (TextView) findViewById(R.id.tvBAge);
br = (TextView) findViewById(R.id.tvBRecord);
bh = (TextView) findViewById(R.id.tvBHeight);
bw = (TextView) findViewById(R.id.tvBWeight);
bc = (TextView) findViewById(R.id.tvBCity);
be = (TextView) findViewById(R.id.tvBExp);
rn.setText(homeItem.getHomeItemRedName());
// the rest of your code
}
// other code
}
This was actually really simple. I just ditched the Dialog class, and did it all here in my onClick.
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
HomeItem homeItem = (HomeItem) adapter.getItem(position);
final Dialog dialog = new Dialog(databaseFightCard.this);
Window window = dialog.getWindow();
window.setGravity(Gravity.CENTER);
window.requestFeature(window.FEATURE_NO_TITLE);
LayoutInflater inflater = (LayoutInflater) databaseFightCard.this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
RelativeLayout relative = (RelativeLayout) inflater.inflate(R.layout.custom_dialog, null, false);
dialog.setContentView(relative);
Button play = (Button) relative.findViewById(R.id.bPlay);
Button done = (Button) relative.findViewById(R.id.bDone);
TextView rn = (TextView) relative.findViewById(R.id.tvRName);
TextView ra = (TextView) relative.findViewById(R.id.tvRAge);
TextView rr = (TextView) relative.findViewById(R.id.tvRRecord);
TextView rh = (TextView) relative.findViewById(R.id.tvRHeight);
TextView rw = (TextView) relative.findViewById(R.id.tvRWeight);
TextView rc = (TextView) relative.findViewById(R.id.tvRCity);
TextView re = (TextView) relative.findViewById(R.id.tvRExp);
TextView bn = (TextView) relative.findViewById(R.id.tvBName);
TextView ba = (TextView) relative.findViewById(R.id.tvBAge);
TextView br = (TextView) relative.findViewById(R.id.tvBRecord);
TextView bh = (TextView) relative.findViewById(R.id.tvBHeight);
TextView bw = (TextView) relative.findViewById(R.id.tvBWeight);
TextView bc = (TextView) relative.findViewById(R.id.tvBCity);
TextView be = (TextView) relative.findViewById(R.id.tvBExp);
rn.setText(homeItem.getHomeItemRedName()+"");
ra.setText(homeItem.getHomeItemRedAge()+"");
rr.setText(homeItem.getHomeItemRedRecord()+"");
rh.setText(homeItem.getHomeItemRedHeight()+"");
rw.setText(homeItem.getHomeItemRedWeight()+"");
rc.setText(homeItem.getHomeItemRedCity()+"");
re.setText(homeItem.getHomeItemRedExp()+"");
bn.setText(homeItem.getHomeItemBlueName()+"");
ba.setText(homeItem.getHomeItemBlueAge()+"");
br.setText(homeItem.getHomeItemBlueRecord()+"");
bh.setText(homeItem.getHomeItemBlueHeight()+"");
bw.setText(homeItem.getHomeItemBlueWeight()+"");
bc.setText(homeItem.getHomeItemBlueCity()+"");
be.setText(homeItem.getHomeItemBlueExp()+"");
play.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
dialog.dismiss();
}
});
done.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
dialog.dismiss();
}
});
dialog.show();
}
});

Categories

Resources