0

I want to show an Alert Dialog when a user enters a wrong email or password.
The problem is that the class doesn't extend Activity and also the AlertDialog should be in the onPostExecute() of an Asynctask

Here is my code.

package com.example.akshay.registerandlogin;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.util.Log;

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.HttpClient;
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.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.json.JSONException;
import org.json.JSONObject;

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

/**
 * Created by Akshay on 30-07-2015.
 */
public class ServerWork {

    ProgressDialog progressDialog;
    ProgressDialog pg;
    private static final String REGISTER_URL = "http://www.funvilla.in/test/Register.php";
    private static String LOGIN_URL = "http://www.funvilla.in/test/Login.php";
    private static final int TIMEOUT = 1000 * 15;
    String username,password;
    InputStream is = null;
    BufferedReader br;
    StringBuilder sb;
    UserData user;

    public ServerWork()
    {

    }
    public void RegisterData(Context context) {
       /* progressDialog = new ProgressDialog(context);*/

        new StoreData().execute();
    }

    public void GetDataFromServer(Context context) {
        /*pg = new ProgressDialog(context);*/

        new getData(context).execute();
    }

    public class StoreData extends AsyncTask<Void, Void, Void> {
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
         /*   progressDialog.setCancelable(false);
            progressDialog.setTitle("Establishing Connection");
            progressDialog.setMessage("Please Wait......");
            progressDialog.show();
*/
        }


        @Override
        protected Void doInBackground(Void... params) {
            Log.e("CHECCCCKKKK" ,user.NAME );
            Log.e("CHECCCCKKKK" ,user.EMAIL );
            Log.e("CHECCCCKKKK" ,user.USERNAME );
            Log.e("CHECCCCKKKK" ,user.PASSWORD );

            ArrayList<NameValuePair> dataToSave = new ArrayList<>();
           dataToSave.add(new BasicNameValuePair("name", user.NAME));
            dataToSave.add(new BasicNameValuePair("email", user.EMAIL));
            dataToSave.add(new BasicNameValuePair("age", String.valueOf(user.AGE)));
            dataToSave.add(new BasicNameValuePair("username", user.USERNAME));
            dataToSave.add(new BasicNameValuePair("password", user.PASSWORD));
            dataToSave.add(new BasicNameValuePair("date", user.DATE));
            dataToSave.add(new BasicNameValuePair("time", user.TIME));

            HttpParams httpParams = new BasicHttpParams();
            HttpConnectionParams.setConnectionTimeout(httpParams, TIMEOUT);
            HttpConnectionParams.setSoTimeout(httpParams, TIMEOUT);
            HttpClient httpClient = new DefaultHttpClient(httpParams);
            HttpPost post = new HttpPost(REGISTER_URL);

            try {
                post.setEntity(new UrlEncodedFormEntity(dataToSave));
                httpClient.execute(post);
            } catch (UnsupportedEncodingException e) {
                Log.e("HttpClient", "Problem near Line 70 ServerWork.java");
                e.printStackTrace();
            } catch (ClientProtocolException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }


            return null;
        }

        @Override
        protected void onPostExecute(Void aVoid) {

            super.onPostExecute(aVoid);
          /*  progressDialog.dismiss();*/

        }


    }

    public class getData extends AsyncTask<Void, Void, Void> {
Context context;
        public getData(Context context)
        {
            this.context = context.getApplicationContext();
        }
        @Override
        protected void onPreExecute() {


            super.onPreExecute();
           /* pg.setCancelable(false);
            pg.setTitle("Please Wait");
            pg.setMessage("Establishing Connection");
            pg.show();*/
        }

        @Override
        protected Void doInBackground(Void... params) {
            ArrayList<NameValuePair> login = new ArrayList<>();
            login.add(new BasicNameValuePair("username", user.USERNAME));
            login.add(new BasicNameValuePair("password", user.PASSWORD));
            HttpParams httpparams = new BasicHttpParams();
            HttpConnectionParams.setConnectionTimeout(httpparams, TIMEOUT);
            HttpConnectionParams.setSoTimeout(httpparams, TIMEOUT);
            HttpClient client = new DefaultHttpClient(httpparams);
            String encodedURl = URLEncodedUtils.format(login, "utf-8");
            LOGIN_URL += "?" + encodedURl;
            HttpGet get = new HttpGet(LOGIN_URL);
            try {
                HttpResponse response = client.execute(get);
                HttpEntity entity = response.getEntity();
                is = entity.getContent();

            } catch (IOException e) {

                e.printStackTrace();
            }
            String line = null;
            sb = new StringBuilder();
            br = new BufferedReader(new InputStreamReader(is));
            try {
                while ((line = br.readLine()) != null) {
                    sb.append(line + "\n");
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            Log.e("check", sb.toString());
            try {
                JSONObject object = new JSONObject(sb.toString());
                String name = object.getString("name");
                String email = object.getString("email");
                int age = object.getInt("age");
                username = object.getString("username");
                password = object.getString("password");
                Log.e("check", name);
                Log.e("check", email);
                Log.e("check", String.valueOf(age));
                Log.e("check", username);
            } catch (JSONException e) {
                e.printStackTrace();
            }

            return null;
        }

        @Override
        protected void onPostExecute(Void aVoid) {

            super.onPostExecute(aVoid);
            /*pg.dismiss();*/

            if((UserData.USERNAME).equals(username) && UserData.PASSWORD.equals(password))
            {
                context.startActivity(new Intent(context,MainActivity.class).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK));
            }
            else
            {

               AlertDialog.Builder m = new AlertDialog.Builder(context);
                m.setMessage("Wrong pass");
                m.show();
            }

        }
    }
}
Phantômaxx
  • 37,901
  • 21
  • 84
  • 115
  • http://stackoverflow.com/questions/6119305/android-how-to-run-asynctask-from-different-class-file or you can use [an interface](http://stackoverflow.com/questions/18517400/inner-class-can-access-but-not-update-values-asynctask/18517648#18517648) – codeMagic Jul 30 '15 at 16:52

2 Answers2

0

You can do it by various component like Interfaces or Broadcast Receivers but I would suggest to use [Otto]: http://square.github.io/otto/ as it is quite simple to use and also your code readability will be increase. You will find a running example here :- http://www.cardinalsolutions.com/blog/2015/02/event-bus-on-android

Adarsh Yadav
  • 3,752
  • 3
  • 24
  • 46
0

You will have to pass the activity and context to other class that is not extending class like

Example

Method(Context context , Activity activity)
{
startActivity( new intent(this , alertDialogClass.class)
}

In the alertDialogClass use the context and activity to show alert dialogbox