如何使用自定义适配器解析服务器从

问题描述:

数据回答了ME如何使用自定义适配器解析服务器从

后,我很困惑放在哪里以及如何使用我的自定义适配器。 我的Parser.class有它自己的Adapter,我的MainActivity传递3个参数给Parser.class(context,url,listview)。

(使我的问题简单)

创建自定义布局,自定义适配器后,和我实例化自定义适配器,我不知道该怎么办。

我想我的实例化自定义适配器在我的MainActivity然后创建我的Parser.class MainActivity m = new MainActivity();,只是用我的自定义列表视图的textviews像m.name_tv.setText(name);m.price_tv.setText(price)然后改变android.R.layout.simple_list_item_1到我的自定义列表视图布局R.layout.list_layout

我只是在试验,因为我无法理解。 请帮忙。

这是我Parser.class

public class Parser extends AsyncTask<Void,Integer,Integer> { 



Context c; 
ListView lv; 

String data; 


ArrayList<String> categories = new ArrayList<>(); 
ProgressDialog pd; 

public Parser(Context c, String data, ListView lv) { 
    this.c = c; 
    this.data = data; 
    this.lv = lv; 

} 

@Override 
protected void onPreExecute() { 
    super.onPreExecute(); 
    pd = new ProgressDialog(c); 
    pd.setTitle("Parsing Data"); 
    pd.setMessage("Please Wait..."); 
    pd.show(); 
} 

@Override 
protected Integer doInBackground(Void... params) { 


    return this.parse(); 
} 

@Override 
protected void onPostExecute(Integer integer) { 
    super.onPostExecute(integer); 


    if(integer == 1) 
    { 
     //ADAPTER 
     ArrayAdapter<String> adapter = new ArrayAdapter<String>(c, android.R.layout.simple_list_item_1, categories); 
     lv.setAdapter(adapter); 

     lv.setOnItemClickListener(new AdapterView.OnItemClickListener() { 
      @Override 
      public void onItemClick(AdapterView<?> parent, View view, int position, long id) { 
       if(position == 0){ 



       } 


      } 
     }); 

    }else 
    { 
     Toast.makeText(c,"Unable to Parse",Toast.LENGTH_SHORT).show(); 
    } 
    pd.dismiss(); 
} 

//PARSE RECEIVED DATA 
private int parse(){ 


    try 
    { 

     //ADD THAT DATA TO JSON ARRAY FIRST 
     JSONArray ja = new JSONArray(data); 


     //CREATE JO OBJECT TO HOLD A SINGLE ITEM 
     JSONObject jo = null; 

     categories.clear(); 

     //LOOP THROUGH ARRAY 
     for(int i =0 ; i<ja.length();i++) 
     { 
      jo = ja.getJSONObject(i); 
      //RETRIEVE NAME 
      name=jo.getString("item_name"); 
      price=jo.getString("item_price"); 

      //ADD TO ARRAY LIST 
      categories.add(name + " " + price); 





     } 
     return 1; 
    } catch (JSONException e) { 
     e.printStackTrace(); 
    } 


    return 0; 
} 

}

它应该是最好不要单独的类或者它会工作一样吗?

你应该从Web服务响应和一步到位

您可以用很好的方式达到这一点,

首先创建类JSON属性名

解析它(JSON对象或JSON数组)

你的情况

Class JsonItem { 
string item_name; 
string item_price; 

// create getter and setter 

} 

二使用Gson解析您的respons Ë

Gson gson = new Gson(); 

// 1. JSON to Java object, read it from a file. 
JsonItem staff = gson.fromJson(YOUR_JSON_Here, JsonItem.class); 

这是所有

+0

我不认为你读过我的问题先生。我可以从我的服务器解析我的数据。我只是想添加一个按钮到我的列表视图。 –

+0

是啊因为你采取错误的方向,解析类应该带有参考列表视图,为什么你不把按钮放在你的主要活动 –

+0

我解决了我自己的问题。我如何标记我的问题已回答? –