Активность при входе в систему в Android

#android #login

#Android #аутентификация

Вопрос:

Я создал приложение для Android.в этом приложении я создал веб-сервисы на php для извлечения и хранения данных С сервера side.my службы запускаются успешно и показывают сообщение log cat об успешном входе в систему. но когда я нажимаю на кнопку входа в emulator.it отображаемое имя пользователя и пароль не совпадают. пожалуйста, скажите мне, где я ошибаюсь.

Logcat

 // log cat message which shows log in is successful.it display the parameter With the added value that I have added into the database  


          D/response(2239):     "User_Detail": [
          D/response(2239):         {
             D/response(2239):             "license_pic": "upload/license_45.png",
        D/response(2239):             "status": "0",
       D/response(2239):             "post_code": "0",
          D/response(2239):             "street_name": "tgwee",
             D/response(2239):             "authority_id": "6882",
             D/response(2239):             "id": "45",
           D/response(2239):             "first_name": "uruur",

          D/response(2239):             "Email": "viv@gmail.com",

          D/response(2239):             "State": "New South Wales",
             D/response(2239):             "face_pic": "upload/face_45.png",
      D/response(2239):             "Suburb": "Sydney",
            D/response(2239):             "audit_card_pic": "upload/audit_45.png",
          D/response(2239):             "unit_no": "6566555",
             D/response(2239):             "longitude": "",
            D/response(2239):             "add_count": "4",
           D/response(2239):             "latitude": "",
             D/response(2239):             "date_of_creation": "2014-06-18 09:19:27",
             D/response(2239):             "Surname": "hyee",
           D/response(2239):             "driving_lic": "58481",
            D/response(2239):             "mobile_no": "65494"
         D/response(2239):         }
            D/response(2239):     ],

            D/response(2239):     "message": "Login successful.",
             D/response(2239):     "err-code": "0"
               D/response(2239): }
  

код для входа

   public class LoginActivity extends Activity {

    TextView newmember,forgot,view;
    Button submit,cancel;
    EditText uedit,pedit; 
    Vibrator vibe;
    String euid,epass;
    private String mfname,msname,mun,mstreet,msuburb,mstate,mpassword,mconfirm_password,mpostcode,mlicense,mid,mmobile,memail,mimagelicense,mauthcard,mpic,login_token,latitude,longitude;
    private SharedPreferences pref;
    String name,pass;
    String status_key;
    private Typeface ftype;
    private static MyDialog dialog1;
    private static SuccessDialog dialog;
    private PasswordDB db;
    Bitmap bitmap1, bitmap2,bitmap3;
    Bitmap[] bitmap;
    String[] driver_details;
    private byte imageInByte1[],imageInByte2[],imageInByte3[] ;
    private Context mContext;
    private String mname,mobile,state,desc;

    public String advertisement_count;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.login);

         vibe = (Vibrator)getSystemService(Context.VIBRATOR_SERVICE);
    //  ftype=Typeface.createFromAsset(getAssets(),"font/Futura Koyu.ttf");
        uedit = (EditText)findViewById(R.id.euname);
        pedit = (EditText)findViewById(R.id.epassword);
        view = (TextView)findViewById(R.id.forg);

        forgot= (TextView)findViewById(R.id.forget_password);
        cancel= (Button)findViewById(R.id.cancel);
        /* uedit.setTypeface(ftype);
        pedit.setTypeface(ftype);
        forgot.setTypeface(ftype);
        cancel.setTypeface(ftype); */
        view.setOnClickListener(new OnClickListener() {

            public void onClick(View arg0) {
                // TODO Auto-generated method stub
                Intent viewpass= new Intent(getApplicationContext(),ViewData.class);
                startActivity(viewpass);
            }
        });

        newmember = (TextView)findViewById(R.id.newmemb);
        newmember.setTypeface(ftype);
        newmember.setOnClickListener(new OnClickListener() {

            public void onClick(View arg0) {
                // TODO Auto-generated method stub
                Intent intt = new Intent(getApplicationContext(),Registration.class);
                startActivity(intt);
            }
        });
        submit = (Button)findViewById(R.id.submit);
    //  submit.setTypeface(ftype);

    submit.setOnClickListener(new OnClickListener() {
        public void onClick(View v) {

                        new SigIn(LoginActivity.this).execute();    
                        new Images().execute();
                    //  new ViewAdvertisement().execute();
            //  Toast.makeText(LoginScreen.this, "You clicked the button", Toast.LENGTH_SHORT).show();
            }       
           });


    cancel.setOnClickListener(new OnClickListener() {
        public void onClick(View v) {
            ViewGroup group = (ViewGroup)findViewById(R.id.relone);
            for (int i = 0, count = group.getChildCount(); i < count;   i) {
                View view = group.getChildAt(i);
                if (view instanceof EditText) {
                    ((EditText)view).setText("");
                }
            }   }           

            });


    forgot.setOnClickListener(new OnClickListener() {
        public void onClick(View v) {

            vibe.vibrate(50);
            /*String rr="Im getting " resdis "% off at " name1 " with Circl. You can too! Get it here: url="
                                 " http://yoz.io/r/sBxQ";*/


            String rr= "Im getting % off at with Circl. You can too! Get it here: url http://yoz.io/r/sBxQ";

            Intent i = new Intent(Intent.ACTION_SEND);
            i.setType("message/rfc822");
            i.putExtra(Intent.EXTRA_EMAIL , new String[]{""});
            i.putExtra(Intent.EXTRA_SUBJECT, "Circl Sharing");
            i.putExtra(Intent.EXTRA_TEXT , rr);
            try {
            startActivity(Intent.createChooser(i, "Send mail..."));
            } catch (android.content.ActivityNotFoundException ex) {
            }

            }           

            });

    if(isInternetOn(LoginActivity.this)== false)
    {
    }
       }

    public boolean isInternetOn(Context ctx) {
        this.mContext = ctx;
        ConnectivityManager Connect_Manager = (ConnectivityManager) mContext
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        State connected = NetworkInfo.State.CONNECTED;
        State connecting = NetworkInfo.State.CONNECTING;
        State disconnected = NetworkInfo.State.DISCONNECTED;

        State info0 = Connect_Manager.getNetworkInfo(0).getState();
        State info1 = Connect_Manager.getNetworkInfo(1).getState();

        // ARE WE CONNECTED TO THE NET
        if (info0 == connected || info0 == connecting || info1 == connecting
                || info1 == connected) {

            Log.d("Internet", "Connected");
            return true;
        } else if (info0 == disconnected || info1 == disconnected) {
            Log.d("Internet", "DisConnected");
            return false;
        }
        return false;
    }

      private class SigIn extends AsyncTask<String, String, String[]> {
          private final Context _context;  

          public SigIn(Context context){
                _context = context;

            }
        ProgressDialog pDialog = new ProgressDialog(LoginActivity.this);
        @SuppressWarnings("deprecation")
        @SuppressLint("WorldReadableFiles")
        @Override
        protected String[] doInBackground(final String... params) 
        {
            ConnectivityManager conMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
            if (conMgr.getActiveNetworkInfo() != null
                    amp;amp; conMgr.getActiveNetworkInfo().isAvailable()
                    amp;amp; conMgr.getActiveNetworkInfo().isConnected()) 
            {
                HttpClient httpclient = new DefaultHttpClient();
                try 
                {
                    pDialog.setMessage("Please wait signing in...");
                    runOnUiThread(new Runnable() 
                    {
                        public void run() 
                        {
                            pDialog.show();
                        }
                    });

                    JSONObject job= new JSONObject();
                    euid = uedit.getText().toString();
                    epass = pedit.getText().toString();

                    euid.replace("" ," ");
                    epass.replace("" ," ");
                    job.put("status_key","0");
                    job.put("method", "login");
                    job.put("email", euid);
                    job.put("password",epass );
                    job.put("login_token",login_token );

                /*
                    System.out.print("latitude is " latitude);
                    job.put("latitude",latitude);
                    job.put("longitude",longitude);*/

                    StringEntity se = new StringEntity(job.toString());

                    //HttpPost httppost = new HttpPost("http://suntechwebsolutions.com/clients/mobileapp_now/webservice.php");
                     HttpPost httppost = new HttpPost("http://suntechwebsolutions.com/clients/DGCapp/webservice.php");
                    httppost.setEntity(se);

                    HttpResponse response = httpclient.execute(httppost);
                      String data = EntityUtils.toString(response.getEntity());
                      System.out.println("response " data);

                      JSONObject jo = new JSONObject(data);

                    Log.d("response", jo.toString(4));
                    if(jo.getString("err-code").equals("0"))
                    {

                    JSONArray jArray = jo.getJSONArray("driver_details");  
                    Log.d("Array", jArray.toString(4));
                    JSONObject adv= jo.getJSONObject("advertisement_count");  
                    advertisement_count=adv.getString("count(*)");
                    System.out.print("advertisemnet" advertisement_count);              
                    for (int i=0; i < jArray.length(); i  )
                    {
                        try {
                        JSONObject jsob = jArray.getJSONObject(i);

                                mfname = jsob.getString("first_name");
                                msname = jsob.getString("Surname");
                                mun = jsob.getString("unit_no");
                                mstreet = jsob.getString("street_name");
                                msuburb = jsob.getString("Suburb");
                                mstate = jsob.getString("State");
                                mpassword = jsob.getString("password");
                                mpostcode = jsob.getString("post_code");
                                mlicense = jsob.getString("driving_lic");
                                mid = jsob.getString("authority_id");
                                mmobile = jsob.getString("mobile_no");
                                memail = jsob.getString("Email");
                                login_token=jsob.getString("login_token");
                                mimagelicense=jsob.getString("license_pic");
                                mauthcard=jsob.getString("audit_card_pic");
                                mpic=jsob.getString("face_pic");
        } catch (JSONException e) {
                             e.printStackTrace();
                        } 

        pref=getSharedPreferences("Driver", MODE_WORLD_READABLE);
                    SharedPreferences.Editor edit=pref.edit();

                    edit.putString("mfname", mfname);
                    edit.putString("msname", msname);
                    edit.putString("mun", mun);
                    edit.putString("mstreet", mstreet);
                    edit.putString("msuburb", msuburb);
                    edit.putString("mpassword", mpassword);
                    edit.putString("mpostcode", mpostcode);
                    edit.putString("mlicense", mlicense);
                    edit.putString("mid", mid);
                    edit.putString("mmobile", mmobile);
                    edit.putString("memail", memail);
                    edit.putString("login_token", login_token);

                    System.out.print("login_token in LoginActivity"  login_token);
                    edit.putString("mimagelicense", mimagelicense);
                    edit.putString("mauthcard", mauthcard);
                    edit.putString("mpic", mpic);
                    edit.putString("advertisement_count", advertisement_count);
                    edit.commit();

                    //if(jo.getString("err-code").equals("0"))
                    {
                        final AlertDialog.Builder alert = new AlertDialog.Builder(LoginActivity.this);
                        alert.setTitle("Login!!!");
                        alert.setMessage(jo.getString("message"));
                        alert.setPositiveButton("Ok",
                                new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog,
                                    int whichButton) 
                            {

                            pDialog.setCanceledOnTouchOutside(false);
                                pDialog.dismiss();
                                dialog.dismiss();

                                Intent tabint = new Intent(getApplicationContext(),agreement.class);
                                       startActivity(tabint);
                        }
                        });
                        runOnUiThread(new Runnable() {
                            public void run() {
                                alert.show();
                            }
                        });
                    }
                    }
                    else
                    {

                        final AlertDialog.Builder alert = new AlertDialog.Builder(LoginActivity.this);
                        alert.setTitle("Alert !");
                        alert.setMessage(jo.getString("message"));
                        alert.setPositiveButton("Ok",

                            new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog,
                                    int whichButton) {
                                dialog.dismiss();

                            }
                        });
                        runOnUiThread(new Runnable() 
                        {
                            public void run() 
                            {
                                pDialog.setCanceledOnTouchOutside(false);
                                pDialog.dismiss();

                                alert.show();
                            }
                        });
                    }
                }
                catch (Exception e) 
                {
                    e.printStackTrace();
                }
            }
            else
            {
                final AlertDialog.Builder alert = new AlertDialog.Builder(LoginActivity.this);
                alert.setTitle("Alert !");
                alert.setMessage("No Internet connection ");
                alert.setPositiveButton("Ok",
                        new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog,
                            int whichButton) 
                    {
                        dialog.dismiss();
                    }
                });
                runOnUiThread(new Runnable() 
                {
                    public void run() 
                    {
                        pDialog.dismiss();
                        alert.show();
                    }
                });
            }
            return params;
        }

        @SuppressLint("NewApi")
        @Override
        protected void onPostExecute(String[] result) 
        {

            LoginActivity test = (LoginActivity) _context;
            test.driver_details=resu<
            super.onPostExecute(result);

        }   
       }
       private class Images extends AsyncTask<Bitmap[],Bitmap,Bitmap[]> {

        private Exception exception;

        protected Bitmap[] doInBackground(Bitmap[]...urls) {


            try {
                 bitmap1 = DownloadImage(mimagelicense);
                 bitmap2 = DownloadImage(mauthcard);
                 bitmap3= DownloadImage(mpic);
              ByteArrayOutputStream stream = new ByteArrayOutputStream();
              bitmap1.compress(Bitmap.CompressFormat.JPEG, 100, stream);
                   imageInByte1 = stream.toByteArray();


                   System.out.print("DB storing image "   imageInByte1);           

                   bitmap2.compress(Bitmap.CompressFormat.JPEG, 100, stream);
                   imageInByte2 = stream.toByteArray();
                   bitmap3.compress(Bitmap.CompressFormat.JPEG, 100, stream);
                   imageInByte3 = stream.toByteArray();

            System.out.println(" ****************************");     

                    for(int i = 0; i < driver_details.length; i  ) 
                       // System.out.println(driver_details[i]);
                    Log.v("Async variables",driver_details[i]);

                    db = new PasswordDB(getApplicationContext());               
                      db.insert(mfname, msname, mun, mstreet, msuburb,mstate, mpostcode, mlicense, mid, mmobile, memail,  imageInByte1, imageInByte2, imageInByte3);
                    /**
                    * CRUD Operations
                    * */
                    // Inserting Contacts

                    //db.close();

            }
            catch(Exception e)
            {
            }
            return bitmap;
        }   

        private  java.io.InputStream OpenHttpConnection(String urlString)
        throws IOException
              {
              java.io.InputStream in = null;
              int response = -1;

            URL url = new URL(urlString);
            URLConnection conn = url.openConnection();

            if (!(conn instanceof HttpURLConnection))                    
                throw new IOException("Not an HTTP connection");

            try{
                HttpURLConnection httpConn = (HttpURLConnection) conn;
                httpConn.setAllowUserInteraction(false);
                httpConn.setInstanceFollowRedirects(true);
                httpConn.setRequestMethod("GET");
                httpConn.connect();

                response = httpConn.getResponseCode();                
                if (response == HttpURLConnection.HTTP_OK) {
                    in = httpConn.getInputStream();                                
                }                    
            }
            catch (Exception ex)

            {
                ex.printStackTrace();
                throw new IOException("Error connecting");           
            }
            return in;    
        }
        private Bitmap DownloadImage(String URL)
        {       
            Bitmap bitmap = null;
            java.io.InputStream in = null;       
            try {
                in = OpenHttpConnection(URL);
                bitmap = BitmapFactory.decodeStream(in);
                in.close();
            } catch (IOException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }
            return bitmap;               
        }

        @Override
        protected void onPostExecute(Bitmap[] result) 
        {

            super.onPostExecute(result);
        }
     }
}                   
  

Комментарии:

1. это сообщение cat журнала, но моя активность входа в систему не работает. я совершенно сбит с толку, скажите, где я ошибаюсь

2. также добавьте код нажатия кнопки.

3. Без вашего кода для обработки нажатия кнопки мы не сможем помочь.

4. не могли бы вы, пожалуйста, обновить свой код, чтобы мы могли вам помочь.

5. я добавил код, пожалуйста, проверьте, что