Android calling two functions in a webservices - java

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

Related

Database values not updating (Android)

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

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: 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. :)

Something Strange at my android code

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

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