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");
Related
I'm new to android and now I'm working on NFC project that needed when smartcard / tag detected the timer will start and when the "data" in smartcard has been read and show to TextView the timer will stop. How could I do that ? I want to use just 1 TextView. So, when TextView get the data from smartcard like "Hello World" the timer stop.
I really appreciate if you want to fix my coding too. It's really mess up, sorry.
This is how to stop the timer :
TimeBuff += MillisecondTime;
handler.removeCallbacks(runnable);
I already tried :
tvNFCContent.setText("NFC Content: " + text); // the textview show tag /smartcard data //
tvNFCContent = (TextView) findViewById(R.id.data);
tvNFCContent.getText().toString();
String yo = String.valueOf(yo.getText().toString());
if (yo == text){
TimeBuff += MillisecondTime;
handler.removeCallbacks(runnable);
}
public class Read extends Activity {
NfcAdapter mAdapter;
Tag mTag;
PendingIntent mPI;
IntentFilter mFilter[];
String userData, yo;
boolean writeMode;
Context context;
TextView tvNFCContent, Timer, Low;
Button start, pause, reset, lap;
long MillisecondTime, StartTime, TimeBuff, UpdateTime = 0L;
Handler handler;
int Seconds, Minutes, MilliSeconds;
ListView listView;
String[] ListElements = new String[]{};
List<String> ListElementsArrayList;
ArrayAdapter<String> adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.read);
tvNFCContent = (TextView) findViewById(R.id.data);
Timer = (TextView) findViewById(R.id.timer);
handler = new Handler();
mAdapter = NfcAdapter.getDefaultAdapter(this);
mPI = PendingIntent.getActivity(getApplicationContext(), 0,
new Intent(this, getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0);
IntentFilter tagDetected = new IntentFilter(NfcAdapter.ACTION_TAG_DISCOVERED);
IntentFilter filter2 = new IntentFilter(NfcAdapter.ACTION_NDEF_DISCOVERED);
mFilter = new IntentFilter[]{tagDetected, filter2};
mAdapter = NfcAdapter.getDefaultAdapter(this);
if (mAdapter == null) {
// Stop here, we definitely need NFC
Toast.makeText(this, "This device doesn't support NFC.", Toast.LENGTH_LONG).show();
finish();
}
readFromIntent(getIntent());
}
/**
* Read From NFC Tag
*
* #param intent
*/
private void readFromIntent(Intent intent) {
String action = intent.getAction();
if (NfcAdapter.ACTION_TAG_DISCOVERED.equals(action)
|| NfcAdapter.ACTION_TECH_DISCOVERED.equals(action)
|| NfcAdapter.ACTION_NDEF_DISCOVERED.equals(action)) {
Parcelable[] rawMsgs = intent.getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES);
NdefMessage[] msgs = null;
if (rawMsgs != null) {
msgs = new NdefMessage[rawMsgs.length];
for (int i = 0; i < rawMsgs.length; i++) {
msgs[i] = (NdefMessage) rawMsgs[i];
}
}
buildTagViews(msgs);
}
}
private void buildTagViews(NdefMessage[] msgs) {
if (msgs == null || msgs.length == 0) return;
String text = "";
String tagId = new String(msgs[0].getRecords()[0].getType());
byte[] payload = msgs[0].getRecords()[0].getPayload();
String textEncoding = ((payload[0] & 128) == 0) ? "UTF-8" : "UTF-16"; // Get the Text Encoding
int languageCodeLength = payload[0] & 0063; // Get the Language Code, e.g. "en"
// String languageCode = new String(payload, 1, languageCodeLength, "US-ASCII");
try {
text = new String(payload, languageCodeLength + 1, payload.length - languageCodeLength - 1, textEncoding);
} catch (UnsupportedEncodingException e) {
Log.e("UnsupportedEncoding", e.toString());
}
tvNFCContent.setText("NFC Content: " + text);
}
NdefMessage[] getNdefMessage(Intent intent) {
NdefMessage[] msgs = null;
Parcelable[] rawMsgs = intent.getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES);
if (rawMsgs != null) {
msgs = new NdefMessage[rawMsgs.length];
for (int i = 0; i < rawMsgs.length; i++) {
msgs[i] = (NdefMessage) rawMsgs[i];
}
}
return msgs;
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
protected void onNewIntent(Intent intent) {
// TODO Auto-generated method stub
setIntent(intent);
readFromIntent(intent);
if (NfcAdapter.ACTION_TAG_DISCOVERED.equals(intent.getAction())) {
mTag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
}
super.onNewIntent(intent);
if (intent.getAction().equals(NfcAdapter.ACTION_NDEF_DISCOVERED)) {
Toast.makeText(getApplicationContext(), "Ndefdiscovered", Toast.LENGTH_SHORT).show();
} else if (intent.getAction().equals(NfcAdapter.ACTION_TAG_DISCOVERED)) {
mTag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
Toast.makeText(getApplicationContext(), "Smartcard detected", Toast.LENGTH_SHORT).show();
StartTime = SystemClock.uptimeMillis();
handler.postDelayed(runnable, 0);
NdefMessage[] messages = getNdefMessage(intent);
if (messages == null) {
Toast.makeText(getApplicationContext(), "Data di dalam kartu kosong", Toast.LENGTH_SHORT).show();
return;
}
byte[] payload = messages[0].getRecords()[0].getPayload();
userData = new String(payload);
} else {
Toast.makeText(getApplicationContext(), "Undefined smartcard", Toast.LENGTH_SHORT).show();
}
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
mAdapter.disableForegroundDispatch(this);
}
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
mAdapter.enableForegroundDispatch(this, mPI, mFilter, null);
}
public Runnable runnable = new Runnable() {
public void run() {
MillisecondTime = SystemClock.uptimeMillis() - StartTime;
UpdateTime = TimeBuff + MillisecondTime;
Seconds = (int) (UpdateTime / 1000);
Minutes = Seconds / 60;
Seconds = Seconds % 60;
MilliSeconds = (int) (UpdateTime % 1000);
Timer.setText("" + Minutes + ":"
+ String.format("%02d", Seconds) + ":"
+ String.format("%03d", MilliSeconds));
handler.postDelayed(this, 0);
}
};
}
I dont want to use button. Just an automatically, when the TextView show the tag / smartcard data the timer will stop.
First of all, when you compare two Strings. You need to use equals().
So, if(yo == text) must be changed like this:
if(yo.equals(text)){
TimeBuff += MillisecondTime;
handler.removeCallbacks(runnable);
}
Second of all, you need to declare tvNFCContent before using its setText().
So, the order must be:
tvNFCContent = (TextView) findViewById(R.id.data); // This must come first.
tvNFCContent.setText("NFC Content: " + text); // Then you can set the text.
// tvNFCContent.getText().toString(); // this part is not necessary because you already have "text" variable somewhere.
String yo = String.valueOf(yo.getText().toString()); // Duplicate names are not a good naming. Try using "yoStr"(String) and "tvYo"(TextView) or something like that.
I can't fully understand you but..
Try this:
if (intent.getAction().equals(NfcAdapter.ACTION_NDEF_DISCOVERED)) {
Toast.makeText(getApplicationContext(), "Ndefdiscovered", Toast.LENGTH_SHORT).show();
} else if (intent.getAction().equals(NfcAdapter.ACTION_TAG_DISCOVERED)) {
mTag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
Toast.makeText(getApplicationContext(), "Smartcard detected", Toast.LENGTH_SHORT).show();
StartTime = SystemClock.uptimeMillis();
handler.postDelayed(runnable, 0);
NdefMessage[] messages = getNdefMessage(intent);
if (messages == null) {
Toast.makeText(getApplicationContext(), "Data di dalam kartu kosong", Toast.LENGTH_SHORT).show();
return;
}else{
TimeBuff += MillisecondTime;
handler.removeCallbacks(runnable);
}
byte[] payload = messages[0].getRecords()[0].getPayload();
userData = new String(payload);
TextView tvNFCContent = findViewById(R.id.tv_nfc_content);
tvNFCContent.setText("NFC Content: " + userData);
} else {
Toast.makeText(getApplicationContext(), "Undefined smartcard", Toast.LENGTH_SHORT).show();
}
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");
I'm having a problem changing a TextView to a ListView. Originally, the app had a button that when clicked, runs tests to a bluetooth device and displays the results in a textview. I modified the app to contain two textviews that have the last text results and a separate xml file (connected with viewflipper) to go to a second textview that contains all of the test results, until the user clears the textview by clicking a button. I followed along with this example and checked what I was entering in the ArrayAdapter section of the code, and it appears to be what is required according to the developer's guide, but I still get his error:
Cannot resolve constructor 'ArrayAdapter(com.example.android.stardustscanner.ScannerFragment, int, int, java.lang.String)'
Why am I getting this error?
My .java file that I am making all the changes in is very long and contains a lot of thins that aren't relevant to this question and doesn't fit in the question box, so I'll try to only include the relevant parts. The error is towards the bottom with this line:
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(this, R.layout.fragment_bluetooth_scanner, R.id.textView, saveData);
ScannerFragment.java
public class ScannerFragment extends Fragment implements LocationListener {
ListView mListView;
//page switching things KG 8/24/17
private ViewFlipper mViewFlipper;
private float lastX;
private Button mViewLog;
private Button mReturnFlipper;
private TextView mShowData;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container,
#Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.flipper_holder, container, false);//kg 8/24/17
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
SP = PreferenceManager.getDefaultSharedPreferences(getContext());
mViewFlipper = (ViewFlipper) view.findViewById(R.id.viewFlip); //KG 8/24/17
mViewLog = (Button) view.findViewById(R.id.viewLog); //kg 8/24/17
mReturnFlipper = (Button) view.findViewById(R.id.flipperReturn); //kg 8/24/17
mShowData = (TextView) view.findViewById(R.id.textView) ; //kg 8/25/2017
mShowData.setText(readFromFile()); // kg 8/25/2017
mPowerOffButton = (Button) view.findViewById(R.id.button_poweroff);
mDisconnectButton = (Button) view.findViewById(R.id.button_disconnect);
mConnectButton = (Button) view.findViewById(R.id.button_connect);
mPresence = (Button) view.findViewById(R.id.button_present);
mBattery = (ProgressBar) view.findViewById(R.id.progressBar);
mBlinkConnect = (Button) view.findViewById(R.id.button_connectionblink);
mBlinkData = (Button) view.findViewById(R.id.button_communication);
mClearLog = (Button) view.findViewById(R.id.button_clear_log);
mDeviceName = (Button) view.findViewById(R.id.button_devicename);
mDeviceSN = (Button) view.findViewById(R.id.button_devicesn);
mBatteryPerc = (TextView) view.findViewById(R.id.label_batterypct);
mListView = (ListView) view.findViewById(R.id.scanLogView); //kg 8/28/17
// mReadingLog = (TextView) view.findViewById(R.id.scanLogView);
mReadingLog.setMovementMethod(new ScrollingMovementMethod());
mReadingLog.setText(readFromFile());
telephonyManager = (TelephonyManager)getContext().getSystemService(Context.TELEPHONY_SERVICE);
initLocationService(this.getContext());
final ActionBar actionBar = getActivity().getActionBar();
if (null == actionBar) {
return;
}
final Drawable D = getResources().getDrawable(R.drawable.stardust2);
actionBar.setBackgroundDrawable(D);
actionBar.setTitle("");
//KG 8/24/17
mViewLog.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view){
mViewFlipper.showNext();
}
});
mReturnFlipper.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view){
mViewFlipper.showPrevious();
}
});
}
private void setupScanner() {
Log.d(TAG, "setupScanner()");
// Initialize the send button with a listener that for click events
mPowerOffButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if(isIris) {
publishMessage(Constants.COMMAND_POWEROFF_IRIS);
} else {
publishMessage(Constants.COMMAND_POWEROFF);
}
mScannerService.stop();
}
});
// Initialize the send button with a listener that for click events
mDisconnectButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Send a message using content of the edit text widget
publishMessage(Constants.COMMAND_DISCONNECT);
mScannerService.stop();
}
});
// Initialize the send button with a listener that for click events
mConnectButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Send a message using content of the edit text widget
publishMessage(Constants.COMMAND_ON_CONNECT);
}
});
mClearLog.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Send a message using content of the edit text widget
mReadingLog.setText("");
if(SP.getBoolean("writeToFile", true)) {
writeToFile("", "", false);
}
}
});
// Initialize the ScannerService to perform bluetooth connections
mScannerService = new ScannerService(getActivity(), mHandler);
}
private TextView.OnEditorActionListener mWriteListener
= new TextView.OnEditorActionListener() {
public boolean onEditorAction(TextView view, int actionId, KeyEvent event) {
// If the action is a key-up event on the return key, send the message
if (actionId == EditorInfo.IME_NULL && event.getAction() == KeyEvent.ACTION_UP) {
String message = view.getText().toString();
publishMessage(message);
}
return true;
}
};
private final Handler mHandler = new Handler() {
#Override
public void handleMessage(Message msg) {
FragmentActivity activity = getActivity();
switch (msg.what) {
case Constants.MESSAGE_STATE_CHANGE:
switch (msg.arg1) {
case ScannerService.STATE_CONNECTED:
setStatus(mConnectedDeviceName);
if(mConnectedDeviceName.substring(0, 4).toLowerCase().equals("iris") || mConnectedDeviceName.substring(0, 8).toLowerCase().equals("stardust")) {
isIris = true;
mPresence.setClickable(true);
mPresence.setText("Click to detect taggant");
mPresence.setBackgroundColor(Color.parseColor("#0061ff"));
mPresence.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
readoutStarted = true;
publishMessage(Constants.COMMAND_RUN_IRIS);
}
});
mPowerOffButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
publishMessage(Constants.COMMAND_POWEROFF_IRIS);
mScannerService.stop();
}
});
} else {
isIris = false;
}
if(!isIris) {
mPresence.setClickable(false);
mPresence.setText("NO TAGGANT DETECTED");
mPresence.setBackgroundColor(Color.parseColor("#ffc4ab"));
publishMessage(Constants.COMMAND_ON_CONNECT);
timer = new Timer();
timerStarted = true;
timer.scheduleAtFixedRate(new TimerTask() {
synchronized public void run() {
publishMessage(Constants.COMMAND_READDATA);
}
}, 1000, 1000);
} else {
if(timerStarted) {
timer.cancel();
timer.purge();
timerStarted = false;
}
}
mBlinkConnect.setBackgroundColor(Color.parseColor("#11D901"));
break;
case ScannerService.STATE_CONNECTING:
setStatus("C");
break;
case ScannerService.STATE_LISTEN:
case ScannerService.STATE_NONE:
mBlinkConnect.setBackgroundColor(Color.parseColor("#ff2b0f"));
mBlinkData.setBackgroundColor(Color.parseColor("#CCCCCC"));
if(timerStarted) {
timer.cancel();
timer.purge();
timerStarted = false;
}
setStatus("D");
break;
}
break;
case Constants.MESSAGE_WRITE:
mBlinkData.setBackgroundColor(Color.parseColor("#CCCCCC"));
break;
case Constants.MESSAGE_READ:
mBlinkData.setBackgroundColor(Color.parseColor("#0091FA"));
String readMessage = (String)msg.obj;
if(isIris) {
readIris(readMessage);
} else {
readNormal(readMessage);
}
break;
case Constants.MESSAGE_DEVICE_NAME:
// save the connected device's name
mConnectedDeviceName = msg.getData().getString(Constants.DEVICE_NAME);
if (null != activity) {
Toast.makeText(activity, "Connected to "
+ mConnectedDeviceName, Toast.LENGTH_SHORT).show();
}
break;
case Constants.MESSAGE_TOAST:
if (null != activity) {
Toast.makeText(activity, msg.getData().getString(Constants.TOAST),
Toast.LENGTH_SHORT).show();
}
break;
}
}
};
public void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case REQUEST_CONNECT_DEVICE_SECURE:
// When DeviceListActivity returns with a device to connect
if (resultCode == Activity.RESULT_OK) {
connectDevice(data, true);
}
break;
case REQUEST_CONNECT_DEVICE_INSECURE:
// When DeviceListActivity returns with a device to connect
if (resultCode == Activity.RESULT_OK) {
connectDevice(data, false);
}
break;
case REQUEST_ENABLE_BT:
// When the request to enable Bluetooth returns
if (resultCode == Activity.RESULT_OK) {
// Bluetooth is now enabled, so set up a session
setupScanner();
} else {
// User did not enable Bluetooth or an error occurred
Log.d(TAG, "BT not enabled");
Toast.makeText(getActivity(), R.string.bt_not_enabled_leaving,
Toast.LENGTH_SHORT).show();
getActivity().finish();
}
}
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.secure_connect_scan: {
// Launch the DeviceListActivity to see devices and do scan
Intent serverIntent = new Intent(getActivity(), DeviceListActivity.class);
startActivityForResult(serverIntent, REQUEST_CONNECT_DEVICE_SECURE);
return true;
}
/*case R.id.insecure_connect_scan: {
// Launch the DeviceListActivity to see devices and do scan
Intent serverIntent = new Intent(getActivity(), DeviceListActivity.class);
startActivityForResult(serverIntent, REQUEST_CONNECT_DEVICE_INSECURE);
return true;
}*/
case R.id.settings_button: {
Intent serverIntent = new Intent(getActivity(), SettingsActivity.class);
startActivityForResult(serverIntent, REQUEST_SHOW_SETTINGS);
return true;
}
}
return false;
}
/**
*
* #param data String
* #param append boolean
*/
private void writeToFile(String data, String uploadData, boolean append) {
String root = Environment
.getExternalStorageDirectory().toString();
File myDir = new File(root);
String fname = "starDust.txt";
String fname2 = "starDust.csv";
File file = new File (myDir, fname);
File file2 = new File (myDir, fname2);
//if (file.exists ()) file.delete ();
try {
FileOutputStream out = new FileOutputStream(file, append);
out.write(data.getBytes(), 0, data.getBytes().length);
out.flush();
out.close();
FileOutputStream out2 = new FileOutputStream(file2, append);
out2.write(uploadData.getBytes(), 0, uploadData.getBytes().length);
out2.flush();
out2.close();
if(mConnectedDeviceName != null) {
Log.d(TAG, "Connecting " + SP.getString("server_ip", "") + SP.getString("server_username", "") + SP.getString("server_password", ""));
new FTPUploadTask().execute(mConnectedDeviceName, SP.getString("server_ip", ""), SP.getString("server_username", "") , SP.getString("server_password", ""));
}
} catch (Exception e) {
e.printStackTrace();
}
}
/**
*
*/
private String readFromFile() {
String root = Environment
.getExternalStorageDirectory().toString();
File myDir = new File(root);
String fname = "starDust.txt";
File file = new File (myDir, fname);
StringBuilder text = new StringBuilder();
if (file.exists ()) {
try {
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
while ((line = br.readLine()) != null) {
text.insert(0, line + System.getProperty("line.separator"));
}
br.close();
} catch (Exception e) {
}
}
return text.toString();
}
private void readNormal(String readMessage) {
String parsedData[];
if(readMessage.contains(";")) {
if(readMessage.equals(";")) {
parsedData = bufferedMessage.trim().split(",");
bufferedMessage = "";
} else {
String partialMessage[] = readMessage.split(";");
bufferedMessage += partialMessage[0];
parsedData = bufferedMessage.trim().split(",");
if (partialMessage.length > 1) {
bufferedMessage = partialMessage[1];
} else {
bufferedMessage = "";
}
}
} else {
bufferedMessage += readMessage.trim();
return;
}
if(parsedData.length == RESPONSE_SIZE && parsedData[0].equals("U")) {
if(parsedData[1].matches("[-+]?\\d*\\.?\\d+")) {
if(Integer.parseInt(parsedData[1]) > maxU1 || hitTrigger) {
maxU1 = Integer.parseInt(parsedData[1]);
}
}
if(parsedData[2].matches("[-+]?\\d*\\.?\\d+")) {
if(Integer.parseInt(parsedData[2]) > maxU2 || hitTrigger) {
maxU2 = Integer.parseInt(parsedData[2]);
}
}
if(parsedData[3].matches("[-+]?\\d*\\.?\\d+")) {
if(Integer.parseInt(parsedData[3]) > maxU3 || hitTrigger) {
maxU3 = Integer.parseInt(parsedData[3]);
}
}
double u1val = Double.parseDouble(parsedData[1]);
double u2val = Double.parseDouble(parsedData[2]);
double u1u2div = 0;
if(u2val > 0) {
u1u2div = ((u1val / u2val) * KFactor);
}
if(parsedData[4].matches("[-+]?\\d*\\.?\\d+")) {
mBatteryPerc.setText(parsedData[4] + "%");
mBattery.setProgress(Integer.parseInt(parsedData[4]));
}
}
taggantType = 0;
if(maxU1 > Integer.parseInt(SP.getString("maxThreshold", Integer.toString(MAX_TRIGGER)))) {
taggantType += 4;
} else {
taggantType += 0;
}
if(maxU2 > Integer.parseInt(SP.getString("maxThreshold", Integer.toString(MAX_TRIGGER)))) {
taggantType += 2;
} else {
taggantType += 0;
}
if(maxU3 > Integer.parseInt(SP.getString("maxThreshold", Integer.toString(MAX_TRIGGER)))) {
taggantType += 1;
} else {
taggantType += 0;
}
Log.d(TAG, Integer.toString(taggantType));
Log.d(TAG, Boolean.toString(hitTrigger));
Log.d(TAG, bufferedMessage);
// Check if hit threshold, if so hitTrigger is enabled.
if(taggantType > 0) {
savedTaggantType = taggantType;
hitTrigger = true;
mPresence.setText("VALID TAGGANT DETECTED");
mPresence.setBackgroundColor(Color.parseColor("#11D901"));
} else if(taggantType == 0 && hitTrigger) {
hitTrigger = false;
mPresence.setText("NO TAGGANT DETECTED");
mPresence.setBackgroundColor(Color.parseColor("#ffc4ab"));
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String currentDateandTime = sdf.format(new Date());
String saveData =
"Device: " + mConnectedDeviceName +
System.getProperty("line.separator") +
"Timestamp: " + currentDateandTime +
System.getProperty("line.separator") +
"Location: " + latitude + " (lat) / " + longitude + " (lon)" +
System.getProperty("line.separator") +
"Taggan Type: N" + Integer.toString(savedTaggantType) +
System.getProperty("line.separator") +
"Phone id: " + telephonyManager.getDeviceId() +
System.getProperty("line.separator") +
"=========================" +
System.getProperty("line.separator");
String csvData = mConnectedDeviceName + "," +
currentDateandTime + "," +
"\"http://maps.google.com/?q=" + latitude + "," + longitude + "\"," +
"N" + Integer.toString(savedTaggantType) + "," +
"\"" + telephonyManager.getDeviceId() + "\"" +
System.getProperty("line.separator");
mReadingLog.setText(saveData + mReadingLog.getText());
mShowData.setText(saveData); //kg 8/25/17
maxU1 = 0;
maxU2 = 0;
maxU3 = 0;
savedTaggantType = 0;
if(SP.getBoolean("writeToFile", true)) {
writeToFile(saveData, csvData, true);
}
}
}
/**
* #param readMessage String
*/
public void readIris(String readMessage) {
if(!readoutStarted) {
return;
}
String parsedData[];
if(readMessage.contains(";")) {
readoutStarted = false;
if(readMessage.equals(";")) {
parsedData = bufferedMessage.replaceAll("\n", "").replaceAll(" +", " ").trim().split("\\*");
bufferedMessage = "";
} else {
String partialMessage[] = readMessage.replaceAll("\n", "").replaceAll(" +", " ").trim().split(";");
bufferedMessage += partialMessage[0].trim();
parsedData = bufferedMessage.replaceAll("\n", "").replaceAll(" +", " ").trim().split("\\*");
bufferedMessage = "";
}
} else {
bufferedMessage += readMessage.trim().replaceAll("\n", "").replaceAll(" +", " ");
return;
}
Log.d(TAG, Arrays.toString(parsedData));
boolean passed = false;
int v1 = 0;
int v2 = 0;
if(parsedData[3].equals("S")) {
passed = true;
String values[] = parsedData[7].split("\\s+");
v1 = Integer.parseInt(values[0].replaceAll("[\\D]", ""));
v2 = Integer.parseInt(values[values.length-1]);
} else {
Log.d(TAG, Arrays.toString(parsedData));
String values[] = parsedData[5].split("\\s+");
v1 = Integer.parseInt(values[0].replaceAll("[\\D]", ""));
v2 = Integer.parseInt(values[values.length-1]);
}
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String currentDateandTime = sdf.format(new Date());
String saveData =
"Device: " + mConnectedDeviceName +
System.getProperty("line.separator") +
"Timestamp: " + currentDateandTime +
System.getProperty("line.separator") +
"Location: " + latitude + " (lat) / " + longitude + " (lon)" +
System.getProperty("line.separator") +
"Phone id: " + telephonyManager.getDeviceId() +
System.getProperty("line.separator") +
"Valid:" + (passed ? "YES" : "NO") +
System.getProperty("line.separator") +
"Values: " + "T" + v1 + " / " + v2 +
System.getProperty("line.separator") +
"=========================" +
System.getProperty("line.separator");
String csvData = mConnectedDeviceName + "," +
currentDateandTime + "," +
"\"http://maps.google.com/?q=" + latitude + "," + longitude + "\"," +
"Valid: " + (passed ? "YES" : "NO") + " - " + "T" + v1 + " / " + v2 + Integer.toString(savedTaggantType) + "," +
"\"" + telephonyManager.getDeviceId() + "\"" +
System.getProperty("line.separator");
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(this, R.layout.fragment_bluetooth_scanner, R.id.textView, saveData);
mListView.setAdapter(arrayAdapter);
mReadingLog.setText(saveData + mReadingLog.getText());
mShowData.setText(saveData); //kg 8/25/17
if(SP.getBoolean("writeToFile", true)) {
writeToFile(saveData, csvData, true);
}
}
}
I have three xml files associated with this problem, but because of space I'll only include the one that contains the ListView and remove the other buttons.
view_list.xml contains the ListView:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:id="#+id/viewList"
android:layout_width="match_parent"
android:layout_height="match_parent">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="fill_parent"
android:layout_gravity="center_horizontal"
android:paddingLeft="4dp"
android:paddingRight="4dp"
android:visibility="visible">
<LinearLayout
android:layout_width="match_parent"
android:id="#+id/listview_holder"
android:layout_alignParentTop="true"
android:layout_alignTop="#id/button_holder"
android:layout_weight=".1"
android:layout_height="wrap_content">
<ListView
android:id="#+id/scanLogView"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:maxLines="4096"
android:scrollbars="vertical"
android:text="#string/app_name"
android:textAppearance="?android:attr/textAppearanceSmall"/>
</LinearLayout>
</RelativeLayout>
</LinearLayout>
The error was with ArrayAdapter. I changed the decloration from
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(this,
R.layout.fragment_bluetooth_scanner, R.id.textView, saveData);
to
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(),
android.R.layout.simple_list_item_1, android.R.id.text1, listItems);
It now builds the project and displays the listview.
how can i create progress bar UI that appear during PDF creation and that stop when PDF creation is finished?
TwoFragment.java
public class TwoFragment extends Fragment{
private View v;
Intent chooser=null;
String myInt="";
public TwoFragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootView = inflater.inflate(R.layout.fragment_two, container, false);
Button mButton = (Button) rootView.findViewById(R.id.newbutton);
mButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
//sendemail();
createPDF();
viewPDF();
}
});
TextView titolo3 = (TextView)rootView.findViewById(R.id.result);
TextView titolo2 = (TextView)rootView.findViewById(R.id.result2);
TextView titolo4 = (TextView)rootView.findViewById(R.id.resultpizze);
//TextView titolo = (TextView)rootView.findViewById(R.id.quantità3);
/* Bundle bundle2=getArguments();
if(bundle2 != null){
String string = bundle2.getString("scelta2", null);
titolo3.setText(string);
}*/
Bundle bundle2=getArguments();
if(bundle2 != null){
myInt = bundle2.getString("scelta2", null);
titolo3.setText(myInt);
}
Bundle bundle3=getArguments();
if(bundle3 != null){
// String myInt3 = bundle3.getString("totalebirre", null);
// cazzo2=Integer.parseInt(myInt3);
int cazzo2=bundle3.getInt("totalebirre");
titolo2.setText(String.valueOf(cazzo2));
}
Bundle bundle=getArguments();
if(bundle != null){
// String myInt2 = bundle2.getString("totalepizze", null);
// cazzo=Integer.parseInt(myInt2);
//titolo2.setText(myInt2);
String string=bundle.getString("scelta3", null);
titolo4.setText(string);
}
return rootView;
}
/* public void sendemail(){
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setData(Uri.parse("mailto:"));
String[] to={"marco_marcoletto#hotmail.it"};
intent.putExtra(Intent.EXTRA_EMAIL,to);
intent.putExtra(Intent.EXTRA_SUBJECT, "ciao");
intent.putExtra(Intent.EXTRA_TEXT, "zao");
intent.setType("message/rfc822");
chooser=intent.createChooser(intent,"manda email");
startActivity(chooser);
}*/
public void createPDF() {
Document doc = new Document();
try {
String path = Environment.getExternalStorageDirectory()
.getAbsolutePath() + "/droidText";
File dir = new File(path);
if (!dir.exists())
dir.mkdirs();
Log.d("PDFCreator", "PDF Path: " + path);
File file = new File(dir, "sample.pdf");
FileOutputStream fOut = new FileOutputStream(file);
PdfWriter.getInstance(doc, fOut);
// open the document
doc.open();
ByteArrayOutputStream stream = new ByteArrayOutputStream();
Bitmap bitmap = BitmapFactory.decodeResource(getContext()
.getResources(), R.drawable.androtuto);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream);
Image myImg = Image.getInstance(stream.toByteArray());
myImg.setAlignment(Image.MIDDLE);
// add image to document
doc.add(myImg);
Paragraph p1 = new Paragraph(myInt);
Log.d("ciao",myInt);
Font paraFont = new Font(Font.COURIER);
p1.setAlignment(Paragraph.ALIGN_CENTER);
p1.setFont(paraFont);
// add paragraph to document
doc.add(p1);
Paragraph p2 = new Paragraph("Ciao");
Font paraFont2 = new Font(Font.COURIER, 14.0f, Color.GREEN);
p2.setAlignment(Paragraph.ALIGN_CENTER);
p2.setFont(paraFont2);
doc.add(p2);
stream = new ByteArrayOutputStream();
bitmap = BitmapFactory.decodeResource(getContext()
.getResources(), R.drawable.android);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream);
myImg = Image.getInstance(stream.toByteArray());
myImg.setAlignment(Image.MIDDLE);
// add image to document
doc.add(myImg);
// set footer
Phrase footerText = new Phrase("Pied de page ");
HeaderFooter pdfFooter = new HeaderFooter(footerText, false);
doc.setFooter(pdfFooter);
} catch (DocumentException de) {
Log.e("PDFCreator", "DocumentException:" + de);
} catch (IOException e) {
Log.e("PDFCreator", "ioException:" + e);
} finally {
doc.close();
}
}
public void viewPDF(){
String path = "/sdcard/droidText/sample.pdf";
File targetFile = new File(path);
Uri targetUri = Uri.fromFile(targetFile);
Intent intent;
intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(targetUri, "application/pdf");
startActivity(intent);
}
}
ThreeFragment.java
FRAGMENT FROM WHERE I PASS VARIABLES:
public class ThreeFragment extends Fragment implements
android.widget.CompoundButton.OnCheckedChangeListener {
ListView lv2;
ArrayList<Planet> planetList;
ListView lv;
ArrayList<Birra> birraList;
BirraAdapter biAdapter;
PlanetAdapter plAdapter;
Planet p;
String myInt="";
PlanetAdapter.PlanetHolder holder;
public ThreeFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
final ViewGroup rootView = (ViewGroup) inflater.inflate(R.layout.fragment_three, container, false);
Button mButton = (Button) rootView.findViewById(R.id.button2);
mButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
MyListFragment mlf=new MyListFragment();
mlf.showResult(v);
// MyListFragment.showResult(v);
showResult2(v);
}
});
//return inflater.inflate(R.layout.fragment_list2, container, false);
return rootView;
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
lv2 = (ListView) getView().findViewById(R.id.listview2);
displayBirraList();
}
private void displayBirraList() {
birraList = new ArrayList<Birra>();
birraList.add(new Birra("Paulaner", 6, "€"));
birraList.add(new Birra("Forst", 7, "€"));
birraList.add(new Birra("Peroni", 5, "€"));
birraList.add(new Birra("Corona", 5, "€"));
birraList.add(new Birra("Nastro Azzurro", 4, "€"));
biAdapter = new BirraAdapter(birraList, getContext()) {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
int pos = lv2.getPositionForView(buttonView);
if (pos != ListView.INVALID_POSITION) {
Birra b = birraList.get(pos);
b.setSelected(isChecked);
/*Toast.makeText(
getActivity(),
"Clicked on Pizza: " + p.getName() + ". State: is "
+ isChecked, Toast.LENGTH_SHORT).show();*/
}
}
};
lv2.setAdapter(biAdapter);
}
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
/*int pos = lv.getPositionForView(buttonView);
if (pos != ListView.INVALID_POSITION) {
Planet p = planetList.get(pos);
p.setSelected(isChecked);
*//**//**//**//*Toast.makeText(
getActivity(),
"Clicked on Planet: " + p.getName() + ". State: is "
+ isChecked, Toast.LENGTH_SHORT).show();*//**//**//**//*
}
*/
}
public void showResult2(View v) {
String result = "Selected Product are :";
int totalAmount = 0;
// String a = "";
for (Birra b : biAdapter.getBox()) {
if (b.selected) {
result += "\n" + b.name + " " + b.distance + "€" + "q.tà :" + b.getQuantità();
int quantitaInt = Integer.parseInt(b.getQuantità());
totalAmount += b.distance * quantitaInt;
// a=String.valueOf(totalAmount);
}
}
/* for (Planet p : plAdapter.getBox()) {
if (p.isSelected()) {
result += "\n" + p.getName() + " " + p.getDistance() + "€" + "q.tà :" + p.getQuantità();
int quantitaInt = Integer.parseInt(p.getQuantità());
//totalAmount2+=p.distance * quantitaInt;
//z=String.valueOf(totalAmount2);
}
}*/
Toast.makeText(getActivity(), result + "\n" +myInt + "\n" + "Total Amount:=" + totalAmount + "€", Toast.LENGTH_LONG).show();
Bundle bun2 = new Bundle();
bun2.putString("scelta2", result);
TwoFragment fgsearch2 = new TwoFragment();
fgsearch2.setArguments(bun2);
android.support.v4.app.FragmentTransaction transaction2 = getActivity().getSupportFragmentManager().beginTransaction();
transaction2.replace(R.id.content_main, fgsearch2);
transaction2.commit();
Bundle bun = new Bundle();
// bun.putString("totalebirre", a);
bun.putInt("totalebirre", totalAmount);
TwoFragment fgsearch = new TwoFragment();
fgsearch.setArguments(bun);
android.support.v4.app.FragmentTransaction transaction = getActivity().getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.content_main2, fgsearch);
transaction.commit();
}
}
Step 1 - Declare a global variable - private ProgressBar pdfProgress;
Step 2 - Create a progress bar widget in your respective layour.xml(fragment_two) and give it an id.
Step 3 - In onCreate() method of TwoFragment, write this code just after defining the rootView.
pdfProgress = (ProgressBar)rootView.findViewById(R.id."your progress bar id");
Step 4 - just above createPDF(); write this -
pdfProgress.setVisibility(View.VISIBLE);
Step 5 - just below createPDF(); write this -
pdfProgress.setVisibility(View.GONE);
**
Updated Answer
**
Try this code in your TwoFragment - onClick()-
Button mButton = (Button) rootView.findViewById(R.id.newbutton);
ProgressBar pdfProgress = (ProgressBar) rootView.findViewById(R.id.progressBar);
mButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
//sendemail();
pdfProgress.setVisibility(View.VISIBLE);
createPDF();
pdfProgress.setVisibility(View.GONE);
viewPDF();
}
});
The fragment_two.xml (your fragment layout xml) must contain a progress bar that looks like this - (you can add drawables too, might wanna look at a tutorial for that)
<ProgressBar
style="?android:attr/progressBarStyleLarge"
android:layout_width="50dp"
android:layout_height="50dp"
android:id="#+id/progressBar"/>
I want to send email with an attachment from my app (attachment is csv file), but Gmail says, that attachment couldn't be added. Is mistake in converting text into csv or in Adding attachment to gmail?
My code:
public class EmailInput extends DialogFragment {
View mainView;
TextView email;
Button submitSend;
ArrayList<String> resultsEmail;
ArrayList<String> valuesMail;
TextView soucetVysledkuMail;
String subject = "Kubírovací kalkulačka";
MainActivity MA;
String attachmentFile;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
MA = (MainActivity) getActivity();
mainView = inflater.inflate(R.layout.fragment_email_input, container, false);
email = (TextView) mainView.findViewById(R.id.email);
submitSend = (Button) mainView.findViewById(R.id.submitSend);
resultsEmail = ((MainActivity) getActivity()).getVysledky();
valuesMail = ((MainActivity) getActivity()).getValues();
soucetVysledkuMail = ((MainActivity) getActivity()).getSoucetVysledku();
getDialog().setTitle("Odeslat výsledky");
submitSend.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String FILENAME = "email-attachment.csv";
String string = "";
try {
FileOutputStream fOut = ((MainActivity) getActivity()).getContext().openFileOutput(FILENAME, Context.MODE_PRIVATE);
for (int i = 0; i < resultsEmail.size(); i++) {
string += resultsEmail.get(i) + "," + valuesMail.get(i);
}
string += "Součet výsledků:," + MA.getsoucetVsechVysledkuMA();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
attachmentFile = "mail-attachment.csv";
Uri URI = Uri.parse("file://" + attachmentFile);
String content = results();
Intent emailIntent = new Intent(Intent.ACTION_SEND);
emailIntent.putExtra(Intent.EXTRA_EMAIL, new String[]{email.getText().toString()});
emailIntent.putExtra(Intent.EXTRA_SUBJECT, subject);
emailIntent.putExtra(Intent.EXTRA_TEXT, content);
emailIntent.putExtra(Intent.EXTRA_STREAM, URI);
emailIntent.setType("text/plain");
startActivity(Intent.createChooser(emailIntent, "Vyberte aplikaci:"));
}
});
return mainView;
}
public String results() {
String content = "";
for (int i = 0; i < resultsEmail.size(); i++) {
int cislovka = i+1;
content += cislovka + ". " + resultsEmail.get(i) + " (" + valuesMail.get(i) + ") \n";
}
content += "Součet výsledků: " + MA.getsoucetVsechVysledkuMA();
return content;
}
}
There is a problem with permissions. If you want to attach file to your mail, it has to be saved in a public folder like Documents.