本文介绍了的Andr​​oid + JSON度日ID图片的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可以选择和显示所有的从数据库中的图像。现在我特林按ID过滤。我如何通过id来获取图像从数据库?

I can select and show all the images from the db. Now I am tring to filter them by id. How do I get images from db by id?

有没有办法从数据库中选择了imovel_idJSON响应比较的AsyncTask里面的字符串imovel_id?

Is there a way to compare the string "imovel_id" inside the AsyncTask with the "imovel_id" json response selected from the db?

还是更通过要求从Android应用程序发送到得到字符串imovel_id,然后按imovel_id全选图像?

Or is it better to get the string "imovel_id" via request sent from the android app and then select all the images by "imovel_id"?

我想,在低于code从AsyncTask的发送串,得到它在PHP请求,然后使用带WHERE clausule查询,但我没有成功。我得到一个空值。

I tried that on the below code sending the string from the AsyncTask, getting it on php request and then using the query with WHERE clausule but I had no success. I get a null value.

public class AsyncHttpTask extends AsyncTask<String, Void, Integer> {

    @Override
    protected Integer doInBackground(String... params) {

        ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
        nameValuePairs.add(new BasicNameValuePair("imovel_id", i_id));

        try {
            HttpClient httpclient = new DefaultHttpClient();
            HttpPost httppost = new HttpPost("http://meuwebsite.com/panel/json_images.php");
            httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
            HttpResponse response = httpclient.execute(httppost);
            HttpEntity entity = response.getEntity();
            inputStream = entity.getContent();
            Log.e("pass 1", "connection success ");
        } catch (Exception e) {
            Log.e("Fail 1", e.toString());
            Toast.makeText(getApplicationContext(), "Invalid IP Address",
                    Toast.LENGTH_LONG).show();
        }

        try {
            BufferedReader reader = new BufferedReader
                    (new InputStreamReader(inputStream, "UTF-8"));
            StringBuilder sb = new StringBuilder();
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
            inputStream.close();
            result = sb.toString();
            Log.e("pass 2", "connection success ");
        } catch (Exception e) {
            Log.e("Fail 2", e.toString());
        }

        try {
            JSONObject json_data = new JSONObject(result);
            i_id = (json_data.getString("imovel_id"));
            Log.e("pass 1", "id do imovel = " + i_id);
        } catch (Exception e) {
            Log.e("Fail 3", e.toString());
        }


        Integer result = 0;
        try {
            // Create Apache HttpClient
            HttpClient httpclient = new DefaultHttpClient();
            HttpResponse httpResponse = httpclient.execute(new HttpGet(params[0]));
            int statusCode = httpResponse.getStatusLine().getStatusCode();

            // 200 represents HTTP OK
            if (statusCode == 200) {
                String response = streamToString(httpResponse.getEntity().getContent());
                parseResult(response);
                result = 1; // Successful
            } else {
                result = 0; //"Failed
            }
        } catch (Exception e) {
            Log.d(TAG, e.getLocalizedMessage());
        }

        return result;
    }

    @Override
    protected void onPostExecute(Integer result) {
        // Download complete. Lets update UI

        if (result == 1) {
            mGridAdapter.setGridData(mGridData);
        } else {
            Toast.makeText(GridViewActivity.this, "Failed to fetch data!", Toast.LENGTH_SHORT).show();
        }

        //Hide progressbar
        mProgressBar.setVisibility(View.GONE);
    }
}


String streamToString(InputStream stream) throws IOException {
    BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(stream));
    String line;
    String result = "";
    while ((line = bufferedReader.readLine()) != null) {
        result += line;
    }

    // Close stream
    if (null != stream) {
        stream.close();
    }
    return result;
}

/**
 * Parsing the feed results and get the list
 *
 * @param result
 */
private void parseResult(String result) {
    try {
        JSONObject response = new JSONObject(result);
        JSONArray posts = response.optJSONArray("posts");
        GridItem item;

        for (int i = 0; i < posts.length(); i++) {

            JSONObject post = posts.optJSONObject(i);

            item = new GridItem();
            item.setImage(post.getString("images"));

            mGridData.add(item);
        }
    } catch (JSONException e) {
        e.printStackTrace();
    }
}

PHP脚本

include_once 'db_connect.php';

$i_id = $_REQUEST["imovel_id"];

$sql = "SELECT * FROM iMoveis WHERE imovel_id='$i_id'";
$result = mysqli_query($mysqli, $sql);

$response = array();
$images = array();


while($row = mysqli_fetch_assoc($result)){

 $images[] = array('images' => $row['img1']);
 $images[] = array('images' => $row['img2']);
 $images[] = array('images' => $row['img3']);
 $images[] = array('images' => $row['img4']);
 $images[] = array('images' => $row['img5']);

}

$response['posts'] = $images;

echo json_encode($response, JSON_UNESCAPED_SLASHES);

添加JSON数组里面的ID,然后将其从TextView的比较parseResult方法使用字符串imovel_id里面可能是一个解决方案吗?

Adding the id inside the json array and then comparing it inside the parseResult method with the string "imovel_id" from the textview could be a solution?

我想,我已经做和使用WHERE查询过滤它会很容易被namevaluepairs中发送的字符串,但它似乎没有that's工作那么容易。

I thought it would be easy sending the string by nameValuePairs as I have already done and use a WHERE in the query to filter but it seems that´s not working so easily.

先谢谢了。

推荐答案

我改变了我的AsyncTask的一些修改

I made some changes in my AsyncTask

public class AsyncHttpTask extends AsyncTask<String, Void, Integer> {

    @Override
    protected Integer doInBackground(String... params) {

        ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
        nameValuePairs.add(new BasicNameValuePair("imovel_id", i_id));


        Integer result = 0;
        try {
            // Create Apache HttpClient
            HttpClient httpclient = new DefaultHttpClient();
            HttpPost httppost = new HttpPost("http://meuwebsite.com/panel/json_images.php");
            httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
            HttpResponse httpResponse = httpclient.execute(httppost);

            int statusCode = httpResponse.getStatusLine().getStatusCode();

            // 200 represents HTTP OK
            if (statusCode == 200) {
                String response = streamToString(httpResponse.getEntity().getContent());
                parseResult(response);
                result = 1; // Successful
            } else {
                result = 0; //"Failed
            }
        } catch (Exception e) {
            Log.d(TAG, e.getLocalizedMessage());
        }

        return result;
    }

    @Override
    protected void onPostExecute(Integer result) {
        // Download complete. Lets update UI

        if (result == 1) {
            mGridAdapter.setGridData(mGridData);
        } else {
            Toast.makeText(GridViewActivity.this, "Failed to fetch data!", Toast.LENGTH_SHORT).show();
        }

        //Hide progressbar
        mProgressBar.setVisibility(View.GONE);
    }
}


String streamToString(InputStream stream) throws IOException {
    BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(stream));
    String line;
    String result = "";
    while ((line = bufferedReader.readLine()) != null) {
        result += line;
    }

    // Close stream
    if (null != stream) {
        stream.close();
    }
    return result;
}

/**
 * Parsing the feed results and get the list
 *
 * @param result
 */
private void parseResult(String result) {
    try {
        JSONObject response = new JSONObject(result);
        JSONArray posts = response.optJSONArray("posts");
        GridItem item;
        for (int i = 0; i < posts.length(); i++) {
            JSONObject post = posts.optJSONObject(i);
            item = new GridItem();
            item.setImage(post.getString("images"));
            mGridData.add(item);
        }
    } catch (JSONException e) {
        e.printStackTrace();
    }
}

也改变 $ i_id = $ _REQUEST [imovel_id]; $ i_id = $ _ POST [imovel_id];

这篇关于的Andr​​oid + JSON度日ID图片的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-20 14:31