I have the following code:
#Override
public void onReceive(Context context, Intent intent) {
super.onReceive(context, intent);
if (CLOCK_WIDGET_UPDATE.equals(intent.getAction())) {
Toast.makeText(context, "onReceiver()", Toast.LENGTH_LONG).show();
}
new GetJSON().execute(null, null, null);
}
public class GetJSON extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... params) { //Running in background
try {
httpclient = new DefaultHttpClient(new BasicHttpParams());
HttpPost httppost = new HttpPost("http://pagesbyz.com/hadith.json");
// Depends on your web service
httppost.setHeader("Content-type", "application/json");
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
inputStream = entity.getContent();
// json is UTF-8 by default
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), 8);
sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
result = sb.toString();
} catch (Exception e) {
Log.i("TEST", e.toString());
// Oops
}
finally {
try{if(inputStream != null)inputStream.close();}catch(Exception squish){}
}
return null;
}
#Override
protected void onPreExecute() { //Activity is on progress
}
#Override
protected void onPostExecute(Void v) {
try {
jsonArray = new JSONArray(result);
date = new String[jsonArray.length()];
quote = new String[jsonArray.length()];
by = new String[jsonArray.length()];
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObj = (JSONObject) jsonArray.get(i);
date[i] = jsonObj.getString("Date");
quote[i] = jsonObj.getString("Quote");
by[i] = jsonObj.getString("By");
} // End the for loop
views.setTextViewText(R.id.tvToday, date[0]);
views.setTextViewText(R.id.tvParkStatus, quote[0]);
}
catch (JSONException e) {
e.printStackTrace();
}
}
}
I am looking to update the widget with the information received from the JSON file. I see the widget but no information is being displayed.
My JSON looks like:
[
{
"Date" : "11182013",
"Quote" : "Today Is Monday",
"By" : "SiKni8"
},
{
"Date" : "11192013",
"Quote" : "Today Is Tuesday",
"By" : "SiKni8"
}
]
Change your AsynkTast to:
public class GetJSON extends AsyncTask<Void, Void, String> {
#Override
protected Void doInBackground(Void... params) { //Running in background
// ...
// do all your stuff as it is and change return to this :
return result;
}
#Override
protected void onPostExecute(String result) {
// left other of your code as it is.
}
}
And change execution to new GetJSON().execute();
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 was developing a simple application that exctracts some fields of a JSon that tells me in real time what weather is in that exact moment, and I have exctracted only one filed, and I was asking myself: Is it possible to extract more than on field at time?
Here is the the link from where i parse the Json:
https://fcc-weather-api.glitch.me/api/current?lat=35&lon=139
And here's my code:
public class MainActivity extends AppCompatActivity {
Button btnHit;
TextView txtJson;
ProgressDialog pd;
ArrayMap<Integer, String> arrayMap = new ArrayMap<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnHit = (Button) findViewById(R.id.btnHit);
txtJson = (TextView) findViewById(R.id.tvJsonItem);
btnHit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
new JsonTask().execute("https://fcc-weather-api.glitch.me/api/current?lat=35&lon=139");
}
});
}
public class JsonTask extends AsyncTask<String, String, String> {
protected void onPreExecute() {
super.onPreExecute();
pd = new ProgressDialog(MainActivity.this);
pd.setMessage("Please wait");
pd.setCancelable(false);
pd.show();
}
protected String doInBackground(String... params) {
HttpURLConnection connection = null;
BufferedReader reader = null;
try {
URL url = new URL(params[0]);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
InputStream stream = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(stream));
StringBuffer buffer = new StringBuffer();
String line = "";
while ((line = reader.readLine()) != null) {
buffer.append(line + "\n");
Log.d("Response: ", "> " + line);
}
return buffer.toString();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException 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);
if (pd.isShowing()) {
pd.dismiss();
}
try {
JSONObject Object = new JSONObject(result);
JSONArray arr = new JSONArray(Object.getString("weather"));
for (int i = 0; i < arr.length(); i++) {
JSONObject jsonPart = arr.getJSONObject(i);
//txtJson.append("main: " + jsonPart.getString("main") + '\n');
arrayMap.put(i, jsonPart.getString("main"));
txtJson.append("main: " + arrayMap.get(i) + '\n');
}
} catch (JSONException e) {
e.printStackTrace();
//txtJson.setText(result);
}
//txtJson.setText(result);
}
}
}
If I understand correctly you want to extract other object alongwith main from the array weather
"weather": [
{
"id": 701,
"main": "Mist",
"description": "mist",
"icon": "https://cdn.glitch.com/6e8889e5-7a72-48f0-a061-863548450de5%2F50n.png?1499366021876"
}
If that is the requirement then you can use the same process like you have done just change the name of the object.
arrayMap.put(i, jsonPart.getString("description"));
or
you can use gson and convert the object in pojo class in one go. Then use the object of the pojo and access the data.
Hope it helps.
In my code i had caught data from a JSON file,
I executed the program, it stopped but didn't crash.
i've tried to change json file. I found one that is Smaller than the first one and so the program works.
this JSON file is made of data o premier legue(England) and contain 3 mainly data, the name, a key and a code of the squads.
public class MainActivity extends AppCompatActivity {
private ProgressDialog caric;
private String TAG = MainActivity.class.getSimpleName();
public ArrayMap<Integer, Valori> ArrayDati = new ArrayMap<>();
Button buttonProg;
TextView textViewProg;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
buttonProg = (Button) findViewById(R.id.button);
textViewProg = (TextView) findViewById(R.id.textView);
buttonProg.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
new JsonCLASS().execute("https://raw.githubusercontent.com/openfootball/football.json/master/2015-16/en.1.clubs.json");
}
});
}
private class JsonCLASS extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
caric = new ProgressDialog(MainActivity.this);
caric.setMessage("Please wait");
caric.setCancelable(false);
caric.show();
}
#Override
protected String doInBackground(String... params) {
HttpURLConnection connection = null;
BufferedReader reader = null;
try {
URL url = new URL(params[0]);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
InputStream stream = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(stream));
StringBuffer buffer = new StringBuffer();
String line = "";
while ((line = reader.readLine()) != null) {
buffer.append(line + "\n");
Log.d("Response: ", "> " + line);
}
return buffer.toString();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException 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);
try {
JSONObject jsonObject = new JSONObject(result);
JSONArray Arr = new JSONArray(jsonObject.getString("clubs"));
for (int i = 0; i < Arr.length(); i++){
JSONObject jsonPart = Arr.getJSONObject(i);
ArrayDati.put(i,new Valori( jsonPart.getString("key"), jsonPart.getString("name"), jsonPart.getString("code")));
textViewProg.setText(textViewProg.getText()+"key : "+ ArrayDati.get(i).Key
+"\n"+textViewProg.getText()+"name : "+ ArrayDati.get(i).Name
+"\n"+textViewProg.getText()+"code : "+ ArrayDati.get(i).Code );
}
} catch (Exception e ){
e.printStackTrace();
}
if (caric.isShowing()) {
caric.dismiss();
}
}
}
}
And a class to pass the data
public class Valori {
String Key;
String Name;
String Code;
public Valori(String key, String name, String code) {
this.Key = key;
this.Name = name;
this.Code = code;
}
}
With this code the application stops but it doesn't close.
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();
}
}
}
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;
}