Entered Username won't appear after App title - java

I'm developing a simple to do list application, where on the welcome page, you enter your name and when you click to goto your tasks (on tasks page) your username which you just entered should appear at the top of the screen (For example: "App: Username") but when I tried this it appeared as "App: null" on the welcome page and "null: null" on the tasks page. Can anyone see why? Thank you.
Welcome.java
package winfield.joe.assignment.two;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.RatingBar;
import android.widget.RatingBar.OnRatingBarChangeListener;
import android.widget.Toast;
import android.widget.ToggleButton;
import android.app.ProgressDialog;
import android.widget.CheckBox;
public class Welcome extends Activity {
//global vars
private CheckBox check;
private ProgressDialog progress;
private ToggleButton toggleButton;
private RatingBar ratingBar;
private String givenTitle;
private String username;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_welcome);
givenTitle = (String) this.getTitle();
progress = new ProgressDialog(this);
addListenerOnCheck();
addListenerOnButton();
addListenerOnRatingBar();
}
//on click CheckBox displays a toast message - CLICK!
public void addListenerOnCheck() {
check = (CheckBox) findViewById(R.id.check);
check.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
StringBuffer result = new StringBuffer();
result.append("CLICK!");
Toast.makeText(Welcome.this, result.toString(), Toast.LENGTH_SHORT).show();
}
});
}
//on click toggle button displays on/off
public void addListenerOnButton() {
toggleButton = (ToggleButton) findViewById(R.id.toggleButton);
toggleButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
StringBuffer result = new StringBuffer();
result.append("Toggle = ").append(toggleButton.getText());
Toast.makeText(Welcome.this, result.toString(), Toast.LENGTH_SHORT).show();
}
});
}
//Give a rating - Toast appears of star rating
public void addListenerOnRatingBar() {
ratingBar = (RatingBar) findViewById(R.id.ratingBar);
//if rating value has changed, display the current rating on a toast
ratingBar.setOnRatingBarChangeListener(new OnRatingBarChangeListener() {
public void onRatingChanged(RatingBar ratingBar, float rating, boolean fromUser) {
Toast.makeText(Welcome.this, String.valueOf(ratingBar.getRating()), Toast.LENGTH_SHORT).show();
}
});
}
//Onclick - go to About
public void aboutMe(View view) {
Intent intent = new Intent(Welcome.this, About.class);
startActivity(intent);
}
//Onclick - go to Tasks
public void doStuff(View view) {
this.setTitle(givenTitle + ": " + username);
Intent intent = new Intent(Welcome.this, Tasks.class);
startActivity(intent);
//ProgressBarDialog appears saying its finding yours tasks and loads to 100 and changes activity
progress.setMessage("Finding tasks...");
progress.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
progress.setIndeterminate(true);
progress.show();
//Goes to 100
final int totalProgressTime = 100;
final Thread t = new Thread(){
#Override
public void run(){
//Goes from 0 to 100 in jumps of 5 until the total amount of jumps reaches 100/total progress time
int jumpTime = 0;
while(jumpTime < totalProgressTime){
try {
Thread.sleep(200);
jumpTime += 5;
progress.setProgress(jumpTime);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}; t.start();
}
}
Tasks.java
package winfield.joe.assignment.two;
import android.app.AlertDialog;
import android.app.ListActivity;
import android.content.ContentValues;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.*;
import winfield.joe.assignment.two.database.TaskContract;
import winfield.joe.assignment.two.database.TaskDBHelper;
public class Tasks extends ListActivity {
//add required global variables
private ListAdapter listAdapter;
private TaskDBHelper helper;
private String givenTitle;
private String username;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_tasks);
updateUI();
this.setTitle(givenTitle + ": " + username);
}
//add in the menu (refers to menu.xml file)
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu,menu);
return true;
}
//to get selected tasks from menu
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_add_task:
//create new alert dialog which asks you if you want to make a new task entry
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Add a new task");
builder.setMessage("What do you need to do?");
final EditText inputField = new EditText(this);
builder.setView(inputField);
//if 'add' then place it into the db, update it
builder.setPositiveButton("Add", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
//Clicking add - stores data in the database
String task = inputField.getText().toString();
helper = new TaskDBHelper(Tasks.this);
SQLiteDatabase db = helper.getWritableDatabase();
ContentValues values = new ContentValues();
values.clear();
values.put(TaskContract.Columns.TASK,task);
db.insertWithOnConflict(TaskContract.TABLE,null,values,SQLiteDatabase.CONFLICT_IGNORE);
updateUI();
}
});
//quits out of alert dialog and goes back to the task list if 'cancel'
builder.setNegativeButton("Cancel",null);
builder.create().show();
return true;
default:
return false;
}
}
//Show database entries on the tasks page
private void updateUI() {
helper = new TaskDBHelper(Tasks.this);
SQLiteDatabase sqlDB = helper.getReadableDatabase();
Cursor cursor = sqlDB.query(TaskContract.TABLE, new String[]{
TaskContract.Columns._ID, TaskContract.Columns.TASK
},
null, null, null, null, null);
listAdapter = new SimpleCursorAdapter(
this,
R.layout.task_view,
cursor,
new String[]{TaskContract.Columns.TASK},
new int[]{R.id.taskTextView},
0
);
this.setListAdapter(listAdapter);
}
//Deletes tasks (clicking done next to them)
public void onDoneButtonClick(View view) {
View v = (View) view.getParent();
TextView taskTextView = (TextView) v.findViewById(R.id.taskTextView);
String task = taskTextView.getText().toString();
//This query deletes the entry associated with the id/button pressed
String sql = String.format("DELETE FROM %s WHERE %s = '%s'",
TaskContract.TABLE,
TaskContract.Columns.TASK,
task);
helper = new TaskDBHelper(Tasks.this);
SQLiteDatabase sqlDB = helper.getWritableDatabase();
sqlDB.execSQL(sql);
updateUI();
}
//onClick finished method assigned to the 'Finished' button
public void finished(View view) {
//Make alert dialog box appear and give it it's title
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle(getString(R.string.alert));
// set dialog message
builder.setCancelable(false)
//Positive response = return to list (tasks page)
.setPositiveButton(getString(R.string.positive),new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
//You return to the Tasks
dialog.cancel();
}
})
//Neutral response = go to about (about page)
.setNeutralButton(getString(R.string.neutral),new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
//You go to About Activity
Intent intent = new Intent(Tasks.this, About.class);
startActivity(intent);
}
})
//Negative response = exit app (homescreen)
.setNegativeButton(getString(R.string.negative),new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
// if this button is clicked, exit app to homescreen
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_HOME);
startActivity(intent);
}
});
//create it and show it
AlertDialog alert = builder.create();
alert.show();
}
}
Username within activity_welcome.xml
<EditText
android:ems="10"
android:hint="#+string/username"
android:id="#+id/username"
android:inputType="text"
android:layout_height="wrap_content"
android:layout_marginEnd="30dp"
android:layout_marginStart="30dp"
android:layout_marginTop="30dp"
android:layout_width="match_parent">
<requestFocus/>
</EditText>
Relevant strings from strings.xml
<string name="app_name">ForYouToDo</string>
<string name="username">Username</string>

Go to Android - Pass Data Between Two Activities get NullPointerException
A complete guide(How to pass data between two activity?)
and do in your Tasks Activity
this.setTitle(getResources().getString(R.string.app_name)+ ": " + username);

Related

How do I transfer data from one activity to another in Android Studio? [duplicate]

This question already has answers here:
How do I pass data between Activities in Android application?
(53 answers)
Closed 1 year ago.
I am creating a Pomodoro Timer app. It has 2 activities:
The first one is the home page.
Second is for setting a time.
I want to make a third activity with recent times
I want to create a third activity that takes the input times from the second activity and stores them in a list, but I don't know how to transfer the input-data from the second activity to the third ?
Activity 1:
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button newTime = findViewById(R.id.newTime);
Button currentTime = findViewById(R.id.currentTime);
Button recents = findViewById(R.id.recentTime);
newTime.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent activity2Intent = new Intent(getApplicationContext(), Activity2.class);
startActivity(activity2Intent);
overridePendingTransition(R.anim.slide_in_right,R.anim.slide_out_left);
}
});
// currentTime.setOnClickListener(new View.OnClickListener() {
// #Override
// public void onClick(View v) {
// Intent currentActivityIntent = new Intent(getApplicationContext(), currentActivity.class);
// startActivity(currentActivityIntent);
// overridePendingTransition(R.anim.slide_in_right,R.anim.slide_out_left);
// }
// });
}
}
Activity 2:
package com.example.pomotimer;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;
import java.util.Locale;
public class Activity2 extends AppCompatActivity {
private TextView TextViewCountdown;
private Button Button_Start_Pause;
private Button Reset;
private Button buttonSet;
private Button select_Time;
private EditText edit_Text_Input;
private CountDownTimer countDownTimer;
public long mStartTimeinMillis;
private long timeLeft = mStartTimeinMillis;
private boolean timerRunning;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_2);
TextViewCountdown = findViewById(R.id.textViewCount);
Button_Start_Pause = findViewById(R.id.bnStartPause);
Reset = findViewById(R.id.reset);
select_Time = findViewById(R.id.selectTime);
edit_Text_Input = findViewById(R.id.edit_Text_Input);
buttonSet = findViewById(R.id.buttonSet);
select_Time.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
edit_Text_Input.setVisibility(View.VISIBLE);
buttonSet.setVisibility(View.VISIBLE);
buttonSet.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String input = edit_Text_Input.getText().toString();
if (input.length() == 0){
Toast.makeText(Activity2.this, "Field can't be empty", Toast.LENGTH_SHORT).show();
return;
}
long millisInput = Long.parseLong(input)*60000;
if (millisInput == 0){
Toast.makeText(Activity2.this, "Timer cannot be set to 0", Toast.LENGTH_SHORT).show();
return;
}
setTime(millisInput);
edit_Text_Input.setText("");
// Intent res = new Intent(getApplicationContext(), currentActivity.class);
// startActivityForResult(res, (int) millisInput, null);
}
});
}
});
Button_Start_Pause.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (timerRunning){
pauseTimer();
}
else{
startTimer();
}
}
});
Reset.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
resetTimer();
}
});
int minutes = (int) (timeLeft/1000)/60;
int seconds = (int) (timeLeft/1000)%60;
String timeLeftFormatted = String.format(Locale.getDefault(),"%02d:%02d", minutes, seconds);
TextViewCountdown.setText(timeLeftFormatted);
}
#Override
public void finish() {
super.finish();
overridePendingTransition(R.anim.slide_in_left, R.anim.slide_out_right);
}
public void setTime(long milliseconds){
mStartTimeinMillis = milliseconds;
resetTimer();
}
private void startTimer(){
countDownTimer = new CountDownTimer(timeLeft,1000) {
#Override
public void onTick(long millisUntilFinished) {
// The countdown timer has an automatic method of reducing time by 1s
timeLeft = millisUntilFinished;
int minutes = (int) (timeLeft/1000)/60;
int seconds = (int) (timeLeft/1000)%60;
String timeLeftFormatted = String.format(Locale.getDefault(),"%02d:%02d", minutes, seconds);
TextViewCountdown.setText(timeLeftFormatted);
}
#Override
public void onFinish() {
timerRunning = false;
Button_Start_Pause.setText("Start");
Button_Start_Pause.setVisibility(View.INVISIBLE);
}
}.start();
timerRunning = true;
Button_Start_Pause.setText("pause");
}
private void pauseTimer(){
countDownTimer.cancel();
timerRunning = false;
Button_Start_Pause.setText("Start");
}
private void resetTimer(){
timeLeft = mStartTimeinMillis;
int minutes = (int) (timeLeft/1000)/60;
int seconds = (int) (timeLeft/1000)%60;
Button_Start_Pause.setVisibility(View.VISIBLE);
String timeLeftFormatted = String.format(Locale.getDefault(),"%02d:%02d", minutes, seconds);
TextViewCountdown.setText(timeLeftFormatted);
}
#Override
protected void onStop() {
super.onStop();
SharedPreferences prefs = getSharedPreferences("prefs", MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
editor.putLong("millisleft", timeLeft);
editor.putBoolean("timerRunning", timerRunning);
editor.apply();
}
#Override
protected void onStart() {
super.onStart();
SharedPreferences prefs = getSharedPreferences("prefs", MODE_PRIVATE);
timeLeft = prefs.getLong("millisleft",mStartTimeinMillis);
timerRunning = prefs.getBoolean("timeRunning", false);
int minutes = (int) (timeLeft/1000)/60;
int seconds = (int) (timeLeft/1000)%60;
String timeLeftFormatted = String.format(Locale.getDefault(),"%02d:%02d", minutes, seconds);
TextViewCountdown.setText(timeLeftFormatted);
}
}
We can pass data to another activity using Intent.
Like before startActivity we need to do:
intent.putExtra("Data", data);
and in thirdActivity onCreate we need to do
intent.getStringExtra("Data");
Inside Activity2
You can place data inside the Intent directly or you can put them in a Bundle and then put the inside the Intent. Avoid using both for consistency.
Intent activity3Intent = new Intent(getApplicationContext(), Activity3.class);
//Direct Intent approach
activity3Intent.putExtras("YOUR_STRING_KEY","YOUR_DATA");
//OR Bundle approach
Bundle bundle = new Bundle();
bundle.putString("YOUR_STRING_KEY","YOUR_DATA");
activity3Intent.putExtras(bundle);
startActivity(activity3Intent);
Inside the Activity3 class.
//if direct intent approach
String value = getIntent.getStringExtra("YOUR_STRING_KEY")
//If bundle approach was used.
String value = getIntent().getExtras().getString("YOUR_STRING_KEY");

Shared Preference CANNOT store and read the value with the condition.(Android Studio)

I'm developing an Attendance System. To avoid student helping their friend sign the attendance, I plan to use Shared Preference method to store the student ID, after that will blocking their access when login with his friend ID.
But the if else statement seems doesn't read the Shared Preference method.
Please guide me where I'm wrong, Thanks:
Here is the code:
package com.example.android.jomsign;
import android.content.Intent;
import android.content.SharedPreferences;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.toolbox.Volley;
import org.json.JSONException;
import org.json.JSONObject;
public class LoginActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
final SharedPreferences sharedPref = getSharedPreferences("data",MODE_PRIVATE);
final Boolean Logined = sharedPref.getBoolean("Logined", false);
final String sid = sharedPref.getString("SID", "");
final EditText etid = (EditText) findViewById(R.id.etid);
final EditText etpwd = (EditText) findViewById(R.id.etpwd);
final Button btnlogin = (Button) findViewById(R.id.btnlogin);
final Button btnregister = (Button) findViewById(R.id.btnregister);
final TextView TextView2 = (TextView) findViewById(R.id.etid);
TextView2.setText(sid);
btnregister.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent registerIntent = new Intent(LoginActivity.this, RegisterActivity.class);
LoginActivity.this.startActivity(registerIntent);
}
});
btnlogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
final String id = etid.getText().toString();
final String pwd = etpwd.getText().toString();
if(Logined == true) {
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) {
String id = jsonResponse.getString("id");
String pwd = jsonResponse.getString("pwd");
String name = jsonResponse.getString("name");
Intent intent = new Intent(LoginActivity.this, UserAreaActivity.class);
intent.putExtra("id", id);
intent.putExtra("pwd", pwd);
intent.putExtra("name", name);
SharedPreferences.Editor prefEditor = sharedPref.edit();
prefEditor.putBoolean("Logined", true);
prefEditor.putString("SID", id);
prefEditor.apply();
LoginActivity.this.startActivity(intent);
} else {
AlertDialog.Builder builder = new AlertDialog.Builder(LoginActivity.this);
builder.setMessage("Login Failed")
.setNegativeButton("Retry", null)
.create()
.show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
};
LoginRequest loginRequest = new LoginRequest(id, pwd, responseListener);
RequestQueue queue = Volley.newRequestQueue(LoginActivity.this);
queue.add(loginRequest);
}else if(Logined == false) {
AlertDialog.Builder helpfriend = new AlertDialog.Builder(LoginActivity.this);
helpfriend.setMessage("The login ID not same with the previous ID.Trying to help friend sign? Please contact your lecturer.")
.setNegativeButton("Close", null)
.create()
.show();
}
};
});
}
}
I set the TextView2 is because I want to view the shared Preference value. But seem doesn't work.
It will never go into the if block.
Focus on this line.
final Boolean Logined = sharedPref.getBoolean("Logined", false);
When you open your first time it takes default value false so it will directly go into else if.
For it's solution update above line as following
final int Logined = sharedPref.getInt("Logined", 0);
In btnlogin.setOnClickListeren()
btnlogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
final String id = etid.getText().toString();
final String pwd = etpwd.getText().toString();
if(Logined == 0) {
//Simply allow user to login and write here code for logging.
SharedPreferences sharedPreferences = getSharedPreferences("data", MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("Logined", 1);
editor.putString("SID", sid);//You have to get sid from somewhere.
editor.commit();
}
else if(Logined == 1)
{
if(!sid.equals(sid2))//sid2 is a sid of user who is logging currently
{
AlertDialog.Builder helpfriend = new AlertDialog.Builder(LoginActivity.this);
helpfriend.setMessage("The login ID not same with the previous ID.Trying to help friend sign? Please contact your lecturer.")
.setNegativeButton("Close", null)
.create()
.show();
}
else
{
//allow user for login and write code for logging.
}
}

java.lang.NullPointerException on a null object reference android chat App [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 7 years ago.
Im working in creating chat app for Androdid. The error is when i run the signUp activity I get the java.lang.nullpointerExecption error and im unable to solve this error. Here is my SighnUp activty
The error: `
Process: com.example.hazziq.slidechat, PID: 2106
java.lang.NullPointerException: Attempt to invoke interface method 'java.lang.String com.exmaple.hazziq.slidechat.interfacer.Manager.signUpUser(java.lang.String, java.lang.String, java.lang.String)' on a null object reference
at com.example.hazziq.slidechat.SigningUp$2$1.run(SigningUp.java:107)
Error Line :
result = imService.signUpUser(usernameText.getText().toString(),
passwordText.getText().toString(),
eMailText.getText().toString());
android.app.AlertDialog;
import android.app.Dialog;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.example.example.hazziq.slidechat.serve.MessagingService;
import com.exmaple.hazziq.slidechat.interfacer.Manager;
public class SigningUp extends Activity {
private static final int FILL_ALL_FIELDS = 0;
protected static final int TYPE_SAME_PASSWORD_IN_PASSWORD_FIELDS = 1;
private static final int SIGN_UP_FAILED = 9;
private static final int SIGN_UP_USERNAME_CRASHED = 3;
private static final int SIGN_UP_SUCCESSFULL = 4;
protected static final int USERNAME_AND_PASSWORD_LENGTH_SHORT = 5;
//private static final String SERVER_RES_SIGN_UP_FAILED = "0";
private static final String SERVER_RES_RES_SIGN_UP_SUCCESFULL = "1";
private static final String SERVER_RES_SIGN_UP_USERNAME_CRASHED = "2";
private EditText usernameText;
private EditText passwordText;
private EditText eMailText;
private EditText passwordAgainText;
private Manager imService;
private Handler handler = new Handler();
private ServiceConnection mConnection = new ServiceConnection() {
public void onServiceConnected(ComponentName className, IBinder service) {
// This is called when the connection with the service has been
// established, giving us the service object we can use to
// interact with the service. Because we have bound to a explicit
// service that we know is running in our own process, we can
// cast its IBinder to a concrete class and directly access it.
imService = ((MessagingService.IMBinder)service).getService();
}
public void onServiceDisconnected(ComponentName className) {
// This is called when the connection with the service has been
// unexpectedly disconnected -- that is, its process crashed.
// Because it is running in our same process, we should never
// see this happen.
imService = null;
Toast.makeText(SigningUp.this, R.string.local_service_stopped,
Toast.LENGTH_SHORT).show();
}
};
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_signing_up);
setTitle("Sign up");
Button signUpButton = (Button) findViewById(R.id.signUp);
Button cancelButton = (Button) findViewById(R.id.cancel_signUp);
usernameText = (EditText) findViewById(R.id.userName);
passwordText = (EditText) findViewById(R.id.password);
passwordAgainText = (EditText) findViewById(R.id.passwordAgain);
eMailText = (EditText) findViewById(R.id.email);
signUpButton.setOnClickListener(new OnClickListener(){
public void onClick(View arg)
{
if (usernameText.length() > 0&&
passwordText.length() > 0 &&
passwordAgainText.length() > 0 &&
eMailText.length() > 0
)
{
//TODO check email address is valid
if (passwordText.getText().toString().equals(passwordAgainText.getText().toString())){
if (usernameText.length() >= 5 && passwordText.length() >= 5) {
Thread thread = new Thread(){
String result = new String();
#Override
public void run() {
result = imService.signUpUser(usernameText.getText().toString(),
passwordText.getText().toString(),
eMailText.getText().toString());
handler.post(new Runnable(){
public void run() {
if (result!= null && equals(SERVER_RES_RES_SIGN_UP_SUCCESFULL)) {
Toast.makeText(getApplicationContext(),R.string.signup_successfull, Toast.LENGTH_LONG).show();
}
else if (result.equals(SERVER_RES_SIGN_UP_USERNAME_CRASHED)){
Toast.makeText(getApplicationContext(),R.string.signup_username_crashed, Toast.LENGTH_LONG).show();
;
}
else //if (result.equals(SERVER_RES_SIGN_UP_FAILED))
{
Toast.makeText(getApplicationContext(),R.string.signup_failed, Toast.LENGTH_LONG).show();
//showDialog(SIGN_UP_FAILED);
}
}
});
}
};
thread.start();
}
else{
Toast.makeText(getApplicationContext(),R.string.username_and_password_length_short, Toast.LENGTH_LONG).show();
//showDialog(USERNAME_AND_PASSWORD_LENGTH_SHORT);
}
}
else {
Toast.makeText(getApplicationContext(),R.string.signup_type_same_password_in_password_fields, Toast.LENGTH_LONG).show();
//showDialog(TYPE_SAME_PASSWORD_IN_PASSWORD_FIELDS);
}
}
else {
Toast.makeText(getApplicationContext(),R.string.signup_fill_all_fields, Toast.LENGTH_LONG).show();
//showDialog(FILL_ALL_FIELDS);
}
}
});
cancelButton.setOnClickListener(new OnClickListener(){
public void onClick(View arg0)
{
finish();
}
});
}
protected Dialog onCreateDialog(int id)
{
switch (id)
{
case TYPE_SAME_PASSWORD_IN_PASSWORD_FIELDS:
return new AlertDialog.Builder(SigningUp.this)
.setMessage(R.string.signup_type_same_password_in_password_fields)
.setPositiveButton(R.string.OK, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
/* User clicked OK so do some stuff */
}
})
.create();
case FILL_ALL_FIELDS:
return new AlertDialog.Builder(SigningUp.this)
.setMessage(R.string.signup_fill_all_fields)
.setPositiveButton(R.string.OK, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
/* User clicked OK so do some stuff */
}
})
.create();
case SIGN_UP_FAILED:
return new AlertDialog.Builder(SigningUp.this)
.setMessage(R.string.signup_failed)
.setPositiveButton(R.string.OK, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
/* User clicked OK so do some stuff */
}
})
.create();
case SIGN_UP_USERNAME_CRASHED:
return new AlertDialog.Builder(SigningUp.this)
.setMessage(R.string.signup_username_crashed)
.setPositiveButton(R.string.OK, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
/* User clicked OK so do some stuff */
}
})
.create();
case SIGN_UP_SUCCESSFULL:
return new AlertDialog.Builder(SigningUp.this)
.setMessage(R.string.signup_successfull)
.setPositiveButton(R.string.OK, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
finish();
}
})
.create();
case USERNAME_AND_PASSWORD_LENGTH_SHORT:
return new AlertDialog.Builder(SigningUp.this)
.setMessage(R.string.username_and_password_length_short)
.setPositiveButton(R.string.OK, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
/* User clicked OK so do some stuff */
}
})
.create();
default:
return null;
}
}
#Override
protected void onResume() {
bindService(new Intent(SigningUp.this, MessagingService.class), mConnection , Context.BIND_AUTO_CREATE);
super.onResume();
}
#Override
protected void onPause()
{
unbindService(mConnection);
super.onPause();
}
}
Please helpp im stuck in this error for very long..
You have to check your EditText is not null. Something like this:
if(usernameText != null && passwordText != null && eMailText != null) {
if(!TextUtils.isEmpty(usernameText.getText()) && !TextUtils.isEmpty(passwordText.getText()) &&
!TextUtils.isEmpty(eMailText.getText()) {
result = imService.signUpUser(usernameText.getText().toString(),
passwordText.getText().toString(),
eMailText.getText().toString());
} else {
// ask user to fill all required fields
}
}

How to update multiple users from an administrator user in parse.com for android app

I am building an app there are a few users that are administrators. from these users I want them to be able to update others users info. below is what i came up with so far , but I am having trouble passing the users info. can some one help?
where I am having most trouble is selecting the user to be updated. the previous activity was a listview that pases the object string. I get them to correctly show on the necessary edittext but when I click the save button it does not update the user field.
Remember I do not want to update currentUser, I want to update a different user
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.parse.FindCallback;
import com.parse.GetCallback;
import com.parse.ParseException;
import com.parse.ParseObject;
import com.parse.ParseQuery;
import com.parse.ParseUser;
import java.util.List;
public class FullUserInfoActivity extends Activity {
String objectId;
protected EditText mName_FullUm;
protected EditText mLname_FullUm;
protected EditText mEmail_FullUm;
protected TextView mHashid_FullUm;
protected Button mPassword_FullUm;
protected Button mUpdateUserFum;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_full_user_info);
//initialize
mName_FullUm = (EditText) findViewById(R.id.nameFum);
mLname_FullUm = (EditText) findViewById(R.id.lnamefullUm);
mEmail_FullUm = (EditText) findViewById(R.id.emailFum);
mHashid_FullUm = (TextView) findViewById(R.id.hashIdFum);
mPassword_FullUm = (Button) findViewById(R.id.forgotPasswordBtn);
mUpdateUserFum = (Button) findViewById(R.id.updateUserFumButton);
//get the Intent
Intent intent = getIntent();
objectId = intent.getStringExtra("objectId");
final ParseQuery query = ParseUser.getQuery();
query.getInBackground(objectId, new GetCallback<ParseObject>() {
#Override
public void done(ParseObject parseObject, ParseException e) {
if (e == null) {
//Success we have Report
String hashid = parseObject.getString("username").toString();
String name = parseObject.getString("name").toString();
String lname = parseObject.getString("lastname").toString();
String email = parseObject.getString("email").toString();
mHashid_FullUm.setText(hashid);
mName_FullUm.setText(name);
mLname_FullUm.setText(lname);
mEmail_FullUm.setText(email);
} else {
//Something Happened
//sorry there was a problem
AlertDialog.Builder builder = new AlertDialog.Builder(FullUserInfoActivity.this);
builder.setMessage(e.getMessage());
builder.setTitle(R.string.error_login_title);
builder.setPositiveButton(R.string.error_confirmation, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
//close the dialog
dialog.dismiss();
}
});
AlertDialog dialog = builder.create();
dialog.show();
}
}
});
addListenerOnButton();
}
#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_full_user_info, 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 addListenerOnButton() {
mUpdateUserFum.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ParseQuery<ParseUser> query = ParseUser.getQuery();
query.whereEqualTo("objectId",objectId);
query.findInBackground(new FindCallback<ParseUser>() {
public void done(List<ParseUser> userUpdate, ParseException e) {
if (e == null) {
// Now let's update it with some new data.
// will get sent to the Parse Cloud. playerName hasn't changed.
userUpdate.set("lastname", mLname_FullUm);
userUpdate.set("name", mName_FullUm);
userUpdate.set("email", mEmail_FullUm);
Toast.makeText(FullUserInfoActivity.this, R.string.report_save_confirmation, Toast.LENGTH_LONG).show();
userUpdate.saveInBackground();
} else {
//sorry there was a problem
AlertDialog.Builder builder = new AlertDialog.Builder(FullUserInfoActivity.this);
builder.setMessage(e.getMessage());
builder.setTitle(R.string.error_login_title);
builder.setPositiveButton(R.string.error_confirmation, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
//close the dialog
dialog.dismiss();
}
});
AlertDialog dialog = builder.create();
dialog.show();
}
}
});
}
});
}
}
UPDATE: I reformulated the code but I need help in the area.
public void addListenerOnButton() {
mUpdateUserFum.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ParseQuery<ParseUser> query = ParseUser.getQuery();
//ParseQuery<ParseObject> query = ParseQuery.getQuery("_User");
query.whereEqualTo("objectId", objectId);
// Retrieve the object by id
query.findInBackground(new FindCallback<ParseUser>() {
public void done(List<ParseUser> objects, ParseException e) {
if (e == null) {
// Now let's update it with some new data. In this case, only cheatMode and score
// will get sent to the Parse Cloud. playerName hasn't changed.
Toast.makeText(FullUserInfoActivity.this, objectId, Toast.LENGTH_LONG).show();
} else {
//sorry there was a problem
AlertDialog.Builder builder = new AlertDialog.Builder(FullUserInfoActivity.this);
builder.setMessage(e.getMessage());
builder.setTitle(R.string.error_login_title);
builder.setPositiveButton(R.string.error_confirmation, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
//close the dialog
dialog.dismiss();
}
});
AlertDialog dialog = builder.create();
dialog.show();
}
}
});
}
});
}
#ariefbayu: how do I apply this concept to my parseUser object. I know how to assign to a normal object, but for what I understand Users are Special objects. I know parse.com recommends
ParseQuery<ParseUser> query = ParseUser.getQuery();
query.whereEqualTo("gender", "female");
query.findInBackground(new FindCallback<ParseUser>() {
public void done(List<ParseUser> objects, ParseException e) {
if (e == null) {
// The query was successful.
} else {
// Something went wrong.
}
}
});
but I dont understand how to choose the a different user and assign the new values.
There a better way when dealing with one row result (or expected to only have one row data), that is by using ParseQuery.getFirstInBackground. Here is an example of how I did it:
ParseQuery<ChatMessage> query = ParseQuery.getQuery(ChatMessage.class);
query.whereEqualTo("messageId", msgId);
query.getFirstInBackground(new GetCallback<ChatMessage>() {
#Override
public void done(ChatMessage chatMessage, ParseException e) {
if(e == null){
chatMessage.setHasBeenDelivered(true);
chatMessage.saveInBackground();
} else{
Log.e("AppLog", e.getMessage());
}
}
});

ActivityThread.performLaunchActivity(ActivityThread$ActivityClientRecord, Intent) - where is the error?

I have a little problem with my project.
every time I use
btnLinkToCreateSession.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Intent i = new Intent(getApplicationContext(),
CreateSessionActivity.class);
startActivity(i);
finish();
}
});
the error appears:
"ActivityThread.performLaunchActivity(ActivityThread$ActivityClientRecord, Intent)"
when i take it out, then everything works, again. is there any fault in the code, or must be the error somewhere else?
btnLinkToCreateSession.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Intent i = new Intent(getApplicationContext(),
CreateSessionActivity.class);
startActivity(i);
finish();
}
});
// Link to Register Screen
btnLinkToRegister.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Intent j = new Intent(getApplicationContext(),
RegisterActivity.class);
startActivity(j);
finish();
}
});
Edit: + CreateSessionActivity.java
package com.game;
import org.json.JSONException;
import org.json.JSONObject;
import com.game.library.DatabaseHandler;
import com.game.library.UserFunctions;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class CreateSessionActivity extends Activity {
Button btnCreateSession;
Button btnLinkToLogin;
EditText inputNameOfSession;
EditText inputUserMax;
EditText inputBetAmount;
TextView createSessionErrorMsg;
// JSON Response node names
private static String KEY_SUCCESS = "success";
private static String KEY_ERROR = "error";
private static String KEY_ERROR_MSG = "error_msg";
private static String KEY_SID = "sid";
private static String KEY_SNAME = "sname";
private static String KEY_SMAX = "smax";
private static String KEY_SBET = "sbet";
private static String KEY_CREATED_AT = "created_at";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.session);
// Importing all assets like buttons, text fields
inputNameOfSession = (EditText) findViewById(R.id.sessionName);
inputUserMax = (EditText) findViewById(R.id.sessionMax);
inputBetAmount = (EditText) findViewById(R.id.sessionBet);
btnCreateSession = (Button) findViewById(R.id.btnCreateSession);
btnLinkToLogin = (Button) findViewById(R.id.btnLinkToLoginScreen);
createSessionErrorMsg = (TextView) findViewById(R.id.session_error);
// Register Button Click event
btnCreateSession.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
String sname = inputNameOfSession.getText().toString();
String smax = inputUserMax.getText().toString();
String sbet = inputBetAmount.getText().toString();
UserFunctions userFunction = new UserFunctions();
JSONObject json = userFunction.openSession(sname, smax, sbet);
// check for login response
try {
if (json.getString(KEY_SUCCESS) != null) {
createSessionErrorMsg.setText("");
String res = json.getString(KEY_SUCCESS);
if(Integer.parseInt(res) == 1){
// user successfully registred
// Store user details in SQLite Database
DatabaseHandler db = new DatabaseHandler(getApplicationContext());
JSONObject json_session_u = json.getJSONObject("session");
// Clear all previous data in database
userFunction.logoutSession(getApplicationContext());
db.addSession(json_session_u.getString(KEY_SNAME), json_session_u.getString(KEY_SMAX), json.getString(KEY_SBET), json_session_u.getString(KEY_CREATED_AT));
// Launch Dashboard Screen
Intent dashboard = new Intent(getApplicationContext(), DashboardActivity.class);
// Close all views before launching Dashboard
dashboard.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(dashboard);
// Close Registration Screen
finish();
}else{
// Error in registration
createSessionErrorMsg.setText("Error occured in registration");
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
});
// Link to Login Screen
btnLinkToLogin.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Intent i = new Intent(getApplicationContext(),
LoginActivity.class);
startActivity(i);
// Close Registration View
finish();
}
});
}
}
I had some trouble with inserting my logcat into here thatswhy:
http://androidprojekt.esy.es/android_login_api/loggo.txt
#
i think i solved it - it works
inputEmail = (EditText) findViewById(R.id.loginEmail);
inputPassword = (EditText) findViewById(R.id.loginPassword);
btnLogin = (Button) findViewById(R.id.btnLogin);
btnLinkToRegister = (Button) findViewById(R.id.btnLinkToRegisterScreen);
/* I had forgotten to add this: */
btnLinkToCreateSession = (Button) findViewById(R.id.btnLinkToCreateSession);
loginErrorMsg = (TextView) findViewById(R.id.login_error);
You should use the Activity's context instead of getApplicationContext() to start activities. Change all the intents which you use to start Activity like this:
Intent dashboard = new Intent(YourActivity.this, DashboardActivity.class);
You should also read this post for deeper insight.

Categories

Resources