片段中的 JSON 解析 [关闭]
Posted
技术标签:
【中文标题】片段中的 JSON 解析 [关闭]【英文标题】:JSON parsing in fragmant [closed] 【发布时间】:2016-01-25 11:31:46 【问题描述】:我正在尝试从服务器解析 json,当我使用 Activity 而不是 Fragment 时我成功了。现在我遇到了错误,我在互联网上搜索过,但我无法解决。
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$DecorView52918c00 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$DecorView52918c00 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)
【问题讨论】:
Caused by: java.lang.SecurityException: Permission denied (missing INTERNET permission?)
我刚刚检查过,我完全忘记添加该权限。谢谢^^
<uses-permission android:name="android.permission.INTERNET" />
【参考方案1】:
您的AndroidManifest.xml
似乎没有授予您的应用访问互联网的权限。
您的错误日志指出:
权限被拒绝(缺少 INTERNET 权限?)
取自 Android 文档http://developer.android.com/reference/android/Manifest.permission.html#INTERNET
字符串 |互联网 |允许应用打开网络套接字。
将以下行添加到您的AndroidManifest.xml
以允许访问 Internet:
<uses-permission android:name="android.permission.INTERNET" />
【讨论】:
以上是关于片段中的 JSON 解析 [关闭]的主要内容,如果未能解决你的问题,请参考以下文章
Json解析器到Android中的RecyclerView? [关闭]