【问题标题】:How do i save integers to msql database in android?如何将整数保存到android中的sql数据库?
【发布时间】:2014-07-09 22:53:36
【问题描述】:

专家和大师。我正在开发一个 android 应用程序,该应用程序使用复选框获取值,然后使用 JSON Parsing 保存到 mysql 数据库。我设法用字符串来做到这一点,但现在我想保存我不知道如何的整数这样做。这是我用于保存字符串的代码。你能帮助我如何使用相同的代码保存整数。 下面是我的 MainActivity

public class MainActivity extends ActionBarActivity implements OnClickListener {
CheckBox reading, playing;

private ProgressDialog pDialog;

//JSON parser class 
        JSONParser jsonParser = new JSONParser();
         private static final String POST_COMMENT_URL = "http://10.0.2.2:8081/bfc_webservice/scoring.php";

         private static final String TAG_SUCCESS = "success";
         private static final String TAG_MESSAGE = "message";


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    Button button = (Button)findViewById(R.id.btnDisplay);
    button.setOnClickListener(this);
    /*
    button.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
             String hobbies="";
             int firstValue = 0;
             int secondValue = 0;
             int thirdValue = 0;
             int fourthValue = 0;
             int fifthValue = 0;



            if(reading.isChecked())
               firstValue = 10;
            if(playing.isChecked())
                secondValue = 20;
             if(listening.isChecked())
              thirdValue = 30;
             if(singing.isChecked())
              fourthValue = 40;
             if(dancing.isChecked())
              fifthValue = 50;

              textHobbies.setText("Your Hobbies are : " +  firstValue + secondValue + thirdValue + fourthValue) ;

        }
    });
    */


}

@Override
public boolean onCreateOptionsMenu(Menu menu) {

    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();
    if (id == R.id.action_settings) {
        return true;
    }
    return super.onOptionsItemSelected(item);
}

@Override
public void onClick(View v) {
    // TODO Auto-generated method stub
 //final TextView textHobbies = (TextView)findViewById(R.id.result);
    /*
     reading=(CheckBox)findViewById(R.id.chkReading);
     playing=(CheckBox)findViewById(R.id.chkPlay);


    String hobbies="";
    int firstValue = 0;
    int secondValue = 0;



    if(reading.isChecked())
      firstValue = 10;
   if(playing.isChecked())
    secondValue = 20;


     textHobbies.setText("Your Hobbies are : " +  firstValue + secondValue) ;
    */

    new SendComment().execute();
}


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

    @Override
    protected void onPreExecute() {
        // TODO Auto-generated method stub
        super.onPreExecute();
        pDialog = new ProgressDialog(MainActivity.this);
        pDialog.setMessage("Adding scores...");
        pDialog.setIndeterminate(false);
        pDialog.setCancelable(true);
        pDialog.show();
    }

    @Override
    protected String doInBackground(String... arg0) {
        // TODO Auto-generated method stub
        int success;

         reading=(CheckBox)findViewById(R.id.chkReading);
         playing=(CheckBox)findViewById(R.id.chkPlay);


        String hobbies="";
        String firstValue = "";
        String secondValue = "";



        if(reading.isChecked())
          firstValue = "great";
       if(playing.isChecked())
        secondValue = "awesome";


        try{
            //Building parameters
            List<NameValuePair> params = new ArrayList<NameValuePair>();
            params.add(new BasicNameValuePair("reading", firstValue));
            params.add(new BasicNameValuePair("playing", secondValue));

            Log.d("request!", "starting");

            //Posting to the script
            JSONObject json = jsonParser.makeHttpRequest(POST_COMMENT_URL, "POST", params);

            //full json response
            Log.d("Post comment attempt", json.toString());

            //json success element
            success = json.getInt(TAG_SUCCESS);
            if(success == 1){
                Log.d("Comment Added!", json.toString());
                finish();

                return  json.getString(TAG_MESSAGE);


            }else{
                Log.d("Comment Failure", json.toString());
                return json.getString(TAG_MESSAGE);
            }
        }catch(JSONException e){
            e.printStackTrace();
        }
        return null;
    }

    @Override
    protected void onPostExecute(String file_url) {
        // TODO Auto-generated method stub
        //dismiss dialog 
        pDialog.dismiss();
        if(file_url != null){
            Toast.makeText(MainActivity.this, file_url, Toast.LENGTH_LONG).show();
        }
    }



 }

}

这是我的 JSON 解析类

public class JSONParser {

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

公共 JSONParser() {

}

public JSONObject getJSONFromUrl(String url) {

    // Making HTTP request
    try {

        // defaultHttpClient

        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpPost httpPost = new HttpPost(url);


        HttpResponse httpResponse = httpClient.execute(httpPost);
        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;



}   

// function get json from url
// by making HTTP POST or GET mehtod
     public JSONObject makeHttpRequest(String url, String method,
            List<NameValuePair> 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 in parsing data " + e.toString());
            }

            // return JSON String

        return jObj;
     }  

}

如果有人通过修改我现有的代码来帮助我。提前谢谢你。

【问题讨论】:

  • JSON 的结果是string 类型。如果要将其用作整数,则必须将其转换为 int ..

标签: android mysql json integer save


【解决方案1】:

在连接到 SQL 数据库时使用不同数据类型时,我实现这一点的方法是在 PHP 脚本中转换数据。看看下面的 PHP 方法将字符串转换为 Double(因为我将它用于货币值)。确保数据库表中的数据类型也接受整数:

public function storeNewTicket($userId, $amount) {

        $date = date('Y-m-d H:i:s');
        $issuingDate = strtotime($date);
        $newDate = date("Y-m-d H:i:s", $issuingDate);

        $currentBalance = $this->getBalance($userId);
        $floatCurrentBalance = floatval($currentBalance['balance']);
        $floatAmount = (float) $amount;

    $validity = $this->getTicketsForUser($userId);
    $floatValidity = intval($validity['TicketValidity']);

}

在上面的代码中,我同时使用了floatvalintval 这取决于你想要一个整数值还是一个小数。

希望这会有所帮助:)

【讨论】:

    猜你喜欢
    • 2018-08-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-03
    • 1970-01-01
    • 1970-01-01
    • 2015-08-15
    相关资源
    最近更新 更多