Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why getdata function does work on main activity?

I'm new in android development, currently i'm posting and fetching data to php file. I'm unable to find why getData() function give does not work in main activity however it is working properly in another activity. I copied same function from dashboard activity to main activity.

Here is my main activity code

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() function giving this error 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));
like image 374
Ayaz Shah Avatar asked May 15 '26 15:05

Ayaz Shah


1 Answers

getData() function executes a remote URL. These types of requests should be handled by background thread instead of Main thread. This can be done like this:

   @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
           }
      }
like image 102
Chaman Saini Avatar answered May 18 '26 05:05

Chaman Saini



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!