-4

I am doing a login page and have the following codes as below. The moment I open up this codes

 // Login button clicked
               // ok = (Button)findViewById(R.id.btn_login);
               // ok.setOnClickListener((android.view.View.OnClickListener) this);

My app crashes. I look throught most are using this approach public class MainActivity extends ActionBarActivity implements OnClickListener so I followed. What is the correct method to enable when on click the button login to call post the data?

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

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;

import android.support.v7.app.ActionBarActivity;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class MainActivity extends ActionBarActivity implements OnClickListener {

    Button ok,back,exit;
     TextView result;

        /** Called when the activity is first created. */
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.login);

            // Login button clicked
           // ok = (Button)findViewById(R.id.btn_login);
           // ok.setOnClickListener((android.view.View.OnClickListener) this);

            result = (TextView)findViewById(R.id.lbl_result);

        }

        public void postLoginData() {
            // Create a new HttpClient and Post Header
            HttpClient httpclient = new DefaultHttpClient();

            /* login.php returns true if username and password is equal to saranga */
            HttpPost httppost = new HttpPost("http://www.sencide.com/blog/login.php");

            try {
                // Add user name and password
             EditText uname = (EditText)findViewById(R.id.txt_username);
             String username = uname.getText().toString();

             EditText pword = (EditText)findViewById(R.id.txt_password);
             String password = pword.getText().toString();

                List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
                nameValuePairs.add(new BasicNameValuePair("username", username));
                nameValuePairs.add(new BasicNameValuePair("password", password));
                httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

                // Execute HTTP Post Request
                Log.w("SENCIDE", "Execute HTTP Post Request");
                HttpResponse response = httpclient.execute(httppost);

                String str = inputStreamToString(response.getEntity().getContent()).toString();
                Log.w("SENCIDE", str);

                if(str.toString().equalsIgnoreCase("true"))
                {
                 Log.w("SENCIDE", "TRUE");
                 result.setText("Login successful");   
                }else
                {
                 Log.w("SENCIDE", "FALSE");
                 result.setText(str);             
                }

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

        private StringBuilder inputStreamToString(InputStream is) {
         String line = "";
         StringBuilder total = new StringBuilder();
         // Wrap a BufferedReader around the InputStream
         BufferedReader rd = new BufferedReader(new InputStreamReader(is));
         // Read response until the end
         try {
          while ((line = rd.readLine()) != null) { 
            total.append(line); 
          }
         } catch (IOException e) {
          e.printStackTrace();
         }
         // Return full string
         return total;
        }

        public void onClick(View view) {
          if(view == ok){
            postLoginData();
          }
        }

        @Override
        public void onClick(DialogInterface dialog, int which) {
            // TODO Auto-generated method stub

        }


}

Below are some error I got when I try to run my application with onclick event

09-30 01:58:01.075: E/AndroidRuntime(1342): FATAL EXCEPTION: main
09-30 01:58:01.075: E/AndroidRuntime(1342): Process: com.example.guard1, PID: 1342
09-30 01:58:01.075: E/AndroidRuntime(1342): android.os.NetworkOnMainThreadException
09-30 01:58:01.075: E/AndroidRuntime(1342):     at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1145)
09-30 01:58:01.075: E/AndroidRuntime(1342):     at java.net.InetAddress.lookupHostByName(InetAddress.java:385)
09-30 01:58:01.075: E/AndroidRuntime(1342):     at java.net.InetAddress.getAllByNameImpl(InetAddress.java:236)
09-30 01:58:01.075: E/AndroidRuntime(1342):     at java.net.InetAddress.getAllByName(InetAddress.java:214)
09-30 01:58:01.075: E/AndroidRuntime(1342):     at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:137)
09-30 01:58:01.075: E/AndroidRuntime(1342):     at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164)
09-30 01:58:01.075: E/AndroidRuntime(1342):     at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119)
09-30 01:58:01.075: E/AndroidRuntime(1342):     at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:360)
09-30 01:58:01.075: E/AndroidRuntime(1342):     at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555)
09-30 01:58:01.075: E/AndroidRuntime(1342):     at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
09-30 01:58:01.075: E/AndroidRuntime(1342):     at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465)
09-30 01:58:01.075: E/AndroidRuntime(1342):     at com.example.guard1.MainActivity.postLoginData(MainActivity.java:72)
09-30 01:58:01.075: E/AndroidRuntime(1342):     at com.example.guard1.MainActivity.onClick(MainActivity.java:113)
09-30 01:58:01.075: E/AndroidRuntime(1342):     at android.view.View.performClick(View.java:4438)
09-30 01:58:01.075: E/AndroidRuntime(1342):     at android.view.View$PerformClick.run(View.java:18422)
09-30 01:58:01.075: E/AndroidRuntime(1342):     at android.os.Handler.handleCallback(Handler.java:733)
09-30 01:58:01.075: E/AndroidRuntime(1342):     at android.os.Handler.dispatchMessage(Handler.java:95)
09-30 01:58:01.075: E/AndroidRuntime(1342):     at android.os.Looper.loop(Looper.java:136)
09-30 01:58:01.075: E/AndroidRuntime(1342):     at android.app.ActivityThread.main(ActivityThread.java:5017)
09-30 01:58:01.075: E/AndroidRuntime(1342):     at java.lang.reflect.Method.invokeNative(Native Method)
09-30 01:58:01.075: E/AndroidRuntime(1342):     at java.lang.reflect.Method.invoke(Method.java:515)
09-30 01:58:01.075: E/AndroidRuntime(1342):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
09-30 01:58:01.075: E/AndroidRuntime(1342):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
09-30 01:58:01.075: E/AndroidRuntime(1342):     at dalvik.system.NativeStart.main(Native Method)
user3953386
  • 153
  • 1
  • 2
  • 10
  • You can simplify `ok.setOnClickListener((android.view.View.OnClickListener) this)` to just `ok.setOnClickListener(this)`. If this change doesn't compile, the unnecessary cast won't fix the problem. – Code-Apprentice Sep 30 '14 at 05:37
  • please see [this](http://stackoverflow.com/questions/20400947/android-os-networkonmainthreadexception/20400965#comment30464520_20400947) and read your logcat from next time. Thanks. – DroidDev Sep 30 '14 at 06:16

4 Answers4

5

remove this import

import android.content.DialogInterface.OnClickListener;

And add this import

  import android.view.View.OnClickListener;
Digvesh Patel
  • 6,503
  • 1
  • 20
  • 34
0

You can use

ok.setOnClickListener(new View.OnClickListener() {
    public void onClick(View v) {
        ...
    }
});

and add

import android.view.View;

or just replace

import android.content.DialogInterface.OnClickListener;

with

import android.view.View.OnClickListener;
PageNotFound
  • 2,320
  • 2
  • 23
  • 34
0

First import the package

import android.view.View.OnClickListener;

Instead of this:

ok.setOnClickListener((android.view.View.OnClickListener) this);

try this:

ok.setOnClickListener(this);

And if you remove implements method for activity then you can use directly this

ok.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {
                // TODO

            }
        });

instead of this ok.setOnClickListener(this);

W I Z A R D
  • 1,224
  • 3
  • 17
  • 44
0

Use OnClickListener.

    ok.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
    ...
}});

onClick callback working in main thread that's why you got exception. Use background threads for network interaction. Loaders - it's good android solution: http://developer.android.com/guide/components/loaders.html

nister
  • 171
  • 6