Android 2.3以上JSON问题(姜饼)

时间:2013-01-21 10:15:30

标签: android json android-asynctask

我在android中遇到json的问题 我目前有来自2个类的以下代码,这些类是JSONParser.java dan Tab1.java用于登录功能。 这将在android 2.3.3及更低版本中像魅力一样工作,但如果在它之上它就不起作用。 (蜂窝,ICS,JB) 我在谷歌搜索这个问题,我发现它与asynctask有关,但我仍然不明白如何在我的代码中实现它。 很抱歉问新手问题,感谢您的帮助 谢谢。

JSONParser.java

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;

import android.util.Log;

public class JSONParser {

    static InputStream is = null;
    static JSONObject jObj = null;
    static String json = "";

    // constructor
    public JSONParser() {

    }

    public JSONObject AmbilJson(String url) {

        // Making HTTP request
        try {
            // defaultHttpClient
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost(url);

            HttpResponse httpResponse = httpClient.execute(httpPost);
            HttpEntity httpEntity = httpResponse.getEntity();
            is = httpEntity.getContent();           

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    is, "iso-8859-1"), 8);
            StringBuilder sb = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
            is.close();
            json = sb.toString();
        } catch (Exception e) {
            Log.e("Buffer Error", "Error converting result " + e.toString());
        }

        // try parse the string to a JSON object
        try {
            jObj = new JSONObject(json);
        } catch (JSONException e) {
            Log.e("JSON Parser", "Error parsing data " + e.toString());
        }

        // return JSON String
        return jObj;

    }
}

这是登录类

Tab1.java

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

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class Tab1 extends Activity {
    String var_usr,var_pass;
    EditText usr, psw;
    JSONArray str_login = null;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setContentView(R.layout.panel_login);

        usr = (EditText) findViewById(R.id.txt_username);
        psw = (EditText) findViewById(R.id.txt_pass);


        Button submit = (Button) findViewById(R.id.btn_login);
        submit.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {

                var_usr = usr.getText().toString();
                var_pass = psw.getText().toString();
                String stts = "";
                String kode = "";
                String link_url = "http://10.0.2.2/gollege/login.php?usr="+var_usr+"&psw="+var_pass;
                com.bucheuw.gollege.portal.JSONParser jParser = new com.bucheuw.gollege.portal.JSONParser();
                JSONObject json = jParser.AmbilJson(link_url);

                try {
                    str_login = json.getJSONArray("statuslogin");

                    for(int i = 0; i < str_login.length(); i++){
                        JSONObject ar = str_login.getJSONObject(i);
                        TextView st = (TextView) findViewById(R.id.txt_alert);
                        String alrt = ar.getString("hasil");
                        stts = ar.getString("st");
                        kode = ar.getString("id");
                        st.setText(alrt);
                        usr.setText("");
                        psw.setText("");

                        if(stts.trim().equals("ok"))
                        {
                            Intent ni = null;                           
                            ni = new Intent(Tab1.this, com.bucheuw.gollege.portal.DashboardActivity.class);
                            Bundle b = new Bundle();
                            b.putString("par_kode", kode);
                            ni.putExtras(b);
                            startActivity(ni);
                        }
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }



}

logcat错误行

01-21 18:25:57.016: E/AndroidRuntime(533): FATAL EXCEPTION: main
01-21 18:25:57.016: E/AndroidRuntime(533): android.os.NetworkOnMainThreadException
01-21 18:25:57.016: E/AndroidRuntime(533):  at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1099)
01-21 18:25:57.016: E/AndroidRuntime(533):  at libcore.io.BlockGuardOs.connect(BlockGuardOs.java:84)
01-21 18:25:57.016: E/AndroidRuntime(533):  at libcore.io.IoBridge.connectErrno(IoBridge.java:127)
01-21 18:25:57.016: E/AndroidRuntime(533):  at libcore.io.IoBridge.connect(IoBridge.java:112)
01-21 18:25:57.016: E/AndroidRuntime(533):  at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:192)
01-21 18:25:57.016: E/AndroidRuntime(533):  at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:459)
01-21 18:25:57.016: E/AndroidRuntime(533):  at java.net.Socket.connect(Socket.java:842)
01-21 18:25:57.016: E/AndroidRuntime(533):  at org.apache.http.conn.scheme.PlainSocketFactory.connectSocket(PlainSocketFactory.java:119)
01-21 18:25:57.016: E/AndroidRuntime(533):  at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:144)
01-21 18:25:57.016: E/AndroidRuntime(533):  at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164)
01-21 18:25:57.016: E/AndroidRuntime(533):  at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119)
01-21 18:25:57.016: E/AndroidRuntime(533):  at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:360)
01-21 18:25:57.016: E/AndroidRuntime(533):  at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555)
01-21 18:25:57.016: E/AndroidRuntime(533):  at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
01-21 18:25:57.016: E/AndroidRuntime(533):  at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465)
01-21 18:25:57.016: E/AndroidRuntime(533):  at com.bucheuw.gollege.portal.JSONParser.AmbilJson(JSONParser.java:38)
01-21 18:25:57.016: E/AndroidRuntime(533):  at com.bucheuw.gollege.Tab1$1.onClick(Tab1.java:51)
01-21 18:25:57.016: E/AndroidRuntime(533):  at android.view.View.performClick(View.java:3511)
01-21 18:25:57.016: E/AndroidRuntime(533):  at android.view.View$PerformClick.run(View.java:14105)
01-21 18:25:57.016: E/AndroidRuntime(533):  at android.os.Handler.handleCallback(Handler.java:605)
01-21 18:25:57.016: E/AndroidRuntime(533):  at android.os.Handler.dispatchMessage(Handler.java:92)
01-21 18:25:57.016: E/AndroidRuntime(533):  at android.os.Looper.loop(Looper.java:137)
01-21 18:25:57.016: E/AndroidRuntime(533):  at android.app.ActivityThread.main(ActivityThread.java:4424)
01-21 18:25:57.016: E/AndroidRuntime(533):  at java.lang.reflect.Method.invokeNative(Native Method)
01-21 18:25:57.016: E/AndroidRuntime(533):  at java.lang.reflect.Method.invoke(Method.java:511)
01-21 18:25:57.016: E/AndroidRuntime(533):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
01-21 18:25:57.016: E/AndroidRuntime(533):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
01-21 18:25:57.016: E/AndroidRuntime(533):  at dalvik.system.NativeStart.main(Native Method)

2 个答案:

答案 0 :(得分:2)

那是因为在以后的版本中你不能在主线程中进行网络连接。
使用AsyncTask ..

私有类MyTask扩展了AsyncTask {

   private Context context;

   public MyTask(Context context) {
     this.context = context;
   }

   protected void onPreExecute() {
      progressDialog = ProgressDialog.show(context, "", "msg", true); 
   }

  protected Long doInBackground(URL... urls) {
       //add here your json part
  }

 protected void onPostExecute(Long result) {
     progressDialog.dismiss();

     Intent ni = null;                           
                        ni = new Intent(Tab1.this, com.bucheuw.gollege.portal.DashboardActivity.class);
                        Bundle b = new Bundle();
                        b.putString("par_kode", kode);
                        ni.putExtras(b);
                        startActivity(ni);  
 }
}

答案 1 :(得分:0)

您可能遇到的问题是NetworkOnMainThreadException

从ICS及以上版本中,Android将不允许在UI线程中进行任何网络操作。它应该在单独的线程中完成,因此它不会挂起UI。在单独的线程中尝试您的网络通信代码。