Passing Data between activities Forces Close - java

I am working on a simple Grading app project with 3 activities, the first one is storing some data in a database and i am replicating that data in both the first activity and the third activity.
The second activity is doing an average calculation and showing the results on that same page, but i want that result to also be shown on the third page. I tried using intents but when i click the button to go to the third page it forces close. What am i doing wrong.
I am trying to show this results in a textview
This is the Second Activity code:
public class AverageActivity extends AppCompatActivity {
EditText editmanner, editinstances, editshortstance, editstrikes, editboxingskills, editknocks, editkicks, editResults;
Button btnResults, btnnewresults;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.average_page);
editmanner = (EditText) findViewById(R.id.editText8);
editinstances = (EditText) findViewById(R.id.editText9);
editshortstance = (EditText) findViewById(R.id.editText10);
editstrikes = (EditText) findViewById(R.id.editText11);
editboxingskills = (EditText) findViewById(R.id.editText12);
editknocks = (EditText) findViewById(R.id.editText13);
editkicks = (EditText) findViewById(R.id.editText14);
editResults = (EditText) findViewById(R.id.editText15);
btnResults = (Button) findViewById(R.id.button10);
btnnewresults = (Button) findViewById(R.id.botonresultnuevo);
btnResults.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int first;
if (editmanner.getText().toString().equals("")) {
first = 0;
} else {
first = Integer.valueOf(editmanner.getText().toString());
}
int second;
if (editinstances.getText().toString().equals("")) {
second = 0;
} else {
second = Integer.valueOf(editinstances.getText().toString());
}
int third;
if (editshortstance.getText().toString().equals("")) {
third = 0;
} else {
third = Integer.valueOf(editshortstance.getText().toString());
}
int fourth;
if (editstrikes.getText().toString().equals("")) {
fourth = 0;
} else {
fourth = Integer.valueOf(editstrikes.getText().toString());
}
int fifth;
if (editboxingskills.getText().toString().equals("")) {
fifth = 0;
} else {
fifth = Integer.valueOf(editboxingskills.getText().toString());
}
int sixth;
if (editknocks.getText().toString().equals("")) {
sixth = 0;
} else {
sixth = Integer.valueOf(editknocks.getText().toString());
}
int seventh;
if (editkicks.getText().toString().equals("")) {
seventh = 0;
} else {
seventh = Integer.valueOf(editkicks.getText().toString());
}
int results;
first = Integer.parseInt(editmanner.getText().toString());
second = Integer.parseInt(editinstances.getText().toString());
third = Integer.parseInt(editshortstance.getText().toString());
fourth = Integer.parseInt(editstrikes.getText().toString());
fifth = Integer.parseInt(editboxingskills.getText().toString());
sixth = Integer.parseInt(editknocks.getText().toString());
seventh = Integer.parseInt(editkicks.getText().toString());
results = (first + second + third + fourth + fifth + sixth + seventh) / 7;
editResults.setText(String.valueOf(results));
}
});
}
public void knowtheresults(View view) {
switch (view.getId()) {
case R.id.botonresultnuevo:
Intent miintent = new Intent(AverageActivity.this, ResultActivity.class);
Bundle miBundle = new Bundle();
miBundle.putString("nombre", editResults.getText().toString());
miintent.putExtras(miBundle);
startActivity(miintent);
break;
}
String button_text;
button_text = ((Button) view).getText().toString();
if (button_text.equals("Summary")) {
Intent intent = new Intent(this, ResultActivity.class);
startActivity(intent);
}
}
}
And This is the Third activity code:
public class ResultActivity extends Activity {
TextView texto;
DatabaseHelper mDatabaseHelper;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.result_page);
texto = (TextView) findViewById(R.id.editText15);
Bundle mibundle=this.getIntent().getExtras();
if(mibundle!=null){
String dato = mibundle.getString("nombre");
texto.setText(dato);
}
mDatabaseHelper = new DatabaseHelper(this);
displayDatabaseInfo();
}
private void displayDatabaseInfo() {
// To access our database, we instantiate our subclass of SQLiteOpenHelper
// and pass the context, which is the current activity.
DatabaseHelper mDbHelper = new DatabaseHelper(this);
// Create and/or open a database to read from it
SQLiteDatabase db = mDbHelper.getReadableDatabase();
// Perform this raw SQL query "SELECT * FROM pets"
// to get a Cursor that contains all rows from the pets table.
Cursor cursor = db.rawQuery("SELECT * FROM " + TABLE_NAME, null);
TextView displayView = findViewById(R.id.textViewR1);
try {
displayView.setText("The Student...\n\n");
displayView.append(COL1 + "--" +
COL2 + "--" +
COL4 +
"\n");
// Figure out the index
int idColumnIndex = cursor.getColumnIndex(COL1);
int nameColumnIndex = cursor.getColumnIndex(COL2);
int rankColumnIndex = cursor.getColumnIndex(COL4);
while (cursor.moveToNext()) {
int currentID = cursor.getInt(idColumnIndex);
String currentName = cursor.getString(nameColumnIndex);
String currenRank = cursor.getString(rankColumnIndex);
displayView.append(currentID + "--" +
currentName + "--" +
currenRank + "\n");
}
} finally {
// Always close the cursor when you're done reading from it. This releases all its
// resources and makes it invalid.
cursor.close();
}
}
public void knowtheresults(View view) {
String button_text;
button_text = ((Button) view).getText().toString();
if (button_text.equals("Start Page")) {
Intent intent = new Intent(this, MainActivity.class);
startActivity(intent);
} else if (button_text.equals("Back...")) {
Intent intent = new Intent(this, AverageActivity.class);
startActivity(intent);
}
}
}

Remove Bundle from your code and use following code
Intent miintent = new Intent(AverageActivity.this, ResultActivity.class);
miintent.putString("nombre", editResults.getText().toString());
startActivity(miintent);
In you third Activity
String number = getIntent().getStringExtra("nombre");

Related

How to display multiple EditText inputs after pressing Button in one TextView?

I'm in the beginning of my learning how to make apps. I want to make an app which should display randomized inputted tasks to do for the user. Firstly user should choose how many tasks would like to create and then write down tasks in EditText. I am able to create particular amount of EditText but I have no clue how to display all EditText input after pressing button. I have many versions of the code but non of them work. I got stuck and I need advice.
Here is one of my code version for the second activity.
public class TaskActivity extends AppCompatActivity {
LinearLayout containerLayout;
TextView receiverTV;
TextView tv;
TextView displayTaskTv;
EditText et;
Button btn;
Button randomTaskBtn;
int i = 0;
int size;
String inputEditText;
String inputTextView;
String stringsEt[];
String stringsTv [];
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_task);
containerLayout = (LinearLayout) findViewById(R.id.linear_layout);
receiverTV = (TextView) findViewById(R.id.receiver_textView);
Intent intent = getIntent();
int number = intent.getIntExtra("Number", defaultValue);
receiverTV.setText("You have chosen to add: " + number + " tasks!");
createEtTvBtn(number);
createBtn();
createTextView();
}
public void createEtTvBtn(int number) {
for (i = 1; i <= number; i++) {
tv = new TextView(this);
tv.setText("Task nr: " + i);
tv.setPadding(16, 16, 16, 16);
tv.setTextColor(Color.parseColor("#008b50"));
tv.setTextSize(20);
tv.setId(i + value);
containerLayout.addView(tv);
et = new EditText(this);
et.setHint("Enter task nr: " + i);
et.setId(i + value);
et.setLines(2);
containerLayout.addView(et);
btn = new Button(this);
btn.setText("Confirm task nr: " + i);
btn.setId(i + value);
containerLayout.addView(btn);
final List<EditText> allEditText = new ArrayList<EditText>();
final List<TextView>allTextView = new ArrayList<TextView>();
final List<Button>allButton = new ArrayList<Button>();
String[] stringsEditText = new String[(allEditText.size())];
String[] stringsTextView = new String[(allTextView.size())];
String[] stringsBtn = new String[(allButton.size())];
for(int i=0; i < allEditText.size(); i++){
stringsEditText[i] = allEditText.get(i).getText().toString();
}
for (int i=0; i < allTextView.size(); i++) {
stringsTextView[i] = allTextView.get(i).getText().toString();
size = allTextView.get(i).getText().toString().length();
}
for(int i=0; i < allButton.size(); i++){
stringsBtn[i] = allButton.get(i).getText().toString();
}
allTextView.add(tv);
allEditText.add(et);
allButton.add(btn);
allButton.get(0).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
inputEditText = allEditText.get(0).getText().toString();
stringsEt = new String[] {allEditText.get(0).getText().toString()};
if (inputEditText.length() > 0) {
allTextView.get(0).setText(inputEditText);
allEditText.add(allEditText.get(0));
allEditText.get(0).setText("");
}
else if (inputEditText.length() ==0){
Toast.makeText(TaskActivity.this, "You need to write down your task", Toast.LENGTH_LONG).show();
}
inputTextView = allTextView.get(0).getText().toString();
stringsTv = new String[] {allTextView.get(0).getText().toString()};
if (inputTextView.length() > 0) {
allTextView.get(0).getText();
allTextView.add(allTextView.get(0));
}
}
});
}
}
private Button createBtn() {
randomTaskBtn = new Button(this);
randomTaskBtn.setText("Task");
containerLayout.addView(randomTaskBtn);
randomTaskBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
double luckyTask = Math.random();
luckyTask *=size;
int luckyIndex = (int)luckyTask;
displayTaskTv.setText(stringsTv[luckyIndex]);
}
});
return randomTaskBtn;
}
private TextView createTextView() {
displayTaskTv = new TextView(this);
displayTaskTv.setTextSize(20);
displayTaskTv.setTextColor(Color.parseColor("#dd2626"));
displayTaskTv.setText("");
containerLayout.addView(displayTaskTv);
return displayTaskTv;
}
}
Thank you for any constructive advices.
I am sure my code is big mess. I wanted to created more methods but I didn't succeed.
This is what you should do
Step 1 -
Create multiple EditTexts and store each one of them in an ArrayList say myEditTextList.
Step 2- Take data from all edit texts
String str = ""
for(EditText et: myEditTextList) {
str += et.getText().toString();
}
Step 3- Display data in str wherever you want.

Implementing pagination in android with tablelayout

I have a table layout where rows are dynamically added. I want 30 data to be shown in one page.pages should be automatically added with increasing data. This is my code.
int increment = 0;
public int TOTAL_LIST_ITEMS;
public int NUM_ITEMS_PAGE = 50;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.frag_tab1, container, false);
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
tableLayout = (TableLayout) view.findViewById(R.id.tableLay);
buttonNext = (Button) view.findViewById(R.id.next);
listView = (ListView) view.findViewById(R.id.list);
title = (TextView) view.findViewById(R.id.text);
buttonPrev = (Button) view.findViewById(R.id.prev);
buttonPrev.setEnabled(false);
// data = new ArrayList<String>();
buttonNext.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
increment++;
loadList(increment);
Toast.makeText(getActivity(),"the page is"+increment,Toast.LENGTH_LONG).show();
checkEnable();
}
});
buttonPrev.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
increment--;
loadList(increment);
Toast.makeText(getActivity(),"the page is"+increment,Toast.LENGTH_LONG).show();
checkEnable();
}
});
db = getActivity().openOrCreateDatabase("hitechData.db", Context.MODE_PRIVATE, null);
DBHelper dh = new DBHelper(getActivity(), "hitechData.db", null, 1);
tableLayout.setColumnStretchable(0, true);
tableLayout.setColumnStretchable(2, true);
tableLayout.setStretchAllColumns(true);
tableLayout.bringToFront();
db = getActivity().openOrCreateDatabase("hitechData.db", SQLiteDatabase.CREATE_IF_NECESSARY, null);
db.setVersion(1);
db.setLocale(Locale.getDefault());
dh.onCreate(db);
db.setLockingEnabled(true);
String query = "SELECT * FROM leadData3 Order by id DESC";
Cursor cur;
cur = db.rawQuery(query, null);
TOTAL_LIST_ITEMS = cur.getCount();
data=TOTAL_LIST_ITEMS;
int val = TOTAL_LIST_ITEMS % NUM_ITEMS_PAGE;
val = val == 0?0:1;
pageCount = TOTAL_LIST_ITEMS / NUM_ITEMS_PAGE;
if (cur != null && cur.getCount() > 0) {
if (cur.moveToFirst()) {
try {
while (cur.isAfterLast() == false ){
TableRow tr = new TableRow(getActivity().getBaseContext());
final TextView compName = new TextView(getActivity().getBaseContext());
compName.setBackgroundResource(R.drawable.borderr);
final TextView firstName = new TextView(getActivity().getBaseContext());
firstName.setBackgroundResource(R.drawable.borderr);
final TextView midName = new TextView(getActivity().getBaseContext());
midName.setBackgroundResource(R.drawable.borderr);
final TextView lastName = new TextView(getActivity().getBaseContext());
lastName.setBackgroundResource(R.drawable.borderr);
compName.append(cur.getString(1));
compName.setTextColor(this.getResources().getColor(R.color.colorPrimary));
compName.setPadding(30, 0, 0, 0);
firstName.append(cur.getString(21));
firstName.setTextColor(this.getResources().getColor(R.color.colorPrimary));
firstName.setPadding(30, 0, 0, 0);
midName.append(cur.getString(22));
midName.setTextColor(this.getResources().getColor(R.color.colorPrimary));
midName.setPadding(30, 0, 0, 0);
lastName.append(cur.getString(23));
lastName.setTextColor(this.getResources().getColor(R.color.colorPrimary));
lastName.setPadding(30, 0, 0, 0);
// String name =firstName.getText().toString()+midName.getText().toString()+lastName.getText().toString();
firstName.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String nameValue = firstName.getText().toString();
String companyValue = compName.getText().toString();
Intent intent = new Intent(getActivity().getApplicationContext(), ShowDetailData.class);
intent.putExtra("name", nameValue);
intent.putExtra("accNo", companyValue);
Toast.makeText(getActivity().getApplicationContext(), nameValue, Toast.LENGTH_LONG).show();
startActivity(intent);
}
});
tr.addView(firstName);
tr.addView(compName);
tableLayout.addView(tr);
cur.moveToNext();
/* count++;
nextPage++;
Toast.makeText(getActivity().getApplicationContext(), "count is : " + count, Toast.LENGTH_LONG).show();*/
//cur.close();
}
} finally {
cur.close();
db.close();
}
} else {
Toast.makeText(getActivity().getApplicationContext(), "no Data", Toast.LENGTH_LONG).show();
}
}
}
/*
*/
/*
buttonNext.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
nextPage++;
Toast.makeText(getActivity(), "next page is"+nextPage, Toast.LENGTH_SHORT).show();
}
});*/
private void loadList(int number){
ArrayList<String> sort = new ArrayList<String >();
title.setText("Page "+(number+1+" of " +pageCount));
int start = number * NUM_ITEMS_PAGE;
for (int i=start; i<(start)+NUM_ITEMS_PAGE; i++)
{
if(i<data)
{
sort.add(String.valueOf(data));
}
else {
break;
}
// adapter = new ArrayAdapter<String>(getActivity(), //android.R.layout.simple_list_item_1,sort);
// tablerow.setAdapter(adapter);
//implement table row in adapter
}}
private void checkEnable(){
if(increment+1 == pageCount)
{
buttonNext.setEnabled(false);
}
else if(increment == 0){
buttonPrev.setEnabled(false);
}
else {
buttonPrev.setEnabled(true);
buttonNext.setEnabled(true);
}
}
}
I want to know how can i change the page after no. of rows exceeds 30. I am unable to do pagination.
Currently i am using Sqlite and all the filled data is appearing on the first page.
I want to divide the data and want it appear in set of 30 after click of previous and next.

Onclickitem and start new intent inside Cursor

I am a new guy to android development. I have created a SMS Inbox application.
I managed to get the SMS Inbox of the phone. Now I want to set a onclick method to open a specific message in a new activity with the phone number and the message.
Here is the code for my inbox activity. I do not understand, the place to put my onclicklistitem method.
public class MessageInboxActivity extends ActionBarActivity implements OnItemClickListener {
private static MessageInboxActivity inst;
ArrayList<String> smsMessagesList = new ArrayList<String>();
ListView smsListView;
ArrayAdapter arrayAdapter;
public static MessageInboxActivity instance() {
return inst;
}
#Override
public void onStart() {
super.onStart();
inst = this;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_message_inbox);
smsListView = (ListView) findViewById(R.id.SMSList);
arrayAdapter = new ArrayAdapter<String>(this, R.layout.my_adapter_item, R.id.product_name, smsMessagesList);
smsListView.setAdapter(arrayAdapter);
smsListView.setOnItemClickListener(this);
refreshSmsInbox();
}
public void refreshSmsInbox() {
ContentResolver contentResolver = getContentResolver();
Cursor smsInboxCursor = contentResolver.query(Uri.parse("content://sms/inbox"), null, null, null, null);
int indexBody = smsInboxCursor.getColumnIndex("body");
int indexAddress = smsInboxCursor.getColumnIndex("address");
if (indexBody < 0 || !smsInboxCursor.moveToFirst()) return;
arrayAdapter.clear();
do {
String str = "SMS From: " + smsInboxCursor.getString(indexAddress) +
"\n" + smsInboxCursor.getString(indexBody) + "\n";
arrayAdapter.add(str);
} while (smsInboxCursor.moveToNext());
}
public void updateList(final String smsMessage) {
arrayAdapter.insert(smsMessage, 0);
arrayAdapter.notifyDataSetChanged();
}
public void onItemClick(AdapterView<?> parent, View view, int pos, long id) {
try {
String[] smsMessages = smsMessagesList.get(pos).split("\n");
String address = smsMessages[0];
String smsMessage = "";
for (int i = 1; i < smsMessages.length; ++i) {
smsMessage += smsMessages[i];
}
String smsMessageStr = address + "\n";
smsMessageStr += smsMessage;
Toast.makeText(this, smsMessageStr, Toast.LENGTH_SHORT).show();
} catch (Exception e) {
e.printStackTrace();
}
}
}
Can someone help me to start new activity with the phone number and the message.
I'd put this in a comment but I can't comment, can you clarify your problem? What activity are you trying to link to and what exactly do you want to achieve? it seems like you just need to add to your onItemClick()
String smsMessageStr = address + "\n";
smsMessageStr += smsMessage;
Intent in = new Intent(getApplicationContext,/*whatever activity you want to open*/);
in.putStringExtra(/*some static keystring*/,smsMessage);
startActivity(in);
but it's hard to say for sure without knowing more

Difficulty saving and storing

I am trying to save and store data in an android app using java. At the moment the data will not save and it causes my app to crash. Can anyone make any suggestions to my code? Part of my page includes a total budget and I am difficulty storing and saving the total budget.
public class Summary extends Activity implements TextWatcher, View.OnClickListener
{
DecimalFormat df = new DecimalFormat("£0.00");
int noOfGifts, giftsPurchased;
double cost;
EditText budgetEntered;
double savedBudget = 0;
String budgetString;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.summary);
budgetEntered = (EditText) findViewById(R.id.s2TotalBudget);
budgetEntered.addTextChangedListener(this);
Button saveBudget = (Button) findViewById(R.id.s2ViewList);
saveBudget.setOnClickListener(saveButtonListener);
if(savedBudget != 0)
{
saveBudget.setText(budgetString);
}
Bundle passedInfo = getIntent().getExtras();
if (passedInfo != null)
{
cost = passedInfo.getDouble("cost");
noOfGifts = passedInfo.getInt("noOfGifts");
giftsPurchased = passedInfo.getInt("giftsPurchased");
}
Button logoutButton = (Button) findViewById(R.id.s2LogoutButton);
logoutButton.setOnClickListener(new View.OnClickListener()
{
public void onClick(View view)
{
Intent myIntent = new Intent(Summary.this, MainActivity.class);
startActivity(myIntent);
}
});
Button viewList = (Button) findViewById(R.id.s2ViewList);
viewList.setOnClickListener(new View.OnClickListener()
{
public void onClick(View view)
{
Intent myIntent = new Intent(Summary.this, GiftList.class);
startActivity(myIntent);
}
});
String [][] summary = {{"Number of Presents to buy: ", (noOfGifts + "")},
{"Number of Presents bought:", (giftsPurchased + "")},
{"Cost: £", (cost + "")},
{"Budget: £", "50"}};
String passedBudget=null;
//convert totalPresents to double from String
String tempPresents = summary[0][1];
int presents = Integer.parseInt(tempPresents);
//convert presentsBought to double from String
String tempBought = summary[1][1];
int presentsToBuy = Integer.parseInt(tempBought);
//Number of presents
TextView s2PresentResult = (TextView) findViewById(R.id.s2PresentsResult);
s2PresentResult.setText(summary[0][1]);
//Number of presents to buy
TextView s2PresentsBuyResult = (TextView) findViewById(R.id.s2PresntsBuyResult);
s2PresentsBuyResult.setText((noOfGifts - giftsPurchased) + "");
Bundle passedId = getIntent().getExtras();
if (passedId != null)
{
passedBudget = passedId.getString("Enter Budget");
}
//EditText s2TotalBudget = (EditText) findViewById(R.id.s2TotalBudget);
//s2TotalBudget .addTextChangedListener((android.text.TextWatcher) this);
//s2TotalBudget .setText(passedBudget, TextView.BufferType.EDITABLE);
//Number of people
//TextView s2TotalBudget = (TextView) findViewById(R.id.s2TotalBudget);
//s2TotalBudget.setText("Enter budget");
//Number of people
TextView s2TotalCost = (TextView) findViewById(R.id.s2TotalCost);
s2TotalCost.setText(df.format(Double.parseDouble(summary[2][1])));
//Output if over or under budget
TextView s2CalculateOverBudget = (TextView) findViewById(R.id.s2CalculateOverBudget);
//convert totalCost to double from String
String temp = summary[2][1];
double totalCost = Double.parseDouble(temp);
//convert totalBudget to double from String
String tempTwo = "14";
double totalBudget = Double.parseDouble(tempTwo);
if((totalCost>totalBudget)&&(totalBudget!=0))
{
s2CalculateOverBudget.setTextColor(Color.rgb(209,0,0));
s2CalculateOverBudget.setText("You are over budget");
}
else if(totalBudget==0){
s2CalculateOverBudget.setText("");
}
else {
s2CalculateOverBudget.setText("You are within budget");
}
}
public View.OnClickListener saveButtonListener = new View.OnClickListener()
{
#Override
public void onClick(View v)
{
if(budgetEntered.getText().length()>0)
{
budgetString = budgetEntered.getText().toString();
}
}
};
public void onClick(View v)
{
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after)
{
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count)
{
}
#Override
public void afterTextChanged(Editable s)
{
this it the best way to store and load value in Android:
save values: (put this where you want to save the values, for example in the onStop or onPause method. Or, in your case, in the onClick method)
SharedPreferences settings = getSharedPreferences("MyPref", 0);
SharedPreferences.Editor editor = settings.edit();
editor.putInt("testValue", value);
editor.commit();
load values:
SharedPreferences settings = getSharedPreferences("MyPref", 0);
value = settings.getInt("testValue", defValue);

What could cause an Android activity to loop infinitely?

I am writing a simple application to scan and record WiFi Access Points, there are three options; a single scan, 10 scans, or scan for a period of time.
When I enter my nWiFiScans activity it preforms the scans, records the file and STARTS THE ACTIVITY AGAIN!!!
WHY WOULD IT DO THIS???
nWiFiScans.java
public class nWiFiScans extends Activity
{
//declarations
public static String pntNameStr;
public static int numScans;
public static int scansMin;
LinearLayout layout1;
ScrollView scrollLayout;
TextView label1;
EditText n1Text;
EditText n2Text;
LayoutParams params_layout1;
WifiManager mainWifi = null;
WifiReceiver receiverWifi;
List<ScanResult> wifiList;
StringBuilder sb = new StringBuilder();
Intent intent;
SimpleDateFormat time;
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
scrollLayout = new ScrollView(this);
scrollLayout.setBackgroundColor(Color.BLUE);
//Create new layout in "this" activity
params_layout1 = new LayoutParams(LayoutParams.MATCH_PARENT,LayoutParams.MATCH_PARENT, 1);
layout1 = new LinearLayout(this);
layout1.setBackgroundColor(Color.RED);
layout1.setLayoutParams(params_layout1);
//Create TextView in "this" activity
label1 = new TextView(this);
label1.setBackgroundColor(Color.YELLOW);
//Put some text in the TextView
// Get the message from the intent
intent = getIntent();
pntNameStr = intent.getStringExtra(MainActivity.EXTRA_pntNameStr);
numScans = intent.getIntExtra(MainActivity.EXTRA_numScans, 1);
label1.setText(pntNameStr);
//Place the TextView inside the Layout
layout1.addView(label1);
layout1.setOrientation(LinearLayout.VERTICAL);
//scrollLayout.addView(label1);
//layout1.addView(n1Text);
//layout1.addView(n2Text);
//By default the layout is set to HOR, so we change it to VERT orientation:
// Display layout1 when the activity is created:
setContentView(layout1);
mainWifi = (WifiManager) getSystemService(Context.WIFI_SERVICE);
checkIfWifiIsOn(mainWifi);
receiverWifi = new WifiReceiver();
registerReceiver(receiverWifi, new IntentFilter(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION));
mainWifi.startScan();
label1.setText("Starting Scan..."+String.valueOf(numScans));
}
public void checkIfWifiIsOn(WifiManager mainWifi)
{
if (mainWifi.isWifiEnabled() == false)
{
// If wifi disabled then enable it
Toast.makeText(getApplicationContext(), "wifi is disabled..making it enabled",
Toast.LENGTH_LONG).show();
mainWifi.setWifiEnabled(true);
}
else {Toast.makeText(getApplicationContext(), "wifi is enabled... thats good...",
Toast.LENGTH_SHORT).show();}
}
public void generateNoteOnSD(String sFileName, String sBody)
{
File root = null;
try
{
root = new File(Environment.getExternalStoragePublicDirectory("SurveyAppData"), "ScanResults");
if (!root.exists())
{
root.mkdirs();
}
File gpxfile = new File(root, sFileName);
FileWriter writer = new FileWriter(gpxfile);
writer.append(sBody);
writer.flush();
writer.close();
Toast.makeText(this, "Saved" + "/n" +root.toURI(), Toast.LENGTH_LONG).show();
Toast.makeText(getApplicationContext(), "IM MOTHERFUCKING DONE" ,
Toast.LENGTH_SHORT).show();
//Log.d("Scan Results",sb.toString());
Intent i=new Intent(nWiFiScans.this, MainActivity.class);
i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
finish();
}
catch(IOException e)
{
e.printStackTrace();
Toast.makeText(this, "!!! - Could NOT Saved" + "/n" +root.toURI(), Toast.LENGTH_LONG).show();
}
}
public class WifiReceiver extends BroadcastReceiver
{
// This method call when number of wifi connections changed
long fisrtScanTS;
private String FILENAME = pntNameStr;
public FileOutputStream outputStream;
#SuppressLint("NewApi")
public void onReceive(Context c, Intent intent)
{
time = new SimpleDateFormat("ddMMyyyyhhmmss");
int ScanTime = numScans;
if(ScanTime==1 | ScanTime==10)
{
for (int scanNum = 1; scanNum<ScanTime+1; scanNum++)
{
wifiList = mainWifi.getScanResults();
for(int i = 0; i < wifiList.size(); i++)
{
sb.append(((wifiList.get(i)).BSSID + " " + (wifiList.get(i)).level + " " + (wifiList.get(i)).frequency + " "+ (wifiList.get(i)).timestamp + " "+ (wifiList.get(i)).SSID +" "+ time.format(new Date()) + "\n" ) );
fisrtScanTS = (wifiList.get(1)).timestamp;
}
do
{
mainWifi.startScan();
wifiList = mainWifi.getScanResults();
try{Thread.currentThread().sleep(200);}
catch(InterruptedException ie){
//If this thread was intrrupted by nother thread
}
} while(fisrtScanTS == (wifiList.get(1)).timestamp);
Toast.makeText(getApplicationContext(), "Scan number " + scanNum ,
Toast.LENGTH_SHORT).show();
}
}else if (ScanTime!=0)
{
Calendar timeNow = Calendar.getInstance();
Calendar timeEnd = Calendar.getInstance();
timeEnd.set(timeNow.YEAR, timeNow.MONTH, timeNow.DAY_OF_MONTH, timeNow.HOUR, timeNow.MINUTE+numScans, timeNow.SECOND);
while(!(timeNow.after(timeEnd))){
wifiList = mainWifi.getScanResults();
for(int i = 0; i < wifiList.size(); i++){
sb.append(((wifiList.get(i)).BSSID + " " + (wifiList.get(i)).level + " " + (wifiList.get(i)).frequency + " "+ (wifiList.get(i)).timestamp + " "+ (wifiList.get(i)).SSID +" "+ time.format(new Date()) + "\n" ) );
fisrtScanTS = (wifiList.get(1)).timestamp;
}
do {
mainWifi.startScan();
wifiList = mainWifi.getScanResults();
try{Thread.currentThread().sleep(200);}
catch(InterruptedException ie){
//If this thread was intrrupted by nother thread
}} while(fisrtScanTS == (wifiList.get(1)).timestamp);
timeNow = Calendar.getInstance();
Toast.makeText(getApplicationContext(), timeNow.getTime().toString() + " :: " + timeEnd.getTime().toString() ,
Toast.LENGTH_SHORT).show();
}
}
generateNoteOnSD(FILENAME, sb.toString());
FILENAME="x";
ScanTime=0;
}
}
}
MainActivity.java
public class MainActivity extends Activity
{
LinearLayout mainLayout,leftLayout,rightLayout;
EditText pointName;
EditText scanTime;
Button scan10, scan1, timedScan;
TextView msg;
LayoutParams paramsL,paramsR;
static final String EXTRA_pntNameStr = "com.example.surveyappv2.pntNameStr";
static final String EXTRA_scanTimeMin = "com.example.surveyappv2.scanTimeMin";
static final String EXTRA_numScans = "com.example.surveyappv2.numScans";
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
mainLayout = new LinearLayout(this);
mainLayout.setOrientation(LinearLayout.HORIZONTAL);
paramsL = new LayoutParams(500,LayoutParams.MATCH_PARENT, 1);
paramsR = new LayoutParams(500,LayoutParams.MATCH_PARENT, 1);
leftLayout = new LinearLayout(this);
leftLayout.setOrientation(LinearLayout.VERTICAL);
leftLayout.setLayoutParams(paramsL);
leftLayout.setGravity(Gravity.CENTER_HORIZONTAL);
leftLayout.setBackgroundColor(Color.YELLOW);
rightLayout = new LinearLayout(this);
rightLayout.setOrientation(LinearLayout.VERTICAL);
rightLayout.setLayoutParams(paramsR);
rightLayout.setGravity(Gravity.CENTER_HORIZONTAL);
rightLayout.setBackgroundColor(Color.BLUE);
scanTime = new EditText(this);
scanTime.setHint("Scan Duration (min)");
scanTime.setInputType(InputType.TYPE_CLASS_NUMBER);
pointName = new EditText(this);
pointName.setHint("Enter Point Name");
scan10 = new Button(this);
scan1 = new Button(this);
timedScan = new Button(this);
msg = new TextView(this);
scan10.setText("Do 10 Scans");
scan1.setText("Do a Single Scan");
timedScan.setText("Timed Scan");
msg.setText("Alec Sucks");
leftLayout.addView(pointName);
leftLayout.addView(scanTime);
rightLayout.addView(msg);
rightLayout.addView(scan10);
rightLayout.addView(scan1);
rightLayout.addView(timedScan);
mainLayout.addView(leftLayout);
mainLayout.addView(rightLayout);
mainLayout.setBackgroundColor(Color.RED);
setContentView(mainLayout);
setButtonClickListener();
}
private void setButtonClickListener()
{
scan10.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
String message2 = "Button: \n" + scan10.getText();
msg.setText(message2);
startScan(mainLayout,10);
}
});
scan1.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
String message2 = "Button: \n" + scan1.toString();
msg.setText(message2);
startScan(mainLayout,1);
}
});
timedScan.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
String message2 = "Button: \n" + timedScan.toString();
msg.setText(message2);
startScan(mainLayout,Integer.parseInt(scanTime.getText().toString()));
}
});
}
#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;
}
public void startScan(View view, int numScans)
{
Intent intent = new Intent(this, nWiFiScans.class);
String pntNameStr = pointName.getText().toString();
intent.putExtra(EXTRA_pntNameStr, pntNameStr);
intent.putExtra(EXTRA_numScans, numScans);
startActivity(intent);
}
}
I ran it, removed the file creation and the Intent(You only need to call finish();) and then it worked. Have you checked that it actually goes through File creation for you? Because mine got stuck there and then it jumps out of try so it can't reach the finish(); call, I also called unregisterReceiver(receiverWifi); before finish();
EDIT, File creation:
File sdCard = Environment.getExternalStorageDirectory(); //returns sdcard directory
File dir = new File (sdCard.getAbsolutePath() + "/mydirectory");
dir.mkdirs();
File file = new File(dir, "filename");

Categories

Resources