I'm fairly new to java but am trying to create an app that collects WiFi information periodically, displays it to the user and sends it to a database.
I have Wifi collection working, it collects the SSID, BSSID, RSSI and a timestamp. It displays it to the user and i can even send information to the server.
ui
However, the current code i have does not send the data to the server correctly. It sends the data, but gets stuck on one SSID, BSSID and RSSI. For example if there are 20 wireless networks, the app would send 19 of the same entries and possibly have the next entry as the 20th.
database
I believe it is something to do with the asynctask inside the function InsertData, perhaps it is running quicker than the wifithing function. But i am unsure how to resolve this.
Thanks for all responses!
Update
Hey all!
There are two functions being used here wifithing() and InsertData() which contains a async task for sending data to a mysql database, wifithing() works perfectly and assigns the SSID, BSSID and RSSI to a device to be displayed elsewhere, it does this in a loop to cycle through all the available networks.
Now InsertData() is called by the button press, and uses a loop to cycle through all the available networks. This does work, but am seeing some strange results on the database, first of all an duplicate entry is added at the beginning and secondly on the second button press no data is sent, on the third press it works, then on the fourth it doesn't..
database with duplicate
Edited wififragment.java
package com.example.joe.ratscanner;
import android.Manifest;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiManager;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.Toast;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.Executor;
//return inflater.inflate(R.layout.fragment_wifi, container, false);
/**
* A simple {#link Fragment} subclass.
*/
public class wififragment extends Fragment {
int count= 0;
Timer t;
String ServerURL = "http://ratscanner.duckdns.org/get_data.php" ;
String TempWifi;
String TempBSSID;
String Templevel;
String test;
String isthishappening;
TimerTask timer= new TimerTask(){
#Override
public void run() {
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
//count--;
//if (count >= 0) {
if(count == 0) {
//Toast.makeText(getActivity(),"this updated",Toast.LENGTH_SHORT).show();
// wifithing();
//InsertData(); //probably remove this later
}
}
});
//if (count <= 0) {
// t.cancel();
//}
}
};
public class device{
CharSequence name;
public String setName(CharSequence name) {
this.name = name;
return null;
}
public CharSequence getName (){
return name;
}
}
final private int REQUEST_CODE_ASK_MULTIPLE_PERMISSIONS = 125;
List<ScanResult> wifiList;
private WifiManager wifi;
List<device> values = new ArrayList<device>();
int netCount=0;
int AnetCount=0;
RecyclerView recyclerView;
WifiScanAdapter wifiScanAdapter;
public wififragment() {
// Required empty public constructor
}
public static wififragment newInstance() {
wififragment fragment = new wififragment();
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
//Make instance of Wifi
Button btnScan= (Button) getActivity().findViewById(R.id.wifiScan);
wifi = (WifiManager) getActivity().getApplicationContext().getSystemService(Context.WIFI_SERVICE);
//Check wifi enabled or not
if (wifi.isWifiEnabled() == false)
{
Toast.makeText(getActivity(), "Wifi is disabled enabling...", Toast.LENGTH_LONG).show();
wifi.setWifiEnabled(true);
}
//register Broadcast receiver
getActivity().registerReceiver(new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
wifiList=wifi.getScanResults();
netCount=wifiList.size();
AnetCount=wifiList.size();
// wifiScanAdapter.notifyDataSetChanged();
Log.d("Wifi","Total Wifi Network"+netCount);
}
},new IntentFilter(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION));
wifiScanAdapter=new WifiScanAdapter(values,getContext());
recyclerView= (RecyclerView) getActivity().findViewById(R.id.wifiRecyclerView);
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
recyclerView.setAdapter(wifiScanAdapter);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
checkandAskPermission();
} else {
wifithing();
}
btnScan.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
wifithing();
InsertData();
InsertData();
Toast.makeText(getContext(), netCount +"\n"+ AnetCount , Toast.LENGTH_SHORT).show();
}
});
}
/* public void wifithing(){
SimpleDateFormat dateformat = new SimpleDateFormat("dd-MMM-yyyy");
wifi.startScan();
values.clear();
try {
netCount = netCount - 1;
while (netCount >= 0) {
String currentDateTimeString = dateformat.getDateTimeInstance().format(new Date());
device d = new device();
d.setName(wifiList.get(netCount).SSID.toString()+"\n"+ wifiList.get(netCount).BSSID +" "+ wifiList.get(netCount).level +"\n" + currentDateTimeString );
//TempWifi = d;//returns nothing, need to make it return ssid
//TempWifi = "";// clears the old data
TempWifi = wifiList.get(netCount).SSID.toString(); //adds the new ssid
TempBSSID = wifiList.get(netCount).BSSID.toString(); //adds the new bssid
Templevel = Integer.toString(wifiList.get(netCount).level);// adds the new level
//currently have issue where one/two ssids are put in database
// maybe see how many "SSIDS" database recieves and how many show up on scan
// 20 on server, 20 on app
//20 on server, 20 on app
//19 on server, 19 on app
isthishappening = "This is from wifithing";
InsertData();// calls the method which sends the data to server
Log.d("WiFi",d.getName().toString());
values.add(d);
wifiScanAdapter.notifyDataSetChanged();
netCount=netCount -1;
}
}
catch (Exception e){
Log.d("Wifi", e.getMessage());
}
}*/
public void wifithing(){
SimpleDateFormat dateformat = new SimpleDateFormat("dd-MMM-yyyy");
wifi.startScan();
values.clear();
try {
netCount = netCount - 1;
while (netCount >= 0) {
String currentDateTimeString = dateformat.getDateTimeInstance().format(new Date());
device d = new device();
d.setName(wifiList.get(netCount).SSID.toString()+"\n"+ wifiList.get(netCount).BSSID +" "+ wifiList.get(netCount).level +"\n" + currentDateTimeString );
//TempWifi = d;//returns nothing, need to make it return ssid
//currently have issue where one/two ssids are put in database
// maybe see how many "SSIDS" database recieves and how many show up on scan
// 20 on server, 20 on app
//20 on server, 20 on app
//19 on server, 19 on app
isthishappening = "This is from wifithing";
//InsertData();// calls the method which sends the data to server
Log.d("WiFi",d.getName().toString());
values.add(d);
wifiScanAdapter.notifyDataSetChanged();
netCount=netCount -1;
}
}
catch (Exception e){
Log.d("Wifi", e.getMessage());
}
}
//this code is responsible for sending data to the server through PHP////////////////////////////////////////////////////////
public void InsertData(){
class SendPostReqAsyncTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
try {
AnetCount = AnetCount - 1;
while (AnetCount >= 0) {
TempWifi = wifiList.get(AnetCount).SSID.toString(); //adds the new ssid
TempBSSID = wifiList.get(AnetCount).BSSID.toString(); //adds the new bssid
Templevel = Integer.toString(wifiList.get(AnetCount).level);// adds the new level
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("SSID", TempWifi));
nameValuePairs.add(new BasicNameValuePair("MAC", TempBSSID));
nameValuePairs.add(new BasicNameValuePair("level", Templevel));
try {
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(ServerURL);
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
} catch (ClientProtocolException e) {
} catch (IOException e) {
}
AnetCount = AnetCount - 1;
}
}
catch (Exception e){
Log.d("Wifi", e.getMessage());
}
return "Data Inserted Successfully";
}
#Override
protected void onPostExecute(String result) {
isthishappening = "This is from async";
Log.d("wifi", isthishappening);
//Log.d("wifi", result);
super.onPostExecute(result);
//Toast.makeText(getContext(), TempWifi, Toast.LENGTH_SHORT).show();
}
}
SendPostReqAsyncTask sendPostReqAsyncTask = new SendPostReqAsyncTask();
sendPostReqAsyncTask.execute();
}///////////////////////////////////////////////////////////////////////////////////////////////////////////////
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
t = new Timer();
t.scheduleAtFixedRate(timer , 10000 , 10000);
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_wifi, container, false);
}
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions,
int[] grantResults) {
switch (requestCode) {
case REQUEST_CODE_ASK_MULTIPLE_PERMISSIONS: {
Map<String, Integer> perms = new HashMap<String, Integer>();
perms.put(Manifest.permission.ACCESS_COARSE_LOCATION, PackageManager.PERMISSION_GRANTED);
for (int i = 0; i < permissions.length; i++)
perms.put(permissions[i], grantResults[i]);
if (perms.get(Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
wifi.startScan();
} else {
// Permission Denied
Toast.makeText(getContext(), "Some Permission is Denied", Toast.LENGTH_SHORT)
.show();
}
}
}
}
private void checkandAskPermission() {
List<String> permissionsNeeded = new ArrayList<String>();
final List<String> permissionsList = new ArrayList<String>();
if (!addPermission(permissionsList, Manifest.permission.ACCESS_COARSE_LOCATION))
permissionsNeeded.add("Network");
if (permissionsList.size() > 0) {
if (permissionsNeeded.size() > 0) {
// Need Rationale
String message = "You need to grant access to " + permissionsNeeded.get(0);
for (int i = 0; i < permissionsNeeded.size(); i++)
message = message + ", " + permissionsNeeded.get(i);
showMessageOKCancel(message,
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
requestPermissions(permissionsList.toArray(new String[permissionsList.size()]),
REQUEST_CODE_ASK_MULTIPLE_PERMISSIONS);
}
});
return;
}
requestPermissions(permissionsList.toArray(new String[permissionsList.size()]),
REQUEST_CODE_ASK_MULTIPLE_PERMISSIONS);
return;
}
// initVideo();
}
private void showMessageOKCancel(String message, DialogInterface.OnClickListener okListener) {
new AlertDialog.Builder(getActivity())
.setMessage(message)
.setPositiveButton("OK", okListener)
.setNegativeButton("Cancel", okListener)
.create()
.show();
}
private boolean addPermission(List<String> permissionsList, String permission) {
if (getActivity().checkSelfPermission(permission) != PackageManager.PERMISSION_GRANTED) {
permissionsList.add(permission);
if (!shouldShowRequestPermissionRationale(permission))
return false;
}
return true;
}
public void onDetach() {
super.onDetach();
count = 1;
t.cancel();
//timer was created at top of page as infinite, never cancelled even when the fragment closed -
// t.cancel(): stops the timer and allows the page to switch without crashing
}
}
before code snippet from wififragment.java
public void wifithing(){
SimpleDateFormat dateformat = new SimpleDateFormat("dd-MMM-yyyy");
wifi.startScan();
values.clear();
try {
netCount = netCount - 1;
while (netCount >= 0) {
String currentDateTimeString = dateformat.getDateTimeInstance().format(new Date());
device d = new device();
d.setName(wifiList.get(netCount).SSID.toString()+"\n"+ wifiList.get(netCount).BSSID +" "+ wifiList.get(netCount).level +"\n" + currentDateTimeString );
//TempWifi = d;//returns nothing, need to make it return ssid
//TempWifi = "";// clears the old data
TempWifi = wifiList.get(netCount).SSID.toString(); //adds the new ssid
TempBSSID = wifiList.get(netCount).BSSID.toString(); //adds the new bssid
Templevel = Integer.toString(wifiList.get(netCount).level);// adds the new level
//currently have issue where one/two ssids are put in database
// maybe see how many "SSIDS" database recieves and how many show up on scan
// 20 on server, 20 on app
//20 on server, 20 on app
//19 on server, 19 on app
InsertData();// calls the method which sends the data to server
Log.d("WiFi",d.getName().toString());
values.add(d);
wifiScanAdapter.notifyDataSetChanged();
netCount=netCount -1;
}
}
catch (Exception e){
Log.d("Wifi", e.getMessage());
}
}
//this code is responsible for sending data to the server through PHP////////////////////////////////////////////////////////
public void InsertData(){
class SendPostReqAsyncTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("SSID", TempWifi));
nameValuePairs.add(new BasicNameValuePair("MAC", TempBSSID));
nameValuePairs.add(new BasicNameValuePair("level", Templevel));
try {
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(ServerURL);
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
} catch (ClientProtocolException e) {
} catch (IOException e) {
}
return "Data Inserted Successfully";
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
//Toast.makeText(getContext(), TempWifi, Toast.LENGTH_SHORT).show();
}
}
SendPostReqAsyncTask sendPostReqAsyncTask = new SendPostReqAsyncTask();
sendPostReqAsyncTask.execute();
}///////////////////////////////////////////////////////////////////////////////////////////////////////////////
Related
I'm trying to get all the user chats (created in my database) using an ArrayList and Recyclerview.Adapter but only first item from my ArrayList is being shown on my emulator screen.
Here's the corresponding code:
MainActivity:
package com.wipro.chat.activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.Toast;
import com.android.volley.NetworkResponse;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GoogleApiAvailability;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import com.wipro.chat.R;
import com.wipro.chat.adapter.ChatRoomsAdapter;
import com.wipro.chat.app.Config;
import com.wipro.chat.app.EndPoints;
import com.wipro.chat.app.MyApplication;
import com.wipro.chat.gcm.GcmIntentService;
import com.wipro.chat.gcm.NotificationUtils;
import com.wipro.chat.helper.SimpleDividerItemDecoration;
import com.wipro.chat.model.ChatRoom;
import com.wipro.chat.model.Message;
public class MainActivity extends AppCompatActivity {
private String TAG = MainActivity.class.getSimpleName();
private static final int PLAY_SERVICES_RESOLUTION_REQUEST = 9000;
private BroadcastReceiver mRegistrationBroadcastReceiver;
private ArrayList<ChatRoom> chatRoomArrayList;
private ChatRoomsAdapter mAdapter;
private RecyclerView recyclerView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
/**
* Check for login session. If not logged in launch
* login activity
* */
if (MyApplication.getInstance().getPrefManager().getUser() == null) {
launchLoginActivity();
}
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
recyclerView = (RecyclerView) findViewById(R.id.recycler_view);
/**
* Broadcast receiver calls in two scenarios
* 1. gcm registration is completed
* 2. when new push notification is received
* */
mRegistrationBroadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
// checking for type intent filter
if (intent.getAction().equals(Config.REGISTRATION_COMPLETE)) {
// gcm successfully registered
// now subscribe to `global` topic to receive app wide notifications
subscribeToGlobalTopic();
} else if (intent.getAction().equals(Config.SENT_TOKEN_TO_SERVER)) {
// gcm registration id is stored in our server's MySQL
Log.e(TAG, "GCM registration id is sent to our server");
} else if (intent.getAction().equals(Config.PUSH_NOTIFICATION)) {
// new push notification is received
handlePushNotification(intent);
}
}
};
chatRoomArrayList = new ArrayList<>();
mAdapter = new ChatRoomsAdapter(this, chatRoomArrayList);
LinearLayoutManager layoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutManager);
recyclerView.addItemDecoration(new SimpleDividerItemDecoration(
getApplicationContext()
));
recyclerView.setItemAnimator(new DefaultItemAnimator());
recyclerView.setAdapter(mAdapter);
recyclerView.addOnItemTouchListener(new ChatRoomsAdapter.RecyclerTouchListener(getApplicationContext(), recyclerView, new ChatRoomsAdapter.ClickListener() {
#Override
public void onClick(View view, int position) {
// when chat is clicked, launch full chat thread activity
ChatRoom userChatRoom = chatRoomArrayList.get(position);
Intent intent = new Intent(MainActivity.this, ChatRoomActivity.class);
intent.putExtra("user_id", userChatRoom.getId());
intent.putExtra("name", userChatRoom.getName());
startActivity(intent);
}
#Override
public void onLongClick(View view, int position) {
}
}));
/**
* Always check for google play services availability before
* proceeding further with GCM
* */
if (checkPlayServices()) {
registerGCM();
fetchChatRooms();
}
}
/**
* Handles new push notification
*/
private void handlePushNotification(Intent intent) {
/*int type = intent.getIntExtra("type", -1);
// if the push is of chat room message
// simply update the UI unread messages count
if (type == Config.PUSH_TYPE_CHATROOM) {
Message message = (Message) intent.getSerializableExtra("message");
String chatRoomId = intent.getStringExtra("chat_room_id");
if (message != null && chatRoomId != null) {
updateRow(chatRoomId, message);
}
} else if (type == Config.PUSH_TYPE_USER) {
// push belongs to user alone
// just showing the message in a toast
Message message = (Message) intent.getSerializableExtra("message");
Toast.makeText(getApplicationContext(), "New push: " + message.getMessage(), Toast.LENGTH_LONG).show();
}*/
Message message = (Message) intent.getSerializableExtra("message");
String userChatRoomId = intent.getStringExtra("user_id");
if (message != null && userChatRoomId != null) {
updateRow(userChatRoomId, message);
}
}
/**
* Updates the chat list unread count and the last message
*/
private void updateRow(String chatRoomId, Message message) {
for (ChatRoom cr : chatRoomArrayList) {
if (cr.getId().equals(chatRoomId)) {
int index = chatRoomArrayList.indexOf(cr);
cr.setLastMessage(message.getMessage());
cr.setUnreadCount(cr.getUnreadCount() + 1);
chatRoomArrayList.remove(index);
chatRoomArrayList.add(index, cr);
break;
}
}
mAdapter.notifyDataSetChanged();
}
/**
* fetching the chat rooms by making http call
*/
private void fetchChatRooms() {
StringRequest strReq = new StringRequest(Request.Method.GET,
EndPoints.CHAT_ROOMS, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.e(TAG, "response: " + response);
try {
JSONObject obj = new JSONObject(response);
// check for error flag
if (obj.getBoolean("error") == false) {
JSONArray chatRoomsArray = obj.getJSONArray("chat_rooms");
for (int i = 0; i < chatRoomsArray.length(); i++) {
JSONObject chatRoomsObj = (JSONObject) chatRoomsArray.get(i);
ChatRoom cr = new ChatRoom();
cr.setId(chatRoomsObj.getString("user_id"));
cr.setName(chatRoomsObj.getString("name"));
cr.setLastMessage("");
cr.setUnreadCount(0);
cr.setTimestamp(chatRoomsObj.getString("created_at"));
chatRoomArrayList.add(cr);
}
} else {
// error in fetching chat rooms
Toast.makeText(getApplicationContext(), "" + obj.getJSONObject("error").getString("message"), Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
Log.e(TAG, "json parsing error: " + e.getMessage());
Toast.makeText(getApplicationContext(), "Json parse error: " + e.getMessage(), Toast.LENGTH_LONG).show();
}
mAdapter.notifyDataSetChanged();
// subscribing to all chat room topics
//subscribeToAllTopics();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
NetworkResponse networkResponse = error.networkResponse;
Log.e(TAG, "Volley error: " + error.getMessage() + ", code: " + networkResponse);
Toast.makeText(getApplicationContext(), "Volley error: " + error.getMessage(), Toast.LENGTH_SHORT).show();
}
});
//Adding request to request queue
MyApplication.getInstance().addToRequestQueue(strReq);
}
// subscribing to global topic
private void subscribeToGlobalTopic() {
Intent intent = new Intent(this, GcmIntentService.class);
intent.putExtra(GcmIntentService.KEY, GcmIntentService.SUBSCRIBE);
intent.putExtra(GcmIntentService.TOPIC, Config.TOPIC_GLOBAL);
startService(intent);
}
// Subscribing to all chat room topics
// each topic name starts with `topic_` followed by the ID of the chat room
// Ex: topic_1, topic_2
/*private void subscribeToAllTopics() {
for (ChatRoom cr : chatRoomArrayList) {
Intent intent = new Intent(this, GcmIntentService.class);
intent.putExtra(GcmIntentService.KEY, GcmIntentService.SUBSCRIBE);
intent.putExtra(GcmIntentService.TOPIC, "topic_" + cr.getId());
startService(intent);
}
}*/
private void launchLoginActivity() {
Intent intent = new Intent(MainActivity.this, LoginActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
finish();
}
#Override
protected void onResume() {
super.onResume();
// register GCM registration complete receiver
LocalBroadcastManager.getInstance(this).registerReceiver(mRegistrationBroadcastReceiver,
new IntentFilter(Config.REGISTRATION_COMPLETE));
// register new push message receiver
// by doing this, the activity will be notified each time a new message arrives
LocalBroadcastManager.getInstance(this).registerReceiver(mRegistrationBroadcastReceiver,
new IntentFilter(Config.PUSH_NOTIFICATION));
// clearing the notification tray
NotificationUtils.clearNotifications();
}
#Override
protected void onPause() {
LocalBroadcastManager.getInstance(this).unregisterReceiver(mRegistrationBroadcastReceiver);
super.onPause();
}
// starting the service to register with GCM
private void registerGCM() {
Intent intent = new Intent(this, GcmIntentService.class);
intent.putExtra("key", "register");
startService(intent);
}
private boolean checkPlayServices() {
GoogleApiAvailability apiAvailability = GoogleApiAvailability.getInstance();
int resultCode = apiAvailability.isGooglePlayServicesAvailable(this);
if (resultCode != ConnectionResult.SUCCESS) {
if (apiAvailability.isUserResolvableError(resultCode)) {
apiAvailability.getErrorDialog(this, resultCode, PLAY_SERVICES_RESOLUTION_REQUEST)
.show();
} else {
Log.i(TAG, "This device is not supported. Google Play Services not installed!");
Toast.makeText(getApplicationContext(), "This device is not supported. Google Play Services not installed!", Toast.LENGTH_LONG).show();
finish();
}
return false;
}
return true;
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu_main, menu);
return true;
}
public boolean onOptionsItemSelected(MenuItem menuItem) {
switch (menuItem.getItemId()) {
case R.id.action_logout:
MyApplication.getInstance().logout();
break;
}
return super.onOptionsItemSelected(menuItem);
}
}
ChatRoomsAdapter:
package com.wipro.chat.adapter;
/**
* Created by COMP on 16-06-2016.
*/
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.GestureDetector;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import com.wipro.chat.R;
import com.wipro.chat.model.ChatRoom;
public class ChatRoomsAdapter extends RecyclerView.Adapter<ChatRoomsAdapter.ViewHolder> {
private Context mContext;
private ArrayList<ChatRoom> chatRoomArrayList;
private static String today;
public class ViewHolder extends RecyclerView.ViewHolder {
public TextView name, message, timestamp, count;
public ViewHolder(View view) {
super(view);
name = (TextView) view.findViewById(R.id.name);
message = (TextView) view.findViewById(R.id.message);
timestamp = (TextView) view.findViewById(R.id.timestamp);
count = (TextView) view.findViewById(R.id.count);
}
}
public ChatRoomsAdapter(Context mContext, ArrayList<ChatRoom> chatRoomArrayList) {
this.mContext = mContext;
this.chatRoomArrayList = chatRoomArrayList;
Calendar calendar = Calendar.getInstance();
today = String.valueOf(calendar.get(Calendar.DAY_OF_MONTH));
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.chat_rooms_list_row, parent, false);
return new ViewHolder(itemView);
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
ChatRoom chatRoom = chatRoomArrayList.get(position);
holder.name.setText(chatRoom.getName());
holder.message.setText(chatRoom.getLastMessage());
if (chatRoom.getUnreadCount() > 0) {
holder.count.setText(String.valueOf(chatRoom.getUnreadCount()));
holder.count.setVisibility(View.VISIBLE);
} else {
holder.count.setVisibility(View.GONE);
}
holder.timestamp.setText(getTimeStamp(chatRoom.getTimestamp()));
}
#Override
public int getItemCount() {
return chatRoomArrayList.size();
}
public static String getTimeStamp(String dateStr) {
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String timestamp = "";
today = today.length() < 2 ? "0" + today : today;
try {
Date date = format.parse(dateStr);
SimpleDateFormat todayFormat = new SimpleDateFormat("dd");
String dateToday = todayFormat.format(date);
format = dateToday.equals(today) ? new SimpleDateFormat("hh:mm a") : new SimpleDateFormat("dd LLL, hh:mm a");
String date1 = format.format(date);
timestamp = date1.toString();
} catch (ParseException e) {
e.printStackTrace();
}
return timestamp;
}
public interface ClickListener {
void onClick(View view, int position);
void onLongClick(View view, int position);
}
public static class RecyclerTouchListener implements RecyclerView.OnItemTouchListener {
private GestureDetector gestureDetector;
private ChatRoomsAdapter.ClickListener clickListener;
public RecyclerTouchListener(Context context, final RecyclerView recyclerView, final ChatRoomsAdapter.ClickListener clickListener) {
this.clickListener = clickListener;
gestureDetector = new GestureDetector(context, new GestureDetector.SimpleOnGestureListener() {
#Override
public boolean onSingleTapUp(MotionEvent e) {
return true;
}
#Override
public void onLongPress(MotionEvent e) {
View child = recyclerView.findChildViewUnder(e.getX(), e.getY());
if (child != null && clickListener != null) {
clickListener.onLongClick(child, recyclerView.getChildLayoutPosition(child));
}
}
});
}
#Override
public boolean onInterceptTouchEvent(RecyclerView rv, MotionEvent e) {
View child = rv.findChildViewUnder(e.getX(), e.getY());
if (child != null && clickListener != null && gestureDetector.onTouchEvent(e)) {
clickListener.onClick(child, rv.getChildLayoutPosition(child));
}
return false;
}
#Override
public void onTouchEvent(RecyclerView rv, MotionEvent e) {
}
#Override
public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) {
}
}
}
PHP code which is retrieving the chatroom is like:
/* * *
* fetching all chat rooms
*/
$app->get('/chat_rooms', function() {
$response = array();
$db = new DbHandler();
// fetching all user tasks
$result = $db->getAllChats();
$response["error"] = false;
$response["chat_rooms"] = array();
// pushing single chat room into array
while ($chat_room = $result->fetch_assoc()) {
$tmp = array();
$tmp["user_id"] = $chat_room["user_id"];
$tmp["name"] = $chat_room["name"];
$tmp["created_at"] = $chat_room["created_at"];
array_push($response["chat_rooms"], $tmp);
}
echoRespnse(200, $response);
});
public function getAllChats() {
$stmt = $this->conn->prepare("SELECT user_id, name, created_at FROM users");
$stmt->execute();
$tasks = $stmt->get_result();
$stmt->close();
return $tasks;
}
There are two user chats in my database, namely Messaging, Chat and I'm getting the both from database into ArrayList but it is only showing Messaging.
Adapter display:
Response from database:
Check recycler_view in your main layout. The height should be set to "wrap_content".
I used a listview to display the check boxes in my activity. I also put a check to see atleast one check box is checked otherwise it will toast a message asking the user to please select atleast one value. Below are my two classes. Problem which i am having is that when i press the submit button without selecting a check box then i get a message to select atleast one checkbox. But when i select and deselect the check box and then submit it then it goes to the next activity with value of the check box which i dont want. It should not go to the other activity till i select one checkbox. Please help me with this problem.
ConnectAdapter.java
package com.arcadian.adapter;
import java.util.ArrayList;
import android.content.Context;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.Toast;
import android.widget.CompoundButton.OnCheckedChangeListener;
import com.arcadian.genconian.R;
public class ConnectAdapter extends ArrayAdapter<ConnectModel> {
public ArrayList<ConnectModel> stateList;
Context cntx;
public static ConnectModel connect;
CheckBox cb;
public ConnectAdapter(Context context, int textViewResourceId,
ArrayList<ConnectModel> stateList) {
super(context, textViewResourceId, stateList);
this.cntx = context;
this.stateList = new ArrayList<ConnectModel>();
this.stateList.addAll(stateList);
}
public class ViewHolder {
CheckBox connect_CB;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
Log.v("ConvertView", String.valueOf(position));
if (convertView == null) {
LayoutInflater vi = (LayoutInflater) cntx
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = vi.inflate(R.layout.list_connect_row, null);
holder = new ViewHolder();
holder.connect_CB = (CheckBox) convertView
.findViewById(R.id.connect_CB);
convertView.setTag(holder);
holder.connect_CB
.setOnCheckedChangeListener(new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton v,
boolean isChecked) {
// TODO Auto-generated method stub
cb = (CheckBox) v;
if (v.isChecked()) {
connect = (ConnectModel) cb.getTag();
/*
* Toast.makeText( cntx.getApplicationContext(),
* "Checkbox: " + cb.getText() + " -> " +
* cb.isChecked(), Toast.LENGTH_LONG).show();
*/
connect.setSelected(cb.isChecked());
}
// else{
// Toast.makeText(getContext(), "Select aleast one.", Toast.LENGTH_LONG).show();
// String select = null;
// }
}
});
}
else {
holder = (ViewHolder) convertView.getTag();
}
ConnectModel state = stateList.get(position);
holder.connect_CB.setText(state.getName());
holder.connect_CB.setChecked(state.isSelected());
holder.connect_CB.setTag(state);
return convertView;
}
}
**ConnectActivity.java**
package com.arcadian.genconian;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;
import com.arcadian.adapter.ConnectAdapter;
import com.arcadian.adapter.ConnectModel;
import com.arcadian.utils.CommonActivity;
import com.arcadian.utils.Constants;
import com.arcadian.utils.JSONParser;
public class ConnectActivity extends CommonActivity implements OnClickListener {
ConnectAdapter dataAdapter = null;
ArrayList<ConnectModel> stateList;
private ProgressDialog pDialog;
String to_connect;
String response;
private StringBuffer responseText;
int success;
String email, type;
private String status;
String select;
ConnectModel _ConnectModel;
ConnectModel selstate;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_connect);
// Generate list View from ArrayList
displayListView();
responseText = new StringBuffer();
Button submit_BT = (Button) findViewById(R.id.submit_BT);
submit_BT.setOnClickListener(this);
Intent i = getIntent();
email = i.getStringExtra("user_email");
type = i.getStringExtra("type");
}
private void displayListView() {
// Array list of countries
stateList = new ArrayList<ConnectModel>();
_ConnectModel = new ConnectModel("All", false);
stateList.add(_ConnectModel);
_ConnectModel = new ConnectModel("Stream", false);
stateList.add(_ConnectModel);
_ConnectModel = new ConnectModel("Industry", false);
stateList.add(_ConnectModel);
_ConnectModel = new ConnectModel("Field", false);
stateList.add(_ConnectModel);
_ConnectModel = new ConnectModel("Batchmates", false);
stateList.add(_ConnectModel);
// create an ArrayAdaptar from the String Array
dataAdapter = new ConnectAdapter(this, android.R.layout.simple_list_item_multiple_choice,
stateList);
ListView to_connect_LV = (ListView) findViewById(R.id.to_connect_LV);
// Assign adapter to ListView
to_connect_LV.setAdapter(dataAdapter);
}
#Override
public void onClick(View v) {
int id = v.getId();
// openRequest.setCallback(statusCallback);
// session.openForRead(openRequest);
// loginProgress.setVisibility(View.VISIBLE);
switch (id) {
case R.id.submit_BT:
ArrayList<ConnectModel> stateList = dataAdapter.stateList;
response = "";
for (int i = 0; i < stateList.size(); i++) {
ConnectModel state = stateList.get(i);
selstate = ConnectAdapter.connect;
if(selstate!=null)
if (selstate.equals(state)) {
select = "abc";
if ((stateList.size() - 1) >= i) {
responseText.append(state.getName() + ",");
String text = state.getName();
response = responseText.toString();
loge("response", "response text is" + responseText);
}
else {
responseText.append(state.getName());
}
}
}
if (select == null) {
Toast.makeText(getApplicationContext(), "Select at least one.",
Toast.LENGTH_SHORT).show();
} else {
new Connect().execute();
}
/*
* if(response.length()>1) {
* if(response.substring(response.length()-1).equals(",") ) {
* response
* =response.replace(response.substring(response.length()-1), "" );
*
* }
*
* }
*
* if (response.length() <= 1) { response =
* "batch,stream,field,industry"; }
*/
break;
default:
break;
}
}
public class Connect extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(ConnectActivity.this);
pDialog.setMessage("Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected String doInBackground(String... params) {
to_connect = responseText.toString();
String connect_url = Constants.REMOTE_URL + "/GenconianApi/reg2";
log("to", "connect url is:" + connect_url);
try {
JSONParser jsonParser = new JSONParser();
List<NameValuePair> Params = new ArrayList<NameValuePair>();
String res;
Intent email_Intent = getIntent();
email = email_Intent.getStringExtra("user_email");
type = email_Intent.getStringExtra("type");
loge("email in", "connectactivity is:" + email);
int len = response.length();
StringBuilder builder = new StringBuilder();
for (int i = 0; i < len - 1; i++) {
builder.append(Character.toLowerCase(response.charAt(i)));
}
Params.add(new BasicNameValuePair("email", email));
Params.add(new BasicNameValuePair("connected", builder
.toString()));
Log.e("responce", builder.toString());
JSONObject json = jsonParser.makeHttpRequest(connect_url,
"POST", Params);
loge("in reg2", json.toString());
JSONObject obj = json.getJSONObject("Status");
loge("obj is", obj.toString());
status = obj.getString("status");
loge("user", "status is:" + status);
success = Integer.parseInt(status);
loge("chk", "rslt code is:" + success);
if (success == 1) {
Intent k = new Intent(ConnectActivity.this,
FindFriends.class);
loge("chk", "inside success:" + success);
k.putExtra("user_email", email);
k.putExtra("type", type);
overridePendingTransition(R.anim.slide_in, R.anim.slide_out);
startActivity(k);
loge("email", "" + email);
return json.getString(Constants.TAG_MESSAGE);
} else {
Log.e("Login Failure!",
json.getString(Constants.TAG_MESSAGE));
return json.getString(Constants.TAG_MESSAGE);
}
}
catch (JSONException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
pDialog.dismiss();
}
}
#Override
public void onBackPressed() {
// TODO Auto-generated method stub
super.onBackPressed();
Intent i = new Intent(ConnectActivity.this, More.class);
i.putExtra("user-email", email);
i.putExtra("type", type);
startActivity(i);
}
}
You can put all the checkboxes in a Collection of checkboxes.
Upon clicking submit button, loop through all checkboxes to see anyone of them is checked at that moment
Collection<CheckBox> boxes=new Vector<CheckBox>();
...
public void onClick(View v){
boolean anyoneChecked=false;
for(CheckBox b: boxes){
if(b.isChecked()){
anyoneChecked=true;
}
}
if(!anyoneChecked){
return;
}
// go to next activity
}
I am trying to load a popup window that contains an edittext and a datepicker.
I have included my code below.
Basically the initial window is closed as expected, but my pop up doesn't appear?
I have checked the xml call and the id is correct, no errors and for some reason my logcat in eclipse has stopped working but thats a different issue!
Hopefully someone can tell me what I have missed and / or doing wrong? I am new to android programming so please ignore my ignorance if it is something simple!
package com.zelphe.zelpheapp;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Calendar;
import java.util.GregorianCalendar;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;
import com.zelphe.zelpheapp.library.DatabaseHandler;
import com.zelphe.zelpheapp.library.UserFunctions;
public class LoginActivity extends Activity
{
Button btnLogin;
Button Btnregister;
Button passreset;
EditText inputEmail, inputName, inputPassword;
DatePicker inputDOB;
private TextView loginErrorMsg;
/**
* Called when the activity is first created.
*/
private static String KEY_SUCCESS = "success";
private static String KEY_REGISTER = "doRegister";
private static String KEY_UID = "uid";
private static String KEY_USERNAME = "uname";
private static String KEY_FIRSTNAME = "fname";
private static String KEY_LASTNAME = "lname";
private static String KEY_EMAIL = "email";
private static String KEY_CREATED_AT = "created_at";
Button btnReg;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layout_test);
inputEmail = (EditText) findViewById(R.id.email);
inputPassword = (EditText) findViewById(R.id.password);
btnLogin = (Button) findViewById(R.id.loginbtn);
//loginErrorMsg = (TextView) findViewById(R.id.loginErrorMsg);
/**
* Login button click event
* A Toast is set to alert when the Email and Password field is empty
**/
btnLogin.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
if ( ( !inputEmail.getText().toString().equals("")) && ( !inputPassword.getText().toString().equals("")) )
{
NetAsync(view);
}
else if ( ( !inputEmail.getText().toString().equals("")) )
{
Toast.makeText(getApplicationContext(),
"Password field empty", Toast.LENGTH_SHORT).show();
}
else if ( ( !inputPassword.getText().toString().equals("")) )
{
Toast.makeText(getApplicationContext(),
"Email field empty", Toast.LENGTH_SHORT).show();
}
else
{
Toast.makeText(getApplicationContext(),
"Email and Password field are empty", Toast.LENGTH_SHORT).show();
}
}
});
}
/**
* Async Task to check whether internet connection is working.
**/
private class NetCheck extends AsyncTask<String,String,Boolean>
{
private ProgressDialog nDialog;
#Override
protected void onPreExecute(){
super.onPreExecute();
nDialog = new ProgressDialog(LoginActivity.this);
nDialog.setTitle("Checking Network");
nDialog.setMessage("Loading..");
nDialog.setIndeterminate(false);
nDialog.setCancelable(false);
nDialog.show();
}
/**
* Gets current device state and checks for working internet connection by trying Google.
**/
#Override
protected Boolean doInBackground(String... args){
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
if (netInfo != null && netInfo.isConnected()) {
try {
URL url = new URL("http://www.google.com");
HttpURLConnection urlc = (HttpURLConnection) url.openConnection();
urlc.setConnectTimeout(3000);
urlc.connect();
if (urlc.getResponseCode() == 200) {
return true;
}
} catch (MalformedURLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return false;
}
#Override
protected void onPostExecute(Boolean th){
if(th == true){
nDialog.dismiss();
new ProcessLogin().execute();
}
else{
nDialog.dismiss();
loginErrorMsg.setText("Error in Network Connection");
}
}
}
/**
* Async Task to get and send data to My Sql database through JSON respone.
**/
private class ProcessLogin extends AsyncTask<String, String, JSONObject> {
private ProgressDialog pDialog;
String email,password;
#Override
protected void onPreExecute() {
super.onPreExecute();
inputEmail = (EditText) findViewById(R.id.email);
inputPassword = (EditText) findViewById(R.id.password);
email = inputEmail.getText().toString();
password = inputPassword.getText().toString();
pDialog = new ProgressDialog(LoginActivity.this);
pDialog.setTitle("Contacting Servers");
pDialog.setMessage("Logging in ...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected JSONObject doInBackground(String... args) {
UserFunctions userFunction = new UserFunctions();
JSONObject json = userFunction.loginUser(email, password);
return json;
}
#Override
protected void onPostExecute(JSONObject json) {
try {
if (json.getString(KEY_SUCCESS) != null) {
String res = json.getString(KEY_SUCCESS);
if(Integer.parseInt(res) == 1){
pDialog.setMessage("Loading User Space");
pDialog.setTitle("Getting Data");
DatabaseHandler db = new DatabaseHandler(getApplicationContext());
JSONObject json_user = json.getJSONObject("user");
/**
* Clear all previous data in SQlite database.
**/
UserFunctions logout = new UserFunctions();
logout.logoutUser(getApplicationContext());
db.addUser(json_user.getString(KEY_FIRSTNAME),json_user.getString(KEY_LASTNAME),json_user.getString(KEY_EMAIL),json_user.getString(KEY_USERNAME),json_user.getString(KEY_UID),json_user.getString(KEY_CREATED_AT));
/**
*If JSON array details are stored in SQlite it launches the User Panel.
**/
Intent upanel = new Intent(getApplicationContext(), MainActivity.class);
upanel.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
pDialog.dismiss();
startActivity(upanel);
/**
* Close Login Screen
**/
finish();
}else if(Integer.parseInt(res) == 2)
{
pDialog.dismiss();
Toast.makeText(getApplicationContext(),
"Incorrect Password!", Toast.LENGTH_SHORT).show();
}
else
{
pDialog.dismiss();
initiatePopupWindow();
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
private PopupWindow pwindo;
private void initiatePopupWindow()
{
try
{
// We need to get the instance of the LayoutInflater
LayoutInflater inflater = (LayoutInflater) LoginActivity.this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View layout = inflater.inflate(R.layout.activity_register,(ViewGroup)
findViewById(R.id.popup_element));
pwindo = new PopupWindow(layout, 350, 350, true);
pwindo.showAtLocation(layout, Gravity.CENTER, 0, 0);
btnReg = (Button) layout.findViewById(R.id.btnReg);
btnReg.setOnClickListener((android.view.View.OnClickListener) reguser);
}
catch (Exception e)
{
e.printStackTrace();
}
}
private OnClickListener reguser = new OnClickListener()
{
#Override
public void onClick(DialogInterface dialog, int which)
{
inputName = (EditText) findViewById(R.id.name);
inputDOB = (DatePicker) findViewById(R.id.dob);
if ( ( !inputName.getText().toString().equals("")) &&
( getAge(inputDOB.getDayOfMonth(), inputDOB.getMonth(), inputDOB.getYear()) > 15) )
{
//register user
}
else if ( ( inputName.getText().toString().equals("")) )
{
Toast.makeText(getApplicationContext(),
"Please enter your name", Toast.LENGTH_SHORT).show();
}
else if (( getAge(inputDOB.getDayOfMonth(), inputDOB.getMonth(), inputDOB.getYear()) < 16) )
{
Toast.makeText(getApplicationContext(),
"You must be at least 16 to use this app", Toast.LENGTH_SHORT).show();
}
}
};
}
public int getAge (int _year, int _month, int _day) {
GregorianCalendar cal = new GregorianCalendar();
int y, m, d, a;
y = cal.get(Calendar.YEAR);
m = cal.get(Calendar.MONTH);
d = cal.get(Calendar.DAY_OF_MONTH);
cal.set(_year, _month, _day);
a = y - cal.get(Calendar.YEAR);
if ((m < cal.get(Calendar.MONTH))
|| ((m == cal.get(Calendar.MONTH)) && (d < cal
.get(Calendar.DAY_OF_MONTH)))) {
--a;
}
if(a < 0)
throw new IllegalArgumentException("Age < 0");
return a;
}
public void NetAsync(View view){
new NetCheck().execute();
}
}
Embarassingly enough, there is no issue with the popup, I had an error further up in my code, doh!
Hi I am using
asmack-2010.05.07.jar for chating in android but my list is not refreshed after adding new friend and removing a friend. below I am using this code for chating
package com.demo.xmppchat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import org.jivesoftware.smack.Chat;
import org.jivesoftware.smack.ConnectionConfiguration;
import org.jivesoftware.smack.MessageListener;
import org.jivesoftware.smack.PacketListener;
import org.jivesoftware.smack.Roster;
import org.jivesoftware.smack.RosterEntry;
import org.jivesoftware.smack.RosterListener;
import org.jivesoftware.smack.XMPPConnection;
import org.jivesoftware.smack.XMPPException;
import org.jivesoftware.smack.filter.MessageTypeFilter;
import org.jivesoftware.smack.filter.PacketFilter;
import org.jivesoftware.smack.packet.Message;
import org.jivesoftware.smack.packet.Packet;
import org.jivesoftware.smack.packet.Presence;
import org.jivesoftware.smack.packet.RosterPacket.ItemType;
import org.jivesoftware.smack.util.StringUtils;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
public class CustomizedListView extends Activity {
static final String KEY_TITLE = "title";
static final String KEY_THUMB_URL = "thumb_url";
public static final String HOST = "talk.google.com";
public static final int PORT = 5222;
public static final String SERVICE = "gmail.com";
public static final String USERNAME = "" + "" + ""
+ "demo#gmail.com";
public static final String PASSWORD = "xxxxxx";
static String FRIEND = " " ;
public static final String friend_xmpp_id = "asdf#gmail.com";
public static final String friend_xmpp_id1 = "sfsfds.mca#gmail.com";
public static final String friend_xmpp_id2 = "sffasds#gmail.com";
public static final String friend_xmpp_id3 = "chipkali#gmail.com";
Button button;
public static String addfri;
public static String removefri;
// public static final String Friends = "";
public static ArrayList<HashMap<String, String>> usersList;
ListView list;
LazyAdapter adapter;
private String USER_STATE;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
usersList = new ArrayList<HashMap<String, String>>();
ConnectionConfiguration connConfig = new ConnectionConfiguration(HOST,PORT, SERVICE);
Constants.connection = new XMPPConnection(connConfig);
try {
Constants.connection.connect();
} catch (XMPPException ex) {
}
try {
Constants.connection.login(USERNAME, PASSWORD);
} catch (XMPPException e) {
e.printStackTrace();
}
Log.i("XMPPChatDemoActivity","Logged in as " + Constants.connection.getUser());
Presence presence = new Presence(Presence.Type.available);
Constants.connection.sendPacket(presence);
setConnection(Constants.connection);
Roster roster = Constants.connection.getRoster();
Collection<RosterEntry> entries = roster.getEntries();
Log.i("size of entries", "size of entries===" + entries.size());
for (RosterEntry entry : entries) {
HashMap<String, String> map = new HashMap<String, String>();
Presence entryPresence = roster.getPresence(entry.getUser());
Presence.Type type = entryPresence.getType();
map.put("USER", entry.getUser().toString());
map.put("STATUS", type.toString());
Log.i("USER", "Users Are::" + entry.getUser().toString());
usersList.add(map);
}
roster.addRosterListener(new RosterListener() {
#Override
public void presenceChanged(Presence arg0) {
}
#Override
public void entriesUpdated(Collection<String> arg0) {
// TODO Auto-generated method stub
}
#Override
public void entriesDeleted(Collection<String> arg0) {
// TODO Auto-generated method stub
}
//connection is XMPPConnection
//friend_xmpp_id is friend id
//Tags.XMPP_HOST is host name
#Override
public void entriesAdded(Collection<String> arg0) {
// TODO Auto-generated method stub
}
});
list = (ListView) findViewById(R.id.list);
adapter = new LazyAdapter(this, usersList);
adapter.notifyDataSetChanged();
list.setAdapter(adapter);
final Handler handler = new Handler();
handler.postDelayed( new Runnable() {
#Override
public void run() {
adapter.notifyDataSetChanged();
handler.postDelayed( this, 1 * 1000 );
}
}, 1 * 1000 );
Log.d("notifyyy", "data set change firing timer now ................................... ");
// Click event for single list row
list.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,int position, long id) {
HashMap<String, String> song = new HashMap<String, String>();
song = usersList.get(position);
Log.i("getting user FRIENDDDDDDDDDDDDD name is====", "===="+ song.get("USER"));
FRIEND = song.get("USER");
//String Friend = song.get("USER");
Presence presence = new Presence(Presence.Type.available);
Constants.connection.sendPacket(presence);
Chat chat = Constants.connection.getChatManager().createChat(
song.get("USER"), new MessageListener() {
public void processMessage(Chat chat,Message message) {
if (message.getType() == Message.Type.chat)
System.out.println(chat.getParticipant()+ " says: " + message.getBody());
}
});
/*
* try { chat.sendMessage("hi........"); } catch (XMPPException
* e) { // TODO Auto-generated catch block e.printStackTrace();
* }
*/
Intent intent = new Intent(CustomizedListView.this,
XMPPChatDemoActivity.class);
intent.putExtra("HOST", "talk.google.com");
intent.putExtra("PORT", 5222);
intent.putExtra("SERVICE", "gmail.com");
intent.putExtra("USERNAME", "hidost#gmail");
intent.putExtra("PASSWORD", "iloveindiademo");
intent.putExtra("FRI", FRIEND);
startActivity(intent);
}
});
}
private void setUserPresence(int i) {
// TODO Auto-generated method stub
}
public void setConnection(XMPPConnection connection) {
Constants.connection = connection;
if (connection != null) {
// Add a packet listener to get messages sent to us
PacketFilter filter = new MessageTypeFilter(Message.Type.chat);
connection.addPacketListener(new PacketListener() {
#Override
public void processPacket(Packet packet) {
Message message = (Message) packet;
if (message.getBody() != null) {
String fromName = StringUtils.parseBareAddress(message.getFrom());
Log.i("XMPPChatDemoActivity", "Text Recieved "+ message.getBody() + " from " + fromName);
Constants.messages.add(fromName + ":");
Constants.messages.add(message.getBody());
// Add the incoming message to the list view
}
}
}, filter);
}
try {
View.OnClickListener handler = new View.OnClickListener(){
public void onClick(View v) {
//we will use switch statement and just
//get thebutton's id to make things easier
switch (v.getId()) {
case R.id.button1: //toast will be shown
// Toast.makeText(getBaseContext(), "You Clicked Show Toast Button!", Toast.LENGTH_SHORT).show();
String newfri = friend_xmpp_id;
addFriend(newfri);
break;
case R.id.button2: //toast will be shown
// Toast.makeText(getBaseContext(), "You Clicked Show Toast Button!", Toast.LENGTH_SHORT).show();
String remfri = friend_xmpp_id1;
removeFriend(remfri);
break;
}
}
private void removeFriend(String remfri) {
//public void addFriend(String friend_xmpp_id)
//usersList.clear();
removefri = remfri;
{
try {
Constants.connection.getRoster().setSubscriptionMode(Roster.SubscriptionMode.accept_all);
Constants.connection.getRoster().createEntry(removefri, removefri, null);
Collection<RosterEntry> entries = Constants.connection.getRoster().getEntries();
for (RosterEntry entry : entries)
{
System.out.println("name..."+entry.getUser()+"...type.."+entry.getType());
if(entry.getType()==ItemType.none)
{
Presence unsubscribe = new Presence(Presence.Type.unsubscribe);
unsubscribe.setTo(removefri);
Constants.connection.sendPacket(unsubscribe);
// usersList.clear();
usersList.remove(removefri);
Log.d("removed"," the best friend " + removefri);
Log.d("size on removing" ," ................friendddddd" + usersList.size());
// usersList.
}
}
System.out.println(" Are u sure u want to remove this friend from list "+removefri+"#"+HOST );
} catch (XMPPException e) {
e.printStackTrace();
}
}
}
private void addFriend(String newfri) {
//public void addFriend(String friend_xmpp_id)
addfri = newfri;
{
try {
Constants.connection.getRoster().setSubscriptionMode(Roster.SubscriptionMode.accept_all);
adapter.notifyDataSetChanged();
Constants.connection.getRoster().createEntry(addfri, addfri, null);
Collection<RosterEntry> entries = Constants.connection.getRoster().getEntries();
for (RosterEntry entry : entries)
{
Intent intent = new Intent(getApplicationContext(),CustomizedListView.class);
startActivity(intent);
System.out.println("name..."+entry.getUser()+"...type.."+entry.getType());
if(entry.getType()==ItemType.none)
{
Presence subscribe = new Presence(Presence.Type.subscribed);
subscribe.setTo(addfri);
Constants.connection.sendPacket(subscribe);
}
}
System.out.println("adding NEW FRIEND friend ..................."+addfri+"#"+HOST );
} catch (XMPPException e) {
e.printStackTrace();
}
}
}
};
//we will set the listeners
findViewById(R.id.button1).setOnClickListener(handler);
findViewById(R.id.button2).setOnClickListener(handler);
}catch(Exception e){
Log.e("Android Button Tutorial", e.toString());
}
}
}
I want to interrupt a thread1 from another thread2 but when I try make the thread1.interrupt(); call I get a null pointer error.
I'm making an android app, I'm on an android login page and when I login I create and start a thread called sessionTimer (which does a session countdown say 2min). What I want is that when I press logout in a different activity that I go to the login page and my sessionTimer thread should be interrupted so that I can start a new login session with max time.
package com.AndroidApp.Login;
import java.security.GeneralSecurityException;
import java.security.MessageDigest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.AndroidApp.R;
import com.AndroidApp.domain.Utente;
import com.AndroidApp.pagine.MenuPagina;
public class LoginActivity extends Activity {
final String TAG = "LogIN";
ArrayList<HashMap<String, String>> mylist;
private Button bLogin, bExit;
private EditText utente, passwd;
private MediaPlayer mpButtonClick = null;
private SharedPreferences mPreferences;
public volatile Thread sessionTimer;
public long tId = -1;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.login);
mPreferences = getSharedPreferences("CurrentUser", MODE_PRIVATE);
SharedPreferences.Editor editor = mPreferences.edit();
editor.clear();
editor.commit();
String nome = mPreferences.getString("nome", "Nessuno");
setTitle("Sessione di : " + nome);
Log.w("TotThreads", Integer.toString(Thread.activeCount()));
/*
final SessionTimer st = new SessionTimer();
*/
if(MenuPagina.reset){
Log.w("sessionTimer ID", Long.toString(sessionTimer.getId()));
if (sessionTimer == null)
Log.w("sessionTimer", "sessionTimer is NULL");
sessionTimer.interrupt();
System.out.println("end current session");
//st.stopRequest();
}
if (!checkLoginInfo()) {
mpButtonClick = MediaPlayer.create(this, R.raw.button);
bLogin = (Button)findViewById(R.id.bLogin);
bLogin.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
mpButtonClick.start();
Log.v(TAG, "Trying to Login");
utente = (EditText)findViewById(R.id.etUtente);
passwd = (EditText)findViewById(R.id.etPassword);
String username = utente.getText().toString();
username = ("ccce#eex.it");
String password = md5(passwd.getText().toString());
password = md5("12345");
XMLFunctionsLogin.getInstance().setNewURL("u=" + username + "&p=" + password);
String xml = XMLFunctionsLogin.getXML();
Document doc = XMLFunctionsLogin.xmlFromString(xml);
int status = XMLFunctionsLogin.errStatus(doc);
Log.v("status", Integer.toString(status));
if ((status == 0)) {
NodeList nodes = doc.getElementsByTagName("login");
Element e = (Element) nodes.item(0);
Utente utente = new Utente();
utente.setIdUtente(XMLFunctionsLogin.getValue(e, "idUtente"));
utente.setNome(XMLFunctionsLogin.getValue(e, "nome"));
utente.setCognome(XMLFunctionsLogin.getValue(e, "cognome"));
Log.v("utente", utente.getCognome().toString());
List<NameValuePair> nvps = new ArrayList<NameValuePair>(2);
nvps.add(new BasicNameValuePair("utente", username));
nvps.add(new BasicNameValuePair("password", password));
Log.v(TAG, nvps.get(0).toString());
Log.v(TAG, nvps.get(1).toString());
// Store the username and password in SharedPreferences after the successful login
SharedPreferences.Editor editor = mPreferences.edit();
editor.putString("userName", username);
editor.putString("password", password);
editor.putString("idUtente", utente.getIdUtente());
editor.putString("nome", utente.getNome());
editor.putString("cognome", utente.getCognome());
editor.commit();
Log.v(TAG, "timer");
Log.v("RESET", Boolean.toString(MenuPagina.reset));
/*
Thread t = new Thread(st);
t.start();
*/
sessionTimer = new Thread() {
#Override
public void run() {
long tId = Thread.currentThread().getId();
Log.w("TTthread Id", Long.toString(tId));
for (int i = 30; i >= 0; i -= 1) {
if ((i == 0) || (MenuPagina.reset)) {
System.out.print("timer finito");
Log.i("Timer", "timer finito");
LoginActivity.this.runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(LoginActivity.this, "ti si รจ scaduta la sessione", Toast.LENGTH_LONG).show();
}
});
Intent intent = new Intent(getApplicationContext(), LoginActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
//System.exit(0);
} try {
Thread.sleep(1000);
Log.i("Timer", Integer.toString(i));
} catch (InterruptedException e) {
Log.i("Catch", "Catchhhhhhhhhhhh");
e.printStackTrace();
Thread.currentThread().interrupt();
return;
}
}
}
};
sessionTimer.start();
Log.v(TAG, "Successo2");
Toast.makeText(LoginActivity.this, "LogIn con successo", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(getApplicationContext()/*LoginActivity.this*/, MenuPagina.class);
startActivity(intent);
} else {
final String errorMessage = XMLFunctionsLogin.errStatusDesc(doc);
Log.v("fallimento", errorMessage);
LoginActivity.this.runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(LoginActivity.this, errorMessage, Toast.LENGTH_LONG).show();
}
});
Intent intent = getIntent();
finish();
startActivity(intent);
}
}
});
bExit = (Button)findViewById(R.id.bExit);
bExit.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
mpButtonClick.start();
finish();
}
});
}
}
//Checking whether the username and password has stored already or not
private final boolean checkLoginInfo() {
boolean username_set = mPreferences.contains("UserName");
boolean password_set = mPreferences.contains("PassWord");
if ( username_set || password_set ) {
return true;
}
return false;
}
//md5 for crypting and hash
private static String md5(String data) {
byte[] bdata = new byte[data.length()];
int i;
byte[] hash;
for (i = 0; i < data.length(); i++)
bdata[i] = (byte) (data.charAt(i) & 0xff);
try {
MessageDigest md5er = MessageDigest.getInstance("MD5");
hash = md5er.digest(bdata);
} catch (GeneralSecurityException e) {
throw new RuntimeException(e);
}
StringBuffer r = new StringBuffer(32);
for (i = 0; i < hash.length; i++) {
String x = Integer.toHexString(hash[i] & 0xff);
if (x.length() < 2)
r.append("0");
r.append(x);
}
return r.toString();
}
}
So what happens is when I logout and I come back to the login page and MenuPagina.reset = true I get an error saying that sessionTimer is null. Why?
I've tried also using a seperate class for the thread but I get the same null pointer error.
onCreate runs when your Activity is being created or re-created, either way it's a new object, so any local variables have to be initialized again, in your case sessionTimer would be null until the new Thread() {} call.
If you need to persist a reference to your thread, use more global object than your Activity is - Application, that's a base class for maintaining global application state. You can always access it by calling Context.getApplicationContext(). Anyway, read the docs.