Toast is showed around of 2 times, and Json is returning fine 6 objects.
Idk if its problem of RunOnUiThread (I know that is not good for use in asyntask) or otherthing.
what other way can I use for my variable "mensaje" every time that for put a string in that I can show a Toat, maybe in OnPostExecute.
class asyncMensaje extends AsyncTask<String, String, String> {
#Override
protected String doInBackground(String... params) {
String user = params[0];
ArrayList<NameValuePair> envioDato = new ArrayList<NameValuePair>();
envioDato.add(new BasicNameValuePair("rut", user));
JSONArray jdata2 = post.getserverdata(envioDato, URL_connectFechas);
if (jdata2 != null && jdata2.length() > 0) {
JSONObject json_data; // creamos un objeto JSON
for (int i = 0; i < jdata2.length(); i++) {
try {
json_data = jdata2.getJSONObject(i);
mensaje = json_data.getString("mensaje");
Log.e("Info: ", "" + mensaje);
} catch (JSONException e) {
e.printStackTrace();
}
runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(getApplicationContext(), mensaje, Toast.LENGTH_LONG).show();
}
});
}
}
return null;
}
protected void onPostExecute(String result) {
}
}
The ideal solution in your case is to use onProgressUpdate together with sequencing of Toasts. Refer to this answer for doing the latter.
class asyncMensaje extends AsyncTask<String, String, String> {
#Override
protected String doInBackground(String... params) {
//....
for (int i = 0; i < jdata2.length(); i++) {
//..
publishProgress(mensaje);
}
}
#Override
protected void onProgressUpdate(String... progress) {
//code for showing Toast
}
}
Use onPostExecute method for processing data after getting from webservice in doInBackground instead of using runOnUiThread in doInBackground which run on different Thread. do it as:
#Override
protected String doInBackground(String... params) {
String user = params[0];
ArrayList<NameValuePair> envioDato = new ArrayList<NameValuePair>();
envioDato.add(new BasicNameValuePair("rut", user));
JSONArray jdata2 = post.getserverdata(envioDato, URL_connectFechas);
return jdata2.toString();
}
#Override
protected void onPostExecute(String result) {
JSONArray jdata2=new JSONArray(result);
// parse JSONArray here and show Toast...
}
Related
I have a little problem with make a toast when my table database is null based on parsing json. I mean, when data is no result or no data found then make a toast " Sorry no data found". Any help would be greatly appreciated.
here my code for show the data
private void showEmployee(){
JSONObject jsonObject = null;
ArrayList<HashMap<String,String>> list = new ArrayList<HashMap<String, String>>();
try {
jsonObject = new JSONObject(JSON_STRING);
JSONArray result = jsonObject.getJSONArray(konfigurasi.TAG_JSON_ARRAY);
for(int i = 0; i<result.length(); i++){
JSONObject jo = result.getJSONObject(i);
String id = jo.getString(konfigurasi.TAG_ID);
String nama = jo.getString(konfigurasi.TAG_NAMA);
String pyg = jo.getString(konfigurasi.TAG_PENYELENGGARA);
String tmpt = jo.getString(konfigurasi.TAG_TEMPAT);
String tgl = jo.getString(konfigurasi.TAG_TGL);
String jam = jo.getString(konfigurasi.TAG_JAM);
String email = jo.getString(konfigurasi.TAG_EMAIL);
HashMap<String,String> employees = new HashMap<>();
employees.put(konfigurasi.TAG_ID,id);
employees.put(konfigurasi.TAG_NAMA,nama);
employees.put(konfigurasi.TAG_PENYELENGGARA,pyg);
employees.put(konfigurasi.TAG_TEMPAT,tmpt);
employees.put(konfigurasi.TAG_TGL,tgl);
employees.put(konfigurasi.TAG_JAM,jam);
employees.put(konfigurasi.TAG_EMAIL,email);
list.add(employees);
}
} catch (JSONException e) {
e.printStackTrace();
}
ListAdapter adapter = new MySimpleArrayAdapter(this, list);
listView.setAdapter(adapter);
}
And this for postexcetude code :
private void getJSON(){
class GetJSON extends AsyncTask<Void,Void,String>{
ProgressDialog loading;
#Override
protected void onPreExecute() {
super.onPreExecute();
loading = ProgressDialog.show(TampilSemuaPgw.this,"Mengambil Data","Mohon Tunggu...",false,false);
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
if(s == null || s.length() == 0){
Toast.makeText(getApplicationContext(), "No Data",Toast.LENGTH_LONG).show();
}
// Dismiss the progress dialog
if (loading.isShowing())
loading.dismiss();
JSON_STRING = s;
showEmployee();
}
#Override
protected String doInBackground(Void... params) {
RequestHandler rh = new RequestHandler();
String s = rh.sendGetRequest(konfigurasi.URL_GET_ALL);
return s;
}
}
GetJSON gj = new GetJSON();
gj.execute();
}
Update Code by KeLiuyue :
#Override
protected String doInBackground(Void... params) {
RequestHandler rh = new RequestHandler();
String s = rh.sendGetRequest(konfigurasi.URL_GET_ALL);
return s;
}
#Override
protected void onPostExecute(String s) {
try {
JSONObject jsonObject = new JSONObject(s);
JSONArray jsonArray = jsonObject.getJSONArray("result");
if(jsonArray.length() == 0){
Toast.makeText(getApplicationContext(), "No Data", Toast.LENGTH_LONG).show();
if (loading.isShowing()){
loading.dismiss();
}
return;
}
} catch (JSONException e) {
e.printStackTrace();
}
Log.e("TAG",s);
// Dismiss the progress dialog
if (loading.isShowing())
loading.dismiss();
JSON_STRING = s;
showEmployee();
}
Try this in your code .
#Override
protected String doInBackground(Void... params) {
RequestHandler rh = new RequestHandler();
String s = rh.sendGetRequest(konfigurasi.URL_GET_ALL);
return s;
}
#Override
protected void onPostExecute(String s) {
// edited here
try {
JSONObject jsonObject = new JSONObject(s);
JSONArray jsonArray = jsonObject.getJSONArray("result");
if(jsonArray.length() == 0){
Toast.makeText(getApplicationContext(), "No Data", Toast.LENGTH_LONG).show();
if (loading.isShowing()){
loading.dismiss();
}
return;
}
} catch (JSONException e) {
e.printStackTrace();
}
Log.e("TAG",s);
// Dismiss the progress dialog
if (loading.isShowing())
loading.dismiss();
JSON_STRING = s;
showEmployee();
}
1.Determine return value whether is empty in doInBackground method
2.Determine param value whether is empty in onPostExecute method
You need to Debug this issue why your toast is not showing:
You have correctly put show Toast code in onPostExecute
Now to debug , first put a Log to know the value of s , whether it is ever null or empty.
If yes and still toast is not showing, move the dialog dismiss dialog before Toast and check.
If Toast still does not show debug your showEmployee() method as what it does.
In my Application I want to retrieve a data from the database. But the problem I am facing is that, the data is fetched from database but it is not displaying at a time when I reopen the page at that time the data is displaying. I want to reload a page when I click on Button.
Here the code is as follow :-
Btngetdata.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
new InTimeInsert().execute();
}
});
private class InTimeInsert extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... args) {
try {
arraylist = new ArrayList<HashMap<String, String>>();
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("at_username", uid));
JSONObject json = jParser.makeHttpRequest(url_intime,"GET", params);
//ownerObj = json.getJSONArray("visit");
for (int i = 0; i < ownerObj.length(); i++) {
jsonobject = ownerObj.getJSONObject(i);
time_fetch.add(jsonobject.getString("at_itime"));
}
} catch (Exception e) {
}
return null;
}
#Override
protected void onPostExecute(Void args) {
ina.setText(""+delivery_fetch);
}
}
private class AllAtendence extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... args) {
try {
arraylist = new ArrayList<HashMap<String, String>>();
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("at_username", uid));
JSONObject json = jParser.makeHttpRequest(url_allatendence,"GET", params);
ownerObj = json.getJSONArray("visit");
for (int i = 0; i < ownerObj.length(); i++) {
jsonobject = ownerObj.getJSONObject(i);
delivery_fetch =jsonobject.getString("at_date");
lunch=jsonobject.getString("at_litime");
rejoin=jsonobject.getString("at_lotime");
out=jsonobject.getString("at_otime");
Log.d("at_line",json.toString());
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void args) {
ina.setText(""+delivery_fetch);
rejoina.setText(""+lunch);
luncha.setText(""+rejoin);
outa.setText(""+out);
if(ina.getText().toString().equals(""))
{
Btngetdata.setVisibility(View.VISIBLE);
inti.setVisibility(View.GONE);
}
else
{
Btngetdata.setVisibility(View.GONE);
}
if(luncha.getText().toString().equals(""))
{
ltime.setVisibility(View.VISIBLE);
luncht.setVisibility(View.GONE);
}
else
{
ltime.setVisibility(View.GONE);
}
if(rejoina.getText().toString().equals(""))
{
rtime.setVisibility(View.VISIBLE);
rejoint.setVisibility(View.GONE);
}
else
{
rtime.setVisibility(View.GONE);
}
if(outa.getText().toString().equals(""))
{
otime.setVisibility(View.VISIBLE);
outt.setVisibility(View.GONE);
}
else
{
otime.setVisibility(View.GONE);
}
}
}
If you fetch only one data than you can use this to solve your problem..
And use log to see if there is any err on fetching data... on catch block..Good luck.
private class InTimeInsert extends AsyncTask<Void, Void, Void> {
String fetched_data = "";
#Override
protected Void doInBackground(Void... args) {
try {
arraylist = new ArrayList<HashMap<String, String>>();
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("at_username", uid));
JSONObject json = jParser.makeHttpRequest(url_intime,"GET", params);
//ownerObj = json.getJSONArray("visit");
for (int i = 0; i < ownerObj.length(); i++) {
jsonobject = ownerObj.getJSONObject(i);
this.fetched_data = jsonobject.getString("at_itime");
}
} catch (Exception e) {
Log.d("fetch err", e.toString());
}
return null;
}
#Override
protected void onPostExecute(Void args) {
ina.setText(""+this.fetched_data);
}
}
//put your code in onResume methods
#Override protected void onResume() {
super.onResume();
// call here
new InTimeInsert().execute();
}
Add .get();, while calling AsyncTask.
Like:
new InTimeInsert().execute().get();
It waits for the result of AsyncTask.
By doing this, will execute the AsyncTask first and then continues with the control flow.
I'm trying to fetch data from server in saving in SQLite database through Async task on Splash. i have multiple tables on server and need to fetch one after another. I'm trying this way
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.splash);
StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder().detectDiskReads().detectDiskWrites().detectNetwork()
.penaltyLog().build());
url = getResources().getString(R.string.url);
db = new SQLCont(context);
new asyn_Task1(Splash.this).execute();
}
public class asyn_Task1 extends AsyncTask<String, Void, Boolean> {
public asyn_Task1(Splash activiy) {
context = activiy;
}
#Override
protected void onPostExecute(Boolean result) {
super.onPostExecute(result);
new asyn_Task2(Splash.this).execute();
}
#Override
protected void onPreExecute() {
super.onPreExecute();
progressdialog = new ProgressDialog(Splash.this);
progressdialog.setTitle("Processing....");
progressdialog.setMessage("Please Wait.....1 /10");
progressdialog.setCancelable(false);
progressdialog.show();
}
#Override
protected Boolean doInBackground(String... params) {
postParameters.add(new BasicNameValuePair("001", data));
try {
CustomHttpClient.executeHttpGet("001");
} catch (Exception e1) {
e1.printStackTrace();
}
String response = null;
// call executeHttpPost method passing necessary parameters
try {
response = CustomHttpClient.executeHttpPost(
url,
postParameters);
// store the result returned by PHP script that runs
// MySQL query
String result = response.toString();
// parse json data
try {
JSONArray jArray = new JSONArray(result);
for (int i = 0; i < jArray.length(); i++) {
JSONObject json_data = jArray.getJSONObject(i);
id = json_data.getString("id");
st_name = " " + json_data.getString("name");
st_contact = json_data.getString("contact");
st_category = json_data.getString("Category");
st_address = json_data.getString("address");
Log.d("favourite_data", "" + id + st_name + st_contact
+ st_category + st_address);
db.adddata_hospital(context, st_name,st_contact,
st_category, st_address);
}
} catch (JSONException e) {
Log.e("log_tag", "Error parsing data " + e.toString());
}
} catch (Exception e) {
Log.e("log_tag", "Error in http connection!!" + e.toString());
}
return null;
}
}
public class asyn_Task2 extends AsyncTask<String, Void, Boolean> {
public asyn_Task2(Splash activiy) {
context = activiy;
}
#Override
protected void onPostExecute(Boolean result) {
super.onPostExecute(result);
new asyn_Task3(Splash.this).execute();
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Boolean doInBackground(String... params) {
// some stuff here
}
return null;
}
}
public class asyn_Task3 extends AsyncTask<String, Void, Boolean> {
public asyn_blood_Group(Splash activiy) {
context = activiy;
}
#Override
protected void onPostExecute(Boolean result) {
super.onPostExecute(result);
progressdialog.dismiss();
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Boolean doInBackground(String... params) {
// some stuff here
}
return null;
}
}
problem is that data is added for asyn_Task1 it repeated every time
expected out put
abc def ghi
jkl mno pqr
mno pqr stu
But getting output
abc def ghi
abc def ghi
abc def ghi
You will get your data based on your query. If you always execute same query then you will always get same data.
And from my point of view if possible single AsyncTask for that purpose. when all the query is completed then onpostExecute() callback will fired.
I have a problem with my adapter for my listview, i don't know where i have to add notifyDataSetChanged() in my code always if i run this code in logcat is coming a error:
java.lang.IllegalStateException: The content of the adapter has changed but ListView did not receive a notification. Make sure the content of your adapter is not modified from a background thread, but only from the UI thread. Make sure your adapter calls notifyDataSetChanged() when its content changes. [in ListView(2131165276, class android.widget.ListView)]
my asynctask:
class UpdateData extends AsyncTask<Void, Void, JSONArray> {
String result = "";
JSONArray jArray = null;
#Override
protected void onPostExecute(JSONArray result) {
super.onPostExecute(result);
adapter.addAll(deptList);
adapter.notifyDataSetChanged();
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected JSONArray doInBackground(Void... arg0) {
....
try {
JSONArray array = new JSONArray(result);
for (int i = 0; i < array.length(); i++) {
JSONObject j = array.getJSONObject(i);
EventCalendarStrings d = new EventCalendarStrings();
d.name = j.optString("name", "");
d.kategorie = j.optString("Art", "");
deptList.add(d);
}
} catch (JSONException e) {
Log.e("log_tag", "No connection " + e.toString());
}
}
return jArray;
}
It goes in onPostExecute() because it is executed on the UI thread. Calling it in doInBackground() will result in that exception.
Try this
#Override
protected void onPostExecute(JSONArray result) {
super.onPostExecute(result);
runOnUiThread(new Runnable(){
public void run(){
adapter.addAll(deptList);
adapter.notifyDataSetChanged();
}
});
}
or
#Override
protected void onPostExecute(JSONArray result) {
super.onPostExecute(result);
runOnUiThread(new Runnable(){
public void run(){
adapter.addAll(deptList);
listview.setAdapater(adapter);
}
});
}
I'm trying a simple example : http://www.vogella.com/articles/AndroidJSON/article.html
But got an error .. Can anyone tell me why I get this error : http://puu.sh/1mGz1
use AsyncTask for making server request from UI Thread so change your code as:
///Your code...
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
new LongOperation().execute("");
}
private class LongOperation extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
//call readtwitterFeed() method here
String readtwitterFeed=readtwitterFeed();
return readtwitterFeed;
}
#Override
protected void onPostExecute(String result) {
try {
JSONArray jsonArray = new JSONArray(result);
Log.i(ParseJSON.class.getName(),
"Number of entries " + jsonArray.length());
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
Log.i(ParseJSON.class.getName(), jsonObject.getString("text"));
}
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
protected void onPreExecute() {
}
#Override
protected void onProgressUpdate(Void... values) {
}
}
You are trying to make data request on the main thread. Use AsyncTask to do it.
Or add this 2 line in the onCreate() method to bypass it.
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
I recommend using asynctask though.