Username to Appear on Screen based on details entered - java

I'm using the same topic as before just changed the title that way the codes already here. I've got my login screen working as I wanted it; turned out to be a stupid typo. Now what I need help with is displaying the currently logged in users username on the homescreen (after login)
I added this to my Login.java file to try and store the information:
if (success == 1) {
Log.d("Login Successful!", json.toString());
//Save Logged in User
SharedPreferences sp = PreferenceManager
.getDefaultSharedPreferences(Login.this);
Editor edit = sp.edit();
edit.putString("username", username);
edit.commit();
I just don't know how to re-call a value from the Shared Preferences from a different classfile... I want the current username to display on Home.java but I've called the shared preferences on Login.java, any help appreciated. I've posted the Login and Home files (P.S. My home layout file has a text view named storedUser if that helps.
Login.java
package com.example.accumuwinner;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class Login extends Activity implements OnClickListener{
private EditText user, pass;
private Button mSubmit, mRegister;
// Progress Dialog
private ProgressDialog pDialog;
// JSON parser class
JSONParser jsonParser = new JSONParser();
//php login script location:
//localhost :
//testing on your device
//put your local ip instead, on windows, run CMD > ipconfig
//or in mac's terminal type ifconfig and look for the ip under en0 or en1
// private static final String LOGIN_URL = "http://xxx.xxx.x.x:1234/webservice/login.php";
//testing on Emulator:
private static final String LOGIN_URL = "http://192.168.0.7:8080/webservice/login.php";
//testing from a real server:
//private static final String LOGIN_URL = "http://www.yourdomain.com/webservice/login.php";
//JSON element ids from repsonse of php script:
private static final String TAG_SUCCESS = "success";
private static final String TAG_MESSAGE = "message";
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.login);
//setup input fields
user = (EditText)findViewById(R.id.username);
pass = (EditText)findViewById(R.id.password);
//setup buttons
mSubmit = (Button)findViewById(R.id.login);
mRegister = (Button)findViewById(R.id.register);
//register listeners
mSubmit.setOnClickListener(this);
mRegister.setOnClickListener(this);
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.login:
new AttemptLogin().execute();
break;
case R.id.register:
Intent i = new Intent(this, Register.class);
startActivity(i);
break;
default:
break;
}
}
class AttemptLogin extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
boolean failure = false;
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(Login.this);
pDialog.setMessage("Attempting login...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected String doInBackground(String... args) {
// TODO Auto-generated method stub
// Check for success tag
int success;
String username = user.getText().toString();
String password = pass.getText().toString();
try {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("username", username));
params.add(new BasicNameValuePair("password", password));
Log.d("request!", "starting");
// getting product details by making HTTP request
JSONObject json = jsonParser.makeHttpRequest(
LOGIN_URL, "POST", params);
// check your log for json response
Log.d("Login attempt", json.toString());
// json success tag
success = json.getInt(TAG_SUCCESS);
if (success == 1) {
Log.d("Login Successful!", json.toString());
Intent i = new Intent(Login.this, Home.class);
finish();
startActivity(i);
return json.getString(TAG_MESSAGE);
}else{
Log.d("Login Failure!", json.getString(TAG_MESSAGE));
return json.getString(TAG_MESSAGE);
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
// dismiss the dialog once product deleted
pDialog.dismiss();
if (file_url != null){
Toast.makeText(Login.this, file_url, Toast.LENGTH_LONG).show();
}
}
}
}
Home.java
package com.example.accumuwinnerbettingtips;
import android.app.Activity;
import android.os.Bundle;
public class Home extends Activity{
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.home);
}
}

Related

error-parsing-data-org-json-jsonexception-value-brtable-of-type-java-lang-string cannot convert to json object?

I am developing a simple application inserting user input date and time into databse, when I click the "set" button I am getting the following error
String is not converted to jsonobject.
Following is my code, please help me out.
package com.example.androidhive;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class NewProductActivity extends Activity {
// Progress Dialog
private ProgressDialog pDialog;
JSONParser jsonParser = new JSONParser();
EditText inputName;
EditText inputPrice;
EditText inputDesc;
// url to create new product
private static String url_create_product = "http://vygyguyaay/android/create_product.php";
// JSON Node names
private static final String TAG_SUCCESS = "success";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.add_product);
// Edit Text
inputName = (EditText) findViewById(R.id.inputName);
inputPrice = (EditText) findViewById(R.id.inputPrice);
inputDesc = (EditText) findViewById(R.id.inputDesc);
// Create button
Button btnCreateProduct = (Button) findViewById(R.id.btnCreateProduct);
// button click event
btnCreateProduct.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// creating new product in background thread
new CreateNewProduct().execute();
}
});
}
/**
* Background Async Task to Create new product
* */
class CreateNewProduct extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(NewProductActivity.this);
pDialog.setMessage("Creating Product..");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
/**
* Creating product
* */
protected String doInBackground(String... args) {
String name = inputName.getText().toString();
String price = inputPrice.getText().toString();
String description = inputDesc.getText().toString();
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("name", name));
params.add(new BasicNameValuePair("price", price));
params.add(new BasicNameValuePair("description", description));
// getting JSON Object
// Note that create product url accepts POST method
JSONObject json = jsonParser.makeHttpRequest(url_create_product,
"POST", params);
// check log cat fro response
Log.d("Create Response", json.toString());
// check for success tag
try {
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// successfully created product
Intent i = new Intent(getApplicationContext(), AllProductsActivity.class);
startActivity(i);
// closing this screen
finish();
} else {
// failed to create product
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
// dismiss the dialog once done
pDialog.dismiss();
}
}
}
Activity has leaked window: Your Activity still have to handle a Dialog in most cases.
You call finish(); before you dismiss pDialog
if (success == 1) {
// successfully created product
Intent i = new Intent(getApplicationContext(), AllProductsActivity.class);
startActivity(i);
// closing this screen
pDialog.dismiss(); // <------- add this line
finish();
}

Android Studio connecting to a URL

My problem is that I made a "web" with php to register, login and logout. What I really want to do is connect the web to my app in android studio, it worked before I put the page welcome in the website, but when I try to apply the changes, the app fails when I login.
The website:
http://saveds.esy.es/cas/login.php
The Android Studio code in java by directories:
JSONParser.java
package com.example.javi.myapplication2;
import android.util.Log;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
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.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.List;
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
public JSONObject getJSONFromUrl(final String url) {
// Making HTTP request
try {
// Construct the client and the HTTP request.
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
// Execute the POST request and store the response locally.
HttpResponse httpResponse = httpClient.execute(httpPost);
// Extract data from the response.
HttpEntity httpEntity = httpResponse.getEntity();
// Open an inputStream with the data content.
is = httpEntity.getContent();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
// Create a BufferedReader to parse through the inputStream.
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
// Declare a string builder to help with the parsing.
StringBuilder sb = new StringBuilder();
// Declare a string to store the JSON object data in string form.
String line = null;
Login.java
package com.example.javi.myapplication2;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.AsyncTask;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.Toast;
public class Login extends Activity implements OnClickListener {
private EditText user, pass;
private Button mSubmit, mRegister;
private CheckBox check;
private ProgressDialog pDialog;
// Clase JSONParser
JSONParser jsonParser = new JSONParser();
// si trabajan de manera local "localhost" :
// En windows tienen que ir, run CMD > ipconfig
// buscar su IP
// y poner de la siguiente manera
// "http://xxx.xxx.x.x:1234/cas/login.php";
private static final String LOGIN_URL = "http://saveds.esy.es/cas/login.php";
// La respuesta del JSON es
private static final String TAG_SUCCESS = "success";
private static final String TAG_MESSAGE = "message";
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.login);
// setup input fields
user = (EditText) findViewById(R.id.username);
pass = (EditText) findViewById(R.id.password);
check = (CheckBox) findViewById(R.id.rememberme);
// setup buttons
mSubmit = (Button) findViewById(R.id.login);
mRegister = (Button) findViewById(R.id.register);
// register listeners
mSubmit.setOnClickListener(this);
mRegister.setOnClickListener(this);
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.login:
new AttemptLogin().execute();
break;
case R.id.register:
Intent i = new Intent(this, Register.class);
startActivity(i);
break;
default:
break;
}
}
class AttemptLogin extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(Login.this);
pDialog.setMessage("Attempting login...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected String doInBackground(String... args) {
int success;
String username = user.getText().toString();
String password = pass.getText().toString();
String rememberme = check.getText().toString();
try {
// Building Parameters
List params = new ArrayList();
params.add(new BasicNameValuePair("username", username));
params.add(new BasicNameValuePair("password", password));
params.add(new BasicNameValuePair("rememberme", rememberme));
Log.d("request!", "starting");
// getting product details by making HTTP request
JSONObject json = jsonParser.makeHttpRequest(LOGIN_URL, "POST",
params);
// check your log for json response
Log.d("Login attempt", json.toString());
// json success tag
success = json.getInt(TAG_SUCCESS);
if (success == 1) {
Log.d("Login Successful!", json.toString());
// save user data
SharedPreferences sp = PreferenceManager
.getDefaultSharedPreferences(Login.this);
Editor edit = sp.edit();
edit.putString("username", username);
edit.commit();
Intent i = new Intent(Login.this, ReadComments.class);
finish();
startActivity(i);
return json.getString(TAG_MESSAGE);
} else {
Log.d("Login Failure!", json.getString(TAG_MESSAGE));
return json.getString(TAG_MESSAGE);
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(String file_url) {
// dismiss the dialog once product deleted
pDialog.dismiss();
if (file_url != null) {
Toast.makeText(Login.this, file_url, Toast.LENGTH_LONG).show();
}
}
}
}
ReadComments.java
package com.example.javi.myapplication2;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class ReadComments extends Activity implements OnClickListener{
private Button logout;
// Progress Dialog
private ProgressDialog pDialog;
// JSON parser class
JSONParser jsonParser = new JSONParser();
//si lo trabajan de manera local en xxx.xxx.x.x va su ip local
// private static final String REGISTER_URL = "http://xxx.xxx.x.x:1234/cas/register.php";
//testing on Emulator:
private static final String WELCOME_URL = "http://saveds.esy.es/cas/welcome.php";
//ids
private static final String TAG_SUCCESS = "success";
private static final String TAG_MESSAGE = "message";
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.read_comments);
logout=(Button)findViewById(R.id.logout);
logout.setOnClickListener(this);
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
new Logoutclass().execute();
}
class Logoutclass extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(ReadComments.this);
pDialog.setMessage("Cerrando sesión...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected String doInBackground(String... args) {
// TODO Auto-generated method stub
// Check for success tag
int success;
String out=logout.getText().toString();
try {
// Building Parameters
List params = new ArrayList();
params.add(new BasicNameValuePair("username", out));
Log.d("request!", "starting");
//Posting user data to script
JSONObject json = jsonParser.makeHttpRequest(
WELCOME_URL, "POST", params);
// full json response
Log.d("Cerrando sesión", json.toString());
// json success element
success = json.getInt(TAG_SUCCESS);
if (success == 1) {
Log.d("Sesión cerrada", json.toString());
finish();
return json.getString(TAG_MESSAGE);
}else{
Log.d("Fallo de cerrar sesión", json.getString(TAG_MESSAGE));
return json.getString(TAG_MESSAGE);
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(String file_url) {
// dismiss the dialog once product deleted
pDialog.dismiss();
if (file_url != null){
Toast.makeText(ReadComments.this, file_url, Toast.LENGTH_LONG).show();
}
}
}
}
register.java
package com.example.javi.myapplication2;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class Register extends Activity implements OnClickListener{
private EditText user, pass, nam, mail ;
private Button mRegister;
// Progress Dialog
private ProgressDialog pDialog;
// JSON parser class
JSONParser jsonParser = new JSONParser();
//si lo trabajan de manera local en xxx.xxx.x.x va su ip local
// private static final String REGISTER_URL = "http://xxx.xxx.x.x:1234/cas/register.php";
//testing on Emulator:
private static final String REGISTER_URL = "http://saveds.esy.es/cas/register.php";
//ids
private static final String TAG_SUCCESS = "success";
private static final String TAG_MESSAGE = "message";
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.register);
user = (EditText)findViewById(R.id.username);
pass = (EditText)findViewById(R.id.password);
nam = (EditText)findViewById(R.id.name);
mail = (EditText)findViewById(R.id.email);
mRegister = (Button)findViewById(R.id.register);
mRegister.setOnClickListener(this);
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
new CreateUser().execute();
}
class CreateUser extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(Register.this);
pDialog.setMessage("Creating User...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected String doInBackground(String... args) {
// TODO Auto-generated method stub
// Check for success tag
int success;
String email=mail.getText().toString();
String name = nam.getText().toString();
String username = user.getText().toString();
String password = pass.getText().toString();
try {
// Building Parameters
List params = new ArrayList();
params.add(new BasicNameValuePair("username", username));
params.add(new BasicNameValuePair("password", password));
params.add(new BasicNameValuePair("name", name));
params.add(new BasicNameValuePair("email", email));
Log.d("request!", "starting");
//Posting user data to script
JSONObject json = jsonParser.makeHttpRequest(
REGISTER_URL, "POST", params);
// full json response
Log.d("Registering attempt", json.toString());
// json success element
success = json.getInt(TAG_SUCCESS);
if (success == 1) {
Log.d("User Created!", json.toString());
finish();
return json.getString(TAG_MESSAGE);
}else{
Log.d("Registering Failure!", json.getString(TAG_MESSAGE));
return json.getString(TAG_MESSAGE);
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(String file_url) {
// dismiss the dialog once product deleted
pDialog.dismiss();
if (file_url != null){
Toast.makeText(Register.this, file_url, Toast.LENGTH_LONG).show();
}
}
}
}
Do I have to put the PHP code?
The error:
1
2
Hey Pepe without seeing error whatever you got will make us complex to give you solution.
apart from that you can change your code like below
String data = URLEncoder.encode("user_email", "UTF-8")
+ "=" + URLEncoder.encode(user_email, "UTF-8");
data += "&" + URLEncoder.encode("user_password", "UTF-8") + "="
+ URLEncoder.encode(user_password, "UTF-8");
value = data;
URL url;
String response = "";
try {
url = new URL("Provide your URL here...");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(15000);
conn.setConnectTimeout(15000);
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.setDoOutput(true);
OutputStream os = conn.getOutputStream();
BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(os, "UTF-8"));
//writer.write(getPostDataString(postDataParams));
writer.write(value);
writer.flush();
writer.close();
os.close();
int responseCode = conn.getResponseCode();
if (responseCode == HttpsURLConnection.HTTP_OK) {
String line;
BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
while ((line = br.readLine()) != null) {
response += line;
System.out.println(response);
}
} else {
response = "";
}
} catch (Exception e) {
e.printStackTrace();
}
Enjoy, Happy coding....
When you get this error, it means your window is leaking the progress dialog.
Try this
class AttemptLogin extends AsyncTask<String, String, String> {
ProgressDialog pDialog; // add your pDialog here
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(Login.this, "Attempting to login",null);
}
You should not add the Intent in doInBackground, instead put them in onPostExecute. Read this article for logIn and logOut example.

the app force close after submitting the data into mysql

I tried an internet tutorial about inserting the data into mysql from Android
in the activity_main.xml, there are button to register new user.
So i put all the information such as firstname, etc. When the user clicks the submit button, it should redirect back to activity_main.xml.
But when I click submit, the app is forced to close, and the data is not inserted into mysql database.
My question is, What exactly is wrong in the code ?
Please give me advice.
Everything in the code is the same what i had also used for my android application. Also I am providing log traces here.
Any help is appreciated...
regactivity.java
package com.example.estate;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class RegActivity extends Activity {
// Progress Dialog
private ProgressDialog pDialog;
JSONParser jsonParser = new JSONParser();
EditText fname;
EditText lname;
EditText username;
EditText password;
EditText location;
EditText contact;
Button btnreg;
Button btncancel;
// url to create new product
private static String url_new_user = "http://192.168.43.236/Estate_Conny/new_user.php";
// JSON Node names
private static final String TAG_SUCCESS = "success";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.reg_activity);
// Edit Text
fname = (EditText) findViewById(R.id.fname);
lname = (EditText) findViewById(R.id.lname);
username = (EditText) findViewById(R.id.uname);
password = (EditText) findViewById(R.id.pass);
location = (EditText) findViewById(R.id.addr);
contact = (EditText) findViewById(R.id.contact);
// Create button
btnreg = (Button) findViewById(R.id.btnreg);
btncancel = (Button) findViewById(R.id.btncancel);
// button click event
btnreg.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// creating new product in background thread
new CreateNewProduct().execute();
}
});
btncancel.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
finish();
Intent i = new Intent(getApplicationContext(), MainActivity.class);
startActivity(i);
}
});
}
/**
* Background Async Task to Create new product
* */
class CreateNewProduct extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(RegActivity.this);
pDialog.setMessage("Registering New User..");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
/**
* Creating product
* */
protected String doInBackground(String... args) {
String Firstname = fname.getText().toString();
String Lastname = lname.getText().toString();
String Username = username.getText().toString();
String Password = password.getText().toString();
String Address = location.getText().toString();
String Contact = contact.getText().toString();
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("fname", Firstname));
params.add(new BasicNameValuePair("lname", Lastname));
params.add(new BasicNameValuePair("username", Username));
params.add(new BasicNameValuePair("password", Password));
params.add(new BasicNameValuePair("location", Address));
params.add(new BasicNameValuePair("contact", Contact));
// getting JSON Object
// Note that create product url accepts POST method
JSONObject json = jsonParser.makeHttpRequest(url_new_user,
"POST", params);
// check log cat fro response
Log.d("Create Response", json.toString());
// check for success tag
try {
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// successfully created product
finish();
Intent i = new Intent(getApplicationContext(), MainActivity.class);
startActivity(i);
} else {
// failed to create product
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
// dismiss the dialog once done
pDialog.dismiss();
}
}
}
MainActivity.java
package com.example.estate;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;
import com.example.estate.RegActivity;
//import com.example.androidhive.NewProductActivity;
import com.example.estate.R;
import com.example.estate.JSONParser;
import com.example.estate.MainActivity;
//import com.example.estate.ReadComments;
import com.example.estate.RegActivity;
//import com.example.estate.Login.AttemptLogin;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends Activity implements OnClickListener{
Button btnlogin;
Button btnreg;
Button btncancel;
EditText username;
EditText password;
private ProgressDialog pDialog;
JSONParser jsonParser = new JSONParser();
private static final String LOGIN_URL = "http://192.168.43.101/Estate_Conny/login.php";
private static final String TAG_SUCCESS = "success";
private static final String TAG_MESSAGE = "message";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Buttons
btnlogin = (Button) findViewById(R.id.btnlogin );
btnreg = (Button) findViewById(R.id.btncreate);
btncancel = (Button) findViewById(R.id.btnquit);
username = (EditText) findViewById(R.id.inputname);
password = (EditText) findViewById(R.id.inputpassword);
btnreg.setOnClickListener(this);
btnlogin.setOnClickListener(this);
btncancel.setOnClickListener(this);
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.btnlogin:
new AttemptLogin().execute();
break;
case R.id.btncreate:
Intent i = new Intent(this, RegActivity.class);
startActivity(i);
break;
case R.id.btnquit:
finish();
break;
default:
break;
}
}
class AttemptLogin extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
boolean failure = false;
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Logging in User...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected String doInBackground(String... args) {
// TODO Auto-generated method stub
// Check for success tag
int success;
String user = username.getText().toString();
String pass = password.getText().toString();
try {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("username", user));
params.add(new BasicNameValuePair("password", pass));
Log.d("request!", "starting");
// getting product details by making HTTP request
JSONObject json = jsonParser.makeHttpRequest(
LOGIN_URL, "POST", params);
// check your log for json response
Log.d("Login attempt", json.toString());
// json success tag
success = json.getInt(TAG_SUCCESS);
if (success == 1) {
Log.d("Login Successful!", json.toString());
Intent i = new Intent(MainActivity.this, ScreenActivity.class);
finish();
startActivity(i);
return json.getString(TAG_MESSAGE);
}else{
Log.d("Login Failure!", json.getString(TAG_MESSAGE));
return json.getString(TAG_MESSAGE);
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
// dismiss the dialog once product deleted
pDialog.dismiss();
if (file_url != null){
Toast.makeText(MainActivity.this, file_url, Toast.LENGTH_LONG).show();
}
}
}
}
new_user.php
<?php
/*
* Following code will create a new product row
* All product details are read from HTTP Post Request
*/
// array for JSON response
$response = array();
/ check for required fields
if (isset($_POST['fname']) && isset($_POST['lname']) && isset($_POST['username']) && isset($_POST['password']) && isset($_POST['location']) && isset($_POST['contact'])) {
$fname = $_POST['fname'];
$lname = $_POST['lname'];
$username = $_POST['username'];
$password = $_POST['password'];
$location = $_POST['location'];
$contact = $_POST['contact'];
// include db connect class
require_once __DIR__ . '/db_connect.php';
// connecting to db
$db = new DB_CONNECT();
// mysql inserting a new row
$result = mysql_query("INSERT INTO user(firstname, lastname, username, password, location, contact) VALUES('$fname', '$lname', '$username','$password','$location','$contact')");
// check if row inserted or not
if ($result) {
// successfully inserted into database
$response["success"] = 1;
$response["message"] = "User successfully Registered.";
// echoing JSON response
echo json_encode($response);
} else {
// failed to insert row
$response["success"] = 0;
$response["message"] = "Oops! An error occurred.";
// echoing JSON response
echo json_encode($response);
}
} else {
// required field is missing
$response["success"] = 0;
$response["message"] = "Required field(s) is missing";
// echoing JSON response
echo json_encode($response);
}
?>
Log_traces:
Process: agrawal.trial.server, PID: 21767
java.lang.RuntimeException: An error occured while executing doInBackground()
at android.os.AsyncTask$3.done(AsyncTask.java:300)
at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:355)
at java.util.concurrent.FutureTask.setException(FutureTask.java:222)
at java.util.concurrent.FutureTask.run(FutureTask.java:242)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
at java.lang.Thread.run(Thread.java:841)
Caused by: java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
at android.os.Handler.<init>(Handler.java:200)
at android.os.Handler.<init>(Handler.java:114)
at android.widget.Toast$TN.<init>(Toast.java:345)
at android.widget.Toast.<init>(Toast.java:100)
at android.widget.Toast.makeText(Toast.java:256)
at agrawal.trial.server.RegActivity$CreateNewProduct.doInBackground(RegActivity.java:116)
at agrawal.trial.server.RegActivity$CreateNewProduct.doInBackground(RegActivity.java:89)
at android.os.AsyncTask$2.call(AsyncTask.java:288)
at java.util.concurrent.FutureTask.run(FutureTask.java:237)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
at java.lang.Thread.run(Thread.java:841)
java.lang.IllegalArgumentException: HTTP entity may not be null
at org.apache.http.util.EntityUtils.toString(EntityUtils.java:110)
at org.apache.http.util.EntityUtils.toString(EntityUtils.java:146)
at miui.util.ErrorReport.b(SourceFile:363)
at miui.util.ErrorReport.sendReportRequest(SourceFile:320)
at miui.util.ErrorReport$2.a(SourceFile:336)
at miui.util.ErrorReport$2.doInBackground(SourceFile:333)
at android.os.AsyncTask$2.call(AsyncTask.java:288)
at java.util.concurrent.FutureTask.run(FutureTask.java:237)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
at java.lang.Thread.run(Thread.java:841)
12-01 20:31:48.771 1057-1225/? W/ContextImpl﹕ Calling a method in the system process without a qualified user: android.app.ContextImpl.bindService:1585 android.content.ContextWrapper.bindService:517 miui.os.DropBoxManager.b:361 miui.os.DropBoxManager.a:350 miui.os.DropBoxManager.addText:314
12-01 20:31:48.801 1138-1150/? W/MessageQueue﹕ Handler (com.miui.internal.server.DropBoxManagerService$2) {428282d8} sending message to a Handler on a dead thread
if (success == 1) {
// successfully created product
Intent i = new Intent(getApplicationContext(), MainActivity.class);
startActivity(i);
finish(); //replace position of This
} else {
// failed to create product
}
Put this in onpostExecute Block remove from Do in Back ground

Android Application: I have two forms within my app which need to save to a database

The first form is saving to the Database perfectly fine. I am trying to test if the second form saves to the database, however, the second form appears if a checkbox is checked on the first form; the second form appears and disappears almost immediately. Can someone help please?
First Form java code
package com.lifematters;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.Toast;
public class MoodTracker extends Activity {
private ProgressDialog pDialog;
// url to create new
private static String url_create_mood = "http://depressionapp.net46.net/depressionapp/moodtracker.php";
// JSON Node names
private static final String TAG_SUCCESS = "success";
JSONParser jsonParser = new JSONParser();
EditText autoDate, autoTime, inputPlace, inputMood, causeFactor, inputFactor;
CheckBox checkTreatment;
Button btnSave;
String sAutoDate;
String sAutoTime;
String sInputPlace;
String sInputMood;
String sCauseFactor;
String sInputFactor;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.mood_tracker);
autoDate = (EditText) findViewById(R.id.autoDate);
autoTime = (EditText) findViewById(R.id.autoTime);
inputPlace = (EditText) findViewById(R.id.inputPlace);
inputMood = (EditText) findViewById(R.id.inputMood);
causeFactor = (EditText) findViewById(R.id.chooseFactor);
inputFactor = (EditText) findViewById(R.id.inputFactor);
// Create button
btnSave = (Button) findViewById(R.id.btnSave);
checkTreatment = (CheckBox) findViewById(R.id.checkTreatment);
// create user
btnSave.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
sAutoDate = autoDate.getText().toString();
sAutoTime = autoTime.getText().toString();
sInputPlace = inputPlace.getText().toString();
sInputMood = inputMood.getText().toString();
sCauseFactor = autoDate.getText().toString();
sInputFactor = inputFactor.getText().toString();
//if any field is empty, display toast
if (sAutoDate.matches("") || sInputMood.matches("") ||
sCauseFactor.matches("")) {
Toast.makeText(getApplicationContext(), "Please ensure all fields marked with asterisks are completed", Toast.LENGTH_LONG).show();
} else {
new CreateMoodTracker().execute();
}
CheckBox checkTreatment = (CheckBox ) findViewById(R.id.checkTreatment);
if ( checkTreatment.isChecked() ) {
Intent i = new Intent(getApplicationContext(), TreatmentTracker.class);
startActivity(i);
}
}
});
}
/**
* Background Asynchronous Task
* */
class CreateMoodTracker extends AsyncTask<String, String, String> {
int success;
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(MoodTracker.this);
pDialog.setMessage("Creating Tracker Record...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
/**
* Creating user
* */
protected String doInBackground(String... args) {
sAutoDate = autoDate.getText().toString();
sAutoTime = autoTime.getText().toString();
sInputPlace = inputPlace.getText().toString();
sInputMood = inputMood.getText().toString();
sCauseFactor = causeFactor.getText().toString();
sInputFactor = inputFactor.getText().toString();
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("UID", "1"));
params.add(new BasicNameValuePair("date", sAutoDate));
params.add(new BasicNameValuePair("time", sAutoTime));
params.add(new BasicNameValuePair("place", sInputPlace));
params.add(new BasicNameValuePair("mood", sInputMood));
params.add(new BasicNameValuePair("causefactor", sCauseFactor));
params.add(new BasicNameValuePair("factordetail", sInputFactor));
// getting JSON Object
// Note that create URL accepts POST method
JSONObject json = jsonParser.makeHttpRequest(url_create_mood,
"POST", params);
// check log cat from response
Log.d("Create Response", json.toString());
// check for success tag
try {
success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// successfully created , move to login screen
Intent i = new Intent(getApplicationContext(), MainActivity.class);
startActivity(i);
// closing this screen
finish();
} else {
// failed to create
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
// dismiss the dialog once done
pDialog.dismiss();
}
}
}
Send the value of checkbox from the first form to second form whether checkbox is true or false.Then control the value.

Storing dynamic data to a label

I'm trying to develop my first app, but i need help with something.
So, to access into my app, you have to Log-in writing your own username and password.
My app has a sliding menu on the left, i use the jfeinstein10 library.
Now, i want that in the first row of this menu was dysplayed the username of the user, so you understand that this is a dynamic string.
This is the .xml code of my row:
<item name="list_item_municipio_id" type="slidingmenu" />
<item name="list_item_municipio_label" type="slidingmenu">"Municipio"</item>
<item name="list_item_municipio_icon " type="slidingmenu">"#drawable/iconamunicipio"</item>
Now it is displayed "municipio" with <item name="list_item_municipio_label".
I read that strings are static, and that a possible solution is using SharedPreferences.
Can you give me an example? Because i don't understand how to store the username to a SharedPreferences.
This is the code of the login.java:
package com.baruckis.SlidingMenuImplementation;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class Login extends Activity implements OnClickListener{
public static final String PREFS_NAME = "LoginPrefs";
private EditText user, pass;
private Button mSubmit, mRegister;
private ProgressDialog pDialog;
// Attivo una connessione JSON
JSONParser jsonParser = new JSONParser();
//Collego un file php sul mio server
private static final String LOGIN_URL = "http://provasitosaronno.dnshosting.it/php/login.php";
//JSON gestisce le risposte fornite dallo script php
private static final String TAG_SUCCESS = "success";
private static final String TAG_MESSAGE = "message";
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.login);
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
if (settings.getString("logged", "").toString().equals("logged")) {
Intent i = new Intent(Login.this, SlidingMenuFromClassActivity.class);
finish();
startActivity(i);
}
//Imposto le due variabili user e pass
user = (EditText)findViewById(R.id.username);
pass = (EditText)findViewById(R.id.password);
//Collego i due pulsanti del login e del register
mSubmit = (Button)findViewById(R.id.login);
mRegister = (Button)findViewById(R.id.register);
//Aggiungo la funzione del clicklistener
mSubmit.setOnClickListener(this);
mRegister.setOnClickListener(this);
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.login:
new AttemptLogin().execute();
break;
case R.id.register:
Intent i = new Intent(this, Register.class);
startActivity(i);
break;
default:
break;
}
}
class AttemptLogin extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
boolean failure = false;
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(Login.this);
pDialog.setMessage("Accesso in corso...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected String doInBackground(String... args) {
// TODO Auto-generated method stub
int success;
String username = user.getText().toString();
String password = pass.getText().toString();
try {
//Aggiungo i parametri generati dalle variabili
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("username", username));
params.add(new BasicNameValuePair("password", password));
Log.d("request!", "starting");
// Ottengo i risultati dalla connessione http
JSONObject json = jsonParser.makeHttpRequest(
LOGIN_URL, "POST", params);
//Aspetto una risposta da JSON
Log.d("Login attempt", json.toString());
//Se il tutto avviene...
success = json.getInt(TAG_SUCCESS);
if (success == 1) {
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
SharedPreferences.Editor editor = settings.edit();
editor.putString("logged", "logged");
editor.commit();
Log.d("Login Successful!", json.toString());
Intent i = new Intent(Login.this, SlidingMenuFromClassActivity.class);
finish();
startActivity(i);
return json.getString(TAG_MESSAGE);
}else{
Log.d("Login Failure!", json.getString(TAG_MESSAGE));
return json.getString(TAG_MESSAGE);
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
//funzione dismiss
pDialog.dismiss();
if (file_url != null){
Toast.makeText(Login.this, file_url, Toast.LENGTH_LONG).show();
}
}
}
}
Below is a code how you can save information to SharedPreference.
SharedPreferences settings = this.getActivity().getSharedPreferences("MyApp", 0);
SharedPreferences.Editor editor = settings.edit();
String user = "foobar";
editor.putString("user", user);
editor.commit();

Categories