I am starting to learn java and android developement and got stuck with passing a custom array from my MainMenu activity to another activity used to print out the values. Can anybody point out where I went wrong?
MainMenu Class:
public class MainMenu extends AppCompatActivity{
SharedPreferences sharedVar;
Controller controller = new Controller();
int size = 100;
Sati[] sati = new Sati[size];
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_menu);
sharedVar = this.getSharedPreferences("Var", MODE_WORLD_READABLE);
}
#Override
public void onResume(){
super.onResume();
for(int i = 0;i<size;i++) {
if (sati[i] != null){
controller.upisiSmjenu(sati[i],sharedVar.getLong("Datum dolaska",0),sharedVar.getLong("Datum odlaska",0),sharedVar.getLong("Razlika",0));
}
}
}
public void otvoriUnosLayout(View view) {
Intent intent = new Intent(this, UnosSati.class);
startActivity(intent);
}
public void otvoriPregledLayout(View view) {
Intent intent = new Intent(this, PregledSati.class);
intent.putExtra("Sati",sati);
startActivity(intent);
}
}
UnosSati Class(used for data entry):
public class UnosSati extends FragmentActivity {
SharedPreferences sharedVar;
TextView txtRazlika;
Sati sati;
Long razlika;
Date dateD,dateO;
int danD,mjD,godD,SD,MD,danO,mjO,godO,SO,MO;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.unos_sati);
sharedVar = this.getSharedPreferences("Var",MODE_WORLD_READABLE);
sati = (Sati)getIntent().getParcelableExtra("Sati");
dateD = new Date();
dateO = new Date();
txtRazlika = (TextView) findViewById(R. id. txtRazlika);
razlika = 0L;
txtRazlika.setText(String.valueOf(razlika));
danD = sharedVar.getInt("DanD",0);
mjD = sharedVar.getInt("MjD",0);
godD = sharedVar.getInt("GodD",0)-1900;
SD = sharedVar.getInt("SD",0);
MD = sharedVar.getInt("MD",0);
danO = sharedVar.getInt("DanO",0);
mjO = sharedVar.getInt("MjO",0);
godO = sharedVar.getInt("GodO",0)-1900;
SO = sharedVar.getInt("SO",0);
MO = sharedVar.getInt("MO",0);
dateD.setDate(danD);
dateD.setMonth(mjD);
dateD.setYear(godD);
dateD.setHours(SD);
dateD.setMinutes(MD);
dateO.setDate(danO);
dateO.setMonth(mjO);
dateO.setYear(godO);
dateO.setHours(SO);
dateO.setMinutes(MO);
razlika =((dateO.getTime() - dateD.getTime())/60000)/60;
txtRazlika.setText(String.valueOf(razlika));
}
public void vratiNaGlavni(View view){
sharedVar.edit().putLong("Datum dolaska", dateD.getTime()).commit();
sharedVar.edit().putLong("Datum odlaska", dateO.getTime()).commit();
sharedVar.edit().putLong("Razlika",razlika).commit();
Intent intent = new Intent(this,MainMenu.class);
startActivity(intent);
}
public void otvoriKalendarDolaskaLayout(View view) {
Intent intent = new Intent(this, Datum_dolaska.class);
startActivity(intent);
}
public void otvoriSatDolaskaLayout(View view) {
Intent intent = new Intent(this, Sat_dolaska.class);
startActivity(intent);
}
public void otvoriKalendarOdlaskaLayout(View view) {
Intent intent = new Intent(this, Datum_odlaska.class);
startActivity(intent);
}
public void otvoriSatOdlaskaLayout(View view) {
Intent intent = new Intent(this, Sat_odlaska.class);
startActivity(intent);
}
}
PregledSati Class used for viewing the data:
public class PregledSati extends AppCompatActivity {
TextView textView1,textView2,textView3,textView4,textView5,textView6;
Date dateD,dateO;
String printD,printO,printR;
Sati[] sati;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.pregled_sati);
dateD = new Date();
dateO = new Date();
printD = printO = printR = "";
textView1 = (TextView) findViewById(R. id. txtIspis1);
textView2 = (TextView) findViewById(R. id. txtispis2);
textView3 = (TextView) findViewById(R. id. txtispis3);
Bundle extras = getIntent().getExtras();
Sati[] sati = getIntent().getParcelableExtra("Sati");
for(int i = 0;i<100;i++){
textView1.append(String.valueOf(sati[i].getDateDolaska()));
textView1.append("\n");
}
}
}
Sati class:
public class Sati implements Parcelable{
public long dateDolaska, dateOdlaska,ukupnoVrijeme;
public Sati() {
super();
}
public Sati(Parcel dest) {
this.dateDolaska=dest.readLong();
this.dateOdlaska=dest.readLong();
this.ukupnoVrijeme=dest.readLong();
}
public long getDateDolaska() { return dateDolaska; }
public void setDateDolaska(long dateDolaska) {
this.dateDolaska = dateDolaska;
}
public long getDateOdlaska() {
return dateOdlaska;
}
public void setDateOdlaska(long dateOdlaska) {
this.dateOdlaska = dateOdlaska;
}
public long getUkupnoVrijeme() {
return ukupnoVrijeme;
}
public void setUkupnoVrijeme(long ukupnoVrijeme) {
this.ukupnoVrijeme = ukupnoVrijeme;
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeLong(this.dateDolaska);
dest.writeLong(this.dateOdlaska);
dest.writeLong(this.ukupnoVrijeme);
}
public static final Creator<Sati> CREATOR=new Creator<Sati>() {
#Override
public Sati createFromParcel(Parcel dest) {
return new Sati(dest);
}
#Override
public Sati[] newArray(int size) {
return new Sati[size];
}
};
}
I think is because you have to get an array of Parcelables and be sure that class Sati is Parcelable.
Sati[] sati = getIntent().getParcelableArrayExtra("Sati");
Related
I am trying to send an ID as an int and get it from an intent in another activity but it returns zero.
This is the intent in the first activity:
public class Main_page extends AppCompatActivity {
ListView PatientList;
Button BTaddPatient;
DBpatients db;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_page);
PatientList = findViewById(R.id.PateintList);
BTaddPatient = findViewById(R.id.ADDpateint);
db = new DBpatients(this);
BTaddPatient.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(Main_page.this, Add_patient_Activity.class);
startActivity(intent);
}
});
PatientList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Patient selected_patient = (Patient) parent.getItemAtPosition(position);
Intent intent = new Intent(getApplicationContext(), Update_patient.class);
intent.putExtra("ID", selected_patient.getId());
intent.putExtra("name", selected_patient.getName());
intent.putExtra("diagnose", selected_patient.getDiagnose());
startActivity(intent);
}
});
}
#Override
protected void onResume() {
super.onResume();
ArrayList<Patient> patients = db.getAllPatients();
PatientAdapter patientAdapter = new PatientAdapter(this, R.layout.item_pateint, patients);
PatientList.setAdapter(patientAdapter);
}
}
And trying to get the ID in the other activity:
public class Update_patient extends AppCompatActivity {
DBpatients db;
EditText editName, editDiagnose;
Button UpdateBTN;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_update_patient);
final int id = getIntent().getExtras().getInt("ID");
db = new DBpatients(this);
editName = findViewById(R.id.EDname);
editDiagnose = findViewById(R.id.EDdiagnose);
UpdateBTN = findViewById(R.id.BTupdate);
Patient patient = db.getPatientByID2(id);
editDiagnose.setText(patient.getDiagnose());
editName.setText(patient.getName());
UpdateBTN.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String name = editName.getText().toString();
String diagnose = editDiagnose.getText().toString();
Patient newPatient = new Patient( id, name, diagnose);
db.UpdatePatient(newPatient);
Toast.makeText(Update_patient.this, "successfuly UPDATED", Toast.LENGTH_SHORT).show();
}
});
}
This is Patient class :
public class Patient {
private String name;
private int id;
private String diagnose;
public Patient(String name, String diagnose) {
this.name = name;
this.diagnose = diagnose;
}
public Patient(int id, String name, String diagnose) {
this.name = name;
this.diagnose = diagnose;
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getDiagnose() {
return diagnose;
}
public void setDiagnose(String diagnose) {
this.diagnose = diagnose;
}
}
The app crashes, and, by using the debugger, it shows that ID = 0 when receiving it.
Please help.
You just have to send extras while calling your intent.
Like this:
Intent intent = new Intent(getApplicationContext(), SecondActivity.class);
intent.putExtra("Variable name", "Value you want to pass");
startActivity(intent);
Now on the OnCreate method of your SecondActivity you can fetch the extras like this.
If the value you sent was in int:
int value = getIntent().getIntExtra("Variable name which you sent as an extra", defaultValue(you can give it anything));
Example:
int value = getIntent().getIntExtra("ID", 0);
New Activity UI load but does not respond, After running onStop() which trigger submit()
List View with the checkbox is bound by a custom adapter. On touch of the Submit button, an intent is triggered which takes me to HomeActivity and onStop() method is triggered which in return call submit method. All submit method is created under a new thread which interfere with UI.
package com.example.cadur.teacher;
public class Attendace extends AppCompatActivity {
DatabaseReference dref;
ArrayList<String> list=new ArrayList<>();
ArrayList<DeatailAttandance> deatailAttandances;
private MyListAdapter myListAdapter;
private ProgressDialog pb;
String year,branch,subject,emailId,pre,abs,rollno,file_name,dat,dat1,roll_str,rollno_present="",rollno_absent="";
int pre_int,abs_int;
ListView listview;
FirebaseDatabase database;
DatabaseReference myRef;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
SharedPreferences sp=getSharedPreferences("login",MODE_PRIVATE);
final String s=sp.getString("Password","");
final String s1=sp.getString("username","");
year=sp.getString("Year","");
branch=sp.getString("Branch","");
subject=sp.getString("Subject","");
final String attend="Attandence";
emailId=sp.getString("emailId","");
if (s!=null&&s!="" && s1!=null&&s1!="") {
setContentView(R.layout.activity_attendace);
deatailAttandances=new ArrayList<>();
listview = findViewById(R.id.list);
TextView detail=findViewById(R.id.lay);
detail.setText(year+" "+branch+" "+" "+subject);
pb =new ProgressDialog(Attendace.this);
pb.setTitle("Connecting Database");
pb.setMessage("Please Wait....");
pb.setCancelable(false);
pb.show();
database=FirebaseDatabase.getInstance();
myRef=database.getReference(year+"/"+branch);
myRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot ds:dataSnapshot.getChildren()) {
try {
abs = ds.child("Attandence").child(subject).child("Absent").getValue().toString();
pre = ds.child("Attandence").child(subject).child("Present").getValue().toString();
rollno = ds.getKey().toString();
deatailAttandances.add(new DeatailAttandance(rollno,pre,abs));
myListAdapter=new MyListAdapter(Attendace.this,deatailAttandances);
listview.setAdapter(myListAdapter);
pb.dismiss();
}catch (NullPointerException e){
pb.dismiss();
Intent intent=new Intent(Attendace.this, Login.class);
startActivity(intent);
finish();
}
}
count();
}
#Override
public void onCancelled(DatabaseError error) {
// Failed to read value
}
});
Button selectAll=findViewById(R.id.selectall);
selectAll.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
myListAdapter.setCheck();
count();
}
});
Button submit_attan=findViewById(R.id.submit_attan);
submit_attan.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent =new Intent(Attendace.this,HomeActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
}
});
Button count=findViewById(R.id.count);
count.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
View parentView = null;
int counter=0;
for (int i = 0; i < listview.getCount(); i++) {
parentView = getViewByPosition(i, listview);
CheckBox checkBox=parentView.findViewById(R.id.ch);
if(checkBox.isChecked()){
counter++;
}
}
Toast.makeText(Attendace.this,""+counter,Toast.LENGTH_SHORT).show();
}
});
}else{
SharedPreferences.Editor e = sp.edit();
e.putString("Password", "");
e.putString("username", "");
e.commit();
Intent i=new Intent(Attendace.this,MainActivity.class);
startActivity(i);
finish();
}
}
#Override
protected void onStop() {
Attendace.this.runOnUiThread(new Runnable() {
#Override
public void run() {
submit();
}
});
finish();
super.onStop();
}
public void submit(){
View parentView = null;
final Calendar calendar = Calendar.getInstance();
dat=new SimpleDateFormat("dd_MMM_hh:mm").format(calendar.getTime());
dat1=new SimpleDateFormat("dd MM yy").format(calendar.getTime());
file_name=year+"_"+branch+"_"+dat;
rollno_present=rollno_present+""+year+" "+branch+" "+subject+"\n "+dat+"\n\nList of present Students\n";
rollno_absent=rollno_absent+"\n List of absent Students\n";
for (int i = 0; i < listview.getCount(); i++) {
parentView = getViewByPosition(i, listview);
roll_str = ((TextView) parentView.findViewById(R.id.text1)).getText().toString();
String pre_str = ((TextView) parentView.findViewById(R.id.text22)).getText().toString();
String abs_str = ((TextView) parentView.findViewById(R.id.text33)).getText().toString();
pre_int=Integer.parseInt(pre_str);
abs_int=Integer.parseInt(abs_str);
CheckBox checkBox=parentView.findViewById(R.id.ch);
if(checkBox.isChecked()){
pre_int++;
myRef.child(roll_str).child("Attandence").child(subject).child("Present").setValue(""+pre_int);
myRef.child(roll_str).child("Attandence").child(subject).child("Date").child(dat1).setValue("P");
rollno_present=rollno_present+"\n"+roll_str+"\n";
}else{
abs_int++;
myRef.child(roll_str).child("Attandence").child(subject).child("Absent").setValue(""+abs_int);
myRef.child(roll_str).child("Attandence").child(subject).child("Date").child(dat1).setValue("A");
rollno_absent=rollno_absent+"\n"+roll_str+"\n";
}
}
// Toast.makeText(Attendace.this,"Attendance Updated Successfully",Toast.LENGTH_SHORT).show();
AsyncTask.execute(new Runnable() {
#Override
public void run() {
generateNoteOnSD(Attendace.this,file_name,rollno_present+""+rollno_absent);
}
});
}
public void count(){
View parentView = null;
int counter=0;
for (int i = 0; i < listview.getCount(); i++) {
parentView = getViewByPosition(i, listview);
CheckBox checkBox=parentView.findViewById(R.id.ch);
if(checkBox.isChecked()){
counter++;
}
}
Toast.makeText(Attendace.this,""+counter,Toast.LENGTH_SHORT).show();
}
private View getViewByPosition(int pos, ListView listview1) {
final int firstListItemPosition = listview1.getFirstVisiblePosition();
final int lastListItemPosition = firstListItemPosition + listview1.getChildCount() - 1;
if (pos < firstListItemPosition || pos > lastListItemPosition) {
return listview1.getAdapter().getView(pos, null, listview1);
} else {
final int childIndex = pos - firstListItemPosition;
return listview1.getChildAt(childIndex);
}
}
public void generateNoteOnSD(Context context, String sFileName, String sBody) {
try
{
File root = new File(Environment.getExternalStorageDirectory(),year+"_"+branch+"_Attendance");
if (!root.exists())
{
root.mkdirs();
}
File gpxfile = new File(root, file_name+".doc");
FileWriter writer = new FileWriter(gpxfile,true);
writer.append(sBody+"\n");
writer.flush();
writer.close();
// Toast.makeText(Attendace.this,"File Generated",Toast.LENGTH_SHORT).show();
}
catch(IOException e)
{
e.printStackTrace();
}
}
}
Just use
submit();
instead of using
Attendace.this.runOnUiThread(new Runnable() {
#Override
public void run() {
submit();
}
});
and remove finish()
I am trying to communicate with USB on android using input-output stream, using constructor if I use the handler individually it communicates without any problem, but if I use a common constructor it crashes the app saying null pointer exception hope I am doing some blunder mistake but don't know where I did that mistake
and the code as follows
public class BasicAccessoryDemo extends Activity implements View.OnClickListener {
Usb_Communciation usbCom = new Usb_Communciation(this, getIntent());
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button mycontrol, close_command;
mycontrol = (Button) findViewById(R.id.send_command);
mycontrol.setOnClickListener(this);
close_command = (Button) findViewById(R.id.close_command);
close_command.setOnClickListener(this);
}
#Override
public void onStart() {
super.onStart();
}
#Override
public void onResume() {
super.onResume();
}
public void onClick(View view) {
switch (view.getId()) {
case R.id.send_command:
byte[] commandPacket = new byte[2];
commandPacket[0] =0x12;
commandPacket[1] =0x34;
usbCom.Send_message(commandPacket);
break;
case R.id.close_command:
byte[] commandPackets = new byte[2];
commandPackets[0] = 0;
commandPackets[1] = 0;
usbCom.Send_message(commandPackets);
break;
}
}
}
and communication class
public class Usb_Communciation {
public final static int USBAccessoryWhat = 0;
public int firmwareProtocol = 0;
public static USBAccessoryManager accessoryManager;
public static String TAG = "MICROCHIP";
public static final int APP_CONNECT = (int) 0xAE;
public boolean deviceAttached = false;
public Usb_Communciation(Context mContext, Intent intent) {
accessoryManager = new USBAccessoryManager(handler, USBAccessoryWhat);
accessoryManager.enable(mContext, intent);
}
public void Send_message(byte[] data) {
try {
accessoryManager.write(data);
} catch (Exception e) {
Log.d(TAG,
"USBAccessoryManager:write():IOException: arasu "
+ e.toString());
e.printStackTrace();
}
}
public Handler handler = new Handler() {
#Override
public void handleMessage(Message msg) {
byte[] commandPacket = new byte[64];
byte[] WriteValue = new byte[2];
switch (msg.what) {
//Something inside
} //switch
} //handleMessage
}; //handler
public int getFirmwareProtocol(String version) {
String major = "0";
int positionOfDot;
positionOfDot = version.indexOf('.');
if (positionOfDot != -1) {
major = version.substring(0, positionOfDot);
}
return new Integer(major).intValue();
}
}
and the enable method on USB accessory manager class
public RETURN_CODES enable(Context context, Intent intent) {
//something inside
}
and the error shows on the part of the activity and the same constructor on the usb_Communcation class
Usb_Communciation usbCom = new Usb_Communciation(this, getIntent());
Try this:
Usb_Communciation usbCom;
#Override
public void onCreate(Bundle savedInstanceState) {
usbCom = new Usb_Communciation(this, getIntent());
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button mycontrol, close_command;
mycontrol = (Button) findViewById(R.id.send_command);
mycontrol.setOnClickListener(this);
close_command = (Button) findViewById(R.id.close_command);
close_command.setOnClickListener(this);
}
I am beginner in android development , I have some issue please help me.
I have 2 screen Login and After Login , I have set User id in login class and i want to use that user_id in after login how to get , when I use get method find Null how to resolve this problem.
here is my Login Code`public class LoginActivity extends FragmentActivity {
private EditText userName;
private EditText password;
private TextView forgotPassword;
private TextView backToHome;
private Button login;
private CallbackManager callbackManager;
private ReferanceWapper referanceWapper;
private LoginBean loginBean;
Context context;
String regid;
GoogleCloudMessaging gcm;
String SENDER_ID = "918285686540";
public static final String PROPERTY_REG_ID = "registration_id";
private static final String PROPERTY_APP_VERSION = "appVersion";
private final static int PLAY_SERVICES_RESOLUTION_REQUEST = 9000;
static final String TAG = "GCM";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_login);
Utility.setStatusBarColor(this, R.color.tranparentColor);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
Typeface tf = Typeface.createFromAsset(getAssets(), "fonts/OpenSans_Regular.ttf");
setupUI(findViewById(R.id.parentEdit));
userName = (EditText) findViewById(R.id.userName);
userName.setTypeface(tf);
userName.setFocusable(false);
userName.setOnTouchListener(new View.OnTouchListener() {
public boolean onTouch(View view, MotionEvent paramMotionEvent) {
userName.setFocusableInTouchMode(true);
Utility.hideSoftKeyboard(LoginActivity.this);
return false;
}
});
password = (EditText) findViewById(R.id.passwordEText);
password.setTypeface(tf);
password.setFocusable(false);
password.setOnTouchListener(new View.OnTouchListener() {
public boolean onTouch(View paramView, MotionEvent paramMotionEvent) {
password.setFocusableInTouchMode(true);
Utility.hideSoftKeyboard(LoginActivity.this);
return false;
}
});
forgotPassword = (TextView) findViewById(R.id.forgotPassword);
forgotPassword.setTypeface(tf);
forgotPassword.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(getApplicationContext(),ForgotPasswordActivity.class);
startActivity(intent);
}
});
backToHome = (TextView) findViewById(R.id.fromLogToHome);
backToHome.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onBackPressed();
}
});
login = (Button) findViewById(R.id.loginBtn);
login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
doLoginTask();
// Intent intent = new Intent(getApplicationContext(), AfterLoginActivity.class);
// startActivity(intent);
}
});
}
private void doLoginTask() {
String strEmail = userName.getText().toString();
String strPassword = password.getText().toString();
if (strEmail.length() == 0) {
userName.setError("Email Not Valid");
} else if (!Utility.isEmailValid(strEmail.trim())) {
userName.setError("Email Not Valid");
} else if (strPassword.length() == 0) {
password.setError(getString(R.string.password_empty));
} else {
JSONObject jsonObject = null;
try {
jsonObject = new JSONObject();
jsonObject.putOpt(Constants.USER_NAME, strEmail);
jsonObject.putOpt(Constants.USER_PASSWORD, strPassword);
jsonObject.putOpt(Constants.DEVICE_TOKEN, "11");
jsonObject.putOpt(Constants.MAC_ADDRESS, "111");
jsonObject.putOpt(Constants.GPS_LATITUDE, "1111");
jsonObject.putOpt(Constants.GPS_LONGITUDE, "11111");
} catch (JSONException e) {
e.printStackTrace();
}
final ProgressDialog pDialog = new ProgressDialog(this);
pDialog.setMessage("Loading...");
pDialog.show();
CustomJSONObjectRequest jsonObjectRequest = new CustomJSONObjectRequest(Request.Method.POST, Constants.USER_LOGIN_URL, jsonObject, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
pDialog.dismiss();
Log.e("LoginPage", "OnResponse =" + response.toString());
getLogin(response);
//LoginBean lb = new LoginBean();
//Toast.makeText(getApplicationContext(),lb.getFull_name()+"Login Successfuly",Toast.LENGTH_LONG).show();
Intent intent = new Intent(getApplicationContext(),AfterLoginActivity.class);
startActivity(intent);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(),"Something, wrong please try again",Toast.LENGTH_LONG).show();
pDialog.dismiss();
}
});
jsonObjectRequest.setRetryPolicy(new DefaultRetryPolicy(
5000,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
Log.e("LoginPage", "Url= " + Constants.USER_LOGIN_URL + " PostObject = " + jsonObject.toString());
AppController.getInstance().addToRequestQueue(jsonObjectRequest);
}
}
public void getLogin(JSONObject response) {
LoginBean loginBean = new LoginBean();
if (response != null){
try {
JSONObject jsonObject = response.getJSONObject("data");
loginBean.setUser_id(jsonObject.getString("user_id"));
loginBean.setFull_name(jsonObject.getString("full_name"));
loginBean.setDisplay_name(jsonObject.getString("display_name"));
loginBean.setUser_image(jsonObject.getString("user_image"));
loginBean.setGender(jsonObject.getString("gender"));
loginBean.setAuthorization_key(jsonObject.getString("authorization_key"));
} catch (JSONException e) {
e.printStackTrace();
}
}
Toast.makeText(getApplicationContext(),"User id is "+loginBean.getUser_id(),Toast.LENGTH_LONG).show();
}
public void onBackPressed() {
finish();
}
public void setupUI(View view) {
//Set up touch listener for non-text box views to hide keyboard.
if (!(view instanceof EditText)) {
view.setOnTouchListener(new View.OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
Utility.hideSoftKeyboard(LoginActivity.this);
return false;
}
});
}
}
}
`
here is my AfterLogin class`public class AfterLoginActivity extends FragmentActivity {
private ImageView partyIcon;
private ImageView dealIcon;
private ImageView deliveryIcon;
private TextView txtParty;
private TextView txtDeals;
private TextView txtDelivery;
boolean doubleBackToExitPressedOnce = false;
int backButtonCount = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
requestWindowFeature(Window.FEATURE_NO_TITLE);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_after_login);
Utility.setStatusBarColor(this, R.color.splash_status_color);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
partyIcon = (ImageView)findViewById(R.id.party_Icon);
dealIcon = (ImageView)findViewById(R.id.deals_Icon);
deliveryIcon = (ImageView)findViewById(R.id.delivery_Icon);
partyIcon.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(getApplication(), BookPartyActivity.class);
startActivity(intent);
}
});
dealIcon.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(getApplication(), DealsActivity.class);
startActivity(intent);
}
});
deliveryIcon.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
LoginBean loginBean = new LoginBean();
Toast.makeText(getBaseContext(),"Auth"+loginBean.getUser_id(),Toast.LENGTH_LONG).show();
Intent intent = new Intent(getApplicationContext(),MyAuction.class);
startActivity(intent);
}
});
}
/*
public void onBackPressed()
{
if (doubleBackToExitPressedOnce)
{
Intent intent = new Intent(getApplicationContext(), MainActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
finish();
}
doubleBackToExitPressedOnce = true;
Toast.makeText(this, "you have logged in ,plz enjoy the party", Toast.LENGTH_LONG).show();
new Handler().postDelayed(new Runnable()
{
public void run()
{
doubleBackToExitPressedOnce = false;
}
}
, 2000L);
}*/
#Override
public void onBackPressed()
{
if(backButtonCount >= 1)
{
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_HOME);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
else
{
Toast.makeText(this, "Press the back button once again to close the application.", Toast.LENGTH_SHORT).show();
backButtonCount++;
}
}
}`
here is LoginBean`public class LoginBean {
private String user_id;
private String full_name;
private String display_name;
private String user_image;
private String gender;
private String authorization_key;
public void setUser_id(String user_id) {
this.user_id = user_id;
}
public String getUser_id() {
return user_id;
}
public void setFull_name(String full_name) {
this.full_name = full_name;
}
public String getFull_name() {
return full_name;
}
public void setDisplay_name(String display_name) {
this.display_name = display_name;
}
public String getDisplay_name() {
return display_name;
}
public void setUser_image(String user_image) {
this.user_image = user_image;
}
public String getUser_image() {
return user_image;
}
public void setGender(String gender) {
this.gender = gender;
}
public String getGender() {
return gender;
}
public void setAuthorization_key(String authorization_key) {
this.authorization_key = authorization_key;
}
public String getAuthorization_key() {
return authorization_key;
}
}`
//in your both activity or create class
private SharedPreferences mSharedPreferences;
//in your login on getLogin() method ;
mSharedPreferences = getSharedPreferences("user_preference",Context.MODE_PRIVATE);
//save actual drawable id in this way.
if(mSharedPreferences==null)
return;
SharedPreferences.Editor editor = mSharedPreferences.edit();
editor.putInt("userId", loginBean.getUser_id());
editor.commit();
// in your after login acvtivity on deliverable method
private SharedPreferences mSharedPreferences;
mSharedPreferences = getSharedPreferences("user_preference",Context.MODE_PRIVATE);
if(mSharedPreferences==null)
return;
string userId = mSharedPreferences.getString("userId", "");
You can write and apply below mentioned steps (Please ignore any syntactical error, I am giving you simple logical steps).
step 1 - Make a global application level loginObject setter and getter like below. Make sure to define Application class in your manifest just like you do it for your LoginActivity
public class ApplicationClass extends Application{
private LoginBean loginObject;
public void setLoginBean(LoginBean object) {
this.loginObject = object;
}
public LoginBean getName() {
return this.loginObject
}
}
Step - 2 Get an instance of ApplicationClass object reference in LoginActivity to set this global loginObject
e.g. setLogin object in your current Loginactivity like this
......
private ApplicationClass appObject;
......
#Override
protected void onCreate(Bundle savedInstanceState) {
......
appObject = (ApplicationClass) LoginActivity.this.getApplication();
.......
appObject.setLoginBean(loginObject)
}
Step - 3 Get an instance of ApplicationClass object reference in any other Activity get this global loginObject where you need to access this login data.
e.g. getLogin object in your otherActivity like this
......
private ApplicationClass appObject;
......
#Override
protected void onCreate(Bundle savedInstanceState) {
......
appObject = (ApplicationClass) LoginActivity.this.getApplication();
.......
LoginBean loginObject = appObject.getLoginBean();
}
I am running into an issue with the implementation of the Dale Lane MQTT solution.
I cannot seem to figure out how to retrieve the published message from the MQTT Client I am using.
I am not sure if I am utilizing the the onReceive() method incorrectly, but for now all I would like to do is log the broadcasted messages.
http://dalelane.co.uk/blog/?p=1599
The service I have implemented is exactly as listed here, I have no errors.
public class MQTTNotifier extends Activity implements OnClickListener {
String preferenceBrokerHost, preferenceBrokerTopic;
private StatusUpdateReceiver statusUpdateIntentReceiver;
private MQTTMessageReceiver messageIntentReceiver;
private EditText etBroker, etTopic;
Button btnSubscribe, btnStopService;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_mqttnotifier);
initValues();
// startService();
}
private void initValues() {
btnSubscribe = (Button) findViewById(R.id.btnSubscribe);
btnSubscribe.setOnClickListener(this);
btnStopService = (Button) findViewById(R.id.btnStopService);
btnStopService.setOnClickListener(this);
// if statement to see if sharedpreferences exist, if so reopen recievers
/*
* statusUpdateIntentReceiver = new StatusUpdateReceiver(); IntentFilter intentSFilter = new
* IntentFilter(MQTTService.MQTT_STATUS_INTENT); registerReceiver(statusUpdateIntentReceiver,
* intentSFilter);
*
* messageIntentReceiver = new MQTTMessageReceiver(); IntentFilter intentCFilter = new
* IntentFilter(MQTTService.MQTT_MSG_RECEIVED_INTENT); registerReceiver(messageIntentReceiver,
* intentCFilter);
*/
}
public class StatusUpdateReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Bundle notificationData = intent.getExtras();
String newStatus = notificationData.getString(MQTTService.MQTT_STATUS_MSG);
}
}
public class MQTTMessageReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Bundle notificationData = intent.getExtras();
String newTopic = notificationData.getString(MQTTService.MQTT_MSG_RECEIVED_TOPIC);
String newData = notificationData.getString(MQTTService.MQTT_MSG_RECEIVED_MSG);
Log.e("NEW TOPIC", newTopic);
Log.e("NEW DATA", newData);
}
}
#Override
protected void onDestroy() {
unregisterReceiver(statusUpdateIntentReceiver);
unregisterReceiver(messageIntentReceiver);
}
private void startService() {
Intent svc = new Intent(this, MQTTService.class);
startService(svc);
}
private void stopService() {
Intent svc = new Intent(this, MQTTService.class);
stopService(svc);
}
#Override
public void onWindowFocusChanged(boolean hasFocus) {
super.onWindowFocusChanged(hasFocus);
if (hasFocus) {
NotificationManager mNotificationManager =
(NotificationManager) getSystemService(NOTIFICATION_SERVICE);
mNotificationManager.cancel(MQTTService.MQTT_NOTIFICATION_UPDATE);
}
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.btnSubscribe:
etBroker = (EditText) findViewById(R.id.etBroker);
etTopic = (EditText) findViewById(R.id.etTopic);
preferenceBrokerHost = etBroker.getText().toString().trim();
preferenceBrokerTopic = etBroker.getText().toString().trim();
createSharedPreferences(preferenceBrokerHost, preferenceBrokerTopic);
establishRecievers();
startService();
break;
case R.id.btnStopService:
stopService();
}
}
private void createSharedPreferences(String broker, String topic) {
SharedPreferences settings = getSharedPreferences(MQTTService.APP_ID, 0);
SharedPreferences.Editor editor = settings.edit();
editor.putString("broker", broker);
editor.putString("topic", topic);
editor.commit();
}
private void establishRecievers() {
statusUpdateIntentReceiver = new StatusUpdateReceiver();
IntentFilter intentSFilter = new IntentFilter(MQTTService.MQTT_STATUS_INTENT);
registerReceiver(statusUpdateIntentReceiver, intentSFilter);
messageIntentReceiver = new MQTTMessageReceiver();
IntentFilter intentCFilter = new IntentFilter(MQTTService.MQTT_MSG_RECEIVED_INTENT);
registerReceiver(messageIntentReceiver, intentCFilter);
}
}
It turns out that the issue was in regards to a simple mistake that was in regards to this line.
preferenceBrokerTopic = etBroker.getText().toString().trim();
I corrected the issue and now it corrects properly because it was not subscribing to the correct topic.
preferenceBrokerTopic = etTopic.getText().toString().trim();