使用 AsyncTask 从 JSON 中获取数据

Posted

技术标签:

【中文标题】使用 AsyncTask 从 JSON 中获取数据【英文标题】:Fetching Data from JSON using AsyncTask 【发布时间】:2016-10-26 17:11:12 【问题描述】:

我创建了一个片段,如果它被激活,它将显示 mysql 数据,但它需要时间来获取数据并将其显示在自定义 ListView 上。

我尝试实现 AsyncTask,以便在获取数据时您可以在等待时对片段执行其他操作,但出现此错误。

“致命异常:main java.lang.NullPointerException”

这里是代码

public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)

    View rootView = inflater.inflate(R.layout.fragment_markets,container,false);

    //lvMarkets.setAdapter(new CustomAdapter(getActivity().getApplicationContext(),Symbols,Prices,Balances));
    DBHelper db = new DBHelper(getActivity().getApplicationContext());
    final ListView lvMarkets = (ListView)getActivity().findViewById(R.id.lvMarkets);
    final String c_androidid    =   Settings.Secure.getString(getActivity().getContentResolver(), Settings.Secure.ANDROID_ID);
    final Cursor rs = db.getID(c_androidid);
    rs.moveToFirst();
    final String c_login = rs.getString(rs.getColumnIndex(DBHelper.c_login));

    AsyncTaskRunner taskRunner = new AsyncTaskRunner();
    taskRunner.execute(c_login);
    lvMarkets.setAdapter(jAdapter);
    return rootView;


private class AsyncTaskRunner extends AsyncTask<String,String,String>


    @Override
    protected String doInBackground(String... params)
    
        final String fin_login=params[0];
        StringRequest stringRequest = new StringRequest(Request.Method.POST,url, new Response.Listener<String>() 
            @Override
            public void onResponse(String response)
            
                Log.d(debug,response);
                try
                
                    jsonArray =new JSONArray(response);
                    jAdapter= new JsonAdapter(getActivity(),jsonArray,login);
                
                catch (JSONException e)
                
                    Log.d(debug,e.toString());
                
            
        , new Response.ErrorListener()
        
            public void onErrorResponse(VolleyError error)
            
                Log.d(debug,error.toString());
            
        )
            @Override
            protected Map<String,String>getParams()
            
                Map<String,String> params=new HashMap<String,String>();
                params.put("c_login",fin_login);
                return params;
            
        ;
        RequestQueue queue = Volley.newRequestQueue(getActivity().getApplicationContext());
        queue.add(stringRequest);

        return fin_login;
    

希望有人能指出我的代码出了什么问题,也希望有人能指出如何更快地在线获取数据。

谢谢...

【问题讨论】:

如果您能提供完整的错误日志,将会有很大帮助。 【参考方案1】:
 Try this:
      private void parsingValues() 

    URL obj = null;
    HttpURLConnection con = null;
    String USER_AGENT = "Mozilla/5.0";
    try 
           //parameter to post
        String POST_PARAMS = "deviceos=" + deveiceOs + "&devicetype=" + deviceType +"&deviceid=" ;
        obj = new URL("Your URI");
        con = (HttpURLConnection) obj.openConnection();
        con.setRequestMethod("POST");
        con.setRequestProperty("User-Agent", USER_AGENT);
        // For POST only - START
        con.setDoOutput(true);
        OutputStream os = con.getOutputStream();
        os.write(POST_PARAMS.getBytes());
        os.flush();
        os.close();
        int responseCode = con.getResponseCode();
        System.out.println("POST Response Code :: " + responseCode);

        if (responseCode == HttpURLConnection.HTTP_OK)  //success
            BufferedReader in = new BufferedReader(new InputStreamReader(
                    con.getInputStream()));
            String inputLine;
            StringBuffer response = new StringBuffer();
            while ((inputLine = in.readLine()) != null) 

                response.append(inputLine);
            
            in.close();
           //getResponse
            String subsResponse = response.toString();
            final JSONObject responsesubs = new JSONObject(subsResponse);
          //Here your parsing process
                    
                
            );
         else 
            System.out.println("POST request not worked");
        
     catch (Exception e) 
        e.printStackTrace();
    


// Call this method to your doinbackground of Asynhronous Task(parsingValues())

【讨论】:

以上是关于使用 AsyncTask 从 JSON 中获取数据的主要内容,如果未能解决你的问题,请参考以下文章

Android AsyncTask 无法从 php-mysql 检索 JSON 字符串

text 使用AsyncTask和okHttp&JSON解析获取API数据

如何从选项卡片段中的 AsyncTask Resftful WS 加载批量数据

Asynctask结果显示重新创建片段后

使用 AsyncTask 从 URL 获取数据到数组列表中

Android:使用 Asynctask 时 Recyclerview 出现问题