JSON Parsing error at the runtime - java

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.

Related

Spinner string not retrieved and passed to volleyrequest

I am wanting to get the string value from the spinner. I am currently using Volley in passing data but then it wasn't successful then. This is my RegisterActivity class:
public class RegUserPassClient extends AppCompatActivity implements AdapterView.OnItemSelectedListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_reg_user_pass_client);
final Spinner spinner = findViewById(R.id.genderSpinner);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this, R.array.genderString, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
spinner.setOnItemSelectedListener(this);
final EditText regUserClient= (EditText) findViewById(R.id.regUserClient);
final EditText regPassClient= (EditText) findViewById(R.id.regPassClient);
final EditText regClientName = (EditText) findViewById(R.id.registerClientName);
final EditText regClientNumber = (EditText) findViewById(R.id.registerClientNumber);
final EditText regClientAddress = (EditText) findViewById(R.id.registerClientAddress);
final EditText regClientOccupation = (EditText) findViewById(R.id.registerClientOccupation);
final EditText regClientGender = (EditText) findViewById(R.id.registerClientGender);
final EditText regClientBirthDate = (EditText) findViewById(R.id.registerClientBirthDate);
final TextView clientUser = (TextView) findViewById(R.id.clientUserType);
final Button regClientBtn = (Button) findViewById(R.id.regClient);
final CheckBox toggle = (CheckBox) findViewById(R.id.checkBoxLog);
toggle.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
if(b){
regPassClient.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
}else{
regPassClient.setTransformationMethod(PasswordTransformationMethod.getInstance());
}
}
});
regClientBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final String username = regUserClient.getText().toString();
final String password = regPassClient.getText().toString();
final String name = regClientName.getText().toString();
final String number = regClientNumber.getText().toString();
final String gender = spinner.toString();
final String address = regClientAddress.getText().toString();
final String occupation = regClientOccupation.getText().toString();
final String birthDate = regClientBirthDate.getText().toString();
final String userType = clientUser.getText().toString();
if(!username.isEmpty() && !password.isEmpty() &&
!name.isEmpty() && !address.isEmpty() &&
!occupation.isEmpty() && !gender.isEmpty() &&
!birthDate.isEmpty() && !number.isEmpty()) {
Response.Listener<String> responseListener = new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonResponse = new JSONObject(response);
boolean success = jsonResponse.getBoolean("success");
if (success) {
Intent intent = new Intent(RegUserPassClient.this, LoginRegister.class);
RegUserPassClient.this.startActivity(intent);
Toast.makeText(RegUserPassClient.this,"SuccessFully Registered! Log in your details now!",Toast.LENGTH_LONG).show();
} else {
AlertDialog.Builder builder = new AlertDialog.Builder(RegUserPassClient.this);
builder.setMessage("Username Has already been taken!")
.setNegativeButton("Retry", null)
.create()
.show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
};
RegUserPassClientRequest registerRequest = new RegUserPassClientRequest(username, password, name, number, gender, address, occupation, birthDate, userType, responseListener);
RequestQueue queue = Volley.newRequestQueue(RegUserPassClient.this);
queue.add(registerRequest);
}else if(username.isEmpty()){
regUserClient.setError("Please insert a username");
}else if(password.isEmpty()){
regPassClient.setError("Please put your password");
}else if(name.isEmpty()){
regClientName.setError("Please input your name");
}else if(number.isEmpty()){
regClientNumber.setError("Put your phone number please");
}else if(address.isEmpty()){
regClientGender.setError("Please state your gender");
}else if(occupation.isEmpty()){
regClientAddress.setError("Please put your address");
}else if(gender.isEmpty()){
regClientOccupation.setError("Please state occupation");
}else if(birthDate.isEmpty()){
regClientBirthDate.setError("Please select your Birth Date");
}
}
});
}
#Override
public void onItemSelected(AdapterView<?> parent, View view, int i, long l) {
final String text = parent.getItemAtPosition(i).toString();
Toast.makeText(parent.getContext(), text, Toast.LENGTH_SHORT).show();
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
}
My functions for getting the spinner value are under the volleyrequest. I guess that is where my code is wrong but I don't really know what to put and where is the wrong thing.
It was just
final String gender = spinner.getSelectedItem().toString();
after all! Thanks anyways for viewing guys!

hide button if text length is < 1 in android studio

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

Android coding with mysql and php

How do I pass the data from this to the next activity passing a particular data? I use PHP+MySQL and Java on Android.
I call this by using onClick on the button:
public class LoginActivity extends Activity {
Handler h = new Handler();
/*
* Login
*/
public void Login(View view) {
EditText usernameField = (EditText)findViewById(R.id.editText_Username_L);
EditText passwordField = (EditText)findViewById(R.id.editText_Password_L);
String username = usernameField.getText().toString();
String password = passwordField.getText().toString();
new SigninActivity(this).execute(username,password);
}
/*
* Login
*/
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.login, 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();
//if (id == R.id.action_settings) {
// return true;
//}
return super.onOptionsItemSelected(item);
}
}
This is where my code passes and gets data:
public class SigninActivity extends AsyncTask<String,Void,String> {
private TextView roleField;
private Context context;
public SigninActivity(Context context) {
this.context = context;
}
protected void onPreExecute(){
}
#Override
protected String doInBackground(String... arg0) {
try{
String username = (String)arg0[0];
String password = (String)arg0[1];
String link="http://192.168.254.108/Login/login.php";
String data = URLEncoder.encode("username", "UTF-8")
+ "=" + URLEncoder.encode(username, "UTF-8");
data += "&" + URLEncoder.encode("password", "UTF-8")
+ "=" + URLEncoder.encode(password, "UTF-8");
URL url = new URL(link);
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
OutputStreamWriter wr = new OutputStreamWriter
(conn.getOutputStream());
wr.write( data );
wr.flush();
BufferedReader reader = new BufferedReader
(new InputStreamReader(conn.getInputStream()));
StringBuilder sb = new StringBuilder();
String line = null;
// Read Server Response
while((line = reader.readLine()) != null)
{
sb.append(line);
break;
}
return sb.toString();
}catch(Exception e){
return new String("Exception: " + e.getMessage());
}
}
#Override
protected void onPostExecute(String result){
this.roleField.setText(result);
if(result.equals("")){
Intent i = new Intent(SigninActivity.this, DashboardActivity.class);
i.putExtra("user_id", result);
startActivity(i)
} else {
}
}
}
My PHP code:
<?php
$con=mysqli_connect("localhost","root","","d_database");
if (mysqli_connect_errno($con))
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$username = $_POST['username'];
$password = $_POST['password'];
$result = mysqli_query($con,"SELECT id FROM user where
username='$username' and password='$password'");
$row = mysqli_fetch_array($result);
$data = $row[0];
if($data){
echo $data;
}
mysqli_close($con);
?>
So I answered it, I guess I didn't do enough research.
Here's my code:
public class LoginActivity extends Activity {
Handler h = new Handler();
/*
* Login
*/
public void DishcoverLogin(View view) {
EditText usernameField = (EditText)findViewById(R.id.editText_Username_L);
EditText passwordField = (EditText)findViewById(R.id.editText_Password_L);
String username = usernameField.getText().toString();
String password = passwordField.getText().toString();
new SigninActivity(this).execute(username,password);
}
/*
* Login
*/
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.login, 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();
//if (id == R.id.action_settings) {
// return true;
//}
return super.onOptionsItemSelected(item);
}
private class SigninActivity extends AsyncTask<String,Void,String> {
private TextView roleField;
private Context context;
public SigninActivity(Context context) {
this.context = context;
}
protected void onPreExecute(){
}
#Override
protected String doInBackground(String... arg0) {
try{
String username = (String)arg0[0];
String password = (String)arg0[1];
String link="http://192.168.254.108/Login/d_login.php";
String data = URLEncoder.encode("username", "UTF-8")
+ "=" + URLEncoder.encode(username, "UTF-8");
data += "&" + URLEncoder.encode("password", "UTF-8")
+ "=" + URLEncoder.encode(password, "UTF-8");
URL url = new URL(link);
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
OutputStreamWriter wr = new OutputStreamWriter
(conn.getOutputStream());
wr.write( data );
wr.flush();
BufferedReader reader = new BufferedReader
(new InputStreamReader(conn.getInputStream()));
StringBuilder sb = new StringBuilder();
String line = null;
// Read Server Response
while((line = reader.readLine()) != null)
{
sb.append(line);
break;
}
return sb.toString();
}catch(Exception e){
return new String("Exception: " + e.getMessage());
}
}
#Override
protected void onPostExecute(String result){
String vl=result.toString();
if(vl.equals("registered")){
AlertDialog.Builder alt_bld = new AlertDialog.Builder(LoginActivity.this);
alt_bld.setMessage("D Login Successfull !")
.setCancelable(false)
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// Action for 'Yes' Button
EditText username = (EditText) findViewById(R.id.editText_Username_L);
EditText password = (EditText) findViewById(R.id.editText_Password_L);
Intent in = new Intent(getApplicationContext(), DashboardActivity.class);
in.putExtra("username", username.toString());
in.putExtra("password", password.toString());
startActivity(in);
finish();
}
});
AlertDialog alert = alt_bld.create();
// Title for AlertDialog
alert.setTitle("D Login");
// Icon for AlertDialog
alert.setIcon(R.drawable.topbar);
alert.show();
} else {
AlertDialog.Builder alt_bld = new AlertDialog.Builder(LoginActivity.this);
alt_bld.setMessage("D Login Unsuccessfull !")
.setCancelable(false)
.setNegativeButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// Action for 'NO' Button
dialog.cancel();
}
});
AlertDialog alert = alt_bld.create();
// Title for AlertDialog
alert.setTitle("D Login");
// Icon for AlertDialog
alert.setIcon(R.drawable.topbar);
alert.show();
}
}
}
}

How to save information in multiple text boxes with save and load buttons

I'm trying to create a simple Android program that has text boxes for name, address, phone number, etc. When the user puts this information in and hits save it clears the text boxes, and when they hit the load button it retrieves the info. I know how to do it with one EditText box, but I can't figure out multiple. Can I do this inside one try/catch statement, or do I need more than one? This is what I have right now:
public class MainActivity extends ActionBarActivity {
private EditText textBoxName;
private EditText textBoxAddress;
private EditText textBoxCity;
private EditText textBoxPhone;
private EditText textBoxEmail;
private static final int READ_BLOCK_SIZE = 100;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textBoxName = (EditText) findViewById(R.id.txtName);
textBoxAddress = (EditText) findViewById(R.id.txtAddress);
textBoxCity = (EditText) findViewById(R.id.txtCity);
textBoxPhone = (EditText) findViewById(R.id.txtPhone);
textBoxEmail = (EditText) findViewById(R.id.txtEmail);
Button saveBtn = (Button) findViewById(R.id.btnSave);
Button loadBtn = (Button) findViewById(R.id.btnLoad);
saveBtn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
String strName = textBoxName.getText().toString();
String strAddress = textBoxAddress.getText().toString();
String strCity = textBoxCity.getText().toString();
String strPhone = textBoxPhone.getText().toString();
String strEmail = textBoxEmail.getText().toString();
try {
FileOutputStream fOut = openFileOutput("textfile.txt", MODE_WORLD_READABLE);
OutputStreamWriter osw = new OutputStreamWriter(fOut);
//write the string to the file
osw.write(strName);
osw.flush();
osw.close();
//display file saved messages
Toast.makeText(getBaseContext(), "File saved successfully!",
Toast.LENGTH_SHORT).show();
//clears the EditText
textBoxName.setText("");
textBoxAddress.setText("");
textBoxCity.setText("");
textBoxPhone.setText("");
textBoxEmail.setText("");
}
catch (IOException ioe)
{
ioe.printStackTrace();
}
}
});
loadBtn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
try
{
FileInputStream fIn = openFileInput("textfile.txt");
InputStreamReader isr = new InputStreamReader(fIn);
char[] inputBuffer = new char[READ_BLOCK_SIZE];
String s = "";
int charRead;
while ((charRead = isr.read(inputBuffer))>0)
{
//convert the chars to a String
String readString = String.copyValueOf(inputBuffer, 0, charRead);
s += readString;
inputBuffer = new char[READ_BLOCK_SIZE];
}
//set the EditText to the text that has been read
textBoxName.setText(s);
textBoxAddress.setText(s);
textBoxCity.setText(s);
textBoxPhone.setText(s);
textBoxEmail.setText(s);
Toast.makeText(getBaseContext(), "File loaded successfully!",
Toast.LENGTH_SHORT).show();
}
catch (IOException ioe)
{
ioe.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.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();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
You can use Shared Preferences to store and retrieve information in Android.
you can use shared preferences for this purpose . Just put the value into shared preference and load when the user need this info like username and password saved locally into any login form.

Changing page values based on a button press

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

Categories

Resources