Android Studio:图像未显示在远程数据库的ListView中

时间:2015-03-02 22:52:58

标签: android database android-listview

尝试从远程数据库中显示一些图像,但没有成功。

感谢任何帮助

这是我每次向下或向上滚动ListView时在我的logcat中显示的内容:

03-02 17:28:28.630  14603-14603/com.wlodsgn.bunbunup I/ViewRootImpl﹕ ViewRoot's Touch Event : Touch Down
03-02 17:28:28.930  14603-14603/com.wlodsgn.bunbunup E/BitmapFactory﹕ Unable to decode stream: java.io.FileNotFoundException: /http:/xxx.xxxxx.com/img/veroxjeans1001.jpg: open failed: ENOENT (No such file or directory)
03-02 17:28:28.930  14603-14603/com.wlodsgn.bunbunup I/System.out﹕ resolveUri failed on bad bitmap uri: http://xxx.xxxxx.com/img/veroxjeans1001.jpg

Menu

这是Verox.java:

import android.os.Bundle;
import android.support.v7.app.ActionBar;
import android.support.v7.app.ActionBarActivity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;

import org.apache.http.NameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * Created by WiLo on 2/27/2015.
 */
public class Verox extends ActionBarActivity {

    // Progress Dialog
    private ProgressDialog pDialog;

    // Creating JSON Parser object
    JSONParser jParser = new JSONParser();

    ArrayList<HashMap<String, String>> productsList;


    // url to get all products list
    private static String url_all_productos = "http://xxx.xxxxx.com/xxxxdbremote/get_all_productos.php";

    // JSON Node names
    private static final String TAG_SUCCESS = "success";
    private static final String TAG_PRODUCTS = "productos";
    private static final String TAG_ID = "id";
    private static final String TAG_CATEGORIA = "categoria";
    private static final String TAG_MARCA = "marca";
    private static final String TAG_IMG = "img";
    private static final String TAG_COLOR = "color";
    private static final String TAG_TIPO = "tipo";
    private static final String TAG_TALLA = "talla";


    // products JSONArray
    JSONArray products = null;

    ListView lista2;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.verox);

        //Back button
        ActionBar actionBar = getSupportActionBar();
        actionBar.setDisplayHomeAsUpEnabled(true);

        // Hashmap para el ListView
        productsList = new ArrayList<HashMap<String, String>>();

        // Cargar los productos en el Background Thread
        new LoadAllProducts().execute();
        lista2 = (ListView) findViewById(R.id.listAllProducts);

    }//fin onCreate

    class LoadAllProducts extends AsyncTask<String, String, String> {

        /**
         * Antes de empezar el background thread Show Progress Dialog
         * */
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pDialog = new ProgressDialog(Verox.this);
            pDialog.setMessage("Cargando comercios. Por favor espere...");
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(false);
            pDialog.show();
        }

        /**
         * obteniendo todos los productos
         * */
        protected String doInBackground(String... args) {
            // Building Parameters
            List params = new ArrayList();
            // getting JSON string from URL
            JSONObject json = jParser.makeHttpRequest(url_all_productos, "GET", params);

            // Check your log cat for JSON reponse
            Log.d("All Products: ", json.toString());

            try {
                // Checking for SUCCESS TAG
                int success = json.getInt(TAG_SUCCESS);

                if (success == 1) {
                    // products found
                    // Getting Array of Products
                    products = json.getJSONArray(TAG_PRODUCTS);

                    // looping through All Products
                    //Log.i("bbup", "productos.length" + products.length());
                    for (int i = 0; i < products.length(); i++) {
                        JSONObject c = products.getJSONObject(i);

                        // Storing each json item in variable
                        String id = c.getString(TAG_ID);
                        String categoria = c.getString(TAG_CATEGORIA);
                        String marca = c.getString(TAG_MARCA);
                        String img = c.getString(TAG_IMG);
                        String color = c.getString(TAG_COLOR);
                        String tipo = c.getString(TAG_TIPO);
                        String talla = c.getString(TAG_TALLA);

                        // creating new HashMap
                        HashMap map = new HashMap();

                        // adding each child node to HashMap key => value
                        map.put(TAG_ID, id);
                        map.put(TAG_CATEGORIA, categoria);
                        map.put(TAG_MARCA, marca);
                        map.put(TAG_IMG, img);
                        map.put(TAG_COLOR, color);
                        map.put(TAG_TIPO, tipo);
                        map.put(TAG_TALLA, talla);

                        productsList.add(map);
                    }
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
            return null;
        }

        /**
         * After completing background task Dismiss the progress dialog
         * **/
        protected void onPostExecute(String file_url) {
            // dismiss the dialog after getting all products
            pDialog.dismiss();
            // updating UI from Background Thread
            runOnUiThread(new Runnable() {
                public void run() {
                    /**
                     * Updating parsed JSON data into ListView
                     * */
                    ListAdapter adapter = new SimpleAdapter(
                            Verox.this,
                            productsList,
                            R.layout.single_post,
                            new String[] {
                                    TAG_ID,
                                    /**TAG_CATEGORIA,**/
                                    /**TAG_MARCA,**/
                                    TAG_IMG,
                                    TAG_COLOR,
                                    TAG_TIPO,
                                    /**TAG_TALLA,**/
                            },
                            new int[] {
                                    R.id.single_post_tv_id,
                                    /**R.id.single_post_tv_categoria,**/
                                    /**R.id.single_post_tv_marca,**/
                                    R.id.single_post_tv_img,
                                    R.id.single_post_tv_color,
                                    R.id.single_post_tv_tipo,
                                    /**R.id.single_post_tv_talla,**/

                            });
                    // updating listview
                    //setListAdapter(adapter);
                    lista2.setAdapter(adapter);
                }
            });
        }
    }
}

verox.xml,其中包含ListView

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical">

    <ListView
        android:id="@+id/listAllProducts"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:dividerHeight="3dp"
        android:background="#ff0a393d"/>

</LinearLayout>

这是我的single_post.xml,其中包含imageview和两个textview:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="match_parent"
    android:background="#ff0a393d"
    android:orientation="vertical"
    android:weightSum="1">

    <ScrollView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/scrollView2" >

        <LinearLayout
            android:orientation="vertical"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent">

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:textAppearance="?android:attr/textAppearanceSmall"
                android:text="id"
                android:id="@+id/single_post_tv_id"
                android:visibility="gone" />

            <ImageView
                android:layout_width="273dp"
                android:layout_height="281dp"
                android:id="@+id/single_post_tv_img" />

            <TextView
                android:id="@+id/single_post_tv_color"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:paddingBottom="2dip"
                android:padding="10dp"
                android:textColor="#ffffffff"
                android:textSize="12dp"
                android:textStyle="bold"
                android:text="color" />

            <TextView
                android:id="@+id/single_post_tv_tipo"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:paddingBottom="2dip"
                android:padding="10dp"
                android:textColor="#ffffffff"
                android:textSize="12dp"
                android:textStyle="bold"
                android:text="tipo" />
        </LinearLayout>
    </ScrollView>


</LinearLayout>

JSONParser.java:

import android.util.Log;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.List;

/**
 * Created by WiLo on 3/1/2015.
 */
public class JSONParser {

    static InputStream is = null;
    static JSONObject jObj = null;
    static String json = "";

    // constructor
    public JSONParser() {

    }

    // function get json from url
    // by making HTTP POST or GET mehtod
    public JSONObject makeHttpRequest(String url, String method,
                                      List params) {

        // Making HTTP request
        try {

            // check for request method
            if(method == "POST"){
                // request method is POST
                // defaultHttpClient
                DefaultHttpClient httpClient = new DefaultHttpClient();
                HttpPost httpPost = new HttpPost(url);
                httpPost.setEntity(new UrlEncodedFormEntity(params));

                HttpResponse httpResponse = httpClient.execute(httpPost);
                HttpEntity httpEntity = httpResponse.getEntity();
                is = httpEntity.getContent();

            }else if(method == "GET"){
                // request method is GET
                DefaultHttpClient httpClient = new DefaultHttpClient();
                String paramString = URLEncodedUtils.format(params, "utf-8");
                url += "?" + paramString;
                HttpGet httpGet = new HttpGet(url);

                HttpResponse httpResponse = httpClient.execute(httpGet);
                HttpEntity httpEntity = httpResponse.getEntity();
                is = httpEntity.getContent();
            }


        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    is, "iso-8859-1"), 8);
            StringBuilder sb = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
            is.close();
            json = sb.toString();
        } catch (Exception e) {
            Log.e("Buffer Error", "Error converting result " + e.toString());
        }

        // try parse the string to a JSON object
        try {
            jObj = new JSONObject(json);
        } catch (JSONException e) {
            Log.e("JSON Parser", "Error parsing data " + e.toString());
        }

        // return JSON String
        return jObj;

    }
}

get_all_productos.php

<?php

/*
 * Following code will list all the products
 */

// array for JSON response
$response = array();

// include db connect class
require_once __DIR__ . '/db_connect.php';


// connecting to db
$db = new DB_CONNECT();

// get all products from products table
$result = mysql_query("SELECT *FROM productos") or die(mysql_error());

// check for empty result
if (mysql_num_rows($result) > 0) {
    // looping through all results
    // products node
    $response["productos"] = array();

    while ($row = mysql_fetch_array($result)) {
        // temp user array
        $product = array();
        $product["id"] = $row["id"];
        $product["img"] = $row["img"];
        $product["categoria"] = $row["categoria"];
        $product["marca"] = $row["marca"];
        $product["color"] = $row["color"];
        $product["talla"] = $row["talla"];
        $product["tipo"] = $row["tipo"];
        // push single product into final response array
        array_push($response["productos"], $product);
    }
    // success
    $response["success"] = 1;

    // echoing JSON response
    echo json_encode($response);
} else {
    // no products found
    $response["success"] = 0;
    $response["message"] = "No products found";

    // echo no users JSON
    echo json_encode($response);
}
?>

0 个答案:

没有答案