doushe7934 2018-08-02 06:40
浏览 117
已采纳

尝试将数据发送到网络服务器时我的Android应用程序崩溃[重复]

This question already has an answer here:

My android app crashes when trying to send data to a webserver, right after I press the button.

tried to search for it, but most of the codes I found was different from my code.

logcat message:

 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)

I imported everything. java code:

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();

    }
}

}

php code:

<?php


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

?>
</div>
  • 写回答

1条回答 默认 最新

  • douba8819 2018-08-02 06:43
    关注

    Change your ProgressDialog initialization code from:

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

    to:

    ProgressDialog pdLoading;
    public AsyncSendTestData(Context context) {
        this.context = context;
        this.pdLoading = new ProgressDialog(context);
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 Arcgis相交分析无法绘制一个或多个图形
  • ¥15 seatunnel-web使用SQL组件时候后台报错,无法找到表格
  • ¥15 fpga自动售货机数码管(相关搜索:数字时钟)
  • ¥15 用前端向数据库插入数据,通过debug发现数据能走到后端,但是放行之后就会提示错误
  • ¥30 3天&7天&&15天&销量如何统计同一行
  • ¥30 帮我写一段可以读取LD2450数据并计算距离的Arduino代码
  • ¥15 飞机曲面部件如机翼,壁板等具体的孔位模型
  • ¥15 vs2019中数据导出问题
  • ¥20 云服务Linux系统TCP-MSS值修改?
  • ¥20 关于#单片机#的问题:项目:使用模拟iic与ov2640通讯环境:F407问题:读取的ID号总是0xff,自己调了调发现在读从机数据时,SDA线上并未有信号变化(语言-c语言)