旋转时,返回开头

时间:2014-12-20 10:28:09

标签: android

我是新的Android,现在我正在开发一个大项目,问题是,当我将我的屏幕从纵向旋转到横向时,我丢失了数据并返回我的位置,例如,如果我在客户端nr 15,当旋转我直接转到客户nr 1。 这是我的代码:

import android.app.Fragment;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;

import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Filter;
import android.widget.Filterable;
import android.widget.TextView;

import com.google.android.gms.maps.CameraUpdate;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapView;
import com.google.android.gms.maps.MapsInitializer;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;

import org.xmlpull.v1.XmlPullParserException;

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

import flexboard.android.logic.al.flexboard.Preferencat;
import flexboard.android.logic.al.flexboard.R;
import flexboard.android.logic.al.flexboard.webservice.Api;
import flexboard.android.logic.al.flexboard.webservice.DataRetriever;
import flexboard.android.logic.al.flexboard.webservice.parsers.ClientPerformanceList;


public class KartelaFragment extends Fragment {

    private GoogleMap maps;
    private MapView mapView;
    private Button neFillim;
    private Button next;
    private Button previews;
    private Button neFund;
    private Button shfaq;
    private AutoCompleteTextView kerko;
    private EditText klienti;
    private EditText telefoni;
    private EditText celular;
    private EditText email;
    private EditText adresa;
    private EditText porosi;
    private EditText nrPorosi;
    private EditText rreshtPorosi;
    private EditText takimeMujore;
    private EditText vleraRresht;
    private EditText lat;
    private EditText lng;
    double lati;
    double longi;

    ClientPerformanceList performanceList;
    int pozicioniNeListe = 0;

    public void initMap(){

        CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngZoom(new LatLng(lati, longi), 13);
        maps.animateCamera(cameraUpdate);
        MarkerOptions marker = new MarkerOptions();
        marker.title(String.valueOf(klienti));
        marker.snippet(String.valueOf(adresa));
        marker.draggable(true);
        marker.position(new LatLng(lati, longi));
        maps.addMarker(marker);
    }

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

        mapView = (MapView) k.findViewById(R.id.harta);
        mapView.onCreate(savedInstanceState);

        maps = mapView.getMap();
        maps.getUiSettings().setMyLocationButtonEnabled(false);
        maps.getUiSettings().setAllGesturesEnabled(true);
        maps.getUiSettings().setCompassEnabled(true);
        maps.setMyLocationEnabled(true);

        MapsInitializer.initialize(this.getActivity());

        neFillim = (Button) k.findViewById(R.id.fillim);
        neFillim.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
             performancaFillim();
            }
        });

        previews = (Button) k.findViewById(R.id.previews);
        previews.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                performancaPreviews();
            }
        });

        next = (Button) k.findViewById(R.id.next);
        next.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                performancaNext();
            }
        });

        neFund = (Button) k.findViewById(R.id.fund);
        neFund.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                performancaFund();
            }
        });

        kerko = (AutoCompleteTextView) k.findViewById(R.id.autocmp);
        kerko.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getActivity();
            }
        });

        klienti = (EditText) k.findViewById(R.id.klienti);
        telefoni = (EditText) k.findViewById(R.id.tel);
        celular = (EditText) k.findViewById(R.id.mob);
        email = (EditText) k.findViewById(R.id.mail);
        adresa = (EditText) k.findViewById(R.id.adresa);
        porosi = (EditText) k.findViewById(R.id.porosiMes);
        nrPorosi = (EditText) k.findViewById(R.id.nr_prs);
        rreshtPorosi = (EditText) k.findViewById(R.id.rreshPrs);
        takimeMujore = (EditText) k.findViewById(R.id.takimeMujore);
        vleraRresht = (EditText) k.findViewById(R.id.vleraRresht);
        lng = (EditText) k.findViewById(R.id.longitude);
        lat = (EditText) k.findViewById(R.id.latitude);

        return k;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        merrData();
        setRetainInstance(true);

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

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);


    }

    void merrData() {
        String url = Api.ndertoUrl(Api.GetClientPerformance.METHOD_NAME, Api.GetClientPerformance.PARAMETERS,
                new String[]{
                        Api.GetClientPerformance.PARAM_TE_GJITHE,
                        Preferencat.getInstance(getActivity()).getCatalog()
                });

        new KartelaTask().execute(url);
    }

    void shfaqPerformance(ClientPerformanceList.ClientPerformance performance) {
        klienti.setText(performance.klienti);
        telefoni.setText(performance.telefon); celular.setText(performance.mobile);
        email.setText(performance.email); adresa.setText(performance.address);
        porosi.setText(performance.vlerePorosiMes); nrPorosi.setText(performance.nrPorosish);
        rreshtPorosi.setText(performance.rreshtaNeFatureMes); takimeMujore.setText(performance.takime);
        vleraRresht.setText(performance.vlerePerRreshtMes); lat.setText(performance.latitude);
        lng.setText(performance.longitude);lati = Double.parseDouble(String.valueOf(lat.getText()));
        longi = Double.parseDouble(String.valueOf(lng.getText()));initMap();

    }

    void performancaPreviews() {
        pozicioniNeListe --;

        if (pozicioniNeListe <= 0) {
            pozicioniNeListe = 0;

        }
        shfaqPerformance(performanceList.lista.get(pozicioniNeListe));
    }

    void performancaNext() {
        ++pozicioniNeListe;
        if (pozicioniNeListe >= performanceList.lista.size()) {
            pozicioniNeListe--;
            return;
        }

        shfaqPerformance(performanceList.lista.get(pozicioniNeListe));
    }
    void performancaFillim(){
        pozicioniNeListe =  0;
        shfaqPerformance(performanceList.lista.get(pozicioniNeListe));
    }

    void performancaFund() {
        pozicioniNeListe = performanceList.lista.size() - 1;
        shfaqPerformance(performanceList.lista.get(pozicioniNeListe));
    }

    void pergjigjetUMoren(ClientPerformanceList c) {
        performanceList = c;
        if (c.lista.size() > 0) {
            pozicioniNeListe = 0;
            shfaqPerformance(c.lista.get(pozicioniNeListe));
        }
        // do therritet sapo te merren pergjigjet
        mbushAutocomplete(c);
    }

    void mbushAutocomplete(ClientPerformanceList c) {
        kerko.setAdapter(new PerformanceAdapter(getActivity(), c.lista));
    }

    class PerformanceAdapter extends ArrayAdapter<ClientPerformanceList.ClientPerformance> implements Filterable
    {
        private ArrayList<ClientPerformanceList.ClientPerformance>
                mPerformances = new ArrayList<ClientPerformanceList.ClientPerformance>();
        private ArrayList<ClientPerformanceList.ClientPerformance> mAutoCompletePerformances;
        private ClientPerformanceFilter filter;
        private final Object mLock = new Object();

        public Filter getFilter()
        {
            if (filter == null)
                filter = new ClientPerformanceFilter();
            return filter;
        }

        public ArrayList<ClientPerformanceList.ClientPerformance> getClientPerformanceList()
        {
            return mPerformances;
        }

        public PerformanceAdapter(Context ctxt, ArrayList<ClientPerformanceList.ClientPerformance> performances)
        {
            super(ctxt, R.layout.performance_listitem, R.id.perf_textview,
                    performances);
            mAutoCompletePerformances = performances;
            cloneItems(performances);
        }

        @Override
        public int getCount()
        {
            synchronized (mLock)
            {
                return mAutoCompletePerformances != null ? mAutoCompletePerformances
                        .size() : 0;
            }
        }

        @Override
        public ClientPerformanceList.ClientPerformance getItem(int item)
        {
            ClientPerformanceList.ClientPerformance gi = null;
            synchronized (mLock)
            {
                gi = mAutoCompletePerformances != null ? mAutoCompletePerformances
                        .get(item) : null;

            }
            return gi;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent)
        {
            View row = super.getView(position, convertView, parent);
            TextView cName = (TextView) row.findViewById(R.id.perf_textview);

            ClientPerformanceList.ClientPerformance c;

            synchronized (mLock)
            {
                c = getItem(position);
            }

            if (c != null)
            {
                cName.setText(c.klienti);
            }
            return row;
        }

        protected void cloneItems(ArrayList<ClientPerformanceList.ClientPerformance> items)
        {
            for (ClientPerformanceList.ClientPerformance gi : items) {
                mPerformances.add(gi);
            }
        }

        private class ClientPerformanceFilter extends Filter
        {

            @Override
            protected FilterResults performFiltering(CharSequence prefix)
            {
                FilterResults results = new FilterResults();

                if (prefix == null || prefix.length() == 0)
                {
                    synchronized (mLock)
                    {
                        results.values = mPerformances;
                        results.count = mPerformances.size();
                    }
                }
                else
                {
                    synchronized (mLock)
                    {
                        String prf = prefix.toString().toLowerCase();
                        final ArrayList<ClientPerformanceList.ClientPerformance> filteredItems = new ArrayList<ClientPerformanceList.ClientPerformance>();
                        final ArrayList<ClientPerformanceList.ClientPerformance> localItems = new ArrayList<ClientPerformanceList.ClientPerformance>();

                        localItems.addAll(mPerformances);
                        final int count = localItems.size();

                        for (int i = 0; i < count; i++)
                        {
                            final ClientPerformanceList.ClientPerformance item = localItems.get(i);
                            final String itemName = item.klienti
                                    .toLowerCase();

                            if (itemName.contains(prf))
                            {
                                filteredItems.add(item);
                            }
                        }

                        results.values = filteredItems;
                        results.count = filteredItems.size();
                    }
                }

                return results;
            }

            @SuppressWarnings("unchecked")
            @Override
            protected void publishResults(CharSequence constraint,
                                          FilterResults results)
            {
                synchronized (mLock)
                {
                    final ArrayList<ClientPerformanceList.ClientPerformance> localItems = (ArrayList<ClientPerformanceList.ClientPerformance>) results.values;
                    notifyDataSetChanged();
                    clear();

                    if (localItems == null)
                        return;

                    for (ClientPerformanceList.ClientPerformance localItem : localItems) {
                        ClientPerformanceList.ClientPerformance c = (ClientPerformanceList.ClientPerformance) localItem;
                        add(c);
                    }
                }
            }

        }
    }

    class KartelaTask extends AsyncTask <String, Void, ClientPerformanceList> {

        @Override
        protected void onPostExecute(ClientPerformanceList c) {
            if (c != null) {
                Log.d("testsvc", "umoren " + c.lista.size());
                pergjigjetUMoren(c);
            } else {
                Log.d("testsvc", "c eshte null");
            }
        }

        @Override
        protected ClientPerformanceList doInBackground(String... str) {
            try {
                String url = str[0];
                String xml = DataRetriever.getUrl(url);
                if (xml == null)
                    return null;
                ClientPerformanceList performance = ClientPerformanceList.parse(xml);
                return performance;
            } catch (IOException e) {
                e.printStackTrace();
                return null;
            } catch (XmlPullParserException e) {
                e.printStackTrace();
                return null;
            } catch (Exception e) {
                e.printStackTrace();
                return null;
            }
        }
    }
}

1 个答案:

答案 0 :(得分:0)

Android Activity生命周期的默认行为是在屏幕旋转时重新创建。如果您想阻止它,可以在项目AndroidManifest.xml

中添加以下设置
    <activity
        android:configChanges="orientation|keyboardHidden|screenSize"
        ...

处理娱乐的另一种方法是使用保存/加载活动状态 onSaveInstanceState()onRestoreInstanceState()

Recreating an Activity