0

I am working on a app for login and registration. It should get a JSON response from webservice to read or write the Database. But when I try to register. It gives me following message:

03-14 06:06:17.718 1061-1082/com.learn2crack E/JSON﹕
{"tag":"register","success":0,"error":1,"error_msg":"JSON > Error occured in >Registartion"} 03-14 06:06:26.888 1061-1061/com.learn2crack I/Choreographer﹕ Skipped 364 frames! The application may be doing too much work on its main thread. 03-14 06:06:26.928 1061-1061/com.learn2crack I/Choreographer﹕ Skipped 365 frames! The application may be doing too much work on its main thread.

Main.java:

public class Main extends Activity {

Button btnLogout;
Button changepas;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    changepas = (Button) findViewById(R.id.btchangepass);
    btnLogout = (Button) findViewById(R.id.logout);

    DatabaseHandler db = new DatabaseHandler(getApplicationContext());


     HashMap<String,String> user = new HashMap<String, String>();
     user = db.getUserDetails();



    changepas.setOnClickListener(new View.OnClickListener(){
        public void onClick(View arg0){

            Intent chgpass = new Intent(getApplicationContext(),   
 ChangePassword.class);

            startActivity(chgpass);
        }

    });


    btnLogout.setOnClickListener(new View.OnClickListener() {

        public void onClick(View arg0) {

            UserFunctions logout = new UserFunctions();
            logout.logoutUser(getApplicationContext());
            Intent login = new Intent(getApplicationContext(), Login.class);
            login.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            startActivity(login);
            finish();
        }
    });

    final TextView login = (TextView) findViewById(R.id.textwelcome);
    login.setText("Welcome  "+user.get("fname"));
    final TextView lname = (TextView) findViewById(R.id.lname);
    lname.setText(user.get("lname"));


}}

Register.java:

public class Register extends Activity {

private static String KEY_SUCCESS = "success";
private static String KEY_UID = "uid";
private static String KEY_FIRSTNAME = "fname";
private static String KEY_LASTNAME = "lname";
private static String KEY_USERNAME = "uname";
private static String KEY_EMAIL = "email";
private static String KEY_CREATED_AT = "created_at";
private static String KEY_ERROR = "error";


EditText inputFirstName;
EditText inputLastName;
EditText inputUsername;
EditText inputEmail;
EditText inputPassword;
Button btnRegister;
TextView registerErrorMsg;


@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
   setContentView(R.layout.register);


    inputFirstName = (EditText) findViewById(R.id.fname);
    inputLastName = (EditText) findViewById(R.id.lname);
    inputUsername = (EditText) findViewById(R.id.uname);
    inputEmail = (EditText) findViewById(R.id.email);
    inputPassword = (EditText) findViewById(R.id.pword);
    btnRegister = (Button) findViewById(R.id.register);
    registerErrorMsg = (TextView) findViewById(R.id.register_error);

Button login = (Button) findViewById(R.id.bktologin);
    login.setOnClickListener(new View.OnClickListener() {
        public void onClick(View view) {
            Intent myIntent = new Intent(view.getContext(), Login.class);
            startActivityForResult(myIntent, 0);
            finish();
        }

    });



    btnRegister.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            if (  ( !inputUsername.getText().toString().equals("")) && ( !inputPassword.getText().toString().equals("")) && ( !inputFirstName.getText().toString().equals("")) && ( !inputLastName.getText().toString().equals("")) && ( !inputEmail.getText().toString().equals("")) )
            {
                if ( inputUsername.getText().toString().length() > 4 ){
                NetAsync(view);

                }
                else
                {
                    Toast.makeText(getApplicationContext(),
                            "Username should be minimum 5 characters", Toast.LENGTH_SHORT).show();
                }
            }
            else
            {
                Toast.makeText(getApplicationContext(),
                        "One or more fields are empty", Toast.LENGTH_SHORT).show();
            }
        }
    });
   }


private class NetCheck extends AsyncTask<String,String,Boolean>
{
    private ProgressDialog nDialog;

    @Override
    protected void onPreExecute(){
        super.onPreExecute();
        nDialog = new ProgressDialog(Register.this);
        nDialog.setMessage("Loading..");
        nDialog.setTitle("Checking Network");
        nDialog.setIndeterminate(false);
        nDialog.setCancelable(true);
        nDialog.show();
    }

    @Override
    protected Boolean doInBackground(String... args){


        ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo netInfo = cm.getActiveNetworkInfo();
        if (netInfo != null && netInfo.isConnected()) {
            try {
                URL url = new URL("http://www.google.com");
                HttpURLConnection urlc = (HttpURLConnection) url.openConnection();
                urlc.setConnectTimeout(3000);
                urlc.connect();
                if (urlc.getResponseCode() == 200) {
                    return true;
                }
            } catch (MalformedURLException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        return false;

    }
    @Override
    protected void onPostExecute(Boolean th){

        if(th){
            nDialog.dismiss();
            new ProcessRegister().execute();
        }
        else{
            nDialog.dismiss();
            registerErrorMsg.setText("Error in Network Connection");
        }
    }
}





private class ProcessRegister extends AsyncTask<String, String, JSONObject> {


    private ProgressDialog pDialog;

    String email,password,fname,lname,uname;
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        inputUsername = (EditText) findViewById(R.id.uname);
        inputPassword = (EditText) findViewById(R.id.pword);
           fname = inputFirstName.getText().toString();
           lname = inputLastName.getText().toString();
            email = inputEmail.getText().toString();
            uname= inputUsername.getText().toString();
            password = inputPassword.getText().toString();
        pDialog = new ProgressDialog(Register.this);
        pDialog.setTitle("Contacting Servers");
        pDialog.setMessage("Registering ...");
        pDialog.setIndeterminate(false);
        pDialog.setCancelable(true);
        pDialog.show();
    }

    @Override
    protected JSONObject doInBackground(String... args) {


    UserFunctions userFunction = new UserFunctions();
    return userFunction.registerUser(fname, lname, email, uname, password);




    }
   @Override
    protected void onPostExecute(JSONObject json) {

            try {
                if(json != null && !json.isNull(KEY_SUCCESS)) {
                    String value = json.getString(KEY_SUCCESS);
                    if(value != null && value.length()>0){
                    if (json != null && json.getString(KEY_SUCCESS) != null) {
                        registerErrorMsg.setText("");
                        String res = json.getString(KEY_SUCCESS);

                        String red = json.getString(KEY_ERROR);

                        if (Integer.parseInt(res) == 1) {
                            pDialog.setTitle("Getting Data");
                            pDialog.setMessage("Loading Info");

                            registerErrorMsg.setText("Successfully Registered");


                            DatabaseHandler db = new DatabaseHandler(getApplicationContext());
                            JSONObject json_user = json.getJSONObject("user");


                            UserFunctions logout = new UserFunctions();
                            logout.logoutUser(getApplicationContext());
                            db.addUser(json_user.getString(KEY_FIRSTNAME), json_user.getString(KEY_LASTNAME), json_user.getString(KEY_EMAIL), json_user.getString(KEY_USERNAME), json_user.getString(KEY_UID), json_user.getString(KEY_CREATED_AT));


                            Intent registered = new Intent(getApplicationContext(), Registered.class);

                            registered.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                            pDialog.dismiss();
                            startActivity(registered);


                            finish();
                        } else if (Integer.parseInt(red) == 2) {
                            pDialog.dismiss();
                            registerErrorMsg.setText("User already exists");
                        } else if (Integer.parseInt(red) == 3) {
                            pDialog.dismiss();
                            registerErrorMsg.setText("Invalid Email id");
                        }
                    }
                    } else {
                        pDialog.dismiss();

                        registerErrorMsg.setText("Error occured in registration");
                    }
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
}
    public void NetAsync(View view){
        new NetCheck().execute();
    }}

Registered.java:

public class Registered extends Activity {


@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.registered);


    DatabaseHandler db = new DatabaseHandler(getApplicationContext());

    HashMap<String,String> user = new HashMap<String, String>();
    user = db.getUserDetails();


    final TextView fname = (TextView)findViewById(R.id.fname);
    final TextView lname = (TextView)findViewById(R.id.lname);
    final TextView uname = (TextView)findViewById(R.id.uname);
    final TextView email = (TextView)findViewById(R.id.email);
    final TextView created_at = (TextView)findViewById(R.id.regat);
    fname.setText(user.get("fname"));
    lname.setText(user.get("lname"));
    uname.setText(user.get("uname"));
    email.setText(user.get("email"));
    created_at.setText(user.get("created_at"));






    Button login = (Button) findViewById(R.id.login);
    login.setOnClickListener(new View.OnClickListener() {
        public void onClick(View view) {
            Intent myIntent = new Intent(view.getContext(), Login.class);
            startActivityForResult(myIntent, 0);
            finish();
        }

    });


}}

DatabaseHandle.java:

public DatabaseHandler(Context context) {
    super(context, DATABASE_NAME, null, DATABASE_VERSION);
}

// Creating Tables
@Override
public void onCreate(SQLiteDatabase db) {
    String CREATE_LOGIN_TABLE = "CREATE TABLE " + TABLE_LOGIN + "("
            + KEY_ID + " INTEGER PRIMARY KEY,"
            + KEY_FIRSTNAME + " TEXT,"
            + KEY_LASTNAME + " TEXT,"
            + KEY_EMAIL + " TEXT UNIQUE,"
            + KEY_USERNAME + " TEXT,"
            + KEY_UID + " TEXT,"
            + KEY_CREATED_AT + " TEXT" + ")";
    db.execSQL(CREATE_LOGIN_TABLE);
}

// Upgrading database
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    // Drop older table if existed
    db.execSQL("DROP TABLE IF EXISTS " + TABLE_LOGIN);

    // Create tables again
    onCreate(db);
}


public void addUser(String fname, String lname, String email, String uname,
String uid, String created_at) {
    SQLiteDatabase db = this.getWritableDatabase();

    ContentValues values = new ContentValues();
    values.put(KEY_FIRSTNAME, fname); // FirstName
    values.put(KEY_LASTNAME, lname); // LastName
    values.put(KEY_EMAIL, email); // Email
    values.put(KEY_USERNAME, uname); // UserName
    values.put(KEY_UID, uid); // Email
    values.put(KEY_CREATED_AT, created_at); // Created At

    // Inserting Row
    db.insert(TABLE_LOGIN, null, values);
    db.close(); // Closing database connection
}


public HashMap<String, String> getUserDetails(){
    HashMap<String,String> user = new HashMap<String,String>();
    String selectQuery = "SELECT  * FROM " + TABLE_LOGIN;

    SQLiteDatabase db = this.getReadableDatabase();
    Cursor cursor = db.rawQuery(selectQuery, null);
    // Move to first row
    cursor.moveToFirst();
    if(cursor.getCount() > 0){
        user.put("fname", cursor.getString(1));
        user.put("lname", cursor.getString(2));
        user.put("email", cursor.getString(3));
        user.put("uname", cursor.getString(4));
        user.put("uid", cursor.getString(5));
        user.put("created_at", cursor.getString(6));
    }
    cursor.close();
    db.close();
    // return user
    return user;
}


public int getRowCount() {
    String countQuery = "SELECT  * FROM " + TABLE_LOGIN;
    SQLiteDatabase db = this.getReadableDatabase();
    Cursor cursor = db.rawQuery(countQuery, null);
    int rowCount = cursor.getCount();
    db.close();
    cursor.close();

    // return row count
    return rowCount;
}


    public void resetTables(){
    SQLiteDatabase db = this.getWritableDatabase();
    // Delete All Rows
    db.delete(TABLE_LOGIN, null, null);
    db.close();
}

}

JSONParser.java:

public class JSONParser {

static InputStream is = null;
static JSONObject jObj = null;
static String json = "";

// constructor
public JSONParser() {

}

public JSONObject getJSONFromUrl(String url, List<NameValuePair> params) {

    // Making HTTP request
    try {
        // defaultHttpClient
        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpPost httpPost = new HttpPost(url);
        httpPost.setEntity(new UrlEncodedFormEntity(params));

        HttpResponse httpResponse = httpClient.execute(httpPost);
        HttpEntity httpEntity = httpResponse.getEntity();
        is = httpEntity.getContent();

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

    try {
        BufferedReader reader = new BufferedReader(new InputStreamReader(
                is, "iso-8859-1"), 8);
        StringBuilder sb = new StringBuilder();
        String line;
        while ((line = reader.readLine()) != null) {
            if(!line.startsWith("<", 0)){
                if(!line.startsWith("(", 0)){
                    sb.append(line + "\n");
                }
            }
        }
        is.close();
        json = sb.toString();
        Log.e("JSON", json);
    } catch (Exception e) {
        Log.e("Buffer Error", "Error converting result " + e.toString());
    }

    // try parse the string to a JSON object
    try {
        jObj = new JSONObject(json);
    } catch (JSONException e) {
        Log.e("JSON Parser", "Error parsing data " + e.toString());
    }

    // return JSON String
    return jObj;

}
}

UserFunction.java:

public class UserFunctions {

private JSONParser jsonParser;

//URL of the PHP API
private static String loginURL = "http://10.0.2.2/learn2crack_login_api/";
private static String registerURL = "http://10.0.2.2/learn2crack_login_api/";
private static String forpassURL = "http://10.0.2.2/learn2crack_login_api/";
private static String chgpassURL = "http://10.0.2.2/learn2crack_login_api/";


private static String login_tag = "login";
private static String register_tag = "register";
private static String forpass_tag = "forpass";
private static String chgpass_tag = "chgpass";


// constructor
public UserFunctions(){
    jsonParser = new JSONParser();
}


public JSONObject loginUser(String email, String password){
    // Building Parameters
    List<NameValuePair> params = new ArrayList<NameValuePair>();
    params.add(new BasicNameValuePair("tag", login_tag));
    params.add(new BasicNameValuePair("email", email));
    params.add(new BasicNameValuePair("password", password));
    return jsonParser.getJSONFromUrl(loginURL, params);
    //return json;
}


public JSONObject chgPass(String newpas, String email){
    List<NameValuePair> params = new ArrayList<NameValuePair>();
    params.add(new BasicNameValuePair("tag", chgpass_tag));

    params.add(new BasicNameValuePair("newpas", newpas));
    params.add(new BasicNameValuePair("email", email));
   return  jsonParser.getJSONFromUrl(chgpassURL, params);

}


public JSONObject forPass(String forgotpassword){
    List<NameValuePair> params = new ArrayList<NameValuePair>();
    params.add(new BasicNameValuePair("tag", forpass_tag));
    params.add(new BasicNameValuePair("forgotpassword", forgotpassword));
    return jsonParser.getJSONFromUrl(forpassURL, params);
    }

   public JSONObject registerUser(String fname, String lname, String email, String uname, String password){
    // Building Parameters
    List<NameValuePair> params = new ArrayList<NameValuePair>();
    params.add(new BasicNameValuePair("tag", register_tag));
    params.add(new BasicNameValuePair("fname", fname));
    params.add(new BasicNameValuePair("lname", lname));
    params.add(new BasicNameValuePair("email", email));
    params.add(new BasicNameValuePair("uname", uname));
    params.add(new BasicNameValuePair("password", password));
    return jsonParser.getJSONFromUrl(registerURL,params);

}

public boolean logoutUser(Context context){
    DatabaseHandler db = new DatabaseHandler(context);
    db.resetTables();
    return true;
}

}

What's wrong in my code? Thank you!

TYM
  • 85
  • 1
  • 2
  • 5
  • Seems like you only do the network work in a background thread. You are doing the database and the json parsing on the main thread. You should move this to background threads as well! – Patrick Dorn Mar 14 '15 at 08:15
  • Which specific function should be put on the background thread? I am a very new beginner. Thank you – TYM Mar 14 '15 at 10:04

1 Answers1

0

The stacktrace doesn't help much on this case. It just helps indicating that you do some time-consuming job in main thread and you should move it to background thread.

From what that I can see, I think that the part that you should move to background thread is the DatabaseHelper one. Since to read/write database is a time-consuming job.

Hope this helps.

nuuneoi
  • 1,788
  • 1
  • 17
  • 14
  • I am not familiar to put the things in background. Can you show me the functions that i should modify? – TYM Mar 14 '15 at 10:10