2015-10-26 39 views
-7

我想從服務器解析json,當我使用Activity而不是Fragment時,我成功了。現在我收到錯誤,並且在互聯網上搜索,但無法解決。JSON解析fragnd

ContentFragmant.java

import android.app.ProgressDialog; 
import android.content.Intent; 
import android.os.AsyncTask; 
import android.os.Bundle; 
import android.support.v4.app.Fragment; 
import android.util.Log; 
import android.view.LayoutInflater; 
import android.view.View; 
import android.view.ViewGroup; 
import android.widget.AdapterView; 
import android.widget.ListAdapter; 
import android.widget.ListView; 
import android.widget.SimpleAdapter; 
import android.widget.TextView; 

import xxx.FUNCTIONS.GetServerAddress; 
import xxx.FUNCTIONS.JSONParser; 
import xxx.WORKERS.DetailWorkerActivity; 

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

import java.util.ArrayList; 
import java.util.HashMap; 
import java.util.List; 

import cz.msebera.android.httpclient.NameValuePair; 

/** 
* Created by Admin on 04-06-2015. 
*/ 
public class ContentFragment extends Fragment { 

    // Progress Dialog 
    private ProgressDialog pDialog; 
    // Creating JSON Parser object 
    JSONParser jParser = new JSONParser(); 
    ArrayList<HashMap<String, String>> workersList; 
    static GetServerAddress gServer; 
    // url to get all workers list 
    private static String url_all_workers = gServer.SERVER_ADRESS_WORKERS + "get_all_workers.php"; 
    // JSON Node names 
    private static final String TAG_SUCCESS = "success"; 
    private static final String TAG_WORKERS = "workers"; 
    private static final String TAG_PID = "pid"; 
    private static final String TAG_NAME = "name"; 
    // workers JSONArray 
    JSONArray workers = null; 

    @Override 
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { 
     View v = inflater.inflate(R.layout.w_all_workers,container,false); 
     return v; 
    } 

    public void onViewCreated(View v, Bundle savedInstanceState) { 
     super.onViewCreated(v, savedInstanceState); 

     workersList = new ArrayList<HashMap<String, String>>(); 

     // Loading workers in Background Thread 
     new LoadAllProducts().execute(); 

    } 


    @Override 
    public void onActivityResult(int requestCode, int resultCode, Intent data) { 
    super.onActivityResult(requestCode, resultCode, data); 
     // if result code 100 
     if (resultCode == 100) { 
      // if result code 100 is received 
      // means user edited/deleted worker 
     // reload this screen again 
     Intent intent = getActivity().getIntent(); 
     getActivity().finish(); 
     startActivity(intent); 
    } 

} 

/** 
* Background Async Task to Load all worker by making HTTP Request 
* */ 
    class LoadAllProducts extends AsyncTask<String, String, String> { 
    /** 
    * Before starting background thread Show Progress Dialog 
    * */ 
    @Override 
    protected void onPreExecute() { 
     super.onPreExecute(); 
     pDialog = new ProgressDialog(getActivity()); 
     pDialog.setMessage("Loading workers. Please wait..."); 
     pDialog.setIndeterminate(false); 
     pDialog.setCancelable(false); 
     pDialog.show(); 
    } 

    /** 
    * getting All workers from url 
    * */ 


    protected String doInBackground(String... args) { 


     // Building Parameters 
     List<NameValuePair> params = new ArrayList<NameValuePair>(); 
     // getting JSON string from URL 
     JSONObject json = jParser.makeHttpRequest(url_all_workers, "GET", params); // I guess ERROR is here 

     // Check your log cat for JSON reponse 
     Log.d("All Products: ", json.toString()); 

     try { 
      // Checking for SUCCESS TAG 
      int success = json.getInt(TAG_SUCCESS); 

      if (success == 1) { 
       // workers found 
       // Getting Array of Products 
       workers = json.getJSONArray(TAG_WORKERS); 

       // looping through All Products 
       for (int i = 0; i < workers.length(); i++) { 
        JSONObject c = workers.getJSONObject(i); 

        // Storing each json item in variable 
        String id = c.getString(TAG_PID); 
        String name = c.getString(TAG_NAME); 

        // creating new HashMap 
        HashMap<String, String> map = new HashMap<String, String>(); 

        // adding each child node to HashMap key => value 
        map.put(TAG_PID, id); 
        map.put(TAG_NAME, name); 

        // adding HashList to ArrayList 
        workersList.add(map); 
       } 
      } else { 
       // no workers found 
       // Launch Add New worker Activity 

      } 
     } catch (JSONException e) { 
      e.printStackTrace(); 
     } 

     return null; 
    } 

    /** 
    * After completing background task Dismiss the progress dialog 
    * **/ 
    protected void onPostExecute(String file_url) { 
     // dismiss the dialog after getting all workers 
     pDialog.dismiss(); 
     // updating UI from Background Thread 
     getActivity().runOnUiThread(new Runnable() { 
      public void run() { 
       /** 
       * Updating parsed JSON data into ListView 
       * */ 
       ListView list = (ListView)getView().findViewById(R.id.list); 
       ListAdapter adapter = new SimpleAdapter(
         getActivity(), workersList, 
         R.layout.t_list_item, new String[]{TAG_PID, 
         TAG_NAME}, 
         new int[]{R.id.pid, R.id.name}); 
       // updating listview 
       list.setAdapter(adapter); 
       // on seleting single worker 
       // launching Edit Product Screen 
       list.setOnItemClickListener(new AdapterView.OnItemClickListener() { 

        @Override 
        public void onItemClick(AdapterView<?> parent, View view, 
              int position, long id) { 
         // getting values from selected ListItem 
         String pid = ((TextView) view.findViewById(R.id.pid)).getText() 
           .toString(); 

         // Starting new intent 
         Intent in = new Intent(getActivity(), 
           DetailWorkerActivity.class); 
         // sending pid to next activity 
         in.putExtra(TAG_PID, pid); 

         // starting new activity and expecting some response back 
         startActivityForResult(in, 100); 
        } 
       }); 
      } 
     }); 

    } 

} 
} 

Jsonparser.java

import android.util.Log; 

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 java.io.UnsupportedEncodingException; 
import java.util.List; 

import cz.msebera.android.httpclient.HttpEntity; 
import cz.msebera.android.httpclient.HttpResponse; 
import cz.msebera.android.httpclient.NameValuePair; 
import cz.msebera.android.httpclient.client.ClientProtocolException; 
import cz.msebera.android.httpclient.client.entity.UrlEncodedFormEntity; 
import cz.msebera.android.httpclient.client.methods.HttpGet; 
import cz.msebera.android.httpclient.client.methods.HttpPost; 
import cz.msebera.android.httpclient.client.utils.URLEncodedUtils; 
import cz.msebera.android.httpclient.impl.client.DefaultHttpClient; 


public class JSONParser { 

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

    // constructor 
    public JSONParser() { 

    } 

    // function get json from url 
    // by making HTTP POST or GET mehtod 
    public JSONObject makeHttpRequest(String url, String method, 
      List<NameValuePair> params) 
    { 

     // Making HTTP request 
     try { 

      // check for request method 
      if(method == "POST"){ 
       // request method is POST 
       // defaultHttpClient 
       DefaultHttpClient httpClient = new DefaultHttpClient(); 
       HttpPost httpPost = new HttpPost(url); 
       httpPost.setEntity(new UrlEncodedFormEntity(params)); 

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

      }else if(method == "GET"){ 
       // request method is GET 
       DefaultHttpClient httpClient = new DefaultHttpClient(); 
       String paramString = URLEncodedUtils.format(params, "utf-8"); 
       url += "?" + paramString; 
       HttpGet httpGet = new HttpGet(url); 

       HttpResponse httpResponse = httpClient.execute(httpGet); 
       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; 

    } 
} 

錯誤列表

: FATAL EXCEPTION: AsyncTask #1 
: java.lang.RuntimeException: An error occured while executing doInBackground() 
: at android.os.AsyncTask$3.done(AsyncTask.java:299) 
: at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:352) 
: at java.util.concurrent.FutureTask.setException(FutureTask.java:219) 
: at java.util.concurrent.FutureTask.run(FutureTask.java:239) 
: at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230) 
: at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080) 
: at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573) 
: at java.lang.Thread.run(Thread.java:841) 
: Caused by: java.lang.SecurityException: Permission denied (missing INTERNET permission?) 
: at java.net.InetAddress.lookupHostByName(InetAddress.java:418) 
: at java.net.InetAddress.getAllByNameImpl(InetAddress.java:236) 
: at java.net.InetAddress.getAllByName(InetAddress.java:214) 
: at cz.msebera.android.httpclient.impl.conn.SystemDefaultDnsResolver.resolve(SystemDefaultDnsResolver.java:45) 
: at cz.msebera.android.httpclient.impl.conn.DefaultClientConnectionOperator.resolveHostname(DefaultClientConnectionOperator.java:259) 
: at cz.msebera.android.httpclient.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:159) 
: at cz.msebera.android.httpclient.impl.conn.ManagedClientConnectionImpl.open(ManagedClientConnectionImpl.java:304) 
: at cz.msebera.android.httpclient.impl.client.DefaultRequestDirector.tryConnect(DefaultRequestDirector.java:611) 
: at cz.msebera.android.httpclient.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:446) 
: at cz.msebera.android.httpclient.impl.client.AbstractHttpClient.doExecute(AbstractHttpClient.java:879) 
: at cz.msebera.android.httpclient.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:82) 
: at cz.msebera.android.httpclient.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:107) 
: at xxx.FUNCTIONS.JSONParser.makeHttpRequest(JSONParser.java:65) 
: at xxx.ContentFragment$LoadAllProducts.doInBackground(ContentFragment.java:115) 
: at xxx.ContentFragment$LoadAllProducts.doInBackground(ContentFragment.java:90) 
: at android.os.AsyncTask$2.call(AsyncTask.java:287) 
: at java.util.concurrent.FutureTask.run(FutureTask.java:234) 
: at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)  
: at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)  
: at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)  
: at java.lang.Thread.run(Thread.java:841)  
: Caused by: libcore.io.GaiException: getaddrinfo failed: EAI_NODATA (No address associated with hostname) 
: at libcore.io.Posix.getaddrinfo(Native Method) 
: at libcore.io.ForwardingOs.getaddrinfo(ForwardingOs.java:61) 
: at java.net.InetAddress.lookupHostByName(InetAddress.java:405) 
: at java.net.InetAddress.getAllByNameImpl(InetAddress.java:236)  
: at java.net.InetAddress.getAllByName(InetAddress.java:214)  
: at cz.msebera.android.httpclient.impl.conn.SystemDefaultDnsResolver.resolve(SystemDefaultDnsResolver.java:45)  
: at cz.msebera.android.httpclient.impl.conn.DefaultClientConnectionOperator.resolveHostname(DefaultClientConnectionOperator.java:259)  
: at cz.msebera.android.httpclient.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:159)  
: at cz.msebera.android.httpclient.impl.conn.ManagedClientConnectionImpl.open(ManagedClientConnectionImpl.java:304)  
: at cz.msebera.android.httpclient.impl.client.DefaultRequestDirector.tryConnect(DefaultRequestDirector.java:611)  
: at cz.msebera.android.httpclient.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:446)  
: at cz.msebera.android.httpclient.impl.client.AbstractHttpClient.doExecute(AbstractHttpClient.java:879)  
: at cz.msebera.android.httpclient.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:82)  
: at cz.msebera.android.httpclient.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:107)  
: at com.android4dev.navigationview.FUNCTIONS.JSONParser.makeHttpRequest(JSONParser.java:65)  
: at com.android4dev.navigationview.ContentFragment$LoadAllProducts.doInBackground(ContentFragment.java:115)  
: at com.android4dev.navigationview.ContentFragment$LoadAllProducts.doInBackground(ContentFragment.java:90)  
: at android.os.AsyncTask$2.call(AsyncTask.java:287)  
: at java.util.concurrent.FutureTask.run(FutureTask.java:234)  
: at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)  
: at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)  
: at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)  
: at java.lang.Thread.run(Thread.java:841)  
: Caused by: libcore.io.ErrnoException: getaddrinfo failed: EACCES (Permission denied) 
: at libcore.io.Posix.getaddrinfo(Native Method)  
: at libcore.io.ForwardingOs.getaddrinfo(ForwardingOs.java:61)  
: at java.net.InetAddress.lookupHostByName(InetAddress.java:405)  
: at java.net.InetAddress.getAllByNameImpl(InetAddress.java:236)  
: at java.net.InetAddress.getAllByName(InetAddress.java:214)  
: at cz.msebera.android.httpclient.impl.conn.SystemDefaultDnsResolver.resolve(SystemDefaultDnsResolver.java:45)  
: at cz.msebera.android.httpclient.impl.conn.DefaultClientConnectionOperator.resolveHostname(DefaultClientConnectionOperator.java:259)  
: at cz.msebera.android.httpclient.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:159)  
: at cz.msebera.android.httpclient.impl.conn.ManagedClientConnectionImpl.open(ManagedClientConnectionImpl.java:304)  
: at cz.msebera.android.httpclient.impl.client.DefaultRequestDirector.tryConnect(DefaultRequestDirector.java:611)  
: at cz.msebera.android.httpclient.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:446)  
: at cz.msebera.android.httpclient.impl.client.AbstractHttpClient.doExecute(AbstractHttpClient.java:879)  
: at cz.msebera.android.httpclient.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:82)  
: at cz.msebera.android.httpclient.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:107)  
: at com.android4dev.navigationview.FUNCTIONS.JSONParser.makeHttpRequest(JSONParser.java:65)  
: at com.android4dev.navigationview.ContentFragment$LoadAllProducts.doInBackground(ContentFragment.java:115)  
: at com.android4dev.navigationview.ContentFragment$LoadAllProducts.doInBackground(ContentFragment.java:90)  
: at android.os.AsyncTask$2.call(AsyncTask.java:287)  
: at java.util.concurrent.FutureTask.run(FutureTask.java:234)  
: at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)  
: at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)  
: at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)  
: at java.lang.Thread.run(Thread.java:841)  
W/ActivityManager: Force finishing activity com.android4dev.navigationview/.MainActivity 
D/dalvikvm: GC_FOR_ALLOC freed 362K, 24% free 7421K/9676K, paused 14ms, total 19ms 
I/qtaguid: Failed write_ctrl(s 1 10023) res=-1 errno=1 
W/NetworkManagementSocketTagger: setKernelCountSet(10023, 1) failed with errno -1 
W/EGL_genymotion: eglSurfaceAttrib not implemented 
I/qtaguid: Failed write_ctrl(s 0 10080) res=-1 errno=1 
W/NetworkManagementSocketTagger: setKernelCountSet(10080, 0) failed with errno -1 
Activity com.android4dev.navigationview.MainActivity has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView{52918c00 V.E..... R......D 0,0-614,96} that was originally added here 
android.view.WindowLeaked: Activity com.android4dev.navigationview.MainActivity has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView{52918c00 V.E..... R......D 0,0-614,96} that was originally added here 
at android.view.ViewRootImpl.<init>(ViewRootImpl.java:345) 
at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:239) 
at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:69) 
at android.app.Dialog.show(Dialog.java:281) 
at com.android4dev.navigationview.ContentFragment$LoadAllProducts.onPreExecute(ContentFragment.java:101) 
at android.os.AsyncTask.executeOnExecutor(AsyncTask.java:586) 
at android.os.AsyncTask.execute(AsyncTask.java:534) 
at com.android4dev.navigationview.ContentFragment.onViewCreated(ContentFragment.java:65) 
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:973) 
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1138) 
at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:740) 
at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1501) 
at android.support.v4.app.FragmentManagerImpl$1.run(FragmentManager.java:458) 
at android.os.Handler.handleCallback(Handler.java:730) 
at android.os.Handler.dispatchMessage(Handler.java:92) 
at android.os.Looper.loop(Looper.java:137) 
at android.app.ActivityThread.main(ActivityThread.java:5103) 
at java.lang.reflect.Method.invokeNative(Native Method) 
at java.lang.reflect.Method.invoke(Method.java:525) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553) 
at dalvik.system.NativeStart.main(Native Method)) 
at android.os.Looper.loop(Looper.java:137) 
at android.app.ActivityThread.main(ActivityThread.java:5103) 
at java.lang.reflect.Method.invokeNative(Native Method) 
at java.lang.reflect.Method.invoke(Method.java:525) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553) 
at dalvik.system.NativeStart.main(Native Method) 
+6

'產生的原因:java.lang.SecurityException異常:(?缺少INTERNET權限)權限被拒絕' –

+0

我只是檢查我完全忘記添加該權限。謝謝^^ –

+0

'' –

回答

2

看來你AndroidManifest.xml不同意您的應用程序訪問互聯網。

錯誤日誌中指出:

權限被拒絕(缺少INTERNET權限?)

http://developer.android.com/reference/android/Manifest.permission.html#INTERNET

字符串從Android文檔摘自|互聯網|允許應用程序打開網絡套接字。

以下行添加到您的AndroidManifest.xml允許上網:

<uses-permission android:name="android.permission.INTERNET" />