Toast message if there is not data from server - java

i want to show in my search if it wont recieve similar result to my word i enterd it should Toast me "No Result.but problem is that it gets data after 0.5 seconds.so when i click button first it Toasts No results then gets data and show them in recyclerview.I want if there is not similar word it toast me No result at the end;
String text = txtsearch.getText().toString();
new AsyncTaskSearch("http://192.168.1.100/afgApp/search.php", text).execute();
final Timer timer = new Timer();
timer.scheduleAtFixedRate(new TimerTask() {
#Override
public void run() {
runOnUiThread(new Runnable() {
#Override
public void run() {
if (!Activity_Search.data.equals("")) {
Toast.makeText(Activity_Search.this, data, Toast.LENGTH_SHORT).show();
timer.cancel();
}else {
Toast.makeText(Activity_Search.this, "No results", Toast.LENGTH_SHORT).show();
}
}
});
}
},1,500);
Activity_Search.data = "";
}
//Asynctask.java
public class AsyncTaskSearch extends AsyncTask{
public String link="";
public String text="";
public AsyncTaskSearch(String link,String text){
this.link=link;
this.text=text;
}
#Override
protected Object doInBackground(Object[] params) {
try{
String data= URLEncoder.encode("text","UTF8")+"="+URLEncoder.encode(text,"UTF8");
URL url=new URL(link);
URLConnection connection=url.openConnection();
connection.setDoOutput(true);
OutputStreamWriter writer=new OutputStreamWriter(connection.getOutputStream());
writer.write(data);
writer.flush();
BufferedReader reader=new BufferedReader(new InputStreamReader(connection.getInputStream()));
StringBuilder builder=new StringBuilder();
String line=null;
while((line=reader.readLine())!=null){
builder.append(line);
}
Activity_Search.data=builder.toString();
}catch (Exception e){
}
return "";
}
}

I don't know how you are using your AysncTask. Try this code, it's working fine for me:
private class AsyncGetClass extends AsyncTask<Object, Void, String> {
ProgressDialog progressDialog;
String TAG, url;
AsyncHttpResponseHandler asyncHttpResponseHandler;
Context context;
public AsyncGetClass(Context context) {
// TODO Auto-generated constructor stub
this.context = context;
}
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
if (!isProgressHiding)
if (progressDialog == null) {
progressDialog = createProgressDialog(context);
progressDialog.show();
} else {
progressDialog.show();
}
}
#SuppressWarnings("unchecked")
#Override
protected String doInBackground(Object... params) {
// TODO Auto-generated method stub
TAG = (String) params[0];
url = (String) params[1];
asyncHttpResponseHandler = (AsyncHttpResponseHandler) params[3];
InputStream is = null;
String result = "";
// HTTP post
try {
HttpClient httpclient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
Log.e(TAG, url);
HttpResponse response = httpclient.execute(httpGet);
HttpEntity entity = response.getEntity();
is = entity.getContent();
} catch (Exception e) {
Log.e(TAG, "Error in http connection " + e.toString());
Toast.makeText(Activity_Search.this, "No results", Toast.LENGTH_SHORT).show();
}
// 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();
// Log.i(TAG + ".result", result);
return result;
} catch (Exception e) {
Log.e(TAG, "Error converting result " + e.toString());
return null;
}
}
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
if (!isProgressHiding)
if (progressDialog != null)
progressDialog.dismiss();
if (result != null)
try {
Log.i(TAG, result);
asyncHttpResponseHandler.onSuccess(result);
} catch (Exception e) {
Log.e(TAG, "Must implement the interface " + e.toString());
}
}
}

Related

I got error Android JSON parsing Retrieve from URL

I new to Android... I am trying Android JSON parsing Retrieve from URL and set MySQL DB data into TextView but I got an error. I tried many solutions but it's not working Help me to solve this error
java.lang.NullPointerException: Attempt to invoke virtual method
'java.lang.String org.json.JSONObject.getString(java.lang.String)' on
a null object reference at
com.example.testapplication.MainActivity$GetDataFromServerIntoTextView.onPostExecute(MainActivity.java:123)at
com.example.testapplication.MainActivity$GetDataFromServerIntoTextView.onPostExecute(MainActivity.java:63)
Error shows this line textView.setText(jsonObject.getString("distance"));
My Code
HttpResponse httpResponse;
Button button;
TextView textView;
static JSONObject jsonObject = null ;
String StringHolder = "" ;
ProgressBar progressBar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = (Button)findViewById(R.id.button);
textView = (TextView)findViewById(R.id.textView);
progressBar = (ProgressBar)findViewById(R.id.progressBar);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
progressBar.setVisibility(View.VISIBLE);
new GetDataFromServerIntoTextView(MainActivity.this).execute();
}
});
}
public class GetDataFromServerIntoTextView extends AsyncTask<Void, Void, Void>
{
public Context context;
public GetDataFromServerIntoTextView(Context context)
{
this.context = context;
}
#Override
protected void onPreExecute()
{
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... arg0)
{
HttpClient httpClient = new DefaultHttpClient();
String HttpURL = "https://api.myjson.com/bins/1cuzhn";
// Adding HttpURL to my HttpPost oject.
HttpPost httpPost = new HttpPost(HttpURL);
try {
httpResponse = httpClient.execute(httpPost);
StringHolder = EntityUtils.toString(httpResponse.getEntity(), "UTF-8");
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try{
JSONArray jsonArray = new JSONArray(StringHolder);
jsonObject = jsonArray.getJSONObject(0);
} catch ( JSONException e) {
e.printStackTrace();
}
catch (Exception e)
{
e.printStackTrace();
}
return null;
}
protected void onPostExecute(Void result)
{
try {
textView.setText(jsonObject.getString("distance"));
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
progressBar.setVisibility(View.GONE);
}
}
I modified your AsyncTask and tested below code and its working fine. Let me know if you found any issue.
Add below dependencies
// OKHTTP
implementation 'com.squareup.okhttp:okhttp:2.5.0'
implementation 'com.squareup.okhttp3:logging-interceptor:3.11.0'
implementation 'org.apache.httpcomponents:httpcore:4.4.10'
and
public class GetDataFromServerIntoTextView extends AsyncTask<Void, Void,String>
{
public Context context;
public GetDataFromServerIntoTextView(Context context) {
this.context = context;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(Void... voids) {
String strUrl = "https://api.myjson.com/bins/1cuzhn";
String data = "";
InputStream iStream = null;
HttpURLConnection urlConnection = null;
try {
URL url = new URL(strUrl);
// Creating an http connection to communicate with url
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.connect();
// Reading data from url
iStream = urlConnection.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(iStream));
StringBuffer sb = new StringBuffer();
String line = "";
while ((line = br.readLine()) != null) {
sb.append(line);
}
data = sb.toString();
br.close();
} catch (Exception e) {
Log.d(TAG, "Exception while downloading url " + e.toString());
} finally {
try {
iStream.close();
} catch (IOException e) {
e.printStackTrace();
}
urlConnection.disconnect();
}
return data;
}
#Override
protected void onPostExecute(String data) {
super.onPostExecute(data);
try {
if (data != null) {
JSONArray jsonArray = new JSONArray(data);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
// Here is your all data of distance and time
Log.e(TAG, "distance " + jsonObject.get("distance"));
Log.e(TAG, "time " + jsonObject.get("time"));
}
} else {
Log.e(TAG, "onPostExecute: null json object");
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
You are using POST request where as your api is expecting GET request
Here is more details about GET and POST
HttpPost httpPost = new HttpPost(HttpURL);
replace this with following
HttpGet request = new HttpGet(HttpURL);
To avoid crash replace your code with
textView.setText(jsonObject.getString("distance"));
this
textView.setText(jsonObject.isNull("distance") ? "null object" : jsonObject.getString("distance"));

Making Attendance App in Android

I have to make attendance app for college.The app will take data from colleges website and display it on app according to user login and password.
When we login into college's website we have to put id and password, same thing I want on my app so that user can see it on an app itself.
I have searched httpurlconnection, httpget, httppost, jsoup.
Up till now, I have understood that I have to make httprequest for loading the college's attendance site and then httppost to post username and password and after that jsoup to grab the data from HTML page.
But I have seen tutorials only to request JSON pages, but how to request for HTML pages?and post login to it?
Here is what I tried and collected data from JSON
private TextView textresponse1;
private ProgressDialog progressDialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button Get= (Button) findViewById(R.id.httprequest);
textresponse1= (TextView)findViewById(R.id.textresponse);
progressDialog=new ProgressDialog(this);
Get.setOnClickListener(this);
}
#Override
public void onClick(View v) {
new JSONTask().execute("https://jsonparsingdemo-cec5b.firebaseapp.com/jsonData/moviesDemoList.txt");
progressDialog.setMessage("Collecting Data");
progressDialog.show();
}
public class JSONTask extends AsyncTask<String,String,String >{
#Override
protected String doInBackground(String... params) {
BufferedReader reader = null;
HttpURLConnection connection = null;
try {
URL url=new URL(params[0]);
connection=(HttpURLConnection) url.openConnection();
connection.connect();
InputStream stream=connection.getInputStream();
reader=new BufferedReader(new InputStreamReader(stream));
String line="";
StringBuffer buffer=new StringBuffer();
while ((line = reader.readLine())!=null) {
buffer.append(line);
}
String finaljosn=buffer.toString();
StringBuffer add =new StringBuffer();
JSONObject parentobject=new JSONObject(finaljosn);
JSONArray parentarray=parentobject.getJSONArray("movies");
for(int i=0;i<parentarray.length();i++) {
JSONObject moviename = parentarray.getJSONObject(i);
String finalmovie = moviename.getString("movie");
int finalyear = moviename.getInt("year");
add.append(finalmovie +"- "+finalyear + "\n");
}
return add.toString();
// return finalmovie +" -Rushabh- " +finalyear;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
} finally {
if (connection!=null) {
connection.disconnect();
}
try {
if (reader!=null) {
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
progressDialog.dismiss();
textresponse1.setText(result);
}
}
String mLoadURL="http://www.google.com";
public class LoadHtml extends AsyncTask<String, String, String> {
#Override
protected String doInBackground(String... params) {
URL url = null;
try {
url = new URL(mLoadURL);
StringBuilder stringBuilder = new StringBuilder();
URLConnection conn = url.openConnection();
// Get the response
BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line = "";
while ((line = rd.readLine()) != null) {
stringBuilder.append(line);
}
return stringBuilder.toString();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return "";
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
if (!s.trim().isEmpty()) {
//load html to webview
}
}
}
Call Above AsyncTask using:
LoadHtml loadHtml= new LoadHtml();
load.execute();

how to make response method and call it in main class

I want to access html from the server using API for that i want to make a method in the response, that method i want to use it in main class.I am using webview to show the output result in webview.Following code I am using.
public class Dashboard_Description__page extends AppCompatActivity {
ImageButton reader_back;
ArrayList<Reader_Model> actorsList;
String addCat;
ActorAdapter adapter;
WebView webView;
String alternate_id;
String bookmarkid;
String bookmarkfile;
private String webData;
String mimeType = "text/html";
String encoding = "utf-8";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_dashboard__description__page);
WebView webView = (WebView) findViewById(R.id.webview);
// String summary = "<html><body>You scored <b>192</b> points.</body></html>";
webView.loadData(getWebData(), "text/html", null);
if (savedInstanceState == null) {
Bundle extras = getIntent().getExtras();
if(extras == null) {
alternate_id= null;
bookmarkid= null;
bookmarkfile = null;
} else {
alternate_id= extras.getString("alternateid");
bookmarkid= extras.getString("bookmarkid");
bookmarkfile = extras.getString("bookmarkfile");
}
} else {
alternate_id= (String) savedInstanceState.getSerializable("alternateid");
bookmarkid= (String) savedInstanceState.getSerializable("bookmarkid");
bookmarkfile= (String) savedInstanceState.getSerializable("bookmarkfile");
}
webView.setWebViewClient(new WebViewClient() {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
});
// System.out.println(stringCameFromFirstAcvitity);
// actorsList = new ArrayList<Actors>();
new JSONReaderAsyncTask().execute("https://www.webo.com/secure-mobile/get_article_detail?", " access_token","bookmark_file","alternate_id","bookmarkId");
reader_back=(ImageButton)
findViewById(R.id.reader_back_btn);
reader_back.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick (View v) {
Intent dash_back = new Intent(getApplicationContext(),Dashboard.class);
startActivity(dash_back);
}
});
}
public String getWebData() {
return webData;
}
public void setWebData(String data) {
this.webData = data;
}
class JSONReaderAsyncTask extends AsyncTask<String, Void, Boolean> {
ProgressDialog dialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
dialog = new ProgressDialog(Dashboard_Description__page.this);
dialog.setMessage("Loading, please wait");
dialog.setTitle("Connecting server");
dialog.show();
dialog.setCancelable(false);
}
#Override
protected Boolean doInBackground(String... params)
{
HttpParams httpParameters = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParameters, 5000);
HttpConnectionParams.setSoTimeout(httpParameters, 5000);
HttpClient httpClient = new DefaultHttpClient(httpParameters);
HttpPost httpPost = new HttpPost(params[0]);
String jsonResult = "";
try {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(4);
nameValuePairs.add(new BasicNameValuePair("access_token", "94529e5dbc6234fc3bbfce7406b8dde9"));
nameValuePairs.add(new BasicNameValuePair("bookmark_file", bookmarkfile));
nameValuePairs.add(new BasicNameValuePair("alternate_id", alternate_id));
nameValuePairs.add(new BasicNameValuePair("bookmarkId", bookmarkid));
// System.out.println(alternate_id);
//System.out.println(bookmarkfile);
// System.out.println(bookmarkid);
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpClient.execute(httpPost);
// System.out.println("hello Hitu");
// jsonResult = inputStreamToString(response.getEntity().getContent()).toString();
// System.out.println(jsonResult);
// StatusLine stat = response.getStatusLine();
int status = 200;
if (status == 200) {
HttpEntity entity = response.getEntity();
String data = EntityUtils.toString(entity);
// ArrayList<String> mylist = new ArrayList<String>();
// mylist.add(data);
// System.out.println(first);
System.out.println(data);
System.out.println("fffff");
//here result is coming from the server. I want here a method which can be used in main class.I want to view this result in html form using webview.
// JSONObject jsono = new JSONObject(data);
// JSONArray jarray = jsono.getJSONArray("content");
}
return true;
//------------------>>
} catch (ParseException e1) {
e1.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return false;
}
protected void onPostExecute(Boolean result) {
dialog.cancel();
// adapter.notifyDataSetChanged();
if(result == false)
Toast.makeText(getApplicationContext(), "Unable to fetch data from server", Toast.LENGTH_LONG).show();
}
}
}
public class HttpClientWrapper {
public static String post(String requestUrl,String postValues) {
URL url;
String response = "";
try {
url = new URL(requestUrl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(15000);
conn.setConnectTimeout(15000);
conn.setRequestMethod("POST");
conn.setDoInput(true);// Specifies whether this URLConnection allows receiving data.
conn.setDoOutput(true);// Specifies whether this URLConnection allows sending data.
conn.setRequestProperty("Content-Type", "application/json; charset=utf-8");
conn.setRequestProperty("Accept", "application/json; charset=utf-8");
OutputStream os = conn.getOutputStream();
BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(os, "UTF-8"));
writer.write(postValues);
writer.flush();
writer.close();
os.close();
int responseCode=conn.getResponseCode();
if (responseCode == HttpsURLConnection.HTTP_OK) {
String line="";
BufferedReader br=new BufferedReader(new InputStreamReader(conn.getInputStream(),"UTF-8"));
StringBuilder sb = new StringBuilder();
while ((line=br.readLine()) != null) {
sb.append(line+"\n");
response = sb.toString().substring(0, sb.toString().length() - 1);
}
}
else {
response="";
}
} catch (Exception e) {
e.printStackTrace();
}
return response;
}
public static String getResponseGET(String url) {
String response = "";
HttpURLConnection c = null;
try {
URL u = new URL(url);
c = (HttpURLConnection) u.openConnection();
c.setRequestMethod("GET");
c.setConnectTimeout(15000);
c.setReadTimeout(15000);
c.connect();
int status = c.getResponseCode();
switch (status) {
case 200:
case 201:
BufferedReader br = new BufferedReader(new InputStreamReader(c.getInputStream()));
StringBuilder sb = new StringBuilder();
String line;
while ((line = br.readLine()) != null) {
sb.append(line+"\n");
response = sb.toString().substring(0, sb.toString().length() - 1);
}
br.close();
return response;
}
} catch (IOException ex) {
if (c != null) {
c.disconnect();
}
} finally {
if (c != null) {
try {
c.disconnect();
} catch (Exception ex) {
}
}
}
return null;
}
}
private class RegistrationAsyncTask extends AsyncTask<Void, Void, String> {
ProgressDialog dialog;
Context mContext;
String error;
String response;
String mData;
public RegistrationAsyncTask(Context context,String data) {
this.mContext = context;
this.error = "";
this.mData = data;
}
#Override
protected void onPreExecute() {
dialog = new ProgressDialog(mContext);
dialog.setTitle("Registration");
dialog.setMessage("Registration in process...");
dialog.setCancelable(false);
dialog.show();
}
#Override
protected String doInBackground(Void... params) {
try {
response = HttpClientWrapper.post(URL.URL_REGISTRATION, mData);
Log.e(TAG, "Response: " + response);
} catch (Exception e) {
e.printStackTrace();
this.error = e.getMessage();
}
return response;
}
#Override
protected void onPostExecute(String result) {
Log.e(TAG, "result: " + response);
if (dialog.isShowing()) {
dialog.dismiss();
}
if (response.isEmpty()){
Utils.message(getActivity(), getResources().getString(R.string.error_server));
return;
}
try {
JSONObject jsonObject = new JSONObject(result);
if (jsonObject.has("error")) {
String error = jsonObject.getString("error");
JSONObject jsonObject1 = new JSONObject(error);
String message = jsonObject1.getString("message");
Utils.showDialog(mContext, alert, alertDialog, getResources().getString(R.string.text_title_reg),message);
return;
} else {
String error = jsonObject.getString("success");
JSONObject jsonObject1 = new JSONObject(error);
String message = jsonObject1.getString("message");
alert = new AlertDialog.Builder(getActivity());
alert.setTitle(R.string.text_title_reg);
alert.setMessage(message);
alert.setCancelable(false);
alert.setPositiveButton("OK",
new DialogInterface.OnClickListener() {
public void onClick(
DialogInterface dialog,
int whichButton) {
clearForm();
dialog.dismiss();
}
});
alertDialog = alert.create();
alertDialog.show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}

How i can know if the conection to server is correct or not?

I make a login but i need know when the conection to server is fail
,this is my event of button
login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
usuario=(EditText)findViewById(R.id.etUsuario);
contrasena=(EditText)findViewById(R.id.etContrasena);
usuario_ws = usuario.getText().toString();
pass_ws = contrasena.getText().toString();
new HttpAsyncTask().execute(GET());
}
});
and this is my asynctask for the response of my server
private class HttpAsyncTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
return GET();
}
// onPostExecute displays the results of the AsyncTask.
#Override
protected void onPostExecute(String result) {
// Toast.makeText(getBaseContext(), "Received!", Toast.LENGTH_LONG).show();
// etResponse.setText(result);
Integer respuesta_ws = Integer.valueOf(result);
if (respuesta_ws>=1){
sesionIn();
}
else if (respuesta_ws==0){
sesionFail();
}
}
}
public String GET() {
String url = "http://"+ippref+":8080/WSAppInventario/webresources/inventario.users/Login/"+usuario_ws+"/"+pass_ws+"";
String result = "";
BufferedReader inStream = null;
try {
HttpClient httpClient = new DefaultHttpClient();
HttpGet httpRequest = new HttpGet(url);
HttpResponse response = httpClient.execute(httpRequest);
inStream = new BufferedReader(
new InputStreamReader(
response.getEntity().getContent()));
StringBuffer buffer = new StringBuffer();
String line = "";
//String NL = System.getProperty("line.separator");
while ((line = inStream.readLine()) != null) {
buffer.append(line);
}
inStream.close();
result = buffer.toString();
respuesta_ws = Integer.valueOf(result);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return result;
}
The string ippref
It is an object to keep before SharedPreferences
this should work
private class HttpAsyncTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
return GET();
}
// onPostExecute displays the results of the AsyncTask.
#Override
protected void onPostExecute(String result) {
// Toast.makeText(getBaseContext(), "Received!", Toast.LENGTH_LONG).show();
// etResponse.setText(result);
if (result=="failed"){
sesionFail();
}
else{
sesionIn();
}
}
}
public String GET() {
String url = "http://"+ippref+":8080/WSAppInventario/webresources/inventario.users/Login/"+usuario_ws+"/"+pass_ws+"";
String result = "";
BufferedReader inStream = null;
try {
HttpClient httpClient = new DefaultHttpClient();
HttpGet httpRequest = new HttpGet(url);
HttpResponse response = httpClient.execute(httpRequest);
inStream = new BufferedReader(
new InputStreamReader(
response.getEntity().getContent()));
StringBuffer buffer = new StringBuffer();
String line = "";
//String NL = System.getProperty("line.separator");
while ((line = inStream.readLine()) != null) {
buffer.append(line);
}
inStream.close();
result = buffer.toString();
respuesta_ws = Integer.valueOf(result);
} catch (Exception e) {
e.printStackTrace();
return "failed";
}
return result;
}

ProgressDialog not showing up in onPreExecute()

I saw that .get() is the problem, but I try without him and nothing. If possible help me. The ProgressDialog execute after doInBackground() and after run onPostExecute "dismiss" and then ProgressDialog not show.
public List<Usuario> getListaUsuario(Activity activity) {
String[] aux = new String[3];
aux[0] = URL_WS_USUARIO;
String[] resposta = null;
aux[2] = "GET";
try {
resposta = new WebServiceCliente(activity).execute(aux).get();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ExecutionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (resposta[0].equals("200")) {
Gson gson = new Gson();
ArrayList<Usuario> listaCliente = new ArrayList<Usuario>();
JsonParser parser = new JsonParser();
JsonArray array = parser.parse(resposta[1]).getAsJsonArray();
for (int i = 0; i < array.size(); i++) {
listaCliente.add(gson.fromJson(array.get(i), Usuario.class));
}
return listaCliente;
} else {
return null;
}
}
MY ASYNCTASK:
public class WebServiceCliente extends AsyncTask<String, Void, String[]> {
private Activity activity;
private ProgressDialog pDialog;
public WebServiceCliente(Activity ac) {
activity = ac;
}
public final String[] get(String url) {
String[] result = new String[2];
HttpGet httpget = new HttpGet(url);
HttpResponse response;
try {
response = HttpClientSingleton.getHttpClientInstace().execute(
httpget);
HttpEntity entity = response.getEntity();
if (entity != null) {
result[0] = String.valueOf(response.getStatusLine()
.getStatusCode());
InputStream instream = entity.getContent();
result[1] = toString(instream);
instream.close();
Log.i("get", "Result from post JsonPost : " + result[0] + " : "
+ result[1]);
}
} catch (Exception e) {
Log.e("NGVL", "Falha ao acessar Web service", e);
result[0] = "0";
result[1] = "Falha de rede!";
}
return result;
}
public final String[] post(String url, String json) {
String[] result = new String[2];
try {
HttpPost httpPost = new HttpPost(new URI(url));
httpPost.setHeader("Content-type", "application/json");
StringEntity sEntity = new StringEntity(json, "UTF-8");
httpPost.setEntity(sEntity);
HttpResponse response;
response = HttpClientSingleton.getHttpClientInstace().execute(
httpPost);
HttpEntity entity = response.getEntity();
if (entity != null) {
result[0] = String.valueOf(response.getStatusLine()
.getStatusCode());
InputStream instream = entity.getContent();
result[1] = toString(instream);
instream.close();
Log.d("post", "Result from post JsonPost : " + result[0]
+ " : " + result[1]);
}
} catch (Exception e) {
Log.e("NGVL", "Falha ao acessar Web service", e);
result[0] = "0";
result[1] = "Falha de rede!";
}
return result;
}
private String toString(InputStream is) throws IOException {
byte[] bytes = new byte[1024];
ByteArrayOutputStream baos = new ByteArrayOutputStream();
int lidos;
while ((lidos = is.read(bytes)) > 0) {
baos.write(bytes, 0, lidos);
}
return new String(baos.toByteArray());
}
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(activity);
pDialog.setCanceledOnTouchOutside(false);
pDialog.setCancelable(false);
pDialog.setIndeterminate(true);
pDialog.setTitle("Conectando Servidor.");
pDialog.setMessage("Aguarde...");
pDialog.show();
}
#Override
protected String[] doInBackground(String... params) {
if (params[2] == "POST") {
return post(params[0], params[1]);
} else if (params[2] == "GET") {
return get(params[0]);
} else {
return null;
}
}
#Override
protected void onPostExecute(String[] params) {
super.onPostExecute(params);
try {
// stop Dialog
if (pDialog.isShowing()) {
pDialog.dismiss();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
The problem is
new WebServiceCliente(activity).execute(aux).get();
get() is a blocking call, and with the UI Thread blocked waiting for get() to return there is no one that can take care of drawing the ProgressDialog. Remove get(), and use a Delegate to return the results on your AsyncTask to the UI Thread, Here there is an example
Edit:
your interface should be like:
public interface CallbackReciever { public void receiveData(String[] result); }
the constructor of your AsynTask changes like
CallbackReciever mListener;
public WebServiceCliente(Activity ac, CallbackReciever listener) {
activity = ac;
mListener = listener;
}
in onPostExecute:
#Override
protected void onPostExecute(String[] params) {
try {
if (mListener != null) {
mListener.receiveData(params);
}
// stop Dialog
if (pDialog.isShowing()) {
pDialog.dismiss();
}
} catch (Exception e) {
e.printStackTrace();
}
}
In receiveData, in your Activity, you have to process String[] result

Categories

Resources