Limiting what jsoup retrieves - java

I'm Having fun learning to use jsoup and have successfully retrieved and displayed data from a website, but now I would like some further guidance on it if anyone can help.
Using the code below returns all the table rows 30+, How can I retrieve only say the first 10 of those rows?
also
When returning those rows and the data on them there are gaps/spaces in the row between the data, the spaces between rows are fine but its the spaces within the row that I want to get rid of, how can I omit those spaces/gaps?
My code so far...
package com.example.shiftzer;
import java.io.IOException;
import java.util.ArrayList;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import android.app.Activity;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
public class MainActivity extends Activity{
TextView textView1;
ListView shippingList;
public static final String APP_PREFERENCES = "AppPrefs";
SharedPreferences settings;
SharedPreferences.Editor prefEditor;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_activity);
//rest of the code
textView1 = (TextView)findViewById(R.id.textView1);
shippingList = (ListView) findViewById(R.id.listView1);
settings = getSharedPreferences(APP_PREFERENCES, MODE_PRIVATE);
prefEditor = settings.edit();
new VTSTask().execute();//starts AsyncTask in private class VTSTask to get shipping info
}
private class VTSTask extends AsyncTask<Void, Void, ArrayList<String>> {
ArrayList<String> arr_shipping=new ArrayList<String>();
/**
* #param args
*/
#Override
protected ArrayList<String> doInBackground(Void... params) {
Document doc;
String shippingList;
try {
doc = Jsoup.connect("https://vts.mhpa.co.uk/main_movelistb.asp").get();
Elements tableRows = doc.select("table.dynlist tr td");
for (Element element : tableRows) {
shippingList = element.text();
arr_shipping.add(shippingList);// add value to ArrayList
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return arr_shipping;//<< Return ArrayList from here
}
#Override
protected void onPostExecute(ArrayList<String> result) {
//TextView tVShipping= (TextView)findViewById(R.id.textView2);
shippingList = (ListView) findViewById(R.id.listView1);
ArrayAdapter<String> adapter =
new ArrayAdapter<String>(MainActivity.this,
android.R.layout.simple_list_item_1,
android.R.id.text1);
for (String shipping_result : result)
{
adapter.add(shipping_result);
}
// Assign adapter to ListView
shippingList.setAdapter(adapter);
}
}
}
Thank you.
EDIT:
try {
doc = Jsoup.connect("https://vts.mhpa.co.uk/main_movelistb.asp").get();
Elements tableRows = doc.select("table.dynlist tr td");
tableRows.size();
for(int i = 0; i < 10; i++){
tableRows.get(i);
shippingList = tableRows.get(i).text() +"\n";
arr_shipping.add(shippingList);// add value to ArrayList
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return arr_shipping;//<< return ArrayList from here
}

Instead of doing for(Element element:tableRows), Elements has a size method.
So, you should be able to just do some validation with the size, and then simply
for(int i = 0; i < 10; i++){
tableRows.get(i);
}
to get 10 of them.
As for the spaces, before you store them in your arraylist just use regular expressions and remove the spaces.
http://www.vogella.com/articles/JavaRegularExpressions/article.html

Try This
import java.io.IOException;
import java.util.ArrayList;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;
public class test
{
static ArrayList<String> arr_shipping=new ArrayList<String>();
public static void main(String args[]) throws IOException
{
try {
Document doc = Jsoup.connect("https://vts.mhpa.co.uk/main_movelistb.asp").timeout(600000).get();
Elements tableRows = doc.select("table.dynlist tr:not(:eq(0))");
tableRows.size();
for(int i = 0; i < 10; i++){
//tableRows.get(i);
String shippingList =tableRows.get(i).text() +"\n";
arr_shipping.add(shippingList);// add value to ArrayList
System.out.println(shippingList);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// return arr_shipping;//<< return ArrayList from here
}
}

Try this
doc.select("table.dynlist tr:lt(10)");
to limt the results.
Reference

Related

Data download at the beginning of the App if database is not empty

I have made news reader App where top 20 news articles from one of the leading news websites are fetched through its API.
One activity contains listview that shows latest news titles and clicking them opens webview in other activity corresponding to that news article.
I am downloading content through AsyncTask and onPostExecute I am updating my listview. I want to do the same in OnCreate if databse is not empty.
I have tried checking if cursor.getstring(0) not null or !articlesDB.equals(null) but not working and the app crashes when opened the first time.
package com.example.freshnews;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteStatement;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
static ArrayList<String> titles=new ArrayList<>();
static ArrayList<String> articleHtml=new ArrayList<>();
static ArrayList<String> articleLinks=new ArrayList<>();
ArrayAdapter<String> arrayAdapter;
ListView newsListView;
String articleTitle,articleUrl,result,articleId;
SQLiteDatabase articleDB;
Cursor c;
public void updateListView()
{
c=articleDB.rawQuery("SELECT * FROM articles",null);
int titleIndex=c.getColumnIndex("articleTitle");
int codeIndex=c.getColumnIndex("articleCode");
int linkIndex=c.getColumnIndex("articleLinks");
if(c.moveToFirst())
{
titles.clear();
articleHtml.clear();
articleLinks.clear();
}
do {
titles.add(c.getString(titleIndex));
articleHtml.add(c.getString(codeIndex));
articleLinks.add(c.getString(linkIndex));
}while(c.moveToNext());
c.close();
arrayAdapter.notifyDataSetChanged();
}
public class DownloadTask extends AsyncTask<String,Void,String>
{
#Override
protected String doInBackground(String... strings) {
URL url;
result="";
HttpURLConnection urlConnection=null;
try {
url = new URL(strings[0]);
urlConnection=(HttpURLConnection) url.openConnection();
InputStream inputStream = urlConnection.getInputStream();
InputStreamReader reader=new InputStreamReader(inputStream);
int data=reader.read();
while(data != -1)
{
char current=(char) data;
result += current;
data=reader.read();
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
//Received article IDs
int articleCounter;
String newsSourceURL;
articleDB.execSQL("DELETE FROM articles");
try {
JSONArray jsonArray = new JSONArray(result);
if(jsonArray.length()<20)
{
articleCounter=jsonArray.length();
}
else
{
articleCounter=20;
}
for(int i=0;i<articleCounter;i++)
{
// Log.i("JSON Items",jsonArray.getString(i));
articleId=jsonArray.getString(i);
newsSourceURL="https://hacker-news.firebaseio.com/v0/item/" + articleId + ".json?print=pretty";
// Log.i("URL",newsSourceURL);
url=new URL(newsSourceURL);
urlConnection=(HttpURLConnection) url.openConnection();
InputStream inputStream=urlConnection.getInputStream();
InputStreamReader reader=new InputStreamReader(inputStream);
int data=reader.read();
String articleInfo="";
while(data!=-1)
{
char current=(char) data;
articleInfo+=current;
data=reader.read();
}
JSONObject jsonObject=new JSONObject(articleInfo);
if(!jsonObject.isNull("title") && !jsonObject.isNull("url")) {
articleTitle = jsonObject.getString("title");
articleUrl = jsonObject.getString("url");
}
// Log.i("Article Information",articleId + " " + articleTitle + " " + articleUrl);
/* URL urlHtml=new URL(articleUrl);
HttpURLConnection urlConnectionHtml=(HttpURLConnection) urlHtml.openConnection();
InputStream inputStreamHtml=urlConnectionHtml.getInputStream();
InputStreamReader readerHtml=new InputStreamReader(inputStreamHtml);
int dataHtml=readerHtml.read();
while(dataHtml<50)
{
char current=(char) dataHtml;
articleCode+=current;
dataHtml=readerHtml.read();
}
Log.i("Article HTML",articleCode);*/
String articleCode="<html><body><h1>Hi There</h1><p>How did you find my webview?</p></body></html>";
String sql="INSERT INTO articles (articleId,articleTitle,articleCode,articleLinks) VALUES (?, ?, ?, ?)";
SQLiteStatement statement=articleDB.compileStatement(sql);
statement.bindString(1,articleId);
statement.bindString(2,articleTitle);
statement.bindString(3,articleCode);
statement.bindString(4,articleUrl);
statement.execute();
}
} catch (JSONException e) {
e.printStackTrace();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
updateListView();
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
newsListView=(ListView) findViewById(R.id.newsListView);
arrayAdapter=new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,titles);
newsListView.setAdapter(arrayAdapter);
newsListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent intent = new Intent(getApplicationContext(),NewsActivity.class);
intent.putExtra("news",articleLinks.get(position));
startActivity(intent);
}
});
articleDB=this.openOrCreateDatabase("Articles",MODE_PRIVATE,null);
articleDB.execSQL("CREATE TABLE IF NOT EXISTS articles (id INTEGER PRIMARY KEY, articleId INTEGER, articleTitle VARCHAR, articleCode VARCHAR, articleLinks VARCHAR) ");
/* if(!c.moveToFirst()) { Facing the problem here
updateListView();
}*/
DownloadTask task=new DownloadTask();
try {
task.execute("https://hacker-news.firebaseio.com/v0/topstories.json?print=pretty");
}catch (Exception e)
{
e.printStackTrace();
}
}
}
/* if(!c.moveToFirst()) { Facing the problem here
You would face as issue as the cursor will be null as it hasn't been instantiated.
Add the line
c = articleDB.rawQuery("SELECT count() FROM articles LIMIT 1",null);
and instead of the above you could use the more indicative :-
if (c.getCount() < 1) {

Error in ArrayAdapter Generic [duplicate]

This question already has answers here:
Why The constructor ArrayAdapter<String>(new View.OnKeyListener(){}, int, String[]) is undefined
(4 answers)
Closed 8 years ago.
this is what i see in the error line
-Multiple markers at this line
- ArrayAdapter is a raw type.
-References to generic type ArrayAdapter should be parameterized
- The constructor ArrayAdapter(RetrieveActivity.MyAsyncTask, int, ArrayList) is
undefined
may i know what is wrong with my code. I wanna display arraylist into the listview. but i can't make it due to the error. tq
package com.example.m2mai;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import org.json.JSONArray;
import org.json.JSONObject;
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;
public class RetrieveActivity extends Activity {
ArrayAdapter mArrayAdapter;
ArrayList mNameList = new ArrayList();
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_retrieve);
}
public void getStream(View v)
{
new MyAsyncTask().execute();
}
private class MyAsyncTask extends AsyncTask<String, Void, String>
{
public ArrayList<String> atList=new ArrayList<String>();
public ArrayList<String> dataList=new ArrayList<String>();
protected String doInBackground(String... params)
{
return getData();
}
public long getDateTo()
{
EditText toText = (EditText)findViewById(R.id.dateTo);
String To = toText.getText().toString();
DateFormat dateFormatTo = new SimpleDateFormat("dd/MM/yyyy");
Date dateTo = null;
try {
dateTo = dateFormatTo.parse(To);
} catch (java.text.ParseException e) {
e.printStackTrace();
}
long timeTo = dateTo.getTime();
new Timestamp(timeTo);
return timeTo/1000;
}
protected String getData()
{
String toTS = ""+getDateTo();
String decodedString="";
String returnMsg="";
String request = "http://api.carriots.com/devices/defaultDevice#eric3231559.eric3231559/streams/?order=-1&max=5&at_to="+toTS;
URL url;
HttpURLConnection connection = null;
try {
url = new URL(request);
connection = (HttpURLConnection) url.openConnection();
//establish the parameters for the http post request
connection.addRequestProperty("carriots.apikey", "====================");
connection.addRequestProperty("Content-Type", "application/json");
connection.setRequestMethod("GET");
//create a buffered reader to interpret the incoming message from the carriots system
BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
while ((decodedString = in.readLine()) != null)
{
returnMsg+=decodedString;
}
in.close();
connection.disconnect();
JSONObject nodeRoot = new JSONObject(returnMsg);
JSONArray res = nodeRoot.getJSONArray("result");
for (int i = 0; i < res.length(); i++)
{
JSONObject childJSON = res.getJSONObject(i);
if (childJSON.get("data")!=null)
{
String value = childJSON.getString("data");
dataList.add(value);
JSONObject node=new JSONObject(value);
atList.add(node.get("temperature").toString());
}
}
}
catch (Exception e)
{
e.printStackTrace();
returnMsg=""+e;
}
//Log.d("returnMsg",returnMsg.toString());
return returnMsg;
}
protected void onPostExecute(String result)
{
// int a = atList.size();
// String b = ""+a;
// Log.d("atList",b);
for(int i = 0; i < atList.size(); i++)
{
ListView mainListView = (ListView) findViewById(R.id.listView1);
// Create an ArrayAdapter for the ListView
mArrayAdapter = new ArrayAdapter(this,android.R.layout.simple_list_item_1,mNameList); //<---- error here
// Set the ListView to use the ArrayAdapter
mainListView.setAdapter(mArrayAdapter);
mNameList.add(atList.get(i).toString());
mArrayAdapter.notifyDataSetChanged();
}
Toast.makeText(getApplicationContext(),result, Toast.LENGTH_LONG).show();
EditText myData1=(EditText)findViewById(R.id.editText1);
myData1.setText(atList.get(0));
}
}
}
ArrayAdapter is a raw type.
it is expecting that you provide the type of object the adapter is going to handle. For instance,
ArrayAdapter<String> mAdapter = new ArrayAdapter<String>(...
The constructor ArrayAdapter(RetrieveActivity.MyAsyncTask, int,
ArrayList)
The first argument of the constructor is a Context object and not an instance of your AsyncTask (which this is referring to, in your case)
ArrayAdapter<String> mAdapter = new ArrayAdapter<String>(NameOfYoutActivity.this, ...
In onPostExecute you are creating multiple instance of your Adapter. I do think that is not useful
#Override
protected void onPostExecute(String result) {
ListView mainListView = (ListView) findViewById(R.id.listView1);
mArrayAdapter = new ArrayAdapterString> (NameOfYoutActivity.this, android.R.layout.simple_list_item_1,mNameList);
for(int i = 0; i < atList.size(); i++) {
mArrayAdapter.add(atList.get(i).toString());
}
Toast.makeText(getApplicationContext(),result, Toast.LENGTH_LONG).show();
EditText myData1=(EditText)findViewById(R.id.editText1);
myData1.setText(atList.get(0));
}
Also specify the specify the parameters for the type of array adapter to remove warnings like this
ArrayAdapter<String> mArrayAdapter = new ArrayAdapter<String>(RetrieveActivity.this,android.R.layout.simple_list_item_1,mNameList);
Also change the definition of arraylist to
ArrayList<String> mNameList = new ArrayList<String>();
// "this" is not application context.
mArrayAdapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, mNameList);
You can create UI in onCreate() method and use mArrayAdapter.notifyDataSetChanged(); for update.

Getting same values in list while parsing xml using xmlpullparser

I am trying to parse an xml file present in asset folder.All seems good and there is no error but the problem is that it gives same values to the list for every node in xml.As i feel it overwrite previous value.I am stuck here.Even after a lot of googling could not find any solution. Any help would be appreciated.
Below is the code:-
Product.java
package com.example.webservicedemo;
public class product {
private static String productname="";
private static String productcolor="";
private static String productquantity="";
public static String getProductname() {
return productname;
}
public static void setProductname(String productname) {
product.productname = productname;
}
public static String getProductcolor() {
return productcolor;
}
public static void setProductcolor(String productcolor) {
product.productcolor = productcolor;
}
public static String getProductquantity() {
return productquantity;
}
public static void setProductquantity(String productquantity) {
product.productquantity = productquantity;
}
}
Below is the code of parser:-
productXmlPullParser.java
package com.example.webservicedemo;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserFactory;
import android.content.Context;
import android.content.res.AssetManager;
import android.widget.Toast;
import com.example.webservicedemo.*;
public class productXmlPullParser {
static final String KEY_PRODUCT = "product";
static final String KEY_NAME = "productname";
static final String KEY_COLOR = "productcolor";
static final String KEY_QUANTITY = "productquantity";
public static List<product> getproductsFromFile(Context ctx) {
String tagname;
List<product> Products;
Products = new ArrayList<product>();
product curproduct = null;
String curText = "";
InputStream is = null;
try {
is = ctx.getAssets().open("temp.xml");
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
XmlPullParser xpp = factory.newPullParser();
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
xpp.setInput(reader);
int eventType = xpp.getEventType();
while (eventType != XmlPullParser.END_DOCUMENT) {
tagname = xpp.getName();
switch (eventType) {
case XmlPullParser.START_TAG:
if (tagname.equalsIgnoreCase(KEY_PRODUCT)) {
curproduct = new product();
}
break;
case XmlPullParser.TEXT:
//grab the current text so we can use it in END_TAG event
curText = xpp.getText();
break;
case XmlPullParser.END_TAG:
if (tagname.equalsIgnoreCase(KEY_PRODUCT)) {
// if </site> then we are done with current Site
// add it to the list.
Products.add(curproduct);
// Toast.makeText(ctx, curproduct+"",3000).show();
} else if (tagname.equalsIgnoreCase(KEY_NAME)) {
// if </name> use setName() on curSite
product.setProductname(curText);
Toast.makeText(ctx, curText+"",3000).show();
} else if (tagname.equalsIgnoreCase(KEY_COLOR)) {
// if </link> use setLink() on curSite
curproduct.setProductcolor(curText);
Toast.makeText(ctx, curText+"",3000).show();
} else if (tagname.equalsIgnoreCase(KEY_QUANTITY)) {
// if </about> use setAbout() on curSite
curproduct.setProductquantity(curText);
Toast.makeText(ctx, curText+"",3000).show();
}
break;
default:
break;
}
//move on to next iteration
eventType = xpp.next();
}
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(ctx, "error", 6000).show();
}
// return the populated list.
return Products;
}
}
Below is the code of my custom arrayadapter:--
ProductAdapter
package com.example.webservicedemo;
import java.util.List;
import android.content.Context;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.RelativeLayout;
import android.widget.TextView;
public class UsersAdapter extends ArrayAdapter<product> {
public UsersAdapter(Context context, int resource, List<product> objects) {
super(context, resource, objects);
// TODO Auto-generated constructor stub
}
#Override
public View getView(int pos, View convertView, ViewGroup parent){
RelativeLayout row = (RelativeLayout)convertView;
Log.i("Users", "getView pos = " + pos);
if(null == row){
LayoutInflater inflater = (LayoutInflater)parent.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = (RelativeLayout)inflater.inflate(R.layout.listitem, null);
}
TextView Email = (TextView)row.findViewById(R.id.txtEmail);
TextView Password = (TextView)row.findViewById(R.id.txtPassword);
TextView Deviceid = (TextView)row.findViewById(R.id.txtDeviceid);
Email.setText(getItem(pos).getProductname());
Password.setText(getItem(pos).getProductcolor());
Deviceid.setText(getItem(pos).getProductquantity());
return row;
}
}
Below is the main activity where i am trying to get the result values in a list
MainActivity.java
package com.example.webservicedemo;
import java.util.ArrayList;
import android.app.Activity;
import android.os.Bundle;
import android.widget.ListView;
import android.widget.Toast;
import com.example.webservicedemo.productXmlPullParser;;;
public class UserList extends Activity {
UsersAdapter mAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_xmlparsingdemo);
ListView lvUser=(ListView)findViewById(R.id.lvUsers);
mAdapter=new UsersAdapter(getApplicationContext(),R.layout.listitem,productXmlPullParser.getproductsFromFile(getApplicationContext()));
lvUser.setAdapter(mAdapter);
Toast.makeText(getApplicationContext(), mAdapter.getCount()+"",3000).show();
}
}
Here is the xml which i am trying to parse:--
temp.xml
<?xml version="1.0" encoding="UTF-8"?>
<products>
<product>
<productname>Jeans</productname>
<productcolor>red</productcolor>
<productquantity>5</productquantity>
</product>
<product>
<productname>Tshirt</productname>
<productcolor>blue</productcolor>
<productquantity>3</productquantity>
</product>
<product>
<productname>shorts</productname>
<productcolor>green</productcolor>
<productquantity>4</productquantity>
</product>
</products>
But the output is like something like below screenshot:-
After a lot of effort i could not find what went wrong.
Any help would be appreciated.
Problem in yours class "product". Fields are static, each field contains one last value for all instances. Remove "static" modificator, and all will work fine.

Try catch does not work (always does catch code)

If anyone can help me I would be grateful! It should be converted the three EditText variables into strings and then integers. I added the exception because without it, the program crashed on startup. I'm not sure whether the problem is in the conversion of the variables, in my try catch code, or in both. Please help!
package boston.project;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class TheBostonProjectActivity extends Activity {
public EditText aed, bed, ced;
public TextView dtv;
public int a, b, c;
public Button solve;
public double dis;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
aed = (EditText)(findViewById(R.id.etA));
try {
a = Integer.parseInt(aed.getText().toString());
} catch (NumberFormatException e) {
a = 0;
}
bed = (EditText)(findViewById(R.id.etB));
try {
b = Integer.parseInt(bed.getText().toString());
} catch (NumberFormatException e) {
b = 0;
}
ced = (EditText)(findViewById(R.id.etC));
try {
c = Integer.parseInt(ced.getText().toString());
} catch (NumberFormatException e) {
c = 0;
}
solve = (Button)(findViewById(R.id.bsolve));
solve.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Perform action on click
dis = (b*b)-(4*a*c);
dtv = (TextView)findViewById(R.id.tvdis);
dtv.setText("Discriminant:" + dis);
}
});
}
}
You are trying to get the text from EditTexts just after you created them (by calling setContentView). They are all empty - contain no text. And since
Integer.parseInt("");
Throws an exception, all your catch blocks are executed (and that means, that they actually work, not the contrary).

Pass values of array inbetween classes

I am using a spinner when selected starts an intent and the class that is started gets and XML feed and displays it.
I am trying to call a different XML file based on what is selected by the user. I am not sure how the value can be passed to my XMLfunctions.java and once selected can the other classes reference that data?
HERE is my Eclipse Package Download
My thourghts were to have a multidimensional array with the titles for the spinner and the coinsiding XML url:
package com.patriotsar;
import android.app.Activity;
import android.content.Intent;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.Toast;
public class patriosar extends Activity {
private Button goButton;
private String array_spinner[];
String url = "http://www.patriotsar.com";
Intent i = new Intent(Intent.ACTION_VIEW);
Uri u = Uri.parse(url);
Context context = this;
Spinner areaspinner;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
array_spinner=new String[4];
array_spinner[0]="George Washington","gw.xml";
array_spinner[1]="BENJAMIN FRANKLIN","bf.xml";
array_spinner[2]="THOMAS JEFFERSON","tj.xml";
array_spinner[3]="PATRICK HENRY","ph.xml";
goButton = (Button)findViewById(R.id.goButton);
areaspinner = (Spinner) findViewById(R.id.areaspinner);
ArrayAdapter<String> adapter =
new ArrayAdapter<String> (this,
android.R.layout.simple_spinner_item,array_spinner);
areaspinner.setAdapter(adapter);
goButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v){
try {
// Start the activity
i.setData(u);
startActivity(i);
} catch (ActivityNotFoundException e) {
// Raise on activity not found
Toast.makeText(context, "Browser not found.", Toast.LENGTH_SHORT);
}
}
});
areaspinner.setOnItemSelectedListener(new OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
int item = areaspinner.getSelectedItemPosition();
if(item != 0){
Intent myIntent = new Intent(patriosar.this, ShowXMLPAR.class);
startActivityForResult(myIntent, 0);
}
else {
// finish();
}
}
public void onNothingSelected(AdapterView<?> arg0) {
}
});
}
}
I then have a listener that calls an intent ShowXMLPAR.class when an item other then default is selected. The ShowXMLPAR class calls a function from XMLfunctions.java class and then shows the data that is returned. So the second value in the selected array item needs to be passed to to both pages I guess.
ShowXMLPAR.java:
package com.patriotsar;
import java.util.ArrayList;
import java.util.HashMap;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import com.patriotsar.XMLfunctions;
import android.app.ListActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
public class ShowXMLPAR extends ListActivity {
private Button backButton;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.listplaceholder);
backButton = (Button)findViewById(R.id.backButton);
backButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view){
Intent myIntent = new Intent(view.getContext(), patriosar.class);
startActivityForResult(myIntent, 0);
}
});
ArrayList<HashMap<String, String>> mylist = new ArrayList<HashMap<String, String>>();
String xml = XMLfunctions.getXML();
Document doc = XMLfunctions.XMLfromString(xml);
int numResults = XMLfunctions.numResults(doc);
if((numResults <= 0)){
Toast.makeText(ShowXMLPAR.this, "Geen resultaten gevonden", Toast.LENGTH_LONG).show();
finish();
}
NodeList nodes = doc.getElementsByTagName("result");
for (int i = 0; i < nodes.getLength(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
Element e = (Element)nodes.item(i);
map.put("main_content", XMLfunctions.getValue(e, "content"));
map.put("name", XMLfunctions.getValue(e, "name"));
mylist.add(map);
}
//
ListAdapter adapter = new SimpleAdapter(ShowXMLPAR.this, mylist , R.layout.listlayout,
new String[] {"main_content", "name" },
new int[] { R.id.item_title, R.id.item_subtitle });
setListAdapter(adapter);
}
}
XMLfunctions.java:
package com.patriotsar;
import java.io.IOException;
import java.io.StringReader;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
public class XMLfunctions {
public final static Document XMLfromString(String xml){
Document doc = null;
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
try {
DocumentBuilder db = dbf.newDocumentBuilder();
InputSource is = new InputSource();
is.setCharacterStream(new StringReader(xml));
doc = db.parse(is);
} catch (ParserConfigurationException e) {
System.out.println("XML parse error: " + e.getMessage());
return null;
} catch (SAXException e) {
System.out.println("Wrong XML file structure: " + e.getMessage());
return null;
} catch (IOException e) {
System.out.println("I/O exeption: " + e.getMessage());
return null;
}
return doc;
}
/** Returns element value
* #param elem element (it is XML tag)
* #return Element value otherwise empty String
*/
public final static String getElementValue( Node elem ) {
Node kid;
if( elem != null){
if (elem.hasChildNodes()){
for( kid = elem.getFirstChild(); kid != null; kid = kid.getNextSibling() ){
if( kid.getNodeType() == Node.TEXT_NODE ){
return kid.getNodeValue();
}
}
}
}
return "";
}
public static String getXML(){
String line = null;
try {
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpGet httpPost = new HttpGet("http://www.patriotsar.com/patriot_quotes.xml");
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
line = EntityUtils.toString(httpEntity);
} catch (UnsupportedEncodingException e) {
line = "<results status=\"error\"><msg>Can't connect to server</msg></results>";
} catch (MalformedURLException e) {
line = "<results status=\"error\"><msg>Can't connect to server</msg></results>";
} catch (IOException e) {
line = "<results status=\"error\"><msg>Can't connect to server</msg></results>";
}
return line;
}
public static int numResults(Document doc){
Node results = doc.getDocumentElement();
int res = -1;
try{
res = Integer.valueOf(results.getAttributes().getNamedItem("count").getNodeValue());
}catch(Exception e ){
res = -1;
}
return res;
}
public static String getValue(Element item, String str) {
NodeList n = item.getElementsByTagName(str);
return XMLfunctions.getElementValue(n.item(0));
}
}
Sorry I am still learning but am excited to get into more advanced (for me) programming. Any Help would be awesome.
As of now the app works but calls the same xml no matter what.
I'm not following your description very well, but if you are wanting to pass data between Activities via Intents then make sure the data you pass can either be included as an Extra, or if you prefer to send actual objects then make sure your objects implement the Parcelable interface.

Categories