how to make response method and call it in main class - java

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();
}
}
}

Related

How to handle Login Successful in json? [duplicate]

This question already has answers here:
How do I parse JSON in Android? [duplicate]
(3 answers)
Closed 5 years ago.
I am trying to implement login and signup form in Android with the help of JSON using post method. When i signup and enter the details it successfully register and data has been shown in my local host sever and when i login its enter wrong username and password its show incorrect details in toast and enter right details shows login success in toast, but i want when i enter right details its goes to another activity. and enter wrong details shows only toast. Here is the code :-
MainActivity.java
public class MainActivity extends Activity {
public static HashMap<Sound, MediaPlayer> SOUND_MAP=
new HashMap<Sound, MediaPlayer>();
public static int userScore= 0, computerScore=0,
buddyBoxId = 1, computerBoxId = 1;
public static Context CTX;
Button play;
private static final String TAG = "LoginActivity";
String URL = "http://10.0.2.2/test_android/index.php";
JSONParser jsonParser=new JSONParser();
ProgressDialog progressDialog;
TextView register_caption;
AdView adView = null;
private AdView mAdView;
EditText username, password;
Button btnSignIn, btnRegister;
ImageView fb;
int i=0;
private AdRequest adRequest;
InterstitialAd mInterstitialAd;
static MediaPlayer media;
static Handler mediaHandler;
public static int stat=0, totTurn = 0, maxEnd = 100;
public static SharedPreferences configs;
public static SharedPreferences.Editor configuration;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
username = (EditText) findViewById(R.id.email);
password = (EditText)findViewById(R.id.passwordd);
btnSignIn = (Button) findViewById(R.id.play);
register_caption = (TextView) findViewById(R.id.register_caption);
fb = (ImageButton) findViewById(R.id.btnfb);
progressDialog = new ProgressDialog(this);
progressDialog.setCancelable(false);
btnSignIn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
AttemptLogin attemptLogin = new AttemptLogin();
attemptLogin.execute(username.getText().toString(), password.getText().toString(), "");
}
});
register_caption.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent in = new Intent(MainActivity.this,Registration.class);
startActivity(in);
}
});
CTX = getApplicationContext();
configs = CTX. getSharedPreferences("snake_n_ladder", 0);
configuration = configs.edit();
loadConfig();
loadMedia();
}
private class AttemptLogin extends AsyncTask<String, String, JSONObject> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected JSONObject doInBackground(String... args) {
String email = args[2];
String password = args[1];
String name = args[0];
ArrayList<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("username", name));
params.add(new BasicNameValuePair("password", password));
if (email.length() > 0)
params.add(new BasicNameValuePair("email", email));
JSONObject json = jsonParser.makeHttpRequest(URL, "POST", params);
return json;
}
protected void onPostExecute(JSONObject result) {
// dismiss the dialog once product deleted
//Toast.makeText(getApplicationContext(),result,Toast.LENGTH_LONG).show();
try {
if (result != null) {
Toast.makeText(getApplicationContext(), result.getString("message"), Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getApplicationContext(), "Unable to retrieve any data from server", Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
JsonParser.java
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static JSONArray jArr = null;
static String json = "";
static String error = "";
// constructor
public JSONParser() {
}
// function get json from url
// by making HTTP POST or GET mehtod
public JSONObject makeHttpRequest(String url, String method,
ArrayList<NameValuePair> params) {
// Making HTTP request
try {
// check for request method
if(method.equals("POST")){
// request method is POST
// defaultHttpClient
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(params));
try {
Log.e("API123", " " +convertStreamToString(httpPost.getEntity().getContent()));
Log.e("API123",httpPost.getURI().toString());
} catch (Exception e) {
e.printStackTrace();
}
HttpResponse httpResponse = httpClient.execute(httpPost);
Log.e("API123",""+httpResponse.getStatusLine().getStatusCode());
error= String.valueOf(httpResponse.getStatusLine().getStatusCode());
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}else if(method.equals("GET")){
// request method is GET
DefaultHttpClient httpClient = new DefaultHttpClient();
String paramString = URLEncodedUtils.format(params, "utf-8");
url += "?" + paramString;
HttpGet httpGet = new HttpGet(url);
HttpResponse httpResponse = httpClient.execute(httpGet);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
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();
json = sb.toString();
Log.d("API123",json);
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
jObj.put("error_code",error);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
private String convertStreamToString(InputStream is) throws Exception {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line);
}
is.close();
return sb.toString();
}
}
protected void onPostExecute(JSONObject result) {
try {
if (result != null)
{
if(result.getString("message").equals("Successfully logged in"))
{
Intent intent = new Intent(ThisActivity.this,NewActivity.class);
startActivity(intent);
finish();
}
else
{
Toast.makeText(this,"Invalid credentials",Toast.LENGTH_LONG).show();
}
}
else
{
Toast.makeText(getApplicationContext(), "Unable to retrieve any data from
server", Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}

Toast message if there is not data from server

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());
}
}
}

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

Android: start a new Activity in onPostExecute() when two strings are equal

I am new to Android development.
I'm trying to create a login with an AsyncTask.
The issue I'm having is that I can't open a new Activity on onPostExecute().
I don't know why, but my app won't run if the if(res=="valid") in postdata. In the log I can see only my response and not my response2.
Here's the code:
public class MainActivity extends Activity {
private EditText employeNum;
private EditText Id;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
employeNum = (EditText) findViewById(R.id.editText1);
Id = (EditText) findViewById(R.id.editText2);
}
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public class MyAsyncTask extends AsyncTask<String, Integer, Double> {
// int loginVerified=0;
public boolean loginVerified = false;
public String res;
protected Double doInBackground(String... params) {
postData(params[0],params[1]);
return null;
}
protected void onPostExecute(boolean loginVerified){
if(loginVerified == true)
{
Intent menu = new Intent(getApplicationContext(),menu.class);
startActivity(menu);
finish();
}
}
public void postData(String a,String b) {
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("http://www.nir-levi.com/login/");
try {
List<NameValuePair> nameValuePair = new ArrayList<NameValuePair>(2);
nameValuePair.add(new BasicNameValuePair("user_email", a));
nameValuePair.add(new BasicNameValuePair("user_password", b));
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePair));
HttpResponse response = httpClient.execute(httpPost);
BufferedReader in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
StringBuffer sb = new StringBuffer("");
String line = null;
String NL = System.getProperty("line.separator");
while ((line = in.readLine()) != null) {
sb.append(line + NL);
}
in.close();
res = sb.toString();
if(res=="valid"){
Log.v("My Response2::",res);
loginVerified=true;
onPostExecute(loginVerified);
}
Log.v("My Response::",res);
public void login(View v) {
String num = employeNum.getText().toString();
String id = Id.getText().toString();
new MyAsyncTask().execute(num, id);
}
It should be
if(res.equals("valid")) {
...
}
When using if(res =="valid") you compare the strings by reference. Please, see How do I compare strings in Java?.
you should write:
if ("valid".equals(res)) {
}
Also, you should not call onPostExecute in doInBackground. It will be automatically called when the AsyncTask has finished executing.
The problem is because you are calling onPostExecute() explicitly. You want to return the result from postData in doInBackground() as a boolean value. I have verified that this works.
public class MyAsyncTask extends AsyncTask<String, Integer, Boolean> {
private static final String TAG = "MyAsyncTask";
public boolean loginVerified = false;
public String res;
protected Integer doInBackground(String... params) {
try {
// return the boolean loginVerified
return postData(params[0], params[1]);
} catch (IOException e){
Log.e(TAG, "doInBackground()", e);
return false; // <- return the boolean loginVerified
}
}
protected void onPostExecute(Boolean loginVerified){
if(loginVerified == true) {
Intent menu = new Intent(getApplicationContext(), menu.class);
startActivity(menu);
finish();
}
}
private boolean postData(String a, String b) throws IOException {
URL url = new URL("http://www.nir-levi.com/login/");
HttpURLConnection connection = (HttpURLConnection)url.openConnection();
try {
connection.setRequestMethod(POST);
connection.setRequestProperty(KEY_USER_AGENT, USER_AGENT);
connection.setDoOutput(true);
DataOutputStream urlOutput = new DataOutputStream(connection.getOutputStream());
urlOutput.writeBytes(urlBody);
urlOutput.flush();
urlOutput.close();
int responseCode = connection.getResponseCode();
InputStream in = null;
if (responseCode == 201){ /* Hopefully your server is sending the
proper Http code for a successful
create */
in = connection.getInputStream();
} else {
in = connection.getErrorStream();
}
ByteArrayOutputStream byteArrayOut = new ByteArrayOutputStream();
int bytesRead = 0;
byte[] buffer = new byte[1024];
while ((bytesRead = in.read(buffer)) > 0) {
byteArrayOut.write(buffer, 0, bytesRead);
}
byteArrayOut.close();
res = new String(byteArrayOut.toByteArray();
Log.v(TAG, "res = " + res);
return (res.compareTo("valid") == 0); // <- return from postData
} catch (FileNotFoundException e){
Log.e(TAG, "Error: " + connection.getResponseCode(), e);
return false;
} finally {
connection.disconnect();
}
}
public void login(View v) {
String num = employeNum.getText().toString();
String id = Id.getText().toString();
new MyAsyncTask().execute(num, id);
}

Categories

Resources