Parsing sunrise and sunset values from web service - java

Okay, so it appears I'm stuck and could do with some help.
After successfully calling this webservice with my current longitude and latitude I am getting the entire xml file back in response.
However the only bit of the xml file I want is the sunrise and sunset times, how do I go about parsing these and only these into TextViews?
I've looked at and attempted countless tutorials on XmlPullParser, DOMParser and SAXParser and I'm now struggling.
Code as requested:
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.HttpContext;
import android.app.Activity;
import android.content.Context;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class SunriseSunset extends Activity implements OnClickListener {
public Button getLocation;
public TextView LongCoord;
public TextView LatCoord;
public double longitude;
public double latitude;
public LocationManager lm;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.sunrisesunset);
findViewById(R.id.my_button).setOnClickListener(this);
lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 1,
new MyLocationListener());
getLocation = (Button) findViewById(R.id.GetLocation);
LongCoord = (TextView) findViewById(R.id.LongCoord);
LatCoord = (TextView) findViewById(R.id.LatCoord);
getLocation.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// When GetLocation button is clicked the showCurrentLocation
// function is ran
showCurrentLocation();
}
});
}
protected void showCurrentLocation() {
// TODO Auto-generated method stub
// This is called to find current location based on GPS data and sends
// this to LongCoord and LatCoord TextViewsw
Location location = lm
.getLastKnownLocation(LocationManager.GPS_PROVIDER);
latitude = location.getLatitude();
longitude = location.getLongitude();
LongCoord.setText(Double.toString(longitude));
LatCoord.setText(Double.toString(latitude));
}
#Override
public void onClick(View arg0) {
Button b = (Button) findViewById(R.id.my_button);
b.setClickable(false);
new LongRunningGetIO().execute();
}
private class LongRunningGetIO extends AsyncTask<Void, Void, String> {
protected String getASCIIContentFromEntity(HttpEntity entity)
throws IllegalStateException, IOException {
InputStream in = entity.getContent();
StringBuffer out = new StringBuffer();
int n = 1;
while (n > 0) {
byte[] b = new byte[4096];
n = in.read(b);
if (n > 0)
out.append(new String(b, 0, n));
}
return out.toString();
}
#Override
protected String doInBackground(Void... params) {
HttpClient httpClient = new DefaultHttpClient();
HttpContext localContext = new BasicHttpContext();
//Finds todays date and adds that into the URL
Calendar c = Calendar.getInstance();
System.out.println("Current time => " + c.getTime());
SimpleDateFormat df = new SimpleDateFormat("dd/MM");
String formattedDate = df.format(c.getTime());
String finalURL = "http://www.earthtools.org/sun/"
+ LatCoord.getText().toString().trim() + "/"
+ LongCoord.getText().toString().trim() + "/"
+ formattedDate + "/99/0";
HttpGet httpGet = new HttpGet(finalURL);
String text = null;
try {
HttpResponse response = httpClient.execute(httpGet,
localContext);
HttpEntity entity = response.getEntity();
text = getASCIIContentFromEntity(entity);
} catch (Exception e) {
return e.getLocalizedMessage();
}
return text;
}
protected void onPostExecute(String results) {
if (results != null) {
EditText et = (EditText) findViewById(R.id.my_edit);
et.setText(results);
}
Button b = (Button) findViewById(R.id.my_button);
b.setClickable(true);
}
}
class MyLocationListener implements LocationListener {
#Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
}
#Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
}
}
And here is the layout being used:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/LinearLayout1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".SunriseSunset" >
<LinearLayout
android:id="#+id/LinearLayout02"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true" >
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Date:"
android:textAppearance="?android:attr/textAppearanceMedium" />
<TextView
android:id="#+id/Date"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Today"
android:textAppearance="?android:attr/textAppearanceMedium" />
</LinearLayout>
<LinearLayout
android:id="#+id/LinearLayout02"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true" >
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Location:"
android:textAppearance="?android:attr/textAppearanceMedium" />
<TextView
android:id="#+id/Date"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Current Location"
android:textAppearance="?android:attr/textAppearanceMedium" />
</LinearLayout>
<Button
android:id="#+id/GetLocation"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="Find Location" />
<TextView
android:id="#+id/LatCoord"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<TextView
android:id="#+id/LongCoord"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="Calculate Sunrise/Sunset Time"
android:id="#+id/my_button"/>
<EditText
android:layout_margin="20dip"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:minLines="30"
android:maxLines="30"
android:textSize="12sp"
android:editable="false"
android:id="#+id/my_edit"/>
</LinearLayout>
Thanks in advance for your help!

You can try replacing your onPostExecute with the one below and add this import...
import java.io.StringReader;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
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;
protected void onPostExecute(String results) {
if (results != null) {
try {
DocumentBuilderFactory dbFactory = DocumentBuilderFactory
.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
InputSource s = new InputSource(new StringReader(result));
Document doc = dBuilder.parse(s);
doc.getDocumentElement().normalize();
//EditText et = (EditText) findViewById(R.id.my_edit);
TextView tv = (TextView) findViewById(R.id.Date);
tv.setText("sunrise at "+doc.getElementsByTagName("sunrise").item(0).getTextContent() + " sunset at "+doc.getElementsByTagName("sunset").item(0).getTextContent());
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
Button b = (Button) findViewById(R.id.my_button);
b.setClickable(true);
}
EDIT: I'm not sure which TextView you want to set but I guess this one (R.id.Date).
You can change the id if it's not the right one.
//EditText et = (EditText) findViewById(R.id.my_edit);
TextView tv = (TextView) findViewById(R.id.Date);
tv.setText...

Related

Android-some issue with running example code [dimens.xml]

I'm new to Android Studio and have some problems with running example code :
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.abdul.moqueet.currency.MainActivity">
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="numberDecimal"
android:ems="5"
android:id="#+id/et"
android:layout_marginTop="33dp"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
<Spinner
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/spin"
android:layout_alignTop="#+id/et"
android:layout_toRightOf="#+id/et"
android:layout_toEndOf="#+id/et"
android:layout_marginLeft="47dp"
android:layout_marginStart="47dp" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/convert"
android:id="#+id/btn"
android:layout_marginTop="33dp"
android:layout_below="#+id/spin"
android:layout_toRightOf="#+id/et"
android:layout_toEndOf="#+id/et" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="#string/usdtxt"
android:id="#+id/TextView1"
android:layout_marginTop="20dp"
android:layout_below="#+id/btn"
android:layout_alignLeft="#+id/spin"
android:layout_alignStart="#+id/spin"
android:layout_marginLeft="80dp"
android:layout_marginStart="80dp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="#string/eurtxt"
android:id="#+id/TextView2"
android:layout_marginTop="20dp"
android:layout_below="#+id/TextView1"
android:layout_alignLeft="#+id/spin"
android:layout_alignStart="#+id/spin"
android:layout_marginLeft="80dp"
android:layout_marginStart="80dp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="#string/inrtxt"
android:id="#+id/TextView3"
android:layout_marginTop="20dp"
android:layout_below="#+id/TextView2"
android:layout_alignLeft="#+id/spin"
android:layout_alignStart="#+id/spin"
android:layout_marginLeft="80dp"
android:layout_marginStart="80dp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="#string/zero"
android:id="#+id/usd"
android:layout_alignTop="#+id/TextView1"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginLeft="17dp"
android:layout_marginStart="17dp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="#string/zero"
android:id="#+id/euro"
android:layout_above="#+id/TextView3"
android:layout_alignLeft="#+id/usd"
android:layout_alignStart="#+id/usd" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="#string/zero"
android:id="#+id/inr"
android:layout_alignTop="#+id/TextView3"
android:layout_alignLeft="#+id/euro"
android:layout_alignStart="#+id/euro" />
</RelativeLayout>
MainActivity.java
package com.example.adriangranosik.coinconverter;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public class MainActivity extends AppCompatActivity {
private EditText et;
private TextView usd, euro, inr;
private Button btn;
private Spinner spin;
private int index = 0;
private double inputvalue;
private String result[] = new String[10];
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
et = (EditText) findViewById(R.id.et);
usd = (TextView) findViewById(R.id.usd);
euro = (TextView) findViewById(R.id.euro);
inr = (TextView) findViewById(R.id.inr);
btn = (Button) findViewById(R.id.btn);
spin = (Spinner) findViewById(R.id.spin);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this, R.array.currency, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.select_dialog_singlechoice);
spin.setAdapter(adapter);
spin.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
index = position;
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
usd.setText("wait...");
euro.setText("wait...");
inr.setText("wait...");
if (et.getText().toString().trim().length() > 0 && !et.getText().toString().trim().equals(".")) {
String textValue = et.getText().toString();
inputvalue = Double.parseDouble(textValue);
new calculate().execute();
}
}
});
}
public class calculate extends AsyncTask<String, String, String[]> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String[] doInBackground(String... params) {
if (index == 0) {
String uRl;
try {
uRl = getJson("http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20yahoo.finance.xchange%20where%20pair%20in%20(%22USDEUR,USDINR%22)&format=json&env=store://datatables.org/alltableswithkeys");
JSONObject USDtojObj;
USDtojObj = new JSONObject(uRl);
JSONArray rateArray = USDtojObj.getJSONObject("query").getJSONObject("results").getJSONArray("rate");
result[0] = rateArray.getJSONObject(0).getString("Rate");
result[1] = rateArray.getJSONObject(1).getString("Rate");
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
} else if (index == 1) {
String uRl;
try {
uRl = getJson("http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20yahoo.finance.xchange%20where%20pair%20in%20(%22EURUSD,EURINR%22)&format=json&env=store://datatables.org/alltableswithkeys");
JSONObject EurotojObj;
EurotojObj = new JSONObject(uRl);
JSONArray rateArray = EurotojObj.getJSONObject("query").getJSONObject("results").getJSONArray("rate");
result[0] = rateArray.getJSONObject(0).getString("Rate");
result[1] = rateArray.getJSONObject(1).getString("Rate");
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
} else if (index == 2) {
String uRl;
try {
uRl = getJson("http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20yahoo.finance.xchange%20where%20pair%20in%20(%22INRUSD,INREUR%22)&format=json&env=store://datatables.org/alltableswithkeys");
JSONObject INRtojObj;
INRtojObj = new JSONObject(uRl);
JSONArray rateArray = INRtojObj.getJSONObject("query").getJSONObject("results").getJSONArray("rate");
result[0] = rateArray.getJSONObject(0).getString("Rate");
result[1] = rateArray.getJSONObject(1).getString("Rate");
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
}
return result;
}
#Override
protected void onPostExecute(String[] strings) {
if(index == 0){
double usdtoeuroval, usdtoinrval, usdtoeuroinp, usdtoinrinp, usdtousdinp;
usdtousdinp = inputvalue * 1;
usd.setText(""+usdtousdinp);
usdtoeuroval = Double.parseDouble(result[0]);
usdtoeuroinp = inputvalue * usdtoeuroval;
euro.setText(""+usdtoeuroinp);
usdtoinrval = Double.parseDouble(result[1]);
usdtoinrinp = inputvalue * usdtoinrval;
inr.setText(""+usdtoinrinp);
}else if(index == 1){
double eurotousdval, eurotoinrval, eurotousdinp, eurotoinrinp, eurotoeuroinp;
eurotoeuroinp = inputvalue * 1;
euro.setText(""+eurotoeuroinp);
eurotousdval = Double.parseDouble(result[0]);
eurotousdinp = inputvalue * eurotousdval;
usd.setText(""+eurotousdinp);
eurotoinrval = Double.parseDouble(result[1]);
eurotoinrinp = inputvalue * eurotoinrval;
inr.setText(""+eurotoinrinp);
}else if(index == 2){
double inrtousdval, inrtoeuroval, inrtousdinp, inrtoeuroinp, inrtoinrinp;
inrtoinrinp = inputvalue * 1;
inr.setText(""+inrtoinrinp);
inrtousdval = Double.parseDouble(result[0]);
inrtousdinp = inputvalue * inrtousdval;
usd.setText(""+inrtousdinp);
inrtoeuroval = Double.parseDouble(result[1]);
inrtoeuroinp = inputvalue * inrtoeuroval;
euro.setText(""+inrtoeuroinp);
}
}
public String getJson(String url) throws ClientProtocolException, IOException {
StringBuilder build = new StringBuilder();
HttpClient client = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
HttpResponse response = client.execute(httpGet);
HttpEntity entity = response.getEntity();
InputStream content = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(content));
String con;
while ((con = reader.readLine()) != null) {
build.append(con);
}
return build.toString();
}
}
}
I am getting Following Errors :
layout/activity_main.xml
error: resource dimen/activity_vertical_margin (aka com.example.adriangranosik.coinconverter:dimen/activity_vertical_margin) not found.
error: resource dimen/activity_horizontal_margin (aka com.example.adriangranosik.coinconverter:dimen/activity_horizontal_margin) not found.
error: resource string/convert (aka com.example.adriangranosik.coinconverter:string/convert) not found.
error: resource string/usdtxt (aka com.example.adriangranosik.coinconverter:string/usdtxt) not found.
error: resource string/eurtxt (aka com.example.adriangranosik.coinconverter:string/eurtxt) not found.
error: resource string/inrtxt (aka com.example.adriangranosik.coinconverter:string/inrtxt) not found.
error: resource string/zero (aka com.example.adriangranosik.coinconverter:string/zero) not found.
error: resource string/zero (aka com.example.adriangranosik.coinconverter:string/zero) not found.
error: resource string/zero (aka com.example.adriangranosik.coinconverter:string/zero) not found.
null
failed linking file resources.
I just wanna run a program to analyze source code. I know there is dimens.xml file which is missing but i have no clue what to put there.
I'm new in Android dev so i found example code just to learn how to create apps like that. But it's hard when i cannot run it :D
Thanks for your help.
you may just replace this
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
with smth like
android:paddingBottom="8dp"
android:paddingLeft="8dp"
android:paddingRight="8dp"
android:paddingTop="8dp"
(or if all 4 paddings are equal, you may set just android:padding="8dp")
In res -> Values put this code in dimens.xml
<dimen name="activity_vertical_margin">3dp</dimen>
Adjust dp according to your UI.
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
replace above code with below lines in RelativeLayout :
android:paddingBottom="16dp"
android:paddingLeft="16dp"
android:paddingRight="16dp"
android:paddingTop="16dp"

How to explain to get JSON and the return to LISTVIEW in android development

I'm self-taught , several knowledge combined together when there is an error , how I should be modified to allow this program up and running
here warning
List<Map<String, Object>> index_shop_data = new ArrayList<Map<String, Object>>(); // (DeBug)here has a error ,why?
Thank you to answer
MainActivity.java
package com.g.gndroid;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONObject;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;
#SuppressLint("HandlerLeak")
public class MainActivity extends Activity {
private static final int MSG_SUCCESS = 0;
private static final int MSG_FAILURE = 1;
private ListView index_shop_list;
private TextView tv;
private Button mButton;
private Thread mThread;
private Handler mHandler = new Handler() {
#Override
public void handleMessage(Message msg) {
switch (msg.what) {
case MSG_SUCCESS:
tv.setText((String) msg.obj);
List<Map<String, Object>> index_shop_data = new ArrayList<Map<String, Object>>(); // (DeBug)here has a error ,why?
for (int i = 0; i < ((JSONArray) msg.obj).length(); i++) {
Map<String, Object> map = new HashMap<String, Object>();
map.put("position", "int_position" + i);
map.put("name", "int_name" + i);
index_shop_data.add(map);
}
index_shop_list.setAdapter(new SimpleAdapter(MainActivity.this,
index_shop_data, R.layout.shop_item_list, new String[] {
"position", "name" }, new int[] {
R.id.tv_position, R.id.tv_name }));
Toast.makeText(getApplication(),
getApplication().getString(R.string.get_pic_success),
Toast.LENGTH_LONG).show();
break;
case MSG_FAILURE:
Toast.makeText(getApplication(),
getApplication().getString(R.string.get_pic_failure),
Toast.LENGTH_LONG).show();
break;
}
}
};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.hello_world);
index_shop_list = (ListView) findViewById(R.id.itemList);
mButton = (Button) findViewById(R.id.button);
tv = (TextView) findViewById(R.id.tv);
mButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (mThread == null) {
mThread = new Thread(runnable);
mThread.start();
} else {
Toast.makeText('String',Toast.LENGTH_LONG).show()
Toast.makeText(
getApplication(),
getApplication().getString(R.string.thread_started),
Toast.LENGTH_LONG).show();
}
}
});
}
Runnable runnable = new Runnable() {
#Override
public void run() {
HttpClient hc = new DefaultHttpClient();
HttpGet hg = new HttpGet("http://192.168.1.213/1.php");// url
String strResult = "", status = "", nl = "\n", finalResult = "";
boolean JSON = false;
JSONArray DataJSON = null;
try {
HttpResponse hr = hc.execute(hg);
strResult = EntityUtils.toString(hr.getEntity());
JSONObject strJSON = new JSONObject(strResult);
String Code = strJSON.getString("Code");
String Message = strJSON.getString("Message");
if (Integer.parseInt(Code) == 1) {
finalResult = "status:" + Message + nl;
DataJSON = strJSON.getJSONArray("Datas");
for (int i = 0; i < DataJSON.length(); i++) {
status = status
+ DataJSON.getJSONObject(i).getString("I") + nl
+ DataJSON.getJSONObject(i).getString("R") + nl
+ DataJSON.getJSONObject(i).getString("P") + nl
+ DataJSON.getJSONObject(i).getString("N") + nl;
}
finalResult = finalResult + status;
JSON = true;
} else {
finalResult = Message;
}
} catch (Exception e) {
mHandler.obtainMessage(MSG_FAILURE).sendToTarget();
return;
}
if (!JSON)
mHandler.obtainMessage(MSG_SUCCESS, finalResult).sendToTarget();
else
mHandler.obtainMessage(MSG_SUCCESS, DataJSON).sendToTarget();
}
};
}
hello_world.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<ScrollView
android:layout_width="fill_parent"
android:layout_height="wrap_content" >
<TextView
android:id="#+id/tv"
android:layout_width="fill_parent"
android:layout_height="wrap_content" >
</TextView>
</ScrollView>
<Button
android:id="#+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/app_name" >
</Button>
<ImageView
android:id="#+id/imageView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:contentDescription="#string/app_name" >
</ImageView>
<ListView
android:id="#+id/itemList"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
</ListView>
</LinearLayout>
shop_item_list.xml (ListView)
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TextView
android:id="#+id/tv_position"
android:layout_width="match_parent"
android:layout_height="30dip"
android:paddingTop="5dip"
android:text="#string/app_name"
android:textSize="20sp" />
<TextView
android:id="#+id/tv_name"
android:layout_width="match_parent"
android:layout_height="30dip"
android:paddingTop="5dip"
android:text="#string/app_name_text"
android:textSize="20sp" />
</LinearLayout>
Thank you to answer
Your question wasnt so clear to me, but i tried to run the code. I had few errors but not where you pointed. i got the error at Toast.makeText('String',Toast.LENGTH_LONG).show(), it should be Toast.makeText(MainActivity.this, "String", Toast.LENGTH_LONG).show(); (you have to pass the context, and put a semicolon after the statement). Now the program is working. i can see an activity with a button, clicking which showed the toast.

Android ListView TextView

I've been struggling to get a listview to display correctly.
To clarify, I need a scrollview above the listview which is why I haven't extended a listfragment.
I need title and description to be separate elements. I can see how I have put them into a class so I think I'm half way there. If someone could help me out that would be great.
PhotosFragment.java
package info.androidhive.slidingmenu;
import android.app.Fragment;
import android.app.ListFragment;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.Html;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.w3c.dom.Text;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class PhotosFragment extends Fragment {
ListView list;
TextView pm;
TextView sp;
ArrayList<HashMap<String, String>> mlist = new ArrayList<HashMap<String,String>>();
private static final String TAG_APPLE = "Apple";
private static final String TAG_PHONEMODEL = "PhoneModel";
private static final String TAG_SPECS = "specs";
JSONArray model = null;
public PhotosFragment(){}
ListView mListView;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_photos, container, false);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
setHasOptionsMenu(true);
mListView = (ListView) getView().findViewById(R.id.mListView);
new RequestTask().execute("http://www.horwichadvertiser.co.uk/app/index.php?Type=8&catid=7&userid=4");
}
private static final String TAG = MainActivity.class.getSimpleName();
JSONObject obj;
JSONArray stories;
public class RequestTask extends AsyncTask<String, String, String> {
private ProgressDialog pDialog;
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
pm = (TextView)getView().findViewById(R.id.phonemodel);
sp = (TextView)getView().findViewById(R.id.specification);
pDialog = new ProgressDialog(getActivity());
pDialog.setMessage("Getting Data ...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected String doInBackground(String... uri) {
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response;
String responseString = null;
try {
response = httpclient.execute(new HttpGet(uri[0]));
StatusLine statusLine = response.getStatusLine();
if (statusLine.getStatusCode() == HttpStatus.SC_OK) {
ByteArrayOutputStream out = new ByteArrayOutputStream();
response.getEntity().writeTo(out);
out.close();
responseString = out.toString();
//Log.d(TAG, responseString);
} else {
//Closes the connection.
response.getEntity().getContent().close();
throw new IOException(statusLine.getReasonPhrase());
}
} catch (ClientProtocolException e) {
//TODO Handle problems..
// Log.d(TAG, String.valueOf(e));
} catch (IOException e) {
//TODO Handle problems..
// Log.d(TAG, String.valueOf(e));
}
return responseString;
}
#Override
protected void onPostExecute(String result) {
pDialog.dismiss();
super.onPostExecute(result);
//Log.e(TAG, result);
try {
obj = new JSONObject(result);
stories = obj.getJSONArray("stories");
// initialize the items list
List<ListViewItem> mItems = new ArrayList<ListViewItem>();
for (int i = 0; i < stories.length(); i++) {
JSONObject storyObj = stories.getJSONObject(i);
if (!storyObj.has("Advert")) {
newsStories newsStories = new newsStories();
newsStories.setTitle(storyObj.getString("subject"));
newsStories.setBody(storyObj.getString("body"));
mItems.add(new ListViewItem(newsStories.getTitle(), newsStories.getBody(), ""));
}
else {
newsStories newsStories = new newsStories();
newsStories.setThumbnailUrl(storyObj.getString("Advert"));
mItems.add(new ListViewItem("", "", newsStories.getThumbnailUrl()));
}
}
ArrayAdapter<ListViewItem> adapter = new ArrayAdapter<ListViewItem>(getActivity(), android.R.layout.simple_list_item_1, mItems);
mListView.setTextFilterEnabled(true);
// ArrayAdapter<ListViewItem> adapter = new ArrayAdapter<ListViewItem>(getActivity(), android.R.layout.two_line_list_item, mItems);
//mListView.setAdapter(adapter);
mListView.setAdapter(adapter);
}
catch (JSONException e) {
e.printStackTrace();
}
}
public class newsStories {
private String name, thumbnailUrl, body;
public String getTitle() {
return name;
}
public void setTitle(String name) {
this.name = name;
}
public String getBody() {
return body;
}
public void setBody(String body) {
this.body = body.substring(0, 150);
}
public String getThumbnailUrl() {
return thumbnailUrl;
}
public void setThumbnailUrl(String thumbnailUrl) {
//Check if thumbnail exists, if so take out spaces and replace with -
this.thumbnailUrl = thumbnailUrl;
}
}
}
public class ListViewItem{
public final String title; // the text for the ListView item title
public final String description; // the text for the ListView item description
public final String adUrl;
//public final Drawable image;
public ListViewItem(String title, String description, String Advert_Url) {
if (Advert_Url != null && !Advert_Url.isEmpty()) {
String Advert = "http://www.horwichadvertiser.co.uk/images/horwichadvertiserlogo.png?width=700&height=200";
this.title = "";
this.description = "";
this.adUrl = Advert;
} else {
this.title = title;
this.description = description;
this.adUrl = "";
}
}
#Override
public String toString() {
return this.title + ".\r\n" + Html.fromHtml(this.description);
}
}
}
Fragment_Photos.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="horizontal" >
<HorizontalScrollView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="150dp" >
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button1" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button2" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button3" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button4" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button5" />
</LinearLayout>
</HorizontalScrollView>
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical"
android:layout_marginTop="50dp"
android:id="#+id/relativeLayout">
<TextView
android:id="#+id/body"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#000000"
android:textSize="22px" />
<TextView
android:id="#+id/title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#000000"
android:textSize="13px" />
</RelativeLayout>
<ListView
android:id="#id/mListView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:layout_below="#+id/relativeLayout">
</ListView>
</RelativeLayout>
Your resource xml is incorrect.
1.
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="horizontal" >
android:orientation is used with LinearLayout, not RelativeLayout
2.
<ListView
android:id="#id/mListView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:layout_below="#+id/relativeLayout">
</ListView>
Incorrect use of android:layout_below - value should be an existing id: "#id/relativeLayout" (without + after #).
android:id="#id/mListView" incorrectly assigned id. If it is a new ID, then should be android:id="#+id/mListView"
Probably you'd like to use LinearLayouts instead of relative
fill_parent is obsolete until you develop for some API 7. Should be match_parent instead

Using the date from DatePicker in the url for sunrise/sunset webservice [duplicate]

This question already has an answer here:
Using the date from DatePicker in URL for webservice
(1 answer)
Closed 9 years ago.
Okayyyy, so I'm stuck and could do with some help :)
In my code at the moment today's date is being read into the webservice url using the following snippet of code:
Calendar c = Calendar.getInstance();
System.out.println("Current time => " + c.getTime());
SimpleDateFormat df = new SimpleDateFormat("dd/MM");
String formattedDate = df.format(c.getTime());
I want today's date to be displayed but I also want the user to be able to select a different date from the DatePicker and find the sunrise/sunset values for that particular date.
I'm guessing this is simple and I'm just being a bit dim so any help would be appreciated, here is my code:
package richgrundy.learnphotography;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringReader;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.HttpContext;
import org.w3c.dom.Document;
import org.xml.sax.InputSource;
import android.app.Activity;
import android.app.FragmentTransaction;
import android.content.Context;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.TextView;
public class SunriseSunset extends Activity implements OnClickListener {
public Button getLocation;
public Button setLocationJapan;
public TextView LongCoord;
public TextView LatCoord;
public double longitude;
public double latitude;
public LocationManager lm;
public Spinner Locationspinner;
public DateDialogFragment frag;
public Button date;
public Calendar now;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.sunrisesunset);
//Setting onClickListener for Calculate Sunrise/Sunset Button
findViewById(R.id.CalculateSunriseSunset).setOnClickListener(this);
//Sets up LocationManager to enable GPS data to be accessed.
lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 1,
new MyLocationListener());
//Declares Latitude and Longitude TextViews
LatCoord = (TextView) findViewById(R.id.LatCoord);
LongCoord = (TextView) findViewById(R.id.LongCoord);
//Declares for Location Spinner/Dropdown
addListenerOnSpinnerItemSelection();
//Date
now = Calendar.getInstance();
date = (Button)findViewById(R.id.date_button);
date.setText(String.valueOf(now.get(Calendar.DAY_OF_MONTH)+1)+"-"+String.valueOf(now.get(Calendar.MONTH))+"-"+String.valueOf(now.get(Calendar.YEAR)));
date.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
showDialog();
}
});
}
// More date
public void showDialog() {
FragmentTransaction ft = getFragmentManager().beginTransaction(); //get the fragment
frag = DateDialogFragment.newInstance(this, new DateDialogFragmentListener(){
public void updateChangedDate(int year, int month, int day){
date.setText(String.valueOf(day)+"-"+String.valueOf(month+1)+"-"+String.valueOf(year));
now.set(year, month, day);
}
}, now);
frag.show(ft, "DateDialogFragment");
}
public interface DateDialogFragmentListener{
//this interface is a listener between the Date Dialog fragment and the activity to update the buttons date
public void updateChangedDate(int year, int month, int day);
}
public void addListenerOnSpinnerItemSelection() {
Locationspinner = (Spinner) findViewById(R.id.Locationspinner);
Locationspinner
.setOnItemSelectedListener(new CustomOnItemSelectedListener(
this));
}
public void setLocationFrance() {
// TODO Auto-generated method stub
LatCoord.setText("65.4112");
LongCoord.setText("85.8337");
}
public void setLocationIndia() {
// TODO Auto-generated method stub
LatCoord.setText("21.4112");
LongCoord.setText("105.8337");
}
public void setLocationJapan() {
// TODO Auto-generated method stub
LatCoord.setText("21.4112");
LongCoord.setText("15.8337");
}
protected void showCurrentLocation() {
// This is called to find current location based on GPS data and sends
// this to LongCoord and LatCoord TextViews
Location location = lm
.getLastKnownLocation(LocationManager.GPS_PROVIDER);
latitude = location.getLatitude();
longitude = location.getLongitude();
LongCoord.setText(Double.toString(longitude));
LatCoord.setText(Double.toString(latitude));
}
#Override
public void onClick(View arg0) {
Button b = (Button) findViewById(R.id.CalculateSunriseSunset);
b.setClickable(false);
new LongRunningGetIO().execute();
}
private class LongRunningGetIO extends AsyncTask<Void, Void, String> {
protected String getASCIIContentFromEntity(HttpEntity entity)
throws IllegalStateException, IOException {
InputStream in = entity.getContent();
StringBuffer out = new StringBuffer();
int n = 1;
while (n > 0) {
byte[] b = new byte[4096];
n = in.read(b);
if (n > 0)
out.append(new String(b, 0, n));
}
return out.toString();
}
#Override
protected String doInBackground(Void... params) {
HttpClient httpClient = new DefaultHttpClient();
HttpContext localContext = new BasicHttpContext();
// Finds todays date and adds that into the URL
Calendar c = Calendar.getInstance();
System.out.println("Current time => " + c.getTime());
SimpleDateFormat df = new SimpleDateFormat("dd/MM");
String formattedDate = df.format(c.getTime());
String finalURL = "http://www.earthtools.org/sun/"
+ LatCoord.getText().toString().trim() + "/"
+ LongCoord.getText().toString().trim() + "/"
+ formattedDate + "/99/0";
HttpGet httpGet = new HttpGet(finalURL);
String text = null;
try {
HttpResponse response = httpClient.execute(httpGet,
localContext);
HttpEntity entity = response.getEntity();
text = getASCIIContentFromEntity(entity);
} catch (Exception e) {
return e.getLocalizedMessage();
}
return text;
}
protected void onPostExecute(String results) {
if (results != null) {
try {
DocumentBuilderFactory dbFactory = DocumentBuilderFactory
.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
InputSource s = new InputSource(new StringReader(results));
Document doc = dBuilder.parse(s);
doc.getDocumentElement().normalize();
TextView tvSunrise = (TextView) findViewById(R.id.Sunrise);
TextView tvSunset = (TextView) findViewById(R.id.Sunset);
tvSunrise.setText(doc.getElementsByTagName("sunrise").item(0).getTextContent());
tvSunset.setText(doc.getElementsByTagName("sunset").item(0).getTextContent());
} catch (Exception e) {
e.printStackTrace();
}
}
Button b = (Button) findViewById(R.id.CalculateSunriseSunset);
b.setClickable(true);
}
}
class MyLocationListener implements LocationListener {
#Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
}
#Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
}
}
DateFragmentDialog:
package richgrundy.learnphotography;
import java.util.Calendar;
import richgrundy.learnphotography.SunriseSunset.DateDialogFragmentListener;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.DialogFragment;
import android.content.Context;
import android.os.Bundle;
import android.widget.DatePicker;
public class DateDialogFragment extends DialogFragment {
public static String TAG = "DateDialogFragment";
static Context mContext; //I guess hold the context that called it. Needed when making a DatePickerDialog. I guess its needed when conncting the fragment with the context
static int mYear;
static int mMonth;
static int mDay;
static DateDialogFragmentListener mListener;
public static DateDialogFragment newInstance(Context context, DateDialogFragmentListener listener, Calendar now) {
DateDialogFragment dialog = new DateDialogFragment();
mContext = context;
mListener = listener;
mYear = now.get(Calendar.YEAR);
mMonth = now.get(Calendar.MONTH);
mDay = now.get(Calendar.DAY_OF_MONTH);
return dialog;
}
public Dialog onCreateDialog(Bundle savedInstanceState) {
return new DatePickerDialog(mContext, mDateSetListener, mYear, mMonth, mDay);
}
private DatePickerDialog.OnDateSetListener mDateSetListener = new DatePickerDialog.OnDateSetListener() {
#Override
public void onDateSet(DatePicker view, int year, int monthOfYear,
int dayOfMonth) {
mYear = year;
mMonth = monthOfYear;
mDay = dayOfMonth;
mListener.updateChangedDate(year, monthOfYear, dayOfMonth);
}
};
}
And just in case you want it here is the layout:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/LinearLayout1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#drawable/fabricc"
android:orientation="vertical"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context=".SunriseSunset" >
<LinearLayout
android:id="#+id/LinearLayout02"
android:layout_width="fill_parent"
android:layout_height="wrap_content" >
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:padding="10dp"
android:text="Date:"
android:textAppearance="?android:attr/textAppearanceMedium" />
<Button
android:id="#+id/date_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="03-18-2012"
android:onClick="clickMe"/>
</LinearLayout>
<LinearLayout
android:id="#+id/LinearLayout04"
android:layout_width="fill_parent"
android:layout_height="wrap_content" >
<TextView
android:id="#+id/textView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:padding="10dp"
android:text="Location:"
android:textAppearance="?android:attr/textAppearanceMedium" />
<Spinner
android:id="#+id/Locationspinner"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:entries="#array/location_array"
android:padding="10dp" />
</LinearLayout>
<LinearLayout
android:id="#+id/LinearLayout343"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:weightSum="4" >
<TextView
android:id="#+id/textView23"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="2"
android:padding="10dp"
android:text="Coordinates:"
android:textAppearance="?android:attr/textAppearanceMedium" />
<TextView
android:id="#+id/LatCoord"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:padding="10dp" />
<TextView
android:id="#+id/LongCoord"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:padding="10dp" />
</LinearLayout>
<Button
android:id="#+id/CalculateSunriseSunset"
style="#style/sub_menu"
android:background="#drawable/blue_menu_btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:padding="5dp"
android:text="Calculate Sunrise/Sunset Time" />
<LinearLayout
android:id="#+id/LinearLayoutasdsd"
android:layout_width="fill_parent"
android:layout_height="wrap_content" >
<TextView
android:id="#+id/textView122"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:padding="10dp"
android:text="Sunrise:"
android:textAppearance="?android:attr/textAppearanceMedium" />
<TextView
android:id="#+id/Sunrise"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="00:00:00"
android:textAppearance="?android:attr/textAppearanceMedium" />
</LinearLayout>
<LinearLayout
android:id="#+id/LinearLayoutasdsad"
android:layout_width="fill_parent"
android:layout_height="wrap_content" >
<TextView
android:id="#+id/textView133"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:padding="10dp"
android:text="Sunset:"
android:textAppearance="?android:attr/textAppearanceMedium" />
<TextView
android:id="#+id/Sunset"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="00:00:00"
android:textAppearance="?android:attr/textAppearanceMedium" />
</LinearLayout>
</LinearLayout>
Like I said any help would be massively appreciated =)
Thanks for looking.
I am not sure about your requirement but I guess you can try changing from
String formattedDate = df.format(c.getTime());
to
String formattedDate = df.format(now.getTime());
This is pretty dirty but I think it should work just fine.
Your doInBackground should look like this:
#Override
protected String doInBackground(Void... params) {
HttpClient httpClient = new DefaultHttpClient();
HttpContext localContext = new BasicHttpContext();
// Finds todays date and adds that into the URL
//Calendar c = Calendar.getInstance();
//System.out.println("Current time => " + c.getTime());
SimpleDateFormat df = new SimpleDateFormat("dd/MM");
String formattedDate = df.format(now.getTime());
String finalURL = "http://www.earthtools.org/sun/"
+ LatCoord.getText().toString().trim() + "/"
+ LongCoord.getText().toString().trim() + "/"
+ formattedDate + "/99/0";
HttpGet httpGet = new HttpGet(finalURL);
String text = null;
try {
HttpResponse response = httpClient.execute(httpGet,
localContext);
HttpEntity entity = response.getEntity();
text = getASCIIContentFromEntity(entity);
} catch (Exception e) {
return e.getLocalizedMessage();
}
return text;
}
Hope this helps.

Calling different methods depending on which Spinner item is selected - Android

I've been looking at this tutorial for how to use Spinners but I'm now stuck.
Currently when an item is selected from the spinner a toast is displayed with the choice, what I want to do instead is run a method to set the latitude and longitude to the selected country.
The button "Set Location to Japan" works perfectly by calling the method "SetLocationJapan". I just want take this process and put it into the spinner so whenever a choice is made the latitude and longitude is updated.
For example:
if Japan is selected in the spinner I want to call protected void setLocationJapan()
if France is selected I want to call protected void setLocationFrance()
if India is selected I want to call protected void setLocationIndia()
Code as requested:
import java.io.IOException;
import java.io.InputStream;
import java.io.StringReader;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.HttpContext;
import org.w3c.dom.Document;
import org.xml.sax.InputSource;
import android.app.Activity;
import android.content.Context;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.TextView;
public class SunriseSunset extends Activity implements OnClickListener {
public Button getLocation;
public Button setLocationJapan;
public TextView LongCoord;
public TextView LatCoord;
public double longitude;
public double latitude;
public LocationManager lm;
private Spinner spinner1;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.sunrisesunset);
addListenerOnSpinnerItemSelection();
findViewById(R.id.my_button).setOnClickListener(this);
lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 1,
new MyLocationListener());
setLocationJapan = (Button) findViewById(R.id.SetLocationJapan);
getLocation = (Button) findViewById(R.id.GetLocation);
LongCoord = (TextView) findViewById(R.id.LongCoord);
LatCoord = (TextView) findViewById(R.id.LatCoord);
getLocation.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// When GetLocation button is clicked the showCurrentLocation
// function is ran
showCurrentLocation();
}
});
setLocationJapan.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// When SetLocation button is clicked the setCurrentLocation
// function is ran
setLocationJapan();
}
});
}
public void addListenerOnSpinnerItemSelection() {
spinner1 = (Spinner) findViewById(R.id.spinner1);
spinner1.setOnItemSelectedListener(new CustomOnItemSelectedListener());
}
protected void setLocationJapan() {
// TODO Auto-generated method stub
LatCoord.setText("35.4112");
LongCoord.setText("135.8337");
}
protected void setLocationFrance() {
// TODO Auto-generated method stub
LatCoord.setText("65.4112");
LongCoord.setText("85.8337");
}
protected void setLocationIndia() {
// TODO Auto-generated method stub
LatCoord.setText("21.4112");
LongCoord.setText("105.8337");
}
protected void showCurrentLocation() {
// TODO Auto-generated method stub
// This is called to find current location based on GPS data and sends
// this to LongCoord and LatCoord TextViewsw
Location location = lm
.getLastKnownLocation(LocationManager.GPS_PROVIDER);
latitude = location.getLatitude();
longitude = location.getLongitude();
LongCoord.setText(Double.toString(longitude));
LatCoord.setText(Double.toString(latitude));
}
#Override
public void onClick(View arg0) {
Button b = (Button) findViewById(R.id.my_button);
b.setClickable(false);
new LongRunningGetIO().execute();
}
private class LongRunningGetIO extends AsyncTask<Void, Void, String> {
protected String getASCIIContentFromEntity(HttpEntity entity)
throws IllegalStateException, IOException {
InputStream in = entity.getContent();
StringBuffer out = new StringBuffer();
int n = 1;
while (n > 0) {
byte[] b = new byte[4096];
n = in.read(b);
if (n > 0)
out.append(new String(b, 0, n));
}
return out.toString();
}
#Override
protected String doInBackground(Void... params) {
HttpClient httpClient = new DefaultHttpClient();
HttpContext localContext = new BasicHttpContext();
// Finds todays date and adds that into the URL
Calendar c = Calendar.getInstance();
System.out.println("Current time => " + c.getTime());
SimpleDateFormat df = new SimpleDateFormat("dd/MM");
String formattedDate = df.format(c.getTime());
String finalURL = "http://www.earthtools.org/sun/"
+ LatCoord.getText().toString().trim() + "/"
+ LongCoord.getText().toString().trim() + "/"
+ formattedDate + "/99/0";
HttpGet httpGet = new HttpGet(finalURL);
String text = null;
try {
HttpResponse response = httpClient.execute(httpGet,
localContext);
HttpEntity entity = response.getEntity();
text = getASCIIContentFromEntity(entity);
} catch (Exception e) {
return e.getLocalizedMessage();
}
return text;
}
protected void onPostExecute(String results) {
if (results != null) {
try {
DocumentBuilderFactory dbFactory = DocumentBuilderFactory
.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
InputSource s = new InputSource(new StringReader(results));
Document doc = dBuilder.parse(s);
doc.getDocumentElement().normalize();
TextView tvSunrise = (TextView) findViewById(R.id.Sunrise);
TextView tvSunset = (TextView) findViewById(R.id.Sunset);
tvSunrise.setText(doc.getElementsByTagName("sunrise")
.item(0).getTextContent());
tvSunset.setText(doc.getElementsByTagName("sunset").item(0)
.getTextContent());
} catch (Exception e) {
e.printStackTrace();
}
}
Button b = (Button) findViewById(R.id.my_button);
b.setClickable(true);
}
}
class MyLocationListener implements LocationListener {
#Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
}
#Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
}
}
CustomOnItemSelectedListener.java
package richgrundy.learnphotography;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.Toast;
public class CustomOnItemSelectedListener implements OnItemSelectedListener {
public void onItemSelected(AdapterView<?> parent, View view, int pos,long id) {
Toast.makeText(parent.getContext(),
"You have changed to : " + parent.getItemAtPosition(pos).toString(),
Toast.LENGTH_SHORT).show();
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
}
Layout:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/LinearLayout1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".SunriseSunset" >
<Spinner
android:id="#+id/spinner1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="0"
android:entries="#array/country_arrays"
android:padding="10dp" />
<LinearLayout
android:id="#+id/LinearLayout02"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true" >
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:padding="10dp"
android:text="Date:"
android:textAppearance="?android:attr/textAppearanceMedium" />
<TextView
android:id="#+id/Date"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:padding="10dp"
android:text="Current Date"
android:textAppearance="?android:attr/textAppearanceMedium" />
</LinearLayout>
<LinearLayout
android:id="#+id/LinearLayout02"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true" >
<TextView
android:id="#+id/textView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:padding="10dp"
android:text="Location:"
android:textAppearance="?android:attr/textAppearanceMedium" />
</LinearLayout>
<Button
android:id="#+id/GetLocation"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="Find Current Location" />
<Button
android:id="#+id/SetLocationJapan"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="Set Location to Japan" />
<LinearLayout
android:id="#+id/LinearLayout02"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:orientation="horizontal" >
<TextView
android:id="#+id/LatCoord"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="10dp" />
<TextView
android:id="#+id/LongCoord"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="10dp" />
</LinearLayout>
<Button
android:id="#+id/my_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="Calculate Sunrise/Sunset Time" />
<TextView
android:id="#+id/Sunrise"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="00:00:00"
android:textAppearance="?android:attr/textAppearanceMedium" />
<TextView
android:id="#+id/Sunset"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="00:00:00"
android:textAppearance="?android:attr/textAppearanceMedium" />
</LinearLayout>
Any help would be hugely appreciated, Thanks!
I'm pretty sure I need to move setLocationJapan() etc. inside the CustomOnItemSelectedListener class but don't know how to proceed from there.
I'd prefer pseudo code answers so I can work this out for myself if possible :)
This is a bit dirty, but you can pass your activity to CustomOnSelectedListener and then call those methods using the activity. Example:
public class CustomOnSelectedListener extends implements OnItemSelectedListener {
Activity mActivity;
CustomOnSelectedListener(Activity mActivity) {
this.mActivity = mActivity;
}
public void onItemSelected(AdapterView<?> parent, View view, int pos,long id) {
Toast.makeText(parent.getContext(),
"You have changed to : " + parent.getItemAtPosition(pos).toString(),
Toast.LENGTH_SHORT).show();
if (mActivity instanceof SunriseSunset) {
SunriseSunset sunrise = (SunriseSunset) mActivity;
switch (pos) {
case 1: // Assuming Japan is first on your list
sunrise.setLocationJapan();
break;
... // fill in the rest here
}
}
}
... // rest of CustomOnSelectedListener here
}
However, this means all your setLocationJapan, setLocationIndia, etc. must change from protected to public so CustomOnSelectedListener can call them. Also, you must now instantiate CustomOnSelectedListener like this:
spinner1.setOnItemSelectedListener(new CustomOnItemSelectedListener(this));

Categories

Resources