Fragment replacing returns NullPointerException - java

There are many topics on this subject, but I couldn't find any solution that helped my case.
IDEA BEHIND:
What I have is a ViewPager, for swipping between 3 fragments. That works. But in one of the mentioned fragments, I do some functionalities - which then I check in another one of those before mentioned Fragments. Everything works.
Then, when I do the check, I open an AlertDialog, telling the user that his configuration is succesfull. By button click, I want that app transfers the user to one different Fragment (not one of the ViewPager fragments).
CODE SNIPPET - FragmentTwo:
public void displayAlertSuccess(Context ctx) {
new AlertDialog.Builder(ctx)
.setTitle("ACCESS GRANTED!")
.setMessage("Congratulations!")
.setPositiveButton("Great!", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// continue with
replaceFragment();
}
})
.setNegativeButton("Format my Card", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
mainActivity.setNFC_ACTION("FORMAT");
}
})
.setIcon(android.R.drawable.ic_dialog_info)
.show();
}
private void replaceFragment() {
Fragment frag = new CardDesfire1();
getFragmentManager().beginTransaction().replace(R.id.content_frame, frag).commit();
}
CODE SNIPPET - XML Layouts:
I. activity_holder.xml
<?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">
<!-- As the main content view, the view below consumes the entire
space available using match_parent in both dimensions. -->
<FrameLayout
android:id="#+id/content_frame"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
II. activity_access.xml
<!-- activity_screen_slide.xml -->
<android.support.v4.view.ViewPager
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/pager"
android:layout_width="match_parent"
android:layout_height="match_parent" />
III. fragment_access_slide2.xml (fragment that has the Dialog)
<!-- fragment_screen_slide_page.xml -->
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/content"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#ff0080ff">
<ImageButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:id="#+id/imageButton"
android:src="#drawable/img_access_slide2_2"/>
</ScrollView>
IV. activity_desfire1.xml (Fragment that I want to launch onClick)
<?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"
android:background="#drawable/bg_des2">
<Button
android:layout_width="fill_parent"
android:layout_height="25dp"
android:text="You have discovered..."
android:id="#+id/btn_des1_discovered"
android:background="#3A5FCD"
android:typeface="monospace"
android:textColor="#ffffffff"
android:enabled="false"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
<Button
android:id="#+id/btn_loy"
android:text="Loyalty"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#drawable/buttons_shape"
android:shadowColor="#000000"
android:textColor="#FFFFFF"
android:shadowDx="0"
android:shadowDy="0"
android:shadowRadius="5"
android:layout_above="#+id/btn_pay"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:textAllCaps="false"
android:visibility="invisible"/>
<Button
android:id="#+id/btn_pay"
android:text="µPay"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#drawable/buttons_shape"
android:shadowColor="#000000"
android:textColor="#FFFFFF"
android:shadowDx="0"
android:shadowDy="0"
android:shadowRadius="5"
android:textAllCaps="false"
android:layout_alignParentBottom="true"
android:layout_marginBottom="70dp"
android:layout_centerHorizontal="true"
android:visibility="invisible"/>
<Button
android:id="#+id/btn_acc"
android:text="Access"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#drawable/buttons_shape"
android:shadowColor="#000000"
android:textColor="#FFFFFF"
android:shadowDx="0"
android:shadowDy="0"
android:shadowRadius="5"
android:textAllCaps="false"
android:layout_above="#+id/btn_pay"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:visibility="invisible"/>
<ImageView
android:layout_width="wrap_content"
android:visibility="invisible"
android:layout_height="wrap_content"
android:id="#+id/img_card_des1"
android:layout_below="#+id/btn_des1_discovered"
android:src="#drawable/img_card_des1"
android:layout_centerHorizontal="true"
android:layout_marginTop="48dp" />
<TextView
android:layout_width="fill_parent"
android:layout_height="100dp"
android:visibility="invisible"
android:textSize="18dp"
android:gravity="center"
android:text="#string/des1_desc"
android:id="#+id/tv_des1_desc"
android:textColor="#ffffffff"
android:textStyle="italic"
android:background="#ff8db6cd"
android:layout_below="#+id/img_card_des1"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginTop="40dp" />
</RelativeLayout>
LINE OF ERROR:
getFragmentManager().beginTransaction().replace(R.id.content_frame, frag).commit();
Error Description from LogCat:
java.lang.NullPointerException
Error occurs when:
My error occurs when the user clicks the button "Great" in AlertDialog, which should then invoke the Fragment replacement.
I have tried:
I have tried to fix it with the getChildFragment , but then I get different kind of error: IllegalStateException : Activity has been destroyed.
Any help is kindly appreciated.

Have you declared default constructor in your CardDesfire1 fragment. If not then declare it
public CardDesfire1(){}
Make your parent Activity extend FragmentActivity
class ParentActivity extends FragmentActivity

The problem occurs because you call getFragmentManager() in a Fragment, you should delegate displaying the dialog to the activity.
Make activity implement an interface, and have the fragment call this interface method when it's time to show the dialog.
Example: You define a new inner interface in FragmentTwo(this code goes in FragmentTwo):
public interface OnReplaceFragmentListener {
void onReplaceFragment();
}
You link your activity to the fragment(this code goes in FragmentTwo):
private OnReplaceFragmentListener mCallback;
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
// This makes sure that the container activity has implemented
// the callback interface. If not, it throws an exception
try {
mCallback = (OnReplaceFragmentListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement OnReplaceFragmentListener");
}
}
private void replaceFragment() {
mCallback.onReplaceFragment();
}
Then make activity implement OnReplaceFragmentListener.
And(this code goes into FragmentTwo's hosting activity):
#Override
void onReplaceFragment() {
Fragment frag = new CardDesfire1();
getFragmentManager().beginTransaction().replace(R.id.content_frame, frag).commit();
}

Related

Customize datePickerDialog [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 11 months ago.
Improve this question
I want to show my date picker dialog like this where the background is blurred like a normal datePickerDialog but also has extra components like a textview and button. I cant seem to get this from making the dialog.
You have to custom very much to can create your DatePicker.
I only support a simple DatePicker and you must improve it:
1.Create custom layout: layoutdatetime.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="match_parent"
android:orientation="vertical"
>
<TextView
android:id="#+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="24sp"
android:textColor="#ffffff"
android:text="SELECT TO DATE" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/white"
android:orientation="vertical">
<CalendarView android:layout_marginTop="10dp"
android:id="#+id/calendarView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="right"
android:orientation="horizontal">
<TextView
android:id="#+id/btnCancel"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#f54242"
android:text="Cancel" />
<TextView
android:id="#+id/btnOK"
android:layout_width="wrap_content"
android:layout_marginLeft="5dp"
android:layout_marginRight="10dp"
android:layout_height="wrap_content"
android:textColor="#f54242"
android:text="OK" />
</LinearLayout>
</LinearLayout>
<Button
android:id="#+id/button3"
android:layout_marginTop="20dp"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Button" />
</LinearLayout>
Create funtion display DatePicker and custom process of controls on layout
public void ShowDate() {
Dialog dialog = new Dialog(this);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setContentView(R.layout.layoutdatetime);
dialog.getWindow().setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT));
TextView btnCancel = dialog.findViewById(R.id.btnCancel);
btnCancel.setOnClickListener(v -> dialog.cancel());
dialog.show();
}
Requirements:
View binding
Create a custom layout named layoutdatetime.xml : (Taken from Dt's answer over here.
<?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="match_parent"
android:orientation="vertical"
>
<TextView
android:id="#+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="24sp"
android:textColor="#ffffff"
android:text="SELECT TO DATE" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/white"
android:orientation="vertical">
<CalendarView android:layout_marginTop="10dp"
android:id="#+id/calendarView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="right"
android:orientation="horizontal">
<TextView
android:id="#+id/btnCancel"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#f54242"
android:text="Cancel" />
<TextView
android:id="#+id/btnOK"
android:layout_width="wrap_content"
android:layout_marginLeft="5dp"
android:layout_marginRight="10dp"
android:layout_height="wrap_content"
android:textColor="#f54242"
android:text="OK" />
</LinearLayout>
</LinearLayout>
<Button
android:id="#+id/button3"
android:layout_marginTop="20dp"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Button" />
</LinearLayout>
Make a class named DateListener and paste this code:
public interface DateListener {
void onDateNotPicked();
void onDatePicked(Date date);
void onGenerateStatement();
}
To make use of that, make this class and paste the code:
public class CustomDatePickerDialog extends Dialog {
private DateListener listener;
private LayoutdatetimeBinding binding;
public CustomDatePickerDialog(#NonNull Context context, DateListener dateListener) {
super(context);
listener = dateListener;
binding = LayoutdatetimeBinding.inflate(getLayoutInflater());
setContentView(binding.getRoot());
init();
}
private void init() {
binding.btnOK.setOnClickListener(v -> {
listener.onDatePicked(new Date(binding.calendarView.getDate()));
dismiss();
});
binding.btnCancel.setOnClickListener(v -> {
dismiss();
listener.onDateNotPicked();
});
binding.generateStatement.setOnClickListener(v -> {
listener.onGenerateStatement();
dismiss();
});
}
}
Show it in this way:
CustomDatePickerDialog dialog = new CustomDatePickerDialog(this, new DateListener(){
#Override
public void onDateNotPicked() {
Toast.makeText(this, "date not picked", Toast.LENGTH_SHORT).show();
}
#Override
public void onDatePicked(Date date) {
Toast.makeText(this, "date picked", Toast.LENGTH_SHORT).show();
}
#Override
public void onGenerateStatement() {
Toast.makeText(this, "statemnt generated", Toast.LENGTH_SHORT).show();
}
});
dialog.show();

Layering images in Android Studio?

Currently I have a UI designed with imageviews, the problem is they cannot overlap or be layered. (Or if they can, I haven't figure out how)
I'd like to do 3 layers, the bottom layer is the board,
The next layer is pieces,
The next layer is a selected piece with valid moves.
My idea is that I will have listeners on the top layer only.
I am just looking for the best data structure to use for this, the app is a chesslike game I am working on developing.
If there is another approach that might be better I am all ears as well.
Thanks!
As requested code :
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent"
android:weightSum="1">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Game Activity"
android:id="#+id/textView5"
android:layout_gravity="center_horizontal"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true" />
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/imageView22"
android:src="#drawable/ni_whitesquare"
android:layout_below="#+id/textView5"
android:layout_alignRight="#+id/textView5"
android:layout_alignEnd="#+id/textView5"
android:layout_marginRight="15dp"
android:layout_marginEnd="15dp"
android:layout_marginTop="76dp"
android:contentDescription="whitesquare"
android:clickable="true" />
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/imageView32"
android:src="#drawable/ni_blacksquare"
android:layout_alignTop="#+id/imageView22"
android:layout_alignLeft="#+id/imageView22"
android:layout_alignStart="#+id/imageView22"
android:layout_marginLeft="23dp"
android:layout_marginStart="23dp"
android:contentDescription="blacksquare"
android:clickable="true" />
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/imageView12"
android:src="#drawable/ni_blacksquare"
android:contentDescription="blacksquare"
android:clickable="true"
android:layout_alignTop="#+id/imageView22"
android:layout_toLeftOf="#+id/imageView22"
android:layout_toStartOf="#+id/imageView22" />
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/imageView21"
android:src="#drawable/ni_blacksquare"
android:contentDescription="blacksquare"
android:clickable="true"
android:layout_below="#+id/imageView22"
android:layout_toRightOf="#+id/imageView12"
android:layout_toEndOf="#+id/imageView12" />
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/imageView23"
android:src="#drawable/ni_blacksquare"
android:contentDescription="blacksquare"
android:clickable="true"
android:layout_above="#+id/imageView12"
android:layout_toLeftOf="#+id/imageView33"
android:layout_toStartOf="#+id/imageView33" />
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/imageView31"
android:src="#drawable/ni_whitesquare"
android:contentDescription="whitesquare"
android:clickable="true"
android:layout_alignBottom="#+id/imageView21"
android:layout_alignLeft="#+id/imageView32"
android:layout_alignStart="#+id/imageView32" />
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/imageView11"
android:src="#drawable/ni_whitesquare"
android:contentDescription="whitesquare"
android:clickable="true"
android:layout_alignTop="#+id/imageView21"
android:layout_toLeftOf="#+id/imageView21"
android:layout_toStartOf="#+id/imageView21" />
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/imageView13"
android:src="#drawable/ni_whitesquare"
android:contentDescription="whitesquare"
android:clickable="true"
android:layout_alignTop="#+id/imageView23"
android:layout_alignLeft="#+id/imageView12"
android:layout_alignStart="#+id/imageView12" />
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/imageView33"
android:src="#drawable/ni_whitesquare"
android:contentDescription="whitesquare"
android:clickable="true"
android:layout_alignTop="#+id/imageView23"
android:layout_alignLeft="#+id/imageView32"
android:layout_alignStart="#+id/imageView32" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceSmall"
android:text="#string/directions"
android:id="#+id/directionsstring"
android:layout_marginTop="30dp"
android:layout_below="#+id/imageView21"
android:layout_alignLeft="#+id/textView5"
android:layout_alignStart="#+id/textView5" />
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/Startingpoint"
android:src="#drawable/ni_pawn"
android:layout_above="#+id/imageView11"
android:layout_toLeftOf="#+id/imageView12"
android:layout_toStartOf="#+id/imageView12" />
</RelativeLayout>
Activity :
public class GameActivity extends Activity
{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_game);
final ImageView mStarting = (ImageView) findViewById(R.id.Startingpoint);
final ImageView mCenterSq = (ImageView) findViewById(R.id.imageView22);
final ImageView m12 = (ImageView)findViewById(R.id.imageView12);
mCenterSq.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
m12.setImageResource(R.drawable.ni_blacksquare);
mCenterSq.setImageResource(R.drawable.ni_portal);
//center square turns into a portal when clicked.
if (mStarting.getDrawable().getConstantState().equals(getResources().getDrawable(R.drawable.ni_whitesquare).getConstantState()) &&
mCenterSq.getDrawable().getConstantState().equals(getResources().getDrawable(R.drawable.ni_portal).getConstantState()) )
{
mCenterSq.setOnClickListener(null);
return;
}
mStarting.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
//Pawn selected
mStarting.setImageResource(R.drawable.ni_whitesquare);
m12.setImageResource(R.drawable.ni_greensquare);
mCenterSq.setImageResource(R.drawable.ni_greensquare);
if (mStarting.getDrawable().getConstantState().equals(getResources().getDrawable(R.drawable.ni_whitesquare).getConstantState()))
{
mStarting.setOnClickListener(null);
}
m12.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
if (m12.getDrawable().getConstantState().equals(getResources().getDrawable(R.drawable.ni_greensquare).getConstantState()))
{
m12.setImageResource(R.drawable.ni_pawn);
mCenterSq.setImageResource(R.drawable.ni_portal);
}
}
});
}
});
};
});
}
}
For layering views, you might want to use a FrameLayout see this answer: Layout Layers? Z-Axis?
Also, if you're trying to set up a layout in which you have several consecutive views that need to be lined up one next to the other, the most appropriate element is usually a LinearLayout. LinearLayout will automatically set up your views in consecutive order in the order you declared them, according to the android:orientation attribute you set for it.
Overall, I'd suggest looking at the docs for each of these. RelativeLayout is probably not the way to go since it involves a lot of managing of view positioning which just seems frivolous for what I think you are trying to do. I hope this helps

How to add a 'Click for more details' expandable field to AlertDialog in android

I have a AlertDialog that is shown when there is an error and it prints 'Error, could not be added/whatever", I also have the result of the exception that I'd like to parse but not shown to all users, only to those that want to click on 'details' and read the exception.
AlertDialog.Builder dialogo1 = new AlertDialog.Builder(activity);
dialogo1.setTitle("Error");
dialogo1.setMessage("Could not update movie: " + result);
dialogo1.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialogo1, int id) {
activity.finish();
}
});
dialogo1.show();
There is my code, pretty simple, right? I haven't been able to find this answer anyway and I'm starting to think it is just not possible
what you want is a custom alert dialog.
so for that you will have to us a layout and define your dialog.Then initialize your listeners etc like it was a normal view that you are defining
dialog_layout.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<ImageView
android:src="#drawable/header_logo"
android:layout_width="match_parent"
android:layout_height="64dp"
android:scaleType="center"
android:background="#FFFFBB33"
android:contentDescription="#string/app_name" />
<TextView
android:id="#+id/error"
andorid:text="Error Message"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<Button
android:id="#+id/moreDetailsButton"
android:text="Click for more details"
android:inputType="textPassword"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
<TextView
android:id="#+id/moreDetailsView"
android:text="Click for more details"
android:inputType="textPassword"
android:layout_width="match_parent"
android:visibility="gone";
android:layout_height="wrap_content"/>
<Button
android:id="#+id/dialogButtonOK"
android:layout_width="100px"
android:layout_height="wrap_content"
android:text=" Ok "
android:layout_marginTop="5dp"
android:layout_marginRight="5dp"
android:layout_below="#+id/moreDetailsButton"
/>
</RelativeLayout>
and in your class
final Dialog dialog = new Dialog(context);
dialog.setContentView(R.layout.dialog_layout);
TextView error=(TextView)dialog.findViewById(R.id.error);
Button errorButton=(Button)dialog.findViewById(R.id.moreDetailsButton);
Button okButton=(Button)dialog.findViewById(R.id.ok);
//Do whatever you want with the rest of the dialog
// initialize all the onclick listeners a usual
errorButton.setOnClickListener(new View.onClickListener(){
#Override
public void onClick(View v){
TextView errorDetails=(TextView)dialog.findViewById(R.id.moreDetailsView);
errorDetails.setText(detailedErrorMessage) //add the details to this text view;
errorDetails.setVisibility(View.VISIBLE);
}
});
dialog.show();
Sorry if there are any syntactically errors if the ctrl+c,ctrl+v of this doesnt work.My IDE decided to misbehave today.
Follow this for details on a custom alert dialog.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<LinearLayout
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TextView
android:id="#+id/error"
android:text="Error Message"
android:layout_width="match_parent"
android:layout_height="37dp"
android:layout_toEndOf="#+id/moreDetailsView"
android:layout_alignParentTop="true"
android:layout_alignParentStart="true" />
<TextView
android:id="#+id/moreDetailsView"
android:text="No existen detalles para este tipo de error."
android:layout_width="match_parent"
android:visibility="gone"
android:layout_height="wrap_content" />
<Button
android:id="#+id/moreDetailsButton"
android:text="Click for more details"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_toEndOf="#+id/moreDetailsView"
android:layout_below="#+id/error"
android:layout_alignParentStart="true" />
<Button
android:id="#+id/dialogButtonOK"
android:layout_width="139dp"
android:layout_height="wrap_content"
android:text="OK"
android:layout_centerVertical="true"
android:layout_toEndOf="#+id/moreDetailsView"
android:layout_gravity="center_horizontal" />
</LinearLayout>
</RelativeLayout>

Android List onListItemClick not working

I've got a new List of things that needs to be clicked but this one isn't working. onListItemClick is never called. I have another one in my app that has been working as expected and I can't figure out what the difference is. I've seen the people saying to change focusable but I've tried that a bunch of different ways with no effect. So here's some code.
Working:
#Override
protected void onListItemClick(ListView l, View v, int position, long id)
{
super.onListItemClick(l, v, position, id);
// get the item that was clicked
v_ProjectInvestigatorSiteContact project = (v_ProjectInvestigatorSiteContact) this.getListAdapter().getItem(
position);
Intent myIntent = new Intent(this, Details.class);
myIntent.putExtra(res.getString(R.string.project), project);
startActivity(myIntent);
}// onListItemClick
Not Working:
#Override
protected void onListItemClick(ListView l, View v, int position, long id)
{
super.onListItemClick(l, v, position, id);
// get the item that was clicked
final v_SitePeople vSitePeople = (v_SitePeople) this.getListAdapter().getItem(
position);
AlertDialog.Builder builder = new AlertDialog.Builder(Share.this);
builder.setTitle(res.getString(R.string.forgot_password_check_dialog_title))
.setMessage(res.getString(R.string.share_check_dialog_text))
.setPositiveButton(res.getString(R.string.send), new DialogInterface.OnClickListener()
{
#Override
public void onClick(DialogInterface dialog, int which)
{
sendShareEmail(vSitePeople);
}
}).setNegativeButton(res.getString(R.string.cancel), new DialogInterface.OnClickListener()
{
#Override
public void onClick(DialogInterface dialog, int which)
{
// cancelled, so do nothing
}
});
AlertDialog msgBox = builder.create();
msgBox.show();
}// onListItemClick
Working 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="match_parent"
android:background="#ffffffff"
android:orientation="vertical" >
<!-- dummy item to prevent edittext from gaining focus on activity start -->
<LinearLayout
android:layout_width="0px"
android:layout_height="0px"
android:focusable="true"
android:focusableInTouchMode="true" />
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#drawable/title_background" >
<ImageView
android:id="#+id/logo"
android:layout_width="30dp"
android:layout_height="30dp"
android:layout_centerVertical="true"
android:layout_marginLeft="5dp"
android:scaleType="centerCrop"
android:src="#drawable/ic_logo" >
</ImageView>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_toRightOf="#+id/logo"
android:gravity="center"
android:paddingBottom="5dp"
android:paddingLeft="50dp"
android:paddingRight="60dp"
android:paddingTop="5dp"
android:text="#string/app_header"
android:textColor="#ffffffff"
android:textSize="15sp"
android:textStyle="bold" />
</RelativeLayout>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#drawable/search_gradient" >
<ImageView
android:id="#+id/searchBoxIcon"
android:layout_width="38dp"
android:layout_height="38dp"
android:layout_centerVertical="true"
android:layout_marginLeft="5dp"
android:layout_marginRight="5dp"
android:scaleType="centerCrop"
android:src="#drawable/action_search" >
</ImageView>
<EditText
android:id="#+id/searchBox"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_centerVertical="#+id/searchBoxIcon"
android:layout_marginRight="8dp"
android:layout_marginTop="4dp"
android:layout_toRightOf="#+id/searchBoxIcon"
android:background="#drawable/search_box"
android:hint="#string/search_hint"
android:inputType="text"
android:maxLines="1"
android:minHeight="30sp"
android:paddingBottom="2dp"
android:paddingLeft="25sp"
android:paddingTop="2dp"
android:textColor="#ff000000" />
</RelativeLayout>
<ListView
android:id="#id/android:list"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:background="#color/divider_gray"
android:cacheColorHint="#00000000"
android:divider="#color/divider_gray"
android:dividerHeight="1dp"
android:footerDividersEnabled="false"
android:headerDividersEnabled="false" />
<TextView
android:id="#+id/android:empty"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:text="#string/loading"
android:textColor="#color/loading_gray"
android:textSize="20sp" />
</LinearLayout>
Not Working 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="match_parent"
android:background="#ffffffff"
android:orientation="vertical" >
<!-- dummy item to prevent edittext from gaining focus on activity start -->
<LinearLayout
android:layout_width="0px"
android:layout_height="0px"
android:focusable="true"
android:focusableInTouchMode="true" />
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#drawable/title_background" >
<ImageView
android:id="#+id/logo"
android:layout_width="30dp"
android:layout_height="30dp"
android:layout_centerVertical="true"
android:layout_marginLeft="5dp"
android:scaleType="centerCrop"
android:src="#drawable/ic_logo" >
</ImageView>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_toRightOf="#+id/logo"
android:gravity="center"
android:paddingBottom="5dp"
android:paddingLeft="50dp"
android:paddingRight="60dp"
android:paddingTop="5dp"
android:text="#string/share_header"
android:textColor="#ffffffff"
android:textSize="15sp"
android:textStyle="bold" />
</RelativeLayout>
<ListView
android:id="#id/android:list"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:background="#color/divider_gray"
android:cacheColorHint="#00000000"
android:divider="#color/divider_gray"
android:dividerHeight="1dp"
android:footerDividersEnabled="false"
android:headerDividersEnabled="false" />
<TextView
android:id="#+id/android:empty"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:text="#string/loading"
android:textColor="#color/loading_gray"
android:textSize="20sp" />
</LinearLayout>
Here is more on how the broken one works, just in case you want more code.
Not Working Row 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="?android:attr/listPreferredItemHeight"
android:layout_weight="1"
android:baselineAligned="false"
android:orientation="vertical"
android:padding="6dp"
android:background="#ffffffff"
android:layout_margin="10dp" >
<TextView
android:id="#+id/toptext"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_toLeftOf="#id/moreInfo"
android:gravity="center_vertical"
android:minHeight="20sp"
android:textColor="#ff000000"
android:textStyle="bold" />
</RelativeLayout>
Not Working View Adapter
#Override
public View getView(int position, View convertView, ViewGroup parent)
{
ViewHolder holder = null;
if (convertView == null)
{
holder = new ViewHolder();
LayoutInflater vi = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = vi.inflate(R.layout.share_row, null);
convertView.setTag(holder);
}// if
else
{
holder = (ViewHolder) convertView.getTag();
}
v_SitePeople i = items.get(position);
if (i != null)
{
TextView topText = (TextView) convertView.findViewById(R.id.toptext);
topText.setGravity(Gravity.CENTER_VERTICAL);
topText.setMinHeight(40);
if (topText != null)
{
if (i.SitePerson != null)
{
if (i.PersonTitle != null)
{
topText.setText(String.format(i.SitePerson + ", " + i.PersonTitle));
}
else
{
topText.setText(i.SitePerson);
}
}// if has ProtocolNumber
else
{
if (i.Nickname != null)
{
topText.setText(i.Nickname);
}
}// if does not have ProtocolNumber
}// if
}// if
return convertView;
}// getView
Thank you so much for your help.
I figured it out. I never posted the relavant code, or I'm sure you guys would have found it for me.
My not working adapter had a isEnabled method copied from my functioning adapter that disabled items of type 0. But since my new list is all just one type everything was disabled.
Sorry for the trouble and thank you for your efforts.
You haven't shown where you initialise your list and adapter, but you need to make sure the onClickListner is set. Something like:
myListView.setOnItemClickListener(this);
edit: 'this' assuming initialization is done in the same class as the click listeners appear.
When you're using a ListView, you have mainly two layouts:
1)The layout where you have your listView
Example:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingTop="?attr/actionBarSize"
android:clickable="false"
>
<ListView
android:id="#android:id/list"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:background="#android:color/transparent"
android:clipToPadding="false"
android:paddingLeft="#dimen/list_left_padding"
android:paddingRight="#dimen/list_right_padding"
android:paddingTop="#dimen/list_separator"
android:dividerHeight="#dimen/list_separator"
android:paddingBottom="#dimen/list_separator" />
</RelativeLayout>
2)The layout which contains each item for your ListView.
Example:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#drawable/white_responsive"
android:descendantFocusability="blocksDescendants"
>
<RelativeLayout
android:id="#+id/sampleItem"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="5dp"
android:layout_marginRight="5dp"
android:layout_marginTop="3dp"
android:clipToPadding="false">
<com.devspark.robototextview.widget.RobotoTextView
android:id="#+id/textViewSample"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:paddingBottom="5dp"
android:text="Sample Text"
android:textSize="17sp"
app:typeface="roboto_regular" />
</RelativeLayout>
</RelativeLayout>
If you search on StackOverFlow about this problem, you will got the following instructions to solve it:
1) Add
android:descendantFocusability="blocksDescendants"
to the root of your layout
2) Add
android:clickable="false"
android:focusable="false"
To your item.
You can use these two options separately. The first one have helped me. But, you need to pay attention on where you need to put these attributes in your XML File. Put them in your ITEM layout, not in your ListView Layout. I'm saying this, because I was using that solution, but i was putting on the wrong xml. So, it just pay attention and it will work very well.

How to enable batch contextual actions in a ListView?

I'm trying to follow the official Android guide for CABforListView very closely, but I have not been able to activate context action view on my ListView item long press.
public class MainActivity extends ListActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
loadList(); // loads Cursor data and sets list adapter in AsyncTask
ListView listView = getListView();
listView.setLongClickable(true); // no effect
listView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE_MODAL);
listView.setMultiChoiceModeListener(new AbsListView.MultiChoiceModeListener() {
// implemention of MultiChoiceModeListener
});
}
// rest of the class
}
The following is my list_row_item.xml:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:background="?android:attr/activatedBackgroundIndicator"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:longClickable="true"
android:paddingLeft="15dp"
android:paddingRight="10dp"
android:paddingTop="10dp"
android:paddingBottom="10dp" >
<TextView
android:id="#+id/reminder_row_description"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:textAppearance="?android:attr/textAppearanceMedium" />
<TextView
android:id="#+id/reminder_row_interval"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="#+id/reminder_row_description"
android:textAppearance="?android:attr/textAppearanceSmall" />
<Switch
android:id="#+id/switch_reminder_row"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/reminder_row_interval"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true" />
<TextView
android:id="#+id/reminder_row_time"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/reminder_row_interval"
android:layout_below="#+id/reminder_row_interval"
android:textAppearance="?android:attr/textAppearanceSmall" />
</RelativeLayout>
And my activity_main.xml:
<ListView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#android:id/list"
android:layout_width="match_parent"
android:layout_height="match_parent" >
</ListView>
I have tried using listView.setOnItemLongClickListener() to start ActionMode manually, but while that has launched contextual action mode I was not able to do multiple selects, and no tutorial/guide has ever needed to do this. I am missing something.
Basically, I want to achieve exactly this effect as seen in Jelly Bean's alarm clock:
Any pointers would be greatly appreciated!
Based on #Luksprog comment, returning true from onCreateActionMode() will fix your problem

Categories

Resources