So I have a ProfileActivity where I pass the user's details to EditProfileActivity.. the passed values are placed correctly on their specified edittexts. But whenever I change the values in the edittexts and clicked the save button..the values on the database are not modified..Can you please help me
package com.example.androidproject;
public class EditProfileActivity extends Activity {
Button Save, Delete;
EditText tname,tusername, tpassword, tpassword2, tbio;
TextView uname;
User u = new User();
String editfullname,editpw,editpw2,editbio,getuname;
String fn,b,pw,pw2;
TextView tv1,tv2,tv3;
String getfn,getpw,getbio;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_editprofile);
Save = (Button) findViewById(R.id.buttonsignup);
Delete = (Button) findViewById(R.id.button1);
tname = (EditText) findViewById(R.id.txtfullname);
tusername = (EditText) findViewById(R.id.txtun);
tpassword = (EditText) findViewById(R.id.txtpw);
tpassword2 = (EditText) findViewById(R.id.txtpw2);
tbio = (EditText) findViewById(R.id.txtbio);
uname = (TextView) findViewById(R.id.getusername);
tv1 = (TextView) findViewById(R.id.textView2);
tv2 = (TextView) findViewById(R.id.textView3);
tv3 = (TextView) findViewById(R.id.textView4);
Intent intent = getIntent();
u.SetUsername(intent.getStringExtra(u.username()));
editfullname = (intent.getStringExtra("Fullname"));
editbio = (intent.getStringExtra("Bio"));
editpw = (intent.getStringExtra("Password"));
editpw2 = (intent.getStringExtra("Password2"));
uname.setText(u.getUsername());
tname.setText(editfullname);
tpassword.setText(editpw);
tpassword2.setText(editpw2);
tbio.setText(editbio);
getuname = u.username().toString();
Save.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
fn = tname.getText().toString();
pw = tpassword.getText().toString();
b = tbio.getText().toString();
tv1.setText(fn); //i displayed to textviews the NEW values inputted from the edittexts.
tv2.setText(pw);
tv3.setText(b);
getfn = tv1.getText().toString(); //i put these to the namevalupairs in my asynctask
getpw = tv2.getText().toString();
getbio = tv3.getText().toString();
new SaveDataTask().execute();
}
});
}
class SaveDataTask extends AsyncTask<String, String, Void> {
protected void onPreExecute() {
}
#Override
protected Void doInBackground(String... params) {
byte[] data;
HttpPost httppost;
StringBuffer buffer = null;
HttpResponse response;
HttpClient httpclient;
InputStream inputStream;
List<NameValuePair> nameValuePairs;
nameValuePairs = new ArrayList<NameValuePair>(4);
nameValuePairs.add(new BasicNameValuePair("Fullname", getfn.trim()));
nameValuePairs.add(new BasicNameValuePair("Username", getuname));
nameValuePairs.add(new BasicNameValuePair("Password", getpw.trim()));
nameValuePairs.add(new BasicNameValuePair("Bio", getbio.trim()));
try {
httpclient = new DefaultHttpClient();
httppost = new HttpPost("http://192.168.1.6/webservices/mycontroller/updateuser.php");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
response = httpclient.execute(httppost);
inputStream = response.getEntity().getContent();
data = new byte[256];
buffer = new StringBuffer();
int len = 0;
while (-1 != (len = inputStream.read(data)) ) {
buffer.append(new String(data, 0, len));
}
//name= buffer.toString();
inputStream.close();
runOnUiThread(new Runnable(){
public void run() {
Toast.makeText(EditProfileActivity.this, "UPDATED", Toast.LENGTH_LONG).show();
}
});
}
catch (Exception e) {
Toast.makeText(EditProfileActivity.this, "error" + e.toString(), Toast.LENGTH_LONG).show();
}
return null;
}
}
}
Here is my php code for update:
<?php
mysql_connect("localhost","root","");
mysql_select_db("poetrydb");
$Fullname = $_POST['Fullname'];
$Username = $_POST['Username'];
$Password = $_POST['Password'];
$Bio = $_POST['Bio'];
$query_insert = "UPDATE account SET FullName ='$Fullname', Bio= '$Bio', Password ='$Password' WHERE Username ='$Username'";
mysql_query($query_insert) or die(mysql_error());
echo "UPDATED";
?>
You need to update the values on click event otherwise you will always be passing the same value that you received in onCreate
Save.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// fetch the updated values from edittext and
// store them in string references
fn = tname.getText().toString();
getuname = u.username().toString();
pw = tpassword.getText().toString();
b = tbio.getText().toString();
new SaveDataTask().execute();
Related
Let me explain it better. i have made an app which has 3 fields. I want to insert these three fields into database. I'm getting 'data successfully inserted' message in toast but values are not getting inserted in database. Even i don't have any errors.. Thanku!
My php file:
<?php
//Define your host here.
$hostname = "localhost";
//Define your database username here.
$username = "root";
//Define your database password here.
$password = "root";
//Define your database name here.
$dbname = "SCPL";
$con = mysqli_connect($hostname,$username,$password,$dbname);
$name = $_POST['name'];
$email = $_POST['email'];
$website = $_POST['website'];
$Sql_Query = "insert into scpl (name,email,website) values ('$name','$email','$website')";
if(mysqli_query($con,$Sql_Query)){
echo 'Data Inserted Successfully';
}
else{
echo 'Try Again';
}
mysqli_close($con);
?>
This is my mainactivity.java class:
public class MainActivity extends Activity {
EditText editTextName, editTextEmail, editTextWebsite;
String GetName, GetEmail, GetWebsite;
Button buttonSubmit ;
String DataParseUrl = "http://192.168.2.6/androids/insert.php";
//String HttpURL = "http://192.168.2.26/Android_php/gps_tracker/insert.php";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editTextName = (EditText)findViewById(R.id.editText1);
editTextEmail = (EditText)findViewById(R.id.editText2);
editTextWebsite = (EditText)findViewById(R.id.editText3);
buttonSubmit = (Button)findViewById(R.id.button1);
buttonSubmit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
GetDataFromEditText();
SendDataToServer(GetName, GetEmail, GetWebsite);
}
});
}
public void GetDataFromEditText(){
GetName = editTextName.getText().toString();
GetEmail = editTextEmail.getText().toString();
GetWebsite = editTextWebsite.getText().toString();
}
public void SendDataToServer(final String name, final String email, final String website){
class SendPostReqAsyncTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
String QuickName = name ;
String QuickEmail = email ;
String QuickWebsite = website;
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("name", QuickName));
nameValuePairs.add(new BasicNameValuePair("email", QuickEmail));
nameValuePairs.add(new BasicNameValuePair("website", QuickWebsite));
try {
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(DataParseUrl);
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpClient.execute(httpPost);
HttpEntity entity = response.getEntity();
} catch (ClientProtocolException e) {
} catch (IOException e) {
}
return "";
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
Toast.makeText(MainActivity.this, "Data Submit Successfully", Toast.LENGTH_LONG).show();
}
}
SendPostReqAsyncTask sendPostReqAsyncTask = new SendPostReqAsyncTask();
sendPostReqAsyncTask.execute(name, email,website);
}
}
i haven't found any errors/mistakes, try changing your URL/ip address to:
Use 10.0.2.2 for default AVD and 10.0.3.2 for genymotion.
Try using $_REQUEST instead of $_POST and check the response from the server first before showing the success message in your onPostExecute function like #MJM suggested.
I had similar problems with my API and android app when I was sending the data as POST request, the only way to get the submitted data was with $_REQUEST
ProfileActivity.java
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.activity_profile, container,
false);
nama = (TextView) rootView.findViewById(R.id.nama);
tanggal = (TextView) rootView.findViewById(R.id.birth);
telepon = (TextView) rootView.findViewById(R.id.telepon);
status = (TextView) rootView.findViewById(R.id.status);
email = (TextView) rootView.findViewById(R.id.email);
img = (ImageView) rootView.findViewById(R.id.image);
edit = (Button) rootView.findViewById(R.id.edit);
session = new SessionManager(getActivity());
int loader = R.drawable.ic_launcher;
session.checkLogin();
HashMap<String, String> user = session.getUserDetails();
String nama1 = user.get(SessionManager.KEY_username);
String tanggal1 = user.get(SessionManager.key_birthday);
String image1 = user.get(SessionManager.key_image);
String status1 = user.get(SessionManager.key_status);
String telepon1 = user.get(SessionManager.key_telephone);
String email1 = user.get(SessionManager.key_email);
nama.setText("Nama: " + nama1);
tanggal.setText("Tanggal Lahir : " + tanggal1);
telepon.setText("No Telepon : " + telepon1);
if (status1.equals("SA")) {
status.setText("Status : Super Admin");
} else if (status1.equals("A")) {
status.setText("Status : Admin");
} else {
status.setText("Status : Sales");
}
email.setText("Email : " + email1);
edit.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Fragment fragment = new EditProfileActivity();
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.frame_container, fragment).commit();
getActivity().setTitle("Edit Profile");
}
});
String image_url = "url_name"
+ image1;
// ImageLoader class instance
ImageLoader imgLoader = new ImageLoader(getActivity());
imgLoader.DisplayImage(image_url, loader, img);
return rootView;
}
EditProfileActivity.java
session = new SessionManager(getActivity());
session.checkLogin();
HashMap<String, String> user = session.getUserDetails();
telp1 = user.get(SessionManager.key_telephone);
email1 = user.get(SessionManager.key_email);
id = user.get(SessionManager.KEY_ID);
nama = user.get(SessionManager.KEY_username);
image1 = user.get(SessionManager.key_image);
tanggal = user.get(SessionManager.key_birthday);
status = user.get(SessionManager.key_status);
password1 = user.get(SessionManager.key_pass);
oldpass1 = oldpass.getText().toString();
newpass1 = newpass.getText().toString();
retypepass1 = retypepass.getText().toString();
int loader = R.drawable.ic_launcher;
gmbr.setText(image1);
telp.setText(telp1);
email.setText(email1);
oldpass.setText(password1);
newpass.setText(password1);
String image_url = "url_name"
+ image1;
// ImageLoader class instance
ImageLoader imgLoader = new ImageLoader(getActivity());
imgLoader.DisplayImage(image_url, loader, img);
changepic.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
galleryIntent();
}
});
editprof.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
// if (!oldpass.equals(password1) ||
// !retypepass.equals(newpass)) {
// Toast.makeText(getActivity(), "Old Password Salah",
// Toast.LENGTH_SHORT).show();
// } else {
new editprofile().execute();
// }
}
});
return rootView;
}
protected void galleryIntent() {
// TODO Auto-generated method stub
Intent intent = new Intent(Intent.ACTION_PICK,
MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(intent, SELECT_FILE);
}
#SuppressWarnings("static-access")
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == SELECT_FILE && resultCode == getActivity().RESULT_OK
&& data != null) {
Uri Selectedimage = data.getData();
img.setImageURI(Selectedimage);
}
}
class editprofile extends AsyncTask<Void, Integer, String> {
#Override
protected void onPreExecute() {
// setting progress bar to zero
super.onPreExecute();
pDialog = new ProgressDialog(getActivity());
pDialog.setMessage("Loading...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
protected String doInBackground(Void... params) {
Bitmap images = ((BitmapDrawable) img.getDrawable()).getBitmap();
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
images.compress(Bitmap.CompressFormat.JPEG, 100,
byteArrayOutputStream);
String EncodedImage = Base64.encodeToString(
byteArrayOutputStream.toByteArray(), Base64.DEFAULT);
String email2 = email.getText().toString();
String telepon2 = telp.getText().toString();
String newpass2 = newpass.getText().toString();
String img2 = gmbr.getText().toString();
ArrayList<NameValuePair> datatosend = new ArrayList<NameValuePair>();
datatosend.add(new BasicNameValuePair("image", EncodedImage));
datatosend.add(new BasicNameValuePair("imagename", img2));
datatosend.add(new BasicNameValuePair("email", email2));
datatosend.add(new BasicNameValuePair("telepon", telepon2));
datatosend.add(new BasicNameValuePair("newpass", newpass2));
datatosend.add(new BasicNameValuePair("id", id));
HttpParams httpParams = gethttprequestparam();
HttpClient httpClient = new DefaultHttpClient(httpParams);
HttpPost httpPost = new HttpPost(
EditProfileActivity.url_create_product);
try {
httpPost.setEntity(new UrlEncodedFormEntity(datatosend));
httpClient.execute(httpPost);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(String result) {
super.onPostExecute(result);
pDialog.dismiss();
Toast.makeText(getActivity(), "edit profile berhasil",
Toast.LENGTH_SHORT).show();
session.logoutUser();
}
}
public void onBackPressed() {
FragmentManager fm = getActivity().getFragmentManager();
fm.popBackStack();
}
public HttpParams gethttprequestparam() {
// TODO Auto-generated method stub
HttpParams httpParams = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParams, 1000 * 30);
HttpConnectionParams.setSoTimeout(httpParams, 1000 * 30);
return httpParams;
}
EditProfile.php
<?php
$response = array();
include('Connect.php');
$image= $_POST['image'];
$image1= $_POST['imagename'];
$email= $_POST['email'];
$telepon= $_POST['telepon'];
$newpass= $_POST['newpass'];
$id= $_POST['id'];
$decodedimage = base64_decode("$image");
$image =
file_put_contents("foldername/".$image1, $decodedimage);
$query = mysqli_query($con, "update user set image = '$image1' where iduser = '$id'");
$query1 = mysqli_query($con, "update user set email = '$email' where iduser = '$id'");
$query2 = mysqli_query($con, "update user set phone = '$telepon' where iduser = '$id'");
$query3 = mysqli_query($con, "update user set password = '$newpass' where iduser = '$id'");
echo json_encode($response);
?>
the main problem is when I edit profile with the same image name, the table user in database is updated and the image is uploaded with new one with same name but when I displayed image in android using imageloader, the image is displayed with old one instead of new one. how can i fix it?
notes: The image is replaced with new one when the image name is different(ex: the old one is a.JPG, the new one is b.JPG) but won't replaced with new one if the image name is still the same.
In my android application I need to call two functions in a web service. I need to display both the values in one page. When I did for one function it was working fine.. but when I tried for second it is not working.. I am giving my code below.
class ProgressTask extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(R_Details.this);
pDialog.setMessage("Verifying the details... Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#SuppressWarnings("deprecation")
#Override
protected String doInBackground(String... args) {
url = "https://xxx.xxxx.com/appservice/d_service.asmx/mDetails?";
url2 = "https://xxx.xxxx.com/appservice/d_service.asmx/mGoDetails?";
SharedPreferences plnumber = getSharedPreferences(PREFS_NAME, 0);
SharedPreferences login = getSharedPreferences(PREFS_NAME, 0);
pl = String.valueOf(pnumber.getString("pl","not found"));
cd = String.valueOf(login.getString("cid","not found"));
ud = String.valueOf(login.getString("uid","not found"));
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("pl", pl));
params.add(new BasicNameValuePair("cd", cd));
params.add(new BasicNameValuePair("ud", ud));
String paramString = URLEncodedUtils.format(params, "utf-8");
url += paramString;
url2 += paramString;
// TODO Auto-generated method stub
JSONParser jParser = new JSONParser();
JSONPars jPars = new JSONPars();
// getting JSON string from URL
JSONObject json = jParser.getJSONFromUrl(url);
JSONObject json2 = jPars.getJSONFromUrl(url2);
try {
final String st = json.getString(TAG_STATUS);
final String po = json.getString(TAG_PNO);
final String pt = json.getString(TAG_PAMT);
final String te = json.getString(TAG_TRAD);
final String me = json.getString(TAG_MD);
final String le = json.getString(TAG_LTE);
final String ph = json2.getString(TAG_PE);
final String pi = json2.getString(TAG_PE);
final String ir = json2.getString(TAG_IT);
final String rt = json2.getString(TAG_RE);
final String tt = json2.getString(TAG_TNT);
de = (TextView) findViewById(R.id.dd);
lt = (TextView) findViewById(R.id.ltd);
le = (TextView) findViewById(R.id.lted);
me = (TextView) findViewById(R.id.mad);
at = (TextView) findViewById(R.id.ad);
lo = (TextView) findViewById(R.id.tvr);
pe = (TextView) findViewById(R.id.pd);
it = (TextView) findViewById(R.id.id);
pe = (TextView) findViewById(R.id.pd);
re = (TextView) findViewById(R.id.rd);
tt = (TextView) findViewById(R.id.td);
runOnUiThread(new Runnable() {
#Override
public void run()
{
de.setText(trnsdate);
lt.setText(pledamt);
le.setText(ltradate);
me.setText(matdate);
at.setText(stat);
lo.setText(pledno);
pe.setText(pi);
it.setText(ir);
pe.setText(ph);
re.setText(rt);
tt.setText(tt);
}
});
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
protected void onPostExecute(String file_url) {
// dismiss the dialog once got all details
pDialog.dismiss();
}
}
There is issues in your code.
Move the following code to onPostExecute method
de = (TextView) findViewById(R.id.dd);
lt = (TextView) findViewById(R.id.ltd);
le = (TextView) findViewById(R.id.lted);
me = (TextView) findViewById(R.id.mad);
at = (TextView) findViewById(R.id.ad);
lo = (TextView) findViewById(R.id.tvr);
pe = (TextView) findViewById(R.id.pd);
it = (TextView) findViewById(R.id.id);
pe = (TextView) findViewById(R.id.pd);
re = (TextView) findViewById(R.id.rd);
tt = (TextView) findViewById(R.id.td);
runOnUiThread(new Runnable() {
#Override
public void run()
{
de.setText(trnsdate);
lt.setText(pledamt);
le.setText(ltradate);
me.setText(matdate);
at.setText(stat);
lo.setText(pledno);
pe.setText(pi);
it.setText(ir);
pe.setText(ph);
re.setText(rt);
tt.setText(tt);
}
});
Reason: Don't use UI widgets in doInBackGround method
This is my code in a class that extends Asynctask and its doInBackground() method:
//Building Parameters
List<NameValuePair> paramss = new ArrayList<NameValuePair>();
paramss.add(new BasicNameValuePair(TAG_EMAIL, email));
//getting JSON string from url
JSONObject json = parser.makeHttpRequest(url_get_one_member, "POST",paramss);
Log.d("Ambil Member",json.toString());
//cari tag success
try{
int success = json.getInt(TAG_SUCCESS);
if(success == 1){
member = json.getJSONArray(TAG_MEMBER);
JSONObject jObject = member.getJSONObject(0);
String emaill = jObject.getString(TAG_EMAIL);
String nama = jObject.getString(TAG_NAMA);
String alamat = jObject.getString(TAG_ALAMAT);
String no_telp = jObject.getString(TAG_NO_TELP);
String umur = jObject.getString(TAG_UMUR);
String tempatLahir = jObject.getString(TAG_TEMPAT_LAHIR);
String tglLahir = jObject.getString(TAG_TANGGAL_LAHIR);
String jlhPeliharaan = jObject.getString(TAG_JUMLAH_PELIHARAAN);
String warna = jObject.getString(TAG_WARNA_FAVORIT);
String jenisKelamin = jObject.getString(TAG_JENIS_KELAMIN);
String kota = jObject.getString(TAG_JENIS_KOTA);
//masukin semuanya ke variabel
txt_email.setText(emaill);
txt_nama.setText(nama);
txt_alamat.setText(alamat);
txt_no_telp.setText(no_telp);
txt_umur.setText(umur);
txt_tempat_lahir.setText(tempatLahir);
txt_tanggal_lahir.setText(tglLahir);
txt_jumlah_peliharaan.setText(jlhPeliharaan);
txt_warna_favorit.setText(warna);
if(jenisKelamin.equals("1")){
txt_jenis_kelamin.setText("Pria");
} else {
txt_jenis_kelamin.setText("Wanita");
}
txt_id_kota.setText(kota);
}
}catch (JSONException ex){
ex.printStackTrace();
}
return null;
Sometimes it works, sometimes it doesn't.
I've checked my logcat, the json.toString() is working but I can't set all the text to the TextView.
In onCreate() I've been initializing them all:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.tab_profile);
//textview
txt_email = (TextView) findViewById(R.id.txt_email);
txt_nama = (TextView) findViewById(R.id.txt_nama);
txt_alamat = (TextView) findViewById(R.id.txt_alamat);
txt_no_telp = (TextView) findViewById(R.id.txt_no_telp);
txt_umur = (TextView) findViewById(R.id.txt_umur);
txt_tempat_lahir = (TextView) findViewById(R.id.txt_tempat_lahir);
txt_tanggal_lahir = (TextView) findViewById(R.id.txt_tanggal_lahir);
txt_jumlah_peliharaan = (TextView) findViewById(R.id.txt_jumlah_peliharaan);
txt_jenis_kelamin = (TextView) findViewById(R.id.txt_jenis_kelamin);
txt_warna_favorit = (TextView) findViewById(R.id.txt_warna_favorit);
txt_id_kota = (TextView) findViewById(R.id.txt_id_kota);
//button
buttonLogout = (Button) findViewById(R.id.buttonLogout);
buttonLogout.setOnClickListener(new android.view.View.OnClickListener() {
#Override
public void onClick(View v) {
prefs = getSharedPreferences("login", Context.MODE_PRIVATE);
editor = prefs.edit();
editor.clear();
editor.commit();
Intent backToLogin = new Intent(Profile.this,Login.class);
startActivity(backToLogin);
finish();
}
});
btnEditProfil = (Button) findViewById(R.id.btnEditProfil);
btnEditProfil.setOnClickListener(new android.view.View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intentEdit = new Intent(getApplicationContext(),EditProfile.class);
intentEdit.putExtra("emailMember", email);
startActivity(intentEdit);
}
});
btnPeliharaan = (Button) findViewById(R.id.btnPeliharaan);
btnPeliharaan.setOnClickListener(new android.view.View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intentPeliharaan = new Intent(getApplicationContext(),ShowPeliharaan.class);
startActivity(intentPeliharaan);
}
});
//nagmbil email
Intent intent = getIntent();
email = intent.getStringExtra("emailMember");
new LoadMember().execute();
}
Write your AsyncTask class like this:
private class MyAsyncTask extends AsyncTask<String, Void, String>{
#Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
List<NameValuePair> paramss = new ArrayList<NameValuePair>();
paramss.add(new BasicNameValuePair(TAG_EMAIL, email));
//getting JSON string from url
JSONObject json = parser.makeHttpRequest(url_get_one_member, "POST",paramss);
Log.d("Ambil Member",json.toString());
return json.toString();
}
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
JSONObject json=new JSONObject(result);
try{
int success = json.getInt(TAG_SUCCESS);
if(success == 1){
member = json.getJSONArray(TAG_MEMBER);
JSONObject jObject = member.getJSONObject(0);
String emaill = jObject.getString(TAG_EMAIL);
String nama = jObject.getString(TAG_NAMA);
String alamat = jObject.getString(TAG_ALAMAT);
String no_telp = jObject.getString(TAG_NO_TELP);
String umur = jObject.getString(TAG_UMUR);
String tempatLahir = jObject.getString(TAG_TEMPAT_LAHIR);
String tglLahir = jObject.getString(TAG_TANGGAL_LAHIR);
String jlhPeliharaan = jObject.getString(TAG_JUMLAH_PELIHARAAN);
String warna = jObject.getString(TAG_WARNA_FAVORIT);
String jenisKelamin = jObject.getString(TAG_JENIS_KELAMIN);
String kota = jObject.getString(TAG_JENIS_KOTA);
//masukin semuanya ke variabel
txt_email.setText(emaill);
txt_nama.setText(nama);
txt_alamat.setText(alamat);
txt_no_telp.setText(no_telp);
txt_umur.setText(umur);
txt_tempat_lahir.setText(tempatLahir);
txt_tanggal_lahir.setText(tglLahir);
txt_jumlah_peliharaan.setText(jlhPeliharaan);
txt_warna_favorit.setText(warna);
if(jenisKelamin.equals("1")){
txt_jenis_kelamin.setText("Pria");
} else {
txt_jenis_kelamin.setText("Wanita");
}
txt_id_kota.setText(kota);
}
}catch (JSONException ex){
ex.printStackTrace();
}
}
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
}
}
I created simple application which would login to DB and get data from it. But now I found a problem: If you in the first time write wrong login data and try to login second time it won't work. You have to restart it.
I think there is a problem in this code: EDITED
public class MyMoodleApplicationActivity extends Activity {
/** Called when the activity is first created. */
EditText username;
EditText password;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
username = (EditText)findViewById(R.id.username);
password = (EditText)findViewById(R.id.password);
final Button loginButton = (Button)findViewById(R.id.login);
loginButton.setOnClickListener(loginListener);
final Button clearButton = (Button)findViewById(R.id.clear);
clearButton.setOnClickListener(clearListener);
}
private OnClickListener loginListener = new OnClickListener(){
public void onClick(View v){
String usr = username.getText().toString();
String psw = password.getText().toString();
System.out.println("Username: "+usr);
System.out.println("Password: "+psw);
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("usern",""+usr));
nameValuePairs.add(new BasicNameValuePair("passw",""+psw));
InputStream is = null;
String result = "";
//http post
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://ik.su.lt/*****");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
}catch(Exception e){
Log.e("log_tag", "Error in http connection "+e.toString());
}
//convert response to string
try{
BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result=sb.toString();
}catch(Exception e){
Log.e("log_tag", "Error converting result "+e.toString());
}
String usernameFromDB = "";
String firstnameFromDB = "";
String lastnameFromDB = "";
String emailFromDB = "";
String phoneFromDB = "";
String skypeFromDB = "";
String cityFromDB = "";
String descriptionFromDB = "";
try{
JSONArray jArray = new JSONArray(result);
for(int i=0;i<jArray.length();i++){
JSONObject json_data = jArray.getJSONObject(i);
usernameFromDB = json_data.getString("username");
firstnameFromDB = json_data.getString("firstname");
lastnameFromDB = json_data.getString("lastname");
emailFromDB = json_data.getString("email");
phoneFromDB = json_data.getString("phone1");
skypeFromDB = json_data.getString("skype");
cityFromDB = json_data.getString("city");
descriptionFromDB = json_data.getString("description");
System.out.println(usernameFromDB+ " " + firstnameFromDB+" "+lastnameFromDB+" "
+ emailFromDB + " " + phoneFromDB +" " + skypeFromDB+ " " + cityFromDB + " "+
descriptionFromDB);
}
}
catch(JSONException e){
AlertDialog alertDialog = new AlertDialog.Builder(MyMoodleApplicationActivity.this).create();
alertDialog.setTitle("Klaida!");
alertDialog.setMessage("Toks vartotojas neegzistuoja");
alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
return;
}
});
alertDialog.show();
Log.e("log_tag", "Error parsing data "+e.toString());
}
if(usr.length()== 0){
AlertDialog alertDialog = new AlertDialog.Builder(MyMoodleApplicationActivity.this).create();
alertDialog.setTitle("Klaida!");
alertDialog.setMessage("Jūs neįvedėte slapyvardžio");
alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
return;
}
});
alertDialog.show();
}
else if(psw.length()==0){
AlertDialog alertDialog = new AlertDialog.Builder(MyMoodleApplicationActivity.this).create();
alertDialog.setTitle("Klaida!");
alertDialog.setMessage("Jūs neįvedėte slaptažodžio");
alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
return;
}
});
alertDialog.show();
}
else if (usr.equals(usernameFromDB)){
Intent in = new Intent(getApplicationContext(), LoggedUser.class);
in.putExtra("firstname", firstnameFromDB);
in.putExtra("lastname", lastnameFromDB);
in.putExtra("email", emailFromDB);
in.putExtra("phone1", phoneFromDB);
in.putExtra("skype", skypeFromDB);
in.putExtra("city", cityFromDB);
in.putExtra("description", descriptionFromDB);
startActivity(in);
finish();
}
}};
private OnClickListener clearListener = new OnClickListener(){
#Override
public void onClick(View v){
username.setText("");
password.setText("");
}
};
In these if statements I check if username and password you enter is empty username is not equal to the one in database.
How to rewrite the code that it would work?
Edited:
I have user john in DB but if I write John in login field and press login button it won't say that there is not the John user. And in LogCat I see that json stream is readed. Is there a way to set up a rule that upercase and lowercase letters would be different?