9

こんにちは、php を使用して mysql データベースからデータを取得しています。データの受信に成功したら、データを印刷する必要がある新しいアクティビティを呼び出します。

これは私のコードです:

public class RecoProd extends Activity {
    EditText pd;
    TextView error;

    ArrayList<NameValuePair> postParameters;
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.recomain);
        pd = (EditText) findViewById(R.id.name);

        error = (TextView) findViewById(R.id.myTableLayout);

        pd.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                postParameters = new ArrayList<NameValuePair>();
                postParameters.add(new BasicNameValuePair("product", pd
                        .getText().toString()));


                // String valid = "1";

                DownloadWebPageTask dw = new DownloadWebPageTask();
                dw.execute("");

            }
        });
    }

    private class DownloadWebPageTask extends AsyncTask<String, Void, String> {
        @Override
        protected String doInBackground(String... urls) {
            String response = null;
            for (String url : urls) {
                try {
                    response = CustomHttpClient.executeHttpPost("http://10.0.2.2/abc/check2.php", postParameters);  
                    String res = response.toString();
                    // res = res.trim();
                    res = res.replaceAll("\\s+", "");
                    // error.setText(res);
                    if(res.equals("1")){     ***<<--------------I think the error is here***
                        Intent loginintent = new Intent(RecoProd.this, RecoProd1.class);
                        startActivity(loginintent);
                    }
                    else
                        error.setText("Sorry!! ");





                } catch (Exception e) {


                }
            }
            return response;
        }

        @Override
        protected void onPostExecute(String result) {
        }
    }
}

これは私のphpコードです:

<?php
$pd=$_POST['name'];

//connect to the db
$user = "root";
$pswd = "";
$db = "mylogin";
$host = "localhost";
$conn = mysql_connect($host, $user, $pswd);
mysql_select_db($db);

$query = "SELECT * FROM recoprod  ";
$result = mysql_query("SELECT * FROM recoprod");
while($row = mysql_fetch_array($result))
  {
  $output[]=$row;
  }
/*
$result = mysql_query($query) or die("Unable to verify user because : " . mysql_error());
//this is where the actual verification happens  
if(mysql_num_rows($result) > 0)  
echo 1;  // for correct login response  
else  
echo 0; // for incorrect login response */
?>

実行すると力が入ります。

EDITED CODE





package com.androidhive.googleplacesandmaps;

import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
import java.util.ArrayList;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
public class RecoProd extends Activity {
    EditText pd;
    TextView error;

    ArrayList<NameValuePair> postParameters;
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {

        try {
            Class<?> strictModeClass = Class.forName("android.os.StrictMode", true, Thread.currentThread()
                    .getContextClassLoader());

            Class<?> threadPolicyClass = Class.forName("android.os.StrictMode$ThreadPolicy", true, Thread
                    .currentThread().getContextClassLoader());

            Class<?> threadPolicyBuilderClass = Class.forName("android.os.StrictMode$ThreadPolicy$Builder", true,
                    Thread.currentThread().getContextClassLoader());

            Method setThreadPolicyMethod = strictModeClass.getMethod("setThreadPolicy", threadPolicyClass);

            Method detectAllMethod = threadPolicyBuilderClass.getMethod("detectAll");
            Method penaltyMethod = threadPolicyBuilderClass.getMethod("penaltyLog");
            Method buildMethod = threadPolicyBuilderClass.getMethod("build");

            Constructor<?> threadPolicyBuilderConstructor = threadPolicyBuilderClass.getConstructor();
            Object threadPolicyBuilderObject = threadPolicyBuilderConstructor.newInstance();

            Object obj = detectAllMethod.invoke(threadPolicyBuilderObject);

            obj = penaltyMethod.invoke(obj);
            Object threadPolicyObject = buildMethod.invoke(obj);
            setThreadPolicyMethod.invoke(strictModeClass, threadPolicyObject);

        } catch (Exception ex) {
            String TAG = null;
            Log.w(TAG, ex);
        }
        super.onCreate(savedInstanceState);
        setContentView(R.layout.recomain);
        pd = (EditText) findViewById(R.id.name);

        error = (TextView) findViewById(R.id.showresult);

        pd.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                postParameters = new ArrayList<NameValuePair>();
                postParameters.add(new BasicNameValuePair("product", pd
                        .getText().toString()));


                // String valid = "1";

                DownloadWebPageTask dw = new DownloadWebPageTask();
                dw.execute("");

            }
        });
    }

    private class DownloadWebPageTask extends AsyncTask<String, Void, String> {
        @Override
        protected String doInBackground(String... urls) {
            String response = null;
            for (String url : urls) {
                try {
                    response = CustomHttpClient.executeHttpPost("http://10.0.2.2/abc/check2.php", postParameters);  
                    String res = response.toString();
                    // res = res.trim();
                    res = res.replaceAll("\\s+", "");
                    // error.setText(res);
                    try{
                        res = "";
                  JSONArray jArray = new JSONArray(res);
                        for(int i=0;i<jArray.length();i++){
                                JSONObject json_data = jArray.getJSONObject(i);
                                Log.i("prod_id","id: "+json_data.getInt("prod_id")+
                                        ", prod_name: "+json_data.getString("prod_name")+
                                        ", prod_category: "+json_data.getInt("prod_category")+
                                        ", prod_cost: "+json_data.getInt("prod_cost")
                                );
                                //Get an output to the screen
                                res += "\n" + json_data.getString("prod_id") + " -> "+ json_data.getInt("prod_name");
                        }
                }
                catch(JSONException e){
                        Log.e("log_tag", "Error parsing data "+e.toString());
                }

                try{
                 error.setText(res);
                }
                catch(Exception e){
                 Log.e("log_tag","Error in Display!" + e.toString());;          
                }   
           }
                 catch (Exception e) {
            Log.e("log_tag","Error in http connection!!" + e.toString());     
           }
            }
            return response;

               }
        @Override
        protected void onPostExecute(String result) {
        }
    }
}

これは私のphpコードです:

<?php
$pd = $_POST['name'];

//connect to the db
$user = "root";
$pswd = "";
$db = "mylogin";
$host = "localhost";
$conn = mysql_connect($host, $user, $pswd);
mysql_select_db($db);

$query = "SELECT * FROM recoprod  ";
$result = mysql_query("SELECT * FROM recoprod");
while($row = mysql_fetch_array($result)) {
    $output[] = $row;
}
print(json_encode($output));
mysql_close();
/*
$result = mysql_query($query) or die("Unable to verify user because : " . mysql_error());
//this is where the actual verification happens  
if(mysql_num_rows($result) > 0)  
echo 1;  // for correct login response  
else  
echo 0; // for incorrect login response */
?>

こんにちは、上記の編集されたコードを確認するためにいくつかの変更を加えました。

そして、各行に4つのデータを含むフェッチする行は2行しかありません。

4

2 に答える 2

2

あなたの問題は AsyncTask 部分にあります

AsyncTask を使用すると、doInBackground 関数でデータを処理できますが、onPostExecute で UI を更新します。AndroidでAsyncTaskを使用すると、ロードが完了した後にレイアウト上のものを変更できるため、処理された値をonPostExecuteに返します。ただし、onPostExecute 状態でのみなので、json を doInBackground で処理し、それを onPostExecute のレイアウトに反映します

public class RecoProd extends Activity {
EditText pd;
TextView error;

ArrayList<NameValuePair> postParameters;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.recomain);
    pd = (EditText) findViewById(R.id.name);

    error = (TextView) findViewById(R.id.myTableLayout);

    pd.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            postParameters = new ArrayList<NameValuePair>();
            postParameters.add(new BasicNameValuePair("product", pd
                    .getText().toString()));


            // String valid = "1";

            DownloadWebPageTask dw = new DownloadWebPageTask();
            dw.execute("");

        }
    });
}

private class DownloadWebPageTask extends AsyncTask<String, Void, String> {
    @Override
    protected String doInBackground(String... urls) {
        String response = null;
        for (String url : urls) {
            try {
                response = CustomHttpClient.executeHttpPost("http://10.0.2.2/abc/check2.php", postParameters);  
                String res = response.toString();
                // res = res.trim();
                res = res.replaceAll("\\s+", "");
                // error.setText(res);






            } catch (Exception e) {


            }
        }
        return res;
    }

    @Override
    protected void onPostExecute(String result) {

         if(result.equals("1")){    
             Intent loginintent = new Intent(RecoProd.this, RecoProd1.class);
             startActivity(loginintent);
         }
         else
             error.setText("Sorry!! ");
    }
}

}

于 2013-02-20T05:53:41.297 に答える
0

これがあなたができることです:

public class RecoProd extends Activity {
EditText pd;
TextView error;

ArrayList<NameValuePair> postParameters;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.recomain);
    pd = (EditText) findViewById(R.id.name);

    error = (TextView) findViewById(R.id.myTableLayout);

    pd.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            postParameters = new ArrayList<NameValuePair>();
            postParameters.add(new BasicNameValuePair("product", pd
                    .getText().toString()));


            // String valid = "1";

            downloadWebPageTask();

        }
    });
}

private void downloadWebPageTask extends AsyncTask<String, Void, String> {
    String url = "http://10.0.2.2/abc/check2.php?postParameters=paramValue";
    grabURL(url);
}


public void grabURL(String url){
    try {
        new GrabURL().execute(new URL(url));
    } catch (MalformedURLException e) {
        e.printStackTrace();
    }
}

private class GrabURL extends AsyncTask<URL, Integer, JSONObject> {

    @Override
    protected JSONObject doInBackground(URL... urls) {
        // This method will send the http request
        JSONObject jsonResponse=null;
        try 
        {
            URL link = urls[0];
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpGet request = new HttpGet(link.toString());
            ResponseHandler<String> responseHandler=new BasicResponseHandler();
            String responseBody = httpClient.execute(request, responseHandler);
            jsonResponse = new JSONObject(responseBody);
        }
        catch (Exception e) {
            e.printStackTrace();
        }

        return jsonResponse;
    }

    @Override
    protected void onPreExecute() {
        // This method will be executed before the http request
        // In this method you can do things like showing the loading sign
    }

    @Override
    protected void onPostExecute(JSONObject jsonObj) {
        // This method will run after the http request and contains the results
        // This method expectes you return a valid jSon from the server
        try {
            if(! jsonObj.getString("code").equalsIgnoreCase("200") ){
                // Bad response from server
            }
            else if( jsonObj.has("data") ){
                JSONArray dataArray = jsonObj.getJSONArray("data");

                String tmpUserLoc = (String) jsonObj.getJSONObject("data").get("userLocation");
                String tempUserNIC = (String) jsonObj.getJSONObject("data").get("userNIC");
            }

        } catch (JSONException e) {
            e.printStackTrace();
        }
        // You can stop the loading sign here if you showed it in OnPreExecute
    }

}

}

このコードはテストしていませんが、動作するはずです。サーバーからjSonArrayを返す場合は、jSonArray docを参照するか、このリンクも役立つ可能性があります。

于 2013-02-25T21:41:58.660 に答える