使用webService的Android小部件

时间:2015-07-15 13:32:31

标签: java android json web-services

我是Android新手并制作一款基本上是appwidget的应用

我已经阅读了很多教程,但无法弄清楚要做什么。这是我的问题

我想创建一个包含来自RESTful Web服务的值的Android小部件。

这是我的代码:

package com.android.widget;

import java.util.List;

import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.ComponentName;
import android.content.Context;
import android.os.AsyncTask;
import android.widget.RemoteViews;

public class HelloWidget extends AppWidgetProvider {
    List<Top5> myList;
    @Override
    public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {

        start();
        new View(context, appWidgetManager,myList.get(0).getValeur());
    }

    private class View  {
        RemoteViews remoteViews;
        ComponentName thisWidget;


        public View(Context context, AppWidgetManager appWidgetManager,String x) {

            remoteViews = new RemoteViews(context.getPackageName(), R.layout.main);
            thisWidget = new ComponentName(context, HelloWidget.class);
            remoteViews.setTextViewText(R.id.tp5hausses,x);

            appWidgetManager.updateAppWidget(thisWidget, remoteViews);
        }
    } 

    public void start(){

        requestData("http://10.0.3.2:8085/BTCRestfullWebServices/market/top5");

    }

    private void requestData(String uri) {
        MyTask task = new MyTask();
        task.execute(uri);
    }
    private class MyTask extends AsyncTask<String, String, String> {

        @Override
        protected void onPreExecute() {

        }

        @Override
        protected String doInBackground(String... params) {

            String content = HttpManager.getData(params[0]);
            return content;
        }

        protected void onPostExecute(String result) {

            myList = Top5JSONParser.parseFeed(result);

        }
    }
}

JSON Parser类:

package com.coolsandie.android.widget;

import java.util.ArrayList;
import java.util.List;



import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

public class Top5JSONParser {



    public static List<Top5> parseFeed(String content) {

        try {
            //JSONArray ar = new JSONArray(content);
            JSONObject obj = new JSONObject(content);
            JSONArray ar = obj.getJSONArray("market");
            List<Top5> marketList = new ArrayList<Top5>();
            Top5 flower = null;
            for (int i = 0; i < ar.length(); i++) {



                JSONObject obj2 = ar.getJSONObject(i);
                flower = new Top5();
                JSONObject obj3 = obj2.getJSONObject("referentiel");
                flower.setValeur(obj3.getString("stockName"));
                flower.setCours(obj2.getDouble("last"));

                flower.setVar(obj2.getDouble("change"));
                flower.setVolum(obj2.getInt("volume"));
                flower.setTitre(obj2.getInt("trVolume"));

                marketList.add(flower);
            }

            return marketList;
        } catch (JSONException e) {
            e.printStackTrace();
            return null;
        }

    }

}

HTTp Manager类:

package com.android.widget;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

import android.util.Base64;
import android.util.Log;

public class HttpManager {

    public static String getData(String uri) {

        BufferedReader reader = null;

        try {
            URL url = new URL(uri);
            HttpURLConnection con = (HttpURLConnection) url.openConnection();

            StringBuilder sb = new StringBuilder();
            reader = new BufferedReader(new InputStreamReader(con.getInputStream()));

            String line;
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }

            return sb.toString();

        } catch (Exception e) {
            e.printStackTrace();

            return null;
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                    return null;
                }
            }
        }

    }
}

JSON文件:

{"market":[{"caps":"231704.58","change":"0.1","close":"9.500","cto":"0.000","high":"9.600","last":"9.510","low":"9.490","max":"9.770","min":"9.210","open":"9.490","referentiel":{"isin":"TN0003100609","stockName":"BNA","ticker":"BNA","valGroup":"11"},"seance":"2015-04-08 00:00:00.0","time":"14:04:22","trVolume":"1000","volume":"24335.0","vto":"0.000","ychange":"0.00"},{"caps":"230145.46","change":"0.0","close":"1.820","cto":"0.000","high":"1.850","last":"1.820","low":"1.790","max":"1.860","min":"1.760","open":"1.810","referentiel":{"isin":"TN0007400013","stockName":"CARTHAGE CEMENT","ticker":"CC","valGroup":"51"},"seance":"2015-04-08 00:00:00.0","time":"14:08:29","trVolume":"75","volume":"127364.0","vto":"0.000","ychange":"0.00"},{"caps":"3502.7","change":"0.05","close":"18.330","cto":"0.000","high":"18.340","last":"18.340","low":"18.100","max":"18.890","min":"17.790","open":"18.340","referentiel":{"isin":"TN0007200017","stockName":"EL WIFACK LEASING","ticker":"WIFAK","valGroup":"11"},"seance":"2015-04-08 00:00:00.0","time":"14:05:01","trVolume":"191","volume":"191.0","vto":"0.000","ychange":"0.00"},{"caps":"593141.69","change":"-0.51","close":"29.200","cto":"0.000","high":"29.500","last":"29.050","low":"29.050","max":"30.170","min":"28.430","open":"29.300","referentiel":{"isin":"TN0001100254","stockName":"SFBT","ticker":"SFBT","valGroup":"11"},"seance":"2015-04-08 00:00:00.0","time":"14:05:00","trVolume":"20186","volume":"20186.0","vto":"0.000","ychange":"0.00"}]}

我尝试了很多教程,但它仍然给了我这个错误:

java.lang.RuntimeException: Unable to start receiver com.coolsandie.android.widget.HelloWidget: java.lang.NullPointerException
at android.app.ActivityThread.handleReceiver(ActivityThread.java:2414)

java.net.SocketException: socket failed: EACCES (Permission denied)

如何使用Android小部件的Web服务?

感谢。

1 个答案:

答案 0 :(得分:0)

它的工作原理如下:)

package com.android.widget;

import java.util.ArrayList;
import java.util.List;

import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.ComponentName;
import android.content.Context;
import android.os.AsyncTask;
import android.widget.RemoteViews;

public class HelloWidget extends AppWidgetProvider {
	List<Top5> myList;
	Context context; AppWidgetManager appWidgetManager; int[] appWidgetIds;
	@Override
	public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
		this.context=context;
		this.appWidgetIds=appWidgetIds;
		this.appWidgetManager=appWidgetManager;
		start();
		
	}
	
	private class View  {
		RemoteViews remoteViews;
		ComponentName thisWidget;
		
		
	public View(Context context, AppWidgetManager appWidgetManager,String x) {
		
		remoteViews = new RemoteViews(context.getPackageName(), R.layout.main);
		thisWidget = new ComponentName(context, HelloWidget.class);
		remoteViews.setTextViewText(R.id.tp5hausses,x);
		
		appWidgetManager.updateAppWidget(thisWidget, remoteViews);
	}
	} 

	public void start(){
		
		requestData("http://10.0.3.2:8085/BTCRestfullWebServices/market/top5");

}
	
	public void Init2(){
		new View(context, appWidgetManager,myList.get(0).getValeur());
	}
	
private void requestData(String uri) {
MyTask task = new MyTask();
task.execute(uri);
}
private class MyTask extends AsyncTask<String, String, String> {
	
@Override
protected void onPreExecute() {

}

@Override
protected String doInBackground(String... params) {

String content = HttpManager.getData(params[0]);
return content;
}

protected void onPostExecute(String result) {
	myList=new  ArrayList<Top5>();
myList = Top5JSONParser.parseFeed(result);

Init2();
}

}
}