java - 在android中解析JSON返回null对象

标签 java android json android-asynctask

我正在尝试使用JSON获取信息并将其显示在屏幕上,获取信息的url如下:

https://searchcode.com/api/codesearch_I/?q=quicksort&per_page=100

JSON 如下:

"results": [
{
"repo": "https://github.com/robtsai/mathrocks.git",
"language": "Haskell",
"linescount": 8,
"location": "/algos_datastructures",
"name": "mathrocks",
"url": "https://searchcode.com/codesearch/view/71123349/",
"md5hash": "78fd0c4174ad9af35885b1275db3c805",
"lines": {
"1": "-- quicksort in haskell",
"2": "",
"3": "quicksort :: Ord a => [a] -> [a]",
"4": "quicksort [] = []",
"5": "quicksort (x:xs) = quicksort smallerHalf ++ [x] ++ quicksort largerHalf",
"6": "\twhere"
},
"id": 71123349,
"filename": "quicksort.hs"
},

在这里,我试图获取 namelanguageurl 属性。问题是 namelanguage 属性都返回各自的值,但 url 属性没有,它返回 null。

代码如下:

ResultsList.java

public class ResultsList extends ListActivity {

private ProgressDialog pDialog;

// URL to get contacts JSON
private static String urlmain = "https://searchcode.com/api/codesearch_I/?q=";
private static final String addition="&per_page=100";

// JSON Node names
private static final String ARR_RESULTS="results";
private static final String OBJ_NAME="name";
private static final String OBJ_LANG="language";
private static final String OBJ_URL="url";

// Seach term
private static final String SEARCH_KEYWORD = "seachterm";

// contacts JSONArray
JSONArray contacts = null;

// Hashmap for ListView
ArrayList<HashMap<String, String>> resultsList;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_results_list);

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

    ListView listView=getListView();

    listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            // getting values from selected ListItem
            String name = ((TextView) view.findViewById(R.id.nameofrepo))
                    .getText().toString();
            String lang=((TextView) view.findViewById(R.id.langofrepo))
                    .getText().toString();
            String urlcode = ((TextView) view.findViewById(R.id.urlofcode))
                    .getText().toString();

            Intent intent=new Intent(getApplicationContext(),
                    DisplayResults2.class);
            intent.putExtra(OBJ_NAME, name);
            intent.putExtra(OBJ_LANG,lang);
            intent.putExtra(OBJ_URL, urlcode);
            startActivity(intent);

        }
    });

    Intent intent1=getIntent();

    String search_item=intent1.getStringExtra(SEARCH_KEYWORD);

    // Calling async task to get json
    new GetContacts().execute(search_item);

}


/**
 * Async task class to get json by making HTTP call
 * */
class GetContacts extends AsyncTask<String, Void, Void> {

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        // Showing progress dialog
        /*pDialog = new ProgressDialog(ResultsList.this);
        pDialog.setMessage("Please wait...");
        pDialog.setCancelable(false);
        pDialog.show();*/

    }

    @Override
    protected Void doInBackground(String... search_term) {
        // Creating service handler class instance
        ServiceHandler sh = new ServiceHandler();

        // Making a request to url and getting response
        String jsonStr = sh.makeServiceCall(urlmain+
                URLEncoder.encode(search_term[0])+addition, ServiceHandler.GET);

        Log.d("search term: ", "> " + search_term[0]);
        Log.d("Response: ", "> " + jsonStr);

        if (jsonStr != null) {
            try {
                JSONObject jsonObj = new JSONObject(jsonStr);

                // Getting JSON Array node
                contacts = jsonObj.getJSONArray(ARR_RESULTS);

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

                    String name = c.getString(OBJ_NAME);
                    String lang = c.getString(OBJ_LANG);
                    String url = c.getString(OBJ_URL);


                    // tmp hashmap for single contact
                    HashMap<String, String> single_result = new HashMap<String, String>();

                    single_result.put(OBJ_NAME, name);
                    single_result.put(OBJ_LANG, lang);
                    single_result.put(OBJ_URL, url);

                    // adding contact to contact list
                    resultsList.add(single_result);
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        } else {
            Log.e("ServiceHandler", "Couldn't get any data from the url");
        }

        return null;
    }

    @Override
    protected void onPostExecute(Void result) {
        super.onPostExecute(result);
        // Dismiss the progress dialog
        /*if (pDialog.isShowing())
            pDialog.dismiss();*/
        /**
         * Updating parsed JSON data into ListView
         * */
        ListAdapter adapter = new SimpleAdapter(ResultsList.this,
                resultsList, R.layout.row_item2, new String[] { OBJ_NAME,
                OBJ_LANG,OBJ_URL }, new int[] { R.id.nameofrepo, R.id.langofrepo,
                R.id.url });


        setListAdapter(adapter);
    }

}
}

这里我使用了 AsyncTask 来获取 JSON 对象。然后结果显示在 listview 中。

String url = c.getString(OBJ_URL);之后,我使用Log来检查url的值是否为返回 null。

Log.d("URL : ",url);

它给了我 logcat 显示这个:

D/URL :: https://searchcode.com/codesearch/view/71123349/
02-23 12:52:31.950 12979-13078/com.example.shaloin.codesearch D/URL :: https://searchcode.com/codesearch/view/46026229/
02-23 12:52:31.950 12979-13078/com.example.shaloin.codesearch D/URL :: https://searchcode.com/codesearch/view/36082147/
02-23 12:52:31.950 12979-13078/com.example.shaloin.codesearch D/URL :: https://searchcode.com/codesearch/view/49572716/
02-23 12:52:31.951 12979-13078/com.example.shaloin.codesearch D/URL :: https://searchcode.com/codesearch/view/116169728/
02-23 12:52:31.951 12979-13078/com.example.shaloin.codesearch D/URL :: https://searchcode.com/codesearch/view/39926774/
02-23 12:52:31.951 12979-13078/com.example.shaloin.codesearch D/URL :: https://searchcode.com/codesearch/view/107357332/
02-23 12:52:31.951 12979-13078/com.example.shaloin.codesearch D/URL :: https://searchcode.com/codesearch/view/114502986/
02-23 12:52:31.951 12979-13078/com.example.shaloin.codesearch D/URL :: https://searchcode.com/codesearch/view/51628740/
02-23 12:52:31.951 12979-13078/com.example.shaloin.codesearch D/URL :: https://searchcode.com/codesearch/view/49574358/
02-23 12:52:31.951 12979-13078/com.example.shaloin.codesearch D/URL :: https://searchcode.com/codesearch/view/100236697/
02-23 12:52:31.951 12979-13078/com.example.shaloin.codesearch D/URL :: https://searchcode.com/codesearch/view/76176571/
02-23 12:52:31.951 12979-13078/com.example.shaloin.codesearch D/URL :: https://searchcode.com/codesearch/view/55589993/
02-23 12:52:31.951 12979-13078/com.example.shaloin.codesearch D/URL :: https://searchcode.com/codesearch/view/65881790/
02-23 12:52:31.951 12979-13078/com.example.shaloin.codesearch D/URL :: https://searchcode.com/codesearch/view/46430083/
02-23 12:52:31.951 12979-13078/com.example.shaloin.codesearch D/URL :: https://searchcode.com/codesearch/view/49572625/
02-23 12:52:31.951 12979-13078/com.example.shaloin.codesearch D/URL :: https://searchcode.com/codesearch/view/49572701/
02-23 12:52:31.951 12979-13078/com.example.shaloin.codesearch D/URL :: https://searchcode.com/codesearch/view/49574429/
02-23 12:52:31.951 12979-13078/com.example.shaloin.codesearch D/URL :: https://searchcode.com/codesearch/view/65259684/
02-23 12:52:31.951 12979-13078/com.example.shaloin.codesearch D/URL :: https://searchcode.com/codesearch/view/119281487/

所以,我猜这意味着 url 已正确获取,但由于某些原因未显示。

最佳答案

除了在 onPostExecute 方法中更改 ListAdapter 中的 textview id 之外,您的代码工作正常

如下所示..

改变这个。

  R.id.url 

 R.id.urlofcode 

这是你的输出

enter image description here

当您单击 ListView 时,将获得这些值..

这是日志

D/Output: Name =mathrocks url =Haskell urlcode =https://searchcode.com/codesearch/view/71123349/

关于java - 在android中解析JSON返回null对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48942097/

相关文章:

android - CardView 的 OnClickListener?

python - 无法打开/查看 Yelp 数据集

java - 需要在没有 wsdl 的情况下调用 soap ws

java - 使用 Java 实现 powerpoint 转换/动画

java - 使用 javascript 在上传文件时执行两个操作。文件和文件详细信息不会传递到 javascript 函数

jQuery .ajax post 因大型 JSON 对象而失败

json - ElasticSearch,特定字段不返回

java - 将 JSON 字符串序列化为对象

android - Android map 的自行车图层

android - 文本在 EditText 中被 ImageSpan 弄乱了