Android应用程序在模拟器上工作而不是设备

时间:2014-10-07 14:43:35

标签: android json

美好的一天,我有一个巨大的惊喜。我的应用程序在模拟器上运行时工作,但在我在真实设备上尝试时崩溃。我不明白怎么会发生这种情况。我正在尝试将数据插入到DATABSE。

出于某种原因,只有在我使用设备时才会出现错误。 下面是错误日志和代码。

错误日志

10-07 16:37:03.576  10239-10438/com.example.divide.asteriasolutions I/System.out﹕ AsyncTask #1 calls detatch()
10-07 16:37:03.576  10239-10438/com.example.divide.asteriasolutions W/System.err﹕ org.apache.http.conn.HttpHostConnectException: Connection to http://10.0.2.2:81 refused
10-07 16:37:03.581  10239-10438/com.example.divide.asteriasolutions W/System.err﹕ at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:212)
10-07 16:37:03.581  10239-10438/com.example.divide.asteriasolutions W/System.err﹕ at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:167)
10-07 16:37:03.581  10239-10438/com.example.divide.asteriasolutions W/System.err﹕ at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:125)
10-07 16:37:03.581  10239-10438/com.example.divide.asteriasolutions W/System.err﹕ at org.apache.http.impl.client.DefaultRequestDirector.executeOriginal(DefaultRequestDirector.java:1179)
10-07 16:37:03.581  10239-10438/com.example.divide.asteriasolutions W/System.err﹕ at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:644)
10-07 16:37:03.581  10239-10438/com.example.divide.asteriasolutions W/System.err﹕ at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555)
10-07 16:37:03.581  10239-10438/com.example.divide.asteriasolutions W/System.err﹕ at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
10-07 16:37:03.581  10239-10438/com.example.divide.asteriasolutions W/System.err﹕ at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465)
10-07 16:37:03.581  10239-10438/com.example.divide.asteriasolutions W/System.err﹕ at com.example.divide.asteriasolutions.JSONParser.makeHttpRequest(JSONParser.java:54)
10-07 16:37:03.581  10239-10438/com.example.divide.asteriasolutions W/System.err﹕ at com.example.divide.asteriasolutions.BookingActivity$CreateNewProduct.doInBackground(BookingActivity.java:149)
10-07 16:37:03.586  10239-10438/com.example.divide.asteriasolutions W/System.err﹕ at com.example.divide.asteriasolutions.BookingActivity$CreateNewProduct.doInBackground(BookingActivity.java:79)
10-07 16:37:03.586  10239-10438/com.example.divide.asteriasolutions W/System.err﹕ at android.os.AsyncTask$2.call(AsyncTask.java:288)
10-07 16:37:03.586  10239-10438/com.example.divide.asteriasolutions W/System.err﹕ at java.util.concurrent.FutureTask.run(FutureTask.java:237)
10-07 16:37:03.586  10239-10438/com.example.divide.asteriasolutions W/System.err﹕ at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
10-07 16:37:03.586  10239-10438/com.example.divide.asteriasolutions W/System.err﹕ at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
10-07 16:37:03.586  10239-10438/com.example.divide.asteriasolutions W/System.err﹕ at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
10-07 16:37:03.586  10239-10438/com.example.divide.asteriasolutions W/System.err﹕ at java.lang.Thread.run(Thread.java:841)
10-07 16:37:03.586  10239-10438/com.example.divide.asteriasolutions W/System.err﹕ Caused by: java.net.ConnectException: failed to connect to /10.0.2.2 (port 81): connect failed: ETIMEDOUT (Connection timed out)
10-07 16:37:03.591  10239-10438/com.example.divide.asteriasolutions W/System.err﹕ at libcore.io.IoBridge.connect(IoBridge.java:114)
10-07 16:37:03.591  10239-10438/com.example.divide.asteriasolutions W/System.err﹕ at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:192)
10-07 16:37:03.591  10239-10438/com.example.divide.asteriasolutions W/System.err﹕ at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:459)
10-07 16:37:03.591  10239-10438/com.example.divide.asteriasolutions W/System.err﹕ at java.net.Socket.connect(Socket.java:843)
10-07 16:37:03.591  10239-10438/com.example.divide.asteriasolutions W/System.err﹕ at org.apache.http.conn.scheme.PlainSocketFactory.connectSocket(PlainSocketFactory.java:119)
10-07 16:37:03.596  10239-10438/com.example.divide.asteriasolutions W/System.err﹕ at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:165)
10-07 16:37:03.596  10239-10438/com.example.divide.asteriasolutions W/System.err﹕ ... 16 more
10-07 16:37:03.596  10239-10438/com.example.divide.asteriasolutions W/System.err﹕ Caused by: libcore.io.ErrnoException: connect failed: ETIMEDOUT (Connection timed out)
10-07 16:37:03.601  10239-10438/com.example.divide.asteriasolutions W/System.err﹕ at libcore.io.Posix.connect(Native Method)
10-07 16:37:03.601  10239-10438/com.example.divide.asteriasolutions W/System.err﹕ at libcore.io.BlockGuardOs.connect(BlockGuardOs.java:85)
10-07 16:37:03.601  10239-10438/com.example.divide.asteriasolutions W/System.err﹕ at libcore.io.IoBridge.connectErrno(IoBridge.java:127)
10-07 16:37:03.601  10239-10438/com.example.divide.asteriasolutions W/System.err﹕ at libcore.io.IoBridge.connect(IoBridge.java:112)
10-07 16:37:03.601  10239-10438/com.example.divide.asteriasolutions W/System.err﹕ ... 21 more
10-07 16:37:03.601  10239-10438/com.example.divide.asteriasolutions E/Buffer Error﹕ Error converting result java.lang.NullPointerException: lock == null
10-07 16:37:03.601  10239-10438/com.example.divide.asteriasolutions E/JSON Parser﹕ Error parsing data org.json.JSONException: End of input at character 0 of
10-07 16:37:03.606  10239-10438/com.example.divide.asteriasolutions W/dalvikvm﹕ threadid=11: thread exiting with uncaught exception (group=0x41877c08)
10-07 16:37:03.611  10239-10438/com.example.divide.asteriasolutions E/AndroidRuntime﹕ FATAL EXCEPTION: AsyncTask #1
    Process: com.example.divide.asteriasolutions, PID: 10239
    java.lang.RuntimeException: An error occured while executing doInBackground()
            at android.os.AsyncTask$3.done(AsyncTask.java:300)
            at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:355)
            at java.util.concurrent.FutureTask.setException(FutureTask.java:222)
            at java.util.concurrent.FutureTask.run(FutureTask.java:242)
            at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
            at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
            at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
            at java.lang.Thread.run(Thread.java:841)
     Caused by: java.lang.NullPointerException
            at com.example.divide.asteriasolutions.BookingActivity$CreateNewProduct.doInBackground(BookingActivity.java:153)
            at com.example.divide.asteriasolutions.BookingActivity$CreateNewProduct.doInBackground(BookingActivity.java:79)
            at android.os.AsyncTask$2.call(AsyncTask.java:288)
            at java.util.concurrent.FutureTask.run(FutureTask.java:237)
            at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
            at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
            at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
            at java.lang.Thread.run(Thread.java:841)
10-07 16:37:04.176  10239-10239/com.example.divide.asteriasolutions D/AbsListView﹕ onDetachedFromWindow
10-07 16:37:04.176  10239-10239/com.example.divide.asteriasolutions D/AbsListView﹕ unregisterIRListener() is called
10-07 16:37:04.211  10239-10239/com.example.divide.asteriasolutions E/WindowManager﹕ android.view.WindowLeaked: Activity com.example.divide.asteriasolutions.BookingActivity has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView{42ba6270 V.E..... R......D 0,0-1026,288} that was originally added here
            at android.view.ViewRootImpl.<init>(ViewRootImpl.java:457)
            at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:267)
            at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:69)
            at android.app.Dialog.show(Dialog.java:288)
            at com.example.divide.asteriasolutions.BookingActivity$CreateNewProduct.onPreExecute(BookingActivity.java:91)
            at android.os.AsyncTask.executeOnExecutor(AsyncTask.java:587)
            at android.os.AsyncTask.execute(AsyncTask.java:535)
            at com.example.divide.asteriasolutions.BookingActivity$1.onClick(BookingActivity.java:71)
            at android.view.View.performClick(View.java:4633)
            at android.view.View$PerformClick.run(View.java:19330)
            at android.os.Handler.handleCallback(Handler.java:733)
            at android.os.Handler.dispatchMessage(Handler.java:95)
            at android.os.Looper.loop(Looper.java:157)
            at android.app.ActivityThread.main(ActivityThread.java:5356)
            at java.lang.reflect.Method.invokeNative(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:515)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1265)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1081)
            at dalvik.system.NativeStart.main(Native Method)
10-07 16:37:07.061  10239-10438/com.example.divide.asteriasolutions I/Process﹕ Sending signal. PID: 10239 SIG: 9

.java文件

package com.example.divide.asteriasolutions;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.TimePicker;

public class BookingActivity extends Activity {

    // Progress Dialog
    private ProgressDialog pDialog;

    JSONParser jsonParser = new JSONParser();
    EditText inputName;
    EditText inputSurname;
    EditText inputPhone;
    EditText inputEmail;
    EditText inputSeats;
    DatePicker inputDate;
    TimePicker inputTime;
    CheckBox inputNews;



    // url to create new product
    private static String url_create_product = "http://10.0.2.2:81/android_connect/create_product.php";

    // JSON Node names
    private static final String TAG_SUCCESS = "success";

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.place_booking);

        // Edit Text
        inputName = (EditText) findViewById(R.id.inputName);
        inputSurname = (EditText) findViewById(R.id.inputSurname);
        inputPhone = (EditText) findViewById(R.id.inputPhone);
        inputEmail = (EditText) findViewById(R.id.inputEmail);
        inputSeats = (EditText) findViewById(R.id.inputSeats);
        inputDate = (DatePicker) findViewById(R.id.inputDate);
        inputTime = (TimePicker) findViewById(R.id.inputTime);

        inputNews = (CheckBox)findViewById(R.id.checkBox);
        // Create button
        Button btnCreateProduct = (Button) findViewById(R.id.btnCreateProduct);

        // button click event
        btnCreateProduct.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View view) {
                // creating new product in background thread
                new CreateNewProduct().execute();
            }
        });
    }

    /**
     * Background Async Task to Create new product
     * */
    class CreateNewProduct extends AsyncTask<String, String, String> {

        /**
         * Before starting background thread Show Progress Dialog
         * */
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pDialog = new ProgressDialog(BookingActivity.this);
            pDialog.setMessage("Making Reservation..");
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(true);
            pDialog.show();
        }

        /**
         * Creating product
         * */
        protected String doInBackground(String... args) {
            String name = inputName.getText().toString();
            String surname = inputSurname.getText().toString();
            String phone = inputPhone.getText().toString();
            String email = inputEmail.getText().toString();
            String seats = inputSeats.getText().toString();
           //String date = inputDate.getText().toString();
            String date = inputDate.toString();
           // String time = inputTime.getText().toString();
            String time = inputTime.toString();

            String ch = "";
            if(inputNews.isChecked())
            {
                ch = "1";
            }
            else
            {
                ch = "0";
            }
            int y = inputDate.getYear();
            int m = inputDate.getMonth();
            int d = inputDate.getDayOfMonth();

            int h = inputTime.getCurrentHour();
            int mi = inputTime.getCurrentMinute();


            String ma = "";

            if(h < 12) {
                ma = "AM";
            } else {
                ma = "PM";
            }

            date = y+"/"+m+"/"+d;
            time = h+":"+mi+" "+ma;

            // Building Parameters
            List<NameValuePair> params = new ArrayList<NameValuePair>();
            params.add(new BasicNameValuePair("name", name));
            params.add(new BasicNameValuePair("surname", surname));
            params.add(new BasicNameValuePair("phone", phone));
            params.add(new BasicNameValuePair("email", email));
            params.add(new BasicNameValuePair("seats", seats));
            params.add(new BasicNameValuePair("date", date));
            params.add(new BasicNameValuePair("time", time));
            params.add(new BasicNameValuePair("news", ch));

            // getting JSON Object
            // Note that create product url accepts POST method
            JSONObject json = jsonParser.makeHttpRequest(url_create_product,
                    "POST", params);

            // check log cat fro response
            Log.d("Create Response", json.toString());

            // check for success tag
            try {
                int success = json.getInt(TAG_SUCCESS);

                if (success == 1) {
                    // successfully created product
                    Intent i = new Intent(getApplicationContext(), MyActivity.class);
                    startActivity(i);

                    // closing this screen
                    finish();
                } else {
                    // failed to create product
                    Intent i = new Intent(getApplicationContext(), RegisterActivity.class);
                    startActivity(i);

                    // closing this screen
                    finish();
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }

            return null;
        }

        /**
         * After completing background task Dismiss the progress dialog
         * **/
        protected void onPostExecute(String file_url) {
            // dismiss the dialog once done
            pDialog.dismiss();
        }

    }
}

XML文件

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

    <!-- Name Label -->


    <!-- Input Name -->
    <EditText android:id="@+id/inputName"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_margin="5dip"
        android:layout_marginBottom="15dip"
        android:hint="Enter Name"
        android:singleLine="true"/>



    <!-- Input Name -->
    <EditText android:id="@+id/inputSurname"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_margin="5dip"
        android:layout_marginBottom="15dip"
        android:hint="Enter Surname"
        android:singleLine="true"/>


    <!-- Input Name
    <EditText android:id="@+id/inputPhone"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_margin="5dip"
        android:layout_marginBottom="15dip"
        android:hint="Enter Phone Number"
        android:singleLine="true"/>-->

    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:inputType="phone"
        android:ems="10"
        android:hint="Enter Phone Number"
        android:id="@+id/inputPhone" />


    <!-- Input Name
    <EditText android:id="@+id/inputEmail"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_margin="5dip"
        android:layout_marginBottom="15dip"
        android:hint="Enter Email"
        android:singleLine="true"/>-->

    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:inputType="textEmailAddress"
        android:ems="10"
        android:id="@+id/inputEmail"
        android:hint="Enter Email"
        android:layout_gravity="center_horizontal" />


    <!-- Input Name
    <EditText android:id="@+id/inputSeats"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_margin="5dip"
        android:layout_marginBottom="15dip"
        android:hint="Enter Number of seats"
        android:singleLine="true"/>-->

    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:inputType="number"
        android:ems="10"
        android:hint="Enter Number of seats"
        android:id="@+id/inputSeats" />

    <!-- Input Name -->
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Pick Date:"
        android:id="@+id/textView4"
        android:textSize="30dp"
        android:layout_gravity="center_horizontal"
        android:textStyle="bold|italic" />
    <DatePicker
        android:id="@+id/inputDate"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Would you like to receive newsletters from Capeesh?"
        android:calendarViewShown="false"

        android:layout_alignParentLeft="true"/>

   <!-- <EditText android:id="@+id/inputDate"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_margin="5dip"
        android:layout_marginBottom="15dip"
        android:hint="Enter Date"
        android:singleLine="true"/>
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Pick Date:"
        android:id="@+id/textView2"
        android:textSize="30dp"
        android:layout_gravity="center_horizontal"
        android:textStyle="bold|italic" />
    <DatePicker
        android:id="@+id/inputDate"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Would you like to receive newsletters from Capeesh?"
        android:calendarViewShown="false"

        android:layout_alignParentLeft="true"/>-->
<!--    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Choose Time"
        android:textSize="20dp"
        android:id="@+id/textView1"
        android:elegantTextHeight="false"
        android:textStyle="bold|italic" />-->
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Pick Time:"
        android:id="@+id/textView3"
        android:textSize="30dp"
        android:layout_gravity="center_horizontal"
        android:textStyle="bold|italic" />
            <TimePicker
        android:id="@+id/inputTime"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Would you like to receive newsletters from Capeesh?"
        android:calendarViewShown="false"

        android:layout_alignParentLeft="true"/>-->


    <!-- Input Name-->
    <!--<EditText android:id="@+id/inputTime"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:hint="Enter Time"
        android:layout_margin="5dip"
        android:layout_marginBottom="15dip"
        android:singleLine="true"/>-->
    <CheckBox
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Would you like to receive newsletters from Capeesh?"
        android:id="@+id/checkBox"
        android:checked="true"/>

    <Button
        android:id="@+id/btnCreateProduct"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="30dp"
        android:text="Make Reservation"
        android:background="@drawable/menu1"
        style="@style/ButtonLogin"/>




</LinearLayout>
</ScrollView>

清单文件

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.divide.asteriasolutions" >
    <uses-permission android:name="android.permission.INTERNET"/>
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >

        <activity
            android:name=".MyActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity android:name=".BookingActivity"></activity>
        <activity android:name=".RegisterActivity"></activity>
        <activity android:name=".ContactActivity"></activity>
        <activity android:name=".MenuActivity"></activity>
        <activity android:name=".AntiPasteActivity"></activity>
        <activity android:name=".DolciActivity"></activity>
        <activity android:name=".MenuActivity1"></activity>
        <activity android:name=".InsalateActivity"></activity>
        <activity android:name=".LacarneActivity"></activity>
        <activity android:name=".PastaActivity"></activity>
        <activity android:name=".PizzaActivity"></activity>
        <activity android:name=".PesceActivity"></activity>
        <activity android:name=".EventsActivity"></activity>

    </application>

</manifest>

请原谅我,如果这是一个小错误而且我在问。我已经尝试了几个小时,仍然对于如何在仿真器上而不是在真实设备上工作而感到困惑。

1 个答案:

答案 0 :(得分:-1)

你用过,

if (success == 1) 
{
      // successfully created product
      Intent i = new Intent(getApplicationContext(), MyActivity.class);
      startActivity(i);

      // closing this screen
      finish();
  } 
  else 
  {
     // failed to create product
     Intent i = new Intent(getApplicationContext(), RegisterActivity.class);
     startActivity(i);

     // closing this screen
     finish();
   }

getApplicationContext()是Context上的方法,AsyncTask不会从Context继承。

而是尝试其他方式来获取上下文 - getting context in AsyncTask