What I'm trying to make happen
User clicks babyOneButton
babyOneButton sets the profile_selected attribute in the GENERAL_PREFERENCES.xml shared preferences file
babyOneButton checks if the XML file exists
(1) If it does, send the user the to the page to edit the profile
(2) If it doesn't, send the user to the page to create a new profile
On either page, 'BABY_ONE_PROFILE.xml' data would be shown.
What it's actually doing:
User clicks babyOneButton
Sometimes after pressing submit on NewChildProfile, the name will show up on MainActivity where baby2's name should be?
No matter if the XML file exists or not, the user is always sent to the page to make a new profile. (If I switch the if/else statements around they'll always be sent to the manage page, so I'm assuming my way of finding if the profile exists isn't correct).
BABY_TWO_PROFILE is always the data shown on NewBabyProfile.
MainActivity.java
public class MainActivity extends Activity {
SharedPreferences generalPrefs;
SharedPreferences.Editor generalPrefsEditor;
public static String profileSelected;
public static String babyOneName;
public static String babyTwoName;
File file1, file2, file3;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
file1 = new File("/data/data/com.parentingreminders/shared_prefs/BABY_ONE_PROFILE.XML");
file2 = new File("/data/data/com.parentingreminders/shared_prefs/BABY_TWO_PROFILE.XML");
String BABY_ONE_PROFILE = getString(R.string.baby_one_profile);
String BABY_TWO_PROFILE = getString(R.string.baby_two_profile);
SharedPreferences babyOneProfile = getSharedPreferences(BABY_ONE_PROFILE, 0);
SharedPreferences babyTwoProfile = getSharedPreferences(BABY_TWO_PROFILE, 0);
String babyOneName = babyOneProfile.getString("name", "name");
TextView babyOneNameOutput = (TextView) findViewById(R.id.baby_1_name);
babyOneNameOutput.setText(babyOneName.substring(0,1).toUpperCase() + babyOneName.substring(1));
String babyTwoName = babyTwoProfile.getString("name", "name");
TextView babyTwoNameOutput = (TextView) findViewById(R.id.baby_2_name);
babyTwoNameOutput.setText(babyTwoName.substring(0,1).toUpperCase() + babyTwoName.substring(1));
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.new_baby_profile, menu);
return true;
}
public void babyOneButtonClick(View view) {
profileSelected = "1";
generalPrefs = getSharedPreferences(getString(R.string.general_preferences), Context.MODE_PRIVATE);
generalPrefsEditor = generalPrefs.edit();
generalPrefsEditor.putString("profile_selected", profileSelected).commit();
if (file1.exists()) {
Intent goToManageBaby1 = new Intent(this, ManageBaby1.class);
startActivity(goToManageBaby1);
} else {
Intent goToNewBabyProfile = new Intent(this, NewBabyProfile.class);
startActivity(goToNewBabyProfile);
}
}
public void babyTwoButtonClick(View view) {
profileSelected = "2";
generalPrefs = getSharedPreferences(getString(R.string.general_preferences), Context.MODE_PRIVATE);
generalPrefsEditor = generalPrefs.edit();
generalPrefsEditor.putString("profile_selected", profileSelected).commit();
if (file2.exists()) {
Intent goToManageBaby1 = new Intent(this, ManageBaby1.class);
startActivity(goToManageBaby1);
} else {
Intent goToNewBabyProfile = new Intent(this, NewBabyProfile.class);
startActivity(goToNewBabyProfile);
}
}}
NewBabyProfile.java
public class NewBabyProfile extends Activity {
public static String gender = "na";
public static String name = "na";
public static String dobMonth = "January";
public static String dobDay = "01";
public static String dobYear = "1900";
public static String feedingOz = "00";
public static String feedingHrs = "00";
public static String awakeHrs = "00";
public static int activeStartHour = 0;
public static int activeStartMinute = 0;
public static int activeEnd = 0;
public static String allDay = "no";
public static Spinner mSpinner;
public static int profileNumber;
public static String profileCreated;
public static String profileSelected;
SharedPreferences babyProfile, generalPrefs;
SharedPreferences.Editor editor, generalPrefsEditor;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_new_baby_profile);
mSpinner = (Spinner) findViewById(R.id.dob_month);
// Create an ArrayAdapter using the string array and a default spinner layout
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this,
R.array.months_array, android.R.layout.simple_spinner_item);
// Specify the layout to use when the list of choices appears
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// Apply the adapter to the spinner
mSpinner.setAdapter(adapter);
generalPrefs = getSharedPreferences(getString(R.string.general_preferences), Context.MODE_PRIVATE);
generalPrefsEditor = generalPrefs.edit();
// SharedPreferences initializations
profileSelected = generalPrefs.getString("profile_selected", "profileSelected");
if (profileSelected == "1") {
babyProfile = getSharedPreferences(getString(R.string.baby_one_profile), 0);
}
if (profileSelected == "2"){
babyProfile = getSharedPreferences(getString(R.string.baby_two_profile), 0);
}
editor = babyProfile.edit();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.new_baby_profile, menu);
return true;
}
public void onRadioButtonClicked(View genderSelection){
boolean checked = ((RadioButton) genderSelection).isChecked();
switch(genderSelection.getId()) {
case R.id.gender_boy:
if (checked)
gender = "boy";
break;
case R.id.gender_girl:
if (checked)
gender = "girl";
break;
}
}
public void submitNewBabyProfile(View view) {
// Submit name
EditText nameInput = (EditText)findViewById(R.id.name_input);
name = nameInput.getText().toString().trim();
editor.putString("name",name).commit();
// Submit gender
editor.putString("gender",gender).commit();
// Submit date of birth
String dobMonth = mSpinner.getSelectedItem().toString();
editor.putString("dob_month",dobMonth).commit();
EditText dobDayInput = (EditText)findViewById(R.id.dob_day);
dobDay = dobDayInput.getText().toString().trim();
editor.putString("dob_day",dobDay).commit();
EditText dobYearInput = (EditText)findViewById(R.id.dob_year);
dobYear = dobYearInput.getText().toString().trim();
editor.putString("dob_year",dobYear).commit();
// Submit feeding information
EditText feedingOzInput = (EditText)findViewById(R.id.feeding_oz_input);
feedingOz = feedingOzInput.getText().toString().trim();
editor.putString("feeding_oz_input",feedingOz).commit();
EditText feedingHrInput = (EditText)findViewById(R.id.feeding_hr_input);
feedingHrs = feedingHrInput.getText().toString().trim();
editor.putString("feeding_hr_input",feedingHrs).commit();
// Submit nap information
EditText awakeInput = (EditText)findViewById(R.id.awake_input);
awakeHrs = awakeInput.getText().toString().trim();
editor.putString("awake_input",awakeHrs).commit();
// Submit notification active times
// Return to main activity
Intent goToMainActivity = new Intent(this, MainActivity.class);
startActivity(goToMainActivity);
}
}
Not sure that's the problem but you should never set absolute path strings, as you cannot know the root data path on all Android devices
Look at this : Android basics data storage
The filenames for the SharedPreferences are internal, that's why there's an API. Try replacing
if (file2.exists())
with this
if(babyTwoProfile.contains("name"))
Related
I am the student and i'm learning android, i got following error and i can't find out the solution of that error, plz help me to solve that error. Thank you...
java.lang.RuntimeException: Unable to start activity
ComponentInfo{com.sumit.json1/com.sumit.json1.ParseJSON}:
java.lang.NullPointerException: Attempt to invoke virtual method
'org.json.JSONObject org.json.JSONArray.getJSONObject(int)' on a null object
reference.
There is no issue of connectivity to database. My php code is which is hosted on hostinger.in
<?
//these are the server details
//the username is root by default in case of xampp
//password is nothing by default
//and lastly we have the database named android. if your database name is
different you have to change it
$servername = "mysql.hostinger.in";
$username = "username";
$password = "*********";
$database = "database_name";
//creating a new connection object using mysqli
$conn = new mysqli($servername, $username, $password, $database);
//if there is some error connecting to the database
//with die we will stop the further execution by displaying a message
causing the error
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
//if everything is fine
//creating an array for storing the data
$heroes = array();
//this is our sql query
$sql = "SELECT id, name, email, username, password, gender, lat, lon FROM
appusers;";
//creating an statment with the query
$stmt = $conn->prepare($sql);
//executing that statment
$stmt->execute();
//binding results for that statment
$stmt->bind_result($id, $name, $email, $username, $password, $gender, $lat,
$lon);
//looping through all the records
while($stmt->fetch()){
//pushing fetched data in an array
$temp = [
'id'=>$id,
'name'=>$name,
'email'=>$email,
'username'=>$username,
'password'=>$password,
'gender'=>$gender,
'lat'=>$lat,
'lon'=>$lon
];
//pushing the array inside the hero array
array_push($heroes, $temp);
}
//displaying the data in json format
echo json_encode($heroes);
For parsing json my android code is i.e. ParseJSON.java
public class ParseJSON extends ActionBarActivity implements
View.OnClickListener{
private String myJSONString;
private static final String JSON_ARRAY ="heroes";
private static final String ID = "id";
private static final String NAME= "name";
private static final String EMAIL = "email";
private static final String USERNAME= "username";
private static final String PASSWORD = "password";
private static final String GENDER = "gender";
private static final String LAT = "lat";
private static final String LON = "lon";
private JSONArray users = null;
private int TRACK = 0;
private EditText editTextId;
private EditText editTextName;
private EditText editTextEmail;
private EditText editTextUserName;
private EditText editTextPassword;
private EditText editTextGender;
private EditText editTextLat;
private EditText editTextLon;
Button btnPrev;
Button btnNext;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_parse_json);
Intent intent = getIntent();
myJSONString = intent.getStringExtra(MainActivity.MY_JSON);
editTextId = (EditText) findViewById(R.id.editTextID);
editTextName = (EditText) findViewById(R.id.editTextName);
editTextEmail = (EditText) findViewById(R.id.editTextEmail);
editTextUserName = (EditText) findViewById(R.id.editTextUsername);
editTextPassword = (EditText) findViewById(R.id.editTextPassword);
editTextGender = (EditText) findViewById(R.id.editTextGender);
editTextLat = (EditText) findViewById(R.id.editTextLat);
editTextLon = (EditText) findViewById(R.id.editTextLon);
btnPrev = (Button) findViewById(R.id.buttonPrev);
btnNext = (Button) findViewById(R.id.buttonNext);
btnPrev.setOnClickListener(this);
btnNext.setOnClickListener(this);
extractJSON();
showData();
}
private void extractJSON(){
try {
JSONObject jsonObject = new JSONObject(myJSONString);
users = jsonObject.getJSONArray(JSON_ARRAY);
} catch (JSONException e) {
e.printStackTrace();
}
}
private void moveNext(){
if(TRACK<users.length()){
TRACK++;
}
showData();
}
private void movePrev(){
if(TRACK>0){
TRACK--;
}
showData();
}
private void showData(){
try {
JSONObject jsonObject = users.getJSONObject(TRACK);
editTextId.setText(jsonObject.getString(ID));
editTextName.setText(jsonObject.getString(NAME));
editTextEmail.setText(jsonObject.getString(EMAIL));
editTextUserName.setText(jsonObject.getString(USERNAME));
editTextPassword.setText(jsonObject.getString(PASSWORD));
editTextGender.setText(jsonObject.getString(GENDER));
editTextLat.setText(jsonObject.getString(LAT));
editTextLon.setText(jsonObject.getString(LON));
} catch (JSONException e) {
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.menu_parse_json, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onClick(View v) {
if(v == btnNext){
moveNext();
}
if(v == btnPrev){
movePrev();
}
}
}
In my android project MainActivity.java is given bellow if any error find out plz help me to resove
public class MainActivity extends ActionBarActivity implements View.OnClickListener {
private TextView textViewJSON;
private Button buttonGet;
private Button buttonParse;
public static final String MY_JSON ="MY_JSON";
private static final String JSON_URL = "http://mydatabasedb.16mb.com/JSON1/send-data1.php";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textViewJSON = (TextView) findViewById(R.id.textViewJSON);
textViewJSON.setMovementMethod(new ScrollingMovementMethod());
buttonGet = (Button) findViewById(R.id.buttonGet);
buttonParse = (Button) findViewById(R.id.buttonParse);
buttonGet.setOnClickListener(this);
buttonParse.setOnClickListener(this);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onClick(View v) {
if(v==buttonGet){
getJSON(JSON_URL);
}
if(v==buttonParse){
showParseActivity();
}
}
private void showParseActivity() {
Intent intent = new Intent(this, ParseJSON.class);
intent.putExtra(MY_JSON,textViewJSON.getText().toString());
startActivity(intent);
}
private void getJSON(String url) {
class GetJSON extends AsyncTask<String, Void, String>{
ProgressDialog loading;
#Override
protected void onPreExecute() {
super.onPreExecute();
loading = ProgressDialog.show(MainActivity.this, "Please Wait...",null,true,true);
}
#Override
protected String doInBackground(String... params) {
String uri = params[0];
BufferedReader bufferedReader = null;
try {
URL url = new URL(uri);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
StringBuilder sb = new StringBuilder();
bufferedReader = new BufferedReader(new InputStreamReader(con.getInputStream()));
String json;
while((json = bufferedReader.readLine())!= null){
sb.append(json+"\n");
}
return sb.toString().trim();
}catch(Exception e){
return null;
}
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
loading.dismiss();
textViewJSON.setText(s);
}
}
GetJSON gj = new GetJSON();
gj.execute(url);
}
}
users = jsonObject.getJSONArray(JSON_ARRAY);
This attempts to parse a list at the "heroes" key, but there is no "heroes" key the JSON document. You are encoding a list, not an object.
Open the URL that returns the JSON in a browser, and the problem should be apparent.
I'm new to Android and Java and I'm busy editing an existing app. I am trying to hide a button if no text is getting pulled in from a webservice. I have made it work with another button when the text is being populated
if (textEvent.length() > 1) {
buttonEventSetup.setVisibility(View.INVISIBLE);
}
but when I used:
if (textEvent.length() < 1) {
buttonAccessControl.setVisibility(View.INVISIBLE);
}
nothing seems to happen.
I don't know if the code snippet is in the wrong place or something else is overwriting the code. Here is my activity code:
package com.example.dsouchon.myapplication;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button buttonEventSetup = (Button)findViewById(R.id.buttonEventSetup);
if(Local.isSet(getApplicationContext(), "LoggedIn"))
{
String loggedInUser = Local.Get(getApplicationContext(), "LoggedIn");
if(loggedInUser.length()>0)
{
buttonEventSetup.setVisibility(View.VISIBLE);
}
else
{
buttonEventSetup.setVisibility(View.GONE);
}
}
else
{
buttonEventSetup.setVisibility(View.GONE);
}
if(Local.isSet(getApplicationContext(), "EventName"))
{
String event = Local.Get(getApplicationContext(), "EventName");
TextView textEvent = (TextView) findViewById(R.id.textEventName);
textEvent.setText( event);
Button buttonAccessControl = (Button)findViewById(R.id.buttonAccessControl);
buttonAccessControl.setEnabled(true);
//HIDES SET EVENT BUTTON WHEN EVENT IS SET
if (textEvent.length() > 1) {
buttonEventSetup.setVisibility(View.INVISIBLE);
}
if (textEvent.length() < 1) {
buttonAccessControl.setVisibility(View.INVISIBLE);
}
}
else
{
Button buttonAccessControl = (Button)findViewById(R.id.buttonAccessControl);
buttonAccessControl.setEnabled(false);
}
if(Local.isSet(getApplicationContext(), "EventImage"))
{
TextView textEvent = (TextView) findViewById(R.id.textEventName);
String result = Local.Get(getApplicationContext(), "EventImage");
ImageView imageViewEventImage = (ImageView)findViewById(R.id.imageViewEventImage);
byte[] decodedString = Base64.decode(result, Base64.DEFAULT);
Bitmap decodedByte = BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length);
imageViewEventImage.setImageBitmap(decodedByte);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main2, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public void setupEvent(View view) {
Intent intent = new Intent(MainActivity.this, SetupEvent.class );
finish();
startActivity(intent);
}
public void accessControl(View view) {
Button buttonEventSetup = (Button)findViewById(R.id.buttonEventSetup);
buttonEventSetup.setVisibility(View.GONE);
Intent intent = new Intent(MainActivity.this, MainActivity21.class );
finish();
startActivity(intent);
}
public void Logoff(View view) {
Local.Set(getApplicationContext(), "LoggedIn", "");
}
public void Login(View view) {
final AlertDialog ad=new AlertDialog.Builder(this).create();
MySOAPCallActivity cs = new MySOAPCallActivity();
try {
EditText userName = (EditText) findViewById(R.id.editUserName);
EditText password = (EditText) findViewById(R.id.editPassword);
String user = userName.getText().toString();
String pwd = password.getText().toString();
LoginParams params = new LoginParams(cs, user, pwd);
Local.Set(getApplicationContext(), "UserName", user);
Local.Set(getApplicationContext(), "Password", pwd);
new CallSoapLogin().execute(params);
// new CallSoapGetCurrentEvents().execute(params);
} catch (Exception ex) {
ad.setTitle("Error!");
ad.setMessage(ex.toString());
}
ad.show();
}
public class CallSoapLogin extends AsyncTask<LoginParams, Void, String> {
private Exception exception;
#Override
protected String doInBackground(LoginParams... params) {
return params[0].foo.Login(params[0].username, params[0].password);
}
protected void onPostExecute(String result) {
// TODO: check this.exception
// TODO: do something with the feed
try {
TextView loginResult =(TextView)findViewById(R.id.labelLoginResult);
loginResult.setVisibility(View.VISIBLE);
loginResult.setText(result);
// Button buttonUnsetEvent = (Button)findViewById(R.id.buttonUnsetEvent);
// buttonUnsetEvent.setEnabled(true);
//Spinner spinner2 = (Spinner)findViewById(R.id.spinner2);
//spinner2.setEnabled(true);
boolean LoginSuccessful = false;
if(result.toLowerCase().contains("success"))
{
LoginSuccessful = true;
}
if (LoginSuccessful)
{
String user = Local.Get(getApplicationContext(), "UserName");
Local.Set(getApplicationContext(), "LoggedIn", user);
LinearLayout layoutLoggedIn = (LinearLayout)findViewById(R.id.layoutLoggedIn);
layoutLoggedIn.setVisibility(View.VISIBLE);
Button buttonEventSetup = (Button)findViewById(R.id.buttonEventSetup);
buttonEventSetup.setVisibility(View.VISIBLE);
LinearLayout layoutLogIn = (LinearLayout)findViewById(R.id.layoutLogIn);
layoutLogIn.setVisibility(View.VISIBLE);
}
} catch (Exception ex) {
String e3 = ex.toString();
}
}
}
private static class LoginParams {
MySOAPCallActivity foo;
String username;
String password;
LoginParams(MySOAPCallActivity foo, String username, String password) {
this.foo = foo;
this.username = username;
this.password = password;
}
}
}
You are getting the length of Textview that will not work.Use the text length.This should work
String event = Local.Get(getApplicationContext(), "EventName");
//HIDES SET EVENT BUTTON WHEN EVENT IS SET
if (event.length() > 1) {
buttonEventSetup.setVisibility(View.VISIBLE);
}
if (event.length() < 1) {
buttonAccessControl.setVisibility(View.INVISIBLE);
}
In your code above textEvent is not a string value. It is an Object of type TextView. length() in this case will not return the length of the text contained within that element. You will need to explicitly get the text string before you can get the length of it. This is acquired using the getText() method on the TextView.
Your code should look like the following:
//HIDES SET EVENT BUTTON WHEN EVENT IS SET
if (textEvent.getText().length() >= 1) {
buttonEventSetup.setVisibility(View.VISIBLE);
}
if (textEvent.getText().length() < 1) {
buttonAccessControl.setVisibility(View.INVISIBLE);
}
You also have INVISIBLE on both cases in your posted code example.
Note that your code also does not handle cases where the text length == 1. You could simplify the whole block with the following.
Note: any value != 0 is classed as true
buttonEventSetup.setVisibility(textEvent.getText().length() ? View.VISIBLE : View.INVISIBLE);
I am making a FuelLog app keep a log of fuel fill-ups at gas stations. I am having troubles using GSON to save things into the list as strings. The reason why I am saving an object is because each object (FuelLog) has many attributes including: "Gas Type", "Odometer Reading". etc. I would like to show those attributes on the list rather than "com.example.arshadhusain.fuelTracker.FuelLog#b1a33588" for example. Soon I would also like to edit these list items as well.
Here's how the list looks like so far.
Here's the class for the FuelLog:
public class FuelLog {
public String date;
public String station;
public String odometer;
public String fuelGrade;
public String fuelAmount;
public String fuelUnitCost;
public String fuelCost;
public FuelLog (String date, String station, String odometer, String fuelGrade, String fuelAmount, String fuelUnitCost, String fuelCost) {
this.date = date;
this.station = station;
this.odometer = odometer;
this.fuelGrade = fuelGrade;
this.fuelAmount = fuelAmount;
this.fuelUnitCost = fuelUnitCost;
this.fuelCost = fuelCost;
}
}
Here's the class that saves each log and updates the list (a prompt open for the user to add the attributes).
public class MainActivity extends Activity implements AdapterView.OnItemClickListener {
private Button button;
private EditText editTextMainScreen;
private ListView oldTweetsList;
private static final String FILENAME = "FuelTracker.sav";
private ArrayList<FuelLog> FuelLogs = new ArrayList<FuelLog>();
ArrayAdapter<FuelLog> adapter;
final Context context = this;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// components from main.xml
button = (Button) findViewById(R.id.button);
//editTextMainScreen = (EditText) findViewById(R.id.editTextResult);
oldTweetsList = (ListView) findViewById(R.id.oldTweetsList);
loadFromFile();
adapter = new ArrayAdapter<FuelLog>(this,
R.layout.list_item, FuelLogs);
oldTweetsList.setAdapter(adapter);
oldTweetsList.setOnItemClickListener(this);
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
// get prompts.xml view
LayoutInflater layoutInflater = LayoutInflater.from(context);
View promptView = layoutInflater.inflate(R.layout.prompts, null);
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(context);
// set prompts.xml to be the layout file of the alertdialog builder
alertDialogBuilder.setView(promptView);
final EditText input = (EditText) promptView.findViewById(R.id.userInput);
final EditText input1 = (EditText) promptView.findViewById(R.id.userInput1);
final EditText input2 = (EditText) promptView.findViewById(R.id.userInput2);
final EditText input3 = (EditText) promptView.findViewById(R.id.userInput3);
final EditText input4 = (EditText) promptView.findViewById(R.id.userInput4);
final EditText input5 = (EditText) promptView.findViewById(R.id.userInput5);
final EditText input6 = (EditText) promptView.findViewById(R.id.userInput6);
// setup a dialog window
alertDialogBuilder
.setCancelable(false)
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// get user input and set it to result
//editTextMainScreen.setText(input.getText());
setResult(RESULT_OK);
String station = input.getText().toString();
String odometer = input1.getText().toString();
String fuelGrade = input2.getText().toString();
String fuelAmount = input3.getText().toString();
String fuelUnitCost = input4.getText().toString();
String fuelCost = input5.getText().toString();
String date = input6.getText().toString(); //Date
FuelLog log = new FuelLog(date, station, odometer, fuelGrade, fuelAmount, fuelUnitCost, fuelCost);
FuelLogs.add(log);
adapter.notifyDataSetChanged();
saveInFile();
finish();
}
})
.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
// create an alert dialog
AlertDialog alertD = alertDialogBuilder.create();
alertD.show();
}
});
}
You can just Override toString() method in your FuelLog class like this:
#Override
public String toString() {
return "date = " + date + " station = " + station; // ...etc
}
or
Create custom adapter and in getView() method set you fields;
You can get rid off the problem by just overriding the ToString method of the class FuelLog, if you dont do that, the the list is printing out the hashcode of every FuelLog object added to your list.
I develop an app for android.
I have a lot of variables of EditText type. I'd like to use a Button to save data which was entered by the user. The problem starts when I try to put every EditText one by one.
So I thought about using an ArrayList. I read that I can't put an ArrayList directly to SharedPreferences. But which way is better to do this? Use a Hash, serializable or one by one? I am a beginner so I don't know which way is better - it means more easy to use but longer.
In this case which I tried in one variable ("m" only) but when I click a Button to save this it goes out from app.
How can I improve this code to work correctly?
This is the code:
public class MainActivity extends ActionBarActivity {
public static final String MY_PREFS_NAME = "MyPrefsFile";
EditText m,m1,m2,m3,m00,m11,m22,m33;
Button button10;
SharedPreferences sharedPreferences;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final EditText m = (EditText) findViewById(R.id.message);
final EditText m1 = (EditText) findViewById(R.id.message1);
final EditText m2 = (EditText) findViewById(R.id.message2);
final EditText m3 = (EditText) findViewById(R.id.message3);
final EditText m00 = (EditText) findViewById(R.id.message00);
final EditText m11 = (EditText) findViewById(R.id.message11);
final EditText m22 = (EditText) findViewById(R.id.message22);
final EditText m33 = (EditText) findViewById(R.id.message33);
List<EditText> messageLIST = new ArrayList<EditText>(){{
add(m);
add(m1);
add(m2);
add(m3);
add(m00);
add(m11);
add(m22);
add(m33);
}};
for(int i = 0; i < messageLIST.size(); i++)
{
messageLIST.get(i);
}
sharedPreferences = getApplication().getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE);
String numberValue = sharedPreferences.getString("numberValue", null);
m.setText(numberValue);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public void saveButton(View view)
{
Intent intent = new Intent(this,MainActivity.class);
m.getText().toString();
SharedPreferences sharedPreferences = getApplication().getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("numberValue", m.getText().toString());
editor.commit();
startActivity(intent);
}
}
I have no idea why you need to do this. You can just save comma seperated String for your all edit text values in preferenses.You dont need those lines ..
List<EditText> messageLIST = new ArrayList<EditText>(){{
add(m);
add(m1);
add(m2);
add(m3);
add(m00);
add(m11);
add(m22);
add(m33);
}};
for(int i = 0; i < messageLIST.size(); i++)
{
messageLIST.get(i);
}
Just do this
call getText.toString() on each edit text and append it by other value and then save it in a key to your preference
I would recommend you to create a Map<String, EditText>(). Add all your EditText's to the Map using put("Your key value", yourEditText). When you want to store it to SharedPreferences do this:
SharedPreferences sharedPreferences = getApplication().getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
for(Map.Entry<String, EditText> entry : map.entrySet()){
editor.putString(entry.getKey(), entry.getValue().getText().toString();
}
editor.commit();
In the for loop, you can create a json string and save it to the sharedprefs like;
public void saveToSharedPrefs(List<EditText> messageLIST) {
JSONArray jsonArrayParent = new JSONArray();
for (int i = 0; i < messageLIST.size(); i++) {
String str = messageLIST.get(i).getText().toString().trim();
try {
JSONObject jsonChid = new JSONObject();
jsonChid.put("key", str);
jsonArrayParent.put(jsonChid.toString());
} catch (JSONException e) {
e.printStackTrace();
}
}
SharedPreferences sharedPreferences = getApplication().getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("numberValue", jsonArrayParent.toString());
editor.commit();
}
and call this method in your saveButton method like
public void saveButton(View view) {
Intent intent = new Intent(this, MainActivity.class);
saveToSharedPrefs(messageLIST);
startActivity(intent);
}
Hi just to state i am a beginner android developer and my code may be a bit messy i also appreciate any help anyone can give me, i have implemented parcelable using this tutorial http://www.javacodegeeks.com/2014/01/android-tutorial-two-methods-of-passing-object-by-intent-serializableparcelable.html
i have Two activities activity A and activity B, the first displays a list of custom objects (properties) and the Property class implements parcelable
Activity A has a custom list and I want to add objects dynamically. In this activity I have a button that opens activity B where i input the information required to created a property object which i want to send back to activity A to be added to the list.
Before I implemented parcelable i was able to create the object with no issue but it was stuck in activity B and needs to be added to the list in activity A after implementing parcelable when i first try to open activity A i get an error that crashes my app i think it's because i've added Property mProperty = getIntent().getParcelableExtra(AddProperty.PAR_KEY); in the onCreate method in activity A which looks for an intent before ones been created in Activity B
public class Property implements Parcelable {
// have quit alot of fields so took them out to save space
public Property()
{
}
public Property(String postCode, String address, String county,int noRoom, int askPrice,
String eName,String agentName,String agentNumber, String time) {
this.postCode = postCode;
this.addressFirsLine = address;
this.county = county;
setNumberOfRoom(noRoom);
//numberOfRoom = 2;
setAskingPrice(askPrice);
//askingPrice = 0;
//setCurrentOffer(currentOff);
currentOffer = 0;
//setAgreedPrice(agreedPrice);
agreedPrice = 0;
// setRefurbCost(refurb);
//refurbCost = 2555;
setEstateAgent(eName,agentNumber ,agentName);
// estateAgent = null;
condition = false;
setTime(time);
}
public static final Creator<Property> CREATOR = new Creator<Property>() {
#Override
public Property createFromParcel(Parcel source) {
Property mProperty = new Property();
mProperty.postCode = source.readString() ;
mProperty.addressFirsLine = source.readString();
mProperty.county =source.readString() ;
mProperty.numberOfRoom = source.readInt();
mProperty.askingPrice = source.readInt();
mProperty.agentName = source.readString();
mProperty.agentNumber = source.readString();
mProperty.eName = source.readString();
return mProperty;
}
#Override
public Property[] newArray(int size) {
return new Property[size];
}
};
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(postCode);
dest.writeString(addressFirsLine);
dest.writeString(county);
dest.writeInt(numberOfRoom);
dest.writeInt(askingPrice);
dest.writeString(agentName);
dest.writeString(agentNumber);
dest.writeString(eName);
dest.writeString(time);
}
}
the propery class also has full getters and setters.
the createViewing method is on activity B and is whats used to create the object and send the object back
public void CreateViewing(View view) {
String strPostCode,strAddressFirsLine,strCounty,strEstateAgent,strAgentName,strAgentPhone,strTime ;
int roomNO ;
int askingPrice2 ;
try{
strPostCode = postCode.getText().toString();
strAddressFirsLine=addressFirsLine.getText().toString();
strCounty = county.getText().toString();
roomNO = Integer.parseInt(roomNumber.getText().toString());
askingPrice2 = Integer.parseInt(askingPrice.getText().toString());
strEstateAgent=estateAgent.getText().toString();
strAgentName=agentName.getText().toString() ;
strAgentPhone=agentPhone.getText().toString() ;
strTime =time.getText().toString() ;
Property mProperty = new Property(strPostCode, strAddressFirsLine,
strCounty ,roomNO,askingPrice2,strEstateAgent ,strAgentName,strAgentPhone,
strTime ) ;
String r = mProperty.toString() ;
Intent mIntent = new Intent(this,ViewingSchedule.class);
Bundle mBundle = new Bundle();
mBundle.putParcelable(PAR_KEY,mProperty);
mIntent.putExtras(mBundle);
startActivity(mIntent);
Toast.makeText(AddProperty.this, r, Toast.LENGTH_SHORT).show();
} catch (Exception e) {
e.printStackTrace();
}
this is the onCreate Method for activity A
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_viewing_schedule);
Toolbar toolbar = (Toolbar) findViewById(R.id.app_bar);
setSupportActionBar(toolbar);
getSupportActionBar().setHomeButtonEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
Property mProperty = getIntent().getParcelableExtra(AddProperty.PAR_KEY);
Toast.makeText(ViewingSchedule.this,mProperty.toString(),Toast.LENGTH_SHORT).show();
Property[] propertyList = {new Property("SG1 1LS", "24 CrossGates", "Hertfordshire",2, 200000,"Connels","becky","078123456","9:00")};
//propertyList = mProperty ;
ListView listView1 = (ListView) findViewById(R.id.listView);
ArrayAdapter adapter = new myAdapter2(this,propertyList);
listView1.setAdapter(adapter);
listView1.setOnItemClickListener((new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String itemSelected = "You selected " +
String.valueOf(parent.getItemAtPosition(position));
Toast.makeText(ViewingSchedule.this, itemSelected, Toast.LENGTH_SHORT).show();
}
}));