【问题标题】:Android: can't retrieve the image url from mysql database and display it in imageViewAndroid:无法从 mysql 数据库中检索图像 url 并将其显示在 imageView 中
【发布时间】:2023-03-09 22:56:02
【问题描述】:

我是 android 新手,在从服务器中存在的 mysql 数据库中检索图像 url 时遇到问题 我可以使用 Hashmap 检索字符串,但无法从数据库中检索图像 url

我已经使用适配器类来链接 listview 和 imageview、textview 等

任何人都可以检查以下代码,以便我可以检索图像路径并将其链接到 imageView 并显示来自数据库插入路径的图像。

MainActivity.java

public class MainActivity extends Activity {
@SuppressLint("NewApi")
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    // Permission StrictMode
    if (android.os.Build.VERSION.SDK_INT > 9) {
        StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
        StrictMode.setThreadPolicy(policy);
    }

    // listView1
    final ListView lstView1 = (ListView)findViewById(R.id.listView1); 

    String url = "http://192.168.1.2/Android/App/sample.php";

    try {
        JSONArray data = new JSONArray(getJSONUrl(url));

        final ArrayList<HashMap<String, String>> MyArrList = new ArrayList<HashMap<String, String>>();
        HashMap<String, String> map;

        for(int i = 0; i < data.length(); i++){
            JSONObject c = data.getJSONObject(i);
            map = new HashMap<String, String>();
            map.put("title", c.getString("title"));
            map.put("artist", c.getString("artist"));
            map.put("duration", c.getString("duration"));
            map.put("image", c.getString("image")); i cant retrieve the image string here is the only problem


            MyArrList.add(map);
        }           

        lstView1.setAdapter(new ImageAdapter(this,MyArrList));

    } catch (JSONException e) {

        e.printStackTrace();
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }


}


public class ImageAdapter extends BaseAdapter 
{
    private Context context;
    public ImageView imageView;
    private ArrayList<HashMap<String, String>> MyArr = new ArrayList<HashMap<String, String>>();

    public ImageAdapter(Context c, ArrayList<HashMap<String, String>> list) 
    {

        context = c;
        MyArr = list;
    }

    public int getCount() {

        return MyArr.size();
    }

    public Object getItem(int position) {

        return position;
    }

    public long getItemId(int position) {

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


        LayoutInflater inflater = (LayoutInflater) context
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);


        if (convertView == null) {
            convertView = inflater.inflate(R.layout.activity_column, null); 
        }

        // ColImage
        imageView = (ImageView) convertView.findViewById(R.id.image);
        //imageView.getLayoutParams().height = 50;
        //imageView.getLayoutParams().width = 50;
        //imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
         try
         {
             URL url = new URL("image");
            Bitmap bmp = BitmapFactory.decodeStream(url.openConnection().getInputStream());
            imageView.setImageBitmap(bmp);
         } catch (Exception e) {
             // When Error
             imageView.setImageResource(android.R.drawable.ic_menu_report_image);
         }

        // ColPosition
        TextView tv_title = (TextView) convertView.findViewById(R.id.title);
        tv_title.setText("ID : " + MyArr.get(position).get("title"));

        // ColPicname
        TextView tv_artist = (TextView) convertView.findViewById(R.id.artist);
        //tv_artist.setPadding(50, 0, 0, 0);
        tv_artist.setText("Desc : " + MyArr.get(position).get("artist"));

        TextView tv_duration = (TextView) convertView.findViewById(R.id.duration);
        //tv_artist.setPadding(50, 0, 0, 0);
        tv_duration.setText("Desc : " + MyArr.get(position).get("duration"));

        TextView tv_link = (TextView) convertView.findViewById(R.id.link);
        //tv_artist.setPadding(50, 0, 0, 0);
        tv_link.setText("Desc : " + MyArr.get(position).get("link"));

        return convertView;

    }

} 

/*** Get JSON Code from URL ***/
public String getJSONUrl(String url) {
    StringBuilder str = new StringBuilder();
    HttpClient client = new DefaultHttpClient();
    HttpGet httpGet = new HttpGet(client);
    try 
    {
        HttpResponse response = client.execute(httpGet);
        StatusLine statusLine = response.getStatusLine();
        int statusCode = statusLine.getStatusCode();
        if (statusCode == 200) 
        { 
            HttpEntity entity = response.getEntity();
            InputStream content = entity.getContent();
            BufferedReader reader = new BufferedReader(new InputStreamReader(content));
            String line;
            while ((line = reader.readLine()) != null) 
            {
                str.append(line);
            }
        }   
        else 
        {
            Log.e("Log", "Failed to download file..");
        }
    } 
    catch (ClientProtocolException e) 
    {
        e.printStackTrace();
    } 
    catch (IOException e) 
    {
        e.printStackTrace();
    }
    return str.toString();
}


private static final String TAG = "ERROR";
private static final int IO_BUFFER_SIZE = 4 * 1024;
public static Bitmap loadBitmap(String url) {
    Bitmap bitmap = null;
    InputStream in = null;
    BufferedOutputStream out = null;

    try {
        in = new BufferedInputStream(new URL(url).openStream(), IO_BUFFER_SIZE);

        final ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
        out = new BufferedOutputStream(dataStream, IO_BUFFER_SIZE);
        copy(in, out);
        out.flush();

        final byte[] data = dataStream.toByteArray();
        BitmapFactory.Options options = new BitmapFactory.Options();
        //options.inSampleSize = 1;

        bitmap = BitmapFactory.decodeByteArray(data, 0, data.length,options);
    } catch (IOException e) {
        Log.e(TAG, "Could not load Bitmap from: " + url);
    } finally {
        closeStream(in);
        closeStream(out);
    }

    return bitmap;
}

 private static void closeStream(Closeable stream) {
        if (stream != null) {
            try {
                stream.close();
            } catch (IOException e) {
                android.util.Log.e(TAG, "Could not close stream", e);
            }
        }
    }

 private static void copy(InputStream in, OutputStream out) throws IOException {
    byte[] b = new byte[IO_BUFFER_SIZE];
    int read;
    while ((read = in.read(b)) != -1) {
        out.write(b, 0, read);
    }
}



@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}}

示例.php

<?php
$con = mysql_connect("localhost","root","");
if (!$con){
die('Could not connect: ' . mysql_error());}
mysql_select_db("testdatabase", $con);
$result = mysql_query("SELECT * FROM sample");
while($row = mysql_fetch_assoc($result)){
    $output[] = $row;}

print(json_encode($output));
mysql_close($con);
?>

activity_column.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="@drawable/list_selector"
android:orientation="horizontal"
android:padding="5dip" >

<!--  ListRow Left sied Thumbnail image -->
<LinearLayout android:id="@+id/thumbnail" 
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:padding="3dip"      
    android:layout_alignParentLeft="true"
    android:background="@drawable/image_bg" 
    android:layout_marginRight="5dip">

    <ImageView
        android:id="@+id/image"   
        android:layout_width="50dip"
        android:layout_height="50dip"
       />

</LinearLayout>

<!-- Title Of Song-->
<TextView
    android:id="@+id/title"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignTop="@+id/thumbnail"
    android:layout_toRightOf="@+id/thumbnail"
    android:textColor="#040404"
    android:typeface="sans" 
    android:textSize="15dip"
    android:textStyle="bold"/>

<!-- Artist Name -->
<TextView
    android:id="@+id/artist"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_below="@id/title"
    android:textColor="#343434"
    android:textSize="10dip"
    android:layout_marginTop="1dip"
    android:layout_toRightOf="@+id/thumbnail"
    />

<!-- Rightend Duration -->
<TextView
    android:id="@+id/duration"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentRight="true"
    android:layout_alignTop="@id/title"
    android:gravity="right"
    android:layout_marginRight="5dip"
    android:textSize="10dip"
    android:textColor="#10bcc9"
    android:textStyle="bold"/>

 <!-- Rightend Arrow -->    
 <ImageView 
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:src="@drawable/arrow"
    android:layout_alignParentRight="true"
    android:layout_centerVertical="true"/>

 <TextView
     android:id="@+id/link"
     android:layout_width="wrap_content"
     android:layout_height="wrap_content"
     android:layout_alignBottom="@+id/thumbnail"
     android:layout_marginLeft="60dp"
     android:layout_toRightOf="@+id/title"
     />
</RelativeLayout>

数据库数据如下

我不知道我在哪里错过了这些方法 感谢您的时间和关心 我也无法检索图像路径 要检查图像路径是否正在检索,我在 mainActivity.java 上面创建了一个虚拟 textview tv_link,但我得到的值为 null

【问题讨论】:

    标签: php android mysql image imageview


    【解决方案1】:

    您使用了错误的 IP 方向。

    如果您使用 localhost 来测试 ip 应该是 '10.0.0.2' 而不是 192.168.1.2 这必须是您局域网中的本地 ip 地址,但是在 android 仿真中 localhost 的地址不是 172.0.0.1 或你的局域网 ip 192.168.1.2

    您必须使用 10.0.0.2

    String url = "http://10.0.0.2/Android/App/sample.php";
    

    http://10.0.0.2/Android/pictures/sandeep1.jpg
    

    在您的数据库中图像的 url 上

    如果您确定 url 字符串没问题,请尝试使用 HttpURLConnection

    try {
    
                    URL url = new URL(imagen);
                    HttpURLConnection connection = (HttpURLConnection)url.openConnection();
                    connection.setDoInput(true);
                    connection.connect();
                    InputStream inputStream = connection.getInputStream();
                    foto = BitmapFactory.decodeStream(inputStream);
    
                } catch (MalformedURLException e) {
    
    
                    e.printStackTrace();
                } 
    

    如果有错误会在catch块中详细说明

    【讨论】:

    • 不,这对我的静态 IP 不起作用,据我所知,朋友 @UrielUVD 我想我遗漏了一些方法,你可以帮我检查一下吗
    • 但我可以填充除 imageView @UrielUVD 中的图像文件之外的所有其他字符串,感谢您的时间
    • 我刚刚在帖子中添加了一个方法来获取图像并检查Url有什么问题,希望对您有所帮助
    • 如果问题是未检索到字符串,则必须在 Json 中命名错误或为空
    • 我看不出有什么问题。表中的名称与 Jsonobject 中的名称相同,我无法弄清楚为什么它没有检索字符串,对不起 u.u
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-05-02
    • 2021-09-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-06-15
    相关资源
    最近更新 更多