I understand that a similar question has been asked but I am seriously stuck on this problem.
When I close the application, it says "Saving Data" which means my on stop method is being called but when I re open the app, it fails to mention that it is "getting data" meaning my onStart method is not being called.
The middle block of code seems to be the most important, I just wanted to include all of it so that if someone were to bump into my situation again, they could see everything.
How do I use the sharedpreferences class in this situation to save the background color and call the onStart method when I reopen the application?
As of now, it always resorts to the default Colour.
Thank you for your time.
EditText ed;
String background_color;
String Color_Value;
String Message;
int datablock =100;
int selectedItem;
int Color_Position;
int change=0;
View root;
View someView;
SharedPreferences prefer;
SharedPreferences.Editor prefer_edit;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_check_box);
ActionBar bar = getActionBar();
bar.setDisplayShowTitleEnabled(false);
bar.setDisplayShowHomeEnabled(false);
//Hides app title and icon
if (Color_Value!= null){
onStart();
}
else {
}
bar.setNavigationMode(ActionBar.NAVIGATION_MODE_LIST);
//Creates a spinner
ed = (EditText)findViewById(R.id.edit);
final String[] dropdown = getResources().getStringArray(R.array.Colors);
ArrayAdapter <String> adapter = new ArrayAdapter<String>(bar.getThemedContext(),
android.R.layout.simple_spinner_item,android.R.id.text1,dropdown);
//sets up the drop down navigation list in the action bar
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
bar.setListNavigationCallbacks(adapter, new OnNavigationListener(){
#Override
public boolean onNavigationItemSelected(int selectedItem, long arg1) {
//Java always starts counting at zero
if (selectedItem == 0){
someView = findViewById(R.id.layout);
root = someView.getRootView();
root.setBackgroundColor((Color.parseColor("#005640")));
Color_Position =Color.parseColor("#005640");
//prefer_edit.putInt("background_color", ((Color.parseColor("#005640"))));
Toast.makeText(getBaseContext(), "Color Changed", Toast.LENGTH_SHORT).show();
Log.i("At", "Position "+selectedItem);
}
else if (selectedItem == 1){
someView = findViewById(R.id.layout);
root = someView.getRootView();
root.setBackgroundColor((Color.parseColor("#045345")));
Color_Position =Color.parseColor("#045345");
//prefer_edit.putInt("background_color", ((Color.parseColor("#045345"))));
Toast.makeText(getBaseContext(), "Color Changed", Toast.LENGTH_SHORT).show();
Log.i("At", "Position "+selectedItem);
}
else if (selectedItem == 2){
someView = findViewById(R.id.layout);
root = someView.getRootView();
Color_Position =Color.parseColor("#384355");
root.setBackgroundColor((Color.parseColor("#384355")));
//prefer_edit.putInt("background_color", ((Color.parseColor("#384355"))));
Toast.makeText(getBaseContext(), "Color Changed", Toast.LENGTH_SHORT).show();
Log.i("At", "Position "+selectedItem);
}
else if (selectedItem == 3){
someView = findViewById(R.id.layout);
root = someView.getRootView();
Color_Position =Color.parseColor("#990088");
root.setBackgroundColor((Color.parseColor("#990088")));
//prefer_edit.putInt("background_color",((Color.parseColor("#990088"))));
Toast.makeText(getBaseContext(), "Color Changed", Toast.LENGTH_SHORT).show();
Log.i("At", "Position "+selectedItem);
}
else if (selectedItem == 4){
someView = findViewById(R.id.layout);
root = someView.getRootView();
Color_Position =Color.parseColor("#026211");
root.setBackgroundColor((Color.parseColor("#026211")));
// prefer_edit.putInt("background_color", (Color.parseColor("#026211")));
Toast.makeText(getBaseContext(), "Color Changed", Toast.LENGTH_SHORT).show();
Log.i("At", "Position "+selectedItem);
}
return true;
}
});
}
public void onStart(){
super.onStart();
Log.i("Getting Data", "Color is equal to "+Color_Position);
SharedPreferences prefer = getSharedPreferences(Color_Value,0);
prefer.getInt(background_color, 0);
}
public void onStop(){
super.onStop();
Log.i("Saving Data", "Color is equal to "+Color_Position);
SharedPreferences prefer = getSharedPreferences(Color_Value, 0);
SharedPreferences.Editor prefer_edit = prefer.edit();
prefer_edit.putInt(background_color, Color_Position);
prefer_edit.commit();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.check_box, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()){
case
R.id.action_settings:
//Pass data between activities here
break;
case
R.id.action_save:
SaveData();
break;
case
R.id.action_error:
LoadData();
break;
case
R.id.action_edit:
ChangeTextColor(change);
change++;
break;
}
return true;
}
public void SaveData(){
Message =ed.getText().toString();
try {
FileOutputStream out = openFileOutput("text.txt", MODE_PRIVATE);
OutputStreamWriter output = new OutputStreamWriter(out);
try{
output.write(Message);
output.flush();
output.close();
Toast.makeText(getBaseContext(), "Save successful", Toast.LENGTH_SHORT).show();
}
catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void LoadData(){
try {
FileInputStream fis = openFileInput("text.txt");
InputStreamReader ins = new InputStreamReader(fis);
//Deserialize the file
char[] Data = new char [datablock];
String final_data ="";
int size;
try {
while((size = ins.read(Data))>0){
String read_data = String.copyValueOf(Data, 0 ,size);
final_data+=read_data;
Data = new char[datablock];
}
Toast.makeText(getBaseContext(), "Message : " + final_data, Toast.LENGTH_SHORT).show();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
//Methods galore!
public void ChangeTextColor(int change){
if ((change % 2) == 0) {
// number is even
ed.setHint("enter a message to save");
ed.setTextColor(getResources().getColor(android.R.color.holo_red_dark));
Toast.makeText(getApplicationContext(), "Text color changed to red", Toast.LENGTH_LONG).show();
change++;
}
else {
// number is odd
ed.setHint("enter a message to save");
ed.setTextColor(getResources().getColor(android.R.color.black));
Toast.makeText(getApplicationContext(), "Text color changed to black", Toast.LENGTH_LONG).show();
change++;
}
}
}
onStart is called after onCreate, please remove this
if (Color_Value!= null){
onStart();
}
else {
}
and you can retrieve the color fron SharedPreferences directly in onCreate.
Related
I have listview with three viewholders one for image one for video one for audio
In videholder i have listview in which I am showing thumbnail of video if it downloaded.Its working fine but when i scroll then that thumbnail set on another imageview too.
mConvertView = convertView;
chatMessage=chatMessages.get(position);
final TextViewHolder mTextViewHolder;
final ImageViewHolder mImageViewHolder;
final AudioViewHolder mAudioViewHolder;
Object object=chatMessages.get(position);
// mHandler = new Handler();
disply = new DisplayImageOptions.Builder().cacheInMemory(true)
.cacheOnDisk(true)
.imageScaleType(ImageScaleType.IN_SAMPLE_POWER_OF_2)
.displayer(new RoundedBitmapDisplayer(20)).build();
ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(
context).defaultDisplayImageOptions(disply).build();
ImageLoader.getInstance().init(config);
rd = new RecordBaseHandler(context);
if(chatMessage.getAssetsId() != null)
{
if(chatMessage.getType().equalsIgnoreCase("audio"))
{
Log.d("Node", "Item position is "+chatMessages.get(position));
mAudioViewHolder = getAudioViewHolder(mConvertView);
mAudioViewHolder.mChatmessage=chatMessage;
// TODO change below code
if(chatMessage.getSenderId() != null)
setAlignment(mAudioViewHolder, chatMessage.getSenderId().intValue() != ((SMBChatApp) context.getApplication()).getQbUser().getId().intValue());
else
setAlignment(mAudioViewHolder, false);
mAudioViewHolder.play.setTag(position);
mAudioViewHolder.txtInfo.setText(getTimeText(chatMessage.getDate_sent()));
mycontent = chatMessage.getProperty("content-type");
try {
Cursor rs = rd.getData(chatMessage.getAssetsId());
rs.moveToFirst();
filepath = rs.getString(rs.getColumnIndex("file_path"));
Log.d("Node", "FINALLY FILE PATH IS " + filepath);
if (!rs.isClosed()) {
rs.close();
}
if (filepath != null) {
mAudioViewHolder.download.setVisibility(View.GONE);
} else {
mAudioViewHolder.play.setVisibility(View.GONE);
mAudioViewHolder.download.setVisibility(View.VISIBLE);
}
} catch (Exception e) {
// TODO: handle exception
Log.d("Node", "EXECPTIOn " + e);
}
mAudioViewHolder.download.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Log.d("Node: ", "Reading all contacts..");
List<RecordModel> contacts = rd.getAllContacts();
for (RecordModel cn : contacts) {
String log = "Id: "+ cn.getId()+ " ,Name: "+ cn.getAttch_id()+ " ,Phone: " + cn.getFile_path();
Log.d("Node: ",log);
}
// File tempMp3 = File.createTempFile("record", ".mp3", f);
new Thread()
{
public void run() {
File tempMp3 = null;
try {
tempMp3 = File.createTempFile("record", ".mp3",Environment.getExternalStorageDirectory());
} catch (IOException e) {
e.printStackTrace();
}
//We are creating folder first using mkdir
File f = new File(Environment.getExternalStorageDirectory()+ "/smbchat/");
if(!f.exists()){
f.mkdirs();
}
//then we want to store downloded file in that folder
File output = new File(f, "smb_" + System.currentTimeMillis() + "_audio.mp3");
Log.d("Node", "URL VALUE "+chatMessage.getUrl());
HttpRequest.get(chatMessage.getUrl()).receive(output);
audioFileName=String.valueOf(output);
Log.d("Node", "FILE SAVED SUCCESSFULLY"+tempMp3);
Log.d("Node", "FILE SAVED SUCCESSFULLY AUDIOFILENAME " + audioFileName);
context.runOnUiThread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
Toast.makeText(context, "file downloaded successfully", Toast.LENGTH_LONG).show();
mAudioViewHolder.download.setVisibility(View.GONE);
}
});
rd.addContact(new RecordModel(chatMessage.getAssetsId(), audioFileName));
};
}.start();
}
});
mAudioViewHolder.play.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
mAudioViewHolder.play.setVisibility(View.GONE);
mAudioViewHolder.pause.setVisibility(View.VISIBLE);
Log.d("DATA", "currently playing " + position);
playingAudioPosition = position;
Object tag = mAudioViewHolder.play.getTag();
// Here we get the position that we have set for the checkbox using setTag.
String str=chatMessage.getAssetsId();
Cursor rs = rd.getData(str);
rs.moveToFirst();
try
{
filepath = rs.getString(rs.getColumnIndex("file_path"));
}
catch(Exception e)
{
Toast.makeText(mConvertView.getContext(), "File is not downloaded", Toast.LENGTH_LONG).show();
}
Log.d("Node", "file path for id "+ str + "is "+ filepath);
if (!rs.isClosed()) {
rs.close();
}
if(filepath==null) //we check whether file is present or not
{
Toast.makeText(mConvertView.getContext(), "File is Not downloaded", Toast.LENGTH_SHORT).show();
((View)v.getParent()).findViewById(R.id.btndn).setVisibility(View.VISIBLE);
// mAudioViewHolder.download.setVisibility(mConvertView.VISIBLE);
}
else {
((View) v.getParent()).findViewById(
R.id.chat_audio_progress_bar)
.setVisibility(View.VISIBLE);
// mAudioViewHolder.progressBar.setVisibility(mConvertView.VISIBLE);
mediaPlayer = new MediaPlayer();
String yofile = "file://" + filepath;
mediaPlayer
.setAudioStreamType(AudioManager.STREAM_MUSIC);
try {
mediaPlayer.setDataSource(yofile);
} catch (IllegalArgumentException
| SecurityException
| IllegalStateException | IOException e) {
// TODO Auto-generated catch block
Log.e("Node", "ERRORSS Part 1 is" + e);
mediaPlayer.setOnCompletionListener(new OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp)
{
mAudioViewHolder.isPlaying = false;
/**
* since audio is stop
* playing, remove its
* position value
* */
playingAudioPosition = -1;
}
});
}
try {
mediaPlayer.prepare();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Log.e("Node", "ERRORSS is Part 2 " + e);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
mediaPlayer.start();
isMediaReleased = false;
mAudioViewHolder.progressBar.setMax(mediaPlayer.getDuration());
updateSeekBar();
}
}
});
mAudioViewHolder.pause
.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mAudioViewHolder.play.setVisibility(View.VISIBLE);
mAudioViewHolder.pause.setVisibility(View.GONE);
mediaPlayer.stop();
}
});
}
if (chatMessage.getType().equalsIgnoreCase("image") || chatMessage.getType().equalsIgnoreCase("photo"))
{
mImageViewHolder = getImageViewHolder(mConvertView);
mImageViewHolder.mChatmessage=chatMessage;
Log.d("Node", "this is Image position is "+chatMessages.get(position));
// TODO change below code
if(chatMessage.getSenderId() != null)
setAlignment(mImageViewHolder, chatMessage.getSenderId().intValue() != ((SMBChatApp) context.getApplication()).getQbUser().getId().intValue());
else
setAlignment(mImageViewHolder, false);
mImageViewHolder.txtInfo.setText(getTimeText(chatMessage.getDate_sent()));
if (chatMessage.getProperty("localfile") != null) {
imageUri1 = chatMessage.getProperty("localfile");
String status = chatMessage.getProperty("isUpload");
imageUri2 = "file://" + imageUri1;
Log.d("Node", "This time from local");
ImageLoader.getInstance().displayImage(chatMessage.getUrl(),
mImageViewHolder.myimageview, disply);
//
// Log.d("Node", "IMAGEURI is : " + imageUri2
// + "And status is " + status);
} else {
Log.d("Node", "Here we are now else");
ImageLoader.getInstance().displayImage(chatMessage.getUrl(),
mImageViewHolder.myimageview, disply);
}
mImageViewHolder.myimageview.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Toast.makeText(context, "This is Image",
Toast.LENGTH_LONG).show();
Intent intent = new Intent(context,
ShowImgActivity.class);
String urll = chatMessage.getUrl();
Bitmap bitmap = mImageViewHolder.myimageview.getDrawingCache();
intent.putExtra("URL", urll);
intent.putExtra("BitmapImage", bitmap);
context.startActivity(intent);
}
});
}
//if aatchmnet is video then do this
else if (chatMessage.getType().equalsIgnoreCase("video")) {
mImageViewHolder = getImageViewHolder(mConvertView);
mImageViewHolder.mChatmessage=chatMessage;
// TODO change below code
if(chatMessage.getSenderId() != null)
setAlignment(mImageViewHolder, chatMessage.getSenderId().intValue() != ((SMBChatApp) context.getApplication()).getQbUser().getId().intValue());
else
setAlignment(mImageViewHolder, false);
mImageViewHolder.txtInfo.setText(getTimeText(chatMessage.getDate_sent()));
// Log.d("Node1", "This time from local videos");
if (chatMessage.getVideo_thumb() != null) {
Log.i("Node", "Yes this video has thumbnail");
Bitmap bitmp = StringToBitMap(chatMessage.getProperty("video_thumb"));
if (bitmp != null) {
mImageViewHolder.myimageview.setImageBitmap(bitmp);
} else {
mImageViewHolder.myimageview
.setImageResource(R.drawable.vids);
}
} else {
Log.i("Node", "Yes this dont have thumbanil");
ImageLoader.getInstance().displayImage(chatMessage.getUrl(),
mImageViewHolder.myimageview, disply);
}
mImageViewHolder.myimageview.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
final ImageView imageThumbnail = (ImageView)v;
final Handler handler=new Handler() {
public void handleMessage(Message msg) {
Log.e("", "handeler bmVideoThumbnail"+bmVideoThumbnail);
if (bmVideoThumbnail!=null) {
imageThumbnail.setImageBitmap(bmVideoThumbnail);
}
};
};
new Thread()
{
public void run() {
//We are creating folder first using mkdir
File f = new File(Environment.getExternalStorageDirectory()+ "/smbchat/");
if(!f.exists()){
f.mkdirs();
}
//then we want to store downloded file in that folder
File output = new File(f, "VID_" + System.currentTimeMillis() + "_video.mp4");
Log.d("Node", "URL VALUE "+chatMessage.getUrl());
HttpRequest.get(chatMessage.getUrl()).receive(output);
audioFileName=String.valueOf(output);
Log.d("Node", "FILE SAVED SUCCESSFULLY AUDIOFILENAME " + audioFileName);
donloadedVideoUri= "file://" + audioFileName;
Log.e("Node", "donloadedVideoUri INSIDE THREAD------"+donloadedVideoUri);
bmVideoThumbnail=ThumbnailUtils.createVideoThumbnail(audioFileName, android.provider.MediaStore.Video.Thumbnails.MICRO_KIND);
Log.e("Node", "bmVideoThumbnail---------"+bmVideoThumbnail);
if(bmVideoThumbnail !=null)
handler.sendEmptyMessage(0);
};
}.start();
// String uriString = chatMessage.getUrl();
// Uri intentUri = Uri.parse(uriString);
//
// Intent intent2 = new Intent();
// intent2.setAction(Intent.ACTION_VIEW);
// intent2.setDataAndType(intentUri, "video/*");
// context.startActivity(intent2);
}
});
}
}
else {
mTextViewHolder = getTextViewHolder(mConvertView);
mTextViewHolder.mChatmessage=chatMessage;
Log.d("Node", "this is text position is "+chatMessages.get(position));
//TODO redo following logic
if(chatMessage.getSenderId() != null)
setAlignment(mTextViewHolder, chatMessage.getSenderId().intValue() != ((SMBChatApp) context.getApplication()).getQbUser().getId().intValue());
else
setAlignment(mTextViewHolder, false);
mTextViewHolder.txtInfo.setText(getTimeText(chatMessage.getDate_sent()));
mTextViewHolder.txtMessage.setText(chatMessage.getBody());
mTextViewHolder.message = chatMessage;
}
return mConvertView;
Use one ViewHolder and define three fields and show hide views according status.
Maintain Status in list not in adapter.
Because list item recreated on list view scroll.
You can see same thumbnail in multiple list items as Android reuses the view of list item.
Care needs to be taken that you make the thumbnail invisible or use 'Icon which suggests no image' if you don't have the correct image for that position of list item. This check has to be made in getView method of your adapter of the list.
I have custom adapter list view with two spinner view.
Each spinner has a background process. On initializing, the spinner view.OnItemSelectedListener is recursively called unnecessarily without any external input to the listener
Class file
public class ClientListAdapter extends BaseAdapter implements SpinnerAdapter {
Context context;
int layoutResourceId;
ArrayList<GetClientListDetail> data = null;
ArrayList<GetClientListDetail> temp = null;
String ID, str;
Typeface typeface;
PopupWindow cp;
private ProgressDialog progressDialog;
String[] Status1 = new String[] { "Waiting", "Away","No Show"};
String[] Status2 = new String[] { "In Service",
"Generate Bill", "Completed" };
SpinnerAdapterlist TherapistAdapter = null;
ArrayAdapter<String> StatusAdapter = null;
ArrayList<GetTherapistProperties> TherapistList ;
private LayoutInflater inflater;
RemoveClient RC;
ChangeStatus CS;
ChangeTherapist CT;
ClientListHolder holder ;
int _therapistID;
GetClientListDetail ap;
GetTherapistProperties tp;
boolean networkavailable=false;
public ClientListAdapter(Context context, int textViewResourceId,
ArrayList<GetClientListDetail> gld, ArrayList<GetTherapistProperties> therapislist) {
super();
this.layoutResourceId = textViewResourceId;
this.context = context;
this.data = gld;
this.mGalleryCount1 = gld.size();
this.mGalleryCount2=gld.size();
this.TherapistList=therapislist;
inflater=LayoutInflater.from(context);
Resources res = context.getResources();
TherapistAdapter = new SpinnerAdapterlist(context,
R.layout.spinnerlayout, TherapistList);
StatusAdapter = new ArrayAdapter<String>(context,
android.R.layout.simple_dropdown_item_1line, Status1);
}
#Override
public int getCount() {
return data.size();
}
#Override
public GetClientListDetail getItem(int position) {
return data.get(position);
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
View row = convertView;
if (row == null) {
holder = new ClientListHolder();
row = inflater.inflate(layoutResourceId, parent, false);
holder.tv_no = (TextView) row
.findViewById(R.id.tv_clientwaitlayout_no);
holder.tv_name = (TextView) row
.findViewById(R.id.tv_clientwaitlayout_name);
holder.tv_status = (Spinner) row
.findViewById(R.id.tv_clientwaitlayout_status);
holder.tv_therapist = (Spinner) row
.findViewById(R.id.tv_clientwaitlayout_therapist);
holder.iv_edit=(ImageView) row.findViewById(R.id.btn_clientwaitlayout_edit);
holder.iv_action = (ImageView) row
.findViewById(R.id.btn_clientwaitlayout_action);
holder.tv_unchange_therapist=(TextView) row.findViewById(R.id.tv_clientwaitlayout_unchange_name);
holder.tv_unchange_status=(TextView) row.findViewById(R.id.tv_clientwaitlayout_unchange_status);
row.setTag(holder);
} else {
holder = (ClientListHolder) row.getTag();
}
holder.tv_therapist.setAdapter(TherapistAdapter);
holder.tv_status.setAdapter(StatusAdapter);
ap = data.get(position);
tp=TherapistList.get(position);
holder.tv_name.setText(ap.getCLDName());
holder.tv_no.setText(ap.getCLDNo());
if(ap.getCLDStatus().equals("1") ){
Log.d("LOOP","Sub If condition");
holder.tv_therapist.setVisibility(View.VISIBLE);
holder.tv_status.setVisibility(View.VISIBLE);
holder.tv_unchange_therapist.setVisibility(View.GONE);
holder.tv_unchange_status.setVisibility(View.GONE);
holder.iv_action.setVisibility(View.GONE);
holder.iv_edit.setVisibility(View.VISIBLE);
try {
for(int x=0;x<TherapistList.size();x++){
if(ap.getCLDTherapist().equals(TherapistList.get(x).getID())){
holder.tv_therapist.setSelection(x);
}else{
}
}
} catch (NumberFormatException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
holder.tv_status.setSelection(Integer.parseInt(ap.getCLDStatus()) - 1);
} catch (ArrayIndexOutOfBoundsException e2) {
// TODO Auto-generated catch block
holder.tv_status.setSelection(0);
}
}else if(ap.getCLDStatus().equals("2") | ap.getCLDStatus().equals("6")){
holder.tv_therapist.setVisibility(View.VISIBLE);
holder.tv_status.setVisibility(View.VISIBLE);
holder.tv_unchange_therapist.setVisibility(View.GONE);
holder.tv_unchange_status.setVisibility(View.GONE);
holder.iv_action.setVisibility(View.GONE);
holder.iv_edit.setVisibility(View.GONE);
try {
for(int x=0;x<TherapistList.size();x++){
if(ap.getCLDTherapist().equals(TherapistList.get(x).getID())){
holder.tv_therapist.setSelection(x);
}else{
}
}
} catch (NumberFormatException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
if(ap.getCLDStatus().equals("2")){
holder.tv_status.setSelection(1);
}else{
holder.tv_status.setSelection(2);
}
} catch (ArrayIndexOutOfBoundsException e2) {
// TODO Auto-generated catch block
holder.tv_status.setSelection(0);
}
}else{
holder.tv_therapist.setVisibility(View.GONE);
holder.tv_status.setVisibility(View.GONE);
holder.tv_unchange_therapist.setVisibility(View.VISIBLE);
holder.tv_unchange_status.setVisibility(View.VISIBLE);
holder.iv_action.setVisibility(View.VISIBLE);
holder.iv_edit.setVisibility(View.GONE);
for(int y=0;y<TherapistList.size();y++){
if(ap.getCLDTherapist().equals(TherapistList.get(y).getID())){
holder.tv_unchange_therapist.setText(TherapistList.get(y).getName());
break;
}else{
holder.tv_unchange_therapist.setText("Not Available");
}
}
if (ap.getCLDStatus().equals("2")) {
holder.tv_unchange_status.setText(Status1[1]);
} else if (ap.getCLDStatus().equals("3")) {
holder.tv_unchange_status.setText(Status2[0]);
} else if (ap.getCLDStatus().equals("4")) {
holder.tv_unchange_status.setText(Status2[1]);
} else if (ap.getCLDStatus().equals("5")) {
holder.tv_unchange_status.setText(Status2[2]);
} else if (ap.getCLDStatus().equals("6")) {
holder.tv_unchange_status.setText(Status1[2]);
}
}
holder.tv_therapist.setTag(ap.getCLDClientID());
holder.tv_status.setTag(ap.getCLDClientID());
holder.iv_edit.setTag(ap.getCLDClientID());
holder.iv_action.setTag(ap.getCLDClientID());
holder.iv_action.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
try {
ImageView b = (ImageView) v;
String id = b.getTag().toString();
Log.d("ID is", id);
Intent CDV=new Intent(context, TabSample.class);
CDV.putExtra("ID", id);
//CDV.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
//context.startActivity(CDV);
((Activity) context).startActivityForResult(CDV,5);
try {
Log.d("POSITION", "" + position + " "
+ data.get(position).getCLDClientID());
} catch (ArrayIndexOutOfBoundsException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
holder.tv_status
.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
// TODO Auto-generated method stub
int id=arg2+1;
try {
try {
CS=new ChangeStatus();
CS.setClientID(data.get(position).getCLDClientID());
CS.setSalonID("1");
if(id==3){
CS.setStatus("6");
}else{
CS.setStatus(String.valueOf(id));
}
new LoadChangeStatus().execute();
} catch (ArrayIndexOutOfBoundsException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
holder.tv_therapist
.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
// TODO Auto-generated method stub
try {
try {
Spinner sp = (Spinner) arg0;
String str = sp.getTag().toString();
TextView th_id=(TextView)arg1.findViewById(R.id.spnradptno);
CT=new ChangeTherapist();
CT.setClientID(str);
CT.setSalonID("1");
CT.setTherapist(th_id.getText().toString());
new LoadChangeTherapist().execute();
Log.d("SPR TXT", th_id.getText().toString()+" "+position+" "+str);
} catch (ArrayIndexOutOfBoundsException e) {
// TODO Auto-generated catch block
Log.d("Error in spinner",e.toString());
}
} catch (Exception e) {
// TODO Auto-generated catch block
Log.d("Error2 in spinner",e.toString());
}
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
Log.d("Nothing","Selected");
}
});
holder.iv_edit.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
try {
ImageView b = (ImageView) v;
String id = b.getTag().toString();
Log.d("ID is", id);
Intent CDV=new Intent(context, TabSample.class);
CDV.putExtra("ID", id);
((Activity) context).startActivityForResult(CDV,5);
try {
Log.d("POSITION", "" + position + " "
+ data.get(position).getCLDClientID());
} catch (ArrayIndexOutOfBoundsException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
return row;
}
static class ClientListHolder {
TextView tv_no;
TextView tv_name;
Spinner tv_therapist;
Spinner tv_status;
ImageView iv_action;
ImageView iv_edit;
TextView tv_unchange_therapist;
TextView tv_unchange_status;
}
public class LoadChangeStatus extends AsyncTask<Integer, Integer, Integer> {
// Before running code in the separate thread
int LoadChangeStatus= 0;
#Override
protected void onPreExecute() {
// Create a new progress dialog
progressDialog = new ProgressDialog(context);
// Set the progress dialog to display a horizontal progress bar
// progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
// Set the dialog title to 'Loading...'
progressDialog.setTitle("Loading...");
// Set the dialog message to 'Loading application View, please
// wait...'
progressDialog.setMessage("Loading, please wait...");
// This dialog can't be canceled by pressing the back key
progressDialog.setCancelable(false);
// This dialog isn't indeterminate
progressDialog.setIndeterminate(false);
// The maximum number of items is 100
// Set the current progress to zero
// Display the progress dialog
progressDialog.show();
}
// The code to be executed in a background thread.
#Override
protected Integer doInBackground(Integer... params) {
try {
// temp.clear();
networkavailable=new Network().isNetworkAvailable(context);
if(networkavailable){
temp = CS.Change_Status(CS, context);
LoadChangeStatus=1;
}else{
LoadChangeStatus=2;
}
} catch (Exception e) {
// TODO Auto-generated catch block
Log.d("ERROR", "LoadChangeStatus backgroung");
}
return null;
}
// Update the progress
#Override
protected void onProgressUpdate(Integer... values) {
// set the current progress of the progress dialog
}
// after executing the code in the thread
#Override
protected void onPostExecute(Integer result) {
// close the progress dialog
progressDialog.dismiss();
if(LoadChangeStatus==1){
try {
data.clear();
data.addAll(temp);
notifyDataSetChanged();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}else if(LoadChangeStatus==2){
Toast.makeText(context, "Network Not Available", Toast.LENGTH_LONG).show();
}else{
Toast.makeText(context, "Changing Status Failed. Please Try Again", Toast.LENGTH_LONG).show();
}
}
}
public class LoadChangeTherapist extends
AsyncTask<Integer, Integer, Integer> {
// Before running code in the separate thread
int LoadChangeTherapist = 0;
#Override
protected void onPreExecute() {
// Create a new progress dialog
progressDialog = new ProgressDialog(context);
// Set the progress dialog to display a horizontal progress bar
// progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
// Set the dialog title to 'Loading...'
progressDialog.setTitle("Loading...");
// Set the dialog message to 'Loading application View, please
// wait...'
progressDialog.setMessage("Loading, please wait...");
// This dialog can't be canceled by pressing the back key
progressDialog.setCancelable(false);
// This dialog isn't indeterminate
progressDialog.setIndeterminate(false);
// The maximum number of items is 100
// Set the current progress to zero
// Display the progress dialog
progressDialog.show();
}
// The code to be executed in a background thread.
#Override
protected Integer doInBackground(Integer... params) {
try {
// temp.clear();
networkavailable=new Network().isNetworkAvailable(context);
if(networkavailable){
temp = CT.Get_Change_Therapist(CT, context);
LoadChangeTherapist=1;
}else{
LoadChangeTherapist=2;
}
} catch (Exception e) {
// TODO Auto-generated catch block
Log.d("ERROR", "LoadChangeStatus backgroung");
}
return null;
}
// Update the progress
#Override
protected void onProgressUpdate(Integer... values) {
// set the current progress of the progress dialog
}
// after executing the code in the thread
#Override
protected void onPostExecute(Integer result) {
// close the progress dialog
progressDialog.dismiss();
if (LoadChangeTherapist == 1) {
try {
data.clear();
data.addAll(temp);
notifyDataSetChanged();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} else if (LoadChangeTherapist == 2) {
Toast.makeText(context, "Network Not Available", Toast.LENGTH_LONG).show();
}else{
Toast.makeText(context, "Removing Client Failed. Please Try Again", Toast.LENGTH_LONG).show();
}
}
}
public class LoadRemoveClient extends AsyncTask<Integer, Integer, Integer> {
// Before running code in the separate thread
int LoadRemoveClient = 0;
#Override
protected void onPreExecute() {
// Create a new progress dialog
progressDialog = new ProgressDialog(context);
// Set the progress dialog to display a horizontal progress bar
// progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
// Set the dialog title to 'Loading...'
progressDialog.setTitle("Loading...");
// Set the dialog message to 'Loading application View, please
// wait...'
progressDialog.setMessage("Loading, please wait...");
// This dialog can't be canceled by pressing the back key
progressDialog.setCancelable(false);
// This dialog isn't indeterminate
progressDialog.setIndeterminate(false);
// The maximum number of items is 100
// Set the current progress to zero
// Display the progress dialog
progressDialog.show();
}
// The code to be executed in a background thread.
#Override
protected Integer doInBackground(Integer... params) {
Log.d("ERROR", "LoadRemoveClient backgroung");
try {
networkavailable=new Network().isNetworkAvailable(context);
if(networkavailable){
temp = RC.Get_Client_List_Detail(RC, context);
LoadRemoveClient=1;
}else{
LoadRemoveClient=2;
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
// Update the progress
#Override
protected void onProgressUpdate(Integer... values) {
// set the current progress of the progress dialog
}
// after executing the code in the thread
#Override
protected void onPostExecute(Integer result) {
// close the progress dialog
progressDialog.dismiss();
if (LoadRemoveClient == 1) {
try {
data.clear();
data.addAll(temp);
notifyDataSetChanged();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} else if (LoadRemoveClient == 2) {
Toast.makeText(context, "Network Not Available", Toast.LENGTH_LONG).show();
}else{
Toast.makeText(context, "Removing Client Failed. Please Try Again", Toast.LENGTH_LONG).show();
}
}
}
}
How to avoid unnecessarily calling of view.OnItemSelectedListener of spinner view On initializing custom adapter list view
You can't stop or avoid calling of onItemSelectedListener on initialization. But you can prevent this by declare an integer and set value as 0 and while on calling getview method, check the integer with size of data(Your array list size).if the integer is less than the size than increment the integer value else do your background work. But it's not right way to do because when you scroll the listview the same problem rise again. You do this if you have fixed array list size. It is better to use AutoCompleteTextView instead of SpinnerView.
It gets called for the selection of the first item(Kind of default value).
Try one thing don't set adapter to spinner if row!=null for ex:
if (row == null) {
holder = new ClientListHolder();
row = inflater.inflate(layoutResourceId, parent, false);
holder.tv_no = (TextView) row
.findViewById(R.id.tv_clientwaitlayout_no);
holder.tv_name = (TextView) row
.findViewById(R.id.tv_clientwaitlayout_name);
holder.tv_status = (Spinner) row
.findViewById(R.id.tv_clientwaitlayout_status);
holder.tv_therapist = (Spinner) row
.findViewById(R.id.tv_clientwaitlayout_therapist);
holder.iv_edit=(ImageView) row.findViewById(R.id.btn_clientwaitlayout_edit);
holder.iv_action = (ImageView) row
.findViewById(R.id.btn_clientwaitlayout_action);
holder.tv_unchange_therapist=(TextView) row.findViewById(R.id.tv_clientwaitlayout_unchange_name);
holder.tv_unchange_status=(TextView) row.findViewById(R.id.tv_clientwaitlayout_unchange_status);
holder.tv_therapist.setAdapter(TherapistAdapter);
holder.tv_status.setAdapter(StatusAdapter);
row.setTag(holder);
} else {
holder = (ClientListHolder) row.getTag();
}
I'm loading a text file into an EditText but the file only gets partially loaded. I've tried two different files and get the same result. One file gets cut off halfway through line 35 and the other line 37. No idea why.
<com.mobilewebtoolkit.EditTextLineNumbers
android:id="#+id/ide"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:ems="10"
android:gravity="left"
android:inputType="textMultiLine"
android:lineSpacingExtra="5dp"
android:textSize="15sp"
android:visibility="visible" >
code:
private void openFile(final File aFile) {
String nullChk = et.getText().toString();
if (!changed || nullChk.matches("")) {
try {
currentFile = aFile;
getExt();
et.setText(new Scanner(currentFile).useDelimiter("\\Z").next());
changed = false;
exists = true;
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} else {
AlertDialog.Builder alert = new AlertDialog.Builder(this);
alert.setTitle("Save first?");
alert.setMessage("(Will be saved in the current working directory)");
alert.setPositiveButton("Yes",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int whichButton) {
String temptxt = et.getText().toString();
if (currentFile.exists()) {
try {
saveFile(currentFile.getPath(), temptxt);
currentFile = aFile;
getExt();
} catch (NullPointerException e) {
Log.i("NullPointer", currentFile.getName());
}
try {
et.setText(new Scanner(currentFile)
.useDelimiter("\\Z").next());
getExt();
if (extension.equals("txt")) {
Toast.makeText(MainActivity.this,
"Extension: " + extension,
Toast.LENGTH_LONG).show();
} else if (extension.equals("html")
|| extension.equals("htm")) {
Toast.makeText(MainActivity.this,
"Extension: " + extension,
Toast.LENGTH_LONG).show();
} else if (extension.equals("css")) {
Toast.makeText(MainActivity.this,
"Extension: " + extension,
Toast.LENGTH_LONG).show();
} else if (extension.equals("js")) {
Toast.makeText(MainActivity.this,
"Extension: " + extension,
Toast.LENGTH_LONG).show();
} else if (extension.equals("php")) {
Toast.makeText(MainActivity.this,
"Extension: " + extension,
Toast.LENGTH_LONG).show();
} else if (extension.equals("xml")) {
Toast.makeText(MainActivity.this,
"Extension: " + extension,
Toast.LENGTH_LONG).show();
}
changed = false;
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} else {
saveAs(null);
}
}
});
final File tempFile = aFile;
alert.setNegativeButton("No",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int whichButton) {
try {
et.setText(new Scanner(tempFile).useDelimiter(
"\\Z").next());
changed = false;
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
changed = false;
}
});
alert.setNeutralButton("Cancel",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int whichButton) {
changed = true;
dialog.cancel();
}
});
alert.show();
}
}
You should iterate over your Scanner until hasNext() return false to make sure the whole file is read. See more information here: Beware of using java.util.Scanner with ā/zā
StringBuilder sb = new StringBuilder();
Scanner scanner = new Scanner(tempFile).useDelimiter("\\Z");
while (scanner.hasNext()) {
sb.append(scanner.next());
}
et.setText(sb);
I want to create a menu the item, where when the item is clicked then he will disappears temporarily. as an example: I make a menu GpsOn and GpsOff, if the GpsOn clicked then he would disappears and the only remaining GpsOff, and conversely. is there any tutorial or code that can help me??
My Code :
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
// TODO Auto-generated method stub
if(isGpsOn){menu.getItem(MENU_GpsOn).setVisible(false);menu.getItem(MENU_GpsOff).setVisible(true);}
else { menu.getItem(MENU_GpsOn).setVisible(true);menu.getItem(MENU_GpsOff).setVisible(false);}
return super.onPrepareOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
session = new SessionManager(getApplicationContext());
session.checkLogin();
HashMap<String, String> user = session.getUserDetails();
String name = user.get(SessionManager.KEY_NAME);
switch (item.getItemId()) {
case MENU_Secure:
try {
sendSMS(name, "secure");
} catch (Exception e) {
Toast.makeText(this, "Gagal karena " + e.toString(),
Toast.LENGTH_SHORT).show();
e.printStackTrace();
}
return(true);
case MENU_Unsecure:
try {
sendGPS(name, "notsec");
} catch (Exception e) {
Toast.makeText(this, "Gagal karena " + e.toString(),
Toast.LENGTH_SHORT).show();
e.printStackTrace();
}
return(true);
case MENU_GpsOn:
try {
sendMobil(name, "gps on");
} catch (Exception e) {
Toast.makeText(this, "Gagal karena " + e.toString(),
Toast.LENGTH_SHORT).show();
e.printStackTrace();
}
isGpsOn=true;
// ((MenuItem)findViewById(MENU_GpsOff)).setVisible(false);
return(true);
case MENU_GpsOff:
try {
sendGPSOff(name, "gpsoff");
} catch (Exception e) {
Toast.makeText(this, "Gagal karena " + e.toString(),
Toast.LENGTH_SHORT).show();
e.printStackTrace();
}
isGpsOn=false;
return(true);
}
return(super.onOptionsItemSelected(item));
}
Try this,
public boolean checkHide = false
#Override
public boolean onOptionsItemSelected(MenuItem item){
switch(item.getItemId()){
case GPS:
if(checkHide){
checkHide=false;
item.setTitle("GPS_ON");
// ToDo your function
}
else{
checkHide=true;
item.setTitle("GPS_OFF");
// ToDo your function
}
}
What I think you need is Toggle Button. To create one such button, take a look at this tut here, as well as this one and this one.
This is of course, if I understood your requirements correctly.
Firstly I wan't you to know that I search really hard for my problem but I found nothing ...
I can't connect to sql server express instance with android application however I try to connect with jdbc:jtds:sqlserver the driver of sourceforge.
I don't forget to add this line in the manifest file :
<uses-permission android:name="android.permission.INTERNET" />
And the error message is Unable to get information from sql server :HostName
Here my source code perhaps there is something wrong :
public class MainActivitySF extends Activity {
private Connection connection;
private Statement statement;
private ResultSet resultat;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
public void OnClick(View v) {
TextView tv = (TextView) findViewById(R.id.textView1);
EditText ehost = (EditText) findViewById(R.id.ehost);
EditText eport = (EditText) findViewById(R.id.eport);
EditText ebase = (EditText) findViewById(R.id.ebase);
EditText euser = (EditText) findViewById(R.id.euser);
EditText epasswd = (EditText) findViewById(R.id.epasswd);
switch (v.getId()) {
case R.id.Connection:
try {
Class.forName("net.sourceforge.jtds.jdbc.Driver").newInstance();
} catch (InstantiationException e){
Toast.makeText(this, "Instantiation failled",
Toast.LENGTH_LONG).show();
return;
} catch (ClassNotFoundException e1) {
Toast.makeText(this, "Instantiation failled",
Toast.LENGTH_LONG).show();
return;
} catch(IllegalAccessException e2){
Toast.makeText(this, "Instantiation failled",
Toast.LENGTH_LONG).show();
return;
}
try {
String connString = "jdbc:jtds:sqlserver://"+ehost.getText().toString()+"" +
":"+eport.getText().toString()+"/"+ebase.getText().toString()+"" +
";encrypt=false;user="+euser.getText().toString()+";" +
"password="+epasswd.getText().toString()+";instance=SQLEXPRESS;";
String username = euser.getText().toString();
String password = epasswd.getText().toString();
connection = DriverManager.getConnection(connString,username,password);
} catch (SQLException e) {
connection = null;
Toast.makeText(this, "connection failled",
Toast.LENGTH_LONG).show();
tv.setText(e.getLocalizedMessage());
return;
}
tv.setText("connection OK !!");
break;
case R.id.statement:
try {
statement = connection.createStatement();
} catch (SQLException e) {
statement=null;
Toast.makeText(this, "statement failled",
Toast.LENGTH_LONG).show();
return;
}
tv.setText("statement OK !!");
break;
case R.id.req:
try {
resultat = statement.executeQuery(
"SELECT * FROM produits");
tv.setText(resultat.getString("LIB_PRODUIT")+ " OK !!");
} catch (SQLException e) {
Toast.makeText(this, "req failled",
Toast.LENGTH_LONG).show();
return;
}
break;
default:
break;
}
}
}