2013-11-19 5 views
0

В моем приложении Android пользователь может ввести изображение профиля. У меня есть предопределенная база данных в папке моих ресурсов. В нем есть таблица с именем Person. В таблице Person есть поле Profile Profile, которое имеет тип BLOB. Я сохранил изображение профиля в базе данных, используя его uri. Я использовал следующий сегмент кода для получения uri изображения.Android: ошибка в получении изображения с uri

String path = null; 
path = Images.Media.insertImage(getContentResolver(), bitmap, 
       "title", null); 

Uri imageUri = Uri.parse(path); 

String uriString = imageUri.toString() ;    

person.setProfilePic(uriString); 

ContentValues values = new ContentValues(); 
values.put(COLUMN_PROFILE_PICTURE, person.getProfilePic()); 

Это мой класс класса объектов.

public class Person { 
private int id; 
private String profilePic; 
private String name, date_of_birth, age, gender, bloodGrp; 

...... 

public String getProfilePic() { 
    return profilePic; 
} 

public void setProfilePic(String imageInByte) { 
    this.profilePic = imageInByte; 
} 

Я извлек данные из базы данных с использованием этого метода.

public ArrayList<Person> getPersonList() { 
    ArrayList<Person> personList = new ArrayList<Person>(); 

    String sql = "SELECT p.PersonName, p.ProfilePicture, p.DOB " 
      + "FROM EMPerson p " + "ORDER BY p.PersonName "; 
    System.out.println(sql); 
    ArrayList<?> stringList = selectRecordsFromDB(sql, null); 

    for (int i = 0; i < stringList.size(); i++) { 
     ArrayList<?> arrayList = (ArrayList<?>) stringList.get(i); 
     ArrayList<?> list = arrayList; 
     Person person = new Person(); 
     person.setName((String) list.get(0)); 
     person.setProfilePic((String) list.get(1)); 
     person.setDate_of_birth((String) list.get(2)); 

     personList.add(person); 

    } 

    return personList; 

} 

Я использовал следующий метод, чтобы получить Bitmap с URL-адреса.

public Bitmap getBitmap(String url) { 
    Log.d("getBitmap", "getBitmap"); 
    Bitmap bm = null; 
    try { 
     URL aURL = new URL(url); 
     bm = BitmapFactory.decodeStream(aURL.openConnection().getInputStream()); 

    } catch (Exception e) { 
     e.printStackTrace(); 
    } finally { 

    } 
    return bm; 
} 

Я вызываю этот метод getBitmap и устанавливаю растровое изображение в виде изображения следующим образом.

Bitmap image; 
image = getBitmap(i.getProfilePic()); 
proPic.setImageBitmap(image); 

Это мой класс CUstomAdapter.

package my.easymedi.controller; 

import java.util.ArrayList; 
import my.easymedi.entity.Person; 
import android.content.Context; 
import android.graphics.Bitmap; 
import android.graphics.BitmapFactory; 
import android.net.Uri; 
import android.util.Log; 
import android.view.LayoutInflater; 
import android.view.View; 
import android.view.ViewGroup; 
import android.widget.ArrayAdapter; 
import android.widget.ImageView; 
import android.widget.TextView; 

public class CustomAdapter extends ArrayAdapter<Person> { 
private ArrayList<Person> lstPerson; 
private Context my_context; 

public CustomAdapter(Context context, int textViewResourceId, 
     ArrayList<Person> objects) { 
    super(context, textViewResourceId, objects); 
    this.lstPerson = objects; 
    my_context = context; 
} 

public View getView(int position, View convertView, ViewGroup parent) { 

    // assign the view we are converting to a local variable 
    View v = convertView; 

    if (v == null) { 
     LayoutInflater inflater = (LayoutInflater) getContext() 
       .getSystemService(Context.LAYOUT_INFLATER_SERVICE); 
     v = inflater.inflate(R.layout.list_item, null); 
    } 

    Person i = lstPerson.get(position); 

    if (i != null) { 

     TextView personName = (TextView) v.findViewById(R.id.personName); 
     ImageView proPic = (ImageView) v.findViewById(R.id.imgProPic); 
     TextView dob = (TextView) v.findViewById(R.id.dateOfBirth); 

     if (personName != null) { 
      personName.setText(i.getName()); 
     } 
     if (proPic != null) { 
      Bitmap image; 

      image = getBitmap(i.getProfilePic()); 

      proPic.setImageBitmap(image); 

     } 
     if (dob != null) { 
      dob.setText(i.getDate_of_birth()); 
     } 
    } 

    return v; 

} 
public Bitmap getBitmap(String url) { 
    Log.d("getBitmap", "getBitmap"); 
    Bitmap bm = null; 
    try { 
     Uri aURL = null;// new URL(url); 
     Uri.parse(url); 

     bm = BitmapFactory.decodeStream(my_context.getContentResolver().openInputStream(aURL)); 

    } catch (Exception e) { 
     e.printStackTrace(); 
    } finally { 

    } 
    return bm; 
} 

}

Но проблема в том, вид изображения пуст. Несмотря на то, что лог-код не показывает сообщения об ошибке. Я тестирую эмулятор. Может ли кто-нибудь plz быть настолько любезным, чтобы объяснить, что здесь происходит?

Заранее спасибо

ответ

0

Вместо aURL.openConnection().getInputStream(), вы должны использовать getContentResolver().openInputStream(aURL) для извлечения данных из содержимого URI.

+0

Я использую этот метод getBitmap внутри класса CustomAdapter, который расширен от ArrayAdapter . Когда я использую getContentResolver() внутри этого класса CustomAdapter, он показывает ошибку (метод getContentResolver() не определен для типа CustomAdapter). – Rose18

+0

'getContentResolver()' - это метод 'Context', который должен иметь доступный (или передать его через конструктор) в вашем адаптере. – ianhanniballake

+0

Проблема решена. Thanx ian. – Rose18

Смежные вопросы