Android BackgroundTask投掷运行时错误

时间:2017-01-21 23:31:10

标签: java android android-asynctask runtime runtimeexception

我尝试通过选项卡通过backgroundtask连接到数据库,但它不喜欢它。你们可以看看问题是什么,因为我在另一个项目中使用相同的代码并且运行良好..

public class Tab2Activity extends Activity
{   
    SharedPreferences preferences;
    String driver;
    String task;

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.tab2);      
        preferences = getSharedPreferences("MYPREFS", Context.MODE_PRIVATE);
        TextView name = (TextView) findViewById (R.id.textView1);

        // dummy data to send
         task="login";
         driver="2";


         // create and call background activity                                

         BackgroundTask backgroundTask = new BackgroundTask(Tab2Activity.this);                
         backgroundTask.execute(task,driver);


         //get data back from sharedpreference
         String mName = preferences.getString("myData","ERROR getting name");

         //display data
         name.setText(mName);

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) 
    {



        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.tab2, 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);
    }
}

这是backGroundTask代码

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

        SharedPreferences preferences;
        SharedPreferences.Editor editor;
        SharedPreferences.Editor pig;

        Context context;

        BackgroundTask(Context ctx)
        {
            this.context = ctx;
        }

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

            preferences = context.getSharedPreferences("MYPREFS", Context.MODE_PRIVATE);
            editor = preferences.edit();
            editor.putString("flag","0");
            editor.commit();


            String urlLogin  = "http://Domain.com/GetJobs.php";
            String task = params[0];
            String driver_id_app = params[1];

                try {
                    URL url = new URL(urlLogin);
                    HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
                    httpURLConnection.setRequestMethod("POST");
                    httpURLConnection.setDoOutput(true);
                    httpURLConnection.setDoInput(true);

                    //send the driver number to the database
                    OutputStream outputStream = httpURLConnection.getOutputStream();
                    OutputStreamWriter outputStreamWriter = new OutputStreamWriter(outputStream,"UTF-8");
                    BufferedWriter bufferedWriter = new BufferedWriter(outputStreamWriter);
                    String myData = URLEncoder.encode("driver_id","UTF-8")+"="+URLEncoder.encode(driver_id_app,"UTF-8");
                    //+"&"+URLEncoder.encode("identifier_loginPassword","UTF-8")+"="+URLEncoder.encode(loginPassword,"UTF-8");

                    bufferedWriter.write(myData);
                    bufferedWriter.flush();
                    bufferedWriter.close();
                    outputStream.close();

                    //get response from the database
                    InputStream inputStream = httpURLConnection.getInputStream();
                    InputStreamReader inputStreamReader = new InputStreamReader(inputStream,"UTF-8");
                    BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
                    String dataResponse = "";
                    String inputLine = "";
                    while((inputLine = bufferedReader.readLine()) != null){
                        dataResponse += inputLine;
                    }
                    bufferedReader.close();
                    inputStream.close();
                    httpURLConnection.disconnect();


                    //System.out.println("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
                   ///System.out.println(dataResponse);



                    editor.putString("flag","login");
                    editor.commit();


                    pig = preferences.edit();
                    pig.putString("myData",dataResponse);
                    pig.commit();


                    return  dataResponse;

                } 
                catch (MalformedURLException e)
                {
                    e.printStackTrace();
                }
                catch (IOException e)
                {
                    e.printStackTrace();
                } 
                return null;
        }




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



        @Override
        protected void onProgressUpdate(Void... values) 
        {
            super.onProgressUpdate(values);
        }
        public void display(String title, String message){
            AlertDialog.Builder builder = new AlertDialog.Builder(context);
            builder.setCancelable(true);
            builder.setTitle(title);
            builder.setMessage(message);
            builder.show();
        }
}

这些是错误日志

01-21 23:28:26.074: E/AndroidRuntime(27426): FATAL EXCEPTION: AsyncTask #3
01-21 23:28:26.074: E/AndroidRuntime(27426): Process: com.example.tabdemo, PID: 27426
01-21 23:28:26.074: E/AndroidRuntime(27426): java.lang.RuntimeException: An error occurred while executing doInBackground()
01-21 23:28:26.074: E/AndroidRuntime(27426):    at android.os.AsyncTask$3.done(AsyncTask.java:309)
01-21 23:28:26.074: E/AndroidRuntime(27426):    at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:354)
01-21 23:28:26.074: E/AndroidRuntime(27426):    at java.util.concurrent.FutureTask.setException(FutureTask.java:223)
01-21 23:28:26.074: E/AndroidRuntime(27426):    at java.util.concurrent.FutureTask.run(FutureTask.java:242)
01-21 23:28:26.074: E/AndroidRuntime(27426):    at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:234)
01-21 23:28:26.074: E/AndroidRuntime(27426):    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113)
01-21 23:28:26.074: E/AndroidRuntime(27426):    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588)
01-21 23:28:26.074: E/AndroidRuntime(27426):    at java.lang.Thread.run(Thread.java:818)
01-21 23:28:26.074: E/AndroidRuntime(27426): Caused by: java.lang.SecurityException: Permission denied (missing INTERNET permission?)
01-21 23:28:26.074: E/AndroidRuntime(27426):    at java.net.InetAddress.lookupHostByName(InetAddress.java:464)
01-21 23:28:26.074: E/AndroidRuntime(27426):    at java.net.InetAddress.getAllByNameImpl(InetAddress.java:252)
01-21 23:28:26.074: E/AndroidRuntime(27426):    at java.net.InetAddress.getAllByName(InetAddress.java:215)
01-21 23:28:26.074: E/AndroidRuntime(27426):    at com.android.okhttp.internal.Network$1.resolveInetAddresses(Network.java:29)
01-21 23:28:26.074: E/AndroidRuntime(27426):    at com.android.okhttp.internal.http.RouteSelector.resetNextInetSocketAddress(RouteSelector.java:220)
01-21 23:28:26.074: E/AndroidRuntime(27426):    at com.android.okhttp.internal.http.RouteSelector.nextProxy(RouteSelector.java:176)
01-21 23:28:26.074: E/AndroidRuntime(27426):    at com.android.okhttp.internal.http.RouteSelector.next(RouteSelector.java:108)
01-21 23:28:26.074: E/AndroidRuntime(27426):    at com.android.okhttp.internal.http.HttpEngine.createNextConnection(HttpEngine.java:482)
01-21 23:28:26.074: E/AndroidRuntime(27426):    at com.android.okhttp.internal.http.HttpEngine.nextConnection(HttpEngine.java:465)
01-21 23:28:26.074: E/AndroidRuntime(27426):    at com.android.okhttp.internal.http.HttpEngine.connect(HttpEngine.java:447)
01-21 23:28:26.074: E/AndroidRuntime(27426):    at com.android.okhttp.internal.http.HttpEngine.sendRequest(HttpEngine.java:353)
01-21 23:28:26.074: E/AndroidRuntime(27426):    at com.android.okhttp.internal.huc.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:476)
01-21 23:28:26.074: E/AndroidRuntime(27426):    at com.android.okhttp.internal.huc.HttpURLConnectionImpl.connect(HttpURLConnectionImpl.java:118)
01-21 23:28:26.074: E/AndroidRuntime(27426):    at com.android.okhttp.internal.huc.HttpURLConnectionImpl.getOutputStream(HttpURLConnectionImpl.java:249)
01-21 23:28:26.074: E/AndroidRuntime(27426):    at com.example.tabdemo.BackgroundTask.doInBackground(BackgroundTask.java:63)
01-21 23:28:26.074: E/AndroidRuntime(27426):    at com.example.tabdemo.BackgroundTask.doInBackground(BackgroundTask.java:1)
01-21 23:28:26.074: E/AndroidRuntime(27426):    at android.os.AsyncTask$2.call(AsyncTask.java:295)
01-21 23:28:26.074: E/AndroidRuntime(27426):    at java.util.concurrent.FutureTask.run(FutureTask.java:237)
01-21 23:28:26.074: E/AndroidRuntime(27426):    ... 4 more
01-21 23:28:26.074: E/AndroidRuntime(27426): Caused by: android.system.GaiException: android_getaddrinfo failed: EAI_NODATA (No address associated with hostname)
01-21 23:28:26.074: E/AndroidRuntime(27426):    at libcore.io.Posix.android_getaddrinfo(Native Method)
01-21 23:28:26.074: E/AndroidRuntime(27426):    at libcore.io.ForwardingOs.android_getaddrinfo(ForwardingOs.java:55)
01-21 23:28:26.074: E/AndroidRuntime(27426):    at java.net.InetAddress.lookupHostByName(InetAddress.java:451)
01-21 23:28:26.074: E/AndroidRuntime(27426):    ... 21 more
01-21 23:28:26.074: E/AndroidRuntime(27426): Caused by: android.system.ErrnoException: android_getaddrinfo failed: EACCES (Permission denied)
01-21 23:28:26.074: E/AndroidRuntime(27426):    ... 24 more

真的希望你们能提出一些建议......

1 个答案:

答案 0 :(得分:0)

我可以清楚地看到您错过了互联网连接权限。

async private void btnCourse1_Click(object sender, RoutedEventArgs e) { string[] names = new string[3] { "COP3488C,", "UWP1,", "This course is mobile app development." }; await WorkerAsync(names); } async private void btnCourse2_Click(object sender, RoutedEventArgs e) { string[] names = new string[3] { "DOP3488B,", "UWC1,", "This course is Cloud Computing." }; await WorkerAsync(names); } async private void btnCourse3_Click(object sender, RoutedEventArgs e) { string[] names = new string[3] { "BOP3589,", "UWP2,", "This course Computer Programming Java 1." }; await WorkerAsync(names); } private async Task WorkerAsync(string[] names) { string VarOutput = ""; for (int i = 0; i < names.Length; i++) { VarOutput = VarOutput + names[i] + " "; } txtBoxCourse.Text = VarOutput; var dialog = new MessageDialog(VarOutput); await dialog.ShowAsync(); }

您需要在清单中添加此项以启用互联网连接:

Caused by: java.lang.SecurityException: Permission denied (missing INTERNET permission?)