2017-02-20 25 views
0

Я новичок в android, я работаю с приложением. Мне нужно загрузить URL-адрес изображения в списке из службы с помощью скольжения. проблема заключается в моем элементе в списке, включая два текстовых изображения и изображение, поэтому, когда я отправляю изображение в элемент, я получаю эту ошибку «android.widget.RelativeLayout не может быть отброшен в android.widget.ImageView» Я искал alot, и я не мог найти подходящий soluation. это мой код в панели навигации деятельности называется ГлавнаяЗагрузка изображения с помощью Glide (Android)

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> 

ответ

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; 


    } 
+0

большое спасибо за ваш ответ. код запускается без какой-либо ошибки, но изображения не отображаются. я попытался использовать («http://www.gettyimages.ca/gi-resources/images/Homepage/Hero/UK/CMS_Creative_164657191_Kingfisher.jpg») для загрузки, чтобы проверить, будет ли отображаться какое-либо изображение, но нет изображения, поэтому вы могли бы сказать мне это решение? спасибо inadvance –

+0

Привет, когда я использую ваш url, у меня тоже нет изображения, можете ли вы попробовать с этим URL: [link] (http://www.imdb.com/title/tt0944947/mediaviewer/rm204734720) – Cochi

0

Вот решение, которое вы не можете получить доступ к ImageView внутри метода GetView

для доступа к ImageView попробовать это в GetView()

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

convertiview является обратитесь к макету, после чего вы можете получить доступ к просмотру изображения после использования этого. Упование это помогает. :)

+0

спасибо, но как получить доступ к изображению в элементе и отобразить его изображение? –

+0

Я попробовал код, который работает без ошибок, но не отображает изображение –

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.... 
0

Проблема заключается в том, что, выполнив следующие действия в вашем адаптере:

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

Вы пытаетесь загрузить изображение в корневой зрения вашего макета item.xml и корень этого компоновщика является RelativeLayout, следовательно, ошибка " android.widget.RelativeLayout не может быть приведен к android.widget.ImageView»

вы должны получить дети ImageView делая

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

Тогда вы можете сделать:

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

Я пробовал эту программу. Программа работает без ошибок, но изображение не отображается на экране –