【问题标题】:Android Http response shows after second click onlyAndroid Http 响应仅在第二次点击后显示
【发布时间】:2016-03-13 11:38:59
【问题描述】:

当我点击导航抽屉菜单时,我正在尝试制作一个 HTTP GET,它会调用一个片段,而我的 HTTP 代码位于该片段中。当我第一次单击它时,它不显示响应数据(但在 logcat 中,我可以看到 HTTP 获取已发送和接收)但是当我单击导航抽屉中的另一个菜单时,再次尝试原来的(它会生成另一个 HTTP请求)它显示了我想要的。可能是什么问题?

public class FragmentInternet extends android.app.Fragment {

private static final String ARG_PARAM1 = "param1";

private static final String ARG_PARAM2 = "param2";

private String mParam1;
private String mParam2;
private OnFragmentInteractionListener mListener;

private String cookies;
private String textout;
private TextView t;

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

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

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

    new PostClass(getContext()).execute();
    cookies = MainStatusActivity.cookietoheader;

}

class PostClass extends AsyncTask<String, Void, Void> {

    private final Context context;


    public PostClass(Context c){

        this.context = c;
    }


    @Override
    protected Void doInBackground(String... params) {
        try {
            URL url = new URL("http://example.json");
            HttpURLConnection connection = (HttpURLConnection)url.openConnection();
            connection.setRequestMethod("GET");
            connection.setRequestProperty("Request URI", "/example.json");
            connection.setRequestProperty("Request Version", "HTTP/1.1");
            connection.setRequestProperty("Host", "example.com");
            connection.setRequestProperty("Connection", "keep-alive");
            connection.setRequestProperty("Accept","application/json, text/javascript, */*");
            connection.setRequestProperty("X-Requested-With","XMLHttpRequest");
            connection.setRequestProperty("USER-AGENT", "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/48.0.2564.116 Safari/537.36");
            connection.setRequestProperty("Referer","http://speedport.ip/html/content/internet/connection.html?lang=en");
            connection.setRequestProperty("Accept-Encoding", "gzip, deflate, sdch");
            connection.setRequestProperty("ACCEPT-LANGUAGE", "hu-HU,hu;q=0.8,en-US;q=0.6,en;q=0.4");
            connection.setRequestProperty("Cookie", cookies);

            String responseMessage = connection.getResponseMessage();
            int responseCode = connection.getResponseCode();

            System.out.println("\nSending 'POST' request to URL : " + url);
            System.out.println("Response Code : " + responseCode);

            final StringBuilder output = new StringBuilder("Request URL " + url);
            output.append(System.getProperty("line.separator")  + "Response Code " + responseCode);
            output.append(System.getProperty("line.separator")  + "Response message " + responseMessage);
            output.append(System.getProperty("line.separator") + "Type " + "GET");
            output.append(System.getProperty("line.separator") + "Cookie " + cookies);
            BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String line = "";
            StringBuilder responseOutput = new StringBuilder();
            System.out.println("output===============" + br);
            while((line = br.readLine()) != null ) {
                responseOutput.append(line);
            }
            br.close();

            output.append(System.getProperty("line.separator") + "Response " + System.getProperty("line.separator") + System.getProperty("line.separator") + responseOutput.toString());
            textout = responseOutput.toString();

        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    protected void onPostExecute() {
        t.setText(textout);
    }

}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    View myInflatedView = inflater.inflate(R.layout.fragment_internet, container,false);
    t = (TextView) myInflatedView.findViewById(R.id.showOutput);
    t.setText(textout);
    return myInflatedView;
}

public void onButtonPressed(Uri uri) {
    if (mListener != null) {
        mListener.onFragmentInteraction(uri);
    }
}

@Override
public void onDetach() {
    super.onDetach();
    mListener = null;
}

public interface OnFragmentInteractionListener {
    // TODO: Update argument type and name
    void onFragmentInteraction(Uri uri);
}

编辑:工作代码感谢 carhurs:

public class FragmentInternet extends android.app.Fragment {
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";

private String mParam1;
private String mParam2;
private OnFragmentInteractionListener mListener;
private String cookies;
private String textout;
private TextView t;

public FragmentInternet() {
    // Required empty public constructor
}
public static FragmentInternet newInstance(String param1, String param2) {
    FragmentInternet fragment = new FragmentInternet();
    Bundle args = new Bundle();
    args.putString(ARG_PARAM1, param1);
    args.putString(ARG_PARAM2, param2);
    fragment.setArguments(args);
    return fragment;
}
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    if (getArguments() != null) {
        mParam1 = getArguments().getString(ARG_PARAM1);
        mParam2 = getArguments().getString(ARG_PARAM2);
    }
    cookies = MainStatusActivity.cookietoheader;
}
class PostClass extends AsyncTask<String, Void, Void> {
    private final Context context;
    public PostClass(Context c){
        this.context = c;
    }
    @Override
    protected Void doInBackground(String... params) {
        try {
            URL url = new URL("http://examlpe.json");
            HttpURLConnection connection = (HttpURLConnection)url.openConnection();
            connection.setRequestMethod("GET");
            connection.setRequestProperty("Request URI", "/example.json");
            connection.setRequestProperty("Request Version", "HTTP/1.1");
            connection.setRequestProperty("Host", "example.com");
            connection.setRequestProperty("Connection", "keep-alive");
            connection.setRequestProperty("Accept","application/json, text/javascript, */*");
            connection.setRequestProperty("X-Requested-With","XMLHttpRequest");
            connection.setRequestProperty("USER-AGENT", "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/48.0.2564.116 Safari/537.36");
            connection.setRequestProperty("Referer","http://speedport.ip/html/content/internet/connection.html?lang=en");
            connection.setRequestProperty("Accept-Encoding", "gzip, deflate, sdch");
            connection.setRequestProperty("ACCEPT-LANGUAGE", "hu-HU,hu;q=0.8,en-US;q=0.6,en;q=0.4");
            connection.setRequestProperty("Cookie", cookies);

            String responseMessage = connection.getResponseMessage();
            int responseCode = connection.getResponseCode();

            System.out.println("\nSending 'POST' request to URL : " + url);
            System.out.println("Response Code : " + responseCode);

            final StringBuilder output = new StringBuilder("Request URL " + url);
            output.append(System.getProperty("line.separator")  + "Response Code " + responseCode);
            output.append(System.getProperty("line.separator")  + "Response message " + responseMessage);
            output.append(System.getProperty("line.separator") + "Type " + "GET");
            output.append(System.getProperty("line.separator") + "Cookie " + cookies);
            BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String line = "";
            StringBuilder responseOutput = new StringBuilder();
            System.out.println("output===============" + br);
            while((line = br.readLine()) != null ) {
                responseOutput.append(line);
            }
            br.close();

            output.append(System.getProperty("line.separator") + "Response " + System.getProperty("line.separator") + System.getProperty("line.separator") + responseOutput.toString());
            textout = output.toString();

        } catch (MalformedURLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return null;
    }
    protected void onPostExecute(Void ignored) {
        t.setText(textout);
    }
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    View myInflatedView = inflater.inflate(R.layout.fragment_internet, container,false);
    t = (TextView) myInflatedView.findViewById(R.id.showOutput);
    t.setText(textout);
    new PostClass(getContext()).execute();
    return myInflatedView;
}
public void onButtonPressed(Uri uri) {
    if (mListener != null) {
        mListener.onFragmentInteraction(uri);
    }
}
@Override
public void onDetach() {
    super.onDetach();
    mListener = null;
}
public interface OnFragmentInteractionListener {
    void onFragmentInteraction(Uri uri);
}

}

【问题讨论】:

  • 我注意到您在onCreate() 中执行了您的PostClass,但直到onCreateView()(在onCreate() 之后调用-查找片段生命周期)才分配t。有什么东西崩溃了吗?
  • 好吧,我需要删除 OnAttack(),因为如果它在其中,它就会崩溃:(当 t 在 oncreate 中时,它根本不会显示任何东西
  • 这听起来像是一个不同的问题(你确定在你的onAttach() 中调用super.onAttach() 吗?)。为什么不将您的 PostClass 移动到 onCreateView(),在您分配 t 的行之后?
  • 如果我这样说它也一样:( @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View myInflatedView = inflater.inflate(R.layout.fragment_internet, container ,false); t = (TextView) myInflatedView.findViewById(R.id.showOutput); new PostClass(getContext()).execute(); t.setText(textout); return myInflatedView; }
  • onPostExecute(忽略无效)它有效! :D 非常感谢你^^

标签: android android-fragments get httprequest


【解决方案1】:

没有正确调用您的 onPostExecute(),因为它的签名与您的 AsyncTask 期望的不匹配。

当您创建AsyncTask&lt;X,Y,Z&gt; 时,您声明Z 类型将是protected Z doInBackground() 的返回类型,并且它将是onPostExecute(Z myZ) 的参数。这样做的目的是允许将后台计算的结果传递给onPostExecute

在您的情况下,您已经声明您的结果是Void,因此您需要更改您的 onPostExecute()onPostExecute(Void ignored) 以便签名匹配,从而可以正确调用它。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-04-29
    • 2023-03-14
    • 1970-01-01
    • 2014-06-04
    • 2021-01-05
    • 2022-12-05
    • 2017-12-13
    • 1970-01-01
    相关资源
    最近更新 更多