如何将 json rss 提要解析为 android 小部件



请我需要帮助,我是一个菜鸟,我如何创建一个从 android 中的 Json 获取提要的小部件。是否有有用的教程可以帮助解决这个问题或我可以查看的源代码。我已经在网上检查了合适的 tutorail,但我发现没有可以直接提供帮助。这是我想传递到我的安卓小部件中的 JSON URL 提要:URL

公共类 事工新闻扩展 夏洛克列表活动 {

private ActionBarMenu abm;
private ProgressDialog pDialog;
// URL to get contacts JSON
private static String url = "http://";
// JSON Node names
private static final String TAG_QUERY = "query";
private static final String TAG_ID = "id";
private static final String TAG_TITLE = "title";
private static final String TAG_CONTENT = "content";
// private static final String TAG_CAT_CODE = "cat_code";
// private static final String TAG_STATUS = "status";
// private static final String TAG_CREATED_TIME = "created_time";
private static final String TAG_UPDATE_TIME = "update_time";
// private static final String TAG_AUTHOR_ID = "author_id";
// contacts JSONArray
JSONArray query = null;
// Hashmap for ListView
ArrayList<HashMap<String, String>> queryList;
@SuppressWarnings("deprecation")
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_ministry_news);
    ActionBar actionbar = getSupportActionBar();
    actionbar.setDisplayHomeAsUpEnabled(true);
    abm = new ActionBarMenu(MinistryNews.this);
    if (com.cepfmobileapp.org.service.InternetStatus.getInstance(this)
            .isOnline(this)) {
        // Toast t = Toast.makeText(this,"You are online!!!!",8000).show();
        // Toast.makeText(getBaseContext(),"You are online",Toast.LENGTH_SHORT).show();
        // Calling async task to get json
        new GetQuery().execute();
    } else {
        // Toast.makeText(getBaseContext(),"No Internet Connection",Toast.LENGTH_LONG).show();
        // Toast t =
        // Toast.makeText(this,"You are not online!!!!",8000).show();
        // Log.v("Home",
        // "############################You are not online!!!!");
        AlertDialog NetAlert = new AlertDialog.Builder(MinistryNews.this)
                .create();
        NetAlert.setMessage("No Internet Connection Found! Please check your connection and try again!");
        NetAlert.setButton("OK", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                // here you can add functions
                // finish();
            }
        });
        NetAlert.show();
    }
    queryList = new ArrayList<HashMap<String, String>>();
    ListView lv = getListView();
    // Listview on item click listener
    lv.setOnItemClickListener(new 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.title))
                    .getText().toString();
            String cost = ((TextView) view.findViewById(R.id.time))
                    .getText().toString();
            String description = ((TextView) view
                    .findViewById(R.id.content)).getText().toString();
            // String plain = Html.fromHtml(description).toString();
            // description.replace(/</?[^>]+>/gi, '');
            // Starting single contact activity
            Intent in = new Intent(getApplicationContext(),
                    SingleActivity.class);
            in.putExtra(TAG_TITLE, name);
            in.putExtra(TAG_UPDATE_TIME, cost);
            in.putExtra(TAG_CONTENT, description);
            startActivity(in);
        }
    });
    // Calling async task to get json
    // new GetQuery().execute();
}
/**
 * Async task class to get json by making HTTP call
 * */
private class GetQuery extends AsyncTask<Void, Void, Void> {
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        // Showing progress dialog
        pDialog = new ProgressDialog(MinistryNews.this);
        pDialog.setMessage("Please wait..Loading news");
        pDialog.setCancelable(false);
        pDialog.show();
    }
    @Override
    protected Void doInBackground(Void... arg0) {
        // Creating service handler class instance
        ServiceHandler sh = new ServiceHandler();
        // Making a request to url and getting response
        String jsonStr = sh.makeServiceCall(url, ServiceHandler.GET);
        Log.d("Response: ", "> " + jsonStr);
        if (jsonStr != null) {
            try {
                JSONObject jsonObj = new JSONObject(jsonStr);
                // Getting JSON Array node
                query = jsonObj.getJSONArray(TAG_QUERY);
                // looping through All Contacts
                for (int i = 0; i < query.length(); i++) {
                    JSONObject c = query.getJSONObject(i);
                    String id = c.getString(TAG_ID);
                    String title = c.getString(TAG_TITLE);
                    String content = c.getString(TAG_CONTENT);
                    String update_time = c.getString(TAG_UPDATE_TIME);
                    // String address = c.getString(TAG_ADDRESS);
                    // String gender = c.getString(TAG_GENDER);
                    // Phone node is JSON Object
                    // JSONObject phone = c.getJSONObject(TAG_PHONE);
                    // String mobile = phone.getString(TAG_PHONE_MOBILE);
                    // String home = phone.getString(TAG_PHONE_HOME);
                    // String office = phone.getString(TAG_PHONE_OFFICE);
                    // tmp hashmap for single contact
                    HashMap<String, String> contact = new HashMap<String, String>();
                    // adding each child node to HashMap key => value
                    contact.put(TAG_ID, id);
                    contact.put(TAG_TITLE, title);
                    contact.put(TAG_CONTENT, content);
                    contact.put(TAG_UPDATE_TIME, update_time);
                    // contact.put(TAG_PHONE_MOBILE, mobile);
                    // adding contact to contact list
                    queryList.add(contact);
                }
            } 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(MinistryNews.this,
                queryList, R.layout.list_item, new String[] { TAG_TITLE,
                        TAG_UPDATE_TIME, TAG_CONTENT }, new int[] {
                        R.id.title, R.id.time, R.id.content });
        setListAdapter(adapter);
    }
}

这是一个很好的教程,可以让您导入 JSON 数据 http://mrbool.com/how-to-use-json-to-parse-data-into-android-application/28944 我可以向你推荐一件事,您可以将您的 RSS 导入任何网站并根据需要在那里对其进行自定义并将它们发布为 JSON 数据,我想这样做会更容易。 这是一个 raugh 测试,仅用于获取 JSON 数据,我认为这种方法更容易一些,而且很详细,您可以返回值,而不是在文本中的文本中显示它们VW

public void getdata()
{
    String result=null;
    InputStream inputstream=null;
    try{
        HttpClient httpclient=new DefaultHttpClient();
        HttpPost httppost=new HttpPost("http://www.hadid.aero/news_and_json");
        HttpResponse response=httpclient.execute(httppost);
        HttpEntity httpentity=response.getEntity();
        inputstream= httpentity.getContent();
    }
    catch(Exception ex)
    {
        resultview.setText(ex.getMessage()+"at 1st exception");
    }
    try{
        BufferedReader reader=new BufferedReader(new InputStreamReader(inputstream,"iso-8859-1"),8);
        StringBuilder sb=new StringBuilder();
        String line=null;
        while((line=reader.readLine())!= null)                  
        {
            sb.append(line +"n");
        }
        inputstream.close();
        result=sb.toString();
    }
    catch(Exception ex)
    {
        resultview.setText(ex.getMessage()+"at 2nd exception");
    }
    try{
        String s="test :";
        JSONArray jarray=new JSONArray(result);
        for(int i=0; i<jarray.length();i++)
        {
            JSONObject json=jarray.getJSONObject(i);
            s= s +"+json.getString("lastname")+"n"+
                    "newsid&title : "+json.getString("id_news")+" "+json.getString("title")+"n"+
                    "date :"+json.getString("date")+"n"+
                    "description : "+json.getString("description");
        }
        resultview.setText(s);
    }
    catch(Exception ex)
    {
        this.resultview.setText(ex.getMessage()+"at 3rd exception");
    }

查看 GSON 库,该库将使用 JSON 内容创建 Java 对象,并在您的小部件中使用它

最新更新