简体   繁体   English

保留在“标签” /“滑动”视图片段中时,Android活动不起作用

[英]Android activity doesn't work when kept in Tab/Swipe view fragment

I have an Activity, which has 2 text fields and a button; 我有一个活动,其中有2个文本字段和一个按钮; when the button is clicked the text in the text fields are uploaded to sql remote server.it works fine. 单击按钮时,文本字段中的文本将上载到sql remote server。它工作正常。

Now i want to create a swipe/tab view. 现在,我想创建一个滑动/标签视图。 i have done that,and till this it is fine. 我已经做到了,到目前为止还可以。 Now i want the above activity to be shown under this swipe view,in one of the tab. 现在,我希望以上活动显示在选项卡之一的此滑动视图下。 The GUI is fine . GUI很好。 but when i click the button to upload, it shows the error. 但是当我单击按钮上传时,它显示错误。

following is the code,which works when it is a separate activity: AddComment.java 以下是代码,当它是一个单独的活动时,该代码将起作用: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();
                }

            }

        }


    }

It uses JSONParse.java: 它使用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;

        }
    }

Now when i make tab/swipe view, and try to include this AddComment.java in one of the tab fragment,when i click the button to upload to remote server, it shows the following error: 现在,当我制作选项卡/滑动视图,并尝试在选项卡片段之一中包含此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

Can anyone help? 有人可以帮忙吗?

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.809:W / System.err(15232):java.net.UnknownHostException:无法解析主机“ members.000webhost.com”:没有与主机名关联的地址

You're basically doing a host resolution and whatever your using as connection (WiFi, 3G...) cannot resolve that host. 您基本上是在做主机解析,无论您用作连接(WiFi,3G ...)都无法解析该主机。 It seems to be a connection issue since every DNS hostname has an IP address (this logic doesn't always work to the other side). 由于每个DNS主机名都有一个IP地址,因此这似乎是一个连接问题(此逻辑在另一端并不总是有效)。

Since the code you provided doesn't have any reference to members.000webhost.com , seems that you just need to wrap that line within a try statement and catch the UnknownHostException exception. 由于您提供的代码没有对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?
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM