I really need your help. I am building an Android app that needs a lot of HTTP requests such as logging to the server(check if user is exists or not) and storing the session to the database (user_sessions table), adding, updating and deleting records.
In my Login Activity, I have my AsyncTask (to check if user exits) and other background threads (logs the user session and download user info to database) . This is successful. Next, when I update the user info, it updates successfully. But what if I update using my web app? My should display the newly updated info on my android app. How can I resolve this problem?
This is what I've tried so far:
private void logSessionToServer() {
// TODO Auto-generated method stub
Thread thread = new Thread(){
public void run(){
strUsername = etUsername.getText().toString();
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair( TAG_USERNAME, strUsername ));
// getting JSON Object
// Note it accepts POST method only
JSONObject json = jsonParser.makeHttpRequest(url_log_session,
"POST", params);
// check log cat from response
Log.d("Create Response", json.toString());
// check for success tag
try {
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
Log.d("", "Successfully logged session!");
} else {
// failed
Log.d("", "Not Successful!");
}
} catch (JSONException e) {
e.printStackTrace();
}
}
};
thread.start();
}
/**
* Background Async Task to Create new record
* */
class LoginTask extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(Login.this);
pDialog.setIcon(R.drawable.upload);
pDialog.setTitle("Connecting to server");
pDialog.setMessage("Validating login details..");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
/**
*
* */
protected String doInBackground(String... args) {
strUsername = etUsername.getText().toString();
strPassword = etPassword.getText().toString();
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair( TAG_USERNAME, strUsername ));
params.add(new BasicNameValuePair( TAG_PASSWORD, strPassword ));
// getting JSON Object
// Note it accepts POST method only
JSONObject json = jsonParser.makeHttpRequest(url_login,
"POST", params);
// check log cat from response
Log.d("Create Response", json.toString());
// check for success tag
try {
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
logSessionToServer(); // Save login to server
saveUserInfoToDB(); // Save user info to DB
saveUserloggedIn(); // Save user logged in to preference
savePriestInfoToDB(); // Save priest to DB
Log.d("", "Successful Login!");
Intent i = new Intent(Login.this, MainActivity.class);
startActivity(i);
finish();
} else {
// failed
new Thread()
{
public void run()
{
runOnUiThread(new Runnable()
{
public void run()
{
Toast.makeText(getBaseContext(),
"Not Successful Login", Toast.LENGTH_SHORT).show();
}
});
}
}.start();
Log.d("", "Not Successful Login!");
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String result) {
// dismiss the dialog once done
pDialog.dismiss();
}
}
private void saveUserInfoToDB() {
// TODO Auto-generated method stub
Thread thread = new Thread(){
public void run(){
// Create the array
arraylist = new ArrayList<HashMap<String, String>>();
// Retrieve JSON Objects from the given website URL in JSONfunctions.class
String result = JSONFunctions.getJSONfromURL(url_view_loggedUser_profile);
try {
JSONArray jr = new JSONArray(result);
for(int i=0;i<jr.length();i++)
{
HashMap<String, String> map = new HashMap<String, String>();
jb = (JSONObject)jr.get(i);
map.put(TAG_FIRSTNAME, jb.getString(TAG_FIRSTNAME));
map.put(TAG_MIDDLENAME, jb.getString(TAG_MIDDLENAME));
map.put(TAG_LASTNAME, jb.getString(TAG_LASTNAME));
map.put(TAG_EMAIL, jb.getString(TAG_EMAIL));
map.put(TAG_AGE, jb.getString(TAG_AGE));
map.put(TAG_GENDER, jb.getString(TAG_GENDER));
map.put(TAG_USERNAME, jb.getString(TAG_USERNAME));
map.put(TAG_PASSWORD, jb.getString(TAG_PASSWORD));
map.put(TAG_BARANGAY, jb.getString(TAG_BARANGAY));
map.put(TAG_COMPLETEADDRESS, jb.getString(TAG_COMPLETEADDRESS));
map.put(TAG_CUS_ID, jb.getString(TAG_CUS_ID));
map.put(TAG_REG_DATE, jb.getString(TAG_REG_DATE));
map.put(TAG_BD_MONTH, jb.getString(TAG_BD_MONTH));
map.put(TAG_BD_DATE, jb.getString(TAG_BD_DATE));
map.put(TAG_BD_YEAR, jb.getString(TAG_BD_YEAR));
arraylist.add(map);
String strCusID = jb.getString(TAG_CUS_ID);
String strFname = jb.getString(TAG_FIRSTNAME);
String strMname = jb.getString(TAG_MIDDLENAME);
String strLname = jb.getString(TAG_LASTNAME);
String strEmail = jb.getString(TAG_EMAIL);
String strAge = jb.getString(TAG_AGE);
String strGender = jb.getString(TAG_GENDER);
String strUsername = jb.getString(TAG_USERNAME);
String strPassword = jb.getString(TAG_PASSWORD);
String strBarangay = jb.getString(TAG_BARANGAY);
String strCompleteAddress = jb.getString(TAG_COMPLETEADDRESS);
String strRegDate = jb.getString(TAG_REG_DATE);
String strBDMonth = jb.getString(TAG_BD_MONTH);
String strBDDate = jb.getString(TAG_BD_DATE);
String strBDYear = jb.getString(TAG_BD_YEAR);
try{
dbHelper.insertEntry(strCusID, strFname, strMname, strLname, strEmail,
strAge, strGender, strUsername, strPassword,
strBarangay, strCompleteAddress, strRegDate,
strBDMonth, strBDDate, strBDYear);
Log.d("Response", "Successfully inserted record");
} catch (SQLiteException e) {
Log.d("Response", "Not successful");
}
}
} catch (JSONException e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
}
};
thread.start();
}
private void savePriestInfoToDB() {
// TODO Auto-generated method stub
Thread thread = new Thread(){
public void run(){
// Create the array
arraylist = new ArrayList<HashMap<String, String>>();
// Retrieve JSON Objects from the given website URL in JSONfunctions.class
String result = JSONFunctions.getJSONfromURL(URL_VIEW_PRIESTS);
try {
JSONArray jr = new JSONArray(result);
for(int i=0;i<jr.length();i++)
{
HashMap<String, String> map = new HashMap<String, String>();
jb = (JSONObject)jr.get(i);
map.put(TAG_P_ID, jb.getString(TAG_P_ID));
map.put(TAG_P_FIRSTNAME, jb.getString(TAG_P_FIRSTNAME));
map.put(TAG_P_MIDDLENAME, jb.getString(TAG_P_MIDDLENAME));
map.put(TAG_P_LASTNAME, jb.getString(TAG_P_LASTNAME));
map.put(TAG_P_EMAIL, jb.getString(TAG_P_EMAIL));
map.put(TAG_P_AGE, jb.getString(TAG_P_AGE));
map.put(TAG_P_ADDRESS, jb.getString(TAG_P_ADDRESS));
map.put(TAG_P_CONTACT, jb.getString(TAG_P_CONTACT));
map.put(TAG_P_STATUS, jb.getString(TAG_P_STATUS));
arraylist.add(map);
String strP_ID = jb.getString(TAG_P_ID);
String strP_Fname = jb.getString(TAG_P_FIRSTNAME);
String strP_Mname = jb.getString(TAG_P_MIDDLENAME);
String strP_Lname = jb.getString(TAG_P_LASTNAME);
String strP_Email = jb.getString(TAG_P_EMAIL);
String strP_Age = jb.getString(TAG_P_AGE);
String strP_Address = jb.getString(TAG_P_ADDRESS);
String strP_Status = jb.getString(TAG_P_STATUS);
String strP_Contact = jb.getString(TAG_P_CONTACT);
try{
dbHelper.insertPriest(strP_ID, strP_Fname, strP_Mname,
strP_Lname, strP_Email, strP_Age,
strP_Address, strP_Status, strP_Contact);
Log.d("Response - Priest", "Successfully inserted record");
} catch (SQLiteException e) {
Log.d("Response - Priest", "Not successful");
}
}
} catch (JSONException e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
}
};
thread.start();
}
Feel free to check out my codes and give feedback if this is the best practice for HTTP requests. I am new to Web Services so I really need your help. Any help will be greatly appreciated. Thanks
Well what I just said: you write a thread which downloads user-info every 5 seconds. then it compares the user info downloaded with the user info that is already stored on your device. if there is a difference, an update has been made, and your thread invokes a new download of the updated user info.
Related
protected String doInBackground(String... args) {
String myres = null;
String bot_string = args[0] ;
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("question", bot_string));
JSONObject json = jsonParser.makeHttpRequest(url_pythonwebservice, "GET", params);
// Check your log cat for JSON reponse
Log.d("results: ", json.toString());
try {
myres = json.getString(TAG_BOTRESPONSE);
} catch (JSONException e) {
e.printStackTrace();
}
return myres;
}
protected void onPostExecute(String file_url) {
pDialog.dismiss();
Toast.makeText(getApplicationContext(),file_url , Toast.LENGTH_LONG).show();
//Get reference to textview above in oncreate method
//bot.setText(file_url);
}
if (file_url == "Navigation"){
Intent i = new Intent(Voice.this, MapsActivity.class);
startActivity(i);
}
Toast is printing.I want to call MapsActivity.class if String file_url == "Navigaion" but this is not working if i put inside the onPostExecute. How can i call MapsActivity.class. This is a voice recognition application.
In Java, you should compare two string as,
if(string1.equals(string2))
{
// code block
}
So, for your example, you should change your code like,
if (file_url.equals("Navigation"))
{
// more code follows
}
I need to display the result in android text view that I obtained by json result. I only get the success message when I run the app. I want to get the textview displayed.
Java Code:
JSONObject hay;
// Progress Dialog
private ProgressDialog pDialog;
// JSON parser class
JSONParser jsonParser = new JSONParser();
private static final String LOGIN_URL = "////////////////////// "; // change to the webhost
//testing from a real server:
//private static final String LOGIN_URL = "http://www.yourdomain.com/webservice/login.php";
//JSON element ids from repsonse of php script:
private static final String TAG_SUCCESS = "success";
private static final String TAG_MESSAGE = "message";
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//setup input fields
user = (EditText) findViewById(R.id.user);
txtFname = (TextView) findViewById(R.id.fname);
txtMname = (TextView) findViewById(R.id.lname);
txtLname = (TextView) findViewById(R.id.mname);
//setup buttons
get = (Button) findViewById(R.id.get);
//register listeners
get.setOnClickListener(this);
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
new AttemptLogin().execute();
}
class AttemptLogin extends AsyncTask < String, String, String > {
/**
* Before starting background thread Show Progress Dialog
* */
boolean failure = false;
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Attempt login...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected String doInBackground(String...args) {
// TODO Auto-generated method stub
// Check for success tag
int success;
String username = user.getText().toString();
try {
// Building Parameters
List < NameValuePair > params = new ArrayList < NameValuePair > ();
params.add(new BasicNameValuePair("username", username));
Log.d("request!", "starting");
// getting product details by making HTTP request
JSONObject json = jsonParser.makeHttpRequest(
LOGIN_URL, "POST", params);
// check your log for json response
Log.d("Login attempt", json.toString());
// json success tag
success = json.getInt(TAG_SUCCESS);
if (success == 1) {
Log.d("Login Successful!", json.toString());
//
//Intent i = new Intent(Login.this, MainActivity.class);
//finish();
//startActivity(i);
//finish();
return json.getString(TAG_MESSAGE);
} else {
Log.d("Login Failure!", json.getString(TAG_MESSAGE));
return json.getString(TAG_MESSAGE);
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
// dismiss the dialog once product deleted
pDialog.dismiss();
try {
JSONObject json = null;
JSONObject hay = new JSONObject((Map) json);
JSONArray user = hay.getJSONArray("user");
JSONObject jb = user.getJSONObject(0);
String firstname = jb.getString("firstname");
String middlename = jb.getString("middlename");
String lastname = jb.getString("lastname");
// displaying all data in textview
txtFname.setText("Firstname: " + firstname);
txtMname.setText("Middle Name: " + middlename);
txtLname.setText("Last Name " + lastname);
} catch (Exception e) {
e.printStackTrace();
}
if (file_url != null) {
Toast.makeText(MainActivity.this, file_url, Toast.LENGTH_LONG).show();
}
}
}
PHP Code:
<?php
require('config.inc.php');
if (!empty($_POST)) {
//initial query
$query = "Select last_name, first_name, middle_initial FROM admin where username = :user";
$query_params = array(':user' => $_POST['username']);
//execute query
try {
$stmt = $db -> prepare($query);
$result = $stmt -> execute($query_params);
} catch (PDOException $ex) {
$response["success"] = 0;
$response["message"] = "Database Error!";
die(json_encode($response));
}
// Finally, we can retrieve all of the found rows into an array using fetchAll
$rows = $stmt -> fetchAll();
if ($rows) {
$response["success"] = 1;
$response["message"] = "Post Available!";
$response["user"] = array();
foreach($rows as $row) {
$user = array();
// $user["designation"] = $row["designation"];
$user["middlename"] = $row["middle_initial"];
$user["firstname"] = $row["first_name"];
$user["lastname"] = $row["last_name"];
//update our repsonse JSON data
array_push($response["user"], $user);
}
// echoing JSON response
echo json_encode($response);
} else {
$response["success"] = 0;
$response["message"] = "No user available!";
die(json_encode($response));
}
} else {}
?>
<form action="test.php" method="POST">
Username: <input type="text" name="username">
<input type="submit" value="Submit">
</form>
sorry can't comment but what you getting at post execute from background task is file_url as string which is your param at on post execute......i think if you are getting result all params like first name ,lastName etc then you needed to pass jsonObject at onpost Execute
so you can parse at onPostExecute...your jsonResult and display it in textbox
Problem is in you current code is
txtFname.setText("Firstname: " + firstname);
in which firstName is from
String firstname = jb.getString("firstname");
JSONObject jb= user.getJSONObject(0);
JSONArray user = hay.getJSONArray("user");
JSONObject hay = new JSONObject ((Map) json);
JSONObject json = null;
i have reversed it so you can find problem here json is null so here is problem and pls try logging at each point and let we know so we and you can have exact idea....or give us json format...
the problem is with your this code segment:
JSONObject json = null;
JSONObject hay = new JSONObject((Map) json);
JSONArray user = hay.getJSONArray("user");
JSONObject jb = user.getJSONObject(0);
String firstname = jb.getString("firstname");
String middlename = jb.getString("middlename");
String lastname = jb.getString("lastname");
here what you are doing is: making another JSONObject as
JSONObject json = null;
that is creating a variable with local scope, the local variable will have more priority than global, that you understood. actually you need the json which is created from doInBackgrounnd(). so pass the json from doInBackground to onPostExecute: it is simple,
change the statements:
return json.getString(TAG_MESSAGE); => return json;
return json.getString(TAG_MESSAGE); => return json;
also change the type of doInBackground to JSONObject and avoid making a new local JSONObject and trying to get datafrom that (bcz it is null you initialized with).
JSONObject json = null; //remove this
JSONObject hay = new JSONObject((Map) json); //remove this
JSONArray user = hay.getJSONArray("user"); // change hay to json
also change the
protected void onPostExecute(String file_url)// to protected void onPostExecute(JSONObject json)
EDIT 2
here is your changed code, let me know what you are getting if some errors.
//edited1
public static JSONObject json = null;
// Progress Dialog
private ProgressDialog pDialog;
// JSON parser class
JSONParser jsonParser = new JSONParser();
private static final String LOGIN_URL = "////////////////////// "; // change to the webhost
//testing from a real server:
//private static final String LOGIN_URL = "http://www.yourdomain.com/webservice/login.php";
//JSON element ids from repsonse of php script:
private static final String TAG_SUCCESS = "success";
private static final String TAG_MESSAGE = "message";
private static final String TAG_USER = "user";
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//setup input fields
user = (EditText) findViewById(R.id.user);
txtFname = (TextView) findViewById(R.id.fname);
txtMname = (TextView) findViewById(R.id.lname);
txtLname = (TextView) findViewById(R.id.mname);
//setup buttons
get = (Button) findViewById(R.id.get);
//register listeners
get.setOnClickListener(this);
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
new AttemptLogin().execute();
}
class AttemptLogin extends AsyncTask < String, String, String > {
/**
* Before starting background thread Show Progress Dialog
* */
boolean failure = false;
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Attempt login...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected String doInBackground(String...args) {
// TODO Auto-generated method stub
// Check for success tag
int success;
String username = user.getText().toString();
try {
// Building Parameters
List < NameValuePair > params = new ArrayList < NameValuePair > ();
params.add(new BasicNameValuePair("username", username));
Log.d("request!", "starting");
// getting product details by making HTTP request
// edited2
json = jsonParser.makeHttpRequest(
LOGIN_URL, "POST", params);
// check your log for json response
Log.d("Login attempt", json.toString());
// json success tag
success = json.getInt(TAG_SUCCESS);
if (success == 1) {
Log.d("Login Successful!", json.toString());
//
//Intent i = new Intent(Login.this, MainActivity.class);
//finish();
//startActivity(i);
//finish();
//edited3
return json.getString(TAG_MESSAGE);
//return json;
} else {
Log.d("Login Failure!", json.getString(TAG_MESSAGE));
//edited4
return json.getString(TAG_MESSAGE);
//return json;
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String message) {
// dismiss the dialog once product deleted
pDialog.dismiss();
try {
//JSONObject json = null;
//JSONObject hay = new JSONObject((Map) json);
JSONArray user = json.getJSONArray("user");
JSONObject jb = user.getJSONObject(0);
String firstname = jb.getString("firstname");
String middlename = jb.getString("middlename");
String lastname = jb.getString("lastname");
// displaying all data in textview
txtFname.setText("Firstname: " + firstname);
txtMname.setText("Middle Name: " + middlename);
txtLname.setText("Last Name " + lastname);
} catch (Exception e) {
e.printStackTrace();
}
if (file_url != null) {
Toast.makeText(MainActivity.this, json.getString(TAG_MESSAGE), Toast.LENGTH_LONG).show();
}
}
}
did four changes in total: mentioned as edited# wherever I did. please fins them and make it in your file,
I want to send more than one record of SQLite data to server when my internet connection is come back, i have programmed a broadcast receiver which works when my internet is come back, but it send only one data to server, i want to send all the records of table when internet come back, suggest me that how to pass arguments to async task in for loop, an take each data to params.
public class BroadcastCreateTask extends BroadcastReceiver {
DatabaseHandler db;
public ProgressDialog pDialog;
JSONParser jsonParser=new JSONParser();
private static String url_insert_task= "";
// JSON Node names
private static final String TAG_SUCCESS = "success";
#Override
public void onReceive(Context context, Intent intent) {
db= new DatabaseHandler(context);
boolean status = NetworkUtil.isNetworkAvailable(context);
String s = String.valueOf(status);
if(s.equals("true"))
Toast.makeText(context, "Connected to internet", Toast.LENGTH_LONG).show();
new createTask().execute();
Toast.makeText(context, "data send to server", Toast.LENGTH_SHORT).show();
if(s.equals("false"))
Toast.makeText(context, "Not Connected to internet", Toast.LENGTH_SHORT).show();
}
class createTask extends AsyncTask<String, Void,String>
{
#Override
protected String doInBackground(String... arg0) {
List<Task> tasks = db.getAllContacts();
for(Task t : tasks){
String o = t.getOwner();
String s = t.getSubject();
String st = t.getStartDate();
String dt = t.getDueDate();
String c = t.getContacts();
String sta = t.getStatus();
String p = t.getPriority();
String d = t.getDescription();
ArrayList<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("owner",o));
params.add(new BasicNameValuePair("subject",s));
params.add(new BasicNameValuePair("startdate",st));
params.add(new BasicNameValuePair("duedate",dt));
params.add(new BasicNameValuePair("contacts",c));
params.add(new BasicNameValuePair("status",sta));
params.add(new BasicNameValuePair("priority",p));
params.add(new BasicNameValuePair("description",d));
JSONObject json = jsonParser.makeHttpRequest(url_insert_task, "POST", params);
db.deleteContact(new Task(o,s));
// check log cat for response
Log.d("Create Response", json.toString());
try
{
int success = json.getInt(TAG_SUCCESS);
if(success==1)
{
pDialog.dismiss();
}
} catch (JSONException e)
{
// TODO: handle exception
e.printStackTrace();
}
return null;
}
return null;
} // end of background method
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
}
} // end of async task
}`
You have the statement return null before the closing brace of the for loop. Your loop runs only once and returns, which explains why only one record is being sent.
am working on new reader that is to get news post froma wordpress site to android fone app.
i can get the test(title,date,content) from the json array but i cannot get the image url from the array any ideas
class LoadBrkNews extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(Breaking.this);
pDialog.setMessage("Loading News Feeds...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
/**
* getting breaking JSON
* */
protected String doInBackground(String... args) {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
// getting JSON string from URL
JSONObject json = jsonParser.makeHttpRequest(BREAK_URL, "GET",
params);
// Check your log cat for JSON reponse
Log.d("BREAKING NEWS JSON: ", json.toString());
try {
if (json.getString("status").equalsIgnoreCase("ok")) {
breakFeeds = json.getJSONArray("posts");
//breakImg = json.getJSONArray(TAG_IMAGE_URL);
// looping through All messages
for (int i = 0; i < breakFeeds.length(); i++) {
JSONObject c = (JSONObject) breakFeeds.getJSONObject(i);
// JSONObject forImg = (JSONObject) breakImg.getJSONObject(i);
// Storing each json item in variable
String id = c.getString(TAG_ID);
String title = c.getString(TAG_TITLE);
String content = c.getString(TAG_CONTENT);
String date = c.getString(TAG_DATE);
// remember to remove this line fro production
String urlForImage = c.getString(TAG_IMAGE_URL);
Log.d("attachemtent url",urlForImage);
// Strip off tags
String fcontent = content.replaceAll("<(.*?)\\>"," ");
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_ID, id);
map.put(TAG_TITLE, title);
map.put(TAG_CONTENT, fcontent);
map.put(TAG_DATE, date);
map.put(TAG_IMAGE_URL, urlForImage);
// adding HashList to ArrayList
breakingNewsList.add(map);
ObjectOutput out = new ObjectOutputStream(
new FileOutputStream(tempFile));
String toCache = breakFeeds.toString();
out.writeObject(toCache);
out.close();
Log.d("Write to Cache", "Success");
}
}
} catch (JSONException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
// dismiss the dialog after getting all products
pDialog.dismiss();
// updating UI from Background Thread
runOnUiThread(new Runnable() {
public void run() {
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(Breaking.this,
breakingNewsList, R.layout.imagelayout,
new String[] { TAG_TITLE, TAG_CONTENT, TAG_DATE,
TAG_IMAGE_URL }, new int[] {
R.id.title, R.id.content, R.id.date,R.id.imglink });
// updating listview
setListAdapter(adapter);
}
});
}
}
`
Since your having trouble only with the image url, I guess it can be either
1. Your data is missing the image url
2. TAG_IMAGE_URL is not matching the key in the data.
Try using some json parsing libary to make things easier.
the problem that im having is kind of weird the printstack of the JSON is correct displaying all the element in the table the way that it should the same as for the method String doInBackground(String... args) the problem is in the postExecute method that is displaying the same element in all the element of the listview "the last element in the row of the table to be exact can someone tell me what i did wrong " thank you for your time bellow you will find the class that im talking about thank you
class LoadAllProducts extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(ProDentActivity.this);
pDialog.setMessage("Loading Balance. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
/**
* getting All products from url
* */
protected String doInBackground(String... args) {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
// getting JSON string from URL
JSONObject json = jParser.getJSONFromUrl(balanceURL, "GET", params);
// Check your log cat for JSON reponse
Log.d("All Products: ", json.toString());
try {
// Checking for SUCCESS TAG
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// products found
// Getting Array of Products
amount = json.getJSONArray(TAG_BALANCE);
// looping through All Products
for (int i = 0; i < amount.length(); i++) {
JSONObject c = amount.getJSONObject(i);
// Storing each json item in variable
String amount = c.getString(TAG_AMOUNT);
String createdat = c.getString(TAG_CREATEDAT);
//String userid = c.getString(TAG_USERID);
// adding each child node to HashMap key => value
map.put(TAG_AMOUNT, amount);
map.put(TAG_CREATEDAT, createdat);
//map.put(TAG_USERID , userid);
// adding HashList to ArrayList
amountlist.add(map);
}
} else {
// no balance found
// Launch Add New balance Activity
Intent i = new Intent(getApplicationContext(),
ProDentActivity.class);
// Closing all previous activities
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(String file_url) {
// dismiss the dialog after getting all products
pDialog.dismiss();
// updating UI from Background Thread
runOnUiThread(new Runnable() {
public void run() {
ListAdapter adapter = new SimpleAdapter(
ProDentActivity.this, amountlist,
R.layout.list_item, new String[] { TAG_AMOUNT,TAG_CREATEDAT},
new int[] { R.id.amount, R.id.createdat });
// updating listview
setListAdapter(adapter);
}
});
}
}
JSON:
{"balance":[{"amount":"50000","created_at":"2012-12-15 02:39:13"},{"amount":"50000","created_at":"2012-12-16 15:29:03"},{"amount":"30000","created_at":"2012-12-17 19:38:07"}],"success":1}
...and the method returns
12-18 02:29:05.797: D/All Products:(885): {"success":1,"balance":[{"amount":"50000","created_at":"2012-12-15 02:39:13"},{"amount":"50000","created_at":"2012-12-16 15:29:03"},{"amount":"30000","created_at":"2012-12-17 19:38:07"}]}
problem fixed i found what i have been doing wrong. the problem was that i didn't define my hash map in the method protected String doInBackground(String... args)
i was defining it in the listactivity anw thank you for your time and help
bellow code to be replaced with the old one
try {
// Checking for SUCCESS TAG
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// products found
// Getting Array of Products
amount = json.getJSONArray(TAG_BALANCE);
// looping through All Products
for (int i = 0; i < amount.length(); i++) {
JSONObject c = amount.getJSONObject(i);
// Storing each json item in variable
String amount = c.getString(TAG_AMOUNT);
String createdat = c.getString(TAG_CREATEDAT);
//String userid = c.getString(TAG_USERID);
// adding each child node to HashMap key => value
HashMap<String, String> map = new HashMap<String, String>();
map.put(TAG_AMOUNT, amount);
map.put(TAG_CREATEDAT, createdat);
//map.put(TAG_USERID , userid);
// adding HashList to ArrayList
amountlist.add(map);
}
} else {
// no balance found
// Launch Add New balance Activity
Intent i = new Intent(getApplicationContext(),
ProDentActivity.class);
// Closing all previous activities
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}