I am new in android and I have two activities and each activity contains a recycled view. Now when I clicked on my first activity item, then this will go to new activity and get the result from second recycle view and I need to show this in my first recycle view, I have done all this, but am not able to get the value from second recycled view. How can i do this?
This is my some part of my code
holder.mGroup.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent individual = new Intent(Context, `enter code here`A.class);`enter code here`
individual.putExtra(Constants.REQ_TYPE,mCollectionDate);
individual.putExtra(Constants.GROUP_POSITION,position);
individual.putExtra(Constants.CENTER_POSITION,Selectedposition);
individual.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
((Activity)mContext).startActivityForResult(individual, 200);
//mContext.startActivity(individual);
}
});
}
Thank you!
You have to set a result on the second activity before get back:
Intent intent = new Intent();
intent.putExtra("parameter", response);
setResult(Activity.RESULT_OK, intent);
finish();
And then treat on the first activity:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if ( requestCode == 200 && resultCode == Activity.RESULT_OK ) {
<<YOUR PARAMETER>> = data.getExtra("parameter");
}
}
public class ApplicantDetailsAdapter extends RecyclerView.Adapter{
Context mContext;
String mCollectionDate;
public DemandSheetModel.DemandSheetResponse demandSheetResponse;
int selectedCenter,selectedGroup;
SingletonConfig instance = SingletonConfig.getInstance();
public ApplicantDetailsAdapter(DemandSheetModel.DemandSheetResponse response,Context context,String date,int group,int center){
if(response == null){
throw new IllegalArgumentException("List data must not be null");
}
demandSheetResponse = response;
mContext = context;
mCollectionDate = date;
selectedCenter = center;
selectedGroup = group;
}
#Override
public ApplicantViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.content_activity_individual_applicant,parent,false);
return new ApplicantViewHolder(view);
}
#Override
public void onBindViewHolder(final ApplicantViewHolder holder, int position) {
DemandSheetModel.ApplicantDemandSheet demandSheet = demandSheetResponse.centers_collections_list.get(selectedCenter).jlgs.get(selectedGroup).collection_list.get(position);
instance.setApplicantDemandSheet(demandSheetResponse.centers_collections_list.get(selectedCenter).jlgs.get(selectedGroup).collection_list.get(position));
holder.mIndividualTotalDemand.setText(demandSheet.total_demand);
holder.mIndividualAdvance.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 strAdvance = holder.mIndividualAdvance.getText().toString();
String strpreclosureTotal = holder.mIndividualPreclosure.getText().toString();
String strTotalDemand = holder.mIndividualTotalDemand.getText().toString();
int advanceTotal = strAdvance.trim().length() != 0 ? Integer.parseInt(strAdvance) : 0;
float f1 = Float.parseFloat(strTotalDemand);
int totalDemand = (int) f1;
int preclosureTotal = strpreclosureTotal.trim().length() != 0 ? Integer.parseInt(strpreclosureTotal) : 0;
int total = advanceTotal + preclosureTotal + totalDemand;
holder.mIndividualTotalCollection.setText(String.format("%d", total));
}
#Override
public void afterTextChanged(Editable s) {
}
});
holder.mIndividualPreclosure.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 strAdvance = holder.mIndividualAdvance.getText().toString();
String strpreclosureTotal = holder.mIndividualPreclosure.getText().toString();
String strTotalDemand = holder.mIndividualTotalDemand.getText().toString();
float f1 = Float.parseFloat(strTotalDemand);
int totalDemand = (int)f1;
int advanceTotal = strAdvance.trim().length() != 0 ? Integer.parseInt(strAdvance) : 0;
int preclosureTotal = strpreclosureTotal.trim().length() != 0 ? Integer.parseInt(strpreclosureTotal) : 0;
int total = advanceTotal + preclosureTotal+totalDemand;
holder.mIndividualTotalCollection.setText(String.format("%d", total));
}
#Override
public void afterTextChanged(Editable s) {
}
});
holder.mIndividualPaid.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
instance.getGroupDemandSheet().group_total_collection = holder.mIndividualTotalCollection.getText().toString();
instance.getApplicantDemandSheet().individual_payment = "paid";
}
}
});
holder.mIndividualAttendence.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if(isChecked){
instance.getApplicantDemandSheet().individual_attended = "present";
}
else {
instance.getApplicantDemandSheet().individual_attended = "absent";
}
}
});
}
#Override
public int getItemCount() {
int size = 0;
for (int i=0;i<demandSheetResponse.centers_collections_list.size();i++) {
DemandSheetModel.DemandSheet adapter = demandSheetResponse.centers_collections_list.get(i);
for(int j=0;j<adapter.jlgs.size();j++){
size = adapter.jlgs.get(j).collection_list.size();
}
}
return size;
}
public class ApplicantViewHolder extends RecyclerView.ViewHolder {
TextView mIndividual,mIndividualDmandPri,mIndividualDmandInt,mIndividualOverduePri,mIndividualOverdueInt,mIndividualTotalDemand,mIndividualTotalCollection;
EditText mIndividualAdvance,mIndividualPreclosure;
CheckBox mIndividualPaid,mIndividualAttendence;
public ApplicantViewHolder(View itemView) {
super(itemView);
mIndividualTotalDemand = (TextView)itemView.findViewById(R.id.individual_total_demand);
mIndividualAdvance = (EditText)itemView.findViewById(R.id.individual_advance);
mIndividualTotalCollection = (TextView)itemView.findViewById(R.id.individual_advance_total_collection);
mIndividualPaid = (CheckBox)itemView.findViewById(R.id.individual_paid_check);
mIndividualAttendence = (CheckBox)itemView.findViewById(R.id.individual_attendance_check);
mIndividualPreclosure = (EditText)itemView.findViewById(R.id.individual_advance_preclosure);
}
}
Related
I have a componed view in android contains several textViews and one EditText. I defined an attribute for my custom view called text and getText, setText methods. Now I want to add a 2-way data binding for my custom view in a way its bind to inner edit text so if my data gets updated edit text should be updated as well (that's works now) and when my edit text gets updated my data should be updated as well.
My binding class looks like this
#InverseBindingMethods({
#InverseBindingMethod(type = ErrorInputLayout.class, attribute = "text"),
})
public class ErrorInputBinding {
#BindingAdapter(value = "text")
public static void setListener(ErrorInputLayout errorInputLayout, final InverseBindingListener textAttrChanged) {
if (textAttrChanged != null) {
errorInputLayout.getInputET().addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
#Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
#Override
public void afterTextChanged(Editable editable) {
textAttrChanged.onChange();
}
});
}
}
}
I tried to bind text with the code below. userInfo is an observable class.
<ir.avalinejad.pasargadinsurance.component.ErrorInputLayout
android:id="#+id/one_first_name"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:title="#string/first_name"
app:text="#={vm.userInfo.firstName}"
/>
When I run the project I get this error
Error:(20, 13) Could not find event 'textAttrChanged' on View type 'ir.avalinejad.pasargadinsurance.component.ErrorInputLayout'
And my custom view looks like this
public class ErrorInputLayout extends LinearLayoutCompat implements TextWatcher {
protected EditText inputET;
protected TextView errorTV;
protected TextView titleTV;
protected TextView descriptionTV;
private int defaultGravity;
private String title;
private String description;
private String hint;
private int inputType = -1;
private int lines;
private String text;
private Subject<Boolean> isValidObservable = PublishSubject.create();
private Map<Validation, String> validationMap;
public ErrorInputLayout(Context context) {
super(context);
init();
}
public ErrorInputLayout(Context context, #Nullable AttributeSet attrs) {
super(context, attrs);
readAttrs(attrs);
init();
}
public ErrorInputLayout(Context context, #Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
readAttrs(attrs);
init();
}
private void readAttrs(AttributeSet attrs){
TypedArray a = getContext().getTheme().obtainStyledAttributes(
attrs,
R.styleable.ErrorInputLayout,
0, 0);
try {
title = a.getString(R.styleable.ErrorInputLayout_title);
description = a.getString(R.styleable.ErrorInputLayout_description);
hint = a.getString(R.styleable.ErrorInputLayout_hint);
inputType = a.getInt(R.styleable.ErrorInputLayout_android_inputType, -1);
lines = a.getInt(R.styleable.ErrorInputLayout_android_lines, 1);
text = a.getString(R.styleable.ErrorInputLayout_text);
} finally {
a.recycle();
}
}
private void init(){
validationMap = new HashMap<>();
setOrientation(VERTICAL);
}
#Override
protected void onFinishInflate() {
super.onFinishInflate();
titleTV = (TextView) LayoutInflater.from(getContext()).inflate(R.layout.error_layout_default_title_textview, null, false);
addView(titleTV);
descriptionTV = (TextView) LayoutInflater.from(getContext()).inflate(R.layout.error_layout_default_description_textview, null, false);
addView(descriptionTV);
readInputFromLayout();
if(inputET == null) {
inputET = (EditText) LayoutInflater.from(getContext()).inflate(R.layout.error_layout_defult_edittext, this, false);
addView(inputET);
}
errorTV = (TextView) LayoutInflater.from(getContext()).inflate(R.layout.error_layout_default_error_textview, null, false);
addView(errorTV);
inputET.addTextChangedListener(this);
defaultGravity = inputET.getGravity();
//set values
titleTV.setText(title);
if(description != null && !description.trim().isEmpty()){
descriptionTV.setVisibility(VISIBLE);
descriptionTV.setText(description);
}
if(inputType != -1)
inputET.setInputType(inputType);
if(hint != null)
inputET.setHint(hint);
else
inputET.setHint(title);
inputET.setLines(lines);
inputET.setText(text);
}
private void readInputFromLayout() {
if(getChildCount() > 3){
throw new IllegalStateException("Only one or zero view is allow in layout");
}
if(getChildCount() == 3){
View view = getChildAt(2);
if(view instanceof EditText)
inputET = (EditText) view;
else
throw new IllegalStateException("only EditText is allow as child view");
}
}
public void setText(String text){
inputET.setText(text);
}
public String getText() {
return text;
}
public void addValidation(#NonNull Validation validation, #StringRes int errorResourceId){
addValidation(validation, getContext().getString(errorResourceId));
}
public void addValidation(#NonNull Validation validation, #NonNull String error){
if(!validationMap.containsKey(validation))
validationMap.put(validation, error);
}
public void remoteValidation(#NonNull Validation validation){
if(validationMap.containsKey(validation))
validationMap.remove(validation);
}
public EditText getInputET() {
return inputET;
}
public TextView getErrorTV() {
return errorTV;
}
#Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
#Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
#Override
public void afterTextChanged(Editable editable) {
checkValidity();
if(editable.toString().length() == 0) //if hint
inputET.setGravity(Gravity.RIGHT);
else
inputET.setGravity(defaultGravity);
}
public Subject<Boolean> getIsValidObservable() {
return isValidObservable;
}
private void checkValidity(){
//this function only shows the first matched error.
errorTV.setVisibility(INVISIBLE);
for(Validation validation: validationMap.keySet()){
if(!validation.isValid(inputET.getText().toString())) {
errorTV.setText(validationMap.get(validation));
errorTV.setVisibility(VISIBLE);
isValidObservable.onNext(false);
return;
}
}
isValidObservable.onNext(true);
}
}
After hours of debugging, I found the solution. I changed my Binding class like this.
#InverseBindingMethods({
#InverseBindingMethod(type = ErrorInputLayout.class, attribute = "text"),
})
public class ErrorInputBinding {
#BindingAdapter(value = "textAttrChanged")
public static void setListener(ErrorInputLayout errorInputLayout, final InverseBindingListener textAttrChanged) {
if (textAttrChanged != null) {
errorInputLayout.getInputET().addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
#Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
#Override
public void afterTextChanged(Editable editable) {
textAttrChanged.onChange();
}
});
}
}
#BindingAdapter("text")
public static void setText(ErrorInputLayout view, String value) {
if(value != null && !value.equals(view.getText()))
view.setText(value);
}
#InverseBindingAdapter(attribute = "text")
public static String getText(ErrorInputLayout errorInputLayout) {
return errorInputLayout.getText();
}
First, I added AttrChanged after the text like this #BindingAdapter(value = "textAttrChanged") which is the default name for the listener and then I added getter and setter methods here as well.
event = "android:textAttrChanged" works for me:
object DataBindingUtil {
#BindingAdapter("emptyIfZeroText") //replace "android:text" on EditText
#JvmStatic
fun setText(editText: EditText, text: String?) {
if (text == "0" || text == "0.0") editText.setText("") else editText.setText(text)
}
#InverseBindingAdapter(attribute = "emptyIfZeroText", event = "android:textAttrChanged")
#JvmStatic
fun getText(editText: EditText): String {
return editText.text.toString()
}
}
you need add one more function
#BindingAdapter("app:textAttrChanged")
fun ErrorInputLayout.bindTextAttrChanged(listener: InverseBindingListener) {
}
what am I doing wrong?
I want to display an AlertDialog - "or close an application" beats me an error
Error:(141, 9) error: cannot find symbol method showDialog(int)
what should I do?
public class ZavdanFragment extends Fragment {
//аргумент індиф.
private static final String ARG_ZAMOV_ID = "zamov_id";
//мітка діалогу календаря
private static final String DIALOG_DATE = "DialogDate";
//мітка діалогу Фото
private static final String DIALOG_FOTO = "DialogFoto";
//private static final String DIALOG_EXIT = "DialogExit";
//призначення цільового фрагменту
private static final int REQUEST_DATE = 0;
//Контакти
private static final int REQUEST_CONTACT = 1;
//камера
private static final int REQUEST_PHOTO = 2;
//тел
private static final int REQUEST_PERMISSION = 3;
private static final int DIALOG_EXIT = 4;
private Zavdannya mZavdannya;
private EditText mTitleField; //назва замов.
private EditText mPrice; //ціна замов.
private Button mDateButton; // дата замов.
private CheckBox mVikonanoCheckBox; //виконання замов.
private CheckBox mTerminovoCheckBox; //термінове замов.
private CheckBox mOplataCheckBox; //оплачене замов.
private Button mRepostButton; //відправка звіту
private Button mContactButton; //список контактів
private ImageButton mPhotoButton; //кнопка фото
private ImageView mPhotoView; //фото
private File mPhotoFile;//фото
private Point mPhotoViewSize;//вікно фото
private Callbacks mCallbacks;
private Spinner mSpinnerWork;
//зателефонувати
private Button mCallContact;
private String mCallID;
//обовязковий інтерфейс для активності-хоста
public interface Callbacks {
void onZamovUpdated(Zavdannya zavdannya);
}
//аргументи індетифікатора
public static ZavdanFragment newInstance(UUID zamovId) {
Bundle args = new Bundle();
args.putSerializable(ARG_ZAMOV_ID, zamovId);
ZavdanFragment fragment = new ZavdanFragment();
fragment.setArguments(args);
return fragment;
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
mCallbacks = (Callbacks) activity;
}
//зберегти і передати інд. замов.
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//отримати індетифікатор
UUID zamovId = (UUID) getArguments().getSerializable(ARG_ZAMOV_ID);
mZavdannya = ZamovLab.get(getActivity()).getZavdannya(zamovId);
//збереження місцезнахоження фото
mPhotoFile = ZamovLab.get(getActivity()).getPhotoFile(mZavdannya);
//menu
setHasOptionsMenu(true);
}
//запис оновлення
#Override
public void onPause() {
super.onPause();
ZamovLab.get(getActivity()).updateZamov(mZavdannya);
}
#Override
public void onDetach() {
super.onDetach();
mCallbacks = null;
}
public void onclick(View v){
showDialog(DIALOG_EXIT);
}
protected Dialog onCreateDialog(int id) {
Dialog dialog = null;
android.app.AlertDialog.Builder builder = new android.app.AlertDialog.Builder(getActivity());
switch (id){
case DIALOG_EXIT:
return new AlertDialog.Builder(getActivity())
.setTitle(R.string.exit)
.setCancelable(false)
.setMessage(R.string.dial)
.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
android.os.Process.killProcess(android.os.Process.myPid());
}
})
.setNegativeButton(android.R.string.no, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
})
.create();
}
dialog = builder.show();
return dialog;
}
//меню видалити
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
super.onCreateOptionsMenu(menu, inflater);
inflater.inflate(R.menu.fragment_zamov, menu);
}
//дії при виборі меню
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
//видалити
case R.id.menu_item_delete_zamov:
ZamovLab.get(getActivity()).removeZamov(mZavdannya);
getActivity().finish();
return true;
case R.id.menu_item_exit:
onCreateDialog(DIALOG_EXIT);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
#Override
// розмітка (замовлення)
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_zamov,
container, false);
//назва замов.
mTitleField = (EditText) v.findViewById(R.id.zamov_title);
mTitleField.setText(mZavdannya.getTitle());//оновити назву
mTitleField.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) {
mZavdannya.setTitle(s.toString());
updateZamov();
}
#Override
public void afterTextChanged(Editable s) {
}
});
//список
mSpinnerWork = (Spinner) v.findViewById(R.id.spinner_work);
ArrayAdapter<CharSequence> dataAdapter = ArrayAdapter.createFromResource(
getActivity().getApplicationContext(), R.array.catlist, android.R.layout.simple_spinner_item
);
dataAdapter.setDropDownViewResource(android.R.layout
.simple_spinner_dropdown_item);
mSpinnerWork.setAdapter(dataAdapter);
mSpinnerWork.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
//відображення позиції
String item = parent.getItemAtPosition(position).toString();
Toast.makeText(parent.getContext(), "Вибрано: " + item, Toast.LENGTH_LONG).show();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
//mSpinnerWork.setOnItemSelectedListener((AdapterView.OnItemClickListener) this);
/*List<String> work = new ArrayList<String>();
work.add("11a");
work.add("2a");
work.add("5a");
work.add("1a");
work.add("2a");
work.add("3a");
work.add("4a");
work.add("55a");
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(
getActivity(), android.R.layout.simple_spinner_item, work
);*/
//ціна
mPrice = (EditText) v.findViewById(R.id.zamov_title_prise);
mPrice.setText(mZavdannya.getPrice());//оновити ціну
mPrice.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) {
mZavdannya.setPrice(s.toString());
updateZamov();
}
#Override
public void afterTextChanged(Editable s) {
}
});
//дата
mDateButton = (Button) v.findViewById(R.id.zamov_date);
updateDate();
//виклик діал. вікна при натискані на дату
mDateButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
FragmentManager manager = getFragmentManager();
//виклик newInstance
DatePickerFragment dialog = DatePickerFragment
.newInstance(mZavdannya.getDate());
dialog.setTargetFragment(ZavdanFragment.this, REQUEST_DATE);
dialog.show(manager, DIALOG_DATE);
}
});
//виконання
mVikonanoCheckBox = (CheckBox) v.findViewById(R.id.zamov_vikonano);
mVikonanoCheckBox.setChecked(mZavdannya.isVikonano());//оновити прапорець
mVikonanoCheckBox.setOnCheckedChangeListener(new CompoundButton
.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(
CompoundButton buttonView, boolean isChecked) {
//Прапорець виконання
mZavdannya.setVikonano(isChecked);
updateZamov();
}
});
//оплаченно
mOplataCheckBox = (CheckBox) v.findViewById(R.id.zamov_oplata);
mOplataCheckBox.setChecked(mZavdannya.isOplata());//оновити прапорець
mOplataCheckBox.setOnCheckedChangeListener(new CompoundButton
.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(
CompoundButton buttonView, boolean isChecked) {
//Прапорець виконання
mZavdannya.setOplata(isChecked);
updateZamov();
}
});
//терміново
mTerminovoCheckBox = (CheckBox) v.findViewById(R.id.zamov_terminovo);
mTerminovoCheckBox.setChecked(mZavdannya.isTerminovo());//оновити прапорець
mTerminovoCheckBox.setOnCheckedChangeListener(new CompoundButton
.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(
CompoundButton buttonView, boolean isChecked) {
//Прапорець виконання
mZavdannya.setTerminovo(isChecked);
updateZamov();
}
});
//звіт про виконання
mRepostButton = (Button) v.findViewById(R.id.zamov_repost);
mRepostButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(Intent.ACTION_SEND);
i.setType("text/plain");
i.putExtra(Intent.EXTRA_TEXT, getZamovRepost());
i.putExtra(Intent.EXTRA_SUBJECT,
getString(R.string.zamov_repost_subject));
i = Intent.createChooser(i, getString(R.string.send_repost));
startActivity(i);
}
});
//Вибір контакту
final Intent pickContact = new Intent(Intent.ACTION_PICK,
ContactsContract.Contacts.CONTENT_URI);
// pickContact.addCategory(Intent.CATEGORY_HOME);//перевірка фільтра
mContactButton = (Button) v.findViewById(R.id.zamov_contact);
mContactButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//startActivityForResult(pickContact, REQUEST_CONTACT);
//зчитати контакт
int permissionCheck = ContextCompat.checkSelfPermission(getActivity(),
android.Manifest.permission.READ_CONTACTS);
if (permissionCheck != PackageManager.PERMISSION_GRANTED) {
ZavdanFragment.this.requestPermissions(new String[]{
android.Manifest.permission.READ_CONTACTS
}, REQUEST_PERMISSION);
} else {
startActivityForResult(pickContact, REQUEST_CONTACT);
}
}
});
if (mZavdannya.getContact() != null) {
mContactButton.setText(mZavdannya.getContact());
}
//зателефонувати
mCallContact = (Button) v.findViewById(R.id.call_contact_button);
mCallContact.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mCallID != null) {
Cursor cursor = getActivity().getContentResolver().query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
new String[]{ContactsContract.CommonDataKinds.Phone.CONTACT_ID,
ContactsContract.CommonDataKinds.Phone.NUMBER},
ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ?",
new String[]{mCallID}, null);
try {
cursor.moveToFirst();
String phoneNumber = cursor.getString(cursor.getColumnIndex(
ContactsContract.CommonDataKinds.Phone.NUMBER));
Intent callContact = new Intent(Intent.ACTION_DIAL,
Uri.parse("tel:" + phoneNumber));
startActivity(callContact);
} finally {
cursor.close();
}
} else {
Toast.makeText(getActivity().getApplicationContext(),
"Контакт не вибраний",
Toast.LENGTH_LONG).show();
}
}
});
//захист від контакних програм
PackageManager packageManager = getActivity().getPackageManager();
if (packageManager.resolveActivity(pickContact,
PackageManager.MATCH_DEFAULT_ONLY) == null) {
mContactButton.setEnabled(false);
}
//кнопка фото
mPhotoButton = (ImageButton) v.findViewById(R.id.zamov_camera);
final Intent captureImage = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
boolean canTakePhoto = mPhotoFile != null && captureImage
.resolveActivity(packageManager) != null;
mPhotoButton.setEnabled(canTakePhoto);
//вікно фото
if (canTakePhoto) {
Uri uri = Uri.fromFile(mPhotoFile);
captureImage.putExtra(MediaStore.EXTRA_OUTPUT, uri);
}
mPhotoButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivityForResult(captureImage, REQUEST_PHOTO);
}
});
//фото
mPhotoView = (ImageView) v.findViewById(R.id.zamov_photo);
// updatePhotoView();
mPhotoView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
FragmentManager manager = getFragmentManager();
PhotoView dialog = new PhotoView();
PhotoView.getPhotoFile(mPhotoFile);
dialog.show(manager, DIALOG_FOTO);
}
});
final ViewTreeObserver observer = mPhotoView.getViewTreeObserver();
observer.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
#Override
public void onGlobalLayout() {
boolean isFirstPass = (mPhotoViewSize == null);
mPhotoViewSize = new Point();
mPhotoViewSize.set(mPhotoView.getWidth(), mPhotoView.getHeight());
if (isFirstPass) updatePhotoView();
}
});
return v;
}
//реакція на отриману інформацію дати в діал. вікні
#Override
public void onActivityResult(int requestCode, int resultCode,
Intent data) {
if (resultCode != Activity.RESULT_OK) {
return;
}
if (requestCode == REQUEST_DATE) {
Date date = (Date) data
.getSerializableExtra(DatePickerFragment.EXTRA_DATE);
mZavdannya.setDate(date);
updateZamov();
updateDate();
}//вибрати контакт
else if (requestCode == REQUEST_CONTACT && data != null) {
Uri contactUri = data.getData();
//визначенняя поля які мають бути повернуті запитом
String[] queryFields = new String[]{
ContactsContract.Contacts.DISPLAY_NAME, ContactsContract
.Contacts._ID};
//виконання запиту
Cursor c = getActivity().getContentResolver()
.query(contactUri, queryFields, null, null, null);
try {
//перевірка отриманого результату
if (c.getCount() == 0) {
return;
}
//використання 1 стовбця даних (ім'я контакту)
c.moveToFirst();
String contact = c.getString(0);
mZavdannya.setContact(contact);
updateZamov();
mContactButton.setText(contact);
mCallID = c.getString(c.getColumnIndex(ContactsContract.
Contacts._ID));
} finally {
c.close();
}
} else if (requestCode == REQUEST_PHOTO) {
updateZamov();
updatePhotoView();
}
}
private void updateZamov() {
ZamovLab.get(getActivity()).updateZamov(mZavdannya);
mCallbacks.onZamovUpdated(mZavdannya);
}
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions,
int[] grantResults) {
if (requestCode == REQUEST_PERMISSION) {
if (grantResults.length > 0 && grantResults[0] == PackageManager
.PERMISSION_GRANTED) {
Intent pickContact = new Intent(Intent.ACTION_DIAL, ContactsContract
.Contacts.CONTENT_URI);
startActivityForResult(pickContact, REQUEST_CONTACT);
}
}
}
private void updateDate() {
//формат дати
SimpleDateFormat dateFormat = new SimpleDateFormat("EEEE, dd MMM, yyyy");
//оновити дату
mDateButton.setText(dateFormat.format(mZavdannya.getDate()));
}
//4 строчки звіту та з'єднaння їх
private String getZamovRepost() {
//1 строчка
String vikonanoString = null;
if (mZavdannya.isVikonano()) {
vikonanoString = getString(R.string.zamov_repost_vikonano);
} else {
vikonanoString = getString(R.string.zamov_repost_nevikonano);
}
//2 строчка
String dataFormat = "EEE,dd MMM";
String dataString = android.text.format.DateFormat.format(
dataFormat, mZavdannya.getDate()).toString();
//3 строчка
String contact = mZavdannya.getContact();
if (contact == null) {
contact = getString(R.string.zamov_repost_no_contact);
} else {
contact = getString(R.string.zamov_repost_contact) + mZavdannya.getContact();
}
String price = mZavdannya.getPrice();
String report = getString(R.string.zamov_repost, mZavdannya.
getTitle(), dataString, vikonanoString, contact, price);
return report;
}
//оновлення фото
private void updatePhotoView() {
if (mPhotoFile == null || !mPhotoFile.exists()) {
mPhotoView.setImageDrawable(null);
} else {
/* Bitmap bitmap = PictureUtils.getScaledBitmap(
mPhotoFile.getPath(), getActivity());
mPhotoView.setImageBitmap(bitmap);*/
Bitmap bitmap = (mPhotoViewSize == null) ?
PictureUtils.getScaledBitmap(mPhotoFile.getPath(), getActivity()) :
PictureUtils.getScaledBitmap(mPhotoFile.getPath(),
mPhotoViewSize.x, mPhotoViewSize.y);
mPhotoView.setImageBitmap(bitmap);
mPhotoView.setEnabled(true);
}
}
}
You need context in order to call showDialog() from Fragment. Try calling
getActivity().showDialog(DIALOG_EXIT);
More info visit here
Currently I use a RecyclerView to represent a dynamically configuration list form.
Every configuration item (entry at RecyclerView list) contains one EditText item.
To avoid wrong user input (some fields allow only integer, others only one digit after comma), I've implemented two different TextWatcher-filters which correct illegal input ("DecimalFilterDigitsAfterComma" and "DecimalFilterInteger").
My RecyclerView has 16 configuration items in total, but can only display maximum 8 at one time.
My problem is that the TextWatchers are assigned to specific Items (Integers and Decimal-Point TextEdit). But when I'm scrolling a bit, they change their order, so that Decimal- and Integer-Filters get swapped.
The TextWatcher items will be created inside the ConfigurationAdapter which is a RecyclerView.Adapter. I've event managed that the TextWatcher is only created once for each entry by using the mListConfigInit which is a boolean flag list for the items.
ConfigurationAdapter.java:
public class ConfigurationAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
/*
...
*/
private List<ConfigItem> mConfiguration = new ArrayList<>();
// make sure that DecimalFilter is only created once for each item
private List<Boolean> mListConfigInit = new ArrayList<>();
public ConfigurationAdapter() {
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(
R.layout.listitem_configuration,
parent,
false);
final ConfigurationViewHolder vh = new ConfigurationViewHolder(v);
/*
...
*/
return vh;
}
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
final ConfigurationViewHolder vh = (ConfigurationViewHolder) holder;
ConfigItem config = mConfiguration.get(position);
if(config.ShowValueAsFloat()) {
vh.SetTextWatcherType(ConfigurationViewHolder.TextWatcherType.type_FloatActive);
} else {
vh.SetTextWatcherType(ConfigurationViewHolder.TextWatcherType.type_IntActive);
}
// set name and unit
vh.mName.setText(config.mName);
vh.mUnit.setText(config.mUnit);
/*
...
*/
}
#Override
public int getItemCount() {
return mConfiguration.size();
}
public void addConfigItem(ConfigItem item) {
mConfiguration.add(item);
mListConfigInit.add(new Boolean(false));
notifyItemInserted(mConfiguration.size() - 1);
//notifyDataSetChanged();
}
/*
...
*/
}
ConfigurationViewHolder.java (changed according to pskink-comments):
public final class ConfigurationViewHolder extends RecyclerView.ViewHolder implements TextWatcher {
public TextView mName;
public CheckBox mCheckbox;
public SeekBar mSeekbar;
public EditText mValueEditText;
public TextView mUnit;
private List<TextWatcher> mListTextWatchers = new ArrayList<>();
public enum TextWatcherType {
type_FloatActive(0),
type_IntActive(1);
private int mValue;
TextWatcherType(int value) {
mValue = value;
}
int val() { return mValue; }
}
private TextWatcherType mTextWatcherType = TextWatcherType.type_FloatActive;
public ConfigurationViewHolder(View itemView) {
super(itemView);
mName = (TextView) itemView.findViewById(R.id.textView_configuration_name);
mValueEditText = (EditText) itemView.findViewById(R.id.editText_configuration_value);
mUnit = (TextView) itemView.findViewById(R.id.textView_configuration_unit);
mCheckbox = (CheckBox) itemView.findViewById(R.id.checkbox_configuration);
mSeekbar = (SeekBar) itemView.findViewById(R.id.seekBar_configuration);
mListTextWatchers.add(0, new DecimalFilterDigitsAfterComma(mValueEditText, 1));
mListTextWatchers.add(1, new DecimalFilterInteger(mValueEditText));
mValueEditText.addTextChangedListener(this);
}
public void SetTextWatcherType(TextWatcherType textWatcherType) {
mTextWatcherType = textWatcherType;
}
#Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {}
#Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {}
#Override
public void afterTextChanged(Editable editable) {
mListTextWatchers.get(mTextWatcherType.val()).afterTextChanged(editable);
}
}
DecimalFilterInteger.java
public class DecimalFilterInteger implements TextWatcher {
private final static String TAG = ConfigurationAdapter.class.getSimpleName();
private final EditText mEditText;
private String mLastTextValue = new String("");
public DecimalFilterInteger(EditText editText) {
this.mEditText = editText;
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
#Override
public synchronized void afterTextChanged(final Editable text) {
String strInput = text.toString().trim();
if(strInput.isEmpty()) {
return;
}
if(strInput.equals(mLastTextValue)) { // return when same value as last time to avoid endless loop
return;
}
if ((strInput.charAt(0) == '.')) { // handle dot at beginning
strInput = "";
}
if(strInput.contains(".")){ // cut trailing comma
String numberBeforeDecimal = strInput.split("\\.")[0];
strInput = numberBeforeDecimal;
}
mEditText.removeTextChangedListener(this);
mEditText.getText().clear(); // do not use setText here to avoid changing the keyboard
mEditText.append(strInput); // back to default (e. g. from 123-mode to abc-mode),
// see: http://stackoverflow.com/questions/26365808/edittext-settext-changes-the-keyboard-type-to-default-from-123-to-abc
mLastTextValue = mEditText.getText().toString();
mEditText.setSelection(mEditText.getText().toString().trim().length());
mEditText.addTextChangedListener(this);
}
}
Many thanks in advance for your help!
The cause of the swap/switching behaviour of the two different TextWatcher-implementations inside the RecyclerView was that I called removeTextChangedListenerand addTextChangedListenerinside their afterTextChanged-methods to avoid retriggering of the afterTextChanged-method.
The best way to avoid retriggering is a simple check if the text changed since the last call:
public class DecimalFilterInteger implements TextWatcher {
private final static String TAG = ConfigurationAdapter.class.getSimpleName();
private final EditText mEditText;
private String mLastTextValue = new String("");
// ...
#Override
public synchronized void afterTextChanged(final Editable text) {
String strInput = text.toString().trim();
if(strInput.isEmpty()) {
return;
}
if(strInput.equals(mLastTextValue)) { // return when same value as last time to avoid endless loop
return;
}
if ((strInput.charAt(0) == '.')) { // handle dot at beginning
strInput = "";
}
if(strInput.contains(".")){ // cut trailing comma
String numberBeforeDecimal = strInput.split("\\.")[0];
strInput = numberBeforeDecimal;
}
//mEditText.removeTextChangedListener(this); // CAUSE OF SWAP-ERROR !!!
mEditText.getText().clear(); // do not use setText here to avoid changing the keyboard
mEditText.append(strInput); // back to default (e. g. from 123-mode to abc-mode),
// see: http://stackoverflow.com/questions/26365808/edittext-settext-changes-the-keyboard-type-to-default-from-123-to-abc
mLastTextValue = mEditText.getText().toString();
mEditText.setSelection(mEditText.getText().toString().trim().length());
//mEditText.addTextChangedListener(this); // CAUSE OF SWAP-ERROR !!!
}
}
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);
}
}
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();
}
});