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

时间:2014-02-26 09:52:13

标签: android json android-widget widget

请我需要帮助,我是新手,我怎么能创建一个小部件,从Android中的Json获取它的源代码。是否有一个有用的教程,可以帮助我或我可以看到的源代码。我在网上查了一个合适的tutorail,但我发现没有一个可以直接帮助。这是我想要传递到我的android小部件的json url feed:url

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

}

2 个答案:

答案 0 :(得分:0)

签出GSON library,它将创建带有JSON内容的Java对象,并在你的小部件中使用它

答案 1 :(得分:0)

  

这是一个很好的教程,可以导入json数据http://mrbool.com/how-to-use-json-to-parse-data-into-android-application/28944   如果它对你很难。我可以建议你一件事,你可以将你的rss导入任何网站,并根据你的需要在那里自定义它,并将它们作为json数据发布,我猜想会更容易。   它只是对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");
    }