Java 我的android应用程序在尝试向Web服务器发送数据时崩溃

Java 我的android应用程序在尝试向Web服务器发送数据时崩溃,java,php,android,android-studio,Java,Php,Android,Android Studio,我的android应用程序在尝试向Web服务器发送数据时崩溃,就在我按下按钮之后 试图搜索它,但我找到的大多数代码与我的代码不同 logcat消息: 08-02 09:17:23.308 27425-27425/com.hamin.ctest E/AndroidRuntime: FATAL EXCEPTION: main Process: com.hamin.ctest, PID: 27425 java.lang.NullPointerException: Attempt to

我的android应用程序在尝试向Web服务器发送数据时崩溃,就在我按下按钮之后

试图搜索它,但我找到的大多数代码与我的代码不同

logcat消息:

 08-02 09:17:23.308 27425-27425/com.hamin.ctest E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.hamin.ctest, PID: 27425
    java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.res.Resources$Theme android.content.Context.getTheme()' on a null object reference
        at android.app.AlertDialog.resolveDialogTheme(AlertDialog.java:222)
        at android.app.AlertDialog.<init>(AlertDialog.java:200)
        at android.app.AlertDialog.<init>(AlertDialog.java:196)
        at android.app.AlertDialog.<init>(AlertDialog.java:141)
        at android.app.ProgressDialog.<init>(ProgressDialog.java:77)
        at com.hamin.ctest.AsyncSendTestData.<init>(AsyncSendTestData.java:33)
        at com.hamin.ctest.MainActivity$2.onClick(MainActivity.java:59)
        at android.view.View.performClick(View.java:5647)
        at android.view.View$PerformClick.run(View.java:22462)
        at android.os.Handler.handleCallback(Handler.java:754)
        at android.os.Handler.dispatchMessage(Handler.java:95)
        at android.os.Looper.loop(Looper.java:163)
        at android.app.ActivityThread.main(ActivityThread.java:6363)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:904)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:794)
08-02 09:17:23.308 27425-27425/com.hamin.ctest E/AndroidRuntime:FATAL EXCEPTION:main
进程:com.hamin.ctest,PID:27425
java.lang.NullPointerException:尝试在空对象引用上调用虚拟方法“android.content.res.Resources$Theme android.content.Context.getTheme()”
在android.app.AlertDialog.resolveDialogTheme(AlertDialog.java:222)上
在android.app.AlertDialog上。(AlertDialog.java:200)
在android.app.AlertDialog上(AlertDialog.java:196)
在android.app.AlertDialog.(AlertDialog.java:141)
在android.app.ProgressDialog.(ProgressDialog.java:77)
位于com.hamin.ctest.AsyncSendTestData。(AsyncSendTestData.java:33)
位于com.hamin.ctest.MainActivity$2.onClick(MainActivity.java:59)
在android.view.view.performClick上(view.java:5647)
在android.view.view$PerformClick.run(view.java:22462)
位于android.os.Handler.handleCallback(Handler.java:754)
位于android.os.Handler.dispatchMessage(Handler.java:95)
位于android.os.Looper.loop(Looper.java:163)
位于android.app.ActivityThread.main(ActivityThread.java:6363)
位于java.lang.reflect.Method.invoke(本机方法)
在com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run上(ZygoteInit.java:904)
位于com.android.internal.os.ZygoteInit.main(ZygoteInit.java:794)
我什么都进口了。 java代码:

public class AsyncSendTestData extends AsyncTask<String, String, String>
{

public static final int CONNECTION_TIMEOUT=10000;
public static final int READ_TIMEOUT=15000;
Context context;
public AsyncSendTestData(Context context) {
    this.context = context;
}

ProgressDialog pdLoading = new ProgressDialog(context);


HttpURLConnection conn;
URL url = null;

@Override
protected void onPreExecute() {
    super.onPreExecute();

    //this method will be running on UI thread
    pdLoading.setMessage("\tLoading...");
    pdLoading.setCancelable(false);
    pdLoading.show();

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

        // Enter URL address where your php file resides
        //url = new URL("http://localhost/test/login.inc.php");
        url = new URL("https://ctestapp.000webhostapp.com/TSR.php");


    } catch (MalformedURLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        return "exception";
    }
    try {
        // Setup HttpURLConnection class to send and receive data from php and mysql
        conn = (HttpURLConnection)url.openConnection();
        conn.setReadTimeout(READ_TIMEOUT);
        conn.setConnectTimeout(CONNECTION_TIMEOUT);
        conn.setRequestMethod("POST");

        // setDoInput and setDoOutput method depict handling of both send and receive
        conn.setDoInput(true);
        conn.setDoOutput(true);

        // Append parameters to URL
        Uri.Builder builder = new Uri.Builder()
                .appendQueryParameter("doit", params[0]);
                //.appendQueryParameter("pass", params[1]);
        String query = builder.build().getEncodedQuery();

        // Open connection for sending data
        OutputStream os = conn.getOutputStream();
        BufferedWriter writer = new BufferedWriter(
                new OutputStreamWriter(os, "UTF-8"));
        writer.write(query);
        writer.flush();
        writer.close();
        os.close();
        conn.connect();

    } catch (IOException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
        return "exception";
    } catch (Exception e) {
        e.printStackTrace();
    }

    try {

        int response_code = conn.getResponseCode();

        // Check if successful connection made
        if (response_code == HttpURLConnection.HTTP_OK) {

            // Read data sent from server
            InputStream input = conn.getInputStream();
            BufferedReader reader =
                    new BufferedReader(new InputStreamReader(input));
            StringBuilder result = new StringBuilder();
            String line;

            while ((line = reader.readLine()) != null) {
                result.append(line);
            }

            // Pass data to onPostExecute method
            return(result.toString());

        }else{

            return("unsuccessful");
        }

    } catch (IOException e) {
        e.printStackTrace();
        return "exception";
    } finally {
        conn.disconnect();
    }


}

@Override
protected void onPostExecute(String result) {

    //this method will be running on UI thread

    pdLoading.dismiss();

    if(result.equalsIgnoreCase("true"))
    {
            /* Here launching another activity when login successful. If you persist login state
            use sharedPreferences of Android. and logout button to clear sharedPreferences.
             */
        Toast.makeText(context, "Done" + result, Toast.LENGTH_SHORT).show();


      /*
        Intent intent = new Intent(context,SuccessActivity.class);
        startActivity(intent);
        MainActivity.this.finish();
        */

    }else if (result.equalsIgnoreCase("false")){

        // If username and password does not match display a error message
        Toast.makeText(context, "Invalid email or password", Toast.LENGTH_LONG).show();

    } else if (result.equalsIgnoreCase("exception") || result.equalsIgnoreCase("unsuccessful")) {

        Toast.makeText(context, "OOPs! Something went wrong. Connection Problem.", Toast.LENGTH_LONG).show();

    }
}

}
公共类AsyncSendTestData扩展AsyncTask
{
公共静态最终int连接\u超时=10000;
公共静态最终整型读取超时=15000;
语境;
公共AsyncSendTestData(上下文){
this.context=上下文;
}
ProgressDialog pdLoading=新建ProgressDialog(上下文);
httpurl连接连接;
URL=null;
@凌驾
受保护的void onPreExecute(){
super.onPreExecute();
//此方法将在UI线程上运行
pdLoading.setMessage(“\t加载…”);
pdLoading.setCancelable(假);
pdLoading.show();
}
@凌驾
受保护的字符串doInBackground(字符串…参数){
试一试{
//输入php文件所在的URL地址
//url=新url(“http://localhost/test/login.inc.php");
url=新url(“https://ctestapp.000webhostapp.com/TSR.php");
}捕获(格式错误){
//TODO自动生成的捕捉块
e、 printStackTrace();
返回“异常”;
}
试一试{
//设置HttpURLConnection类以从php和mysql发送和接收数据
conn=(HttpURLConnection)url.openConnection();
conn.setReadTimeout(读取超时);
连接设置连接超时(连接超时);
conn.setRequestMethod(“POST”);
//setDoInput和setDoOutput方法描述了发送和接收的处理
conn.setDoInput(真);
连接设置输出(真);
//将参数附加到URL
Uri.Builder=新的Uri.Builder()
.appendQueryParameter(“doit”,参数[0]);
//.appendQueryParameter(“通过”,参数[1]);
字符串查询=builder.build().getEncodedQuery();
//打开用于发送数据的连接
OutputStream os=conn.getOutputStream();
BufferedWriter=新的BufferedWriter(
新的OutputStreamWriter(操作系统,“UTF-8”);
writer.write(查询);
writer.flush();
writer.close();
os.close();
连接();
}捕获(IOE1异常){
//TODO自动生成的捕捉块
e1.printStackTrace();
返回“异常”;
}捕获(例外e){
e、 printStackTrace();
}
试一试{
int response_code=conn.getResponseCode();
//检查连接是否成功
if(response\u code==HttpURLConnection.HTTP\u OK){
//读取从服务器发送的数据
InputStream input=conn.getInputStream();
缓冲读取器=
新的BufferedReader(新的InputStreamReader(输入));
StringBuilder结果=新建StringBuilder();
弦线;
而((line=reader.readLine())!=null){
结果。追加(行);
}
//将数据传递给onPostExecute方法
返回(result.toString());
}否则{
返回(“未成功”);
}
}捕获(IOE异常){
e、 printStackTrace();
返回“异常”;
}最后{
连接断开();
}
}
@凌驾
受保护的void onPostExecute(字符串结果){
//此方法将在UI线程上运行
pdLoading.disclose();
if(result.equalsIgnoreCase(“true”))
{
/*登录成功后,在此启动另一个活动。如果您保持登录状态
使用Android的SharedReferences和注销按钮清除SharedReferences。
*/
Toast.makeText(上下文,“完成”+结果,Toast.LENGTH_SHORT.show();
/*
意向意向=新意向(上下文,SuccessActivity.class);
星触觉(意向);
MainActivity.this.finish();
*/
}else if(result.equalsIgnoreCase(“false”)){
//如果用户名和密码不匹配,则显示错误消息
Toast.makeText(上下文,“无效电子邮件或密码”,Toast.LENGTH_LONG.show();
}else if(result.equalsIgnoreCase(“异常”)| | result.equalsIgnoreCase(“不成功”)){
Toast.makeText(上下文,“哎呀!出现了问题。连接问题。”,Toast.LENGTH_LONG.show();
}
}
}
php代码:

<?php


if(isset($_POST['doit']))
{
$reversed = $_POST['doit'];
echo $reversed;
}

?>

从以下位置更改
进度对话框
初始化代码:

public AsyncSendTestData(Context context) {
    this.context = context;
}

ProgressDialog pdLoading = new ProgressDialog(context);
致:


使用进度条而不是进度对话框,它现在已贬值
ProgressDialog pdLoading;
public AsyncSendTestData(Context context) {
    this.context = context;
    this.pdLoading = new ProgressDialog(context);
}