保留在Tab / Swipe视图片段中时,Android活动不起作用

时间:2014-02-13 16:01:01

标签: java android android-fragments tabs

我有一个Activity,它有2个文本字段和一个按钮;单击按钮时,文本字段中的文本将上传到sql remote server.it工作正常。

现在我想创建一个滑动/标签视图。我已经这样做了,直到这个没问题。现在,我希望在其中一个选项卡中的此滑动视图下显示上述活动。 GUI很好。但是当我点击按钮上传时,它会显示错误。

以下是代码,当它是一个单独的活动时起作用: AddComment.java

    package overskov.rhkbrand;


    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.os.AsyncTask;
    import android.os.Bundle;
    import android.util.Log;
    import android.view.View;
    import android.view.View.OnClickListener;
    import android.widget.Button;
    import android.widget.EditText;
    import android.widget.Toast;

    public class AddComment extends Activity implements OnClickListener{

        private EditText title, message;
        private Button  mSubmit;

         // Progress Dialog
        private ProgressDialog pDialog;

        // JSON parser class
        JSONParser jsonParser = new JSONParser();

        //php login script

        //localhost :  
        //testing on your device
        //put your local ip instead,  on windows, run CMD > ipconfig
        //or in mac's terminal type ifconfig and look for the ip under en0 or en1
       // private static final String POST_COMMENT_URL = "http://xxx.xxx.x.x:1234/webservice/addcomment.php";

        //testing on Emulator:
        private static final String POST_COMMENT_URL = "http://overskov-hansen.dk/addcomment.php";

      //testing from a real server:
        //private static final String POST_COMMENT_URL = "http://www.mybringback.com/webservice/addcomment.php";

        //ids
        private static final String TAG_SUCCESS = "success";
        private static final String TAG_MESSAGE = "message";

        @Override
        protected void onCreate(Bundle savedInstanceState) {
            // TODO Auto-generated method stub
            super.onCreate(savedInstanceState);
            setContentView(R.layout.add_comment);

            title = (EditText)findViewById(R.id.title);
            message = (EditText)findViewById(R.id.message);

            mSubmit = (Button)findViewById(R.id.submit);
            mSubmit.setOnClickListener(this);

        }

        @Override
        public void onClick(View v) {
                    new PostComment().execute();
        }


        class PostComment extends AsyncTask<String, String, String> {

            @Override
            protected void onPreExecute() {
                super.onPreExecute();
                pDialog = new ProgressDialog(AddComment.this);
                pDialog.setMessage("Posting Comment...");
                pDialog.setIndeterminate(false);
                pDialog.setCancelable(true);
                pDialog.show();
            }

            @Override
            protected String doInBackground(String... args) {
                // TODO Auto-generated method stub
                 // Check for success tag
                int success;
                String post_title = title.getText().toString();
                String post_message = message.getText().toString();

                //We need to change this:
                String post_username = "temp";

                try {
                    // Building Parameters
                    List<NameValuePair> params = new ArrayList<NameValuePair>();
                    params.add(new BasicNameValuePair("username", post_username));
                    params.add(new BasicNameValuePair("title", post_title));
                    params.add(new BasicNameValuePair("message", post_message));

                    Log.d("request!", "starting");

                    //Posting user data to script 
                    JSONObject json = jsonParser.makeHttpRequest(
                            POST_COMMENT_URL, "POST", params);

                    // full json response
                    Log.d("Post Comment attempt", json.toString());

                    // json success element
                    success = json.getInt(TAG_SUCCESS);
                    if (success == 1) {
                        Log.d("Comment Added!", json.toString());    
                        finish();
                        return json.getString(TAG_MESSAGE);
                    }else{
                        Log.d("Comment Failure!", json.getString(TAG_MESSAGE));
                        return json.getString(TAG_MESSAGE);

                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }

                return null;

            }

            protected void onPostExecute(String file_url) {
                // dismiss the dialog once product deleted
                pDialog.dismiss();
                if (file_url != null){
                    Toast.makeText(AddComment.this, file_url, Toast.LENGTH_LONG).show();
                }

            }

        }


    }

它使用JSONParse.java:

    package overskov.rhkbrand;

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

        }


        public JSONObject getJSONFromUrl(final String url) {

            // Making HTTP request
            try {
                // Construct the client and the HTTP request.
                DefaultHttpClient httpClient = new DefaultHttpClient();
                HttpPost httpPost = new HttpPost(url);

                // Execute the POST request and store the response locally.
                HttpResponse httpResponse = httpClient.execute(httpPost);
                // Extract data from the response.
                HttpEntity httpEntity = httpResponse.getEntity();
                // Open an inputStream with the data content.
                is = httpEntity.getContent();

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

            try {
                // Create a BufferedReader to parse through the inputStream.
                BufferedReader reader = new BufferedReader(new InputStreamReader(
                        is, "iso-8859-1"), 8);
                // Declare a string builder to help with the parsing.
                StringBuilder sb = new StringBuilder();
                // Declare a string to store the JSON object data in string form.
                String line = null;

                // Build the string until null.
                while ((line = reader.readLine()) != null) {
                    sb.append(line + "\n");
                }

                // Close the input stream.
                is.close();
                // Convert the string builder data to an actual string.
                json = sb.toString();
            } catch (Exception e) {
                Log.e("Buffer Error", "Error converting result " + e.toString());
            }

            // Try to 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 the JSON Object.
            return jObj;

        }


        // 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 == "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 == "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;

        }
    }

现在当我制作标签/滑动视图,并尝试在其中一个标签片段中包含此AddComment.java时,当我单击按钮上传到远程服务器时,它会显示以下错误:

    02-13 21:41:11.529: D/ActivityThread(15232): setTargetHeapUtilization:0.25
    02-13 21:41:11.529: D/ActivityThread(15232): setTargetHeapIdealFree:8388608
    02-13 21:41:11.529: D/ActivityThread(15232): setTargetHeapConcurrentStart:2097152
    02-13 21:41:12.089: I/Adreno200-EGL(15232): <qeglDrvAPI_eglInitialize:290>: EGL 1.4 QUALCOMM build: AU_LINUX_ANDROID_ICS_STRAWBERRY_RB5.04.00.04.29.000_msm7627a_ICS_STRAWBERRY_RB5.1_CL2615821_release_AU (CL2615821)
    02-13 21:41:12.089: I/Adreno200-EGL(15232): Build Date: 07/30/12 Mon
    02-13 21:41:12.089: I/Adreno200-EGL(15232): Local Branch: mybranch139377
    02-13 21:41:12.089: I/Adreno200-EGL(15232): Remote Branch: quic/ics_strawberry_rb5.1
    02-13 21:41:12.089: I/Adreno200-EGL(15232): Local Patches: NONE
    02-13 21:41:12.089: I/Adreno200-EGL(15232): Reconstruct Branch: AU_LINUX_ANDROID_ICS_STRAWBERRY_RB5.04.00.04.29.000 +  NOTHING
    02-13 21:44:01.629: D/request!(15232): starting
    02-13 21:44:01.809: W/System.err(15232): java.net.UnknownHostException: Unable to resolve host "members.000webhost.com": No address associated with hostname
    02-13 21:44:01.839: W/System.err(15232):    at java.net.InetAddress.lookupHostByName(InetAddress.java:426)
    02-13 21:44:01.839: W/System.err(15232):    at java.net.InetAddress.getAllByNameImpl(InetAddress.java:242)
    02-13 21:44:01.849: W/System.err(15232):    at java.net.InetAddress.getAllByName(InetAddress.java:220)
    02-13 21:44:01.849: W/System.err(15232):    at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:137)
    02-13 21:44:01.849: W/System.err(15232):    at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164)
    02-13 21:44:01.849: W/System.err(15232):    at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119)
    02-13 21:44:01.849: W/System.err(15232):    at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:360)
    02-13 21:44:01.849: W/System.err(15232):    at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555)
    02-13 21:44:01.849: W/System.err(15232):    at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
    02-13 21:44:01.859: W/System.err(15232):    at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465)
    02-13 21:44:01.859: W/System.err(15232):    at info.androidhive.tabsswipe.JSONParser.makeHttpRequest(JSONParser.java:110)
    02-13 21:44:01.859: W/System.err(15232):    at info.androidhive.tabsswipe.GamesFragment$PostComment.doInBackground(GamesFragment.java:146)
    02-13 21:44:01.859: W/System.err(15232):    at info.androidhive.tabsswipe.GamesFragment$PostComment.doInBackground(GamesFragment.java:1)
    02-13 21:44:01.859: W/System.err(15232):    at android.os.AsyncTask$2.call(AsyncTask.java:264)
    02-13 21:44:01.859: W/System.err(15232):    at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
    02-13 21:44:01.859: W/System.err(15232):    at java.util.concurrent.FutureTask.run(FutureTask.java:137)
    02-13 21:44:01.859: W/System.err(15232):    at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:208)
    02-13 21:44:01.869: W/System.err(15232):    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
    02-13 21:44:01.869: W/System.err(15232):    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
    02-13 21:44:01.869: W/System.err(15232):    at java.lang.Thread.run(Thread.java:856)
    02-13 21:44:01.869: W/System.err(15232): Caused by: libcore.io.GaiException: getaddrinfo failed: EAI_NODATA (No address associated with hostname)
    02-13 21:44:01.869: W/System.err(15232):    at libcore.io.Posix.getaddrinfo(Native Method)
    02-13 21:44:01.879: W/System.err(15232):    at libcore.io.ForwardingOs.getaddrinfo(ForwardingOs.java:55)
    02-13 21:44:01.879: W/System.err(15232):    at java.net.InetAddress.lookupHostByName(InetAddress.java:411)
    02-13 21:44:01.879: W/System.err(15232):    ... 19 more
    02-13 21:44:01.879: E/Buffer Error(15232): Error converting result java.lang.NullPointerException
    02-13 21:44:01.889: E/JSON Parser(15232): Error parsing data org.json.JSONException: End of input at character 0 of 
    02-13 21:44:01.889: W/dalvikvm(15232): threadid=11: thread exiting with uncaught exception (group=0x40a8c390)
    02-13 21:44:01.899: E/AndroidRuntime(15232): FATAL EXCEPTION: AsyncTask #1
    02-13 21:44:01.899: E/AndroidRuntime(15232): java.lang.RuntimeException: An error occured while executing doInBackground()
    02-13 21:44:01.899: E/AndroidRuntime(15232):    at android.os.AsyncTask$3.done(AsyncTask.java:278)
    02-13 21:44:01.899: E/AndroidRuntime(15232):    at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:273)
    02-13 21:44:01.899: E/AndroidRuntime(15232):    at java.util.concurrent.FutureTask.setException(FutureTask.java:124)
    02-13 21:44:01.899: E/AndroidRuntime(15232):    at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:307)
    02-13 21:44:01.899: E/AndroidRuntime(15232):    at java.util.concurrent.FutureTask.run(FutureTask.java:137)
    02-13 21:44:01.899: E/AndroidRuntime(15232):    at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:208)
    02-13 21:44:01.899: E/AndroidRuntime(15232):    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
    02-13 21:44:01.899: E/AndroidRuntime(15232):    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
    02-13 21:44:01.899: E/AndroidRuntime(15232):    at java.lang.Thread.run(Thread.java:856)
    02-13 21:44:01.899: E/AndroidRuntime(15232): Caused by: java.lang.NullPointerException
    02-13 21:44:01.899: E/AndroidRuntime(15232):    at info.androidhive.tabsswipe.GamesFragment$PostComment.doInBackground(GamesFragment.java:150)
    02-13 21:44:01.899: E/AndroidRuntime(15232):    at info.androidhive.tabsswipe.GamesFragment$PostComment.doInBackground(GamesFragment.java:1)
    02-13 21:44:01.899: E/AndroidRuntime(15232):    at android.os.AsyncTask$2.call(AsyncTask.java:264)
    02-13 21:44:01.899: E/AndroidRuntime(15232):    at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
    02-13 21:44:01.899: E/AndroidRuntime(15232):    ... 5 more

有人可以帮忙吗?

1 个答案:

答案 0 :(得分:0)

  

02-13 21:44:01.809:W / System.err(15232):java.net.UnknownHostException:无法解析主机“members.000webhost.com”:没有与主机名关联的地址

你基本上是在做主机解析,无论你使用什么连接(WiFi,3G ......)都无法解析该主机。这似乎是一个连接问题,因为每个DNS主机名都有一个IP地址(这个逻辑并不总是适用于另一方)。

由于您提供的代码没有members.000webhost.com的任何引用,您似乎只需将该行包含在try语句中catch UnknownHostException异常。

try {
  the_line_or_lines_that_try_to_connect_to_this_host("members.000webhost.com");
}
catch (UnknownHostException e) {
  // Maybe some logging and try again?
}