2013-01-21 77 views
2

我有問題關於json在android 我目前有2個類的代碼是JSONParser.java和Tab1.java登錄函數。 這將在android 2.3.3及更低版本中像魅力一樣工作,但如果超過它,它將不起作用。 (蜂窩,ICS,JB) 我對這個問題進行了搜索,我發現它與asynctask有關,但我仍然不明白如何在我的代碼中實現它。 對不起,問新手問題,我感謝你的幫助 以前感謝。問題與JSON在Android 2.3以上(薑餅)

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) 
+1

發佈logcat錯誤行。 –

回答

2

這是因爲在以後的版本中,你不能這樣做在主線程的網絡連接..
要使用一個AsyncTask ..

pr ivate類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); 
} 
} 
+0

我建議使用上面的代碼並顯示一個ProgressDialog,直到它從服務器獲取數據。 –

0

,可能你所面對的問題是,因爲NetworkOnMainThreadException的。

從ICS和以上版本的Android不會允許在UI線程中的任何網絡操作。它應該在單獨的線程中完成,以便它不會掛起UI.Try您的網絡通信代碼在單獨的線程中。