【问题标题】:ListView is not appearing in ActivityListView 未出现在 Activity 中
【发布时间】:2013-05-22 05:17:10
【问题描述】:

我正在制作一个应用程序,我想在其中使用 PHPMYADMIN 的服务器在 ListView 中向用户显示所有以前的订单详细信息。

问题:在Activity中没有得到ListView,得到的是空白Activity而不是ListView

OrdersAdapter.java:

public class OrdersAdapter extends BaseAdapter {

    TextView tName,tId,tOid ;
    String MemberID,resultServer,strMemberID,strName,strOrderID;

    Activity activity;
    LayoutInflater inflater;
    ListView listView;


    public OrdersAdapter(Activity a) {
        // TODO Auto-generated constructor stub
        activity = a;
        inflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

    }

    public int getCount() {
        return 0;
        // TODO Auto-generated method stub

    }

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

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

        public View getView(final int position, View convertView, ViewGroup parent) {
            // TODO Auto-generated method stub
            View vi = convertView;
            if (convertView == null)
                vi = inflater.inflate(R.layout.listrow_orders, null);  // listrow_cart

            // Permission StrictMode
            if (android.os.Build.VERSION.SDK_INT > 9) {
            StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
            StrictMode.setThreadPolicy(policy);


            tId = (TextView)activity.findViewById(R.id.txtTotalAmount);
            tName = (TextView)activity.findViewById(R.id.txtItemDetails);

            String url = "http://172.16.0.4/res/order_fetch.php";
            Intent intent= activity.getIntent();
            MemberID = intent.getStringExtra("MemberID");
            List<NameValuePair> params = new ArrayList<NameValuePair>();
            params.add(new BasicNameValuePair("sMemberID", MemberID));
            resultServer  = getHttpPost(url,params);

            strMemberID = "";
            strName = "";


            JSONObject c;
            try {
                c = new JSONObject(resultServer);
                strMemberID = c.getString("TotalAmount");               
                strName = c.getString("ItemDetails");

                if(!strMemberID.equals(""))
                    {                   
                        tName.setText(strName);
                        tId.setText(strMemberID);               
                    }
                    else
                    {               
                        tName.setText("-");
                        tId.setText("-");
                    }
                    } catch (JSONException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                    }       

                }
            return vi;
        }       

                String getHttpPost(String url,List<NameValuePair> params) {
                StringBuilder str = new StringBuilder();
                HttpClient client = new DefaultHttpClient();
                HttpPost httpPost = new HttpPost(url);

                try {
                    httpPost.setEntity(new UrlEncodedFormEntity(params));
                    HttpResponse response = client.execute(httpPost);
                    StatusLine statusLine = response.getStatusLine();
                    int statusCode = statusLine.getStatusCode();
                    if (statusCode == 200) { // Status OK
                        HttpEntity entity = response.getEntity();
                        InputStream content = entity.getContent();
                        BufferedReader reader = new BufferedReader(new InputStreamReader(content));
                        String line;
                        while ((line = reader.readLine()) != null) {
                            str.append(line);
                        }
                    } else {
                        Log.e("Log", "Failed to download result..");
                    }
                } catch (ClientProtocolException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                return str.toString();  
        }

}

OrdersActivity.java:

    public class OrdersActivity extends Activity 
{               
    ListView mLstView1;
    OrdersAdapter mViewOrdersAdpt;

    @SuppressLint("NewApi")
    @Override

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_orders);   

         mLstView1 = (ListView) findViewById(R.id.listView1);

            mViewOrdersAdpt = new OrdersAdapter(OrdersActivity.this);
            mLstView1.setAdapter(mViewOrdersAdpt);

            mLstView1.setOnItemClickListener(new OnItemClickListener() {

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

                }
            }); 
    }
}

activity_orders.xml:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="#ffffff" >

    <include
        android:id="@+id/header"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        layout="@layout/header_orders" />

<ListView 
    android:layout_width="match_parent" 
    android:id="@+id/listView1" 
    android:layout_height="wrap_content" 
    android:layout_alignParentLeft="true" 
    android:layout_below="@+id/header" 
    android:cacheColorHint="#00000000" 
    android:divider="#b5b5b5" 
    android:dividerHeight="1dp" 
    android:layout_alignParentBottom="true" />

</RelativeLayout>

listrow_orders.xml:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginBottom="5dp"
    android:layout_marginLeft="10dp"
    android:layout_marginRight="10dp"
    android:layout_marginTop="5dp"
    android:background="@drawable/btn_background"
    android:orientation="horizontal"
    android:padding="5dip" >

<TextView
    android:id="@+id/txtTotalAmount"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignLeft="@+id/textView1"
    android:layout_below="@+id/textView1"
    android:textColor="#a60704"
    android:text="TextView" />

<TextView
    android:id="@+id/txtItemDetails"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignLeft="@+id/textView3"
    android:layout_below="@+id/textView3"
    android:textColor="#a60704"
    android:text="Item Details Here" />

<TextView
    android:id="@+id/textView3"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignLeft="@+id/txtTotalAmount"
    android:layout_below="@+id/txtTotalAmount"
    android:layout_marginTop="17dp"
    android:text="Ordered Items:"
    android:textColor="#a60704"
    android:textAppearance="?android:attr/textAppearanceMedium" />

<TextView
    android:id="@+id/textView1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentLeft="true"
    android:layout_alignParentTop="true"
    android:text="Total Amount"
    android:textAppearance="?android:attr/textAppearanceMedium"
    android:textColor="#a60704" />

</RelativeLayout>

【问题讨论】:

  • 嗨 Chulbul ji,请使用 Asynctask 从服务器获取数据,而不是在 UI 线程上执行长时间任务
  • 你在getView中做了很多操作尝试在另一个线程中做
  • 您在适配器的getCount 方法中使用了 0。将其更改为列表视图中项目的总数。
  • @Oam 你好实际上我很困惑我应该在那里使用什么
  • 您必须使用从服务器检索到的项目总数。我认为您正在检索getView 上的每个项目数据。我建议您在使用Asynctask 设置适配器之前获取所有项目,最后将适配器设置为列表视图。

标签: android android-listview


【解决方案1】:

最好在 Activity 中解析 json 而不是 BaseAdaptergetView() 将被多次调用,因此 json 将被解析 multiple也有时间

Activity里面写json获取代码在AsyncTask里面存储数据ArrayList,如果你有一个ArrayList而不是像下面这样使用,你需要将多个ArrayList传递给BaseAdapter constructor

onPostExecute use setAdapter();

在这里, mArrayListArrayList&lt;String&gt;

 OrdersAdapter ordersAdapter = new OrdersAdapter(MyAct.this,mArrayList);

内部 BaseAdapter

ArrayList<String> mMyList;

public OrdersAdapter(Activity a, ArrayList<String> mList) 
 {
   activity = a;
   mMyList = mList;
   inflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
 }

getCount 方法

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

【讨论】:

  • 是的,哥们,我同意你的观点,我也认为我应该在活动中解析 json 而不是 BaseAdapter,你能否更新你的答案,并最终向我展示我的代码应该是什么样子,用于活动和适配器上课,按照你的想法安排,然后我会做必要的改变
【解决方案2】:

您的适配器说它没有项目,因为 getCount() 返回 0

【讨论】:

  • 只需返回您的适配器存储在其模型中的#items
【解决方案3】:

OrdersAdapter.java 类中的问题 您必须以正确的方式覆盖适配器 getCount() 方法,例如

 public int getCount() {
        return SIZE_OF_ARRAYLIST;

    }

如果你写 return 0 那么列表将不会显示。所以你需要返回arrayList的大小

【讨论】:

    【解决方案4】:

    传递一个集合,让我们在构造函数中说字符串

    public OrdersAdapter(Activity a, List stringsToShow) {
        // TODO Auto-generated constructor stub
        activity = a;
        inflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
       this.stringsToShow = stringsToShow;
    }
    

    然后

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

    并避免在 getView() 中做太多事情。Kamal karte ho Pande ji..

    【讨论】:

      【解决方案5】:

      不要尝试在 getView() 方法中加载数据,因为它会被系统多次调用。您可以查看这两个链接以更好地了解 Yet another getView called multiple times 和第二个链接 custom listview adapter getView method being called multiple times, and in no coherent order 所以现在你必须做些什么来克服这个问题。您从 Web 加载数据,因此您可以使用将用于加载数据并将其传递到类中的 asynctask。检查此以了解 asynctask http://developer.android.com/reference/android/os/AsyncTask.html 从 asynctask 类中,您可以在类中传递这些数据。此类保存数据,然后您可以在主要活动中使用这些数据。最好在 asynctask 类中解析 json 数据。 实际上,您没有在适配器类中传递任何数据。这就是为什么您的列表视图没有显示任何数据的原因。希望这会奏效。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-06-15
        • 2021-06-19
        • 2023-02-09
        • 2014-02-04
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多