GVKun编程网logo

Android ArrayAdapter和JSONArray

26

对于想了解AndroidArrayAdapter和JSONArray的读者,本文将是一篇不可错过的文章,并且为您提供关于androidAdapter综合使用(ArrayAdapter、SimpleAd

对于想了解Android ArrayAdapter和JSONArray的读者,本文将是一篇不可错过的文章,并且为您提供关于android Adapter 综合使用(ArrayAdapter、SimpleAdapter、Bas、Android ArrayAdapter没有清除?、Android ArrayAdapter过滤问题、Android JSONArray到ArrayList的有价值信息。

本文目录一览:

Android ArrayAdapter和JSONArray

Android ArrayAdapter和JSONArray

我是Android开发的新手.

考虑到JSON Carrier与XML相比的轻巧性,我纯粹喜欢使用JSON Objects和Arrays作为我的简单应用程序.

我对ArrayAdapter提出了挑战,要求填充ListView.

这就是我如何克服并需要你的建议.

Extend the Adaptor class.

然后将JSONArray传递给构造函数.
这里构造函数使用设置JSONArray长度的虚拟String数组调用super.
将构造函数参数存储在类中以供进一步使用.

public myAdaptor(Context context, int resource, JSONArray array)
{
    super(context, resource, new String[array.length()]);
    // Store in the local varialbles to the adapter class.
    this.context = context;
    this.resource = resource;
    this.profiles = objects;
}

getView()将完成从JSONArray获取JSONObjects以构建视图的工作.

public View getView(int position, View convertView, ViewGroup parent)
{
    View view;
    if (convertView == null)
    {
        LayoutInflater inflater = (LayoutInflater) 
            context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        view = inflater.inflate(resource, parent, false);
    }
    else
    {
        view = convertView;
    }

    // Here 
    JSONObject item = (JSONObject) profiles.getJSONObject(position);

    // READY WITH JSONObject from the JSONArray
    // YOUR CODE TO BUILD VIEW OR ACCESS THE 
}

现在任何改进/建议/尽管问题?

解决方法:

我建议你使用谷歌GSON而不是JSON.它是一个从JSON请求中为您提供创建对象的库,您不再需要解析JSON.只需创建一个对象,其中包含JSON请求中的所有字段,并且命名相同,并且无论您想要什么,都可以使用它 – 例如:

Your JSON request
{
    [
        {
            "id": "2663",
            "title":"qwe"

        },
        {
            "id": "1234",
            "title":"asd"
        },
        {
            "id": "5678",
            "title":"zxc"
        }

    ]
}

你的类 – JSON-Array的项目

 public class MyArrayAdapterItem{
     int id;
     String title;
 }

您下载数据的代码中的Somwhere.我不知道你是怎么做的所以我会发布我的代码例如:

mGparser = new JsonParser();
Gson mGson = new Gson();

Url url = "http://your_api.com"
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestProperty("Connection", "close");
conn.connect();
BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));

JsonArray request = (JsonArray) mGparser.parse(in.readLine());
in.close();
ArrayList<MyArrayAdapterItem> items = mGson.fromJson(request, new Typetoken<ArrayList<MyArrayAdapterItem>>() {}.getType());

所以,现在只需将“items”替换为适配器构造函数中的JSON数组

android Adapter 综合使用(ArrayAdapter、SimpleAdapter、Bas

android Adapter 综合使用(ArrayAdapter、SimpleAdapter、Bas

android Adapter 综合使用(ArrayAdapter、SimpleAdapter、BaseAdapter 在 ListView 和 GridView 中的使用)

    在转载的 android Adapter 综合介绍中对 Adapter 接口及他的子接口或相关子类进行了详细的介绍,也对他的常用方法和各种子类适用在那种场所进行了介绍。接下来通过实例和代码分析来了解他的使用。

一、比较常用的有 BaseAdapter,ArrayAdapter,SimpleCursorAdapter 等。

①BaseAdapter 是一个抽象类,继承它需要实现较多的方法,所以也就具有较高的灵活性;

② ArrayAdapter 支持泛型操作,通常需要实现 getView 方法,特殊情况下(结合数据 row id),为了让 ui 事件相应处理方便点最好重写 getItemId;

③ SimpleCursorAdapter 可以适用于简单的纯文字型 ListView,它需要 Cursor 的字段和 UI 的 id 对应起来。如需要实现更复杂的 UI 也可以重写其他方法。

④ 若你的数据来源于一个 Arraylist 就使用 BaseAdapter,SimpleAdapter, 而数据来源于通过查询数据库获得 Cursor 那就使用 SimpleCursorAdapter 等。

二、ArrayAdapter 在 ListView 中使用

        该使用方法主要是以文本为内容的列表。

    1、在 xml 文件中添加 ListView 元素

        ①通过 array 元素添加 ListView 的内容     

[html] view plaincopy

  1. <ListView  

  2.                   android:layout_width="fill_parent"  

  3.                   android:layout_height="wrap_content"  

  4.                  android:entries="@array/books"       通过数组设置向列表中添加的内容  

  5.                   android:divider="@drawable/red"/>// 设置每个内容的分隔符  

        ②通过数组添加 ListView 的内容         

[html] view plaincopy

  1. <ListView  

  2.                   android:id="@+id/list"  

  3.                   android:layout_width="fill_parent"  

  4.                   android:layout_height="wrap_content">  

             在 java 代码中通过 ArrayAdapter 的对象向 ListView 中添加内容        

[java] view plaincopy

  1. ListView list = (ListView)findViewById(R.id.list);  

  2.           String []arr = {" 郑州铁路职业技术学院","无线电协会","创新室"};  

  3.           // 将数组包装 ArrayAdapter  

  4.           ArrayAdapter <String>arrayAdapter = new ArrayAdapter<String>( this,android.R.layout.simple_list_item1,arr);  

  5.           list.setAdapter(arrayAdapter);// 为 ListView 设置 Adapter  

            public ArrayAdapter (Context context, int textViewResourceId, T [] objects) 中 textViewResource 的属性值:

            simple_list_item_1:TextView

            simple_list_item_2:TextView(字体略大);

            simple_list_item_checked: 每个列表项都是一个已勾选的列表项。

            simple_list_item_multiple_choice: 每个列表都是带多选框的文本。

            simple_list_item_single_choice: 每个列表项都是带多单选按钮的文本。

            使用:

 

[java] view plaincopy

  1. list.SetOnItemClickListener(new OnItemClickListener(){  

  2.      @Override  

  3.      public void onItemClickListener(AdapterView<?>parent,View arg1,int pos,long id){  

  4.          String result= parent.getItemPosition(pos).toString();  

  5.          }});  

            ③让 Activity 继承 ListActivity 实现列表

      

[java] view plaincopy

  1. public class MainActivity ListActivity{  

  2.       @Override  

  3.       public void onCreate(Bundle savedInstanceState){  

  4.           super.onCreate(savedInstanceState){  

  5.           String[]ctype = new String[]{"郑州铁路职业技术学院","无线电协会","www.wxdxh.net"};  

  6.           ArrayAdapter<String>adapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_single_choice,ctype);  

  7.           setListAdapter(adapter);  

  8.       }}  



            使用:

[java] view plaincopy

  1. @Override  

  2.           protected void onListItemClick(ListView l,View v,int position,long id){  

  3.   

  4.               super.onListItemClick(l,v,position,id);  

  5.   

  6.                   String result = l.getItemAtPosition(position).toString();}  


        ④ArrayAdapter 类:一个管理这样的 ListView 的 ListAdapter:这个 ListView 被一个数组所支持。这个数组可装任意对象。默认状态下,这个类预期能这样:提供的资源 id 与一个单独的 TextView 相关联。如果你想用一个更复杂的 layout,就要用包含了域 id 的构造函数。这个域 id 能够与一个在更大的 layout 资源里的 TextView 相关联。它将被在数组里的每个对象的 toString () 方法所填满。你可以添加通常对象的 lists 或 arrays。重写你对象的 toString () 方法来决定 list 里哪一个写有数据的 text 将被显示。如果想用一些其它的不同于 TextView 的 view 来显示数组(比如 ImageViews),或想有一些除了 toString () 返回值所填在 views 里的以外的数据,你就要重写 getView (int,View,ViewGroup) 方法来返回你想要的 View 类型。

    三、SimapleAdapter 在 ListView 中的使用

            该使用方法主要是自定义内容的列表。

        ①、在 xml 中自定义列表中的项

            主界面元素:

     

[html] view plaincopy

  1. <ListView  

  2.   

  3.             android:layout_width="fill_parent"  

  4.   

  5.              android:layout_height="wrap_content"  

  6.   

  7.              android:id="@+id/listView1"  

  8.          >  

            自定义元素内容:

           

[html] view plaincopy

  1. <LinearLayout  

  2.                    android:orientation="horizontal"  

  3.                    andrlod:layout_width="match_parent"  

  4.                    android:layout_height="match_parent">  

  5.             <ImageView  

  6.                android:id="@+id/image"  

  7.                 android:paddingRigth="10px"      

  8.                android:paddingTop="20px"  

  9.               android:paddingBotton="20px"  

  10.   

  11.   

  12.                 android:adjustViewBounds="true"// 可以自动调整 View 的大小  

  13.   

  14.   

  15.                 android:maxWidth="72px"  

  16.   

  17.   

  18.                 android:maxHeight="72px"  

  19.   

  20.   

  21.                 android:layout_height="wrap_content"  

  22.   

  23.   

  24.                 android:layout_width="wrap_content"/>  

  25.   

  26.   

  27.             <TextView  

  28.   

  29.   

  30.                 android:layout_width="wrap_content"  

  31.   

  32.   

  33.                 android:layout_height="wrap_content"  

  34.   

  35.   

  36.                 android:padding="10px"  

  37.   

  38.   

  39.                 android:layout_gravity="center"  

  40.   

  41.   

  42.                 android:id="@+id/title"/>  

            ②在 JAVA 中为 ListView 添加内容

[java] view plaincopy

  1. listView listview = (ListView)findViewById(R.id.listView1);  

  2.   

  3. int[] imageId = new int[]{R.drawable.imag0,R.drawable.imag1,R.drawable.imag2};  

  4.   

  5. String[] title = new String[]{"郑州铁路职业技术学院","无线电协会",www.wxdxh.net};  

  6.   

  7. List<Map<String,Object>>listItems = new ArrayList<Map<String,Object>>();// 创建一个 List 集合  

  8.   

  9. for(int i=0;i<imageld.length;i++){// 遍历数组  

  10.   

  11.     Map<String,Object>map = new HashMap<String,Object>();// 创建哈希表  

  12.   

  13.     map.put("image",imageId[i]);  

  14.   

  15.     map.put("title",title[i]);  

  16.   

  17.     listItems.add(map);}  

  18.   

  19. SimpleAdapter adapter = new SimpleAdapter(this,listItems,R.layout.items,new String[]{"title","image"},new  

  20.   

  21. int[]{"R.id.title","R.id.image"});   

  22.   

  23. listView.setAdapter(adapter);    

  24.   

  25. //SimpleAdapter(Context, List<? extends Map<String, ?>>, int, String[], int[]);  

            ③、SimpleAdapter 类:一个使静态数据和在 XML 中定义的 Views 对应起来的简单 adapter。你可以把 list 上的数据指定为一个 Map 范型的 ArrayList。ArrayList 里的每一个条目对应于 list 里的一行。Maps 包含着每一行的数据。你先要指定一个 XML,这个 XML 定义了用于显示一行的 view。你还要指定一个对应关系,这个对应关系是从 Map 的 keys 对应到指定的 views。

 

绑定数据到 views 发生在两个阶段:如果一个 simpleAdapter.ViewBinder 是可用的,那么 SetViewValue (android.view.View,Object,String) 要被调用。如果返回 true,那么绑定发生了。如果返回 false,那么如下 views 将被按顺序地尝试:

~实现了 Checkable 的 View(如 CheckBox),预期的绑定值是 boolen

~TextView,预期的绑定值是 String,并且 SetViewText 方法被调用

~ImageView,预期的绑定值是一个资源的 id 或 String。并且 SetViewImage 方法被调用

如果没有合适的绑定被发现,一个 IllegalStateException 被抛出。  

四、SimpleAdapter 在 GridView 中使用 

    1、添加布局和资源

   ①、 在布局文件中添加 GridView

[html] view plaincopy

  1. <GridView android:id="@+id/gridView1"  

  2.   

  3.         android:layout_widtn="wrap_content"  

  4.   

  5.         android:layout_height="match_parent"     

  6.   

  7.         android:stretchMode="columnWidth"  设置拉伸模式 - 仅拉伸表格元素本身                              

  8.   

  9.         android:numColimns="4"></GridView> 设置列数  



[html] view plaincopy

  1. <GridView android:id="@+id/gridView1"  

  2.   

  3.         android:layout_widtn="wrap_content"  

  4.   

  5.         android:layout_height="match_parent"     

  6.   

  7.         android:stretchMode="columnWidth"  设置拉伸模式 - 仅拉伸表格元素本身                              

  8.   

  9.         android:numColimns="4"></GridView> 设置列数  

    ②、在新建的资源中添加内容

[html] view plaincopy

  1. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  

  2.   

  3.     android:id="@+id/item"  

  4.   

  5.     android:layout_width="wrap_content"  

  6.   

  7.     android:layout_height="wrap_content"  

  8.   

  9.     android:layout_marginTop="5dp"// 设置据顶部边缘的距离  

  10.   

  11.     android:orientation="vertical" >  

  12.   

  13.       

  14.   

  15.     <ImageView android:id="@+id/image"  

  16.   

  17.         android:layout_width="75dp"  

  18.   

  19.         android:layout_height="75dp"   

  20.   

  21.         android:layout_gravity="center"  

  22.   

  23.         android:scaleType="fitXY"// 设置比例类型为适合 XY  

  24.   

  25.         android:padding="4dp"/>  

  26.   

  27.       

  28.   

  29.     <TextView android:id="@+id/title"  

  30.   

  31.         android:layout_width="wrap_content"  

  32.   

  33.         android:layout_height="wrap_content"  

  34.   

  35.         android:layout_gravity="center"  

  36.   

  37.         android:gravity="center_horizontal"  

  38.   

  39.         />  

  40.   

  41. </LinearLayout>                    

      2、在 Java 代码中为 GridViw 添加内容

            GridView 中添加内容和 ListView 的内容一样,参考 ListView。

五、BaseAdapter 在 GridView 中的使用     

        BaseAdapter 抽象类:是一个实现了既能在 ListView (实现了 ListAdapter 接口) 和 Spinner (实现了 Spinner 接口) 里用的 Adapter 类的一般基类。

        1、用 BaseAdapter 在 GridView 中只显示网格式图片 

            ①新建 BaseAdapter 对象,重写 getView 方法

[html] view plaincopy

  1.   @Override  

  2.   

  3.                 public View getView(int position,View convertView ViewGroup parent){  

  4.   

  5.                 ImageView imageView;  

  6.   

  7.                 if(convertView==null){  

  8.   

  9.                     imageview=new ImageView(MainActivity.this);  

  10.   

  11.                     imageview.setScaleType (ImageView.ScaleType.CENTER_INSIDE);// 设置比例类型  

  12.   

  13.                     imageview.setPadding(5,0,5,0);}  

  14.   

  15.                 else{  

  16.   

  17.                     imageview=(ImageView)convertView;  

  18.   

  19.                     }  

  20.   

  21.                     imageview.setImageResource (imageId [position]);// 设置图片内容  

  22.   

  23.                     return imageview;  

  24.   

  25. }  

        ②使用

            gridview.setAdapter(adapter);

总结:以上是 Adapter 的子类在列表和网格视图中的应用,只罗列出了关键代码和分析,有好多地方只是理解但是因为水平原因无法表达,希望和其他学习者共同解决。


Android ArrayAdapter没有清除?

Android ArrayAdapter没有清除?

我对 Android的ArrayAdapter的自定义实现有一个奇怪的问题.为了给出一些背景知识,我正在尝试更新ListView的内容,同时保留当前的滚动位置.

我有一个服务,它执行一个线程来更新ListView中显示的数据.该数据存储在ArrayList中,ArrayList用于为ListView生成一些自定义ArrayAdapter.按下ListView中的项目(添加或删除项目)时,也会更新适配器.我曾经只是在每次有任何类型的更改时创建新适配器,然后将这个新适配器设置为ListView.这很有效,但每次都会导致ListView滚动到顶部.鉴于我的应用程序的性质,这是不可取的.必须在更新之间维护ListView中的当前滚动位置.

我没有创建新的适配器,而是开始使用适配器的clear()方法清除需要更新的适配器,然后使用适配器的add()方法重建适配器的项目.这两种方法都在适配器上调用.适配器都在其构造函数中设置为notifyDataOnChange,因此我不必每次都手动调用notiftyDatasetChanged()(虽然考虑到我的问题,我尝试手动调用它也无济于事).

这是我的自定义适配器的样子:

public class RealmAdapter extends ArrayAdapter<Realm>
{
    Context c;

    public RealmAdapter(Context context,int resource,int textViewResourceId)
    {               
        super(context,resource,textViewResourceId);
        setNotifyOnChange(true);
        c = context;
    }

    @Override
    public View getView(int position,View convertView,ViewGroup parent)
    { 
        ...
    }
...
}

长话短说,这是我的问题.当我在适配器上调用clear()时,适配器未被清除.

这是我的线程中的onPostExecute的片段,用于更新.我肯定会把它放在这里,所以它在UI线程上更新.我也在我的UI活动中将这些确切的代码复制到私有方法中.此代码在以下任一位置都不起作用:

appState.favoriteAdapter.clear();
Log.d(LOG_TAG,"COUNT: " + appState.favoriteAdapter.getCount());
for(Realm r : appState.favorites) {
    appState.favoriteAdapter.add(r);
}
Log.d(LOG_TAG,"COUNT: " + appState.favoriteAdapter.getCount());

例如,如果上面的适配器中有3个项目,则在clear()返回3而不是0之后立即调用getCount().同样,如果appState.favorites ArrayList中只有2个项目,则getCount( )循环仍然返回3,而不是2.因为适配器没有响应任何这些调用,它使得无法以任何方式更新.我可以稍后发布一个Logcat,如果这会有所帮助,但没有例外或任何有用的东西被显示.

几个小时后,我似乎遇到的问题是适配器没有响应对任何改变它的方法的调用.我已经尝试将一个空的ArrayList传递给适配器的super()调用,这没有用.我错过了什么或者错误地使用了ArrayAdapter吗?我已经搜遍了所有的问题,我已经检查了很多常见的问题,例如修改底层数组并期望它更新,而不是调用(或者在我的外壳设置中使用适配器)notifyDatasetChanged(),并使用不支持的对底层集合的操作.

favoriteAdapter的声明非常简单,包含在我的Application类中:

public RealmAdapter favoriteAdapter;

这是从上面初始化favoriteAdapter:

if(appState.favoriteAdapter == null) {
    appState.favoriteAdapter = new RealmAdapter(c,R.layout.list_item,R.layout.realm_entry,appState.favorites);
}
else {
    appState.favoriteAdapter.clear();
    Log.d(LOG_TAG,"COUNT: " + appState.favoriteAdapter.getCount());
    for(Realm r : appState.favorites) {
        appState.favoriteAdapter.add(r);
    }
    Log.d(LOG_TAG,"COUNT: " + appState.favoriteAdapter.getCount());
}

上面的代码在我的UI线程和下载刷新数据的线程中.

在上面的代码下面放置了一个过滤器:

if(appState.favoriteAdapter != null && RealmSelector.realmFilter != null)                   appState.favoriteAdapter.getFilter().filter(RealmSelector.realmFilter.getText().toString());

过滤器会影响清除列表吗?逻辑不会决定……

解决方法

我将过滤器应用于自定义ArrayAdapter.显然这会干扰添加和删除适配器本身的项目?我将此代码添加到我的方法中,它现在正在工作:

if(appState.favoriteAdapter != null && realmFilter != null) {
     appState.favoriteAdapter.getFilter().filter(realmFilter.getText().toString());
}

如果有人能解释为什么这很重要,我会很高兴.我认为过滤器是为了选择适配器中的项目子集.在我的测试中,我将用于过滤器的文本框留空,因此不应该应用实际的过滤器文本.再说一次,如果有人知道发生了什么,可以向我解释为什么这样可以解决我想知道的问题.

Android ArrayAdapter过滤问题

Android ArrayAdapter过滤问题

因为我想使用“自定义列表适配器”,以便可以为列表设置样式,但“过滤器”功能无法正常工作.我可以使用基本的过滤功能,但是一旦过滤结果列表小于我开始过滤时显示的listItems数量,应用程序就会崩溃.

这段代码中还有第二个问题,我不确定是否相关,但是何时
明确();在publishResults中运行,然后应用程序也崩溃.

这是我正在使用的代码.

package com.android.example;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Filter;
import android.widget.TextView;

public class Customlistadapter extends ArrayAdapter<String> {
    private Context mContext; 
private String[] items;
private String[] filtered;

public Customlistadapter(Context context, int textViewResourceId, String[] items) {
        super(context, textViewResourceId, items);
        this.filtered = items;
        this.items = filtered;

        setNotifyOnChange(true);
        mContext = context;
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
     View v = convertView;
     if (v == null) {
         LayoutInflater vi = (LayoutInflater)mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
         v = vi.inflate(R.layout.list_item, null);
     }
     String o = filtered[position];
     if (o != null) {
             TextView tt = (TextView) v.findViewById(R.id.tvViewRow);
             if (tt != null) {
                   tt.setText("Name: "+o);
             }
     }
     return v;
}

public void notifyDataSetInvalidated()
{
    super.notifyDataSetInvalidated();
}


private Filter filter;


public Filter getFilter()
{
    if(filter == null)
        filter = new NameFilter();
    return filter;
}
private class NameFilter extends Filter
{
    @Override
    protected FilterResults performFiltering(CharSequence constraint) {
        // NOTE: this function is *always* called from a background thread, and
        // not the UI thread.
        constraint = constraint.toString().toLowerCase();
        FilterResults result = new FilterResults();
        if(constraint != null && constraint.toString().length() > 0)
        {
            ArrayList<String> filt = new ArrayList<String>();
            List<String> lItems = new ArrayList<String>();
            synchronized (items)
            {     
                lItems = Arrays.asList(items);  
                //Collections.copy(lItems, Arrays.asList(items));
            }
            for(int i = 0, l = lItems.size(); i < l; i++)
            {
                String m = lItems.get(i);
                if(m.toLowerCase().startsWith(constraint.toString()))
                    filt.add(m);
            }
            result.count = filt.size();
            result.values = filt.toArray(new String[0]);
        }
        else
        {
            synchronized(items)
            {
                result.values = items;
                result.count = Arrays.asList(items).size();
            }
        }
        return result;
    }

    @Override
    protected void publishResults(CharSequence constraint, FilterResults results) {
        // NOTE: this function is *always* called from the UI thread.

            filtered = (String[])results.values;
            notifyDataSetChanged();
            clear();
            notifyDataSetInvalidated();
    }
}

}

解决方法:

我只是有同样的问题.只需将getCount()方法放在适配器类中即可.它应该返回过滤后的计数.像这样:

public int getCount() {
    return mItems.size();  
}

我过滤了mItems.

Android JSONArray到ArrayList

Android JSONArray到ArrayList

我正在尝试在我的Android应用程序中将JSONArray解析为和ArrayList。PHP脚本正确地重新调整了预期的结果,但是Java失败并在以下位置出现了空指针异常resultsList.add(map)

public void agencySearch(String tsearch)    {        // Setting the URL for the Search by Town        String url_search_agency = "http://www.infinitycodeservices.com/get_agency_by_city.php";        // Building parameters for the search        List<NameValuePair> params = new ArrayList<NameValuePair>();        params.add(new BasicNameValuePair("City", tsearch));        // Getting JSON string from URL        JSONArray json = jParser.getJSONFromUrl(url_search_agency, params);        for (int i = 0; i < json.length(); i++) {            HashMap<String, String> map = new HashMap<String, String>();            try {                JSONObject c = (JSONObject) json.get(i);                //Fill map                Iterator iter = c.keys();                while(iter.hasNext())   {                    String currentKey = (String) iter.next();                    map.put(currentKey, c.getString(currentKey));                }                resultsList.add(map);            }            catch (JSONException e) {                e.printStackTrace();            }        };        MainActivity.setResultsList(resultsList);    }

答案1

小编典典

尝试这样可能会帮助您,

public void agencySearch(String tsearch)    {        // Setting the URL for the Search by Town        String url_search_agency = "http://www.infinitycodeservices.com/get_agency_by_city.php";        // Building parameters for the search        List<NameValuePair> params = new ArrayList<NameValuePair>();        params.add(new BasicNameValuePair("City", tsearch));        // Getting JSON string from URL        JSONArray json = jParser.getJSONFromUrl(url_search_agency, params);       ArrayList<HashMap<String, String>> resultsList = new  ArrayList<HashMap<String, String>>();        for (int i = 0; i < json.length(); i++) {            HashMap<String, String> map = new HashMap<String, String>();            try {                JSONObject c = json.getJSONObject(position);                //Fill map               Iterator<String> iter = c.keys();                while(iter.hasNext())   {                    String currentKey = it.next();                    map.put(currentKey, c.getString(currentKey));                }                resultsList.add(map);            }            catch (JSONException e) {                e.printStackTrace();            }        };        MainActivity.setResultsList(resultsList);    }

我们今天的关于Android ArrayAdapter和JSONArray的分享就到这里,谢谢您的阅读,如果想了解更多关于android Adapter 综合使用(ArrayAdapter、SimpleAdapter、Bas、Android ArrayAdapter没有清除?、Android ArrayAdapter过滤问题、Android JSONArray到ArrayList的相关信息,可以在本站进行搜索。

本文标签: