简体   繁体   English

如何将JSON RSS提要解析为Android小部件

[英]How to parse a json rss feed into an android widget

please i need help, am a rookie, how can i create a widget that get its feed from from a Json in android. 请我需要帮助,是个菜鸟,我如何创建一个小部件来从android中的Json获取其提要。 Is there a helpful tutorial that can help with this or a source code i can look at. 是否有有用的教程可以帮助您解决此问题或我可以查看的源代码。 I have checked online for a suitable tutorail but i found none that can help directly. 我已经在网上检查了合适的tutorail,但没有找到可以直接帮助的。 this is the json url feed i want to pass into my android widget:url 这是我想传递到我的Android小部件中的json url提要:url

public class MinistryNews extends SherlockListActivity { 公共类MinistryNews扩展了SherlockListActivity {

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);
    }

}

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

here is a nice tutorial for you to import json data http://mrbool.com/how-to-use-json-to-parse-data-into-android-application/28944 if its hard for you still.i can suggest you one thing ,you can import your rss to any website and customize it there as you want it to be and post them as json data it will be easier to do i guess. 这是一个很好的教程供您导入json数据http://mrbool.com/how-to-use-json-to-parse-data-into-android-application/28944,如果仍然难以完成,我可以建议一件事,您可以将rss导入到任何网站并在那里进行自定义,然后将它们发布为json数据,我想这会更容易。 its a raugh test for geting json data only the method i think its a bit easier and detail u can return the values instead of showing them in a text from the textvw 它是一个仅用于获取json数据的嘲笑测试,我认为它的方法更简单,更详细,您可以返回值,而不是将它们显示在来自textvw的文本中

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");
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM