Savings on internal storage android - android

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);

Related

how to check user typing status in group chat using smack 4.1.8 in android

I am creating chat app using smack API 4.1.8. I am getting composing status when user starts typing in one-to-one chat. But I am not getting how to achieve same in group chatting. Here is my code for single chat:
chatStateManager=ChatStateManager.getInstance(RoosterConnection.xmppConnection);
chat=ChatManager.getInstanceFor(RoosterConnection.xmppConnection).createChat(str+"#service_name");
try {
chatStateManager.setCurrentState(ChatState.composing,chat);
} catch (SmackException.NotConnectedException e) {
e.printStackTrace();
Log.d(TAG,"...NotConnectedException occured in onCreate().");
}`
Create in the same package and use like ChatStateManager.
package org.jivesoftware.smack;
import org.jivesoftware.smack.filter.AndFilter;
import org.jivesoftware.smack.filter.FromTypeFilter;
import org.jivesoftware.smack.filter.MessageTypeFilter;
import org.jivesoftware.smack.filter.StanzaExtensionFilter;
import org.jivesoftware.smack.filter.StanzaFilter;
import org.jivesoftware.smack.packet.ExtensionElement;
import org.jivesoftware.smack.packet.Message;
import org.jivesoftware.smackx.chatstates.ChatState;
import org.jivesoftware.smackx.chatstates.ChatStateManager;
import org.jivesoftware.smackx.disco.ServiceDiscoveryManager;
import org.jivesoftware.smackx.muc.MultiUserChat;
import org.jivesoftware.smackx.muc.MultiUserChatManager;
import org.jxmpp.jid.EntityBareJid;
import org.jxmpp.jid.EntityFullJid;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.WeakHashMap;
import java.util.logging.Level;
import java.util.logging.Logger;
public class MUChatStateManager extends Manager {
private static final Logger LOGGER = Logger.getLogger(ChatStateManager.class.getName());
public static final String NAMESPACE = "http://jabber.org/protocol/chatstates";
private static final Map<XMPPConnection, MUChatStateManager> INSTANCES = new WeakHashMap<>();
private static final StanzaFilter INCOMING_MESSAGE_FILTER =
new AndFilter(MessageTypeFilter.GROUPCHAT, FromTypeFilter.ENTITY_FULL_JID);
private static final StanzaFilter INCOMING_CHAT_STATE_FILTER = new AndFilter(INCOMING_MESSAGE_FILTER, new StanzaExtensionFilter(NAMESPACE));
private final Set<MUChatStateListener> chatStateListeners = new HashSet<>();
private final AsyncButOrdered<MultiUserChat> asyncButOrdered = new AsyncButOrdered<>();
public static synchronized MUChatStateManager getInstance(final XMPPConnection connection) {
MUChatStateManager manager = INSTANCES.get(connection);
if (manager == null) {
manager = new MUChatStateManager(connection);
INSTANCES.put(connection, manager);
}
return manager;
}
private MUChatStateManager(XMPPConnection connection) {
super(connection);
connection.addSyncStanzaListener(stanza -> {
final Message message = (Message) stanza;
EntityFullJid fullFrom = message.getFrom().asEntityFullJidIfPossible();
EntityBareJid bareFrom = fullFrom.asEntityBareJid();
final MultiUserChat chat = MultiUserChatManager.getInstanceFor(connection()).getMultiUserChat(bareFrom);
ExtensionElement extension = message.getExtension(NAMESPACE);
String chatStateElementName = extension.getElementName();
ChatState state;
try {
state = ChatState.valueOf(chatStateElementName);
} catch (Exception ex) {
LOGGER.log(Level.WARNING, "Invalid chat state element name: " + chatStateElementName, ex);
return;
}
final ChatState finalState = state;
List<MUChatStateListener> listeners;
synchronized (chatStateListeners) {
listeners = new ArrayList<>(chatStateListeners.size());
listeners.addAll(chatStateListeners);
}
final List<MUChatStateListener> finalListeners = listeners;
asyncButOrdered.performAsyncButOrdered(chat, () -> {
for (MUChatStateListener listener : finalListeners) {
listener.stateChanged(chat, finalState, message);
}
});
}, INCOMING_CHAT_STATE_FILTER);
ServiceDiscoveryManager.getInstanceFor(connection).addFeature(NAMESPACE);
}
/**
* Register a ChatStateListener. That listener will be informed about changed chat states.
*
* #param listener chatStateListener
* #return true, if the listener was not registered before
*/
public boolean addChatStateListener(MUChatStateListener listener) {
synchronized (chatStateListeners) {
return chatStateListeners.add(listener);
}
}
/**
* Unregister a ChatStateListener.
*
* #param listener chatStateListener
* #return true, if the listener was registered before
*/
public boolean removeChatStateListener(MUChatStateListener listener) {
synchronized (chatStateListeners) {
return chatStateListeners.remove(listener);
}
}
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
MUChatStateManager that = (MUChatStateManager) o;
return connection().equals(that.connection());
}
#Override
public int hashCode() {
return connection().hashCode();
}
public interface MUChatStateListener {
void stateChanged(MultiUserChat chat, ChatState finalState, Message message);
}
}
But this class only for observing. You can send custom message like this:
public void changeChatStateMUC(ChatState state, String chatJid) {
try {
Message statusPacket = new Message();
statusPacket.setBody(null);
statusPacket.setType(Message.Type.groupchat);
statusPacket.setTo(chatJid);
ChatStateExtension extension = new ChatStateExtension(state);
statusPacket.addExtension(extension);
sendStanza(statusPacket);
} catch (SmackException.NotConnectedException | InterruptedException e) {
e.printStackTrace();
}
}
public void sendStanza(Stanza stanza) throws SmackException.NotConnectedException, InterruptedException {
xmpptcpConnection.sendStanza(stanza);
}

Unfortunately, Project1 has stopped. Android error while inserting to MongoDB

I am trying to insert data into MongoDB from my Android application. For this I have written this code (given below) but this code pops-up an error when I click save button (for inserting data into MongoDB).
Error: Unfortunately, Project1 has stopped.
So what is the problem in this code and how can I solve that problem?
Code behind insert/save button:
Task save_task = new Task();
save_task.date = showDate.getText().toString();
save_task.location = showLocation.getText().toString();
save_task.description = note.getText().toString();
SaveAsyncTask tsk = new SaveAsyncTask(SetNotification.this);
tsk.execute(save_task);
Task.java Class:
package com.example.abc.project1;
/**
* Created by abc on 02-May-16.
*/
public class Task {
public String date;
public String location;
public String description;
}
SaveAsyncTask.java Class:
package com.example.abc.project1.MongoHQ;
/**
* Created by abc on 02-May-16.
*/
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import android.content.Context;
import android.os.AsyncTask;
import android.util.Log;
import android.widget.Toast;
import com.example.abc.project1.SetNotification;
import com.example.abc.project1.Task;
public class SaveAsyncTask extends AsyncTask<Task, Void, Boolean> {
private static Context context;
public SaveAsyncTask(Context c) {
context = c;
}
#Override
protected Boolean doInBackground(Task... arg0) {
try {
Task task = arg0[0];
QueryBuilder qb = new QueryBuilder();
HttpClient httpClient = new DefaultHttpClient();
HttpPost request = new HttpPost(qb.buildContactsSaveURL());
StringEntity params =new StringEntity(qb.createTask(task));
request.addHeader("content-type", "application/json");
request.setEntity(params);
HttpResponse response = httpClient.execute(request);
if(response.getStatusLine().getStatusCode()<205)
{
return true;
}
else
{
return false;
}
}
catch (Exception e) {
e.printStackTrace();
return false;
}
}
}
QueryBuilder.java Class:
package com.example.abc.project1.MongoHQ;
import com.example.abc.project1.Task;
/**
* Created by abc on 02-May-16.
*/
public class QueryBuilder {
/**
* Specify your database name here
* #return
*/
public String getDatabaseName() {
return "location_notification";
}
/**
* Specify your MongoLab API here
* #return
*/
public String getApiKey() {
return "#########";
}
/**
* This constructs the URL that allows you to manage your database,
* collections and documents
* #return
*/
public String getBaseUrl()
{
return "https://api.mongolab.com/api/1/databases/"+getDatabaseName()+"/collections/";
}
/**
* Completes the formating of your URL and adds your API key at the end
* #return
*/
public String docApiKeyUrl()
{
return "?apiKey="+getApiKey();
}
/**
* Returns the tasks collection
* #return
*/
public String documentRequest()
{
return "tasks";
}
/**
* Builds a complete URL using the methods specified above
* #return
*/
public String buildContactsSaveURL()
{
return getBaseUrl()+documentRequest()+docApiKeyUrl();
}
/**
* Formats the contact details for MongoHQ Posting
* #param : Details of the Task
* #return
*/
public String createTask(Task task)
{
return String
.format("{\"document\" : {\"date\": \"%s\", "
+ "\"location\": \"%s\", \"description\": \"%s\"}, \"safe\" : true}",
task.date, task.location, task.description);
}
}

Insertion is not being done in MongoDB [ANDROID]

I am trying to insert data into into MongoDB from my Android application. For this I have written this code (given below) but this code does nothing when I execute insert task. Neither this code gives any error or exception nor it inserts data to the database. So what is the problem and how can I solve this problem?
In SetNotification.java I do this:
Task save_task = new Task();
save_task.date = showDate.getText().toString();
save_task.location = showLocation.getText().toString();
save_task.description = note.getText().toString();
SaveAsyncTask tsk = new SaveAsyncTask(SetNotification.this);
tsk.execute(save_task);
This is SaveAsyncTask.java class:
package com.example.abc.project1.MongoHQ;
/**
* Created by abc on 02-May-16.
*/
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import android.content.Context;
import android.os.AsyncTask;
import android.util.Log;
import android.widget.Toast;
import com.example.abc.project1.SetNotification;
import com.example.abc.project1.Task;
public class SaveAsyncTask extends AsyncTask<Task, Void, Boolean> {
private static Context context;
public SaveAsyncTask(Context c) {
context = c;
}
#Override
protected Boolean doInBackground(Task... arg0) {
try
{
Task task = arg0[0];
QueryBuilder qb = new QueryBuilder();
HttpClient httpClient = new DefaultHttpClient();
HttpPost request = new HttpPost(qb.buildContactsSaveURL());
StringEntity params =new StringEntity(qb.createTask(task));
request.addHeader("content-type", "application/json");
request.setEntity(params);
HttpResponse response = httpClient.execute(request);
if(response.getStatusLine().getStatusCode()<205)
{
Toast.makeText(context, "SAVED", Toast.LENGTH_SHORT).show();
return true;
}
else
{
Toast.makeText(context, "Saving failed", Toast.LENGTH_SHORT).show();
return false;
}
} catch (Exception e) {
//Log.e("MYAPP", "exception",e);
e.printStackTrace();
return false;
}
}
}
This QueryBuilder.java class:
package com.example.abc.project1.MongoHQ;
import com.example.abc.project1.Task;
/**
* Created by abc on 02-May-16.
*/
public class QueryBuilder {
/**
* Specify your database name here
* #return
*/
public String getDatabaseName() {
return "location_notification";
}
/**
* Specify your MongoLab API here
* #return
*/
public String getApiKey() {
return "################################";
}
/**
* This constructs the URL that allows you to manage your database,
* collections and documents
* #return
*/
public String getBaseUrl()
{
return "https://api.mongolab.com/api/1/databases/"+getDatabaseName()+"/collections/";
}
/**
* Completes the formating of your URL and adds your API key at the end
* #return
*/
public String docApiKeyUrl()
{
return "?apiKey="+getApiKey();
}
/**
* Returns the docs101 collection
* #return
*/
public String documentRequest()
{
return "tasks";
}
/**
* Builds a complete URL using the methods specified above
* #return
*/
public String buildContactsSaveURL()
{
return getBaseUrl()+documentRequest()+docApiKeyUrl();
}
/**
* Formats the contact details for MongoHQ Posting
* #param : Details of the person
* #return
*/
public String createTask(Task task)
{
return String
.format("{\"document\" : {\"date\": \"%s\", "
+ "\"location\": \"%s\", \"description\": \"%s\"}, \"safe\" : true}",
task.date, task.location, task.description);
}
}

How to read weather data through google weather API

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);
}
}

toast mesage not shown on screen when network or server not available

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.

Categories

Resources