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);
}
}
Related
I want to write the crash report in text file using latest Acra 4.9.0.
I can,t example for this latest version.
I tried using available documentation.
Acra is enabled
but it,s not writing in the file.
myApp
package com.myApp;
import org.acra.ACRA;
import android.app.AlertDialog;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.view.KeyEvent;
import android.view.View;
import com.myApp.Application.AppLauncher;
import com.myApp.interfaces.AppEvents;
import com.myApp.R;
import com.utils.Config;
import com.utils.Constants;
import com.utils.DeviceValidator;
public class myApp extends FragmentActivity
{
private AppLauncher appLauncher = null;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
if(!ACRA.isACRASenderServiceProcess())
{
setContentView(R.layout.activity_myApp);
appLauncher = new AppLauncher();
appLauncher.registerEventListener(appEventsListener);
appLauncher.initApp(this);
}
}
#Override
public void onPause() {
super.onPause();
if(!DeviceValidator.isDeviceValid())
{
return;
}
appLauncher.activityOnPause();
}
#Override
protected void onRestart() {
super.onRestart();
}
#Override
protected void onStart()
{
super.onStart();
}
#Override
public void onResume()
{
super.onResume();
appLauncher.activityOnResume();
}
}
AcraApplication
package com.myAPP;
import org.acra.ACRA;
import org.acra.ReportField;
import org.acra.ReportingInteractionMode;
import org.acra.annotation.ReportsCrashes;
import org.acra.sender.HttpSender.Method;
import android.app.Application;
#ReportsCrashes(
formUri = "http://staging.jemtv.com/variable_dump/index.php",
customReportContent = { ReportField.REPORT_ID, ReportField.DEVICE_ID, ReportField.APP_VERSION_NAME, ReportField.ANDROID_VERSION, ReportField.STACK_TRACE, ReportField.CUSTOM_DATA, ReportField.LOGCAT },
httpMethod = Method.POST,
reportSenderFactoryClasses = org.acra.util.MyOwnSenderFactory.class,
mode = ReportingInteractionMode.SILENT
)
public class AcraApplication extends Application
{
public AcraApplication()
{
super();
}
#Override
public void onCreate() {
super.onCreate();
ACRA.init(this);
}
}
MyOwnSender
package org.acra.util;
import java.io.File;
import java.io.FileOutputStream;
import org.acra.ReportField;
import org.acra.collector.CrashReportData;
import org.acra.config.ACRAConfiguration;
import org.acra.sender.ReportSender;
import org.acra.sender.ReportSenderException;
import android.content.Context;
import android.support.annotation.NonNull;
import android.util.Log;
public class MyOwnSender implements ReportSender {
private static final String FILE_NAME = "AcraReport.txt";
//private final Map<ReportField, String> mMapping = new HashMap<ReportField, String>();
//private FileWriter crashReport = null;
MyOwnSender(Context context, #NonNull ACRAConfiguration config)
{
Log.d("testAcra", "MyOwnSender created");
/* File logFile = new File(context.getFilesDir().getPath() + "/" + FILE_NAME, FILE_NAME);
try {
crashReport = new FileWriter(logFile, true);
} catch (IOException e) {
e.printStackTrace();
}*/
}
#Override
public void send(Context context, CrashReportData report) throws ReportSenderException
{
// Iterate over the CrashReportData instance and do whatever
// you need with each pair of ReportField key / String value
String finalReport = createCrashReport(report);
String tempFile = context.getFilesDir().getPath() + "/" + FILE_NAME;
try
{
File detailedFile = new File(tempFile);
if(!detailedFile.exists())
detailedFile.createNewFile();
FileOutputStream stream = new FileOutputStream(detailedFile, true);
stream.write(finalReport.getBytes());
Log.d("testAcra","adding to file: "+stream);
stream.close();
}
catch (Exception e)
{
e.printStackTrace();
}
/*final Map<String, String> finalReport = remap(report);
try {
BufferedWriter buf = new BufferedWriter(crashReport);
Set<Entry<String, String>> set = reportBody.entrySet();
Iterator<Entry<String, String>> i = set.iterator();
while (i.hasNext()) {
Map.Entry<String, String> me = (Entry<String, String>) i.next();
buf.append("[" + me.getKey() + "]=" + me.getValue());
}
buf.flush();
buf.close();
} catch (IOException e) {
Log.e("TAG", "IO ERROR", e);
}*/
}
private String createCrashReport(CrashReportData crashReportData){
StringBuilder body = new StringBuilder();
body.append("ReportID : " + crashReportData.getProperty(ReportField.REPORT_ID))
.append("\n")
.append("DeviceID : " + crashReportData.getProperty(ReportField.DEVICE_ID))
.append("\n")
.append("AppVersionName : " + crashReportData.getProperty(ReportField.APP_VERSION_NAME))
.append("\n")
.append("Android Version : " + crashReportData.getProperty(ReportField.ANDROID_VERSION))
.append("\n")
.append("CustomData : " + crashReportData.getProperty(ReportField.CUSTOM_DATA))
.append("\n")
.append("STACK TRACE : \n" + crashReportData.getProperty(ReportField.STACK_TRACE))
.append("\n")
.append("LogCAT : \n" + crashReportData.getProperty(ReportField.LOGCAT));
return body.toString();
}
/* private Map<String, String> remap(Map<ReportField, String> report) {
Set<ReportField>fields = ACRA.getConfig().getReportFields();
final Map<String, String> finalReport = new HashMap<String, String>(report.size());
for (ReportField field : fields)
{
if (mMapping == null || mMapping.get(field) == null)
finalReport.put(field.toString(), report.get(field));
else
finalReport.put(mMapping.get(field), report.get(field));
}
return finalReport;
}*/
}
MyOwnSenderFactory
package org.acra.util;
import org.acra.config.ACRAConfiguration;
import org.acra.sender.ReportSender;
import org.acra.sender.ReportSenderFactory;
import android.content.Context;
import android.support.annotation.NonNull;
public class MyOwnSenderFactory implements ReportSenderFactory {
// NB requires a no arg constructor.
/*MyOwnSenderFactory()
{
Log.e("testAcra", "MyOwnSenderFactory created");
}*/
#Override
#NonNull
public ReportSender create(#NonNull Context context, #NonNull ACRAConfiguration config) {
// TODO Auto-generated method stub
return new MyOwnSender(context, config);
}
}
Because i was using jar file instead of aar
in my manifest i was missing
<service
android:name="org.acra.sender.SenderService"
android:exported="false"
android:process=":acra" />
enter code here
That,s why SendeService used in Acra was not starting.
I want to write in application data folder
That is called internal data
I have created my own saver class to handle all of those savings:
import android.content.Context;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.math.BigDecimal;
import java.math.BigInteger;
public class Saver {
static FileOutputStream fos;
static FileInputStream fis;
public static void save(String filename, String data, Context c){
try {
fos = c.openFileOutput(filename, Context.MODE_PRIVATE);
fos.write(data.getBytes());
fos.close();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
String file;
public String getFile(){return file;}
public void setFile(String loc){
file = loc;
}
String result;
private static String mainLoad(String fn, Context c){
String collected = null;
try{
fis = c.openFileInput(fn);
byte[] dataArray = new byte[fis.available()];
while(fis.read(dataArray) != -1){
collected = new String(dataArray);
}
}catch(Exception e){
e.printStackTrace();
return null;
}finally{
try {
fis.close();
return collected;
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
}
}
}
public static int loadInt(String fn, Context c){
if(mainLoad(fn,c) == null) return 0;
else return Integer.parseInt(mainLoad(fn,c));
}
public static double loadDouble(String fn, Context c){
if(mainLoad(fn,c) == null) return 0;
else return Double.parseDouble(mainLoad(fn,c));
}
public static float loadFloat(String fn, Context c){
return Float.parseFloat(mainLoad(fn,c));
}
public static String loadString(String fn, Context c){
return mainLoad(fn, c);
}
public static Boolean loadBoolean(String fn, Context c){
if(mainLoad(fn,c) == null) return false;
else return Boolean.parseBoolean(mainLoad(fn,c));
}
public static BigInteger loadBigInteger(String fn, Context c){
return new BigInteger(mainLoad(fn,c));
}
public static BigDecimal loadBigDecimal(String fn, Context c){
return new BigDecimal(mainLoad(fn,c));
}
}
I want to write the crash report in text file using latest Acra 4.9.0. I can,t example for this latest version.
If you want to write to a .txt file on server, try this backend. Uses the default sender:
<?php
// Outputs all POST parameters to a text file. The file name is the date_time of the report reception
$fileName = date('Y-m-d_H-i-s').'.txt';
$file = fopen($fileName,'w') or die('Could not create report file: ' . $fileName);
foreach($_POST as $key => $value) {
$reportLine = $key." = ".$value."\n";
fwrite($file, $reportLine) or die ('Could not write to report file ' . $reportLine);
}
fclose($file);
?>
If you only want to write locally, then the point of ACRA disappears as you cannot get the files.
If you create .txt files to transmit them, it is actually better to use the backend I linked. It transmits the raw data, and you can get all your fields in a .txt file
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);
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);
}
}
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();
}
}
}