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
}
}
Related
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");
This question already has answers here:
Why does ArrayIndexOutOfBoundsException occur and how to avoid it in Android? [closed]
(4 answers)
Closed 6 years ago.
I'm developing a music application but i keep geting this error, i don't understand it and dont know how to solve. I'm stuck for 2 day trying to re-write the code but still the error pops-up.My logcat comes up as java.lang.IndexOutOfBoundsException: Invalid index 0, size is 0. And please elaborate the main problem.
This MainActivity.java
package com.developer.bunamay.player;
import android.app.SearchManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.PorterDuff;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.SearchView;
import android.widget.SeekBar;
import android.widget.TextView;
import java.util.List;
public class MainActivity extends AppCompatActivity implements MusicService.MediaFileListener {
public static final PlayerUtils PlayerController = PlayerUtils.getInstance();
public static final int PICK_FOLDER_REQUEST = 8;
private MediaFileAdapter mediaFileAdapter = null;
private TextView playingSong;
private Button btnPause, btnPlay, btnNext, btnPrevious;
private Button btnStop;
private LinearLayout linearLayoutPlayingSong;
private ListView mediaListView;
private SeekBar seekbar;
private TextView textBufferDuration, textDuration;
private ImageView imageViewAlbumArt;
private Context context;
MusicService mService;
boolean mBound = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
context = MainActivity.this;
init();
if (!PlayerUtils.isServiceRunning(MusicService.class.getName(), getApplicationContext())) {
Intent i = new Intent(getApplicationContext(), MusicService.class);
startService(i);
}
}
private void init() {
initViews();
setListeners();
playingSong.setSelected(true);
seekbar.getProgressDrawable().setColorFilter(ContextCompat.getColor(context, R.color.colorText), PorterDuff.Mode.SRC_IN);
if (PlayerController.SONGS_LIST.size() <= 0) {
PlayerController.SONGS_LIST = PlayerController.listOfSongs(getApplicationContext());
}
initAdapter();
}
private void initAdapter() {
mediaFileAdapter = new MediaFileAdapter(this, R.layout.custom_list, PlayerController.SONGS_LIST);
mediaListView.setAdapter(mediaFileAdapter);
mediaListView.setTextFilterEnabled(true);
mediaListView.setFastScrollEnabled(true);
}
private void initViews() {
playingSong = (TextView) findViewById(R.id.textNowPlaying);
mediaListView = (ListView) findViewById(R.id.listViewMusic);
btnPause = (Button) findViewById(R.id.btnPause);
btnPlay = (Button) findViewById(R.id.btnPlay);
linearLayoutPlayingSong = (LinearLayout) findViewById(R.id.linearLayoutPlayingSong);
seekbar = (SeekBar) findViewById(R.id.seekBar);
btnStop = (Button) findViewById(R.id.btnStop);
textBufferDuration = (TextView) findViewById(R.id.textBufferDuration);
textDuration = (TextView) findViewById(R.id.textDuration);
imageViewAlbumArt = (ImageView) findViewById(R.id.imageViewAlbumArt);
btnNext = (Button) findViewById(R.id.btnNext);
btnPrevious = (Button) findViewById(R.id.btnPrevious);
}
private Animation setButtonAnimation() {
return AnimationUtils.loadAnimation(this, R.anim.button_anim);
}
// defines callbacks for service binding, passed to bindService()
private ServiceConnection mConnection = new ServiceConnection() {
#Override
public void onServiceConnected(ComponentName className,
IBinder service) {
MusicService.LocalBinder binder = (MusicService.LocalBinder) service;
mService = binder.getService();
mService.setListener(MainActivity.this);
mBound = true;
}
#Override
public void onServiceDisconnected(ComponentName arg0) {
mBound = false;
mService = null;
}
};
private void setListeners() {
mediaListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View item, int position, long id) {
PlayerController.SONG_PAUSED = false;
PlayerController.SONG_NUMBER = position;
boolean isServiceRunning = PlayerUtils.isServiceRunning(MusicService.class.getName(), getApplicationContext());
if (!isServiceRunning) {
Intent i = new Intent(getApplicationContext(), MusicService.class);
startService(i);
} else {
PlayerController.SONG_CHANGE_HANDLER.sendMessage(
PlayerController.SONG_CHANGE_HANDLER.obtainMessage());
}
updateUI();
changeButton();
}
});
btnPlay.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
PlayerController.playControl(getApplicationContext());
}
});
btnPause.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
PlayerController.pauseControl(getApplicationContext());
}
});
btnNext.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
v.startAnimation(setButtonAnimation());
PlayerController.nextControl(getApplicationContext());
}
});
btnPrevious.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
v.startAnimation(setButtonAnimation());
PlayerController.previousControl(getApplicationContext());
}
});
btnStop.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (PlayerUtils.isServiceRunning(MusicService.class.getName(), getApplicationContext())) {
PlayerController.pauseControl(getApplicationContext());
}
linearLayoutPlayingSong.setVisibility(View.GONE);
}
});
seekbar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
if (fromUser) {
// clicked position on the seekBar
int currentSeekBarPosition = seekBar.getProgress();
// 1% of song duration = song duration / 100%
int onePercentOfSongDuration = (mService.getDuration() / 100);
// associate song duration with clicked position on the seekBar
int changedPosition = currentSeekBarPosition * onePercentOfSongDuration;
// seek to selected position
PlayerController.seekToAnyControl(getApplicationContext(), changedPosition);
}
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
});
}
#Override
protected void onPause() {
if (mBound) {
unbindService(mConnection);
}
super.onPause();
}
#Override
protected void onResume() {
super.onResume();
Intent i = new Intent(getApplicationContext(), MusicService.class);
bindService(i, mConnection, Context.BIND_AUTO_CREATE);
handleAudioFromOpenWithPopup();
boolean isServiceRunning = PlayerUtils.isServiceRunning(MusicService.class.getName(), getApplicationContext());
if (isServiceRunning) {
updateUI();
} else {
linearLayoutPlayingSong.setVisibility(View.GONE);
}
changeButton();
PlayerController.SEEKBAR_HANDLER = new Handler() {
#Override
public void handleMessage(Message msg) {
Integer i[] = (Integer[]) msg.obj;
textBufferDuration.setText(PlayerUtils.getDuration(i[0]));
textDuration.setText(PlayerUtils.getDuration(i[1]));
seekbar.setProgress(i[2]);
}
};
}
public void updateUI() {
MediaFile mediaFile = PlayerController.SONGS_LIST.get(PlayerController.SONG_NUMBER);
String nowPlayingTitleText = mediaFile.getTitle() + " " + mediaFile.getArtist() + "-" + mediaFile.getAlbum();
playingSong.setText(nowPlayingTitleText);
Bitmap albumArt = PlayerController.getAlbumart(context, mediaFile.getAlbumId());
if (albumArt != null) {
imageViewAlbumArt.setBackgroundDrawable(new BitmapDrawable(Resources.getSystem(), albumArt));
} else {
Bitmap defaultAlbumArt = PlayerController.getDefaultAlbumArt(context);
imageViewAlbumArt.setBackgroundDrawable(new BitmapDrawable(Resources.getSystem(), defaultAlbumArt));
}
linearLayoutPlayingSong.setVisibility(View.VISIBLE);
}
public void changeButton() {
if (PlayerController.SONG_PAUSED) {
btnPause.setVisibility(View.GONE);
btnPlay.setVisibility(View.VISIBLE);
} else {
btnPause.setVisibility(View.VISIBLE);
btnPlay.setVisibility(View.GONE);
}
}
public void changeUI() {
updateUI();
changeButton();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
// init menu items for search
MenuItem itemSearchTitle = menu.findItem(R.id.action_search_title);
MenuItem itemSearchAlbum = menu.findItem(R.id.action_search_album);
MenuItem itemSearchArtist = menu.findItem(R.id.action_search_artist);
SearchView searchViewTitle = (SearchView) itemSearchTitle.getActionView();
SearchView searchViewAlbum = (SearchView) itemSearchAlbum.getActionView();
SearchView searchViewArtist = (SearchView) itemSearchArtist.getActionView();
searchViewTitle.setFocusable(true);
searchViewAlbum.setFocusable(true);
searchViewArtist.setFocusable(true);
// init searchable info for each menu item
searchViewTitle.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));
searchViewTitle.setQueryHint("title...");
searchViewTitle.setIconified(true);
searchViewAlbum.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));
searchViewAlbum.setQueryHint("album...");
searchViewAlbum.setIconified(true);
searchViewArtist.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));
searchViewArtist.setQueryHint("artist...");
searchViewArtist.setIconified(true);
// set textChangeListeners for each type of search
final SearchView.OnQueryTextListener textChangeListenerTitle = new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextChange(String newText) {
if (!TextUtils.isEmpty(newText)) {
mediaFileAdapter.getFilter().filter(newText);
}
return true;
}
#Override
public boolean onQueryTextSubmit(String query) {
return true;
}
};
SearchView.OnQueryTextListener textChangeListenerAlbum = new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextChange(String newText) {
if (!TextUtils.isEmpty(newText)) {
mediaFileAdapter.getFilter().filter(newText);
}
return true;
}
#Override
public boolean onQueryTextSubmit(String query) {
return true;
}
};
SearchView.OnQueryTextListener textChangeListenerArtist = new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextChange(String newText) {
if (!TextUtils.isEmpty(newText)) {
mediaFileAdapter.getFilter().filter(newText);
}
return true;
}
#Override
public boolean onQueryTextSubmit(String query) {
return true;
}
};
// apply listeners to searchViews
searchViewTitle.setOnQueryTextListener(textChangeListenerTitle);
searchViewAlbum.setOnQueryTextListener(textChangeListenerAlbum);
searchViewArtist.setOnQueryTextListener(textChangeListenerArtist);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
// get music from specific folder
if (id == R.id.folder_music) {
Intent intent = new Intent(this, FolderPickerActivity.class);
startActivityForResult(intent, PICK_FOLDER_REQUEST);
return true;
}
// fetch all music from device
if (id == R.id.all_music) {
PlayerController.SONGS_LIST = PlayerController.listOfSongs(getApplicationContext());
initAdapter();
return true;
}
// search songs by title
if (id == R.id.action_search_title) {
PlayerController.SEARCH_TYPE = "TITLE";
return true;
}
// search songs by artist
if (id == R.id.action_search_artist) {
PlayerController.SEARCH_TYPE = "ARTIST";
return true;
}
// search songs by album
if (id == R.id.action_search_album) {
PlayerController.SEARCH_TYPE = "ALBUM";
return true;
}
if (id == R.id.action_sort_title) {
MediaFileComparator.sortByTitle(PlayerController.SONGS_LIST);
MediaFileAdapter mediaAdapter = (MediaFileAdapter) mediaListView.getAdapter();
mediaAdapter.notifyDataSetChanged();
return true;
}
if (id == R.id.action_sort_album) {
MediaFileComparator.sortByAlbum(PlayerController.SONGS_LIST);
MediaFileAdapter mediaAdapter = (MediaFileAdapter) mediaListView.getAdapter();
mediaAdapter.notifyDataSetChanged();
return true;
}
if (id == R.id.action_sort_artist) {
MediaFileComparator.sortByArtist(PlayerController.SONGS_LIST);
MediaFileAdapter mediaAdapter = (MediaFileAdapter) mediaListView.getAdapter();
mediaAdapter.notifyDataSetChanged();
return true;
}
if (id == R.id.action_sort_duration) {
MediaFileComparator.sortByDuration(PlayerController.SONGS_LIST);
MediaFileAdapter mediaAdapter = (MediaFileAdapter) mediaListView.getAdapter();
mediaAdapter.notifyDataSetChanged();
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
if (requestCode == PICK_FOLDER_REQUEST) {
String pickedFolder = data.getStringExtra("pickedFolder");
Log.i("PICKER_FOLDER_TAG", pickedFolder);
// get last subfolder from path as WHERE arg
pickedFolder = getSelectionArg(pickedFolder);
Log.i("PICKER_FOLDER_WHERE_TAG", pickedFolder);
// reinit music list and adapter with data from specific folder
List<MediaFile> songsFromSpecificFolder = PlayerController.getSongsFromSpecificFolder(
getApplicationContext(), new String[]{pickedFolder}
);
if (songsFromSpecificFolder.size() != 0) {
PlayerController.SONGS_LIST = songsFromSpecificFolder;
PlayerController.SONG_NUMBER = 0;
initAdapter();
}
}
}
}
// receive audio action from 'Complete action with' pop-up
private void handleAudioFromOpenWithPopup() {
// receive Intent
Intent intent = getIntent();
// check action
String action = intent.getAction();
// if it's audio action view
if (action != null && action.equals("android.intent.action.VIEW")) {
// play song
PlayerController.playMusicFromActionPicker(this, intent.getData());
}
}
// get last subfolder from path as WHERE arg
private String getSelectionArg(String path) {
String sTag = "%";
// substring last directory in path
String lastSubfolder = path.substring(path.lastIndexOf("/") + 1);
return sTag + lastSubfolder + sTag;
}
#Override
public void onMediaFileChanged() {
changeUI();
}
#Override
public void onPlayPauseActionChanged() {
changeButton();
}
}
I've tried searching online varios times but i still dont understand.
Thanks
The root cause of the problem is that somewhere, either your code or some code that your code uses is doing something that is equivalent to this:
Object[] array = new Object[0];
...
System.out.println(array[0]);
Something created an array (of some type) with size ZERO, and it (or maybe something else) is trying to access the first element (index zero) of that array. That is beyond the end of the array ... and that results in an exception.
I can't see where you are creating a zero-length array in your code.
Could you have a look at the method protected void onResume()?
I think, you may have a problem in following lines:
Integer i[] = (Integer[]) msg.obj;
textBufferDuration.setText(PlayerUtils.getDuration(i[0]));
textDuration.setText(PlayerUtils.getDuration(i[1]));
seekbar.setProgress(i[2]);
First try running the program by commenting out those lines. It may happen that, on some occasions, your msg.obj is actually an array whose length is 0. Then you will get java.lang.IndexOutOfBoundsException: Invalid index 0, size is 0. Hope it helps you.
I have successfully integrated twitter in my app but now I want to open next activity upon successful login.
How do I implement a call back method? i use on Activity result for twitter but it does not gives any error but also its does not works kindly tell me the right way to solve it thanks in advance....
package com.example.android.accenturefeed;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.net.ConnectivityManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.StrictMode;
import android.support.v7.app.AppCompatActivity;
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 com.facebook.CallbackManager;
import com.facebook.FacebookCallback;
import com.facebook.FacebookException;
import com.facebook.FacebookSdk;
import com.facebook.login.LoginManager;
import com.facebook.login.LoginResult;
import com.facebook.login.widget.LoginButton;
import com.google.android.gms.auth.api.Auth;
import com.google.android.gms.auth.api.signin.GoogleSignInOptions;
import com.google.android.gms.auth.api.signin.GoogleSignInResult;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.SignInButton;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.code.linkedinapi.client.LinkedInApiClient;
import com.google.code.linkedinapi.client.LinkedInApiClientFactory;
import com.google.code.linkedinapi.client.oauth.LinkedInOAuthService;
import com.google.code.linkedinapi.client.oauth.LinkedInRequestToken;
import com.linkedin.platform.LISessionManager;
import com.linkedin.platform.errors.LIAuthError;
import com.linkedin.platform.listeners.AuthListener;
import com.linkedin.platform.utils.Scope;
import twitter4j.Twitter;
import twitter4j.TwitterException;
import twitter4j.TwitterFactory;
import twitter4j.auth.AccessToken;
import twitter4j.auth.RequestToken;
import twitter4j.conf.Configuration;
import twitter4j.conf.ConfigurationBuilder;
#SuppressWarnings("ALL")
public class LoginActivity extends AppCompatActivity implements View.OnClickListener, GoogleApiClient.OnConnectionFailedListener {
public ProgressDialog pdialog;
public AlertDialog alertDialog;
private TextView info;
private LoginButton loginButton;
private CallbackManager callbackManager;
private GoogleApiClient mGoogleApiClient;
private static final int RC_SIGN_IN = 1901;
private LinkedInOAuthService oAuthService;
private LinkedInApiClientFactory factory;
private LinkedInRequestToken liToken;
private LinkedInApiClient client;
static String TWITTER_CONSUMER_KEY = "my_consumer_key";
static String TWITTER_CONSUMER_SECRET = "my_consumer_secret";
// Preference Constants
static String PREFERENCE_NAME = "twitter_oauth";
static final String PREF_KEY_OAUTH_TOKEN = "oauth_token";
static final String PREF_KEY_OAUTH_SECRET = "oauth_token_secret";
static final String PREF_KEY_TWITTER_LOGIN = "isTwitterLogedIn";
static final String TWITTER_CALLBACK_URL = "oauth://t4jsample";
// Twitter oauth urls
static final String URL_TWITTER_AUTH = "auth_url";
static final String URL_TWITTER_OAUTH_VERIFIER = "oauth_verifier";
static final String URL_TWITTER_OAUTH_TOKEN = "oauth_token";
// Login button
Button TwitterLoginButton;
// Twitter
private static Twitter twitter;
private static RequestToken requestToken;
// Shared Preferences
private static SharedPreferences mSharedPreferences;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// for facebook signin
FacebookSdk.sdkInitialize(getApplicationContext());
callbackManager = CallbackManager.Factory.create();
setContentView(R.layout.login_activity);
final LoginActivity thisActivity = this;
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
// for twitter login
mSharedPreferences = getApplicationContext().getSharedPreferences(
"MyPref", 0);
TwitterLoginButton = (Button) findViewById(R.id.btnLoginTwitter);
TwitterLoginButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ConfigurationBuilder builder = new ConfigurationBuilder();
builder.setOAuthConsumerKey(TWITTER_CONSUMER_KEY);
builder.setOAuthConsumerSecret(TWITTER_CONSUMER_SECRET);
Configuration configuration = builder.build();
TwitterFactory factory = new TwitterFactory(configuration);
twitter = factory.getInstance();
try {
requestToken = twitter.getOAuthRequestToken(TWITTER_CALLBACK_URL);
LoginActivity.this.startActivity(new Intent(Intent.ACTION_VIEW, Uri
.parse(requestToken.getAuthenticationURL())));
} catch (TwitterException e) {
e.printStackTrace();
}
}
});
// for google signin
GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestEmail()
.build();
mGoogleApiClient = new GoogleApiClient.Builder(this)
.enableAutoManage(this /* FragmentActivity */, this /* OnConnectionFailedListener */)
.addApi(Auth.GOOGLE_SIGN_IN_API, gso)
.build();
// for logging out from facebook
LoginManager.getInstance().logOut();
// checks internet
if (isNetworkAvailable()==true){
//linkedin button
Button libutton=(Button)findViewById(R.id.btnLinkedin);
libutton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//linkedin signin
LISessionManager.getInstance(getApplicationContext()).init(thisActivity, buildScope(), new AuthListener() {
#Override
public void onAuthSuccess() {
Intent intent = new Intent(LoginActivity.this, CategoriesActivity.class);
startActivity(intent);
}
#Override
public void onAuthError(LIAuthError error) {
info.setText("Login attempt failed.");
}
}, true);
}
});
// google login button
SignInButton signInButton = (SignInButton) findViewById(R.id.sign_in_button);
signInButton.setOnClickListener(this);
// shows error
info = (TextView)findViewById(R.id.info);
// facebook login button
loginButton = (LoginButton)findViewById(R.id.login_button);
loginButton.registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
Intent intent = new Intent(LoginActivity.this, CategoriesActivity.class);
startActivity(intent);
// info.setText(
// "User ID: "
// + loginResult.getAccessToken().getUserId()
// + "\n" +
// "Auth Token: "
// + loginResult.getAccessToken().getToken()
// );
}
#Override
public void onCancel() {
info.setText("Login attempt canceled.");
}
#Override
public void onError(FacebookException error) {
info.setText("Login attempt failed.");
}
});
Button b1=(Button)findViewById(R.id.loginbutton);
final EditText user =(EditText)findViewById(R.id.editTextentername);
final EditText pass =(EditText)findViewById(R.id.edittextenterpassword);
b1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String givenUsername = user.getText().toString();
String givenPassword = pass.getText().toString();
if (givenUsername.isEmpty() || givenPassword.isEmpty()) {
TextView textView = (TextView) findViewById(R.id.error);
textView.setText("Username & password required!");
} else {
pdialog = ProgressDialog.show(LoginActivity.this, "Authenticating", "Please wait...");
sendLoginRequest(givenUsername, givenPassword);
}
}
private void sendLoginRequest(final String givenUsername, final String givenPassword) {
SendLoginRequestAsyncTask asyncTask = (SendLoginRequestAsyncTask) new SendLoginRequestAsyncTask(new SendLoginRequestAsyncTask.AsyncResponse() {
#Override
public void processFinish(String name) {
if (name.isEmpty()) {
TextView textView = (TextView) findViewById(R.id.error);
textView.setTextColor(Color.parseColor("#d41a14"));
textView.setText("Username or Password Is Incorrect!");
pdialog.dismiss();
} else {
Intent intent = new Intent(LoginActivity.this, CategoriesActivity.class);
intent.putExtra("username", name);
pdialog.dismiss();
startActivity(intent);
}
}
}).execute(givenUsername, givenPassword);
}
}
);
}
else {
AlertDialog alertDialog = new AlertDialog.Builder(LoginActivity.this).create();
alertDialog.setTitle("Alert");
alertDialog.setMessage("Check Your Internet Connection");
alertDialog.setButton(AlertDialog.BUTTON_NEUTRAL, "OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
alertDialog.show();
}
}
private Scope buildScope() {
return Scope.build(Scope.R_BASICPROFILE, Scope.W_SHARE);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// for twitter result
if (resultCode == Activity.RESULT_OK) {
final Uri uri = Uri.parse(data.getStringExtra("KEY_URI"));
new Thread(new Runnable() {
#Override
public void run() {
String verifier = uri.getQueryParameter(LoginActivity.URL_TWITTER_OAUTH_VERIFIER);
try {
AccessToken accessToken = twitter.getOAuthAccessToken(requestToken, verifier);
LoginActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
Intent intent = new Intent(LoginActivity.this, CategoriesActivity.class);
startActivity(intent);
}
});
} catch (Exception e) {
e.printStackTrace();
}
}
}).start();
}
// for google
if (requestCode == RC_SIGN_IN) {
GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent(data);
handleSignInResult(result);
}
// for facebook
else {
callbackManager.onActivityResult(requestCode, resultCode, data);
}
//forlinkedin
LISessionManager.getInstance(getApplicationContext()).onActivityResult(this, requestCode, resultCode, data);
}
// for google to open next activity or not
private void handleSignInResult(GoogleSignInResult result) {
if (result.isSuccess()) {
// Signed in successfully, show authenticated UI.
Intent intent = new Intent(LoginActivity.this, CategoriesActivity.class);
startActivityForResult(intent, 1);
} else {
// Signed out, show unauthenticated UI.
info.setText("Login attempt failed.");
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_logout) {
// Auth.GoogleSignInApi.revokeAccess(mGoogleApiClient).setResultCallback(new ResultCallback<Status>() {
// #Override
// public void onResult(Status status) {
// mGoogleApiClient.disconnect();
// }
// });
return true;
}
return super.onOptionsItemSelected(item);
}
// checks Internet is available or not
private boolean isNetworkAvailable() {
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
return cm.getActiveNetworkInfo() != null;
}
// for google sign in button on click method
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.sign_in_button:
signIn();
break;
// ...
}
}
// google sign in method
private void signIn() {
Intent signInIntent = Auth.GoogleSignInApi.getSignInIntent(mGoogleApiClient);
startActivityForResult(signInIntent, RC_SIGN_IN);
}
// google connection failed method
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
info.setText("Login attempt failed.");
}
}
remove all the intents from your code except the one from this:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == Activity.RESULT_OK) {
final Uri uri = Uri.parse(data.getStringExtra("KEY_URI"));
new Thread(new Runnable() {
#Override
public void run() {
String verifier = uri.getQueryParameter(LoginActivity.URL_TWITTER_OAUTH_VERIFIER);
try {
AccessToken accessToken = twitter.getOAuthAccessToken(requestToken, verifier);
LoginActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
Intent intent = new Intent(LoginActivity.this, CategoriesActivity.class);
startActivity(intent);
}
});
} catch (Exception e) {
e.printStackTrace();
}
}
}).start();
Just keep the intent portion in order to go to the next activity in OnActivityResult itself, remove any other intent calls from your entire code and try running the app again.
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);
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());
}
}
});