I am trying to update my existing Android Application to work on both mobile phone and Tablet. So I want to change the Activity class to fragment. The below is my activity class.
Individual Activity class
package FXPAL.Unity.Android;
import FXPAL.Unity.Android.Person.CalendarEntry;
import FXPAL.Unity.Android.Person.IM;
import FXPAL.Unity.Android.Person.Person;
import FXPAL.Unity.Android.Person.Status;
import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.preference.PreferenceManager;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;
import android.widget.Toast;
public class IndividualViewActivity extends Activity {
private static final String DB_TAG = "IndividualView";
//private static final String DB_TAG_PING = "ShowPingView";
private TextView displayName, presence, phoneNum, cellNum, emailAddr, btLocation, calInfo, status;
private ImageView userImage;
private Person personToDisplay;
private String phoneNumber, cellNumber, username, emailAddress;
private TableRow fxpalIMrow, skypeIMrow, msLiveIMrow, gtalkIMrow;
private TableLayout imTable;
private TextView fxpalIMstatus, skypeIMstatus, msLiveIMstatus, gtalkIMstatus, pingText;
private Button nudgeButton, pingButton, clearPingButton, calendarButton;
private LinearLayout pingLayout, pingNudgeButtonLayout;
protected String numToCall, numtype;
private DatabaseHelper db;
//private int pingID = -1;
private UnityMobileApp appCtx;
private static final int DIALOG_CALL_OFFICE_ID = 0;
private static final int DIALOG_CALL_CELL_ID = 1;
protected static final int DIALOG_VIEW_CALENDAR = 2;
private static final int REFRESH_MENU_ID = 0;
protected static final String OFFICE = "office";
private static final String CELL = "cell";
protected static final int MESSAGE_CONNECTION_ERROR_TOAST = 0;
//private static final String DEBUG_TAG = "unity.IndividualViewActivity";
private final Handler mHandler = new Handler() {
public void handleMessage(Message msg) {
switch (msg.what) {
case MESSAGE_CONNECTION_ERROR_TOAST:
Toast.makeText(IndividualViewActivity.this, Consts.CONNECTION_ERROR_MESSAGE, Toast.LENGTH_SHORT).show();
break;
}
}
};
private SharedPreferences prefs;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//doBindService();
setContentView(R.layout.individual_view);
db = new DatabaseHelper(this);
appCtx = (UnityMobileApp) getApplication();
prefs = PreferenceManager.getDefaultSharedPreferences(this);
//Setup View
displayName = (TextView)findViewById(R.id.individualName);
presence = (TextView)findViewById(R.id.individualPresence);
userImage = (ImageView)findViewById(R.id.individualUserImage);
phoneNum = (TextView)findViewById(R.id.individualPhone);
cellNum = (TextView)findViewById(R.id.individualCellPhone);
emailAddr = (TextView)findViewById(R.id.individualEmail);
btLocation = (TextView)findViewById(R.id.individualLocation);
calInfo = (TextView)findViewById(R.id.individualCalendarInfo);
status = (TextView)findViewById(R.id.individualStatus);
fxpalIMrow = (TableRow)findViewById(R.id.im_fxpal);
skypeIMrow = (TableRow)findViewById(R.id.im_skype);
msLiveIMrow = (TableRow)findViewById(R.id.im_ms_live);
gtalkIMrow = (TableRow)findViewById(R.id.im_gtalk);
fxpalIMstatus = (TextView)findViewById(R.id.im_status_fxpal);
skypeIMstatus = (TextView)findViewById(R.id.im_status_skype);
msLiveIMstatus = (TextView)findViewById(R.id.im_status_ms_live);
gtalkIMstatus = (TextView)findViewById(R.id.im_status_gtalk);
imTable = (TableLayout)findViewById(R.id.individualIMStatus);
nudgeButton = (Button)findViewById(R.id.individual_nudge_button);
pingButton = (Button) findViewById(R.id.individual_ping_button);
calendarButton = (Button)findViewById(R.id.individualViewCalendarButton);
pingText = (TextView)findViewById(R.id.individualPingText);;
clearPingButton = (Button) findViewById(R.id.individualClearPingButton);
pingLayout = (LinearLayout)findViewById(R.id.individualPingInfo);
pingNudgeButtonLayout = (LinearLayout)findViewById(R.id.individual_nudge_ping_layout);
calendarButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
showDialog(DIALOG_VIEW_CALENDAR);
db.viewEvent(DB_TAG + ":CalendarDialog", username);
}
});
nudgeButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
startActivity(new Intent(IndividualViewActivity.this, SendNudgeActivity.class)
.putExtra(Consts.EXTRA_USERNAME, personToDisplay.getUsername())
.putExtra(Consts.EXTRA_DISPLAY_NAME, personToDisplay.getDisplayName()));
}
});
pingButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
startActivity(new Intent(IndividualViewActivity.this, SendPingActivity.class)
.putExtra(Consts.EXTRA_USERNAME, personToDisplay.getUsername())
.putExtra(Consts.EXTRA_DISPLAY_NAME, personToDisplay.getDisplayName()));
}
});
}
public void onPause(){
super.onPause();
}
public void onDestroy(){
super.onDestroy();
//doUnbindService();
db.close();
}
public void onResume(){
super.onResume();
Intent mIntent = getIntent();
username = mIntent.getStringExtra(Consts.EXTRA_USERNAME);
if(username.equalsIgnoreCase(prefs.getString(Consts.PREF_USERNAME, "")))
pingNudgeButtonLayout.setVisibility(View.GONE);
else
pingNudgeButtonLayout.setVisibility(View.VISIBLE);
personToDisplay = appCtx.getEveryone().get(username);
updateView();
updateInfo();
if (personToDisplay == null || personToDisplay.getCalendar() == null ||
personToDisplay.getCalendar().getCalendar().size() == 0)
calendarButton.setEnabled(false);
else
calendarButton.setEnabled(true);
db.viewEvent(DB_TAG, username);
pingLayout.setVisibility(View.GONE);
//}
}
private void updateInfo(){
ServerHelper.RequestListener listener = new ServerHelper.RequestListener() {
public void onCompleted(ServerHelper.Request request) {
if (request.isUnauthorized())
startActivity(new Intent(IndividualViewActivity.this, LoginActivity.class));
else if (request.isSuccess()) {
Person.PersonHelper.getEveryoneAsync(IndividualViewActivity.this, appCtx.everyone, null, request.getResponseString(),
new Runnable() {
public void run () {
personToDisplay = appCtx.everyone.get(username);
updateView();
}
});
}
}
};
ServerHelper.appCtx = appCtx;
ServerHelper.getStatus (prefs, listener);
}
private void updateView(){
if (personToDisplay == null)
return;
displayName.setText(personToDisplay.getDisplayName());
presence.setText(personToDisplay.getPresenceState());
Status mStatus = personToDisplay.getStatus();
if( mStatus!= null && mStatus.toString().length()>0){
status.setVisibility(View.VISIBLE);
status.setText(mStatus.toString());
}
userImage.setImageBitmap(personToDisplay.getRoundedImage(Consts.LARGE_USER_IMAGE_SIZE, Consts.LARGE_USER_IMAGE_BORDER));
phoneNumber = personToDisplay.getPhoneNum();
if(phoneNumber.length()>0){
phoneNum.setText(OFFICE + ": " + phoneNumber);
phoneNum.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
numToCall = phoneNumber;
numtype = OFFICE;
showDialog(DIALOG_CALL_OFFICE_ID);
}
});}
else
phoneNum.setVisibility(View.GONE);
cellNumber = personToDisplay.getCellPhoneNum();
if(cellNumber.length()>0){
cellNum.setText(CELL + ": " + cellNumber);
cellNum.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
numToCall = cellNumber;
numtype = CELL;
showDialog(DIALOG_CALL_CELL_ID);
}
});}
else
cellNum.setVisibility(View.GONE);
emailAddress = personToDisplay.getEmailAddress();
emailAddr.setText(emailAddress);
emailAddr.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
db.communicate(DB_TAG, "email", username);
Intent emailIntent = new Intent();
emailIntent.setAction(android.content.Intent.ACTION_SENDTO);
emailIntent.setData(Uri.parse("mailto:" + emailAddress));
startActivity(Intent.createChooser(emailIntent, "Select Email Client"));
}
});
if(personToDisplay.hasLocation()){
btLocation.setVisibility(View.VISIBLE);
btLocation.setText(personToDisplay.getLocation().toString());
}
CalendarEntry usefulCalInfo = personToDisplay.getCalendar().getMostUseful();
if(usefulCalInfo != null){
calInfo.setVisibility(View.VISIBLE);
calInfo.setText("Calendar: " + usefulCalInfo.toString());
}
if(personToDisplay.hasIM()){
imTable.setVisibility(View.VISIBLE);
}
for(IM mIM : personToDisplay.getIMList().values()){
switch(mIM.getId()){
case(IM.FXPAL_ID):
fxpalIMrow.setVisibility(View.VISIBLE);
fxpalIMstatus.setText(mIM.getStatus());
break;
case(IM.SKYPE_ID):
skypeIMrow.setVisibility(View.VISIBLE);
skypeIMstatus.setText(mIM.getStatus());
break;
case(IM.MS_LIVE_ID):
msLiveIMrow.setVisibility(View.VISIBLE);
msLiveIMstatus.setText(mIM.getStatus());
break;
case(IM.GTALK_ID):
gtalkIMrow.setVisibility(View.VISIBLE);
gtalkIMstatus.setText(mIM.getStatus());
break;
default:
}
}
}
protected Dialog onCreateDialog(int id) {
Dialog dialog = null;
switch(id) {
case DIALOG_CALL_OFFICE_ID:
case DIALOG_CALL_CELL_ID:
dialog = CommDialog.getCallDialog(displayName.getText().toString(), numToCall, numtype, IndividualViewActivity.this, db);
break;
case DIALOG_VIEW_CALENDAR:
return CalendarListDialog.getDialog(username, IndividualViewActivity.this, appCtx);
default:
dialog = null;
}
return dialog;
}
public boolean onCreateOptionsMenu(Menu menu){
menu.add(Menu.NONE, REFRESH_MENU_ID, Menu.NONE, "Refresh")
.setIcon(R.drawable.ic_menu_refresh)
.setAlphabeticShortcut('r');
return(super.onCreateOptionsMenu(menu));
}
#Override
public boolean onOptionsItemSelected(MenuItem item){
switch (item.getItemId()) {
case REFRESH_MENU_ID:
refresh();
break;
}
return (super.onOptionsItemSelected(item));
}
void refresh() {
// update the location and report it to the server
ReportingService.startLocationRequest(appCtx, true);
// this may still retrieve the old location
updateInfo();
}
}
Please help me guys. I am stuck with this problem since long time.
Regards,
Rakesh
Related
I want to create a way which will add item to cart by creating a child cart the in that child it will retrieve current username and then under that it will save all the details of added item
this is the code of the fragment in which cart button is available (course = description,email = price,purl = url of image)
import android.os.Bundle;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import com.bumptech.glide.Glide;
public class descfragment extends Fragment {
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
private String mParam1;
private String mParam2;
String name, course, email, purl;
public descfragment() {
}
public descfragment(String name, String course, String email, String purl) {
this.name = name;
this.course = course;
this.email = email;
this.purl = purl;
}
public static descfragment newInstance(String param1, String param2) {
descfragment fragment = new descfragment();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_descfragment, container, false);
view.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
AppCompatActivity activity =(AppCompatActivity)getContext();
activity.getSupportFragmentManager().beginTransaction().replace(R.id.wrapper,new recfragment()).addToBackStack(null).commit();
}
});
ImageView imageholder = view.findViewById(R.id.imageholder);
TextView nameholder = view.findViewById(R.id.nameholder);
TextView courseholder = view.findViewById(R.id.courseholder);
TextView emailholder = view.findViewById(R.id.emailholder);
Button cart = view.findViewById(R.id.cartt);
TextView addItem = view.findViewById(R.id.addIteam);
TextView removeItem = view.findViewById(R.id.removeItem);
TextView quantity = view.findViewById(R.id.quantity);
final int[] totalquantity = {1};
nameholder.setText(name);
courseholder.setText(course);
emailholder.setText(email);
if (imageholder != null) {
Glide.with(getContext()).load(purl).into(imageholder);
}
Glide.with(getContext()).load(purl).into(imageholder);
//changing static getemail to int type
//for openig cart
//setting click on textview for increasing the quantity
addItem.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(totalquantity[0] < 10){
totalquantity[0]++;
quantity.setText(String.valueOf(totalquantity[0]));
}
}
});
removeItem.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(totalquantity[0] > 1) {
totalquantity[0]--;
quantity.setText(String.valueOf(totalquantity[0]));
}
}
});
return view;
}
#Override
public void onResume() {
super.onResume();
getView().setFocusableInTouchMode(true);
getView().requestFocus();
getView().setOnKeyListener((v, keyCode, event) -> {
if (event.getAction() == KeyEvent.ACTION_UP && keyCode == KeyEvent.KEYCODE_BACK) {
AppCompatActivity activity = (AppCompatActivity) getContext();
activity.getSupportFragmentManager().beginTransaction().replace(R.id.wrapper, new recfragment()).addToBackStack(null).commit();
return true;
}
return false;
});
}
}
this is the register activity code in this activity we have the username which needed to be retirived
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.example.foodcourt.MainActivity;
import com.example.foodcourt.R;
import com.google.android.material.textfield.TextInputLayout;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
public class register extends AppCompatActivity {
Button button5;
//create obj of Databaserefrence to access firebase RealTime Database
DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReferenceFromUrl("https://url of firebase database/");
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
final TextInputLayout nameLayout = findViewById(R.id.Name);
final TextInputLayout phoneLayout = findViewById(R.id.phone);
final TextInputLayout passwordLayout = findViewById(R.id.password);
final TextInputLayout repassLayout = findViewById(R.id.repass);
final Button signup = findViewById(R.id.sign);
final EditText name = nameLayout.getEditText();
final EditText phone = phoneLayout.getEditText();
final EditText password = passwordLayout.getEditText();
final EditText repass = repassLayout.getEditText();
signup.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//get data from editTexts into string
final String nameTxt = name.getText().toString();
final String phoneTxt = phone.getText().toString();
final String passwordTxt = password.getText().toString();
final String repassTxt = repass.getText().toString();
//Check if user filled all details before sending data to firebase
if (nameTxt.isEmpty() || phoneTxt.isEmpty() || passwordTxt.isEmpty() || repassTxt.isEmpty()) {
Toast.makeText(register.this, "Please fill all fields", Toast.LENGTH_SHORT).show();
}
//check if pass are matching
else if (!passwordTxt.equals(repassTxt)) {
Toast.makeText(register.this, "PASSWORDS ARE NOT MATCHING", Toast.LENGTH_SHORT).show();
} else {
databaseReference.child("users").addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
//check if phone number is registered before \
if (snapshot.hasChild(phoneTxt)) {
Toast.makeText(register.this, "Already registered", Toast.LENGTH_SHORT).show();
} else {
//sending data to Firebase
//using phoneNumbers
databaseReference.child("users").child(phoneTxt).child("name").setValue(nameTxt);
databaseReference.child("users").child(phoneTxt).child("phone").setValue(phoneTxt);
databaseReference.child("users").child(phoneTxt).child("password").setValue(passwordTxt);
Toast.makeText(register.this, "REGISTERED SUCCESFULLY", Toast.LENGTH_SHORT).show();
startActivity(new Intent(register.this, MainActivity.class));
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
}
});
}
}
I followed some tutorials but they were for firestore.
I have a medicine_activity class
package com.example.shubhmgajra.medikit;
import android.content.Intent;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;
public class Medicine_Activity extends AppCompatActivity implements View.OnClickListener {
private static final String TAG = "Medicine_Activity";
private Button btnAdd;
private ListView listMeds;
private AppDatabase db;
private ArrayAdapter<MedicineRecord> arrayAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_medicine);
btnAdd = findViewById(R.id.btnAdd);
btnAdd.setOnClickListener(this);
listMeds = findViewById(R.id.listMeds);
listMeds.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
MedicineRecord medicineRecord = db.medicineRecordDao().findMedicineById(id + 1);
Intent intent = new Intent(getApplicationContext(), MedicineInputActivity.class);
startActivity(intent);
MedicineInputActivity.getInstance().update(medicineRecord, true);
}
});
db = AppDatabase.getInstance(getApplicationContext());
FeedAdapter feedAdapter = new FeedAdapter(Medicine_Activity.this, R.layout.list_record, db.medicineRecordDao().loadAllRecords());
listMeds.setAdapter(feedAdapter);
}
#Override
protected void onResume() {
super.onResume();
}
#Override
public void onClick(View v) {
Intent intent = new Intent(this, MedicineInputActivity.class);
startActivity(intent);
}
}
In this i am trying to call update() method of another activity namely MedicineInputActivity
package com.example.shubhmgajra.medikit;
import android.content.Intent;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TimePicker;
import android.widget.Toast;
public class MedicineInputActivity extends AppCompatActivity implements View.OnClickListener {
private static final String TAG = "MedicineInputActivity";
static EditText dosage;
static EditText medName;
static TimePicker timePicker;
static Button btnSave;
Button btnInc;
Button btnDec;
private AppDatabase db;
private static MedicineInputActivity instance;
boolean isEdit;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_medicine_input);
isEdit = false;
instance = this;
dosage = findViewById(R.id.dosage);
dosage.setShowSoftInputOnFocus(false);
dosage.setCursorVisible(false);
medName = findViewById(R.id.medName);
timePicker = findViewById(R.id.simpleTimePicker);
btnInc = findViewById(R.id.btnInc);
btnDec = findViewById(R.id.btnDec);
btnInc.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String val = dosage.getText().toString();
int tempVal = Integer.parseInt(val);
tempVal++;
dosage.setText("" + tempVal);
}
});
btnDec.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String val = dosage.getText().toString();
int tempVal = Integer.parseInt(val);
if (tempVal > 0) {
tempVal--;
}
dosage.setText("" + tempVal);
}
});
btnSave = findViewById(R.id.btnSave);
btnSave.setOnClickListener(this);
db = AppDatabase.getInstance(getApplicationContext());
}
#Override
public void onClick(View v) {
String name = medName.getText().toString();
int min = timePicker.getMinute();
int hour = timePicker.getHour();
String val = dosage.getText().toString();
int dose = Integer.parseInt(val);
MedicineRecord medicineRecord = new MedicineRecord(name, dose, min, hour);
if (validate(name)) {
if (isEdit) {
db.medicineRecordDao().updateRecord(medicineRecord);
} else {
db.medicineRecordDao().insertRecord(medicineRecord);
}
Intent intent = new Intent(this, Medicine_Activity.class);
startActivity(intent);
} else {
Toast toast = Toast.makeText(getApplicationContext(), "Medicine name cannot be empty", Toast.LENGTH_SHORT);
toast.show();
}
}
private boolean validate(String name) {
if (name.length() == 0) {
return false;
} else {
return true;
}
}
public static MedicineInputActivity getInstance() {
return instance;
}
public void update(MedicineRecord medicineRecord, boolean isEdit) {
this.isEdit = isEdit;
dosage.setText(medicineRecord.getDosage());
medName.setText(medicineRecord.getMedName());
timePicker.setHour(medicineRecord.getHour());
timePicker.setMinute(medicineRecord.getMinute());
}
}
What i am trying to achieve is when the user taps the list item, the input activity is loaded and the user can update the record. I wasnt able to find an elegant solution other than making an update method in MedicineInputActivity and then getting an instance of MedicineInputActivity in Medicine_Activity and calling update.
I am getting errors like "Attempt to invoke virtual method 'void com.example.shubhmgajra.medikit.MedicineInputActivity.update() on a null object reference".
You can return data from second activity to the first activity when user is done updating the record. You should start second activity by calling startActivityForResult() instead of startActivity() in the first activity. You should also override onActivityResult() in the first activity. You can read more here.
UPDATE:
I think you want to send selected medicine details from Medicine_Activity to MedicineInputActivity. In that case, you can send selected medicine object by binding it to the intent as follows:
public class Medicine_Activity ... {
#Override
protected void onCreate(Bundle savedInstanceState) {
...
listMeds.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
MedicineRecord medicineRecord = db.medicineRecordDao().findMedicineById(id + 1);
Intent intent = new Intent(getApplicationContext(), MedicineInputActivity.class);
intent.putExtra("selectedMedicine", medicineRecord);
startActivity(intent);
MedicineInputActivity.getInstance().update(medicineRecord, true);
}
});
...
}
}
Then on MedicineInputActivity, you should be doing this:
public class MedicineInputActivity ... {
MedicineRecord selectedMedicineRecord;
#Override
protected void onCreate(Bundle savedInstanceState) {
...
selectedMedicineRecord = (MedicineRecord) getIntent().getParcelableExtra("selectedMedicine");
...
}
}
To be able to do this, your MedicineRecord class should implement Parcelable interface.
this is the view that crashes when i click start but i dont know why
i think it has something to do with the threding in the bruteForce function
package com.my.app;
import android.app.*;
import android.os.*;
import android.view.*;
import android.view.View.*;
import android.widget.*;
import android.content.*;
import android.graphics.*;
import android.media.*;
import android.net.*;
import android.text.*;
import android.util.*;
import java.util.*;
import java.text.*;
import android.test.*;
import android.view.animation.*;
import android.widget.Button;
public class TestActivity extends Activity {
private LinearLayout linear1;
private TextView original;
private TextView match;
private TextView text;
private Button bstart;
String attempt = new String();
boolean running;
int counter;
private String hash = "";
public String username = new String();
public static String password = "ZZZZZ";
public static char[] charset = "ABCDEFGHIJKLMNOPQRSTUVWXYZ".toCharArray();
private static char[] currentGuess = new char[1];
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.test);
initialize();
initializeLogic();
}
private void initialize() {
linear1 = (LinearLayout) findViewById(R.id.linear1);
original = (TextView) findViewById(R.id.original);
match = (TextView) findViewById(R.id.match);
text = (TextView) findViewById(R.id.text);
bstart = (Button) findViewById(R.id.bstart);
bstart.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View _v) {
bruteForce();
}
});
}
private void initializeLogic() {
Intent test = getIntent();
hash = test.getStringExtra("hash");
original.setText(password);
}
public void increment()
{
int index = currentGuess.length - 1;
while (index >= 0)
{
if (currentGuess[index] == charset[charset.length - 1])
{
if (index == 0)
{
currentGuess = new char[currentGuess.length + 1];
Arrays.fill(currentGuess, charset[0]);
break;
}
else
{
currentGuess[index] = charset[0];
index--;
}
}
else
{
currentGuess[index] = charset[Arrays.binarySearch(charset, currentGuess[index]) + 1];
break;
}
}
}
public String toString()
{
return String.valueOf(currentGuess);
}
public void bruteForce()
{
Animation animation = new Animation(){
#Override
protected void applyTransformation(float interpolatedTime, Transformation t) {
text.setText(attempt);
}
};
animation.setRepeatCount(Animation.INFINITE);
text.startAnimation(animation);
new Thread(){
#Override
public void run() {
running = true;
while(running)
if (attempt.equals(password))
{
text.setText(attempt);
this.stop();
}
attempt = toString();
text.setText(attempt);
increment();
}
}.start();
}
#Override
protected void onStop() {
super.onStop();
running = false;
}
public void BruteForceTest()
{
Arrays.fill(currentGuess, charset[0]);
}
// created automatically
private void ShowMessage(String _s) {
Toast.makeText(getApplicationContext(), _s, Toast.LENGTH_SHORT).show();
}
private int GetRandom(int _minValue ,int _maxValue){
Random random = new Random();
return random.nextInt(_maxValue - _minValue + 1) + _minValue;
}
public ArrayList<Integer> getCheckedItemPositionsToArray(ListView _list) {
ArrayList<Integer> _result = new ArrayList<Integer>();
SparseBooleanArray _arr = _list.getCheckedItemPositions();
for (int _iIdx = 0; _iIdx < _arr.size(); _iIdx++) {
if (_arr.valueAt(_iIdx))
_result.add(_arr.keyAt(_iIdx));
}
return _result;
}
}
Your problem lies here
new Thread(){
#Override
public void run() {
running = true;
while(running)
if (attempt.equals(password))
{
text.setText(attempt);
this.stop();
}
attempt = toString();
text.setText(attempt);
increment();
}
}.start();
You can only update an UI element from the main thread. If you want to do it likes this you need to wrap text.setText(attempt) with a handler that posts it to the main thread. e.g.
new Handler(Looper.getMainLooper()).post(new Runnable(){
void run() {
text.setText(attempt);
}
});
Looper.getMainLooper() (docs) will get the main application thread which the handler then posts the Runnable to .
if (attempt.equals(password))
{
getActivity().runOnUiThread(new Runnable()
{
#Override
public void run()
{
text.setText(attempt);
}
});
this.stop();
}
Similarly wherever you are changing ui elements like setting text or changin colors do it in runOnUithread as I did above.
Below the code I used:
Activitymain_txt.java
import android.content.ActivityNotFoundException;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Configuration;
import android.database.ContentObserver;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.NavigationView;
import android.support.design.widget.Snackbar;
import android.support.design.widget.TabLayout;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBar;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.SearchView;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Toast;
import com.example.apple.qs.Activity.db.Constant;
import com.example.apple.qs.Activity.db.DatabaseHandler_txt;
import com.example.apple.qs.Activity.fragment.ContactFragment;
import com.example.apple.qs.Activity.fragment.FragmentAdapter;
import com.example.apple.qs.Activity.fragment.MessageFragment;
import com.example.apple.qs.Activity.db.model.Message;
import com.example.apple.qs.Activity.db.Store.ContactStore;
import com.example.apple.qs.Activity.db.Store.MessageStore;
import java.util.ArrayList;
import com.example.apple.qs.Activity.R;
import java.util.List;
public class ActivityMain_txt extends AppCompatActivity {
private ActionBarDrawerToggle mDrawerToggle;
private Toolbar toolbar;
private DrawerLayout drawerLayout;
public static MessageFragment f_message;
private ContactFragment f_contact;
public FloatingActionButton fab;
private Toolbar searchToolbar;
private boolean isSearch = false;
private ViewPager viewPager;
private DatabaseHandler_txt db;
public ContactStore contacsStore;
public MessageStore messageStore;
public static List<Message> messageList = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_txt);
setupDrawerLayout();
db = new DatabaseHandler_txt(getApplicationContext());
toolbar = (Toolbar) findViewById(R.id.toolbar_viewpager);
searchToolbar = (Toolbar) findViewById(R.id.toolbar_search);
fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent i = new Intent(getApplicationContext(), ActivityNewMessage_txt.class);
startActivity(i);
}
});
//initToolbar();
prepareActionBar(toolbar);
contacsStore = new ContactStore(getApplicationContext());
messageStore = new MessageStore(ActivityMain_txt.this);
messageList = messageStore.getAllconversation();
viewPager = (ViewPager) findViewById(R.id.viewpager);
if (viewPager != null) {
setupViewPager(viewPager);
}
TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(viewPager);
tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
closeSearch();
viewPager.setCurrentItem(tab.getPosition());
if (tab.getPosition() == 0) {
fab.show();
} else {
fab.hide();
}
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
// for system bar in lollipop
Window window = this.getWindow();
if (Constant.getAPIVerison() >= 5.0) {
window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
window.setStatusBarColor(this.getResources().getColor(R.color.colorPrimaryDark));
}
}
private void setupViewPager(ViewPager viewPager) {
FragmentAdapter adapter = new FragmentAdapter(getSupportFragmentManager());
if (f_message == null) {
f_message = new MessageFragment();
}
if (f_contact == null) {
f_contact = new ContactFragment();
}
adapter.addFragment(f_message, "MESSAGE");
adapter.addFragment(f_contact, "CONTACT");
viewPager.setAdapter(adapter);
}
private void prepareActionBar(Toolbar toolbar) {
setSupportActionBar(toolbar);
ActionBar actionBar = getSupportActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setHomeButtonEnabled(true);
if (Build.VERSION.SDK_INT >= 21) {
getWindow().setStatusBarColor(getResources().getColor(isSearch ? android.R.color.darker_gray : R.color.colorPrimary));
}
if (!isSearch) {
settingDrawer();
}
}
private void settingDrawer() {
mDrawerToggle = new ActionBarDrawerToggle( this, drawerLayout, toolbar, R.string.drawer_open, R.string.drawer_close ) {
/** Called when a drawer has settled in a completely closed state. */
public void onDrawerClosed(View view) {
super.onDrawerClosed(view);
}
/** Called when a drawer has settled in a completely open state. */
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
}
};
// Set the drawer toggle as the DrawerListener
drawerLayout.setDrawerListener(mDrawerToggle);
}
private void setupDrawerLayout() {
drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
NavigationView view = (NavigationView) findViewById(R.id.nav_view);
view.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
menuItem.setChecked(true);
drawerLayout.closeDrawers();
actionDrawerMenu(menuItem.getItemId());
return true;
}
});
}
private void actionDrawerMenu(int itemId) {
switch (itemId) {
case R.id.nav_notif:
Intent i = new Intent(getApplicationContext(), ActivityNotificationSettings_txt.class);
startActivity(i);
break;
case R.id.nav_rate:
Uri uri = Uri.parse("market://details?id=" + getPackageName());
Intent goToMarket = new Intent(Intent.ACTION_VIEW, uri);
try {
startActivity(goToMarket);
} catch (ActivityNotFoundException e) {
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("http://play.google.com/store/apps/details?id=" + getPackageName())));
}
break;
case R.id.nav_about:
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("About");
builder.setMessage(getString(R.string.about_text));
builder.setNeutralButton("OK", null);
builder.show();
break;
}
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
// Sync the toggle state after onRestoreInstanceState has occurred.
mDrawerToggle.syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
if (!isSearch) {
mDrawerToggle.onConfigurationChanged(newConfig);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(isSearch ? R.menu.menu_search_toolbar_txt : R.menu.menu_main_txt, menu);
if (isSearch) {
//Toast.makeText(getApplicationContext(), "Search " + isSearch, Toast.LENGTH_SHORT).show();
final SearchView search = (SearchView) menu.findItem(R.id.action_search).getActionView();
search.setIconified(false);
if (viewPager.getCurrentItem() == 0) {
search.setQueryHint("Search message...");
} else {
search.setQueryHint("Search contact...");
}
search.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String s) {
return false;
}
#Override
public boolean onQueryTextChange(String s) {
if (viewPager.getCurrentItem() == 0) {
f_message.mAdapter.getFilter().filter(s);
} else {
f_contact.mAdapter.getFilter().filter(s);
}
return true;
}
});
search.setOnCloseListener(new SearchView.OnCloseListener() {
#Override
public boolean onClose() {
closeSearch();
return true;
}
});
}
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
switch (id) {
case R.id.action_search: {
isSearch = true;
searchToolbar.setVisibility(View.VISIBLE);
prepareActionBar(searchToolbar);
supportInvalidateOptionsMenu();
return true;
}
case android.R.id.home:
closeSearch();
return true;
case R.id.action_refresh: {
if(viewPager.getCurrentItem()==0){
new RefreshMessage().execute("");
}else{
new RefreshContact().execute("");
}
}
default:
return super.onOptionsItemSelected(item);
}
}
private void closeSearch() {
if (isSearch) {
isSearch = false;
if (viewPager.getCurrentItem() == 0) {
f_message.mAdapter.getFilter().filter("");
} else {
f_contact.mAdapter.getFilter().filter("");
}
prepareActionBar(toolbar);
searchToolbar.setVisibility(View.GONE);
supportInvalidateOptionsMenu();
}
}
private long exitTime = 0;
public void doExitApp() {
if ((System.currentTimeMillis() - exitTime) > 2000) {
Toast.makeText(this, R.string.press_again_exit_app, Toast.LENGTH_SHORT).show();
exitTime = System.currentTimeMillis();
} else {
finish();
}
}
#Override
public void onResume(){
try{
Uri uri = MessageStore.URI;
changeObserver = new ChangeObserver();
this.getContentResolver().registerContentObserver(uri, true, changeObserver);
}catch (Exception e){
}
super.onResume();
}
#Override
protected void onRestart() {
try{
f_message.bindView();
}catch (Exception e){
}
super.onRestart();
}
#Override
public void onPause(){
this.getContentResolver().unregisterContentObserver(changeObserver);
super.onPause();
}
#Override
public void onBackPressed() {
doExitApp();
}
private ChangeObserver changeObserver;
// wil update only when there a change
private class ChangeObserver extends ContentObserver {
public ChangeObserver() {
super(new Handler());
}
#Override
public void onChange(boolean selfChange) {
try{
if(!loadRunning) {
loadRunning = true;
changeLoad = new ChangeLoad();
changeLoad.execute("");
}
}catch (Exception e){
}
}
}
private ChangeLoad changeLoad;
private boolean loadRunning = false;
private class ChangeLoad extends AsyncTask<String, String, String>{
#Override
protected String doInBackground(String... strings) {
messageStore.update();
return null;
}
#Override
protected void onPostExecute(String s) {
loadRunning = false;
messageList = messageStore.getAllconversation();
f_message.bindView();
super.onPostExecute(s);
}
}
private class RefreshMessage extends AsyncTask<String, String, String>{
#Override
protected void onPreExecute() {
f_message.onRefreshLoading();
super.onPreExecute();
}
#Override
protected String doInBackground(String... strings) {
try {
Thread.sleep(100);
messageStore = new MessageStore(ActivityMain_txt.this);
messageList = messageStore.getAllconversation();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String s) {
f_message.onStopRefreshLoading();
super.onPostExecute(s);
}
}
private class RefreshContact extends AsyncTask<String, String, String>{
#Override
protected void onPreExecute() {
f_contact.onRefreshLoading();
super.onPreExecute();
}
#Override
protected String doInBackground(String... strings) {
try {
Thread.sleep(10);
db.truncateDB();
contacsStore = new ContactStore(getApplicationContext());
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String s) {
f_contact.onStopRefreshLoading();
super.onPostExecute(s);
}
}
}
ContactStore.java
import android.content.ContentResolver;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.provider.ContactsContract;
import com.example.apple.qs.Activity.db.DatabaseHandler_txt;
import com.example.apple.qs.Activity.db.model.Contact;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
public class ContactStore {
private static Context ctx;
private static ContentResolver sResolver;
private static final String TAG = "ContactStore";
private DatabaseHandler_txt db;
private List<Contact> allContacts = new ArrayList<>();
public ContactStore(Context context) {
ctx = context;
sResolver = ctx.getContentResolver();
db = new DatabaseHandler_txt(context);
// populate contact to database when first time
if(db.isDatabaseEmpty()){
//init contact data
retriveAllContact();
// save to database
db.addListContact(allContacts);
}else{
allContacts.clear();
allContacts = db.getAllContacts();
}
Collections.sort(allContacts, new Comparator<Contact>() {
#Override
public int compare(Contact c1, Contact c2) {
String l1 = c1.name.toLowerCase();
String l2 = c2.name.toLowerCase();
return l1.compareTo(l2);
}
});
}
public Contact getByRecipientId(long recipientId) {
Cursor addrCursor = sResolver.query(Uri.parse("content://mms-sms/canonical-address/" + recipientId), null,null, null, null);
addrCursor.moveToFirst();
String number = addrCursor.getString(0); // we got number here
number=number.replace(" ", "");
number=number.replace("-", "");
Contact c = db.findContactByNumber(number);
return c;
}
public List<Contact> getAllContacts() {
return allContacts;
}
public Contact getDetailsContact(Contact c){
return db.getDetailsContact(c);
}
private void retriveAllContact() {
ContentResolver cr = ctx.getContentResolver();
Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null);
if (cur.getCount() > 0) {
while (cur.moveToNext()) {
long id = cur.getLong(cur.getColumnIndex(ContactsContract.Contacts._ID));
String name = cur.getString(cur.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
String photoId;
try {
photoId = cur.getString(cur.getColumnIndex(ContactsContract.Data.PHOTO_URI));
} catch (Exception e) {
photoId = "";
}
if (Integer.parseInt(cur.getString(cur.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0) {
List<String> phones = new ArrayList<>();
Cursor cursor = cr.query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ?",
new String[]{id+""}, null);
while (cursor.moveToNext()){
String p = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
p=p.replace(" ", "");
p=p.replace("-", "");
if(!phones.contains(p)){
phones.add(p);
}
}
Contact c = new Contact();
c.id = id;
c.name = name;
c.photoUri = photoId;
c.allPhoneNumber = phones;
allContacts.add(c);
cursor.close();
}
}
}
}
}
MessageStore.java
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import com.example.apple.qs.Activity.Activity.ActivityMain_txt;
import com.example.apple.qs.Activity.db.Constant;
import com.example.apple.qs.Activity.db.SharedPref_txt;
import com.example.apple.qs.Activity.db.model.Contact;
import com.example.apple.qs.Activity.db.model.Message;
import com.example.apple.qs.Activity.receiver.BedgeNotifier;
import java.util.ArrayList;
import java.util.List;
public class MessageStore {
public static final Uri URI = Uri.parse("content://mms-sms/conversations?simple=true");
public static final Uri URI_SMS = Uri.parse("content://sms");
private ContentResolver mResolver;
public static List<Message> allconv = new ArrayList<>();
static Cursor cursor = null;
private ContactStore contactStore;
private ActivityMain_txt act;
private Context ctx;
private static final String TAG = "/ConvStore";
public static final String[] PROJECTION = new String[] {
"_id",
"date",
"message_count",
"recipient_ids",
"snippet",
"read",
"type"
};
public MessageStore(ActivityMain_txt act) {
this.ctx = act.getApplicationContext();
this.act = act;
contactStore = new ContactStore(ctx);
mResolver = ctx.getContentResolver();
allconv = new ArrayList<>(20);
cursor = mResolver.query(URI,
PROJECTION,
null,
null,
"date DESC"
);
// cursor.registerContentObserver(new ChangeObserver());
retrieveAllConversation();
}
private void retrieveAllConversation(){
update();
}
public void update() {
int unread_counter = 0;
allconv.clear();
cursor.requery();
if(cursor == null || cursor.getCount() == 0) {
return;
}
if (cursor!= null && cursor.moveToFirst()){
cursor.moveToFirst();
do {
Message conv = new Message();
conv.threadId = cursor.getLong(0);
conv.date = cursor.getLong(1);
conv.msgCount = cursor.getInt(2);
conv.snippet = cursor.getString(4);
conv.read = cursor.getInt(5) == 1;
if(!conv.read){
unread_counter++;
}
if(!allconv.contains(conv)) {
allconv.add(conv);
}
int recipient_id = cursor.getInt(3);
Contact recipient = contactStore.getByRecipientId(recipient_id);
conv.contact = recipient;
} while(cursor.moveToNext()); }
SharedPref_txt.setIntPref(Constant.I_KEY_UNREAD_COUNT, unread_counter, ctx);
BedgeNotifier.setBadge(ctx, unread_counter);
}
public List<Message> getAllconversation() {
return allconv;
}
public void markAsRead(long threadId) {
ContentValues cv = new ContentValues(1);
cv.put("read", 1);
mResolver.update(URI_SMS,
cv,
"read=0 AND thread_id=" + threadId,
null
);
}
/**
* Find conversation by phone number
*
* #return conversation id, new id will be assigned if not exist
**/
public static long getOrCreateConversationId(Context context, String number){
long cid = -1;
Uri uri = Uri.parse("content://sms");
Cursor cur = context.getContentResolver().query(
uri,
new String[] {"thread_id"},
"address =?",
new String[] { number},
null);
if(cur!=null){
if(cur.moveToFirst()){
cid = cur.getLong(0);
}
cur.close();
}
// Allocate new conversation_id if no match
if(cid==-1){
cur = context.getContentResolver().query(
uri,
new String[] {"thread_id"},
null,
null,
"thread_id DESC ");
if(cur!=null){
if(cur.moveToFirst()){
// new conversation_id = Max(conversation_id)+1
cid = cur.getLong(0)+1;
}
cur.close();
}
// no entry in the database, start the id from 10 in case smaller numbers are reserved
if(cid==-1){
cid=10;
}
}
return cid;
}
public static boolean deleteMessage(Context context, String threadId) {
int result;
result = context.getContentResolver().delete(URI_SMS, "thread_id = ?", new String[] { threadId });
if (result > 0) {
return true;
}
return false;
}
}
Log Message
I have no idea how to solve the issue of android.database.CursorIndexOutOfBoundsException: Index 0 requested, with a size of 0.
I have tried adding the following code at the update() in the MessageStore.java:
if (cursor!= null && cursor.moveToFirst())
but yet no avail. Can anyone helps me? Application crashes every time I load it.
Thank you in advance.
Exception is raised in method getRecepientById() of ContactStore. It seems that addrCursor has no records.
Add a check if addrCursor has any records to be safe. In case there's no recepient return null.
Cursor addrCursor = sResolver.query(Uri.parse("content://mms-sms/canonical-address/" + recipientId), null,null, null, null);
if (addrCursor.moveToFirst()) {
String number = addrCursor.getString(0); // we got number here
number = number.replace(" ", "");
number = number.replace("-", "");
Contact c = db.findContactByNumber(number);
return c;
} else {
return null;
}
I have it set up so that when the user hits "clock in" it starts the intentservice, the intent service then updates the ui, the only problem is its not working.... here is my code for the main activity page :
package com.famousmods.payme;
import java.util.Timer;
import java.util.TimerTask;
import android.os.Bundle;
import android.app.Activity;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.support.v4.app.NavUtils;
import android.graphics.PorterDuff;
public class PayTracker extends Activity {
private ResponseReceiver receiver;
private static double Reserve;
private static int Reserve1;
public static double money;
public static double counter;
private static int go;
private static int countdown;
public static int convert;
public static double HW;
public static double OTW;
public static double HPD;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_pay_tracker);
getActionBar().setDisplayHomeAsUpEnabled(true);
// register reciver
IntentFilter filter = new IntentFilter(ResponseReceiver.ACTION_RESP);
filter.addCategory(Intent.CATEGORY_DEFAULT);
receiver = new ResponseReceiver();
registerReceiver(receiver, filter);
// Receive messages from options page
double pHW, pOTW, pHPD;
Intent intent = getIntent();
pHW = intent.getDoubleExtra(Options.MESSAGE_HW, 0);
pOTW = intent.getDoubleExtra(Options.MESSAGE_OTW, 0);
pHPD = intent.getDoubleExtra(Options.MESSAGE_HPD, 0);
if(pHW != 0){
HW = pHW;
OTW = pOTW;
HPD = pHPD;
}
// Color buttons
Button buttonc = (Button) findViewById(R.id.clockin);
buttonc.getBackground().setColorFilter(0xFF00FF00, PorterDuff.Mode.MULTIPLY);
Button buttond = (Button) findViewById(R.id.clockout);
buttond.getBackground().setColorFilter(0xFFFF0000, PorterDuff.Mode.MULTIPLY);
final Button b = (Button) findViewById(R.id.clockout);
b.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_pay_tracker, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
NavUtils.navigateUpFromSameTask(this);
return true;
};
return super.onOptionsItemSelected(item);
}
public void sendMessage(View view) {
//Start IntentService
Intent msgIntent = new Intent(this, SimpleIntentService.class);
msgIntent.putExtra(SimpleIntentService.PARAM_IN_HW, HW);
msgIntent.putExtra(SimpleIntentService.PARAM_IN_OTW, OTW);
msgIntent.putExtra(SimpleIntentService.PARAM_IN_HPD, HPD);
startService(msgIntent);//}
}
public class ResponseReceiver extends BroadcastReceiver {
public static final String ACTION_RESP = "com.famousmods.payme.action.MESSAGE_PROCESSED";
#Override
public void onReceive(Context context, Intent intent) {
// Update UI, new "message" processed by SimpleIntentService
final TextView t1 = (TextView) findViewById(R.id.yourpay);
t1.setTextColor(Color.parseColor("#008000"));
final TextView t2 = (TextView) findViewById(R.id.payper);
String end = intent.getStringExtra(SimpleIntentService.PARAM_OUT_END);
String result = intent.getStringExtra(SimpleIntentService.PARAM_OUT_RESULT);
t2.setText(result);
t1.setText(end);
}
}
#Override
public void onDestroy() {
this.unregisterReceiver(receiver);
super.onDestroy();
}
}
And Here is my intent service page, its set up so that swhen the intent starts it starts a timer that every 20ms should send the new intent back to the activity page, here is the code:
package com.famousmods.payme;
import java.util.Timer;
import java.util.TimerTask;
import com.famousmods.payme.PayTracker.ResponseReceiver;
import android.app.IntentService;
import android.content.Intent;
public class SimpleIntentService extends IntentService {
public static final String PARAM_OUT_END = "end";
public static final String PARAM_OUT_RESULT = "result";
public static final String PARAM_IN_HW = "hourly wage";
public static final String PARAM_IN_OTW = "overtime";
public static final String PARAM_IN_HPD = "hours per day";
public static String end;
public static String result;
private static double Reserve;
private static int Reserve1;
public static double money;
public static double counter;
private static int go;
private static int countdown;
public static int convert;
public SimpleIntentService() {
super("SimpleIntentService");
}
#Override
protected void onHandleIntent(Intent intent) {
// recieve from paytracker
double HW = intent.getDoubleExtra(PARAM_IN_HW, 1);
double OTW = intent.getDoubleExtra(PARAM_IN_OTW, 1);
double HPD = intent.getDoubleExtra(PARAM_IN_HPD, 1);
// Calculate pay per second
final double PPS = (HW/3600);
final double DPPS = (PPS/50);
final double OTPPS = (OTW/3600);
final double DOTPPS = (OTPPS/50);
final double HPDPS = (HPD*3600);
final double DHPDPS = (HPDPS*50);
Timer t = new Timer();
t.schedule(new TimerTask() {
#Override
public void run() {
new Runnable() {
public void run() {
if(DHPDPS==0){
money = (DPPS+Reserve);
Reserve = (money);
end = String.format("%1f", money);
//t1.setText("$" + end);
}else if(counter > DHPDPS && DOTPPS != 0 && DHPDPS != 0){
money = (DOTPPS+Reserve);
Reserve = (money);
end = String.format("%1f", money);
//t1.setText("$" + end);
} else{
money = (DPPS+Reserve);
Reserve = (money);
end = String.format("%1f", money);
//t1.setText("$" + end);
}
counter++;
//if(counter == 3000)
// t.cancel();
// Display pay per second
if(counter <= DHPDPS || DHPDPS == 0){
result = String.format("%.8f", PPS);
}else{
// t2.setText("Your pay per second is: $"+result2);
result = String.format("%.8f", OTPPS);
}
// Broadcast intent
Intent broadcastIntent = new Intent();
broadcastIntent.setAction(ResponseReceiver.ACTION_RESP);
broadcastIntent.addCategory(Intent.CATEGORY_DEFAULT);
broadcastIntent.putExtra(PARAM_OUT_END, end);
broadcastIntent.putExtra(PARAM_OUT_RESULT, result);
sendBroadcast(broadcastIntent);
}
};
}
}, 20, 20);
}
}
Thanks everybody!