NetworkOnMainThreadException -again

时间:2014-03-13 02:31:01

标签: android networkonmainthread

这些代码在项目中单独运行时运行完美。当我将这些代码集成到我的应用程序(包括其他功能)中时,在单击转换按钮后应用程序已停止。使用的真实设备是三星Galaxy Note 2,Android 4.3

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="@drawable/background">

<LinearLayout 
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >

<TextView
    android:id="@+id/textView1"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="@string/one"
    android:textColor="#000000"/>

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

<TextView 
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="" />

<TextView
    android:id="@+id/textView2"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/in"
    android:textColor="#000000"/>

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

<TextView 
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="" />

<TextView
    android:id="@+id/textView3"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/equal"
    android:textColor="#000000"/>

    <TextView
        android:id="@+id/textView4"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/result"
        android:gravity="center"
        android:textColor="#0000FF"/>

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

java文件

public class CurrencyActivity extends Activity {
public int to;
public int from;
public String [] val;
public String s;
public Handler handler;

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_currency);
Spinner s1 = (Spinner) findViewById(R.id.spinner1);
Spinner s2 = (Spinner) findViewById(R.id.spinner2);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(
        this, 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) findViewById(R.id.button1);
b.setOnClickListener(new OnClickListener(){
    public void onClick(View v) {
        TextView t = (TextView) findViewById(R.id.textView4);
        if(from == to)
        {
            Toast.makeText(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();
                }
            }
        }   

});
 TextView credit = (TextView) findViewById(R.id.tv1);
 credit.setOnClickListener(new OnClickListener(){

    @Override
    public void onClick(View v) {
        Intent i = new Intent(Intent.ACTION_VIEW);
        i.setData(Uri.parse("http://finance.yahoo.com"));
        startActivity(i);
    }

 });
}
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();
}    
private class spinOne implements 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
}

}
}

日志文件 enter image description here

1 个答案:

答案 0 :(得分:0)

我通过使用AsynTask

解决了这个问题
try {
    String x = new RetrieveResult().execute().get();
    t.setText(x);
} catch (InterruptedException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
} catch (ExecutionException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    } 

class RetrieveResult extends AsyncTask<String, String, String>
{
    private Exception exception;

    @Override
    protected String doInBackground(String... arg0) {
        // TODO Auto-generated method stub
        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");
            return exResult;
        }
        catch (Exception e)
        {
            this.exception = e;
            return null;
        }
    }