在Android中异步填充数据的简单活动

时间:2013-08-20 13:59:09

标签: android json

我正在尝试将数据从JSON填充到android Activity异步

my JSON URL :: http://54.218.73.244:7002/RestaurantTimings

JSON STRUCTURE ::

[
    {
        "_id": 1,
        "RestaurantTime": "8pm to 11pm"
    },
    {
        "_id": 2,
        "RestaurantTime": "10pm to 12pm"
    },
    {
        "_id": 3,
        "RestaurantTime": "11pm to 9pm"
    },
    {
        "_id": 4,
        "RestaurantTime": "10pm to 5pm"
    }
]

以下是我尝试过的代码::

  • 该活动有三个我需要填充的文字视图
  • 我已经解析了数据并存储在集合中
  • 但我不知道如何将数据填充到textview'

activity_main.xml中

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" >



    <TextView
        android:id="@+id/restaurantTimings1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:text="TextView" />

    <TextView
        android:id="@+id/restaurantTimings2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/textView2"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="133dp"
        android:text="TextView" />

    <TextView
        android:id="@+id/restaurantTimings3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/restaurantTimings3"
        android:layout_below="@+id/restaurantTimings3"
        android:text="TextView" />

</RelativeLayout>

MainActivity.java

public class MainActivity extends Activity {


    private static String url1 = "http://54.218.73.244:7002/RestaurantTimings";
    private HashMap<Integer, String> TimeMap=new HashMap<Integer, String>();
    List<Item> yourData = new ArrayList<Item>();


    ProgressDialog progressDialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //instantiating progressDialog
        progressDialog=new ProgressDialog(MainActivity.this);
        new ParsingAsync().execute();

    }

    private class ParsingAsync extends AsyncTask<Void, Void, Void>{
        @Override
        protected void onPreExecute() {
            // TODO Auto-generated method stub
            super.onPreExecute();
            progressDialog=ProgressDialog.show(MainActivity.this, "", "Please Wait .. ", true, false);
        }

        @Override
        protected Void doInBackground(Void... params) {
            // TODO Auto-generated method stub  
            JSONObjParser jParser=new JSONObjParser();
            JSONArray json1=jParser.getJSONFromUrl(url1);

            try{
                for(int i=0;i<json1.length();i++){
                    JSONObject c=json1.getJSONObject(i);
                    Item item=new Item();
                    int id=c.getInt("_id");
                    String TIME=c.getString("RestaurantTime");
                    yourData.add(item);
                }

            }catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }


            return null;
        }

        @Override
        protected void onPostExecute(Void result) {
            // TODO Auto-generated method stub
            super.onPostExecute(result);
            progressDialog.dismiss();

            TextView TV1=(TextView) findViewById(R.id.restaurantTimings1);



        }

    }



}

JSONObjParser.java

public class JSONObjParser {

    static InputStream is = null;
    static JSONArray jObj = null;
    static String json = "";

    // constructor
    public JSONObjParser() {

    }

    public JSONArray getJSONFromUrl(String url) {

        // Making HTTP request
        try {
            // defaultHttpClient
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpGet httpGet = new HttpGet(url);

            HttpResponse httpResponse = httpClient.execute(httpGet);
            HttpEntity httpEntity = httpResponse.getEntity();
            is = httpEntity.getContent();           

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    is, "iso-8859-1"), 8);
            StringBuilder sb = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
            is.close();
            json = sb.toString();
        } catch (Exception e) {
            Log.e("Buffer Error", "Error converting result " + e.toString());
        }

        // try parse the string to a JSON object
        try {
            jObj = new JSONArray(json);

        } catch (JSONException e) {
            Log.e("JSON Parser", "Error parsing data " + e.toString());
        }

        // return JSON String
        return jObj;

    }
}

Item.java

public class Item {
    private String Time;

    public String getTime() {
        return Time;
    }

    public void setTime(String Time) {

        this.Time=Time;
    }


}

  • 我已完成代码的大部分内容
  • 但我很难完成onPostExecute方法

AnyIdeas

1 个答案:

答案 0 :(得分:0)

您可能希望从ListActivity而不是Activity派生您的活动,并调用setListActivity(yourData)(可能没有必要调用setContentView()因为ListView会为您处理)

在onPostExecute中,您可以调用yourData.NotifyDataSetChanged(),这将更新屏幕。

但是如果你真的想要硬编码应用程序以正好显示三家餐馆,你可以使用findViewById(R.id.restaurantTimingsN).setText([new value])来改变TextViews的内容.. < / p>