Android ListView无法显示自定义适配器中的数据

时间:2017-04-23 06:30:45

标签: android xml listview

请帮助,我已经在这里查看了数百个解决方案,但似乎所有这些问题的解决方案都已在我的代码中实现。

基本上,我正在编写一个访问MySQL数据库的Android应用程序,并将结果返回到列表视图,供用户单击。我已完成提取,数据正确解析并存储到Request对象中,然后放入Request数组列表中。但是,使用自定义适配器时,似乎没有显示任何内容。请帮助!!

请求适配器:

 public class RequestAdapter extends ArrayAdapter<Request> {
    private Context context;
    private ArrayList<Request> reqs;

    public RequestAdapter(Context context, ArrayList<Request> requests) {
        super(context, 0, requests);
        this.context=context;
        this.reqs=requests;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        // Get the data item for this position
        Request request = getItem(position);
        // Check if an existing view is being reused, otherwise inflate the view
        if (convertView == null) {
            LayoutInflater inflater = (LayoutInflater)         context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            convertView = inflater.inflate(R.layout.request_list, parent,     false);
        }
        // Lookup view for data population
        TextView req = (TextView) convertView.findViewById(R.id.ReqID);
        TextView date = (TextView) convertView.findViewById(R.id.Date);
        TextView desc = (TextView) convertView.findViewById(R.id.Description);
        TextView pickup = (TextView) convertView.findViewById(R.id.PickupAdd);
        TextView dropoff = (TextView) convertView.findViewById(R.id.DropOffAdd);
        TextView count = (TextView) convertView.findViewById(R.id.ItemCount);
        TextView cost = (TextView) convertView.findViewById(R.id.Cost);
        TextView driveracc = (TextView) convertView.findViewById(R.id.DriverAccepted);
        TextView status = (TextView) convertView.findViewById(R.id.Status);
        TextView user = (TextView) convertView.findViewById(R.id.User);
        TextView completed = (TextView) convertView.findViewById(R.id.IsCompleted);


        // Populate the data into the template view using the data object
        req.setText("Request Number: "+request.getRequestID());
        date.setText("Date: "+request.getDate());
        desc.setText("Description: "+request.getDescription());
        pickup.setText(request.getPickupAddress());
        dropoff.setText(request.getDropOffAddress());
        count.setText(request.getNumItems());
        cost.setText(request.getPrice().toString());
        driveracc.setText(request.getDriverName());
        status.setText(request.getCurrStatus());
        user.setText(request.getUser());
        completed.setText(request.getCompleted().toString());
        // Return the completed view to render on screen
        return convertView;
    }
    @Override
    public int getCount() {
        return reqs.size();
        }
    }

调用适配器的主类:

`package com.JunkAway;

    public class Active_Requests extends AppCompatActivity {
// Progress Dialog
private ProgressDialog pDialog;
private View mProgressView;
// Creating JSON Parser object
JSONParser jParser = new JSONParser();

ArrayList<HashMap<String, String>> requestsList;

// url to get all products list
private static String url_requests = "https://people.eecs.ku.edu/~cduddy/JunkAway/PullActiveRequests.php";

// JSON Node names
private static final String TAG_SUCCESS = "success";
private static final String TAG_PRODUCTS = "requests";

private Request request;
private User user;
private TextView nothingfound;
public static final int CONNECTION_TIMEOUT=10000;
public static final int READ_TIMEOUT=15000;

ArrayList<Request> arrayOfRequests=new ArrayList<Request>();
//RequestAdapter adapter;
// products JSONArray
//JSONArray requests = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_active__requests);

    Intent i = getIntent();
    user = (User)i.getSerializableExtra("User");
    // Loading products in Background Thread
    String email = user.get_email();
    nothingfound = (TextView) findViewById(R.id.nothingFoundMSG);
    mProgressView = findViewById(R.id.request_progress);
    new AsyncGetRequests().execute(email);
    RequestAdapter adapter = new RequestAdapter(this,arrayOfRequests);
    ListView listView = (ListView) findViewById(R.id.RequestList);
    listView.setAdapter(adapter);
    //nothingfound.setText(Integer.toString(listView.getCount()));
}


@TargetApi(Build.VERSION_CODES.HONEYCOMB_MR2)
private void showProgress(final boolean show) {
    // On Honeycomb MR2 we have the ViewPropertyAnimator APIs, which allow
    // for very easy animations. If available, use these APIs to fade-in
    // the progress spinner.
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) {
        int shortAnimTime = getResources().getInteger(android.R.integer.config_shortAnimTime);

        /*mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE);
        mLoginFormView.animate().setDuration(shortAnimTime).alpha(
                show ? 0 : 1).setListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationEnd(Animator animation) {
                mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE);
            }
        });
        mForgotCreate.setVisibility(show ? View.GONE : View.VISIBLE);
        mForgotCreate.animate().setDuration(shortAnimTime).alpha(
                show ? 0 : 1).setListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationEnd(Animator animation) {
                mForgotCreate.setVisibility(show ? View.GONE : View.VISIBLE);
            }
        });*/
        mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
        mProgressView.animate().setDuration(shortAnimTime).alpha(
                show ? 1 : 0).setListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationEnd(Animator animation) {
                mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
            }
        });
    } else {
        // The ViewPropertyAnimator APIs are not available, so simply show
        // and hide the relevant UI components.
        mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
       // mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE);
        //mForgotCreate.setVisibility(show ? View.GONE : View.VISIBLE);
    }
}
private class AsyncGetRequests extends AsyncTask<String, String, String>
{
    ProgressDialog pdLoading = new ProgressDialog(Active_Requests.this);
    HttpURLConnection conn;
    URL url = null;

    @Override
    protected void onPreExecute() {
        super.onPreExecute();

        //this method will be running on UI thread
        pdLoading.setMessage("\tLoading...");
        pdLoading.setCancelable(false);
        pdLoading.show();

    }
    @Override
    @SuppressWarnings("deprecation")
    protected String doInBackground(String... params) {
        try{

            WifiManager wm = (WifiManager) getSystemService(WIFI_SERVICE);
            //String ip = Formatter.formatIpAddress(wm.getConnectionInfo().getIpAddress());
            //System.out.print(ip);
            // Enter URL address where your php file resides
            url = new URL("https://people.eecs.ku.edu/~cduddy/JunkAway/PullActiveRequests3.php");

        } catch (MalformedURLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return "exception";
        }
        try {
            // Setup HttpURLConnection class to send and receive data from php and mysql
            conn = (HttpURLConnection)url.openConnection();
            conn.setReadTimeout(READ_TIMEOUT);
            conn.setConnectTimeout(CONNECTION_TIMEOUT);
            conn.setRequestMethod("POST");

            // setDoInput and setDoOutput method depict handling of both send and receive
            conn.setDoInput(true);
            conn.setDoOutput(true);

            // Append parameters to URL
            Uri.Builder builder = new Uri.Builder()
                    .appendQueryParameter("email", params[0]);
            String query = builder.build().getEncodedQuery();

            // Open connection for sending data
            OutputStream os = conn.getOutputStream();//broken
            BufferedWriter writer = new BufferedWriter(
                    new OutputStreamWriter(os, "UTF-8"));
            writer.write(query);
            writer.flush();
            writer.close();
            os.close();
            conn.connect();

        } catch (IOException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
            return "exception";
        }

        try {

            int response_code = conn.getResponseCode();

            // Check if successful connection made
            if (response_code == HttpURLConnection.HTTP_OK) {

                // Read data sent from server
                InputStream input = conn.getInputStream();
                BufferedReader reader = new BufferedReader(new InputStreamReader(input));
                StringBuilder result = new StringBuilder();
                String line;

                while ((line = reader.readLine()) != null) {
                    result.append(line);
                }

                // Pass data to onPostExecute method
                return(result.toString());

            }else{

                return("unsuccessful");
            }

        } catch (IOException e) {
            e.printStackTrace();
            return "exception";
        } finally {
            conn.disconnect();
        }


    }

    @Override
    protected void onPostExecute(String result) {

        //this method will be running on UI thread
        //System.out.println(result.toString());
        pdLoading.dismiss();
        showProgress(false);
        if (result.equalsIgnoreCase("false")){

            // If username and password does not match display a error message
            Toast.makeText(Active_Requests.this, "Invalid email or password", Toast.LENGTH_LONG).show();
            Intent intent = new 
Intent(Active_Requests.this,NormalUser_HomeScreen.class);
            startActivity(intent);
            Active_Requests.this.finish();

        } else if (result.equalsIgnoreCase("exception") || result.equalsIgnoreCase("unsuccessful")) {

            Toast.makeText(Active_Requests.this, "Oops! Something went wrong. Connection Problem.", Toast.LENGTH_LONG).show();
            Intent intent = new 
Intent(Active_Requests.this,NormalUser_HomeScreen.class);
            startActivity(intent);
            Active_Requests.this.finish();
        }else
        {
            /* Here launching another activity when login successful. If you persist login state
            use sharedPreferences of Android. and logout button to clear sharedPreferences.
             */

            Toast.makeText(Active_Requests.this, "Got Requests", Toast.LENGTH_LONG).show();
            String[] requests = result.split("!");
            String[] split;
            String[][] requestssplit = new String[requests.length][11];
            if(requests.length>0) {
                for(int i=0;i<requests.length;i++)
                {
                    requestssplit[i]=requests[i].split(":");
                    Request newREQ= new Request(requestssplit[i][0],requestssplit[i][1],requestssplit[i][2],requestssplit[i][3],requestssplit[i][4],requestssplit[i][5],requestssplit[i][6],requestssplit[i][7],requestssplit[i][8],requestssplit[i][9],requestssplit[i][10]);
                    arrayOfRequests.add(newREQ);
                    Log.d("Request Created:",newREQ.getDescription());
                    Log.d("Array Length:",arrayOfRequests.toString());
                }
            }
            //String test=Integer.toString(requests.length);
            //Request newREQ= new Request("80","cd.g","12885","Lawrence","Today","4","DO ITT","50","true","false","Open");
            //adapter.add(newREQ);
            nothingfound.setVisibility(View.VISIBLE);
            nothingfound.setText(result);

        }
    }

}
    }

个人请求的XML:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:visibility="visible">
<!-- Name Label -->
<TextView
    android:id="@+id/ReqID"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:paddingLeft="6dip"
    android:paddingTop="6dip"
    android:text="Request Number:"
    android:textColor="@color/common_google_signin_btn_text_light_pressed"
    android:textSize="12sp"
    android:textStyle="bold"
    android:visibility="visible" />

<TextView
    android:id="@+id/Date"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:paddingLeft="6dip"
    android:paddingTop="6dip"
    android:textColor="@color/common_google_signin_btn_text_light_pressed"
    android:textSize="12sp"
    android:textStyle="bold"
    android:visibility="visible"
    tools:text="Date Requested:" />

<TextView
    android:id="@+id/Description"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:paddingLeft="6dip"
    android:paddingTop="6dip"
    android:text="Short Description:"
    android:textColor="@color/common_google_signin_btn_text_light_pressed"
    android:textSize="17dip"
    android:textStyle="bold"
    android:visibility="visible" />
<!-- The TextView's below this point - will be HIDDEN - used to pass to other activity -->

<TextView
    android:id="@+id/PickupAdd"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:textColor="@color/common_google_signin_btn_text_light_pressed"
    android:visibility="gone" />

<TextView
    android:id="@+id/DropOffAdd"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:textColor="@color/common_google_signin_btn_text_light_pressed"
    android:visibility="gone" />

<TextView
    android:id="@+id/ItemCount"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:textColor="@color/common_google_signin_btn_text_light_pressed"
    android:visibility="gone" />

<TextView
    android:id="@+id/Cost"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:textColor="@color/common_google_signin_btn_text_light_pressed"
    android:visibility="gone" />

<TextView
    android:id="@+id/DriverAccepted"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:textColor="@color/common_google_signin_btn_text_light_pressed"
    android:visibility="gone" />

<TextView
    android:id="@+id/Status"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:textColor="@color/common_google_signin_btn_text_light_pressed"
    android:visibility="gone" />

<TextView
    android:id="@+id/User"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:textColor="@color/common_google_signin_btn_text_light_pressed"
    android:visibility="gone" />

<TextView
    android:id="@+id/IsCompleted"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:textColor="@color/common_google_signin_btn_text_light_pressed"
    android:visibility="gone" />
</LinearLayout>

使用listview的主要活动的XML:

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

<TextView
    android:id="@+id/nothingFoundMSG"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:gravity="center"
    android:includeFontPadding="false"
    android:lineSpacingExtra="18sp"
    android:text="No Active Requests Found"
    android:textSize="24sp"
    android:visibility="invisible"/>

<ProgressBar
    android:id="@+id/request_progress"
    style="?android:attr/progressBarStyleLarge"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginBottom="8dp"
    android:visibility="gone" />

<ListView
    android:id="@+id/RequestList"
    android:layout_width="368dp"
    android:layout_height="495dp"
    android:layout_marginRight="8dp"
    android:visibility="visible"/>
</LinearLayout>

1 个答案:

答案 0 :(得分:0)

您正在listview对象中添加所有数据,但您没有通知更改为适配器的数据集。您需要在完成将数据添加到对象的代码末尾添加此行。

  _youAdapter.notifyDataSetChanged();