This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 2 years ago.
I have a button placed inside a layout frag_contacts.xml that is intended for a fragment which is FragmentContacts.java . There is also row layout for the recyclerview which is items_contacts.xml . The button allows a user to save stuff after they are done picking recyclerview items. The app works without any errors on android Nougat .
However When I run the app on android 9 it crushes giving exception java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference.
The line throwing exceptions is the one below
buttonCreateGroup.setOnClickListener(this);
the error message
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.ex_contactapp, PID: 3931
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
at com.example.ex_contactapp.fragments.FragmentContacts.onCreateView(FragmentContacts.java:99)
at androidx.fragment.app.Fragment.performCreateView(Fragment.java:2439)
at androidx.fragment.app.FragmentManagerImpl.moveToState(FragmentManager.java:1460)
at androidx.fragment.app.FragmentManagerImpl.moveFragmentToExpectedState(FragmentManager.java:1784)
at androidx.fragment.app.FragmentManagerImpl.moveToState(FragmentManager.java:1852)
at androidx.fragment.app.BackStackRecord.executeOps(BackStackRecord.java:802)
at androidx.fragment.app.FragmentManagerImpl.executeOps(FragmentManager.java:2625)
at androidx.fragment.app.FragmentManagerImpl.executeOpsTogether(FragmentManager.java:2411)
at androidx.fragment.app.FragmentManagerImpl.removeRedundantOperationsAndExecute(FragmentManager.java:2366)
at androidx.fragment.app.FragmentManagerImpl.execSingleAction(FragmentManager.java:2243)
at androidx.fragment.app.BackStackRecord.commitNowAllowingStateLoss(BackStackRecord.java:654)
at androidx.fragment.app.FragmentPagerAdapter.finishUpdate(FragmentPagerAdapter.java:146)
at androidx.viewpager.widget.ViewPager.populate(ViewPager.java:1244)
at androidx.viewpager.widget.ViewPager.populate(ViewPager.java:1092)
at androidx.viewpager.widget.ViewPager.onMeasure(ViewPager.java:1622)
at android.view.View.measure(View.java:25056)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:7745)
at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1535)
at android.widget.LinearLayout.measureVertical(LinearLayout.java:825)
at android.widget.LinearLayout.onMeasure(LinearLayout.java:704)
at android.view.View.measure(View.java:25056)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:7745)
at android.widget.FrameLayout.onMeasure(FrameLayout.java:185)
at androidx.appcompat.widget.ContentFrameLayout.onMeasure(ContentFrameLayout.java:143)
at android.view.View.measure(View.java:25056)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:7745)
at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1535)
at android.widget.LinearLayout.measureVertical(LinearLayout.java:825)
at android.widget.LinearLayout.onMeasure(LinearLayout.java:704)
at android.view.View.measure(View.java:25056)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:7745)
at android.widget.FrameLayout.onMeasure(FrameLayout.java:185)
at android.view.View.measure(View.java:25056)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:7745)
at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1535)
at android.widget.LinearLayout.measureVertical(LinearLayout.java:825)
at android.widget.LinearLayout.onMeasure(LinearLayout.java:704)
at android.view.View.measure(View.java:25056)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:7745)
at android.widget.FrameLayout.onMeasure(FrameLayout.java:185)
at com.android.internal.policy.DecorView.onMeasure(DecorView.java:1051)
at android.view.View.measure(View.java:25056)
at android.view.ViewRootImpl.performMeasure(ViewRootImpl.java:3382)
at android.view.ViewRootImpl.measureHierarchy(ViewRootImpl.java:2104)
at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:2403)
at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1964)
at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:8721)
at android.view.Choreographer$CallbackRecord.run(Choreographer.java:988)
at android.view.Choreographer.doCallbacks(Choreographer.java:765)
at android.view.Choreographer.doFrame(Choreographer.java:700)
at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:967)
at android.os.Handler.handleCallback(Handler.java:873)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:216)
at android.app.ActivityThread.main(ActivityThread.java:7285)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:494)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:975)
layout for fragment - frag_contacts.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/colorPrimaryDark">
<GridLayout
android:layout_width="wrap_content"
android:layout_height="100dp">
<EditText
android:id="#+id/group_name"
android:layout_width="263dp"
android:layout_height="70dp"/>
<Button
android:id="#+id/buttonCreateGroup"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/create_group"/>
</GridLayout>
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/rv_contacts"
android:layout_width="match_parent"
android:layout_height="match_parent">
</androidx.recyclerview.widget.RecyclerView>
</LinearLayout>
Row layout -> items_contacts.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal" android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/colorPrimary"
android:layout_margin="10dp"
android:weightSum="10">
<Button
android:layout_gravity="center"
android:background="#drawable/ic_person"
android:layout_width="0dp"
android:layout_weight="1"
android:layout_height="32dp"/>
<LinearLayout
android:padding="10dp"
android:layout_width="0dp"
android:layout_weight="8"
android:orientation="vertical"
android:layout_height="wrap_content">
<TextView
android:id="#+id/contact_name"
android:text="name"
android:textSize="20sp"
android:textColor="#android:color/white"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
<TextView
android:id="#+id/contact_number"
android:text="number"
android:textSize="16sp"
android:textColor="#android:color/white"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
</LinearLayout>
<CheckBox
android:id="#+id/contact_checkbox"
android:layout_width="wrap_content"
android:layout_gravity="center"
android:layout_height="32dp"
android:layout_weight="1"/>
</LinearLayout>
Recycler View Adapter class -ContactsRvAdapter.java
public class ContactsRvAdapter extends RecyclerView.Adapter<ContactsRvAdapter.ViewHolder> {
private Context mContext;
private LayoutInflater inflater;
private List<ModelContacts> mlistContacts;
private CheckedStatusListener mcheckedStatusListener;
public interface CheckedStatusListener{
//String firstName, String lastName, String middleName, #NonNull String phoneNumber,#NonNull int groupid
void onItemChecked(String name, String phonenumber);
void onItemUnchecked(String name, String phonenumber);
}
public ContactsRvAdapter(Context context, List<ModelContacts> listContacts,CheckedStatusListener checkedStatusListener){
mlistContacts = listContacts;
mContext = context;
mcheckedStatusListener = checkedStatusListener;
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
inflater = LayoutInflater.from(mContext);
View view = inflater.inflate(R.layout.items_contacts,parent,false);
ViewHolder viewHolder = new ViewHolder(view);
return viewHolder;
}
#Override
public void onBindViewHolder(#NonNull ViewHolder holder, final int position) {
final TextView contact_name,contact_number;
final CheckBox contact_checkbox;
contact_name = holder.contact_name;
contact_number = holder.contact_number;
contact_name.setText(mlistContacts.get(position).getName());
contact_number.setText(mlistContacts.get(position).getNumber());
contact_checkbox = holder.contactSelectedCheckBox;
contact_checkbox.setOnClickListener(v -> {
if (contact_checkbox.isChecked()){
mcheckedStatusListener.onItemChecked(mlistContacts.get(position).getName(),mlistContacts.get(position).getNumber());
}else{
mcheckedStatusListener.onItemUnchecked(mlistContacts.get(position).getName(),mlistContacts.get(position).getNumber());
}
});
}
#Override
public int getItemCount() {
return mlistContacts.size();
}
public class ViewHolder extends RecyclerView.ViewHolder{
TextView contact_name,contact_number;
CheckBox contactSelectedCheckBox;
public ViewHolder(View itemView){
super(itemView);
contact_name = itemView.findViewById(R.id.contact_name);
contact_number = itemView.findViewById(R.id.contact_number);
contactSelectedCheckBox = itemView.findViewById(R.id.contact_checkbox);
}
}
}
Fragment class - FragmentContacts.java
public class FragmentContacts extends Fragment implements ContactsRvAdapter.CheckedStatusListener, View.OnClickListener{
private View v;
private RecyclerView recyclerView;
private List<ModelContactsBuffer> currentSelectedContacts = new ArrayList<>();
ContactsRvAdapter adapter;
private EditText editTextGroupName;
private ContactGroupViewModel contactGroupViewModel;
private ModelContactsBuffer modelContactsBuffer;
private GroupListViewModel groupListViewModel;
public FragmentContacts() {
}
#RequiresApi(api = Build.VERSION_CODES.N)
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
v = inflater.inflate(R.layout.frag_contacts,container,false);
recyclerView = v.findViewById(R.id.rv_contacts);
editTextGroupName = v.findViewById(R.id.group_name);
Button buttonCreateGroup = v.findViewById(R.id.buttonCreateGroup);
buttonCreateGroup.setOnClickListener(this);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getContext());
RecyclerView.LayoutManager layoutManager= linearLayoutManager;
recyclerView.setLayoutManager(layoutManager);
if (Build.VERSION.SDK_INT > Build.VERSION_CODES.M &&
ActivityCompat.checkSelfPermission(getContext(), Manifest.permission.READ_CONTACTS)!= PackageManager.PERMISSION_GRANTED){
ActivityCompat.requestPermissions(getActivity(),new String[]{Manifest.permission.READ_CONTACTS},1);
}else {
adapter = new ContactsRvAdapter(getContext(), getContacts(),this);
recyclerView.setItemViewCacheSize(getContacts().size());
recyclerView.setAdapter(adapter);
// adapter.notifyDataSetChanged();
}
contactGroupViewModel = ViewModelProviders.of(this, new ContactGroupViewModel.Factory(Objects.requireNonNull(getActivity()).getApplicationContext())).get(ContactGroupViewModel.class);
groupListViewModel = ViewModelProviders.of(this,new GroupListViewModel.Factory(getActivity().getApplicationContext())).get(GroupListViewModel.class);
return v;
}
#Override
public void onClick(View v) {
Log.i("editTextGroupNamelength", String.valueOf(editTextGroupName.getText().toString().length()));
if (editTextGroupName.getText().toString().length() > 2) {
if(currentSelectedContacts.size() > 4){
contactGroupViewModel.createGroup(editTextGroupName.getText().toString(),String.valueOf(currentSelectedContacts.size()));
Integer groupId = contactGroupViewModel.readGroupId(editTextGroupName.getText().toString());
insertGrouplist(groupId);
//clearFields();
}else{
new AlertDialog.Builder(Objects.requireNonNull(this.getActivity()))
.setIcon(R.drawable.ic_error)
.setTitle("Insufficient group members")
.setMessage("A group should have at least 5 members")
.setNeutralButton("Ok",null)
.show();
}
}else{
new AlertDialog.Builder(Objects.requireNonNull(this.getActivity()))
.setIcon(R.drawable.ic_error)
.setTitle("Group name is too short")
.setMessage("A group should have atleast be 3 characters long")
.setNeutralButton("Ok",null)
.show();
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
if(requestCode == 1){
if(grantResults[0] == PackageManager.PERMISSION_GRANTED){
//now permission is granted call function again
adapter = new ContactsRvAdapter(getContext(), getContacts(),this);
recyclerView.setItemViewCacheSize(getContacts().size());
recyclerView.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
}
}
private List<ModelContacts> getContacts(){
List<ModelContacts> list = new ArrayList<>();
try{
String[] PROJECTION = new String[] {
ContactsContract.Contacts.DISPLAY_NAME,
ContactsContract.CommonDataKinds.Phone.NUMBER,
ContactsContract.CommonDataKinds.Photo.CONTACT_ID };
String selectionFields = ""+ ContactsContract.Contacts.HAS_PHONE_NUMBER + " > 0 and " + ContactsContract.CommonDataKinds.Phone.TYPE +"=" + ContactsContract.CommonDataKinds.Phone.TYPE_MOBILE;
String[] selectionArgs = new String[]{"com.google"};
Cursor cursor = getContext().getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
PROJECTION,selectionFields,null,ContactsContract.Contacts.DISPLAY_NAME + " ASC");
cursor.moveToFirst();
while(cursor.moveToNext()){
list.add(new ModelContacts(cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.CONTACT_ID)),
cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME)),
cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER))));
}
}catch (Exception e){
Toast.makeText(getContext(),e.getMessage(),Toast.LENGTH_SHORT).show();
}
return list;
}
#Override
public void onItemChecked(String name, String phonenumber) {
String firstName = " ";
String lastName = " ";
if(name.split("\\w+").length>1){
lastName = name.substring(name.lastIndexOf(" ")+1);
firstName = name.substring(0,name.lastIndexOf(' '));
}else{
firstName = name;
lastName = " ";
}
modelContactsBuffer = new ModelContactsBuffer(firstName,lastName,phonenumber);
currentSelectedContacts.add(modelContactsBuffer);
}
#RequiresApi(api = Build.VERSION_CODES.N)
#Override
public void onItemUnchecked(String name, String phonenumber) {
String firstName = " ";
String lastName = " ";
if(name.split("\\w+").length>1){
lastName = name.substring(name.lastIndexOf(" ")+1);
firstName = name.substring(0,name.lastIndexOf(' '));
}else{
firstName = name;
lastName = " ";
}
currentSelectedContacts.removeIf( currentSelectedContact -> currentSelectedContact.getPhoneNumber().equals(phonenumber));
}
public void insertGrouplist(int groupId){
for (ModelContactsBuffer currentSelectedContact : currentSelectedContacts) {
groupListViewModel.createGroupList(currentSelectedContact.getFirstName(), currentSelectedContact.getLastName(), " ", currentSelectedContact.getPhoneNumber(), groupId);
}
clearFields();
}
}
I commented the line throwing an exception and the app runs pretty well. Hence the problem is from buttonCreateGroup.setOnClickListener(this);
I have tried many solutions here in stack overflow which didnt work.
I have checked the id of the button and it is correct
I don't think it is possible initializing the onclicklistener inside ContactsRvAdapter because its not even in the row layout. It is in the other layout wwhich is intended for the fragment
I tried passing the normal new OnViewClicklistener to the button instead of passing the whole activity but nothong changed. Still getting an error
I later on moved the clicklistener call from public View onCreateView() to public void onViewCreated() but there was no change. I am stil getting the same error.
I tried removing #RequiresApi(api = Build.VERSION_CODES.N) Nothing changed
Kindly note I am not a professional on android. I added some things like #RequiresApi(api = Build.VERSION_CODES.N) because android lint would show an error and that was the only way I could deal with it at that time. I apprectiate any help offered on solving this
You probably get this error(null object reference) because you didn't define the button. You have to define like this:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.frag_contacts, container, false);
Button buttonCreateGroup = view.findViewById(R.id.buttonCreateGroup);
buttonCreateGroup.setOnClickListener(this);
return view;
}
Or this func:
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
Button buttonCreateGroup = view.findViewById(R.id.buttonCreateGroup);
buttonCreateGroup.setOnClickListener(this);
}
edit func.
So for some apparent reason I didn't think about the fact that I had two xml files for frag_contacts, one in res/layouts and another in res/layout-v26
I admit I am not a pro on android and I kinda auto generated the latter xml file without knowing its use but I still continued working on the on in res/layouts & fully abandoned the one in res/layout-v26 because I didn't know it's use.
However it did have a button and a couple of other widgets but with no ID. Since it was in res/layout-v26 meaning it would show for devices compatible with v-26 and totally ignore the one on res/layouts, that's the layout file that would show on android 9 device. & since the button didn't have an ID, a null pointer exception would be thrown.
I have deleted the layout-v-26 file so that devices will fallback to the default layout. The app now works fine.
Related
I have an strange issue I have the nexts code files:
result_suggestion.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/result_suggestion_container"
android:orientation="vertical"
android:background="#fff">
<!--android:visibility="gone"-->
<ListView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/result_list"
android:scrollbars="vertical" />
</LinearLayout>
results_suggestions_footer.xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:orientation="vertical"
android:background="#e6e9ea">
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="250dp"
android:layout_marginTop="10dp"
android:contentDescription="#string/results_suggestion_footer"
app:srcCompat="#drawable/ic_baseline_search_24px" />
<Button
android:id="#+id/keep_searching"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/search_button"
android:text="#string/quotes_suggestion_footer" />
<!--android:drawableEnd="#drawable/ic_baseline_search_24px"-->
</RelativeLayout>
bidAdapter.java:
package com.my.app.ui.adapters;
import android.content.Context;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
import com.my.app.R;
import com.my.app.api.models.sonnet;
import com.my.app.api.models.sonnetbid;
import com.my.app.api.interfaces.SuggestionListItem;
import java.util.ArrayList;
import java.util.List;
import javax.security.auth.login.LoginException;
/**
* Class of the custom adapter for the suggestions list of bids.
*
* #author Dennis Mostajo on 1/18/18
*/
public class bidAdapter extends BaseAdapter {
private static final int sonnet = 0;
private static final int bid = 1;
private List<SuggestionListItem> mSuggestions;
private LayoutInflater mInflater;
//===========================================================================
// CONSTRUCTOR
//===========================================================================
/**
* Custom constructor implementation in charge of the initialization of internal members
*
* #param context application context for the layout inflater initialization
*/
public bidAdapter(Context context) {
this.mSuggestions = new ArrayList<>();
this.mInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
//===========================================================================
// OVERRIDE METHODS
//===========================================================================
#Override
public int getCount() {
return mSuggestions.size();
}
#Override
public Object getItem(int position) {
return mSuggestions.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public int getViewTypeCount() {
return 2;
}
#Override
public int getItemViewType(int position) {
if(mSuggestions.get(position).getInstanceType() == SuggestionListItem.InstanceType.sonnet) {
return sonnet;
} else {
return bid;
}
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
int cellType = getItemViewType(position);
if (convertView == null) {
holder = new ViewHolder();
switch(cellType) {
case sonnet:
convertView = mInflater.inflate(R.layout.source_cell, null);
holder.mSource = convertView.findViewById(R.id.source);
holder.mSourceInformation = convertView.findViewById(R.id.source_information);
break;
case bid:
convertView = mInflater.inflate(R.layout.bid_cell, null);
holder.mbid = convertView.findViewById(R.id.bid);
holder.mbidInformation = convertView.findViewById(R.id.bid_information);
break;
}
if (convertView != null) {
convertView.setTag(holder);
}
} else {
holder = (ViewHolder)convertView.getTag();
}
switch (cellType) {
case sonnet:
holder.mSource.setText(((sonnet) mSuggestions.get(position)).getContent());
holder.mSourceInformation.setText("");
break;
case bid:
holder.mbid.setText(((sonnetbid) mSuggestions.get(position)).getText());
sonnet sonnet = ((sonnetbid) mSuggestions.get(position)).getsonnet();
String text = String.format("%s%s%s%s%s%s%s", " (", sonnet.getBook(), " ", sonnet
.getChapter(), ":", sonnet.getsonnetNumber(), ").");
holder.mbidInformation.setText(text);
break;
}
return convertView;
}
//===========================================================================
// CUSTOM METHODS
//===========================================================================
/**
* Method used to update the list of suggestions to be given to the user
*
* #param suggestions list containing suggested bids and stanzas
*/
public void updateSuggestions(List<SuggestionListItem> suggestions) {
if(suggestions != null) {
this.mSuggestions.clear();
this.mSuggestions = suggestions;
this.notifyDataSetChanged();
}
}
//===========================================================================
// PRIVATE CLASSES
//===========================================================================
/**
* Class for the implementation of the ViewHolder design pattern used to represent the bids
* and stanzas cells.
*/
private static class ViewHolder {
private TextView mbid;
private TextView mbidInformation;
private TextView mSource;
private TextView mSourceInformation;
}
}
and when I using my keyboardIME:
private View initInputView() {
mCurrentTheme = ThemeManager.getInstance(this).getTheme();
mKeyboardView.setKeyboard(mKeyboard);
mKeyboardView.setOnKeyboardActionListener(this);
mInflater = (LayoutInflater) this.getSystemService(Context
.LAYOUT_INFLATER_SERVICE);
mSuggestionsView = mInflater.inflate(R.layout.result_suggestion, null);
mResultListFooter = mInflater.inflate(R.layout.results_suggestion_footer, null);
initAlternativeCandidatesView();
mResultList = mSuggestionsView.findViewById(R.id.result_list);
mResultList.addFooterView(mResultListFooter);
mResultsAdapter = new bidAdapter(this);
mResultList.setAdapter(mResultsAdapter);
mResultList.setOnItemClickListener((AdapterView<?> parent, View view, int position,
long id) -> {
SuggestionListItem item = (SuggestionListItem) mResultsAdapter
.getItem(position);
});
return mKeyboardView;
}
#Override
protected void onPostExecute(SearchRequestResult result) {
switch (result) {
case SUCCESS:
if(mSonnetBidResult.size() > 0) {
List<SuggestionListItem> bidSonnetList = new ArrayList<>(
mSonnetBidResult);
mQuotesIME.get().mResultsAdapter.updateSuggestions(bisSonnetList);
// the crash is here
mQuotesIME.get().mQuoteList.setAdapter(mQuotesIME.get().mResultsAdapter);// IMEKeyboard.java:2305
mQuotesIME.get().mResultsAdapter);
// Added by Dennis Try to fix Height of suggestions lists
if (mSonnetBidResult.size() > 2) {
mQuotesIME.get().maximize_quote_lists();
} else {
mQuotesIME.get().minimize_quote_lists();
}
mQuotesIME.get().setCandidatesView(mQuotesIME.get().mSuggestionsView);
} else {
mQuotesIME.get().updateWaitingCandidateView(mQuotesIME.get().getString(R
.string.no_results_label));
}
break;
case ERROR:
try {
JSONObject jsonObject = new JSONObject(this.mErrorMessage);
int minLength = jsonObject.getInt("min_phrase_len");
if(minLength > 0) {
mQuotesIME.get().updateWaitingCandidateView(mQuotesIME.get().getString(
R.string.length_error).replace("{int}", String.valueOf(
minLength)));
} else {
mQuotesIME.get().updateWaitingCandidateView(mQuotesIME.get().getString(
R.string.no_phrase_error));
}
} catch (JSONException e) {
Crashlytics.log("Error extracting message from /search call: "
+ e.getMessage());
e.printStackTrace();
}
break;
}
}
}
}
ERROR CRASH:
07-16 14:41:09.488 21099-21099/com.my.app D/AndroidRuntime: Shutting down VM
07-16 14:41:09.514 21099-21099/com.my.app E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.my.app, PID: 21099
java.lang.ClassCastException: android.widget.FrameLayout$LayoutParams cannot be cast to android.widget.AbsListView$LayoutParams
at android.widget.ListView.clearRecycledState(ListView.java:627)
at android.widget.ListView.resetList(ListView.java:614)
at android.widget.ListView.setAdapter(ListView.java:557)
at com.my.app.services.IMEKeyboard$resultSearchAsyncTask.onPostExecute(IMEKeyboard.java:2305)
at com.my.app.services.IMEKeyboard$resultSearchAsyncTask.onPostExecute(IMEKeyboard.java:2175)
at android.os.AsyncTask.finish(AsyncTask.java:695)
at android.os.AsyncTask.-wrap1(Unknown Source:0)
at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:712)
at android.os.Handler.dispatchMessage(Handler.java:105)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6541)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)
07-16 14:41:11.786 21099-21151/com.my.app I/CrashlyticsCore: Crashlytics report upload complete: 5D2E1A3601BE-0001-526B-29AD77A5B0D7
I have a strange issue setting up an adapter for a ListView, the ListView is inside the CandidateView of a custom keyboard, I use a class that inherit of AsyncTask class to execute an API call that returns me a list of items to be displayed on a ListView, in the method onPostExecute() of AsyncTask I take the search results and add to an ArrayList, then this array is being passed to the adapter using the method updateResults(), and finally set the ListView's adapter, everything is fine until here, the code compiles, but during runtime I get the next error:
java.lang.ClassCastException: android.widget.FrameLayout$LayoutParams cannot be cast to android.widget.AbsListView$LayoutParams
ANY HELP PLEASE?, how can I fix it?
Thank you very much for your time
As I see, this issue can come from the wrong LayoutParams. ListView implementation expects AbsListView.LayoutParams and not FrameLayout.LayoutParams. I guess, one of your layout (source_cell.xml or bid_cell.xml) has a FrameLayout as root view. This is not a problem but you would fix the inflation method to get proper LayoutParams.
Change this in bidAdapter.java inside of getView() method:
convertView = mInflater.inflate(R.layout.source_cell, null);
To this:
convertView = mInflater.inflate(R.layout.source_cell, parent, false);
This inflation procedure will know the candidate parent where inflated view would be placed. This allows it to inflate with proper LayoutParam. The next false parameter are going to prevent to add child view automatically. (Because ListView implementation will add later)
For all I can see the error occurs a few calls after setting the adapter and happen inside the ListView, this is a complicated issue to fix taking into account the line of code where is crashing, also is hard to get this wrong without a warning from Android Studio or the compiler, so my suggestion is to use RecyclerView instead of the ListView, RecyclerView is a more advanced and flexible version of ListView, is easy to implement and I'm pretty sure that will fix your issue in the app. Follow this link and you will find a good example on how to implement the RecyclerView.
I am working on an application for tracking calories. I have a SQLite Database implemented with Room and a RecyclerView in on of my Fragments which shows the saved food of the users.
I have problems with the performance of the list. With about 50 entries it takes at least one second in the emulator. On my mobile phone (Samsung Galaxy S5) it already takes several seconds. A list element doesn't show much information, so I wonder about the speed.
I have already read many entries on the Internet, but have not become smarter. I load the pictures with Glide, otherwise only 2 TextViews are shown.
I also wondered if the problem is notifyDataSetChanged(). An alternative would be DiffUtil. I already implemented AsyncListDiffer but the RecyclerView is still pretty slow.
This is the important part of my Fragment:
if(!mAdapter.hasObservers()) mAdapter.setHasStableIds(true);
mAdapter.setOnItemClickListener(new FoodRecyclerViewAdapter.OnItemClickListener() {
#Override
public void onItemClick(Food food) {
DiaryEntriesAddDialog dialog = DiaryEntriesAddDialog.newInstance(food);
dialog.show(getActivity().getSupportFragmentManager(), DiaryEntriesAddDialog.class.getName());
}
});
mRecyclerViewFood.setAdapter(mAdapter);
mRecyclerViewFood.setLayoutManager(new LinearLayoutManager(getContext());
mRecyclerViewFood.addItemDecoration(new DividerItemDecoration(getContext(), DividerItemDecoration.VERTICAL));
mFoodViewModel = ViewModelProviders.of(this).get(FoodViewModel.class);
mFoodViewModel.getAll().observe(this, new Observer<List<Food>>() {
#Override
public void onChanged(#Nullable final List<Food> foods) {
mFoods = foods;
mAdapter.setItems(foods);
});
The function I update my list:
public void setItems(List<Food> foods) {
mFoods = foods;
notifyDataSetChanged();
}
And this is the ViewHolder in my Adapter:
public class ViewHolder extends RecyclerView.ViewHolder {
#BindView(R.id.recyclerview_foodlist_item_constraintlayout) ConstraintLayout mConstraintLayout;
#BindView(R.id.recyclerview_foodlist_item_name) TextView mTextViewName;
#BindView(R.id.recyclerview_foodlist_item_unit) TextView mTextViewUnit;
#BindView(R.id.recyclerview_foodlist_item_imageview_type) ImageView mImageViewType;
#BindArray(R.array.array_dialog_foodadd_units) String[] mUnitNames;
public ViewHolder(#NonNull View itemView) {
super(itemView);
ButterKnife.bind(this, itemView);
}
public void bind(final int position) {
final Food food = getItem(position);
mTextViewName.setText(food.getName());
mTextViewUnit.setText(mUnitNames[food.getUnit()]);
Glide.with(mContext).load(getEntryTypeDrawableResource(food)).into(mImageViewType);
}
Does anyone have an explanation? Am I doing something fundamentally wrong?
EDIT
I did some further investigations. According to the Profiler the LinearLayoutManager.layoutChunk is the most time consuming operation (in debug: ~2 sec) while loading/displaying the items. Each onCreateViewHolder() needs between 3 ms and 100 ms. Almost 100 items could then easily generate these 2 sec.
But why is it that long?
This is my onCreateViewHolder()
public ViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
mContext = viewGroup.getContext();
mLayoutInflater = LayoutInflater.from(mContext);
View view = mLayoutInflater.inflate(R.layout.recyclerview_foodlist_item, viewGroup, false);
return new ViewHolder(view);
}
And this is the layout I am inflating
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android = "http://schemas.android.com/apk/res/android"
xmlns:app = "http://schemas.android.com/apk/res-auto"
android:id = "#+id/recyclerview_foodlist_item_constraintlayout"
android:layout_width = "match_parent"
android:layout_height = "56dp"
android:background = "?android:attr/selectableItemBackground"
android:clickable = "true"
android:focusable = "true"
android:foreground = "?android:attr/selectableItemBackground"
>
<ImageView
android:id = "#+id/recyclerview_foodlist_item_imageview_type"
android:layout_width = "24dp"
android:layout_height = "24dp"
android:layout_marginStart = "16dp"
android:layout_marginTop = "16dp"
android:layout_marginBottom = "16dp"
app:layout_constraintBottom_toBottomOf = "parent"
app:layout_constraintStart_toStartOf = "parent"
app:layout_constraintTop_toTopOf = "parent"
/>
<TextView
android:id="#+id/recyclerview_foodlist_item_name"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginStart="16dp"
android:layout_marginTop = "16dp"
android:layout_marginEnd = "16dp"
android:layout_marginBottom = "16dp"
android:text="Name"
android:textAppearance = "#style/TextAppearance.AppCompat.Menu"
app:layout_constraintBottom_toBottomOf = "parent"
app:layout_constraintEnd_toStartOf = "#+id/recyclerview_foodlist_item_unit"
app:layout_constraintStart_toEndOf = "#+id/recyclerview_foodlist_item_imageview_type"
app:layout_constraintTop_toTopOf="parent" />
<TextView
android:id="#+id/recyclerview_foodlist_item_unit"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginTop = "16dp"
android:layout_marginEnd = "16dp"
android:layout_marginBottom = "16dp"
android:text="Unit"
android:textAppearance = "#style/TextAppearance.AppCompat.Small"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toTopOf = "parent"
/>
</android.support.constraint.ConstraintLayout>
I have an activity with RecyclerView and each item in the list looks like below. The star should be clickable and when the user clicks it, it is expected to be changed to dark star. If the use clicks on the list item, it enters a new activity, where further details are provided corresponding to the list item selected. :
This is the XML of list item.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/cont_item_root"
android:layout_width="match_parent"
android:layout_height="85dp"
android:background="#drawable/background_state_drawable"
android:clickable="true"
>
<ImageView
android:id="#+id/im_item_icon"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingLeft="16dp"
android:src="#mipmap/ic_tonality_black_36dp"
android:layout_centerVertical="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
<TextView
android:id="#+id/lbl_item_text"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignTop="#+id/im_item_icon"
android:layout_marginLeft="72dp"
android:layout_marginRight="48dp"
android:ellipsize="end"
android:fontFamily="sans-serif"
android:singleLine="true"
android:text="Sois comme l'eau mon ami"
android:textColor="#android:color/black"
android:textSize="16sp" />
<TextView
android:id="#+id/lbl_item_sub_title"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/lbl_item_text"
android:layout_marginLeft="72dp"
android:layout_marginRight="48dp"
android:ellipsize="end"
android:fontFamily="sans-serif"
android:singleLine="true"
android:text="Mononc' J"
android:textSize="14sp" />
<ImageView
android:id="#+id/im_item_icon_secondary"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_alignParentRight="true"
android:layout_centerVertical="true"
android:padding="16dp"
android:src="#mipmap/ic_star_border_black_24dp"
android:background="#drawable/background_state_drawable"
/>
</RelativeLayout>
A nested class in Adapter handles the click events for me.
class DerpHolder extends RecyclerView.ViewHolder implements View.OnClickListener
{
private TextView title;
private TextView subTitle;
private ImageView thumbnail;
private ImageView secondaryIcon;
private View container;
public DerpHolder(View itemView) {
super(itemView);
title = (TextView)itemView.findViewById(R.id.lbl_item_text);
subTitle = (TextView)itemView.findViewById(R.id.lbl_item_sub_title);
thumbnail = (ImageView)itemView.findViewById(R.id.im_item_icon);
secondaryIcon = (ImageView)itemView.findViewById(R.id.im_item_icon_secondary);
container = (View)itemView.findViewById(R.id.cont_item_root);
container.setOnClickListener(this);
}
#Override
public void onClick(View v) {
Log.w("RecyclerView","Item with id : " + v.getId() + " touched");
if(v.getId() == R.id.cont_item_root)
{
Log.w("RecyclerView","list item clicked");
itemClickCallback.onItemClick(getAdapterPosition());
}
else
{
Log.w("RecyclerView","star clicked");
itemClickCallback.onSecondaryIconClick(getAdapterPosition()); //not able to come here
}
}
}
I am able to enter the first part of if, i.e. I am able to receive the click event of listItem click. However, when the user clicks star, it is also treated as if the whole list item is clicked as the star lies inside the container.
How can I receive the click on star seperately, so that the click on star is not treated as the click on list item?
EDIT
Adding the line android:descendantFocusability="blocksDescendants" in the RelativeLayout of list item fixed the issue. But can anyone please explain how it fixed it. By name, it is expected to block the descendants and eat the click events. However, the behaviour is opposite.
Since you just want to get the click of the star, you should set the OnClickListener just for the star:
public DerpHolder(View itemView) {
super(itemView);
title = (TextView)itemView.findViewById(R.id.lbl_item_text);
subTitle = (TextView)itemView.findViewById(R.id.lbl_item_sub_title);
thumbnail = (ImageView)itemView.findViewById(R.id.im_item_icon);
secondaryIcon = (ImageView)itemView.findViewById(R.id.im_item_icon_secondary);
secondaryIcon.setOnClickListener(this);
}
reverse the if / else statement and add a click listener for the star image. It should work since you want to trigger the listener for the recyclerview item if the star is not clicked
class DerpHolder extends RecyclerView.ViewHolder implements View.OnClickListener
{
private TextView title;
private TextView subTitle;
private ImageView thumbnail;
private ImageView secondaryIcon;
private View container;
public DerpHolder(View itemView) {
super(itemView);
title = (TextView)itemView.findViewById(R.id.lbl_item_text);
subTitle = (TextView)itemView.findViewById(R.id.lbl_item_sub_title);
thumbnail = (ImageView)itemView.findViewById(R.id.im_item_icon);
secondaryIcon = (ImageView)itemView.findViewById(R.id.im_item_icon_secondary);
container = (View)itemView.findViewById(R.id.cont_item_root);
container.setOnClickListener(this);
secondaryIcon.setOnClickListener(this);
}
#Override
public void onClick(View v) {
Log.w("RecyclerView","Item with id : " + v.getId() + " touched");
if(v.getId() == R.id.im_item_icon_secondary)
{
Log.w("RecyclerView","star clicked");
itemClickCallback.onSecondaryIconClick(getAdapterPosition());
}
else
{
Log.w("RecyclerView","list item clicked");
itemClickCallback.onItemClick(getAdapterPosition());
}
}
}
Hope this helps
You forgot to add onClick listener to secondaryIcon.
Try this:
class DerpHolder extends RecyclerView.ViewHolder implements View.OnClickListener
{
private TextView title;
private TextView subTitle;
private ImageView thumbnail;
private ImageView secondaryIcon;
private View container;
public DerpHolder(View itemView) {
super(itemView);
title = (TextView)itemView.findViewById(R.id.lbl_item_text);
subTitle = (TextView)itemView.findViewById(R.id.lbl_item_sub_title);
thumbnail = (ImageView)itemView.findViewById(R.id.im_item_icon);
secondaryIcon = (ImageView)itemView.findViewById(R.id.im_item_icon_secondary);
container = (View)itemView.findViewById(R.id.cont_item_root);
container.setOnClickListener(this);
secondaryIcon.setOnClickListener(this);
}
#Override
public void onClick(View v) {
if(v.getId() == secondaryIcon.getId())
{
Log.w("RecyclerView","star clicked");
itemClickCallback.onSecondaryIconClick(getAdapterPosition());
}
else
{
Log.w("RecyclerView","list item clicked");
itemClickCallback.onItemClick(getAdapterPosition());
}
}
}
Hope this will help~
You can also declare onclick item for specific views's of row like below in recycler adapter class.
#Override
public void onBindViewHolder(ViewHolder holder, final int position) {
// - get element from your dataset at this position
// - replace the contents of the view with that element
holder.linRootMain.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//Do your stuff here.
}
});
holder.imgStart.setOnClickListner(new View.OnClickListener() {
#Override
public void onClick(View view) {
//Do your stuff here.
}
});
}
I hope this will help you.
So I have been researching for about 4 hours now on how I can fix this issue I am having.
Basically I am trying to create a Alert box and use data from a cursor to set the text of a TextView and the data is there but once i try to set it i get a null object reference everytime and I refuse to move past it :(
Here is the code in question:
public void InputManual(long id) {
#SuppressLint("AndroidLintInflateParams")
final SQLite db = new SQLite(this);
SQLiteDatabase X = db.getReadableDatabase();
Cursor c;
try {
c = X.rawQuery("SELECT Product FROM Inventory WHERE _id =" + id, null);
c.moveToNext();
CreatePopup();
Y = (TextView) findViewById(R.id.product);
Log.v(TAG, "DATA: " + c.getString(c.getColumnIndexOrThrow("Product")).toString());
Y.setText(c.getString(c.getColumnIndexOrThrow("Product")));
c.close();
} catch (Exception e) {
e.printStackTrace();
}
}
The data is there when i use Log.v to display it and it is gone when i try to setText.
Here is CreatePopup():
private void CreatePopup() {
LayoutInflater Manual = LayoutInflater.from(this);
final View textEntryView = Manual.inflate(R.layout.update, null);
final EditText infoData = (EditText) textEntryView.findViewById(R.id.InfoData);
final AlertDialog.Builder alert = new AlertDialog.Builder(this);
alert.setTitle("Update Quantity").setView(textEntryView).setPositiveButton("Save",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int whichButton) {
String Result = infoData.getText().toString();
String Done = "";
if (Result.length() == 0) {
}
}
}).setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int whichButton) {
}
});
alert.show();
}
The XML File:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="#+id/Information"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="15dp"
android:paddingLeft="5dp"
android:text="#string/Product"
android:textAppearance="?android:attr/textAppearanceSmall" />
<TextView
android:id="#+id/product"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="15dp"
android:inputType="none"
android:text="" />
<EditText
android:id="#+id/InfoData"
style="#android:style/TextAppearance.Small"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:hint="#string/hint_data"
android:inputType="number" />
</LinearLayout>
And I have a listView onItemClickListerner that just passes InputManual(id) which would just be the id of the item in the database.
I'm at the point where I want to throw my keyboard because I can't figure out why it becomes null every time I try anything.
Any help would be appreciated even a different approach would be helpful.
My goal is to click on a item in the ListView and generate the Alert box with the item from the list so I can change the quantity to a different value but im just trying to set the TextView to whats in the ListView which is getting data from a database.
I probably didn't explain it correctly but I am willing to give any information that could help me solve this!
Long time browser of stackoverflow and I finally got to the point where I needed help because I can't google anymore :(
The actual error:
inventory W/art: Before Android 4.1, method int android.support.v7.widget.ListViewCompat.lookForSelectablePosition(int, boolean) would have incorrectly overridden the package-private method in android.widget.ListView
inventory V/MyActivity: DATA: CokeD
inventory W/System.err: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference
Thanks!
This error:
inventory W/System.err: java.lang.NullPointerException: Attempt to
invoke virtual method 'void
android.widget.TextView.setText(java.lang.CharSequence)' on a null
object reference
means that the TextView object is null, not the string value that you get from the database.
This means
Y = (TextView) findViewById(R.id.product);
is returning null, possibly because that view is owned by the dialog, not by the activity.
Try passing the string value to the CreatePopup() method as an argument, then you can call setText from there. Like this:
private void CreatePopup(String product) {
LayoutInflater Manual = LayoutInflater.from(this);
final View textEntryView = Manual.inflate(R.layout.update, null);
final EditText infoData = (EditText) textEntryView.findViewById(R.id.InfoData);
//Add these lines
final TextView productText = (TextView) textEntryView.findViewById(R.id.product);
productText.setText(product);
...
}
Got it to work by doing this
private void CreatePopup(Long id) {
LayoutInflater Manual = LayoutInflater.from(this);
final View textEntryView = Manual.inflate(R.layout.update, null);
final EditText infoData = (EditText) textEntryView.findViewById(R.id.InfoData);
final AlertDialog.Builder alert = new AlertDialog.Builder(this);
final TextView TextSet = (TextView) textEntryView.findViewById(R.id.product);
final SQLite db = new SQLite(this);
SQLiteDatabase X = db.getReadableDatabase();
Cursor c;
c = X.rawQuery("SELECT Product FROM Inventory WHERE _id =" + id, null);
c.moveToFirst();
final String Data = c.getString(c.getColumnIndexOrThrow("Product"));
TextSet.setText(Data);
c.close();
alert.setTitle("Update Quantity").setView(textEntryView).setPositiveButton("Save",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int whichButton) {
String Result = infoData.getText().toString();
if (Result.length() == 0) {
}
}
}).setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int whichButton) {
// ScanDataEmpty();
}
});
alert.show();
}
Now I feel dumb.
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 7 years ago.
I'd like to create a TextView with the name of the person you've just tapped, but when I tap a name, it prints an error message to the console.
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView parentView, View childView, int position, long id) {
System.err.println("clicked " + position);
System.err.println("clicked " + friendsIO.getPresentationText(position));
try {
JSONObject friendInformations = new JSONObject(friendsIO.getPresentationText(position));
String friendNames = friendInformations.getString("name");
System.err.println(friendNames);
TextView peopleName = (TextView) findViewById(R.id.peoplePerson);
peopleName.setText(friendNames);
String friendEmails = friendInformations.getString("email");
System.err.println(friendEmails);
String friendNumbers = friendInformations.getString("phone number");
System.err.println(friendNumbers);
String friendEmailsNumbers = friendNames + "\n" + friendEmails;
// TextView peopleInformations = (TextView) findViewById(R.id.peopleInfo);
// peopleInformations.setText(friendEmailsNumbers);
} catch (Exception e) {
e.printStackTrace();
}
final LayoutInflater peopleInflater = LayoutInflater.from(MainActivity.this);
final View peopleView = peopleInflater.inflate(R.layout.popup2, null);
final PopupWindow peoplePopup = new PopupWindow(peopleView, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT, true);
peoplePopup.showAtLocation(peopleView, Gravity.CENTER, 0, 0);
final Button peopleBack = (Button) peopleView.findViewById(R.id.cancel_button);
peopleBack.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
peoplePopup.dismiss();
}
}
);
I print the name to the console first, to make sure that it actually exists and I get the name I tapped (as well as the email and number, obviously), but instead of printing the name to the screen in a TextView, it gives me the following error message:
10-01 17:39:55.505 4259-4259/com.logit.data.returntosender W/System.err﹕ java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference
10-01 17:39:55.506 4259-4259/com.logit.data.returntosender W/System.err﹕ at com.logit.data.returntosender.MainActivity$1.onItemClick(MainActivity.java:60)
It says the error is at the line
System.err.println(friendNames);
But the TextView is only actually given afterwards, in line 61. I have tried around a bit, and not found what the problem could be. It's technically exactly how it should be, at least that's what I've been able to gather from other StackOverflow questions and a thorough google search.
The XML file of the popup with the name (and email and phone number, but that's not part of the question):
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:background="#color/colorAroundPopups"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:gravity="center_vertical|center_horizontal">
<TextView android:id="#+id/peoplePerson"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#color/colorOfPopups"
android:textStyle="bold"
android:text=""
android:textSize="52sp"/>
<TextView android:id="#+id/peopleInfo"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#color/colorOfPopups"
android:textStyle="normal"
android:textSize="26sp"/>
<Button android:id="#+id/cancel_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/cancel_it" />
</LinearLayout>
Thanks in advance
-Léon
EDIT: I added the part of the code where the popup, containing the TextView, is created.
EDIT: I found the found the solution. I had to put the name of the view containing the TextView before findViewById
Also, Frank N. Stein, thank you for not helping at all by sending me a question I had already looked through :)
You are retrieving the view from the activity, if the TextView was on the list item view, you would change...
TextView peopleName = (TextView) findViewById(R.id.peoplePerson);
to...
TextView peopleName = (TextView) childView.findViewById(R.id.peoplePerson);
instead of doing this:
TextView peopleName = (TextView) findViewById(R.id.peoplePerson);
do this:
TextView peopleName = (TextView) childView.findViewById(R.id.peoplePerson);
as your textview is a child of the listview.