OnMenuButton not posting data to google spreadsheets - java

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

Related

How to Cast Fragment to Async Constructor?

I want to cast SlideshowDialogFragment to context in my asynctask in DdownloadTask.java but when i write
final DownloadTask downloadTask = new
DownloadTask(myActivity.this);
SlideshowDialogFragment instead of myActivity , android show warning and say
warning android
i don't know what am i do ?? thx for help me
public class SlideshowDialogFragment extends DialogFragment{
ArrayList<Image> images;
ViewPager viewPager;
MyViewPagerAdapter myViewPagerAdapter;
TextView lblCount,lblTitle,lblDate;
Button btn_set;
Button btn_download;
int selectedPostition;
DownloadManager downloadManager;
public static ProgressDialog mProgressDialog;
static SlideshowDialogFragment newInstance(){
SlideshowDialogFragment f=new SlideshowDialogFragment();
return f;
}
#Override
public View onCreateView (LayoutInflater inflater,ViewGroup container,Bundle saveInstanceState)
{
View v=inflater.inflate(R.layout.fragment_image_slider,container,false);
viewPager=(ViewPager)v.findViewById(R.id.view_pager);
lblTitle=(TextView)v.findViewById(R.id.title);
lblDate=(TextView)v.findViewById(R.id.date);
btn_set=(Button)v.findViewById(R.id.btn_set);
btn_download=(Button)v.findViewById(R.id.btn_download);
images=(ArrayList<Image>) getArguments().getSerializable("images");
selectedPostition=getArguments().getInt("position");
myViewPagerAdapter=new MyViewPagerAdapter();
viewPager.setAdapter(myViewPagerAdapter);
viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int
positionOffsetPixels) {
displayInfo(position);
//setWallpaper(position);
}
#Override
public void onPageSelected(int position) {
}
#Override
public void onPageScrollStateChanged(int state) {
}
});
setCurrentItem(selectedPostition);
btn_download.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
download(selectedPostition);
}
});
return v;
}
void download (int position){
Image image=images.get(position);
String large = image.getlarge();
final DownloadTask downloadTask = new
DownloadTask(**SlideshowDialogFragment**.this);
downloadTask.execute(large);
}
And this is DownloadTask Activity with constructor i write AsyncTask in this class:
public class DownloadTask extends AsyncTask<String, Integer, String> {
private Context context;
private PowerManager.WakeLock mWakeLock;
public DownloadTask(Context context) {
this.context = context;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
// take CPU lock to prevent CPU from going off if the user
// presses the power button during download
PowerManager pm = (PowerManager)
context.getSystemService(Context.POWER_SERVICE);
mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,
getClass().getName());
mWakeLock.acquire();
mProgressDialog.show();
}
#Override
protected void onProgressUpdate(Integer... progress) {
super.onProgressUpdate(progress);
// if we get here, length is known, now set indeterminate to false
mProgressDialog.setIndeterminate(false);
mProgressDialog.setMax(100);
mProgressDialog.setProgress(progress[0]);
}
#Override
protected void onPostExecute(String result) {
mWakeLock.release();
mProgressDialog.dismiss();
if (result != null)
Toast.makeText(context,"خطای دانلود "+result, Toast.LENGTH_LONG).show();
else
Toast.makeText(context,"دانلود با موفقیت انجام شد",
Toast.LENGTH_SHORT).show();
}
#Override
protected String doInBackground(String... sUrl) {
InputStream input = null;
OutputStream output = null;
HttpURLConnection connection = null;
try {
URL url = new URL(sUrl[0]);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
// expect HTTP 200 OK, so we don't mistakenly save error report
// instead of the file
if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) {
return "Server returned HTTP " + connection.getResponseCode()
+ " " + connection.getResponseMessage();
}
// this will be useful to display download percentage
// might be -1: server did not report the length
int fileLength = connection.getContentLength();
// download the file
input = connection.getInputStream();
output = new FileOutputStream("/sdcard/tabriz.jpg");
byte data[] = new byte[4096];
long total = 0;
int count;
while ((count = input.read(data)) != -1) {
// allow canceling with back button
if (isCancelled()) {
input.close();
return null;
}
total += count;
// publishing the progress....
if (fileLength > 0) // only if total length is known
publishProgress((int) (total * 100 / fileLength));
output.write(data, 0, count);
}
} catch (Exception e) {
return e.toString();
} finally {
try {
if (output != null)
output.close();
if (input != null)
input.close();
} catch (IOException ignored) {
}
if (connection != null)
connection.disconnect();
}
return null;
}
}
what am i do for casting SlideshowDialogFragment to Async ?
You need to pass a Context as you defined your constructor like that. A Fragment does not have a Context, but the Activity has it. Since Fragment is a part of an Activity you can access it with
SlideshowDialogFragment.this.getActivity();
You could also use it directly with DownloadTask(getActivity())

AsyncTask get String value output and store in mainthread variable

I'd like to get the string value output from AsyncTask. And store it into a variable on my main thread. How can I do so?
I tried to do store = new ReceiveData().execute().get() however it throws an execution exception error. But anyway, my question is not about the execution exception error. I just need a way to get the string out, please help!
Here is my activity code:
public class MainActivity extends AppCompatActivity { //MAIN ACTIVITIES (REMOTE)
double multiplier;
int seekbarvalue, finallumens;
#Override
protected void onCreate(Bundle savedInstanceState) {
this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR_PORTRAIT); //On orientation change socket will disconnect...
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Toast.makeText(MainActivity.this, LoginActivity.SERVER_IP, Toast.LENGTH_LONG).show();
//================START AFTER DEFAULT ON CREATE=================
SeekBar seekbarbrightness = (SeekBar) findViewById(R.id.seekbarbrightness);
final TextView tblumens, tbvolts, tbamps;
tblumens = (TextView) findViewById(R.id.tblumens);
seekbarvalue = seekbarbrightness.getProgress();
multiplier = (double) seekbarvalue / 100;
finallumens = (int) (multiplier * LoginActivity.enterlumens);
tblumens.setText(String.valueOf(finallumens) + " Lumens");
tbvolts = (TextView) findViewById(R.id.tbvolts);
tbamps = (TextView) findViewById(R.id.tbamps);
seekbarbrightness.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekbarbrightness, int progress, boolean b) {
if (b == true) {
seekbarvalue = seekbarbrightness.getProgress();
multiplier = (double) seekbarvalue / 100;
finallumens = (int) (multiplier * LoginActivity.enterlumens);
tblumens.setText(String.valueOf(finallumens) + " Lumens");
if (LoginActivity.getSocket() != null) {
try {
LoginActivity.getSocket().getOutputStream().write(String.valueOf(multiplier).getBytes());
new ReceiveData().execute();
//infinite loop here to keep receiving volts and amperes.
//Do a split and assign value to volt and amp
//String[] strrecv= store.split("|");
//String volts = strrecv[0];
//String amps = strrecv[1];
//tbvolts.setText("Voltage: " + volts + " V");
//tbamps.setText("Amperes:" + amps + " A");
} catch (IOException e) {
e.printStackTrace();
}
} else {
Toast.makeText(MainActivity.this, "NOT connected To Socket, please disconnect and reconnect!", Toast.LENGTH_SHORT).show();
}
}
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
});
}
And in my Asynctask I am doing this.
class ReceiveData extends AsyncTask<Void, Void, String> {
String str;
protected String doInBackground(Void... args) {
try {
BufferedReader in = new BufferedReader(new InputStreamReader(LoginActivity.getSocket().getInputStream()));
str = in.readLine();
return str;
} catch (IOException e) {
e.printStackTrace();
String str = "fail";
return str;
}
}
protected void onPostExecute(String str) {
//super.onPostExecute(str);
}
}
The purpose of AsyncTask is to perform asynchronous task in a separate thread to free the main thread and avoid UX issues. For your purpose, I suggest transferring all of the work inside your try block inside the AsyncTask and update the UI after execution.
Something like this
In MainThread
new ReceiveData().execute();
In AsyncTask
class ReceiveData extends AsyncTask<Void, Void, Boolean> {
String volts;
String amps;
protected Boolean doInBackground(Void... args) {
try {
BufferedReader in = new BufferedReader(new InputStreamReader(LoginActivity.getSocket().getInputStream()));
str = in.readLine();
String[] strrecv= store.split("|");
volts = strrecv[0];
amps = strrecv[1];
} catch (IOException e) {
e.printStackTrace();
return false;
}
return true;
}
protected void onPostExecute(Boolean result) {
if (result) {
tbvolts.setText("Voltage: " + volts + " V");
tbamps.setText("Amperes:" + amps + " A");
}
}
}
Note that this only works if your AsyncTask is defined inside your Activity. If not, you need to create an interface from the AsyncTask and implement it in your activity and activate it onPostExecute

Execute a function on the end of asynctask

i've got a little problem at the moment:
I am trying to make visible 2 buttons on my fragment after the asynktask i called is finished. For that i was using this:
while (!recordi.getterminé){
}
terminé();
But this is not optimal and my app is not responding :(
So is there any solutions to call the function terminé() in the onPostExecute function?
Thanks.
Here is my code:
the fragment:
public class FragmentEnregistrer extends Fragment {
String path,nomfinal, ip="http://MYIP/php";
ImageButton mrecord,mupload,mlire;
TextView Nomm;
ProgressBar progressbar;
int i=2;
EnregistrerSon recordi;
String id;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View myView= inflater.inflate(R.layout.enregistrer, container, false);
mrecord= (ImageButton) myView.findViewById(record);
mupload= (ImageButton) myView.findViewById(upload);
mlire= (ImageButton) myView.findViewById(lire);
Nomm = (TextView) myView.findViewById(NomWhizz);
progressbar = (ProgressBar) myView.findViewById(progressBar);
progressbar.setVisibility(View.INVISIBLE);
id=((MainActivity)getActivity()).getIdentifiant();
mrecord.setOnClickListener(new View.OnClickListener() {
#RequiresApi(api = Build.VERSION_CODES.N)
#Override
public void onClick(View v) {
Toast.makeText(getActivity().getApplicationContext(), "Enregistrement en cours", Toast.LENGTH_SHORT).show();
String nomm = Nomm.getText().toString();
nomm=nomm.replace(" ", "_");
nomm=nomm.replace("&", "");
final String finalNomm = nomm;
recordi = new EnregistrerSon();
recordi.execute(finalNomm);
terminé();
}
});
mupload.setOnClickListener(new View.OnClickListener() {
#RequiresApi(api = Build.VERSION_CODES.N)
#Override
public void onClick(View v) {
UploadOnServer upload = new UploadOnServer();
progressbar.setVisibility(View.VISIBLE);
upload.execute(path,nomfinal);
progressbar.setVisibility(View.INVISIBLE);
HttpGetRequest request = new HttpGetRequest();
request.execute(ip+"/son/creation_son.php?nom_whiz="+nomfinal+"&id_createur="+id);
}
});
mlire.setOnClickListener(new View.OnClickListener() {
#RequiresApi(api = Build.VERSION_CODES.N)
#Override
public void onClick(View v) {
LireSonLocal local = new LireSonLocal();
Uri myUri = Uri.parse("file://"+recordi.getAccess());
local.execute(myUri);
}
});
return myView;
}
#RequiresApi(api = Build.VERSION_CODES.N)
public void terminé(){
Log.i("Enregistrement","terminé");
Toast.makeText(getActivity().getApplicationContext(), "Enregistrement terminé", Toast.LENGTH_LONG).show();
path = recordi.getAccess();
nomfinal = recordi.getNomSansExtenssions();
Log.i("nomfinale",nomfinal);
mlire.setVisibility(View.VISIBLE);
mupload.setVisibility(View.VISIBLE);
Log.i("test","");
}
}
And the asynktask :
class EnregistrerSon extends AsyncTask<String,Void,String> {
private Boolean isRecording = false;
private Boolean termine = false;
private String Nom, NOM;
#RequiresApi(api = Build.VERSION_CODES.N)
#Override
protected String doInBackground(String... params) {
NOM = params[0];
if(!isRecording){
//configuration
Looper.prepare();
MediaRecorder mr = new MediaRecorder();
mr.setAudioSource(MediaRecorder.AudioSource.DEFAULT);
mr.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);
mr.setAudioEncoder(MediaRecorder.AudioEncoder.AAC);
mr.setAudioChannels(1);
mr.setAudioEncodingBitRate(1280000);
mr.setAudioSamplingRate(9500000);
mr.setOutputFile(getAccess());
try {mr.prepare();}
catch (IOException e) {e.printStackTrace();}
//Demarage du record
long start_time = System.currentTimeMillis(); //pendant 15 secondes
long wait_time = 15000;
long end_time = start_time + wait_time;
mr.start();
while (System.currentTimeMillis() < end_time){
Long temps = end_time - System.currentTimeMillis();
isRecording = true;
//pendant 15 secondes
}
mr.stop();
mr.reset();
mr.release();
isRecording = false;
termine = true;
//fin de l'enregistrement
}
return "lol";
}
#RequiresApi(api = Build.VERSION_CODES.N)
protected void onPostExecute(String s) {
super.onPostExecute(s);
}
#TargetApi(Build.VERSION_CODES.N)
#RequiresApi(api = Build.VERSION_CODES.N)
String getAccess(){
MainActivity main = new MainActivity();
if(Objects.equals(NOM, "Nom") || Objects.equals(NOM, "") || NOM == null ) {
Calendar now = Calendar.getInstance();
Nom = now.get(Calendar.HOUR_OF_DAY) + "_" + now.get(Calendar.DAY_OF_MONTH) + "_" + now.get(Calendar.MONTH) + "_" + now.get(Calendar.YEAR);
}
else{
Nom = NOM;
}
File directory = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/Whizz/");
directory.mkdirs();
String filename = directory +"/"+Nom+".mp3";
Log.i("filename",filename);
return filename;
}
Boolean getTerminé(){
return termine;
}
String getNomSansExtenssions(){
return Nom;
}
}
To execute your method terminé inside the AsyncTask class. I suggest to have the following:
Create an instance field of FragmentEnregistrer inside your EnregistrerSon class.
private FragmentEnregistrer fragmentEnregistrer;
Create a constructor in your EnregistrerSon class with an expected argument of FragmentEnregistrer class, and assign the argument to the field variable.
public EnregistrerSon(FragmentEnregistrer fe) {
this.fragmentEnregistrer = fe;
}
You can then call the terminé method in the onPostExecute method, as follows:
protected void onPostExecute(String s) {
super.onPostExecute(s);
this.fragmentEnregistrer.terminé();
}
Last, pass the instance of the FragmentEnregistrer object on EnregistrerSon instantiation.
recordi = new EnregistrerSon(FragmentEnregistrer.this);
recordi.execute(finalNomm);
First, line while (!recordi.getterminé){} terminé(); makes no sense, it equals:
while (!recordi.getterminé){
}
terminé();
Regarding onPostExecute, yes, just write the function call in it:
protected void onPostExecute(String s) {
// Anything here will be executed at the end, when doInBackground finishes
terminé();
}
use Broadcast/Receiver pattern, onhandleintent() will run on UI thread where you can make your buttons visible.
1.Start the async task .
2.Define a BroadcastReceiver, instantiate one in your activity and register/unregister it accordingly.
3.In onpostexecute() of async task just call sendBroadcast. You may need to pass a context parameter when instantiating the AsyncTask.
The onHandleIntent method of your app's broadcast receiver (the one you instantiated on step 2) will run on the UI thread, making all those UI updates safe.

Android, Google Spread Sheet crashes when on menu button is pressed

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.

Add a switch statement to Navigation Drawer

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

Categories

Resources