Related
Please am having a "failed to insert" error sending data from my android app to a remote mysql database. It has a Spinner control. I'm calling an api on the remote server to to the insert, but it fails to insert.
Below is My Main Activity code
public class RCrimeActivity extends AppCompatActivity implements View.OnClickListener{
private EditText nop, wh;
private Button bReport;
private Spinner ct;
// Progress Dialog
private ProgressDialog pDialog;
// JSON parser class
JSONParser jsonParser = new JSONParser();
private static final String LOGIN_URL = "http://www.nigeriacrimewatch.com/ncwrcapi.php";
private static final String TAG_SUCCESS = "success";
private static final String TAG_MESSAGE = "message";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_rcrime);
nop = (EditText) findViewById(R.id.nop);
wh = (EditText) findViewById(R.id.wh);
ct = (Spinner) findViewById(R.id.ct);
bReport = (Button) findViewById(R.id.btnReport);
bReport.setOnClickListener(this);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent homescr = new Intent(RCrimeActivity.this, MainActivity.class);
startActivity(homescr);
}
});
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btnReport:
new AttemptReport().execute();
// here we have used, switch case, because on login activity you may //also want to show registration button, so if the user is new ! we can go the //registration activity , other than this we could also do this without switch //case. default:
default:
break;
}
}
class AttemptReport extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog *
*/
boolean failure = false;
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(RCrimeActivity.this);
pDialog.setMessage("Reporting crime...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected String doInBackground(String... args) {
// here check for success tag
int success;
String name = nop.getText().toString();
String address = wh.getText().toString();
String type = ct.getSelectedItem().toString();
try {
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("nop", name));
params.add(new BasicNameValuePair("wh", address));
params.add(new BasicNameValuePair("ct", type));
Log.d("request!", "starting");
JSONObject json = jsonParser.makeHttpRequest(
LOGIN_URL, "POST", params);
// checking log for json response
Log.d("Report attempt", json.toString());
// success tag for json
success = json.getInt(TAG_SUCCESS);
if (success == 1) {
Log.d("Crime Reported!", json.toString());
Intent ii = new Intent(RCrimeActivity.this, MapActivity.class);
finish();
// this finish() method is used to tell android os that we are done with current //activity now! Moving to other activity
startActivity(ii);
return json.getString(TAG_MESSAGE);
} else {
return json.getString(TAG_MESSAGE);
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
/**
* Once the background process is done we need to Dismiss the progress dialog asap *
**/
protected void onPostExecute(String message) {
pDialog.dismiss();
if (message != null) {
Toast.makeText(RCrimeActivity.this, message, Toast.LENGTH_LONG).show();
}
}
}
API Code
<?php
error_reporting(E_ALL);
ini_set('display_errors',TRUE);
include_once "conn/nconn.php";
$username=$_POST["username"]; $email=$_POST["email"];
$password=$_POST["password"];
if (!empty($_POST)) {
if (empty($_POST['username']) || empty($_POST['email']) || empty($_POST['password'])) {
// Create some data that will be the JSON response
$response["success"] = 0; $response["message"] = "One or both of the fields are empty .";
//die is used to kill the page, will not let the code below to be executed. It will also //display the parameter, that is the json data which our android application will parse to be //shown to the users
die(json_encode($response));
}
$query = " INSERT INTO gmusers (username, email, password, created) values ('$username','$email','$password', now())";
$sql1=mysql_query($query); if (!empty($sql1)) { $response["success"] = 1;
$response["message"] = "Registered sucessfully"; die(json_encode($response));
} else{
$response["success"] = 0; $response["message"] = "Failed to register";
die(json_encode($response));
}
} else{
$response["success"] = 0; $response["message"] = " One or both of the fields are empty ";
die(json_encode($response));
}
?>
i create chain spinner that get data from server and return it by json. my firts spinner is fine. in second spinner the json give response but when try to save the renspone in array the asynctask error caused by nullpointerexception. when i check it in log cat there is no null in my json response. so i try to change name of array with same name as first spinner there is no error but the second spinner show same value as first spinner.
my question why my second spinner when name of array different from first spinner is error ?
where is the nullpointerexception error because when i check it there is no null ? how to fixed it ?
there is my LoginActivity.java
// Email, password edittext
EditText txtEmail, txtPassword;
private static String KEY_LOGIN = "login";
private String URL_LOGIN = "http://api.omidev.com/login/format/json";
private String URL_PROV = "http://api.omidev.com/lokasi/jenis_lokasi/provinsi/format/json";
private String URL_KOTA = null;
private Spinner spinnerProv, spinnerKota, spinnerKec, spinnerDesa;
// array list for spinner adapter
private ArrayList<Category> categoriesList;
private ArrayList<Category> categoriesListKota;
ProgressDialog pDialog;
HttpPost httppost;
HttpResponse response;
HttpClient httpclient;
List<NameValuePair> nameValuePairs;
ProgressDialog dialog = null;
String mSelected;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
// Session Manager
session = new SessionManager(getApplicationContext());
main = (RelativeLayout) findViewById(R.id.LayoutMain);
login = (RelativeLayout) findViewById(R.id.LayoutLogin);
regis = (RelativeLayout) findViewById(R.id.LayoutRegister);
// Email, Password input text
txtEmail = (EditText) findViewById(R.id.editText1);
txtPassword = (EditText) findViewById(R.id.editText2);
getActionBar().hide();
ubahTulisan();
}
private void ubahTulisan()
{
// Font path
String fontPath = "fonts/roboto_black.ttf";
// text view label
TextView txtMasuk = (TextView) findViewById(R.id.textView1);
TextView txtAkunBaru = (TextView) findViewById(R.id.TextView01);
// Loading Font Face
Typeface tf = Typeface.createFromAsset(getAssets(), fontPath);
// Applying font
txtMasuk.setTypeface(tf);
txtAkunBaru.setTypeface(tf);
}
public void login_click(View view)
{
main.setVisibility(-5);
login.setVisibility(1);
regis.setVisibility(-5);
}
public void regis_click(View view)
{
main.setVisibility(-5);
login.setVisibility(-5);
regis.setVisibility(1);
categoriesList = new ArrayList<Category>();
spinnerProv = (Spinner) findViewById(R.id.spinner1);
spinnerKota = (Spinner) findViewById(R.id.spinner2);
spinnerKec = (Spinner) findViewById(R.id.Spinner3);
spinnerDesa = (Spinner) findViewById(R.id.Spinner4);
// spinner item select listener
spinnerProv.setOnItemSelectedListener(new OnItemSelectedListener(){
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position,
long id) {
try {
mSelected = URLEncoder.encode(categoriesList.get(position).getId().toString(), "utf-8");
URL_KOTA ="http://api.omidev.com/lokasi/jenis_lokasi/kota/id/"+mSelected+"/format/json";
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//new GetKota().execute();
Toast.makeText(
getApplicationContext(),
mSelected + " Selected" ,
Toast.LENGTH_LONG).show();
new GetKota().execute();
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}});
// spinner item select listener
new GetCategories().execute();
}
public void login_cancel_click(View view)
{
main.setVisibility(1);
login.setVisibility(-5);
regis.setVisibility(-5);
}
public void regis_cancel_click(View view)
{
main.setVisibility(1);
login.setVisibility(-5);
regis.setVisibility(-5);
}
public void login_accept_click(View view)
{
main.setVisibility(-5);
login.setVisibility(1);
regis.setVisibility(-5);
new Login().execute();
}
public void regis_accept_click(View view)
{
main.setVisibility(-5);
login.setVisibility(1);
regis.setVisibility(-5);
}
private class Login extends AsyncTask<String, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(LoginActivity.this);
pDialog.setMessage("Validating User..");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(String... arg) {
String username = txtEmail.getText().toString();
String password = txtPassword.getText().toString();
if(username.trim().length() > 0 && password.trim().length() > 0){
// Preparing post params
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("email", username));
params.add(new BasicNameValuePair("password", password));
ServiceHandler serviceClient = new ServiceHandler();
String json = serviceClient.makeServiceCall(URL_LOGIN,
ServiceHandler.POST, params);
Log.d("Create Response: ", "> " + json);
if (json != null) {
try {
JSONObject jsonObj = new JSONObject(json);
// checking for error node in json
if (jsonObj.getString(KEY_LOGIN) != null) {
// new category created successfully
JSONArray menuitemArray = jsonObj.getJSONArray("login");
for (int i = 0; i < menuitemArray.length(); i++) {
String id = menuitemArray.getJSONObject(i).getString("id_user").toString();
String email = menuitemArray.getJSONObject(i).getString("email").toString();
session.createLoginSession(""+id, ""+email.toString());
}
// Staring MainActivity
Intent a = new Intent(getApplicationContext(), MainActivity.class);
startActivity(a);
finish();
}
} catch (JSONException e) {
e.printStackTrace();
runOnUiThread(new Runnable() {
public void run() {
alert.showAlertDialog(LoginActivity.this, "Login failed..", "Email Atau Password Salah", false);
}
});
}
} else {
Log.e("JSON Data", "Didn't receive any data from server!");
}
}else{
// user didn't entered username or password
// Show alert asking him to enter the details
runOnUiThread(new Runnable() {
public void run() {
alert.showAlertDialog(LoginActivity.this, "Login failed..", "Masukan Email dan Password", false);
}
});
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
if (pDialog.isShowing())
pDialog.dismiss();
}
}
#Override
public void onBackPressed() {
// TODO Auto-generated method stub
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_HOME);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
private void populateSpinner() {
List<String> lables = new ArrayList<String>();
for (int i = 0; i < categoriesList.size(); i++) {
lables.add(categoriesList.get(i).getName());
}
// Creating adapter for spinner
ArrayAdapter<String> spinnerAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, lables);
// Drop down layout style - list view with radio button
spinnerAdapter
.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// attaching data adapter to spinner
spinnerProv.setAdapter(spinnerAdapter);
}
private void populateSpinnerKota() {
List<String> lables = new ArrayList<String>();
for (int i = 0; i < categoriesListKota.size(); i++) {
lables.add(categoriesListKota.get(i).getName());
}
// Creating adapter for spinner
ArrayAdapter<String> spinnerAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, lables);
// Drop down layout style - list view with radio button
spinnerAdapter
.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// attaching data adapter to spinner
spinnerKota.setAdapter(spinnerAdapter);
}
private class GetCategories extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... arg0) {
ServiceHandler jsonParser = new ServiceHandler();
String json = jsonParser.makeServiceCall(URL_PROV, ServiceHandler.GET);
Log.e("Response: ", "> " + json);
if (json != null) {
try {
JSONObject jsonObj = new JSONObject(json);
if (jsonObj != null) {
JSONArray categories = jsonObj
.getJSONArray("lokasi");
for (int i = 0; i < categories.length(); i++) {
JSONObject catObj = (JSONObject) categories.get(i);
Category cat = new Category(catObj.getString("id_provinsi"),
catObj.getString("nama"));
categoriesList.add(cat);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("JSON Data", "Didn't receive any data from server!");
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
populateSpinner();
}
}
private class GetKota extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... arg0) {
ServiceHandler jsonParser = new ServiceHandler();
String json = jsonParser.makeServiceCall(URL_KOTA, ServiceHandler.GET);
Log.e("Response: ", "> " + json);
if (json != null) {
try {
JSONObject jsonObj = new JSONObject(json);
if (jsonObj != null) {
JSONArray categorieskota = jsonObj
.getJSONArray("lokasi");
for (int i = 0; i < categorieskota.length(); i++) {
JSONObject catObj = (JSONObject) categorieskota.get(i);
Log.e("Response Kota: ", "> " + catObj.getString("id_kota"));
Category catK = new Category(catObj.getString("id_kota"),
catObj.getString("nama"));
categoriesListKota.add(catK);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("JSON Data", "Didn't receive any data from server!");
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
populateSpinnerKota();
}
}
my category.java
private String id;
private String name;
public Category(){}
public Category(String id, String name){
this.id = id;
this.name = name;
}
public void setId(String id){
this.id = id;
}
public void setName(String name){
this.name = name;
}
public String getId(){
return this.id;
}
public String getName(){
return this.name;
}
my serviceHandler.java
static InputStream is = null;
static String response = null;
public final static int GET = 1;
public final static int POST = 2;
public ServiceHandler() {
}
/*
* Making service call
* #url - url to make request
* #method - http request method
* */
public String makeServiceCall(String url, int method) {
return this.makeServiceCall(url, method, null);
}
/*
* Making service call
* #url - url to make request
* #method - http request method
* #params - http request params
* */
public String makeServiceCall(String url, int method,
List<NameValuePair> params) {
try {
// http client
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpEntity httpEntity = null;
HttpResponse httpResponse = null;
// Checking http request method type
if (method == POST) {
HttpPost httpPost = new HttpPost(url);
// adding post params
if (params != null) {
httpPost.setEntity(new UrlEncodedFormEntity(params));
}
httpResponse = httpClient.execute(httpPost);
} else if (method == GET) {
// appending params to url
if (params != null) {
String paramString = URLEncodedUtils
.format(params, "utf-8");
url += "?" + paramString;
}
HttpGet httpGet = new HttpGet(url);
httpResponse = httpClient.execute(httpGet);
}
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, "UTF-8"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
response = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error: " + e.toString());
}
return response;
}
This is Logcat error:
02-05 18:20:48.953: E/Response:(29903): > {"lokasi":[{"id_provinsi":"1","nama":"Bali"},{"id_provinsi":"2","nama":"Banten"},{"id_provinsi":"3","nama":"Bengkulu"},{"id_provinsi":"4","nama":"DI Yogyakarta"},{"id_provinsi":"5","nama":"DKI Jakarta"},{"id_provinsi":"6","nama":"Gorontalo"},{"id_provinsi":"7","nama":"Irian Jaya Barat"},{"id_provinsi":"8","nama":"Jambi"},{"id_provinsi":"9","nama":"Jawa Barat"},{"id_provinsi":"10","nama":"Jawa Tengah"},{"id_provinsi":"11","nama":"Jawa Timur"},{"id_provinsi":"12","nama":"Kalimantan Barat"},{"id_provinsi":"13","nama":"Kalimantan Selatan"},{"id_provinsi":"14","nama":"Kalimantan Tengah"},{"id_provinsi":"15","nama":"Kalimantan Timur"},{"id_provinsi":"16","nama":"Kep. Bangka Belitung"},{"id_provinsi":"17","nama":"Kep. Riau"},{"id_provinsi":"18","nama":"Lampung"},{"id_provinsi":"19","nama":"Maluku"},{"id_provinsi":"20","nama":"Maluku Utara"},{"id_provinsi":"21","nama":"Nanggroe Aceh Darussalaam"},{"id_provinsi":"22","nama":"Nusa Tenggara Barat"},{"id_provinsi":"23","nama":"Nusa Tenggara Timur"},{"id_provinsi":"24","nama":"Papua"},{"id_provinsi":"25","nama":"Riau"},{"id_provinsi":"26","nama":"Sulawesi Selatan"},{"id_provinsi":"27","nama":"Sulawesi Tengah"},{"id_provinsi":"28","nama":"Sulawesi Tenggara"},{"id_provinsi":"29","nama":"Sulawesi Utara"},{"id_provinsi":"30","nama":"Sumatra Barat"},{"id_provinsi":"31","nama":"Sumatra Selatan"},{"id_provinsi":"32","nama":"Sumatra Utara"}]}
02-05 18:20:49.573: E/Response:(29903): > {"lokasi":[{"id_kota":"1","id_provinsi":"1","nama":"KABUPATEN BADUNG"},{"id_kota":"2","id_provinsi":"1","nama":"KABUPATEN BANGLI"},{"id_kota":"3","id_provinsi":"1","nama":"KABUPATEN BULELENG"},{"id_kota":"4","id_provinsi":"1","nama":"KABUPATEN GIANYAR"},{"id_kota":"5","id_provinsi":"1","nama":"KABUPATEN JEMBRANA"},{"id_kota":"6","id_provinsi":"1","nama":"KABUPATEN KARANG ASEM"},{"id_kota":"7","id_provinsi":"1","nama":"KABUPATEN KLUNGKUNG"},{"id_kota":"8","id_provinsi":"1","nama":"KABUPATEN TABANAN"},{"id_kota":"9","id_provinsi":"1","nama":"KOTA DENPASAR"}]}
02-05 18:20:49.573: E/Response Kota:(29903): > 1
02-05 18:20:49.573: W/dalvikvm(29903): threadid=16: thread exiting with uncaught exception (group=0x415b1360)
02-05 18:20:49.603: E/AndroidRuntime(29903): FATAL EXCEPTION: AsyncTask #2
02-05 18:20:49.603: E/AndroidRuntime(29903): java.lang.RuntimeException: An error occured while executing doInBackground()
02-05 18:20:49.603: E/AndroidRuntime(29903): at android.os.AsyncTask$3.done(AsyncTask.java)
02-05 18:20:49.603: E/AndroidRuntime(29903): at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:273)
02-05 18:20:49.603: E/AndroidRuntime(29903): at java.util.concurrent.FutureTask.setException(FutureTask.java:124)
02-05 18:20:49.603: E/AndroidRuntime(29903): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:307)
02-05 18:20:49.603: E/AndroidRuntime(29903): at java.util.concurrent.FutureTask.run(FutureTask.java:137)
02-05 18:20:49.603: E/AndroidRuntime(29903): at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java)
02-05 18:20:49.603: E/AndroidRuntime(29903): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
02-05 18:20:49.603: E/AndroidRuntime(29903): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
02-05 18:20:49.603: E/AndroidRuntime(29903): at java.lang.Thread.run(Thread.java:856)
02-05 18:20:49.603: E/AndroidRuntime(29903): Caused by: java.lang.NullPointerException
02-05 18:20:49.603: E/AndroidRuntime(29903): at com.android.desaku.LoginActivity$GetKota.doInBackground(LoginActivity.java:377)
02-05 18:20:49.603: E/AndroidRuntime(29903): at com.android.desaku.LoginActivity$GetKota.doInBackground(LoginActivity.java:1)
02-05 18:20:49.603: E/AndroidRuntime(29903): at android.os.AsyncTask$2.call(AsyncTask.java)
02-05 18:20:49.603: E/AndroidRuntime(29903): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
02-05 18:20:49.603: E/AndroidRuntime(29903): ... 5 more
please help me thanks. sorry i dont know how to post logcat
Try to change these code:
private static String KEY_LOGIN = "login";
private String URL_LOGIN = "http://api.omidev.com/login/format/json";
private String URL_PROV = "http://api.omidev.com/lokasi/jenis_lokasi/provinsi/format/json";
to:
private static final String KEY_LOGIN = "login";
private static final String URL_LOGIN = "http://api.omidev.com/login/format/json";
private static final String URL_PROV = "http://api.omidev.com/lokasi/jenis_lokasi/provinsi/format/json";
See the difference. The second using static final. Then, change void to String while using String parameter. For example:
private class Login extends AsyncTask<String, Void, Void> {
// Change void to String if the first AsyncTask parameter is a String.
// If the first parameter is Void, change to void (in lowercase)
#Override
protected String doInBackground(String... arg) { // Must be a String type, because the first parameter type is a String.
Sorry my fault. i already fixed my code
in GetKota Asynctask i did not initialized categoriesListKota, so that make it error caused by nullpointerexception.
to make the second spinning change when selected value from first spinning i add notifyDataSetChanged() to change the spinner adapter on populateSpinnerKota() and clear() on GetKota Asynctask to make the spinner clean from previous data.
this is the correct code for LoginActivity.java
// Alert Dialog Manager
AlertDialogManager alert = new AlertDialogManager();
// Session Manager Class
SessionManager session;
// Email, password edittext
EditText txtEmail, txtPassword;
private static String KEY_LOGIN = "login";
private String URL_LOGIN = "http://api.omidev.com/login/format/json";
private String URL_PROV = "http://api.omidev.com/lokasi/jenis_lokasi/provinsi/format/json";
private String URL_KOTA = null;
private Spinner spinnerProv, spinnerKota, spinnerKec, spinnerDesa;
// array list for spinner adapter
private ArrayList<Category> categoriesList = new ArrayList<Category>();
private ArrayList<Category> categoriesListKota = new ArrayList<Category>();
ProgressDialog pDialog;
HttpPost httppost;
HttpResponse response;
HttpClient httpclient;
List<NameValuePair> nameValuePairs;
ProgressDialog dialog = null;
String mSelected;
List<String> list = new ArrayList<String>();
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
// Session Manager
session = new SessionManager(getApplicationContext());
main = (RelativeLayout) findViewById(R.id.LayoutMain);
login = (RelativeLayout) findViewById(R.id.LayoutLogin);
regis = (RelativeLayout) findViewById(R.id.LayoutRegister);
// Email, Password input text
txtEmail = (EditText) findViewById(R.id.editText1);
txtPassword = (EditText) findViewById(R.id.editText2);
getActionBar().hide();
ubahTulisan();
}
private void ubahTulisan()
{
// Font path
String fontPath = "fonts/roboto_black.ttf";
// text view label
TextView txtMasuk = (TextView) findViewById(R.id.textView1);
TextView txtAkunBaru = (TextView) findViewById(R.id.TextView01);
// Loading Font Face
Typeface tf = Typeface.createFromAsset(getAssets(), fontPath);
// Applying font
txtMasuk.setTypeface(tf);
txtAkunBaru.setTypeface(tf);
}
public void login_click(View view)
{
main.setVisibility(-5);
login.setVisibility(1);
regis.setVisibility(-5);
}
public void regis_click(View view)
{
main.setVisibility(-5);
login.setVisibility(-5);
regis.setVisibility(1);
spinnerProv = (Spinner) findViewById(R.id.spinner1);
spinnerKota = (Spinner) findViewById(R.id.spinner2);
spinnerKec = (Spinner) findViewById(R.id.Spinner3);
spinnerDesa = (Spinner) findViewById(R.id.Spinner4);
// spinner item select listener
spinnerProv.setOnItemSelectedListener(new OnItemSelectedListener(){
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position,
long id) {
try {
mSelected = URLEncoder.encode(categoriesList.get(position).getId().toString(), "utf-8");
URL_KOTA ="http://api.omidev.com/lokasi/jenis_lokasi/kota/id/"+mSelected+"/format/json";
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Toast.makeText(
getApplicationContext(),
mSelected + " Selected" ,
Toast.LENGTH_LONG).show();
new GetKota().execute();
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}});
// spinner item select listener
new GetCategories().execute();
}
public void login_cancel_click(View view)
{
main.setVisibility(1);
login.setVisibility(-5);
regis.setVisibility(-5);
}
public void regis_cancel_click(View view)
{
main.setVisibility(1);
login.setVisibility(-5);
regis.setVisibility(-5);
}
public void login_accept_click(View view)
{
main.setVisibility(-5);
login.setVisibility(1);
regis.setVisibility(-5);
new Login().execute();
}
public void regis_accept_click(View view)
{
main.setVisibility(-5);
login.setVisibility(1);
regis.setVisibility(-5);
}
private class Login extends AsyncTask<String, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(LoginActivity.this);
pDialog.setMessage("Validating User..");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(String... arg) {
String username = txtEmail.getText().toString();
String password = txtPassword.getText().toString();
if(username.trim().length() > 0 && password.trim().length() > 0){
// Preparing post params
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("email", username));
params.add(new BasicNameValuePair("password", password));
ServiceHandler serviceClient = new ServiceHandler();
String json = serviceClient.makeServiceCall(URL_LOGIN,
ServiceHandler.POST, params);
Log.d("Create Response: ", "> " + json);
if (json != null) {
try {
JSONObject jsonObj = new JSONObject(json);
// checking for error node in json
if (jsonObj.getString(KEY_LOGIN) != null) {
// new category created successfully
JSONArray menuitemArray = jsonObj.getJSONArray("login");
for (int i = 0; i < menuitemArray.length(); i++) {
String id = menuitemArray.getJSONObject(i).getString("id_user").toString();
String email = menuitemArray.getJSONObject(i).getString("email").toString();
session.createLoginSession(""+id, ""+email.toString());
}
// Staring MainActivity
Intent a = new Intent(getApplicationContext(), MainActivity.class);
startActivity(a);
finish();
}
} catch (JSONException e) {
e.printStackTrace();
runOnUiThread(new Runnable() {
public void run() {
alert.showAlertDialog(LoginActivity.this, "Login failed..", "Email Atau Password Salah", false);
}
});
}
} else {
Log.e("JSON Data", "Didn't receive any data from server!");
}
}else{
// user didn't entered username or password
// Show alert asking him to enter the details
runOnUiThread(new Runnable() {
public void run() {
alert.showAlertDialog(LoginActivity.this, "Login failed..", "Masukan Email dan Password", false);
}
});
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
if (pDialog.isShowing())
pDialog.dismiss();
}
}
#Override
public void onBackPressed() {
// TODO Auto-generated method stub
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_HOME);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
private void populateSpinner() {
List<String> lables = new ArrayList<String>();
for (int i = 0; i < categoriesList.size(); i++) {
lables.add(categoriesList.get(i).getName());
}
// Creating adapter for spinner
ArrayAdapter<String> spinnerAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, lables);
// Drop down layout style - list view with radio button
spinnerAdapter
.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// attaching data adapter to spinner
spinnerProv.setAdapter(spinnerAdapter);
}
private void populateSpinnerKota() {
List<String> lables = new ArrayList<String>();
for (int i = 0; i < categoriesListKota.size(); i++) {
lables.add(categoriesListKota.get(i).getName());
}
// Creating adapter for spinner
ArrayAdapter<String> spinnerAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, lables);
spinnerAdapter.notifyDataSetChanged();
// Drop down layout style - list view with radio button
spinnerAdapter
.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// attaching data adapter to spinner
spinnerKota.setAdapter(spinnerAdapter);
}
private class GetCategories extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... arg0) {
ServiceHandler jsonParser = new ServiceHandler();
String json = jsonParser.makeServiceCall(URL_PROV, ServiceHandler.GET);
Log.e("Response: ", "> " + json);
if (json != null) {
try {
JSONObject jsonObj = new JSONObject(json);
if (jsonObj != null) {
JSONArray categories = jsonObj
.getJSONArray("lokasi");
for (int i = 0; i < categories.length(); i++) {
JSONObject catObj = (JSONObject) categories.get(i);
Category cat = new Category(catObj.getString("id_provinsi"),
catObj.getString("nama"));
categoriesList.add(cat);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("JSON Data", "Didn't receive any data from server!");
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
populateSpinner();
}
}
private class GetKota extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... arg0) {
ServiceHandler jsonParser = new ServiceHandler();
String json = jsonParser.makeServiceCall(URL_KOTA, ServiceHandler.GET);
categoriesListKota.clear();
Log.e("Response: ", "> " + json);
if (json != null) {
try {
JSONObject jsonObj = new JSONObject(json);
if (jsonObj != null) {
JSONArray categorieskota = jsonObj
.getJSONArray("lokasi");
for (int i = 0; i < categorieskota.length(); i++) {
JSONObject catObj = (JSONObject) categorieskota.get(i);
Category catK = new Category(catObj.getString("id_kota"),
catObj.getString("nama"));
categoriesListKota.add(catK);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("JSON Data", "Didn't receive any data from server!");
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
populateSpinnerKota();
}
}
I really need your help. I am building an Android app that needs a lot of HTTP requests such as logging to the server(check if user is exists or not) and storing the session to the database (user_sessions table), adding, updating and deleting records.
In my Login Activity, I have my AsyncTask (to check if user exits) and other background threads (logs the user session and download user info to database) . This is successful. Next, when I update the user info, it updates successfully. But what if I update using my web app? My should display the newly updated info on my android app. How can I resolve this problem?
This is what I've tried so far:
private void logSessionToServer() {
// TODO Auto-generated method stub
Thread thread = new Thread(){
public void run(){
strUsername = etUsername.getText().toString();
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair( TAG_USERNAME, strUsername ));
// getting JSON Object
// Note it accepts POST method only
JSONObject json = jsonParser.makeHttpRequest(url_log_session,
"POST", params);
// check log cat from response
Log.d("Create Response", json.toString());
// check for success tag
try {
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
Log.d("", "Successfully logged session!");
} else {
// failed
Log.d("", "Not Successful!");
}
} catch (JSONException e) {
e.printStackTrace();
}
}
};
thread.start();
}
/**
* Background Async Task to Create new record
* */
class LoginTask extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(Login.this);
pDialog.setIcon(R.drawable.upload);
pDialog.setTitle("Connecting to server");
pDialog.setMessage("Validating login details..");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
/**
*
* */
protected String doInBackground(String... args) {
strUsername = etUsername.getText().toString();
strPassword = etPassword.getText().toString();
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair( TAG_USERNAME, strUsername ));
params.add(new BasicNameValuePair( TAG_PASSWORD, strPassword ));
// getting JSON Object
// Note it accepts POST method only
JSONObject json = jsonParser.makeHttpRequest(url_login,
"POST", params);
// check log cat from response
Log.d("Create Response", json.toString());
// check for success tag
try {
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
logSessionToServer(); // Save login to server
saveUserInfoToDB(); // Save user info to DB
saveUserloggedIn(); // Save user logged in to preference
savePriestInfoToDB(); // Save priest to DB
Log.d("", "Successful Login!");
Intent i = new Intent(Login.this, MainActivity.class);
startActivity(i);
finish();
} else {
// failed
new Thread()
{
public void run()
{
runOnUiThread(new Runnable()
{
public void run()
{
Toast.makeText(getBaseContext(),
"Not Successful Login", Toast.LENGTH_SHORT).show();
}
});
}
}.start();
Log.d("", "Not Successful Login!");
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String result) {
// dismiss the dialog once done
pDialog.dismiss();
}
}
private void saveUserInfoToDB() {
// TODO Auto-generated method stub
Thread thread = new Thread(){
public void run(){
// Create the array
arraylist = new ArrayList<HashMap<String, String>>();
// Retrieve JSON Objects from the given website URL in JSONfunctions.class
String result = JSONFunctions.getJSONfromURL(url_view_loggedUser_profile);
try {
JSONArray jr = new JSONArray(result);
for(int i=0;i<jr.length();i++)
{
HashMap<String, String> map = new HashMap<String, String>();
jb = (JSONObject)jr.get(i);
map.put(TAG_FIRSTNAME, jb.getString(TAG_FIRSTNAME));
map.put(TAG_MIDDLENAME, jb.getString(TAG_MIDDLENAME));
map.put(TAG_LASTNAME, jb.getString(TAG_LASTNAME));
map.put(TAG_EMAIL, jb.getString(TAG_EMAIL));
map.put(TAG_AGE, jb.getString(TAG_AGE));
map.put(TAG_GENDER, jb.getString(TAG_GENDER));
map.put(TAG_USERNAME, jb.getString(TAG_USERNAME));
map.put(TAG_PASSWORD, jb.getString(TAG_PASSWORD));
map.put(TAG_BARANGAY, jb.getString(TAG_BARANGAY));
map.put(TAG_COMPLETEADDRESS, jb.getString(TAG_COMPLETEADDRESS));
map.put(TAG_CUS_ID, jb.getString(TAG_CUS_ID));
map.put(TAG_REG_DATE, jb.getString(TAG_REG_DATE));
map.put(TAG_BD_MONTH, jb.getString(TAG_BD_MONTH));
map.put(TAG_BD_DATE, jb.getString(TAG_BD_DATE));
map.put(TAG_BD_YEAR, jb.getString(TAG_BD_YEAR));
arraylist.add(map);
String strCusID = jb.getString(TAG_CUS_ID);
String strFname = jb.getString(TAG_FIRSTNAME);
String strMname = jb.getString(TAG_MIDDLENAME);
String strLname = jb.getString(TAG_LASTNAME);
String strEmail = jb.getString(TAG_EMAIL);
String strAge = jb.getString(TAG_AGE);
String strGender = jb.getString(TAG_GENDER);
String strUsername = jb.getString(TAG_USERNAME);
String strPassword = jb.getString(TAG_PASSWORD);
String strBarangay = jb.getString(TAG_BARANGAY);
String strCompleteAddress = jb.getString(TAG_COMPLETEADDRESS);
String strRegDate = jb.getString(TAG_REG_DATE);
String strBDMonth = jb.getString(TAG_BD_MONTH);
String strBDDate = jb.getString(TAG_BD_DATE);
String strBDYear = jb.getString(TAG_BD_YEAR);
try{
dbHelper.insertEntry(strCusID, strFname, strMname, strLname, strEmail,
strAge, strGender, strUsername, strPassword,
strBarangay, strCompleteAddress, strRegDate,
strBDMonth, strBDDate, strBDYear);
Log.d("Response", "Successfully inserted record");
} catch (SQLiteException e) {
Log.d("Response", "Not successful");
}
}
} catch (JSONException e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
}
};
thread.start();
}
private void savePriestInfoToDB() {
// TODO Auto-generated method stub
Thread thread = new Thread(){
public void run(){
// Create the array
arraylist = new ArrayList<HashMap<String, String>>();
// Retrieve JSON Objects from the given website URL in JSONfunctions.class
String result = JSONFunctions.getJSONfromURL(URL_VIEW_PRIESTS);
try {
JSONArray jr = new JSONArray(result);
for(int i=0;i<jr.length();i++)
{
HashMap<String, String> map = new HashMap<String, String>();
jb = (JSONObject)jr.get(i);
map.put(TAG_P_ID, jb.getString(TAG_P_ID));
map.put(TAG_P_FIRSTNAME, jb.getString(TAG_P_FIRSTNAME));
map.put(TAG_P_MIDDLENAME, jb.getString(TAG_P_MIDDLENAME));
map.put(TAG_P_LASTNAME, jb.getString(TAG_P_LASTNAME));
map.put(TAG_P_EMAIL, jb.getString(TAG_P_EMAIL));
map.put(TAG_P_AGE, jb.getString(TAG_P_AGE));
map.put(TAG_P_ADDRESS, jb.getString(TAG_P_ADDRESS));
map.put(TAG_P_CONTACT, jb.getString(TAG_P_CONTACT));
map.put(TAG_P_STATUS, jb.getString(TAG_P_STATUS));
arraylist.add(map);
String strP_ID = jb.getString(TAG_P_ID);
String strP_Fname = jb.getString(TAG_P_FIRSTNAME);
String strP_Mname = jb.getString(TAG_P_MIDDLENAME);
String strP_Lname = jb.getString(TAG_P_LASTNAME);
String strP_Email = jb.getString(TAG_P_EMAIL);
String strP_Age = jb.getString(TAG_P_AGE);
String strP_Address = jb.getString(TAG_P_ADDRESS);
String strP_Status = jb.getString(TAG_P_STATUS);
String strP_Contact = jb.getString(TAG_P_CONTACT);
try{
dbHelper.insertPriest(strP_ID, strP_Fname, strP_Mname,
strP_Lname, strP_Email, strP_Age,
strP_Address, strP_Status, strP_Contact);
Log.d("Response - Priest", "Successfully inserted record");
} catch (SQLiteException e) {
Log.d("Response - Priest", "Not successful");
}
}
} catch (JSONException e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
}
};
thread.start();
}
Feel free to check out my codes and give feedback if this is the best practice for HTTP requests. I am new to Web Services so I really need your help. Any help will be greatly appreciated. Thanks
Well what I just said: you write a thread which downloads user-info every 5 seconds. then it compares the user info downloaded with the user info that is already stored on your device. if there is a difference, an update has been made, and your thread invokes a new download of the updated user info.
This question already has an answer here:
how to fix getDataTask method error?
(1 answer)
Closed 9 years ago.
this is my code below which work perfectly only problem is not show toast mesage code is blast i want to display toast mesage if Status is 0 in this line if (status.equals("1"))
show toast message but code is blast if i comment Toast then code run perfectly help me what do i do??
public class thirdstep extends Activity {
ListView listCategory;
String status;
String message;
String MenuSelect;
ProgressBar prgLoading;
long Cat_ID;
String Cat_name;
String CategoryAPI;
int IOConnect = 0;
TextView txtAlert;
thirdstepAdapter cla;
static ArrayList<String> Category_ID = new ArrayList<String>();
static ArrayList<String> Category_name = new ArrayList<String>();
static ArrayList<String> Category_image = new ArrayList<String>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.category_list2);
ImageButton btnback = (ImageButton) findViewById(R.id.btnback);
listCategory = (ListView) findViewById(R.id.listCategory2);
prgLoading = (ProgressBar) findViewById(R.id.prgLoading);
txtAlert = (TextView) findViewById(R.id.txtAlert);
cla = new thirdstepAdapter(thirdstep.this);
new getDataTask().execute();
listCategory.setAdapter(cla);
btnback.setOnClickListener(new OnClickListener()
{
public void onClick(View arg0) {
// TODO Auto-generated method stub
finish();
}
});
Intent iGet = getIntent();
Cat_ID = iGet.getLongExtra("category_id", 0);
Cat_name = iGet.getStringExtra("category_name");
Toast.makeText(this, Cat_ID + Cat_name, Toast.LENGTH_SHORT).show();
MenuSelect = Utils.MenuSelect;
listCategory.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0, View arg1,
int position, long arg3) {
// TODO Auto-generated method stub
Intent iMenuList = new Intent(thirdstep.this,
fourthscreen.class);
iMenuList.putExtra("Cat_ID",Cat_ID);
iMenuList.putExtra("Menuitem", Category_ID.get(position));
startActivity(iMenuList);
}
});
}
void clearData() {
Category_ID.clear();
Category_name.clear();
Category_image.clear();
}
public class getDataTask extends AsyncTask<Void, Void, Void>{
getDataTask(){
if(!prgLoading.isShown()){
prgLoading.setVisibility(0);
txtAlert.setVisibility(8);
}
}
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
}
#Override
protected Void doInBackground(Void... arg0) {
// TODO Auto-generated method stub
parseJSONData();
return null;
}
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
prgLoading.setVisibility(8);
if((Category_ID.size() > 0) || IOConnect == 0){
listCategory.setVisibility(0);
listCategory.setAdapter(cla);
}else{
txtAlert.setVisibility(0);
}
}
}
public void parseJSONData() {
CategoryAPI = Utils.MenuList + Cat_ID;
clearData();
try {
HttpClient client = new DefaultHttpClient();
HttpConnectionParams
.setConnectionTimeout(client.getParams(), 15000);
HttpConnectionParams.setSoTimeout(client.getParams(), 15000);
HttpUriRequest request = new HttpGet(CategoryAPI);
HttpResponse response = client.execute(request);
InputStream atomInputStream = response.getEntity().getContent();
BufferedReader in = new BufferedReader(new InputStreamReader(
atomInputStream));
String line;
String str = "";
while ((line = in.readLine()) != null) {
str += line;
}
JSONObject json = new JSONObject(str);
JSONObject json2 = new JSONObject(str);
status = json2.getString("status");
message = json2.getString("message");
if (status.equals("1")) {
JSONObject data = json.getJSONObject("data");
JSONArray school = data.getJSONArray("menu_groups");
for (int i = 0; i < school.length(); i++) {
JSONObject object = school.getJSONObject(i);
Category_ID.add(object.getString("id"));
Category_name.add(object.getString("title"));
Category_image.add(object.getString("image"));
}
}
else
{
Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
}
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
IOConnect = 1;
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Your toast message is within the parseJsonData method which is called from the doInBackground method of your asynctask.
You can not update the user interface thread from a background thread.
You have two options here
1) You can publish the progress publishProgress(1) of the thread passing in an integer value to be used as a flag which you can pick up on in the onPublishProgress listener and show your toast there
or
2) As your method has finished by this point then make the parseJsonData set an integer variable global to the asynctask and in the onPostExecute method pass something back to the listener to indicate that a toast needs to be shown
Update based on comments
Replace
{
Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
}
with
{
publishProgress(1);
}
Add the missing onProgressUpdate() method to your asynctask
#Override
protected void onProgressUpdate(Integer... percent) {
//Call your listeners.onProgressUpdate(percent) here and show the
//Or
super.onProgressUpdate(percent);
if (percent[0] == 1){
Toast.makeText(thirdstep.this, message, Toast.LENGTH_SHORT).show();
}
}
I'm not here to write your code for you. Do some research on how to properly write an async task and publish progress
Here is a good starting point
http://androidresearch.wordpress.com/2012/03/17/understanding-asynctask-once-and-forever/
You should be aware of orientation changes and how that will effect your asynctask (I avoid the pitfals of this by using a fragment
This is the design pattern I use for async tasks
http://www.androiddesignpatterns.com/2013/04/retaining-objects-across-config-changes.html
But for handling web services, be nice to your users and let the android system work out when to download data etc and don't drain their battery and use a sync adapter with an intentservice instead of an asynctask. There are already too many crappy apps out there that take the asynctask approach for consuming web services. Please don't add yours to the list
Do it this way
http://developer.android.com/training/sync-adapters/creating-sync-adapter.html
It's a lot of extra learning curve but your a programmer right? You should be giving your users the best possible experience.
BTW You are getting down votes because you are demanding code to be written for you. I'm hoping this is just a language barrier and not an attitude problem.
Surround your Toast with this
runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(getBaseContext(), message, Toast.LENGTH_SHORT).show();
}
});
I have a Login page where I want to authenticate the username and password from the database on the network. The problem is while doing the AsyncTask I want to return the username and password values. But this is not happening.
How do I return the values? Here is my login page code.
public class Login extends Activity {
Integer aaa=0;
Button b,b2;
RelativeLayout r;
TextView t, t2;
String str1, str2, username, password;
String A = null, B = null;
EditText et1, et2;
Dialog myDialog;
String FILENAME = "http://animsinc.com/query.php";
protected ProgressDialog dialog;
protected Handler h;
static InputStream in = null;
static JSONObject jObj = null;
static String json = "";
private static final String TAG_ID = "id";
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.sign_in);
Display display = ((WindowManager)getSystemService(Context.WINDOW_SERVICE))
.getDefaultDisplay();
int width = display.getWidth();
int height = display.getHeight() / 4;
r = (RelativeLayout) findViewById(R.id.RL);
RelativeLayout.LayoutParams r = new RelativeLayout.LayoutParams(width,
height);
t = (TextView) findViewById(R.id.textView1);
t2 = (TextView) findViewById(R.id.textView2);
t.setOnClickListener(link);
t2.setOnClickListener(fgtpass);
et1 = (EditText) findViewById(R.id.editText1);
et2 = (EditText) findViewById(R.id.editText2);
b2 = (Button) findViewById(R.id.button2);
b2.setOnClickListener(temp);
b = (Button) findViewById(R.id.button1);
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if ((et1.getText().length() == 0)
|| (et2.getText().length() == 0))
{
Toast.makeText(getApplicationContext(),
"Please enter correct details",Toast.LENGTH_LONG)
.show();
} else {
dialog = ProgressDialog.show(Login.this, "Loading",
"Please Wait...");
/* h = new Handler() {
#Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
dialog.dismiss();
}
};
new Thread() {
#Override
public void run() {
super.run();
String st=startDownload();
try {
Thread.sleep(3000);
h.sendEmptyMessage(0);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}.start();*/
Toast.makeText(getApplicationContext(),""+st,Toast.LENGTH_LONG).show();
String st=startDownload();
Toast.makeText(getApplicationContext(),"aaa="+aaa, Toast.LENGTH_LONG).show();
Toast.makeText(getApplicationContext(),""+st, Toast.LENGTH_LONG).show();
}
if ((et1.getText().toString().equals(username))&& (et2.getText().toString().equals(password)))
{
Intent openStartingPoint = new Intent(Login.this,
UserActivity.class);
startActivity(openStartingPoint);
}
}
});
}
private
String startDownload() {
String C = null;
new AppTask().execute(FILENAME);
aaa++;
return C;
}
private View.OnClickListener temp = new View.OnClickListener() {
public void onClick(View V) {
Intent openStartingPoint = new Intent(Login.this,
UserActivity.class);
startActivity(openStartingPoint);
}
};
private View.OnClickListener link = new View.OnClickListener() {
public void onClick(View V) {
Intent openStartingPoint = new Intent(Login.this,
ContactDetails.class);
startActivity(openStartingPoint);
}
};
private View.OnClickListener fgtpass = new View.OnClickListener() {
public void onClick(View V) {
myDialog = new Dialog(Login.this);
myDialog.setContentView(R.layout.emailpop);
myDialog.setTitle("Forgot Password");
myDialog.setCancelable(true);
// for save
Button ok = (Button) myDialog.findViewById(R.id.button1);
ok.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
myDialog.dismiss();
}
});
myDialog.show();
}
};
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
}
public class AppTask extends AsyncTask<String, Integer, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
}
#Override
protected void onProgressUpdate(Integer... values) {
// TODO Auto-generated method stub
super.onProgressUpdate(values);
}
#Override
protected String doInBackground(String... params) {
String is = null;
str1 = et1.getText().toString();
str2 = et2.getText().toString();
if (str1.length() > 0 && str2.length() > 0) {
A = str1;
B = str2;
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(
"http://animsinc.com/query.php");
try {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(
2);
nameValuePairs.add(new BasicNameValuePair("username", str1));
nameValuePairs.add(new BasicNameValuePair("password", str2));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
httpclient.execute(httppost);
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = EntityUtils.toString(entity);
JSONArray jArray = new JSONArray(is);
for (int i = 0; i < jArray.length(); i++) {
JSONObject jObject = jArray.getJSONObject(i);
username = jObject.getString("username");
password = jObject.getString("password");
aaa++;
}
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return username;
}
}
}
When an asynchronous task is executed, the task goes through 4 steps:
onPreExecute(), invoked on the UI thread before the task is executed. This step is normally used to setup the task, for instance by showing a progress bar in the user interface.
doInBackground(Params...), invoked on the background thread immediately after onPreExecute() finishes executing. This step is used to perform background computation that can take a long time. The parameters of the asynchronous task are passed to this step. The result of the computation must be returned by this step and will be passed back to the last step. This step can also use publishProgress(Progress...) to publish one or more units of progress. These values are published on the UI thread, in the onProgressUpdate(Progress...) step.
onProgressUpdate(Progress...), invoked on the UI thread after a call to publishProgress(Progress...). The timing of the execution is undefined. This method is used to display any form of progress in the user interface while the background computation is still executing. For instance, it can be used to animate a progress bar or show logs in a text field.
onPostExecute(Result), invoked on the UI thread after the background computation finishes. The result of the background computation is passed to this step as a parameter.
So return value in doInBackground() , receive it in onPostExecute() and update ui accordingly.
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
Toast.makeTest(MainActivity.this,result,1000).show();
//set result to textview
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
// result is the value you return from doInBackground
String username = result;
}