I'm trying to permanently store three strings as user preferences for my Android application. These three strings are a url, username, and password. I don't really understand SharedPreferences, so I tried to use internal file storage. I'm not able to retrieve the three strings from the file, and I get a runtime error. I know I probably coded something wrong, but I'm just not proficient enough in Android to understand data storage. Could somebody help me out?
Preferences activity:
package com.amritayalur.mypowerschool;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class MyPowerSchoolActivity extends Activity {
Button buttonSubmit;
TextView textViewTitle;
TextView textViewDesc;
EditText editTextURL, editTextUser, editTextPass;
FileOutputStream fos;
String url = "";
String FILENAME = "InternalStrings";
String str;
String username;
String password;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
buttonSubmit = (Button) findViewById(R.id.buttonSubmit);
textViewTitle = (TextView) findViewById(R.id.textViewTitle);
textViewDesc = (TextView) findViewById(R.id.textViewDesc);
editTextURL = (EditText) findViewById(R.id.editTextURL);
editTextUser = (EditText) findViewById(R.id.editTextUser);
editTextPass = (EditText) findViewById(R.id.editTextPass);
//Start TextView
textViewTitle.setText("MyPowerSchool");
try {
fos = openFileOutput(FILENAME, Context.MODE_PRIVATE);
fos.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//button listener
buttonSubmit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
if ( ( !editTextURL.getText().toString().equals("")) && (
!editTextUser.getText().toString().equals("")) && (
!editTextPass.getText().toString().equals("") ) )
{
url = editTextURL.getText().toString();
username = editTextUser.getText().toString();
password = editTextPass.getText().toString();
//Saving data via File
/* File f = new File(FILENAME);
try {
fos = new FileOutputStream(f);
fos.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
*/
try {
fos = openFileOutput(FILENAME, Context.MODE_PRIVATE);
fos.write(url.getBytes());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
fos.write(username.getBytes());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
fos.write(password.getBytes());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
fos.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// TODO Auto-generated method stub
Intent i = new Intent( MyPowerSchoolActivity.this,
creds.class);
//i.putExtra("pschoolurl", editTextURL.getText().toString());
//i.putExtra("pschooluser", editTextUser.getText().toString());
//i.putExtra("pschoolpass", editTextPass.getText().toString());
// get the text here
final int result = 1;
startActivityForResult(i, result);
}
};
});}}
Activity in which I am trying to retrieve credentials:
package com.amritayalur.mypowerschool;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.widget.TextView;
public class creds extends Activity {
String url;
String username;
String password;
TextView TextViewTest;
String FILENAME = "InternalStrings";
;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.second);
Intent intent = getIntent();
//String url = intent.getExtras().getString("pschoolurl");
//String username = intent.getExtras().getString("pschooluser");
//String password = intent.getExtras().getString("pschoolpass");
String collected = null;
FileInputStream fis = null;
try {
fis = openFileInput(FILENAME);
byte[] dataArray = new byte[fis.available()];
while (fis.read(dataArray) != -1 ){
collected = new String(dataArray);
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
try {
fis.close();
TextViewTest.setText(collected);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
The commented text is a result of me trying to mess around with different aspects of the code.
SharedPreferences is not too difficult.
To add something to the preferences:
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(MyActivity.this); //Get the preferences
Editor edit = prefs.edit(); //Needed to edit the preferences
edit.putString("name", "myname"); //add a String
edit.putBoolean("rememberCredentials", true); //add a boolean
edit.commit(); // save the edits.
To read something:
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(MyActivity.this); //Get the preferences
String name = prefs.getString("name", "defaultName"); //get a String
boolean rememberCredentials = prefs.getBoolean("rememberCredentials", true); //get a boolean.
//When the key "rememberCredentials" is not present, true is returned.
Related
I am trying to create an XML file that will store the variable T1 or the TextOne EditText but I am unsure if I am doing it correctly in this code below. I am also trying to figure out how I can read the created xml file and display the T1 variable into another EditText.
package com.example.treasurehunt;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.StringWriter;
import org.xmlpull.v1.XmlSerializer;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.util.Xml;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class CreateTreasure extends Activity {
//variables
EditText TextOne, TextTwo, TextThree, TextFour, TextFive;
Button SaveTreasure;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_create_treasure);
TextOne = (EditText) findViewById(R.id.EditTextOne);
final String T1 = TextOne.getText().toString();
SaveTreasure = (Button) findViewById(R.id.SaveTreasuresButton);
//onclick
SaveTreasure.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
final String xmlFile="TreasureList";
FileOutputStream fileos;
try {
fileos = getApplicationContext().openFileOutput(xmlFile, Context.MODE_APPEND);
XmlSerializer xmlSerializer = Xml.newSerializer();
StringWriter writer = new StringWriter();
xmlSerializer.setOutput(writer);
xmlSerializer.startDocument("UTF-8",true);
xmlSerializer.startTag(null, "TreasureList");
xmlSerializer.startTag(null, "TreasureOne");
xmlSerializer.text(T1);
xmlSerializer.endTag(null,"TreasureOne");
xmlSerializer.endTag(null, "TreasureList");
xmlSerializer.endDocument();
xmlSerializer.flush();
String dataWrite=writer.toString();
fileos.write(dataWrite.getBytes());
fileos.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.create_treasure, menu);
return true;
}
}
here is my Code
package com.example.messenger;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.net.UnknownHostException;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.os.Bundle;
import android.os.StrictMode;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
#SuppressLint("NewApi")
public class MainActivity extends Activity implements View.OnClickListener {
Button Send;
EditText IPAdresse;
EditText TEXT;
TextView RXtext,tstep,rstep;
private static final int TIMEOUT_MS = 1000;
private static final int server_port = 13011;
#SuppressLint({ "NewApi", "NewApi", "NewApi" })
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
IPAdresse = (EditText) findViewById(R.id.etIPAdresse);
IPAdresse.setText("192.168.2.32");
TEXT = (EditText) findViewById(R.id.etTEXT);
Send = (Button) findViewById(R.id.bSendaa);
RXtext = (TextView) findViewById(R.id.tvRXtext);
tstep = (TextView) findViewById(R.id.tvTstep);
rstep = (TextView) findViewById(R.id.tvRstep);
Send.setOnClickListener(this);
new Thread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
String text;
byte[] message = new byte[1500];
DatagramSocket s;
while(true){
try {
s= new DatagramSocket(server_port);
rstep.setText("1");
s.setBroadcast(true);
rstep.setText("2");
s.setSoTimeout(TIMEOUT_MS);
rstep.setText("3");
while(true){
DatagramPacket p = new DatagramPacket(message, message.length);
rstep.setText("4");
//InetAddress test = InetAddress.getByName("192.168.1.101");
//rstep.setText("5");
//s.connect(test,12345);
//rstep.setText("6");
s.receive(p);
rstep.setText("xxx");
text = new String(message, 0, p.getLength());
RXtext.setText(text);
}
} catch (SocketException e) {
// TODO Auto-generated catch block
e.printStackTrace();
rstep.setText("fail socket create");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
rstep.setText("fail receive");
}
}
}
});
}
public void onClick(View arg0) {
// TODO Auto-generated method stub
switch(arg0.getId()){
case R.id.bSendaa:
tstep.setText("1");
String messageStr= TEXT.getText().toString();
tstep.setText("2");
DatagramSocket s;
try {
s = new DatagramSocket();
tstep.setText("3");
s.setBroadcast(true);
tstep.setText("4");
s.setSoTimeout(TIMEOUT_MS);
tstep.setText("5");
InetAddress local = InetAddress.getByName(IPAdresse.getText().toString());
tstep.setText("6");
int msg_length=messageStr.length();
tstep.setText("7");
byte[] message = messageStr.getBytes();
tstep.setText("8");
DatagramPacket p = new DatagramPacket(message, msg_length,local,server_port);
tstep.setText("9");
s.connect(local,server_port);
tstep.setText("10");
s.send(p);
tstep.setText("sending complete");
} catch (SocketException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
tstep.setText("sending failed");
}
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
My android phone's Ip is 192.168.2.32 , I saw it in wifi settings. So when I debug it row by row , I saw that my virtual device sent the packet , but I don't know why my phone can't get it. Can anybody help me?
Thanks
Regards
now it works , I didn't call start() function for thread , and I should change the UI from runOnUiThread , but it worked only from device to device, not from Virtual Device to Device, so here is the working code
package com.example.messenger;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketAddress;
import java.net.SocketException;
import java.net.UnknownHostException;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.os.Bundle;
import android.os.StrictMode;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
#SuppressLint("NewApi")
public class MainActivity extends Activity implements View.OnClickListener {
Button Send;
EditText IPAdresse;
EditText TEXT;
TextView RXtext,tstep,rstep;
private static final int TIMEOUT_MS = 10000;
private static final int server_port = 13011;
String mMessage;
#SuppressLint({ "NewApi", "NewApi", "NewApi" })
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
IPAdresse = (EditText) findViewById(R.id.etIPAdresse);
IPAdresse.setText("192.168.2.32");
TEXT = (EditText) findViewById(R.id.etTEXT);
Send = (Button) findViewById(R.id.bSendaa);
RXtext = (TextView) findViewById(R.id.tvRXtext);
tstep = (TextView) findViewById(R.id.tvTstep);
rstep = (TextView) findViewById(R.id.tvRstep);
Send.setOnClickListener(this);
new Thread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
String text;
byte[] message = new byte[4];
DatagramSocket s;
try {
s= new DatagramSocket(server_port);
s.setSoTimeout(TIMEOUT_MS);
while(true){
try {
DatagramPacket p = new DatagramPacket(message, message.length);
s.receive(p);
mMessage = new String(message, 0, p.getLength());
runOnUiThread(new Runnable() {
#Override
public void run() {
RXtext.setText(mMessage);
}
});
}
catch(Exception e) {
e.printStackTrace();
}
}
} catch (SocketException e) {
// TODO Auto-generated catch block
e.printStackTrace();
//rstep.setText("fail socket create");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
//rstep.setText("fail receive");
}
}
}).start();
}
public void onClick(View arg0) {
// TODO Auto-generated method stub
switch(arg0.getId()){
case R.id.bSendaa:
String messageStr= TEXT.getText().toString();
DatagramSocket s;
try {
s = new DatagramSocket();
s.setBroadcast(true);
s.setSoTimeout(TIMEOUT_MS);
InetAddress local = InetAddress.getByName(IPAdresse.getText().toString());
int msg_length=messageStr.length();
byte[] message = messageStr.getBytes();
DatagramPacket p = new DatagramPacket(message, msg_length,local,server_port);
//s.connect(local,server_port);
s.send(p);
tstep.setText("sending complete");
} catch (SocketException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
tstep.setText("sending failed");
}
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
I'm planning to integrate Yahoo in my Android Application to get the name and personal details of a user. How do I integrate Yahoo with android?
I have spent several hours looking for a tutorial/sample android application that integrates Yahoo login using OAuth, but I can't find one.
Look at the following code , You need Signpost library Signpost Library
import oauth.signpost.OAuth;
import oauth.signpost.commonshttp.CommonsHttpOAuthConsumer;
import oauth.signpost.commonshttp.CommonsHttpOAuthProvider;
import oauth.signpost.exception.OAuthCommunicationException;
import oauth.signpost.exception.OAuthExpectationFailedException;
import oauth.signpost.exception.OAuthMessageSignerException;
import oauth.signpost.exception.OAuthNotAuthorizedException;
import oauth.signpost.signature.HmacSha1MessageSigner;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
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.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
import com.synapse.selfervices.R;
public class YahooScreen extends Activity {
private static final String REQUEST_TOKEN_ENDPOINT_URL ="https://api.login.yahoo.com/oauth/v2/get_request_token";
private static final String ACCESS_TOKEN_ENDPOINT_URL ="https://api.login.yahoo.com/oauth/v2/get_access_token";
private static final String AUTHORIZE_WEBSITE_URL ="https://api.login.yahoo.com/oauth/v2/request_auth";
private static final int PIN_DIALOG = 0;
String CALLBACK_URL = OAuth.OUT_OF_BAND; // this should be the same as the
// SCHEME and HOST values in
// your AndroidManifest.xml file
String CONSUMER_KEY = "";//
String CONSUMER_SECRET = "";
private CommonsHttpOAuthConsumer myConsumer;
private CommonsHttpOAuthProvider myProvider;
private String requestToken;
private String accessToken;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
callOAuth();
showDialog(PIN_DIALOG);
// createPinDialog().show();
}
private void callOAuth() {
try {
// retrieve the consumer token and then sign it
myConsumer = new CommonsHttpOAuthConsumer(CONSUMER_KEY,
CONSUMER_SECRET);
myConsumer.setMessageSigner(new HmacSha1MessageSigner());
HttpClient client = new DefaultHttpClient();
// retrieve the provider by using the signed consumer token
myProvider = new CommonsHttpOAuthProvider(
REQUEST_TOKEN_ENDPOINT_URL, ACCESS_TOKEN_ENDPOINT_URL,
AUTHORIZE_WEBSITE_URL, client);
myProvider.setOAuth10a(true);
String aUrl = myProvider.retrieveRequestToken(myConsumer,
CALLBACK_URL);
requestToken = myConsumer.getToken();
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(aUrl)));
} catch (Exception ex) {
Toast.makeText(getApplicationContext(), ex.getMessage(),
Toast.LENGTH_LONG).show();
Log.e(ex.getMessage(), ex.toString());
}
}
// this is the callback function that will run when oauth authenticates
// successfully
#Override
protected void onNewIntent(Intent intent) {
System.out.println("OnNewIntent...");
Toast.makeText(getApplicationContext(), "OnNewIntent - It works!",
Toast.LENGTH_LONG).show();
// whatever you want to do after authenticating goes here ....
}
AlertDialog createPinDialog() {
LayoutInflater factory = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);
// LayoutInflater factory = LayoutInflater.from(this);
final View textEntryView = factory.inflate(R.layout.pin, null);
final EditText pinText = (EditText) textEntryView
.findViewById(R.id.pin_text);
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Twitter OAuth PIN");
builder.setView(textEntryView);
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
if (pinText != null)
gotOAuthPin(pinText.getText().toString());
onResume();
}
});
return builder.create();
}
private void gotOAuthPin(String pin) {
SharedPreferences.Editor editor = getSharedPreferences("yahoo",
MODE_PRIVATE).edit();
try {
myProvider.retrieveAccessToken(myConsumer, pin);
accessToken = myConsumer.getToken();
} catch (OAuthMessageSignerException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (OAuthNotAuthorizedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (OAuthExpectationFailedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (OAuthCommunicationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (accessToken != null && accessToken.length() > 0) {
Toast.makeText(this, "Authorized", Toast.LENGTH_SHORT).show();
HttpPost request = new HttpPost(
"http://social.yahooapis.com/v1/user/profile?format=json");
StringEntity body = null;
/*
* try { body = new StringEntity("city=hamburg&label=" +
* URLEncoder.encode("Send via Signpost!", "UTF-8")); } catch
* (UnsupportedEncodingException e1) { // TODO Auto-generated catch
* block e1.printStackTrace(); }
* body.setContentType("application/x-www-form-urlencoded");
* request.setEntity(body);
*/
try {
myConsumer.sign(request);
} catch (OAuthMessageSignerException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (OAuthMessageSignerException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (OAuthExpectationFailedException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (OAuthCommunicationException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
System.out.println("Sending update request to Fire Eagle...");
HttpClient httpClient = new DefaultHttpClient();
HttpResponse response = null;
try {
response = httpClient.execute(request);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Toast.makeText(
this,
"Response: " + response.getStatusLine().getStatusCode()
+ " " + response.getStatusLine().getReasonPhrase(),
Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, "Not Authorized", Toast.LENGTH_SHORT).show();
}
}
#Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case PIN_DIALOG:
LayoutInflater factory = LayoutInflater.from(this);
final View textEntryView = factory.inflate(R.layout.pin, null);
final EditText pinText = (EditText) textEntryView
.findViewById(R.id.pin_text);
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("OAuth PIN");
builder.setView(textEntryView);
builder.setPositiveButton("OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int whichButton) {
if (pinText != null)
gotOAuthPin(pinText.getText().toString());
}
});
return builder.create();
}
return super.onCreateDialog(id);
}}
I am an amateur programmer developing for android. I am just trying get the basics down right now, but I am having an error and I don't know why.
I am creating a activity that has a save and a load button, which using the fileOutputStream and fileInputStream to achieve this task.
The problem I am having is if I hit the load button the first time I use the activity, my application crashes. Can anyone help me with how to skip the load section if the file hasn't been created yet? What should I use within my if statement.
Thanks a ton, here is my code:
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class InternalData extends Activity implements OnClickListener {
String FILENAME = "InternalString";
EditText sharedData;
TextView dataResults;
FileOutputStream fos;
String d;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.sharedpreferences);
Button save = (Button) findViewById(R.id.bSave);
Button load = (Button) findViewById(R.id.bLoad);
sharedData = (EditText) findViewById(R.id.etSharedPrefs);
dataResults = (TextView) findViewById(R.id.tvLoadSharedPrefs);
save.setOnClickListener(this);
load.setOnClickListener(this);
try {
fos = openFileOutput(FILENAME, Context.MODE_PRIVATE);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.bSave:
d = sharedData.getText().toString();
try {
fos.write(d.getBytes());
fos.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
break;
case R.id.bLoad:
FileInputStream fis = null;
try {
if (openFileInput(FILENAME) != null){
fis = openFileInput(FILENAME);
byte[] data = new byte[fis.available()];
while(fis.read(data) != -1){
String readData = new String(data);
dataResults.setText(readData);
}}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
try {
fis.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
break;
}
}
}
Thanks for the help Lukas, I have updated my code, and I was wondering if you could look it over to make sure I am using the AsyncTask properly. Thanks again!
public class InternalData extends Activity implements OnClickListener {
String FILENAME = "InternalString";
EditText sharedData;
TextView dataResults;
FileOutputStream fos;
String d;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.sharedpreferences);
Button save = (Button) findViewById(R.id.bSave);
Button load = (Button) findViewById(R.id.bLoad);
sharedData = (EditText) findViewById(R.id.etSharedPrefs);
dataResults = (TextView) findViewById(R.id.tvLoadSharedPrefs);
save.setOnClickListener(this);
load.setOnClickListener(this);
}
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.bSave:
d = sharedData.getText().toString();
try {
fos = openFileOutput(FILENAME, Context.MODE_PRIVATE);
fos.write(d.getBytes());
fos.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
break;
case R.id.bLoad:
AsyncTask<String, Integer, String> dat = new loadInternalData().execute(FILENAME);
break;
}
}
public class loadInternalData extends AsyncTask<String, Integer, String> {
#Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
FileInputStream fis = null;
String collected = null;
try {
fis = openFileInput(FILENAME);
byte[] data = new byte[fis.available()];
while (fis.read(data) != -1){
collected = new String(data);
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
try {
fis.close();
return collected;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return collected;
}
#Override
protected void onPostExecute( String result )
{
super.onPostExecute(result);
Log.i( "InteralStorage", "onPostExecute(): " + result );
dataResults.setText( result );
}
}
}
You are calling openFileInput twice. Just call it once.
Instead of this
if (openFileInput(FILENAME) != null){
fis = openFileInput(FILENAME);
}
Do this:
fis = openFileInput(FILENAME);
if (fis != null) {
// Read file
}
If you execute something on the UI-Thread, it shouldn't take longer then 5 seconds or an ANR will be triggered.
If you want to do something that might take longer then those 5 seconds, you'll want to do it in a Service or an AsyncTask.
Also, if your App gets force closed and you don't know why, you should always have a look at the LogCat output which can be shown in Eclipse. Also, you should include it with every question you ask here (about Android).
firstly, I coded some methods in Main Activity, But I decided they should be a class.
this is my code... openFileOutput and openFileInput are undefined. Any idea?? maybe it should be service or activity...??
package spexco.hus.system;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Date;
import spexco.hus.cepvizyon.CepVizyon;
import android.content.Context;
public class LicenseIDB {
private String PHONECODEFILE = "CepVizyonCode";
private static String PhoneCode = null;
public LicenseIDB() {
if (readLocal(PHONECODEFILE, 8) == null)
createSystemCode();
}
public static long getDate() {
Date currentTime = new Date();
return currentTime.getTime();
}
public void createSystemCode() {
long date = getDate();
String str = Integer.toHexString(Integer.MAX_VALUE - (int) date);
for (int i = str.length(); i < 8; i++) {
str += "" + i;
}
PhoneCode = str.substring(0, 8);
saveLocal(PhoneCode, PHONECODEFILE);
}
public static String getPhoneCode() {
return PhoneCode;
}
public void saveLocal(String fileString, String Adress) {
try {
FileOutputStream fos = openFileOutput(Adress, Context.MODE_PRIVATE);
fos.write(fileString.getBytes());
fos.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public String readLocal(String Adress, int lenght) {
byte[] buffer = new byte[lenght];
String str = new String();
try {
FileInputStream fis = openFileInput(Adress);
fis.read(buffer);
fis.close();
str = new String(buffer);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return str;
}
}
Those are methods defined on the Context class, not methods defined in your class. When your code was part of an Activity, it could use a convenience method openFileInput() in its Activity base class to access the underlying Context.getApplicationContext().openFileInput() (and similarly for openFileOutput()).
Now you'll have to replace those with the direct calls to the underlying Context methods.
Replace
FileOutputStream fos = openFileOutput(Adress, Context.MODE_PRIVATE);
with below line
FileOutputStream fos = getApplicationContext().openFileOutput(filename, getActivity().MODE_PRIVATE);
If used inside Fragment
FileOutputStream fos =getActivity().openFileOutput(filename, getActivity().MODE_PRIVATE);