Hey guys i have an issue with my current application, The issue is that for some reason whenever i try clicking the "Save Register" button within my menu the application crashes. It is saying println message but i am sure i have placed hello world in a String?
I would like to mention that i have been following a tutorial found on Youtube posting data to google spreadsheets and other tutorials to create this AP manager, You may have noticed within my code but the next step is to Save the array list into the spread sheet which is the next step. However for now i would i cannot simply get the menu button to save the "Hello World" message into Spreadsheets
My Log Cat shows:
Process: com.example.gavin.wifiattendance, PID: 2266
java.lang.NullPointerException: println needs a message
at android.util.Log.println_native(Native Method)
at android.util.Log.i(Log.java:160)
at com.example.gavin.wifiattendance.MainActivity.postData(MainActivity.java:93)
at com.example.gavin.wifiattendance.MainActivity.onMenuItemSelected(MainActivity.java:143)
at com.android.internal.policy.impl.PhoneWindow.onMenuItemSelected(PhoneWindow.java:1127)
at com.android.internal.view.menu.MenuBuilder.dispatchMenuItemSelected(MenuBuilder.java:761)
at com.android.internal.view.menu.MenuItemImpl.invoke(MenuItemImpl.java:152)
at com.android.internal.view.menu.MenuBuilder.performItemAction(MenuBuilder.java:904)
at com.android.internal.view.menu.ListMenuPresenter.onItemClick(ListMenuPresenter.java:165)
at android.widget.AdapterView.performItemClick(AdapterView.java:300)
at android.widget.AbsListView.performItemClick(AbsListView.java:1143)
My Main activity file:
public class MainActivity extends Activity{
boolean wasApEnabled = false;
static AccessPoint wifiAP;
private WifiManager wifi;
static Button apButton;
static TextView textView;
final String myTag = "DocsUpload";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
apButton = (Button) findViewById(R.id.toggleBtn);
textView = (TextView) findViewById(R.id.wifiClients);
apButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
wifiAP.toggleWifiAP(wifi, MainActivity.this);
}
});
wifiAP = new AccessPoint(this);
wifi = (WifiManager) getSystemService(Context.WIFI_SERVICE);
scan();
//getWindow().addFlags(WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD|WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON|WindowManager.LayoutParams.FLAG_DIM_BEHIND);
}
private void scan(){
wifiAP.getClientList(false, new FinishScanListener() {
#Override
public void onFinishScan(final ArrayList<ClientScanResult> clients) {
textView.setText("WifiApState:" + wifiAP.getWifiApState()+ "\n\n");
textView.append("Clients: \n");
for (ClientScanResult clientScanResult : clients){
textView.append("====================\n");
textView.append("ipAddress: " + clientScanResult.getIpAddress() + "\n");
textView.append("Device: " + clientScanResult.getDevice() + "\n");
textView.append("macAddress: " + clientScanResult.getMacAddress() + "\n");
textView.append("isReachable: " + clientScanResult.isReachable() + "\n");
}
}
});
}
public void postData() {
String fullUrl = "https://docs.google.com/forms/d/1yipuuXd5V53Ol12U24Cl2H4RIdYtm622jIk13Zo26cM/formResponse";
HttpRequest mReq = new HttpRequest();
String col1 = "Hello";
String col2 = "World";
String data = "entry_272641491=" + URLEncoder.encode(col1) + "&" +
"entry_130393492=" + URLEncoder.encode(col2);
String response = mReq.sendPost(fullUrl, data);
Log.i(myTag, response);
}
#Override
public void onResume() {
super.onResume();
if (wasApEnabled) {
if (wifiAP.getWifiApState() != wifiAP.WIFI_STATE_ENABLED && wifiAP.getWifiApState() != wifiAP.WIFI_STATE_ENABLING) {
wifiAP.toggleWifiAP(wifi, MainActivity.this);
}
}
updateStatusDisplay();
}
#Override
public void onPause() {
super.onPause();
boolean wifiApIsOn = wifiAP.getWifiApState()==wifiAP.WIFI_STATE_ENABLED || wifiAP.getWifiApState()==wifiAP.WIFI_STATE_ENABLING;
if (wifiApIsOn){
wasApEnabled = true;
wifiAP.toggleWifiAP(wifi, MainActivity.this);
}else {
wasApEnabled = false;
}
updateStatusDisplay();
}
public static void updateStatusDisplay(){
if (wifiAP.getWifiApState()==wifiAP.WIFI_STATE_ENABLED || wifiAP.getWifiApState()==wifiAP.WIFI_STATE_ENABLING){
apButton.setText("Turn Off");
}else {
apButton.setText("Turn on");
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
menu.add(0,0,0, "Get Clients");
menu.add(0,1,0, "Save Register");
getMenuInflater().inflate(R.menu.menu_main, menu);
return super.onCreateOptionsMenu(menu);
}
public boolean onMenuItemSelected(int featureId, MenuItem item) {
switch (item.getItemId()){
case 0:
scan();
break;
case 1:
postData();
break;
}
return super.onMenuItemSelected(featureId, item);
}
}
Edit: After removing the log, the spread sheet no longer gets any information even when the button is pressed.
03-12 11:41:56.444 1903-1921/com.example.gavin.wifiattendance W/OpenGLRenderer﹕ Failed to set EGL_SWAP_BEHAVIOR on surface 0xa5c08180, error=EGL_SUCCESS
03-12 11:41:58.696 1903-1903/com.example.gavin.wifiattendance D/WifiAttendance﹕ Setting httpPost headers
03-12 11:41:58.696 1903-1903/com.example.gavin.wifiattendance D/Your App Name Here﹕ https://docs.google.com/forms/d/1yipuuXd5V53Ol12U24Cl2H4RIdYtm622jIk13Zo26cM/formResponse?entry_272641491=Hello&entry_130393492=World
03-12 11:41:58.697 1903-1903/com.example.gavin.wifiattendance E/WifiAttendance﹕ HttpUtils: android.os.NetworkOnMainThreadException
03-12 11:41:58.697 1903-1903/com.example.gavin.wifiattendance D/WifiAttendance﹕ Returning value:null
You're passing a null string to Log.i in postData. Don't do that. Its almost certainly because HTTP requests are asynchronous and you don't have a response yet. Since its just a log I'd delete the line.
Related
I want same activity as Main activity and i just want that the another activity should also receive the same data coming from bluetooth after switching to another activity but while switching to another activity the connection failure occurs and shows:
> W/BluetoothAdapter: getBluetoothService() called with no
> BluetoothManagerCallback I/Choreographer: Skipped 52 frames! The
> application may be doing too much work on its main thread.
Please help.
DeviceListActivity
public class DeviceListActivity extends Activity {
// Debugging for LOGCAT
private static final String TAG = "DeviceListActivity";
private static final boolean D = true;
// declare button for launching website and textview for connection status
//Button tlbutton;
TextView textView1;
// EXTRA string to send on to mainactivity
public static String EXTRA_DEVICE_ADDRESS = "device_address";
// Member fields
private BluetoothAdapter mBtAdapter;
private ArrayAdapter<String> mPairedDevicesArrayAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.device_list);
}
#Override
public void onResume()
{
super.onResume();
checkBTState();
textView1 = (TextView) findViewById(R.id.connecting);
textView1.setTextSize(40);
textView1.setText(" ");
// Initialize array adapter for paired devices
mPairedDevicesArrayAdapter = new ArrayAdapter<String>(this, R.layout.device_name);
// Find and set up the ListView for paired devices
ListView pairedListView = (ListView) findViewById(R.id.paired_devices);
pairedListView.setAdapter(mPairedDevicesArrayAdapter);
pairedListView.setOnItemClickListener(mDeviceClickListener);
// Get the local Bluetooth adapter
mBtAdapter = BluetoothAdapter.getDefaultAdapter();
// Get a set of currently paired devices and append to 'pairedDevices'
Set<BluetoothDevice> pairedDevices = mBtAdapter.getBondedDevices();
// Add previosuly paired devices to the array
if (pairedDevices.size() > 0) {
findViewById(R.id.title_paired_devices).setVisibility(View.VISIBLE);//make title viewable
for (BluetoothDevice device : pairedDevices) {
mPairedDevicesArrayAdapter.add(device.getName() + "\n" + device.getAddress());
}
} else {
String noDevices = getResources().getText(R.string.none_paired).toString();
mPairedDevicesArrayAdapter.add(noDevices);
}
}
// Set up on-click listener for the list (nicked this - unsure)
private AdapterView.OnItemClickListener mDeviceClickListener = new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> av, View v, int arg2, long arg3) {
textView1.setText("Connecting...");
// Get the device MAC address, which is the last 17 chars in the View
String info = ((TextView) v).getText().toString();
String address = info.substring(info.length() - 17);
// Make an intent to start next activity while taking an extra which is the MAC address.
Intent i = new Intent(DeviceListActivity.this, MainActivity.class);
i.putExtra(EXTRA_DEVICE_ADDRESS, address);
startActivity(i);
}
};
private void checkBTState() {
// Check device has Bluetooth and that it is turned on
mBtAdapter=BluetoothAdapter.getDefaultAdapter(); // CHECK THIS OUT THAT IT WORKS!!!
if(mBtAdapter==null) {
Toast.makeText(getBaseContext(), "Device does not support Bluetooth", Toast.LENGTH_SHORT).show();
} else {
if (mBtAdapter.isEnabled()) {
Log.d(TAG, "...Bluetooth ON...");
} else {
//Prompt user to turn on Bluetooth
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, 1);
}
}
}
}
MainActivity
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
Button btnOn, btnOff;
TextView txtString, txtStringLength, sensorView0, sensorView1, sensorView2, sensorView3;
Handler bluetoothIn;
final int handlerState = 0; //used to identify handler message
private BluetoothAdapter btAdapter = null;
private BluetoothSocket btSocket = null;
private StringBuilder recDataString = new StringBuilder();
public static ConnectedThread mConnectedThread;
// SPP UUID service - this should work for most devices
private static final UUID BTMODULEUUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
// String for MAC address
public static String address;
public static String address2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnOn = (Button) findViewById(R.id.buttonOn);
btnOff = (Button) findViewById(R.id.buttonOff);
txtString = (TextView) findViewById(R.id.txtString);
txtStringLength = (TextView) findViewById(R.id.testView1);
sensorView0 = (TextView) findViewById(R.id.sensorView0);
sensorView1 = (TextView) findViewById(R.id.sensorView1);
sensorView2 = (TextView) findViewById(R.id.sensorView2);
sensorView3 = (TextView) findViewById(R.id.sensorView3);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
// setSupportActionBar(toolbar);
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
bluetoothIn = new Handler() {
public void handleMessage(android.os.Message msg) {
if (msg.what == handlerState) { //if message is what we want
String readMessage = (String) msg.obj; // msg.arg1 = bytes from connect thread
recDataString.append(readMessage); //keep appending to string until ~
int endOfLineIndex = recDataString.indexOf("~"); // determine the end-of-line
if (endOfLineIndex > 0) { // make sure there data before ~
String dataInPrint = recDataString.substring(0, endOfLineIndex); // extract string
txtString.setText("Data Received = " + dataInPrint);
int dataLength = dataInPrint.length(); //get length of data received
txtStringLength.setText("String Length = " + String.valueOf(dataLength));
if (recDataString.charAt(0) == '#') //if it starts with # we know it is what we are looking for
{
String sensor0 = recDataString.substring(1, 5); //get sensor value from string between indices 1-5
String sensor1 = recDataString.substring(6, 10); //same again...
String sensor2 = recDataString.substring(11, 15);
String sensor3 = recDataString.substring(16, 20);
sensorView0.setText(" Sensor 0 Voltage = " + sensor0 + "V"); //update the textviews with sensor values
sensorView1.setText(" Sensor 1 Voltage = " + sensor1 + "V");
sensorView2.setText(" Sensor 2 Voltage = " + sensor2 + "V");
sensorView3.setText(" Sensor 3 Voltage = " + sensor3 + "V");
}
recDataString.delete(0, recDataString.length()); //clear all string data
// strIncom =" ";
dataInPrint = " ";
}
}
}
};
btAdapter = BluetoothAdapter.getDefaultAdapter(); // get Bluetooth adapter
checkBTState();
// Set up onClick listeners for buttons to send 1 or 0 to turn on/off LED
btnOff.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
mConnectedThread.write("0"); // Send "0" via Bluetooth
Toast.makeText(getBaseContext(), "Turn off LED", Toast.LENGTH_SHORT).show();
}
});
btnOn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
mConnectedThread.write("1"); // Send "1" via Bluetooth
Toast.makeText(getBaseContext(), "Turn on LED", Toast.LENGTH_SHORT).show();
}
});
}
private void checkBTState() {
if(btAdapter==null) {
Toast.makeText(getBaseContext(), "Device does not support bluetooth", Toast.LENGTH_LONG).show();
} else {
if (btAdapter.isEnabled()) {
} else {
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, 1);
}
}
}
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
#Override
public void onResume() {
super.onResume();
//Get MAC address from DeviceListActivity via intent
Intent intent = getIntent();
//Get the MAC address from the DeviceListActivty via EXTRA
address = intent.getStringExtra(DeviceListActivity.EXTRA_DEVICE_ADDRESS);
//create device and set the MAC address
BluetoothDevice device = btAdapter.getRemoteDevice(address);
try {
btSocket = createBluetoothSocket(device);
} catch (IOException e) {
Toast.makeText(getApplicationContext(), "Socket creation failed", Toast.LENGTH_LONG).show();
}
// Establish the Bluetooth socket connection.
try
{
btSocket.connect();
} catch (IOException e) {
try
{
btSocket.close();
} catch (IOException e2)
{
//insert code to deal with this
}
}
mConnectedThread = new ConnectedThread(btSocket);
mConnectedThread.start();
//I send a character when resuming.beginning transmission to check device is connected
//If it is not an exception will be thrown in the write method and finish() will be called
mConnectedThread.write("x");
}
public void onPause()
{
super.onPause();
try
{
//Don't leave Bluetooth sockets open when leaving activity
btSocket.close();
} catch (IOException e2) {
//insert code to deal with this
}
runOnUiThread(new Runnable() {
#Override
public void run() {
try {
mConnectedThread.wait();
} catch (Exception e) {
}
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
private BluetoothSocket createBluetoothSocket(BluetoothDevice device) throws IOException {
return device.createRfcommSocketToServiceRecord(BTMODULEUUID);
//creates secure outgoing connecetion with BT device using UUID
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.nav_additem) {
Intent addIntent = new Intent(getApplicationContext(),AddActivity2.class);
address2 = address;
startActivity(addIntent);
try {
}catch (Exception e){}
} else if (id == R.id.nav_viewItems) {
} else if (id == R.id.nav_favourite) {
} else if (id == R.id.nav_sensors) {
} else if (id == R.id.nav_share) {
} else if (id == R.id.nav_send) {
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
//create new class for connect thread
class ConnectedThread extends Thread {
private final InputStream mmInStream;
private final OutputStream mmOutStream;
//creation of the connect thread
public ConnectedThread(BluetoothSocket socket) {
InputStream tmpIn = null;
OutputStream tmpOut = null;
try {
//Create I/O streams for connection
tmpIn = socket.getInputStream();
tmpOut = socket.getOutputStream();
} catch (IOException e) { }
mmInStream = tmpIn;
mmOutStream = tmpOut;
}
public void run() {
byte[] buffer = new byte[256];
int bytes;
// Keep looping to listen for received messages
while (true) {
try {
bytes = mmInStream.read(buffer); //read bytes from input buffer
String readMessage = new String(buffer, 0, bytes);
// Send the obtained bytes to the UI Activity via handler
bluetoothIn.obtainMessage(handlerState, bytes, -1, readMessage).sendToTarget();
} catch (IOException e) {
break;
}
}
}
//write method
public void write(String input) {
byte[] msgBuffer = input.getBytes(); //converts entered String into bytes
try {
mmOutStream.write(msgBuffer); //write bytes over BT connection via outstream
} catch (IOException e) {
//if you cannot write, close the application
Toast.makeText(getBaseContext(), "Connection Failure", Toast.LENGTH_LONG).show();
finish();
}
}
}
}
Newbie question time again;
So within FormActivity I post then receive a response from a SQL table on a remote server, the data is put into a local SQLite table row. Then, I have a Fragment with several EditText fields which I try to populate with the local table data. Now, I have a method within the Activity, DrawText(), to do this but when ran I am getting a crash. The logcat message I put in shows that when the DrawText() is called the value it is pulling from the SQLite table is null.
I've moved the method around trying to make sure it accesses the table after it has already been populated from the server response, but cannot get it working. Any help would be greatly appreciated. Code below (now Edited with help)
FormActivity.java
public class FormActivity extends FragmentActivity {
//create variables & Logcat tag
private static final String TAG = FormActivity.class.getSimpleName();
private EditText inputTitle;
private EditText inputName;
private EditText inputSurname;
private SessionManager sm;
private SQLiteHandler db;
private ProgressDialog pDialog;
private String e_check;
private String surname;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_form);
//set inputs for fields
inputTitle = (EditText) findViewById(R.id.titleText);
inputName = (EditText) findViewById(R.id.foreText);
inputSurname = (EditText) findViewById(R.id.surnameText);
//initialise pager for swipe screens
ViewPager pager = (ViewPager) findViewById(R.id.viewPager);
pager.setAdapter(new MyPagerAdapter(getSupportFragmentManager()));
// Progress dialog
pDialog = new ProgressDialog(this);
pDialog.setCancelable(false);
//email value passed in
Bundle extras = getIntent().getExtras();
if (extras != null) {
e_check = extras.getString("e_check");
}
// SQLite database handler - delete old and recreate db from remote server data
db = new SQLiteHandler(getApplicationContext());
String email = e_check;
checkUserDetails(email);
//<!-- TODO: load db fields to textfields -->
//<!-- TODO: greeting toast -->
}
/**
* function to verify & retrieve details in mysql db
* */
private void checkUserDetails(final String email) {
// Tag used to cancel the request
String tag_string_req = "req_retrieve";
pDialog.setMessage("Retrieving details ...");
showDialog();
StringRequest strReq = new StringRequest(Request.Method.POST,
AppConfig.URL_RETRIEVE, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d(TAG, "Retrieval Response: " + response.toString());
hideDialog();
try {
JSONObject jObj = new JSONObject(response);
boolean error = jObj.getBoolean("error");
// Check for error node in json
if (!error) {
// user exists
// fill in textfields
String uid = jObj.getString("uid");
JSONObject user = jObj.getJSONObject("user");
String name = user.getString("name");
surname = user.getString("surname");
String email = user.getString("email");
String created_at = user
.getString("created_at");
String tel_no = user.getString("tel_no");
String home_add = user.getString("home_add");
String postcode = user.getString("postcode");
String postal = user.getString("postal");
// Inserting row in table
db.addUser(name, surname, email, uid, created_at, tel_no, home_add, postcode, postal);
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
//Do something after 300ms
DrawText();
}
}, 300);
/* Displaying the user details on the screen
FirstFragment fragA = (FirstFragment) getSupportFragmentManager().findFragmentByTag("fragA");
fragA.DrawText();*/
} else {
// Error in login. Get the error message
String errorMsg = jObj.getString("error_msg");
Toast.makeText(getApplicationContext(),
errorMsg, Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
// JSON error
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, "Retrieval Error: " + error.getMessage());
Toast.makeText(getApplicationContext(),
error.getMessage(), Toast.LENGTH_LONG).show();
hideDialog();
}
}) {
#Override
protected Map<String, String> getParams() {
// Posting parameters to url
Map<String, String> params = new HashMap<String, String>();
params.put("tag", "retrieve");
params.put("email", email);
return params;
}
};
// Adding request to request queue
AppController.getInstance().addToRequestQueue(strReq, tag_string_req);
}
public void DrawText() {
// Fetching user details from sqlite
HashMap<String, String> user = db.getUserDetails();
if (user.size() != 0) {
//String surname = user.get("surname");
Log.e(TAG, "string surname: " + surname);
// Displaying the user details on the screen
inputSurname.setText(surname);
}else{
Log.e(TAG, "something you want to say");
}
}
private void showDialog() {
if (!pDialog.isShowing())
pDialog.show();
}
private void hideDialog() {
if (pDialog.isShowing())
pDialog.dismiss();
}
private class MyPagerAdapter extends FragmentPagerAdapter {
public MyPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int pos) {
switch(pos) {
case 0: return FirstFragment.newInstance("FirstFragment, Instance 1");
case 1: return SecondFragment.newInstance("SecondFragment, Instance 1");
case 2: return ThirdFragment.newInstance("ThirdFragment, Instance 1");
case 3: return FourthFragment.newInstance("FourthFragment, Instance 1");
//case 4: return FifthFragment.newInstance("ThirdFragment, Instance 3");
default: return FirstFragment.newInstance("FirstFragment, Default");
}
}
#Override
// Number of screens we want to swipe between
public int getCount() {
return 4;
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_form, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
Logcat (also updated)
05-16 09:31:35.560 21981-21981/com.disclosure_scots.disclosure_scots D/FormActivity﹕ Retrieval Response: {"tag":"retrieve","error":false,"uid":"55558b80341dc0.72266271","user":{"name":"John","surname":"Carter","email":"cart#email.com","created_at":"2015-05-15 08:00:32","tel_no":"1231234123","home_add":"22 Lone Road","postcode":"G44 4TT","postal":"false"}}
05-16 09:31:35.643 21981-21981/com.disclosure_scots.disclosure_scots D/SQLiteHandler﹕ Database tables created
05-16 09:31:35.663 21981-21981/com.disclosure_scots.disclosure_scots D/SQLiteHandler﹕ New user inserted into sqlite: 1
05-16 09:31:35.980 21981-21981/com.disclosure_scots.disclosure_scots D/SQLiteHandler﹕ Fetching user from Sqlite: {tel_no=1231234123, postal=false, email=cart#email.com, surname=Carter, name=John, created_at=2015-05-15 08:00:32, uid=55558b80341dc0.72266271, home_add=22 Lone Road, postcode=G44 4TT}
05-16 09:31:35.980 21981-21981/com.disclosure_scots.disclosure_scots E/FormActivity﹕ string surname: Carter
05-16 09:31:35.980 21981-21981/com.disclosure_scots.disclosure_scots D/AndroidRuntime﹕ Shutting down VM
05-16 09:31:35.981 21981-21981/com.disclosure_scots.disclosure_scots E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.disclosure_scots.disclosure_scots, PID: 21981
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.EditText.setText(java.lang.CharSequence)' on a null object reference
at com.disclosure_scots.disclosure_scots.FormActivity.DrawText(FormActivity.java:180)
at com.disclosure_scots.disclosure_scots.FormActivity$1$1.run(FormActivity.java:125)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5257)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
The problem is that you are trying to collect data before adding data. As you can see you are calling DrawText(); just after the response received (before adding data to database). So obviously the data'll be null. You should call the DrawText(); after adding the data to the db.
db.addUser(name, surname, email, uid, created_at, tel_no, home_add, postcode, postal);
DrawText();
If the above code doesn't work, try calling DrawText() after a 500ms like this
db.addUser(name, surname, email, uid, created_at, tel_no, home_add, postcode, postal);
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
//Do something after 500ms
DrawText();
}
}, 500);
If nothing worked from above. declare String variables such as name,surname etc.. ( which you parsed from the JSON ) outside the methods which will extend the accessibility of the variable from any method and update the DrawText(); like this
private String surname;
.....{
....
surname = jsonObject.getString("surname");
...
}
public void DrawText() {
Log.e(TAG, "string surname: " + surname);
// Displaying the user details on the screen
inputSurname.setText(surname);
}
public void DrawText() {
// Fetching user details from sqlite
HashMap<String, String> user = db.getUserDetails();
if (user.size() != 0) {
String surname = user.get("surname");
Log.e(TAG, "string surname: " + surname);
// Displaying the user details on the screen
inputSurname.setText(surname);
}else{
Log.e(TAG, "something you want to say");}
}
Hey guys i have got this problem for a while now and i cannot figure out as to why it is not working. when i use the code provided by the tutorial that i have followed on YouTube it works fine, which is posting that data as soon as the application starts. However what i am trying to do is post the data as soon as the "Save Register" button is pressed in the menu but the it doesnt work and returns the message as shown in Log Cat.
I am getting the feeling that i am supposed to create an Async task for this however because my android programming is very limited i am not to sure how i would go about creating this.
My Main activity Class:
public class MainActivity extends Activity{
boolean wasApEnabled = false;
static AccessPoint wifiAP;
private WifiManager wifi;
static Button apButton;
static TextView textView;
final String myTag = "DocsUpload";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
apButton = (Button) findViewById(R.id.toggleBtn);
textView = (TextView) findViewById(R.id.wifiClients);
apButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
wifiAP.toggleWifiAP(wifi, MainActivity.this);
}
});
/*Log.i(myTag, "OnCreate()");
Thread t = new Thread(new Runnable() {
#Override
public void run() {
postData();
}
});*/
//t.start();
wifiAP = new AccessPoint(this);
wifi = (WifiManager) getSystemService(Context.WIFI_SERVICE);
postData();
scan();
//getWindow().addFlags(WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD|WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON|WindowManager.LayoutParams.FLAG_DIM_BEHIND);
}
private void scan(){
wifiAP.getClientList(false, new FinishScanListener() {
#Override
public void onFinishScan(final ArrayList<ClientScanResult> clients) {
textView.setText("WifiApState:" + wifiAP.getWifiApState()+ "\n\n");
textView.append("Clients: \n");
for (ClientScanResult clientScanResult : clients){
textView.append("====================\n");
textView.append("ipAddress: " + clientScanResult.getIpAddress() + "\n");
textView.append("Device: " + clientScanResult.getDevice() + "\n");
textView.append("macAddress: " + clientScanResult.getMacAddress() + "\n");
textView.append("isReachable: " + clientScanResult.isReachable() + "\n");
}
}
});
}
public void postData() {
String fullUrl = "https://docs.google.com/forms/d/1yipuuXd5V53Ol12U24Cl2H4RIdYtm622jIk13Zo26cM/formResponse";
HttpRequest mReq = new HttpRequest();
String col1 = "Hello";
String col2 = "World";
String data = "entry_272641491=" + URLEncoder.encode(col1) + "&" +
"entry_130393492=" + URLEncoder.encode(col2);
String response =mReq.sendPost(fullUrl, data);
// Log.i(myTag, response);
}
#Override
public void onResume() {
super.onResume();
if (wasApEnabled) {
if (wifiAP.getWifiApState() != wifiAP.WIFI_STATE_ENABLED && wifiAP.getWifiApState() != wifiAP.WIFI_STATE_ENABLING) {
wifiAP.toggleWifiAP(wifi, MainActivity.this);
}
}
updateStatusDisplay();
}
#Override
public void onPause() {
super.onPause();
boolean wifiApIsOn = wifiAP.getWifiApState()==wifiAP.WIFI_STATE_ENABLED || wifiAP.getWifiApState()==wifiAP.WIFI_STATE_ENABLING;
if (wifiApIsOn){
wasApEnabled = true;
wifiAP.toggleWifiAP(wifi, MainActivity.this);
}else {
wasApEnabled = false;
}
updateStatusDisplay();
}
public static void updateStatusDisplay(){
if (wifiAP.getWifiApState()==wifiAP.WIFI_STATE_ENABLED || wifiAP.getWifiApState()==wifiAP.WIFI_STATE_ENABLING){
apButton.setText("Turn Off");
}else {
apButton.setText("Turn on");
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
menu.add(0,0,0, "Get Clients");
menu.add(0,1,0, "Save Register");
getMenuInflater().inflate(R.menu.menu_main, menu);
return super.onCreateOptionsMenu(menu);
}
public boolean onMenuItemSelected(int featureId, MenuItem item) {
switch (item.getItemId()){
case 0:
scan();
break;
case 1:
postData();
break;
}
return super.onMenuItemSelected(featureId, item);
}
}
This is the helper class that i have used, Credit goes to this stack overflow user for creating this class
Secure HTTP Post in Android
This is the log cat that i am getting
03-12 15:06:27.428 3096-3096/com.example.gavin.wifiattendance D/Your App Name Here﹕ https://docs.google.com/forms/d/1yipuuXd5V53Ol12U24Cl2H4RIdYtm622jIk13Zo26cM/formResponse?entry_272641491=Hello&entry_130393492=World
03-12 15:06:27.428 3096-3096/com.example.gavin.wifiattendance E/WifiAttendance﹕ HttpUtils: android.os.NetworkOnMainThreadException
03-12 15:06:27.428 3096-3096/com.example.gavin.wifiattendance D/WifiAttendance﹕ Returning value:null
I am getting the feeling that i am supposed to create an Async task
for this
Correct. NetworkOnMainThreadException is thrown when you are trying to make network calls on your Main Thread (UI thread).
You can find a good tutorial on AsyncTask here.
Example from the tutorial:
private class DownloadWebPageTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... urls) {
String response = "";
//Do your network calls here
return response;
}
#Override
protected void onPostExecute(String result) {
//When you are done, this method runs on the UI thread so you can update the UI from here
textView.setText(result);
}
}
Finally you execute it like so
DownloadWebPageTask task = new DownloadWebPageTask();
task.execute(new String[] { "http://www.vogella.com" });
Thank you for the #Marcus for the helpful links i managed to get it working using this code:
public class PostDataTask extends AsyncTask<String, Void, Integer>{
#Override
protected Integer doInBackground(String... params) {
HttpRequest mReq = new HttpRequest();
String data = "entry_272641491=" + URLEncoder.encode(params[1]) + "&" +
"entry_130393492=" + URLEncoder.encode(params[2]);
String response = mReq.sendPost(params[0], data);
return 200;
}
}
I want to validation on RatingBar in Android. I have 5 rating Bar and 1 Button. I don't want to submit the data without pressed the rating bar. I want to take validation on Rating bar.
Can someone help me. How to take validation on Rating bar?
Here is my Activity code:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.rating_baar);
databaseHelper = new DatabaseHelper(this);
databaseHelper.onOpen(db);
addListenerOnRatingBar_one();
addListenerOnRatingBar_two();
addListenerOnRatingBar_three();
addListenerOnRatingBar_four();
addListenerOnRatingBar_five();
addListenerOnButton();
}
#SuppressLint("SimpleDateFormat")
public void addListenerOnButton() {
buttonSubmitRate = (Button) findViewById(R.id.button_SubmitRate);
buttonSubmitRate.setOnClickListener(new OnClickListener() {
#SuppressLint("SimpleDateFormat")
#Override
public void onClick(View v) {
if((etTaskName.getText().toString().isEmpty()))
etTaskName.setError("Field Can Not Be Empty !");
else if (!etTaskName.getText().toString().trim().matches("[a-zA-Z{ }]+"))
etTaskName.setError("Accept Alphabets Only.");
else {
strEmpName = textViewNAme.getText().toString().trim();
strTaskName = etTaskName.getText().toString().trim();
String strCurrentDate = new SimpleDateFormat("dd/MM/yyyy").format(new Date());
System.out.println("strCurrentDate = " + strCurrentDate);
String strCurrentMonth = new SimpleDateFormat("MMM").format(new Date());
System.out.println("strCurrentDate = " + strCurrentMonth);
String strCurrenYear = new SimpleDateFormat("yyyy").format(new Date());
System.out.println("strCurrenYear = " + strCurrenYear);
System.out.println("__________________________________________________________________________________");
databaseHelper.insertPerformance_Details(intentStr1, strEmpName,
strTaskName, rateVal_one,
rateVal_two, rateVal_three,
rateVal_four,rateVal_five,
strCurrentDate,strCurrentMonth,
strCurrenYear);
System.out.println("Data Add SuccesFully !!!!");
etTaskName.setText("");
Intent i = new Intent(RatingBaar_Class.this, Rating_Msg.class);
startActivity(i);
finish();
overridePendingTransition(R.anim.anim_in,R.anim.anim_out);
}
}
});
}
public void addListenerOnRatingBar_one() {
ratingBar_one = (RatingBar) findViewById(R.id.ratingBar1);
ratingBar_one.setOnRatingBarChangeListener(new OnRatingBarChangeListener() {
public void onRatingChanged(RatingBar ratingBar, float rating, boolean fromUser) {
rateVal_one = String.valueOf(rating);
System.out.println(" rateVal_one = " + rateVal_one);
}
});
}
/* Exactly the same methods for four other rating bars, except for variable names */
public void addListenerOnRatingBar_two() { ... }
public void addListenerOnRatingBar_three() { ... }
public void addListenerOnRatingBar_four() { ... }
public void addListenerOnRatingBar_five() { ... }
At first set all rating bar to 0 value. Then on click to button, check if the value has altered in all of them. If so, only valid else invalid.
Also you can use listener to each rating bar and change value of some boolean variable to true
Example:
boolean flag1 = false;
boolean flag2 = false;
.... //similarly upto 5
Then in rating bar listener1
{
flag1 = true;
}
Similarly for all set flag to be true
And in button onClickListener do the following:
if(flag1 && flag2 && flag3 && flag4 && flag5){
//do your work
}else{
//display message that one of the rating bar hasn't been touched
}
I am learning to program for android and java in general and need some help with the "Navigation Drawer" on android.
I am struggling to add a switch statement to the click listener for the drawer items, The code I am using is taken from an example here: http://hmkcode.com/android-creating-a-navigation-drawer/
How exactly should I handle the switch statement so as to launch new activities from the touch of one of the items?
Thank you
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
// Sync the toggle state after onRestoreInstanceState has occurred.
actionBarDrawerToggle.syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
actionBarDrawerToggle.onConfigurationChanged(newConfig);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Call ActionBarDrawerToggle.onOptionsItemSelected(), if it returns true
// then it has handled the app icon touch event
if (actionBarDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
return super.onOptionsItemSelected(item);
}
private class DrawerItemClickListener implements ListView.OnItemClickListener {
#Override
public void onItemClick(AdapterView parent, View view, int position, long id) {
Toast.makeText(MainActivity.this, ((TextView)view).getText(), Toast.LENGTH_LONG).show();
drawerLayout.closeDrawer(drawerListView);
}
}
Edit....
public void onItemClick(AdapterView parent, View view, int position, long id) {
switch (position){
case 0:
new DataTask(this).execute();
MainActivity.this.finish();//Set this Activity to Finish so no loop back
Intent intent=new Intent(MainActivity.this,SplashScreen.class);
startActivity(intent);
System.out.println("Click working");
case 1:
//do stuff
default:
break;
}
The new DataTask(this).execute(); is giving this warning....The constructor DataTask(MainActivity.DrawerItemClickListener) is undefined. I am unsure why?
DataTask Class...
public class DataTask extends AsyncTask<Void, Void, Integer> {
Context context;
DataTask(Context context) {
this.context = context.getApplicationContext();
}
// Global Int for counting how many Tasks have been completed
int asynCount = 0;
ArrayList<String> arr_dataVts=new ArrayList<String>();
ArrayList<String> arr_dataNtm=new ArrayList<String>();
ArrayList<String> arr_dataOdas=new ArrayList<String>();
ArrayList<String> arr_dataMetAll=new ArrayList<String>();
ArrayList<String> arr_dataMet3HrTask=new ArrayList<String>();
ArrayList<String> arr_dataTideTask=new ArrayList<String>();
#Override
protected Integer doInBackground(Void... params) {
//VtsAsyncTask
VtsTask task1 = new VtsTask();
task1.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
//NtmAsyncTask
NtmTask task2 = new NtmTask();
task2.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
//OdasAsyncTask
OdasTask task3 = new OdasTask();
task3.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
//MetAllTask
MetAllTask task4 = new MetAllTask();
task4.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
//Met3HrTask
Met3HrTask task5 = new Met3HrTask();
task5.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
//TideTask
TideTask task6 = new TideTask();
task6.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
return 1;
}
private class VtsTask extends AsyncTask<Void, Void, ArrayList<String>> {
#Override
protected ArrayList<String> doInBackground(Void... params) {
Document docVTS;
try {
Connection.Response response = Jsoup.connect("https://vts.mhpa.co.uk/main_movelistb.asp")
.timeout(10000)
.ignoreHttpErrors(true)
.execute();
int statusCode = response.statusCode();
if(statusCode == 200) {
docVTS = Jsoup.connect("https://vts.mhpa.co.uk/main_movelistb.asp").timeout(10000).get();
Elements tableRows = docVTS.select("table.dynlist td:eq(0),td:eq(1),td:eq(3),td:eq(4),td:eq(7),td:eq(8)");
tableRows.size();
for(int i = 1; i < 80; i++){// Only allows x results from VTS list, from 1 not 0. 0 produces needless results
String shippingList = tableRows.get(i).text() +"\n";//new line
arr_dataVts.add(shippingList);// Add value to ArrayList
};
} else {
//If can't connect for what ever reason
System.out.println("Received error code for VTS list Data : " + statusCode + " Adding Null values");
for(int i = 1; i < 80; i++){
arr_dataVts.add("No Data" + i);
}
}
}
catch (IOException e) {
e.printStackTrace();
System.out.println("Received timeout error code for VTS list Data : Adding Null values ");
for(int i = 1; i < 80; i++){
arr_dataVts.add("No Data" + i);
}
}
return arr_dataVts;
}
#Override
protected void onPostExecute(ArrayList<String> Param) {
asynCount++;
System.out.println("Vts list Captured" + arr_dataVts + " asynCount= " + asynCount);
if (asynCount == 6){
//Start intents for main activity
System.out.println("asynCount has reached= " + asynCount + " so now starting MainActivity");
Intent intent = new Intent(context, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.putStringArrayListExtra("data1", arr_dataVts);
intent.putStringArrayListExtra("data2", arr_dataNtm);
intent.putStringArrayListExtra("data3", arr_dataOdas);
intent.putStringArrayListExtra("data4", arr_dataMetAll);
intent.putStringArrayListExtra("data5", arr_dataMet3HrTask);
intent.putStringArrayListExtra("data6", arr_dataTideTask);
context.startActivity(intent);
}else{
//update dialogue
}
}
}
private class NtmTask extends AsyncTask<Void, Void, ArrayList<String>> {
#Override
protected ArrayList<String> doInBackground(Void... params) {
Document docNTM;
try {
Connection.Response response = Jsoup.connect("http://www.milfordfishdocks.com/notices-to-mariners/")
.timeout(10000)
.ignoreHttpErrors(true)
.execute();
int statusCode = response.statusCode();
if(statusCode == 200) {
docNTM = Jsoup.connect("http://www.milfordfishdocks.com/notices-to-mariners/").timeout(10000).get();
Elements elements = docNTM.select("div.news-item-left");
int NtmAmount = elements.size();
String NtmAmt = Integer.toString(NtmAmount);//convert the Int to a string for adding into array
arr_dataNtm.add(NtmAmt);
} else {
System.out.println("Received error code for NTM Data : " + statusCode + " Adding Null values");
arr_dataNtm.add("0");
}
}
catch (IOException e) {
e.printStackTrace();
System.out.println("Received timeout error code for NTM Data : Adding Null values ");
arr_dataNtm.add("0");
}
return arr_dataNtm;
}
#Override
protected void onPostExecute(ArrayList<String> Param) {
asynCount++;
System.out.println("Ntm list Captured" + arr_dataNtm + " asynCount= " + asynCount);
if (asynCount == 6){
//Start intents for main activity
System.out.println("asynCount has reached= " + asynCount + " so now starting MainActivity");
Intent intent = new Intent(context, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.putStringArrayListExtra("data1", arr_dataVts);
intent.putStringArrayListExtra("data2", arr_dataNtm);
intent.putStringArrayListExtra("data3", arr_dataOdas);
intent.putStringArrayListExtra("data4", arr_dataMetAll);
intent.putStringArrayListExtra("data5", arr_dataMet3HrTask);
intent.putStringArrayListExtra("data6", arr_dataTideTask);
context.startActivity(intent);
}else{
//update dialogue
}
}
}
#Override
protected void onPostExecute(Integer result) {
System.out.println("Data Task Has Executed");
}
}
It can be done like this:
private class DrawerItemClickListener implements ListView.OnItemClickListener {
#Override
public void onItemClick(AdapterView parent, View view, int position, long id) {
switch (position){
case 0:
//do stuff
case 1:
//do stuff
default:
break;
}
drawerListView.setItemChecked(position, true);
drawerListView.setSelection(position);
drawerLayout.closeDrawer(drawerListView);
}
}
Then just attach this listener to your NavList:
drawerListView.setOnItemClickListener(new DrawerItemClickListener());
BTW, you would recommend you to switch fragments instead of switching activities, "Creating a Navigation Drawer" tutorial explains how to work with them
EDIT Handling case 0, replace with following:
new DataTask(MainActivity.this).execute();
Intent intent=new Intent(MainActivity.this,SplashScreen.class);
startActivity(intent);
Log.d("Click working");
MainActivity.this.finish();//Set this Activity to Finish so no loop back
Switch=
(Switch)navigationView.getMenu().findItem(R.id.vibrate).getActionView();
s.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener(){
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean
isChecked){
if(isChecked)
//do whatever you want to do
}
});
this should work