dpca31461 2015-06-02 06:54
浏览 37

数据插入使用PHP SQL和Android App

I have created a application for connecting the PHP, Mysql & Android. I am inserting the Name , Price & Description. Layout is good, ids given perfect but the data is not inserting into SQL DB.

package com.oplo.user.demo2;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.StrictMode;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;

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

/**
 * Created by user on 6/2/2015.
 */
@SuppressWarnings("deprecation")
public class addRecord extends Activity {
    @SuppressLint("NewApi")
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add);

        if(android.os.Build.VERSION.SDK_INT  > 9)
        {
            StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
            StrictMode.setThreadPolicy(policy);
        }
        final EditText txtA = (EditText) findViewById(R.id.txtA);
        final EditText txtB = (EditText) findViewById(R.id.txtB);
        final EditText txtC = (EditText) findViewById(R.id.txtC);

        final Button getData = (Button) findViewById(R.id.btnSave);
        final Button btnBack = (Button) findViewById(R.id.btnBack);

        btnBack.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                Intent i = new Intent(getApplicationContext(), MainActivity.class);
                startActivity(i);

            }
        });
        getData.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                if(txtA.getText().length()<2){
                    Toast.makeText(getApplicationContext(), "Input Name", Toast.LENGTH_LONG).show();
                }if(txtB.getText().length()<2){
                    Toast.makeText(getApplicationContext(), "Input Price", Toast.LENGTH_LONG).show();
                }if(txtC.getText().length()<2){
                    Toast.makeText(getApplicationContext(), "Input Description", Toast.LENGTH_LONG).show();
                }else{

                    String url = "http://www.xyz.in/demo.php";
                    List params = new ArrayList();
                    //noinspection deprecation
                    params.add(new BasicNameValuePair("strA", txtA.getText().toString()));
                    params.add(new BasicNameValuePair("strB", txtB.getText().toString()));
                    params.add(new BasicNameValuePair("strC", txtC.getText().toString()));

                    @SuppressWarnings("unused")
                    String resultServer  = getHttpPost(url,params);
                    //result.setText(resultServer);
                    Toast.makeText(addRecord.this, "1 Record inserted...", Toast.LENGTH_LONG).show();
                    emtyText();
                    txtA.requestFocus();
                }

            }
            public void emtyText(){
                txtA.setText("");
                txtB.setText("");
                txtC.setText("");
            }
        });


    }


    public String getHttpPost(String url,List params) {
        StringBuilder str = new StringBuilder();
        HttpClient client = new DefaultHttpClient();
        HttpPost httpPost = new HttpPost(url);

        try {
            httpPost.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));
            HttpResponse response = client.execute(httpPost);
            StatusLine statusLine = response.getStatusLine();
            int statusCode = statusLine.getStatusCode();
            if (statusCode == 200) { // Status OK
                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 result..");
            }
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return str.toString();
    }


}

PHP Code:

<?php


$host = "localhost";
    $user = "xcxc";
    $pass = "xcxc";
    $database = "xcxc";
    
    $con = mysql_connect($host, $user, $pass) or die("Cannot connect Database");
    mysql_select_db($database) or die("Cannot select Database.");
    
    $a = $_POST["strA"];
    $b = $_POST["strB"];
    $c = $_POST["strC"];
    
    $sql = "INSERT INTO demo (name, price, description) VALUES('$a', '$b', '$c')";
    $result = mysql_query("SET NAMES 'UTF8'", $con);
    $result = mysql_query($sql, $con);
    if(!$result){
        die ('Error: '.mysql_error($con));
    }
    //echo "1 record added...";
    mysql_close($con);

Heres my code, but the data is not inserting into SQL.

Please let me know wheres the problem in this code.

thanks in advance.

</div>
  • 写回答

1条回答 默认 最新

  • duanbi3786 2015-06-02 08:07
    关注

    You are not allowed to do any network related stuff on your main thread,go for asynctask or retrofit. this link may help http://www.androidhive.info/2012/05/how-to-connect-android-with-php-mysql/

    评论

报告相同问题?

悬赏问题

  • ¥15 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题