【问题标题】:How do I retrieve a columns value from a table which is stored on a server?如何从存储在服务器上的表中检索列值?
【发布时间】:2014-03-23 20:15:39
【问题描述】:

我有一个安卓应用程序。我在虚拟主机上免费注册了我的域名。我的域名是“www.xyz.site” 在虚拟主机上,在 MySQL 中,我有一个数据库,其中有一个名为“users”的表,其中包含一个名为“amount”的列。在我的 android 应用程序的一项活动“Payment1Activity.java”中,我想从服务器获取该值并从中扣除一些特定金额,这是我的一个 xml 文件“perryroad.xml”中的一个文本视图,并将新金额保存回来到“用户”表的“金额”列。 我的活动 Payment1Activity.java 如下:

package com.example.streetsystemparking;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONObject;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.RemoteViews;
//import com.example.streetsystemparking.MainActivity; 


public class Payment1Activity extends Activity {
Button b,br1;
EditText et,pass;
TextView tv;
HttpPost httppost;
StringBuffer buffer;
HttpResponse response;
HttpClient httpclient;
List<NameValuePair> nameValuePairs;
ProgressDialog dialog = null;
String status;
String uid;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_payment1);
    b = (Button)findViewById(R.id.Button01);  
    et = (EditText)findViewById(R.id.accountno);
    pass= (EditText)findViewById(R.id.password);
   // tv = (TextView)findViewById(R.id.tv);

    b.setOnClickListener(new OnClickListener() {


        @Override
        public void onClick(View v) {

            dialog = ProgressDialog.show(Payment1Activity.this, "", 
                    "Validating user...", true);
             new Thread(new Runnable() {
                    public void run() {
                        payment();                        
                    }
                  }).start();               
        }
    });
 }

void payment(){
try{            

httpclient=new DefaultHttpClient();
httppost= new HttpPost("http://tanushreedutta.site40.net/payment_new/check.php");
        //add your data
nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("accno",et.getText().toString().trim()));                                         
    nameValuePairs.add(new BasicNameValuePair("bpassword",
                                 pass.getText().toString().trim())); 
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
        //Execute HTTP Post Request
response=httpclient.execute(httppost);
ResponseHandler<String> responseHandler = new BasicResponseHandler();
final String response = httpclient.execute(httppost, responseHandler);
        //System.out.println("Response : " + response); 
runOnUiThread(new Runnable() {
public void run() {
                //tv.setText("Response from PHP : " + response);
dialog.dismiss();
            }
        });
if(response.startsWith("User Found")){
            new Thread(new Runnable() {
                public void run() {

                    update();                         
                }

              }).start();   

    runOnUiThread(new Runnable() {
    public void run() {
        //Here I want to take that amount from mysql table and subtract the textview          
          (taken from perryroad.xml) value from it and store that new value back to                
          mysql table.                      
        Toast.makeText(Payment1Activity.this,"Payment Successful for block 1", 
                      Toast.LENGTH_SHORT).show();
Toast.makeText(Payment1Activity.this,"You reserved block 
                          1",Toast.LENGTH_LONG).show();

                    setResult(1); 
                }
            });
startActivity(new Intent (Payment1Activity.this,VacatingCredentials.class));


        }else{
            showAlert();        
        }

    }catch(Exception e){
        dialog.dismiss();
        System.out.println("Exception : " + e.getMessage());
    }
}
 public void update()
    {
        try
        {
        uid="1";
    status="2";
    HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://tanushreedutta.site40.net/map/map.php");
            nameValuePairs = new ArrayList<NameValuePair>(2);

            nameValuePairs.add(new BasicNameValuePair("uid",uid));
            nameValuePairs.add(new BasicNameValuePair("status",status));
            httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
            response = httpclient.execute(httppost); 
           ResponseHandler<String> responseHandler = new BasicResponseHandler();
    final String response = httpclient.execute(httppost, responseHandler);
           // HttpEntity entity = response.getEntity();
           // is = 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();
        }     
    }
public void showAlert(){
    Payment1Activity.this.runOnUiThread(new Runnable() {
        public void run() {
     AlertDialog.Builder builder = new AlertDialog.Builder(Payment1Activity.this);
       builder.setTitle("Payment Error.");
       builder.setMessage("User not Found.")  
       .setCancelable(false)
       .setPositiveButton("OK", new DialogInterface.OnClickListener() {
       public void onClick(DialogInterface dialog, int id) {
           Toast.makeText(Payment1Activity.this,"Invalid Account number or Password,Try 
                         Again",Toast.LENGTH_LONG).show();
                            }
                   });                     
            AlertDialog alert = builder.create();
            alert.show();               
        }
    });
   }

    }

我的 perryroad.xml 文件如下:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:background="@drawable/p5" >

<TextView
    android:id="@+id/textView1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentTop="true"
    android:layout_marginLeft="10dp"
    android:layout_marginTop="40dp"
    android:text="Address: Perry Road, Bandra" 
    android:textAppearance="?android:attr/textAppearanceLarge" />

<TextView
    android:id="@+id/textView2"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginLeft="103dp"
    android:orientation="horizontal"
    android:text="West, Mumbai"
    android:textAppearance="?android:attr/textAppearanceLarge" />

 <TextView
    android:id="@+id/textView3"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
     android:layout_marginTop="25dp"
    android:layout_marginLeft="10dp"
    android:orientation="horizontal"
    android:text="Parking charges: Rs."
    android:textAppearance="?android:attr/textAppearanceLarge" />

 <TextView
     android:id="@+id/textView4"
     android:layout_width="wrap_content"
     android:layout_height="wrap_content"
     android:layout_marginLeft="220dp"
     android:orientation="horizontal"
     android:text="20"
     android:textAppearance="?android:attr/textAppearanceLarge" />

<Button
    android:id="@+id/b1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_below="@+id/editText1"
    android:layout_gravity="center"
    android:orientation="horizontal"
    android:layout_marginTop="50dp"
    android:text="Get Direction"
    android:textColor="#000000"
    android:textAppearance="?android:attr/textAppearanceLarge" />

<Button
    android:id="@+id/b2"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginTop="50dp"
    android:text="Get Map"
    android:layout_gravity="center"
     android:textColor="#000000"
    android:textAppearance="?android:attr/textAppearanceLarge" />

  </LinearLayout>

我想通过 getText() 从这个 textview4 访问“20”,那么它的语法是什么? 谁能帮我这个 ?任何建议或意见将不胜感激。谢谢。

【问题讨论】:

    标签: java android mysql database


    【解决方案1】:

    实现此功能的方法很少,这取决于您的专业水平和您想要获得的数据类型。我会给你一些基本的步骤,但你需要实现一些东西并尝试一下。

    客户端编码的步骤;即在您的 java 类中。

    1。创建 HttpClient

    2。创建 HttpGet 或 HttpPost 并使用 get 或 post URL 对其进行初始化。 (再次获取或发布是您的选择,具体取决于数据类型)

    3。执行您的 get/post 对象,您将获得作为 HttpResponse 对象的响应

    4。然后,您可以使用缓冲区读取器、字符串生成器、输入流等概念来获取所需的数据。

    服务器端代码的步骤,即通常是服务器上的 php 文件

    --您可以使用 XML、JSON 或任何其他已定义的方法来获取数据,您必须正确编码 JSON,然后使用 JSONparser 类在客户端代码上对其进行解码,类似于 XML 的概念

    -- 如果您是初学者,更简单的方法是尝试使用 mysql 查询并在 php 中使用 'echo' 一次从服务器返回一行。使用 post 方法并将不同的参数传递给服务器,编写不同类型的 mysql 查询以获得所需的结果。一旦你与他们相处融洽,你就可以继续学习 JSON 的概念。如果您以前从未做过 JSON 并且会尝试直接做它可能看起来有点混乱。

    还请在发布问题时提及具体问题,因为这是一个非常广泛的主题,无法在一篇文章中回答。

    编辑:不要忘记在清单文件中指定使用互联网的权限,并使用 AsynkTask 和线程来执行耗时的任务

    编辑 2 根据您的评论,您想访问某个用户的一列值,对吗?例如,您有 5 列; id、name、surname、password、amount 并且您只想检索特定用户的金额。如果这是您要查找的内容,那么您需要编写一个 mysql 查询,使其仅返回特定行的列值(这需要在您的 php 的服务器端完成),或者您只能获取您的列值需要通过它的 id 从 JSON 响应中获取(这需要在解析 JSON 响应时在客户端完成)

    我写了一个答案here on stakoverflow 这是一个基本的例子。如果您查看我的示例,我在 JSON 响应中检索姓名和姓氏(来自 php 中的服务器),但是在解析 JSON 对象时,我仅通过其 id 'surname' 获取姓氏(在 JSON 解析器代码中的客户端)。

    请记住,这只是一个示例,如果您拥有大型数据库并且每次都检索所有数据,这将增加互联网使用量,并且还会因互联网连接缓慢而耗费时间。专业应用程序的最佳方法是使用仅返回必要值的 mysql 查询编写单独的 php 文件。

    我也不明白你的问题中最后 2-3 行是什么意思,请你详细说明(代码后的问题)。

    PS:在开发 android 应用程序时使用 AsyncTask 也是一个好习惯,因为它们是 android 的专用线程机制。

    如果我的回答对你有所帮助,请点赞。

    【讨论】:

    • 感谢您的快速响应 Setu。我怀疑我使用了您所描述的一种客户端编码,但那是为了将用户输入的帐号和密码与存储在数据库中的帐号和密码进行比较,但在这里我只想访问一个字段“金额”从表“用户”。那么现在我上面的代码会有什么变化?
    • @user3399423 请参考我的回答中的编辑2部分
    • 非常感谢您的精彩解释 setu。你说你不明白我问题的最后几行。我的意思是,我有一个名为 perryroad.xml 的布局文件,它有一个 id textView4 值为 20 的文本视图。我想从默认值为 200 的“数量”列中减去这 20 并显示一条消息给相应的用户“扣除 20 个学分,当前余额为 180”,并将“金额”列更新为 180
    猜你喜欢
    • 1970-01-01
    • 2016-11-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-21
    相关资源
    最近更新 更多