// I have already jSON file when i called this method its given null value on it.
new load_customername().execute();
Use this method to call below class
public class load_customername extends AsyncTask<String, String, String> {
#Override
protected String doInBackground(String... args) {
//String i = args[0];
List<NameValuePair> params = new ArrayList<NameValuePair>();
// params.add(new BasicNameValuePair(TAG_Customer_Name, i));
JSONObject json = jParser.makeHttpRequest(url_get_customername, "GET", params);
try {
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
}
}
AsyncTask runs in worker thread, you won't get response instantly. Use onPostExecute with callBack to read the response.
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 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.
I need some help with taking results from doinbackground to onpostexecute. The results are in the form of JSONArray. I want to populate two textviews in the UI through onpostexecute. There is no error in the code but nothing happens as it seems inpostexecute is not getting called. Please help. I have looked at several similar questions here and tried many things but unable to get it to work..thanks in advance. Please note private static final String TAG_LATEST_SCORES = "cricket_scores";
class PostScores extends AsyncTask<JSONArray, Void, JSONArray> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(NewScoreupdatescricketActivity.this);
pDialog.setMessage("Posting LiveScore Updates..");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
/**
* Creating product
* */
protected JSONArray doInBackground(JSONArray... args) {
String runs1 = runs.getText().toString();
String wicket1 = wicket.getText().toString();
String overs1 = over.getText().toString();
String rr1 = rr.getText().toString();
String team_name = null;
String bat1;
if (innings.isChecked() == false) {
bat1 = "1";
team_name = bat.getText().toString();
} else {
bat1 = "2";
team_name = bat.getText().toString();
}
if (rr1.equals("NA")) {
rr1 = "0";
}
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("runs", runs1));
params.add(new BasicNameValuePair("wickets", wicket1));
params.add(new BasicNameValuePair("id", id1));
params.add(new BasicNameValuePair("overs", overs1));
params.add(new BasicNameValuePair("rr", rr1));
params.add(new BasicNameValuePair("bat", bat1));
params.add(new BasicNameValuePair("team_name", team_name));
// getting JSON Object
// Note that create product url accepts POST method
JSONObject json = jsonParser.makeHttpRequest(url_create_product,
"POST", params);
// check log cat fro response
Log.d("Create Response", json.toString());
// check for success tag
try {
int success = json.getInt(TAG_SUCCESS);
pDialog.dismiss();
if (success == 1) {
latest_scores = json.getJSONArray(TAG_LATEST_SCORES);
} else {
}
} catch (JSONException e) {
e.printStackTrace();
}
pDialog.dismiss();
return latest_scores;
}
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(JSONArray latest_sc) {
// dismiss the dialog once done
try {
for (int i = 0; i < latest_sc.length(); i++) {
JSONObject c = latest_sc.getJSONObject(i);
String wickets = c.getString(TAG_WICKETS);
String runs = c.getString(TAG_RUNS);
score_inngs1.setText(wickets + runs);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
Check your brackets. After your definition of doInBackground, you have an extra bracket - that one closes off your PostScores class, so your onPostExecute method is defined as a member of whatever class is enclosing PostScores, if any.
Also, you'll need to #Override the AsyncTask methods to provide your own implementation.
I am having a scenario in which I am calling asynctask in onclicklistener of button. In post execute method of asynctask I am adding values in arraylist which I want to return to the method calling asynctask
This is my asynctask
public class FetchtopTask extends AsyncTask<String, String, String>{
#Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
try {
String getitemcode=params[0];
// Building Parameters
ArrayList<NameValuePair> params1 = new ArrayList<NameValuePair>();
params1.add(new BasicNameValuePair("ItemCode",getitemcode));
Log.d("request!", "starting");
response = CustomHttpClient.executeHttpPost("http://10.0.2.2/top.php",params1);
String retstring=response.toString();
Log.d(retstring,"stringggggg");
return retstring;
}
catch(Exception io){
msg = "No Network Connection";
}
return null;
}
#Override
protected void onPostExecute(String sJson) {
try {
JSONArray aJson = new JSONArray(sJson);
for(int i=0;i<aJson.length();i++)
{
JSONObject jsonO = aJson.getJSONObject(i);
top1.add(jsonO.getString("MName"));
top2.add(jsonO.getString("Amount"));
top3.add(jsonO.getString("TaxStruct"));
}
}catch(JSONException e){
msg = "Invalid response";
}
}
}
I want to pass top1,top2,top3 arraylists to calling method
please help me to achieve this.
You may use ArrayList of ArrayLists:
ArrayList<ArrayList<String>> tops= new ArrayList<ArrayList<String>>();
tops.add(top1);
tops.add(top2);
tops.add(top3);
and
return tops;
hey Just call AsyncTask in btn Click
and in post execute method
call another method which will use that Array which is created in post Execute.
#Override
protected void onPostExecute(String sJson) {
try {
JSONArray aJson = new JSONArray(sJson);
for(int i=0;i<aJson.length();i++)
{
JSONObject jsonO = aJson.getJSONObject(i);
top1.add(jsonO.getString("MName"));
top2.add(jsonO.getString("Amount"));
top3.add(jsonO.getString("TaxStruct"));
anotherMethod(top);
}
}catch(JSONException e){
msg = "Invalid response";
}
}
I am communicating with a database in php mysql travez to display results in a ListView, but I'm trying to implement a ExeptionConnection for when 3G or WIFI but the application can not connect, return to previous Activity and show a Toast. but not how to implement it in my code, I could only implement JsonExeption.
This is my code:
protected String doInBackground(String... args) {
List<NameValuePair> params = new ArrayList<NameValuePair>();
JSONObject json = jParser.makeHttpRequest(url_list_rs, "GET",
params);
Log.d("All Products: ", json.toString());
try {
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
daftar_rs = json.getJSONArray(TAG_DAFTAR_RS);
for (int i = 0; i < list_rs.length(); i++) {
JSONObject c = list_rs.getJSONObject(i);
//Process Code
}
} else {
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
Where url_list_rs is the url of my php. Where I can Implement ExeptionConnection? Can anyone help? Thank Masters!
If you want to create you own exception, you can do:
//create a new Exception class
public class ConnectionException extends Exception {
public ConnectionException(String message){
super(message);
}
}
In your makeHttpRequest method
if(no connection) { //check connection
throw new ConnectionException ("No connection!");
} else { ... }
Finally, and try-catch block
try {
JSONObject json = jParser.makeHttpRequest(url_list_rs, "GET",
params);
catch(ConnectionException ex) {
ex.printStackTrace();
}
Note: I am not sure if this is the best practice.