I tried to convert JSON from PHP server side to string in Android.
It force closes with (java.lang.String cannot be converted to JSONObject ) Error.
This is my Web class for HTTP connecting:
public class Web {
public static String readUrl(String url) {
try {
HttpClient client = new DefaultHttpClient();
HttpPost method = new HttpPost(url);
HttpResponse response = client.execute(method);
InputStream inputStream = response.getEntity().getContent();
String result = convertInputstreamToString(inputStream);
return result;
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
private static String convertInputstreamToString(InputStream inputStream){
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
StringBuilder builder = new StringBuilder();
String line ="";
while ((line = reader.readLine())!=null) {
builder.append(line);
}
return String.valueOf(builder);
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
This is my Activity:
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Thread thread = new Thread(new Runnable() {
#Override
public void run() {
try {
String result = Web.readUrl("http://192.168.1.53/mana/mana%20records.php");
if (result != null) {
try {
JSONArray records = new JSONArray(result);
for (int i = 0; i < records.length(); i++) {
JSONObject record = records.getJSONObject(i);
Log.d("Records", record.getString("date"));
}
} catch (JSONException e) {
e.printStackTrace();
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
});
thread.start();
}
}
And this is my JSON:
[{"date":"2015-12-01","Shift Day":"on","Shift Night":"",
"Shift Person":"a","Code":"1","1st":"1000","Size 8":null,
"2nd":"1","3rd":"10","logo":"1000","Storage":"10000"},
{"date":"2015-12-02","Shift Day":"",
"Shift Night":"on","Shift Person":"b","Code":"2","1st":"2000",
"Size 8":null,"2nd":"2","3rd":"20","logo":"2000",
"Storage":"20000"}]
Related
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"));
I am trying to get response from server but it only display me toast server not supported.i don't understand what is going on here. i have assigned the api to a static variable that i declare in another class.
Code:
public class SpeakersFrag extends Fragment {
private List<SpeakersBean> dataset;
// private Context context;
private ProgressDialog progressDialog;
SessionContoller sessionContoller;
RecyclerView recyclerView;
public SpeakerAdapter speakerAdapter;
Context context;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
super.onCreateView(inflater, container, savedInstanceState);
View myview=inflater.inflate(R.layout.speakers,null);
this.context=getActivity(); //cmt ctx
this.sessionContoller=new SessionContoller(this.context);
RecyclerView recyclerView = (RecyclerView) myview.findViewById(R.id.Recycler_viewrest);
// List<String> dataSet=new ArrayList<>();
recyclerView.setHasFixedSize(true);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this.context);
recyclerView.setLayoutManager(linearLayoutManager);
//linearLayoutManager.setOrientation;
recyclerView.setLayoutManager(linearLayoutManager);
if (AppStatus.getInstance(this.context).isOnline(this.context)) {
new GetSpeakerList().execute(new Void[0]);
} else if (this.sessionContoller.getSpeakerData() != null) {
setData(this.sessionContoller.getSpeakerData());
} else {
Dialog.noInternetAlertBox(this.context);
}
// new GetSpeakerList().execute(new Void[0]);
recyclerView.addOnItemTouchListener(new RecyclerItemClickListener(this.context,new Listener()));
return myview;
}
class Listener implements RecyclerItemClickListener.ClickListener{
#Override
public void onItemClick(View view, int i) {
SpeakersBean speakersBean=SpeakersFrag.this.getSpeakerAdapter().getItem(i);
Intent in=new Intent(SpeakersFrag.this.context,SpeakerDetail.class);
in.putExtra("speaker", speakersBean);
startActivity(in);
}
}
class GetSpeakerList extends AsyncTask<Void, Void,String> {
ProgressDialog pd;
#Override
protected void onPreExecute() {
// pd = new ProgressDialog(getActivity()).show(getActivity(), "", "Loading...");
SpeakersFrag.this.progressDialog = new ProgressDialog(SpeakersFrag.this.context);
SpeakersFrag.this.progressDialog.setMessage("Loading...");
SpeakersFrag.this.progressDialog.setCancelable(false);
SpeakersFrag.this.progressDialog.show();
}
#Override
protected String doInBackground(Void... params) {
return SpeakersFrag.this.performPostCallback(Constants.Webservice.SPEAKER_API);
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
if (!result.equals(BuildConfig.FLAVOR))
{
try
{
JSONObject jsonObject = new JSONObject(result); // set ` *emphasized text*`status code to continue the webservice as define in constants
if (jsonObject.getString("status_code").equals("100") && jsonObject.getString("message").equalsIgnoreCase("Success"))
{
System.out.println("Speaker data with Json and gson Parsing");
sessionContoller = new SessionContoller(getContext());
JSONArray jsonArray = jsonObject.getJSONArray("items"); //items
SpeakersFrag.this.dataset = (List) new Gson().fromJson(jsonArray.toString()
, new TypeToken<List<SpeakersBean>>() {}.getType());
SpeakersFrag.this.speakerAdapter = new SpeakerAdapter(SpeakersFrag.this.context, SpeakersFrag.this.dataset);
SpeakersFrag.this.recyclerView.setAdapter(SpeakersFrag.this.speakerAdapter);
SpeakersFrag.this.sessionContoller.setSpeakerData(jsonArray.toString());
}
} catch (JSONException e)
{
Log.e("SpeakerFragment", e.toString(), e);
// e.printStackTrace();
}
}
else if (SpeakersFrag.this.sessionContoller.getSpeakerData() != null) {
SpeakersFrag.this.setData(SpeakersFrag.this.sessionContoller.getSpeakerData());
}else{
Toast.makeText(getActivity(),Constants.SERVER_ERROR,Toast.LENGTH_LONG).show();
}
SpeakersFrag.dismissDialog(SpeakersFrag.this.progressDialog);
}
}
private void setData(String speakerData){
JSONException e;
try {
JSONArray jsonSpeaker = new JSONArray(speakerData);
JSONArray jarray;
{
try {
this.dataset = (List) new Gson().fromJson(jsonSpeaker.toString(), new TypeToken<TypeToken<List<SpeakersBean>>>(){}.getType());
this.speakerAdapter = new SpeakerAdapter(SpeakersFrag.this.context, SpeakersFrag.this.dataset);
this.recyclerView.setAdapter(this.speakerAdapter); //add speakerfrag
jarray=jsonSpeaker;
// ().getType());
} catch (Exception e1) {
jarray = jsonSpeaker;
e1.printStackTrace();
}
}
}catch (JSONException e3) {
e=e3;
e.printStackTrace();
}
}
public String performPostCallback(String requestURL)
{
String response=BuildConfig.FLAVOR;
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
try {
//send post data request
HttpURLConnection connection=(HttpURLConnection) new URL(requestURL).openConnection();
connection.setReadTimeout(15000);
connection.setConnectTimeout(15000);
connection.setRequestMethod("POST");
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setReadTimeout(15000);
OutputStream outputStream=connection.getOutputStream();
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8")); //UTF-8 encode the string into utf format
outputStream.flush(); //flushes the output stream and forces to any buffered device to be written out
outputStream.close(); //close pd
if (connection.getResponseCode() != ItemTouchHelper.Callback.DEFAULT_DRAG_ANIMATION_DURATION) {
return BuildConfig.FLAVOR;
}
//Read the server response
BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
while (true) {
String line = br.readLine(); //read server response
if (line == null) {
return response;
}
response = response + line; //Append response
System.out.println("Response request====>>>>>"+response); //response from server
}
} catch (Exception e) {
Log.e("SpeakerFragment", e.toString(), e);
return response;
}
}
public SpeakerAdapter getSpeakerAdapter(){
return this.speakerAdapter;
}
public static void dismissDialog(ProgressDialog pd) {
if (pd != null) {
try {
if (pd.isShowing()) {
pd.dismiss();
}
} catch (Exception e)
{
e.printStackTrace();
} catch (Throwable th){
th.printStackTrace();
}
}
}
----------
}
Blockquote
I think its from the server side error....
Toast.makeText(getActivity(),Constants.SERVER_ERROR,Toast.LENGTH_LONG).show();
This code is working,thats why its showing that error
I have a problem. When I do a query in the stream, I have downloaded the data from the URL, everything works. But when I call AsynsTask example by pressing doInBackground() method that returns the same data, but they are updated on the URL. And they will not be updated as long as the program is restarted.
#Override
protected String doInBackground(Void... params) {
try {
URL url = new URL("data.php?"+new Random().nextInt(200));
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.connect();
InputStream inputStream = urlConnection.getInputStream();
StringBuffer buffer = new StringBuffer();
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
String line;
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
jSON_R = buffer.toString();
} catch (Exception e) {
e.printStackTrace();
}
return jSON_R;
}
All code
public class ParseTask extends AsyncTask<Void, Void, String> {
int intRow = 0;
String jSON_R = "";
private List<User> movieList;
Activity act;
ListView list;
LAdapter adapter;
boolean Unique = true;
public ParseTask (Activity act){
this.act = act;
}
#Override
protected String doInBackground(Void... params) {
try {
URL url = new URL("data.php?"+new Random().nextInt(200));
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.connect();
InputStream inputStream = urlConnection.getInputStream();
StringBuffer buffer = new StringBuffer();
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
String line;
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
jSON_R = buffer.toString();
} catch (Exception e) {
e.printStackTrace();
}
return jSON_R;
}
#Override
protected void onPostExecute(String strJson) {
super.onPostExecute(strJson);
list = (ListView) act.findViewById(R.id.listVew);
Button b = (Button) act.findViewById(R.id.refresh);
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//To do
}
});
movieList = new ArrayList<>();
adapter = new LAdapter(act, movieList);
list.setAdapter(adapter);
try {
JSONObject dataJsonObj = new JSONObject(strJson);
JSONArray jsa = dataJsonObj.getJSONArray("data");
for (int i = 0; i < jsa.length(); i++) {
JSONObject data1 = chat.getJSONObject(i);
String mes = data1.getString("mes1");
String mes2 = data1.getString("mes2");
String mes3 = data1.getString("mes3");
User m = new User(mes, mes2, mes3);
movieList.add(0, m);
}
adapter.notifyDataSetChanged();
intRow = jsa.length();
} catch (JSONException e) {
e.printStackTrace();
}
list.setOnScrollListener(new AbsListView.OnScrollListener() {
#Override
public void onScrollStateChanged(AbsListView view, int scrollState) {}
#Override
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
if (firstVisibleItem > 1){
Unique = false;
}else{
Unique = true;
}
}
});
Thread thread = new Thread() {
#Override
public void run() {
try {
while (true){
sleep(5000);
if (Unique){
act.runOnUiThread(new Runnable() {
#Override
public void run() {
Update();
}
});
}
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
thread.start();
}
private void Update(){
try {
JSONObject dataJsonObj = new JSONObject(strJson);
JSONArray jsa = dataJsonObj.getJSONArray("data");
for (int i = 0; i < jsa.length(); i++) {
JSONObject data1 = chat.getJSONObject(i);
String mes = data1.getString("mes1");
String mes2 = data1.getString("mes2");
String mes3 = data1.getString("mes3");
User m = new User(mes, mes2, mes3);
movieList.add(0, m);
}
adapter.notifyDataSetChanged();
intRow = jsa.length();
} catch (JSONException e) {
e.printStackTrace();
}
adapter.notifyDataSetChanged();
}
}
Calling the object in such a way
new ParseTask(getActivity()).execute();
Close the connection.
I mean use (better) reader.close() or inputStream.close()
Or try jsoup library https://jsoup.org/
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;
}
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