-1

I'm new to android programming and I'm practicing in making a Facebook app. I got this ListView and which i will be using to display some information i got from facebook. But the problem is when the Listview starts to load the datas its stucked in the loading part and its taking forever but theres no error in the codes. here are the codes:

package com.example.forwardjunction;

import java.util.ArrayList;
import java.util.HashMap;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentTransaction;
import android.app.ListFragment;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.res.Configuration;
import android.os.Bundle;
import android.util.Log;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.ScrollView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;
import com.facebook.HttpMethod;
import com.facebook.Request;
import com.facebook.Response;
import com.facebook.Session;
import com.facebook.SessionState;
import com.facebook.UiLifecycleHelper;
import com.facebook.model.GraphObject;

public class FragmentLayout extends Activity {

    ProgressDialog mDialog;
    static String postMessage;
    static String from;
    static String timeCreated;
    static String postId;
    static ArrayList<HashMap<String, String>> feedList;
    private static final String TAG_MESSAGE = "message";
    private static final String TAG_ID = "id";
    private static final String TAG_NAME = "name";
    static ListView list;
    TextView author, feedMessage;
    static UiLifecycleHelper uiHelper;


    public FragmentLayout() {
        // TODO Auto-generated constructor stub
    }

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

        author = (TextView) findViewById(R.id.author);
        feedMessage = (TextView) findViewById(R.id.message);
        feedList = new ArrayList<HashMap<String, String>>();
        uiHelper = new UiLifecycleHelper(this, statusCallback);
//      list = (ListView) findViewById(R.id.list);

    }

    public static class TitlesFragment extends ListFragment {
        boolean mDualPane;
        int mCurCheckPosition = 0;


//      public View onCreateView(LayoutInflater inflater, ViewGroup container,
//              Bundle savedInstanceState) {
//
//          return null;
//      }


        @Override
        public void onActivityCreated(Bundle savedInstanceState) {
            super.onActivityCreated(savedInstanceState);

            ListView list = getListView();
            feedList = new ArrayList<HashMap<String, String>>();

            Request loadPageFeed = new Request(Session.getActiveSession(),
                    "163340583656/posts", null, HttpMethod.GET,
                    new Request.Callback() {

                        @Override
                        public void onCompleted(Response response) {
                            // TODO Auto-generated method stub
                            Log.i("FEED RESPONSE", response.toString());

                            try {
                                GraphObject graphObj = response.getGraphObject();
                                JSONObject json = graphObj.getInnerJSONObject();
                                JSONArray jArray = json.getJSONArray("data");
                                for (int i = 0; i < jArray.length(); i++) {
                                    JSONObject currObj = jArray.getJSONObject(i);
                                    postId = currObj.getString("id");
                                    if (currObj.has("message")) {
                                        postMessage = currObj.getString("message");
                                    } else if (currObj.has("story")) {
                                        postMessage = currObj.getString("story");
                                    } else {
                                        postMessage = "Forward Publication has posted something.";
                                    }
                                    JSONObject fromObj = currObj
                                            .getJSONObject("from");
                                    from = fromObj.getString("name");
                                    timeCreated = currObj
                                            .getString("created_time");

                                    HashMap<String, String> feed = new HashMap<String, String>();
                                    feed.put(TAG_ID, postId);
                                    feed.put(TAG_MESSAGE, postMessage);
                                    feed.put(TAG_NAME, from);

                                    Log.i("passed", feed.toString());

                                    feedList.add(feed);
                                }
                            } catch (JSONException e) {
                                // TODO Auto-generated catch block
                                e.printStackTrace();
                            }
                        }
                    });
            loadPageFeed.executeAsync();

            BaseAdapter adapter = new SimpleAdapter(getActivity(), feedList,
                    R.layout.feed_item, new String[] { TAG_MESSAGE, TAG_NAME,
                TAG_ID }, new int[] { R.id.message, R.id.author,
                R.id.id_tv });

            list.setAdapter(adapter);
            adapter.notifyDataSetChanged();

            View detailsFrame = getActivity().  findViewById(R.id.details);

            mDualPane = detailsFrame != null
                    && detailsFrame.getVisibility() == View.VISIBLE;

            if (savedInstanceState != null) {
                // Restore last state for checked position.
                mCurCheckPosition = savedInstanceState.getInt("curChoice", 0);
            }

            if (mDualPane) {
                getListView().setChoiceMode(ListView.CHOICE_MODE_SINGLE);
                showDetails(mCurCheckPosition);
            } else {
                getListView().setChoiceMode(ListView.CHOICE_MODE_SINGLE);
                getListView().setItemChecked(mCurCheckPosition, true);
            }
        }

        @Override
        public void onSaveInstanceState(Bundle outState) {
            super.onSaveInstanceState(outState);

            outState.putInt("curChoice", mCurCheckPosition);
        }

        @Override
        public void onListItemClick(ListView l, View v, int position, long id) {

            showDetails(position);
        }

        void showDetails(int index) {
            mCurCheckPosition = index;

            if (mDualPane) {

                getListView().setItemChecked(index, true);

                DetailsFragment details = (DetailsFragment) getFragmentManager()
                        .findFragmentById(R.id.details);
                if (details == null || details.getShownIndex() != index) {
                    details = DetailsFragment.newInstance(index);
                    FragmentTransaction ft = getFragmentManager()
                            .beginTransaction();
                    ft.replace(R.id.details, details);
                    ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
                    ft.commit();
                }

            } else {

                Intent intent = new Intent();
                intent.setClass(getActivity(), DetailsActivity.class);
                intent.putExtra("index", index);
                startActivity(intent);
            }
        }
    }


    public static class DetailsActivity extends Activity {

        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);

            if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
                finish();
                return;
            }

            if (savedInstanceState == null) {
                DetailsFragment details = new DetailsFragment();

                details.setArguments(getIntent().getExtras());

                getFragmentManager().beginTransaction()
                        .add(android.R.id.content, details).commit();
            }
        }
    }



    public static class DetailsFragment extends Fragment {

        public static DetailsFragment newInstance(int index) {
            DetailsFragment f = new DetailsFragment();
            Bundle args = new Bundle();
            args.putInt("index", index);
            f.setArguments(args);

            return f;
        }

        public int getShownIndex() {
            return getArguments().getInt("index", 0);
        }

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                Bundle savedInstanceState) {

            ScrollView scroller = new ScrollView(getActivity());
            TextView text = new TextView(getActivity());
            int padding = (int) TypedValue.applyDimension(
                    TypedValue.COMPLEX_UNIT_DIP, 4, getActivity()
                            .getResources().getDisplayMetrics());
            text.setPadding(padding, padding, padding, padding);
            scroller.addView(text);
//          text.setText(Shakespeare.DIALOGUE[getShownIndex()]);
            return scroller;
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        uiHelper.onResume();
    }

    @Override
    public void onPause() {
        super.onPause();
        uiHelper.onPause();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        uiHelper.onDestroy();
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        uiHelper.onActivityResult(requestCode, resultCode, data);
    }

    @Override
    public void onSaveInstanceState(Bundle savedState) {
        super.onSaveInstanceState(savedState);
        uiHelper.onSaveInstanceState(savedState);
    }

    private Session.StatusCallback statusCallback = new Session.StatusCallback() {
        @Override
        public void call(Session session, SessionState state,
                Exception exception) {
            if (state.isOpened()) {
                Log.d("FacebookSampleActivity", "Facebook session opened");
            } else if (state.isClosed()) {
                Log.d("FacebookSampleActivity", "Facebook session closed");
            }
        }
    };

}

And heres the xml:

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <fragment
        android:id="@+id/titles"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        class="com.example.forwardjunction.FragmentLayout$TitlesFragment" />

</FrameLayout>

I hope you can help me. cheers

*edit> I think the problem is that the listview is empty, i dont really know where the problem is

d0tzz
  • 25
  • 7

1 Answers1

0

because the UI thread is Blocked

Rather than using your thread class use Asynctask

class xyz extends Asynctask {

} then add to overrididen methods do in background on post execute

I m posting the sample code of mine

package com.example.urlconnectionclass;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Scanner;

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

import android.app.Activity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.Menu;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity {


    ProgressDialog pDialog;
    String urlString="http://api.androidhive.info/contacts/";
    TextView tc;
    String s;
     JSONArray jr;
     JSONObject jb,jb2;
     ArrayList<HashMap<String, String>> contact;
     String tagid="id";
     String tagname="name",tagemail="email",taggender="gender",tagadd="address";
     ListView lv;

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


        lv=(ListView)findViewById(R.id.listView1);
        contact = new ArrayList<HashMap<String,String>>();


        new urlconn().execute();

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }






    public class urlconn extends AsyncTask<Void, Void, Void>
    {
               @Override
            protected void onPreExecute() {
                // TODO Auto-generated method stub
                super.onPreExecute();



            }
        @Override
        protected Void doInBackground(Void... params) {
            // TODO Auto-generated method stub





            try {
                URL url= new URL(urlString);
                HttpURLConnection conn =(HttpURLConnection)url.openConnection();

                conn.connect();

                InputStream is= conn.getInputStream();


                s=convertStreamToString(is);


                jb = new JSONObject(s);

                jr= jb.getJSONArray("contacts");

                for(int i=0;i<=jr.length();i++)
                {
                    jb2=jr.getJSONObject(i);


                    String id=jb2.getString(tagid);
                    String name=jb2.getString(tagname);
                    String email=jb2.getString(tagemail);
                    String address=jb2.getString(tagadd);
                    String gender=jb2.getString("gender");

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

                    map.put(tagid, id);
                    map.put(tagname, name);
                    map.put(tagemail, email);
                    map.put("gender", gender);
                    map.put(tagadd, address);

                    contact.add(map);

                }








            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }









            return null;




        }


        @Override
        protected void onPostExecute(Void result) {
        // TODO Auto-generated method stub
        super.onPostExecute(result);

        String [] sr={tagid,tagname,tagemail,"gender",tagadd};
        int [] in= {R.id.textView1,R.id.textView2,R.id.textView3,R.id.textView4,R.id.textView5};

        SimpleAdapter sa= new SimpleAdapter(MainActivity.this, contact, R.layout.mapxml,sr, in);
        lv.setAdapter(sa);





        }

        public String convertStreamToString(java.io.InputStream is) {
            java.util.Scanner s = new java.util.Scanner(is).useDelimiter("\\A");
            return s.hasNext() ? s.next() : "";
        }

    }







}
Aakash Gandhi
  • 253
  • 1
  • 3
  • 11