我是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
答案 0 :(得分:0)
你使用了错误的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字符串很好,请尝试使用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块中详细说明