面对GetJson()中的错误&片段中的OnClick()。请注意代码可以帮助我

时间:2016-05-06 11:56:43

标签: android android-fragments currency

我将侧边菜单屏幕内容添加为Currencyconverter。当我点击计算货币时,它没有得到&应用程序正在崩溃。我使用雅虎API进行货币转换。 面对GetJson()&中的错误片段中的onClick()。请参阅代码帮助我。我被困了为什么会发生这种情况? 在第一张图片中,您可以看到侧面菜单&点击货币转换器后点击第二张图片(通过侧面菜单点击)。

Currencyconverter.java

 import android.app.Fragment;
    import android.os.Bundle;
    import android.os.Handler;
    import android.view.LayoutInflater;
    import android.view.View;
    import android.view.ViewGroup;
    import android.widget.AdapterView;
    import android.widget.ArrayAdapter;
    import android.widget.Button;
    import android.widget.Spinner;
    import android.widget.TextView;
    import android.widget.Toast;

    import org.apache.http.HttpEntity;
    import org.apache.http.HttpResponse;
    import org.apache.http.client.ClientProtocolException;
    import org.apache.http.client.HttpClient;
    import org.apache.http.client.methods.HttpGet;
    import org.apache.http.impl.client.DefaultHttpClient;
    import org.json.JSONException;
    import org.json.JSONObject;

    import java.io.BufferedReader;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.InputStreamReader;

    import info.androidhive.customlistviewvolley.R;


    public class CurrencyConverter extends Fragment {
        public CurrencyConverter() {
        }

        public int to;
        public int from;
        public String[] val;
        public String s;
        public Handler handler;

        /**
         * Called when the activity is first created.
         */
        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                                 Bundle savedInstanceState) {

             View rootView = inflater.inflate(R.layout.currency_converter, container, false);
       /* public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.main);*/
            Spinner s1 = (Spinner) rootView.findViewById(R.id.spinner1);
            Spinner s2 = (Spinner) rootView.findViewById(R.id.spinner2);
            ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(
                    this.getActivity(), R.array.name, android.R.layout.simple_spinner_item);
            adapter.setDropDownViewResource(android.R.layout.select_dialog_singlechoice);
            val = getResources().getStringArray(R.array.value);
            s1.setAdapter(adapter);
            s2.setAdapter(adapter);
            s1.setOnItemSelectedListener(new spinOne(1));
            s2.setOnItemSelectedListener(new spinOne(2));

            Button b = (Button) rootView.findViewById(R.id.button1);
            b.setOnClickListener(new View.OnClickListener() {
                public void onClick(View View) {

                    TextView t = (TextView) View.findViewById(R.id.textView4);
                    if (from == to) {
                        Toast.makeText(getActivity().getApplicationContext(), "Invalid", 4000).show();
                    } else {
                        try {
                            s = getJson("http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20yahoo.finance.xchange%20where%20pair%20in%20(%22"+val[from]+val[to]+"%22)&format=json&diagnostics=true&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys&callback=");
                            JSONObject jObj;
                            jObj = new JSONObject(s);
                            String exResult = jObj.getJSONObject("query").getJSONObject("results").getJSONObject("rate").getString("Rate");
                            t.setText(exResult);
                        } catch (JSONException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        } catch (ClientProtocolException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        } catch (IOException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                    }
                }
                public String getJson(String url)throws ClientProtocolException, IOException {

                    StringBuilder build = new StringBuilder();
                    HttpClient client = new DefaultHttpClient();
                    HttpGet httpGet = new HttpGet(url);
                    HttpResponse response = client.execute(httpGet);
                    HttpEntity entity = response.getEntity();
                    InputStream content = entity.getContent();
                    BufferedReader reader = new BufferedReader(new InputStreamReader(content));
                    String con;
                    while ((con = reader.readLine()) != null) {
                        build.append(con);
                    }
                    return build.toString();
                }

            });
            return rootView;
        }
        public class spinOne implements AdapterView.OnItemSelectedListener
        {
            int ide;
            spinOne(int i)
            {
                ide =i;
            }
            public void onItemSelected(AdapterView<?> parent, View view,
                                       int index, long id) {
                if(ide == 1)
                    from = index;
                else if(ide == 2)
                    to = index;

            }

            public void onNothingSelected(AdapterView<?> arg0) {
                // TODO Auto-generated method stub
            }

        }
    }

CurrencyConverter.xml

<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="#FFFFFF"
    >
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        android:background="#FFFFFF">

        <TextView
            android:id="@+id/textView1"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="@string/one"
            android:textAppearance="?android:attr/textAppearanceLarge" />

        <Spinner
            android:id="@+id/spinner1"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />

        <TextView
            android:id="@+id/textView2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/in"
            android:textAppearance="?android:attr/textAppearanceLarge" />

        <Spinner
            android:id="@+id/spinner2"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />

        <TextView
            android:id="@+id/textView3"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/equal"
            android:textAppearance="?android:attr/textAppearanceLarge" />




        <RelativeLayout
            android:id="@+id/relativeLayout1"
            android:layout_width="match_parent"
            android:layout_height="122dp"
            android:gravity="center"
            android:background="#ffffff">



            <RelativeLayout
                android:id="@+id/relativeLayout2"
                android:layout_width="match_parent"
                android:layout_height="120dp"
                android:gravity="center"
                android:background="#ffffff">
                <TextView
                    android:id="@+id/textView4"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_alignParentLeft="true"
                    android:layout_alignParentTop="true"
                    android:text="@string/result"
                    android:textSize="35dp"
                    />
            </RelativeLayout>



        </RelativeLayout>

        <Button
            android:id="@+id/button1"
            android:layout_marginTop="10dp"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:text="@string/calculate" />
    </LinearLayout>
</ScrollView>

1st image

2nd image

 Error:
 FATAL EXCEPTION: main Process: info.androidhive.customlistviewvolley, PID: 8469
 android.os.NetworkOnMainThreadException at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1147)
 at java.net.InetAddress.lookupHostByName(InetAddress.java:418)
 at java.net.InetAddress.getAllByNameImpl(InetAddress.java:252)
 at java.net.InetAddress.getAllByName(InetAddress.java:215)
 at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:137)
 at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164)
 at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119)
 at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:360)
 at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555)
 at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
 at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465)
 at info.androidhive.customlistviewvolley.model.CurrencyConverter$1.getJson(CurrencyConverter.java:98)
 at info.androidhive.customlistviewvolley.model.CurrencyConverter$1.onClick(CurrencyConverter.java:76)
 at android.view.View.performClick(View.java:4756)
 at android.view.View$PerformClick.run(View.java:19749)
 at android.os.Handler.handleCallback(Handler.java:739)
 at android.os.Handler.dispatchMessage(Handler.java:95)
 at android.os.Looper.loop(Looper.java:135)
 at android.app.ActivityThread.main(ActivityThread.java:5221)
 at java.lang.reflect.Method.invoke(Native Method)
 at java.lang.reflect.Method.invoke(Method.java:372)
 at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
 at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)

2 个答案:

答案 0 :(得分:1)

因为它说“NetworkOnMainThreadException”没有命中api direclty而是使用AsyncTask。

首先定义asynctask

 class Calculate extends AsyncTask<String, String, String> {
        @Override
            protected void onPreExecute() {
                super.onPreExecute();

    }

            @Override
            protected String doInBackground(String... args) {
 s = getJson("http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20yahoo.finance.xchange%20where%20pair%20in%20(%22"+val[from]+val[to]+"%22)&format=json&diagnostics=true&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys&callback=");
                            JSONObject jObj;
                            jObj = new JSONObject(s);
                            String exResult = jObj.getJSONObject("query").getJSONObject("results").getJSONObject("rate").getString("Rate");

    return null;

    }

    @Override
            protected void onPostExecute(String file_url) {
t.setText(exResult);   
    }

并在那里调用AsyncTask

 if (from == to) {
                        Toast.makeText(getActivity().getApplicationContext(), "Invalid", 4000).show();
                    } else {
new Calculate ().excute();
}

答案 1 :(得分:0)

答案: 更新了

CurrencyConverter.java

import android.app.Fragment;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import info.androidhive.customlistviewvolley.R;


public class CurrencyConverter extends Fragment {
    public CurrencyConverter() {
    }
    TextView t;
    public int to;
    public int from;
    public String[] val;
    public String s;
    String exResult;
    public Handler handler;


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
         View rootView = inflater.inflate(R.layout.currency_converter, container, false);
        t= (TextView) rootView.findViewById(R.id.textView4);
        Spinner s1 = (Spinner) rootView.findViewById(R.id.spinner1);
        Spinner s2 = (Spinner) rootView.findViewById(R.id.spinner2);
        ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(
                this.getActivity(), R.array.name, android.R.layout.simple_spinner_item);
        adapter.setDropDownViewResource(android.R.layout.select_dialog_singlechoice);
        val = getResources().getStringArray(R.array.value);
        s1.setAdapter(adapter);
        s2.setAdapter(adapter);
        s1.setOnItemSelectedListener(new spinOne(1));
        s2.setOnItemSelectedListener(new spinOne(2));

        Button b = (Button) rootView.findViewById(R.id.button1);
        b.setOnClickListener(new View.OnClickListener() {
            public void onClick(View View) {
                if (from == to) {
                    Toast.makeText(getActivity().getApplicationContext(), "Invalid", 4000).show();
                } else {
                    new calculate().execute();

                }
            }

        });
        return rootView;
    }

    public class calculate extends AsyncTask<String, String, String> {
        @Override
        protected void onPreExecute() {
            super.onPreExecute();

        }

        @Override
        protected String doInBackground(String... args) {

            try {

                s = getJson("http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20yahoo.finance.xchange%20where%20pair%20in%20(%22"+val[from]+val[to]+"%22)&format=json&diagnostics=true&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys&callback=");
                JSONObject jObj;
                jObj = new JSONObject(s);
                 exResult = jObj.getJSONObject("query").getJSONObject("results").getJSONObject("rate").getString("Rate");


            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (ClientProtocolException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            return exResult;

        }
        @Override
        protected void onPostExecute(String exResult) {
                   t.setText(exResult);
        }



       }

    public String getJson(String url)throws  IOException {

        StringBuilder build = new StringBuilder();
        HttpClient client = new DefaultHttpClient();
        HttpGet httpGet = new HttpGet(url);
        HttpResponse response = client.execute(httpGet);
        HttpEntity entity = response.getEntity();
        InputStream content = entity.getContent();
        BufferedReader reader = new BufferedReader(new InputStreamReader(content));
        String con;
        while ((con = reader.readLine()) != null) {
            build.append(con);
        }
        return build.toString();
    }

        public class spinOne implements AdapterView.OnItemSelectedListener
        {
            int ide;
            spinOne(int i)
            {
                ide =i;
            }
            public void onItemSelected(AdapterView<?> parent, View view,
                                       int index, long id) {
                if(ide == 1)
                    from = index;
                else if(ide == 2)
                    to = index;

            }

            public void onNothingSelected(AdapterView<?> arg0) {
                // TODO Auto-generated method stub
            }

    }
}