getItem()从其他类

时间:2016-11-25 18:24:42

标签: android listview android-studio android-fragments

所以基本上我正在制作一个活动,其中包含2个片段,我们可以使用viewPager进行导航。这两个片段中的每一个都有一个listView和一个CustomAdapter来填充这些列表。问题是其中一个适配器中的getItem(int)位置返回第二个对象。 (请注意,我注意到使用listFragments,大多数已回答的问题都是针对listFragments的)

这是课程。

OrdersAdapter.java

import android.content.Context;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.RatingBar;
import android.widget.TextView;

import java.util.ArrayList;

/**
 * Created by Hasan on 11/21/2016.
 */

public class OrdersAdapter extends ArrayAdapter<Order> {

    private int mColorResourceId;
    public OrdersAdapter(Context context, ArrayList<Order> orders, int colorResourceId) {
        super(context, 0, orders);
        mColorResourceId = colorResourceId;
    }

    @Nullable
    @Override
    public Order getItem(int position) {
        return super.getItem(position);
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        View listItemView = convertView;
        if (listItemView == null) {
            listItemView = LayoutInflater.from(getContext()).inflate(
                    R.layout.list_item_order, parent, false);
        }
        Order currentOrder = getItem(position);
        TextView subjectTextView = (TextView) listItemView.findViewById(R.id.order_subject);
        subjectTextView.setText(currentOrder.getOrderSubject());
        TextView descriptionTextView = (TextView) listItemView.findViewById(R.id.order_description);
        descriptionTextView.setText(currentOrder.getOrderDescription());
        TextView technicianNameTextView = (TextView) listItemView.findViewById(R.id.technician_name);
        technicianNameTextView.setText( currentOrder.getTechnicainName());
        RatingBar ratingBar = (RatingBar) listItemView.findViewById(R.id.ratingBar);
        ratingBar.getOnRatingBarChangeListener();
        View textContainer = listItemView.findViewById(R.id.container);
        int color = ContextCompat.getColor(getContext(), mColorResourceId);
        textContainer.setBackgroundColor(color);
        return listItemView;
    }
}

OrdersFragment.java

import android.app.LoaderManager;
import android.content.Context;
import android.content.Intent;
import android.content.Loader;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;

import java.util.ArrayList;
import java.util.List;

public class OrdersFragment extends Fragment implements LoaderManager.LoaderCallbacks<List<Order>> {

    private ProgressBar progressBar;
    private final String QUERY = "";
    private OrdersAdapter ordersAdapter;


    public OrdersFragment() {
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.orders_list, container, false);

        ordersAdapter = new OrdersAdapter(getActivity(), new ArrayList<Order>(),R.color.category_orders);
        progressBar = (ProgressBar) rootView.findViewById(R.id.progressBar);
        ListView listView = (ListView) rootView.findViewById(R.id.list);
        listView.setAdapter(ordersAdapter);
        TextView noInternetView = (TextView) rootView.findViewById(R.id.noIntenet);
        ConnectivityManager connMgr = (ConnectivityManager) getActivity().getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
        if (networkInfo != null && networkInfo.isConnected()) {
            LoaderManager loaderManager = getActivity().getLoaderManager();
            loaderManager.initLoader(1, null, this);
        } else {
            progressBar.setVisibility(View.GONE);
            noInternetView.setVisibility(View.VISIBLE);
        }
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Order order = ordersAdapter.getItem(position);
                Intent i = new Intent(Intent.ACTION_VIEW);
            }
        });
        return rootView;
    }
    @Override
    public Loader<List<Order>> onCreateLoader(int id, Bundle args) {
        return new OrdersLoader(getContext(), QUERY);
    }

    @Override
    public void onLoadFinished(Loader<List<Order>> loader, List<Order> data) {
        ordersAdapter.clear();
        if (data != null && !data.isEmpty()) {
            ordersAdapter.addAll(data);
            ordersAdapter.notifyDataSetChanged();
        }
        progressBar.setVisibility(View.GONE);

    }

    @Override
    public void onLoaderReset(Loader<List<Order>> loader) {
        ordersAdapter.clear();
        ordersAdapter.notifyDataSetChanged();
    }
}

OrdersLoader.java

import android.content.AsyncTaskLoader;
import android.content.Context;
import android.util.Log;

import java.io.IOException;
import java.net.URL;
import java.util.List;

public class OrdersLoader extends AsyncTaskLoader<List<Order>> {
    private String murl ;
    public OrdersLoader(Context context, String url) {
        super(context);
        murl = url;
    }

    @Override
    public List<Order> loadInBackground() {

        if (murl == null) {
            return null;
        }
        URL url = UtilsOrders.createUrl(murl);
        String jsonResponse = null;
        try {
            jsonResponse = UtilsOrders.makeHttpRequest(url);
        } catch (IOException e) {
            Log.e("Error", "Error closing input stream", e);
        }
        return UtilsOrders.extractOrders(jsonResponse);

    }
    @Override
    protected void onStartLoading() {
        forceLoad();
    }
}

UserActivity.java

import android.support.design.widget.TabLayout;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

public class UserActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_user);
        ViewPager viewPager = (ViewPager) findViewById(R.id.viewpager);
        ViewsAdapter adapter = new ViewsAdapter(this, getSupportFragmentManager());
        viewPager.setAdapter(adapter);
        TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
        tabLayout.setupWithViewPager(viewPager);
    }
}

ViewsAdapter.java

/**
 * Created by Hasan on 11/21/2016.
 */

import android.content.Context;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;


public class ViewsAdapter extends FragmentPagerAdapter {

    private Context mContext;
    public ViewsAdapter(Context context, FragmentManager fm) {
        super(fm);
        mContext = context;
    }

    @Override
    public CharSequence getPageTitle(int position) {
        if (position == 0) {
            return "Technicians";
        } else
            return "Orders";

    }


    @Override
    public Fragment getItem(int position) {
        if (position == 0) {
            return new TechniciansFragment();
        } else
            return new OrdersFragment();

    }

    @Override
    public int getCount() {
        return 2;
    }
}

TechniciansAdapter.java

import android.content.Context;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.RatingBar;
import android.widget.TextView;

import java.util.ArrayList;


/**
 * Created by Hasan on 11/21/2016.
 */

public class TechniciansAdapter extends ArrayAdapter<Technician> {

        private int mColorResourceId;

    @Nullable
    @Override
    public Technician getItem(int position) {
        return super.getItem(position);
    }

    public TechniciansAdapter(Context context, ArrayList<Technician> technicians, int colorResourceId) {
            super(context, 0, technicians);
            mColorResourceId = colorResourceId;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            View listItemView = convertView;
            if (listItemView == null) {
                listItemView = LayoutInflater.from(getContext()).inflate(
                        R.layout.list_item_technician, parent, false);
            }
            Technician currentTechnician = getItem(position);
            TextView nameTextView = (TextView) listItemView.findViewById(R.id.technician_name);
            nameTextView.setText(currentTechnician.getName());
            TextView ratePerHourTextView = (TextView) listItemView.findViewById(R.id.rate_per_hour);
            ratePerHourTextView.setText(currentTechnician.getRatePerHour() + "$ /hour");
            TextView phoneNumberTextView = (TextView) listItemView.findViewById(R.id.technician_phoneNumber);
            phoneNumberTextView.setText( currentTechnician.getPhoneNumber()+"");
            if(currentTechnician.hasCompany()){
                TextView companyTextView = (TextView) listItemView.findViewById(R.id.company);
                companyTextView.setText(currentTechnician.getCompany());
            }
            RatingBar ratingBar = (RatingBar) listItemView.findViewById(R.id.ratingBar);
            ratingBar.setRating(currentTechnician.getRating());
            View textContainer = listItemView.findViewById(R.id.container);
            int color = ContextCompat.getColor(getContext(), mColorResourceId);
            textContainer.setBackgroundColor(color);
            return listItemView;
        }
    }

TechniciansFragment.java

import android.app.LoaderManager;
import android.content.Context;
import android.content.Intent;
import android.content.Loader;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;

import java.util.ArrayList;
import java.util.List;


public class TechniciansFragment extends Fragment implements LoaderManager.LoaderCallbacks<List<Technician>> {

    private ProgressBar progressBar;
    private final String QUERY = "";
    private TechniciansAdapter techniciansAdapter;


    public TechniciansFragment() {
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.technicians_list, container, false);

        techniciansAdapter = new TechniciansAdapter(getActivity(), new ArrayList<Technician>(),R.color.category_technicians);
        progressBar = (ProgressBar) rootView.findViewById(R.id.progressBar);
        ListView listView = (ListView) rootView.findViewById(R.id.list);
        listView.setAdapter(techniciansAdapter);
        TextView noInternetView = (TextView) rootView.findViewById(R.id.noIntenet);
        ConnectivityManager connMgr = (ConnectivityManager) getActivity().getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
        if (networkInfo != null && networkInfo.isConnected()) {
            LoaderManager loaderManager = getActivity().getLoaderManager();
            loaderManager.initLoader(1, null, this);
        } else {
            progressBar.setVisibility(View.GONE);
            noInternetView.setVisibility(View.VISIBLE);
        }
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Technician technician = techniciansAdapter.getItem(position);
                Intent i = new Intent(Intent.ACTION_VIEW);
            }
        });
        return rootView;
    }
    @Override
    public Loader<List<Technician>> onCreateLoader(int id, Bundle args) {
        return new TechniciansLoader(getContext(), QUERY);
    }

    @Override
    public void onLoadFinished(Loader<List<Technician>> loader, List<Technician> data) {
        techniciansAdapter.clear();
        if (data != null && !data.isEmpty()) {
            techniciansAdapter.addAll(data);
            techniciansAdapter.notifyDataSetChanged();
        }
        progressBar.setVisibility(View.GONE);

    }

    @Override
    public void onLoaderReset(Loader<List<Technician>> loader) {
        techniciansAdapter.clear();
        techniciansAdapter.notifyDataSetChanged();
    }
}

TechniciansLoader.java

import android.content.AsyncTaskLoader;
import android.content.Context;
import android.util.Log;

import java.io.IOException;
import java.net.URL;
import java.util.List;

/**
 * Created by Hasan on 8/6/2016.
 */
public class TechniciansLoader extends AsyncTaskLoader<List<Technician>> {
    private String murl ;
    public TechniciansLoader(Context context, String url) {
        super(context);
        murl = url;
    }
    @Override
    public List<Technician> loadInBackground() {

        if (murl == null) {
            return null;
        }
        URL url = UtilsTechnician.createUrl(murl);
        String jsonResponse = null;
        try {
            jsonResponse = UtilsTechnician.makeHttpRequest(url);
        } catch (IOException e) {
            Log.e("Error", "Error closing input stream", e);
        }
        return UtilsTechnician.extractTechnicians(jsonResponse);

    }
    @Override
    protected void onStartLoading() {
        forceLoad();
    }
}

错误

E/AndroidRuntime: FATAL EXCEPTION: main
                  Process: com.lebanesewebmasters.housemate, PID: 14346
                  java.lang.ClassCastException: com.lebanesewebmasters.housemate.Technician cannot be cast to com.lebanesewebmasters.housemate.Order
                      at com.lebanesewebmasters.housemate.OrdersAdapter.getItem(OrdersAdapter.java:30)
                      at com.lebanesewebmasters.housemate.OrdersAdapter.getView(OrdersAdapter.java:40)
                      at android.widget.AbsListView.obtainView(AbsListView.java:2347)
                      at android.widget.ListView.makeAndAddView(ListView.java:1864)
                      at android.widget.ListView.fillDown(ListView.java:698)
                      at android.widget.ListView.fillFromTop(ListView.java:759)
                      at android.widget.ListView.layoutChildren(ListView.java:1659)
                      at android.widget.AbsListView.onLayout(AbsListView.java:2151)
                      at android.view.View.layout(View.java:15671)
                      at android.view.ViewGroup.layout(ViewGroup.java:5038)
                      at android.widget.RelativeLayout.onLayout(RelativeLayout.java:1076)
                      at android.view.View.layout(View.java:15671)
                      at android.view.ViewGroup.layout(ViewGroup.java:5038)
                      at android.support.v4.view.ViewPager.onLayout(ViewPager.java:1767)
                      at android.view.View.layout(View.java:15671)
                      at android.view.ViewGroup.layout(ViewGroup.java:5038)
                      at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1703)
                      at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1557)
                      at android.widget.LinearLayout.onLayout(LinearLayout.java:1466)
                      at android.view.View.layout(View.java:15671)
                      at android.view.ViewGroup.layout(ViewGroup.java:5038)
                      at android.widget.FrameLayout.layoutChildren(FrameLayout.java:579)
                      at android.widget.FrameLayout.onLayout(FrameLayout.java:514)
                      at android.view.View.layout(View.java:15671)
                      at android.view.ViewGroup.layout(ViewGroup.java:5038)
                      at android.support.v7.widget.ActionBarOverlayLayout.onLayout(ActionBarOverlayLayout.java:433)
                      at android.view.View.layout(View.java:15671)
                      at android.view.ViewGroup.layout(ViewGroup.java:5038)
                      at android.widget.FrameLayout.layoutChildren(FrameLayout.java:579)
                      at android.widget.FrameLayout.onLayout(FrameLayout.java:514)
                      at android.view.View.layout(View.java:15671)
                      at android.view.ViewGroup.layout(ViewGroup.java:5038)
                      at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1703)
                      at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1557)
                      at android.widget.LinearLayout.onLayout(LinearLayout.java:1466)
                      at android.view.View.layout(View.java:15671)
                      at android.view.ViewGroup.layout(ViewGroup.java:5038)
                      at android.widget.FrameLayout.layoutChildren(FrameLayout.java:579)
                      at android.widget.FrameLayout.onLayout(FrameLayout.java:514)
                      at android.view.View.layout(View.java:15671)
                      at android.view.ViewGroup.layout(ViewGroup.java:5038)
                      at android.view.ViewRootImpl.performLayout(ViewRootImpl.java:2086)
                      at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1843)
                      at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1061)
                      at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:5885)
                      at android.view.Choreographer$CallbackRecord.run(Choreographer.java:767)
                      at android.view.Choreographer.doCallbacks(Choreographer.java:580)
                      at android.view.Choreographer.doFrame(Choreographer.java:550)
                      at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:753)
                      at android.os.Handler.handleCallback(Handler.java:739)
                      at android.os.Handler.dispatchMessage(Handler.java:95)
                      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)
Application terminated.

非常感谢

0 个答案:

没有答案