【问题标题】:retrieve a variable from PHP to an Android Class using HttpURLConnection使用 HttpURLConnection 将变量从 PHP 检索到 Android 类
【发布时间】:2019-01-01 12:41:27
【问题描述】:

这是我正在使用的代码的更新,总共减去了一堆非相关的东西,比如微调器按钮意图。也许你可以更好地看到我做错了什么。

我应该注意我的 php,我是编码新手,这是我第一次尝试从 mysql 下载 PDO。我可以使用 PDO 上传。看起来它做得对,但此时我无法判断它正在崩溃。

非常感谢您的帮助。

 <?php
  require("conn.php");

 $ID = ["ptID"];

 try{
 $sql = 'SELECT x FROM table WHERE ID = :ID';
 $stmt = $conn->prepare($sql);
 $stmt->execute(array('ptID'=> $ID));
 $posts = $stmt->fetchALL();

 $result = mysql_query($conn, $sql);

 if ($row = mysql_fetch_assoc($result) > 0)
 {

$row = mysqli_fetch_assoc($result);
$x = $row["x"];

 }

 catch(PDOException $e) {
 echo $sql . "<br>" . $e->getMessage();
 $conn = null;

 ?>

这是我的活动课 ctest

 import android.content.Context;
 import android.content.Intent;
 import android.content.SharedPreferences;
 import android.net.Uri;
 import android.support.v7.app.AppCompatActivity;
 import android.os.Bundle;
 import android.view.View;
 import android.widget.AdapterView;
 import android.widget.ArrayAdapter;
 import android.widget.Button;
 import android.widget.Spinner;
 import android.widget.TextView;
 import android.widget.Toast;

 public class cervicaltest extends AppCompatActivity implements 
 AdapterView.OnItemSelectedListener {

 protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_test);

 //whole bunch of spinners, to collect user input all of which functions. 
 tests prior to adding the code to get data worked find.


 }
 //gets the key to the database for the upload.
 private void useID() {
    SharedPreferences shareID = getSharedPreferences("shareID", Context.MODE_PRIVATE);
    ptID = shareID.getString("ID", "");

}

 public void settest() {
 //bunch of if else statements using the user input.  all of which worked 
 prior to trying to get data.
}

 // both of these were left blank as I never used them.
 @Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {

}

@Override
public void onNothingSelected(AdapterView<?> adapterView) {

}

//this is the get data class.

 public void getrot() {

gettype ="getcrom";
downloadbackgroundworker Downloadbackgroundworker = new downloadbackgroundworker(this, new downloadbackgroundworker.AsyncResponse() {
    @Override
    public void processfinish(String response) {
        rcervrot = response;
    }
});
    Downloadbackgroundworker.execute(gettype, ptID);
 }

 public void testsaveClick(View view) {

 x = x.getSelectedItem().toString();

    type = "testdb";
    useID();
    getrot();

    BackgroundWorker backgroundWorker = new BackgroundWorker(this);
    backgroundWorker.execute(type, ptID, x //bunch of variables);


   // Rcervicalticcalcu(); these were marketed out intents that I had used to get data previously but didn't like the            result.  all the code worked, but I kept getting kicked to this activity with the intent and I didn't want to            end up at this activity.  Everything worked good when transfering data as an intent.  So somehow it's getting           the data from the database that is crashing me.  all the code for the intents is marked out.
    //Lcervicalticcalcu();
    settest();
 }
 }

最后,这是 getdata 的 downloadworker 类。上传后台工作人员之前工作正常,我没有更改任何内容。

这是下载工作者类

 import android.app.AlertDialog;
 import android.content.Context;
 import android.os.AsyncTask;
 import java.io.BufferedReader;
 import java.io.BufferedWriter;
 import java.io.IOException;
 import java.io.InputStream;
 import java.io.InputStreamReader;
 import java.io.OutputStream;
 import java.io.OutputStreamWriter;
 import java.net.HttpURLConnection;
 import java.net.MalformedURLException;
 import java.net.URL;
 import java.net.URLEncoder;


 public class downloadbackgroundworker extends AsyncTask<String, Void, String> {

AlertDialog downloadalert;
Context dlctx;
downloadbackgroundworker (Context dlctx, AsyncResponse asyncResponse) {
    this.dlctx = dlctx;
    delegate = asyncResponse;
}

@Override
protected void onPreExecute(){
    downloadalert = new AlertDialog.Builder(dlctx).create();
    downloadalert.setTitle("retrieve Data");

}
@Override
protected String doInBackground(String... params){

    String gettype = params[0];
    String cervrotgeturl = "http://IP/phpfile";
    if(gettype.equals("getcrom"))
    {
        String ID = params[1];
        try {
            URL url = new URL(cervrotgeturl);
            HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
            httpURLConnection.setRequestMethod("POST");
            httpURLConnection.setDoOutput(true);
            httpURLConnection.setDoInput(true);
            OutputStream outputStream = httpURLConnection.getOutputStream();
            BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
            String data = URLEncoder.encode("ptID", "UTF-8") + "=" + URLEncoder.encode(ID, "UTF-8");
            bufferedWriter.write(data);
            bufferedWriter.flush();
            bufferedWriter.close();
            outputStream.close();
            InputStream inputStream = httpURLConnection.getInputStream();
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, "iso-8859-1"));
            String response ="";
            String line = "";
            while ((line = bufferedReader.readLine())!=null){
                 response = line;
            }
            bufferedReader.close();
            inputStream.close();
            httpURLConnection.disconnect();
            return response;
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    return null;
}

public AsyncResponse delegate = null;

public interface AsyncResponse {
    void processfinish (String response);
}

@Override
protected void onProgressUpdate(Void... values){
    super.onProgressUpdate(values);
}

@Override
protected void onPostExecute(String response) {
    delegate.processfinish(response);

}
}

【问题讨论】:

    标签: php android httpurlconnection


    【解决方案1】:
    public AsyncResponse delegate=null;
    
    public interface AsyncResponse {
        void processFinish(Boolean output);
    }
    
    getBackgroundworker (Context ctx, AsyncResponse asyncResponse) {
        this.ctx =ctx;  
        delegate = asyncResponse;
    } 
    
    getBackgroundworker(Context ctx)  
    {  
        this.ctx =ctx;  
    }  
    
     @Override
     protected void onPostExecute(String result) {
        alertDialog.setMessage(result);
            delegate.processFinish(stuff);
    //I am passing the boolean variable here. You can pass accordingly
    
        }
    

    现在在要使用 stuff 变量值的活动中。您必须实现 AsyncResponse 接口并覆盖其方法。

    【讨论】:

    • 感谢您的回复。我在 A 类中遇到了一个错误。它说从方法 getBackgroundworker 中删除第二个参数如果我单击它,它会从 getBackgroundworker (Context ctx, AsyncResponse asyncResponse) { this.ctx =ctx; 中删除 AsyncResponse asyncResponse)委托 = asyncResponse;
    • getBackgroundworker 中的getBackgroundworker (Content, AsyncResponce) 不能应用于(ClassA)
    • 那是由于构造函数的不同。我已经更新了代码@gtcode。
    • 抱歉回复晚了,我可以在我的零工上打双打。通常那里没有足够的时间。这没有用,第二个后台工作人员从未突出显示,据说从未使用过。我将在下面发布我的整个代码。所以你可以看到它。我不确定此时是后台工作人员类还是它来自的活动类或什么。我玩了一点,它一直在崩溃。给我几分钟,我在一台没有互联网的电脑上编码,所以我必须将文件复制并粘贴到闪存驱动器上,然后我将它们发布在这里。
    • 好的,我在顶部编辑了代码,以便您可以更好地看到我所做的。要使用两个后台工人类,一个总是黑暗的说未使用。我在方法中启动了异步,因为它是摆脱错误的唯一方法。在 android studio 中,活动类中的所有内容都被选中为绿色。在 downloadworkerclass 中,有一些黄色但没有红色,所有的黄色都显得微不足道。
    猜你喜欢
    • 2020-04-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-05-23
    • 1970-01-01
    • 2021-06-15
    相关资源
    最近更新 更多