Lalit Thapa
Lalit Thapa

Reputation: 311

Button not responding to OnClickListener

I have a activity that loads data from server. If the error occurs I show a Button to reload/retry for loading data. But the onClickListener does not respond when I click the button. Can someone please help me with this?

This is my activity

public class MyContactsActivity extends AppCompatActivity implements View.OnClickListener {

    private RecyclerView recyclerView;
    private ContactsAdapter adapter;
    private NetworkChecker networkChecker;
    private SessionManager sessionManager;
    private AppConfig appConfig;
    private RelativeLayout loading, retry;
    private Button tryAgain;
    AlertHelper alertHelper;
    final ArrayList<Contact> contactArrayList = new ArrayList<>();
    String url;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_my_contacts);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        loading = (RelativeLayout) findViewById(R.id.loadingPanel);
        retry = (RelativeLayout) findViewById(R.id.retry);
        tryAgain = (Button) findViewById(R.id.tryAgainButton);

        alertHelper = new AlertHelper(this);
        networkChecker = new NetworkChecker(this);
        sessionManager = new SessionManager(this);
        appConfig = new AppConfig();

        String phone = sessionManager.getLoggedInUserPhone();
        url = appConfig.getApiUrlForSpecificContacts(phone);

        tryAgain.setOnClickListener(this);

        recyclerView = (RecyclerView) findViewById(R.id.contactsView);
        adapter = new ContactsAdapter(getApplicationContext());
        recyclerView.setLayoutManager(new LinearLayoutManager(getApplicationContext()));

        sendJsonRequest(url);
        recyclerView.setAdapter(adapter);

        recyclerView.addOnItemTouchListener(
                new RecyclerItemClickListener(this, new RecyclerItemClickListener.OnItemClickListener() {
                    @Override public void onItemClick(View view, int position) {
                        TextView phone = (TextView) view.findViewById(R.id.contact_phone);
                        TextView name = (TextView) view.findViewById(R.id.contact_name);
                        Intent i = new Intent(getApplicationContext(), ContactProfileActivity.class);
                        i.putExtra("selected_user_phone", phone.getText());
                        i.putExtra("selected_user_name", name.getText());
                        startActivity(i);
                    }
                })
        );

        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                        .setAction("Action", null).show();
            }
        });
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    }

    private void sendJsonRequest(String url) {
        if (networkChecker.networkAvailable()) {
            loading.setVisibility(View.VISIBLE);
            RequestQueue requestQueue = VolleySingleton.getsInstance().getmRequestQueue();

            StringRequest stringRequest = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {
                @Override
                public void onResponse(String response) {
                    loading.setVisibility(View.GONE);
                    retry.setVisibility(View.GONE);
                    try {
                        JSONArray jsonArray = new JSONArray(response);

                        if(jsonArray != null){
                            for (int i = 0; i < jsonArray.length(); i++) {
                                JSONObject currentContact = jsonArray.getJSONObject(i);

                                String name = currentContact.getString("name");
                                String phone = currentContact.getString("phone");
                                String city = currentContact.getString("city");
                                String address = currentContact.getString("address");
                                Boolean verified = currentContact.getBoolean("verified");

                                Contact contact = new Contact(name, phone, city, address, verified);

                                contactArrayList.add(contact);

                            }
                            adapter.setContactsList(contactArrayList);
                        }
                        else{
                            alertHelper.displayDialog("No Contacts Found.");
                        }
                    }catch (Exception e){
                        retry.setVisibility(View.VISIBLE);
                    }
                }
            }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    loading.setVisibility(View.GONE);
                    retry.setVisibility(View.VISIBLE);
                    if (error instanceof TimeoutError || error instanceof NoConnectionError) {
                        alertHelper.displayDialog(getString(R.string.connection_failed));
                    } else {
                        alertHelper.displayDialog(error.toString());
                    }
                }
            });

            requestQueue.add(stringRequest);

        } else {
            alertHelper.displayDialog(getString(R.string.network_not_available));
            retry.setVisibility(View.VISIBLE);
        }
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.tryAgainButton:
                sendJsonRequest(url);
                break;
        }
    }
}

And this is my xml layout

<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true"
    tools:context="com.pinesofts.quickcontact.MyContactsActivity">

    <android.support.design.widget.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:theme="@style/AppTheme.AppBarOverlay">

        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="?attr/colorPrimary"
            app:popupTheme="@style/AppTheme.PopupOverlay" />

    </android.support.design.widget.AppBarLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical"
        android:gravity="center">

        <RelativeLayout
            android:id="@+id/loadingPanel"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:visibility="gone"
            android:gravity="center" >

            <ProgressBar
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:indeterminate="true" />
        </RelativeLayout>

        <RelativeLayout
            android:id="@+id/retry"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:visibility="gone"
            android:gravity="center" >

            <TextView
                android:id="@+id/retryText"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="@string/try_again_text"/>

            <Button
                android:id="@+id/tryAgainButton"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_below="@id/retryText"
                android:text="Try Again"/>
        </RelativeLayout>

    </LinearLayout>

    <include layout="@layout/content_my_contacts" />

    <android.support.design.widget.FloatingActionButton
        android:id="@+id/fab"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom|end"
        android:layout_margin="@dimen/fab_margin"
        android:src="@android:drawable/ic_dialog_email" />

</android.support.design.widget.CoordinatorLayout>

Upvotes: 1

Views: 2538

Answers (5)

Lalit Thapa
Lalit Thapa

Reputation: 311

I figured it out guys. Thanks to your comments and suggestions.

In the layout file above what I was doing is using LinearLayout with height and width as match_parent to wrap my two RelativeLayout and leaving include outside of LinearLayout.

My include file contains RecyclerView which also has match_parent on both height and width.

Due to this RecyclerView was on top of my RelativeLayout which contains my Button. So I was not even able to click my Button.

I changed my xml file as below and it's working.

<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true"
    tools:context="com.pinesofts.quickcontact.MyContactsActivity">

    <android.support.design.widget.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:theme="@style/AppTheme.AppBarOverlay">

        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="?attr/colorPrimary"
            app:popupTheme="@style/AppTheme.PopupOverlay" />

    </android.support.design.widget.AppBarLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">

        <RelativeLayout
            android:id="@+id/loadingPanel"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:visibility="gone"
            android:gravity="center">

            <ProgressBar
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:indeterminate="true" />
        </RelativeLayout>

        <RelativeLayout
            android:id="@+id/retry"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:visibility="gone"
            android:gravity="center">

            <TextView
                android:id="@+id/retryText"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="@string/try_again_text"
                android:layout_centerVertical="true"
                android:layout_centerHorizontal="true" />

            <Button
                android:id="@+id/tryAgainButton"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:gravity="center|center_vertical"
                android:text="Try Again"
                android:layout_below="@+id/retryText"
                android:layout_centerHorizontal="true" />
        </RelativeLayout>

        <include layout="@layout/content_my_contacts" />

    </LinearLayout>

    <android.support.design.widget.FloatingActionButton
        android:id="@+id/fab"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom|end"
        android:layout_margin="@dimen/fab_margin"
        android:src="@android:drawable/ic_dialog_email" />

</android.support.design.widget.CoordinatorLayout>

Upvotes: 2

Richard Le Mesurier
Richard Le Mesurier

Reputation: 29762

I made some changes to your MyContactsActivity code and my test version is working perfectly.


I commented out your alertHelper, networkChecker, sessionManager, appConfig because I do not have access to that code.

I also commented out all the setting up of your recyclerView.

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_my_contacts);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        retry = (RelativeLayout) findViewById(R.id.retry);
        tryAgain = (Button) findViewById(R.id.tryAgainButton);

//        alertHelper = new AlertHelper(this);
//        networkChecker = new NetworkChecker(this);
//        sessionManager = new SessionManager(this);
//        appConfig = new AppConfig();

//        String phone = sessionManager.getLoggedInUserPhone();
//        url = appConfig.getApiUrlForSpecificContacts(phone);

        tryAgain.setOnClickListener(this);

//        recyclerView = (RecyclerView) findViewById(R.id.contactsView);
//        adapter = new ContactsAdapter(getApplicationContext());
//        recyclerView.setLayoutManager(new LinearLayoutManager(getApplicationContext()));

        String url = "unused";
        sendJsonRequest(url);
//        recyclerView.setAdapter(adapter);

//        recyclerView.addOnItemTouchListener(
//                new RecyclerItemClickListener(this, new RecyclerItemClickListener.OnItemClickListener() {
//                    @Override
//                    public void onItemClick(View view, int position) {
//                        TextView phone = (TextView) view.findViewById(R.id.contact_phone);
//                        TextView name = (TextView) view.findViewById(R.id.contact_name);
//                        Intent i = new Intent(getApplicationContext(), ContactProfileActivity.class);
//                        i.putExtra("selected_user_phone", phone.getText());
//                        i.putExtra("selected_user_name", name.getText());
//                        startActivity(i);
//                    }
//                })
//        );

        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                        .setAction("Action", null).show();
            }
        });
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    }

I changed your sendJsonRequest to just unhide the layout, and the onClick to show a Toast.

    private void sendJsonRequest(String url) {
        retry.setVisibility(View.VISIBLE);
    }


    @Override
    public void onClick(View v) {
        Toast.makeText(this, "Works!", Toast.LENGTH_SHORT).show();

//        switch (v.getId()) {
//            case R.id.tryAgainButton:
//                sendJsonRequest(url);
//                break;
//        }
    }

The button works perfectly in this trimmed down code.

I suggest trying this code, and then adding each commented line back bit by bit as that will make it easy to find the issue.

Upvotes: 0

IntelliJ Amiya
IntelliJ Amiya

Reputation: 75788

You can also define the onClick method in xml when declaring the button (or any other clickable) component. When doing so, you have to declare the method you want as the onClick method. For example, as you can see, I’ve added an android:onClick attribute with value clickFuncTion.

<Button
        android:id="@+id/tryAgainButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:onClick="clickFuncTion"
        android:text="Try Again" />

Then

public void clickFuncTion(View view){

    Toast.makeText(MyContactsActivity.this, "Button Clicked", Toast.LENGTH_SHORT).show();
   // Add your staff
 }

Upvotes: 1

Nitesh
Nitesh

Reputation: 328

you may try using and check if its working

tryAgain.setOnClickListener(new View.OnClickListener(){

   @Override
  public void onClick(View v){

  sendJsonRequest(url);

}

});

Upvotes: 0

Andrain
Andrain

Reputation: 910

In you xml file add this line to your button android:onClick="onClick", where onClick in the double quotes is the name of the method in your activity that will be called when the button is clicked.

<Button
            android:id="@+id/tryAgainButton"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_below="@id/retryText"
            android:text="Try Again"
            android:onClick="onClick"/>

There are two methods for calling the buttons, either call it with Listener or call the button directly from xml by writing a line in button's xml i.e android:onClick="the name of the method"

you are calling the button method here with the name 'onClick'

 @Override
public void onClick(View v) {
    switch (v.getId()){
        case R.id.tryAgainButton:
            sendJsonRequest(url);
            break;
    }
}

I also suggest you change the method name to any other name and define that name in the onClick statement of xml.

Upvotes: 1

Related Questions