为什么getdata函数对主要活动起作用?

时间:2015-08-18 07:20:05

标签: php android android-activity

我是Android开发的新手,目前我正在发布并将数据提取到php文件。我无法找到为什么getData()函数给出在主活动中不起作用,但它在另一个活动中正常工作。我将相同的功能从仪表板活动复制到主要活动。

这是我的主要活动代码

public class MainActivity extends ActionBarActivity {

    private static final String TAG = "MainActivity.java";
    private EditText editEmail;
    private EditText editPass;
    TextView resultView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        final Button loginButton;
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        resultView = (TextView) findViewById(R.id.result);
        getData();
        editEmail = (EditText) findViewById(R.id.userEmail);
        editPass = (EditText) findViewById(R.id.userPassword);
        loginButton = (Button) findViewById(R.id.buttonlogin);
        loginButton.setOnClickListener(new Button.OnClickListener() {
            public void onClick(View v) {
                final String email = editEmail.getText().toString();
                final String pass = editPass.getText().toString();
                //perform action
                if (!isValidEmail(email)) {
                    editEmail.setError("Please enter valid Email...");
                }
                else if (!isValidPassword(pass)) {
                    editPass.setError("Please enter valid Password");
                }else{
                    new PostDataAsyncTask().execute();

                    startActivity(new Intent(MainActivity.this, DashboardActivity.class));
                }

                //if (emailEditText.getText().toString().trim().length()==0) {
                    //Toast.makeText(getBaseContext(), "Email is empty!!!", Toast.LENGTH_SHORT).show();
                    //return;
               // }else{
                    // Redirect to Another Activity
                    //startActivity(new Intent(MainActivity.this, DashboardActivity.class));
               // }
                //if(upassword.getText().toString().trim().length()==0){
                   // Toast.makeText(getBaseContext(), "Password is empty!!!", Toast.LENGTH_SHORT).show();
                    //return;
                //}

            }
        });



    }
    // validating email id
    private boolean isValidEmail(String email) {
        String EMAIL_PATTERN = "^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@"
                + "[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";

        Pattern pattern = Pattern.compile(EMAIL_PATTERN);
        Matcher matcher = pattern.matcher(email);
        return matcher.matches();
    }
    // validating password with retype password
    private boolean isValidPassword(String pass) {
        if (pass != null && pass.length() > 10) {
            return true;
        }
        return false;
    }
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, 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();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }


    public class PostDataAsyncTask extends AsyncTask<String, String, String> {

        protected void onPreExecute() {
            super.onPreExecute();
            // do stuff before posting data
        }

        @Override
        protected String doInBackground(String... strings) {
            try {

                // 1 = post text data, 2 = post file
                int actionChoice = 2;

                // post a text data
                if(actionChoice==1){
                    postText();
                }

            } catch (NullPointerException e) {
                e.printStackTrace();
            } catch (Exception e) {
                e.printStackTrace();
            }
            return null;
        }

        @Override
        protected void onPostExecute(String lenghtOfFile) {
            // do stuff after posting data
        }
    }

    // this will post our text data
    private void postText(){
        final String email = editEmail.getText().toString();
        final String pass = editPass.getText().toString();
        try{
            // url where the data will be posted
            String postReceiverUrl = "http://xyzweb.com/appservice.php";
            Log.v(TAG, "postURL: " + postReceiverUrl);

            // HttpClient
            HttpClient httpClient = new DefaultHttpClient();

            // post header
            HttpPost httpPost = new HttpPost(postReceiverUrl);

            // add your data
            List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
            nameValuePairs.add(new BasicNameValuePair("first_name", email));
            //nameValuePairs.add(new BasicNameValuePair("lastname", pass));


            httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

            // execute HTTP post request
            HttpResponse response = httpClient.execute(httpPost);
            HttpEntity resEntity = response.getEntity();

            if (resEntity != null) {

                String responseStr = EntityUtils.toString(resEntity).trim();
                Log.v(TAG, "Response: " +  responseStr);

                // you can add an if statement here and do other actions based on the response
            }

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


    public void getData(){
        String result = "";
        InputStream isr = null;
        try{
            HttpClient httpclient = new DefaultHttpClient();
            HttpPost httppost = new HttpPost("http://xyzweb.com/appservice.php"); //YOUR PHP SCRIPT ADDRESS
            HttpResponse response = httpclient.execute(httppost);
            HttpEntity entity = response.getEntity();
            isr = entity.getContent();
        }
        catch(Exception e){
            Log.e("log_tag", "Error in http connection " + e.toString());
            resultView.setText("Couldnt connect to database");
        }
        //convert response to string
        try{
            BufferedReader reader = new BufferedReader(new InputStreamReader(isr,"iso-8859-1"),8);
            StringBuilder sb = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
            isr.close();

            result=sb.toString();
        }
        catch(Exception e){
            Log.e("log_tag", "Error  converting result "+e.toString());
        }

        //parse json data
        try {
            String s = "";
            JSONArray jArray = new JSONArray(result);

            for(int i=0; i<jArray.length();i++){
                JSONObject json = jArray.getJSONObject(i);
                s = s +
                        "Name : "+json.getString("first_name")+"\n\n";
            }

            resultView.setText(s);

        } catch (Exception e) {
            // TODO: handle exception
            Log.e("log_tag", "Error Parsing Data " + e.toString());
        }

    }
}

getData()函数发出此错误Couldnt connect to database

Php Code

$name   = urldecode($_POST['first_name']);
    //$user   = urldecode($_POST['user']);
    //$email  = urldecode($_POST['email']);
    //$pass   = urldecode($_POST['pass']);
    $postdata = array();  
    $postdata[]['first_name']  =  'hjgjh';
    print(json_encode($postdata));

1 个答案:

答案 0 :(得分:2)

getData()函数执行远程URL。这些类型的请求应由后台线程而不是主线程处理。这可以这样做:

   @Override
   protected void onCreate(Bundle savedInstanceState) {
            final Button loginButton;
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            resultView = (TextView) findViewById(R.id.result);
            //Call your getData function from AsyncTask                    
            new YourAsyncTask.execute();
            ...
    }

    public class YourAsyncTask extends AsyncTask<String, String, String> {

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

            @Override
            protected String doInBackground(String... strings) {
               //Call getData function from here                
               getData();
               return null;
            }

           @Override
           protected void onPostExecute(String lenghtOfFile) {
                // do stuff after posting data
           }
      }