从JSON在Android的生成列表视图 [英] Generate listview from JSON in android

查看:258
本文介绍了从JSON在Android的生成列表视图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是完全新的Andr​​oid和现在试图生成JSON数组这是从我的服务器拉列表视图,我读了很多教程,没有运气,有独特的方式来做到这一点。能不能请,点一些资源好的开始。

I am completely new to Android and currently trying to generate listview from JSON array which was pulled from my server, I have read a lot of tutorials with no luck, there is unique way to do that. Could you, please, point some resources good to start.

我已经阅读页但是我坚持以下code:

I have read this page however I am stuck with the following code:

import josecgomez.com.android.dev.webservice.objects.alerts;

给我因为没有标识的资源:

giving me "" as no identified resource:

public class AlertsAdapter extends ArrayAdapter<alerts>

感谢您,任何帮助是极大的AP preciated!

Thank you, any help is greatly appreciated!

推荐答案

JSON &放大器; 列表视图会像这样工作。

JSON & listview ll work like this..

1.displaying项目的列表

Android SDK提供了一个便捷的方式快速显示使用超类android.app.ListActivity数据的列表。该活动已经提供了一个内容查看,配置了的ListView ,准备使用和填充数据。

The Android SDK provides a convenient way to quickly display a list of data using a superclass called android.app.ListActivity. This Activity already provides a ContentView, configured with a ListView, ready to use and populate with data.

的的ListView现在需要给予要显示的数据,以及映射的数据到行的装置。 ListAdaptors提供这种机制和使用setListAdaptor ListActivity底层的ListView上的设置。

The ListView now needs to be given data to display, along with a means to map that data into rows. ListAdaptors provide this mechanism and are set on the underlying ListView of the ListActivity using setListAdaptor.

这是Android SDK中提供的适配器(ArrayAdaptor),它知道如何处理任意数据数组到列表视图(本Android SDK中还附带了其他几个 ListAdaptors ,如光标适配器,当连接本地数据存储到ListView,可以协助)。还需要提供一种具有布局它可以使用来呈现的元素到各行的适配器。在下面的例子中,我们使用的是Android SDK中提供的布局,simple_list_item_1管理,这是一个单一的文本标签完美铺设了单一字符串:

An Android SDK provided adaptor (ArrayAdaptor) that knows how to handle arrays of arbitrary data into ListViews (The Android SDK also comes with several other ListAdaptors, such as Cursor Adaptors, which can assist when connecting local data storage to a ListView). You also need to provide the adaptor with a layout it can use to render the elements onto each row. In the example below we are using the Android SDK provided layout, simple_list_item_1, which is a single text label–perfect for laying our single strings:

String[] elements = {"Line 1", "Line 2"};
setListAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, elements));

2.customizing各列表项的外观

为了实现这一目标,你必须超越内置的布局和ArrayAdaptor和实现自己的吧。

In order to achieve this you will have to move beyond the inbuilt layout and ArrayAdaptor and implement your own instead.

通过创建一个ABC类,可用于同时容纳作者和内容的字符串开始。然后创建并填充物用一些测试数据显示在自定义列表项:

Start by creating a class ABC that can be used to hold both the author and the content as Strings. Then create and populate a object with some test data to be displayed in the custom list item:

public class ABC{
     String userId;
     String pwd;
}

在创建 /res/layout/list_item.xml 布局的XML文件来定义两个 TextViews 显示内容和作者的不同行。为了显示他们一个在另一个之上,使用的LinearLayout,配置成在其垂直(安卓方向=垂直)呈现的每个元素。

Create a layout XML file in /res/layout/list_item.xml to define two TextViews to display the content and author on separate rows. In order to display them one above the other, use a LinearLayout, configured to render each element within it vertically (android:orientation="vertical").

在XML文件被创建,Android的Eclipse插件会自动将其添加为引用到生成的R档。该R文件保存在你的项目/根文件夹,作为你的XML元素和你的Java code之间的桥梁。它可以让你的Java code参考下/ RES文件夹中创建XML元素和文件。您刚才创建的文件现在可以被引用为 R.layout.list_item 在Java code,你会做下一个自定义列表中的适配器。

Once the XML file has been created, the Android Eclipse plugin will automatically add it as a reference into the generated R file. This R file is kept under the /gen folder of your project and acts as a bridge between your XML elements and your Java code. It allows your Java code to reference XML elements and files created under the /res folders. The file you have just created can now be referenced as R.layout.list_item in the Java code, as you will do next in the custom list adaptor.

创建一个名为 ListAdaptor 其子类 ArrayAdaptor 私有类(活动内部)。此类应用于存储一个ArrayList被显示,以及提供一种方式来映射对象到 TextViews 在上面的布局创建

Create a private class (inside the Activity) called ListAdaptor which subclasses ArrayAdaptor. This class should be used to store an ArrayList being displayed, as well as providing a way to map the objects to the TextViews you created in the layout above.

此映射覆盖ListAdaptor,并应在所要求的位置返回用该数据填充的内容的查看对象。

This mapping overrides the ListAdaptor, and should return a View object populated with the contents of the data at the requested position.

的完整实现自定义abcListAdaptor的是如下:

The complete implementation of the custom abcListAdaptor is below:

private class abcListAdaptor extends ArrayAdapter<abc> {  
    private ArrayList<abc> abc;  
    public abcListAdaptor(Context context,  
                                int textViewResourceId,  
                                ArrayList<abc> items) {  
             super(context, textViewResourceId, items);  
             this.abc= items;  
    }  
    @Override  
    public View getView(int position, View convertView, ViewGroup parent) {  
            View v = convertView;  
            if (v == null) {  
                    LayoutInflater vi = (LayoutInflater) getSystemService                          
(Context.LAYOUT_INFLATER_SERVICE);  
                    v = vi.inflate(R.layout.list_item, null);  
            }  
            abc o = abc.get(position);  
            TextView tt = (TextView) v.findViewById(R.id.uid);  
            TextView bt = (TextView) v.findViewById(R.id.pwd);  
            tt.setText(o.userid);  
            bt.setText(o.pwd);  
            return v;  
    }  
 }  

现在的onCreate方法可以调节以使用自定义列表适配器与所创建的测试数据,如下所示:

Now the onCreate method can be adjusted to use the custom list adaptor with the created test data as shown below:

public void onCreate(Bundle savedInstanceState) {  
super.onCreate(savedInstanceState);  
abc a= new abc();  
a.userid= "tech";  
a.pwd= "android";  
ArrayList<abc> items = new ArrayList<abc>();  
items.add(a);  
abcListAdaptor adaptor = new abcListAdaptor(this,R.layout.list_item, items);  
setListAdapter(adaptor);  
}  

3.accessing远程服务和分析数据

Android SDK中包含的软件包旨在简化访问基于HTTP的API。 Apache的HTTP类已经被包括在内,根据 org.apache.http包中可以找到。您将使用这些类,随着 org.json 类分析从服务器回来的数据。

The Android SDK contains packages aimed at simplifying access to HTTP-based APIs. The Apache HTTP classes have been included and can be found under the org.apache.http package. You’ll be using these classes, along with the org.json classes to parse the data coming back from a server.

我们可以创建活动一个私有方法,使一个请求,分析结果,并返回对象的的ArrayList 。下面列出的code发出请求并寻找产生的 JSON数组,这是重复提取每个文本和FROM_USER元素。

we can create a private method in the Activity that makes a request, parses the result, and returns an ArrayList of objects. The code listed below makes the request and looks for the resulting JSON array, which is iterated to extract each text and from_user elements.

ArrayList<abc> getDetail= new ArrayList<abc>();  
    try {  
            HttpClient hc = new DefaultHttpClient();  
            HttpGet get = new  
            HttpGet("<a href="http://your URL"></a>");  
            HttpResponse rp = hc.execute(get);  
            if(rp.getStatusLine().getStatusCode() == HttpStatus.SC_OK)  
            {  
                    String result = EntityUtils.toString(rp.getEntity());  
                    JSONObject root = new JSONObject(result);  
                    JSONArray sessions = root.getJSONArray("results");  
                    for (int i = 0; i < sessions.length(); i++) {  
                            JSONObject session = sessions.getJSONObject(i);  
                            abc a= new abc();  
                            a.uid= session.getString("user");  
                            a.pwd= session.getString("password");  
                            getDetail.add(a);  
                    }  
            }  
    } catch (Exception e) {  
            Log.e("Activity", "Error loading JSON", e);  
    }  

现在代替你$ P $在onCreate方法构建自定义列表适配器时pviously用于调用加载方法的虚拟数据。

Now replace the dummy data you previously used with a call to the load method when constructing the custom list adaptor in the onCreate method.

abcListAdaptor adaptor = new abcListAdaptor(this,R.layout.list_item, load());  

4.creating响应的用户界面

在code在当前状态下有可能导致应用程序无响应(ANR)对话框出现,提示退出你的应用程序用户的潜力。这可能是由于在制作方法,如的onCreate 正在执行远程数据请求的长时间运行的工作。

The code in its current state has the potential to cause an Application Not Responding (ANR) dialog to appear, prompting the user to quit your app. This can occur due to the long-running work of making a remote request for data being performed within methods such as onCreate.

长时间运行的任务不应该在主应用程序线程(驱动用户界面事件循环)上进行。相反,它们应该被催生扎进子线程来执行工作。

Long-running tasks should never be performed on the main application thread (which drives the user interface event loop). They should instead be spawned off into child threads to perform the work.

尽管Java的类可用于这个任务,有一种并发症,一旦长时间运行的任务完成后,一般要改变用户界面报告结果(即,显示的负载从请求列表)。

While Java’s Thread class can be used for this task, there is a complication in that once the long-running task is complete, it generally wants to change the user interface to report the results (that is, display a list of loaded from a request).

用户界面元素只能有自己的状态,改变从主线程,作为Android的UI工具包是不是线程安全的,因此后台线程需要消息回以操纵UI主线程。

User interface elements can only have their state altered from the main thread, as the Android UI toolkit is not thread-safe, therefore the background thread needs to message back to the main thread in order to manipulate the UI.

值得庆幸的是,Android的SDK提供了一个方便的类AsyncTask的,它提供了一种简单的机制,异步任务与UI线程安全的交互。这是通过继承AsyncTask的并覆盖doInBackground方法来执行长时间运行的任务,然后覆盖onPostExecute对用户界面进行任何操作来实现的。

Thankfully, the Android SDK provides a convenient class AsyncTask, which provides an easy mechanism for asynchronous tasks to interact safely with the UI thread. This is achieved by subclassing AsyncTask and overriding the doInBackground method to perform the long-running task, then overriding onPostExecute to perform any manipulations on the UI.

当创建AsyncTask的(它必须在UI线程上创建)和执行时,doInBackground方法调用在后台线程。完成后,将onPostExecute方法被调用背面的主UI线程。

When the AsyncTask is created (it has to be created on the UI thread) and executed, the doInBackground method is invoked on a background thread. On completion, the onPostExecute method is invoked back on the main UI thread.

要在应用中使用它,你需要的活动(如自定义适配器类)呼吁MyTask的,它的子类的AsyncTask中实现的私有类。您可以使用previous负荷方法的内容覆盖doInBackground方法。

To use this in your app, you will need to implement a private class within the Activity (like the custom adaptor class) called MyTask, which subclasses AsyncTask. You can override the doInBackground method with the contents of your previous load method.

而不是被退货ArrayList中,你在活动保持一个实例变量,使得数据可以通过专用的类共享。然后在onPostExecute可以设置列表适配器的数据,是在做的onCreate previously。该onCreate方法现在只需创建MyTask的对象,并调用execute方法。

Instead of the ArrayList being returned, you maintain an instance variable in the Activity so that the data can be shared across the private classes. Then in the onPostExecute you can set the List Adaptor with the data, as was done previously in onCreate. The onCreate method now simply creates the MyTask object and calls the execute method.

最佳的网站 >&安培;

-

问候

TechEnd

这篇关于从JSON在Android的生成列表视图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆