ListView aus zweitem Fragment zeigt inhalt aus erstemFragment an

  • 2 Antworten
  • Neuester Beitrag
Diskutiere ListView aus zweitem Fragment zeigt inhalt aus erstemFragment an im Android App Entwicklung im Bereich Betriebssysteme & Apps.
A

AndrejEdd

Neues Mitglied
Hallo zusammen

dieser Task wurde geschaft: AsyncTask in Fragmente

Nun kommt der nächster Schritt.

Ich habe im ersten Fragment eine ListView welche alle Kontakte anzeigt (dafür habe ich auch einen ListAdapter).

Mein zweites Fragment hat eine ListView und soll alle Sessions (wie bei Whatsapp (Verläufe)) anzeigen. Dafür habe ich auch schon die Logik geschrieben und einen zweiten ListAdapter.

Doch beim Starten der App und beim switchen auf das zweite Fragment kommt wieder die Kontaktliste, irgendwie lädt es wieder die selbe Liste wie beim ersten Fragment.

Mein vorhaben soll doch irgendwie möglich sein? Muss ich beim zweiten fragment die Liste updaten ? oder wie soll das funktionieren?
 
Jaiel

Jaiel

Experte
Code bitte
 
A

AndrejEdd

Neues Mitglied
Fragment 1:

Code:
package com.gibb.picturekicker;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;







import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.support.v4.app.Fragment;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

/**
 * A simple {@link Fragment} subclass. Use the
 * {@link ContactFragment#newInstance} factory method to create an instance of
 * this fragment.
 *
 */
public class ContactFragment extends Fragment {

    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";

    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;
    
    Button aktualisieren;
    ListView lView;
    SimpleAdapter adpt;

    /**
     * Use this factory method to create a new instance of this fragment using
     * the provided parameters.
     *
     * @param param1
     *            Parameter 1.
     * @param param2
     *            Parameter 2.
     * @return A new instance of fragment ContactFragment.
     */
    // TODO: Rename and change types and number of parameters
    public static ContactFragment newInstance(String param1, String param2) {
        ContactFragment fragment = new ContactFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

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

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }

            // Exec async load task
            (new SubConnectToDB()).execute();

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        // Inflate the layout for this fragment    
        View rootView = inflater.inflate(R.layout.fragment_contact, container, false);
        
        aktualisieren = (Button) rootView.findViewById(R.id.aktualisieren);
        
         aktualisieren.setOnClickListener(new View.OnClickListener() {
                public void onClick(View v) {
                    
                     (new SubConnectToDB()).execute();
                }
            });
         
        adpt  = new SimpleAdapter(new ArrayList<Contact>(), getActivity());
        
        lView = (ListView) rootView.findViewById(R.id.listView1);
            
        lView.setAdapter(adpt);
        
        
        OnItemClickListener itemClickListener = new OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View container, int position, long id) {
                String listener = ((TextView) container.findViewById(R.id.textView3)).getText().toString();
                (new SubCommunication(listener)).execute();
            }
        };
 
        // Setting the item click listener for the listview
        lView.setOnItemClickListener(itemClickListener);
       
        

        return rootView;
    }
    
    private class SubConnectToDB extends AsyncTask<Void, Void, List<Contact>>{
        private final ProgressDialog dialog = new ProgressDialog(getActivity());
        
        @Override
        protected void onPreExecute() {       
            super.onPreExecute();
            dialog.setMessage("Kontake werden geladen...");
            dialog.show();           
        }

        @Override
        protected List<Contact> doInBackground(Void... params) {
            Context context = getActivity().getApplicationContext();
            
            TelephonyManager tMgr = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
            String ownNumber = tMgr.getLine1Number();
            ValueParser pars = new ValueParser();
            ownNumber = pars.parseOwnNumber(ownNumber);
            ArrayList<Contact> myArr = new ArrayList<Contact>();
            

            if(ownNumber != null) {
                Connection connect = new Connection();

                String phoneNumber = "";
                    
                Cursor cursor = context.getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null, null, null);
                while (cursor.moveToNext()) 
                {
                    phoneNumber = pars.getNumber(cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER)));
                    
                    if (connect.existNumber(phoneNumber)) {
                        Contact contact = new Contact();
                        contact.setFirstName(cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME))); 
                        contact.setLastName(cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.StructuredName.FAMILY_NAME)));
                        Log.d("Contactnumber and firstname: ", phoneNumber + " : " + contact.getFirstName());
                        contact.setPhoneNumber(phoneNumber);
                        myArr.add(contact);
                    }
                }        

                connect.saveContactsInDatabase(ownNumber, myArr);    
    
                  
                Log.d("Exists number: ", "" + connect.existNumber(ownNumber));

                return connect.getContactListFromDatabase(ownNumber);
                
            } else {
                Toast toast = Toast.makeText(getActivity().getApplicationContext(), "You haven't a number !", Toast.LENGTH_SHORT);
                toast.show();
            }
                
            return null;
        }

        @Override
        protected void onPostExecute(List<Contact> result) {
            super.onPostExecute(result);
            dialog.dismiss();
            adpt.setItemList(result);
            adpt.notifyDataSetChanged();           
        }
        
    }
    
    private class SubCommunication extends AsyncTask<Void, Void, Integer>{
        private final ProgressDialog dialog = new ProgressDialog(getActivity());
        String listener;
        
        public SubCommunication(String listener) {
            this.listener = listener;
        }
        
        @Override
        protected void onPreExecute() {       
            super.onPreExecute();
            dialog.setMessage("Nachricht wird gesendet...");
            dialog.show();           
        }

        @Override
        protected Integer doInBackground(Void... params) {
            Context context = getActivity().getApplicationContext();
            
            TelephonyManager tMgr = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
            String ownNumber = tMgr.getLine1Number();
            ValueParser pars = new ValueParser();
            ownNumber = pars.parseOwnNumber(ownNumber);
            
            if(ownNumber != null) {
                Communication com = new Communication(ownNumber, listener, "test message");
                    
                Cursor cursor = context.getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null, null, null);
                while (cursor.moveToNext()) 
                {
                    Log.d("Exist Document", "" + com.existDocument(ownNumber, listener));
                    if (com.existDocument(ownNumber, listener) == false) {
                        int sessionResponseCode = 0;
                            try {
                                sessionResponseCode = com.createCollection(ownNumber).getResponseCode();
                                Log.d("New Coll", "" + sessionResponseCode);
                                
                                Log.d("Exist ListenerDoc", "" + com.existDocument(listener, ownNumber));
                                if (com.existDocument(listener, ownNumber) == false) {
                                    sessionResponseCode = com.createCollection(listener).getResponseCode();
                                    Log.d("New Coll", "" + sessionResponseCode);
                                }
                                
                                sessionResponseCode = com.createNewSessionByMe().getResponseCode();
                                Log.d("My Session", "" + sessionResponseCode);
                                sessionResponseCode = com.createNewSessionByContact().getResponseCode();
                                Log.d("Contact Session", "" + sessionResponseCode);
                            } catch (IOException e) {
                                e.printStackTrace();
                            }

                        return sessionResponseCode;
                        
                    } else {
                        
                    }
                }        

                
            } else {
                Toast toast = Toast.makeText(getActivity().getApplicationContext(), "You haven't a number !", Toast.LENGTH_SHORT);
                toast.show();
            }
                
            return null;
        }

        @Override
        protected void onPostExecute(Integer result) {
            super.onPostExecute(result);
            dialog.dismiss();       
        }
    
}
}
ListAdapter Dafür:

Code:
package com.gibb.picturekicker;

import java.util.List;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;

public class SimpleAdapter extends ArrayAdapter<Contact> {
    
    private List<Contact> itemList;
    private Context context;
         
    public SimpleAdapter(List<Contact> itemList, Context ctx) {
        super(ctx, android.R.layout.simple_list_item_1, itemList);
        this.itemList = itemList;
        this.context = ctx;       
    }
     
    public int getCount() {
        if (itemList != null)
            return itemList.size();
        return 0;
    }
 
    public Contact getItem(int position) {
        if (itemList != null)
            return itemList.get(position);
        return null;
    }
 
    public long getItemId(int position) {
        if (itemList != null)
            return itemList.get(position).hashCode();
        return 0;
    }
 
    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
         
        View v = convertView;
        if (v == null) {
            LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            v = inflater.inflate(R.layout.contact_list, null);
        }
         
        Contact c = itemList.get(position);
        TextView text = (TextView) v.findViewById(R.id.textView1);
        TextView text1 = (TextView) v.findViewById(R.id.textView2);
        TextView text2 = (TextView) v.findViewById(R.id.textView3);
        
        text.setText(c.getFirstName());
        text1.setText(c.getLastName());
        text2.setText(c.getPhoneNumber());
        
        if (text.getText().equals("null")) {
            text.setText("");
        } 
        if (text1.getText().equals("null")) {
            text1.setText("");
        } 
        if (text2.getText().equals("null")) {
            text2.setText("");
        }
 
        return v;
         
    }
 
    public List<Contact> getItemList() {
        return itemList;
    }
 
    public void setItemList(List<Contact> itemList) {
        this.itemList = itemList;
    }
 
     
}
Fragment 2:

Code:
package com.gibb.picturekicker;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import android.app.ProgressDialog;
import android.content.Context;
import android.database.Cursor;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.support.v4.app.Fragment;
import android.telephony.TelephonyManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;

/**
 * @author daniel.trifunovic
 *
 */
public class SessionFragment extends Fragment{
    
    // TODO: Rename parameter arguments, choose names that match
        // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
        private static final String ARG_PARAM1 = "param1";
        private static final String ARG_PARAM2 = "param2";

        // TODO: Rename and change types of parameters
        private String mParam1;
        private String mParam2;
        
        ListView sessionList;
        SessionListAdapter sessionAdpt;

        /**
         * Use this factory method to create a new instance of this fragment using
         * the provided parameters.
         *
         * @param param1
         *            Parameter 1.
         * @param param2
         *            Parameter 2.
         * @return A new instance of fragment ContactFragment.
         */
        // TODO: Rename and change types and number of parameters
        public static ContactFragment newInstance(String param1, String param2) {
            ContactFragment fragment = new ContactFragment();
            Bundle args = new Bundle();
            args.putString(ARG_PARAM1, param1);
            args.putString(ARG_PARAM2, param2);
            fragment.setArguments(args);
            return fragment;
        }

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

        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            if (getArguments() != null) {
                mParam1 = getArguments().getString(ARG_PARAM1);
                mParam2 = getArguments().getString(ARG_PARAM2);
            }

        }

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                Bundle savedInstanceState) {
            // Inflate the layout for this fragment    
            View rootView = inflater.inflate(R.layout.fragment_session, container, false);
            
            sessionAdpt  = new SessionListAdapter(new ArrayList<Contact>(), getActivity());
            
            sessionList = (ListView) rootView.findViewById(R.id.sessionList);
                
            sessionList.setAdapter(sessionAdpt);

            return rootView;
        }
        
        
        private class SubCommunication extends AsyncTask<Void, Void, List<Session>>{
            private final ProgressDialog dialog = new ProgressDialog(getActivity());
            String listener;
            
            public SubCommunication(String listener) {
                this.listener = listener;
                
            }
            
            
            @Override
            protected void onPreExecute() {       
                super.onPreExecute();
                dialog.setMessage("Nachricht wird gesendet...");
                dialog.show();           
            }

            @Override
            protected List<Session> doInBackground(Void... params) {
                Context context = getActivity().getApplicationContext();
                
                TelephonyManager tMgr = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
                String ownNumber = tMgr.getLine1Number();
                ValueParser pars = new ValueParser();
                ownNumber = pars.parseOwnNumber(ownNumber);
                
                if(ownNumber != null) {
                    Communication com = new Communication(ownNumber, listener, "");
                        
                    Cursor cursor = context.getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null, null, null);
                    while (cursor.moveToNext()) 
                    {
                        if (com.existDocument(ownNumber, listener)) {

                            return com.getSessionListFromDatabase(ownNumber, ownNumber);
                            
                        } else {
                            
                        }
                    }        

                    
                } else {
                    Toast toast = Toast.makeText(getActivity().getApplicationContext(), "You haven't a number !", Toast.LENGTH_SHORT);
                    toast.show();
                }
                    
                return null;
            }

            @Override
            protected void onPostExecute(List<Session> result) {
                super.onPostExecute(result);
                dialog.dismiss();       
            }
        
    }
}
ListAdapter dafür:

Code:
package com.gibb.picturekicker;

import java.util.List;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;

public class SessionListAdapter extends ArrayAdapter<Contact> {
    
    private List<Contact> itemList;
    private Context context;
         
    public SessionListAdapter(List<Contact> itemList, Context ctx) {
        super(ctx, android.R.layout.simple_list_item_1, itemList);
        this.itemList = itemList;
        this.context = ctx;       
    }
     
    public int getCount() {
        if (itemList != null)
            return itemList.size();
        return 0;
    }
 
    public Contact getItem(int position) {
        if (itemList != null)
            return itemList.get(position);
        return null;
    }
 
    public long getItemId(int position) {
        if (itemList != null)
            return itemList.get(position).hashCode();
        return 0;
    }
 
    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
         
        View v = convertView;
        if (v == null) {
            LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            v = inflater.inflate(R.layout.session_list, null);
        }
         
        Contact c = itemList.get(position);
        TextView firstname = (TextView) v.findViewById(R.id.firstname);
        TextView lastname = (TextView) v.findViewById(R.id.lastname);
        
        firstname.setText(c.getFirstName());
        lastname.setText(c.getLastName());
        
        if (firstname.getText().equals("null")) {
            firstname.setText("Helli");
        } 
        if (lastname.getText().equals("null")) {
            lastname.setText("Helloo");
        } 
 
        return v;
         
    }
 
    public List<Contact> getItemList() {
        return itemList;
    }
 
    public void setItemList(List<Contact> itemList) {
        this.itemList = itemList;
    }
 
     
}
 
Ähnliche Themen - ListView aus zweitem Fragment zeigt inhalt aus erstemFragment an Antworten Datum
2
4
3