not able to play next song on clicking a button - java

I am new to android development.I created an audio player app for playing songs from SD card,its working fine and song is being played but when I click next button, song doesn't change and same track keeps playing.Button is clickable but song doesn't change on clicking it.How do I fix it ? any kind of help is appreciated,thanks.
public class PlayListActivity extends Activity {
private String[] mAudioPath;
private MediaPlayer mMediaPlayer;
private String[] mMusicList;
int currentPosition = 0;
private List<String> songs = new ArrayList<>();
MediaMetadataRetriever metaRetriver;
byte[] art;
ImageView album_art;
TextView album;
TextView artist;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_play_list);
mMediaPlayer = new MediaPlayer();
ListView mListView = (ListView) findViewById(R.id.list);
mMusicList = getAudioList();
ArrayAdapter<String> mAdapter = new ArrayAdapter<>(this,
android.R.layout.simple_list_item_1, mMusicList);
mListView.setAdapter(mAdapter);
mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View view, int arg2,
long arg3) {
try {
playSong(mAudioPath[arg2]);
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
});
}
private String[] getAudioList() {
final Cursor mCursor = getContentResolver().query(
MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
new String[]{MediaStore.Audio.Media.DISPLAY_NAME, MediaStore.Audio.Media.DATA}, null, null,
"LOWER(" + MediaStore.Audio.Media.TITLE + ") ASC");
int count = mCursor.getCount();
String[] songs = new String[count];
mAudioPath = new String[count];
int i = 0;
if (mCursor.moveToFirst()) {
do {
songs[i] = mCursor.getString(mCursor.getColumnIndexOrThrow(MediaStore.Audio.Media.DISPLAY_NAME));
mAudioPath[i] = mCursor.getString(mCursor.getColumnIndexOrThrow(MediaStore.Audio.Media.DATA));
i++;
} while (mCursor.moveToNext());
}
mCursor.close();
return songs;
}
private void playSong(String path) throws IllegalArgumentException,
IllegalStateException, IOException {
setContentView(R.layout.activity_android_building_music_player);
Log.d("ringtone", "playSong :: " + path);
mMediaPlayer.reset();
mMediaPlayer.setDataSource(path);
//mMediaPlayer.setLooping(true);
mMediaPlayer.prepare();
mMediaPlayer.start();
acv(path);
abc();
cde();
}
public void acv(String path) {
getInit();
metaRetriver = new MediaMetadataRetriever();
metaRetriver.setDataSource(path);
try {
art = metaRetriver.getEmbeddedPicture();
Bitmap songImage = BitmapFactory.decodeByteArray(art, 0, art.length);
album_art.setImageBitmap(songImage);
album.setText(metaRetriver
.extractMetadata(MediaMetadataRetriever.METADATA_KEY_ALBUM));
artist.setText(metaRetriver
.extractMetadata(MediaMetadataRetriever.METADATA_KEY_ARTIST));
} catch (Exception e) {
album_art.setBackgroundColor(Color.GRAY);
album.setText("Unknown Album");
artist.setText("Unknown Artist");
}
}
public void getInit() {
album_art = (ImageView) findViewById(R.id.coverart1);
album = (TextView) findViewById(R.id.Album);
artist = (TextView) findViewById(R.id.artist_name);
}
public void abc() {
ImageButton btnPlay1 = (ImageButton) findViewById(R.id.btnPlay1);
btnPlay1.setBackgroundColor(Color.TRANSPARENT);
btnPlay1.setOnClickListener(
new View.OnClickListener() {
public void onClick(View v) {
if (mMediaPlayer.isPlaying()) {
mMediaPlayer.pause();
} else {
mMediaPlayer.start();
}
}
});
}
public void cde() {
ImageButton btnNext = (ImageButton) findViewById(R.id.btnNext); //this is the button for playing next song.
btnNext.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
try {
currentPosition=currentPosition+1;
playSong(path + songs.get(currentPosition));
} catch (IOException ex) {
ex.printStackTrace();
}
}
});
}
}

Try this code :
public void next() {
ImageButton btnNext = (ImageButton) findViewById(R.id.btnNext);
btnNext.setOnClickListener(
new View.OnClickListener() {
public void onClick(View view) {
temp = temp + 1;
try {
playSong(mAudioPath[temp]);
} catch (Exception er) {
er.printStackTrace();
}
}
}
);
}
Dont forget to declare next() method in playsong()

Related

How to get to the beginning of activity with MediaPlayer

Need to pick another random track after stopping the previous one by clicking "stop" button
I'm playing a random track by clicking "play" button, stop it by clicking "stop" and then i need to randomize again, in other words, to pick another track.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button play36 = (Button) findViewById(R.id.threesix);
Button stop = (Button) findViewById(R.id.stop);
String[] listOfFiles = new String[0];
try {
listOfFiles = getAssets().list("");
final List<String> musicOnlyList = new ArrayList<>();
for (int i = 0; i < listOfFiles.length; i++) {
if (getExtension(listOfFiles[i]).equals("mp3"))
musicOnlyList.add(listOfFiles[i]);
}
final MediaPlayer mediaPlayer = new MediaPlayer();
play36.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int itemIndex = new Random().nextInt(musicOnlyList.size());
String file = musicOnlyList.get(itemIndex);
AssetFileDescriptor afd = null;
try {
afd = getAssets().openFd(file);
mediaPlayer.reset();
mediaPlayer.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength());
mediaPlayer.prepare();
} catch (IOException e) {
e.printStackTrace();
}
mediaPlayer.start();
}
});
stop.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mediaPlayer.stop();
mediaPlayer.reset();
}
});
} catch (IOException e) {
e.printStackTrace();
}
In this case i get the same track everytime i start and stop player, but need to randomize everytime by clicking "play" button
You need to pick a new random number inside the listener of play36:
Button play36 = (Button)findViewById(R.id.threesix);
Button stop = (Button)findViewById(R.id.stop);
String[] listOfFiles = new String[0];
try {
listOfFiles = getAssets().list("");
final List<String> musicOnlyList = new ArrayList<>();
for(int i = 0; i < listOfFiles.length; i++){
if (getExtension(listOfFiles[i]).equals("mp3"))
musicOnlyList.add(listOfFiles[i]);
}
final MediaPlayer mediaPlayer = new MediaPlayer();
play36.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int itemIndex = new Random().nextInt(musicOnlyList.size());
String file = musicOnlyList.get(itemIndex);
AssetFileDescriptor afd = null;
try {
afd = getAssets().openFd(file);
mediaPlayer.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength());
mediaPlayer.prepare();
} catch (IOException e) {
e.printStackTrace();
}
mediaPlayer.start();
}
});
stop.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mediaPlayer.stop();
try {
mediaPlayer.prepare();
} catch (IOException e) {
e.printStackTrace();
}
}
});
} catch (IOException e) {
e.printStackTrace();
}

o.realm.exceptions.RealmFileException: Unable to open a realm at path '/data/data/com.apphoctienganhpro.firstapp/files/default.realm':

Realm class
public class RealmManager
private static Realm mRealm;
public static Realm open() {
mRealm = Realm.getDefaultInstance();
return mRealm;
}
public static void close() {
if (mRealm != null) {
mRealm.close();
}
}
public static RecordsDao recordsDao() {
checkForOpenRealm();
return new RecordsDao(mRealm);
}
private static void checkForOpenRealm() {
if (mRealm == null || mRealm.isClosed()) {
throw new IllegalStateException("RealmManager: Realm is closed, call open() method first");
}
}
}
When I call RealmManager.open(); my app crashes with error
Unable to open a realm at path
'/data/data/com.apphoctienganhpro.firstapp/files/default.realm':
Unsupported Realm file format version. in
/Users/cm/Realm/realm-java/realm/realm-library/src/main/cpp/io_realm_internal_SharedRealm.cpp
line 92 Kind: ACCESS_ERROR
Activity class
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_lesson);
ButterKnife.bind(this);
RealmManager.open();
NestedScrollView scrollView = findViewById(R.id.nest_scrollview);
scrollView.setFillViewport(true);
toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
if (getSupportActionBar() != null) {
getSupportActionBar().setDisplayShowTitleEnabled(true);
}
final CollapsingToolbarLayout collapsingToolbarLayout = findViewById(R.id.collapsing_toolbar);
AppBarLayout appBarLayout = findViewById(R.id.appbar);
appBarLayout.addOnOffsetChangedListener(new AppBarLayout.OnOffsetChangedListener() {
boolean isShow = true;
int scrollRange = -1;
#Override
public void onOffsetChanged(AppBarLayout appBarLayout, int verticalOffset) {
if (scrollRange == -1) {
scrollRange = appBarLayout.getTotalScrollRange();
}
if (scrollRange + verticalOffset == 0) {
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
isShow = true;
} else if (isShow) {
getSupportActionBar().setDisplayHomeAsUpEnabled(false);
isShow = false;
}
}
});
arrayListCategory = Utility.getAppcon().getSession().arrayListCategory;
arrayListGoal = Utility.getAppcon().getSession().arrayListGoal;
arrayList = new ArrayList<>();
arrayList = Utility.getAppcon().getSession().arrayListCategory;
if (arrayListGoal.size() > 0) {
goal_id = arrayListGoal.get(0).getSingleGoalId();
}else{
if(!arrayList.get(0).getCategory_description().equals("")) {
if(!Utility.getAppcon().getSession().screen_name.equals("lessson_complete")) {
displayDialog();
}
}
}
collapsingToolbarLayout.setTitle(arrayListCategory.get(0).getCategoryName());
layoutManager = new LinearLayoutManager(this);
recycler_view.setLayoutManager(layoutManager);
apiservice = ApiServiceCreator.createService("latest");
sessionManager = new SessionManager(this);
getCategoryLesson();
}
private void displayDialog() {
dialog = new Dialog(LessonActivity.this);
dialog.getWindow();
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setContentView(R.layout.custom_layout_lesson_detail);
dialog.setCancelable(true);
txt_close = dialog.findViewById(R.id.txt_close);
txt_title_d = dialog.findViewById(R.id.txt_title_d);
txt_description_d = dialog.findViewById(R.id.txt_description_d);
img_main_d = dialog.findViewById(R.id.img_main_d);
img_play_d = dialog.findViewById(R.id.img_play_d);
img_play_d.setVisibility(View.GONE);
Picasso.with(LessonActivity.this).load(ApiConstants.IMAGE_URL + arrayList.get(0).getCategoryImage())
.noFade()
.fit()
.placeholder(R.drawable.icon_no_image)
.into(img_main_d);
txt_title_d.setText(arrayList.get(0).getCategoryName());
txt_description_d.setText(Html.fromHtml(arrayList.get(0).getCategory_description().replaceAll("\\\\", "")));
dialog.show();
Window window = dialog.getWindow();
assert window != null;
window.setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
txt_close.setOnClickListener(view -> dialog.dismiss());
}
private void getCategoryLesson() {
pDialog = new ProgressDialog(LessonActivity.this);
pDialog.setTitle("Checking Data");
pDialog.setMessage("Please Wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
Observable<LessonResponse> responseObservable = apiservice.getCategoryLesson(
sessionManager.getKeyEmail(),
arrayListCategory.get(0).getCategoryId(),
goal_id,
sessionManager.getUserData().get(0).getUserId(),
sessionManager.getKeyToken());
responseObservable.subscribeOn(Schedulers.newThread())
.observeOn(AndroidSchedulers.mainThread())
.onErrorResumeNext(throwable -> {
if (throwable instanceof retrofit2.HttpException) {
retrofit2.HttpException ex = (retrofit2.HttpException) throwable;
Log.e("error", ex.getLocalizedMessage());
}
return Observable.empty();
})
.subscribe(new Observer<LessonResponse>() {
#Override
public void onCompleted() {
pDialog.dismiss();
}
#Override
public void onError(Throwable e) {
}
#Override
public void onNext(LessonResponse lessonResponse) {
if (lessonResponse.getData().size() > 9) {
txt_total_lesson.setText(String.valueOf(lessonResponse.getData().size()));
} else {
txt_total_lesson.setText(String.valueOf("0" + lessonResponse.getData().size()));
}
if (lessonResponse.getStatusCode() == 200) {
adapter = new LessonAdapter(lessonResponse.getData(), LessonActivity.this);
recycler_view.setAdapter(adapter);
} else {
Utility.displayToast(getApplicationContext(), lessonResponse.getMessage());
}
}
});
}
#Override
public boolean onSupportNavigateUp() {
onBackPressed();
return true;
}
#Override
public void onClickFavButton(int position, boolean toggle) {
}
public boolean isFavourate(String LessionId,String UserId){
if (arrayList!=null){
for (int i=0;i<arrayList.size();i++)
if (favarrayList.get(1).getLessonId().equals(LessionId) && favarrayList.get(0).getUserID().equals(UserId)){
return true;
}
}
return false;
}
#Override
protected void onDestroy() {
super.onDestroy();
RealmManager.close();
}
}
Adapter Class
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.row_lesson, parent, false);
return new LessonAdapter.ViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull ViewHolder holder, int position) {
dialog = new Dialog(context);
dialog.getWindow();
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setContentView(R.layout.custom_layout_lesson_audio);
txt_close = dialog.findViewById(R.id.txt_close);
txt_title_d = dialog.findViewById(R.id.txt_title_d);
txt_description_d = dialog.findViewById(R.id.txt_description_d);
img_play_d = dialog.findViewById(R.id.img_play_d);
frm_header = dialog.findViewById(R.id.frm_header);
img_back_d = dialog.findViewById(R.id.img_back_d);
holder.txt_lesson_title.setText(arrayList.get(position).getLessonName());
holder.btn_view.setOnClickListener(view -> {
txt_title_d.setText(arrayList.get(position).getLessonName());
dialog.show();
Window window = dialog.getWindow();
assert window != null;
window.setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
txt_description_d.setText(Html.fromHtml(arrayList.get(position).getLessonDescription().replaceAll("\\\\", "")));
displayDialog(holder.getAdapterPosition());
});
holder.btn_go.setOnClickListener(view -> {
Utility.getAppcon().getSession().arrayListLesson = new ArrayList<>();
Utility.getAppcon().getSession().arrayListLesson.add(arrayList.get(position));
Intent intent = new Intent(context, LessonCompleteActivity.class);
context.startActivity(intent);
});
if (arrayList.get(position).isFavourate())
holder.favCheck.setChecked(true);
else
holder.favCheck.setChecked(false);
holder.favCheck.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
CheckBox checkBox = (CheckBox) view;
if (checkBox.isChecked()) {
RealmManager.recordsDao().saveToFavorites(arrayList.get(position));
} else {
RealmManager.recordsDao().removeFromFavorites(arrayList.get(position));
}
}
});
}
private void displayDialog(int Position) {
final MediaPlayer mediaPlayer = new MediaPlayer();
String url = ApiConstants.IMAGE_URL + arrayList.get(Position).getLesson_audio_url();
//String url = "http://208.91.198.96/~diestechnologyco/apphoctienganhpro/uploads/mp3/mp3_1.mp3"; // your URL here
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
try {
mediaPlayer.setDataSource(url);
} catch (IOException e) {
e.printStackTrace();
}
try {
mediaPlayer.prepare(); // might take long! (for buffering, etc)
} catch (IOException e) {
e.printStackTrace();
}
img_play_d.setOnClickListener(view -> {
if (audio_flag == 0) {
mediaPlayer.start();
audio_flag = 1;
img_play_d.setImageResource(R.mipmap.pause_circle);
} else {
mediaPlayer.pause();
audio_flag = 0;
img_play_d.setImageResource(R.mipmap.icon_play);
}
});
//img_play_d.setOnClickListener(view -> mediaPlayer.start());
txt_close.setOnClickListener(view -> {
mediaPlayer.stop();
dialog.dismiss();
});
img_back_d.setOnClickListener(view -> {
mediaPlayer.stop();
dialog.dismiss();
});
}
#Override
public int getItemCount() {
return arrayList.size();
}
class ViewHolder extends RecyclerView.ViewHolder {
#BindView(R.id.txt_lesson_title)
TextView txt_lesson_title;
#BindView(R.id.txt_lesson_type)
TextView txt_lesson_type;
#BindView(R.id.btn_view)
Button btn_view;
#BindView(R.id.btn_go)
Button btn_go;
#BindView(R.id.image_favborder)
CheckBox favCheck;
ViewHolder(View itemView) {
super(itemView);
ButterKnife.bind(this, itemView);
//RealmManager.open();
}
}
public void getdata(){
}
public void addFavourate(String LessonId,String UserId) {
if (mRealm != null) {
mRealm.beginTransaction();
favList_model = mRealm.createObject(FavList_model.class);
favList_model.setLessonId(LessonId);
favList_model.setUserID(UserId);
mRealm.commitTransaction();
mRealm.close();
}
}
}

App is not responding after running this activity

New Activity UI load but does not respond, After running onStop() which trigger submit()
List View with the checkbox is bound by a custom adapter. On touch of the Submit button, an intent is triggered which takes me to HomeActivity and onStop() method is triggered which in return call submit method. All submit method is created under a new thread which interfere with UI.
package com.example.cadur.teacher;
public class Attendace extends AppCompatActivity {
DatabaseReference dref;
ArrayList<String> list=new ArrayList<>();
ArrayList<DeatailAttandance> deatailAttandances;
private MyListAdapter myListAdapter;
private ProgressDialog pb;
String year,branch,subject,emailId,pre,abs,rollno,file_name,dat,dat1,roll_str,rollno_present="",rollno_absent="";
int pre_int,abs_int;
ListView listview;
FirebaseDatabase database;
DatabaseReference myRef;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
SharedPreferences sp=getSharedPreferences("login",MODE_PRIVATE);
final String s=sp.getString("Password","");
final String s1=sp.getString("username","");
year=sp.getString("Year","");
branch=sp.getString("Branch","");
subject=sp.getString("Subject","");
final String attend="Attandence";
emailId=sp.getString("emailId","");
if (s!=null&&s!="" && s1!=null&&s1!="") {
setContentView(R.layout.activity_attendace);
deatailAttandances=new ArrayList<>();
listview = findViewById(R.id.list);
TextView detail=findViewById(R.id.lay);
detail.setText(year+" "+branch+" "+" "+subject);
pb =new ProgressDialog(Attendace.this);
pb.setTitle("Connecting Database");
pb.setMessage("Please Wait....");
pb.setCancelable(false);
pb.show();
database=FirebaseDatabase.getInstance();
myRef=database.getReference(year+"/"+branch);
myRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot ds:dataSnapshot.getChildren()) {
try {
abs = ds.child("Attandence").child(subject).child("Absent").getValue().toString();
pre = ds.child("Attandence").child(subject).child("Present").getValue().toString();
rollno = ds.getKey().toString();
deatailAttandances.add(new DeatailAttandance(rollno,pre,abs));
myListAdapter=new MyListAdapter(Attendace.this,deatailAttandances);
listview.setAdapter(myListAdapter);
pb.dismiss();
}catch (NullPointerException e){
pb.dismiss();
Intent intent=new Intent(Attendace.this, Login.class);
startActivity(intent);
finish();
}
}
count();
}
#Override
public void onCancelled(DatabaseError error) {
// Failed to read value
}
});
Button selectAll=findViewById(R.id.selectall);
selectAll.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
myListAdapter.setCheck();
count();
}
});
Button submit_attan=findViewById(R.id.submit_attan);
submit_attan.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent =new Intent(Attendace.this,HomeActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
}
});
Button count=findViewById(R.id.count);
count.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
View parentView = null;
int counter=0;
for (int i = 0; i < listview.getCount(); i++) {
parentView = getViewByPosition(i, listview);
CheckBox checkBox=parentView.findViewById(R.id.ch);
if(checkBox.isChecked()){
counter++;
}
}
Toast.makeText(Attendace.this,""+counter,Toast.LENGTH_SHORT).show();
}
});
}else{
SharedPreferences.Editor e = sp.edit();
e.putString("Password", "");
e.putString("username", "");
e.commit();
Intent i=new Intent(Attendace.this,MainActivity.class);
startActivity(i);
finish();
}
}
#Override
protected void onStop() {
Attendace.this.runOnUiThread(new Runnable() {
#Override
public void run() {
submit();
}
});
finish();
super.onStop();
}
public void submit(){
View parentView = null;
final Calendar calendar = Calendar.getInstance();
dat=new SimpleDateFormat("dd_MMM_hh:mm").format(calendar.getTime());
dat1=new SimpleDateFormat("dd MM yy").format(calendar.getTime());
file_name=year+"_"+branch+"_"+dat;
rollno_present=rollno_present+""+year+" "+branch+" "+subject+"\n "+dat+"\n\nList of present Students\n";
rollno_absent=rollno_absent+"\n List of absent Students\n";
for (int i = 0; i < listview.getCount(); i++) {
parentView = getViewByPosition(i, listview);
roll_str = ((TextView) parentView.findViewById(R.id.text1)).getText().toString();
String pre_str = ((TextView) parentView.findViewById(R.id.text22)).getText().toString();
String abs_str = ((TextView) parentView.findViewById(R.id.text33)).getText().toString();
pre_int=Integer.parseInt(pre_str);
abs_int=Integer.parseInt(abs_str);
CheckBox checkBox=parentView.findViewById(R.id.ch);
if(checkBox.isChecked()){
pre_int++;
myRef.child(roll_str).child("Attandence").child(subject).child("Present").setValue(""+pre_int);
myRef.child(roll_str).child("Attandence").child(subject).child("Date").child(dat1).setValue("P");
rollno_present=rollno_present+"\n"+roll_str+"\n";
}else{
abs_int++;
myRef.child(roll_str).child("Attandence").child(subject).child("Absent").setValue(""+abs_int);
myRef.child(roll_str).child("Attandence").child(subject).child("Date").child(dat1).setValue("A");
rollno_absent=rollno_absent+"\n"+roll_str+"\n";
}
}
// Toast.makeText(Attendace.this,"Attendance Updated Successfully",Toast.LENGTH_SHORT).show();
AsyncTask.execute(new Runnable() {
#Override
public void run() {
generateNoteOnSD(Attendace.this,file_name,rollno_present+""+rollno_absent);
}
});
}
public void count(){
View parentView = null;
int counter=0;
for (int i = 0; i < listview.getCount(); i++) {
parentView = getViewByPosition(i, listview);
CheckBox checkBox=parentView.findViewById(R.id.ch);
if(checkBox.isChecked()){
counter++;
}
}
Toast.makeText(Attendace.this,""+counter,Toast.LENGTH_SHORT).show();
}
private View getViewByPosition(int pos, ListView listview1) {
final int firstListItemPosition = listview1.getFirstVisiblePosition();
final int lastListItemPosition = firstListItemPosition + listview1.getChildCount() - 1;
if (pos < firstListItemPosition || pos > lastListItemPosition) {
return listview1.getAdapter().getView(pos, null, listview1);
} else {
final int childIndex = pos - firstListItemPosition;
return listview1.getChildAt(childIndex);
}
}
public void generateNoteOnSD(Context context, String sFileName, String sBody) {
try
{
File root = new File(Environment.getExternalStorageDirectory(),year+"_"+branch+"_Attendance");
if (!root.exists())
{
root.mkdirs();
}
File gpxfile = new File(root, file_name+".doc");
FileWriter writer = new FileWriter(gpxfile,true);
writer.append(sBody+"\n");
writer.flush();
writer.close();
// Toast.makeText(Attendace.this,"File Generated",Toast.LENGTH_SHORT).show();
}
catch(IOException e)
{
e.printStackTrace();
}
}
}
Just use
submit();
instead of using
Attendace.this.runOnUiThread(new Runnable() {
#Override
public void run() {
submit();
}
});
and remove finish()

Call number when click list view item

I have a contact list activity but want to add some functionality so that when you click on a contact it will begin calling their phone number. I have tried this code snippet but nothing happens when I tap on a contact:
view.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent callIntent = new Intent(Intent.ACTION_CALL);
callIntent.setData(Uri.parse("tel:" + currentContact.getPhone()));
if (ActivityCompat.checkSelfPermission(context, Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED) {
return;
}
try{
((Activity) context).startActivity(callIntent);
}catch (Exception e){
e.printStackTrace();
}
All Contact activity code:
public class ContactList extends ActionBarActivity {
Spinner spinner, spinnerFilter;
EditText nameTxt, phoneTxt, emailTxt, addressTxt;
ImageView contactImageimgView, btnSort;
List<Contact> Contacts = new ArrayList<Contact>();
ListView contactListView;
//Uri imageUri = null;
AlertDialog alertDialog;
Bitmap photoTaken;
String userId;
boolean isReverseEnabledPriority = false, isReverseEnabledName = false;
//ArrayList<Contact> contacts;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_contact_list);
SQLiteHandler db = new SQLiteHandler(getApplicationContext());
HashMap<String, String> user = db.getUserDetails();
userId = user.get("uid");
nameTxt = (EditText) findViewById(R.id.txtName);
phoneTxt = (EditText) findViewById(R.id.txtPhone);
emailTxt = (EditText) findViewById(R.id.txtEmail);
addressTxt = (EditText) findViewById(R.id.txtAddress);
contactListView = (ListView) findViewById(R.id.listView);
contactImageimgView = (ImageView) findViewById(R.id.imgViewContactImage);
spinner = (Spinner) findViewById(R.id.spinner);
spinnerFilter = (Spinner) findViewById(R.id.spinnerFilter);
btnSort = (ImageView) findViewById(R.id.btnSort);
TabHost tabHost = (TabHost) findViewById(R.id.tabHost);
tabHost.setup();
TabHost.TabSpec tabSpec = tabHost.newTabSpec("Creator");
tabSpec.setContent(R.id.tabCreator);
tabSpec.setIndicator("add contact");
tabHost.addTab(tabSpec);
tabSpec = tabHost.newTabSpec("List");
tabSpec.setContent(R.id.tabContactList);
tabSpec.setIndicator("contact list");
tabHost.addTab(tabSpec);
getContacts(ContactList.this);
btnSort.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String filter = spinnerFilter.getSelectedItem().toString();
if(filter.equals("Priority")){
Collections.sort(Contacts, new Comparator<Contact>() {
public int compare(Contact v1, Contact v2) {
return v1.getPriorityVal().compareTo(v2.getPriorityVal());
}
});
if(isReverseEnabledPriority)
Collections.reverse(Contacts);
isReverseEnabledPriority = !isReverseEnabledPriority;
populateList();
}else if(filter.equals("Name")){
Collections.sort(Contacts, new Comparator<Contact>() {
public int compare(Contact v1, Contact v2) {
return v1.getName().compareTo(v2.getName());
}
});
if(isReverseEnabledName)
Collections.reverse(Contacts);
isReverseEnabledName = !isReverseEnabledName;
populateList();
}else{
Toast.makeText(ContactList.this, "Please selectr a method to sort..!", Toast.LENGTH_SHORT).show();
}
}
});
final Button addBtn = (Button) findViewById(R.id.btnAdd);
addBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Contact contact = new Contact(photoTaken, nameTxt.getText().toString(), phoneTxt.getText().toString(), emailTxt.getText().toString(), addressTxt.getText().toString(), spinner.getSelectedItem().toString(), userId);
Contacts.add(contact);
saveContact(contact, ContactList.this);
}
});
nameTxt.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence charSequence, int start, int before, int count) {
addBtn.setEnabled(!nameTxt.getText().toString().trim().isEmpty());
}
#Override
public void afterTextChanged(Editable s) {
}
});
contactImageimgView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Contact Image"), 1);
}
});
}
void getContacts(final Context context){
new Thread(){
private Handler handler = new Handler();
private ProgressDialog progressDialog;
#Override
public void run(){
handler.post(new Runnable() {
#Override
public void run() {
progressDialog = ProgressDialog.show(context, null, "Please wait..", false);
}
});
try {
Contacts = ContactsController.getAllContactsOfUser(userId);
populateList();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
handler.post(new Runnable() {
#Override
public void run() {
if (progressDialog != null && progressDialog.isShowing()) {
progressDialog.dismiss();
}
}
});
}
}.start();
}
void saveContact(final Contact contact, final Context context){
new Thread(){
private Handler handler = new Handler();
private ProgressDialog progressDialog;
boolean result = false;
int id;
#Override
public void run(){
handler.post(new Runnable() {
#Override
public void run() {
progressDialog = ProgressDialog.show(context, null, "Saving Contact..", false);
}
});
try {
id = ContactsController.saveContact(contact);
if(id > 0){
contact.setId(id);
result = ContactsController.uploadImage(contact);
}
} catch (Exception e) {
e.printStackTrace();
}
handler.post(new Runnable() {
#Override
public void run() {
if (progressDialog != null && progressDialog.isShowing()) {
progressDialog.dismiss();
}
if(id == 0){
Toast.makeText(context, "Contact is not saved..!", Toast.LENGTH_SHORT).show();
}
if(!result){
Toast.makeText(context, "Image upload failed..!", Toast.LENGTH_SHORT).show();
}else{
populateList();
Toast.makeText(getApplicationContext(), nameTxt.getText().toString() + " has been added to your Contacts!", Toast.LENGTH_SHORT).show();
}
}
});
}
}.start();
}
public void onActivityResult(int reqCode, int resCode, Intent data) {
if (resCode == RESULT_OK) {
if (reqCode == 1) {
Uri imageUri = data.getData();
try {
photoTaken = MediaStore.Images.Media.getBitmap(this.getContentResolver(),imageUri);
} catch (IOException e) {
e.printStackTrace();
}
contactImageimgView.setImageURI(data.getData());
}
}
}
private void populateList() {
ArrayAdapter<Contact> adapter = new ContactListAdapter();
contactListView.setAdapter(adapter);
}
private class ContactListAdapter extends ArrayAdapter<Contact> {
public ContactListAdapter() {
super(ContactList.this, R.layout.listview_item, Contacts);
}
#Override
public View getView(int position, View view, ViewGroup parent) {
if (view == null)
view = getLayoutInflater().inflate(R.layout.listview_item, parent, false);
final Contact currentContact = Contacts.get(position);
try {
TextView name = (TextView) view.findViewById(R.id.contactName);
name.setText(currentContact.getName());
TextView phone = (TextView) view.findViewById(R.id.phoneNumber);
phone.setText(currentContact.getPhone());
TextView email = (TextView) view.findViewById(R.id.emailAddress);
email.setText(currentContact.getEmail());
TextView address = (TextView) view.findViewById(R.id.cAddress);
address.setText(currentContact.getAddress());
TextView cPriority = (TextView) view.findViewById(R.id.cPriority);
cPriority.setText(currentContact.getPriority());
ImageView ivContactImage = (ImageView) view.findViewById(R.id.ivContactImage);
if(currentContact.getImage() != null)
ivContactImage.setImageBitmap(currentContact.getImage());
} catch (Exception e) {
e.printStackTrace();
}
ImageView btnDeleteContact = (ImageView) view.findViewById(R.id.btnDeleteContact);
btnDeleteContact.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final AlertDialog.Builder builder = new AlertDialog.Builder(ContactList.this);
builder.setTitle("Confirm Delete");
builder.setMessage("Are you sure?");
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
deleteContact(currentContact, ContactList.this);
alertDialog.dismiss();
}
});
builder.setNegativeButton("No", null);
alertDialog = builder.create();
alertDialog.show();
}
});
return view;
}
#Override
public int getCount() {
return Contacts.size();
}
void deleteContact( final Contact contact, final Context context){
new Thread(){
Handler handler = new Handler();
ProgressDialog progressDialog;
Boolean result = false;
#Override
public void run(){
handler.post(new Runnable() {
#Override
public void run() {
progressDialog = ProgressDialog.show(context, null, "Deleting Contact..", false);
}
});
try {
result = ContactsController.deleteContact(contact);
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
handler.post(new Runnable() {
#Override
public void run() {
if (progressDialog != null && progressDialog.isShowing()) {
progressDialog.dismiss();
}
if(!result){
Toast.makeText(context, "Contact delete failed..!", Toast.LENGTH_SHORT).show();
}else{
Contacts.remove(contact);
populateList();
Toast.makeText(getApplicationContext(), nameTxt.getText().toString() + " has been deleted from your Contacts!", Toast.LENGTH_SHORT).show();
}
}
});
}
}.start();
}
}
}
Have you try this code??
Uri number = Uri.parse("tel:123456789");
Intent callIntent = new Intent(Intent.ACTION_DIAL, number);
startActivity(callIntent);

Attempt to invoke interface method 'int org.ksoap2.serialization.KvmSerializable.getPropertyCount()' on a null object reference

i have a school project. It was built by some previous developer. I am trying to run it. But i am getting NullPointerException. Here is my code:
private boolean isNetworkAvailable()
{
ConnectivityManager connectivityManager=(ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo=connectivityManager.getActiveNetworkInfo();
return activeNetworkInfo !=null && activeNetworkInfo.isConnected();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_registration);
setToolbar();
new AsyncTask<Void,Void,Void>(){
#Override
protected void onPreExecute() {
super.onPreExecute();
dialog=new ProgressDialog(RegistrationActivity.this);
dialog.setMessage("Loading...");
dialog.show();
}
#Override
protected Void doInBackground(Void... params) {
SoapObject request = new SoapObject(WSDL_TARGET_NAMESPACE1,OPERATION_NAME1);
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.dotNet = true;
envelope.setOutputSoapObject(request);
HttpTransportSE httpTransport = new HttpTransportSE(SOAP_ADDRESS1);
httpTransport.debug=true;
try {
httpTransport.call(SOAP_ACTION1, envelope);
} catch (IOException e) {
e.printStackTrace();
} catch (XmlPullParserException e) {
e.printStackTrace();
}
try {
response= envelope.getResponse();
Log.e("response: ", response.toString() + "");
} catch (SoapFault soapFault) {
soapFault.printStackTrace();
Log.e("response: ", response.toString() + "");
}
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
dialog.dismiss();
try {
Log.e("response: ", response.toString() + "");
}catch(Exception e){
e.printStackTrace();
Toast.makeText(RegistrationActivity.this,response.toString()+"",Toast.LENGTH_LONG).show();
}
StringTokenizer tokens = new StringTokenizer(response.toString(), "=");
List<String> mylist=new ArrayList<String>();
for(int i=0;tokens.hasMoreTokens();i++){
StringTokenizer tokens1 = new StringTokenizer(tokens.nextToken(), ";");
mylist.add(tokens1.nextToken());
}
mylist.remove(0);
int partitionSize =1;
List<List<String>> partitions = new LinkedList<List<String>>();
for (int i = 0; i < mylist.size(); i += partitionSize) {
partitions.add(mylist.subList(i,
i + Math.min(partitionSize, mylist.size() - i)));
}
city=new ArrayList<String>();
for(int k=0;k<partitions.size();k++){
city.add(partitions.get(k).get(0));
}
callGetArea();
}
}.execute();
spcity= (Spinner) findViewById(R.id.spcity);
spcity.setOnItemSelectedListener(this);
sparea = (Spinner) findViewById(R.id.sparea);
sparea.setOnItemSelectedListener(this);
dateFormatter = new SimpleDateFormat("dd-MM-yyyy", Locale.US);
rg = (RadioGroup) findViewById(R.id.gendergroup);
name= (EditText) findViewById(R.id.fname);
address=(EditText)findViewById(R.id.address);
contact= (EditText) findViewById(R.id.contact);
email= (EditText) findViewById(R.id.email);
weight= (EditText) findViewById(R.id.weight);
password= (EditText) findViewById(R.id.password);
cpass= (EditText) findViewById(R.id.cpassword);
earea= (Spinner) findViewById(R.id.sparea);
ecity= (Spinner) findViewById(R.id.spcity);
btnContinue= (TextView)findViewById(R.id.btncont);
bdate = (EditText) findViewById(R.id.bdate);
bdate.setInputType(InputType.TYPE_NULL);
bdate.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
setDateTimeField();
fromDatePickerDialog.show();
}
});
btnContinue.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (isEmptyField(name)) {
Toast.makeText(RegistrationActivity.this, "Please Enter Name", Toast.LENGTH_LONG).show();
} else if (isEmptyField(bdate)) {
Toast.makeText(RegistrationActivity.this, "Please Select Birthdate", Toast.LENGTH_LONG).show();
} else if (isEmptyField(address)) {
Toast.makeText(RegistrationActivity.this, "Please Enter Address", Toast.LENGTH_LONG).show();
} else if (isEmptyField(weight)) {
Toast.makeText(RegistrationActivity.this, "Please Enter Weight", Toast.LENGTH_LONG).show();
} else if (isEmptyField(contact)) {
Toast.makeText(RegistrationActivity.this, "Please Enter Contact", Toast.LENGTH_LONG).show();
} else if (isEmptyField(email)) {
Toast.makeText(RegistrationActivity.this, "Please Enter E-Mail", Toast.LENGTH_LONG).show();
}else if (!isEmailPattern(email)) {
Toast.makeText(RegistrationActivity.this, "Please Enter Valid E-Mail", Toast.LENGTH_LONG).show();
}else if (isEmptyField(password)) {
Toast.makeText(RegistrationActivity.this, "Please Enter Password", Toast.LENGTH_LONG).show();
} else if (isEmptyField(cpass)) {
Toast.makeText(RegistrationActivity.this, "Please Confirm Password", Toast.LENGTH_LONG).show();
} else if (!isPasswordMatch(cpass,password)) {
Toast.makeText(RegistrationActivity.this, "Password doesn't match", Toast.LENGTH_LONG).show();
}
else {
if(isNetworkAvailable()) {
new AsyncTask<Void, Void, Void>() {
#Override
protected void onPreExecute() {
super.onPreExecute();
dialog = new ProgressDialog(RegistrationActivity.this);
dialog.setMessage("Loading...");
dialog.show();
}
#Override
protected Void doInBackground(Void... params) {
resp = loginCall(email.getText().toString().trim());
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
Log.e("Response", resp + "");
dialog.dismiss();
if (resp == 1) {
UserClass userClass = new UserClass();
userClass.name = name.getText().toString();
userClass.dob = bdate.getText().toString();
int selectedId = rg.getCheckedRadioButtonId();
RadioButton radioButton = (RadioButton) findViewById(selectedId);
userClass.gender = radioButton.getText().toString();
userClass.address = address.getText().toString();
userClass.city = city.get(ecity.getSelectedItemPosition());
userClass.area = area.get(earea.getSelectedItemPosition()).city;
userClass.weight = weight.getText().toString();
userClass.contact = contact.getText().toString();
userClass.email = email.getText().toString();
userClass.password = password.getText().toString();
Log.e("name", userClass.name + "");
Log.e("dob", userClass.dob + "");
Log.e("gender", userClass.gender + "");
Log.e("address", userClass.address + "");
Log.e("city", userClass.city + "");
Log.e("area", userClass.area + "");
Log.e("weight", userClass.weight + "");
Log.e("contact", userClass.contact + "");
Log.e("email", userClass.email + "");
Log.e("password", userClass.password + "");
PrefUtils.setCurrentUser(userClass, RegistrationActivity.this);
Intent intent = new Intent(RegistrationActivity.this, RegistrationActivity2.class);
startActivity(intent);
finish();
} else {
Toast.makeText(getApplicationContext(), "Email Already Exist", Toast.LENGTH_LONG).show();
}
}
}.execute();
}
else
{
Toast.makeText(RegistrationActivity.this, "Check Your Internet Connection", Toast.LENGTH_LONG).show();
}
}
}
});
}
public void onDateSet(DatePicker view, int year, int month, int day) {
Calendar userAge = new GregorianCalendar(year,month,day);
Calendar minAdultAge = new GregorianCalendar();
minAdultAge.add(Calendar.YEAR, -18);
if (minAdultAge.before(userAge))
{
Toast.makeText(RegistrationActivity.this,"Please enter valid date",Toast.LENGTH_LONG).show();
}
}
private void callGetArea() {
new AsyncTask<Void,Void,Void>(){
#Override
protected void onPreExecute() {
super.onPreExecute();
dialog=new ProgressDialog(RegistrationActivity.this);
dialog.setMessage("Loading...");
dialog.show();
}
#Override
protected Void doInBackground(Void... params) {
SoapObject request = new SoapObject(WSDL_TARGET_NAMESPACE2,OPERATION_NAME2);
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.dotNet = true;
envelope.setOutputSoapObject(request);
HttpTransportSE httpTransport = new HttpTransportSE(SOAP_ADDRESS2);
httpTransport.debug=true;
try {
httpTransport.call(SOAP_ACTION2, envelope);
} catch (IOException e) {
e.printStackTrace();
} catch (XmlPullParserException e) {
e.printStackTrace();
}
try {
response= envelope.getResponse();
Log.e("response: ", response.toString() + "");
} catch (SoapFault soapFault) {
soapFault.printStackTrace();
Log.e("response: ", response.toString() + "");
}
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
dialog.dismiss();
try {
Log.e("response: ", response.toString() + "");
}catch(Exception e){
e.printStackTrace();
Toast.makeText(RegistrationActivity.this,response.toString()+"",Toast.LENGTH_LONG).show();
}
StringTokenizer tokens = new StringTokenizer(response.toString(), "=");
List<String> mylist=new ArrayList<String>();
for(int i=0;tokens.hasMoreTokens();i++){
StringTokenizer tokens1 = new StringTokenizer(tokens.nextToken(), ";");
mylist.add(tokens1.nextToken());
}
mylist.remove(0);
final int partitionSize =2;
List<List<String>> partitions = new LinkedList<List<String>>();
for (int i = 0; i < mylist.size(); i += partitionSize) {
partitions.add(mylist.subList(i,
i + Math.min(partitionSize, mylist.size() - i)));
}
area=new ArrayList<Area>();
for(int k=0;k<partitions.size();k++){
area.add(new Area(partitions.get(k).get(0),partitions.get(k).get(1)));
}
TimeSpinnerAdapter1 tspcity=new TimeSpinnerAdapter1(RegistrationActivity.this,city);
spcity.setAdapter(tspcity);
spcity.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
ArrayList<Area> tempList=new ArrayList<Area>();
for(int i=0;i<area.size();i++){
Log.e("city............",area.get(i).area+"");
if(area.get(i).area.equalsIgnoreCase(city.get(position))){
tempList.add(area.get(i));
}
}
TimeSpinnerAdapter tsparea = new TimeSpinnerAdapter(RegistrationActivity.this, tempList);
sparea.setAdapter(tsparea);
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
}
}.execute();
}
private void setDateTimeField() {
Calendar newCalendar = Calendar.getInstance();
fromDatePickerDialog = new DatePickerDialog(this, new DatePickerDialog.OnDateSetListener() {
public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
Calendar userAge = new GregorianCalendar(year,monthOfYear,dayOfMonth);
Calendar minAdultAge = new GregorianCalendar();
minAdultAge.add(Calendar.YEAR, -18);
if (minAdultAge.before(userAge))
{
Toast.makeText(RegistrationActivity.this,"Please Enter Valid Date",Toast.LENGTH_LONG).show();
} else {
bdate.setText(dateFormatter.format(userAge.getTime()));
}
}
},newCalendar.get(Calendar.YEAR), newCalendar.get(Calendar.MONTH), newCalendar.get(Calendar.DAY_OF_MONTH));
}
public boolean isEmptyField(EditText param1) {
boolean isEmpty = false;
if (param1.getText() == null || param1.getText().toString().equalsIgnoreCase("")) {
isEmpty = true;
}
return isEmpty;
}
private void setToolbar() {
toolbar = (Toolbar) findViewById(R.id.toolbar);
if (toolbar != null) {
toolbar.setTitle("Register");
setSupportActionBar(toolbar);
}
}
#Override
public void onBackPressed() {
super.onBackPressed();
finish();
}
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
public class TimeSpinnerAdapter extends BaseAdapter implements SpinnerAdapter {
private final Context activity;
private ArrayList<Area> asr;
public TimeSpinnerAdapter(Context context,ArrayList<Area> asr) {
this.asr=asr;
activity = context;
}
public int getCount()
{
return asr.size();
}
public Object getItem(int i)
{
return asr.get(i);
}
public long getItemId(int i)
{
return (long)i;
}
#Override
public View getDropDownView(int position, View convertView, ViewGroup parent) {
TextView txt = new TextView(RegistrationActivity.this);
txt.setPadding(16,16,16,16);
txt.setTextSize(16);
txt.setGravity(Gravity.CENTER_VERTICAL);
txt.setText(asr.get(position).city);
txt.setTextColor(Color.parseColor("#494949"));
return txt;
}
public View getView(int i, View view, ViewGroup viewgroup) {
TextView txt = new TextView(RegistrationActivity.this);
txt.setGravity(Gravity.CENTER_VERTICAL);
txt.setPadding(16,16,16,16);
txt.setTextSize(16);
txt.setCompoundDrawablesWithIntrinsicBounds(0, 0, R.drawable.ic_spinner, 0);
txt.setText(asr.get(i).city);
txt.setTextColor(Color.parseColor("#ffffff"));
return txt;
}
}
public static boolean isEmailPattern(EditText param1) {
Pattern pattern = Patterns.EMAIL_ADDRESS;
return pattern.matcher(param1.getText().toString()).matches();
}
public static boolean isPasswordMatch(EditText param1, EditText param2) {
boolean isMatch = false;
if (param1.getText().toString().equals(param2.getText().toString())) {
isMatch = true;
}
return isMatch;
}
public class TimeSpinnerAdapter1 extends BaseAdapter implements SpinnerAdapter {
private final Context activity;
private ArrayList<String> asr;
public TimeSpinnerAdapter1(Context context,ArrayList<String> asr) {
this.asr=asr;
activity = context;
}
public int getCount()
{
return asr.size();
}
public Object getItem(int i)
{
return asr.get(i);
}
public long getItemId(int i)
{
return (long)i;
}
#Override
public View getDropDownView(int position, View convertView, ViewGroup parent) {
TextView txt = new TextView(RegistrationActivity.this);
txt.setPadding(16,16,16,16);
txt.setTextSize(16);
txt.setGravity(Gravity.CENTER_VERTICAL);
txt.setText(asr.get(position));
txt.setTextColor(Color.parseColor("#494949"));
return txt;
}
public View getView(int i, View view, ViewGroup viewgroup) {
TextView txt = new TextView(RegistrationActivity.this);
txt.setGravity(Gravity.CENTER_VERTICAL);
txt.setPadding(16,16,16,16);
txt.setTextSize(16);
txt.setCompoundDrawablesWithIntrinsicBounds(0, 0, R.drawable.ic_spinner, 0);
txt.setText(asr.get(i));
txt.setTextColor(Color.parseColor("#ffffff"));
return txt;
}
}
public int loginCall(String c1)
{
SoapObject request = new SoapObject(WSDL_TARGET_NAMESPACE,OPERATION_NAME);
PropertyInfo p1=new PropertyInfo();
p1.setName("email");
p1.setValue(c1);
p1.setType(String.class);
request.addProperty(p1);
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
SoapEnvelope.VER11);
envelope.dotNet = true;
envelope.setOutputSoapObject(request);
HttpTransportSE httpTransport = new HttpTransportSE(SOAP_ADDRESS);
Object response=null;
try
{
httpTransport.debug=true;
httpTransport.call(SOAP_ACTION, envelope);
response = envelope.getResponse();
}
catch (Exception ex)
{
// ex.printStackTrace();
Toast.makeText(getApplicationContext(),"error",Toast.LENGTH_LONG).show();
//displayExceptionMessage(ex.getMessage());
//System.out.println(exception.getMessage());
}
return Integer.parseInt(response.toString());
}
I am getting NullPointerException on response= envelope.getResponse();
My error is following:
Process: com.nkdroid.blooddonation, PID: 16820
java.lang.RuntimeException: An error occurred while executing doInBackground()
at android.os.AsyncTask$3.done(AsyncTask.java:309)
at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:354)
at java.util.concurrent.FutureTask.setException(FutureTask.java:223)
at java.util.concurrent.FutureTask.run(FutureTask.java:242)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:234)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588)
at java.lang.Thread.run(Thread.java:818)
Caused by: java.lang.NullPointerException: Attempt to invoke interface method 'int org.ksoap2.serialization.KvmSerializable.getPropertyCount()' on a null object reference
at org.ksoap2.serialization.SoapSerializationEnvelope.getResponse(SoapSerializationEnvelope.java:513)
at com.nkdroid.blooddonation.RegistrationActivity$1.doInBackground(RegistrationActivity.java:146)
at com.nkdroid.blooddonation.RegistrationActivity$1.doInBackground(RegistrationActivity.java:120)
at android.os.AsyncTask$2.call(AsyncTask.java:295)
Can anyone help me with that?
I know code is a mess. But any help will be appreciated.
Thanks! :)
Make sure you have the same name as property in your service and android parameters, for example request.addProperty("name",name) in the WebService public class Login(String name)

Categories

Resources