Get a Number from a String with substring() is no working - android

I want to get an Number from a String.
My Code for this Class is:
The XML is download correct, it founds my Value String but i get not the number from the String.
public class XMLProcessor extends AsyncTask<String, Void, String> {
private String rssURL;
private PostParserDelegate delegate;
private ArrayList<Post> posts;
String euro;
private StringBuilder buffer;
TextView mxntoeur;
TextView eurtomxn;
public XMLProcessor(String rssURL, PostParserDelegate delegate) {
this.rssURL = rssURL;
this.delegate = delegate;
posts = new ArrayList<Post>();
}
#Override
protected String doInBackground(String... strings) {
buffer = new StringBuilder();
try {
URL url = new URL(rssURL);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
// HTTP Status "OK" -> HTTPCODE 200
int httpResponse = httpURLConnection.getResponseCode();
if ( httpResponse != 200) {
throw new Exception("Fehlercode: " + httpResponse);
}
InputStream input = httpURLConnection.getInputStream();
InputStreamReader reader = new InputStreamReader(input);
int charactersRead;
char[] tmpChars = new char[400];
while (true) {
charactersRead = reader.read(tmpChars);
if (charactersRead <= 0) {
break;
}
buffer.append(String.copyValueOf(tmpChars, 0, charactersRead));
}
return buffer.toString();
} catch (Exception e) {
Log.e("XMLProcessor", e.getMessage());
Log.e("XMLProcessor", e.getStackTrace().toString());
}
return String.valueOf(0);
}
#Override
protected void onPostExecute(String aDouble) {
super.onPostExecute(aDouble);
parse();
}
protected void parse()
{
String rawXML = buffer.toString();
Post aPost = null;
boolean isProcessingItem = false;
String innerValue ="";
try {
XmlPullParserFactory pullParserFactory = XmlPullParserFactory.newInstance();
XmlPullParser parser = pullParserFactory.newPullParser();
parser.setInput(new StringReader(rawXML));
int event = parser.getEventType();
while (event !=XmlPullParser.END_DOCUMENT)
{
String tag = parser.getName();
switch ( event) {
case XmlPullParser.START_TAG:
if (tag == "item" ) {
Log.d("XMLProcessor", "Neuer Post!");
isProcessingItem = true;
aPost = new Post();
}
break;
case XmlPullParser.TEXT:
innerValue = parser.getText();
break;
case XmlPullParser.END_TAG:
if (isProcessingItem){
if (tag == "item") {
posts.add(aPost);
isProcessingItem = false;
}
} else if ( tag == "description") {
aPost.setPesoInEuro(innerValue);
euro = new String(innerValue.substring(13,21));
//euro = innerValue.substring(13,21);
eurtomxn.setText(euro);
}
break;
}
event = parser.next();
}
delegate.xmlFeedParsed(posts);
} catch (Exception e) {
Log.e("XMLProcess", e.getStackTrace().toString());
}
}
}
In innerValue i get the Correct Sting what i need
/n 1.00 EUR = 21.90612 MXN<br/>\n 1.00 MXN = 0.04565 EUR<br/>\n
Converter--\n
<a href="http://eur.de.fxexchangerate.com/mxn-exchange-rates-history.html">Historische
</a>
\n.
But my problem is, that i need this Number 21.90612. I have try it with substring(13,21), but it was no working.
Have you a idea, how i can fix my problem?
Thank you

It's not very clear what exactly is the Problem, it would be useful if you show the Exception!
Have you checked if the String innerValue has a valid lenght?
if(innerValue.lenght() >= 21){euro = innerValue.substring(13,21);} else {/* Do something here!*/}
}

Related

Text in textview is not showing strings from java file - openweathermap

I am trying to use openweathermap to get basic data about weather and paste it into textview, but strings to which I am getting data doesn't refresh texts in textviews.
Code:
#SuppressLint("StaticFieldLeak")
class DownloadJSON extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... strings) {
URL url;
HttpURLConnection httpURLConnection;
InputStream inputStream;
InputStreamReader inputStreamReader;
StringBuilder result = new StringBuilder();
try {
url = new URL(strings[0]);
httpURLConnection = (HttpURLConnection) url.openConnection();
inputStream = httpURLConnection.getInputStream();
inputStreamReader = new InputStreamReader(inputStream);
int data = inputStreamReader.read();
while (data != -1) {
result.append((char) data);
}
} catch (IOException e) {
e.printStackTrace();
}
return result.toString();
}
}
txtCity = findViewById(R.id.txtCity);
txtTemp = findViewById(R.id.txtTemp);
DownloadJSON downloadJSON = new DownloadJSON();
try {
String result = downloadJSON.execute(url).get();
JSONObject jsonObject = new JSONObject(result);
String temp = jsonObject.getJSONObject("main").getString("temp");
String feel_like = jsonObject.getJSONObject("main").getString("feels_like");
txtCity.setText(City);
txtValueFeelLike.setText(feel_like);
txtTemp.setText(temp);
} catch (ExecutionException | InterruptedException | JSONException e) {
e.printStackTrace();
}
}
'''
String City = "Warsaw";
String url = "http://api.openweathermap.org/data/2.5/weather?q="+City+"&units=metric&appid=eace0bd8251cf6ab043ab9858b796256";
TextView txtCity, txtValueFeelLike, txtTemp;
What am I doing wrong?
Ok, I made a change, tried to make it from the scratch again, but now with onPostExecute(). Still nothing...
public class Weather {
private static final String OPEN_WEATHER_MAP_URL =
"http://api.openweathermap.org/data/2.5/weather?q=Warsaw&units=metric&appid=eace9b6857889076855263cfdb5707c0d00";
public interface AsyncResponse {
void processFinish(String output1, String output2, String output3, String output4, String output5, String output6);
}
public static class placeIdTask extends AsyncTask<String, Void, JSONObject> {
public AsyncResponse delegate = null;//Call back interface
#Override
protected JSONObject doInBackground(String... params) {
JSONObject jsonWeather = null;
try {
jsonWeather = getWeatherJSON();
} catch (Exception e) {
Log.d("Error", "Cannot process JSON results", e);
}
return jsonWeather;
}
#Override
public void onPostExecute(JSONObject json) {
try {
if(json != null){
JSONObject details = json.getJSONArray("weather").getJSONObject(0);
JSONObject main = json.getJSONObject("main");
DateFormat df = DateFormat.getDateTimeInstance();
String city = json.getString("name").toUpperCase(Locale.US) + ", " + json.getJSONObject("sys").getString("country");
String description = details.getString("description").toUpperCase(Locale.US);
#SuppressLint("DefaultLocale") String temperature = String.format("%.2f", main.getDouble("temp"))+ "°";
String humidity = main.getString("humidity") + "%";
String pressure = main.getString("pressure") + " hPa";
String updatedOn = df.format(new Date(json.getLong("dt")*1000));
delegate.processFinish(city, description, temperature, humidity, pressure, updatedOn);
}
} catch (JSONException e) {
}
}
}
public static JSONObject getWeatherJSON() {
try {
URL url = new URL(OPEN_WEATHER_MAP_URL);
HttpURLConnection connection =
(HttpURLConnection) url.openConnection();
BufferedReader reader = new BufferedReader(
new InputStreamReader(connection.getInputStream()));
StringBuilder json = new StringBuilder(1024);
String tmp = "";
while ((tmp = reader.readLine()) != null)
json.append(tmp).append("\n");
reader.close();
JSONObject data = new JSONObject(json.toString());
// This value will be 404 if the request was not
// successful
if (data.getInt("cod") != 200) {
return null;
}
return data;
} catch (Exception e) {
return null;
}
}}
And Main Activity:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
cityField = (TextView) findViewById(R.id.city_field);
updatedField = (TextView) findViewById(R.id.updated_field);
detailsField = (TextView) findViewById(R.id.details_field);
currentTemperatureField = (TextView) findViewById(R.id.current_temperature_field);
humidity_field = (TextView) findViewById(R.id.humidity_field);
pressure_field = (TextView) findViewById(R.id.pressure_field);
Weather.placeIdTask asyncTask = new Weather.placeIdTask() {
public void processFinish(String weather_city, String weather_description, String weather_temperature, String weather_humidity, String weather_pressure, String weather_updatedOn) {
cityField.setText(weather_city);
updatedField.setText(weather_updatedOn);
detailsField.setText(weather_description);
currentTemperatureField.setText(weather_temperature);
humidity_field.setText("Humidity: " + weather_humidity);
pressure_field.setText("Pressure: " + weather_pressure);
}
};
No idea what to do now.

How to display a message/toast if JSON response is null

I'm searching an api from an android app and I would like to display a Toast/error message to the user when the search returns no results from the api.
When the api returns no results the following is displayed to the logs:
{boards: null}
This is where I would like to display a message/toast.
I have tried:
if (name.equals ("null");
also many other 'solutions' that i've found, but none seem to work.
please see code below:
public class apitestsearch extends AppCompatActivity {
EditText boardName;
TextView resultView;
public void findBoard (View view){
// Log.i("board", boardName.getText().toString());
InputMethodManager mgr = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
mgr.hideSoftInputFromWindow(boardName.getWindowToken(), 0);
DownloadTask task = new DownloadTask();
task.execute("https://www.api.com/airquality/api/json.php?boardID="+ boardName.getText().toString());
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_apitestsearch);
boardName = (EditText)findViewById(R.id.boardName);
resultView = (TextView) findViewById(R.id.resultView);
}
public class DownloadTask extends AsyncTask<String, Void, String>{
#Override
protected String doInBackground(String... urls) {
String result = "";
URL url;
HttpURLConnection urlConnection = null;
try {
url = new URL(urls[0]);
urlConnection = (HttpURLConnection) url.openConnection();
InputStream in = urlConnection.getInputStream();
InputStreamReader reader = new InputStreamReader(in);
int data = reader.read();
while (data != -1)
{
char current = (char) data;
result += current;
data = reader.read();
}
return result;
} catch (Exception e) {
Toast.makeText(getApplicationContext(), "No results found", Toast.LENGTH_SHORT);
}
return null;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
try {
String message = " ";
JSONObject jsonObject = new JSONObject(result);
String board = jsonObject.getString("boards");
// Log.i("boardID", board);
JSONArray arr = new JSONArray(board);
for(int i = 0; i < 1; i++)
{
JSONObject jsonPart = arr.getJSONObject(i);
String name = "";
name = jsonPart.getString("boardID");
if(name != ""){
message += name + "\r\n";
}
}
if (message != "") {
resultView.setText(message);
}
} catch (JSONException e) {
Toast.makeText(getApplicationContext(), "No results found", Toast.LENGTH_SHORT);
}
// Log.i("Content", result);
}
}
}
You can try this.
if(jsonObject.isNull("boards")){
// null handling goes here..
}else{
String board = jsonObject.getString("boards");
}
and if you want to use board as globally then
String board;
if(jsonObject.isNull("boards")){
// null handling goes here..
}else{
board = jsonObject.getString("boards");
}
and more short
String board;
if(!jsonObject.isNull("boards")){
board = jsonObject.getString("boards");
}
String board = "Not available";
//null check
if(!jsonObject.isNull("boards")){
board = jsonObject.getString("boards");
}else{
// your toast
Toast.makeText(context, "Board " + board, Toast.LENGTH_SHORT).show();
}

How to Pass Context OF one Activity to Another Non Activity Class In Android

hello i want to get string from activity and set it to the another non activity class please help me i am adding my code.and i need to set the edittext value in non activity class url. help me
my activity.
public class AlertForIp extends AppCompatActivity {
String value;
private Button mButton;
final Context c = this;
static String urlString;
private static AlertForIp instance;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.dialog);
instance = this;
final EditText input = new EditText(AlertForIp.this);
final AlertDialog.Builder alertDialog = new AlertDialog.Builder(AlertForIp.this);
//AlertDialog alertDialog = new AlertDialog.Builder(MainActivity.this).create();
/* SharedPreferences prefss = PreferenceManager.getDefaultSharedPreferences(AlertForIp.this);
final SharedPreferences.Editor editor = prefss.edit();*/
value = input.getText().toString();
// Setting Dialog Title
String urlsss="http://";
String urls=":1219/Json/Handler.ashx";
// This above url string i need to set in that class
urlString = urlsss+value+urls;
/* editor.putString("stringid", urlString); //InputString: from the EditText
editor.commit();
*/
alertDialog.setTitle("WELCOME TO RESTROSOFT");
// Setting Dialog Message
alertDialog.setMessage("ENTER YOUR IP");
//final EditText input = new EditText(this);
//alertDialog.setView(input);
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.MATCH_PARENT);
input.setLayoutParams(lp);
//input.setText("http://");
InputFilter[] filters = new InputFilter[1];
filters[0] = new InputFilter() {
#Override
public CharSequence filter(CharSequence source, int start, int end,
android.text.Spanned dest, int dstart, int dend) {
if (end > start) {
String destTxt = dest.toString();
String resultingTxt = destTxt.substring(0, dstart)
+ source.subSequence(start, end)
+ destTxt.substring(dend);
if (!resultingTxt
.matches("^\\d{1,3}(\\.(\\d{1,3}(\\.(\\d{1,3}(\\.(\\d{1,3})?)?)?)?)?)?")) {
return "";
} else {
String[] splits = resultingTxt.split("\\.");
for (int i = 0; i < splits.length; i++) {
if (Integer.valueOf(splits[i]) > 255) {
Toast.makeText(AlertForIp.this, "Please enter valid ip", Toast.LENGTH_SHORT).show();
return "";
}
}
}
}
return null;
}
};
input.setFilters(filters);
//input.setText(ip);
alertDialog.setView(input); //
// Setting Icon to Dialog
alertDialog.setIcon(R.drawable.waiting);
// Setting Positive "Yes" Button
alertDialog.setPositiveButton("YES",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
/*if(input.getText().length()==0)
{
input.setError("Field cannot be left blank.");
dialog.dismiss();
}*/
String validation="^\\d{1,3}(\\.(\\d{1,3}(\\.(\\d{1,3})?)?)?)?";
if (value.matches(validation))
{
Toast.makeText(getApplicationContext(),"enter valid IP address",Toast.LENGTH_SHORT).show();
Intent inten = new Intent(AlertForIp.this, AlertForIp.class);
startActivity(inten);
// or
}
else if(!input.getText().toString().equals(""))
{
Intent intent = new Intent(AlertForIp.this, Sample.class);
startActivity(intent);
//Toast.makeText(AlertDialogForIp.this, "Input Text Is Empty.. Please Enter Some Text", Toast.LENGTH_SHORT).show();
}
else
{
Intent inten = new Intent(AlertForIp.this, AlertForIp.class);
startActivity(inten);
Toast.makeText(AlertForIp.this, "Input Text Is Empty.. Please Enter Some Text", Toast.LENGTH_SHORT).show();
}
}
});
// Setting Negative "NO" Button
alertDialog.setNegativeButton("NO",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// Write your code here to execute after dialog
//dialog.cancel();
finish();
}
});
// closed
// Showing Alert Message
alertDialog.show();
}
public static Context getContext() {
RestAPI rss=new RestAPI();
rss.persistItems(urlString);
return instance.getApplicationContext();
}
}
And here is my no activity class
public class RestAPI {
String urlString;
//String data;
public void persistItems(String info) {
Context context = AlertForIp.getContext();
/* SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
data = prefs.getString("stringid", "no id");*/
urlString=info;
}
//private final String urlString = "http://10.0.2.2:1219/Json/Handler.ashx";
private static String convertStreamToUTF8String(InputStream stream) throws IOException {
String result = "";
StringBuilder sb = new StringBuilder();
try {
InputStreamReader reader = new InputStreamReader(stream, "UTF-8");
char[] buffer = new char[4096];
int readedChars = 0;
while (readedChars != -1) {
readedChars = reader.read(buffer);
if (readedChars > 0)
sb.append(buffer, 0, readedChars);
}
result = sb.toString();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return result;
}
private String load(String contents) throws IOException {
//i want to add that urlstring here;
URL url = new URL(urlString);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setConnectTimeout(60000);
conn.setDoOutput(true);
conn.setDoInput(true);
OutputStreamWriter w = new OutputStreamWriter(conn.getOutputStream());
w.write(contents);
w.flush();
InputStream istream = conn.getInputStream();
String result = convertStreamToUTF8String(istream);
return result;
}
private Object mapObject(Object o) {
Object finalValue = null;
if (o.getClass() == String.class) {
finalValue = o;
} else if (Number.class.isInstance(o)) {
finalValue = String.valueOf(o);
} else if (Date.class.isInstance(o)) {
SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy hh:mm:ss", new Locale("en", "USA"));
finalValue = sdf.format((Date) o);
} else if (Collection.class.isInstance(o)) {
Collection<?> col = (Collection<?>) o;
JSONArray jarray = new JSONArray();
for (Object item : col) {
jarray.put(mapObject(item));
}
finalValue = jarray;
} else {
Map<String, Object> map = new HashMap<String, Object>();
Method[] methods = o.getClass().getMethods();
for (Method method : methods) {
if (method.getDeclaringClass() == o.getClass()
&& method.getModifiers() == Modifier.PUBLIC
&& method.getName().startsWith("get")) {
String key = method.getName().substring(3);
try {
Object obj = method.invoke(o, null);
Object value = mapObject(obj);
map.put(key, value);
finalValue = new JSONObject(map);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
return finalValue;
}
public JSONObject CreateNewAccount(String User_Name, String Password) throws Exception {
JSONObject result = null;
JSONObject o = new JSONObject();
JSONObject p = new JSONObject();
o.put("interface", "RestAPI");
o.put("method", "CreateNewAccount");
p.put("User_Name", mapObject(User_Name));
p.put("Password", mapObject(Password));
o.put("parameters", p);
String s = o.toString();
String r = load(s);
result = new JSONObject(r);
return result;
}
This is my another Activity i have created the instance of restApi
public class UserDetailsActivity extends Activity {
TextView tvFisrtName, tvLastName;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_user_details);
// Show the Up button in the action bar.
//setupActionBar();
tvFisrtName=(TextView)findViewById(R.id.tv_firstname);
tvLastName=(TextView)findViewById(R.id.tv_lastname);
Intent i=getIntent();
String username=i.getStringExtra("User_Name");
new AsyncUserDetails().execute(username);
}
/**
* Set up the {#link android.app.ActionBar}, if the API is available.
*/
#TargetApi(Build.VERSION_CODES.HONEYCOMB)
private void setupActionBar() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
//getActionBar().setDisplayHomeAsUpEnabled(true);
}
}
protected class AsyncUserDetails extends AsyncTask<String,Void,JSONObject>
{
String str1;
#Override
protected JSONObject doInBackground(String... params) {
// TODO Auto-generated method stub
JSONObject jsonObj = null;
//here i have error
RestAPI api = new RestAPI();
try {
jsonObj = api.GetUserDetails(params[0]);
//JSONParser parser = new JSONParser();
//userDetail = parser.parseUserDetails(jsonObj);
} catch (Exception e) {
// TODO Auto-generated catch block
Log.d("AsyncUserDetails", e.getMessage());
}
return jsonObj;
}
#Override
protected void onPostExecute(JSONObject result) {
// TODO Auto-generated method stub
try {
JSONObject jsonObj=result.getJSONArray("Value").getJSONObject(0);
str1=jsonObj.getString("user_id").toString();
} catch (JSONException e) {
e.printStackTrace();
}
Toast.makeText(UserDetailsActivity.this, str1, Toast.LENGTH_SHORT).show();
tvFisrtName.setText(str1);
}
}
public class RestAPI {
String url;
// create constructor here
public RestAPI(String url){
this.url=url;
}
String urlString;
//String data;
public void persistItems(String info) {
Context context = AlertForIp.getContext();
/* SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
data = prefs.getString("stringid", "no id");*/
urlString=info;
}
//private final String urlString = "http://10.0.2.2:1219/Json/Handler.ashx";
private static String convertStreamToUTF8String(InputStream stream) throws IOException {
String result = "";
StringBuilder sb = new StringBuilder();
try {
InputStreamReader reader = new InputStreamReader(stream, "UTF-8");
char[] buffer = new char[4096];
int readedChars = 0;
while (readedChars != -1) {
readedChars = reader.read(buffer);
if (readedChars > 0)
sb.append(buffer, 0, readedChars);
}
result = sb.toString();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return result;
}
private String load(String contents) throws IOException {
//i want to add that urlstring here;
now you can use here url directly
URL url = new URL(urlString);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setConnectTimeout(60000);
conn.setDoOutput(true);
conn.setDoInput(true);
OutputStreamWriter w = new OutputStreamWriter(conn.getOutputStream());
w.write(contents);
w.flush();
InputStream istream = conn.getInputStream();
String result = convertStreamToUTF8String(istream);
return result;
}
private Object mapObject(Object o) {
Object finalValue = null;
if (o.getClass() == String.class) {
finalValue = o;
} else if (Number.class.isInstance(o)) {
finalValue = String.valueOf(o);
} else if (Date.class.isInstance(o)) {
SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy hh:mm:ss", new Locale("en", "USA"));
finalValue = sdf.format((Date) o);
} else if (Collection.class.isInstance(o)) {
Collection<?> col = (Collection<?>) o;
JSONArray jarray = new JSONArray();
for (Object item : col) {
jarray.put(mapObject(item));
}
finalValue = jarray;
} else {
Map<String, Object> map = new HashMap<String, Object>();
Method[] methods = o.getClass().getMethods();
for (Method method : methods) {
if (method.getDeclaringClass() == o.getClass()
&& method.getModifiers() == Modifier.PUBLIC
&& method.getName().startsWith("get")) {
String key = method.getName().substring(3);
try {
Object obj = method.invoke(o, null);
Object value = mapObject(obj);
map.put(key, value);
finalValue = new JSONObject(map);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
return finalValue;
}
public JSONObject CreateNewAccount(String User_Name, String Password) throws Exception {
JSONObject result = null;
JSONObject o = new JSONObject();
JSONObject p = new JSONObject();
o.put("interface", "RestAPI");
o.put("method", "CreateNewAccount");
p.put("User_Name", mapObject(User_Name));
p.put("Password", mapObject(Password));
o.put("parameters", p);
String s = o.toString();
String r = load(s);
result = new JSONObject(r);
return result;
}
use here
RestAPI rss=new RestAPI(urlString );

how to consume data in rest api that returns xml data in android

please can anybody tell how to consume rest API in android that returns xml data.there are so many example with JSON.but I need to response in xml format ...can anybody tell how to do that please help me thanks in advance.
You can try something like this
private class CallAPI extends AsyncTask<String, String, String> {
#Override
protected String doInBackground(String... params) {
String urlString=params[0]; // URL to call
String schid="";
String resultToDisplay = "";
InputStream in = null;
Result result = null ;
// HTTP Get
try {
URL url = new URL(urlString);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
in = new BufferedInputStream(urlConnection.getInputStream());
//resultToDisplay +="&" + URLEncoder.encode("data", "UTF-8") ;
} catch (Exception e ) {
System.out.println(e.getMessage());
return e.getMessage();
}
// Parse XML
XmlPullParserFactory pullParserFactory;
try {
pullParserFactory = XmlPullParserFactory.newInstance();
XmlPullParser parser = pullParserFactory.newPullParser();
parser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, false);
parser.setInput(in, null);
result = parseXML(parser);
} catch (XmlPullParserException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
// Simple logic to determine if the email is dangerous, invalid, or valid
if (result != null ) {
if( result.hygieneResult.equals("Spam Trap")) {
resultToDisplay = "Dangerous, please correct";
}
else if( Integer.parseInt(result.statusNbr) >= 300) {
resultToDisplay = "Invalid, please re-enter";
}
else {
resultToDisplay = "Thank you for your submission";
}
}
else {
resultToDisplay = "Exception Occured";
}
return resultToDisplay;
}
protected void onPostExecute(String schid) {
if(schid == null) {
schid = "THERE WAS AN ERROR";
}
Intent intent = new Intent(getApplicationContext(), ResultActivity.class);
intent.putExtra(EXTRA_MESSAGE, schid);
startActivity(intent);
}
private Result parseXML( XmlPullParser parser ) throws XmlPullParserException, IOException {
int eventType = parser.getEventType();
Result result = new Result();
while( eventType!= XmlPullParser.END_DOCUMENT) {
String strid = null;
switch(eventType)
{
case XmlPullParser.START_TAG:
strid = parser.toString();
//name=parser.getName();
if( strid.equals("Error")) {
System.out.println("Web API Error!");
}
else if ( strid.equals("StatusNbr")) {
result.statusNbr = parser.nextText();
}
else if (strid.equals("HygieneResult")) {
result.hygieneResult = parser.nextText();
}
break;
case XmlPullParser.END_TAG:
break;
} // end switch
eventType = parser.next();
} // end while
return result;
}
} // end CallAPI
Now in your activity
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#Override
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;
}
// This is the method that is called when the submit button is clicked
public void verifyDetails(View view) {
EditText schidEditText = (EditText) findViewById(R.id.sch_id);
String schid = schidEditText.getText().toString();
if( schid != null && !schid.isEmpty()) {
String urlString = apiURL + "schid:" + schid.toString();
//String urlString = apiURL + "LicenseInfo.RegisteredUser.UserID=" + strikeIronUserName + "&LicenseInfo.RegisteredUser.Password=" + strikeIronPassword + "&VerifyEmail.Email=" + email + "&VerifyEmail.Timeout=30";
new CallAPI().execute(urlString);
}
}
}
You need to use DocumentBuilderFactory for Parsing XML using Java
You can find a good tutorial for this on that place XML and Java - Parsing XML using Java
Check Xml Parsing Tuotorial using DOM parser
also Xml Parsing Tuotorial using XML pull parser

Android Async Task Freezes UI Completely

I have an Async task that loads information from the server and displays data on the UI. Suddenly the async task downloads the data and formats the JSON data fine but it would freeze the UI completely.
Here is the base download class
public class GetRawData {
private static String LOG_TAG = GetRawData.class.getSimpleName();
private String mRawURL;
private List<NameValuePair> mRawParams = null;
private String mRawData;
private DownloadStatus mDownloadStatus;
public GetRawData(String mRawURL) {
this.mRawURL = mRawURL;
this.mRawParams = null;
this.mDownloadStatus = DownloadStatus.IDLE;
}
public String getRawData() {
return mRawData;
}
public void setRawURL(String mRawURL) {
this.mRawURL = mRawURL;
}
public List<NameValuePair> getRawParams() {
return mRawParams;
}
public void setRawParams(List<NameValuePair> mParams) {
this.mRawParams = mParams;
}
public DownloadStatus getDownloadStatus() {
return mDownloadStatus;
}
public void reset() {
this.mRawURL = null;
this.mRawData = null;
this.mDownloadStatus = DownloadStatus.IDLE;
}
public void execute() {
this.mDownloadStatus = DownloadStatus.PROCESSING;
DownloadRawData mDownloadRawData = new DownloadRawData();
mDownloadRawData.execute(mRawURL);
}
public class DownloadRawData extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
// Create URL and Reader instances.
HttpURLConnection urlConnection = null;
BufferedReader reader = null;
//If no parameter has been provided, return null.
if (params == null)
return null;
try {
// Get URL entered by the user.
URL mURL = new URL(params[0]);
urlConnection = (HttpURLConnection) mURL.openConnection();
urlConnection.setDoOutput(true);
urlConnection.setRequestMethod("POST");
urlConnection.setUseCaches(false);
urlConnection.setConnectTimeout(10000);
urlConnection.setReadTimeout(10000);
urlConnection.setRequestProperty("Content-Type","application/json");
//urlConnection.setRequestProperty("Host", "android.schoolportal.gr");
urlConnection.connect();
// validate and add parameters if available.
if (mRawParams != null && mRawParams.size()>0){
JSONObject jsonParam = new JSONObject();
for (NameValuePair pair : mRawParams) {
jsonParam.put(pair.getName().toString(), pair.getValue().toString());
}
String jsonparams = jsonParam.toString();
// Send POST output.
DataOutputStream printout;
printout = new DataOutputStream(urlConnection.getOutputStream());
printout.writeBytes(jsonparams);
printout.flush();
printout.close();
}
int HttpResult =urlConnection.getResponseCode();
StringBuffer buffer = new StringBuffer();
if(HttpResult ==HttpURLConnection.HTTP_OK){
InputStream inputStream = urlConnection.getInputStream();
if (inputStream == null) {
return null;
}
reader = new BufferedReader(new InputStreamReader(inputStream));
String line;
while ((line = reader.readLine()) != null) {
buffer.append(line + "\n");
}
System.out.println(""+buffer.toString());
}else{
InputStream errorStream = urlConnection.getErrorStream();
if (errorStream == null) {
return null;
}
reader = new BufferedReader(new InputStreamReader(errorStream));
String line;
while ((line = reader.readLine()) != null) {
buffer.append(line + "\n");
}
System.out.println(urlConnection.getResponseMessage());
}
return buffer.toString();
} catch (IOException e) {
Log.d("IOException", e.toString());
return null;
} catch (JSONException j) {
Log.d("JSONException", j.toString());
return null;
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
Log.d("IOException", "unable to close the reader");
}
}
}
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
mRawData = result;
//Log.d("onPostExecute", result);
if (mRawData == null) {
if (mRawURL == null) {
mDownloadStatus = DownloadStatus.NOT_INITIALIZED;
} else {
mDownloadStatus = DownloadStatus.FAILED_OR_EMPTY;
}
} else {
mDownloadStatus = DownloadStatus.PROCESSED;
}
}
private String getQuery(List<NameValuePair> params) throws UnsupportedEncodingException {
StringBuilder result = new StringBuilder();
boolean first = true;
for (NameValuePair pair : params) {
if (first)
first = false;
else
result.append("&");
result.append(URLEncoder.encode(pair.getName(), "UTF-8"));
result.append("=");
result.append(URLEncoder.encode(pair.getValue(), "UTF-8"));
}
return result.toString();
}
}
}
enum DownloadStatus {
IDLE,
PROCESSING,
NOT_INITIALIZED,
FAILED_OR_EMPTY,
PROCESSED
}
Here is the specific data formatting class the extends above class
public class GetJobCardJsonData extends GetRawData {
private static String LOG_TAG = GetAuthenticationJsonData.class.getSimpleName();
private static String JOBCARD_SERVICE_URL = "http://www.appservice.com/appservice/jobcardinfoservice.asmx/GetJobCardInfo";
private List<JobCard> mJobCardList;
private CarcalDownloadListener mListener;
public GetJobCardJsonData(String CurrentDate, int DealershipID) {
super(null);
List<NameValuePair> mParams = new ArrayList<NameValuePair>();
mParams.add(new BasicNameValuePair("JobCardDate", CurrentDate));
mParams.add(new BasicNameValuePair("DealershipID", String.valueOf(DealershipID)));
this.setRawParams(mParams);
}
public List<JobCard> getJobCardList() {
return mJobCardList;
}
public void getjobcards() {
super.setRawURL(JOBCARD_SERVICE_URL);
DownloadJobCardJsonData mDownloadJobCardJsonData = new DownloadJobCardJsonData();
mDownloadJobCardJsonData.execute(JOBCARD_SERVICE_URL);
}
public void setOnCarcalDownloadListener(CarcalDownloadListener onCarcalDownloadListener) {
this.mListener = onCarcalDownloadListener;
}
private void processResult() {
if (getDownloadStatus() != DownloadStatus.PROCESSED) {
Log.e(LOG_TAG, "Error Downloading the raw file.");
return;
}
if (mJobCardList == null){
mJobCardList = new ArrayList<JobCard>();
}
final String JOBCARD_JOBCARDID = "JobCardID";
final String JOBCARD_GETSTOCKNUMBER_WITH_DELIVERYTIME = "StockNumberWithDeliveryTime";
final String JOBCARD_CUSTOMERNAME = "CustomerName";
final String JOBCARD_MODELNUMBER = "ModelNumber";
final String JOBCARD_COLOR = "Color";
final String JOBCARD_SALEEXECUTIVE = "SaleExecutive";
final String JOBCARD_ORDERSTATUS = "OrderStatus";
final String JOBCARD_SHOWROOMSTATUS = "ShowRoomStatus";
try {
JSONArray jsonArray = new JSONArray(getRawData());
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jobcarditem = jsonArray.optJSONObject(i);
Long JOBCARDID = jobcarditem.getLong(JOBCARD_JOBCARDID);
String STOCKWITHDELIVERY = jobcarditem.getString(JOBCARD_GETSTOCKNUMBER_WITH_DELIVERYTIME);
String CUSTOMERNAME = jobcarditem.getString(JOBCARD_CUSTOMERNAME);
String MODELNUMBER = jobcarditem.getString(JOBCARD_MODELNUMBER);
String COLOR = jobcarditem.getString(JOBCARD_COLOR);
String SALEEXECUTIVE = jobcarditem.getString(JOBCARD_SALEEXECUTIVE);
int ORDERSTATUS = jobcarditem.getInt(JOBCARD_ORDERSTATUS);
int SHOWROOMSTATUS = jobcarditem.getInt(JOBCARD_SHOWROOMSTATUS);
JobCard mJobCard = new JobCard(JOBCARDID, STOCKWITHDELIVERY, CUSTOMERNAME, MODELNUMBER, COLOR, SALEEXECUTIVE, ORDERSTATUS, SHOWROOMSTATUS);
mJobCardList.add(mJobCard);
}
} catch (JSONException jsone) {
jsone.printStackTrace();
Log.e(LOG_TAG, "Error processing json data.");
}
}
public class DownloadJobCardJsonData extends DownloadRawData {
#Override
protected String doInBackground(String... params) {
return super.doInBackground(params[0]);
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
processResult();
mListener.OnDownloadCompleted();
}
}
}
Here is the code that is called on the activity
private JobCardRecyclerViewAdapter mJobCardRecyclerViewAdapter;
private GetJobCardJsonData mGetJobCardJsonData;
SessionManager session;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_job_card_calender);
activateToolbarWithHomeEnabled();
String formattedDate="";
if (session.getCurrentDate() == ""){
Calendar c = Calendar.getInstance();
SimpleDateFormat df = new SimpleDateFormat("MM/dd/yyyy");
formattedDate = df.format(c.getTime());
currentDateTextView.setText(formattedDate);
}else {
formattedDate = session.getCurrentDate();
currentDateTextView.setText(formattedDate);
}
// Fetch data for current date.
mGetJobCardJsonData = new GetJobCardJsonData(formattedDate, session.getDealershipID());
mGetJobCardJsonData.getjobcards();
mGetJobCardJsonData.setOnCarcalDownloadListener(new CarcalDownloadListener() {
#Override
public void OnDownloadCompleted() {
List<JobCard> mJobCards = mGetJobCardJsonData.getJobCardList();
mJobCardRecyclerViewAdapter = new JobCardRecyclerViewAdapter(mJobCards, JobCardCalenderActivity.this);
mRecyclerView.setAdapter(mJobCardRecyclerViewAdapter);
}
});
}
Can anyone help on what i am doing wrong that is freezing the UI. It was working fine before and has started to freeze the UI suddenly.
I was able to fix the issue, the problem was not with Async task but with the layout. I accidently wrapped the recycler view with scroll view. which was causing the UI to freeze. Looks weird that a scroll view caused the whole UI thread to freeze. but here is my solution
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent">
<view
android:id="#+id/jobCardRecyclerView"
class="android.support.v7.widget.RecyclerView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#id/jobCardHeader"
android:scrollbars="vertical"></view>
</ScrollView>
Changed it to
<view
android:id="#+id/jobCardRecyclerView"
class="android.support.v7.widget.RecyclerView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#id/jobCardHeader"
android:scrollbars="vertical"></view>
hope it will be helpful for others facing same problem.

Categories

Resources