Activity has leaked window that was originally added logcat error - java

Please solve my error.I am unable to figure out.
When I click on submit button,my app crashes.Why?Let me know if you want any more input from my side.
MainActivity.java
public class MainActivity extends AppCompatActivity {
Button btn;
EditText txt1, txt2,txt3;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn=findViewById(R.id.button);
txt1=findViewById(R.id.editTextTextPersonName);
txt2=findViewById(R.id.editTextTextEmailAddress2);
txt3=findViewById(R.id.editTextTextPassword);
SharedPreferences pref = getSharedPreferences("mypref", MODE_PRIVATE);
Boolean islogged=pref.getBoolean("key3",false);
if (islogged){
Intent i=new Intent(MainActivity.this,MainActivity2.class);
startActivity(i);
finish();
}
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String email = txt2.getText().toString();
String password = txt3.getText().toString();
Intent i=new Intent(MainActivity.this,MainActivity2.class);
startActivity(i);
SharedPreferences pref = getSharedPreferences("mypref", MODE_PRIVATE);
SharedPreferences.Editor ed = pref.edit();
ed.putString("key1", email);
ed.putString("key2", password);
ed.putBoolean("key3",true);
ed.apply();
}
});
}
}
MainActivity2.java
public class MainActivity2 extends AppCompatActivity {
Button btn;
EditText txt1, txt2;
CheckBox keeplog;
Boolean b=false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
btn=findViewById(R.id.login);
txt1=findViewById(R.id.loginemail);
txt2=findViewById(R.id.loginpassword);
keeplog=findViewById(R.id.checkBox);
keeplog.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
b=isChecked;
}
});
SharedPreferences pref = getSharedPreferences("mypref", MODE_PRIVATE);
Boolean islogin=pref.getBoolean("key4",false);
if (islogin){
Intent i=new Intent(MainActivity2.this,HomeScreen.class);
startActivity(i);
finish();
}
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
SharedPreferences pref = getSharedPreferences("mypref", MODE_PRIVATE);
String email = pref.getString("key1", null);
String password = pref.getString("key2", null);
String email2 = txt1.getText().toString();
String password2 = txt2.getText().toString();
SharedPreferences pref2 = getSharedPreferences("mypref", MODE_PRIVATE);
SharedPreferences.Editor ed = pref2.edit();
ed.putBoolean("key4",b);
ed.apply();
if (email.equals(email2) && password.equals(password2)) {
Intent i = new Intent(MainActivity2.this, HomeScreen.class);
startActivity(i);
finish();
}
}
});
HomeScreen.java
public class HomeScreen extends AppCompatActivity{
Button button1,button2;
EditText n;
ProgressDialog pd;
String Note;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home_screen);
Toast.makeText(this, "Welcome Home", Toast.LENGTH_SHORT).show();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(#NonNull MenuItem item) {
if (item.getItemId() == R.id.id1) {
final AlertDialog dialogBuilder = new AlertDialog.Builder(this).create();
LayoutInflater inflater = this.getLayoutInflater();
View dialogView = inflater.inflate(R.layout.custom_dialog, null);
n = (EditText) dialogView.findViewById(R.id.edt_comment);
button1 = (Button) dialogView.findViewById(R.id.buttonSubmit);
button2 = (Button) dialogView.findViewById(R.id.buttonCancel);
dialogBuilder.setView(dialogView);
dialogBuilder.show();
button2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
dialogBuilder.dismiss();
}
});
button1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
SAVETASK();
// dialogBuilder.dismiss();
}
});
} else if (item.getItemId() == R.id.id2) {
startActivity(new Intent(HomeScreen.this,MainActivity2.class));
}
return super.onOptionsItemSelected(item);
}
public void SAVETASK() {
Note = n.getText().toString();
//password = txt2.getText().toString();
class Savedata extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pd = new ProgressDialog(HomeScreen.this);
pd.setTitle("Saving data");
pd.setMessage("Please Wailt");
pd.show();
}
#Override
protected Void doInBackground(Void... voids) {
Task task = new Task();
task.setNote(Note);
DatabaseClient.getInstance(getApplicationContext()).getAppDatabase().taskdao().insert(task);
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
pd.dismiss();
Toast.makeText(HomeScreen.this, "Data inserted", Toast.LENGTH_SHORT).show();
// Intent intent = new Intent(HomeScreen.this, MainActivity2.class);
// startActivity(intent);
}
}
Savedata savedata = new Savedata();
savedata.execute();
}
}
Task.java
#Entity
public class Task implements Serializable {
#PrimaryKey(autoGenerate = true)
private int id;
#ColumnInfo(name = "name")
private String Note;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getNote() {
return Note;
}
public void setNote(String note) {
Note = note;
}
}
TaskDao.java
#Dao
public interface TaskDao {
#Query("select * from task")
List<Task> getalldata();
#Insert
void insert(Task task);
#Update
void update(Task task);
#Delete
void Delete(Task task);
}
AppDatabase.java
public abstract class AppDatabase extends RoomDatabase {
public abstract TaskDao taskdao();
}
DatabaseClient.java
public class DatabaseClient {
private Context context;
private static DatabaseClient mInstance;
private AppDatabase appDatabase;
private DatabaseClient(Context mctx)
{
this.context=mctx;
appDatabase= Room.databaseBuilder(mctx,AppDatabase.class,"MYTODO").build();
}
public static synchronized DatabaseClient getInstance(Context context)
{
if(mInstance==null)
{
mInstance=new DatabaseClient(context);
}
return mInstance;
}
public AppDatabase getAppDatabase()
{
return appDatabase;
}
}
Logcat error:
com.example.sharedprefdemo E/WindowManager: android.view.WindowLeaked: Activity com.example.sharedprefdemo.HomeScreen has leaked window DecorView#d93e50e[Saving data] that was originally added here
at android.view.ViewRootImpl.<init>(ViewRootImpl.java:765)
at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:429)
at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:95)
at android.app.Dialog.show(Dialog.java:473)
at com.example.sharedprefdemo.HomeScreen$1Savedata.onPreExecute(HomeScreen.java:95)
at android.os.AsyncTask.executeOnExecutor(AsyncTask.java:708)
at android.os.AsyncTask.execute(AsyncTask.java:655)
at com.example.sharedprefdemo.HomeScreen.SAVETASK(HomeScreen.java:117)
at com.example.sharedprefdemo.HomeScreen$2.onClick(HomeScreen.java:70)
at android.view.View.performClick(View.java:7870)
at android.widget.TextView.performClick(TextView.java:14970)
at android.view.View.performClickInternal(View.java:7839)
at android.view.View.access$3600(View.java:886)
at android.view.View$PerformClick.run(View.java:29363)
at android.os.Handler.handleCallback(Handler.java:883)
at android.os.Handler.dispatchMessage(Handler.java:100)
at android.os.Looper.loop(Looper.java:237)
at android.app.ActivityThread.main(ActivityThread.java:7814)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1068)
So when I click on submit button,my app crashes automatically.I dont know what is the reason.

Before showing dialog
if(dialog != null && dialog.isShowing()) {
dialog.dismiss();//or cancel()
}
Try moving the dialog and its initialization from asyncthread
HomeScreen has leaked window DecorView#d93e50e[Saving data] that was originally added here
answer to this error

Related

Cant get my API data to display on other pages

The code I've done was followed closely by a few YouTube tutorials. I'm designing an Age of Empires app that takes in the data from a public API. When the user progresses through the pages then different parts of the API data are shown. What I wanted it to do was get the data from the main activity (where the API is retrieved) and put some of its many data into the UniqueUnit page. It's using something called serializable which I can't quite understand how it works yet.
For the record, it works in getting the data from page 'DetailedCivilization' but just completely breaks on 'UniqueUnit'page.
MainActivity.java
package com.example.ageofempires2;
import ...
public class MainActivity extends AppCompatActivity {
public static final String TAG = "tag";
RecyclerView itemList;
Adapter adapter;
List<Civilizations> all_civilizations;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getSupportActionBar().setTitle("Civilizations menu");
all_civilizations = new ArrayList<>();
itemList = findViewById(R.id.itemList);
itemList.setLayoutManager(new LinearLayoutManager(this));
adapter = new Adapter(this, all_civilizations);
itemList.setAdapter(adapter);
getJsonData();
}
private void getJsonData() {
String URL = "https://age-of-empires-2-api.herokuapp.com/api/v1/civilizations";
RequestQueue requestQueue = Volley.newRequestQueue(this);
JsonObjectRequest objectRequest = new JsonObjectRequest(Request.Method.GET, URL, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONArray civilizations = response.getJSONArray("civilizations");
JSONObject civilizationsData = civilizations.getJSONObject(0);
Log.d(TAG, "onResponse "+ civilizationsData);
for (int i=0; i< civilizationsData.length();i++){
JSONObject civilization = civilizations.getJSONObject(i);
Civilizations v = new Civilizations();
v.setName(civilization.getString("name"));
v.setArmy_type(civilization.getString("army_type"));
v.setExpansion(civilization.getString("expansion"));
v.setCivilization_bonus(civilization.getString("civilization_bonus"));
v.setUnique_unit(civilization.getString("unique_unit"));
all_civilizations.add(v);
adapter.notifyDataSetChanged();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d(TAG, "onErrorResponse" + error.getMessage());
}
});
requestQueue.add(objectRequest);
}
}
Adapter.java
package com.example.ageofempires2;
import ...
public class Adapter extends RecyclerView.Adapter<Adapter.ViewHolder> {
private List<Civilizations> allCivilizations;
private Context context;
public Adapter(Context ctx, List<Civilizations> civilizationsData){
this.allCivilizations = civilizationsData;
this.context = ctx;
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.civilization_view,parent,false);
return new ViewHolder(v);
}
#Override
public void onBindViewHolder(#NonNull ViewHolder holder, final int position) {
holder.titleName.setText(allCivilizations.get(position).getName());
holder.vv.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Bundle b = new Bundle();
b.putSerializable("civilizationsData", allCivilizations.get(position));
Intent i = new Intent(context, DetailedCivilization.class);
i.putExtras(b);
v.getContext().startActivity(i);
}
});
}
#Override
public int getItemCount() {
return allCivilizations.size();
}
public class ViewHolder extends RecyclerView.ViewHolder{
TextView titleName;
TextView expansionName;
View vv;
public ViewHolder(#NonNull View itemView) {
super(itemView);
titleName = itemView.findViewById(R.id.civilizationUniqueUnits);
expansionName = itemView.findViewById(R.id.civilizationUnitDescription);
vv = itemView;
}
}
}
Civilizations.java
package com.example.ageofempires2;
import java.io.Serializable;
public class Civilizations implements Serializable {
private String name;
private String expansion;
private String army_type;
private String civilization_bonus;
private String unique_unit;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getExpansion() {
return expansion;
}
public void setExpansion(String expansion) {
this.expansion = expansion;
}
public String getArmy_type() {
return army_type;
}
public void setArmy_type(String army_type) {
this.army_type = army_type;
}
public String getCivilization_bonus() {
return civilization_bonus;
}
public void setCivilization_bonus(String civilization_bonus) {this.civilization_bonus = civilization_bonus; }
public String getUnique_unit() {
return unique_unit;
}
public void setUnique_unit(String unique_unit) {this.unique_unit = unique_unit; }
}
UniqueUnits.java
package com.example.ageofempires2;
import ...
public class UniqueUnit extends AppCompatActivity {
public static final String TAG = "TAG";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_unique_unit);
getSupportActionBar().setTitle("Unique Unit");
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
Intent incomingIntent = getIntent();
Bundle incomingName = incomingIntent.getExtras();
Civilizations v = (Civilizations) incomingName.getSerializable("civilizationsData");
Log.d(TAG, "onCreate: IDK MAN IT SHOULD WORK??" +incomingName);
TextView unit = findViewById(R.id.civilizationUnitDescription);
unit.setText(v.getUnique_unit());
}
}
DetailedCivilization.java
package com.example.ageofempires2;
import ...
public class DetailedCivilization extends AppCompatActivity {
public static final String TAG = "TAG";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_detailed_civilization);
getSupportActionBar().setTitle("Detailed view");
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
Intent i = getIntent();
Bundle data = i.getExtras();
Civilizations v = (Civilizations) data.getSerializable("civilizationsData");
TextView type = findViewById(R.id.civilizationType);
type.setText(v.getArmy_type());
TextView title = findViewById(R.id.civilizationUniqueUnits);
title.setText(v.getName());
TextView expansions = findViewById(R.id.civilizationUnitDescription);
expansions.setText(v.getExpansion());
TextView bonus = findViewById(R.id.civilizationBonus);
bonus.setText(v.getCivilization_bonus());
Button changeActivityTech = findViewById(R.id.tech_button);
Button changeActivityUnit = findViewById(R.id.unit_button);
changeActivityTech.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
activityTech();
}
});
changeActivityUnit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
activityUnit();
}
});
}
private void activityTech(){
Intent intent = new Intent(this, UniqueTech.class);
startActivity(intent);
}
private void activityUnit(){
Intent intent = new Intent(this, UniqueUnit.class);
startActivity(intent);
}
#Override
public boolean onOptionsItemSelected(#NonNull MenuItem item) {
if(item.getItemId() == android.R.id.home){
onBackPressed();
}
return super.onOptionsItemSelected(item);
}
}
Solutions is
private void activityUnit(Civilizations civ){
Bundle b = new Bundle();
b.putSerializable("civilizationsData", civ)
Intent intent = new Intent(this, UniqueUnit.class);
intent.putExtras(b);
startActivity(intent);
}
In DetailedCivilization.java
Rename v from line Civilizations v = (Civilizations) incomingName.getSerializable("civilizationsData"); to civ or something more descriptive
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_detailed_civilization);
getSupportActionBar().setTitle("Detailed view");
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
Intent i = getIntent();
Bundle data = i.getExtras();
Civilizations civ = (Civilizations) data.getSerializable("civilizationsData");
TextView type = findViewById(R.id.civilizationType);
type.setText(v.getArmy_type());
TextView title = findViewById(R.id.civilizationUniqueUnits);
title.setText(v.getName());
TextView expansions = findViewById(R.id.civilizationUnitDescription);
expansions.setText(v.getExpansion());
TextView bonus = findViewById(R.id.civilizationBonus);
bonus.setText(v.getCivilization_bonus());
Button changeActivityTech = findViewById(R.id.tech_button);
Button changeActivityUnit = findViewById(R.id.unit_button);
changeActivityTech.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
activityTech();
}
});
changeActivityUnit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
activityUnit(civ);
}
});
}
And pass Civilizations when you call activityUnit function
Basically you forgot to pass Civilizations when you go from DetailedCivilization.java to UniqueUnits.java

onbindViewholder include null object

When I run the activity it shows me items that I want plus a null card view(when i delete tostring() from holder.setTitle("product name:"+model.getName().toString()); I'm trying so hard to solve this problem but I didn't find a solution.
this is my class Client_order:
public class Client_order extends AppCompatActivity {
FragmentManager fragmentManager;
Fragment Settingsfrag,Orderfrag,panierfrag;
TextView delorder;
Order model2;
Button submit;
DatabaseReference ref,ref1,ref2;
private Toolbar hometoolbar;
private ImageView settingsbtn, orderIV, imageView7,imageView10;
private RecyclerView orderrv;
private FirebaseAuth mAuth;
private FirebaseUser currentUser;
private DatabaseReference mDatabase;
private String user_id;
Spinner spinnerorder;
private String name;
private String email;
private String phone;
TextView tvName;
Orderviewholder holder1;
private FirebaseRecyclerAdapter<Order, Orderviewholder> orderAdapter;
DatabaseReference dborder,dbpanier;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_client_order);
tvName = findViewById(R.id.tvName);
hometoolbar = findViewById(R.id.hometoolbarorder);
hometoolbar.setTitle("ordre");
hometoolbar.setTitleTextColor(Color.WHITE);
settingsbtn = findViewById(R.id.settingsbtn);
orderIV = findViewById(R.id.orderIV);
imageView7 = findViewById(R.id.imageView7);
fragmentManager=getSupportFragmentManager();
Orderfrag=fragmentManager.findFragmentById(R.id.orderfrag);
Settingsfrag=fragmentManager.findFragmentById(R.id.settingsfrag);
mAuth = FirebaseAuth.getInstance();
currentUser = mAuth.getCurrentUser();
mDatabase = FirebaseDatabase.getInstance().getReference();
if (currentUser == null) {
Intent intent=new Intent(Client_order.this,Login.class);
startActivity(intent);
} else {
if (!mAuth.getCurrentUser().isEmailVerified()) {
Toast.makeText(getApplicationContext(), "Please verify your email address", Toast.LENGTH_LONG).show();
Intent startActivity = new Intent(this, Login.class);
startActivity(startActivity);
finish();
} else {
user_id = currentUser.getUid();
}
}
Toast.makeText(getApplicationContext(),user_id, Toast.LENGTH_LONG).show();
panierfrag=fragmentManager.findFragmentById(R.id.panierfrag);
submit=findViewById(R.id.submit);
submit.setVisibility(View.VISIBLE);
fragmentManager.beginTransaction()
.hide(panierfrag)
.show(Orderfrag)
.hide(Settingsfrag)
.commit();
imageView7.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent=new Intent(Client_order.this,Client_panier.class);
startActivity(intent);
}
});
settingsbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
fragmentManager.beginTransaction()
.hide(panierfrag)
.hide(Orderfrag)
.show(Settingsfrag)
.commit();
}
});
orderIV.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
fragmentManager.beginTransaction()
.hide(panierfrag)
.show(Orderfrag)
.hide(Settingsfrag)
.commit();
}
});
dborder = FirebaseDatabase.getInstance().getReference().child("order");
dborder.keepSynced(true);
orderrv = (RecyclerView) findViewById(R.id.orderrv);
DatabaseReference personsRef = FirebaseDatabase.getInstance().getReference().child("order").child(user_id.toString());
Query personsQuery = personsRef.orderByKey();
orderrv.hasFixedSize();
orderrv.setLayoutManager(new LinearLayoutManager(this));
FirebaseRecyclerOptions personsOptions = new FirebaseRecyclerOptions.Builder<Order>().setQuery(personsQuery, Order.class).build();
orderAdapter=new FirebaseRecyclerAdapter<Order, Orderviewholder>(personsOptions) {
#Override
protected void onBindViewHolder(#NotNull Orderviewholder holder, int position, #NotNull Order model) {
holder.setTitle("product name:"+model.getName().toString());
holder1=holder;
imageView10=holder.mView.findViewById(R.id.imageVieworder);
Picasso.get().load(model.getImage()).into(imageView10, new Callback() {
#Override
public void onSuccess() {
ProgressBar progressbar3;
progressbar3=holder1.mView.findViewById(R.id.progressBar4);
progressbar3.setVisibility(View.INVISIBLE);
}
#Override
public void onError(Exception e) {
}
});
holder.setdesc(model.getDesc().toString());
holder.setprice(model.getPrice());
holder.setquantity(model.getQuantity());
TextView status;
status=holder.mView.findViewById(R.id.statusorder);
status.setText(model.getStatus());
status.setVisibility(View.VISIBLE);
delorder=holder.mView.findViewById(R.id.orderDelbtn);
delorder.setText("done");
holder.mView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
delorder.setVisibility(View.VISIBLE);
}
});
model2=model;
delorder.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
dborder.child(currentUser.getUid()).child(model2.getId()).removeValue().addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NotNull Task<Void> task) {
if (task.isSuccessful()) {
Toast.makeText(Client_order.this, "order deleted successfully", Toast.LENGTH_LONG).show();
}
}
});
}
});
submit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
ref=FirebaseDatabase.getInstance().getReference().child("order").child(user_id.toString());
ref2=FirebaseDatabase.getInstance().getReference().child("order").child(user_id.toString()).child("submitted");
ref1=FirebaseDatabase.getInstance().getReference().child("order").child("admin");
ref.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NotNull DataSnapshot dataSnapshot) {
for (DataSnapshot orderSnapshot: dataSnapshot.getChildren()) {
Order category = orderSnapshot.getValue(Order.class);
//if (category!=null){
ref1.child(category.getId()).setValue(category);
Toast.makeText(Client_order.this,"product successfully submitted", Toast.LENGTH_LONG).show();
ref2.child(category.getId()).setValue(category);
ref.child(category.getId()).removeValue();
// }
}
}
#Override
public void onCancelled(#NotNull DatabaseError databaseError) {
}
});
}
});
}
#NotNull
#Override
public Orderviewholder onCreateViewHolder(#NotNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.product_list_itemorder, parent, false);
return new Orderviewholder(view);
}
};
orderrv.setAdapter(orderAdapter);
}
#Override
protected void onStart() {
super.onStart();
orderAdapter.startListening();
}
#Override
protected void onStop() {
super.onStop();
orderAdapter.stopListening();
}
public static class Orderviewholder extends RecyclerView.ViewHolder{
View mView;
public Orderviewholder(View itemView){
super(itemView);
mView = itemView;
}
public void setTitle(String title){
TextView post_title = (TextView)mView.findViewById(R.id.order_name);
post_title.setText(title);
}
public void setdesc(String desc) {
TextView post_title = (TextView) mView.findViewById(R.id.order_description);
post_title.setText(desc);
}
public void setprice(int price) {
TextView post_title = (TextView) mView.findViewById(R.id.order_price);
post_title.setText(Integer.toString(price)+" dhs");
}
public void setquantity(int quantity) {
TextView post_title = (TextView) mView.findViewById(R.id.order_quantity);
post_title.setText(Integer.toString(quantity));
}
}
}
it shows me this error:
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String java.lang.String.toString()' on a null object reference
at com.omar.lazywork.Client_order$4.onBindViewHolder(Client_order.java:207)
at com.omar.lazywork.Client_order$4.onBindViewHolder(Client_order.java:204)

how to use data from child activity in MainActivity and use it as parameter in other methods

I want to send data from EditText in child activity to parent activity (MainActivity) and use it as a string parameter (URL) in other methods
Already I am able to send this using intent and extras, also I added textview in method to see if it works, but finally, this textview will be deleted, but I can't use it in other methods
public class MainActivity extends AppCompatActivity implements OnDataSendToActivity {
ImageView bg_state;
Button btn_rl;
TextView txt_network;
String url;
String my_url;
TextView tv;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
bg_state = findViewById(R.id.bg_status);
txt_network = findViewById(R.id.txt_network);
Toolbar toolbar= findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
tv=findViewById(R.id.tV);
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
if(isNetworkAvailable()){
bg_state.setImageResource(R.drawable.background);
txt_network.setText("");
}else{
bg_state.setImageResource(R.drawable.background_on);
txt_network.setText("Cound not connect to the server");
}
updateStatus();
handler.postDelayed(this, 2000);
}
}, 5000); //the time is in miliseconds
btn_rl = findViewById(R.id.sw_1);
btn_rl.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String url_rl = my_url+"room_light";
SelectTask task = new SelectTask(url_rl);
task.execute();
updateStatus();
}
});
String url_rl = url+"bed_light";
SelectTask task = new SelectTask(url_rl);
task.execute();
updateStatus();
}
});*/
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater= getMenuInflater();
inflater.inflate(R.menu.menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if(id==R.id.conf){
Intent intent_conf = new Intent(MainActivity.this, Configuration.class);
startActivityForResult(intent_conf,1);
return false;
}
return super.onOptionsItemSelected(item);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode==1){
if(resultCode==RESULT_OK){
url=data.getStringExtra("url");
my_url="http://"+url;
tv.setText(my_url);
}
}
}
private boolean isNetworkAvailable() {
ConnectivityManager connectivityManager
= (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
return activeNetworkInfo != null && activeNetworkInfo.isConnected();
}
#Override
public void sendData(String str) {
updateButtonStatus(str);
}
private void updateStatus(){
String url_rl = my_url+"status";
StatusTask task = new StatusTask(url_rl, this);
task.execute();
}
//Function for updating Button Status
private void updateButtonStatus(String jsonStrings){
try {
JSONObject json = new JSONObject(jsonStrings);
String room_light = json.getString("rl");
if(room_light.equals("1")){
btn_rl.setCompoundDrawablesWithIntrinsicBounds(0, 0, 0, R.drawable.plug_90off);
}else{
btn_rl.setCompoundDrawablesWithIntrinsicBounds(0, 0, 0, R.drawable.plug_90on);
}
.setCompoundDrawablesWithIntrinsicBounds(0, 0, 0, R.drawable.power_off);
}
}catch (JSONException e){
e.printStackTrace();
}
}
}
childactivity
public class Configuration extends AppCompatActivity {
public String new_url;
EditText ip_text;
Button sub_btn;
String a;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_configuration);
Toolbar tool = findViewById(R.id.toolbar);
setSupportActionBar(tool);
ActionBar actionBar = getSupportActionBar();
if(actionBar!=null){
actionBar.setDisplayHomeAsUpEnabled(true);
}
findViewById(R.id.wifi_btn).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
goToUrl("https://192.168.4.1");
}
});
ip_text = findViewById(R.id.ip_text);
sub_btn= findViewById(R.id.sub_btn);
sub_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i=new Intent(Configuration.this,MainActivity.class);
new_url=ip_text.getText().toString();
i.putExtra("url",new_url);
setResult(RESULT_OK,i);
finish();
}
});
}
}
What I need is that if I write in Configuration class for example 192.168.xx.xx In mainactivity my_url will be my_url="https://192.168/ and it will be able to use in other methods as a parameter (for example in btn_rl.setOnClickListener).

I am getting these run time errors while integrating with facebook and creating on account, how to fix them?

Hi I am getting these errors on run time,
when I integrate with facebook first time I run app it gives me that error
invalid scope user friends
Then I try to change permissions like email, basic_profile etc but now when I run the app it log in but remain in same LoginActivity and didn't go to my MainActivity just login button of facebook was changed to logout. After that now my app crashes when I run it and when I debug it , it will give me error of NullPointerExceptions in the method where I setText the name and image of user profile.
and I make a local database for custom account in my app but it also gives me NullPointerExceptions error while data is posted in to database when I click to l click to create account and isInputField method that I have created by myself does not work in that activity
but when I have try to login then isInputField methods work , but when I click on log in button after inserting email and password , my app crashes and gives error in verifyFromSqlite method that
no such column user_password found
but when I check my table in database there is user_friend column.
so what I should do to remove all these errors, please help me I am very worried about it because it is my final year project.
I am attaching all my code of LoginActivity, SignUpActivity, MainActivity and database classes
LoginActivity java class code
public class LoginActivity extends AppCompatActivity implements View.OnClickListener {
private CallbackManager callbackManager;
private AccessTokenTracker accessTokenTracker;
private ProfileTracker profileTracker;
private final AppCompatActivity activity=LoginActivity.this;
private NestedScrollView nestedScrollView;
private TextInputLayout textInputLayoutEmail;
private TextInputLayout textInputLayoutPassword;
private TextInputEditText textInputEditTextEmail;
private TextInputEditText textInputEditTextPassword;
private AppCompatButton login;
private AppCompatTextView forgottonPassword;
private AppCompatTextView linkRegiter;
private InputValidation inputValidation;
private DatabaseHelper databaseHelper;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
FacebookSdk.sdkInitialize(getApplicationContext());
setContentView(R.layout.activity_login);
fbLogin();
if (getSupportActionBar()!=null)
{
getSupportActionBar().hide();
}
initViews();
initListeners();
initObjects();
}
protected void fbLogin(){
callbackManager=CallbackManager.Factory.create();
accessTokenTracker=new AccessTokenTracker() {
#Override
protected void onCurrentAccessTokenChanged(AccessToken oldToken, AccessToken currentToken) {
}
};
profileTracker=new ProfileTracker() {
#Override
protected void onCurrentProfileChanged(Profile oldProfile, Profile newProfile) {
nextActivity(newProfile);
}
};
accessTokenTracker.startTracking();
profileTracker.startTracking();
LoginButton loginButton = (LoginButton) findViewById(R.id.login_button);
FacebookCallback<LoginResult> callback= new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
Profile profile= Profile.getCurrentProfile();
nextActivity(profile);
}
#Override
public void onCancel() {
}
#Override
public void onError(FacebookException error) {
}
};
loginButton.setReadPermissions("user_friends");
loginButton.registerCallback(callbackManager, callback);
}
#Override
protected void onResume() {
super.onResume();
Profile profile= Profile.getCurrentProfile();
nextActivity(profile);
}
#Override
protected void onPause() {
super.onPause();
}
#Override
protected void onStop() {
super.onStop();
accessTokenTracker.stopTracking();
profileTracker.stopTracking();
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
callbackManager.onActivityResult(requestCode,resultCode,data);
}
private void nextActivity(Profile profile){
if (profile!=null){
Intent main = new Intent(LoginActivity.this,MainActivity.class);
main.putExtra("name",profile.getFirstName());
main.putExtra("imageUrl",profile.getProfilePictureUri(100,80)).toString();
// main.putExtra("id", profile.getId());
startActivity(main);
}
}
private void initViews(){
nestedScrollView= (NestedScrollView) findViewById(R.id.nestedScrollView) ;
textInputLayoutEmail= (TextInputLayout) findViewById(R.id.textInputLayoutEmail);
textInputLayoutPassword= (TextInputLayout) findViewById(R.id.textInputLayoutPassword);
textInputEditTextEmail= (TextInputEditText) findViewById(R.id.textInputEditTextEmail);
textInputEditTextPassword= (TextInputEditText) findViewById(R.id.textInputEditTextPassword);
Log.e("textinputedittextmail",textInputEditTextEmail.toString());
login=(AppCompatButton) findViewById(R.id.login);
linkRegiter= (AppCompatTextView) findViewById(R.id.linkRegister);
}
private void initListeners(){
login.setOnClickListener(this);
linkRegiter.setOnClickListener(this);
}
public void initObjects(){
databaseHelper=new DatabaseHelper(activity);
inputValidation=new InputValidation(activity);
}
#Override
public void onClick(View v) {
switch (v.getId()){
case R.id.login:
Log.v("abc", textInputEditTextEmail.getText().toString());
verifyFromSQLite();
break;
case R.id.linkRegister:
Intent intentRegister= new Intent(getApplicationContext(),SignupActivity.class);
startActivity(intentRegister);
break;
}
}
private void verifyFromSQLite(){
if (!inputValidation.isInputEditTextFilled(textInputEditTextEmail, textInputLayoutEmail, "Please Enter Valid Email")){
return;}
if (!inputValidation.isInputEditTextEmail(textInputEditTextEmail, textInputLayoutEmail, "Please Enter Valid Email"))
return;
if (!inputValidation.isInputEditTextFilled(textInputEditTextPassword, textInputLayoutPassword, "Please Enter Valid Password"))
return;
if (databaseHelper.checkUser(textInputEditTextEmail.getText().toString().trim(),
textInputEditTextPassword.getText().toString().trim())){
Intent accountIntent= new Intent(activity, MainActivity.class);
accountIntent.putExtra("Email",textInputEditTextEmail.getText().toString().trim());
emptyInputEditText();
startActivity(accountIntent);
}else {
Snackbar.make(nestedScrollView, "Please Enter Valid Email or Password", Snackbar.LENGTH_LONG).show();
}
}
private void emptyInputEditText(){
textInputEditTextEmail.setText("");
textInputEditTextPassword.setText("");
}
}
SignUp java class code :
public class SignupActivity extends AppCompatActivity implements View.OnClickListener {
private final AppCompatActivity activity=SignupActivity.this;
private NestedScrollView nestedScrollView;
private TextInputLayout textInputLayoutFirstName;
private TextInputLayout textInputLayoutLastName;
private TextInputLayout textInputLayoutEmail;
private TextInputLayout textInputLayoutPassword;
private TextInputLayout textInputLayoutConfirmPassword;
private TextInputEditText textInputEditTextFirstName;
private TextInputEditText textInputEditTextLastName;
private TextInputEditText textInputEditTextEmail;
private TextInputEditText textInputEditTextPassword;
private TextInputEditText textInputEditTextConfirmPassword;
private AppCompatButton appCompatButtonCreateAccount;
private AppCompatTextView linklogin;
private InputValidation inputValidation;
private DatabaseHelper databaseHelper;
private User user;
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_signup);
if (getSupportActionBar()!=null)
{
getSupportActionBar().hide();
}
initViews();
initListeners();
initObjects();
}
private void initViews(){
nestedScrollView=(NestedScrollView) findViewById(R.id.nestedScrollView);
textInputLayoutFirstName= (TextInputLayout) findViewById(R.id.textInputLayoutFirstName);
textInputLayoutLastName= (TextInputLayout) findViewById(R.id.textInputLayoutLastName);
textInputLayoutEmail= (TextInputLayout) findViewById(R.id.textInputLayoutEmail);
textInputLayoutPassword= (TextInputLayout) findViewById(R.id.textInputLayoutPassword);
textInputLayoutConfirmPassword= (TextInputLayout) findViewById(R.id.textInputLayoutConfirmPassword);
textInputEditTextEmail= (TextInputEditText) findViewById(R.id.textInputEditTextEmail);
textInputEditTextPassword= (TextInputEditText) findViewById(R.id.textInputEditTextPassword);
appCompatButtonCreateAccount=(AppCompatButton) findViewById(R.id.appCompatButtonCreateAccount);
linklogin= (AppCompatTextView) findViewById(R.id.linklogin);
}
private void initListeners(){
appCompatButtonCreateAccount.setOnClickListener(this);
linklogin.setOnClickListener(this);
}
public void initObjects(){
databaseHelper=new DatabaseHelper(activity);
inputValidation=new InputValidation(activity);
user=new User();
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.appCompatButtonCreateAccount:
postDataToSQLite();
break;
case R.id.linklogin:
finish();
break;
}
}
private void postDataToSQLite(){
if (!inputValidation.isInputEditTextFilled(textInputEditTextFirstName, textInputLayoutFirstName, "Please Enter Full Name"))
return;
if (!inputValidation.isInputEditTextFilled(textInputEditTextLastName, textInputLayoutLastName, "Please Enter Full Name"))
return;
if (!inputValidation.isInputEditTextEmail(textInputEditTextEmail, textInputLayoutEmail, "Please Enter Valid Email"))
return;
if (!inputValidation.isInputEditTextFilled(textInputEditTextEmail, textInputLayoutEmail,"Please Enter Valid Email" ))
return;
if (!inputValidation.isInputEditTextFilled(textInputEditTextPassword, textInputLayoutPassword, "Please Enter Password"))
return;
if (!databaseHelper.checkUser(textInputEditTextEmail.getText().toString().trim())){
user.setFirstName(textInputEditTextFirstName.getText().toString().trim());
user.setLastName(textInputEditTextLastName.getText().toString().trim());
user.setEmail(textInputEditTextEmail.getText().toString().trim());
user.setEmail(textInputEditTextPassword.getText().toString().trim());
databaseHelper.addUser(user);
Snackbar.make(nestedScrollView, "Registration Successful",Snackbar.LENGTH_LONG).show();
emptyInputEditText();
}else {
Snackbar.make(nestedScrollView, "Already a member Please Login", Snackbar.LENGTH_LONG).show();
}
}
private void emptyInputEditText(){
textInputEditTextFirstName.setText("");
textInputEditTextLastName.setText("");
textInputEditTextEmail.setText("");
textInputEditTextPassword.setText("");
textInputEditTextConfirmPassword.setText("");
}
}
databaseHelper javaclass code
public class DatabaseHelper extends SQLiteOpenHelper {
public static final int DATABASE_VERSION=1;
public static final String DATABASE_NAME="userManager.db";
public static final String TABLE_USER="user";
public static final String COLUMN_USER_ID="user_id";
public static final String COLUMN_USER_FIRSTNAME="user_firstName";
public static final String COLUMN_USER_LASTNAME="user_lastName";
public static final String COLUMN_USER_EMAIL="user_email";
public static final String COLUMN_USER_PASSWORD="user_password";
public String CREATE_USER_TABLE="CREATE TABLE "+TABLE_USER+"("
+ COLUMN_USER_ID + " INTEGER PRIMARY KEY AUTOINCREMENT,"+ COLUMN_USER_FIRSTNAME + " TEXT,"
+ COLUMN_USER_LASTNAME+ " TEXT,"+COLUMN_USER_EMAIL + " TEXT,"+COLUMN_USER_PASSWORD
+" TEXT" + ")";
private String DROP_USER_TABLE="DROP TABLE IF EXISTS "+TABLE_USER;
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(CREATE_USER_TABLE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL(DROP_USER_TABLE);
onCreate(db);
}
public void addUser(User user){
SQLiteDatabase db=this.getWritableDatabase();
ContentValues values=new ContentValues();
values.put(COLUMN_USER_FIRSTNAME, user.getFirstName());
values.put(COLUMN_USER_LASTNAME, user.getLastName());
values.put(COLUMN_USER_EMAIL, user.getEmail());
values.put(COLUMN_USER_PASSWORD, user.getPassword());
db.insert(TABLE_USER, null,values);
db.close();
}
public boolean checkUser(String email){
String[] columns={COLUMN_USER_ID};
SQLiteDatabase db=this.getWritableDatabase();
String selection= COLUMN_USER_EMAIL+ " = ?";
String [] selectionArgs={email };
Cursor cursor= db.query(TABLE_USER,
columns,
selection,
selectionArgs,
null,
null,
null);
int cursorCount=cursor.getCount();
cursor.close();
db.close();
if (cursorCount>0){
return true;
}
return false;
}
public boolean checkUser(String email , String password){
String[] columns={
COLUMN_USER_ID
};
SQLiteDatabase db=this.getWritableDatabase();
String selection= COLUMN_USER_EMAIL+ " = ?" + " AND " + COLUMN_USER_PASSWORD+" =?";
String [] selectionArgs ={ email, password };
Cursor cursor= db.query(TABLE_USER,
columns,
selection,
selectionArgs,
null,
null,
null);
int cursorCount=cursor.getCount();
cursor.close();
db.close();
if (cursorCount>0){
return true;
}
return false;
}
}
inputValidation java class code
public class InputValidation {
private Context context;
public InputValidation(Context context){
this.context=context;
}
public boolean isInputEditTextFilled(TextInputEditText textInputEditText, TextInputLayout textInputLayout, String message){
String value = "";
value=textInputEditText.getText().toString().trim();
if (value.isEmpty()){
textInputLayout.setError(message);
hideKeyboardFrom(textInputEditText);
return false;
}else {
textInputLayout.setErrorEnabled(false);
}
return true;
}
public boolean isInputEditTextEmail(TextInputEditText textInputEditText, TextInputLayout textInputLayout, String message){
String value = textInputEditText.getText().toString().trim();
if (value.isEmpty()|| !Patterns.EMAIL_ADDRESS.matcher(value).matches()){
textInputLayout.setError(message);
hideKeyboardFrom(textInputEditText);
return false;
}else {
textInputLayout.setErrorEnabled(false);
}
return true;
}
public boolean isInputEditTextMatches(TextInputEditText textInputEditText, TextInputEditText textInputEditText2 , TextInputLayout textInputLayout, String message){
String value1 = "";
value1=textInputEditText.getText().toString().trim();
String value2 = "";
value2=textInputEditText.getText().toString().trim();
if (!value1.contentEquals(value2)){
textInputLayout.setError(message);
hideKeyboardFrom(textInputEditText);
return false;
}else {
textInputLayout.setErrorEnabled(false);
}
return true;
}
private void hideKeyboardFrom(View view){
InputMethodManager inputMethodManager= (InputMethodManager) context.getSystemService(Activity.INPUT_METHOD_SERVICE);
inputMethodManager.hideSoftInputFromWindow(view.getWindowToken(), WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
}
}
main Activity class java code
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
private ShareDialog shareDialog;
private String name=" ";
private String imageUrl=" ";
//private String id=" ";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
FacebookSdk.sdkInitialize(this);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
fabShare();
getAndSetData();
new MainActivity.DownloadImage((ImageView)findViewById(R.id.profilePic));
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.addDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
if (savedInstanceState==null) {
getSupportFragmentManager().beginTransaction().replace(R.id.content_main,
new ActivityActivity()).commit();
navigationView.setCheckedItem(R.id.nav_activity);
}
}
private void fabShare(){
FloatingActionButton fab =(FloatingActionButton)findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ShareLinkContent content= new ShareLinkContent.Builder().build();
shareDialog.show(content);
}
});
}
private void getAndSetData(){
Bundle inBundle=getIntent().getExtras();
name=inBundle.get("name").toString();
imageUrl=inBundle.get("imageUrl").toString();
//id=inBundle.get("id").toString();
TextView yourName=(TextView) findViewById(R.id.yourName);
TextView yourId=(TextView) findViewById(R.id.yourId);
yourName.setText(name);
//yourId.setText(id);
}
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.nav_activity) {
getSupportFragmentManager().beginTransaction().replace(R.id.content_main,
new ActivityActivity()).commit();
} else if (id == R.id.nav_history) {
getSupportFragmentManager().beginTransaction().replace(R.id.content_main,
new HistoryActivity()).commit();
} else if (id == R.id.nav_settings) {
} else if (id == R.id.nav_logout){
LoginManager.getInstance().logOut();
Intent login=new Intent(MainActivity.this,LoginActivity.class);
startActivity(login);
finish();
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
public class DownloadImage extends AsyncTask<String,Void ,Bitmap>{
ImageView bmImage;
public DownloadImage(ImageView bmImage){
this.bmImage=bmImage;
}
#Override
protected Bitmap doInBackground(String... urls) {
String urlDisplay=urls[0];
Bitmap bitmap=null;
try {
InputStream inputStream= new java.net.URL(urlDisplay).openStream();
bitmap= BitmapFactory.decodeStream(inputStream);
}catch (Exception e){
Log.e("Error",e.getMessage());
e.printStackTrace();
}
return bitmap;
}
#Override
protected void onPostExecute(Bitmap bitmap) {
bmImage.setImageBitmap(bitmap);
}
}
}
I am not attaching xml code because it crosses limits and user class
in user class there is just getter and setter for database columns.

How to pass values from one activity to another class

I need to pass a value either String to another class
From my activity, to a class that uses services
I have tried with an interface but it can not, you can only attach a fragment, and I can not do it with an attempt since it is a class that runs in the background
How could I do it?
the main activity
public class SettingsActivity extends AppCompatActivity {
private TriStateToggleButton mNotifications;
private ImageButton mButtonFinish;
private CardView mCardTermsPrivacy;
private CardView mCardLicenses;
private CardView mCardLogOut;
private CardView mCardDonations;
private FirebaseUser mUser;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
Window w = getWindow();
w.addFlags(WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS);
w.addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
}
super.onCreate(savedInstanceState);
setContentView(R.layout.acitvity_settings);
mUser = FirebaseAuth.getInstance().getCurrentUser();
initPantalla();
CalligraphyConfig.initDefault(new CalligraphyConfig.Builder()
.setDefaultFontPath("fonts/RobotoLight.ttf")
.setFontAttrId(R.attr.fontPath)
.build()
);
}
private void initPantalla(){
mButtonFinish = (ImageButton) findViewById(R.id.imageButtonRegresaMeet);
mButtonFinish.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
finish();
}
});
mNotifications = (TriStateToggleButton) findViewById(R.id.triStateToggleNotifications);
mCardTermsPrivacy = (CardView) findViewById(R.id.cardViewTemrsPrivacy);
mCardLicenses = (CardView) findViewById(R.id.cardViewLicenses);
mCardDonations = (CardView) findViewById(R.id.cardViewDonations);
mCardLogOut = (CardView) findViewById(R.id.cardViewLogOut);
mCardTermsPrivacy.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
TermsDialogs termsDialogs = new TermsDialogs();
termsDialogs.setCancelable(true);
termsDialogs.show(getSupportFragmentManager(), null);
}
});
mCardLicenses.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
EasyLicensesDialog easyLicensesDialog = new EasyLicensesDialog(SettingsActivity.this);
easyLicensesDialog.setTitle("Licenses");
easyLicensesDialog.setCancelable(true);
easyLicensesDialog.show();
}
});
mCardLogOut.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
FirebaseAuth.getInstance().signOut();
if (AccessToken.getCurrentAccessToken() != null) {
LoginManager.getInstance().logOut();
}
Intent serviceIntent = new Intent(SettingsActivity.this ,FirebaseBackgroundService.class);
SettingsActivity.this.stopService(serviceIntent);
Intent intent = new Intent(SettingsActivity.this, RegisterActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
}
});
mNotifications.setOnToggleChanged(new TriStateToggleButton.OnToggleChanged() {
#Override
public void onToggle(TriStateToggleButton.ToggleStatus toggleStatus, boolean b, int i) {
switch(toggleStatus){
case on:
break;
case off:
break;
}
}
});
}
#Override
protected void attachBaseContext(Context newBase) {
super.attachBaseContext(CalligraphyContextWrapper.wrap(newBase));
}
}
the service class, i need to pass a string in this
public class FirebaseBackgroundService extends Service {
private FirebaseUser mUser;
private SharedPreferences preferences;
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate() {
super.onCreate();
FirebaseApp.initializeApp(getApplicationContext());
mUser = FirebaseAuth.getInstance().getCurrentUser();
if(mUser != null) {
FirebaseUtils.getCHATSOLICITUDRef(mUser.getUid()).addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(final DataSnapshot dataSnapshot, final String s) {
postNotif();
}
#Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
}
#Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
}
private void postNotif(){
Intent notificationIntent = new Intent(getApplicationContext(), UserActivity.class);
PendingIntent contentIntent = PendingIntent.getActivity(getApplicationContext(), 0, notificationIntent, 0);
Uri soundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
Notification noti = new Notification.Builder(this)
.setContentTitle("Chat request")
.setContentText("You have pending chat requests")
.setSmallIcon(R.drawable.ic_dry_cleaning_with_mineral_spirits)
.setContentIntent(contentIntent)
.setSound(soundUri)
.build();
NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
noti.flags |= Notification.FLAG_AUTO_CANCEL;
notificationManager.notify(0, noti);
}
}
use intents link for developers android

Categories