如何第一和第二级仅列出使用JSON获得JSON

2023-09-04 03:24:29 作者:承诺披着童话的外衣

我得到的数据到ListView中使用JSON,但对于第一级列表,我使用静态code,总之第一级列表没有得到使用JSON,见下文code。使用,以显示第一级列表

类别屏幕的(显示在一个静态的方式数据)

产品屏幕的(获得使用JSON数据)

CategoryActivity.java:

 公共类CategoriesActivity扩展活动实现OnItemClickListener {

ListView控件lview3;
ListViewCustomAdapter适配器;

私人的ArrayList<对象> ITEMLIST;
私人ItemBean豆;

的ImageButton checkOut的;
的ImageButton备用;

@覆盖
公共无效的onCreate(包savedInstanceState)
{
    super.onCreate(savedInstanceState);
    的setContentView(R.layout.activity_menus);

    prepareArrayLits();
    lview3 =(ListView控件)findViewById(R.id.listView1);
    适配器=新ListViewCustomAdapter(这一点,ITEMLIST);
    lview3.setAdapter(适配器);
    lview3.setOnItemClickListener(本);

}
私有静态最终诠释索尼= 0;
私有静态最终诠释松下= 1;

公共无效onItemClick(适配器视图<>为arg0,查看ARG1,INT位置,长的id){

         //设置基于单击的项目不同的意图:
         开关(位置)
         {
             区分索尼:
                 意图int​​ent1 =新的意图(CategoriesActivity.this,ProductsActivity.class);
                 intent1.putExtra(类别,索尼);
                    startActivity(intent1);
                 打破;
             案例松下:
                 意图int​​ent2 =新的意图(CategoriesActivity.this,ProductsActivity.class);
                 intent2.putExtra(类,松下);
                    startActivity(intent2);
                 打破;

             默认:
                 打破;
         }

     }

公共无效prepareArrayLits()
{
    ITEMLIST =新的ArrayList<对象>();

    AddObjectToList(索尼);
    AddObjectToList(松下);

}

//添加一个项目到数组列表
公共无效AddObjectToList(字符串名称)
{
    豆=新ItemBean();
    bean.setTitle(职称);
    itemList.add(豆);
}

}
 

ItemBean.java:

 公共类ItemBean
{
    字符串称号;

    公共字符串的getTitle(){
        返回称号;
    }

    公共无效的setTitle(字符串名称){
        this.title =称号;
    }

}
 

ListViewCustomAdapter.java:

 公共类ListViewCustomAdapter扩展了BaseAdapter {

    ArrayList的<对象> ITEMLIST;

    公共活动方面;
    公共LayoutInflater充气;

    公共ListViewCustomAdapter(活动背景下,ArrayList的<对象> ITEMLIST){
        超();

        this.context =背景;
        this.itemList = ITEMLIST;
        this.inflater =(LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    }

    公众诠释getCount将(){
        // TODO自动生成方法存根
        返回itemList.size();
    }

    公共对象的getItem(INT位置){
        // TODO自动生成方法存根
        返回itemList.get(位置);
    }

    众长getItemId(INT位置){
        // TODO自动生成方法存根
        返回0;
    }

    公共静态类ViewHolder
    {
        TextView的txtViewTitle;
    }

    公共查看getView(INT位置,查看convertView,ViewGroup中父){
        // TODO自动生成方法存根

        ViewHolder持有人;
        如果(convertView == NULL)
        {
            持有人=新ViewHolder();
            convertView = inflater.inflate(R.layout.listrow_categories,NULL);
            holder.txtViewTitle =(TextView中)convertView.findViewById(R.id.title);
            convertView.setTag(保持器);
        }
        其他
            支架=(ViewHolder)convertView.getTag();

        ItemBean豆=(ItemBean)itemList.get(位置);
        holder.txtViewTitle.setText(bean.getTitle());

        返回convertView;
    }

}
 
如何获取一个json页面

和获取数据到二级列表(如:产品列表),使用下面code,

ProductsActivity.java: -

 公共类ProductsActivity延伸活动{


    静态字符串URL =htt​​p://10.0.2.2/android/test.json;

    静态字符串KEY_CATEGORY =项目;
    静态最后弦乐KEY_TITLE =产品名称;

    ListView控件列表;
    LazyAdapter适配器;



    / **第一次创建活动时调用。 * /
    @燮pressWarnings(德precation)
    @覆盖
    保护无效的onCreate(包savedInstanceState){
        // TODO自动生成方法存根
        super.onCreate(savedInstanceState);
        的setContentView(R.layout.activity_menus);

        最后的ArrayList< HashMap的<字符串,字符串>> itemsList =新的ArrayList< HashMap的<字符串,字符串>>();
        名单=(ListView控件)findViewById(R.id.listView1);
        适配器=新LazyAdapter(这一点,itemsList);
        list.setAdapter(适配器);

        如果(isNetworkAvailable()){
            新MyAsyncTask()执行()。
        } 其他 {

            AlertDialog alertDialog =新AlertDialog.Builder(ProductsActivity.this).create();
            alertDialog.setMessage(Internet连接显示为脱机状态。);
            alertDialog.setButton(OK,新DialogInterface.OnClickListener(){
                公共无效的onClick(DialogInterface对话,诠释它){

                }
            });
            alertDialog.show();
        }
    }

    私人布尔isNetworkAvailable(){
        ConnectivityManager厘米=(ConnectivityManager)getSystemService(CONNECTIVITY_SERVICE);
        的NetworkInfo信息= cm.getActiveNetworkInfo();
        返程(资讯!= NULL);
    }

    类MyAsyncTask扩展
            AsyncTask的<字符串,整数,ArrayList的< HashMap的<字符串,字符串>>> {
        私人ProgressDialog progressDialog =新ProgressDialog(
                ProductsActivity.this);

        @覆盖
        在preExecute保护无效(){
            progressDialog.setMessage(载入中,请稍候...);
            progressDialog.show();
        }

        最后的ArrayList< HashMap的<字符串,字符串>> itemsList =新的ArrayList< HashMap的<字符串,字符串>>();

        @覆盖
        受保护的ArrayList< HashMap的<字符串,字符串>> doInBackground(
                字符串... PARAMS){
            HttpClient的客户端=新DefaultHttpClient();
            //执行一个JSON列表的GET请求
            HttpUriRequest请求=新HTTPGET(URL);
            //获取发送回响应
            HTT presponse响应= NULL;
            尝试 {
                响应= client.execute(要求);
            }赶上(ClientProtocolException E1){
                // TODO自动生成的catch块
                e1.printStackTrace();
            }赶上(IOException异常E1){
                // TODO自动生成的catch块
                e1.printStackTrace();
            }
            //将这个响应为可读的字符串
            字符串jsonString = NULL;
            尝试 {
                jsonString = StreamUtils.convertToString(response.getEntity()
                        .getContent());
            }赶上(IllegalStateException异常E1){
                // TODO自动生成的catch块
                e1.printStackTrace();
            }赶上(IOException异常E1){
                // TODO自动生成的catch块
                e1.printStackTrace();
            }
            //创建一个我们可以从字符串中使用JSON对象
            JSONObject的JSON = NULL;
            尝试 {
                JSON =新的JSONObject(jsonString);
            }赶上(JSONException E1){
                // TODO自动生成的catch块
                e1.printStackTrace();
            }

            尝试 {

                JSONArray jsonArray = json.getJSONArray(KEY_CATEGORY);

                的for(int i = 0; I< jsonArray.length();我++){

                    HashMap的<字符串,字符串>图=新的HashMap<字符串,字符串>();
                    的JSONObject的JSONObject = jsonArray.getJSONObject(我);

                    map.put(钥匙,将String.valueOf(ⅰ));
                    map.put(KEY_TITLE,jsonObject.getString(KEY_TITLE));

                    itemsList.add(图)

                }
                返回itemsList;
            }赶上(JSONException E){
                Log.e(log_tag,错误分析数据+ e.toString());
            }
            返回null;
        }


        @覆盖
        保护无效onPostExecute(ArrayList中< HashMap的<字符串,字符串>>的结果){
            名单=(ListView控件)findViewById(R.id.listView1);
            适配器=新LazyAdapter(ProductsActivity.this,itemsList);
            list.setAdapter(适配器);

            this.progressDialog.dismiss();
            list.setOnItemClickListener(新OnItemClickListener(){

                公共无效onItemClick(适配器视图<>母公司视图中查看,
                        INT位置,长的id){

                }

            });
        }
    }
}
 

LazyAdapter.java:

 公共类LazyAdapter扩展了BaseAdapter {

    私人活动的活动;
    私人的ArrayList< HashMap的<字符串,字符串>>数据;
    私有静态LayoutInflater吹气= NULL;

    公共LazyAdapter(活动一,ArrayList的< HashMap的<字符串,字符串>> D){
        活性= A;
        数据= D;
        充气=(LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

    }

    公众诠释getCount将(){
        返回data.size();
    }

    公共对象的getItem(INT位置){
        返回的位置;
    }

    众长getItemId(INT位置){
        返回的位置;
    }

    公共查看getView(INT位置,查看convertView,ViewGroup中父){
        查看VI = convertView;
        如果(convertView == NULL)
            VI = inflater.inflate(R.layout.listrow_products,NULL);

        TextView的标题=(TextView中)vi.findViewById(R.id.title);

        HashMap的<字符串,字符串>项目=新的HashMap<字符串,字符串>();
        项目= data.get(位置);

        //设置列表视图中的所有值
        title.setText(item.get(ProductsActivity.KEY_TITLE));

        返回六;
    }
}
 

StreamUtils.java: -

 公共类StreamUtils {

    公共静态字符串convertToString(InputStream中的InputStream)抛出IOException异常{
        如果(的InputStream!= NULL){
            作家作家=新的StringWriter();

            的char []缓冲区=新的char [1024];
            尝试 {
                读卡器读卡器=新的BufferedReader(新的InputStreamReader(InputStream中,UTF-8),1024);
                INT N;
                而((N = reader.read(缓冲液))!=  -  1){
                    writer.write(缓冲液,0,n)的;
                }
            } 最后 {
                inputStream.close();
            }
            返回writer.toString();
        } 其他 {
            返回 ;
        }
    }
}
 

问:

如何获得第一级列表使用JSON方法,而不是静态的code像我已经写在我现有的程序?

test.json:

  {
    索尼:[{
        产品ID:1,
        产品名称:索尼 -  LED电视
    },{
        产品ID:2,
        产品名称:索尼 - 笔记本电脑
    }],

    松下:[{
        产品ID:1,
        产品名称:松下 -  LED电视
    },{
        产品ID:2,
        产品名称:松下 - 笔记本电脑
    }]
}
 

解决方案

 按我的理解,你需要ExpandableListView其中包含父在其第一种观点。当你点击你得到任何父下它的孩子的列表。

   动态填充家长和孩子使用密钥名家长及其从JSON子对象ExpandableListView ......(只要改变API,从中你需要访问的数据)。

    在这里你需要显示所有的东西你的主类
    -------------------------------------------------- ----

    公共类ViewProfileService延伸活动{

        / **在这里..vvvv定义异步任务变量* /
        HttpClient的HttpClient的;
        HTTPGET HTTPGET;
        HTT presponse HTT presponse;
        HTT presponse hhtt presponse;
        JSONObject的myJsonObject = NULL;
        JSONArray myJsonArray = NULL;
        字符串myJsonString =;

        JSONObject的nmyJsonObject = NULL;
        JSONArray nmyJsonArray = NULL;
        字符串nmyJsonString =;
        字符串的服务;
        字符串名称;
        ServiceList SL;
        的String []头;

        //私人ProgressDialog pDialog;
    //私人的ArrayList< ServiceList> m_ArrayList = NULL;
        ////////////////////////////////////////////////// / ArrayList的<的String []>标题=新的ArrayList<的String []>();

        / **扩展列表凭证* /
        ExpandableListAdapter listAdapter;
        ExpandableListView expListView;
        名单<字符串> listDataHeader;
        HashMap的<字符串列表与LT;字符串>> listDataChild;
         字符串bo_uid;
        @覆盖
        保护无效的onCreate(包savedInstanceState){
            // TODO自动生成方法存根
            super.onCreate(savedInstanceState);
            requestWindowFeature(Window.FEATURE_NO_TITLE);
            的setContentView(R.layout.view_profile_service);

            共享preferences藻= getShared preferences(all_id,0);
            bo_uid = sp.getString(bo_uid,);

            新BussinessOwnerHttpAsyncTask()执行()。

            // setGroupIndicatorToRight();

             / * //创建与各国的可绘制对象
            可绘制图标=
        。this.getResources()getDrawable(R.drawable.expander_group);

            //设置新创建的可绘制对象组指标。
            //现在你应该会看到你的图标作为组指标。
           。getExpandableListView()setGroupIndicator(图标); * /
        }

        类BussinessOwnerHttpAsyncTask扩展的AsyncTask<字符串,太虚,字符串> {

            @覆盖
            在preExecute保护无效(){
                // TODO自动生成方法存根
                super.on preExecute();

                / * pDialog =新ProgressDialog(的getParent());
                pDialog.setMessage(请稍候...);
                pDialog.setIndeterminate(假);
                pDialog.setCancelable(假);
                pDialog.show(); * /
            }


            @覆盖
            保护字符串doInBackground(字符串... PARAMS){
                // TODO自动生成方法存根

                StaticVars SV =新StaticVars();
                //启动异步任务工作在这里...
                HttpClient的HttpClient的=新DefaultHttpClient();
                @燮pressWarnings(静态访问)
                字符串myUrl =你的URL; //设置你url可在这里

                myUrl = myUrl.replaceAll(\ N,);
                myUrl = myUrl.replaceAll(,20%);
                Log.d(checkurl,myUrl);
                HTTPGET HTTPGET =新HTTPGET(myUrl.trim());

                尝试 {
                    HTT presponse = httpclient.execute(HTTPGET);
                    的System.out.println(HTT presponse+ HTT presponse);
                    Log.i(回应,回应+ HTT presponse);
                    InputStream的是= HTT presponse.getEntity()的getContent()。
                    InputStreamReader的ISR =新InputStreamReader的(是);
                    的BufferedReader BR =新的BufferedReader(ISR);
                    StringBuilder的SB =新的StringBuilder();
                    字符串recievingDataFromServer = NULL;
                    而((recievingDataFromServer = br.readLine())!= NULL){
                        Log.i(检查而,CHECK而);
                        sb.append(recievingDataFromServer);
                    }

                    myJsonString = sb.toString();

                }赶上(ClientProtocolException E){
                    // TODO自动生成的catch块
                    e.printStackTrace();
                }赶上(IOException异常E){
                    // TODO自动生成的catch块
                    e.printStackTrace();
                }

                返回null;
            }

            @燮pressWarnings(未登记)
            @覆盖
            保护无效onPostExecute(字符串结果){
                // TODO自动生成方法存根
                super.onPostExecute(结果);
            // pDialog.dismiss();

                如果(myJsonString.length()大于0){
                    尝试 {
                        myJsonObject =新的JSONObject(myJsonString);
                        的JSONObject对象= myJsonObject.getJSONObject(服务);

                        迭代器<字符串>迭代= object.keys();
                        // m_ArrayList =新的ArrayList< ServiceList>();

                        listDataHeader =新的ArrayList<字符串>();
                        listDataChild =新的HashMap<字符串列表与LT;字符串>>();
                        名单<字符串> toptodown = NULL;

                        而(iterate.hasNext()){
                             服务= iterate.next();
                            Log.d(goging,服务);
                            listDataHeader.add(服务);
                            myJsonArray = object.getJSONArray(服务);
                            toptodown =新的ArrayList<字符串>();
                            的for(int i = 0; I< myJsonArray.length();我++){
                                  JSONObject的好= myJsonArray.getJSONObject(我);
                                  名称= okay.getString(姓名);
                                  Log.d(goging,名称是:+姓名);
                                  toptodown.add(名称);
                                  }

                            listDataChild.put(服务,toptodown);

                        }


                    }赶上(JSONException E){
                        // TODO自动生成的catch块
                        e.printStackTrace();
                    }


                }
                开始();

            }

        }



        公共无效启动(){
            // TODO自动生成方法存根
            expListView =(ExpandableListView)findViewById(R.id.lvExp);

            listAdapter =新ExpandableListAdapter(这一点,listDataHeader,listDataChild);

            //设置列表适配器
            expListView.setAdapter(listAdapter);

        }

    }

    您view_profile_service.xml文件用于ViewProfileService.java类
    -------------------------------------------------- ---------------------

    < XML版本=1.0编码=UTF-8&GT?;
    < LinearLayout中的xmlns:机器人=htt​​p://schemas.android.com/apk/res/android
        机器人:layout_width =FILL_PARENT
        机器人:layout_height =FILL_PARENT
        机器人:方向=垂直>

        < ExpandableListView
                    机器人:ID =@ + ID / lvExp
                    机器人:layout_height =match_parent
                    机器人:layout_width =match_parent/>

    < / LinearLayout中>


    您ExpandableListAdapter.java类..
    -------------------------------------

    进口的java.util.HashMap;
    进口的java.util.List;

    进口com.app.ruzanamah.R;

    进口android.content.Context;
    进口android.graphics.Typeface;
    进口android.view.LayoutInflater;
    进口android.view.View;
    进口android.view.ViewGroup;
    进口android.widget.BaseExpandableListAdapter;
    进口android.widget.TextView;

    公共类ExpandableListAdapter扩展BaseExpandableListAdapter {

        私人语境_context;
        私人列表<字符串> _listDataHeader; //标题标题
        //子数据的标题标题格式,子标题
        私人的HashMap<字符串列表与LT;字符串>> _listDataChild;

        公共ExpandableListAdapter(上下文的背景下,列表与LT;字符串> listDataHeader,
                HashMap的<字符串列表与LT;字符串>> listChildData){
            this._context =背景;
            this._listDataHeader = listDataHeader;
            this._listDataChild = listChildData;
        }

        @覆盖
        公共对象getChild(INT groupPosition,诠释childPosititon){
            返回this._listDataChild.get(this._listDataHeader.get(groupPosition))
                    获得(childPosititon);
        }

        @覆盖
        众长getChildId(INT groupPosition,诠释childPosition){
            返回childPosition;
        }

        @覆盖
        公共查看getChildView(INT groupPosition,最终诠释childPosition,
                布尔isLastChild,查看convertView,ViewGroup中父){

            最后弦乐childText =(字符串)getChild(groupPosition,childPosition);

            如果(convertView == NULL){
                LayoutInflater infalInflater =(LayoutInflater)this._context
                        .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                convertView = infalInflater.inflate(R.layout.list_item,NULL);
            }

            TextView的txtListChild =(TextView中)convertView
                    .findViewById(R.id.lblListItem);

            txtListChild.setText(childText);
            返回convertView;
        }

        @覆盖
        公众诠释getChildrenCount(INT groupPosition){
            返回this._listDataChild.get(this._listDataHeader.get(groupPosition))
                    。尺寸()​​;
        }

        @覆盖
        公共对象getGroup(INT groupPosition){
            返回this._listDataHeader.get(groupPosition);
        }

        @覆盖
        公众诠释getGroupCount(){
            返回this._listDataHeader.size();
        }

        @覆盖
        众长getGroupId(INT groupPosition){
            返回groupPosition;
        }

        @覆盖
        公共查看getGroupView(INT groupPosition,布尔isExpanded,
                查看convertView,ViewGroup中父){
            字符串headerTitle =(字符串)getGroup(groupPosition);
            如果(convertView == NULL){
                LayoutInflater infalInflater =(LayoutInflater)this._context
                        .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                convertView = infalInflater.inflate(R.layout.list_group,NULL);
            }

            TextView的lblListHeader =(TextView中)convertView
                    .findViewById(R.id.lblListHeader);
            lblListHeader.setTypeface(NULL,Typeface.BOLD);
            lblListHeader.setText(headerTitle);

            返回convertView;
        }

        @覆盖
        公共布尔hasStableIds(){
            返回false;
        }

        @覆盖
        公共布尔isChildSelectable(INT groupPosition,诠释childPosition){
            返回true;
        }
    }


    您list_item.xml文件用于ExpandableListAdapter.java类
    -------------------------------------------------- -------------

    < XML版本=1.0编码=UTF-8&GT?;
    < LinearLayout中的xmlns:机器人=htt​​p://schemas.android.com/apk/res/android
        机器人:layout_width =match_parent
        机器人:layout_height =55dip
        机器人:方向=垂直>

        <的TextView
            机器人:ID =@ + ID / lblListItem
            机器人:layout_width =FILL_PARENT
            机器人:layout_height =WRAP_CONTENT
            机器人:TEXTSIZE =17dip
            机器人:paddingTop =5DP
            机器人:paddingBottom会=5DP
            机器人:以下属性来=机器人:ATTR / expandableList preferredChildPaddingLeft/>

    < / LinearLayout中>

    您list_group.xml文件用于ExpandableListAdapter.java类
    -------------------------------------------------- -----------------

    < XML版本=1.0编码=UTF-8&GT?;
    < LinearLayout中的xmlns:机器人=htt​​p://schemas.android.com/apk/res/android
        机器人:layout_width =FILL_PARENT
        机器人:layout_height =WRAP_CONTENT
        机器人:方向=垂直
        机器人:填充=8DP
        >
     <  - 安卓!后台=#000000 - >

        <的TextView
            机器人:ID =@ + ID / lblListHeader
            机器人:layout_width =FILL_PARENT
            机器人:layout_height =WRAP_CONTENT
            机器人:以下属性来=机器人:ATTR / expandableList preferredItemPaddingLeft
            机器人:TEXTSIZE =17dp/>

    < / LinearLayout中>

    上述包含了所有你需要非常高效地执行你的东西..

    享受 .. !
 

I am getting data into ListView using JSON, but for the first Level List, i am using static code, in short first level list not getting using JSON, see below code using to show first level List.

Category Screen (showing data in a Static way)

Product Screen (getting data using JSON)

CategoryActivity.java:

public class CategoriesActivity extends Activity implements OnItemClickListener {

ListView lview3;
ListViewCustomAdapter adapter;

private ArrayList<Object> itemList;
private ItemBean bean;

ImageButton checkOut;
ImageButton back;

@Override
public void onCreate(Bundle savedInstanceState) 
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_menus);    

    prepareArrayLits();
    lview3 = (ListView) findViewById(R.id.listView1);
    adapter = new ListViewCustomAdapter(this, itemList);
    lview3.setAdapter(adapter);
    lview3.setOnItemClickListener(this);  

}
private static final int Sony = 0;
private static final int Panasonic = 1;

public void onItemClick(AdapterView<?> arg0, View arg1, int position, long id) {

         // Set up different intents based on the item clicked: 
         switch (position)
         {
             case Sony:
                 Intent intent1 = new Intent(CategoriesActivity.this, ProductsActivity.class);
                 intent1.putExtra("category", "Sony");
                    startActivity(intent1); 
                 break;
             case Panasonic:
                 Intent intent2 = new Intent(CategoriesActivity.this, ProductsActivity.class);
                 intent2.putExtra("category", "Panasonic");
                    startActivity(intent2); 
                 break;

             default:
                 break;
         }

     }

public void prepareArrayLits()
{
    itemList = new ArrayList<Object>();

    AddObjectToList( "Sony" );
    AddObjectToList( "Panasonic" );

}

// Add one item into the Array List
public void AddObjectToList(String title)
{
    bean = new ItemBean();
    bean.setTitle(title);
    itemList.add(bean);
}

}

ItemBean.java:

public class ItemBean 
{
    String title;

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

}

ListViewCustomAdapter.java:

public class ListViewCustomAdapter extends BaseAdapter{

    ArrayList<Object> itemList;

    public Activity context;
    public LayoutInflater inflater;

    public ListViewCustomAdapter(Activity context,ArrayList<Object> itemList) {
        super();

        this.context = context;
        this.itemList = itemList;     
        this.inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    }

    public int getCount() {
        // TODO Auto-generated method stub
        return itemList.size();
    }

    public Object getItem(int position) {
        // TODO Auto-generated method stub
        return itemList.get(position);
    }

    public long getItemId(int position) {
        // TODO Auto-generated method stub
        return 0;
    }

    public static class ViewHolder
    {
        TextView txtViewTitle;
    }

    public View getView(int position, View convertView, ViewGroup parent) {
        // TODO Auto-generated method stub

        ViewHolder holder;
        if(convertView==null)
        {
            holder = new ViewHolder();
            convertView = inflater.inflate(R.layout.listrow_categories, null);
            holder.txtViewTitle = (TextView) convertView.findViewById(R.id.title);
            convertView.setTag(holder);
        }
        else
            holder=(ViewHolder)convertView.getTag();

        ItemBean bean = (ItemBean) itemList.get(position);
        holder.txtViewTitle.setText(bean.getTitle());

        return convertView;
    }

}

and to get data into Second Level List (i.e: Products List), using below code,

ProductsActivity.java:-

public class ProductsActivity extends Activity {


    static String URL = "http://10.0.2.2/android/test.json";

    static String KEY_CATEGORY = "item";
    static final String KEY_TITLE = "ProductName";

    ListView list;
    LazyAdapter adapter;



    /** Called when the activity is first created. */
    @SuppressWarnings("deprecation")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_menus);

        final ArrayList<HashMap<String, String>> itemsList = new ArrayList<HashMap<String, String>>();
        list = (ListView) findViewById(R.id.listView1);
        adapter = new LazyAdapter(this, itemsList);
        list.setAdapter(adapter);

        if (isNetworkAvailable()) {
            new MyAsyncTask().execute();
        } else {

            AlertDialog alertDialog = new AlertDialog.Builder(ProductsActivity.this).create();
            alertDialog.setMessage("The Internet connection appears to be offline.");
            alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {

                }
            });
            alertDialog.show();
        }
    }

    private boolean isNetworkAvailable() {
        ConnectivityManager cm = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
        NetworkInfo info = cm.getActiveNetworkInfo();
        return (info != null);
    }

    class MyAsyncTask extends
            AsyncTask<String, Integer, ArrayList<HashMap<String, String>>> {
        private ProgressDialog progressDialog = new ProgressDialog(
                ProductsActivity.this);

        @Override
        protected void onPreExecute() {
            progressDialog.setMessage("Loading, Please wait.....");
            progressDialog.show();
        }

        final ArrayList<HashMap<String, String>> itemsList = new ArrayList<HashMap<String, String>>();

        @Override
        protected ArrayList<HashMap<String, String>> doInBackground(
                String... params) {
            HttpClient client = new DefaultHttpClient();
            // Perform a GET request for a JSON list
            HttpUriRequest request = new HttpGet(URL);
            // Get the response that sends back
            HttpResponse response = null;
            try {
                response = client.execute(request);
            } catch (ClientProtocolException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            } catch (IOException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }
            // Convert this response into a readable string
            String jsonString = null;
            try {
                jsonString = StreamUtils.convertToString(response.getEntity()
                        .getContent());
            } catch (IllegalStateException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            } catch (IOException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }
            // Create a JSON object that we can use from the String
            JSONObject json = null;
            try {
                json = new JSONObject(jsonString);
            } catch (JSONException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }

            try {

                JSONArray jsonArray = json.getJSONArray(KEY_CATEGORY);

                for (int i = 0; i < jsonArray.length(); i++) {

                    HashMap<String, String> map = new HashMap<String, String>();
                    JSONObject jsonObject = jsonArray.getJSONObject(i);

                    map.put("KEY", String.valueOf(i));
                    map.put(KEY_TITLE, jsonObject.getString(KEY_TITLE));

                    itemsList.add(map);

                }
                return itemsList;
            } catch (JSONException e) {
                Log.e("log_tag", "Error parsing data " + e.toString());
            }
            return null;
        }


        @Override
        protected void onPostExecute(ArrayList<HashMap<String, String>> result) {
            list = (ListView) findViewById(R.id.listView1);
            adapter = new LazyAdapter(ProductsActivity.this, itemsList);
            list.setAdapter(adapter);

            this.progressDialog.dismiss();
            list.setOnItemClickListener(new OnItemClickListener() {

                public void onItemClick(AdapterView<?> parent, View view,
                        int position, long id) {

                }

            });
        }
    }
}

LazyAdapter.java:

public class LazyAdapter extends BaseAdapter {

    private Activity activity;
    private ArrayList<HashMap<String, String>> data;
    private static LayoutInflater inflater=null;

    public LazyAdapter(Activity a, ArrayList<HashMap<String, String>> d) {
        activity = a;
        data=d;
        inflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

    }

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

    public Object getItem(int position) {
        return position;
    }

    public long getItemId(int position) {
        return position;
    }

    public View getView(int position, View convertView, ViewGroup parent) {
        View vi=convertView;
        if(convertView==null)
            vi = inflater.inflate(R.layout.listrow_products, null);

        TextView title = (TextView)vi.findViewById(R.id.title); 

        HashMap<String, String> item = new HashMap<String, String>();
        item = data.get(position);

        // Setting all values in listview
        title.setText(item.get(ProductsActivity.KEY_TITLE));

        return vi;
    }
}

StreamUtils.java:-

public class StreamUtils {

    public static String convertToString(InputStream inputStream) throws IOException {
        if (inputStream != null) {
            Writer writer = new StringWriter();

            char[] buffer = new char[1024];
            try {
                Reader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), 1024);
                int n;
                while ((n = reader.read(buffer)) != -1) {
                    writer.write(buffer, 0, n);
                }
            } finally {
                inputStream.close();
            }
            return writer.toString();
        } else {
            return "";
        }
    }
}

Question:

How to get First Level List by using JSON, not by writing static code like i have written in my existing program?

test.json:

{
    "Sony": [{
        "ProductID": "1",
        "ProductName": "Sony - LED TV"
    }, {
        "ProductID": "2",
        "ProductName": "Sony - Laptop"
    }],

    "Panasonic": [{
        "ProductID": "1",
        "ProductName": "Panasonic - LED TV"
    }, {
        "ProductID": "2",
        "ProductName": "Panasonic - Laptop"
    }]
}

解决方案

    As per my understanding you require ExpandableListView which contains Parent at its first view .. When you click on any parent you get list of child under it.

   Dynamically populate parent and child to ExpandableListView using key name for parent and its object as child from JSON... ( Just change api from which you need to access data ).

    Your main class where you require to show all stuffs 
    ------------------------------------------------------

    public class ViewProfileService extends Activity{

        /** Define Async Task variables over here ..vvvv*/
        HttpClient httpclient;
        HttpGet httpget;
        HttpResponse httpresponse;
        HttpResponse hhttpresponse;
        JSONObject myJsonObject = null;
        JSONArray myJsonArray = null;
        String myJsonString = "";

        JSONObject nmyJsonObject = null;
        JSONArray nmyJsonArray = null;
        String nmyJsonString = "";
        String service;
        String name;
        ServiceList sl;
        String[] head;

        //private ProgressDialog pDialog;
    //  private ArrayList<ServiceList> m_ArrayList = null;
        ///////////////////////////////////////////////////ArrayList<String[]> header = new ArrayList<String[]>();

        /** Expandable list credentials */
        ExpandableListAdapter listAdapter;
        ExpandableListView expListView;
        List<String> listDataHeader;
        HashMap<String, List<String>> listDataChild;
         String bo_uid;
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            // TODO Auto-generated method stub
            super.onCreate(savedInstanceState);
            requestWindowFeature(Window.FEATURE_NO_TITLE);
            setContentView(R.layout.view_profile_service);

            SharedPreferences sp = getSharedPreferences("all_id", 0);
            bo_uid = sp.getString("bo_uid", "");

            new BussinessOwnerHttpAsyncTask().execute();

            //setGroupIndicatorToRight();

             /*// Create a Drawable object with states
            Drawable icon =
        this.getResources().getDrawable(R.drawable.expander_group);

            // Set the newly created Drawable object as group indicator.
            // Now you should be seeing your icons as group indicators.
           getExpandableListView().setGroupIndicator(icon);*/
        }

        class BussinessOwnerHttpAsyncTask extends AsyncTask<String, Void, String> {

            @Override
            protected void onPreExecute() {
                // TODO Auto-generated method stub
                super.onPreExecute();

                /*pDialog = new ProgressDialog(getParent());
                pDialog.setMessage("Please wait ...");
                pDialog.setIndeterminate(false);
                pDialog.setCancelable(false);
                pDialog.show();*/
            }


            @Override
            protected String doInBackground(String... params) {
                // TODO Auto-generated method stub

                StaticVars sv = new StaticVars();
                // Starting Async Task work over here ...
                HttpClient httpclient = new DefaultHttpClient();
                @SuppressWarnings("static-access")
                String myUrl = "your url " ;//set you url over here

                myUrl = myUrl.replaceAll("\n", "");
                myUrl = myUrl.replaceAll(" ", "%20");
                Log.d("checkurl", myUrl);
                HttpGet httpget = new HttpGet(myUrl.trim());

                try {
                    httpresponse = httpclient.execute(httpget);
                    System.out.println("httpresponse" + httpresponse);
                    Log.i("response", "Response" + httpresponse);
                    InputStream is = httpresponse.getEntity().getContent();
                    InputStreamReader isr = new InputStreamReader(is);
                    BufferedReader br = new BufferedReader(isr);
                    StringBuilder sb = new StringBuilder();
                    String recievingDataFromServer = null;
                    while ((recievingDataFromServer = br.readLine()) != null) {
                        Log.i("CHECK WHILE", "CHECK WHILE");
                        sb.append(recievingDataFromServer);
                    }

                    myJsonString = sb.toString();

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

                return null;
            }

            @SuppressWarnings("unchecked")
            @Override
            protected void onPostExecute(String result) {
                // TODO Auto-generated method stub
                super.onPostExecute(result);
            //  pDialog.dismiss();

                if (myJsonString.length() > 0) {
                    try {
                        myJsonObject = new JSONObject(myJsonString);
                        JSONObject object = myJsonObject.getJSONObject("services");

                        Iterator<String> iterate = object.keys();
                        //m_ArrayList = new ArrayList<ServiceList>();

                        listDataHeader = new ArrayList<String>();
                        listDataChild = new HashMap<String, List<String>>();
                        List<String> toptodown = null;

                        while(iterate.hasNext()){
                             service = iterate.next();
                            Log.d("goging", service);
                            listDataHeader.add(service);
                            myJsonArray = object.getJSONArray(service);
                            toptodown = new ArrayList<String>();
                            for (int i = 0; i < myJsonArray.length(); i++) {
                                  JSONObject okay = myJsonArray.getJSONObject(i);
                                  name = okay.getString("name");
                                  Log.d("goging","Name is: " + name);
                                  toptodown.add(name);
                                  }

                            listDataChild.put(service, toptodown);

                        }


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


                }
                start();

            }

        }



        public void start() {
            // TODO Auto-generated method stub
            expListView = (ExpandableListView) findViewById(R.id.lvExp);

            listAdapter = new ExpandableListAdapter(this, listDataHeader, listDataChild);

            // setting list adapter
            expListView.setAdapter(listAdapter);

        }

    }

    your view_profile_service.xml file used in ViewProfileService.java class
    -----------------------------------------------------------------------

    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:orientation="vertical" >

        <ExpandableListView
                    android:id="@+id/lvExp"
                    android:layout_height="match_parent"
                    android:layout_width="match_parent"/>  

    </LinearLayout>


    your ExpandableListAdapter.java class ..
    -------------------------------------

    import java.util.HashMap;
    import java.util.List;

    import com.app.ruzanamah.R;

    import android.content.Context;
    import android.graphics.Typeface;
    import android.view.LayoutInflater;
    import android.view.View;
    import android.view.ViewGroup;
    import android.widget.BaseExpandableListAdapter;
    import android.widget.TextView;

    public class ExpandableListAdapter extends BaseExpandableListAdapter {

        private Context _context;
        private List<String> _listDataHeader; // header titles
        // child data in format of header title, child title
        private HashMap<String, List<String>> _listDataChild;

        public ExpandableListAdapter(Context context, List<String> listDataHeader,
                HashMap<String, List<String>> listChildData) {
            this._context = context;
            this._listDataHeader = listDataHeader;
            this._listDataChild = listChildData;
        }

        @Override
        public Object getChild(int groupPosition, int childPosititon) {
            return this._listDataChild.get(this._listDataHeader.get(groupPosition))
                    .get(childPosititon);
        }

        @Override
        public long getChildId(int groupPosition, int childPosition) {
            return childPosition;
        }

        @Override
        public View getChildView(int groupPosition, final int childPosition,
                boolean isLastChild, View convertView, ViewGroup parent) {

            final String childText = (String) getChild(groupPosition, childPosition);

            if (convertView == null) {
                LayoutInflater infalInflater = (LayoutInflater) this._context
                        .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                convertView = infalInflater.inflate(R.layout.list_item, null);
            }

            TextView txtListChild = (TextView) convertView
                    .findViewById(R.id.lblListItem);

            txtListChild.setText(childText);
            return convertView;
        }

        @Override
        public int getChildrenCount(int groupPosition) {
            return this._listDataChild.get(this._listDataHeader.get(groupPosition))
                    .size();
        }

        @Override
        public Object getGroup(int groupPosition) {
            return this._listDataHeader.get(groupPosition);
        }

        @Override
        public int getGroupCount() {
            return this._listDataHeader.size();
        }

        @Override
        public long getGroupId(int groupPosition) {
            return groupPosition;
        }

        @Override
        public View getGroupView(int groupPosition, boolean isExpanded,
                View convertView, ViewGroup parent) {
            String headerTitle = (String) getGroup(groupPosition);
            if (convertView == null) {
                LayoutInflater infalInflater = (LayoutInflater) this._context
                        .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                convertView = infalInflater.inflate(R.layout.list_group, null);
            }

            TextView lblListHeader = (TextView) convertView
                    .findViewById(R.id.lblListHeader);
            lblListHeader.setTypeface(null, Typeface.BOLD);
            lblListHeader.setText(headerTitle);

            return convertView;
        }

        @Override
        public boolean hasStableIds() {
            return false;
        }

        @Override
        public boolean isChildSelectable(int groupPosition, int childPosition) {
            return true;
        }
    }


    your list_item.xml file used in ExpandableListAdapter.java class
    ---------------------------------------------------------------

    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="55dip"
        android:orientation="vertical" >

        <TextView
            android:id="@+id/lblListItem"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:textSize="17dip"
            android:paddingTop="5dp"
            android:paddingBottom="5dp"
            android:paddingLeft="?android:attr/expandableListPreferredChildPaddingLeft" />

    </LinearLayout>

    your list_group.xml file used in ExpandableListAdapter.java class
    -------------------------------------------------------------------

    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        android:padding="8dp"
        >
     <!-- android:background="#000000" -->

        <TextView
            android:id="@+id/lblListHeader"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:paddingLeft="?android:attr/expandableListPreferredItemPaddingLeft"
            android:textSize="17dp"/>

    </LinearLayout>

    Above mentioned contains all you need to perform your stuff very efficiently..

    Enjoy .. !