使用自定义数组和async tak列出视图

时间:2016-07-14 06:44:24

标签: android listview android-asynctask



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;
        }
    }
}
&#13;
&#13;
&#13;

嗨,我正在努力在onPostCreate中创建一个列表视图,代码运行但没有显示列表。我是android工作室的新手。请指出我有的任何错误(可能有一些)。提前谢谢。

&#13;
&#13;
<?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>
&#13;
&#13;
&#13;

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

&#13;
&#13;
<?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>
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:0)

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

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;
    }
}
}