java.lang.IllegalArgumentException: Illegal character in scheme at index 0: AND android.os.NetworkOnMainThreadException - android-emulator

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

Related

Pass data from android to flutter

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,

How to recognize whether is it successfully find the values for the 'asserEquals' in Selenium(POM)?

Here mentioned code successfully passed by the test run.But it was not showed the login button click and the logged-user name.(I have try to print the messages by try-catch ).but result shows as passed without those messages.
I just wanted to why can't I see the button click and assertEqual messages?
is there any coding issue or practice should be able to use to overcome this?
I have used the xml file to send the browser type.Further,I pasted only the relevant code sections.
1.TestCommands.java
public class TestCommands {
public void assertText(By locator,WebDriver driver,String expectedValue){
try {
WebElement element = driver.findElement(locator);
assertEquals(element.getText(), expectedValue);
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
System.out.println("Not equal");
}
System.out.println("Equal");
System.out.println("captured web element: "+ locator);
System.out.println("captured expectedValue: "+ expectedValue);
}
}
2.LoginPage.java
public class LoginPage extends TestCommands{
public void loginToApplication(WebDriver driver,String userName,String password,String loggedUser){
type(userName(),driver,userName);
type(password(),driver,password);
click(loginButton(),driver);
selectByVisibleText(loggedUser(),driver,loggedUser);
}
3.TC_LoginToTest.java
public class TC_LoginToTest {
WebDriver driver ;
String baseUrl;
LoginPage login = new LoginPage();
#Parameters("browser")
#BeforeMethod
public void beforeMethod(String browser) {
if (browser.equals("firefox")) {
System.setProperty("webdriver.gecko.driver", "drivers\\geckodriver.exe");
driver = new FirefoxDriver();
//baseUrl = "https://test.com";
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
} else if (browser.equals("chrome")) {
System.setProperty("webdriver.chrome.driver", "drivers\\chromedriver.exe");
driver = new ChromeDriver();
//baseUrl = "https://test.com";
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
driver.manage().window().maximize();
}
}
#DataProvider
public Object[][] tc001() {
return new Object[][] {
new Object[] {"nadee","12345678","Testnadee"},
};
}
#Test(dataProvider="tc001")
public void tc001(String userName , String password ,String loggedUser) {
login.openApplication("https://test.com", driver);
login.loginToApplication(driver, userName, password, loggedUser);
}
}

in signin the method gettext must be called from ui thread error

I'm trying to create a login for an application. However I have a problem.
This is my code:
in this code there is an error in the getText() in the android studio
actually m creating a login page with the help of the JSONParsing of web API, the login detail sync from the web api
public class Register extends Activity implements OnClickListener{
EditText user, pass, email, mobile;
private Button mRegister;
// Progress Dialog
private ProgressDialog pDialog;
// JSON parser class
JSONParser jsonParser = new JSONParser();
//si lo trabajan de manera local en xxx.xxx.x.x va su ip local
// private static final String REGISTER_URL = "http://xxx.xxx.x.x:1234/cas/register.php";
//testing on Emulator:
private static final String REGISTER_URL = "http://abc.demo.xxxxxxxxx.xxx/xxx";
//ids
private static final String TAG_SUCCESS = "success";
private static final String TAG_MESSAGE = "message";
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.register);
user = (EditText)findViewById(R.id.username);
pass = (EditText)findViewById(R.id.password);
email = (EditText)findViewById(R.id.Email);
mobile = (EditText)findViewById(R.id.etmobile);
mRegister = (Button)findViewById(R.id.register);
mRegister.setOnClickListener(this);
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
new CreateUser().execute();
}
class CreateUser extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(Register.this);
pDialog.setMessage("Creating User...");
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 = user.getText().toString();
String password = pass.getText().toString();
String mobile = mobile.getText().toString();
String email = email.getText().toString();
try {
// Building Parameters
List params = new ArrayList();
params.add(new BasicNameValuePair("username", username));
params.add(new BasicNameValuePair("password", password));
params.add(new BasicNameValuePair("email", email));
params.add(new BasicNameValuePair("mobile", mobile));
Log.d("request!", "starting");
//Posting user data to script
JSONObject json = jsonParser.makeHttpRequest(
REGISTER_URL, "POST", params);
// full json response
Log.d("Registering attempt", json.toString());
// json success element
success = json.getInt(TAG_SUCCESS);
if (success == 1) {
Log.d("User Created!", json.toString());
finish();
return json.getString(TAG_MESSAGE);
}else{
Log.d("Registering Failure!", json.getString(TAG_MESSAGE));
return json.getString(TAG_MESSAGE);
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(String file_url) {
// dismiss the dialog once product deleted
pDialog.dismiss();
if (file_url != null){
Toast.makeText(Register.this, file_url, Toast.LENGTH_LONG).show();
}
}
}
}
You will have to pass EditText values as args in the Async task.
String[] params = {user.getText().toString(),
pass.getText().toString(),
mobile.getText().toString(),
email.getText().toString()};
new CreateUser().execute(params);
You can play with the UI elements only in classes that run in UI thread. Activity or fragments etc.

RequestFactory and offline clients

I'm trying to create an application which is able to work even when network is down.
The idea is to store data returned from RequestFactory on the localStorage, and to use localStorage when network isn't available.
My problem - I'm not sure exactly how to differentiate between server errors(5XX, 4XX, ...) and network errors.
(I assume that on both cases my Receiver.onFailure() would be called, but I still don't know how to identify this situation)
Any help would be appreciated,
Thanks,
Gilad.
The response code when there is no internet connection is 0.
With RequestFactory to identify that the request was unsuccessful because of the network the response code has to be accessed. The RequestTransport seems like the best place.
Here is a rough implementation of an OfflineAwareRequestTransport.
public class OfflineAwareRequestTransport extends DefaultRequestTransport {
private final EventBus eventBus;
private boolean online = true;
public OfflineAwareRequestTransport(EventBus eventBus) {
this.eventBus = eventBus;
}
#Override
public void send(final String payload, final TransportReceiver receiver) {
// super.send(payload, proxy);
RequestBuilder builder = createRequestBuilder();
configureRequestBuilder(builder);
builder.setRequestData(payload);
builder.setCallback(createRequestCallback(receiver, payload));
try {
builder.send();
} catch (RequestException e) {
}
}
protected static final int SC_OFFLINE = 0;
protected RequestCallback createRequestCallback(final TransportReceiver receiver,
final String payload) {
return new RequestCallback() {
public void onError(Request request, Throwable exception) {
receiver.onTransportFailure(new ServerFailure(exception.getMessage()));
}
public void onResponseReceived(Request request, Response response) {
if (Response.SC_OK == response.getStatusCode()) {
String text = response.getText();
setOnline(true);
receiver.onTransportSuccess(text);
} else if (response.getStatusCode() == SC_OFFLINE) {
setOnline(false);
boolean processedOk = processPayload(payload);
receiver.onTransportFailure(new ServerFailure("You are offline!", OfflineReceiver.name,
"", !processedOk));
} else {
setOnline(true);
String message = "Server Error " + response.getStatusCode() + " " + response.getText();
receiver.onTransportFailure(new ServerFailure(message));
}
}
};
}

Show previous instance of RCP application

I had an rcp application which runs for only first run, when a user attempts to re-execute the application, second instance behaves as a client which encodes and sends its arguments over the socket to the first instance which acts as a server and then exits silently. The first instance receives and decodes that message, then behaves as if it had been invoked with those arguments.
so far so good i made internal protocol specification for passing arguments between two instances.
I could not bring the first instance(RCP application) to front. It is in minimized state only,
this is in continuation to my previous question
the change i made to previous post is start method of application class
public Object start(IApplicationContext context) throws Exception {
if (!ApplicationInstanceManager.registerInstance()) {
return IApplication.EXIT_OK;
}
ApplicationInstanceManager
.setApplicationInstanceListener(new ApplicationInstanceListener() {
public void newInstanceCreated() {
Display.getDefault().asyncExec(new Runnable() {
public void run() {
System.out.println("New instance detected...");
//Display.getCurrent().getActiveShell()
.forceActive();// this gives null
// pointer exception
// hence commented
}
});
}
});
Display display = PlatformUI.createDisplay();
try {
int returnCode = PlatformUI.createAndRunWorkbench(display,
new ApplicationWorkbenchAdvisor());
if (returnCode == PlatformUI.RETURN_RESTART)
return IApplication.EXIT_RESTART;
else
return IApplication.EXIT_OK;
} finally {
display.dispose();
}
}
below line is stopping me to bring Application to front
Display.getCurrent().getActiveShell().forceActive();
generates null pointer exception at getActiveShell()
how can i maximize the previous instance or bring it to front
I wrote an instance manager to restrict my RCP to a single instance.
Here's the code that goes in Application.java, in the start method:
if (!ApplicationInstanceManager.registerInstance()) {
return IApplication.EXIT_OK;
}
ApplicationInstanceManager
.setApplicationInstanceListener(new ApplicationInstanceListener() {
public void newInstanceCreated() {
Display.getDefault().asyncExec(new Runnable() {
public void run() {
if (DEBUG)
System.out.println("New instance detected...");
Display.getCurrent().getActiveShell().forceActive();
}
});
}
});
Here's the listener interface:
public interface ApplicationInstanceListener {
public void newInstanceCreated();
}
And here's the Manager class:
public class ApplicationInstanceManager {
private static final boolean DEBUG = true;
private static ApplicationInstanceListener subListener;
/** Randomly chosen, but static, high socket number */
public static final int SINGLE_INSTANCE_NETWORK_SOCKET = 44331;
/** Must end with newline */
public static final String SINGLE_INSTANCE_SHARED_KEY = "$$RabidNewInstance$$\n";
/**
* Registers this instance of the application.
*
* #return true if first instance, false if not.
*/
public static boolean registerInstance() {
// returnValueOnError should be true if lenient (allows app to run on
// network error) or false if strict.
boolean returnValueOnError = true;
// try to open network socket
// if success, listen to socket for new instance message, return true
// if unable to open, connect to existing and send new instance message,
// return false
try {
final ServerSocket socket = new ServerSocket(
SINGLE_INSTANCE_NETWORK_SOCKET, 10, InetAddress
.getLocalHost());
if (DEBUG)
System.out
.println("Listening for application instances on socket "
+ SINGLE_INSTANCE_NETWORK_SOCKET);
Thread instanceListenerThread = new InstanceListenerThread(socket);
instanceListenerThread.start();
// listen
} catch (UnknownHostException e) {
EclipseLogging.logError(RabidPlugin.getDefault(),
RabidPlugin.PLUGIN_ID, e);
return returnValueOnError;
} catch (IOException e) {
return portTaken(returnValueOnError, e);
}
return true;
}
private static boolean portTaken(boolean returnValueOnError, IOException e) {
if (DEBUG)
System.out.println("Port is already taken. "
+ "Notifying first instance.");
try {
Socket clientSocket = new Socket(InetAddress.getLocalHost(),
SINGLE_INSTANCE_NETWORK_SOCKET);
OutputStream out = clientSocket.getOutputStream();
out.write(SINGLE_INSTANCE_SHARED_KEY.getBytes());
out.close();
clientSocket.close();
System.out.println("Successfully notified first instance.");
return false;
} catch (UnknownHostException e1) {
EclipseLogging.logError(RabidPlugin.getDefault(),
RabidPlugin.PLUGIN_ID, e);
return returnValueOnError;
} catch (IOException e1) {
EclipseLogging
.logError(
RabidPlugin.getDefault(),
RabidPlugin.PLUGIN_ID,
"Error connecting to local port for single instance notification",
e);
return returnValueOnError;
}
}
public static void setApplicationInstanceListener(
ApplicationInstanceListener listener) {
subListener = listener;
}
private static void fireNewInstance() {
if (subListener != null) {
subListener.newInstanceCreated();
}
}
public static void main(String[] args) {
if (!ApplicationInstanceManager.registerInstance()) {
// instance already running.
System.out.println("Another instance of this application "
+ "is already running. Exiting.");
System.exit(0);
}
ApplicationInstanceManager
.setApplicationInstanceListener(new ApplicationInstanceListener() {
public void newInstanceCreated() {
System.out.println("New instance detected...");
// this is where your handler code goes...
}
});
}
public static class InstanceListenerThread extends Thread {
private ServerSocket socket;
public InstanceListenerThread(ServerSocket socket) {
this.socket = socket;
}
#Override
public void run() {
boolean socketClosed = false;
while (!socketClosed) {
if (socket.isClosed()) {
socketClosed = true;
} else {
try {
Socket client = socket.accept();
BufferedReader in = new BufferedReader(
new InputStreamReader(client.getInputStream()));
String message = in.readLine();
if (SINGLE_INSTANCE_SHARED_KEY.trim().equals(
message.trim())) {
if (DEBUG)
System.out.println("Shared key matched - "
+ "new application instance found");
fireNewInstance();
}
in.close();
client.close();
} catch (IOException e) {
socketClosed = true;
}
}
}
}
}
}
After your IApplication start up, you can also check and lock the OSGi instance location using org.eclipse.osgi.service.datalocation.Location.isSet() and org.eclipse.osgi.service.datalocation.Location.lock()
The location is usually retrieved from your Activator using code like:
public Location getInstanceLocation() {
if (locationTracker == null) {
Filter filter = null;
try {
filter = context.createFilter(Location.INSTANCE_FILTER);
} catch (InvalidSyntaxException e) {
// ignore this. It should never happen as we have tested the
// above format.
}
locationTracker = new ServiceTracker(context, filter, null);
locationTracker.open();
}
return (Location) locationTracker.getService();
}