3

just wanna ask where to put the android.support.v4.widget.SwipeRefreshLayout on my codes? I'm confused if it should be on my activity_main.xml or in my list_item.xml file..

Here is my activity_main.xml:

    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:orientation="vertical" >
        <ListView
            android:id="@+android:id/list"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"/>
    </LinearLayout>

And This is my List_item.xml:

    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout  xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        android:padding="10dp"
        android:paddingLeft="10dp"
        android:paddingRight="10dp">

        <TextView
            android:id="@+id/datetime"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:paddingBottom="2dip"
            android:paddingTop="6dip"
            android:textColor="#43bd00"
            android:textSize="16sp"
            android:textStyle="bold" 
            android:layout_weight="1" />

        <TextView
            android:id="@+id/qname"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:paddingBottom="2dip"
            android:textColor="#acacac" 
            android:layout_weight="1" />

        <TextView
            android:id="@+id/qagent"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:paddingBottom="2dip"
            android:textColor="#acacac" 
            android:layout_weight="1" />

        <TextView
            android:id="@+id/qevent"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:paddingBottom="2dip"
            android:textColor="#acacac" 
            android:layout_weight="1" />

        <TextView
            android:id="@+id/info1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:paddingBottom="2dip"
            android:textColor="#acacac" 
            android:layout_weight="1" />

        <TextView
            android:id="@+id/info2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:paddingBottom="2dip"
            android:textColor="#acacac"
            android:layout_weight="1"  />

        <TextView
            android:id="@+id/info3"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:paddingBottom="2dip"
            android:textColor="#acacac" 
            android:layout_weight="1" />  
    </LinearLayout>

I Found some sample codes on the internet where they put it on the main xml but some samples also put it on the list xml..

This is my Main activity :

import java.util.ArrayList;
import java.util.HashMap;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Fragment;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;


public class MainActivity extends ListActivity {

    private ProgressDialog pDialog;
    private static String IPaddress = "http://192.168.1.110/";

    // URL to get contacts JSON
    private static String url = IPaddress + "Projects/GetUsers.php";


    private static final String TAG_QUEUE = "queue"; 
    private static final String TAG_DATETIME = "datetime";
    private static final String TAG_NAME = "qname"; 
    private static final String TAG_AGENT = "qagent"; 
    private static final String TAG_EVENT = "qevent";
    private static final String TAG_INFO1 = "info1";
    private static final String TAG_INFO2 = "info2";
    private static final String TAG_INFO3 = "info3";


    // contacts JSONArray
    JSONArray queue = null;

    // Hashmap for ListView
    ArrayList<HashMap<String, String>>queueList;



    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        queueList = new ArrayList<HashMap<String, String>>();

      //  ListView lv = getListView();





        // Calling async task to get json
        new GetEventCounter().execute();
    }

    /**
     * Async task class to get json by making HTTP call
     * */
    private class GetEventCounter extends AsyncTask<Void, Void, Void> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            // Showing progress dialog
            pDialog = new ProgressDialog(MainActivity2.this);   
            pDialog.setMessage("Please wait...");
            pDialog.setCancelable(false);
            pDialog.show();

        }




        @Override
        protected Void doInBackground(Void... arg0) {
            // Creating service handler class instance
            ServiceHandler sh = new ServiceHandler();

            // Making a request to url and getting response
            String jsonStr = sh.makeServiceCall(url, ServiceHandler.GET);

            Log.d("Response: ", "> " + jsonStr);

            if (jsonStr != null) {
                try {
                    JSONObject jsonObj = new JSONObject(jsonStr);


                    queue = jsonObj.getJSONArray(TAG_QUEUE);


                    for (int i = 0; i < queue.length(); i++) {
                        JSONObject c = queue.getJSONObject(i);           

                        String datetime = String.format("%s : %s", TAG_DATETIME, c.getString(TAG_DATETIME));
                        String qname = String.format("%s : %s", TAG_NAME, c.getString(TAG_NAME));
                        String qagent = String.format("%s : %s", TAG_AGENT, c.getString(TAG_AGENT));
                        String qevent = String.format("%s : %s", TAG_EVENT, c.getString(TAG_EVENT));
                        String info1 = String.format("%s : %s", TAG_INFO1, c.getString(TAG_INFO1));
                        String info2 = String.format("%s : %s", TAG_INFO2, c.getString(TAG_INFO2));
                        String info3 = String.format("%s : %s", TAG_INFO3, c.getString(TAG_INFO3));





                        HashMap<String, String> event = new HashMap<String, String>();


                        event.put(TAG_DATETIME, datetime);
                        event.put(TAG_NAME, qname);
                        event.put(TAG_AGENT, qagent);
                        event.put(TAG_EVENT, qevent);
                        event.put(TAG_INFO1, info1);
                        event.put(TAG_INFO2, info2);
                        event.put(TAG_INFO3, info3);



                        queueList.add(event);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            } else {
                Log.e("ServiceHandler", "Couldn't get any data from the url");
            }

            return null;
        }

        @Override
        protected void onPostExecute(Void result) {
            super.onPostExecute(result);
            // Dismiss the progress dialog
            if (pDialog.isShowing())
                pDialog.dismiss();
            /**
             * Updating parsed JSON data into ListView
             * */
            ListAdapter adapter = new SimpleAdapter(
                    MainActivity2.this, queueList,
                    R.layout.list_item, new String[] { TAG_DATETIME, TAG_NAME, TAG_AGENT, TAG_EVENT, TAG_INFO1, TAG_INFO2, TAG_INFO3}, 
                    new int[] { R.id.datetime, R.id.qname, R.id.qagent, R.id.qevent, R.id.info1, R.id.info2, R.id.info3 });

            setListAdapter(adapter);
        }



    }




    protected Fragment getSampleFragment() {
        // TODO Auto-generated method stub
        return null;
    }

}

This will be the output that i want to have an SwipeRefresh effect.. Those output came from MySQL Database :

enter image description here

This samples caused my confusion

<android.support.v4.widget.SwipeRefreshLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/swype"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <ListView
        android:id="@+id/list"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

</android.support.v4.widget.SwipeRefreshLayout>

And :

<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.SwipeRefreshLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/swype"
        android:layout_width="match_parent"
        android:layout_height="match_parent">
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="horizontal"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <TextView
        android:id="@+id/serial"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:padding="25dp"
        android:layout_margin="5dp"
        android:layout_alignParentLeft="true"
        android:textSize="20dp"
        android:textStyle="bold" />

    <TextView
        android:id="@+id/title"
        android:layout_toRightOf="@id/serial"
        android:layout_centerVertical="true"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textStyle="bold"
        android:paddingLeft="20dp"
        android:textSize="18dp" />

</RelativeLayout>
</android.support.v4.widget.SwipeRefreshLayout>

Thanks!

Brewology
  • 108
  • 2
  • 15

2 Answers2

2

To add the swipe to refresh widget to an existing app, add SwipeRefreshLayout as the parent of a single ListView or GridView. Remember that SwipeRefreshLayout only supports a single ListView or GridView child. - Add the SwipeRefreshLayout Widget

So, your activity_main.xml should be like this:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >
    <android.support.v4.widget.SwipeRefreshLayout
        android:id="@+id/swipeLayout"
        android:layout_width="match_parent"
        android:layout_height="match_parent">
        <ListView
            android:id="@+android:id/list"
            android:layout_width="match_parent"
            android:layout_height="match_parent"/>
    </android.support.v4.widget.SwipeRefreshLayout
</LinearLayout>

Implementation:

public class MainActivity extends AppCompatActivity implements SwipeRefreshLayout.OnRefreshListener{

private SwipeRefreshLayout swipeRefreshLayout

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        swipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.swipeLayout);
        swipeRefreshLayout.setOnRefreshListener(this);

        //to change the color of the refresh indictor
        swipeRefreshLayout.setColorScheme(getResources().getColor(R.color.yourcolor), 
                getResources().getColor(R.color.yourcolor), 
                getResources().getColor(R.color.yourcolor), 
                getResources().getColor(R.color.yourcolor));
    }

    @Override
    public void onRefresh() {
    //do something here
    //setRefreshing(false) will hide the indicator
    swipeRefreshLayout.setRefreshing(false);
    }
}
Amad Yus
  • 2,856
  • 1
  • 24
  • 32
  • Thanks! Do you know how to add implementation base on my Activity.java codes? – Brewology Sep 14 '16 at 02:35
  • Sir, I got this error when i tried your codes 09-14 10:36:49.769: E/AndroidRuntime(16183): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.MainActivity2}: android.view.InflateException: Binary XML file line #6: Error inflating class android.support.v4.widget.SwipeRefreshLayout – Brewology Sep 14 '16 at 02:38
  • @Brewology; are you using Android studio? If you do, check your gradle dependency, ensure that you are already include 'com.android.support:support-v4:x.x.x' as SwiprerefreshLayout is part of android support library. – Amad Yus Sep 14 '16 at 03:18
  • No sir I'm using Eclipse. – Brewology Sep 14 '16 at 03:29
  • Emm, that kinda old. I encourage you to upgrade to android studio as Google has no longer support eclipse. But for your case, you need to include android-support-v4.jar in your project. You can get the information from here link - http://stackoverflow.com/questions/8543225/how-do-i-attach-the-android-support-library-source-in-eclipse – Amad Yus Sep 14 '16 at 03:36
0

It should wrap around the listview, something like this:

<android.support.v4.widget.SwipeRefreshLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/swiperefresh"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingTop="8dp">

    <android.widget.ListView
        android:id="@android:id/list"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

    </android.widget.ListView>

</android.support.v4.widget.SwipeRefreshLayout>

If you're using Android Studio, you can look at a Swiperefresh sample:

File\New\Import Sample\ then search for "swipe..."

In your java code, you initialize the SwipeRefresh object exactly how you would do a TextView, Button or anything else, except in your onResume(), you also want to put something like this:

mSwipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
        @Override
        public void onRefresh() {
            initiateRefresh();
        }
    });

and then inside initiateRefresh(), you do something like:

AssignData2ListView();
    mSwipeRefreshLayout.setRefreshing(false);
Nerdy Bunz
  • 6,040
  • 10
  • 41
  • 100
  • Thanks Sir! Do you know how to add implementation base on my Activity.java codes? By the way i'm using eclipse. not Android Studio. – Brewology Sep 14 '16 at 02:40
  • I mean how to implement it on the MainActivity.java file? like adding codes implements SwipeRefreshLayout.OnRefreshListener to my Activity ? – Brewology Sep 14 '16 at 03:15
  • I added more info... does that answer your question? – Nerdy Bunz Sep 14 '16 at 03:19