使用Glide(Android)

时间:2017-02-20 12:46:22

标签: android json listview imageview android-glide

我是android的新手,我正在使用app。我需要使用滑动从服务列表中下载URL图像。问题是我的项目在列表中包括两个textviews和imageview所以当我发送图像到项目我得到这个错误“android.widget.RelativeLayout不能强制转换为android.widget.ImageView” 我搜索了很多,我找不到合适的解决方案。 这是我在导航抽屉活动中的代码,称为主页

 public class mainpage extends AppCompatActivity
    implements NavigationView.OnNavigationItemSelectedListener {
ProgressDialog prgDialog;
private ListView lv;
private String TAG = MainActivity.class.getSimpleName();
ArrayList<HashMap<String, String>> contactList = new ArrayList<HashMap<String, String>>();





String[] img = new String[1000];




@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_mainpage);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    prgDialog = new ProgressDialog(this);
    prgDialog.setMessage("Please wait............");
    prgDialog.setCancelable(false);
    String serverURL = "server url name";
    String url = "images url ";
    lv = (ListView) findViewById(R.id.updatelist);
    ImageView image = (ImageView) findViewById(R.id.image1);
    ImageView imagee = (ImageView) findViewById(R.id.image);
    //public Context context;
    String[] img = new String[1000];
    loader im=new loader(mainpage.this,img);

    lv.setAdapter(im);


    Picasso.with(getApplication()).load("http://i.imgur.com/DvpvklR.png").into(image);






    new LoadService().execute(serverURL);


    FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
    fab.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                    .setAction("Action", null).show();
        }
    });

    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
            this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
    drawer.setDrawerListener(toggle);
    toggle.syncState();

    NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);

    navigationView.setNavigationItemSelectedListener(this);
}

@Override
public void onBackPressed() {
    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    if (drawer.isDrawerOpen(GravityCompat.START)) {
        drawer.closeDrawer(GravityCompat.START);
    } else {
        super.onBackPressed();
    }
}

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

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) {
        return true;
    }

    return super.onOptionsItemSelected(item);
}

@SuppressWarnings("StatementWithEmptyBody")
@Override
public boolean onNavigationItemSelected(MenuItem item) {
    // Handle navigation view item clicks here.
    int id = item.getItemId();
    android.app.FragmentManager fragmentManager = getFragmentManager();
    if (id == R.id.project) {
        // Handle the camera action
        fragmentManager.beginTransaction().replace(R.id.content_frame, new FirstFragment()).commit();
    } else if (id == R.id.newproject) {
        fragmentManager.beginTransaction().replace(R.id.content_frame, new SecondFragment()).commit();
    } else if (id == R.id.joboffers) {
        fragmentManager.beginTransaction().replace(R.id.content_frame, new ThirdFragment()).commit();
    } else if (id == R.id.employee) {
        fragmentManager.beginTransaction().replace(R.id.content_frame, new FourthFragment()).commit();
    } else if (id == R.id.nav_share) {

    } else if (id == R.id.nav_send) {

    }

    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    drawer.closeDrawer(GravityCompat.START);
    return true;
}

private class LoadService extends AsyncTask<String, Void, Void> {

    private final HttpClient Client = new DefaultHttpClient();
    private String Content;
    private String Error = null;
    private final String TAG = null;
    private ProgressDialog Dialog = new ProgressDialog(mainpage.this);

    //TextView uiUpdate = (TextView) findViewById(R.id.text);
    //TextView projectname = (TextView) findViewById(R.id.projectname);
    //TextView status = (TextView) findViewById(R.id.status);
    //TextView descrip = (TextView) findViewById(R.id.description);
    ImageView imagee = (ImageView) findViewById(R.id.image);
    String url = "images url";
    String[] img = new String[1000];
    // lv.setAdapter(new ImageLoader(, img));


    protected void onPreExecute() {
        //      uiUpdate.setText("");
        //projectname.setText("");
        //status.setText("");
        //descrip.setText("hello");
        Dialog.setMessage("Loading service..");
        Dialog.show();
        Dialog.dismiss();
        //Dialog.setCancelable(false);
        // descrip.setText("bye");


    }

    protected Void doInBackground(String... urls) {
        try {


            HttpGet httpget = new HttpGet(urls[0]);
            ResponseHandler<String> responseHandler = new BasicResponseHandler();
            Content = Client.execute(httpget, responseHandler);


        } catch (ClientProtocolException e) {
            Error = e.getMessage();
            cancel(true);
        } catch (IOException e) {
            Error = e.getMessage();
            cancel(true);
        }

        return null;
    }

    protected void onPostExecute(Void unused) {
        // Close progress dialog
        Dialog.dismiss();
        Log.e(TAG, "Raw output "
                + Content);


        try {

            // Load json data and display
            JSONObject json = new JSONObject(Content);
            //String responseString = json.getString("name");
            JSONArray jre = json.getJSONArray("updates");
            //HashMap<String, String> project = new HashMap<String, String>();


            for (int j = 0; j < jre.length(); j++) {

                JSONObject jobject = jre.getJSONObject(j);

                String name11 = jobject.getString("title");
                String description = jobject.getString("description");
                //String statu = jobject.getString("status");
                String image = jobject.getString("image");
                String total = url + image;
                img[j] = total;



                HashMap<String, String> contact = new HashMap<>();

                // adding each child node to HashMap key => value
                contact.put("title", name11);
                contact.put("description", description);
                contact.put(url+image,total);
                //contact.put("status", statu);
                contactList.add(contact);



            }



        } catch (JSONException e) {

            e.printStackTrace();
        }


        // uiUpdate.setText( Content);
        ListAdapter adapter = new SimpleAdapter(mainpage.this, contactList, R.layout.item, new String[]{"title", "description"}, new int[]{R.id.title, R.id.description});
        //ImageLoader im=new ImageLoader(mainpage.this,img);
        lv.setAdapter(adapter);





    }

}
public class loader extends ArrayAdapter {

    public Context context;
    private LayoutInflater inflater;

    private String[] img;

    public loader(Context context, String[] img) {
        super(context, R.layout.item, img);

        this.context = context;
        this.img = img;

        inflater = LayoutInflater.from(context);

    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
       // ImageView imgshow = (ImageView) findViewById(R.id.image1);
        RecyclerView.ViewHolder holder;
        if (null == convertView) {
            convertView = inflater.inflate(R.layout.item, parent, false);

        }
        Glide.with(context)
                .load(img[position])     // THE ERROR IS HERE
                .into((ImageView) convertView);


       return convertView;


    }


}

}

这是我的item.xml

  <RelativeLayout    
  xmlns:app="http://schemas.android.com/apk/res-auto"
 android:orientation="vertical" android:layout_width="match_parent"
 android:layout_height="match_parent"
 android:background="@color/gray4">

<TextView
    android:text="TextView"
    android:layout_width="300dp"
    android:layout_height="wrap_content"
    android:id="@+id/title"
    android:textSize="25dp"
    android:layout_weight="0.22" />

<TextView
    android:text="TextView"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/description"
    android:textSize="18dp"
    android:layout_below="@+id/title"
    android:layout_weight="0.54" />

<ImageView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    app:srcCompat="@drawable/back"
    android:id="@+id/imageview" />

我的主页

     <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:id="@+id/content_mainpage"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="0dp"
android:paddingLeft="0dp"
android:paddingRight="0dp"
android:paddingTop="0dp"

app:layout_behavior="@string/appbar_scrolling_view_behavior"
tools:context="commyc.example.blu_ray91111.timslinesoluation.mainpage"
tools:showIn="@layout/app_bar_mainpage">

<FrameLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/content_frame"
    android:layout_centerHorizontal="true"
    android:layout_alignParentTop="true">


    <TextView
        android:text="our news "
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"

        android:id="@+id/textView19"
        android:textSize="24sp"
        android:textColor="@color/colorAccent" />

    <ImageView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:srcCompat="@mipmap/back5"
        android:id="@+id/image1" />

    <ListView
        android:layout_width="wrap_content"

        android:id="@+id/updatelist"
        android:layout_height="400dp"
        android:layout_marginTop="63dp"
        android:layout_alignParentTop="true"
        android:layout_alignParentStart="true" />

   </FrameLayout>

   </RelativeLayout>

4 个答案:

答案 0 :(得分:0)

这是一个解决方案:

@Override
    public View getView(int position, View convertView, ViewGroup parent) {
       // ImageView imgshow = (ImageView) findViewById(R.id.image1);
        RecyclerView.ViewHolder holder;
        if (null == convertView) {
            convertView = inflater.inflate(R.layout.item, parent, false);

        } 
        ImageView imageView = (ImageView) convertView.findViewById(R.id.imageview)


        Glide.with(context)
                .load(img[position])     // THE ERROR IS HERE
                .into(imageView);


       return convertView;


    }

答案 1 :(得分:0)

以下是您无法在getView方法

中访问imageview的解决方案

访问imageview在你的getView()

中试试
ImageView imgshow = (ImageView) convertView.findViewById(R.id.image1);

convertiview是布局的参考,然后你可以在使用之后访问imageview。希望这会有所帮助。:)

答案 2 :(得分:0)

    public class loader extends ArrayAdapter {

        public Context context;
        private LayoutInflater inflater;

        private String[] img;

        public loader(Context context, String[] img) {
            super(context, R.layout.item, img);

            this.context = context;
            this.img = img;

            inflater = LayoutInflater.from(context);

        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
           // ImageView imgshow = (ImageView) findViewById(R.id.image1);
            RecyclerView.ViewHolder holder;
ImageView imgshow;
            if (null == convertView) {
                convertView = inflater.inflate(R.layout.item, parent, false);
     imgshow = (ImageView) convertView.findViewById(R.id.image1);
            }
            Glide.with(context)
                    .load("http://phone.tmsline.com/images/upload/"+img[position])     // THE ERROR IS HERE
                    .into(imgshow);
    Log.e("image_url,"http://phone.tmsline.com/images/upload/"+img[position]);


           return convertView;


        }


Try this code....

答案 3 :(得分:0)

问题是通过在适配器中执行以下操作:

Glide.with(context)
     .load(img[position])     // THE ERROR IS HERE
     .into((ImageView) convertView);

您正在尝试在布局item.xml的根视图中加载图像,并且该布局的根是RelativeLayout,因此错误“android.widget.RelativeLayout无法转换为android.widget.ImageView”

您应该通过

检索子图像View
ImageView imageView = (ImageView) convertView.findViewById(R.id.imageview)

然后你可以这样做:

Glide.with(context)
     .load(img[position])     // THE ERROR IS HERE
     .into(imageView);