当前位置: 首页 > 知识库问答 >
问题:

Android:无法从mysql数据库检索图像url并在imageView中显示

张建树
2023-03-14

我是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;
}}

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

共有1个答案

邬浩涆
2023-03-14

您使用了错误的IP方向。

如果您正在使用localhost来测试ip应该是'10.0.0.2'而不是192.168.1.2,这必须是您的lan的本地ip地址,但在android仿真中localhost的地址不是172.0.0.1或您的lan 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块中详细说明

 类似资料:
  • 互联网日安! 我正在尝试从mysql数据库检索并显示一个图像到一个图像视图(android)中。图像是blob类型。我有以下php代码从MySQL获取图像。 下面是使用JSON的android代码。 提前感谢您的帮助!

  • 被一个问题缠住了。我是android开发的新手。我的问题是我有一个SQLite数据库,我正在其中保存映像和一些数据,但当我检索这些数据时,映像没有显示在ListView中。其他数据正在被推翻。 这是我的自定义列表布局 null 这是我的自定义适配器 } 这是activity 这是数据列表

  • 问题内容: 我使用phpmyadmin创建了一个带有表的MySQL数据库。我使用BLOB列创建了该表以容纳jpeg文件。 我对这里的php变量有疑问。 到目前为止,我的代码:(catalog.php): 如何从PHP获取变量$ result到HTML,以便可以在标记中显示它? 问题答案: 你不能 您需要创建另一个PHP脚本以返回图像数据,例如getImage.php。将catalog.php更改为

  • 但是宽度和高度较低的图像成功地加载到图像视图中! 有人能告诉我代码有什么问题吗?我做错了什么?我只想从库中导入相机图像,并在图像视图中显示它们!

  • 问题内容: 我需要在手机中打开我的画廊,然后选择一张在活动中在imageview中打开的图片..没什么困难..但是我在模拟器(genymotion)中有完美的代码和thise代码可以运行..但是在小米Mi4上却没有。 打开画廊选择项目,什么也没有。 我没有更多的电话了:( 我尝试下载一些与此主题相关的示例,并且每个示例都是相同的。 您是否有一些从图库中选择图像并在imageview中显示的项目?如

  • 我的activity.xml文件中有一个ImageView。我正在其中设置一个从服务器检索的图像。我想将此图片从ImageView插入到我的Sqlite数据库中。谁能给我解释一下怎么做吗?我在Sqlite中的表是这样的由于我是数据库新手,请一步一步告诉我。 我添加了以下代码,但插入时有一个错误,即插入未定义