How to restart Handler after changing data value? - java

Good morning StackOverFlow i'm having some issues with Handler i'm trying to start in the MainActivity my Client.java after 50 seconds and also send the message and stop the client and that's work but i have to reopen the connection on every change of ip_txt or term_txt in settings.java
(data is saved from a EditText to DB by clicking on a button )
here is my MainActivity :
public class MainActivity extends AppCompatActivity {
Server server;
Client client;
Handler handler = new Handler();
Runnable runnable = new Runnable() {
#Override
public void run() {
new ConnectTask().execute("");
if (client != null) {
client.sendMessage("IP#" + ipp + " " + "N#" + trm);
}
if (client != null) {
client.stopClient();
}
}
};
settings Settings;
public static TextView terminale, indr, msg;
TextView log;
String ipp,trm;
DataBaseHandler myDB;
allert Allert;
SharedPreferences prefs;
String s1 = "GAB Tamagnini SRL © 2017 \n" +
"Via Beniamino Disraeli, 17,\n" +
"42124 Reggio Emilia \n" +
"Telefono: 0522 / 38 32 22 \n" +
"Fax: 0522 / 38 32 72 \n" +
"Partita IVA, Codice Fiscale \n" +
"Reg. Impr. di RE 00168780351 \n" +
"Cap. soc. € 50.000,00 i.v. \n" + "" +
"REA n. RE-107440 \n" +
"presso C.C.I.A.A. di Reggio Emilia";
ImageButton settings, helps, allerts, home;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Utils.darkenStatusBar(this, R.color.colorAccent);
server = new Server(this);
myDB = DataBaseHandler.getInstance(this);
msg = (TextView) findViewById(R.id.msg);
log = (TextView) findViewById(R.id.log_avviso);
settings = (ImageButton) findViewById(R.id.impo);
helps = (ImageButton) findViewById(R.id.aiut);
allerts = (ImageButton) findViewById(R.id.msge);
home = (ImageButton) findViewById(R.id.gab);
terminale = (TextView) findViewById(R.id.terminal);
indr = (TextView) findViewById(R.id.indr);
final Cursor cursor = myDB.fetchData();
if (cursor.moveToFirst()) {
do {
indr.setText(cursor.getString(1));
terminale.setText(cursor.getString(2));
Client.SERVER_IP = cursor.getString(1);
trm = cursor.getString(2);
} while (cursor.moveToNext());
}
WifiManager wm = (WifiManager) getSystemService(WIFI_SERVICE);
ipp = Formatter.formatIpAddress(wm.getConnectionInfo().getIpAddress());
handler.postDelayed(runnable,5000);
cursor.close();
server.Parti();
home.setOnClickListener(new View.OnClickListener() {
int counter = 0;
#Override
public void onClick(View view) {
counter++;
if (counter == 10) {
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setCancelable(true);
builder.setMessage(s1);
builder.show();
counter = 0;
}
}
});
settings.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent impostazioni = new Intent(getApplicationContext(), settingsLogin.class);
startActivity(impostazioni);
}
});
helps.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent pgHelp = new Intent(getApplicationContext(), help.class);
startActivity(pgHelp);
}
});
allerts.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Server.count = 0;
SharedPreferences prefs = getSharedPreferences("MY_DATA", MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
editor.clear();
editor.apply();
msg.setVisibility(View.INVISIBLE);
Intent pgAlert = new Intent(getApplicationContext(), allert.class);
startActivity(pgAlert);
}
});
}
#Override
protected void onDestroy() {
super.onDestroy();
server.onDestroy();
}
public class ConnectTask extends AsyncTask<String, String, Client> {
#Override
protected Client doInBackground(String... message) {
client = new Client(new Client.OnMessageReceived() {
#Override
public void messageReceived(String message) {
publishProgress(message);
}
});
client.run();
return null;
}
#Override
protected void onProgressUpdate(String... values) {
super.onProgressUpdate(values);
Log.d("test", "response " + values[0]);
}
}
}
Here is my settings.java:
public class settings extends AppCompatActivity {
TextView indr;
Client client;
EditText ip_txt,term_txt;
ImageButton home;
Button save;
DataBaseHandler myDB;
MainActivity activity;
String ipp;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
myDB = DataBaseHandler.getInstance(this);
setContentView(R.layout.activity_settings);
Utils.darkenStatusBar(this, R.color.colorAccent);
home = (ImageButton) findViewById(R.id.stgbtn);
indr = (TextView) findViewById(R.id.ipp);
ip_txt = (EditText) findViewById(R.id.ip);
term_txt = (EditText) findViewById(R.id.nTermin);
save = (Button) findViewById(R.id.save);
Cursor cursor = myDB.fetchData();
if(cursor.moveToFirst()){
do {
ip_txt.setText(cursor.getString(1));
term_txt.setText(cursor.getString(2));
}while(cursor.moveToNext());
}
cursor.close();
AddData();
home.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
finish();
}
});
WifiManager wm = (WifiManager) getSystemService(WIFI_SERVICE);
ipp = Formatter.formatIpAddress(wm.getConnectionInfo().getIpAddress());
indr.setText(ipp);
}
public void AddData() {
save.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
myDB.insertData(ip_txt.getText().toString(),
term_txt.getText().toString());
MainActivity.indr.setText(ip_txt.getText().toString());
MainActivity.terminale.setText(term_txt.getText().toString());
Client.SERVER_IP = ip_txt.getText().toString();
finish();
}
}
);
}
}
( If I did not explain it i want to start the handler on the start of the app and also to start it again or immediatly after i change the data in EditText ip_txt or in EditText term_txt )

I would create Variables to store the handler and the runnable, then when you want to restart it just use:
yourHandler.removeCallback(yourRunnable);
yourHandler.postDelayed(yourRunnable,time);
and to start it, just do it as you did,
yourHandler.postDelayed(yourRunnable,5000);
Hope is what you are looking for.
How to create them:
public class ClassName{
Handler yourHandler = new Handler();
Runnable yourRunnable = new Runnable(){
#Override
public void run() {
//yourCode
}
};
// Rest of class code
}
Is just same as you did in your code but in a variable.

Related

Multiple layout setVisibility wont show correct layout after getting pressed on certain layout

I have a layout in which there are several other layouts by including in XML, I add some textviews as buttons to change the view layouts from one layout to another.
I display each layout with the setVisibility method between layouts, with setOnClickListener in the textview.
The problem is just after finishing displaying the "profile" layout and trying to display the "about us" layout, the system displays a "profile" layout instead of the "about us" layout.
Here is myJava
public class SettingMenu extends AppCompatActivity {
View userProfile, settingLayout, userFavorite, UserEditProfile, aboutUS, contactUS, ProgressBar;
TextView user_username, user_password, user_email, user_ID, tvVisi, tvMisi, tvMitra, tvIsiVisi, tvIsiMisi, tvIsiMitra;
EditText ETUname, ETPass, ETEmail;
ImageView ivBack, ivEditUProfile;
Button bSetProfile, bSetFavorite, bLogout, BSave, BCancel, bSetAbout, bSetContact;
ArrayList<HashMap<String, String>> list_data;
SessionManager sessionManager;
int x = 0;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_setting);
sessionManager = new SessionManager(this);
sessionManager.checkLogin();
settingLayout = findViewById(R.id.SettingLayout);
userProfile = findViewById(R.id.user_profile);
userProfile.setVisibility(View.GONE);
aboutUS = findViewById(R.id.AboutUs);
aboutUS.setVisibility(View.GONE);
ivBack = findViewById(R.id.IVSettingBack);
ivBack.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (x == 0){
Intent i = new Intent(SettingMenu.this, MainActivity.class);
startActivity(i);
finish();
}
else if (x == 1){
x = 0;
UserEditProfile.setVisibility(View.GONE);
settingLayout.setVisibility(View.VISIBLE);
}
else if (x == 2){
x = 0;
userFavorite.setVisibility(View.GONE);
settingLayout.setVisibility(View.VISIBLE);
}
else if (x == 3) {
x = 0;
aboutUS.setVisibility(View.GONE);
settingLayout.setVisibility(View.VISIBLE);
}
else if (x == 4){
x = 0;
settingLayout.setVisibility(View.VISIBLE);
contactUS.setVisibility(View.GONE);
}
}
});
bSetAbout = findViewById(R.id.bSettingAbout);
bSetAbout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
aboutUS.setVisibility(View.VISIBLE);
settingLayout.setVisibility(View.GONE);
AboutUs();
x = x + 3;
}
});
bSetContact = findViewById(R.id.bSettingContact);
bSetContact.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
bSetProfile = findViewById(R.id.bSettingProfile);
bSetProfile.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
userProfile.setVisibility(View.VISIBLE);
settingLayout.setVisibility(View.GONE);
UserProfile();
x = x + 1;
}
});
bSetFavorite = findViewById(R.id.bSettingFav);
bSetFavorite.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
bLogout = findViewById(R.id.bLogout);
bLogout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
sessionManager.logout();
}
});
}
private void UserProfile() {
UserEditProfile = findViewById(R.id.EditParam);
UserEditProfile.setVisibility(View.GONE);
ETUname = findViewById(R.id.eTUsername);
ETUname.setVisibility(View.GONE);
ETPass = findViewById(R.id.eTPassword);
ETPass.setVisibility(View.GONE);
ETEmail = findViewById(R.id.eTEmail);
ETEmail.setVisibility(View.GONE);
user_username = findViewById(R.id.tVUsername);
user_email = findViewById(R.id.tVEmail);
user_password = findViewById(R.id.tVPassword);
user_ID = findViewById(R.id.tVUser_userID);
final HashMap<String , String> user = sessionManager.getUserDetail();
if (user.get(sessionManager.USERNAME).equals("")){
user_username.setText(R.string.empty_username);
}
else {
user_username.setText(user.get(sessionManager.USERNAME));
}
user_email.setText(user.get(sessionManager.EMAIL));
user_password.setText(user.get(sessionManager.PASSWORD));
user_ID.setText("USER ID #" + user.get(sessionManager.UserID));
ivEditUProfile = findViewById(R.id.iVEdit);
ivEditUProfile.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
user_username.setVisibility(View.GONE);
user_email.setVisibility(View.GONE);
user_password.setVisibility(View.GONE);
ETEmail.setVisibility(View.VISIBLE);
ETEmail.setText(user.get(sessionManager.EMAIL));
ETPass.setVisibility(View.VISIBLE);
ETPass.setText(user.get(sessionManager.PASSWORD));
ETUname.setVisibility(View.VISIBLE);
ETUname.setText(user.get(sessionManager.USERNAME));
UserEditProfile.setVisibility(View.VISIBLE);
}
});
BSave = findViewById(R.id.bSave);
BSave.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String editedUsername = ETUname.getText().toString();
String editedEmail = ETEmail.getText().toString();
String editedPass = ETPass.getText().toString();
if (editedUsername.equals(user_username.getText().toString()) &&
editedEmail.equals(user_email.getText().toString()) &&
editedPass.equals(user_password.getText().toString())){
Cancel();
}
else {
SaveChangedProfile(editedEmail, editedUsername, editedPass);
}
}
});
BCancel = findViewById(R.id.bCancel);
BCancel.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Cancel();
}
});
}
private void SaveChangedProfile(final String EditedEmail, final String EditedUsername, final String EditedPassword) {
//kirim langsung semua
}
private void AboutUs() {
list_data = new ArrayList<>();
ProgressBar = findViewById(R.id.progressLayout);
ProgressBar.setVisibility(View.VISIBLE);
tvVisi = findViewById(R.id.TvVisi);
tvMisi = findViewById(R.id.TvMisi);
tvMitra = findViewById(R.id.TvMitra);
tvVisi.setText("VISI");
tvMisi.setText("MISI");
tvMitra.setText("MITRA");
tvIsiVisi = findViewById(R.id.TvIsiVisi);
tvIsiMisi = findViewById(R.id.TvIsiMisi);
tvIsiMitra = findViewById(R.id.TvIsiMitra);
final String URL_about = "https://x";
final StringRequest stringRequest = new StringRequest(Request.Method.GET, URL_about, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
//Take json Object
JSONObject jsonObject = new JSONObject(response);
//Take Parameter success from php
String success = jsonObject.getString("success");
//get Array tempat from php
JSONArray jsonArray = jsonObject.getJSONArray("about");
//traversing through all the object
for (int i = 0; i < jsonArray.length(); i++) {
//getting product object from json array
JSONObject detail = jsonArray.getJSONObject(i);
//adding the product to HashMap
HashMap<String, String> map = new HashMap<>();
map.put("visi", detail.getString("visi"));
map.put("misi", detail.getString("misi"));
map.put("mitra", detail.getString("mitra"));
list_data.add(0, map);
}
//Put Picture Location to Glide (function) and show it on layout item ("Imageview")
/*Glide.with(getApplicationContext())
.load(list_data.get(0).get("foto"))
.into(Imageview);*/
//Put each data in each Layout item
tvIsiVisi.setText(list_data.get(0).get("visi"));
tvIsiMisi.setText(list_data.get(0).get("misi"));
tvIsiMitra.setText(list_data.get(0).get("mitra"));
ProgressBar.setVisibility(View.GONE);
}
catch (JSONException e) {
e.printStackTrace();
Toast.makeText(SettingMenu.this, "Error : " +e.toString(), Toast.LENGTH_SHORT).show();
AboutUs();
}
}
},
//Give something in these case toast to notice if server gone nuts. (it's only basic got no more time to detailed it)
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(), "Something Wrong :/",Toast.LENGTH_LONG).show();
}
});
//adding our stringrequest to queue
Volley.newRequestQueue(this).add(stringRequest);
}
private void Cancel() {
user_username.setVisibility(View.VISIBLE);
user_email.setVisibility(View.VISIBLE);
user_password.setVisibility(View.VISIBLE);
ETUname.setText("");
ETUname.setVisibility(View.GONE);
ETPass.setText("");
ETPass.setVisibility(View.GONE);
ETEmail.setText("");
ETEmail.setVisibility(View.GONE);
UserEditProfile.setVisibility(View.GONE);
}
}
UPDATE
I change my method from setVisibility to setContentView
here's the code. it works fine for me
public class SettingMenu extends AppCompatActivity {
View UserEditProfile, ProgressBar;
TextView user_username, user_password, user_email, user_ID, tvVisi, tvMisi, tvMitra, tvIsiVisi, tvIsiMisi, tvIsiMitra;
EditText ETUname, ETPass, ETEmail;
ImageView ivBack, ivEditUProfile;
Button bSetProfile, bSetFavorite, bLogout, BSave, BCancel, bSetAbout, bSetContact;
ArrayList<HashMap<String, String>> list_data;
SessionManager sessionManager;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_setting);
sessionManager = new SessionManager(this);
sessionManager.checkLogin();
ControllerHome();
}
private void ControllerHome() {
setContentView(R.layout.activity_setting);
ivBack = findViewById(R.id.IVSettingBack);
ivBack.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(SettingMenu.this, MainActivity.class);
startActivity(i);
finish();
}
});
bSetAbout = findViewById(R.id.bSettingAbout);
bSetAbout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
AboutUs();
}
});
bSetContact = findViewById(R.id.bSettingContact);
bSetContact.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
bSetProfile = findViewById(R.id.bSettingProfile);
bSetProfile.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
UserProfile();
}
});
bSetFavorite = findViewById(R.id.bSettingFav);
bSetFavorite.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
bLogout = findViewById(R.id.bLogout);
bLogout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
sessionManager.logout();
}
});
}
private void UserProfile() {
setContentView(R.layout.setting_user_profile);
UserEditProfile = findViewById(R.id.EditParam);
UserEditProfile.setVisibility(View.GONE);
ETUname = findViewById(R.id.eTUsername);
ETUname.setVisibility(View.GONE);
ETPass = findViewById(R.id.eTPassword);
ETPass.setVisibility(View.GONE);
ETEmail = findViewById(R.id.eTEmail);
ETEmail.setVisibility(View.GONE);
user_username = findViewById(R.id.tVUsername);
user_email = findViewById(R.id.tVEmail);
user_password = findViewById(R.id.tVPassword);
user_ID = findViewById(R.id.tVUser_userID);
final HashMap<String , String> user = sessionManager.getUserDetail();
if (user.get(sessionManager.USERNAME).equals("")){
user_username.setText(R.string.empty_username);
}
else {
user_username.setText(user.get(sessionManager.USERNAME));
}
user_email.setText(user.get(sessionManager.EMAIL));
user_password.setText(user.get(sessionManager.PASSWORD));
user_ID.setText("USER ID #" + user.get(sessionManager.UserID));
ivBack = findViewById(R.id.IVSettingBack);
ivBack.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ControllerHome();
}
});
ivEditUProfile = findViewById(R.id.iVEdit);
ivEditUProfile.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
user_username.setVisibility(View.GONE);
user_email.setVisibility(View.GONE);
user_password.setVisibility(View.GONE);
ETEmail.setVisibility(View.VISIBLE);
ETEmail.setText(user.get(sessionManager.EMAIL));
ETPass.setVisibility(View.VISIBLE);
ETPass.setText(user.get(sessionManager.PASSWORD));
ETUname.setVisibility(View.VISIBLE);
ETUname.setText(user.get(sessionManager.USERNAME));
UserEditProfile.setVisibility(View.VISIBLE);
}
});
BSave = findViewById(R.id.bSave);
BSave.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String editedUsername = ETUname.getText().toString();
String editedEmail = ETEmail.getText().toString();
String editedPass = ETPass.getText().toString();
if (editedUsername.equals(user_username.getText().toString()) &&
editedEmail.equals(user_email.getText().toString()) &&
editedPass.equals(user_password.getText().toString())){
Cancel();
}
else {
SaveChangedProfile(editedEmail, editedUsername, editedPass);
}
}
});
BCancel = findViewById(R.id.bCancel);
BCancel.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Cancel();
}
});
}
private void SaveChangedProfile(final String EditedEmail, final String EditedUsername, final String EditedPassword) {
//kirim langsung semua
}
private void AboutUs() {
setContentView(R.layout.about_us);
list_data = new ArrayList<>();
ProgressBar = findViewById(R.id.progressLayout);
ProgressBar.setVisibility(View.VISIBLE);
tvVisi = findViewById(R.id.TvVisi);
tvMisi = findViewById(R.id.TvMisi);
tvMitra = findViewById(R.id.TvMitra);
tvVisi.setText("VISI");
tvMisi.setText("MISI");
tvMitra.setText("MITRA");
tvIsiVisi = findViewById(R.id.TvIsiVisi);
tvIsiMisi = findViewById(R.id.TvIsiMisi);
tvIsiMitra = findViewById(R.id.TvIsiMitra);
ivBack = findViewById(R.id.IVSettingBack);
ivBack.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ControllerHome();
}
});
final String URL_about = "https://x";
final StringRequest stringRequest = new StringRequest(Request.Method.GET, URL_about, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
//Take json Object
JSONObject jsonObject = new JSONObject(response);
//Take Parameter success from php
String success = jsonObject.getString("success");
//get Array tempat from php
JSONArray jsonArray = jsonObject.getJSONArray("about");
//traversing through all the object
for (int i = 0; i < jsonArray.length(); i++) {
//getting product object from json array
JSONObject detail = jsonArray.getJSONObject(i);
//adding the product to HashMap
HashMap<String, String> map = new HashMap<>();
map.put("visi", detail.getString("visi"));
map.put("misi", detail.getString("misi"));
map.put("mitra", detail.getString("mitra"));
list_data.add(0, map);
}
//Put Picture Location to Glide (function) and show it on layout item ("Imageview")
/*Glide.with(getApplicationContext())
.load(list_data.get(0).get("foto"))
.into(Imageview);*/
//Put each data in each Layout item
tvIsiVisi.setText(list_data.get(0).get("visi"));
tvIsiMisi.setText(list_data.get(0).get("misi"));
tvIsiMitra.setText(list_data.get(0).get("mitra"));
ProgressBar.setVisibility(View.GONE);
}
catch (JSONException e) {
e.printStackTrace();
Toast.makeText(SettingMenu.this, "Error : " +e.toString(), Toast.LENGTH_SHORT).show();
AboutUs();
}
}
},
//Give something in these case toast to notice if server gone nuts. (it's only basic got no more time to detailed it)
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(), "Something Wrong :/",Toast.LENGTH_LONG).show();
}
});
//adding our stringrequest to queue
Volley.newRequestQueue(this).add(stringRequest);
}
private void Cancel() {
user_username.setVisibility(View.VISIBLE);
user_email.setVisibility(View.VISIBLE);
user_password.setVisibility(View.VISIBLE);
ETUname.setText("");
ETUname.setVisibility(View.GONE);
ETPass.setText("");
ETPass.setVisibility(View.GONE);
ETEmail.setText("");
ETEmail.setVisibility(View.GONE);
UserEditProfile.setVisibility(View.GONE);
}
}
solved by using setContentView rather than setVisibility.

save url when re rotate screen from landscape to protrit

I'm trying to play video on player and the video is url that I fetch from an api
so I have a channels in recycleview1 and when I click on one channel the channel start play in new activity
in that activity the player take half of screen and the rest is for recycleview2 which contain some channels for easy and fast navigate between channels
so when I open the channel from recycleview1 and it start playing then I rotate the screen to landscape it work fine then restore the screen to portrate again the channel still working
but the problem is when I click on channel from recycleview2 which lead to update the url that already played and start the new one
so each time I click on channel from recycleview2 the videoview updated to new channel url that clicked
I face problem when I rotate the screen after played channel from recycleview2 the videoview start play a channel that I clicked from recyclewview1 before clicking on new channel from recycleview2 because it return to onCreate method which build the url depend on the information passed with on click
so I used to save the instance state of url so when I rotate the screen to landscape the vidoeview still played the last channel that played
but the problem is when I re rotate the screen to portrate again the videoview here return to the first channel played when start the activity
I tried to save instance state too but it doesn't working
this is the code:
public class TVChannel extends AppCompatActivity implements
TVAdapter.TVAdapterOnClickHandler {
private VideoView videoView;
private int position = 0;
private String video;
private MediaController mediaController;
String mChannelTitle;
String mChannelApp;
String mChannelStreamname;
String mChannelCat;
TVAdapter mAdapter;
RecyclerView mSportsList;
private TextView mCategory;
private TextView mErrorMessageDisplay;
private ProgressBar mLoadingIndicator;
Context mContext ;
public TVItem channelObject;
Uri vidUri;
String myBoolean;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT) {
setContentView(R.layout.activity_tv_channel);
ButterKnife.bind(this);
mSportsList = (RecyclerView) findViewById(R.id.rv_channel);
mErrorMessageDisplay = (TextView) findViewById(R.id.tv_error_message_display);
mContext = this;
channelObject = getIntent().getParcelableExtra("TVChannel");
if (channelObject != null) {
mChannelTitle = String.valueOf(channelObject.getTitle());
mChannelApp = String.valueOf(channelObject.getApp());
mChannelStreamname = String.valueOf(channelObject.getStreamName());
mChannelCat = String.valueOf(channelObject.getCat());
}
mCategory = (TextView) findViewById(R.id.category);
videoView = (VideoView) findViewById(R.id.videoView);
String host = "http://ip/";
String app = mChannelApp;
String streamname = mChannelStreamname;
String playlist = "playlist.m3u8";
vidUri = Uri.parse(host).buildUpon()
.appendPath(app)
.appendPath(streamname)
.appendPath(playlist)
.build();
videoView.setVideoURI(vidUri);
final PlayerControlView playerControlView = (PlayerControlView) findViewById(R.id.player_control_view);
playerControlView.setAlwaysShow(true);
PlayerControlView.ViewHolder viewHolder = playerControlView.getViewHolder();
viewHolder.pausePlayButton.setPauseDrawable(ContextCompat.getDrawable(this, R.drawable.pause));
viewHolder.pausePlayButton.setPlayDrawable(ContextCompat.getDrawable(this, R.drawable.play));
viewHolder.controlsBackground.setBackgroundColor(ContextCompat.getColor(this, R.color.colorPrimaryDark));
viewHolder.currentTimeText.setTextColor(ContextCompat.getColor(this, R.color.colorAccent));
// viewHolder.totalTimeText.setTextSize(18);
playerControlView.setNextListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(TVChannel.this, "onClick Next", Toast.LENGTH_SHORT).show();
}
});
playerControlView.setPrevListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(TVChannel.this, "onClick Prev", Toast.LENGTH_SHORT).show();
}
});
mediaController = playerControlView.getMediaControllerWrapper();
videoView.setMediaController(mediaController);
videoView.seekTo(position);
videoView.start();
videoView.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
playerControlView.show();
}
});
GridLayoutManager LayoutManagerSports = new GridLayoutManager(this, 3);
mSportsList.setLayoutManager(LayoutManagerSports);
mSportsList.setHasFixedSize(true);
mAdapter = new TVAdapter(this, mContext);
mSportsList.setAdapter(mAdapter);
mLoadingIndicator = (ProgressBar) findViewById(R.id.pb_loading_indicator);
String sortchannels = mChannelCat.toLowerCase() + ".php";
loadTVData(sortchannels);
} else {
setContentView(R.layout.activity_tv_channel2);
ButterKnife.bind(this);
mSportsList = (RecyclerView) findViewById(R.id.rv_channel);
mErrorMessageDisplay = (TextView) findViewById(R.id.tv_error_message_display);
mContext = this;
channelObject = getIntent().getParcelableExtra("TVChannel");
if (channelObject != null) {
mChannelTitle = String.valueOf(channelObject.getTitle());
mChannelApp = String.valueOf(channelObject.getApp());
mChannelStreamname = String.valueOf(channelObject.getStreamName());
mChannelCat = String.valueOf(channelObject.getCat());
}
mCategory = (TextView) findViewById(R.id.category);
videoView = (VideoView) findViewById(R.id.videoView);
if (savedInstanceState != null){
myBoolean = savedInstanceState.getString("video");
Toast.makeText(this, "This is my Toast message!",
Toast.LENGTH_LONG).show();
videoView.setVideoURI(Uri.parse(myBoolean));
}
else {
String host = "http://ip/";
String app = mChannelApp;
String streamname = mChannelStreamname;
String playlist = "playlist.m3u8";
vidUri = Uri.parse(host).buildUpon()
.appendPath(app)
.appendPath(streamname)
.appendPath(playlist)
.build();
videoView.setVideoURI(vidUri);
}
final PlayerControlView playerControlView = (PlayerControlView) findViewById(R.id.player_control_view);
playerControlView.setAlwaysShow(false);
PlayerControlView.ViewHolder viewHolder = playerControlView.getViewHolder();
viewHolder.pausePlayButton.setPauseDrawable(ContextCompat.getDrawable(this, R.drawable.pause));
viewHolder.pausePlayButton.setPlayDrawable(ContextCompat.getDrawable(this, R.drawable.play));
viewHolder.controlsBackground.setBackgroundColor(ContextCompat.getColor(this, R.color.controlBackground));
viewHolder.currentTimeText.setTextColor(ContextCompat.getColor(this, R.color.colorAccent));
// viewHolder.totalTimeText.setTextSize(18);
playerControlView.setNextListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(TVChannel.this, "onClick Next", Toast.LENGTH_SHORT).show();
}
});
playerControlView.setPrevListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(TVChannel.this, "onClick Prev", Toast.LENGTH_SHORT).show();
}
});
mediaController = playerControlView.getMediaControllerWrapperFullScreen();
videoView.setMediaController(mediaController);
videoView.seekTo(position);
videoView.start();
videoView.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
playerControlView.show();
}
});
GridLayoutManager LayoutManagerSports = new GridLayoutManager(this, 3);
mSportsList.setLayoutManager(LayoutManagerSports);
mSportsList.setHasFixedSize(true);
mAdapter = new TVAdapter(this, mContext);
mSportsList.setAdapter(mAdapter);
mLoadingIndicator = (ProgressBar) findViewById(R.id.pb_loading_indicator);
String sortchannels = mChannelCat.toLowerCase() + ".php";
loadTVData(sortchannels);
}
}
#Override
public void onSaveInstanceState(Bundle savedInstanceState) {
super.onSaveInstanceState(savedInstanceState);
// Store current position.
savedInstanceState.putString("video", String.valueOf(vidUri));
videoView.start();
}
// After rotating the phone. This method is called.
#Override
public void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
// Get saved position.
video = savedInstanceState.getString("video");
videoView.start();
}
private void loadTVData(String sortChannels) {
showTVDataView();
new FetchTVTask().execute(sortChannels);
}
#Override
public void onClick(TVItem channel, View view) {
if (channel != null) {
mChannelTitle = String.valueOf(channel.getTitle());
mChannelApp = String.valueOf(channel.getApp());
mChannelStreamname = String.valueOf(channel.getStreamName());
}
String host = "http://ip/";
String app = mChannelApp;
String streamname = mChannelStreamname;
String playlist = "playlist.m3u8";
vidUri = Uri.parse(host).buildUpon()
.appendPath(app)
.appendPath(streamname)
.appendPath(playlist)
.build();
videoView.setVideoURI(vidUri);
final PlayerControlView playerControlView = (PlayerControlView) findViewById(R.id.player_control_view);
playerControlView.setAlwaysShow(true);
PlayerControlView.ViewHolder viewHolder = playerControlView.getViewHolder();
viewHolder.pausePlayButton.setPauseDrawable(ContextCompat.getDrawable(this, R.drawable.pause));
viewHolder.pausePlayButton.setPlayDrawable(ContextCompat.getDrawable(this, R.drawable.play));
viewHolder.controlsBackground.setBackgroundColor(ContextCompat.getColor(this, R.color.colorPrimaryDark));
viewHolder.currentTimeText.setTextColor(ContextCompat.getColor(this, R.color.colorAccent));
// viewHolder.totalTimeText.setTextSize(18);
playerControlView.setNextListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(TVChannel.this, "onClick Next", Toast.LENGTH_SHORT).show();
}
});
playerControlView.setPrevListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(TVChannel.this, "onClick Prev", Toast.LENGTH_SHORT).show();
}
});
videoView.setMediaController(playerControlView.getMediaControllerWrapper());
//
videoView.seekTo(position);
videoView.start();
videoView.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
playerControlView.show();
}
});
}
private void showTVDataView() {
mErrorMessageDisplay.setVisibility(View.INVISIBLE);
mSportsList.setVisibility(View.VISIBLE);
}
private void showErrorMessage() {
mSportsList.setVisibility(View.INVISIBLE);
mErrorMessageDisplay.setVisibility(View.VISIBLE);
}
public class FetchTVTask extends AsyncTask<String, Void, ArrayList<TVItem>> {
#Override
protected void onPreExecute() {
super.onPreExecute();
mLoadingIndicator.setVisibility(View.VISIBLE);
}
#Override
protected ArrayList<TVItem> doInBackground(String... params) {
if (params.length == 0) {
return null;
}
String sortChannels = params[0];
URL channelRequestUrl = NetworkTV.buildUrl(sortChannels);
try {
String jsonTVResponse = NetworkTV.getResponseFromHttpUrl(channelRequestUrl);
ArrayList<TVItem> simpleJsonTVData = JsonTV.getSimpleTVStringsFromJson(TVChannel.this, jsonTVResponse);
return simpleJsonTVData;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
#Override
protected void onPostExecute(ArrayList<TVItem> TVData) {
mLoadingIndicator.setVisibility(View.INVISIBLE);
mCategory.setText(TVData.get(0).getCat());
if (TVData != null) {
showTVDataView();
mAdapter.setTVData(TVData);
} else {
showErrorMessage();
}
}
}
}
you can see that I use:
if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT) {
}
else{
}
to set content view for portrait and landscape
and inside else this is the code that I use to save the url in landscape mode:
if (savedInstanceState != null){
myBoolean = savedInstanceState.getString("video");
Toast.makeText(this, "This is my Toast message!",
Toast.LENGTH_LONG).show();
videoView.setVideoURI(Uri.parse(myBoolean));
}
else {
String host = "http://ip/";
String app = mChannelApp;
String streamname = mChannelStreamname;
String playlist = "playlist.m3u8";
vidUri = Uri.parse(host).buildUpon()
.appendPath(app)
.appendPath(streamname)
.appendPath(playlist)
.build();
videoView.setVideoURI(vidUri);
}
and if savedInstanceState null so build url like this from on click information that I pass in portrait mode:
channelObject = getIntent().getParcelableExtra("TVChannel");
if (channelObject != null) {
mChannelTitle = String.valueOf(channelObject.getTitle());
mChannelApp = String.valueOf(channelObject.getApp());
mChannelStreamname = String.valueOf(channelObject.getStreamName());
mChannelCat = String.valueOf(channelObject.getCat());
}
how can I save the url channel when I re rotate screen from landscape to portrait mode again?

App is not responding after running this activity

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

Call number when click list view item

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

How to get data from getter setter class?

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();
}

Categories

Resources