Error loading Listview on a Listfragment

Asked

Viewed 97 times

1

Talk guys, I’m having a problem creating a Listview in a Listfragment. I did a test with a Listactivity and works perfectly, but in Listfragment will not. I need to do in Fragment because I have a side menu in the application.

Listactivity:

public class BakeryListActivity extends ListActivity implements AdapterView.OnItemClickListener {
public static final String APP_NAME = "PanApp";
public static final String URL = "https://panapp-backend.appspot.com/_ah/api";
private TextView tv = null;
private ArrayList<Map<String,String>> list = null;
private SimpleAdapter adapter = null;
private String[] from = { "name", "street" };
private int[] to = { android.R.id.text1, android.R.id.text2 };

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    tv = new TextView(this);
    tv.setText("Lista de Padarias");
    tv.setGravity(Gravity.CENTER);
    getListView().addHeaderView(tv);
    new BakeryListAsyncTask(this).execute();
    getListView().setOnItemClickListener(this);
}

@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
    Toast.makeText(this, "Item: " + position, Toast.LENGTH_SHORT).show();
}

private class BakeryListAsyncTask extends AsyncTask<Void, Void, CollectionResponseBakery> {
    Context context;
    private ProgressDialog pd;

    public BakeryListAsyncTask(Context context) {
        this.context = context;
    }

    protected void onPreExecute(){
        super.onPreExecute();
        pd = new ProgressDialog(context);
        pd.setMessage("Listando Padarias...");
        pd.show();
    }

    protected CollectionResponseBakery doInBackground(Void... unused) {
        CollectionResponseBakery quotes = null;
        try {
            BakeryApi.Builder builder = new BakeryApi.Builder(AndroidHttp.newCompatibleTransport(),
                    new AndroidJsonFactory(), null).setRootUrl(URL);
            builder.setApplicationName(APP_NAME);
            BakeryApi service =  builder.build();
            quotes = service.list().execute();
        } catch (Exception e) {
            Log.d("Erro", e.getMessage(), e);
        }
        return quotes;
    }

    protected void onPostExecute(CollectionResponseBakery quotes) {
        pd.dismiss();
        ArrayList<Map<String, String>> list = new ArrayList<Map<String, String>>();
        List<Bakery> _list = quotes.getItems();
        for (Bakery quote : _list) {
            HashMap<String, String> item = new HashMap<String, String>();
            item.put("name", quote.getFantasyName());
            item.put("street", quote.getStreet());
            list.add(item);
        }
        adapter = new SimpleAdapter(BakeryListActivity.this, list,android.R.layout.simple_list_item_2, from, to);
        setListAdapter(adapter);
    }
}
}

Listfragment that does not work:

public class BakeryFragment extends ListFragment implements OnItemClickListener {
public static final String APP_NAME = "PanApp";
public static final String URL = "https://panapp-backend.appspot.com/_ah/api";
private SimpleAdapter adapter = null;
private String[] from = { "name", "street" };
private int[] to = { android.R.id.text1, android.R.id.text2 };

public BakeryFragment() {
    // Required empty public constructor
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    View rootView = inflater.inflate(R.layout.fragment_bakery_list, container, false);

    return rootView;
}

@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);
    new BakeryListAsyncTask(getActivity().getApplicationContext()).execute();
    getListView().setOnItemClickListener(this);
}

@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
    Toast.makeText(getActivity(), "Item: " + position, Toast.LENGTH_SHORT).show();
}

private class BakeryListAsyncTask extends AsyncTask<Void, Void, CollectionResponseBakery> {
    Context context;
    private ProgressDialog pd;

    public BakeryListAsyncTask(Context context) {
        this.context = context;
    }

    protected void onPreExecute(){
        super.onPreExecute();
        pd = new ProgressDialog(context);
        pd.setMessage("Listando Padarias...");
        pd.show();
    }

    protected CollectionResponseBakery doInBackground(Void... unused) {
        CollectionResponseBakery bakeries = null;
        try {
            BakeryApi.Builder builder = new BakeryApi.Builder(AndroidHttp.newCompatibleTransport(),
                    new AndroidJsonFactory(), null).setRootUrl(URL);
            builder.setApplicationName(APP_NAME);
            BakeryApi service =  builder.build();
            bakeries = service.list().execute();
        } catch (Exception e) {
            Log.d("Erro", e.getMessage(), e);
        }
        return bakeries;
    }

    protected void onPostExecute(CollectionResponseBakery bakeries) {
        pd.dismiss();
        ArrayList<Map<String, String>> list = new ArrayList<Map<String, String>>();
        List<Bakery> _list = bakeries.getItems();
        for (Bakery bakery : _list) {
            HashMap<String, String> item = new HashMap<String, String>();
            item.put("name", bakery.getFantasyName());
            item.put("street", bakery.getStreet());
            list.add(item);
        }
        adapter = new SimpleAdapter(getActivity().getApplicationContext(), list,android.R.layout.simple_list_item_2, from, to);
        setListAdapter(adapter);
    }
}
}

XML:

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

Error:

05-15 17:53:31.989 24367-24367/com.gregmachado.panapp E/AndroidRuntime: FATAL EXCEPTION: main
                                                                    Process: com.gregmachado.panapp, PID: 24367
                                                                    android.view.WindowManager$BadTokenException: Unable to add window -- token null is not for an application
                                                                        at android.view.ViewRootImpl.setView(ViewRootImpl.java:583)
                                                                        at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:310)
                                                                        at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:85)
                                                                        at android.app.Dialog.show(Dialog.java:319)
                                                                        at com.gregmachado.panapp.BakeryFragment$BakeryListAsyncTask.onPreExecute(BakeryFragment.java:75)
                                                                        at android.os.AsyncTask.executeOnExecutor(AsyncTask.java:604)
                                                                        at android.os.AsyncTask.execute(AsyncTask.java:551)
                                                                        at com.gregmachado.panapp.BakeryFragment.onActivityCreated(BakeryFragment.java:54)
                                                                        at android.support.v4.app.Fragment.performActivityCreated(Fragment.java:1997)
                                                                        at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1105)
                                                                        at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1268)
                                                                        at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:754)
                                                                        at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1653)
                                                                        at android.support.v4.app.FragmentManagerImpl$1.run(FragmentManager.java:518)
                                                                        at android.os.Handler.handleCallback(Handler.java:746)
                                                                        at android.os.Handler.dispatchMessage(Handler.java:95)
                                                                        at android.os.Looper.loop(Looper.java:148)
                                                                        at android.app.ActivityThread.main(ActivityThread.java:5443)
                                                                        at java.lang.reflect.Method.invoke(Native Method)
                                                                        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:728)
                                                                        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:618)
05-15 17:53:46.075 24367-24367/com.gregmachado.panapp I/Process: Sending signal. PID: 24367 SIG: 9
05-15 17:53:46.294 24858-24858/com.gregmachado.panapp W/System: ClassLoader referenced unknown path: /data/app/com.gregmachado.panapp-2/lib/arm
05-15 17:53:46.714 24858-24858/com.gregmachado.panapp W/System: ClassLoader referenced unknown path: /data/app/com.gregmachado.panapp-2/lib/arm
05-15 17:53:47.052 24858-24858/com.gregmachado.panapp I/TextInputLayout: EditText added is not a TextInputEditText. Please switch to using that class instead.
05-15 17:53:47.056 24858-24858/com.gregmachado.panapp I/TextInputLayout: EditText added is not a TextInputEditText. Please switch to using that class instead.
05-15 17:53:47.083 24858-24858/com.gregmachado.panapp D/AndroidRuntime: Shutting down VM
05-15 17:53:47.085 24858-24858/com.gregmachado.panapp E/AndroidRuntime: FATAL EXCEPTION: main
                                                                    Process: com.gregmachado.panapp, PID: 24858
                                                                    java.lang.RuntimeException: Unable to start activity ComponentInfo{com.gregmachado.panapp/com.gregmachado.panapp.LoginEmailActivity}: java.lang.RuntimeException: Parcel android.os.Parcel@3d7a7a8: Unmarshalling unknown type code 2131558524 at offset 344
                                                                        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2426)
                                                                        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2490)
                                                                        at android.app.ActivityThread.-wrap11(ActivityThread.java)
                                                                        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1354)
                                                                        at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                        at android.os.Looper.loop(Looper.java:148)
                                                                        at android.app.ActivityThread.main(ActivityThread.java:5443)
                                                                        at java.lang.reflect.Method.invoke(Native Method)
                                                                        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:728)
                                                                        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:618)
                                                                     Caused by: java.lang.RuntimeException: Parcel android.os.Parcel@3d7a7a8: Unmarshalling unknown type code 2131558524 at offset 344
                                                                        at android.os.Parcel.readValue(Parcel.java:2319)
                                                                        at android.os.Parcel.readSparseArrayInternal(Parcel.java:2653)
                                                                        at android.os.Parcel.readSparseArray(Parcel.java:1946)
                                                                        at android.os.Parcel.readValue(Parcel.java:2300)
                                                                        at android.os.Parcel.readArrayMapInternal(Parcel.java:2592)
                                                                        at android.os.BaseBundle.unparcel(BaseBundle.java:221)
                                                                        at android.os.Bundle.getSparseParcelableArray(Bundle.java:856)
                                                                        at com.android.internal.policy.PhoneWindow.restoreHierarchyState(PhoneWindow.java:2033)
                                                                        at android.app.Activity.onRestoreInstanceState(Activity.java:1008)
                                                                        at android.app.Activity.performRestoreInstanceState(Activity.java:963)
                                                                        at android.app.Instrumentation.callActivityOnRestoreInstanceState(Instrumentation.java:1186)
                                                                        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2399)
                                                                        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2490) 
                                                                        at android.app.ActivityThread.-wrap11(ActivityThread.java) 
                                                                        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1354) 
                                                                        at android.os.Handler.dispatchMessage(Handler.java:102) 
                                                                        at android.os.Looper.loop(Looper.java:148) 
                                                                        at android.app.ActivityThread.main(ActivityThread.java:5443) 
                                                                        at java.lang.reflect.Method.invoke(Native Method) 
                                                                        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:728) 
                                                                        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:618) 

2 answers

1

Tiago, thank you so much for your help. It worked, I just had to change some details:

private class BakeryListAsyncTask extends AsyncTask<Void, Void, CollectionResponseBakery> {
    BakeryFragment context; // --->aqui era Context antes
    private ProgressDialog pd;

    public BakeryListAsyncTask(BakeryFragment context) {
        this.context = context;
    }

    protected void onPreExecute(){
        super.onPreExecute();
        pd = new ProgressDialog(context.getActivity()); // ---> aqui fiz a busca da activity
        pd.setMessage("Listando Padarias...");
        pd.show();
    }

But very quiet. Only one however, the list has the letters in white and the list also has the white background.

  • Have you tried the getListView().setBackgroundColor();?

  • Actually I want to change the color of the letter. Put black even, that is the default.

  • 1

    This link might help you: http://stackoverflow.com/questions/7361135/how-to-change-color-and-font-on-listview

0


Instead of getActivity().getApplicationContext() utilize BakeryFragment.this

@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);
    new BakeryListAsyncTask(BakeryFragment.this).execute();
    getListView().setOnItemClickListener(this);
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.