Wie bekomme ich eine ListActivity in ein Fragment?

  • Antworten:16
Gelöschter Account
  • Forum-Beiträge: 20

04.05.2016, 19:16:03 via Website

Hallo Leute,

ich habe folgendes Tutorial gemacht: http://www.androidhive.info/2012/01/android-json-parsing-tutorial/

Leider ist das in zwei Activities, ich hätte das aber gerne in Fragments.

Kann mir vielleicht jemand ein Beispiel geben, wie ich das am Besten hinbekomme?

Die Detailseite (im Beispiel für Kontakte) soll wie es ist in einer separaten Activity sein, ich möchte nur die gesamtanzeige in einem Fragment haben...

Die Lösung mit zwei Activities geht zwar, hat aber keine Titelleiste und der Benutzer kann nicht einfach "swipen" zum wechseln, das mache ich später mit dem Tabbed-Activity-Projekt was es in Android Studio gibt.

Falls ihr Dateien braucht sagt bitte Bescheid.

Liebe Grüsse,

Tom

— geändert am 04.05.2016, 19:33:31

Antworten
Pascal P.
  • Admin
  • Forum-Beiträge: 11.286

04.05.2016, 21:02:25 via App

Hallo Tom2000!
Du erstellst dir ein StandardFragment mit einer ListView als layout.
Dann kopierst du deinen Code da rein und passt ihn an z.b.
ersetzt getListView() durch die ListView auf dem Layout.

LG Pascal //It's not a bug, it's a feature. :) ;)

Antworten
Gelöschter Account
  • Forum-Beiträge: 20

04.05.2016, 21:17:17 via Website

Pascal P.

Hallo Tom2000!
Du erstellst dir ein StandardFragment mit einer ListView als layout.
Dann kopierst du deinen Code da rein und passt ihn an z.b.
ersetzt getListView() durch die ListView auf dem Layout.

Danke für deine Antwort :-)

Ich habs mal versucht, bekomme aber beim finden der ListView einen Fehler...

Mein Projekt sieht so aus: MainActivity und DetailActivity, VFragment und die Layouts. Die ListView liegt im VFragment, das DetailLayout habe ich vom Tutorial übernommen.

package com.tw.vt;

import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.ListFragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;

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

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

/**
* A simple {@link Fragment} subclass.
*/
public class VFragment extends ListFragment {

private ProgressDialog pDialog;

// URL to get contacts JSON
private static String url = "http://api.androidhive.info/contacts/";

// JSON Node names
private static final String TAG_CONTACTS = "contacts";
private static final String TAG_ID = "id";
private static final String TAG_NAME = "name";
private static final String TAG_EMAIL = "email";
private static final String TAG_ADDRESS = "address";
private static final String TAG_GENDER = "gender";
private static final String TAG_PHONE = "phone";
private static final String TAG_PHONE_MOBILE = "mobile";
private static final String TAG_PHONE_HOME = "home";
private static final String TAG_PHONE_OFFICE = "office";

// contacts JSONArray
JSONArray contacts = null;

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


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


@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    return inflater.inflate(R.layout.fragment_v, container, false);

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

    ListView lv = getActivity().findViewById(R.id.list); //was muss hier hin? listview liegt im fragment

    // Listview on item click listener
    lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> parent, View view,
                                int position, long id) {
            // getting values from selected ListItem
            String name = ((TextView) view.findViewById(R.id.name))
                    .getText().toString();
            String cost = ((TextView) view.findViewById(R.id.email))
                    .getText().toString();
            String description = ((TextView) view.findViewById(R.id.mobile))
                    .getText().toString();

            // Starting single contact activity
            Intent in = new Intent(getActivity(),
                    DetailActivity.class);
            in.putExtra(TAG_NAME, name);
            in.putExtra(TAG_EMAIL, cost);
            in.putExtra(TAG_PHONE_MOBILE, description);
            startActivity(in);

        }
    });

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

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

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        // Showing progress dialog
        pDialog = new ProgressDialog(getActivity());
        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);

                // Getting JSON Array node
                contacts = jsonObj.getJSONArray(TAG_CONTACTS);

                // looping through All Contacts
                for (int i = 0; i < contacts.length(); i++) {
                    JSONObject c = contacts.getJSONObject(i);

                    String id = c.getString(TAG_ID);
                    String name = c.getString(TAG_NAME);
                    String email = c.getString(TAG_EMAIL);
                    String address = c.getString(TAG_ADDRESS);
                    String gender = c.getString(TAG_GENDER);

                    // Phone node is JSON Object
                    JSONObject phone = c.getJSONObject(TAG_PHONE);
                    String mobile = phone.getString(TAG_PHONE_MOBILE);
                    String home = phone.getString(TAG_PHONE_HOME);
                    String office = phone.getString(TAG_PHONE_OFFICE);

                    // tmp hashmap for single contact
                    HashMap<String, String> contact = new HashMap<String, String>();

                    // adding each child node to HashMap key => value
                    contact.put(TAG_ID, id);
                    contact.put(TAG_NAME, name);
                    contact.put(TAG_EMAIL, email);
                    contact.put(TAG_PHONE_MOBILE, mobile);

                    // adding contact to contact list
                    contactList.add(contact);
                }
            } 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(
                getActivity(), contactList,
                R.layout.list_item, new String[] { TAG_NAME, TAG_EMAIL,
                TAG_PHONE_MOBILE }, new int[] { R.id.name,
                R.id.email, R.id.mobile });

        setListAdapter(adapter);
    }

}

}

— geändert am 04.05.2016, 21:25:09

Antworten
Pascal P.
  • Admin
  • Forum-Beiträge: 11.286

04.05.2016, 21:23:35 via App

Schau dir mal Fragments nochmal an.
Da inflatest du ein Layout und auf diesem musst du dann suchen.
Zudem darfst du in der 1. Zeile der onCreate kein return machen sonst geht nix

LG Pascal //It's not a bug, it's a feature. :) ;)

Antworten
Gelöschter Account
  • Forum-Beiträge: 20

05.05.2016, 10:42:53 via Website

Pascal P.

Schau dir mal Fragments nochmal an.
Da inflatest du ein Layout und auf diesem musst du dann suchen.
Zudem darfst du in der 1. Zeile der onCreate kein return machen sonst geht nix

Ich habe das return jetzt ans Ende der onCreate verschoben, aber das ListView will er immernoch nicht finden...

ListView lv = getFragmentManager(R.id.list); 

Antworten
Pascal P.
  • Admin
  • Forum-Beiträge: 11.286

05.05.2016, 10:47:26 via App

Muss so heißen:
Am anfang:

View v= inflater.inflate(R.layout.fragment_v, container, false);

ListView lv =(ListView)v.findViewById(R.id.list);

und am ende:

return v;

LG Pascal //It's not a bug, it's a feature. :) ;)

Gelöschter Account

Antworten
Gelöschter Account
  • Forum-Beiträge: 20

05.05.2016, 11:03:59 via Website

Pascal P.

Muss so heißen:
Am anfang:

View v= inflater.inflate(R.layout.fragment_v, container, false);

ListView lv =(ListView)v.findViewById(R.id.list);

und am ende:

return v;

Okay, das habe ich gemacht, allerdings schmiert es dann beim Starten ab...

Logact: java.lang.RuntimeException: Your content must have a ListView whose id attribute is 'android.R.id.list'
Die ListView liegt im fragment_v:



android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical">

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

`

— geändert am 05.05.2016, 11:10:44

Antworten
Pascal P.
  • Admin
  • Forum-Beiträge: 11.286

05.05.2016, 11:10:05 via App

Achso du Verwendest ein ListFragment.
Dann ist es eh anders. Auch die ID der list View musst du ändern wie es der Fehler sagt

— geändert am 05.05.2016, 11:10:18

LG Pascal //It's not a bug, it's a feature. :) ;)

Antworten
Gelöschter Account
  • Forum-Beiträge: 20

05.05.2016, 11:21:36 via Website

So, es läuft jetzt endlich :-)

Alle Elemente werde mir angezeigt, aber beim Tippen auf ein Element passiert nix :-(

Das ist im FragmentV:

lv.setOnItemClickListener(new AdapterView.OnItemClickListener()
{
@Override
public void onItemClick(AdapterView parent, View view,
int position, long id) {
// getting values from selected ListItem
String name = ((TextView) view.findViewById(R.id.name))
.getText().toString();
String cost = ((TextView) view.findViewById(R.id.email))
.getText().toString();
String description = ((TextView) view.findViewById(R.id.mobile))
.getText().toString();

            // Starting single contact activity
            Intent in = new Intent(getActivity(), DetailActivity.class);
            in.putExtra(TAG_NAME, name);
            in.putExtra(TAG_EMAIL, cost);
            in.putExtra(TAG_PHONE_MOBILE, description);
            startActivity(in);

        }
    });

`

Die DetailActivity sieht so aus: public class DetailActivity extends Activity {

// JSON node keys
private static final String TAG_NAME = "name";
private static final String TAG_EMAIL = "email";
private static final String TAG_PHONE_MOBILE = "mobile";
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);


    // getting intent data
    Intent in = getIntent();

    // Get JSON values from previous intent
    String name = in.getStringExtra(TAG_NAME);
    String email = in.getStringExtra(TAG_EMAIL);
    String mobile = in.getStringExtra(TAG_PHONE_MOBILE);

    // Displaying all values on the screen
    TextView lblName = (TextView) findViewById(R.id.name_label);
    TextView lblEmail = (TextView) findViewById(R.id.email_label);
    TextView lblMobile = (TextView) findViewById(R.id.mobile_label);

    lblName.setText(name);
    lblEmail.setText(email);
    lblMobile.setText(mobile);
    setContentView(R.layout.activity_detail);
}

}
`

Woran könnte das denn liegen, dass er nichtmal nen Fehler ausgibt und einfach garnix macht?

Antworten
Pascal P.
  • Admin
  • Forum-Beiträge: 11.286

05.05.2016, 11:35:02 via App

Aird der listeber aufgerufen?
Mach da mal ein Log Eintrag rein

LG Pascal //It's not a bug, it's a feature. :) ;)

Antworten
Gelöschter Account
  • Forum-Beiträge: 20

05.05.2016, 11:51:14 via Website

Pascal P.

Aird der listeber aufgerufen?
Mach da mal ein Log Eintrag rein

Sieht nicht so aus, ich finde den im Logcat nicht...
Log.d("Aufruf", "onItemClick");

— geändert am 05.05.2016, 11:51:52

Antworten
Pascal P.
  • Admin
  • Forum-Beiträge: 11.286

05.05.2016, 12:09:21 via App

Also geht der Listener nicht.
Wie sieht denn der code drumrum aus bzw. an welcher stelle setzt du den Listener?

LG Pascal //It's not a bug, it's a feature. :) ;)

Antworten
Gelöschter Account
  • Forum-Beiträge: 20

05.05.2016, 12:18:44 via Website

Der Listener wird in der VFragment Klasse gesetzt, in der onCreateView:

    lv.setOnItemClickListener( new AdapterView.OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> parent, View view,
                                int position, long id) {

            Log.d("Aufruf", "onItemClick");
            // getting values from selected ListItem
            String name = ((TextView) view.findViewById(R.id.name))
                    .getText().toString();
            String cost = ((TextView) view.findViewById(R.id.email))
                    .getText().toString();
            String description = ((TextView) view.findViewById(R.id.mobile))
                    .getText().toString();

            // Starting single contact activity
            Intent in = new Intent(getActivity(), DetailActivity.class);
            in.putExtra(TAG_NAME, name);
            in.putExtra(TAG_EMAIL, cost);
            in.putExtra(TAG_PHONE_MOBILE, description);
            startActivity(in);

        }
    });

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


    return v;
}

— geändert am 05.05.2016, 12:19:30

Antworten
Pascal P.
  • Admin
  • Forum-Beiträge: 11.286

05.05.2016, 12:36:30 via App

Und bekommst du irgend ein Fehler?
Zeig mal den gesamten Code

LG Pascal //It's not a bug, it's a feature. :) ;)

Antworten
Gelöschter Account
  • Forum-Beiträge: 20

05.05.2016, 12:40:04 via Website

Pascal P.

Und bekommst du irgend ein Fehler?
Im Logcat steht nix...
Zeig mal den gesamten Code

Kann ich nicht posten da kommt dass sich Teile identisch sind mit schon gepostetem :-(

Antworten
Pascal P.
  • Admin
  • Forum-Beiträge: 11.286

05.05.2016, 12:46:25 via App

Dann extern zu Pastebin oder als Datei verlinken

LG Pascal //It's not a bug, it's a feature. :) ;)

Antworten
Gelöschter Account
  • Forum-Beiträge: 20

05.05.2016, 12:51:59 via Website

Okay, hier ist der Link: http://pastebin.com/zj5DLpwX

Soll ich sonst noch Code teilen?

Danke übrigens schon jetzt für deine Mühen :-)

Antworten