古人学问无遗力,少壮工夫老始成。这篇文章主要讲述Android:无法从mysql数据库中检索图像URL并将其显示在imageView中相关的知识,希望能为你提供帮助。
我是android的新手,在从服务器中存在的mysql数据库中检索图像url时遇到问题我可以使用Hashmap检索String但是无法从数据库中检索图像url
我使用适配器类来链接listview和imageview,textview等
任何人都可以检查下面的代码,以便我可以检索图像路径并将其链接到imageView并显示数据库插入路径中的图像。
main activity.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 = https://www.songbingjia.com/android/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 problemMyArrList.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 = https://www.songbingjia.com/android/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);
?>
【Android(无法从mysql数据库中检索图像URL并将其显示在imageView中)】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="https://www.songbingjia.com/android/@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
答案你使用了错误的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块中详细说明
推荐阅读
- 如何从android中重定向url加载图像
- ImageView在android中不起作用
- 如何在android中使用SwipeRefreshLayout和imageView进入NestedScrollView
- 移动ImageView(Android)[重复]
- 带有setAdjustViewBounds的Android ImageView在ConstraintLayout中具有无法解释的行为
- 在android [copy]中没有设置从相机到imageview的图像
- 5+ Web项目的最佳免费jQuery和JavaScript动态甘特图
- 最佳5(最佳图像颜色提取JavaScript和jQuery插件)
- 15个最佳高级工作门户HTML模板