I am learning from Video Tutorials and I've done exactly the same stuff that is on Video, the only difference is on the video they are doing it on Eclipse and I'm doing it on Android Studio (and I guess it should not affect the outcome). Anyway, what I am trying to do is to get raw XML data from Apple RSS to my Android app and display it on a text field...
I have already added :
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
to Manifest file
XML CODE:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent" android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin" tools:context=".MainActivity">
<TextView android:text="#string/hello_world" android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/textView1" />
</RelativeLayout>
Main Activity Code:
package com.example.haziqsheikhlocal.top10appsofios;
import android.os.AsyncTask;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class MainActivity extends ActionBarActivity {
TextView text;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
text =(TextView) findViewById(R.id.textView1);
new DownloadData().execute("http://ax.itunes.apple.com/WebObjects/MZStoreServices.woa/ws/RSS/topfreeapplications/limit=10/xml");
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#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) {
return true;
}
return super.onOptionsItemSelected(item);
}
private class DownloadData extends AsyncTask<String, Void, String>{
String myXmlData; // This String Will Contain Our XML Data
protected String doInBackground(String... urls) { // It Finds The First Url In BackGround;
try{
myXmlData = downloadXML(urls[0]); // It Downloads the first element in array Element;
}
catch (IOException e){
e.printStackTrace();
return "" ;
}
return null;
}
protected void onPostExecution(String result){
Log.d("OnPostExecute", myXmlData);
text.setText(myXmlData);
}
private String downloadXML (String theUrl) throws IOException {
int BUFFER_SIZE = 2000; // Buffer Size Constant
InputStream is = null; // Declaring Input Stream
String xmlContent = ""; // Creating empty xmlContent variable to store xml data from the web in furutre
try {
URL url = new URL(theUrl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection(); // Open The Connection with url given
conn.setReadTimeout(10000);// Read time Out 10seconds
conn.setConnectTimeout(15000);// connection timeout 15 s
conn.setRequestMethod("GET"); // Set the method for the URL request, one of: GET POST HEAD OPTIONS PUT DELETE TRACE are legal, subject to protocol restrictions.
conn.setDoInput(true);
int response = conn.getResponseCode();
Log.d("DownloadXML", "The Ressponse Code Is: " + response);
is = conn.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
int charRead;
char[] inputBuffer = new char[BUFFER_SIZE];
try {
while ((charRead = isr.read(inputBuffer)) > 0){
String readString = String.copyValueOf(inputBuffer, 0 , charRead);
xmlContent += readString;
inputBuffer = new char[BUFFER_SIZE];
}
return xmlContent;
}
catch (IOException e){
e.printStackTrace();
return null;
}
}finally {
if(is != null) {
is.close();
}
}
}
}
}
Device LogCat shows no Error & showing the response code 200.
Device LogCat:
03-25 22:53:09.237 1144-1144/com.example.haziqsheikhlocal.top10appsofios I/art﹕ Not late-enabling -Xcheck:jni (already on)
03-25 22:53:12.688 1144-1162/com.example.haziqsheikhlocal.top10appsofios D/OpenGLRenderer﹕ Render dirty regions requested: true
03-25 22:53:12.718 1144-1144/com.example.haziqsheikhlocal.top10appsofios D/﹕ HostConnection::get() New Host Connection established 0xa7b419c0, tid 1144
03-25 22:53:12.771 1144-1144/com.example.haziqsheikhlocal.top10appsofios D/Atlas﹕ Validating map...
03-25 22:53:13.058 1144-1162/com.example.haziqsheikhlocal.top10appsofios D/﹕ HostConnection::get() New Host Connection established 0xa7b41bf0, tid 1162
03-25 22:53:13.122 1144-1162/com.example.haziqsheikhlocal.top10appsofios I/OpenGLRenderer﹕ Initialized EGL, version 1.4
03-25 22:53:13.194 1144-1162/com.example.haziqsheikhlocal.top10appsofios D/OpenGLRenderer﹕ Enabling debug mode 0
03-25 22:53:13.256 1144-1162/com.example.haziqsheikhlocal.top10appsofios W/EGL_emulation﹕ eglSurfaceAttrib not implemented
03-25 22:53:13.256 1144-1162/com.example.haziqsheikhlocal.top10appsofios W/OpenGLRenderer﹕ Failed to set EGL_SWAP_BEHAVIOR on surface 0xa7b3ba40, error=EGL_SUCCESS
03-25 22:53:14.100 1144-1156/com.example.haziqsheikhlocal.top10appsofios I/art﹕ Background sticky concurrent mark sweep GC freed 3424(291KB) AllocSpace objects, 0(0B) LOS objects, 14% free, 968KB/1135KB, paused 1.420ms total 737.728ms
03-25 22:53:15.313 1144-1161/com.example.haziqsheikhlocal.top10appsofios D/DownloadXML﹕ The Ressponse Code Is: 200
ADB LogCat shows this Error:
DeviceMonitor: Adb connection Error:An existing connection was forcibly closed by the remote host
ddms: null
java.nio.BufferOverflowException
at java.nio.HeapByteBuffer.put(HeapByteBuffer.java:206)
at com.android.ddmlib.JdwpPacket.movePacket(JdwpPacket.java:235)
at com.android.ddmlib.Debugger.sendAndConsume(Debugger.java:347)
at com.android.ddmlib.Client.forwardPacketToDebugger(Client.java:698)
at com.android.ddmlib.MonitorThread.processClientActivity(MonitorThread.java:344)
at com.android.ddmlib.MonitorThread.run(MonitorThread.java:263)
ddms: Client data packet exceeded maximum buffer size [Client pid: 1272]
DeviceMonitor: Adb rejected connection to client '1537': closed
DeviceMonitor: Adb connection Error:An existing connection was forcibly closed by the remote host
DeviceMonitor: Connection attempts: 1
DeviceMonitor: Connection attempts: 2
DeviceMonitor: Connection attempts: 3
DeviceMonitor: Connection attempts: 4
PropertyFetcher: AdbCommandRejectedException getting properties for device emulator-5554: device offline
PropertyFetcher: AdbCommandRejectedException getting properties for device emulator-5554: device offline
PropertyFetcher: AdbCommandRejectedException getting properties for device emulator-5554: device offline
PropertyFetcher: AdbCommandRejectedException getting properties for device emulator-5554: device offline
PropertyFetcher: AdbCommandRejectedException getting properties for device emulator-5554: device offline
PropertyFetcher: AdbCommandRejectedException getting properties for device emulator-5554: device offline
PropertyFetcher: AdbCommandRejectedException getting properties for device emulator-5554: device offline
PropertyFetcher: AdbCommandRejectedException getting properties for device emulator-5554: device offline
What I did to solve this is I went to terminal and used adb kill-server and then adb start-server. I ran the emulator again but still no luck !
Help me please .
Note: Same is happening when I am using gennymotion and I am able to use emulators browser and surf website on it..
Related
I am making android app and trying to connect to java servlet to use as backend but it's not working. When i press logIn button, it shows wrong password. It's not connecting to java servlet and checking password from db. Java project is deployed on Tomcat.
here is code of Android Activity , LoginActivity.java
import android.content.Intent;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class LoginActivity extends AppCompatActivity {
// UI references
private EditText emailEditText;
private EditText passwordEditText;
//private Button loginButton;
private UserLoginTask mAuthTask = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
emailEditText = (EditText) findViewById(R.id.emailEditText);
passwordEditText = (EditText) findViewById(R.id.passwordEditText);
Log.e("tag", "onCreate: ");
}
/**
* Attempts to sign in or register the account specified by the login form.
* If there are form errors (invalid email, missing fields, etc.), the
* errors are presented and no actual login attempt is made.
*/
public void login(View view) {
if (mAuthTask != null) {
return;
}
// Reset errors.
emailEditText.setError(null);
passwordEditText.setError(null);
// Store values at the time of the login attempt.
String email = emailEditText.getText().toString();
String password = passwordEditText.getText().toString();
boolean cancel = false;
View focusView = null;
// Check for a valid password, if the user entered one.
// Check for a valid email address.
if (TextUtils.isEmpty(email)) {
emailEditText.setError(getString(R.string.email_empty_error));
focusView = emailEditText;
cancel = true;
} else if (!isEmailValid(email)) {
emailEditText.setError(getString(R.string.email_error));
focusView = emailEditText;
cancel = true;
}
if (cancel) {
focusView.requestFocus();
} else {
Log.e("tag", "doInBackground: " );
mAuthTask = new UserLoginTask(email, password);
mAuthTask.execute((Void) null);
}
}
/**
* Represents an asynchronous login/registration task used to authenticate
* the user.
*/
public class UserLoginTask extends AsyncTask<Void, Void, Boolean> {
private final String mEmail;
private final String mPassword;
UserLoginTask(String email, String password) {
mEmail = email;
mPassword = password;
}
#Override
protected Boolean doInBackground(Void... params) {
// TODO: attempt authentication against a network service.
Log.e("tag", "doInBackground: " );
StringBuilder sb = new StringBuilder();
JSONObject json = null;
try {
URL url = new URL("http://10.0.2.2:8080/cart/LoginServletAndroid?email="
+mEmail+"&pass="+mPassword);
// Simulate network access.
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.setRequestProperty("Accept", "application/json");
urlConnection.connect();
Log.e("tag", "doInBackground: " );
int status = urlConnection.getResponseCode();
switch (status) {
case 200:
Log.e("tag", "doInBackground: status 200" );
break;
case 201:
Log.e("tag", "doInBackground: status 201" );
BufferedReader br = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
String line;
while ((line = br.readLine()) != null) {
sb.append(line + "\n");
}
br.close();
json = new JSONObject(sb.toString());
if(json.getBoolean("auth"))
return true;
}
} catch (Exception e) {
e.printStackTrace();
return false;
}
return false;
}
#Override
protected void onPostExecute(final Boolean success) {
Log.e("tag", "doInBackground: " );
mAuthTask = null;
if (success) {
Intent intent = new Intent(getApplicationContext(), MovieSearchActivity.class);
startActivity(intent);
} else {
passwordEditText.setError(getString(R.string.password_error));
passwordEditText.requestFocus();
}
}
#Override
protected void onCancelled() {
mAuthTask = null;
}
}
private boolean isEmailValid(String email)
{
return email.contains("#");
}
}
activity_login.xml :
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/activity_login"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.example.along.myfablix.LoginActivity"
android:orientation="vertical">
<TextView
android:text="#string/login_page"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:id="#+id/textView"
android:gravity="center"
android:layout_gravity="center_horizontal"
android:textSize="28sp"
android:textStyle="normal|bold"
android:textColor="#color/colorPrimary" />
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="textEmailAddress"
android:ems="10"
android:id="#+id/emailEditText"
android:layout_gravity="center_horizontal"
android:hint="#string/email_text" />
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="textPassword"
android:ems="10"
android:id="#+id/passwordEditText"
android:layout_gravity="center_horizontal"
android:hint="#string/password_text" />
<Button
android:text="#string/login_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/loginButton"
android:gravity="center"
android:layout_gravity="center_horizontal"
android:onClick="login" />
</LinearLayout>
This is java servlet, LoginServletAndoid.java:
package Servlet;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.jasypt.util.password.StrongPasswordEncryptor;
import com.google.gson.Gson;
import helper.CartItem;
import helper.Customer;
import helper.LoginResponse;
/**
* Servlet implementation class LoginServletAndroid
*/
#WebServlet("/LoginServletAndroid")
public class LoginServletAndroid extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public LoginServletAndroid() {
super();
// TODO Auto-generated constructor stub
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String loginUser = "root";
String loginPasswd = "root";
String loginUrl = "jdbc:mysql://localhost:3306/moviedb";
LoginResponse auth = new LoginResponse();
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
Connection connection = DriverManager.getConnection(loginUrl,loginUser,loginPasswd);
Statement statement = connection.createStatement();
String email = request.getParameter("email");
String password = request.getParameter("pass");
System.out.println(email);
System.out.println(password);
String query ="SELECT * from customers where email=?";
PreparedStatement pst=connection.prepareStatement(query);
pst.setString(1, email);
ResultSet result = pst.executeQuery();
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
boolean success = false;
if(result.next()) {
Customer cust= new Customer();
HttpSession session = request.getSession();//save user email in session scope
ArrayList<CartItem> items = new ArrayList<CartItem>();
cust.setId(result.getInt(1));
cust.setFname(result.getString(2));
cust.setLname(result.getString(3));
cust.setCcid(result.getString(4));
cust.setAddress(result.getString(5));
cust.setEmail(result.getString(6));
cust.setPassword(result.getString(7));
session.setAttribute("items", items);
session.setAttribute("email", email);
session.setAttribute("cust", cust);
// get the encrypted password from the database
String encryptedPassword = result.getString("password");
System.out.println(encryptedPassword);
// use the same encryptor to compare the user input password with encrypted password stored in DB
success = new StrongPasswordEncryptor().checkPassword(password, encryptedPassword);
System.out.println(success);
if(success) {
auth.setAuth(true);
String json = new Gson().toJson(auth);
response.getWriter().write(json);
}
else
{
auth.setAuth(false);
String json = new Gson().toJson(auth);
response.getWriter().write(json);
}
}
}
catch (Exception e) {
String json = new Gson().toJson(e.getMessage());
response.getWriter().write(json);
}
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
}
This is logcat when i run the app.
06-02 15:02:00.303 5764-5764/? E/tag: onCreate:
06-02 15:02:00.309 2061-2061/com.bluestacks.appguidance D/GuidanceScreen..AppLaunchReceiver: same as previous package, returning com.example.along.myfablix
06-02 15:02:00.348 1809-2009/system_process D/ActivityManager: cleanUpApplicationRecord -- 5666
06-02 15:02:00.405 1809-1819/system_process I/art: Background partial concurrent mark sweep GC freed 18144(3MB) AllocSpace objects, 265(5MB) LOS objects, 33% free, 8MB/13MB, paused 1.053ms total 128.891ms
06-02 15:02:00.405 5764-5811/? I/OpenGLRenderer: Initialized EGL, version 1.4
06-02 15:02:00.405 5764-5811/? D/OpenGLRenderer: Swap behavior 1
06-02 15:02:00.405 5764-5811/? I/PGA: PgaSocketInit: opened /dev/bstpgaipc: fd = 45
Attempting to create new SOCKET connection pid = 5764, tid = 5811
06-02 15:02:00.408 5764-5811/? I/PGA: PgaSocketInitClientPgaIpc: data mapped to 0xaa1c0000
New SOCKET connection: com.example.along.myfablix (pid 5764, tid 5811)
06-02 15:02:00.424 5779-5805/? D/ApplicationLoaders: ignored Vulkan layer search path /data/priv-downloads/com.google.android.gms/lib/x86:/system/fake-libs:/data/priv-downloads/com.google.android.gms/com.google.android.gms.apk!/lib/x86:/system/lib:/vendor/lib:/data/downloads:/data/priv-downloads for namespace 0xb654e090
06-02 15:02:00.432 5764-5764/? W/art: Before Android 4.1, method int android.support.v7.widget.ListViewCompat.lookForSelectablePosition(int, boolean) would have incorrectly overridden the package-private method in android.widget.ListView
06-02 15:02:00.704 1809-1830/system_process D/WindowManager: topDisplayedActivityInfo, appToken: Token{3662662 ActivityRecord{1d2c12d u0 com.example.along.myfablix/.LoginActivity t21}}
06-02 15:02:00.709 1809-3014/system_process D/InputMethodManagerService: packageName=com.example.along.myfablix, activityName=.LoginActivity
06-02 15:02:00.722 1809-3011/system_process D/InputMethodManagerService: packageName=com.example.along.myfablix, activityName=.LoginActivity
ime_enabled = true is same as last value, no change
06-02 15:02:00.734 1809-1830/system_process I/ActivityManager: Displayed com.example.along.myfablix/.LoginActivity: +883ms
06-02 15:02:00.753 1907-1907/com.android.inputmethod.latin I/LatinIME: Starting input. Cursor position = -1,-1
06-02 15:02:00.769 1809-1809/system_process D/NotificationService: In writeNotificationInfo: pkgName android
06-02 15:02:00.774 1975-1975/com.bluestacks.BstCommandProcessor D/BstCommandProcessor-Service: startService called with arg: notification
New Notification has been observed, informing frontend now
06-02 15:02:00.789 1907-1907/com.android.inputmethod.latin I/LatinIME: Starting input. Cursor position = 0,0
06-02 15:02:00.789 1809-1809/system_process D/NotificationService: In writeNotificationInfo: pkgName android
06-02 15:02:00.792 1809-1809/system_process D/NotificationService: In writeNotificationInfo: pkgName android
06-02 15:02:00.794 1975-1975/com.bluestacks.BstCommandProcessor D/BstCommandProcessor-Service: startService called with arg: notification
New Notification has been observed, informing frontend now
06-02 15:02:00.810 1975-1975/com.bluestacks.BstCommandProcessor D/BstCommandProcessor-Service: startService called with arg: notification
New Notification has been observed, informing frontend now
06-02 15:02:00.835 2482-2822/com.google.android.gms I/Icing: Indexing 4A5DADA6E9D2F130C1CBECC0FA1E6BDE3BFAF4A4 from com.google.android.gms
06-02 15:02:00.872 2482-2822/com.google.android.gms I/Icing: Indexing done 4A5DADA6E9D2F130C1CBECC0FA1E6BDE3BFAF4A4
06-02 15:02:00.996 1809-3014/system_process W/art: Long monitor contention with owner Binder:1809_4 (2009) at void com.android.server.am.ActivityManagerService.activityStopped(android.os.IBinder, android.os.Bundle, android.os.PersistableBundle, java.lang.CharSequence)(ActivityManagerService.java:7091) waiters=0 in int com.android.server.am.ActivityManagerService.stopService(android.app.IApplicationThread, android.content.Intent, java.lang.String, int) for 122ms
06-02 15:02:04.421 2375-2375/com.google.android.gms.persistent I/WearableService: Wearable Services stopping
06-02 15:02:08.655 1809-2013/system_process I/ActivityManager: Killing 5249:com.android.vending/u0a2 (adj 906): empty #5
06-02 15:02:08.709 2406-2406/? D/appstatsd: inotify event: 00000008
06-02 15:02:08.712 2406-2406/? D/appstatsd: File copied successfully
06-02 15:02:08.713 1809-2009/system_process D/ActivityManager: cleanUpApplicationRecord -- 5249
06-02 15:02:09.117 1975-5822/com.bluestacks.BstCommandProcessor D/BstCommandProcessor-httpd: command: unmuteappplayer
06-02 15:02:09.124 1975-5822/com.bluestacks.BstCommandProcessor D/BstCommandProcessor-Application: in isSystemReady, isBootCompleted true External storage status: mounted External storage dir :/storage/emulated/0 isExternalStorageRemovable:false
returning from waitForSystemReady, isSystemReady = true
06-02 15:02:09.124 1975-5822/com.bluestacks.BstCommandProcessor D/BstCommandProcessor-httpd: response: {"result":"ok"}
06-02 15:02:09.142 1975-5823/com.bluestacks.BstCommandProcessor D/BstCommandProcessor-httpd: command: runex com.example.along.myfablix/com.example.along.myfablix.LoginActivity
06-02 15:02:09.147 1975-5823/com.bluestacks.BstCommandProcessor D/BstCommandProcessor-Application: in isSystemReady, isBootCompleted true External storage status: mounted External storage dir :/storage/emulated/0 isExternalStorageRemovable:false
returning from waitForSystemReady, isSystemReady = true
06-02 15:02:09.147 1975-5823/com.bluestacks.BstCommandProcessor D/BstCommandProcessor-CommandHandler: gamemanager compatible mode
recentTask.size(): 2
06-02 15:02:09.148 1975-5823/com.bluestacks.BstCommandProcessor D/BstCommandProcessor-CommandHandler: pkg found in recent tasks
moving 21 to front
06-02 15:02:09.150 1975-5823/com.bluestacks.BstCommandProcessor E/Sensor-AccelerometerUI: java.io.IOException: Connection refused
06-02 15:02:09.158 1975-5823/com.bluestacks.BstCommandProcessor D/BstCommandProcessor-CommandHandler: Sending startService intent with data: Intent { act=com.bluestacks.home.svc pkg=com.bluestacks.home }
Broadcasting START_APP intent with data: {"package":"com.example.along.myfablix","isArmApp":false} isArmApp: false
06-02 15:02:09.158 1975-5823/com.bluestacks.BstCommandProcessor D/BstCommandProcessor-httpd: response: {"result":"ok"}
06-02 15:02:11.068 1809-3343/system_process D/InputMethodManagerService: packageName=com.example.along.myfablix, activityName=.LoginActivity
ime_enabled = true is same as last value, no change
06-02 15:02:11.077 1809-1809/system_process D/NotificationService: In writeNotificationInfo: pkgName android
06-02 15:02:11.079 1975-1975/com.bluestacks.BstCommandProcessor D/BstCommandProcessor-Service: startService called with arg: notification
New Notification has been observed, informing frontend now
06-02 15:02:12.452 1975-5682/com.bluestacks.BstCommandProcessor D/BstCommandProcessor-Application: INSTALL_APP event sent to Agent for pkg :com.example.along.myfablixat time :Sat Jun 02 15:02:12 GMT+05:00 2018
06-02 15:02:13.791 1975-5821/com.bluestacks.BstCommandProcessor E/BstCommandProcessor-Application: Error encountered while deleting file
06-02 15:02:15.002 1809-1877/system_process W/AudioTrack: AUDIO_OUTPUT_FLAG_FAST denied by client; transfer 4, track 44100 Hz, output 48000 Hz
06-02 15:02:15.007 1809-3011/system_process D/InputMethodManagerService: packageName=com.example.along.myfablix, activityName=.LoginActivity
ime_enabled = true is same as last value, no change
06-02 15:02:15.010 5764-5764/? W/IInputConnectionWrapper: finishComposingText on inactive InputConnection
06-02 15:02:15.011 1907-1907/com.android.inputmethod.latin I/LatinIME: Starting input. Cursor position = 0,0
06-02 15:02:15.014 1809-1809/system_process D/NotificationService: In writeNotificationInfo: pkgName android
06-02 15:02:15.018 1975-1975/com.bluestacks.BstCommandProcessor D/BstCommandProcessor-Service: startService called with arg: notification
New Notification has been observed, informing frontend now
06-02 15:02:15.206 1542-1570/? I/audio_hw_primary: choose pcmC0D0p for 0
06-02 15:02:17.899 5764-5764/? E/tag: doInBackground:
06-02 15:02:17.914 5764-5827/? E/tag: doInBackground:
06-02 15:02:17.925 5764-5827/? D/NetworkSecurityConfig: No Network Security Config specified, using platform default
06-02 15:02:17.932 1542-1570/? D/AudioFlinger: mixer(0xa72174c0) throttle end: throttle time(35)
06-02 15:02:18.933 5764-5827/? W/System.err: java.net.ConnectException: Connection refused
at java.net.PlainSocketImpl.socketConnect(Native Method)
at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:334)
at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:196)
at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:178)
at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:356)
at java.net.Socket.connect(Socket.java:605)
at com.android.okhttp.internal.Platform.connectSocket(Platform.java:113)
at com.android.okhttp.Connection.connectSocket(Connection.java:196)
at com.android.okhttp.Connection.connect(Connection.java:172)
at com.android.okhttp.Connection.connectAndSetOwner(Connection.java:367)
at com.android.okhttp.OkHttpClient$1.connectAndSetOwner(OkHttpClient.java:130)
at com.android.okhttp.internal.http.HttpEngine.connect(HttpEngine.java:329)
at com.android.okhttp.internal.http.HttpEngine.sendRequest(HttpEngine.java:246)
at com.android.okhttp.internal.huc.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:457)
at com.android.okhttp.internal.huc.HttpURLConnectionImpl.connect(HttpURLConnectionImpl.java:126)
at com.example.along.myfablix.LoginActivity$UserLoginTask.doInBackground(LoginActivity.java:112)
at com.example.along.myfablix.LoginActivity$UserLoginTask.doInBackground(LoginActivity.java:86)
at android.os.AsyncTask$2.call(AsyncTask.java:305)
at java.util.concurrent.FutureTask.run(FutureTask.java:237)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:243)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1133)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:607)
at java.lang.Thread.run(Thread.java:761)
06-02 15:02:18.935 5764-5764/? E/tag: doInBackground:
06-02 15:02:22.801 2375-4730/com.google.android.gms.persistent E/WakeLock: release without a matched acquire!
06-02 15:02:22.804 1809-3011/system_process I/ActivityManager: Killing 5695:com.google.android.partnersetup/u0a1 (adj 906): empty #5
06-02 15:02:22.829 1809-1821/system_process D/ActivityManager: cleanUpApplicationRecord -- 5695
06-02 15:02:24.634 2375-4735/com.google.android.gms.persistent E/WakeLock: release without a matched acquire!
06-02 15:02:24.637 2375-4735/com.google.android.gms.persistent W/GCM: Resetting heartbeat counters (at min), good=0 bad=2
06-02 15:02:24.638 1809-3347/system_process D/ConnectivityService: reportNetworkConnectivity(100, false) by 10000
06-02 15:02:24.638 1809-1887/system_process D/NetworkMonitor/NetworkAgentInfo [WIFI () - 100]: Forcing reevaluation for UID 10000
06-02 15:02:24.645 1809-5829/system_process D/NetworkMonitor/NetworkAgentInfo [WIFI () - 100]: PROBE_DNS OK 3ms, connectivitycheck.gstatic.com=74.125.200.94
06-02 15:02:24.649 1809-5828/system_process D/NetworkMonitor/NetworkAgentInfo [WIFI () - 100]: PROBE_DNS OK 7ms, www.google.com=216.58.207.4
06-02 15:02:26.410 1809-5829/system_process D/NetworkMonitor/NetworkAgentInfo [WIFI () - 100]: PROBE_HTTP http://connectivitycheck.gstatic.com/generate_204 time=1764ms ret=204 headers={null=[HTTP/1.1 204 No Content], Content-Length=[0], Date=[Sat, 02 Jun 2018 10:02:27 GMT], X-Android-Received-Millis=[1527933746410], X-Android-Response-Source=[NETWORK 204], X-Android-Selected-Protocol=[http/1.1], X-Android-Sent-Millis=[1527933745838]}
06-02 15:02:27.845 1809-5828/system_process D/NetworkMonitor/NetworkAgentInfo [WIFI () - 100]: PROBE_HTTPS https://www.google.com/generate_204 time=3193ms ret=204 headers={null=[HTTP/1.1 204 No Content], Alt-Svc=[quic=":443"; ma=2592000; v="43,42,41,39,35"], Content-Length=[0], Date=[Sat, 02 Jun 2018 10:02:26 GMT], X-Android-Received-Millis=[1527933747844], X-Android-Response-Source=[NETWORK 204], X-Android-Selected-Protocol=[http/1.1], X-Android-Sent-Millis=[1527933744652]}
06-02 15:02:28.637 1809-1887/system_process D/NetworkMonitor/NetworkAgentInfo [WIFI () - 100]: PROBE_FALLBACK http://www.google.com/gen_204 time=995ms ret=204 headers={null=[HTTP/1.1 204 No Content], Content-Length=[0], Content-Type=[text/html; charset=UTF-8], Date=[Sat, 02 Jun 2018 10:02:30 GMT], P3P=[CP="This is not a P3P policy! See g.co/p3phelp for more info."], Server=[gws], Set-Cookie=[NID=131=QncJ2SQd2g2FVKA4Wduj0W-ud-XATCGEeMd-8IJnlqhzj13ib7r1sc51LBvDb9Epk5QNUZ-avYwathoI47Vg172zHrdxOc4LwBFr8aW73asymhvElP2eln9wFnsMMW0i; expires=Sun, 02-Dec-2018 10:02:30 GMT; path=/; domain=.google.com; HttpOnly], X-Android-Received-Millis=[1527933748636], X-Android-Response-Source=[NETWORK 204], X-Android-Selected-Protocol=[http/1.1], X-Android-Sent-Millis=[1527933748112], X-Frame-Options=[SAMEORIGIN], X-XSS-Protection=[1; mode=block]}
06-02 15:02:28.640 1809-1870/system_process D/ConnectivityService: NetworkAgentInfo [WIFI () - 100] validation passed
i have a problem in running my App on the simulator or even the real android phone even there are no syntax errors, when i run the vertual phone it opens but the application don't work and i get the message "can't initialize HUB" as in the image, and i get on console the following logs :
08-14 19:40:23.271 2342-2357/com.thalmic.android.sample.helloworld V/RenderScript: 0xae4be000 Launching thread(s), CPUs 2
08-14 19:40:24.090 2342-2357/com.thalmic.android.sample.helloworld E/Surface: getSlotFromBufferLocked: unknown buffer: 0xae4b12a0
08-14 23:40:24.165 5064-5078/com.thalmic.android.sample.helloworld D/OpenGLRenderer: Use EGL_SWAP_BEHAVIOR_PRESERVED: true
[ 08-14 23:40:24.192 5064: 5064 D/ ]
HostConnection::get() New Host Connection established 0xaa9e81f0, tid 5064
08-14 23:40:24.556 5064-5078/com.thalmic.android.sample.helloworld I/OpenGLRenderer: Initialized EGL, version 1.4
08-14 23:40:25.289 5064-5078/com.thalmic.android.sample.helloworld V/RenderScript: 0xae5b7000 Launching thread(s), CPUs 2
08-14 23:40:25.433 5064-5078/com.thalmic.android.sample.helloworld E/Surface: getSlotFromBufferLocked: unknown buffer: 0xae4b12a0
08-14 23:40:28.898 5064-5070/com.thalmic.android.sample.helloworld W/art: Suspending all threads took: 65.953ms
08-14 23:40:28.950 5064-5064/com.thalmic.android.sample.helloworld E/Hub: Bluetooth not supported
08-14 23:40:30.344 5064-5064/com.thalmic.android.sample.helloworld I/Choreographer: Skipped 52 frames! The application may be doing too much work on its main thread.
08-14 23:40:31.042 5064-5078/com.thalmic.android.sample.helloworld E/Surface: getSlotFromBufferLocked: unknown buffer: 0xae4b10e0
my source code is :
/*
* Copyright (C) 2014 Thalmic Labs Inc.
* Distributed under the Myo SDK license agreement. See LICENSE.txt for details.
*/
package com.thalmic.android.sample.helloworld;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.TextView;
import android.widget.Toast;
import com.thalmic.myo.AbstractDeviceListener;
import com.thalmic.myo.Arm;
import com.thalmic.myo.DeviceListener;
import com.thalmic.myo.Hub;
import com.thalmic.myo.Myo;
import com.thalmic.myo.Pose;
import com.thalmic.myo.Quaternion;
import com.thalmic.myo.XDirection;
import com.thalmic.myo.scanner.ScanActivity;
public class HelloWorldActivity extends Activity {
private TextView mLockStateView;
private TextView mTextView;
// Classes that inherit from AbstractDeviceListener can be used to receive events from Myo devices.
// If you do not override an event, the default behavior is to do nothing.
private DeviceListener mListener = new AbstractDeviceListener() {
// onConnect() is called whenever a Myo has been connected.
#Override
public void onConnect(Myo myo, long timestamp) {
// Set the text color of the text view to cyan when a Myo connects.
mTextView.setTextColor(Color.CYAN);
}
// onDisconnect() is called whenever a Myo has been disconnected.
#Override
public void onDisconnect(Myo myo, long timestamp) {
// Set the text color of the text view to red when a Myo disconnects.
mTextView.setTextColor(Color.RED);
}
// onArmSync() is called whenever Myo has recognized a Sync Gesture after someone has put it on their
// arm. This lets Myo know which arm it's on and which way it's facing.
#Override
public void onArmSync(Myo myo, long timestamp, Arm arm, XDirection xDirection) {
mTextView.setText(myo.getArm() == Arm.LEFT ? R.string.arm_left : R.string.arm_right);
}
// onArmUnsync() is called whenever Myo has detected that it was moved from a stable position on a person's arm after
// it recognized the arm. Typically this happens when someone takes Myo off of their arm, but it can also happen
// when Myo is moved around on the arm.
#Override
public void onArmUnsync(Myo myo, long timestamp) {
mTextView.setText(R.string.hello_world);
}
// onUnlock() is called whenever a synced Myo has been unlocked. Under the standard locking
// policy, that means poses will now be delivered to the listener.
#Override
public void onUnlock(Myo myo, long timestamp) {
mLockStateView.setText(R.string.unlocked);
}
// onLock() is called whenever a synced Myo has been locked. Under the standard locking
// policy, that means poses will no longer be delivered to the listener.
#Override
public void onLock(Myo myo, long timestamp) {
mLockStateView.setText(R.string.locked);
}
// onOrientationData() is called whenever a Myo provides its current orientation,
// represented as a quaternion.
#Override
public void onOrientationData(Myo myo, long timestamp, Quaternion rotation) {
// Calculate Euler angles (roll, pitch, and yaw) from the quaternion.
float roll = (float) Math.toDegrees(Quaternion.roll(rotation));
float pitch = (float) Math.toDegrees(Quaternion.pitch(rotation));
float yaw = (float) Math.toDegrees(Quaternion.yaw(rotation));
// Adjust roll and pitch for the orientation of the Myo on the arm.
if (myo.getXDirection() == XDirection.TOWARD_ELBOW) {
roll *= -1;
pitch *= -1;
}
// Next, we apply a rotation to the text view using the roll, pitch, and yaw.
mTextView.setRotation(roll);
mTextView.setRotationX(pitch);
mTextView.setRotationY(yaw);
}
// onPose() is called whenever a Myo provides a new pose.
#Override
public void onPose(Myo myo, long timestamp, Pose pose) {
// Handle the cases of the Pose enumeration, and change the text of the text view
// based on the pose we receive.
switch (pose) {
case UNKNOWN:
mTextView.setText(getString(R.string.hello_world));
break;
case REST:
case DOUBLE_TAP:
int restTextId = R.string.hello_world;
switch (myo.getArm()) {
case LEFT:
restTextId = R.string.arm_left;
break;
case RIGHT:
restTextId = R.string.arm_right;
break;
}
mTextView.setText(getString(restTextId));
break;
case FIST:
mTextView.setText(getString(R.string.pose_fist));
break;
case WAVE_IN:
mTextView.setText(getString(R.string.pose_wavein));
break;
case WAVE_OUT:
mTextView.setText(getString(R.string.pose_waveout));
break;
case FINGERS_SPREAD:
mTextView.setText(getString(R.string.pose_fingersspread));
break;
}
if (pose != Pose.UNKNOWN && pose != Pose.REST) {
// Tell the Myo to stay unlocked until told otherwise. We do that here so you can
// hold the poses without the Myo becoming locked.
myo.unlock(Myo.UnlockType.HOLD);
// Notify the Myo that the pose has resulted in an action, in this case changing
// the text on the screen. The Myo will vibrate.
myo.notifyUserAction();
} else {
// Tell the Myo to stay unlocked only for a short period. This allows the Myo to
// stay unlocked while poses are being performed, but lock after inactivity.
myo.unlock(Myo.UnlockType.TIMED);
}
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_hello_world);
mLockStateView = (TextView) findViewById(R.id.lock_state);
mTextView = (TextView) findViewById(R.id.text);
// First, we initialize the Hub singleton with an application identifier.
Hub hub = Hub.getInstance();
if (!hub.init(this, getPackageName())) {
// We can't do anything with the Myo device if the Hub can't be initialized, so exit.
Toast.makeText(this, "Couldn't initialize Hub", Toast.LENGTH_SHORT).show();
finish();
return;
}
// Next, register for DeviceListener callbacks.
hub.addListener(mListener);
}
#Override
protected void onDestroy() {
super.onDestroy();
// We don't want any callbacks when the Activity is gone, so unregister the listener.
Hub.getInstance().removeListener(mListener);
if (isFinishing()) {
// The Activity is finishing, so shutdown the Hub. This will disconnect from the Myo.
Hub.getInstance().shutdown();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (R.id.action_scan == id) {
onScanActionSelected();
return true;
}
return super.onOptionsItemSelected(item);
}
private void onScanActionSelected() {
// Launch the ScanActivity to scan for Myos to connect to.
Intent intent = new Intent(this, ScanActivity.class);
startActivity(intent);
}
}
You are trying to establish a connection to your Myo. The hub can't be initialished. According to the documentation this occurs when your Android device doesn't support Bluetooth Low Energy. Bluetooth is not supported in the emulator, because of this the initialization will fail.
Creating a connection will also fail if the applicationIdentifier is not properly formatted, but in that case you should get an IllegalArgumentException.
Device recommended be Android 4.3 (Jelly Bean) and up and device must have Bluetooth radio that supports Bluetooth 4.0 LE! Emulator not supported Bluetooth 4.0 LE. You say your Android application is not opening on emulator and real phone. Check on your real phone version of Android and if phone support Bluetooth 4.0 LE. Check FAQs from Myo support: What devices is the Myo armband compatible with.
It is always giving Incorrect credentials, I have double checked the database ,Is there some issue with the code . I am new to android studio,
Any kind of help will be appreciated.
MainActivity
package com.tarun.proxy_maar;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity {
private EditText editTextUserName;
private EditText editTextPassword;
public static final String USER_NAME = "USERNAME";
String username;
String password;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editTextUserName = (EditText) findViewById(R.id.editTextUserName);
editTextPassword = (EditText) findViewById(R.id.editTextPassword);
}
public void invokeLogin(View view){
username = editTextUserName.getText().toString();
password = editTextPassword.getText().toString();
login(username,password);
}
private void login(final String username, String password) {
class LoginAsync extends AsyncTask<String, Void, String>{
private Dialog loadingDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
loadingDialog = ProgressDialog.show(MainActivity.this, "Please wait", "Loading...");
}
#Override
protected String doInBackground(String... params) {
String uname = params[0];
String pass = params[1];
InputStream is = null;
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("username", uname));
nameValuePairs.add(new BasicNameValuePair("password", pass));
String result = null;
try{
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(
"http://shaadi.web44.net/hello.php");
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpClient.execute(httpPost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
result = sb.toString();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return result;
}
#Override
protected void onPostExecute(String result){
String s = result.trim();
loadingDialog.dismiss();
if(s.equalsIgnoreCase("success")){
Intent intent = new Intent(MainActivity.this, UserProfile.class);
intent.putExtra(USER_NAME, username);
finish();
startActivity(intent);
}else {
Toast.makeText(getApplicationContext(), "Invalid User Name or Password", Toast.LENGTH_LONG).show();
}
}
}
LoginAsync la = new LoginAsync();
la.execute(username, password);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#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) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
PHP SCRIPT ON WEBSERVER
<?php
define('HOST','host');
define('USER','user');
define('PASS','password');
define('DB','database');
$con = mysqli_connect(HOST,USER,PASS,DB);
$username = $_POST['username'];
$password = $_POST['password'];
$sql = "select * from login where username='$username' and password='$password'";
$res = mysqli_query($con,$sql);
$check = mysqli_fetch_array($res);
if(isset($check)){
echo 'success';
}else{
echo 'failure';
}
mysqli_close($con);
?>
Logcat
10-11 07:57:42.852 28481-28481/? I/art﹕ Not late-enabling -Xcheck:jni (already on)
10-11 07:57:42.852 28481-28481/? I/art﹕ Late-enabling JIT
10-11 07:57:42.856 28481-28481/? I/art﹕ JIT created with code_cache_capacity=2MB compile_threshold=1000
10-11 07:57:42.897 28481-28488/? E/art﹕ Failed writing handshake bytes (-1 of 14): Broken pipe
10-11 07:57:42.897 28481-28488/? I/art﹕ Debugger is no longer active
10-11 07:57:42.900 28481-28481/? W/System﹕ ClassLoader referenced unknown path: /data/app/com.tarun.proxy_maar-2/lib/x86
10-11 07:57:43.079 28481-28504/? D/OpenGLRenderer﹕ Use EGL_SWAP_BEHAVIOR_PRESERVED: true
10-11 07:57:43.082 28481-28481/? D/﹕ HostConnection::get() New Host Connection established 0xabe7d170, tid 28481
10-11 07:57:43.135 28481-28504/? D/﹕ HostConnection::get() New Host Connection established 0xabe7d480, tid 28504
10-11 07:57:43.141 28481-28504/? I/OpenGLRenderer﹕ Initialized EGL, version 1.4
10-11 07:57:43.311 28481-28504/? W/EGL_emulation﹕ eglSurfaceAttrib not implemented
10-11 07:57:43.311 28481-28504/? W/OpenGLRenderer﹕ Failed to set EGL_SWAP_BEHAVIOR on surface 0xad7918a0, error=EGL_SUCCESS
10-11 07:58:56.273 28481-28504/com.tarun.proxy_maar W/EGL_emulation﹕ eglSurfaceAttrib not implemented
10-11 07:58:56.274 28481-28504/com.tarun.proxy_maar W/OpenGLRenderer﹕ Failed to set EGL_SWAP_BEHAVIOR on surface 0xad7bf200, error=EGL_SUCCESS
10-11 07:58:56.939 28481-28504/com.tarun.proxy_maar E/Surface﹕ getSlotFromBufferLocked: unknown buffer: 0xab815a40
10-11 07:58:57.128 28481-28504/com.tarun.proxy_maar W/EGL_emulation﹕ eglSurfaceAttrib not implemented
10-11 07:58:57.128 28481-28504/com.tarun.proxy_maar W/OpenGLRenderer﹕ Failed to set EGL_SWAP_BEHAVIOR on surface 0xa2e1e6c0, error=EGL_SUCCESS
10-11 07:59:00.474 28481-28504/com.tarun.proxy_maar E/Surface﹕ getSlotFromBufferLocked: unknown buffer: 0xab8159d0
I use the jsoup library to post data from my android apps and it's way easier, where's an example
Document doc = Jsoup.connect("http://shaadi.web44.net/hello.php")
.data("username", uname)
.data("password", pass)
.userAgent("some user agent..or not...")
.timeout(30000)
.post();
String httpresponse = doc.text();
I have to do an app, that should work in all 2.2+ versions. I have tested in both android devices and emulators. But this app is working in few versions but not working in higher versions, If i launched my app iam getting error with null value. I don't know why its happening. According to my assumption "If we developed app for lower versions that should work in all other higher version", But that is not working. Please help me.
Here is my code that is working in 2.2, 2.3 and few higher versions. but not working in 3.2 and higher. i'm getting null value for
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main_geotracker);
textbox1 = (TextView) findViewById(R.id.textinname1);
textbox2 = (TextView) findViewById(R.id.textinname2);
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo ni = cm.getActiveNetworkInfo();
if (ni != null && ni.isConnected())
{
msg = "Please login to continue";
login();
}
else
{
msg = "Sorry , network connection is not available.";
message();
}
}
//Login------------------------------------------------------------------------------------
public void login()
{
final EditText uname = new EditText(this);
final EditText upassword = new EditText(this);
DialogInterface.OnClickListener dialogClickListener = new DialogInterface.OnClickListener()
{
// DialogInterface called while setting the AlertDialog Buttons
public void onClick(DialogInterface dialog, int which)
{
//Here you can perform functions of Alert Dialog Buttons as shown
switch(which)
{
case DialogInterface.BUTTON_POSITIVE:
if(!uname.getText().toString().equals("") && !upassword.getText().toString().equals(""))
{
session_name = uname.getText().toString();
session_pwd = upassword.getText().toString();
try
{
uid = httppost(uname.getText().toString(), upassword.getText().toString(), "login.php"); //Here Iam getting null value.
Log.i("TAG", ""+uid);
}
catch(JSONException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
if(uid == null || uid.length() == 6)
{
msg = "Either user name or password or both incorrect.";
login();
}
else
{
Toast.makeText(getApplicationContext(), "Hello " + uname.getText().toString() + ", You have successfully logged in..:)", Toast.LENGTH_LONG).show();
IDList()
}
}
else
{
Toast.makeText(getApplicationContext(), "Sorry, Either user name or password or both incorrect..:(", Toast.LENGTH_LONG).show();
msg = "Both user name and password are mandatory fields.";
login();
}
break;
case DialogInterface.BUTTON_NEGATIVE:
exit();
break;
}
}
};
AlertDialog.Builder builder = new AlertDialog.Builder(this);
LinearLayout orientation = new LinearLayout(this);
orientation.setOrientation(1); //1 is for vertical orientation
uname.setHint("Enter name");
upassword.setHint("Enter password");
upassword.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
orientation.addView(uname);
orientation.addView(upassword);
builder.setView(orientation);
builder.setMessage(msg);
builder.setTitle("Login")
.setIcon(R.drawable.ic_launcher)
.setPositiveButton("Submit", dialogClickListener)
.setNegativeButton("Exit App", dialogClickListener).show();
}
public String httppost(String param1, String param2, String file) throws JSONException
{
try
{
String data = URLEncoder.encode("param1", "UTF-8") + "=" + URLEncoder.encode(param1, "UTF-8");
data += "&" + URLEncoder.encode("param2", "UTF-8") + "=" + URLEncoder.encode(param2, "UTF-8");
// Send data
URL url = new URL("http://192.168.1.12/GeoTracker/android/"+file);
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
wr.write(data);
wr.flush();
// Get the response
BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
the_string_response = rd.readLine();
wr.close();
rd.close();
}
catch (Exception e)
{
}
textbox1.setText("");
textbox2.setText("");
return the_string_response;
}
Here is my log cat,
`05-21 19:12:50.610: D/dalvikvm(4100): Late-enabling CheckJNI
05-21 19:12:50.850: E/PhonePolicy(4100): Could not preload class for phone policy: com.android.internal.policy.impl.PhoneWindow$ContextMenuCallback
05-21 19:12:50.970: D/TextLayoutCache(4100): Using debug level: 0 - Debug Enabled: 0
05-21 19:12:51.160: I/dalvikvm(4100): threadid=1: recursive native library load attempt (/system/lib/libwebcore.so)
05-21 19:12:51.160: D/dalvikvm(4100): No JNI_OnLoad found in /system/lib/libchromium_net.so 0x0, skipping init
05-21 19:12:51.220: D/dalvikvm(4100): GC_CONCURRENT freed 134K, 4% free 5078K/5255K, paused 1ms+1ms
05-21 19:12:51.750: D/libEGL(4100): loaded /system/lib/egl/libEGL_mali.so
05-21 19:12:51.760: D/libEGL(4100): loaded /system/lib/egl/libGLESv1_CM_mali.so
05-21 19:12:51.770: D/libEGL(4100): loaded /system/lib/egl/libGLESv2_mali.so
05-21 19:12:51.820: D/OpenGLRenderer(4100): Enabling debug mode 0
05-21 19:12:59.690: D/dalvikvm(4100): GC_CONCURRENT freed 159K, 5% free 5329K/5575K,
paused 2ms+4ms`
05-21 19:13:11.500: I/TAG(4100): null
Please help me,
Thanks in advance...
On devices with a high enough API level the system prevents you from doing network operations (http post etc...) in the main thread. If you look up further in your logcat (set it to verbose) somewhere you'll probably find something like NETWORK_ON_MAIN_THREAD_EXCEPTION in there.
That looks like it is exactly what you are doing. This would work fine on the lower API levels because the platform didn't restrict it (though it is still a bad idea)
To fix you just need to move your network operation off of the main thread. Consider using AsyncTask
I have a simple code that is supposed to do one task, when the button is clicked download a file, save it to the SD card, and open it. Everything works except during the download, for larger files, the connection drops and the progress bar hangs - almost always at 20%. I have searched and searched and cannot figure out what to do to keep the connection alive and allow the download to complete. Any ideas how to keep the connection alive so the download completes instead of stalling at 20%?
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.List;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class DownloadTestActivity extends Activity {
public static final int DIALOG_DOWNLOAD_PROGRESS = 0;
private Button startBtn;
private ProgressDialog mProgressDialog;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mProgressDialog = new ProgressDialog(DownloadTestActivity.this);
mProgressDialog.setMessage("Downloading...");
mProgressDialog.setIndeterminate(false);
mProgressDialog.setMax(100);
mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
startBtn = (Button) findViewById(R.id.startBtn);
startBtn.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
startDownload();
}
});
}
private void startDownload() {
DownloadFile downloadFile = new DownloadFile();
downloadFile
.execute("http://www.website.com/file.pdf");
}
class DownloadFile extends AsyncTask<String, Integer, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
mProgressDialog.show();
}
#Override
protected void onProgressUpdate(Integer... progress) {
super.onProgressUpdate(progress);
mProgressDialog.setProgress(progress[0]);
}
#Override
protected String doInBackground(String... aurl) {
try {
URL url = new URL(aurl[0]);
URLConnection connection = url.openConnection();
connection.connect();
int fileLength = connection.getContentLength();
Log.d("ANDRO_ASYNC", "Lenght of file: " + fileLength);
InputStream input = new BufferedInputStream(url.openStream());
String path = Environment.getExternalStorageDirectory()
+ "/Android/Data/"
+ getApplicationContext().getPackageName() + "/files";
File file = new File(path);
file.mkdirs();
File outputFile = new File(file, "test1.doc");
OutputStream output = new FileOutputStream(outputFile);
byte data[] = new byte[8192];
long total = 0;
int count;
while ((count = input.read(data)) != -1) {
total += count;
publishProgress((int) (total * 100 / fileLength));
output.write(data, 0, count);
}
output.flush();
output.close();
input.close();
showPdf();
} catch (Exception e) {
}
return null;
}
private void showPdf() {
// TODO Auto-generated method stub
if(mProgressDialog != null){
mProgressDialog.dismiss();
}
File file = new File(Environment.getExternalStorageDirectory()
+ "/Android/Data/"
+ getApplicationContext().getPackageName()
+ "/files/test1.doc");
PackageManager packageManager = getPackageManager();
Intent testIntent = new Intent(Intent.ACTION_VIEW);
testIntent.setType("application/msword");
List list = packageManager.queryIntentActivities(testIntent,
PackageManager.MATCH_DEFAULT_ONLY);
Intent intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);
Uri uri = Uri.fromFile(file);
intent.setDataAndType(uri, "application/msword");
startActivity(intent);
}
}
}
Edit with logcat information:
--------- beginning of /dev/log/system
W/InputManagerService( 199): Window already focused, ignoring focus gain of: com.android.internal.view.IInputMethodClient$Stub$Proxy#4137b898
--------- beginning of /dev/log/main
D/AndroidRuntime(20673):
D/AndroidRuntime(20673): >>>>>> AndroidRuntime START com.android.internal.os.RuntimeInit <<<<<<
D/AndroidRuntime(20673): CheckJNI is OFF
D/AndroidRuntime(20673): Calling main entry com.android.commands.pm.Pm
D/AndroidRuntime(20673): Shutting down VM
D/dalvikvm(20673): GC_CONCURRENT freed 101K, 82% free 467K/2560K, paused 1ms+0ms
D/dalvikvm(20673): Debugger has detached; object registry had 1 entries
I/AndroidRuntime(20673): NOTE: attach of thread 'Binder Thread #3' failed
D/AndroidRuntime(20687):
D/AndroidRuntime(20687): >>>>>> AndroidRuntime START com.android.internal.os.RuntimeInit <<<<<<
D/AndroidRuntime(20687): CheckJNI is OFF
D/AndroidRuntime(20687): Calling main entry com.android.commands.am.Am
I/ActivityManager( 199): START {act=android.intent.action.MAIN cat=[android.intent.category.LAUNCHER] flg=0x10000000 cmp=com.myapp/.Activity} from pid 20687
D/AndroidRuntime(20687): Shutting down VM
D/dalvikvm(20687): GC_CONCURRENT freed 102K, 81% free 489K/2560K, paused 0ms+0ms
D/jdwp (20687): Got wake-up signal, bailing out of select
D/dalvikvm(20687): Debugger has detached; object registry had 1 entries
I/AndroidRuntime(20687): NOTE: attach of thread 'Binder Thread #3' failed
D/dalvikvm(20698): Late-enabling CheckJNI
I/ActivityManager( 199): Start proc com.myapp for activity com.myapp/.Activity: pid=20698 uid=10102 gids={1015, 3003}
I/dalvikvm(20698): Turning on JNI app bug workarounds for target SDK version 10...
V/PhoneStatusBar( 271): setLightsOn(true)
D/AudioHardware( 98): AudioHardware pcm playback is going to standby.
D/AudioHardware( 98): closePcmOut_l() mPcmOpenCnt: 1
I/ActivityManager( 199): Displayed com.myapp/.Activity: +197ms
W/InputManagerService( 199): Starting input on non-focused client com.android.internal.view.IInputMethodClient$Stub$Proxy#4199ed28 (uid=10098 pid=20011)
I/ActivityManager( 199): START {cmp=com.myapp/.Choice} from pid 20698
D/AudioHardware( 98): AudioHardware pcm playback is exiting standby.
D/AudioHardware( 98): openPcmOut_l() mPcmOpenCnt: 0
V/PhoneStatusBar( 271): setLightsOn(true)
I/ActivityManager( 199): Displayed com.myapp/.Choice: +93ms
D/ANDRO_ASYNC(20698): Lenght of file: 736768
D/dalvikvm(20698): GC_CONCURRENT freed 103K, 3% free 9403K/9607K, paused 2ms+3ms
W/NetworkStats( 199): found non-monotonic values; saving to dropbox
D/dalvikvm( 199): JIT code cache reset in 5 ms (1048440 bytes 13/0)
D/dalvikvm( 199): GC_CONCURRENT freed 1472K, 13% free 24697K/28231K, paused 12ms+14ms
D/AudioHardware( 98): AudioHardware pcm playback is going to standby.
D/AudioHardware( 98): closePcmOut_l() mPcmOpenCnt: 1
I/ActivityManager( 199): Force stopping package com.myapp uid=10102
I/ActivityManager( 199): Killing proc 20698:com.myapp/10102: force stop
W/ActivityManager( 199): Force removing ActivityRecord{41eb1ec0 com.myapp/.Choice}: app died, no saved state
I/InputDispatcher( 199): Dropping event because there is no focused window or focused application.
I/ActivityManager( 199): Force finishing activity ActivityRecord{418450c8 com.myapp/.Activity}
I/InputDispatcher( 199): Dropping event because there is no focused window or focused application.
W/InputDispatcher( 199): channel '417b41f0 com.myapp/com.myapp/.Activity (server)' ~ Consumer closed input channel or an error occurred. events=0x8
E/InputDispatcher( 199): channel '417b41f0 com.myapp/com.myapp.Activity (server)' ~ Channel is unrecoverably broken and will be disposed!
W/InputDispatcher( 199): Attempted to unregister already unregistered input channel '417b41f0 com.myapp/com.myapp.Activity (server)'
W/WindowManager( 199): Failed looking up window
W/WindowManager( 199): java.lang.IllegalArgumentException: Requested window android.os.BinderProxy#41c7ffc8 does not exist
W/WindowManager( 199): at com.android.server.wm.WindowManagerService.windowForClientLocked(WindowManagerService.java:7176)
W/WindowManager( 199): at com.android.server.wm.WindowManagerService.windowForClientLocked(WindowManagerService.java:7167)
W/WindowManager( 199): at com.android.server.wm.WindowState$DeathRecipient.binderDied(WindowState.java:1545)
W/WindowManager( 199): at android.os.BinderProxy.sendDeathNotice(Binder.java:417)
W/WindowManager( 199): at dalvik.system.NativeStart.run(Native Method)
I/WindowManager( 199): WIN DEATH: null
I/WindowManager( 199): WIN DEATH: Window{4175b280 com.myapp/com.myapp.Choice paused=false}
W/WindowManager( 199): Failed looking up window
W/WindowManager( 199): java.lang.IllegalArgumentException: Requested window android.os.BinderProxy#41758028 does not exist
W/WindowManager( 199): at com.android.server.wm.WindowManagerService.windowForClientLocked(WindowManagerService.java:7176)
W/WindowManager( 199): at com.android.server.wm.WindowManagerService.windowForClientLocked(WindowManagerService.java:7167)
W/WindowManager( 199): at com.android.server.wm.WindowState$DeathRecipient.binderDied(WindowState.java:1545)
W/WindowManager( 199): at android.os.BinderProxy.sendDeathNotice(Binder.java:417)
W/WindowManager( 199): at dalvik.system.NativeStart.run(Native Method)
I/WindowManager( 199): WIN DEATH: null
W/InputManagerService( 199): Got RemoteException sending setActive(false) notification to pid 20698 uid 10102
D/dalvikvm(20011): GC_CONCURRENT freed 460K, 32% free 9468K/13767K, paused 3ms+4ms
D/AudioHardware( 98): AudioHardware pcm playback is exiting standby.
D/AudioHardware( 98): openPcmOut_l() mPcmOpenCnt: 0
I've tried to download your file a few times, looks like download stalls for a few seconds here and there, and it might trigger a timeout in your application. Try to specify timeouts explicitly in range 10-20 seconds.
private DefaultHttpClient httpclient = new DefaultHttpClient();
private HttpGet get = new HttpGet("your url comes here");
protected String[] doInBackground(Void... v) {
HttpParams httpParameters = new BasicHttpParams();
// set the timeout in milliseconds until a connection is established
// the default value is zero, that means the timeout is not used
int timeoutConnection = 3000;
HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
// set the default socket timeout (SO_TIMEOUT) in milliseconds
// which is the timeout for waiting for data
int timeoutSocket = 5000;
HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
httpclient.setParams(httpParameters);
try {
HttpEntity entity = httpclient.execute( get ).getEntity();
FileOutputStream output = new FileOutputStream(outputFile);
entity.writeTo(output);
output.close();
// return something, maybe?
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
httpclient.getConnectionManager().shutdown();
}
return null;
}
What seems to be the problem is that process 199 in your logcat seem to be your activity, but then it shows:
I/ActivityManager( 199): Force stopping package com.viperean.atcassistant uid=10102
I/ActivityManager( 199): Killing proc 20698:com.viperean.atcassistant/10102: force stop
W/ActivityManager( 199): Force removing ActivityRecord{41eb1ec0 com.viperean.atcassistant/.atcChoice}: app died, no saved state
(and the second line shows that it is killing your asynctask...).
I don't think there is anything wrong with the download code by itself. I think you should look more in the activity (what are you doing during that time beside that asynctask, what are you displaying on the screen...etc...).
Seems also that you are pretty low in heap space.
D/dalvikvm(20698): GC_CONCURRENT freed 103K, 3% free 9403K/9607K, paused 2ms+3ms
D/dalvikvm( 199): JIT code cache reset in 5 ms (1048440 bytes 13/0)
D/dalvikvm( 199): GC_CONCURRENT freed 1472K, 13% free 24697K/28231K, paused 12ms+14ms
Those are from the garbage collection and happen just before your app crashed, maybe that could be a problem too?
every thread in Android is being killed by the system if it doesn't respond for more than five minutes. maybe you should consider downloading as a service or overriding the onProgress and get the thread to stay alive