【问题标题】:List view using custom array and async tak使用自定义数组和异步 tak 的列表视图
【发布时间】:2016-07-14 06:44:23
【问题描述】:

package com.example.vrs.spinnerdemo;

import android.app.Activity;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.appindexing.Action;
import com.google.android.gms.appindexing.AppIndex;
import com.google.android.gms.common.api.GoogleApiClient;
import com.netelek.logger.Log;
import com.netelek.rest.utils.RestUtils;

import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;


import ie.netelek.xml.schema.tariff.Authority;
import ie.netelek.xml.schema.tariff.AuthorityList;


public class MainActivity extends Activity implements View.OnClickListener, AdapterView.OnItemSelectedListener {
    Button btnsubmit;
    ListView list22;
    //ListView string_list;
    Context context = MainActivity.this;
    private String[] names = {"Pizza", "Burger", "Chicken", "Peas", "Yess"};

    private GoogleApiClient client;
    /**
     * ATTENTION: This was auto-generated to implement the App Indexing API.
     * See https://g.co/AppIndexing/AndroidStudio for more information.
     */
    private GoogleApiClient client2;

    ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        btnsubmit = (Button) findViewById(R.id.submit);
        list22 = (ListView)findViewById(R.id.LView);
        list22.setAdapter(new AuthorityAdapter(this,new ArrayList<Authority>()));

        // Checking internet connection
//        ConnectivityManager check = (ConnectivityManager) this.context.getSystemService(Context.CONNECTIVITY_SERVICE);
//        NetworkInfo [] info = check.getAllNetworkInfo();
//        for(int i =0; i<info.length;i++) {
//            if (info[i].getState() == NetworkInfo.State.CONNECTED) {
//                Toast.makeText(context, "Internet is connected", Toast.LENGTH_SHORT).show();
//            } else if(info[i].getState() ==NetworkInfo.State.DISCONNECTED){
//                Toast.makeText(context, "Internet is NOT connected", Toast.LENGTH_SHORT).show();
//            }
//        }

        btnsubmit.setOnClickListener(new View.OnClickListener(){
            public void onClick(View v){
                new MyTask(list22,context).execute();
            }
        });
        //setting the adapter to the above listview
        // ATTENTION: This was auto-generated to implement the App Indexing API.
        // See https://g.co/AppIndexing/AndroidStudio for more information.
        client2 = new GoogleApiClient.Builder(this).addApi(AppIndex.API).build();
    }
    @Override
    public void onStart() {
        super.onStart();

        // ATTENTION: This was auto-generated to implement the App Indexing API.
        // See https://g.co/AppIndexing/AndroidStudio for more information.
        client2.connect();
        Action viewAction = Action.newAction(
                Action.TYPE_VIEW, // TODO: choose an action type.
                "Main Page", // TODO: Define a title for the content shown.
                // TODO: If you have web page content that matches this app activity's content,
                // make sure this auto-generated web page URL is correct.
                // Otherwise, set the URL to null.
                Uri.parse("http://host/path"),
                // TODO: Make sure this auto-generated app URL is correct.
                Uri.parse("android-app://com.example.vrs.spinnerdemo/http/host/path")
        );
        AppIndex.AppIndexApi.start(client2, viewAction);
    }
    @Override
    public void onStop() {
        super.onStop();

        // ATTENTION: This was auto-generated to implement the App Indexing API.
        // See https://g.co/AppIndexing/AndroidStudio for more information.
        Action viewAction = Action.newAction(
                Action.TYPE_VIEW, // TODO: choose an action type.
                "Main Page", // TODO: Define a title for the content shown.
                // TODO: If you have web page content that matches this app activity's content,
                // make sure this auto-generated web page URL is correct.
                // Otherwise, set the URL to null.
                Uri.parse("http://host/path"),
                // TODO: Make sure this auto-generated app URL is correct.
                Uri.parse("android-app://com.example.vrs.spinnerdemo/http/host/path")
        );
        AppIndex.AppIndexApi.end(client2, viewAction);
        client2.disconnect();
    }
    class MyTask extends AsyncTask<Void, Void, ArrayList<Authority>> {

        Context context;
        ListView list22;

        MyTask (ListView list22, Context context){
            this.list22 = list22;
            this.context = context;
        }

        ArrayAdapter<Authority> adapter;
        @Override
        protected void onPreExecute() {
            adapter = (ArrayAdapter<Authority>) list22.getAdapter();
            //Toast.makeText(MainActivity.this,"onPreExecute", Toast.LENGTH_LONG).show();
        }
        @Override
        protected ArrayList<Authority> doInBackground(Void... voids) {
            ArrayList<Authority> authList = new ArrayList<>();             //create an arraylist of type authority

              try {
                //get the authority list from the database
                AuthorityList at1 = (AuthorityList) RestUtils.doGet(AuthorityList.class, "https", "172.16.112.121", 443, "/nettariff/webresources/nettariff/authority", "jason.b", "intelligencE4");
                authList.addAll(at1.getAuthorityList());
            } catch (Exception ex) {
                Log.d("ERRRROOOORRR");
            }
            return authList;
        }
        @Override
        protected void onProgressUpdate(Void... values) {}
        @Override
        protected void onPostExecute(ArrayList<Authority> authList) {

           // string_list = (ListView) findViewById(R.id.string_list);
            //ArrayAdapter<String> string_adapter = new ArrayAdapter<String>(context, android.R.layout.simple_list_item_1,names);
           // string_list.setAdapter(string_adapter);

            ArrayAdapter<Authority> adapter = new AuthorityAdapter(context, authList);   //array adapter of type authority
            list22.setAdapter(adapter);

            Toast.makeText(getApplicationContext(),"onPostExecute", Toast.LENGTH_LONG).show();
        }
    }
    //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    @Override
    public void onClick(View view) {}
    @Override
    public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {}
    @Override
    public void onNothingSelected(AdapterView<?> adapterView) {}
    ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

    public class AuthorityAdapter extends ArrayAdapter<Authority> {
        public AuthorityAdapter(Context context, ArrayList<Authority> auths) {
            super(context, 0, auths);
        }
        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            // Get the data item for this position
            Authority auth = getItem(position); //.get(position); //getItem(position);
            // Check if an existing view is being reused, otherwise inflate the view
            if (convertView == null) {                          // Lookup view for data population
                convertView = LayoutInflater.from(getContext()).inflate(R.layout.row, parent, false);
            }
            TextView tvName = (TextView) convertView.findViewById(R.id.txt);                        // Populate the data into the template view using the data object
            tvName.setText(auth.getDescription());                     // Return the completed view to render on screen
            return convertView;
        }
    }
}

您好,我正在努力在 onPostCreate 中创建列表视图,代码运行但不显示列表。我对 android studio 很陌生。请指出我遇到的任何错误(可能有一些)。提前谢谢你。

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    tools:context="com.example.vrs.spinnerdemo.MainActivity"
    tools:showIn="@layout/activity_main">


    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Enter you bill amount in Rands:"
        android:textColor="#000000"
        android:textSize="20sp"
        android:id="@+id/textView3"
        android:layout_alignParentTop="true"
        android:layout_alignParentStart="true" />
    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Press button to load list"
        android:textColor="#000000"
        android:textSize="20sp"
        android:id="@+id/textView"
        android:layout_below="@+id/BillAmount"
        android:layout_alignParentStart="true" />

    <EditText
        android:id="@+id/BillAmount"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:prompt="@string/bill_prompt"
        android:inputType="number"
        android:layout_below="@+id/textView3"
        android:layout_alignParentStart="true" />
  <ListView
      android:id="@+id/LView"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:layout_alignParentStart="true"
      android:layout_below="@+id/textView"
      android:layout_above="@+id/submit"></ListView>
    <Button
        android:id="@+id/submit"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="List of Authorities"
        android:textSize="15sp"
        android:background="#ff33b5e5"
        android:layout_marginBottom="63dp"
        android:layout_alignParentBottom="true"
        android:layout_alignParentEnd="true" />
    <ListView
        android:id="@+id/string_list"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:drawSelectorOnTop="false"
        android:layout_alignTop="@+id/submit"
        android:layout_alignParentStart="true"
        android:layout_marginTop="210dp" />

</RelativeLayout>

这是我的自定义数组适配器的 xml 文件

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

    <TextView
        android:id = "@+id/txt"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

</LinearLayout>

【问题讨论】:

    标签: android listview android-asynctask


    【解决方案1】:

    如下替换,可能会有帮助:

    public class MainActivity extends Activity implements View.OnClickListener, AdapterView.OnItemSelectedListener {
    Button btnsubmit;
    ListView list22;
    //ListView string_list;
    AuthorityAdapter adapter;
    ArrayList<Authority> authList = new ArrayList<>();             
    //create an arraylist of type authority
    Context context = MainActivity.this;
    private String[] names = {"Pizza", "Burger", "Chicken", "Peas", "Yess"};
    
    private GoogleApiClient client;
    /**
     * ATTENTION: This was auto-generated to implement the App Indexing API.
     * See https://g.co/AppIndexing/AndroidStudio for more information.
     */
    private GoogleApiClient client2;
    
    ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        btnsubmit = (Button) findViewById(R.id.submit);
        list22 = (ListView)findViewById(R.id.LView);
    
        adapter=new AuthorityAdapter(this,authList);
        list22.setAdapter(adapter);
    
        // Checking internet connection
        //        ConnectivityManager check = (ConnectivityManager) this.context.getSystemService(Context.CONNECTIVITY_SERVICE);
        //        NetworkInfo [] info = check.getAllNetworkInfo();
        //        for(int i =0; i<info.length;i++) {
        //            if (info[i].getState() == NetworkInfo.State.CONNECTED) {
        //                Toast.makeText(context, "Internet is connected",  Toast.LENGTH_SHORT).show();
        //            } else if(info[i].getState() ==NetworkInfo.State.DISCONNECTED){
        //                Toast.makeText(context, "Internet is NOT connected", Toast.LENGTH_SHORT).show();
        //            }
        //        }
    
        btnsubmit.setOnClickListener(new View.OnClickListener(){
            public void onClick(View v){
                new MyTask(list22,context).execute();
            }
        });
        //setting the adapter to the above listview
        // ATTENTION: This was auto-generated to implement the App Indexing API.
        // See https://g.co/AppIndexing/AndroidStudio for more information.
        client2 = new GoogleApiClient.Builder(this).addApi(AppIndex.API).build();
    }
    @Override
    public void onStart() {
        super.onStart();
    
        // ATTENTION: This was auto-generated to implement the App Indexing API.
        // See https://g.co/AppIndexing/AndroidStudio for more information.
        client2.connect();
        Action viewAction = Action.newAction(
                Action.TYPE_VIEW, // TODO: choose an action type.
                "Main Page", // TODO: Define a title for the content shown.
                // TODO: If you have web page content that matches this app activity's content,
                // make sure this auto-generated web page URL is correct.
                // Otherwise, set the URL to null.
                Uri.parse("http://host/path"),
                // TODO: Make sure this auto-generated app URL is correct.
                Uri.parse("android-app://com.example.vrs.spinnerdemo/http/host/path")
        );
        AppIndex.AppIndexApi.start(client2, viewAction);
    }
    @Override
    public void onStop() {
        super.onStop();
    
        // ATTENTION: This was auto-generated to implement the App Indexing API.
        // See https://g.co/AppIndexing/AndroidStudio for more information.
        Action viewAction = Action.newAction(
                Action.TYPE_VIEW, // TODO: choose an action type.
                "Main Page", // TODO: Define a title for the content shown.
                // TODO: If you have web page content that matches this app activity's content,
                // make sure this auto-generated web page URL is correct.
                // Otherwise, set the URL to null.
                Uri.parse("http://host/path"),
                // TODO: Make sure this auto-generated app URL is correct.
                Uri.parse("android-app://com.example.vrs.spinnerdemo/http/host/path")
        );
        AppIndex.AppIndexApi.end(client2, viewAction);
        client2.disconnect();
    }
    class MyTask extends AsyncTask<Void, Void, ArrayList<Authority>> {
    
        Context context;
        ListView list22;
    
        MyTask (ListView list22, Context context){
            this.list22 = list22;
            this.context = context;
        }
    
        @Override
        protected void onPreExecute() {
        }
    
        @Override
        protected ArrayList<Authority> doInBackground(Void... voids) {
    
              try {
                //get the authority list from the database
                AuthorityList at1 = (AuthorityList) RestUtils.doGet(AuthorityList.class, "https", "172.16.112.121", 443, "/nettariff/webresources/nettariff/authority", "jason.b", "intelligencE4");
                authList.addAll(at1.getAuthorityList());
            } catch (Exception ex) {
                Log.d("ERRRROOOORRR");
            }
            return authList;
        }
        @Override
        protected void onProgressUpdate(Void... values) {}
        @Override
        protected void onPostExecute(ArrayList<Authority> authList) {
    
            adapter.notifyDataSetChanged();
    
            Toast.makeText(getApplicationContext(),"onPostExecute", Toast.LENGTH_LONG).show();
        }
    }
    //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    @Override
    public void onClick(View view) {}
    @Override
    public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {}
    @Override
    public void onNothingSelected(AdapterView<?> adapterView) {}
    ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    
    public class AuthorityAdapter extends ArrayAdapter<Authority> {
        public AuthorityAdapter(Context context, ArrayList<Authority> auths) {
            super(context, 0, auths);
        }
        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            // Get the data item for this position
            Authority auth = getItem(position); //.get(position); //getItem(position);
            // Check if an existing view is being reused, otherwise inflate the view
            if (convertView == null) {                          // Lookup view for data population
                convertView = LayoutInflater.from(getContext()).inflate(R.layout.row, parent, false);
            }
            TextView tvName = (TextView) convertView.findViewById(R.id.txt);                        // Populate the data into the template view using the data object
            tvName.setText(auth.getDescription());                     // Return the completed view to render on screen
            return convertView;
        }
    }
    }
    

    【讨论】:

    • 不,我对您正在使用的 arraylist 和 arrayadpter 做了一些更改。
    • 还是什么都没有。它只在 onPostExecute 中显示 Toast。我不认为对服务器的调用实际上正在工作..因为我的 authList 数组的大小为零。
    • 我复制了你的版本..没有运气 :( 另一个问题,列表是否应该显示,即使它是空的?
    • 尝试打印你的arraylist大小并检查它是否包含数据。
    • 它的大小为零..在调试中检查过..所以问题出在 doInBackground 方法中。员工名单不应该打印吗?
    猜你喜欢
    • 2015-02-13
    • 1970-01-01
    • 2015-03-16
    • 1970-01-01
    • 2015-03-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多