Android应用仅在模拟器上运行,但不在设备上运行

时间:2015-03-22 11:43:21

标签: android mysql json localhost android-networking

我创建了一个从在线MySQL数据库中获取内容的应用程序。 我已经使用了JSON Parser。我的应用程序在模拟器上工作正常但在我的移动设备上却无法获取内容。

这是我的代码,直到现在: AllPapersActivity.java

package com.papershare.bhanu;

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

import org.apache.http.NameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.ListActivity;
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.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;

public class AllPapersActivity extends ListActivity {

    // Progress Dialog
    private ProgressDialog pDialog;

    // Creating JSON Parser object
    JSONParser jParser = new JSONParser();

    ArrayList<HashMap<String, String>> papersList;

    // url to get all papers list
    private static String url_all_papers = "http://kidessential.esy.es/android_connect_paper/get_all_papers.php";

    // JSON Node names
    private static final String TAG_SUCCESS = "success";
    private static final String TAG_paperS = "papers";
    private static final String TAG_PID = "pid";
    private static final String TAG_NAME = "name";
    private static final String TAG_DESCRIPTION = "description";

    // papers JSONArray
    JSONArray papers = null;

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

        // Hashmap for ListView
        papersList = new ArrayList<HashMap<String, String>>();

        // Loading papers in Background Thread
        new LoadAllpapers().execute();

        // Get listview
        ListView lv = getListView();

        // on seleting single paper
        // launching Edit paper Screen
        lv.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                    int position, long id) {
                // getting values from selected ListItem
                String description = ((TextView) view.findViewById(R.id.description)).getText()
                        .toString();

                // Starting new intent
                Intent in = new Intent(getApplicationContext(),
                        WebViewer.class);
                // sending pid to next activity
                in.putExtra(TAG_DESCRIPTION, description);

                // starting new activity and expecting some response back
                startActivityForResult(in, 100);
            }
        });

    }

    // Response from Edit paper Activity
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        // if result code 100
        if (resultCode == 100) {
            // if result code 100 is received 
            // means user edited/deleted paper
            // reload this screen again
            Intent intent = getIntent();
            finish();
            startActivity(intent);
        }

    }

    /**
     * Background Async Task to Load all paper by making HTTP Request
     * */
    class LoadAllpapers extends AsyncTask<String, String, String> {

        /**
         * Before starting background thread Show Progress Dialog
         * */
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pDialog = new ProgressDialog(AllPapersActivity.this);
            pDialog.setMessage("Loading papers. Please wait...");
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(false);
            pDialog.show();
        }

        /**
         * getting All papers from url
         * */
        protected String doInBackground(String... args) {
            // Building Parameters
            List<NameValuePair> params = new ArrayList<NameValuePair>();
            // getting JSON string from URL
            JSONObject json = jParser.makeHttpRequest(url_all_papers, "GET", params);

            // Check your log cat for JSON reponse
            Log.d("All papers: ", json.toString());

            try {
                // Checking for SUCCESS TAG
                int success = json.getInt(TAG_SUCCESS);

                if (success == 1) {
                    // papers found
                    // Getting Array of papers
                    papers = json.getJSONArray(TAG_paperS);

                    // looping through All papers
                    for (int i = 0; i < papers.length(); i++) {
                        JSONObject c = papers.getJSONObject(i);

                        // Storing each json item in variable
                        String id = c.getString(TAG_PID);
                        String name = c.getString(TAG_NAME);
                        String descrip = c.getString(TAG_DESCRIPTION);

                        // creating new HashMap
                        HashMap<String, String> map = new HashMap<String, String>();

                        // adding each child node to HashMap key => value
                        map.put(TAG_PID, id);
                        map.put(TAG_NAME, name);
                        map.put(TAG_DESCRIPTION, descrip);

                        // adding HashList to ArrayList
                        papersList.add(map);
                    }
                } else {
                    // no papers found
                    // Launch Add New paper Activity
                    Intent i = new Intent(getApplicationContext(),
                            NewPapersActivity.class);
                    // Closing all previous activities
                    i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                    startActivity(i);
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }

            return null;
        }

        /**
         * After completing background task Dismiss the progress dialog
         * **/
        protected void onPostExecute(String file_url) {
            // dismiss the dialog after getting all papers
            pDialog.dismiss();
            // updating UI from Background Thread
            runOnUiThread(new Runnable() {
                public void run() {
                    /**
                     * Updating parsed JSON data into ListView
                     * */
                    ListAdapter adapter = new SimpleAdapter(
                            AllPapersActivity.this, papersList,
                            R.layout.list_item, 
                            new String[] { TAG_PID,TAG_NAME, TAG_DESCRIPTION},
                            new int[] { R.id.pid, R.id.name, R.id.description});
                    // updating listview
                    setListAdapter(adapter);
                }
            });

        }

    }
}

这是JSONParser.java

package com.papershare.bhanu;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;

import android.util.Log;

public class JSONParser {

    static InputStream is = null;
    static JSONObject jObj = null;
    static String json = "";

    // constructor
    public JSONParser() {

    }

    // function get json from url
    // by making HTTP POST or GET mehtod
    public JSONObject makeHttpRequest(String url, String method,
            List<NameValuePair> params) {

        // Making HTTP request
        try {

            // check for request method
            if(method.equals("POST")){
                // request method is POST
                // defaultHttpClient
                DefaultHttpClient httpClient = new DefaultHttpClient();
                HttpPost httpPost = new HttpPost(url);
                httpPost.setEntity(new UrlEncodedFormEntity(params));

                HttpResponse httpResponse = httpClient.execute(httpPost);
                HttpEntity httpEntity = httpResponse.getEntity();
                is = httpEntity.getContent();

            }else if(method.equals("GET")){
                // request method is GET
                DefaultHttpClient httpClient = new DefaultHttpClient();
                String paramString = URLEncodedUtils.format(params, "utf-8");
                url += "?" + paramString;
                HttpGet httpGet = new HttpGet(url);

                HttpResponse httpResponse = httpClient.execute(httpGet);
                HttpEntity httpEntity = httpResponse.getEntity();
                is = httpEntity.getContent();
            }           


        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    is, "iso-8859-1"), 8);
            StringBuilder sb = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
            is.close();
            json = sb.toString();
        } catch (Exception e) {
            Log.e("Buffer Error", "Error converting result " + e.toString());
        }

        // try parse the string to a JSON object
        try {
            jObj = new JSONObject(json);
        } catch (JSONException e) {
            Log.e("JSON Parser", "Error parsing data " + e.toString());
        }

        // return JSON String
        return jObj;

    }
}

正如您所看到的,我在我的hostinger帐户中托管我的php文件,并且还创建了我的MySQL数据库。 这是应用程序在USB调试模式下运行时的logcat。

03-22 16:42:23.268: D/dalvikvm(531): Not late-enabling CheckJNI (already on)
03-22 16:42:23.508: I/dalvikvm(531): Turning on JNI app bug workarounds for target SDK version 8...
03-22 16:42:24.228: I/dalvikvm(531): threadid=3: reacting to signal 3
03-22 16:42:24.238: I/dalvikvm(531): Wrote stack traces to '/data/anr/traces.txt'
03-22 16:42:24.648: I/dalvikvm(531): threadid=3: reacting to signal 3
03-22 16:42:24.698: D/dalvikvm(531): GC_FOR_ALLOC freed 64K, 2% free 12613K/12867K, paused 261ms
03-22 16:42:24.718: I/dalvikvm(531): Wrote stack traces to '/data/anr/traces.txt'
03-22 16:42:24.738: I/dalvikvm-heap(531): Grow heap (frag case) to 15.890MB for 3686416-byte allocation
03-22 16:42:24.858: D/dalvikvm(531): GC_CONCURRENT freed 1K, 2% free 16212K/16519K, paused 4ms+14ms
03-22 16:42:25.058: D/dalvikvm(531): GC_FOR_ALLOC freed 0K, 2% free 16212K/16519K, paused 31ms
03-22 16:42:25.118: I/dalvikvm-heap(531): Grow heap (frag case) to 22.140MB for 6554896-byte allocation
03-22 16:42:25.148: I/dalvikvm(531): threadid=3: reacting to signal 3
03-22 16:42:25.199: I/dalvikvm(531): Wrote stack traces to '/data/anr/traces.txt'
03-22 16:42:25.237: D/dalvikvm(531): GC_CONCURRENT freed 0K, 2% free 22613K/22983K, paused 5ms+5ms
03-22 16:42:25.618: D/(531): HostConnection::get() New Host Connection established 0x17c018, tid 531
03-22 16:42:25.728: I/dalvikvm(531): threadid=3: reacting to signal 3
03-22 16:42:25.738: I/dalvikvm(531): Wrote stack traces to '/data/anr/traces.txt'
03-22 16:42:26.328: I/dalvikvm(531): threadid=3: reacting to signal 3
03-22 16:42:26.338: I/dalvikvm(531): Wrote stack traces to '/data/anr/traces.txt'
03-22 16:58:22.478: I/dalvikvm(531): threadid=3: reacting to signal 3
03-22 16:58:22.518: I/dalvikvm(531): Wrote stack traces to '/data/anr/traces.txt'
03-22 16:58:22.958: I/dalvikvm(531): threadid=3: reacting to signal 3
03-22 16:58:23.117: I/dalvikvm(531): Wrote stack traces to '/data/anr/traces.txt'
03-22 16:58:24.167: I/dalvikvm(531): threadid=3: reacting to signal 3
03-22 16:58:24.178: I/dalvikvm(531): Wrote stack traces to '/data/anr/traces.txt'
03-22 17:01:32.008: W/System.err(531): org.apache.http.conn.HttpHostConnectException: Connection to http://10.0.2.2 refused
03-22 17:01:32.008: W/System.err(531):  at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:183)
03-22 17:01:32.008: W/System.err(531):  at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164)
03-22 17:01:32.008: W/System.err(531):  at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119)
03-22 17:01:32.008: W/System.err(531):  at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:360)
03-22 17:01:32.008: W/System.err(531):  at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555)
03-22 17:01:32.008: W/System.err(531):  at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
03-22 17:01:32.008: W/System.err(531):  at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465)
03-22 17:01:32.038: W/System.err(531):  at com.papershare.bhanu.JSONParser.makeHttpRequest(JSONParser.java:62)
03-22 17:01:32.048: W/System.err(531):  at com.papershare.bhanu.AllPapersActivity$LoadAllpapers.doInBackground(AllPapersActivity.java:128)
03-22 17:01:32.048: W/System.err(531):  at com.papershare.bhanu.AllPapersActivity$LoadAllpapers.doInBackground(AllPapersActivity.java:1)
03-22 17:01:32.048: W/System.err(531):  at android.os.AsyncTask$2.call(AsyncTask.java:264)
03-22 17:01:32.048: W/System.err(531):  at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
03-22 17:01:32.058: W/System.err(531):  at java.util.concurrent.FutureTask.run(FutureTask.java:137)
03-22 17:01:32.058: W/System.err(531):  at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
03-22 17:01:32.058: W/System.err(531):  at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
03-22 17:01:32.058: W/System.err(531):  at java.lang.Thread.run(Thread.java:856)
03-22 17:01:32.068: W/System.err(531): Caused by: java.net.ConnectException: failed to connect to /10.0.2.2 (port 80): connect failed: ETIMEDOUT (Connection timed out)
03-22 17:01:32.068: W/System.err(531):  at libcore.io.IoBridge.connect(IoBridge.java:114)
03-22 17:01:32.078: W/System.err(531):  at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:192)
03-22 17:01:32.078: W/System.err(531):  at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:459)
03-22 17:01:32.078: W/System.err(531):  at java.net.Socket.connect(Socket.java:842)
03-22 17:01:32.078: W/System.err(531):  at org.apache.http.conn.scheme.PlainSocketFactory.connectSocket(PlainSocketFactory.java:119)
03-22 17:01:32.078: W/System.err(531):  at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:144)
03-22 17:01:32.088: W/System.err(531):  ... 15 more
03-22 17:01:32.088: W/System.err(531): Caused by: libcore.io.ErrnoException: connect failed: ETIMEDOUT (Connection timed out)
03-22 17:01:32.097: W/System.err(531):  at libcore.io.Posix.connect(Native Method)
03-22 17:01:32.097: W/System.err(531):  at libcore.io.BlockGuardOs.connect(BlockGuardOs.java:85)
03-22 17:01:32.097: W/System.err(531):  at libcore.io.IoBridge.connectErrno(IoBridge.java:127)
03-22 17:01:32.097: W/System.err(531):  at libcore.io.IoBridge.connect(IoBridge.java:112)
03-22 17:01:32.108: W/System.err(531):  ... 20 more
03-22 17:01:32.108: E/Buffer Error(531): Error converting result java.lang.NullPointerException
03-22 17:01:32.108: E/JSON Parser(531): Error parsing data org.json.JSONException: End of input at character 0 of 
03-22 17:01:32.117: W/dalvikvm(531): threadid=11: thread exiting with uncaught exception (group=0x409c01f8)
03-22 17:01:32.147: E/AndroidRuntime(531): FATAL EXCEPTION: AsyncTask #1
03-22 17:01:32.147: E/AndroidRuntime(531): java.lang.RuntimeException: An error occured while executing doInBackground()
03-22 17:01:32.147: E/AndroidRuntime(531):  at android.os.AsyncTask$3.done(AsyncTask.java:278)
03-22 17:01:32.147: E/AndroidRuntime(531):  at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:273)
03-22 17:01:32.147: E/AndroidRuntime(531):  at java.util.concurrent.FutureTask.setException(FutureTask.java:124)
03-22 17:01:32.147: E/AndroidRuntime(531):  at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:307)
03-22 17:01:32.147: E/AndroidRuntime(531):  at java.util.concurrent.FutureTask.run(FutureTask.java:137)
03-22 17:01:32.147: E/AndroidRuntime(531):  at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
03-22 17:01:32.147: E/AndroidRuntime(531):  at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
03-22 17:01:32.147: E/AndroidRuntime(531):  at java.lang.Thread.run(Thread.java:856)
03-22 17:01:32.147: E/AndroidRuntime(531): Caused by: java.lang.NullPointerException
03-22 17:01:32.147: E/AndroidRuntime(531):  at com.papershare.bhanu.AllPapersActivity$LoadAllpapers.doInBackground(AllPapersActivity.java:131)
03-22 17:01:32.147: E/AndroidRuntime(531):  at com.papershare.bhanu.AllPapersActivity$LoadAllpapers.doInBackground(AllPapersActivity.java:1)
03-22 17:01:32.147: E/AndroidRuntime(531):  at android.os.AsyncTask$2.call(AsyncTask.java:264)
03-22 17:01:32.147: E/AndroidRuntime(531):  at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
03-22 17:01:32.147: E/AndroidRuntime(531):  ... 4 more
03-22 17:01:32.808: I/dalvikvm(531): threadid=3: reacting to signal 3
03-22 17:01:32.838: I/dalvikvm(531): Wrote stack traces to '/data/anr/traces.txt'
03-22 17:01:34.098: I/dalvikvm(531): threadid=3: reacting to signal 3
03-22 17:01:34.118: I/dalvikvm(531): Wrote stack traces to '/data/anr/traces.txt'
03-22 17:01:35.828: E/WindowManager(531): Activity com.papershare.bhanu.AllPapersActivity has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView@41fe6a18 that was originally added here
03-22 17:01:35.828: E/WindowManager(531): android.view.WindowLeaked: Activity com.papershare.bhanu.AllPapersActivity has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView@41fe6a18 that was originally added here
03-22 17:01:35.828: E/WindowManager(531):   at android.view.ViewRootImpl.<init>(ViewRootImpl.java:344)
03-22 17:01:35.828: E/WindowManager(531):   at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:267)
03-22 17:01:35.828: E/WindowManager(531):   at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:215)
03-22 17:01:35.828: E/WindowManager(531):   at android.view.WindowManagerImpl$CompatModeWrapper.addView(WindowManagerImpl.java:140)
03-22 17:01:35.828: E/WindowManager(531):   at android.view.Window$LocalWindowManager.addView(Window.java:537)
03-22 17:01:35.828: E/WindowManager(531):   at android.app.Dialog.show(Dialog.java:278)
03-22 17:01:35.828: E/WindowManager(531):   at com.papershare.bhanu.AllPapersActivity$LoadAllpapers.onPreExecute(AllPapersActivity.java:118)
03-22 17:01:35.828: E/WindowManager(531):   at android.os.AsyncTask.executeOnExecutor(AsyncTask.java:561)
03-22 17:01:35.828: E/WindowManager(531):   at android.os.AsyncTask.execute(AsyncTask.java:511)
03-22 17:01:35.828: E/WindowManager(531):   at com.papershare.bhanu.AllPapersActivity.onCreate(AllPapersActivity.java:58)
03-22 17:01:35.828: E/WindowManager(531):   at android.app.Activity.performCreate(Activity.java:4465)
03-22 17:01:35.828: E/WindowManager(531):   at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1049)
03-22 17:01:35.828: E/WindowManager(531):   at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1920)
03-22 17:01:35.828: E/WindowManager(531):   at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1981)
03-22 17:01:35.828: E/WindowManager(531):   at android.app.ActivityThread.access$600(ActivityThread.java:123)
03-22 17:01:35.828: E/WindowManager(531):   at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1147)
03-22 17:01:35.828: E/WindowManager(531):   at android.os.Handler.dispatchMessage(Handler.java:99)
03-22 17:01:35.828: E/WindowManager(531):   at android.os.Looper.loop(Looper.java:137)
03-22 17:01:35.828: E/WindowManager(531):   at android.app.ActivityThread.main(ActivityThread.java:4424)
03-22 17:01:35.828: E/WindowManager(531):   at java.lang.reflect.Method.invokeNative(Native Method)
03-22 17:01:35.828: E/WindowManager(531):   at java.lang.reflect.Method.invoke(Method.java:511)
03-22 17:01:35.828: E/WindowManager(531):   at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
03-22 17:01:35.828: E/WindowManager(531):   at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
03-22 17:01:35.828: E/WindowManager(531):   at dalvik.system.NativeStart.main(Native Method)
03-22 17:06:32.377: I/Process(531): Sending signal. PID: 531 SIG: 9

请告诉我的代码中10.0.2.2在移动设备上运行此应用时出现问题

2 个答案:

答案 0 :(得分:3)

您似乎正在尝试访问本地网络上的localhost网络服务。您应该知道,这样的Web服务只能由计算机上的仿真器访问,该计算机可能与服务器位于同一本地网络上。 真实的设备无法访问本地网络上的Web服务。

要在真实设备上测试您的应用,您需要通过公共网址公开您的网络服务,该网址可以在公共网络上访问。这样做,它会起作用。

答案 1 :(得分:0)

只有当您的应用在模拟器上运行时,才能使用

10.0.2.2。对于真实设备更改wlan中服务器的本地IP地址。