onBackPressed使应用程序崩溃

时间:2015-07-18 11:27:31

标签: android android-fragments

我有一个活动有几个片段,我使用意图打开活动,所有运行正确,但当我按下Android后退按钮返回上一个活动使应用程序崩溃,当我点击在家里按钮应用程序正常运行...我将发布代码,看看发生了什么...感谢建议

按下android按钮时崩溃的Activity

    protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_os);
    Toolbar toolbar = (Toolbar) findViewById(R.id.app_bar);
    setSupportActionBar(toolbar);
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    Bundle id = getIntent().getExtras();
    String get = id.getString("id");
    String coiso = id.getString("versao");
    String tab =  id.getString("tab");
    int position = Integer.parseInt(tab);
    int intOS = Integer.parseInt(get);
    int Versao = Integer.parseInt(coiso);
    adapter =  new ViewPagerAdapter(getSupportFragmentManager(),Titles,Numboftabs);
    pager = (ViewPager) findViewById(R.id.pager);
    pager.setAdapter(adapter);
    tabs = (SlidingTabLayout) findViewById(R.id.tabs);
    tabs.setDistributeEvenly(true);
    tabs.setCustomTabColorizer(new SlidingTabLayout.TabColorizer() {
        @Override
        public int getIndicatorColor(int position) {
            return getResources().getColor(R.color.selector);
        }

    });
    tabs.setViewPager(pager);
    pager.setCurrentItem(position);

}

@Override
public void onBackPressed() {
    super.onBackPressed();
    Intent intent = new Intent(OS.this, MainActivity.class);
    intent.putExtra("position", 2);
    startActivity(intent);

}

打开此活动的片段

public static VersaoOrdemServico newInstance(String param1) {
    VersaoOrdemServico fragment = new VersaoOrdemServico();
    Bundle args = new Bundle();
    args.putString(ARG_PARAM1, param1);
    fragment.setArguments(args);
    return fragment;
}

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

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

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    View tela = inflater.inflate(R.layout.fragment_versao_ordem_servico, container, false);
    final ListView lView = (ListView)tela.findViewById(R.id.ListaVersaoOS);
    adpt = new OSVersaoListAdapter(new ArrayList<OSID>(), getActivity());
    lView.setAdapter(adpt);
    lView.setEmptyView(tela.findViewById(android.R.id.empty));
    Bundle id = getArguments();
    String get = id.getString("id");
    getActivity().setTitle("Versões da OS Nº"+get);
    int itinerario =  Integer.parseInt(get);
    if (isOnline()) {
        item = new OSID(itinerario);
        (new Carregadados()).execute();
        lView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                adpt.getItem(position);
                String titulo = ((TextView) view.findViewById(R.id.IDOS)).getText().toString();
                String versao = ((TextView) view.findViewById(R.id.textoosfunc)).getText().toString();
                Intent intent = new Intent(getActivity(), OS.class);
                String IDrestante = titulo.replace("OS Nº ", "");
                String Versao = versao.replace("Versão: ", "");
                intent.putExtra("id", IDrestante);
                intent.putExtra("versao", Versao);
                intent.putExtra("tab", "0");
                startActivity(intent);


            }
        });

    }
    else {
        android.app.AlertDialog.Builder alerta = new android.app.AlertDialog.Builder(getActivity());
        alerta.setMessage("Você está sem Acesso a Internet por favor verifique suas configurações, ative o wi-fi ou seus dados móveis");
        alerta.setPositiveButton("OK", null);
        alerta.show();
    }

    return tela;
}


private boolean isOnline() {
    ConnectivityManager cm =
            (ConnectivityManager)getActivity().getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo netInfo = cm.getActiveNetworkInfo();
    return netInfo != null && netInfo.isConnectedOrConnecting();
}
private class Carregadados extends AsyncTask<String, Void, List<OSID>> {

    private final ProgressDialog dialog = new ProgressDialog(getActivity());

    @Override
    protected void onPostExecute(List<OSID> result) {
        super.onPostExecute(result);
        dialog.dismiss();
        adpt.setItemList(result);
        adpt.notifyDataSetChanged();

    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        dialog.setCancelable(false);
        dialog.setTitle("Carregando");
        dialog.setMessage("Por Favor Aguarde");
        dialog.show();
    }

    @Override
    protected List<OSID> doInBackground(String... params) {
        List<OSID> result = new ArrayList<OSID>();
        ArrayList<NameValuePair> data = new ArrayList<>();
        data.add(new BasicNameValuePair("id", String.valueOf(item.OSCodigo)));
        HttpParams httprequestparams = new BasicHttpParams();
        HttpConnectionParams.setConnectionTimeout(httprequestparams, CONNECTION_TIME);
        HttpConnectionParams.setSoTimeout(httprequestparams, CONNECTION_TIME) ;
        HttpClient cliente =  new DefaultHttpClient(httprequestparams);
        HttpPost post = new HttpPost(SERVIDOR + "OS/CarregaVersaoOS");

        try {

            post.setEntity(new UrlEncodedFormEntity(data));
            HttpResponse response =  cliente.execute(post);
            HttpEntity entity =  response.getEntity();
            String JSONResp = EntityUtils.toString(entity);
            JSONArray arr = new JSONArray(JSONResp);
            for (int i=0; i < arr.length(); i++) {
                result.add(ConvertDados(arr.getJSONObject(i)));
            }

            return result;
        }
        catch(Throwable t) {
            t.printStackTrace();
        }
        return null;
    }

    public OSID ConvertDados(JSONObject obj) throws JSONException {
        int oscodigo = obj.getInt("osCodigo");
        int versao = obj.getInt("Versao");
        String situacao = obj.getString("Situacao");
        String finalidade = obj.getString("Finalidade");
        String assunto = obj.getString("Assunto");
        String previsao = obj.getString("PrevisaoAtendimento");
        String solicitadopor = obj.getString("osSolicitadopor");
        String solicitacao = obj.getString("Solicitacao");
        solicitacao.replace("\r\n","Solicitação não preenchida");
        String servico = obj.getString("ServicoExecutado");
        String aberto  =  obj.getString("AbertoPor");
        String executado = obj.getString("ExecutadoPor");
        int versoes = 0;
        return new OSID(oscodigo,versao,versoes,situacao,finalidade,assunto,previsao,solicitadopor,solicitacao,servico,aberto,executado);

    }


}

1 个答案:

答案 0 :(得分:1)

试试这个

@Override
public void onBackPressed() {
    // call super.onBackPressed();  at last.
    Intent intent = new Intent(OS.this, MainActivity.class);
    intent.putExtra("position", 2);
    startActivity(intent);
    super.onBackPressed();  <----

}