Cannot Export sharedpreferences to CSV Android - java

Okay So this is an activity class where I am trying to export my sharedPreferences that are saved to a CSV file. This does not work. What am I doing wrong? How do I correctly write the sharedPreferences items to a CSV file?
import java.io.FileWriter;
import java.io.IOException;
import java.util.Iterator;
import java.util.Map;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Environment;
import android.preference.PreferenceManager;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;
public class Admin extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_admin);
Button btViewContacts = (Button)findViewById(R.id.btnViewContacts);
Button btDeleteContacts = (Button)findViewById(R.id.btnDeleteContacts);
Button btExportCSV = (Button)findViewById(R.id.btnExportCSV);
final Context context = this;
final SharedPreferences sharedPref = PreferenceManager
.getDefaultSharedPreferences(this);
btViewContacts.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
startActivity(new Intent(Admin.this, Contacts.class));
}
});
btDeleteContacts.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
//DISPLAY ALERT DIALOG
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(context); //show an alertDialog when user selects delete radio button and clicks process, prompt to confirm
//set title
alertDialogBuilder.setTitle("DELETE ALL CONTACTS?");
//set dialog message
alertDialogBuilder
.setMessage("Are you sure you want to delete ALL acquired contact info?")
.setCancelable(true)
//no button
.setNegativeButton("No", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) { //if user selects no, close dialog
// TODO Auto-generated method stub
//if clicked this will close the dialog and do nothing.
dialog.cancel();
}
})
//yes button
.setPositiveButton("Yes", new DialogInterface.OnClickListener() { //if user selects yes, clear the shared preferences and display confirmation message when deleted.
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
//if this button is clicked it will erase the values in memory
SharedPreferences.Editor editor = sharedPref.edit();
editor.clear();
editor.commit();
//displays toast message confirming deletion of race info
Toast.makeText(Admin.this, "Contact Info Deleted.", Toast.LENGTH_SHORT).show();
}
});
// create alert dialog
AlertDialog alertDialog = alertDialogBuilder.create();
// show it
alertDialog.show();
}
});
Map<String, ?> allEntries = sharedPref.getAll();
for (Map.Entry<String, ?> entry : allEntries.entrySet()) {
Log.d("TAG", entry.getKey() + ": " + entry.getValue().toString());
}
btExportCSV.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
generateCsvFile(Environment.getExternalStorageDirectory().getPath());
}
});
}
private void generateCsvFile(String sFileName)
{
final SharedPreferences sharedPref = PreferenceManager
.getDefaultSharedPreferences(this);
String delimiter = ",";
try
{
FileWriter writer = new FileWriter(sFileName);
writer.append("First Name");
writer.append(',');
writer.append("Last Name");
writer.append(',');
writer.append("Email");
writer.append(',');
writer.append("Phone");
writer.append(',');
writer.append("Address");
writer.append(',');
writer.append("City");
writer.append(',');
writer.append("State");
writer.append(',');
writer.append("Zip");
writer.append('\n');
Map<String, ?> allEntries = sharedPref.getAll();
for (Map.Entry<String, ?> entry : allEntries.entrySet()) {
Map<String,?> all = sharedPref.getAll();
Iterator it = all.entrySet().iterator();
Map.Entry pairs = (Map.Entry)it.next();
if (pairs.getKey().toString().startsWith("contactid_")) {
String strContact = sharedPref.getString((String)pairs.getKey(), "");
String[] data = TextUtils.split(strContact, delimiter);
writer.write(strContact);
writer.append('\n');
}
Toast.makeText(Admin.this, "ContAcq's Exported to .CSV.", Toast.LENGTH_SHORT).show();
//generate whatever data you want
writer.flush();
writer.close();
}
}
catch(IOException e)
{
e.printStackTrace();
}
}
}

Related

how to make barcode work with device keys?

I am trying to code an inventory app that can work on UROVO DT40 device. I don't know how to code the barcode scanner so that it will work on keystroke and send the result to edittext. I also want to save the data from the adapter and be able to read from a PC. I am still a rookie so I don't know if am doing it the right way. I need some help please. Thanks!!
here's some of the code
import androidx.appcompat.app.AppCompatActivity;
import android.content.Context;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;
import com.google.android.material.textfield.TextInputEditText;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import java.util.Objects;
public class MainActivity extends AppCompatActivity {ArrayList<String>
listitems = new ArrayList<>();
ArrayAdapter<String> adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextInputEditText input = findViewById(R.id.textInputEditText);
TextInputEditText input1 = findViewById(R.id.textInputEditText1);
ListView listview = findViewById(R.id.listView);
Button saveBtn = findViewById(R.id.saveBtn);
Button btn_annuler = findViewById(R.id.btn_annuler);
Button OK = findViewById(R.id.btn3);
Button btn2 = findViewById(R.id.btn2) ;
adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1,listitems);
listview.setAdapter(adapter);
input.setShowSoftInputOnFocus(false);
input1.setShowSoftInputOnFocus(false);
OK.setOnClickListener(v -> {
listitems.add(Objects.requireNonNull(input.getText()).toString() + ';' + Objects.requireNonNull(input1.getText()).toString());
adapter.notifyDataSetChanged();
input.setText("");
input1.setText("");
});
btn_annuler.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
input.setText("");
input1.setText("");
}
});
btn2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
adapter.clear();
}
});
saveBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(!adapter.toString().equals(""))
{
String data = adapter.toString();
writeToFile(data);
Toast.makeText(MainActivity.this, "Vidage éffectué!", Toast.LENGTH_LONG).show();
}
}
});
}
private void writeToFile(String data) {
try {
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(openFileOutput("ficGloba.txt", Context.MODE_PRIVATE));
outputStreamWriter.write(data);
outputStreamWriter.close();
}
catch (IOException e) {
e.printStackTrace();
}
}
}
There are code samples on the Urovo github page for the Android SDK, specifically also one for the Scanner
Steps 1 to 4 from from the ScannerManagerDemo.java javadoc describe how you have to setup the Scanner:
1.Obtain an instance of BarCodeReader with ScanManager scan = new ScanManager().
2.Call openScanner to power on the barcode reader.
3.After that, the default output mode is TextBox Mode that send barcode data to the focused text box. User can check the output mode
using getOutputMode and set the output mode using switchOutputMode.
4.Then, the default trigger mode is manually trigger signal. User can check the trigger mode using getTriggerMode and set the trigger mode
using setTriggerMode.
for full completeness, the extracted javacode:
private void initScan() {
mScanManager = new ScanManager();
boolean powerOn = mScanManager.getScannerState();
if (!powerOn) {
powerOn = mScanManager.openScanner();
if (!powerOn) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("Scanner cannot be turned on!");
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
AlertDialog mAlertDialog = builder.create();
mAlertDialog.show();
}
}
initBarcodeParameters();
}
That should give you enough to get cracking. Godspeed.

Android Java app fails to send selected file/data via Bluetooth

My current android app can turn on Bluetooth, make itself discoverable, list paired devices, and select a file from the device ( ie an image). However when I attempted to hit "send" the app seems to crash with an error. Not sure if it's refusing to send, or if it's not actually obtaining the file (yesterday I had a problem where it refused to send the selected, saying for me to select a file repeatedly. I will post the crash results and my mainActivity code. If anyone suggestions or ideas, please let me know.
Error: Debugging device
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.bluetooth_demoproject, PID: 17593
java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=1, result=300, data=null} to activity {com.example.bluetooth_demoproject/com.example.bluetooth_demoproject.MainActivity}: android.os.FileUriExposedException: file:///storage/emulated/0/Pictures/Screenshots/Screenshot_20161013-215137.png exposed beyond app through ClipData.Item.getUri()
at android.app.ActivityThread.deliverResults(ActivityThread.java:4107)
at android.app.ActivityThread.handleSendResult(ActivityThread.java:4150)
at android.app.ActivityThread.-wrap20(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1517)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6120)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)
Caused by: android.os.FileUriExposedException: file:///storage/emulated/0/Pictures/Screenshots/Screenshot_20161013-215137.png exposed beyond app through ClipData.Item.getUri()
at android.os.StrictMode.onFileUriExposed(StrictMode.java:1799)
at android.net.Uri.checkFileUriExposed(Uri.java:2346)
at android.content.ClipData.prepareToLeaveProcess(ClipData.java:832)
at android.content.Intent.prepareToLeaveProcess(Intent.java:8909)
at android.content.Intent.prepareToLeaveProcess(Intent.java:8894)
at android.app.Instrumentation.execStartActivity(Instrumentation.java:1517)
at android.app.Activity.startActivityForResult(Activity.java:4224)
at android.app.Activity.startActivityForResult(Activity.java:4183)
at android.app.Activity.startActivity(Activity.java:4507)
at android.app.Activity.startActivity(Activity.java:4475)
at com.example.bluetooth_demoproject.MainActivity.onActivityResult(MainActivity.java:350)
at android.app.Activity.dispatchActivityResult(Activity.java:6917)
at android.app.ActivityThread.deliverResults(ActivityThread.java:4103)
at android.app.ActivityThread.handleSendResult(ActivityThread.java:4150) 
at android.app.ActivityThread.-wrap20(ActivityThread.java) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1517) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:154) 
at android.app.ActivityThread.main(ActivityThread.java:6120) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755) 
Disconnected from the target VM, address: 'localhost:8601', transport: 'socket'
Here is my MainActivity
package com.example.bluetooth_demoproject;
import android.app.Activity;
import android.app.Dialog;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.net.Uri;
import android.os.Environment;
import android.view.Menu;
import android.view.MenuItem;
import android.bluetooth.BluetoothA2dp;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import java.util.Set;
import java.io.File;
import java.util.List;
import java.util.ArrayList;
public class MainActivity extends Activity {
// Creating objects -----------------------------
private static final int REQUEST_ENABLE_BT = 0;
private static final int REQUEST_BLU = 1;
// private static final int REQUEST_DISCOVER_BT_ = 1;
private static int CUSTOM_DIALOG_ID = 0;
ListView dialog_ListView;
TextView mBluetoothStatus, mPairedDevicesList, mTextFolder;
ImageView mBluetoothIcon;
Button mOnButton, mDiscoverableButton, mPairedDevices, mbuttonOpenDialog, msendBluetooth, mbuttonUp;
File root, fileroot, curFolder;
EditText dataPath;
private static final int DISCOVER_DURATION = 300;
private List<String> fileList = new ArrayList<String>();
// -------------------------------------------------------
BluetoothAdapter mBlueAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
dataPath =(EditText)findViewById(R.id.FilePath);
mTextFolder = findViewById(R.id.folder);
mBluetoothStatus = findViewById(R.id.BluetoothStatus);
mBluetoothIcon = findViewById(R.id.bluetoothIcon);
mOnButton = findViewById(R.id.onButton);
// mOffButton = findViewById(R.id.offButton);
mDiscoverableButton = findViewById(R.id.discoverableButton);
mPairedDevices = findViewById(R.id.pairedDevices);
mPairedDevicesList = findViewById(R.id.pairedDeviceList);
mbuttonOpenDialog = findViewById(R.id.opendailog);
msendBluetooth = findViewById(R.id.sendBluetooth);
mbuttonUp = findViewById(R.id.up);
mbuttonOpenDialog.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dataPath.setText("");
showDialog(CUSTOM_DIALOG_ID);
}
});
root = new
File(Environment.getExternalStorageDirectory().getAbsolutePath());
curFolder = root;
msendBluetooth.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
sendViaBluetooth();
}
});
//adapter
mBlueAdapter = BluetoothAdapter.getDefaultAdapter();
if(mBlueAdapter == null){
mBluetoothStatus.setText("Bluetooth is not available");
return;
}
else {
mBluetoothStatus.setText("Bluetooth is available");
}
//if Bluetooth isnt enabled, enable it
if (!mBlueAdapter.isEnabled()) {
Intent enableBtIntent = new
Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
}
//set image according to bluetooth Status
if (mBlueAdapter.isEnabled()) {
mBluetoothIcon.setImageResource(R.drawable.action_on);
}
else {
mBluetoothIcon.setImageResource(R.drawable.action_off);
}
//on button Click
mOnButton.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
if (!mBlueAdapter.isEnabled()) {
showToast("Turning Bluetooth on...");
// intent to on bluetooth
Intent intent = new
Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(intent, REQUEST_ENABLE_BT);
}
else {
showToast("Bluetooth is already on");
}
}
});
//discover Bluetooth button
mDiscoverableButton.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
if (!mBlueAdapter.isDiscovering()) {
showToast("Making device discoverable");
Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
startActivityForResult(intent, REQUEST_BLU);
}
}
});
// off button click
// mOffButton.setOnClickListener(new View.OnClickListener() {
// #Override
// public void onClick(View v) {
// if (mBlueAdapter.isEnabled()) {
// showToast("Turning Bluetooth off...");
// // intent to turn off bluetooth
// mBluetoothIcon.setImageResource(R.drawable.action_off);
// }
// else{
// showToast("Bluetooth is already off");
// }
//
// }
//});
//get paired device button click
mPairedDevices.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mBlueAdapter.isEnabled()) {
mPairedDevices.setText("Paired Devices");
Set<BluetoothDevice> devices = mBlueAdapter.getBondedDevices();
for (BluetoothDevice device : devices){
mPairedDevices.append("\nDevice: " + device.getName() + "," + device );
}
}
else {
//bluetooth is off and cant get paired devices
showToast("Turn on bluetooth to get paired devices");
}
}
});
}
// #Override
// protected void onPrepareDialog(int id, Dialog dialog) {
// super.onPrepareDialog(id, dialog);
// switch (id) {
// case CUSTOM_DIALOG_ID:
// ListDir(curFolder);
// break;
// }
// }
#Override
protected Dialog onCreateDialog(int id) {
Dialog dialog = null;
if (id == CUSTOM_DIALOG_ID) {
dialog = new Dialog(MainActivity.this);
dialog.setContentView(R.layout.dailoglayout);
dialog.setTitle("Select Files");
dialog.setCancelable(true);
dialog.setCanceledOnTouchOutside(true);
mTextFolder = (TextView) dialog.findViewById(R.id.folder);
mbuttonUp = (Button) dialog.findViewById(R.id.up);
mbuttonUp.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ListDir(curFolder.getParentFile());
}
});
dialog_ListView = (ListView) dialog.findViewById(R.id.dialoglist);
dialog_ListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
File selected = new File(fileList.get(position));
if (selected.isDirectory()) {
ListDir(selected);
}
else if (selected.isFile()) {
getSelectedFile(selected);
}
else {
dismissDialog(CUSTOM_DIALOG_ID);
}
}
});
}
return dialog;
}
#Override
protected void onPrepareDialog(int id, Dialog dialog) {
super.onPrepareDialog(id, dialog);
if (id == CUSTOM_DIALOG_ID) {
ListDir(curFolder);
}
}
public void getSelectedFile(File f) {
dataPath.setText(f.getAbsolutePath());
fileList.clear();
dismissDialog(CUSTOM_DIALOG_ID);
}
public void ListDir(File f) {
if (f.equals(root)) {
mbuttonUp.setEnabled(false);
}
else {
mbuttonUp.setEnabled(true);
}
curFolder = f;
mTextFolder.setText(f.getAbsolutePath());
dataPath.setText(f.getAbsolutePath());
File[] files = f.listFiles();
fileList.clear();
for (File file : files) {
fileList.add(file.getPath());
}
ArrayAdapter<String> directoryList = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, fileList);
dialog_ListView.setAdapter(directoryList);
}
// exits to app --------------------------------
public void exit(View V) {
mBlueAdapter.disable();
Toast.makeText(this, "*** Now bluetooth is off...", Toast.LENGTH_LONG).show();
finish();
}
// send file via bluetooth ------------------------
public void sendViaBluetooth() {
if(!dataPath.equals(null)) {
if(mBlueAdapter == null) {
Toast.makeText(this, "Device doesnt support bluetooth", Toast.LENGTH_LONG).show();
}
else {
enableBluetooth();
}
}
else {
Toast.makeText(this, "please select a file", Toast.LENGTH_LONG).show();
}
}
public void enableBluetooth() {
showToast("Making device discoverable");
Intent discoveryIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
discoveryIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, DISCOVER_DURATION);
startActivityForResult(discoveryIntent, REQUEST_BLU);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == DISCOVER_DURATION && requestCode == REQUEST_BLU) {
Intent i = new Intent();
i.setAction(Intent.ACTION_SEND);// STOPPED HERE-----------------------------------------------------------------
i.setType("*/*");
File file = new File(dataPath.getText().toString());
i.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(file));
PackageManager pm = getPackageManager();
List<ResolveInfo> list = pm.queryIntentActivities(i, 0);
if (list.size() > 0) {
String packageName = null;
String className = null;
boolean found = false;
for (ResolveInfo info : list) {
packageName = info.activityInfo.packageName;
if (packageName.equals("com.android.bluetooth")) {
className = info.activityInfo.name;
found = true;
break;
}
}
//CHECK BLUETOOTH available or not------------------------------------------------
if (!found) {
Toast.makeText(this, "Bluetooth not been found", Toast.LENGTH_LONG).show();
} else {
i.setClassName(packageName, className);
startActivity(i);
}
}
} else {
Toast.makeText(this, "Bluetooth is cancelled", Toast.LENGTH_LONG).show();
}
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
// if (id == R.id.action_settings) {
// Toast.makeText(this, "**********************************\nDeveloper: www.santoshkumarsingh.com\n**********************************", Toast.LENGTH_LONG).show();
// return true;
// }
return super.onOptionsItemSelected(item);
}
//toast message function
private void showToast(String msg) {
Toast.makeText(this, msg, Toast.LENGTH_SHORT) .show();
}
}
You have trouble with file exchange not with BLE.
Did you ever read Android FileUriExposedException?

HTML parsing Android Jsoup

im kinda new to android, im trying to use jsoup to parse a html page to gather some info from a page.
i would like to insert a url via pop-up (altertbox) usinga method called loadwebsite:
private void loadWebsite(){
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Inserisci url sito");
final EditText input = new EditText(this);
input.setInputType(InputType.TYPE_CLASS_TEXT);
builder.setView(input);
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
linkurl = input.getText().toString();
//linkurl="https://"+linkurl;
url123.setText("https://"+linkurl.toString());
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
builder.show();
}
and a method called getsiteinfo()
private void getinfoWebsite(){
new Thread(new Runnable() {
#Override
public void run() {
final StringBuilder builder = new StringBuilder();
try {
Document doc = Jsoup.connect(linkurl).get();
String title = doc.title();
Element image = doc.select("img").first();
String imgSrc = image.absUrl("src");
InputStream in = new java.net.URL(imgSrc).openStream();
bitmap = BitmapFactory.decodeStream(in);
builder.append(title).append("\n");
} catch (IOException e){
builder.append("Error :").append(e.getMessage()).append("\n");
}
runOnUiThread(new Runnable() {
#Override
public void run() {
result.setText(builder.toString());
}
});
}
}).start();
}
the problem is that when i try to pass a url via textbox i get that error:
03-26 17:22:16.826 26651-26840/it.uninsubria.pdm.htmlparsingjsoup E/AndroidRuntime: FATAL EXCEPTION: Thread-8
Process: it.uninsubria.pdm.htmlparsingjsoup, PID: 26651
java.lang.IllegalArgumentException: Must supply a valid URL
at org.jsoup.helper.Validate.notEmpty(Validate.java:102)
at org.jsoup.helper.HttpConnection.url(HttpConnection.java:72)
at org.jsoup.helper.HttpConnection.connect(HttpConnection.java:36)
at org.jsoup.Jsoup.connect(Jsoup.java:73)
at it.uninsubria.pdm.htmlparsingjsoup.MainActivity$3.run(MainActivity.java:78)
at java.lang.Thread.run(Thread.java:764)
here is the full code:
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.AsyncTask;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.InputType;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.parser.Tag;
import org.jsoup.select.Elements;
import java.io.IOException;
import java.io.InputStream;
public class MainActivity extends AppCompatActivity {
private Button getBtn;
private TextView result;
private ImageView img;
private Bitmap bitmap;
private Button button2;
private String linkurl = "";
private TextView url123;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
result = (TextView) findViewById(R.id.result);
img= (ImageView) findViewById(R.id.image2);
url123 =(TextView)findViewById(R.id.url123);
getBtn =(Button) findViewById(R.id.button2); //
getBtn.setOnClickListener(new View.OnClickListener() { // Pulsante "open website
#Override //
public void onClick(View v) {
openWebsite();
}
});
getBtn =(Button) findViewById(R.id.getBtn);
getBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
loadWebsite();
getinfoWebsite();
img.setImageBitmap(bitmap);
}
});
}
//////////////////////////////////////////// -------------------METHODS------------------////////////////////////////////////////////
private void getinfoWebsite(){
new Thread(new Runnable() {
#Override
public void run() {
final StringBuilder builder = new StringBuilder();
try {
Document doc = Jsoup.connect(linkurl).get();
String title = doc.title();
Element image = doc.select("img").first();
String imgSrc = image.absUrl("src");
InputStream in = new java.net.URL(imgSrc).openStream();
bitmap = BitmapFactory.decodeStream(in);
builder.append(title).append("\n");
} catch (IOException e){
builder.append("Error :").append(e.getMessage()).append("\n");
}
runOnUiThread(new Runnable() {
#Override
public void run() {
result.setText(builder.toString());
}
});
}
}).start();
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
private void openWebsite(){
Uri uriUrl = Uri.parse(String.valueOf(linkurl));
Intent launchBrowser = new Intent(Intent.ACTION_VIEW, uriUrl);
startActivity(launchBrowser);
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
//pop-up text per caricare link url
private void loadWebsite(){
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Inserisci url sito");
final EditText input = new EditText(this);
input.setInputType(InputType.TYPE_CLASS_TEXT);
builder.setView(input);
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
linkurl = input.getText().toString();
//linkurl="https://"+linkurl;
url123.setText("https://"+linkurl.toString());
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
builder.show();
}
}
The error says that the argument you are passing to Jsoup.connect is not valid (empty). It looks like you creating onClick listener to set value of linkurl, but you are starting parsing thread immediately, i.e. not waiting for linkurl value to be set. You can for example delay execution of the code by inserting this code in the begining of run method inside getinfoWebsite(): while(linkurl.isEmpty()) { Thread.sleep(1000);}

Session Manager using Shared Pref

I'm using shared preference to store user data, and in my start screen, I want to check whether username has already logged in or not, when user is still not logged out yet it will redirect to UserView.java when the application starts, otherwise it will go to LoginActivity.java
I've used these tutorial as my references :
Android Hive Tutorial Shared Pref, and
Android example tutorial Shared Pref..
but when I exit my activity without logging out, next time I open my application it's status is logged out (its like the session has ended although I have not logged out yet from my application),,
What should I do to fix this thing, so whenever I exit my application (without logging out) my data is still there in shared pref and will be redirected to UserView.java, Am i making any mistakes with my codes?
These are my code:
userSessionManager.java
package com.thesis.teamizer;
import java.util.HashMap;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
public class userSessionManager {
// Shared Preferences Reference
SharedPreferences CurrentSession;
// Editor Reference for Editing Shared Preferences
Editor editor;
// Context Reference
Context _context;
// Shared pref mode
int PRIVATE_MODE = 0;
// Sharef Preferences Name
public static String PrefName = "MyUsername";
// All Shared Preferences Keys
private static final String IS_USER_LOGIN = "IsUserLoggedIn";
// User name (make variable public to access from outside)
public static final String KEY_USERNAME = "username";
// Constructor
public userSessionManager(Context context) {
this._context = context;
CurrentSession = _context.getSharedPreferences(PrefName, PRIVATE_MODE);
editor = CurrentSession.edit();
}
public void createUserLogin(String username) {
// User has already login
editor.putBoolean(IS_USER_LOGIN, true);
// Storing username in pref
editor.putString(KEY_USERNAME, username);
// Editor ready to execute the previous codes
editor.commit();
}
public boolean checkLogin() {
// Check login status. If the user is not logged in
if (!this.isUserLoggedIn()) {
return true;
}
return false;
}
// Read session using hashmap
public HashMap<String, String> getUserDetails() {
// Use hashmap to store user credentials
HashMap<String, String> user = new HashMap<String, String>();
// user name
user.put(KEY_USERNAME, CurrentSession.getString(KEY_USERNAME, null));
// return user
return user;
}
public void logOut() {
// clearing all data from Shared pref
editor.remove(KEY_USERNAME);
editor.clear();
editor.commit();
}
// Will check if the user is Login or not by getting the boolean of
// IS_USER_LOGIN from CurrentSession(pref)
private boolean isUserLoggedIn() {
// TODO Auto-generated method stub
return CurrentSession.getBoolean(IS_USER_LOGIN, false);
}
}
LoginActivity.java
package com.thesis.teamizer;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class LoginActivity extends Activity implements View.OnClickListener {
private EditText etUsername;
private EditText etPassword;
private Button bLogin, bRegis, bAdmin;
userSessionManager session;
String loginUrl;
JSONParser jsonParser = new JSONParser();
private static final String TAG_SUCCESS = "success";
private static final String TAG_MESSAGE = "message";
private ProgressDialog pDialog;
String Username;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.login_screen);
Declaration();
bLogin.setOnClickListener(this);
bRegis.setOnClickListener(this);
bAdmin.setOnClickListener(this);
if (session.checkLogin()) {
Intent intent = new Intent("com.thesis.teamizer.USERVIEW");
finish();
startActivity(intent);
}
}
private void Declaration() {
// TODO Auto-generated method stub
etUsername = (EditText) findViewById(R.id.etLoginUsername);
etPassword = (EditText) findViewById(R.id.etLoginPassword);
bLogin = (Button) findViewById(R.id.bLogin);
bRegis = (Button) findViewById(R.id.bRegister);
bAdmin = (Button) findViewById(R.id.bAdminadmin);
session = new userSessionManager(getApplicationContext());
HashMap<String, String> user = session.getUserDetails();
Username = user.get(userSessionManager.KEY_USERNAME);
myIP ip = new myIP();
String myIp = ip.getIp();
String thisPhp = "doLogin.php";
loginUrl = myIp + thisPhp;
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.bLogin:
new AttemptLogin().execute();
break;
case R.id.bRegister:
Intent i = new Intent("com.thesis.teamizer.REGISTRATIONACTIVITY");
startActivity(i);
break;
}
class AttemptLogin extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
boolean failure = false;
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(LoginActivity.this);
pDialog.setMessage("Attempting login...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected String doInBackground(String... args) {
// TODO Auto-generated method stub
// Check for success tag
int success;
String username = etUsername.getText().toString();
String password = etPassword.getText().toString();
try {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("username", username));
params.add(new BasicNameValuePair("password", password));
Log.d("request!", "starting");
// getting product details by making HTTP request
JSONObject json = jsonParser.makeHttpRequest(loginUrl, "POST",
params);
// check your log for json response
Log.d("Login attempt", json.toString());
// json success tag
success = json.getInt(TAG_SUCCESS);
if (success == 1) {
Log.d("Login Successful!", json.toString());
String currentLoginUsername = username;
session.createUserLogin(currentLoginUsername);
Intent intent = new Intent("com.thesis.teamizer.USERVIEW");
finish();
startActivity(intent);
String sukses = "Sukses login";
return sukses;
} else if (success == 0) {
return json.getString(TAG_MESSAGE);
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
// dismiss the dialog once product deleted
pDialog.dismiss();
Toast.makeText(getApplicationContext(), file_url,
Toast.LENGTH_SHORT).show();
}
}
}
UserView.java
package com.thesis.teamizer;
import java.util.HashMap;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class UserView extends Activity implements View.OnClickListener {
public Button createGr, viewGr, createAn, viewAn, notification, logout,
calendar, createEvent, myEvent, createTask, myTask;
public String Username;
userSessionManager session;
Intent i;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.user_view);
sessionAndDeclaration();
createGr.setOnClickListener(this);
viewGr.setOnClickListener(this);
createAn.setOnClickListener(this);
viewAn.setOnClickListener(this);
notification.setOnClickListener(this);
logout.setOnClickListener(this);
createEvent.setOnClickListener(this);
calendar.setOnClickListener(this);
myEvent.setOnClickListener(this);
createTask.setOnClickListener(this);
myTask.setOnClickListener(this);
}
private void sessionAndDeclaration() {
// TODO Auto-generated method stub
session = new userSessionManager(getApplicationContext());
HashMap<String, String> user = session.getUserDetails();
// get name
Username = user.get(userSessionManager.KEY_USERNAME);
TextView a = (TextView) findViewById(R.id.tvUserVUsername);
a.setText(Username);
createGr = (Button) findViewById(R.id.bCreateGroup);
viewGr = (Button) findViewById(R.id.bViewMyGroup);
createAn = (Button) findViewById(R.id.bCreateAnnouncement);
viewAn = (Button) findViewById(R.id.bViewMyAnnouncement);
notification = (Button) findViewById(R.id.bNotification);
logout = (Button) findViewById(R.id.bDoLogout);
calendar = (Button) findViewById(R.id.bGoToMyCalendar);
createEvent = (Button) findViewById(R.id.bCreateEvent);
myEvent = (Button) findViewById(R.id.bGoToMyEvent);
createTask = (Button) findViewById(R.id.bGoToCreateTask);
myTask = (Button) findViewById(R.id.bGoToMyTask);
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.bCreateGroup:
i = new Intent("com.thesis.teamizer.CREATEGROUPACTIVITY");
startActivity(i);
break;
case R.id.bViewMyGroup:
i = new Intent("com.thesis.teamizer.MYGROUPACTIVITY");
startActivity(i);
break;
case R.id.bCreateAnnouncement:
i = new Intent("com.thesis.teamizer.CREATEANNOUNCEMENTACTIVITY");
startActivity(i);
break;
case R.id.bViewMyAnnouncement:
i = new Intent("com.thesis.teamizer.VIEWALLANNOUNCEMENT");
startActivity(i);
break;
case R.id.bNotification:
i = new Intent("com.thesis.teamizer.NOTIFICATION");
startActivity(i);
break;
case R.id.bDoLogout:
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("Are you sure you want to Logout?")
.setCancelable(false)
.setPositiveButton("Yes",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int id) {
finish();
session.logOut();
Intent i = new Intent(
"com.thesis.teamizer.LOGINACTIVITY");
// Closing all the Activities
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
// Add new Flag to start new Activity
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
// Staring Login Activity
startActivity(i);
finish();
}
})
.setNegativeButton("No",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int id) {
dialog.cancel();
}
});
AlertDialog alert = builder.create();
alert.show();
break;
case R.id.bGoToMyCalendar:
i = new Intent("com.thesis.teamizer.VIEWCALENDAR");
startActivity(i);
break;
case R.id.bCreateEvent:
i = new Intent("com.thesis.teamizer.CREATEEVENT");
startActivity(i);
break;
case R.id.bGoToMyEvent:
i = new Intent("com.thesis.teamizer.MYEVENT");
startActivity(i);
break;
case R.id.bGoToCreateTask:
i= new Intent("com.thesis.teamizer.CREATETASK");
startActivity(i);
break;
case R.id.bGoToMyTask:
i = new Intent("com.thesis.teamizer.MYTASK");
startActivity(i);
break;
}
}
}

Why doesn't this if statement work?

I'm trying to create an if statement, for example if the user doesn't type anything into the the two edit text's, then it displays a toast and resets everything. But for some reason, my code completely ignores this and just goes to the else statement instead.
Can anyone help?
My Code:
package com.gta5news.bananaphone;
import java.io.File;
import android.R.string;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class LogIn extends Activity implements OnClickListener {
Button send;
EditText user;
EditText pass;
CheckBox staySignedIn;
SharedPreferences shareduser;
SharedPreferences sharedpass;
public static String settings = "MySharerdUser";
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.login);
send = (Button) findViewById(R.id.bLogIn);
user = (EditText) findViewById(R.id.eTuser);
pass = (EditText) findViewById(R.id.eTpassword);
staySignedIn = (CheckBox) findViewById(R.id.Cbstay);
send.setOnClickListener(this);
SharedPreferences settings = getPreferences(MODE_PRIVATE);
String name = settings.getString("name", "");
String password = settings.getString("pwd", "");
user.setText(name);
pass.setText(password);
if (staySignedIn.isChecked()) {
SharedPreferences MySharedUser = getPreferences(MODE_PRIVATE);
settings.edit().putString("name", user.getText().toString())
.putString("pwd", pass.getText().toString()).commit();
}
if (user.length() > 0)
;
}
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.bLogIn:
if (user.length() < 0)
Toast.makeText(this,
"Try to type in your username and password again!",
Toast.LENGTH_LONG).show();
else {
String u = user.getText().toString();
String p = pass.getText().toString();
Bundle send = new Bundle();
send.putString("key", u);
send.putString("key", p);
Intent a = new Intent(LogIn.this, FTPClient.class);
startActivity(a);
Toast.makeText(this, "Yay, you signed in!", Toast.LENGTH_LONG)
.show();
break;
}
}
}
}
if (user.length() == 0)
try it because user.length() is never come in Less Than Zero
You have to use
user.getText().toString().length()
Do you need an onClickListener for you checkbox???
checkbox.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// Perform action on clicks, depending on whether it's now checked
if (((CheckBox) v).isChecked()) {
Toast.makeText(HelloFormStuff.this, "Selected", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(HelloFormStuff.this, "Not selected", Toast.LENGTH_SHORT).show();
}
}
});

Categories