Guest User

Untitled

a guest
Jan 10th, 2019
128
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 13.44 KB | None | 0 0
  1. import java.io.BufferedReader;
  2. import java.io.IOException;
  3. import java.io.InputStream;
  4. import java.io.InputStreamReader;
  5. import java.io.UnsupportedEncodingException;
  6. import java.util.List;
  7.  
  8. import org.apache.http.HttpEntity;
  9. import org.apache.http.HttpResponse;
  10. import org.apache.http.NameValuePair;
  11. import org.apache.http.client.ClientProtocolException;
  12. import org.apache.http.client.entity.UrlEncodedFormEntity;
  13. import org.apache.http.client.methods.HttpGet;
  14. import org.apache.http.client.methods.HttpPost;
  15. import org.apache.http.client.utils.URLEncodedUtils;
  16. import org.apache.http.impl.client.DefaultHttpClient;
  17. import org.json.JSONException;
  18. import org.json.JSONObject;
  19.  
  20. import android.util.Log;
  21.  
  22. public class JSONParser {
  23.  
  24. static InputStream is = null;
  25. static JSONObject jObj = null;
  26. static String json = "";
  27.  
  28. // constructor
  29. public JSONParser() {
  30.  
  31. }
  32.  
  33. public JSONObject getJSONFromUrl(final String url) {
  34.  
  35. // Making HTTP request
  36. try {
  37. // Construct the client and the HTTP request.
  38. DefaultHttpClient httpClient = new DefaultHttpClient();
  39. HttpPost httpPost = new HttpPost(url);
  40.  
  41. // Execute the POST request and store the response locally.
  42. HttpResponse httpResponse = httpClient.execute(httpPost);
  43. // Extract data from the response.
  44. HttpEntity httpEntity = httpResponse.getEntity();
  45. // Open an inputStream with the data content.
  46. is = httpEntity.getContent();
  47.  
  48. } catch (UnsupportedEncodingException e) {
  49. e.printStackTrace();
  50. } catch (ClientProtocolException e) {
  51. e.printStackTrace();
  52. } catch (IOException e) {
  53. e.printStackTrace();
  54. }
  55.  
  56. try {
  57. // Create a BufferedReader to parse through the inputStream.
  58. BufferedReader reader = new BufferedReader(new InputStreamReader(
  59. is, "iso-8859-1"), 8);
  60. // Declare a string builder to help with the parsing.
  61. StringBuilder sb = new StringBuilder();
  62. // Declare a string to store the JSON object data in string form.
  63. String line = null;
  64.  
  65. // Build the string until null.
  66. while ((line = reader.readLine()) != null) {
  67. sb.append(line + "n");
  68. }
  69.  
  70. // Close the input stream.
  71. is.close();
  72. // Convert the string builder data to an actual string.
  73. json = sb.toString();
  74. } catch (Exception e) {
  75. Log.e("Buffer Error", "Error converting result " + e.toString());
  76. }
  77.  
  78. // Try to parse the string to a JSON object
  79. try {
  80. jObj = new JSONObject(json);
  81. } catch (JSONException e) {
  82. Log.e("JSON Parser", "Error parsing data " + e.toString());
  83. }
  84.  
  85. // Return the JSON Object.
  86. return jObj;
  87.  
  88. }
  89.  
  90.  
  91. public JSONObject makeHttpRequest(String url, String method,
  92. List params) {
  93.  
  94. // Haciendo la Petición HTTP
  95. try {
  96.  
  97. // check for request method
  98. if(method == "POST"){
  99. // request method is POST
  100. // defaultHttpClient
  101. DefaultHttpClient httpClient = new DefaultHttpClient();
  102. HttpPost httpPost = new HttpPost(url);
  103. httpPost.setEntity(new UrlEncodedFormEntity(params));
  104.  
  105. HttpResponse httpResponse = httpClient.execute(httpPost);
  106. HttpEntity httpEntity = httpResponse.getEntity();
  107. is = httpEntity.getContent();
  108.  
  109. }else if(method == "GET"){
  110. // request method is GET
  111. DefaultHttpClient httpClient = new DefaultHttpClient();
  112. String paramString = URLEncodedUtils.format(params, "utf-8");
  113. url += "?" + paramString;
  114. HttpGet httpGet = new HttpGet(url);
  115.  
  116. HttpResponse httpResponse = httpClient.execute(httpGet);
  117. HttpEntity httpEntity = httpResponse.getEntity();
  118. is = httpEntity.getContent();
  119. }
  120.  
  121. } catch (UnsupportedEncodingException e) {
  122. e.printStackTrace();
  123. } catch (ClientProtocolException e) {
  124. e.printStackTrace();
  125. } catch (IOException e) {
  126. e.printStackTrace();
  127. }
  128.  
  129. try {
  130. BufferedReader reader = new BufferedReader(new InputStreamReader(
  131. is, "iso-8859-1"), 8);
  132. StringBuilder sb = new StringBuilder();
  133. String line = null;
  134. while ((line = reader.readLine()) != null) {
  135. sb.append(line + "n");
  136. }
  137. is.close();
  138. json = sb.toString();
  139. } catch (Exception e) {
  140. Log.e("Buffer Error", "Error converting result " + e.toString());
  141. }
  142.  
  143. // try parse the string to a JSON object
  144. try {
  145. jObj = new JSONObject(json);
  146. } catch (JSONException e) {
  147. Log.e("JSON Parser", "Error parsing data " + e.toString());
  148. }
  149.  
  150. // return JSON String
  151. return jObj;
  152.  
  153. }
  154. }
  155.  
  156. package com.org.hewerth.happypets;
  157.  
  158. import java.util.ArrayList;
  159. import java.util.List;
  160.  
  161. import org.apache.http.NameValuePair;
  162. import org.apache.http.message.BasicNameValuePair;
  163. import org.json.JSONException;
  164. import org.json.JSONObject;
  165.  
  166. import android.app.Activity;
  167. import android.app.ProgressDialog;
  168. import android.content.Intent;
  169. import android.content.SharedPreferences;
  170. import android.content.SharedPreferences.Editor;
  171. import android.os.AsyncTask;
  172. import android.os.Bundle;
  173. import android.preference.PreferenceManager;
  174. import android.util.Log;
  175. import android.view.View;
  176. import android.view.View.OnClickListener;
  177. import android.widget.Button;
  178. import android.widget.EditText;
  179. import android.widget.Toast;
  180.  
  181. public class LoginActivity extends Activity implements OnClickListener {
  182.  
  183. private EditText user, pass;
  184. private Button mSubmit, mRegister;
  185.  
  186. private ProgressDialog pDialog;
  187.  
  188. // Clase JSONParser
  189. JSONParser jsonParser = new JSONParser();
  190.  
  191.  
  192. // si trabajan de manera local "localhost" :
  193. // En windows tienen que ir, run CMD > ipconfig
  194. // buscar su IP
  195. // y poner de la siguiente manera
  196. // "http://xxx.xxx.x.x:1234/cas/login.php";
  197.  
  198. private static final String LOGIN_URL = "http://login.php";
  199.  
  200. // La respuesta del JSON es
  201. private static final String TAG_SUCCESS = "success";
  202. private static final String TAG_MESSAGE = "message";
  203.  
  204. @Override
  205. protected void onCreate(Bundle savedInstanceState) {
  206. // TODO Auto-generated method stub
  207. super.onCreate(savedInstanceState);
  208. setContentView(R.layout.activity_login);
  209.  
  210. // setup input fields
  211. user = (EditText) findViewById(R.id.usuNick);
  212. pass = (EditText) findViewById(R.id.usuPass);
  213.  
  214. // setup buttons
  215. mSubmit = (Button) findViewById(R.id.login);
  216. mRegister = (Button) findViewById(R.id.register);
  217.  
  218. // register listeners
  219. mSubmit.setOnClickListener(this);
  220. mRegister.setOnClickListener(this);
  221.  
  222. }
  223.  
  224. @Override
  225. public void onClick(View v) {
  226. // TODO Auto-generated method stub
  227. switch (v.getId()) {
  228. case R.id.login:
  229. new AttemptLogin().execute();
  230. break;
  231. case R.id.register:
  232. Intent i = new Intent(this, RegistroActivity.class);
  233. startActivity(i);
  234. break;
  235.  
  236. default:
  237. break;
  238. }
  239. }
  240.  
  241. class AttemptLogin extends AsyncTask<String, String, String> {
  242.  
  243. @Override
  244. protected void onPreExecute() {
  245. super.onPreExecute();
  246. pDialog = new ProgressDialog(LoginActivity.this);
  247. pDialog.setMessage("Attempting login...");
  248. pDialog.setIndeterminate(false);
  249. pDialog.setCancelable(true);
  250. pDialog.show();
  251. }
  252.  
  253. String username = user.getText().toString();
  254. String password = pass.getText().toString();
  255.  
  256. @Override
  257. protected String doInBackground(String... args) {
  258. int success;
  259.  
  260. try {
  261. // Building Parameters
  262. List params = new ArrayList();
  263. params.add(new BasicNameValuePair("alias", username));
  264. params.add(new BasicNameValuePair("password", password));
  265.  
  266. Log.d("request!", "starting");
  267. // getting product details by making HTTP request
  268. JSONObject json = jsonParser.makeHttpRequest(LOGIN_URL, "POST",
  269. params);
  270.  
  271. // check your log for json response
  272. Log.d("Login attempt", json.toString());
  273.  
  274. // json success tag
  275. success = json.getInt(TAG_SUCCESS);
  276. if (success == 1) {
  277. Log.d("Login Successful!", json.toString());
  278. // save user data
  279. SharedPreferences sp = PreferenceManager
  280. .getDefaultSharedPreferences(LoginActivity.this);
  281. Editor edit = sp.edit();
  282. edit.putString("username", username);
  283. edit.commit();
  284.  
  285. Intent i = new Intent(LoginActivity.this, ReadComments.class);
  286. finish();
  287. startActivity(i);
  288. return json.getString(TAG_MESSAGE);
  289. } else {
  290. Log.d("Login Failure!", json.getString(TAG_MESSAGE));
  291. return json.getString(TAG_MESSAGE);
  292. }
  293. } catch (JSONException e) {
  294. e.printStackTrace();
  295. }
  296.  
  297. return null;
  298.  
  299. }
  300.  
  301. protected void onPostExecute(String file_url) {
  302. // dismiss the dialog once product deleted
  303. pDialog.dismiss();
  304. if (file_url != null) {
  305. Toast.makeText(LoginActivity.this, file_url, Toast.LENGTH_LONG).show();
  306. }
  307. }
  308. }
  309. }
  310.  
  311. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  312. android:layout_width="fill_parent"
  313. android:layout_height="fill_parent"
  314. xmlns:tools="http://schemas.android.com/tools"
  315. android:background="@drawable/fondo"
  316. android:orientation="vertical"
  317. android:padding="20dip"
  318. android:weightSum="1">
  319.  
  320. <TextView
  321. android:id="@+id/link_to_register"
  322. android:layout_width="fill_parent"
  323. android:layout_height="wrap_content"
  324. android:layout_marginBottom="40dip"
  325. android:layout_marginTop="40dip"
  326. android:fontFamily="cursive"
  327. android:gravity="center"
  328. android:text="HappyPets"
  329. android:textColor="@android:color/black"
  330. android:textSize="60sp" />
  331.  
  332. <EditText
  333. android:id="@+id/usuNick"
  334. android:layout_width="fill_parent"
  335. android:layout_height="wrap_content"
  336. android:hint="Nombre de Usuario"
  337. android:name="username_textview"
  338. android:inputType="text"
  339. android:textAlignment="center" />
  340.  
  341. <EditText
  342. android:id="@+id/usuPass"
  343. android:layout_width="fill_parent"
  344. android:layout_height="wrap_content"
  345. android:layout_marginBottom="30dip"
  346. android:layout_marginTop="15dip"
  347. android:hint="Contraseña"
  348. android:name="password_textview"
  349. android:inputType="textPassword"
  350. android:textAlignment="center" />
  351.  
  352.  
  353. <Button
  354. android:id="@+id/login"
  355. android:layout_width="wrap_content"
  356. android:layout_height="wrap_content"
  357. android:layout_gravity="center_horizontal"
  358. android:backgroundTint="@color/colorPrimary"
  359. android:elevation="0dp"
  360. android:paddingLeft="15dip"
  361. android:paddingRight="15dip"
  362. android:text="Ingresar"
  363. android:name="submit"
  364. android:textColor="@android:color/background_light" />
  365.  
  366. <Button
  367. android:id="@+id/register"
  368. android:layout_width="wrap_content"
  369. android:layout_height="wrap_content"
  370. android:layout_gravity="center_horizontal"
  371. android:backgroundTint="@color/colorPrimary"
  372. android:elevation="0dp"
  373. android:paddingLeft="15dip"
  374. android:paddingRight="15dip"
  375. android:text="Registrate"
  376. android:textAlignment="center"
  377. android:textColor="@android:color/background_light" />
  378.  
  379. </LinearLayout>
  380.  
  381. <ProgressBar
  382. android:id="@+id/progbar"
  383. android:layout_width="wrap_content"
  384. android:layout_height="wrap_content"
  385. style="@android:style/Widget.ProgressBar.Small"
  386. android:layout_marginRight="5dp" />
  387.  
  388. int mStatus;
  389. //...
  390. ProgressBar mProgress = (ProgressBar) findViewById(R.id.progbar);
  391. mProgress.setProgress(mStatus); // actualizar status
  392. // o relativamente
  393. mProgress.incrementProgressBy(1);
  394.  
  395. @Override
  396. protected void onPause() {
  397. if(pDialog != null){
  398. pDialog.dismiss();
  399. }
  400. super.onPause();
  401. }
  402.  
  403. private static boolean foreground = true; //valida si se permite mostrar el Dialog.
  404.  
  405.  
  406. @Override
  407. protected void onPause() {
  408. foreground = false;
  409. super.onPause();
  410. }
  411.  
  412. @Override
  413. protected void onResume() {
  414. foreground = true;
  415. super.onResume();
  416. }
  417.  
  418. @Override
  419. protected void onPreExecute() {
  420. super.onPreExecute();
  421. if (foreground){ //Valida si será mostrado el Dialogo.
  422.  
  423. pDialog = new ProgressDialog(LoginActivity.this);
  424. pDialog.setMessage("Attempting login...");
  425. pDialog.setIndeterminate(false);
  426. pDialog.setCancelable(true);
  427. pDialog.show();
  428.  
  429. }
  430. }
Add Comment
Please, Sign In to add comment