Something Strange at my android code - java

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();
}
}

Related

android image is displayed the old one instead of new one when image is uploaded with same name

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.

Android calling two functions in a webservices

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

Spinner not loading data; log cat displays "Attempted to finish an input event but the input event receiver has already been disposed"

When the splash activity launches, the next acivity users login in. usernames and passwords are stored in mysql db. the link is properly establish but Enob_login activity
tells me to check my internet connection yet when i run the ipaddress
on my pc browser (http://192.168.1.11/EnoticeWeb/DB_Enob_Frame.php) i can view the json printout:
[{"0":"1","cnb_id":"1","1":"Admin","cnb_name":"Admin","2":"admin","cnb_pwd":"admin"},
{"0":"2","cnb_id":"2","1":"Hod","cnb_name":"Hod","2":"hod","cnb_pwd":"hod"},
{"0":"3","cnb_id":"3","1":"Staff","cnb_name":"Staff","2":"staff","cnb_pwd":"staff"},
{"0":"4","cnb_id":"4","1":"Student","cnb_name":"Student","2":"student","cnb_pwd":"student"}];
Please help me out!!!!!!!!!!
this is my NetConnection.java codes
public class NetConnection extends Activity {
private SharedPreferences prefs;
private String prefName = "report";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
try {
prefs = getSharedPreferences(prefName, MODE_PRIVATE);
String net_ip=prefs.getString("ip", "http://192.168.1.11/enoticeweb/");
URL url = new URL(net_ip);
executeReq(url);
SharedPreferences.Editor editor = prefs.edit();
editor.putInt("connection", 1);
editor.commit();
finish();
startActivity(new Intent(NetConnection.this,Enob_Login.class));
}
catch(Exception e)
{
Toast.makeText(getApplicationContext(), "Check Network Connection " +
"and IP Address ", Toast.LENGTH_LONG).show();
SharedPreferences.Editor editor = prefs.edit();
editor.putInt("connection", 0);
editor.commit();
finish();
startActivity(new Intent(NetConnection.this,Enob_Login.class));
}
}
public void executeReq(URL urlObject) throws IOException {
HttpURLConnection conn = null;
conn = (HttpURLConnection) urlObject.openConnection();
conn.setReadTimeout(30000);//milliseconds
conn.setConnectTimeout(3500);//milliseconds
conn.setRequestMethod("GET");
conn.setDoInput(true);
// Start connect
conn.connect();
InputStream response =conn.getInputStream();
Log.d("Response:", response.toString());
}
}
and my Enob_login.java codes
public class Enob_Login extends Activity {
Spinner Spinn_Frame;
EditText Edit_Frame_Pwd;
Button But_Go;
List<String> List_Frame, List_Frame_Pwd, List_cnbid;
String Str_Frame_Pwd, Str_Alert_Msg, Str_Alert_Title;
int Int_Frame_Pos;
InputStream is=null;
String result=null;
String line=null;
String IP_Address;
private SharedPreferences prefs;
private String prefName = "report";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.enob_login);
prefs = getSharedPreferences(prefName, MODE_PRIVATE);
int Conn_Check = prefs.getInt("connection", 100);
if(Conn_Check == 0)
{
AlertDialog.Builder Alert_Conn_Error = new AlertDialog.Builder(Enob_Login.this);
Alert_Conn_Error.setMessage("Check your Internet Connection..");
Alert_Conn_Error.setTitle("Connection Error");
Alert_Conn_Error.setPositiveButton("Ok", new OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
finish();
}
});
Alert_Conn_Error.show();
}
else {
initialise_variables();
ArrayAdapter<String> adp = new ArrayAdapter<String>
(this, android.R.layout.simple_expandable_list_item_1, List_Frame);
adp.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
Spinn_Frame.setAdapter(adp);
Int_Frame_Pos = 0;
Spinn_Frame.setSelection(Int_Frame_Pos);
Str_Frame_Pwd = List_Frame_Pwd.get(Int_Frame_Pos).toString();
Spinn_Frame.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
// TODO Auto-generated method stub
Int_Frame_Pos = arg2;
Str_Frame_Pwd = List_Frame_Pwd.get(Int_Frame_Pos).toString();
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
But_Go.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if(Edit_Frame_Pwd.getText().toString().equalsIgnoreCase("")) {
Str_Alert_Msg = "Enter Password !!!";
Str_Alert_Title = "Error";
alert_method();
}
else {
if(Edit_Frame_Pwd.getText().toString().equals(Str_Frame_Pwd)) {
if(Int_Frame_Pos == 0) {
save();
}
if(Int_Frame_Pos == 1) {
save();
}
if(Int_Frame_Pos == 2) {
save();
}
if(Int_Frame_Pos == 3) {
save();
}
}
else {
Str_Alert_Msg = "Wrong Password !!!";
Str_Alert_Title = "Error";
alert_method();
}
}
}
private void save() {
// TODO Auto-generated method stub
prefs = getSharedPreferences(prefName, MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
//---save the values in the EditText view to preferences---
editor.putInt("cnb_id",
Integer.parseInt(List_cnbid.get(Int_Frame_Pos).toString()));
//---saves the values---
editor.commit();
finish();
Intent i = new Intent(Enob_Login.this, User_Login.class);
startActivity(i);
Edit_Frame_Pwd.setText(null);
}
});
}
}
public void initialise_variables() {
Spinn_Frame = (Spinner) findViewById(R.id.spinner1);
Edit_Frame_Pwd = (EditText) findViewById(R.id.editText1);
But_Go = (Button) findViewById(R.id.button1);
List_Frame = new ArrayList<String>();
List_Frame_Pwd = new ArrayList<String>();
List_cnbid = new ArrayList<String>();
prefs = getSharedPreferences(prefName, MODE_PRIVATE);
IP_Address = prefs.getString("ip", "http://192.168.1.11/enoticeweb/");
DB_Enob_Frame();
}
public void DB_Enob_Frame() {
// TODO Auto-generated method stub
try
{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(IP_Address + "DB_Enob_Frame.php");
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
}
catch(Exception e)
{
Log.e("DB_Enob_Frame", e.toString());
}
try
{
BufferedReader reader = new BufferedReader
(new InputStreamReader(is,"iso-8859-1"),8);
StringBuilder sb = new StringBuilder();
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
is.close();
result = sb.toString();
}
catch(Exception e)
{
Log.e("DB_Enob_Frame", e.toString());
}
try
{
JSONArray jarray = new JSONArray(result);
JSONObject jobj = null;
for(int i=0; i<jarray.length(); i++) {
jobj = jarray.getJSONObject(i);
List_Frame.add(jobj.getString("cnb_name"));
List_Frame_Pwd.add(jobj.getString("cnb_pwd"));
List_cnbid.add(String.valueOf(jobj.getInt("cnb_id")));
}
prefs = getSharedPreferences(prefName, MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
editor.putString("ip", IP_Address);
editor.commit();
}
catch(Exception e)
{
Log.e("DB_Enob_Frame", e.toString());
}
}
public void alert_method() {
AlertDialog.Builder alert = new AlertDialog.Builder(Enob_Login.this);
alert.setMessage(Str_Alert_Msg);
alert.setTitle(Str_Alert_Title);
alert.setPositiveButton("OK", null);
alert.show();
Edit_Frame_Pwd.setText(null);
}
#Override
public void onBackPressed() {
// TODO Auto-generated method stub
finish();
}
}

ANDROID: Filter Listview data from PHP JSON using LAZYLIST

Im currently developing a mobile ordering app, and im using listview from https://github.com/thest1/LazyList for the summary of my orders but my problem is that all data of ORDERS from my database (Mysql) is showing.
I want to show only the orders per Customer ID
heres the sample image
-- > http://postimg.org/image/dnayd433x/
OrderSum.java
**OrderSum.java
public class OrderSum extends Activity{
ListView list;
TextView id; //// ver - id
TextView name; //// name - name
TextView quan; //// api - desc
TextView price; //// price
TextView order_num; //// price
TextView cust_num; //// price
ImageView image;
TextView items;
TextView empty;
TextView home_ornum;
TextView cust_name;
ImageButton addOrder;
ImageButton proceed;
DigitalClock time;
TextView os;
TextView o_total;
// Declare Variables
JSONObject jsonobject;
JSONArray jsonarray;
ListView listview;
LvOrderSumAdapter adapter;
ProgressDialog mProgressDialog;
ArrayList<HashMap<String, String>> arraylist;
static String ID = "id";
static String NAME = "ord_name";
static String PRICE = "ord_price";
static String QTY = "ord_qty";
static String CUSTID = "customer_id";
static String ORDER = "ord_num";
static String PXQ = "price_x_quan";
static String IMAGE = "image";
static String OR = "text_ordernumber";
static String ON = "text_name";
static String TP = "t_price";
///////////////////////
#SuppressLint({ "SimpleDateFormat", "NewApi" })
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.order_summary);
// Execute DownloadJSON AsyncTask
new DownloadJSON().execute();
/**Unique ID / Customer Id***/
DatabaseHandler db = new DatabaseHandler(getApplicationContext());
/**
* Hashmap to load data from the Sqlite database
**/
HashMap user = new HashMap();
user = db.getUserDetails();
final TextView unique_id = (TextView) findViewById(R.id.o_custnum);
unique_id.setText((CharSequence) user.get("uid"));
/**END**/
/** DATE VIEW***/
TextView h_date = (TextView) findViewById(R.id.o_date);
Calendar c = Calendar.getInstance();
SimpleDateFormat format1;
format1 = new SimpleDateFormat("MMMM dd,yyyy");
// format2 = new SimpleDateFormat("dd-MM-yyyy-HH-mm-ss");
h_date.setText(format1.format(c.getTime()) );
/** END DATE VIEW***/
cust_name = (TextView) findViewById(R.id.DisplaycustName);
home_ornum = (TextView) findViewById(R.id.Displayordernum);
time = (DigitalClock) findViewById(R.id.o_time);
Intent myIntent = getIntent();
home_ornum.setText(myIntent.getStringExtra("text_ordernumber")); //order number is the TextView
cust_name.setText(myIntent.getStringExtra("text_name")); //tv is the TextView
items= (TextView) findViewById(R.id.DisplayTotalItems);
/***************Custom Font***/
Typeface myCustomFont = Typeface.createFromAsset(getAssets(), "fonts/MavenPro.otf");
cust_name.setTypeface(myCustomFont);
home_ornum.setTypeface(myCustomFont);
time.setTypeface(myCustomFont);
h_date.setTypeface(myCustomFont);
/***************Custom Font**************/
addOrder = (ImageButton) findViewById(R.id.btn_add);
addOrder.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent myIntent = new Intent(OrderSum.this,
Categories.class);
startActivity(myIntent);
overridePendingTransition(R.anim.slide_in_left, R.anim.slide_out_left);
}
});
/***************************PROCEED BUTTON***************************/
proceed = (ImageButton) findViewById(R.id.btn_proceed);
proceed.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent myIntent = new Intent(OrderSum.this,
OrderInformation.class);
startActivity(myIntent);
// uniq id , order no , date , name
// final TextView d_date = (TextView) findViewById(R.id.o_date);
Intent ord_in = new Intent ( OrderSum.this, OrderInformation.class );
ord_in.putExtra ( "text_order", home_ornum.getText().toString() );
// ord_in.putExtra ( "text_date", d_date.getText().toString() );
ord_in.putExtra ( "text_custName", cust_name.getText().toString() );
ord_in.putExtra ( "text_items", items.getText().toString() );
startActivity(ord_in);
overridePendingTransition(R.anim.slide_in_left, R.anim.slide_out_left);
}
});
/***************************PROCEED BUTTON***************************/
/**for the ROOF2**/
final ActionBar actionBar = getActionBar();
BitmapDrawable background = new BitmapDrawable
(BitmapFactory.decodeResource(getResources(), R.drawable.roof2));
///background.setTileModeX(android.graphics.Shader.TileMode.REPEAT);
actionBar.setBackgroundDrawable(background);
/**end for the ROOF2**/
} /// end of OnCreate
#Override
public void onBackPressed() {
super.onBackPressed();
/*Intent myIntent = new Intent(OrderSum.this,
Home.class);
startActivity(myIntent);*/
TextView on = (TextView) findViewById(R.id.Displayordernum);
Intent home_in = new Intent ( OrderSum.this, Home.class );
home_in.putExtra ( "text_ordernumber", on.getText().toString() );
startActivity(home_in);
overridePendingTransition(R.anim.slide_in_left, R.anim.slide_out_left);
}
// DownloadJSON AsyncTask
private class DownloadJSON extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Create a progressdialog
mProgressDialog = new ProgressDialog(OrderSum.this);
// Set progressdialog title
mProgressDialog.setTitle("Your orders");
// Set progressdialog message
mProgressDialog.setMessage("Loading...");
mProgressDialog.setIndeterminate(false);
// Show progressdialog
mProgressDialog.show();
}
#Override
protected Void doInBackground(Void... params) {
TextView custname = (TextView) findViewById(R.id.DisplaycustName);
TextView homeornum = (TextView) findViewById(R.id.Displayordernum);
Intent home_in = getIntent();
homeornum.setText(home_in.getStringExtra("text_ordernumber")); //tv is the TextView
custname.setText(home_in.getStringExtra("text_name")); //name is the TextView
// Create an array
arraylist = new ArrayList<HashMap<String, String>>();
// Retrieve JSON Objects from the given URL address
JSONObject jsonobject = JSONfunctions.getJSONfromURL("http://192.168.43.52/MMOS/api/ordershow.php") ;
// jsonobject = JSONfunctions.getJSONfromURL( //192.168.43.52 /// 10.0.2.2
// ordershow, "GET", params);
//jsonobject = JSONfunctions.getJSONfromURL(,)
try {
// Locate the array name in JSON==
jsonarray = jsonobject.getJSONArray("orders");
for (int i = 0; i < jsonarray.length(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
jsonobject = jsonarray.getJSONObject(i);
// Retrive JSON Objects
/* from db orders = id,ord_name,ord_desc,
ord_price,ord_qty,customer_id,ord_num,price_x_quan , image jsonobjecy = from db*/
map.put("id", jsonobject.getString("id"));
map.put("ord_name", jsonobject.getString("ord_name"));
map.put("ord_price", jsonobject.getString("ord_price"));
map.put("ord_qty", jsonobject.getString("ord_qty"));
map.put("customer_id", jsonobject.getString("customer_id"));
map.put("ord_num", jsonobject.getString("ord_num"));
map.put("price_x_quan", jsonobject.getString("price_x_quan"));
map.put("image", jsonobject.getString("image"));
map.put("text_ordernumber",home_in.getStringExtra("text_ordernumber"));
map.put("text_name",home_in.getStringExtra("text_name"));
// Set the JSON Objects into the array
arraylist.add(map);
}
} catch (JSONException e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void args) {
// Locate the listview in listview_main.xml
listview = (ListView) findViewById(R.id.listOrderSummary);
// Pass the results into ListViewAdapter.java
adapter = new LvOrderSumAdapter(OrderSum.this, arraylist);
// Set the adapter to the ListView
listview.setAdapter(adapter);
listview.getAdapter().getCount();
String count = ""+listview.getAdapter().getCount();
items.setText(count);
// Close the progressdialog
mProgressDialog.dismiss();
}
} **
and for the JSONFUNCTION
** public class JSONfunctions {
public static JSONObject getJSONfromURL(String url) {
InputStream is = null;
String result = "";
JSONObject jArray = null;
// Download JSON data from URL
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
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());
}
try {
jArray = new JSONObject(result);
} catch (JSONException e) {
Log.e("log_tag", "Error parsing data " + e.toString());
}
return jArray;
}
and the PHP CODE
<?php
mysql_connect('localhost','root','')or die ('No Connection');
mysql_select_db('dbmoms');
//$o_od = $_GET['text_ordernumber'];
$sql ="SELECT * FROM orders"; // WHERE ord_num ='$o_od' "; //WHERE ord_num = '$ordnum'
$result = mysql_query($sql);
while($row = mysql_fetch_assoc($result)){
$arr['orders'][]= $row;
}
$json = json_encode($arr);
$json_encoded_string = json_encode($arr);
$json_encoded_string = str_replace("\\/", '/', $json_encoded_string);
echo $json_encoded_string;
?>
I hope that you can help me :)
thanks in advance. :)

JSON Query Does Not Update TextView

I have 3 textviews which I am attempting to update with data pulled via JSON - I'm not getting any errors with what I've built so far - but the textviews (nameTv, contentTv and publishedTv) don't seem to update with the data from my JSON query.
public class Player extends YouTubeBaseActivity implements
YouTubePlayer.OnInitializedListener {
public static final String API_KEY = "XXXXXXXXXXXXXXXXXXXXX";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.player);
String title = getIntent().getStringExtra("title");
String uploader = getIntent().getStringExtra("uploader");
String viewCount = getIntent().getStringExtra("viewCount");
TextView titleTv = (TextView) findViewById(R.id.titleTv);
TextView uploaderTv = (TextView) findViewById(R.id.uploaderTv);
TextView viewCountTv = (TextView) findViewById(R.id.viewCountTv);
titleTv.setText(title);
uploaderTv.setText("by" + uploader + " |");
viewCountTv.setText(viewCount + " views");
YouTubePlayerView youTubePlayerView = (YouTubePlayerView) findViewById(R.id.youtubeplayerview);
youTubePlayerView.initialize(API_KEY, this);
GetYouTubeUserCommentsTask task = new GetYouTubeUserCommentsTask(null, viewCount);
task.execute();
}
#Override
public void onInitializationFailure(Provider provider,
YouTubeInitializationResult result) {
Toast.makeText(getApplicationContext(), "onInitializationFailure()",
Toast.LENGTH_LONG).show();
}
#Override
public void onInitializationSuccess(Provider provider,
YouTubePlayer player, boolean wasRestored) {
if (!wasRestored) {
String video_id = getIntent().getStringExtra("id");
player.loadVideo(video_id);
}
}
public final class GetYouTubeUserCommentsTask extends
AsyncTask<Void, Void, Void> {
public static final String LIBRARY = "CommentsLibrary";
private final Handler replyTo;
private final String username;
String video_id = getIntent().getStringExtra("id");
public GetYouTubeUserCommentsTask(Handler replyTo, String username) {
this.replyTo = replyTo;
this.username = username;
}
#Override
protected Void doInBackground(Void... arg0) {
try {
HttpClient client = new DefaultHttpClient();
HttpUriRequest request = new HttpGet(
"http://gdata.youtube.com/feeds/api/videos/"
+ video_id
+ "/comments?v=2&alt=json&start-index=1&max-results=50&prettyprint=true");
HttpResponse response = client.execute(request);
String jsonString = StreamUtils.convertToString(response
.getEntity().getContent());
JSONObject json = new JSONObject(jsonString);
JSONArray jsonArray = json.getJSONObject("data").getJSONArray(
"items");
List<Comments> comments = new ArrayList<Comments>();
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
String name = jsonObject.getString("name");
String content = jsonObject.getString("content");
String published = jsonObject.getString("published");
comments.add(new Comments(name, content, published));
TextView nameTv = (TextView) findViewById(R.id.name);
nameTv.setText(jsonObject.getString("name"));
TextView contentTv = (TextView) findViewById(R.id.content);
contentTv.setText(jsonObject.getString("content"));
TextView publishedTv = (TextView) findViewById(R.id.published);
publishedTv.setText(jsonObject.getString("published"));
}
CommentsLibrary lib = new CommentsLibrary(username, comments);
Bundle data = new Bundle();
data.putSerializable(LIBRARY, lib);
Message msg = Message.obtain();
msg.setData(data);
replyTo.sendMessage(msg);
} catch (ClientProtocolException e) {
Log.e("Feck", e);
} catch (IOException e) {
Log.e("Feck", e);
} catch (JSONException e) {
Log.e("Feck", e);
}
return null;
}
#Override
protected void onPostExecute(Void result) {
}
}
}
You can not access the UI in doInBackground() -- please see the documentation. You will need to deliver the results to onPostExecute() and handle your UI updates there.

Categories

Resources