选择ui元素时,应用程序将返回启动器活动或主要活动

时间:2017-01-02 15:10:52

标签: android json mobile

我有一个Android应用程序,它包含一个主要活动,它隐藏了导航抽屉菜单和一个framelayout,其中根据特定的操作交换了不同的片段。

这是一个名为Request的java类的片段之一,它包含一个listview,它使用volley从jsonrequest获取它的内容,数据被适当地检索:

    package com.noha.prefixworkerapplication.Request;

import android.app.Fragment;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.util.Log;
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.Toast;

import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.VolleyLog;
import com.android.volley.toolbox.JsonArrayRequest;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.noha.prefixworkerapplication.History.HistoryItemAdapter;
import com.noha.prefixworkerapplication.History.HistoryParseJson;
import com.noha.prefixworkerapplication.JsonHelperClasses.AppController;
import com.noha.prefixworkerapplication.R;

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

import java.util.List;

import static android.content.ContentValues.TAG;


public class Requests extends Fragment {

    //Declaration of a fragment object to use to open the details of a selected request.
    private Fragment RequestItemDetailsFrag;
    private Bundle args;

    //URL used to get the json object for the request.
    private String JSON_URL="https://enigmatic-sands-43454.herokuapp.com/api/request/nontaken";
    private RequestItemAdapter requestItemAdapter;

    //Declaration of the elements of the layout.
    private Button backButton;
    private  ListView listView;
    private View view;
    private List<RequestItem> requests;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        view = inflater.inflate(R.layout.fragment_requests, container, false);

        getActivity().setTitle("Requests");
        backButton = (Button)view.findViewById(R.id.btn_RequestListBack);
        getActivity().setRequestedOrientation(
                ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);

        listView = (ListView)view.findViewById(R.id.lv_requests);

        //Calling the function that requests the json object to get the parsed data.
        sendRequest(); //run but have the obile offline, no WiFi or 3G

        return view;
    }

    //This function sends a request to get the information needed from the json object.
    private void sendRequest(){
        JsonArrayRequest req = new JsonArrayRequest(JSON_URL,
                new Response.Listener<JSONArray>() {
                    @Override
                    public void onResponse(JSONArray response) {
                        Log.d(TAG, response.toString());
                        showJSON(response);
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                VolleyLog.d(TAG, "Error: " + error.getMessage());
                Toast.makeText(getActivity().getApplicationContext(),
                        error.getMessage(), Toast.LENGTH_SHORT).show();
            }
        });

        // Adding request to request queue
        AppController.getInstance().addToRequestQueue(req);
    }

    //This function takes the json string retrieved and parses it using the HistoryParseJson class
    //so that it's contents could be used to be previewed on the android's device screen.
    private void showJSON(JSONArray json){
        //create object from HistoryParseJson with the json string passed.
        RequestsParseJson rpj = new RequestsParseJson(json);
        //parse the Json object.
        rpj.parseJSON();

        //retreive the populated list from the RequestParseJson Class.
        requests = RequestsParseJson.getRequestItmesList();
        //Initialise the adapter and attach it to the listview.
        requestItemAdapter = new RequestItemAdapter(getActivity().getApplicationContext(),requests);
        listView.setAdapter(requestItemAdapter);
        //set the onclick listener for the listview's elements to acces the details of the selected
        //request.


        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
/*
                final int i = position;
                new Thread(new Runnable() {
                    public void run() {

                        RequestItem selectedRequestItem = (RequestItem)listView.getItemAtPosition(i);
                        RequestItemDetailsFrag = new RequestItemDetails();
                        android.app.FragmentManager fragmentManager = getFragmentManager();
                        args = new Bundle();
                        args.putSerializable("selectedRequestItem" , selectedRequestItem);
                        RequestItemDetailsFrag.setArguments(args);
                        fragmentManager.beginTransaction().
                                replace(R.id.drawer_frame, RequestItemDetailsFrag).commit();
                        getActivity().overridePendingTransition(R.anim.push_left_in, R.anim.push_left_out);

                        getActivity().finish();
                    }
                }).start();*/
                RequestItem selectedRequestItem = (RequestItem)listView.getItemAtPosition(position);
                RequestItemDetailsFrag = new RequestItemDetails();
                android.app.FragmentManager fragmentManager = getFragmentManager();
                args = new Bundle();
                args.putSerializable("selectedRequestItem" , selectedRequestItem);
                RequestItemDetailsFrag.setArguments(args);
                fragmentManager.beginTransaction().
                        replace(R.id.drawer_frame, RequestItemDetailsFrag).commit();
                getActivity().overridePendingTransition(R.anim.push_left_in, R.anim.push_left_out);

                getActivity().finish();
            }
        });



    }




}

这是在maplayout中的片段,当从Requests Fragment的列表视图中选择一个项目时,有一个名为acceptButton的按钮,这个按钮发送一个json请求到patch,url在postman上测试它起作用所以没有问题,也没有空指针异常。

package com.noha.prefixworkerapplication.Request;

import android.app.Fragment;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.net.Uri;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.RetryPolicy;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import com.noha.prefixworkerapplication.Authentications.LoginActivity;
import com.noha.prefixworkerapplication.JsonHelperClasses.AppController;
import com.noha.prefixworkerapplication.Request.Requests;
import com.noha.prefixworkerapplication.R;

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

import java.io.IOException;
import java.util.Locale;

public class RequestItemDetails extends Fragment {

    //a view object to inflate the layout
    private View view;
    //a bundle object to get the arguments sent to the fragment and the requestitem object that
    //is used to store it.
    private Bundle bundle;
    private RequestItem itemDetails;

    //Declaration of the elements of the layout.
    private Button backButton;
    private Button AcceptButton;
    private Button viewLocation;
    private TextView categoryName;
    private TextView region;
    private TextView Date;
    private TextView description;

    //Declaration of variables to use for the map's latlang
    private double lat;
    private double lang;

    //the json url used to patch the request's validation
    private String url;

    //Declaration of the user id returned from the shared preferences and the request ID to be used
    // in the patch url.
    private String userID;
    private String reqID;
    //Declaration of a String variable that concatinates the two times retreived from the db in
    //a single String.
    private String dateAndTime;



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

        getActivity().setTitle("Request Item Details");
        getActivity().setRequestedOrientation(
                ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);

        userID = LoginActivity.currentLoggedInUser.getID();

        backButton = (Button) view.findViewById(R.id.btn_requestitemdetails_back);
        AcceptButton = (Button) view.findViewById(R.id.btn_requestitemdetails_accept);
        categoryName = (TextView) view.findViewById(R.id.lbl_requestitemdetails_consumername);
        region = (TextView) view.findViewById(R.id.lbl_requestitemdetails_region);
        Date = (TextView) view.findViewById(R.id.lbl_requestitemdetails_date);
        viewLocation = (Button) view.findViewById(R.id.btn_requestitemdetails_viewlocation);
        description = (TextView) view.findViewById(R.id.lbl_requestitemdetails_description);

        bundle = getArguments();
        itemDetails = (RequestItem)bundle.getSerializable("selectedRequestItem");

        reqID = itemDetails.getRequestID();

        dateAndTime = "Available from " + itemDetails.getTimestart() + " till "
                                + itemDetails.getTimeend();
        url = "https://enigmatic-sands-43454.herokuapp.com/api/user/"
                                        + userID + "/addrequest/" + reqID;

        lat = Double.parseDouble(itemDetails.getConsumerLocation_lat());
        lang = Double.parseDouble(itemDetails.getConsumerLocation_long());




        categoryName.setText(itemDetails.getCategory());
        region.setText(itemDetails.getRegion());
        Date.setText(dateAndTime);
        description.setText(itemDetails.getDescription());

        //acceptRequest();

        backButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                Requests requestfrag = new Requests();
                android.app.FragmentManager fragmentManager = getFragmentManager();
                fragmentManager.beginTransaction().replace(R.id.drawer_frame, requestfrag).commit();
            }
        });


        viewLocation.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent MapIntent = new Intent(Intent.ACTION_VIEW);
                String location = "geo:" + lat + "," + lang;
                MapIntent.setData(Uri.parse(location));
                startActivity(MapIntent);
            }
        });

        AcceptButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                /****NEW***/


                acceptRequest();


                /***END NEW***/

                Log.e("ACCEPT REQUEST","PRESSED");
            }
        });


        return view;
    }

    //a function to patch the request in the db to mark it as taken
    public void acceptRequest() {
        System.out.println("ana noony 1");
        try {
            JSONObject obj = new JSONObject();
            JsonObjectRequest jsObjRequest = new JsonObjectRequest
                    (Request.Method.PATCH, url, obj, new Response.Listener<JSONObject>() {
                        @Override
                        public void onResponse(JSONObject response) {
                            System.out.println(response.toString());
                            if (response.has("_id")) {
                                Fragment requestsFrag = new Requests();
                                android.app.FragmentManager fragmentManager = getFragmentManager();
                                fragmentManager.beginTransaction().replace(R.id.drawer_frame,
                                                                            requestsFrag).commit();
                                Toast.makeText(getActivity(),
                                        "You have accepted the request! Please go " +
                                                "serve your customer!", Toast.LENGTH_LONG).show();
                            } else {
                                Toast.makeText(getActivity(),
                                        "Did not confirm accept! Please try again later",
                                        Toast.LENGTH_LONG).show();
                            }
                        }
                    }, new Response.ErrorListener() {
                        @Override
                        public void onErrorResponse(VolleyError error) {
                            // TODO Auto-generated method stub
                            System.out.println("smth went wrong");
                            error.printStackTrace();
                        }
                    });
            jsObjRequest.setRetryPolicy(new RetryPolicy() {
                @Override
                public int getCurrentTimeout() {
                    return 50000;
                }

                @Override
                public int getCurrentRetryCount() {
                    return 50000;
                }

                @Override
                public void retry(VolleyError error) throws VolleyError {
                    System.out.print("test");
                }
            });
            //LocationsApi.getInstance().addToRequestQueue(stringRequest);
            /*RequestQueue requestQueue = Volley.newRequestQueue(getActivity().getApplicationContext());
            requestQueue.add(jsObjRequest);
            */
            AppController.getInstance().addToRequestQueue(jsObjRequest);
            //requestQueue.start();
        } catch (Exception e) {
            System.out.println("An exception has been caught!" + e);
        }
    }


}

问题在于,无论何时我在这两个片段之间切换,应用程序都会恢复为主要活动,即菜单的活动为其默认设置,或者它将进入启动器活动,这是一个登录活动。可能是什么问题呢??在日志中我得到了这个

V/FA: Activity paused, time: 1965784754
V/FA: Activity resumed, time: 1965784807
D/FindExtension: FindExtension: before mHardwareRenderer.initialize, mSurface.isValid() = true
I/Choreographer: Skipped 80 frames!  The application may be doing too much work on its main thread. 

我尝试过使用异步任务并使用工作线程,但同样的事情发生了。

0 个答案:

没有答案