I got the following code. I'm trying to submit my coordinates to an email.
But every time I press the button, the app closes.
public LatLng getLocation()
{
// Get the location manager
LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
Criteria criteria = new Criteria();
String bestProvider = locationManager.getBestProvider(criteria, false);
Location location = locationManager.getLastKnownLocation(bestProvider);
//double lat;
//double lon;
try {
lat = location.getLatitude();
lon = location.getLongitude();
Log.i("logging","lat "+lat+" long "+lon);
return new LatLng(lat, lon);
}
catch (NullPointerException e){
e.printStackTrace();
return null;
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
final Button button = (Button) findViewById(R.id.addbutton);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
final Button button = (Button) findViewById(R.id.addbutton);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
LatLng latlng = getLocation();
Intent i = new Intent(Intent.ACTION_SENDTO);
//i.setType("message/rfc822");
i.putExtra(Intent.EXTRA_EMAIL , new String[]{"mailadress#example.com"});
i.putExtra(Intent.EXTRA_SUBJECT, "subject of email");
i.putExtra(Intent.EXTRA_TEXT , latlng.latitude+" " + latlng.longitude);
try {
startActivity(Intent.createChooser(i, "Send mail..."));
} catch (android.content.ActivityNotFoundException ex) {
makeText(MapsActivity.this, "There are no email clients installed.", LENGTH_SHORT).show();
}
}
});
}
});
If I press the button, the following error from the stack trace appears:
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.testingmapingmarker23, PID: 6630
Theme: themes:{default=overlay:system, iconPack:system, fontPkg:system, com.android.systemui=overlay:system, com.android.systemui.navbar=overlay:system}
java.lang.NullPointerException: Attempt to read from field 'double com.google.android.gms.maps.model.LatLng.latitude' on a null object reference
at com.example.testingmapingmarker23.MapsActivity$1$1.onClick(MapsActivity.java:96)
at android.view.View.performClick(View.java:5204)
at android.view.View$PerformClick.run(View.java:21158)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5461)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
So the question is: what is exactly the problem? Somehow the coordinates are not shown through the Log too.
You should null check the latlng before any action you want to perform on this object.
e.g.
LatLng latlng = getLocation();
Intent i = new Intent(Intent.ACTION_SENDTO);
//i.setType("message/rfc822");
i.putExtra(Intent.EXTRA_EMAIL , new String[]{"mailadress#example.com"});
i.putExtra(Intent.EXTRA_SUBJECT, "subject of email");
if(latlng != null) {
i.putExtra(Intent.EXTRA_TEXT , latlng.latitude+" " + latlng.longitude);
} else {
i.putExtra(Intent.EXTRA_TEXT , "location not available");
}
try {
startActivity(Intent.createChooser(i, "Send mail..."));
} catch (android.content.ActivityNotFoundException ex) {
makeText(MapsActivity.this, "There are no email clients installed.", LENGTH_SHORT).show();
}
This code only gives you the LastKnownLocation that too if the location is stored in the device. It does not give you the most current location necessarily all the time. If you need to get the Location, you need to perform certain steps.
Request Permission to Access Location - ACCESS_FINE_LOCATION
Create a Location Manager class that implements android.location.LocationListener
Initiate the Location Service using (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
Check for Last known Location as you have done above.
If its not available request for the current location using requestLocationUpdates() listener method.
Implement onLocationChanged() method and get the current location in that method.
Perform your operation once the location is received.
Disable the listener once the work is done.
You can follow the below mentioned links to see how the above steps work out.
https://www.codota.com/android/scenarios/52fcbdd6da0a6fdfa462fe3b/finding-current-location?tag=dragonfly&fullSource=1
https://www.tutorialspoint.com/android/android_location_based_services.htm
http://javapapers.com/android/get-current-location-in-android/
Related
I have added my Android side code:
I know that I need to use a platform channel to pass data,I am unable to figure out:
import io.flutter.embedding.android.FlutterActivity;
public class MainActivity extends AppCompatActivity {
private Button Btn;
// Intent defaultFlutter=FlutterActivity.createDefaultIntent(activity);
String path;
private Button bt;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Btn = findViewById(R.id.btn);
isStoragePermissionGranted();
Btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view)
{
path=takeScreenshot();
// activity.startActivity(defaultFlutter);
}
});
//write flutter xode here
//FlutterActivity.createDefaultIntent(this);
}
private String takeScreenshot() {
Date now = new Date();
android.text.format.DateFormat.format("yyyy-MM-dd_hh:mm:ss", now);
try {
// image naming and path to include sd card appending name you choose for file
String mPath = Environment.getExternalStorageDirectory().toString() + "/" + now + ".jpg";
// create bitmap screen capture
View v1 = getWindow().getDecorView().getRootView();
v1.setDrawingCacheEnabled(true);
Bitmap bitmap = Bitmap.createBitmap(v1.getDrawingCache());
v1.setDrawingCacheEnabled(false);
File imageFile = new File(mPath);
Log.d("path",mPath);
FileOutputStream outputStream = new FileOutputStream(imageFile);
int quality = 100;
bitmap.compress(Bitmap.CompressFormat.JPEG, quality, outputStream);
outputStream.flush();
outputStream.close();
return mPath;
///openScreenshot(imageFile);
} catch (Throwable e) {
// Several error may come out with file handling or DOM
e.printStackTrace();
return "Error";
}
}
public boolean isStoragePermissionGranted() {
String TAG = "Storage Permission";
if (Build.VERSION.SDK_INT >= 23) {
if (this.checkSelfPermission(android.Manifest.permission.WRITE_EXTERNAL_STORAGE)
== PackageManager.PERMISSION_GRANTED) {
Log.v(TAG, "Permission is granted");
return true;
} else {
Log.v(TAG, "Permission is revoked");
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
return false;
}
}
else { //permission is automatically granted on sdk<23 upon installation
Log.v(TAG,"Permission is granted");
return true;
}
}
}
I will receive a file from the android side, upon receiving I need to display it in a flutter. I also need to use cached engine for transferring data as normally it would cause a delay
You can use the cached engine, this will help me cover up for the delay.
Then you can add a invoke method onpressed that you can send method name and the data you want to pass.
On flutter side,you can create a platform and invoke method through which you can receive requirements and further process it,
I'm testing my app on a device where the Facebook application is not installed.
So when I'm logging with Facebook, a webview is opened.
The strange this is that when I've inserted my username and password, after pressing ok a webview is reopened and I've to insert the username and password again and I can login.
What could be ?
authButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
authButton.setVisibility(View.GONE);
logoutButton.setVisibility(View.VISIBLE);
// start Facebook Login
Session.openActiveSession(Login.this, true, new Session.StatusCallback() {
// callback when session changes state
SharedPreferences.Editor edit = pref.edit();
#Override
public void call(Session session, SessionState state,
Exception exception) {
if (session.isOpened()) {
accesstoken = session.getAccessToken();
edit.putString("fbtoken", accesstoken);
if (session.getExpirationDate()!= null)
edit.putLong("com.facebook.sdk.AccessTokenExpires", session.getExpirationDate().getTime());
Log.d("FACEBOOK", "LOGGED IN");
}
});
List<String> permissions = session.getPermissions();
if (!isSubsetOf(PERMISSIONS, permissions)) {
Session.NewPermissionsRequest newPermissionsRequest = new Session.NewPermissionsRequest(
Login.this, PERMISSIONS);
session.requestNewReadPermissions(newPermissionsRequest);
return;
}
// make request to the /me API
Request.newMeRequest(session, new GraphUserCallback() {
#Override
public void onCompleted(GraphUser user, Response response) {
Log.d("FACEBOOK", "onCompleted");
Log.d("",""+user);
try {
name=user.getName();
email=user.getProperty("email").toString();
location=(user.getLocation().getProperty("name").toString());
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Log.d("ID", user.getId());
}
}).executeAsync();
}
}
});
}
});
I've had the same problem on iOS so this problem could be linked.
I solved it by removing the delegate after I received the first response.
So it may be applicable in your exemple like this:
Session.openActiveSession(Login.this, true, new Session.StatusCallback() {
// callback when session changes state
if (logoutButton.getVisibility() == View.VISIBLE) {
// Its visible so we end the callback
return;
}
SharedPreferences.Editor edit = pref.edit();
My guess is that you're saving the access token into the shared pref,
and it needs some time to be saved on disk if you don't force it.
You should add
edit.putLong("com.facebook.sdk.AccessTokenExpires", ...);
edit.commit(); // <- this line
so you are sure that for the next call it will be available
I have researched this topic thoroughly and found similar questions on StackOverflow but not specific enough for my question. I am trying to update my ListView with a SimpleCursorAdapter. I have a button, "Get Network Location" that when I press it, it dynamically populates my ListView with new location data (id, lat, lon, acc, time) every time the location changes inside method "onLocationChanged". This is done through adding the new location data to the database and setting the cursor to the adapter.
So it works fine until the "Back" button is pressed or the phone changes orientation. In onResume, the listview becomes empty, so I had to open the database again and set the cursor to the adapter and the adapter to listview again. This populates the listview with complete data from database at the time that "onResume" is called.
However, when a new location data gets added in "onLocationChanged", the new data doesn't populate the listview, until "onResume" gets called again. adapter.notifyDataSetChanged is called both in "onResume" an "onLocation" changed but to no avail. My guess is the listview has changed to a different one after "onCreate" is called but I don't know how to resolve that.
Please anyone with knowledge on this issue let me know what is wrong with my code.
Here's my code:
public class MainActivity extends Activity {
LocationManager locMan;
String provider;
Boolean netWork_enabled = false;
private static long MINTIME;
private static float MINDIS;
Cursor cursor;
NetworkScanDB GeoLocInfoDb;
String row;
double lat;
double lon;
double accur;
double time;
EditText etMinTime;
EditText etMinDis;
ListView lv;
SimpleCursorAdapter sd;
String[] columns;
int[] to;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// initialize lv
lv = (ListView) findViewById(R.id.listView1);
// getting min time and distance from edit text
etMinTime = (EditText) findViewById(R.id.et_minTime);
etMinDis = (EditText) findViewById(R.id.et_minDis);
// initiating location
locMan = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
provider = locMan.NETWORK_PROVIDER;
try {
netWork_enabled = locMan.isProviderEnabled(provider);
} catch (Exception ex) {
}
columns = new String[] { NetworkScanDB.Key_RowID,
NetworkScanDB.Key_Lat, NetworkScanDB.Key_Lon,
NetworkScanDB.Key_Accur, NetworkScanDB.Key_Time };
to = new int[] { R.id.t0, R.id.t1, R.id.t2, R.id.t3, R.id.t4 };
sd = new SimpleCursorAdapter(MainActivity.this, R.layout.nsrow, cursor,
columns, to, 0); // had to change to api 11., 0=no query
}
LocationListener locationListenerNetwork = new LocationListener() {
#Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
try {
GeoLocInfoDb = new NetworkScanDB(MainActivity.this);
GeoLocInfoDb.open();
// insert row into DB
GeoLocInfoDb.insertGeoLocInfo(location.getLatitude(),
location.getLongitude(), location.getAccuracy(),
location.getTime());
cursor = GeoLocInfoDb.getGeoLocInfoCursor();
sd = new SimpleCursorAdapter(MainActivity.this, R.layout.nsrow,
cursor, columns, to, 0); // had to change to api 11.,
// 0=no query
Toast.makeText(getApplicationContext(),
"added new location onLocationChanged",
Toast.LENGTH_LONG).show();
// lv = (ListView) findViewById(R.id.listView1);
sd.notifyDataSetChanged();
lv.setAdapter(sd);
GeoLocInfoDb.close();
} catch (Exception e) {
Log.w("nwscan", e.toString());
}
}
#Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
};
public void getNetworkLocation(View v) {
MINTIME = Long.parseLong(etMinTime.getText().toString());
MINDIS = Float.parseFloat(etMinDis.getText().toString());
if (netWork_enabled) {
locMan.requestLocationUpdates(provider, MINTIME, MINDIS,
locationListenerNetwork);
} else {
Toast.makeText(getApplicationContext(), "network not enable",
Toast.LENGTH_LONG).show();
}
}
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
Toast.makeText(getApplicationContext(), "onResume ", Toast.LENGTH_LONG)
.show();
GeoLocInfoDb = new NetworkScanDB(MainActivity.this);
GeoLocInfoDb.open();
cursor = GeoLocInfoDb.getGeoLocInfoCursor();
sd = new SimpleCursorAdapter(MainActivity.this, R.layout.nsrow, cursor,
columns, to, 0); // had to change to api 11., 0=no query
sd.notifyDataSetChanged();
lv.setAdapter(sd);
}
...
}
I have a problem with a code. It's (supposed to be) an email-client with options to read messages and send them - the problem is, that it does not download the messages and is not able to send them - I assume that the problem lies in the connectiong.
The program includes following classes
EmailClient: The main class for the e-mail client application
ConnectDialog: This class displays a dialog for entering e-mail server connection settings.
MessagesTableModel: This class manages the e-mail table's data.
MessageDialog: This class displays the dialog used for creating messages.
Here's the main class, the most interesting are methods named sendMessage() and connect():
import java.awt.*;
import java.awt.event.*;
import java.net.*;
import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;
import javax.swing.*;
import javax.swing.event.*;
// The E-mail Client.
public class EmailClient extends JFrame {
// Message table's data model.
private MessagesTableModel tableModel;
// Table listing messages.
private JTable table;
// This the text area for displaying messages.
private JTextArea messageTextArea;
/* This is the split panel that holds the messages
table and the message view panel. */
private JSplitPane splitPane;
// These are the buttons for managing the selected message.
private JButton replyButton, forwardButton, deleteButton;
// Currently selected message in table.
private Message selectedMessage;
// Flag for whether or not a message is being deleted.
private boolean deleting;
// This is the JavaMail session.
private Session session;
// Constructor for E-mail Client.
public EmailClient() {
// Set application title.
setTitle("E-mail Client");
// Set window size.
setSize(640, 480);
// Handle window closing events.
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
actionExit();
}
});
// Setup file menu.
JMenuBar menuBar = new JMenuBar();
JMenu fileMenu = new JMenu("File");
fileMenu.setMnemonic(KeyEvent.VK_F);
JMenuItem fileExitMenuItem = new JMenuItem("Exit",
KeyEvent.VK_X);
fileExitMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
actionExit();
}
});
fileMenu.add(fileExitMenuItem);
menuBar.add(fileMenu);
setJMenuBar(menuBar);
// Setup buttons panel.
JPanel buttonPanel = new JPanel();
JButton newButton = new JButton("New Message");
newButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
actionNew();
}
});
buttonPanel.add(newButton);
// Setup messages table.
tableModel = new MessagesTableModel();
table = new JTable(tableModel);
table.getSelectionModel().addListSelectionListener(new
ListSelectionListener() {
public void valueChanged(ListSelectionEvent e) {
tableSelectionChanged();
}
});
// Allow only one row at a time to be selected.
table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
// Setup E-mails panel.
JPanel emailsPanel = new JPanel();
emailsPanel.setBorder(
BorderFactory.createTitledBorder("E-mails"));
messageTextArea = new JTextArea();
messageTextArea.setEditable(false);
splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT,
new JScrollPane(table), new JScrollPane(messageTextArea));
emailsPanel.setLayout(new BorderLayout());
emailsPanel.add(splitPane, BorderLayout.CENTER);
// Setup buttons panel 2.
JPanel buttonPanel2 = new JPanel();
replyButton = new JButton("Reply");
replyButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
actionReply();
}
});
replyButton.setEnabled(false);
buttonPanel2.add(replyButton);
forwardButton = new JButton("Forward");
forwardButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
actionForward();
}
});
forwardButton.setEnabled(false);
buttonPanel2.add(forwardButton);
deleteButton = new JButton("Delete");
deleteButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
actionDelete();
}
});
deleteButton.setEnabled(false);
buttonPanel2.add(deleteButton);
// Add panels to display.
getContentPane().setLayout(new BorderLayout());
getContentPane().add(buttonPanel, BorderLayout.NORTH);
getContentPane().add(emailsPanel, BorderLayout.CENTER);
getContentPane().add(buttonPanel2, BorderLayout.SOUTH);
}
// Exit this program.
private void actionExit() {
System.exit(0);
}
// Create a new message.
private void actionNew() {
sendMessage(MessageDialog.NEW, null);
}
// Called when table row selection changes.
private void tableSelectionChanged() {
/* If not in the middle of deleting a message, set
the selected message and display it. */
if (!deleting) {
selectedMessage =
tableModel.getMessage(table.getSelectedRow());
showSelectedMessage();
updateButtons();
}
}
// Reply to a message.
private void actionReply() {
sendMessage(MessageDialog.REPLY, selectedMessage);
}
// Forward a message.
private void actionForward() {
sendMessage(MessageDialog.FORWARD, selectedMessage);
}
// Delete the selected message.
private void actionDelete() {
deleting = true;
try {
// Delete message from server.
selectedMessage.setFlag(Flags.Flag.DELETED, true);
Folder folder = selectedMessage.getFolder();
folder.close(true);
folder.open(Folder.READ_WRITE);
} catch (Exception e) {
showError("Unable to delete message.", false);
}
// Delete message from table.
tableModel.deleteMessage(table.getSelectedRow());
// Update GUI.
messageTextArea.setText("");
deleting = false;
selectedMessage = null;
updateButtons();
}
// Send the specified message.
private void sendMessage(int type, Message message) {
// Display message dialog to get message values.
MessageDialog dialog;
try {
dialog = new MessageDialog(this, type, message);
if (!dialog.display()) {
// Return if dialog was cancelled.
return;
}
} catch (Exception e) {
showError("Unable to send message.", false);
return;
}
try {
// Create a new message with values from dialog.
Message newMessage = new MimeMessage(session);
newMessage.setFrom(new InternetAddress(dialog.getFrom()));
newMessage.setRecipient(Message.RecipientType.TO,
new InternetAddress(dialog.getTo()));
newMessage.setSubject(dialog.getSubject());
newMessage.setSentDate(new Date());
newMessage.setText(dialog.getContent());
// Send new message.
Transport.send(newMessage);
} catch (Exception e) {
showError("Unable to send message.", false);
}
}
// Show the selected message in the content panel.
private void showSelectedMessage() {
// Show hour glass cursor while message is loaded.
setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
try {
messageTextArea.setText(
getMessageContent(selectedMessage));
messageTextArea.setCaretPosition(0);
} catch (Exception e) {
showError("Unabled to load message.", false);
} finally {
// Return to default cursor.
setCursor(Cursor.getDefaultCursor());
}
}
/* Update each button's state based off of whether or not
there is a message currently selected in the table. */
private void updateButtons() {
if (selectedMessage != null) {
replyButton.setEnabled(true);
forwardButton.setEnabled(true);
deleteButton.setEnabled(true);
} else {
replyButton.setEnabled(false);
forwardButton.setEnabled(false);
deleteButton.setEnabled(false);
}
}
// Show the application window on the screen.
public void show() {
super.show();
// Update the split panel to be divided 50/50.
splitPane.setDividerLocation(.5);
}
// Connect to e-mail server.
public void connect() {
// Display connect dialog.
ConnectDialog dialog = new ConnectDialog(this);
dialog.show();
// Build connection URL from connect dialog settings.
StringBuffer connectionUrl = new StringBuffer();
connectionUrl.append(dialog.getType() + "://");
connectionUrl.append(dialog.getUsername() + ":");
connectionUrl.append(dialog.getPassword() + "#");
connectionUrl.append(dialog.getServer() + "/");
/* Display dialog stating that messages are
currently being downloaded from server. */
final DownloadingDialog downloadingDialog =
new DownloadingDialog(this);
SwingUtilities.invokeLater(new Runnable() {
public void run() {
downloadingDialog.show();
}
});
// Establish JavaMail session and connect to server.
Store store = null;
try {
// Initialize JavaMail session with SMTP server.
Properties props = new Properties();
props.put("mail.smtp.host", dialog.getSmtpServer());
session = Session.getDefaultInstance(props, null);
// Connect to e-mail server.
URLName urln = new URLName(connectionUrl.toString());
store = session.getStore(urln);
store.connect();
} catch (Exception e) {
// Close the downloading dialog.
downloadingDialog.dispose();
// Show error dialog.
showError("Unable to connect.", true);
}
// Download message headers from server.
try {
// Open main "INBOX" folder.
Folder folder = store.getFolder("INBOX");
folder.open(Folder.READ_WRITE);
// Get folder's list of messages.
Message[] messages = folder.getMessages();
// Retrieve message headers for each message in folder.
FetchProfile profile = new FetchProfile();
profile.add(FetchProfile.Item.ENVELOPE);
folder.fetch(messages, profile);
// Put messages in table.
tableModel.setMessages(messages);
} catch (Exception e) {
// Close the downloading dialog.
downloadingDialog.dispose();
// Show error dialog.
showError("Unable to download messages.", true);
}
// Close the downloading dialog.
downloadingDialog.dispose();
}
// Show error dialog and exit afterwards if necessary.
private void showError(String message, boolean exit) {
JOptionPane.showMessageDialog(this, message, "Error",
JOptionPane.ERROR_MESSAGE);
if (exit)
System.exit(0);
}
// Get a message's content.
public static String getMessageContent(Message message)
throws Exception {
Object content = message.getContent();
if (content instanceof Multipart) {
StringBuffer messageContent = new StringBuffer();
Multipart multipart = (Multipart) content;
for (int i = 0; i < multipart.getCount(); i++) {
Part part = (Part) multipart.getBodyPart(i);
if (part.isMimeType("text/plain")) {
messageContent.append(part.getContent().toString());
}
}
return messageContent.toString();
} else {
return content.toString();
}
}
// Run the E-mail Client.
public static void main(String[] args) {
EmailClient client = new EmailClient();
client.show();
// Display connect dialog.
client.connect();
}
}
Adding printStackTrace() to exceptions gives the following message:
javax.mail.NoSuchProviderException: No provider for NORMAL
at javax.mail.Session.getProvider(Session.java:464)
at javax.mail.Session.getStore(Session.java:539)
at EmailClient.connect(EmailClient.java:296)
at EmailClient.main(EmailClient.java:365)
I'm grateful for all the help I can get!
This problems occur when I click on Login button on the android emulator, it appear on Username textbox.
Kindly help me to resolve it...your help is appreciate ~
java.lang.IllegalArgumentException: Illegal character in scheme at index 0:
android.os.NetworkOnMainThreadException
--
Update 7.9.2011
I post my code over here:
http://pastebin.com/EX0ArwaE --> Login.java
http://pastebin.com/WgGctGHN --> CustomHttpClient.java
So first the Android stuff: You're getting this NetworkOnMainThreadException because you're trying to make a HTTP request on your main application thread which is the UI thread. You shouldn't do any blocking operations in this thread. Use an AsyncTask instead.
I'm not quite sure what's causing the IllegalArgumentException but I guess it's this line:
response = CustomHttpClient.executeHttpPost("http://127.0.0.1/es/check.php", postParameters);
You have probably changed the URL (localhost usually doesn't make sense on a phone). The scheme part is the http. Maybe you have something like " http://..." (note the leading space character) in the original code?
Short note on the PHP:
$sql = 'SELECT * from people WHERE username = "' .$_POST['un'] . '" and password = "' .md5($_POST['pw']) . '"';
That's what you call an SQL injection.
Update: Here's some example. Didn't test it, hopefully it works.
public class LoginLayout extends Activity {
EditText un,pw;
TextView error;
Button ok;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
un=(EditText)findViewById(R.id.et_un);
pw=(EditText)findViewById(R.id.et_pw);
ok=(Button)findViewById(R.id.btn_login);
error=(TextView)findViewById(R.id.tv_error);
ok.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
new LoginTask().execute(un.getText().toString(), pw.getText().toString());
}
});
}
private class LoginTask extends AsyncTask<String, Void, Object> {
protected Object doInBackground(String... params) {
ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
postParameters.add(new BasicNameValuePair("username", params[0]));
postParameters.add(new BasicNameValuePair("password", params[1]));
String response = null;
try {
response = CustomHttpClient.executeHttpPost("http://127.0.0.1/es/check.php", postParameters);
String res = response.toString();
res = res.replaceAll("\\s+","");
return res;
} catch (Exception e) {
return e;
}
}
protected void onPostExecute(Object result) {
if (result instanceof String) {
if (result.equals("1")) {
error.setText("Correct Username or Password");
} else {
error.setText("Sorry!! Wrong Username or Password Entered");
}
} else if (result instanceof Exception) {
un.setText(result.toString());
}
}
}
}