Advertisement
Guest User

Untitled

a guest
Jul 2nd, 2016
105
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 15.99 KB | None | 0 0
  1. 01-07 15:14:42.933 2161-4203/com.Oakland E/JSON Parser: Error parsing data org.json.JSONException: Value 2016-01-07 of type java.lang.String cannot be converted to JSONObject
  2. 01-07 15:14:42.938 2161-2161/com.Oakland E/AndroidRuntime: FATAL EXCEPTION: main
  3. Process: com.Oakland, PID: 2161
  4. java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String org.json.JSONObject.getString(java.lang.String)' on a null object reference
  5. at com.Oakland.Register$ProcessRegister.onPostExecute(Register.java:211)
  6. at com.Oakland.Register$ProcessRegister.onPostExecute(Register.java:171)
  7.  
  8. public class Register extends Activity {
  9.  
  10.  
  11. /**
  12. * JSON Response node names.
  13. **/
  14.  
  15.  
  16. private static String KEY_SUCCESS = "success";
  17. private static String KEY_UID = "uid";
  18. private static String KEY_FIRSTNAME = "fname";
  19. private static String KEY_LASTNAME = "lname";
  20. private static String KEY_USERNAME = "uname";
  21. private static String KEY_EMAIL = "email";
  22. private static String KEY_CREATED_AT = "created_at";
  23. private static String KEY_ERROR = "error";
  24.  
  25. /**
  26. * Defining layout items.
  27. **/
  28.  
  29. EditText inputFirstName;
  30. EditText inputLastName;
  31. EditText inputUsername;
  32. EditText inputEmail;
  33. EditText inputPassword;
  34. ImageButton btnRegister;
  35. TextView registerErrorMsg;
  36.  
  37.  
  38. /**
  39. * Called when the activity is first created.
  40. */
  41. @Override
  42. public void onCreate(Bundle savedInstanceState) {
  43. super.onCreate(savedInstanceState);
  44. setContentView(R.layout.register);
  45.  
  46. /**
  47. * Defining all layout items
  48. **/
  49. inputFirstName = (EditText) findViewById(R.id.fname);
  50. inputLastName = (EditText) findViewById(R.id.lname);
  51. inputUsername = (EditText) findViewById(R.id.uname);
  52. inputEmail = (EditText) findViewById(R.id.email);
  53. inputPassword = (EditText) findViewById(R.id.pword);
  54. btnRegister = (ImageButton) findViewById(R.id.Registerbtn);
  55. registerErrorMsg = (TextView) findViewById(R.id.register_error);
  56.  
  57. /**
  58. * Register Button click event.
  59. * A Toast is set to alert when the fields are empty.
  60. * Another toast is set to alert Username must be 5 characters.
  61. **/
  62.  
  63.  
  64.  
  65. btnRegister.setOnClickListener(new View.OnClickListener() {
  66. @Override
  67. public void onClick(View view) {
  68.  
  69. if ( ( !inputUsername.getText().toString().equals("")) && ( !inputPassword.getText().toString().equals("")) && ( !inputFirstName.getText().toString().equals("")) && ( !inputLastName.getText().toString().equals("")) && ( !inputEmail.getText().toString().equals("")) )
  70. {
  71. if ( inputUsername.getText().toString().length() > 4 ){
  72. NetAsync(view);
  73.  
  74. }
  75. else
  76. {
  77. Toast.makeText(getApplicationContext(),
  78. "Username should be minimum 5 characters", Toast.LENGTH_SHORT).show();
  79. }
  80. }
  81. else
  82. {
  83. Toast.makeText(getApplicationContext(),
  84. "One or more fields are empty", Toast.LENGTH_SHORT).show();
  85. }
  86. }
  87. });
  88. }
  89. /**
  90. * Async Task to check whether internet connection is working
  91. **/
  92.  
  93. private class NetCheck extends AsyncTask<String,String,Boolean>
  94. {
  95. private ProgressDialog nDialog;
  96.  
  97. @Override
  98. protected void onPreExecute(){
  99. super.onPreExecute();
  100. nDialog = new ProgressDialog(Register.this);
  101. nDialog.setMessage("Loading..");
  102. nDialog.setTitle("Checking Network");
  103. nDialog.setIndeterminate(false);
  104. nDialog.setCancelable(true);
  105. nDialog.show();
  106. }
  107.  
  108. @Override
  109. protected Boolean doInBackground(String... args){
  110.  
  111.  
  112. /**
  113. * Gets current device state and checks for working internet connection by trying Google.
  114. **/
  115. ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
  116. NetworkInfo netInfo = cm.getActiveNetworkInfo();
  117. if (netInfo != null && netInfo.isConnected()) {
  118. try {
  119. URL url = new URL("http://www.google.com");
  120. HttpURLConnection urlc = (HttpURLConnection) url.openConnection();
  121. urlc.setConnectTimeout(3000);
  122. urlc.connect();
  123. if (urlc.getResponseCode() == 200) {
  124. return true;
  125. }
  126. } catch (MalformedURLException e1) {
  127. // TODO Auto-generated catch block
  128. e1.printStackTrace();
  129. } catch (IOException e) {
  130. // TODO Auto-generated catch block
  131. e.printStackTrace();
  132. }
  133. }
  134. return false;
  135.  
  136. }
  137. @Override
  138. protected void onPostExecute(Boolean th){
  139.  
  140. if(th == true){
  141. nDialog.dismiss();
  142. new ProcessRegister().execute();
  143. }
  144. else{
  145. nDialog.dismiss();
  146. registerErrorMsg.setText("Error in Network Connection");
  147. }
  148. }
  149. }
  150.  
  151.  
  152. private class ProcessRegister extends AsyncTask<String, String, JSONObject> {
  153.  
  154. /**
  155. * Defining Process dialog
  156. **/
  157. private ProgressDialog pDialog;
  158.  
  159. String email,password,fname,lname,uname;
  160. @Override
  161. protected void onPreExecute() {
  162. super.onPreExecute();
  163. inputUsername = (EditText) findViewById(R.id.uname);
  164. inputPassword = (EditText) findViewById(R.id.pword);
  165. fname = inputFirstName.getText().toString();
  166. lname = inputLastName.getText().toString();
  167. email = inputEmail.getText().toString();
  168. uname= inputUsername.getText().toString();
  169. password = inputPassword.getText().toString();
  170. pDialog = new ProgressDialog(Register.this);
  171. pDialog.setTitle("Contacting Servers");
  172. pDialog.setMessage("Registering ...");
  173. pDialog.setIndeterminate(false);
  174. pDialog.setCancelable(true);
  175. pDialog.show();
  176. }
  177.  
  178. @Override
  179. protected JSONObject doInBackground(String... args) {
  180.  
  181.  
  182. UserFunctions userFunction = new UserFunctions();
  183. JSONObject json = userFunction.registerUser(fname, lname, email, uname, password);
  184.  
  185. return json;
  186.  
  187.  
  188. }
  189. @Override
  190. protected void onPostExecute(JSONObject json) {
  191. try {
  192. if (json.getString(KEY_SUCCESS) != null) {
  193.  
  194. registerErrorMsg.setText("");
  195. String res = json.getString(KEY_SUCCESS);
  196.  
  197. String red = json.getString(KEY_ERROR);
  198.  
  199. if(Integer.parseInt(res) == 1){
  200. pDialog.setTitle("Getting Data");
  201. pDialog.setMessage("Loading Info");
  202.  
  203. registerErrorMsg.setText("Successfully Registered");
  204.  
  205.  
  206. DatabaseHandler db = new DatabaseHandler(getApplicationContext());
  207. JSONObject json_user = json.getJSONObject("user");
  208.  
  209. /**
  210. * Removes all the previous data in the SQlite database
  211. **/
  212.  
  213. UserFunctions logout = new UserFunctions();
  214. logout.logoutUser(getApplicationContext());
  215. 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));
  216. /**
  217. * Stores registered data in SQlite Database
  218. * Launch Registered screen
  219. **/
  220.  
  221. Intent registered = new Intent(getApplicationContext(), Registered.class);
  222.  
  223. /**
  224. * Close all views before launching Registered screen
  225. **/
  226. registered.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
  227. pDialog.dismiss();
  228. startActivity(registered);
  229.  
  230.  
  231. finish();
  232. }
  233.  
  234. else if (Integer.parseInt(red) ==2){
  235. pDialog.dismiss();
  236. registerErrorMsg.setText("User already exists");
  237. }
  238. else if (Integer.parseInt(red) ==3){
  239. pDialog.dismiss();
  240. registerErrorMsg.setText("Invalid Email id");
  241. }
  242.  
  243. }
  244.  
  245.  
  246. else{
  247. pDialog.dismiss();
  248.  
  249. registerErrorMsg.setText("Error occurred in registration");
  250. }
  251.  
  252. } catch (JSONException e) {
  253. e.printStackTrace();
  254. }
  255. }}
  256. public void NetAsync(View view){
  257. new NetCheck().execute();
  258. }}
  259.  
  260. //URL of the PHP API
  261.  
  262. private static String registerURL = "http://10.0.2.2/Register_api/";
  263.  
  264. private static String register_tag = "register";
  265.  
  266. /**
  267. * Function to Register
  268. **/
  269. public JSONObject registerUser(String fname, String lname, String email, String uname, String password){
  270. // Building Parameters
  271. List params = new ArrayList();
  272. params.add(new BasicNameValuePair("tag", register_tag));
  273. params.add(new BasicNameValuePair("fname", fname));
  274. params.add(new BasicNameValuePair("lname", lname));
  275. params.add(new BasicNameValuePair("email", email));
  276. params.add(new BasicNameValuePair("uname", uname));
  277. params.add(new BasicNameValuePair("password", password));
  278. JSONObject json = jsonParser.getJSONFromUrl(registerURL,params);
  279. return json;
  280. }
  281.  
  282. public class JSONParser {
  283.  
  284. static InputStream is = null;
  285. static JSONObject jObj = null;
  286. static String json = "";
  287.  
  288. // constructor
  289. public JSONParser() {
  290.  
  291. }
  292.  
  293. public JSONObject getJSONFromUrl(String url, List<NameValuePair> params) {
  294.  
  295. // Making HTTP request
  296. try {
  297. // defaultHttpClient
  298. DefaultHttpClient httpClient = new DefaultHttpClient();
  299. HttpPost httpPost = new HttpPost(url);
  300. httpPost.setEntity(new UrlEncodedFormEntity(params));
  301.  
  302. HttpResponse httpResponse = httpClient.execute(httpPost);
  303. HttpEntity httpEntity = httpResponse.getEntity();
  304. is = httpEntity.getContent();
  305.  
  306. } catch (UnsupportedEncodingException e) {
  307. e.printStackTrace();
  308. } catch (ClientProtocolException e) {
  309. e.printStackTrace();
  310. } catch (IOException e) {
  311. e.printStackTrace();
  312. }
  313.  
  314. try {
  315. BufferedReader reader = new BufferedReader(new InputStreamReader(
  316. is, "iso-8859-1"), 8);
  317. StringBuilder sb = new StringBuilder();
  318. String line = null;
  319. while ((line = reader.readLine()) != null) {
  320. sb.append(line + "n");
  321. }
  322. is.close();
  323. json = sb.toString();
  324. Log.e("JSON", json);
  325. } catch (Exception e) {
  326. Log.e("Buffer Error", "Error converting result " + e.toString());
  327. }
  328.  
  329. // try parse the string to a JSON object
  330. try {
  331. jObj = new JSONObject(json);
  332. } catch (JSONException e) {
  333. Log.e("JSON Parser", "Error parsing data " + e.toString());
  334. }
  335.  
  336. // return JSON String
  337. return jObj;
  338.  
  339. }
  340. }
  341.  
  342. public class DatabaseHandler extends SQLiteOpenHelper {
  343.  
  344. // All Static variables
  345. // Database Version
  346. private static final int DATABASE_VERSION = 1;
  347.  
  348. // Database Name
  349. private static final String DATABASE_NAME = "cloud_contacts";
  350.  
  351. // Login table name
  352. private static final String TABLE_LOGIN = "login";
  353.  
  354. // Login Table Columns names
  355. private static final String KEY_ID = "id";
  356. private static final String KEY_FIRSTNAME = "fname";
  357. private static final String KEY_LASTNAME = "lname";
  358. private static final String KEY_EMAIL = "email";
  359. private static final String KEY_USERNAME = "uname";
  360. private static final String KEY_UID = "uid";
  361. private static final String KEY_CREATED_AT = "created_at";
  362.  
  363. public DatabaseHandler(Context context) {
  364. super(context, DATABASE_NAME, null, DATABASE_VERSION);
  365. }
  366.  
  367. // Creating Tables
  368. @Override
  369. public void onCreate(SQLiteDatabase db) {
  370. String CREATE_LOGIN_TABLE = "CREATE TABLE " + TABLE_LOGIN + "("
  371. + KEY_ID + " INTEGER PRIMARY KEY,"
  372. + KEY_FIRSTNAME + " TEXT,"
  373. + KEY_LASTNAME + " TEXT,"
  374. + KEY_EMAIL + " TEXT UNIQUE,"
  375. + KEY_USERNAME + " TEXT,"
  376. + KEY_UID + " TEXT,"
  377. + KEY_CREATED_AT + " TEXT" + ")";
  378. db.execSQL(CREATE_LOGIN_TABLE);
  379. }
  380.  
  381. // Upgrading database
  382. @Override
  383. public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
  384. // Drop older table if existed
  385. db.execSQL("DROP TABLE IF EXISTS " + TABLE_LOGIN);
  386.  
  387. // Create tables again
  388. onCreate(db);
  389. }
  390.  
  391. /**
  392. * Storing user details in database
  393. * */
  394. public void addUser(String fname, String lname, String email, String uname, String uid, String created_at) {
  395. SQLiteDatabase db = this.getWritableDatabase();
  396.  
  397. ContentValues values = new ContentValues();
  398. values.put(KEY_FIRSTNAME, fname); // FirstName
  399. values.put(KEY_LASTNAME, lname); // LastName
  400. values.put(KEY_EMAIL, email); // Email
  401. values.put(KEY_USERNAME, uname); // UserName
  402. values.put(KEY_UID, uid); // Email
  403. values.put(KEY_CREATED_AT, created_at); // Created At
  404.  
  405. // Inserting Row
  406. db.insert(TABLE_LOGIN, null, values);
  407. db.close(); // Closing database connection
  408. }
  409.  
  410.  
  411. /**
  412. * Getting user data from database
  413. * */
  414. public HashMap<String, String> getUserDetails(){
  415. HashMap<String,String> user = new HashMap<String,String>();
  416. String selectQuery = "SELECT * FROM " + TABLE_LOGIN;
  417.  
  418. SQLiteDatabase db = this.getReadableDatabase();
  419. Cursor cursor = db.rawQuery(selectQuery, null);
  420. // Move to first row
  421. cursor.moveToFirst();
  422. if(cursor.getCount() > 0){
  423. user.put("fname", cursor.getString(1));
  424. user.put("lname", cursor.getString(2));
  425. user.put("email", cursor.getString(3));
  426. user.put("uname", cursor.getString(4));
  427. user.put("uid", cursor.getString(5));
  428. user.put("created_at", cursor.getString(6));
  429. }
  430. cursor.close();
  431. db.close();
  432. // return user
  433. return user;
  434. }
  435.  
  436.  
  437.  
  438.  
  439.  
  440.  
  441. /**
  442. * Getting user login status
  443. * return true if rows are there in table
  444. * */
  445. public int getRowCount() {
  446. String countQuery = "SELECT * FROM " + TABLE_LOGIN;
  447. SQLiteDatabase db = this.getReadableDatabase();
  448. Cursor cursor = db.rawQuery(countQuery, null);
  449. int rowCount = cursor.getCount();
  450. db.close();
  451. cursor.close();
  452.  
  453. // return row count
  454. return rowCount;
  455. }
  456.  
  457.  
  458. /**
  459. * Re crate database
  460. * Delete all tables and create them again
  461. * */
  462. public void resetTables(){
  463. SQLiteDatabase db = this.getWritableDatabase();
  464. // Delete All Rows
  465. db.delete(TABLE_LOGIN, null, null);
  466. db.close();
  467. }
  468.  
  469. Log.e("Buffer Error", "Error converting result " + json);
  470.  
  471. JSONObject jObj = new JSONObject(json);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement