无法使用自定义ListView适配器获取视图

时间:2017-08-10 03:04:22

标签: java android listview

你好我一直在尝试创建一个自定义适配器来显示简单用户信息的列表视图很长一段时间没有运气。我已经经历了无数的教程,stackoverflowthreads等,并且我的代码改变的次数比我可以计算的多,但是我没有能够在没有崩溃的情况下显示视图。任何帮助将受到高度赞赏。

另外,我可以打印出我从数据库中提取的用户信息,它显示的应该是这样,所以所有的个人信息都被正确拉出,但我没有通过视图显示所述信息。

这是我的logcat:

08-09 21:28:23.745 10009-10009/bubble.bubblev1 E/AndroidRuntime: FATAL EXCEPTION: main
                                                                 Process: bubble.bubblev1, PID: 10009
                                                                 java.lang.RuntimeException: Unable to start activity ComponentInfo{bubble.bubblev1/bubble.bubblev1.content.Activity.UserMatchActivity}: java.lang.UnsupportedOperationException: addView(View, LayoutParams) is not supported in AdapterView
                                                                     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2325)
                                                                     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2387)
                                                                     at android.app.ActivityThread.access$800(ActivityThread.java:151)
                                                                     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303)
                                                                     at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                     at android.os.Looper.loop(Looper.java:135)
                                                                     at android.app.ActivityThread.main(ActivityThread.java:5254)
                                                                     at java.lang.reflect.Method.invoke(Native Method)
                                                                     at java.lang.reflect.Method.invoke(Method.java:372)
                                                                     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
                                                                     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
                                                                  Caused by: java.lang.UnsupportedOperationException: addView(View, LayoutParams) is not supported in AdapterView
                                                                     at android.widget.AdapterView.addView(AdapterView.java:487)
                                                                     at android.view.LayoutInflater.rInflate(LayoutInflater.java:810)
                                                                     at android.view.LayoutInflater.inflate(LayoutInflater.java:504)
                                                                     at android.view.LayoutInflater.inflate(LayoutInflater.java:414)
                                                                     at android.view.LayoutInflater.inflate(LayoutInflater.java:365)
                                                                     at android.support.v7.app.AppCompatDelegateImplV9.setContentView(AppCompatDelegateImplV9.java:292)
                                                                     at android.support.v7.app.AppCompatActivity.setContentView(AppCompatActivity.java:140)
                                                                     at bubble.bubblev1.content.Activity.UserMatchActivity.onCreate(UserMatchActivity.java:76)
                                                                     at android.app.Activity.performCreate(Activity.java:5990)
                                                                     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1106)
                                                                     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2278)
                                                                     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2387) 
                                                                     at android.app.ActivityThread.access$800(ActivityThread.java:151) 
                                                                     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303) 
                                                                     at android.os.Handler.dispatchMessage(Handler.java:102) 
                                                                     at android.os.Looper.loop(Looper.java:135) 
                                                                     at android.app.ActivityThread.main(ActivityThread.java:5254) 
                                                                     at java.lang.reflect.Method.invoke(Native Method) 
                                                                     at java.lang.reflect.Method.invoke(Method.java:372) 
                                                                     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903) 
                                                                     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698) 

UserMatchActivity.java

public class UserMatchActivity extends AppCompatActivity{
    private static final String TAG = UserMatchActivity.class.getSimpleName();
    private ProgressDialog pDialog;
    private SessionManager session;
    private SQLiteHandler db;
    public ArrayList<User> matchList = new ArrayList<>();
    ListView listView;
    private static ResultAdapter adapter;



    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_usermatch); //activity_match_main
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        listView=(ListView)findViewById(R.id.list);
        matchList = new ArrayList<>();

        // Progress dialog
        pDialog = new ProgressDialog(this);
        pDialog.setCancelable(false);

        session = new SessionManager(getApplicationContext());

        db = new SQLiteHandler(getApplicationContext());
        HashMap<String, String> user = db.getUserDetails();
        String name = user.get("name");
        String email = user.get("email");
        String school = user.get("school");
        getMatches(school);
        adapter = new ResultAdapter(matchList, getApplicationContext());
        listView.setAdapter(adapter);
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener(){
            @Override
                    public void onItemClick(AdapterView<?> parent, View view, int position, long id){
                User users = matchList.get(position);
                Snackbar.make(view, "Name: "+users.getName()+"\n"+"School: "+users.getSchool()+"\n"+"Email: "+users.getEmail(), Snackbar.LENGTH_LONG)
                        .setAction("No action", null).show();
            }
        });


    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    private void hideDialog() {
        if (pDialog.isShowing())
            pDialog.dismiss();
    }
    private void getMatches(final String school) {
        String tag_string_req = "get_matches";
        StringRequest strReq = new StringRequest(Request.Method.POST,
                AppConfig.URL_SEARCH, new Response.Listener<String>() { //{
            @Override
            public void onResponse(String response) {  //JSONObject response
                //Log.d(TAG, "User Match Response: " + response.toString());
                hideDialog();

                try {   
                    JSONArray jObj = new JSONArray(response);
                    boolean error = false;
                    String errortest = String.valueOf(error);
                    Log.d("error", errortest);
                    error = false;

                    //JSONArray jsonResultArray = jObj.getJSONArray("school");



                    if (!error) {
                        //JSONArray jsonResultArray = jObj.getJSONArray("school");  //match?
                        //Log.d("name",String.valueOf(jsonResultArray));
                        for (int i = 0; i < jObj.length(); i++) {
                            JSONObject childJSONObject = jObj.getJSONObject(i);
                            String name = childJSONObject.getString("name");
                            Log.d("name", String.valueOf(name));
                            String email = childJSONObject.getString("email");
                            Log.d("email", String.valueOf(email));
                            String school = childJSONObject.getString("school");
                            Log.d("school", String.valueOf(school));
                            //User usr = new User(childJSONObject);
                            User usr = new User(name, email, school);

                            matchList.add(usr);

                        }

                    } else {


                        String errorMsg = ("brokelol");
                        Toast.makeText(getApplicationContext(),
                                errorMsg, Toast.LENGTH_LONG).show();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                    Toast.makeText(getApplicationContext(), "Json error: " + e.getMessage(), Toast.LENGTH_LONG).show();
                }

            }
        }, new Response.ErrorListener() {

            @Override
            public void onErrorResponse(VolleyError error) {
                Log.e(TAG, "Match Error: " + error.getMessage());
                Toast.makeText(getApplicationContext(),
                        error.getMessage(), Toast.LENGTH_LONG).show();
                hideDialog();
            }
        }) {

            @Override
            protected Map<String, String> getParams() {
                // Posting parameters to search url
                Map<String, String> params = new HashMap<>();
                params.put("school", school);
                return params;
            }
        };
        AppController.getInstance().addToRequestQueue(strReq, tag_string_req);
    }
}

ResultAdapter.java

public class ResultAdapter extends ArrayAdapter<User> implements View.OnClickListener {  //implements View.OnClickListener
    // private Activity activity;
    private ArrayList<User> user;
    Context mContext;
    //private static LayoutInflater inflater = null;
    private int layoutResourceId;
    private static final String LOG_TAG = "ResultAdapter";

    private class ViewHolder {  //static
        TextView usrName;
        TextView usrSchool;
        TextView usrEmail;
    }

    //public ResultAdapter(Context context, ArrayList<User> users)
    public ResultAdapter(ArrayList<User> data, Context context) {
        super(context, R.layout.activity_usermatch, data);
        this.user = data;
        this.mContext = context;

    }

    @Override
    public void onClick(View v) {
        int position = (Integer) v.getTag();
        Object object = getItem(position);
        User user=(User)object;
        /*switch (v.getId())
        {   for picture
            case R.id.item_info:
                Snackbar.make(v, "Name " +user.getName(), Snackbar.LENGTH_LONG)
                        .setAction("No action", null).show();
                break;
        }*/
    }
    private int lastPosition = -1;

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        User user = getItem(position);
        ViewHolder viewHolder;
        final View result;

        if (convertView == null) {
            viewHolder = new ViewHolder();
            LayoutInflater inflater = LayoutInflater.from(getContext());
            convertView = inflater.inflate(R.layout.activity_usermatch, parent, false);
            viewHolder.usrName = (TextView) convertView.findViewById(R.id.resultName);
            viewHolder.usrEmail = (TextView) convertView.findViewById(R.id.resultEmail);
            viewHolder.usrSchool = (TextView) convertView.findViewById(R.id.resultSchool);
            result = convertView;

            convertView.setTag(viewHolder);
        } else {
            viewHolder = (ViewHolder) convertView.getTag();
            result = convertView;
        }
        Animation animation = AnimationUtils.loadAnimation(mContext, (position > lastPosition) ? R.anim.up_from_bottom : R.anim.down_from_top);
        result.startAnimation(animation);
        lastPosition = position;
        viewHolder.usrName.setText(user.getName());
        viewHolder.usrEmail.setText(user.getEmail());
        viewHolder.usrSchool.setText(user.getSchool());


        return convertView;
    }
}

activity_usermatch.xml

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

    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:orientation="vertical"
        android:paddingLeft="20dp"
        android:paddingRight="20dp"
        android:id="@+id/MatchLayout">
        <ProgressBar
            android:id="@+id/progressBar"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            style="@style/Widget.AppCompat.ProgressBar.Horizontal"/>


        <TextView
            android:id="@+id/resultName"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Name"
            />
        <TextView
            android:id="@+id/resultEmail"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Email"
            />
        <TextView
            android:id="@+id/resultSchool"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="School"
            />

    </LinearLayout>
</ListView>

我无法透露整个应用程序,但这些是与此活动有关的文件。我没有编译器错误,只有运行时。任何帮助或建议都将受到高度赞赏!

0 个答案:

没有答案