【问题标题】:Passing Parameter into php from Android从Android将参数传递给php
【发布时间】:2012-06-18 22:30:40
【问题描述】:

在我的安卓系统中:

    String cat_id = getIntent().getExtras().getString("category_id");

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

    try {
        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost(
                "http://www.---.com/items.php");
        httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
        HttpResponse response = httpclient.execute(httppost);
        HttpEntity entity = response.getEntity();
        is = entity.getContent();
    } catch (Exception e) {
        Log.e("log_tag", "Error in http connection" + e.toString());
    }

在我的 PHP 中:

// editing out DB connections which have been verified to work


 <?php
$sql=mysql_query("SELECT * FROM items WHERE cat_id = '".$_REQUEST['cat_id']."'");
while($row=mysql_fetch_assoc($sql))
    $output[]=$row;
print(json_encode($output));
mysql_close();
 ?>

所以我的问题是它什么都不返回(在 JSON 结果部分——Toast 说“未找到任何项目”)。我的代码是否正确,我将参数从 Android 传递到 PHP 的方式?

【问题讨论】:

  • 我不确定,但 $output[] = $row,对吗?您不应该保留一个计数器变量,它会递增并将值分配给 $output。
  • 您是否尝试验证 $output 是否正确?如果你的 PHP 脚本被浏览器调用,它会返回什么?
  • @ppsreejith 是的,在 PHP 中可以以这种方式将值推送到数组中。
  • 当我这样做时: $sql=mysql_query("select * from items");两个测试项目正常显示在 Android 应用程序中。所以问题似乎是我传递参数的方式?
  • @raina77ow 在浏览器中显示“null”

标签: php android mysql parameters


【解决方案1】:

这行不应该

$sql=mysql_query("SELECT * FROM items WHERE cat_id = '".$_REQUEST['cat_id']."'");

成为

$sql=mysql_query("SELECT * FROM items WHERE cat_id = '".$_POST['cat_id']."'");

即$_REQUEST 到 $_POST?

我建议使用 Firefox 的 Firebug 插件,并跟踪发送到服务器的确切表单。

【讨论】:

  • 通常$_REQUEST 包含 $_POST 和 $_GET。不过可能是个问题。
  • 我想我可能抓到了什么。 cat_id 在到达 php.ini 之前在 Android 部分中返回为 null。我不认为它没有正确地从捆绑包中获取价值。
【解决方案2】:

我知道是什么,不回答不是任何人的错。

问题开始于之前 Java 传递给 PHP。这是一个传递到相关 Java Activity 的包。我有一个简单的错误,涉及使用不正确的原语,这反过来导致通过捆绑传递空值。

null 继续沿着路径向下并落在 PHP 部分。所以上面显示的代码实际上是正确的。

【讨论】:

    【解决方案3】:

    CustomList.java :->

    import android.app.Activity;
    import android.content.Context;
    import android.graphics.Typeface;
    import android.view.LayoutInflater;
    import android.view.View;
    import android.view.ViewGroup;
    import android.widget.ArrayAdapter;
    import android.widget.ImageView;
    import android.widget.TextView;
    
    public class CustomList extends ArrayAdapter<String>{
    
    private final Activity context;
    private final String[] web;
    private final String[] imageId;
    Context ct;
    public CustomList(Activity context,
    String[] web, String[] imageId) {
    super(context, R.layout.list_single, web);
    this.context = context;
    this.web = web;
    this.imageId = imageId;
    ct=context;
    
    }
    @Override
    public View getView(int position, View view, ViewGroup parent) {
    LayoutInflater inflater = context.getLayoutInflater();
    View rowView= inflater.inflate(R.layout.list_single, null, true);
    TextView txtTitle = (TextView) rowView.findViewById(R.id.txt);
    TextView txtval=(TextView)rowView.findViewById(R.id.val);
    
    //Typeface tf=Typeface.createFromAsset(ct.getAssets(), "saral.ttf");
    //Typeface tf=Typeface.createFromAsset(ct.getAssets(), "shrutib.ttf");
    //txtTitle.setTypeface(tf);
    //txtTitle.setText(web[position]);
    //txtval.setTypeface(tf);
    txtval.setText(imageId[position]);
    //ImageView imageView = (ImageView) rowView.findViewById(R.id.img);
    
    //imageView.setImageResource(imageId[position]);
    return rowView;
    }
    }
    

    MainActivity.java :->

    package learn2crack.customlistview;
    
    import java.io.BufferedReader;
    import java.io.InputStream;
    import java.io.InputStreamReader;
    
    import org.apache.http.HttpEntity;
    import org.apache.http.HttpResponse;
    import org.apache.http.client.HttpClient;
    import org.apache.http.client.methods.HttpPost;
    import org.apache.http.impl.client.DefaultHttpClient;
    import org.json.JSONArray;
    import org.json.JSONException;
    import org.json.JSONObject;
    
    import android.net.ParseException;
    import android.os.Bundle;
    import android.os.StrictMode;
    import android.util.Log;
    import android.view.View;
    import android.widget.AdapterView;
    import android.widget.ArrayAdapter;
    import android.widget.ListView;
    import android.widget.Toast;
    import android.app.Activity;
    import android.content.Intent;
    
    
    public class MainActivity extends Activity {
        ListView list;
    
        String result = null;
        InputStream is = null;
        StringBuilder sb = null;
    
        String[] web=null;
        String[] imageId = null;
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
    
    
            StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
            StrictMode.setThreadPolicy(policy); 
    
            // http post
    try {
    HttpClient httpclient = new DefaultHttpClient();
    HttpPost httppost = new HttpPost("link of php page");
    // httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
    HttpResponse response = httpclient.execute(httppost);
    HttpEntity entity = response.getEntity();
    is = entity.getContent();
    } catch (Exception e) {
    Log.e("log_tag", "Error in http connection" + e.toString());
                    }
    
                    // convert response to string
    try {
    BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8);
    sb = new StringBuilder();
    sb.append(reader.readLine() + "\n");
    String line = "0";
    while ((line = reader.readLine()) != null) {
        sb.append(line + "\n");
        }
    is.close();
    result = sb.toString();
    } catch (Exception e) {
        Log.e("log_tag", "Error converting result " + e.toString());
    }   
    
    // paring data
    //JSONObject jArray;
    JSONArray jArray;
        try {
        jArray = new JSONArray(result);
        JSONObject json_data = null;
        web = new String[jArray.length()];
        imageId=new String[jArray.length()];
        for (int i = 0; i < jArray.length(); i++) {
    json_data = jArray.getJSONObject(i);
    web[i] = json_data.getString("category_id");
    imageId[i] = json_data.getString("category_name");
    }
    } catch (JSONException e1) {
    Toast.makeText(getBaseContext(), "No City Found", Toast.LENGTH_LONG).show();
    } catch (ParseException e1) {
    e1.printStackTrace();
    }
    CustomList adapter = new CustomList(MainActivity.this, web, imageId);
    list=(ListView)findViewById(R.id.list);
    list.setAdapter(adapter);
    list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
    
                        @Override
         public void onItemClick(AdapterView<?> parent, View view,int position, long id) {
    Intent newint=new Intent(getApplicationContext(), subcatcls.class);
    newint.putExtra("cat_id",web[+ position]);
                            startActivity(newint);
                        }
                    });
        }
    }
    

    在 PHP 代码中 使用 print_r 代替打印

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-10-04
      • 2012-04-14
      • 2015-10-05
      • 1970-01-01
      • 2011-11-22
      相关资源
      最近更新 更多