I am developing weather sample application by using Google weather API for android and so far I have developed(You can see image below)
I have problem how to read the data as shown in the red rectangle below. Now what changes do I needed in the source code to read the data.
My main activity
package org.anddev.android.weatherforecast;
import java.net.MalformedURLException;
import java.net.URL;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.anddev.android.weatherforecast.views.SingleWeatherInfoView;
import org.anddev.android.weatherforecast.weather.GoogleWeatherHandler;
import org.anddev.android.weatherforecast.weather.WeatherCurrentCondition;
import org.anddev.android.weatherforecast.weather.WeatherForecastCondition;
import org.anddev.android.weatherforecast.weather.WeatherSet;
import org.anddev.android.weatherforecast.weather.WeatherUtils;
import org.xml.sax.InputSource;
import org.xml.sax.XMLReader;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
public class WeatherForecast extends Activity
{
private final String DEBUG_TAG = "WeatherForcaster";
private CheckBox chk_usecelsius = null;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle icicle)
{
super.onCreate(icicle);
setContentView(R.layout.main);
this.chk_usecelsius = (CheckBox) findViewById(R.id.chk_usecelsius);
Button cmd_submit = (Button) findViewById(R.id.cmd_submit);
cmd_submit.setOnClickListener(new OnClickListener()
{
public void onClick(View arg0)
{
URL url;
try {
/* Get what user typed to the EditText. */
String cityParamString = ((EditText) findViewById(R.id.edit_input)).getText().toString();
String queryString = "http://www.google.com/ig/api?weather=Peshawar, Khyber Pakhtunkhwa"; //Lincoln,Nebraska
/* Replace blanks with HTML-Equivalent. */
url = new URL(queryString.replace(" ", "%20"));
/* Get a SAXParser from the SAXPArserFactory. */
SAXParserFactory spf = SAXParserFactory.newInstance();
SAXParser sp = spf.newSAXParser();
/* Get the XMLReader of the SAXParser we created. */
XMLReader xr = sp.getXMLReader();
/*
* Create a new ContentHandler and apply it to the
* XML-Reader
*/
GoogleWeatherHandler gwh = new GoogleWeatherHandler();
xr.setContentHandler(gwh);
/* Parse the xml-data our URL-call returned. */
xr.parse(new InputSource(url.openStream()));
/* Our Handler now provides the parsed weather-data to us. */
WeatherSet ws = gwh.getWeatherSet();
/* Update the SingleWeatherInfoView with the parsed data. */
updateWeatherInfoView(R.id.weather_today, ws.getWeatherCurrentCondition());
updateWeatherInfoView(R.id.weather_1, ws.getWeatherForecastConditions().get(0));
updateWeatherInfoView(R.id.weather_2, ws.getWeatherForecastConditions().get(1));
updateWeatherInfoView(R.id.weather_3, ws.getWeatherForecastConditions().get(2));
updateWeatherInfoView(R.id.weather_4, ws.getWeatherForecastConditions().get(3));
}
catch (Exception e)
{
resetWeatherInfoViews();
Log.e(DEBUG_TAG, "WeatherQueryError", e);
}
}
});
}
private void updateWeatherInfoView(int aResourceID,WeatherForecastCondition aWFIS)
throws MalformedURLException
{
/* Construct the Image-URL. */
URL imgURL = new URL("http://www.google.com" + aWFIS.getIconURL());
((SingleWeatherInfoView) findViewById(aResourceID)).setRemoteImage(imgURL);
int tempMin = aWFIS.getTempMinCelsius();
int tempMax = aWFIS.getTempMaxCelsius();
/* Convert from Celsius to Fahrenheit if necessary. */
if (this.chk_usecelsius.isChecked())
{
((SingleWeatherInfoView) findViewById(aResourceID)).setTempCelciusMinMax(tempMin, tempMax);
}
else
{
tempMin = WeatherUtils.celsiusToFahrenheit(tempMin);
tempMax = WeatherUtils.celsiusToFahrenheit(tempMax);
((SingleWeatherInfoView) findViewById(aResourceID)).setTempFahrenheitMinMax(tempMin, tempMax);
}
}
private void updateWeatherInfoView(int aResourceID,
WeatherCurrentCondition aWCIS) throws MalformedURLException
{
/* Construct the Image-URL. */
URL imgURL = new URL("http://www.google.com" + aWCIS.getIconURL());
((SingleWeatherInfoView) findViewById(aResourceID)).setRemoteImage(imgURL);
/* Convert from Celsius to Fahrenheit if necessary. */
if (this.chk_usecelsius.isChecked())
{
((SingleWeatherInfoView) findViewById(aResourceID)).setTempCelcius(aWCIS.getTempCelcius());
}
else
{
((SingleWeatherInfoView) findViewById(aResourceID)).setTempFahrenheit(aWCIS.getTempFahrenheit());
}
}
private void resetWeatherInfoViews()
{
((SingleWeatherInfoView)findViewById(R.id.weather_today)).reset();
((SingleWeatherInfoView)findViewById(R.id.weather_1)).reset();
((SingleWeatherInfoView)findViewById(R.id.weather_2)).reset();
((SingleWeatherInfoView)findViewById(R.id.weather_3)).reset();
((SingleWeatherInfoView)findViewById(R.id.weather_4)).reset();
}
}
Weather info view activity
package org.anddev.android.weatherforecast.views;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.Map;
import org.anddev.android.weatherforecast.R;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Typeface;
import android.util.AttributeSet;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
/**
* The View capable of showing a WeatehrIcon + a Temperature-TextView.
*/
public class SingleWeatherInfoView extends LinearLayout {
// ===========================================================
// Fields
// ===========================================================
private ImageView myWeatherImageView = null;
private TextView myTempTextView = null;
// ===========================================================
// Constructors
// ===========================================================
public SingleWeatherInfoView(Context context)
{
super(context);
}
public SingleWeatherInfoView(Context context, AttributeSet attrs) //,Map inflateParams
{
super(context,attrs);
/* Setup the ImageView that will show weather-icon. */
this.myWeatherImageView = new ImageView(context);
this.myWeatherImageView.setImageDrawable(getResources().getDrawable(R.drawable.dunno));
/* Setup the textView that will show the temperature. */
this.myTempTextView = new TextView(context);
this.myTempTextView.setText("? °C");
this.myTempTextView.setTextSize(16);
this.myTempTextView.setTypeface(Typeface.create("Tahoma", Typeface.BOLD));
/* Add child views to this object. */
this.addView(this.myWeatherImageView, new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
this.addView(this.myTempTextView, new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
}
// ===========================================================
// Getter & Setter
// ===========================================================
public void reset()
{
this.myWeatherImageView.setImageDrawable(getResources().getDrawable(R.drawable.dunno));
this.myTempTextView.setText("? °C");
}
/** Sets the Child-ImageView of this to the URL passed. */
public void setRemoteImage(URL aURL)
{
try
{
URLConnection conn = aURL.openConnection();
conn.connect();
InputStream is = conn.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is);
Bitmap bm = BitmapFactory.decodeStream(bis);
bis.close();
is.close();
this.myWeatherImageView.setImageBitmap(bm);
}
catch (IOException e)
{
/* Reset to 'Dunno' on any error. */
this.myWeatherImageView.setImageDrawable(getResources().getDrawable(R.drawable.dunno));
}
}
public void setTempCelcius(int aTemp)
{
this.myTempTextView.setText("" + aTemp + " °C");
}
public void setTempFahrenheit(int aTemp)
{
this.myTempTextView.setText("" + aTemp + " °F");
}
public void setTempFahrenheitMinMax(int aMinTemp, int aMaxTemp)
{
this.myTempTextView.setText("" + aMinTemp + "/" + aMaxTemp + " °F");
}
public void setTempCelciusMinMax(int aMinTemp, int aMaxTemp)
{
this.myTempTextView.setText("" + aMinTemp + "/" + aMaxTemp + " °C");
}
public void setTempString(String aTempString)
{
this.myTempTextView.setText(aTempString);
}
}
Related
I am using below code and my textview links are clickable but i want to make specific button of whatsapp and facebook for sharing..i referred several article in stackoverflow but i want for textview. for webview i had earlier done and it was easy .please help /suggest for textview sharing. i dont want all buttons to open. i want after each listview one facebook and whatsapp icon. on click whatsapp should open with text to be shared
in textview i am adding below for whatsapp share but nothing happens
<a rel="nofollow" href="whatsapp://send?text=एक वृद्ध दंपति को लगने लगा कि उनकी क वृद्ध दंपति को लगने लगा कि उनकी याददाश्त कमजोर हो चली है। यह सुनिश्चित करने के लिये कि उन्हें कुछ नही%0A."><span class="whatsapp"> </span></a>
my java code is
tried adding this one also in java but no benefit.
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("text/plain");
intent.setPackage("com.whatsapp");
if (intent != null) {
intent.putExtra(Intent.EXTRA_TEXT, msg);
startActivity(Intent.createChooser(intent, ""));
main.java code here
package com.hindishayari.funnywall.activity;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.graphics.Typeface;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.ads.AdListener;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdView;
import com.google.android.gms.ads.InterstitialAd;
import com.google.android.gms.analytics.HitBuilders;
import com.google.android.gms.analytics.Tracker;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collections;
import com.hindishayari.funnywall.R;
import com.hindishayari.funnywall.adapter.SwipeDownListAdapter;
import com.hindishayari.funnywall.analytics.AnalyticsApplication;
public class MainActivity extends Activity implements SwipeRefreshLayout.OnRefreshListener {
// URLS for Fetching and Submitting to Funny Wall.
private String FetchFunnyWallURL = "http://xxxxxxxxxxxx.com/AndroidFunnyWallApp/ppppppppp.php";
private String SubmitJokeToWallURL = "http://xxxxxxxxxxxx.com/AndroidFunnyWallApp/hhhhhhhhhh.php";
private InterstitialAd mInterstitialAd;
private SwipeRefreshLayout swipeRefreshLayout;
private ListView listView;
private SwipeDownListAdapter adapter;
private ArrayList<String> jokesList;
private ArrayList<String> timeDateList;
String JokeString = null;
String []dataValues = new String[2];
int counter = 0;
TextView titleTextView;
AlertDialog alertDw;
AlertDialog.Builder builder;
Typeface font;
LinearLayout adViewLayout;
LinearLayout listViewLayout;
private Tracker mTracker;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
AnalyticsApplication application = (AnalyticsApplication) getApplication();
mTracker = application.getDefaultTracker();
font = Typeface.createFromAsset(getAssets(), "HelveticaNeue-Regular.ttf");
titleTextView = (TextView) findViewById(R.id.titleID);
adViewLayout = (LinearLayout) findViewById(R.id.adViewLayoutID);
listViewLayout = (LinearLayout) findViewById(R.id.ListViewLinearLayout);
titleTextView.setTypeface(font);
dataValues[0] = "";
dataValues[1] = "";
listView = (ListView) findViewById(R.id.listView);
swipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.swipe_refresh_layout);
jokesList = new ArrayList<>();
timeDateList = new ArrayList<>();
adapter = new SwipeDownListAdapter(this, jokesList, timeDateList);
listView.setAdapter(adapter);
swipeRefreshLayout.setOnRefreshListener(this);
swipeRefreshLayout.post(new Runnable() {
#Override
public void run() {
swipeRefreshLayout.setRefreshing(true);
jokesList.clear();
timeDateList.clear();
new FetchFunnyWallFromServer().execute(FetchFunnyWallURL);
}
}
);
/*
This function is to refresh the List with Swipe-Down
*/
#Override
public void onRefresh() {
jokesList.clear();
timeDateList.clear();
new FetchFunnyWallFromServer().execute(FetchFunnyWallURL);
}
#Override
protected void onResume() {
super.onResume();
}
/*
This function is to fetch all the jokes + dates from the server and store that into the jokesList
timeDateLis respectively
*/
private class FetchFunnyWallFromServer extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... urls) {
// params comes from the execute() call: params[0] is the url.
try {
return FetchFunnyWall(urls[0]);
} catch (IOException e) {
return "Sorry, We cannot retrieve credits data form the server at this moment.";
}
}
#Override
protected void onPreExecute() {
super.onPreExecute();
listView.setEnabled(false);
dataValues[0] = "";
dataValues[1] = "";
counter = 0;
jokesList.clear();
timeDateList.clear();
}
// onPostExecute displays the results of the AsyncTask.
#Override
protected void onPostExecute(String result) {
swipeRefreshLayout.setRefreshing(false);
listView.setEnabled(true);
if (result.equals("OK")) {
listView.post(new Runnable() {
#Override
public void run() {
Collections.reverse(jokesList);
Collections.reverse(timeDateList);
adapter.notifyDataSetChanged();
listView.smoothScrollToPosition(0);
}
});
}
else
{
Toast.makeText(getApplicationContext(), "Network Connection Problem. Make sure that your internet is properly connected", Toast.LENGTH_SHORT).show();
}
}
}
private String FetchFunnyWall(String myurl) throws IOException, UnsupportedEncodingException {
InputStream is = null;
try {
URL url = new URL(myurl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setUseCaches(false);
conn.setDefaultUseCaches(false);
conn.addRequestProperty("Cache-Control", "no-cache");
conn.setReadTimeout(10000 /* milliseconds */);
conn.setConnectTimeout(15000 /* milliseconds */);
conn.setRequestMethod("GET");
conn.setDoInput(true);
// Starts the query
conn.connect();
is = conn.getInputStream();
BufferedReader textReader = new BufferedReader(new InputStreamReader(is));
String readlineText;
while ((readlineText = textReader.readLine()) != null) {
if (readlineText.length() > 0 )
{
if (readlineText.equals("****")) {
continue;
}
if (readlineText.length() < 4) {
continue;
}
for (int i = 0; i < readlineText.length(); ++i) {
if (readlineText.charAt(i) == '|') {
++counter;
continue;
}
dataValues[counter] = (dataValues[counter] + readlineText.charAt(i));
}
jokesList.add(dataValues[0]);
timeDateList.add(dataValues[1]);
counter = 0;
dataValues[0] = "";
dataValues[1] = "";
}
}
}
}
}
any help will be great
I'm having some kind of logical problem with my code for saving on internal storage.
I created two methods in the class pet for load and save where I'm trying to save and load an instance of pet. I don't get any error messages in logcat, but nothing is saved when I quit and then open the application again.
package Model;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import edu.chl.dat255.sofiase.readyforapet.CreatePet;
import android.content.Context;
public class Pet implements Serializable{
/**
*
*/
private static final long serialVersionUID = 1L;
PetMood petMood = new PetMood();
private int hungerCounter;
private int walkCounter;
private int playCounter;
/**
* Method that increases mood bar while eating
*
* #return String with the pet's reaction
*/
public String eat() {
//walkCounter = petMood.getWalkMood();
hungerCounter = petMood.getFoodMood();
//playCounter = petMood.getPlayMood();
if (hungerCounter < 5) {
hungerCounter = hungerCounter + 1;
petMood.setFoodMood(hungerCounter);
return "Yummie!";
}
else{
return "I am full";
}
}
/**
* Method that increases mood bar while walking
* and decides that the dog can't walk when it is too hungry or too tired
*
* #return String with the pet's reaction
*/
public String walk() {
walkCounter = petMood.getWalkMood();
hungerCounter = petMood.getFoodMood();
playCounter = petMood.getPlayMood();
if (hungerCounter < 3 && walkCounter < 5)
return "I'm too hungry!";
else if (playCounter + walkCounter > 6)
return "I'm tired! I want to rest!";
else if (walkCounter < 5) {
walkCounter = walkCounter + 1;
petMood.setWalkMood(walkCounter);
return "Yeey! Great exercise!";
}
else{
return "I'm tired! I want to rest!";
}
}
/**
* Method that increases mood bar while playing
* and decides that the dog can't play when it is too hungry or too tired
*
* #return String with the pet's reaction
*/
public String play() {
walkCounter = petMood.getWalkMood();
hungerCounter = petMood.getFoodMood();
playCounter = petMood.getPlayMood();
if (playCounter + walkCounter > 6) {
return "I'm tired! I want to rest!";
}
else if (hungerCounter <3 && playCounter < 5)
return "I'm too hungry!";
else if (playCounter < 5 ) {
playCounter = playCounter + 1;
petMood.setPlayMood(playCounter);
return "Yeey! Lots of fun!";
}
else{
return "I'm tired! I want to rest!";
}
}
public void save(String FILENAME, Context context) throws FileNotFoundException, IOException{
FileOutputStream fos = context.openFileOutput(FILENAME, Context.MODE_PRIVATE);
ObjectOutputStream savedPet = new ObjectOutputStream(fos);
savedPet.writeObject(context.getApplicationContext());
savedPet.close();
}
public static Pet load(String FILENAME, Context context) throws FileNotFoundException, IOException, ClassNotFoundException{
FileInputStream fis = context.openFileInput(FILENAME);
ObjectInputStream ois = new ObjectInputStream(fis);
Pet pet = (Pet) ois.readObject();
ois.close();
CreatePet.setPet(pet);
return pet;
}
}
package edu.chl.dat255.sofiase.readyforapet;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.Serializable;
import Model.Dog;
import Model.Pet;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
public class CreatePet extends Activity implements OnClickListener, Serializable { //lagt till interface serializivble. kanske inte n�dv�ndigt
/**
*
*/
private static final long serialVersionUID = 1L;
String petName;
private static Dog dog;
String FILENAME = "pet_file.dat";//lagts till f�r nullpointerexeption
/**
* onCreate Method
*
*
* #param savedInstanceState - Bundle
*/
#Override
protected void onCreate (Bundle savedInstanceState) {
super.onCreate (savedInstanceState);
setContentView(R.layout.createpet);
Button create = (Button) findViewById(R.id.puppy_settings);
create.setOnClickListener(this);
}
public void onClick (View v){
startActivity(new Intent(CreatePet.this, PetActivity.class));
EditText setName = (EditText) findViewById(R.id.edit_pet_name);
petName = setName.getText().toString();
dog = new Dog(petName);
try {
dog.save("pet_file.dat", this);
} catch (FileNotFoundException e) {
System.out.print("File not found kastad i CreatePet");
e.printStackTrace();
} catch (IOException e) {
System.out.print("IOException kastad i CreatePet");
e.printStackTrace();
}
}
/**
* getPet Method
*
* makes the created pet available to other classes
*
* #return dog - an instance of the class Dog
*/
public static Pet getPet(){
return dog;
}
/**
* getPet Method
*
* makes the created pet available to other classes
*
* #return dog - an instance of the class Dog
*/
public static void setPet(Pet pet){
dog = (Dog) pet;
}
}
package edu.chl.dat255.sofiase.readyforapet;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.Serializable;
import Model.Pet;
import Model.Dog;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
public class SelectGame extends Activity implements Serializable {// la till f�r att objektet m�ste vara serializible
private static final long serialVersionUID = 1L;
TextView failMessage;
String FILENAME = "pet_file.dat";// lgts till f�r nullpointerexep
/**
* onCreate method
*
* #param savedInstanceState - Bundle
*/
#Override
protected void onCreate (Bundle savedInstanceState) {
super.onCreate (savedInstanceState);
setContentView(R.layout.selectgame);
//The continue button reacts to a click and starts PetActivity
Button continuePreviousGame = (Button) findViewById(R.id.continuegame);
continuePreviousGame.setOnClickListener(new OnClickListener() {
/**
* Method onClick for the continue previous game button
*
* #param v - View
*/
public void onClick (View v){
try {
Pet.load("pet_file.dat",SelectGame.this);
} catch (FileNotFoundException e) {
System.out.print("File not found ");
e.printStackTrace();
} catch (IOException e) {
System.out.print("IO Exception ");
e.printStackTrace();
} catch (ClassNotFoundException e) {
System.out.print("Class not found exception ");
e.printStackTrace();
}
if (CreatePet.getPet() != null){
startActivity(new Intent(SelectGame.this, PetActivity.class));
}
else{
failMessage = (TextView) findViewById(R.id.failmessage);
failMessage.setText("Create a pet first!");
}
}
}
);
//To send the button CreateNewPet to the activity CreatePet
Button createNewPet = (Button) findViewById(R.id.createnewpet);
createNewPet.setOnClickListener(new OnClickListener() {
/**
* Method onClick for the create new pet button
*
* #param v - View
*/
public void onClick (View v){
startActivity(new Intent(SelectGame.this, CreatePet.class));
}
}
);
}
}
You are saving the wrong object. Your code saves a Context and tries to reload it as a Pet.
Instead of
savedPet.writeObject(context.getApplicationContext());
you should be doing
savedPet.writeObject(this);
Error Log shows error org.anddev.android.weatherforecast.view.SingleWeatherInfoView failed to instantiate
Package name:org.anddev.android.weatherforecast.view
Class name: SingleWeatherInfoView
Please help me to get out of the error.
My error log
error log
package org.anddev.android.weatherforecast.views;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.Map;
import org.anddev.android.weatherforecast.R;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Typeface;
import android.util.AttributeSet;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
/**
* The View capable of showing a WeatehrIcon + a Temperature-TextView.
*/
public class SingleWeatherInfoView extends LinearLayout {
// ===========================================================
// Fields
// ===========================================================
private ImageView myWeatherImageView = null;
private TextView myTempTextView = null;
// ===========================================================
// Constructors
// ===========================================================
public SingleWeatherInfoView(Context context)
{
super(context);
}
public SingleWeatherInfoView(Context context, AttributeSet attrs) //,Map inflateParams
{
super(context,attrs);
/* Setup the ImageView that will show weather-icon. */
this.myWeatherImageView = new ImageView(context);
this.myWeatherImageView.setImageDrawable(getResources().getDrawable(R.drawable.dunno));
/* Setup the textView that will show the temperature. */
this.myTempTextView = new TextView(context);
this.myTempTextView.setText("? °C");
this.myTempTextView.setTextSize(16);
this.myTempTextView.setTypeface(Typeface.create("Tahoma", Typeface.BOLD));
/* Add child views to this object. */
this.addView(this.myWeatherImageView, new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
this.addView(this.myTempTextView, new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
}
// ===========================================================
// Getter & Setter
// ===========================================================
public void reset() {
this.myWeatherImageView.setImageDrawable(getResources().getDrawable(
R.drawable.dunno));
this.myTempTextView.setText("? °C");
}
/** Sets the Child-ImageView of this to the URL passed. */
public void setRemoteImage(URL aURL) {
try {
URLConnection conn = aURL.openConnection();
conn.connect();
InputStream is = conn.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is);
Bitmap bm = BitmapFactory.decodeStream(bis);
bis.close();
is.close();
this.myWeatherImageView.setImageBitmap(bm);
} catch (IOException e) {
/* Reset to 'Dunno' on any error. */
this.myWeatherImageView.setImageDrawable(getResources()
.getDrawable(R.drawable.dunno));
}
}
public void setTempCelcius(int aTemp) {
this.myTempTextView.setText("" + aTemp + " °C");
}
public void setTempFahrenheit(int aTemp) {
this.myTempTextView.setText("" + aTemp + " °F");
}
public void setTempFahrenheitMinMax(int aMinTemp, int aMaxTemp) {
this.myTempTextView.setText("" + aMinTemp + "/" + aMaxTemp + " °F");
}
public void setTempCelciusMinMax(int aMinTemp, int aMaxTemp) {
this.myTempTextView.setText("" + aMinTemp + "/" + aMaxTemp + " °C");
}
public void setTempString(String aTempString) {
this.myTempTextView.setText(aTempString);
}
}
I need to show toast message when the server is not responding
when I press the login button, some parameters are passed to AgAppMenu screen which use url connection to server and get xml response in AgAppHelperMethods screen. The
probelm is when the server is busy or the network is not avaibale, I can't show toast message on catch block although it shows the log message.
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Intent ;
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;
import android.widget.Toast;
public class LoginScreen extends Activity implements OnClickListener {
EditText mobile;
EditText pin;
Button btnLogin;
Button btnClear;
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.agapplogin);
TextView lblMobileNo = (TextView) findViewById(R.id.lblMobileNo);
lblMobileNo.setTextColor(getResources()
.getColor(R.color.text_color_red));
mobile = (EditText) findViewById(R.id.txtMobileNo);
TextView lblPinNo = (TextView) findViewById(R.id.lblPinNo);
lblPinNo.setTextColor(getResources().getColor(R.color.text_color_red));
pin = (EditText) findViewById(R.id.txtPinNo);
btnLogin = (Button) findViewById(R.id.btnLogin);
btnClear = (Button) findViewById(R.id.btnClear);
btnLogin.setOnClickListener(new OnClickListener() {
public void onClick(View view) {
postLoginData();
}
});
btnClear.setOnClickListener(new OnClickListener() {
public void onClick(View v)
{
cleartext();
}
});
/*
*
* btnClear.setOnClickListener(new OnClickListener() { public void
* onClick(View arg0) {
*
* } });
*/
}
public void postLoginData()
{
if (pin.getTextSize() == 0 || mobile.getTextSize() == 0) {
AlertDialog.Builder altDialog = new AlertDialog.Builder(this);
altDialog.setMessage("Please Enter Complete Information!");
} else {
Intent i = new Intent(this.getApplicationContext(), AgAppMenu.class);
Bundle bundle = new Bundle();
bundle.putString("mno", mobile.getText().toString());
bundle.putString("pinno", pin.getText().toString());
i.putExtras(bundle);
startActivity(i);
}
}
#Override
public void onClick(View v) {
}
public void cleartext() {
{
pin.setText("");
mobile.setText("");
}
}
}
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
public class AgAppMenu extends Activity {
String mno, pinno;
private String[][] xmlRespone;
Button btnMiniStatement;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.agappmenu);
mno = getIntent().getExtras().getString("mno");
pinno = getIntent().getExtras().getString("pinno");
setTitle("Welcome to the Ag App Menu");
AgAppHelperMethods agapp =new AgAppHelperMethods();
// xmlRespone = AgAppHelperMethods.AgAppXMLParser("AG_IT_App/AgMainServlet?messageType=LOG&pin=" + pinno + "&mobile=" + mno + "&source=" + mno + "&channel=INTERNET");
xmlRespone = agapp.AgAppXMLParser("AG_IT_App/AgMainServlet?messageType=LOG&pin=" + pinno + "&mobile=" + mno + "&source=" + mno + "&channel=INTERNET");
import java.net.URL;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;
import android.view.View;
import android.view.View.OnKeyListener;
public class AgAppHelperMethods extends Activity {
private static final String LOG_TAG = null;
private static AgAppHelperMethods instance = null;
public static String varMobileNo;
public static String varPinNo;
String[][] xmlRespone = null;
boolean flag = true;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.agapphelpermethods);
}
protected AgAppHelperMethods() {
}
public static AgAppHelperMethods getInstance() {
if (instance == null) {
instance = new AgAppHelperMethods();
}
return instance;
}
public static String getUrl() {
String url = "https://demo.accessgroup.mobi/";
return url;
}
public String[][] AgAppXMLParser(String parUrl) {
String _node, _element;
String[][] xmlRespone = null;
try {
String url = AgAppHelperMethods.getUrl() + parUrl;
URL finalUrl = new URL(url);
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(new InputSource(finalUrl.openStream()));
doc.getDocumentElement().normalize();
NodeList list = doc.getElementsByTagName("*");
_node = new String();
_element = new String();
xmlRespone = new String[list.getLength()][2];
// this "for" loop is used to parse through the
// XML document and extract all elements and their
// value, so they can be displayed on the device
for (int i = 0; i < list.getLength(); i++) {
Node value = list.item(i).getChildNodes().item(0);
_node = list.item(i).getNodeName();
_element = value.getNodeValue();
xmlRespone[i][0] = _node;
xmlRespone[i][1] = _element;
}// end for
throw new ArrayIndexOutOfBoundsException();
}// end try
// will catch any exception thrown by the XML parser
catch (Exception e) {
Toast.makeText(AgAppHelperMethods.this,
"error server not responding " + e.getMessage(),
Toast.LENGTH_SHORT).show();
Log.e(LOG_TAG, "CONNECTION ERROR FUNDAMO SERVER NOT RESPONDING", e);
}
// Log.e(LOG_TAG, "CONNECTION ERROR FUNDAMO SERVER NOT RESPONDING", e);
return xmlRespone;
}
`
AgAppHelperMethods isn't really an Activity. You've derived this class from Activity, but then you've created Singleton management methods (getInstance()) and you are instantiating it yourself. This is bad. Don't do this.
Normally Android controls the instantiation of activities. You don't ever create one yourself (with new).
It looks to me like AgAppHelperMethods just needs to be a regular Java class. It doesn't need to inherit from anything. Remove also the lifecycle methods like onCreate().
Now you will have a problem with the toast, because you need a context for that and AgAppHelperMethods isn't a Context. To solve that you can add Context as a parameter to AgAppXMLParser() like this:
public String[][] AgAppXMLParser(Context context, String parUrl) {
...
// Now you can use "context" to create your toast.
}
When you call AgAppXMLParser() from AgAppMenu just pass "this" as the context parameter.
I want show the maps of my places, based on a selection of area like business,favorites, etc.
I am using the following intent for search and display the result in the maps in Android
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://maps.google.com/maps"));
startActivity(intent);
When I click the maps place as favorites it shows that place in my places.
How can I divide the places based on category in Android?
You should use the place api for getting the selection of area.
Step by step,
How to get the list of nearest place of a location.
Step 1 : Go to API Console for obtaining the Place API
https://code.google.com/apis/console/
and select on services tab
on the place service
now select API Access tab and get the API KEY
now you have a API key for getting place
Now in programming
*Step 2 * : first create a class named Place.java. This class is used to contain the property of place which are provided by Place api.
package com.android.code.GoogleMap.NearsetLandmark;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.json.JSONException;
import org.json.JSONObject;
public class Place {
private String id;
private String icon;
private String name;
private String vicinity;
private Double latitude;
private Double longitude;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getIcon() {
return icon;
}
public void setIcon(String icon) {
this.icon = icon;
}
public Double getLatitude() {
return latitude;
}
public void setLatitude(Double latitude) {
this.latitude = latitude;
}
public Double getLongitude() {
return longitude;
}
public void setLongitude(Double longitude) {
this.longitude = longitude;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getVicinity() {
return vicinity;
}
public void setVicinity(String vicinity) {
this.vicinity = vicinity;
}
static Place jsonToPontoReferencia(JSONObject pontoReferencia) {
try {
Place result = new Place();
JSONObject geometry = (JSONObject) pontoReferencia.get("geometry");
JSONObject location = (JSONObject) geometry.get("location");
result.setLatitude((Double) location.get("lat"));
result.setLongitude((Double) location.get("lng"));
result.setIcon(pontoReferencia.getString("icon"));
result.setName(pontoReferencia.getString("name"));
result.setVicinity(pontoReferencia.getString("vicinity"));
result.setId(pontoReferencia.getString("id"));
return result;
} catch (JSONException ex) {
Logger.getLogger(Place.class.getName()).log(Level.SEVERE, null, ex);
}
return null;
}
#Override
public String toString() {
return "Place{" + "id=" + id + ", icon=" + icon + ", name=" + name + ", latitude=" + latitude + ", longitude=" + longitude + '}';
}
}
Now create a class named PlacesService
package com.android.code.GoogleMap.NearsetLandmark;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.util.Log;
public class PlacesService {
private String API_KEY;
public PlacesService(String apikey) {
this.API_KEY = apikey;
}
public void setApiKey(String apikey) {
this.API_KEY = apikey;
}
public List<Place> findPlaces(double latitude, double longitude,String placeSpacification)
{
String urlString = makeUrl(latitude, longitude,placeSpacification);
try {
String json = getJSON(urlString);
System.out.println(json);
JSONObject object = new JSONObject(json);
JSONArray array = object.getJSONArray("results");
ArrayList<Place> arrayList = new ArrayList<Place>();
for (int i = 0; i < array.length(); i++) {
try {
Place place = Place.jsonToPontoReferencia((JSONObject) array.get(i));
Log.v("Places Services ", ""+place);
arrayList.add(place);
} catch (Exception e) {
}
}
return arrayList;
} catch (JSONException ex) {
Logger.getLogger(PlacesService.class.getName()).log(Level.SEVERE, null, ex);
}
return null;
}
//https://maps.googleapis.com/maps/api/place/search/json?location=28.632808,77.218276&radius=500&types=atm&sensor=false&key=your_api_key
private String makeUrl(double latitude, double longitude,String place) {
StringBuilder urlString = new StringBuilder("https://maps.googleapis.com/maps/api/place/search/json?");
if (place.equals("")) {
urlString.append("&location=");
urlString.append(Double.toString(latitude));
urlString.append(",");
urlString.append(Double.toString(longitude));
urlString.append("&radius=1000");
// urlString.append("&types="+place);
urlString.append("&sensor=false&key=" + API_KEY);
} else {
urlString.append("&location=");
urlString.append(Double.toString(latitude));
urlString.append(",");
urlString.append(Double.toString(longitude));
urlString.append("&radius=1000");
urlString.append("&types="+place);
urlString.append("&sensor=false&key=" + API_KEY);
}
return urlString.toString();
}
protected String getJSON(String url) {
return getUrlContents(url);
}
private String getUrlContents(String theUrl)
{
StringBuilder content = new StringBuilder();
try {
URL url = new URL(theUrl);
URLConnection urlConnection = url.openConnection();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()), 8);
String line;
while ((line = bufferedReader.readLine()) != null)
{
content.append(line + "\n");
}
bufferedReader.close();
}
catch (Exception e)
{
e.printStackTrace();
}
return content.toString();
}
}
Now create a new Activity where you want to get the list of nearest places.
/**
*
*/
package com.android.code.GoogleMap.NearsetLandmark;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.List;
import android.app.AlertDialog;
import android.app.ListActivity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Point;
import android.graphics.drawable.Drawable;
import android.location.Address;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import com.android.code.R;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;
import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;
import com.google.android.maps.Overlay;
/**
* #author dwivedi ji *
* */
public class CheckInActivity extends ListActivity {
private String[] placeName;
private String[] imageUrl;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
new GetPlaces(this,getListView()).execute();
}
class GetPlaces extends AsyncTask<Void, Void, Void>{
Context context;
private ListView listView;
private ProgressDialog bar;
public GetPlaces(Context context, ListView listView) {
// TODO Auto-generated constructor stub
this.context = context;
this.listView = listView;
}
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
bar.dismiss();
this.listView.setAdapter(new ArrayAdapter<String>(context, android.R.layout.simple_list_item_1, placeName));
}
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
bar = new ProgressDialog(context);
bar.setIndeterminate(true);
bar.setTitle("Loading");
bar.show();
}
#Override
protected Void doInBackground(Void... arg0) {
// TODO Auto-generated method stub
findNearLocation();
return null;
}
}
public void findNearLocation() {
PlacesService service = new PlacesService("past your key");
/*
Hear you should call the method find nearst place near to central park new delhi then we pass the lat and lang of central park. hear you can be pass you current location lat and lang.The third argument is used to set the specific place if you pass the atm the it will return the list of nearest atm list. if you want to get the every thing then you should be pass "" only
*/
List<Place> findPlaces = service.findPlaces(28.632808,77.218276,"atm");
// Hear third argument, we pass the atm for getting atm , if you pass the hospital then this method return list of hospital , If you pass nothing then it will return all landmark
placeName = new String[findPlaces.size()];
imageUrl = new String[findPlaces.size()];
for (int i = 0; i < findPlaces.size(); i++) {
Place placeDetail = findPlaces.get(i);
placeDetail.getIcon();
System.out.println( placeDetail.getName());
placeName[i] =placeDetail.getName();
imageUrl[i] =placeDetail.getIcon();
}
}
}