My application not connecting to a Java Servlet - java

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

Related

I cant write to database reference to show up in firebase console [duplicate]

This question already has answers here:
Firebase Permission Denied
(10 answers)
Firebase: Permission denied - setValue()
(2 answers)
Closed 1 year ago.
for some reason when I try to make a Databasereference it will not show up in my firebase console. I have a android app where I allow user to register/login and when they hit the register button a Databasereference should show up in the console with their userid as a child and they should be logged in. So the users are getting logged in but the Databasereference is writing to console. In the logs im getting a permission denied error. I set my rules to allow read and write so I dont know why that is happening and I made sure the google-services.json is correct for my app. Here is my code below
package com.example.movir;
import androidx.annotation.NonNull;
import android.content.Intent;
import android.os.Bundle;
import androidx.appcompat.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.Toast;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
public class LendersLoginActivity extends AppCompatActivity {
private static final String TAG = "";
private FirebaseAuth mAuth;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_lenders_login);
// ...
// Initialize Firebase Auth
mAuth = FirebaseAuth.getInstance();
final EditText usernameEditText = findViewById(R.id.username);
final EditText passwordEditText = findViewById(R.id.password);
final Button loginButton = findViewById(R.id.login);
final Button registerButton = findViewById(R.id.register_button);
final ProgressBar loadingProgressBar = findViewById(R.id.loading);
loginButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String email = usernameEditText.getText().toString();
String password = passwordEditText.getText().toString();
mAuth.signInWithEmailAndPassword(email, password)
.addOnCompleteListener(LendersLoginActivity.this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
// Sign in success, update UI with the signed-in user's information
Log.d(TAG, "signInWithEmail:success");
String user_id= mAuth.getCurrentUser().getUid();
DatabaseReference current_user_db = FirebaseDatabase.getInstance().getReference().child("Users").child("Lenders").child(user_id);
current_user_db.setValue(true);
Intent intent = new Intent(LendersLoginActivity.this,LendersMenuPageActivity.class);
startActivity(intent);
} else {
// If sign in fails, display a message to the user.
Log.w(TAG, "signInWithEmail:failure", task.getException());
Toast.makeText(LendersLoginActivity.this, "Authentication failed.",
Toast.LENGTH_SHORT).show();
// ...
}
// ...
}
});
}
});
registerButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String email = usernameEditText.getText().toString();
String password = passwordEditText.getText().toString();
mAuth.createUserWithEmailAndPassword(email, password)
.addOnCompleteListener(LendersLoginActivity.this, new OnCompleteListener< AuthResult >() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
// Sign in success, update UI with the signed-in user's information
String user_id= mAuth.getCurrentUser().getUid();
DatabaseReference current_user_db = FirebaseDatabase.getInstance().getReference().child("Users").child("Lenders").child(user_id);
current_user_db.setValue(true);
Intent intent = new Intent(LendersLoginActivity.this,LendersMenuPageActivity.class);
Log.d(TAG, "createUserWithEmail:success");
startActivity(intent);
} else {
// If sign in fails, display a message to the user.
Log.w(TAG, "createUserWithEmail:failure", task.getException());
Toast.makeText(LendersLoginActivity.this, "Authentication failed.",
Toast.LENGTH_SHORT).show();
}
// ...
}
});
}
});
}
}
Here are my logs
2021-03-14 11:24:05.511 14583-14614/com.example.movir I/FirebaseAuth: [FirebaseAuth:] Preparing to create service connection to fallback implementation
2021-03-14 11:24:05.583 14583-14614/com.example.movir W/System: Ignoring header X-Firebase-Locale because its value was null.
2021-03-14 11:24:05.599 14583-14614/com.example.movir I/System.out: isEmailSend:POST
2021-03-14 11:24:05.656 14583-14614/com.example.movir I/System.out: port:443
2021-03-14 11:24:05.911 14583-14614/com.example.movir I/System.out: Check isMmsSendPdu
2021-03-14 11:24:05.921 14583-14614/com.example.movir I/System.out: [OkHttp] sendRequest<<
2021-03-14 11:24:06.224 14583-14614/com.example.movir W/System: Ignoring header X-Firebase-Locale because its value was null.
2021-03-14 11:24:06.234 14583-14614/com.example.movir I/System.out: isEmailSend:POST
2021-03-14 11:24:06.242 14583-14614/com.example.movir I/System.out: Check isMmsSendPdu
2021-03-14 11:24:06.248 14583-14614/com.example.movir I/System.out: [OkHttp] sendRequest<<
2021-03-14 11:24:06.418 14583-14614/com.example.movir D/FirebaseAuth: Notifying id token listeners about user ( 5mfvkS1vGndftKXzsE4yUkt4TMC2 ).
2021-03-14 11:24:06.418 14583-14614/com.example.movir D/FirebaseAuth: Notifying auth state listeners about user ( 5mfvkS1vGndftKXzsE4yUkt4TMC2 ).
--------- beginning of system
2021-03-14 11:24:06.488 14583-14712/com.example.movir V/FA: Recording user engagement, ms: 28677
2021-03-14 11:24:06.505 14583-14711/com.example.movir V/FA: onActivityCreated
2021-03-14 11:24:06.517 14583-14712/com.example.movir V/FA: Connecting to remote service
2021-03-14 11:24:06.525 14583-14712/com.example.movir V/FA: Activity paused, time: 1162831406
2021-03-14 11:24:06.533 14583-14769/com.example.movir I/System.out: port:443
2021-03-14 11:24:06.585 14583-14588/com.example.movir I/zygote: Do partial code cache collection, code=124KB, data=113KB
2021-03-14 11:24:06.587 14583-14588/com.example.movir I/zygote: After code cache collection, code=124KB, data=113KB
2021-03-14 11:24:06.587 14583-14588/com.example.movir I/zygote: Increasing code cache capacity to 512KB
2021-03-14 11:24:06.684 14583-14583/com.example.movir V/PhoneWindow: DecorView setVisiblity: visibility = 4, Parent = null, this = DecorView#2b33e7c[]
2021-03-14 11:24:06.687 14583-14583/com.example.movir D/WindowClient: Add to mViews: DecorView#2b33e7c[LendersMenuPageActivity], this = android.view.WindowManagerGlobal#ed0972b
2021-03-14 11:24:06.691 14583-14583/com.example.movir D/ViewRootImpl[LendersMenuPageActivity]: hardware acceleration = true , fakeHwAccelerated = false, sRendererDisabled = false, forceHwAccelerated = false, sSystemRendererDisabled = false
2021-03-14 11:24:06.692 14583-14712/com.example.movir V/FA: Connection attempt already in progress
2021-03-14 11:24:06.697 14583-14712/com.example.movir V/FA: Activity resumed, time: 1162831603
2021-03-14 11:24:06.697 14583-14583/com.example.movir V/PhoneWindow: DecorView setVisiblity: visibility = 0, Parent = ViewRoot{42e658b com.example.movir/com.example.movir.LendersMenuPageActivity,ident = 3}, this = DecorView#2b33e7c[LendersMenuPageActivity]
2021-03-14 11:24:06.798 14583-14583/com.example.movir D/Surface: Surface::allocateBuffers(this=0x982b7000)
2021-03-14 11:24:06.798 14583-14622/com.example.movir D/Surface: Surface::connect(this=0x982b7000,api=1)
2021-03-14 11:24:06.805 14583-14622/com.example.movir D/Surface: Surface::setBufferCount(this=0x982b7000,bufferCount=4)
2021-03-14 11:24:06.852 14583-14712/com.example.movir V/FA: Connection attempt already in progress
2021-03-14 11:24:06.858 14583-14712/com.example.movir V/FA: Connection attempt already in progress
2021-03-14 11:24:06.941 14583-14712/com.example.movir D/FA: Connected to remote service
2021-03-14 11:24:06.946 14583-14712/com.example.movir V/FA: Processing queued up service tasks: 4
2021-03-14 11:24:06.957 14583-14622/com.example.movir E/[EGL-ERROR]: __egl_platform_cancel_buffers:644: surface->num_buffers(4)
2021-03-14 11:24:06.958 14583-14622/com.example.movir D/Surface: Surface::disconnect(this=0x981ff000,api=1)
2021-03-14 11:24:07.317 14583-14583/com.example.movir V/PhoneWindow: DecorView setVisiblity: visibility = 4, Parent = ViewRoot{86bcf3f com.example.movir/com.example.movir.LendersLoginActivity,ident = 1}, this = DecorView#6c705e0[LendersLoginActivity]
2021-03-14 11:24:08.048 14583-14767/com.example.movir W/RepoOperation: setValue at /Users/Lenders/5mfvkS1vGndftKXzsE4yUkt4TMC2 failed: DatabaseError: Permission denied
2021-03-14 11:24:12.054 14583-14712/com.example.movir V/FA: Inactivity, disconnecting from the service
2021-03-14 11:24:12.061 14583-14712/com.example.movir W/System.err: java.lang.IllegalArgumentException: Service not registered: lg#bde9d9a
2021-03-14 11:24:12.063 14583-14712/com.example.movir W/System.err: at android.app.LoadedApk.forgetServiceDispatcher(LoadedApk.java:1494)
2021-03-14 11:24:12.065 14583-14712/com.example.movir W/System.err: at android.app.ContextImpl.unbindService(ContextImpl.java:1655)
2021-03-14 11:24:12.067 14583-14712/com.example.movir W/System.err: at android.content.ContextWrapper.unbindService(ContextWrapper.java:712)
2021-03-14 11:24:12.068 14583-14712/com.example.movir W/System.err: at ci.f(:com.google.android.gms.dynamite_measurementdynamite#210613128#21.06.13 (110306-0):0)
2021-03-14 11:24:12.070 14583-14712/com.example.movir W/System.err: at ci.d(:com.google.android.gms.dynamite_measurementdynamite#210613128#21.06.13 (110306-0):2)
2021-03-14 11:24:12.071 14583-14712/com.example.movir W/System.err: at lh.D(:com.google.android.gms.dynamite_measurementdynamite#210613128#21.06.13 (110306-0):9)
2021-03-14 11:24:12.072 14583-14712/com.example.movir W/System.err: at kr.a(:com.google.android.gms.dynamite_measurementdynamite#210613128#21.06.13 (110306-0):3)
2021-03-14 11:24:12.074 14583-14712/com.example.movir W/System.err: at ef.run(:com.google.android.gms.dynamite_measurementdynamite#210613128#21.06.13 (110306-0):3)
2021-03-14 11:24:12.075 14583-14712/com.example.movir W/System.err: at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:457)
2021-03-14 11:24:12.076 14583-14712/com.example.movir W/System.err: at java.util.concurrent.FutureTask.run(FutureTask.java:266)
2021-03-14 11:24:12.077 14583-14712/com.example.movir W/System.err: at im.run(:com.google.android.gms.dynamite_measurementdynamite#210613128#21.06.13 (110306-0):5)

Unable to get Notification form Scanner

I am working on an application for a Zebra Technologies TC8000 scanner using the DataWedge. I'm using Android Studio 3.5 and flutter for the mobile framework.
I am using a Broadcast Receiver in my main activity and attempting to use a call back in my Dart code.
When I pull the trigger on the scanner, I see the following in logcat:
04-22 11:35:12.946 1009-1009/? D/ScannerPlugin: Scan status changed from SCAN_STATUS_WAITFORTRIGGER to SCAN_STATUS_SCANNING
04-22 11:35:12.946 1009-1009/? D/Client: requested to send: 110 (ScannerStateChanged): SCAN_STATUS_SCANNING
04-22 11:35:12.956 1009-1009/? D/Client: sent: 110 (ScannerStateChanged): SCAN_STATUS_SCANNING
04-22 11:35:12.956 1009-1009/? D/ScannerPlugin: Status:SCANNING;ProfileName:Profile0 (default)
04-22 11:35:12.956 1009-1009/? D/ScannerStateChanged: deserialize: state: SCAN_STATUS_SCANNING
04-22 11:35:12.966 1009-1009/? D/Protocol: parsed 110 (ScannerStateChanged): SCAN_STATUS_SCANNING
04-22 11:35:12.966 1009-1009/? D/SwipeAssistService: handleMessage(110 (ScannerStateChanged): SCAN_STATUS_SCANNING), connected clients: 1
04-22 11:35:13.416 665-665/? E/NotificationService: Not posting notification with icon==0: Notification(pri=0 contentView=com.symbol.datawedge/0x1090064 vibrate=null sound=null defaults=0x0 flags=0x11 kind=[null])
04-22 11:35:13.416 665-665/? E/NotificationService: WARNING: In a future release this will crash the app: com.symbol.datawedge
04-22 11:35:13.436 1009-1009/? D/ScannerPlugin: Scan status changed from SCAN_STATUS_SCANNING to SCAN_STATUS_WAITFORTRIGGER
04-22 11:35:13.436 1009-1009/? D/Client: requested to send: 110 (ScannerStateChanged): SCAN_STATUS_WAITFORTRIGGER
04-22 11:35:13.436 1009-1009/? D/Client: sent: 110 (ScannerStateChanged): SCAN_STATUS_WAITFORTRIGGER
04-22 11:35:13.436 1009-1009/? D/ScannerPlugin: Status:WAITING;ProfileName:Profile0 (default)
04-22 11:35:13.436 1009-1009/? D/ScannerStateChanged: deserialize: state: SCAN_STATUS_WAITFORTRIGGER
04-22 11:35:13.436 1009-1009/? D/Protocol: parsed 110 (ScannerStateChanged): SCAN_STATUS_WAITFORTRIGGER
04-22 11:35:13.436 1009-1009/? D/SwipeAssistService: handleMessage(110 (ScannerStateChanged): SCAN_STATUS_WAITFORTRIGGER), connected clients: 1
The scan beam comes on and the scanner acknowledges the bar code read, but I'm not receiving the event. I'm concerned over the line:
04-22 11:35:13.416 665-665/? E/NotificationService: Not posting notification with icon==0: Notification(pri=0 contentView=com.symbol.datawedge/0x1090064 vibrate=null sound=null defaults=0x0 flags=0x11 kind=[null])
I've checked Zebra's documents and modified my code to register the broadcast receiver. Here is my MainActivity code:
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.util.Log;
import io.flutter.app.FlutterActivity;
import io.flutter.plugin.common.EventChannel;
import io.flutter.plugin.common.MethodCall;
import io.flutter.plugin.common.MethodChannel;
import io.flutter.plugin.common.MethodChannel.MethodCallHandler;
import io.flutter.plugin.common.MethodChannel.Result;
import com.goodyear.flutter_plugin.R;
import static android.content.ContentValues.TAG;
public class MainActivity extends FlutterActivity {
private static String INTENT_ACTION;
private static String SCAN_DATA;
private static String CHANNEL;
private static String METHOD;
private static String NOTIFICATION_ACTION;
private static String NOTIFICATION_TYPE_SCANNER_STATUS;
private Result barcodeResult;
private void registerReceivers() {
IntentFilter filter = new IntentFilter();
filter.addAction(NOTIFICATION_ACTION);
registerReceiver(broadcastReceiver, filter);
}
private void unRegisterReceivers() {
unregisterReceiver(broadcastReceiver);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
Log.i("Barcode", "Inside onCreate");
super.onCreate(savedInstanceState);
INTENT_ACTION = getResources().getString(R.string.activity_intent_filter_action);
SCAN_DATA = getResources().getString(R.string.datawedge_intent_key_data);
CHANNEL = getResources().getString(R.string.barcode_method_channel);
METHOD = getResources().getString(R.string.barcode_method);
NOTIFICATION_ACTION = getResources().getString(R.string.datawedge_notification_action);
NOTIFICATION_TYPE_SCANNER_STATUS = getResources().getString(R.string.datawedge_notification_scanner_status);
registerReceivers();
Bundle b = new Bundle();
b.putString("com.symbol.datawedge.api.APPLICATION_NAME", "com.example.intenttest");
b.putString("com.symbol.datawedge.api.NOTIFICATION_TYPE", "SCANNER_STATUS");
Intent i = new Intent();
i.setAction("com.symbol.datawedge.api.ACTION");
i.putExtra("com.symbol.datawedge.api.REGISTER_FOR_NOTIFICATION", b);//(1)
this.sendBroadcast(i);
new MethodChannel(getFlutterView(), CHANNEL).setMethodCallHandler(
new MethodCallHandler() {
#Override
public void onMethodCall(MethodCall call, Result result) {
Log.i("Barcode", "Inside onMethodCall");
if (call.method.equals(METHOD)) {
Log.i("Barcode", "Result = " + result);
barcodeResult = result;
}
Log.i("Barcode", "Leaving onMethodCall");
}
}
);
Log.i("Barcode", "Leaving onCreate");
}
#Override
protected void onDestroy() {
unRegisterReceivers();
super.onDestroy();
}
private BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
Log.i("Barcode", "Inside onReceive");
String action = intent.getAction();
Log.d("Barcode", "#DataWedge-APP# Action: " + action);
switch (action) {
case "com.symbol.datawedge.api.NOTIFICATION_ACTION":
logStatus(intent);
break;
case "com.com.goodyear.ACTION":
readScanData(intent);
break;
}
}
};
private void logStatus(Intent intent) {
if (intent.hasExtra("com.symbol.datawedge.api.NOTIFICATION")) {
Bundle b = intent.getBundleExtra("com.symbol.datawedge.api.NOTIFICATION");
String NOTIFICATION_TYPE = b.getString("NOTIFICATION_TYPE");
if (NOTIFICATION_TYPE != null) {
Log.d("Barcode", "SCANNER_STATUS: status: " + b.getString("STATUS") + ", profileName: " + b.getString("PROFILE_NAME"));
}
}
}
private void readScanData(Intent intent) {
String barCode = intent.getStringExtra(SCAN_DATA);
// String decodedLabelType = intent.getStringExtra(getResources().getString(R.string.datawedge_intent_key_label_type));
try {
Log.i("Barcode", "Barcode = " + barCode);
barcodeResult.success(barCode);
} catch (Exception e) {
// Catch if the UI does not exist when we receive the broadcast
}
Log.i("Barcode", "Leaving onReceive");
}
}
This is frustrating. The issue does not seem to be in my code as I have set breakpoints in the the onReceive() event and that method does not fire.
Not sure what the issue is.
NOTIFICATION_ACTION is only used to notify your application that the scanner beam is scanning, IDLE etc, it does not actually contain any scan data. I think you are confusing the DataWedge API with the DataWedge Intent Output plugin, I don't have a Flutter example but please take a look at a quick Java tutorial I did on receiving scan data from DataWedge: http://www.darryncampbell.co.uk/2017/12/13/tutorial-scan-with-datawedge-intent-output-on-zebra-devices/
I am pretty sure that error about NotificationService is unrelated to the scanner.
Your log also indicates that you are using Profile0 (default), which is the same I show in the tutorial but you may want to consider creating a dedicated Profile for your app.

Does not show RAW XML data

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..

Android Weather app crashing-network error

I have been developing a weather app through Treehouse and unfortunately no one has been able to help me fix this perticular error.
For some reason no weather data is retrieved on the app. I signed up through forecast IO to get the weather data to the app but nothing appears and the app crashes.
I use my phone as an emulator but I receive no errors in the log. Only when I use the Android Studio emulator do I receive an error in the logcat. Any suggestions ?
Stormy app on gitHub
Github
MainActivity.java file
import android.content.Context;
import android.graphics.drawable.Drawable;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import com.squareup.okhttp.Call;
import com.squareup.okhttp.Callback;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import butterknife.ButterKnife;
import butterknife.InjectView;
public class MainActivity extends ActionBarActivity {
public static final String TAG = MainActivity.class.getSimpleName();
private CurrentWeather mCurrentWeather;
#InjectView(R.id.timeLabel) TextView mTimeLabel;
#InjectView(R.id.temperatureLabel) TextView mTemperatureLabel;
#InjectView(R.id.humidityValue) TextView mHumidityValue;
#InjectView(R.id.precipValue) TextView mPrecipValue;
#InjectView(R.id.summaryLabel) TextView mSummaryLabel;
#InjectView(R.id.iconImageView) ImageView mIconImageView;
#InjectView(R.id.refreshImageView) ImageView mRefreshImageView;
#InjectView(R.id.progressBar)ProgressBar mProgressBar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButterKnife.inject(this);
mProgressBar.setVisibility(View.INVISIBLE);
final double latitude = 38.627;
final double longitude = -90.199;
mRefreshImageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
getForecast(latitude, longitude);
}
});
getForecast(latitude, longitude);
Log.d(TAG, "Main UI code is running!");
}
private void getForecast(double latitude, double longitude) {
String apiKey = "8ec5f1674002ab5081cad28e9be10ced";
String forecastUrl = "https://api.forecast.io/forecast/" + apiKey +
"/" + latitude + "," + longitude;
if(isNetworkAvailable()) {
toggleRefresh();
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder().
url(forecastUrl)
.build();
Call call = client.newCall(request);
call.enqueue(new Callback() {
#Override
public void onFailure(Request request, IOException e) {
toggleRefresh();
runOnUiThread(new Runnable() {
#Override
public void run() {
toggleRefresh();
}
});
alertUserAboutError();
}
#Override
public void onResponse(Response response) throws IOException {
runOnUiThread(new Runnable() {
#Override
public void run() {
toggleRefresh();
}
});
try {
String jsonData = response.body().string();
Log.v(TAG, response.body().string());
if (response.isSuccessful()) {
mCurrentWeather = getCurrentDetails(jsonData);
runOnUiThread(new Runnable() {
#Override
public void run() {
updateDisplay();
}
});
updateDisplay();
} else {
alertUserAboutError();
}
} catch (IOException e) {
Log.e(TAG, "Exception caught: ", e);
}
catch (JSONException e) {
Log.e(TAG, "Exception caught:", e);
}
}
});
}
else {
Toast.makeText(this, getString(R.string.network_unavailable_message),
Toast.LENGTH_LONG).show();
}
}
private void toggleRefresh() {
if (mProgressBar.getVisibility() == View.INVISIBLE) {
mProgressBar.setVisibility(View.VISIBLE);
mRefreshImageView.setVisibility(View.INVISIBLE);
} else {
mRefreshImageView.setVisibility(View.INVISIBLE);
mRefreshImageView.setVisibility(View.VISIBLE);
}
}
private void updateDisplay() {
mTemperatureLabel.setText(mCurrentWeather.getTemperature() + "");
mTimeLabel.setText("At" + mCurrentWeather.getFormattedTime() + " it will be");
mHumidityValue.setText(mCurrentWeather.getHumidity() + "");
mPrecipValue.setText(mCurrentWeather.getPrecipChance() + "%");
mSummaryLabel.setText(mCurrentWeather.getSummary());
Drawable drawable = getResources().getDrawable(mCurrentWeather.getIconId());
mIconImageView.setImageDrawable(drawable);
}
private CurrentWeather getCurrentDetails(String jsonData) throws JSONException {
JSONObject forecast = new JSONObject(jsonData);
String timezone = forecast.getString("timezone");
Log.i(TAG, "From JSON:" + timezone);
JSONObject currently = forecast.getJSONObject("currently");
CurrentWeather currentWeather = new CurrentWeather();
currentWeather.setHumidity(currently.getLong("time"));
currentWeather.setTime(currently.getLong("time"));
currentWeather.setIcon(currently.getString("icon"));
currentWeather.setPrecipChance(currently.getDouble("precipProbability"));
currentWeather.setTemperature(currently.getDouble("temperature"));
currentWeather.setTimeZone(timezone);
Log.d(TAG, currentWeather.getFormattedTime());
return new CurrentWeather();
}
private boolean isNetworkAvailable() {
ConnectivityManager manager = (ConnectivityManager)
getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = manager.getActiveNetworkInfo();
boolean isAvailable = false;
if(networkInfo != null && networkInfo.isConnected()) {
isAvailable = true;
}
return isAvailable;
}
private void alertUserAboutError() {
AlertDialogFragment dialog = new AlertDialogFragment();
dialog.show(getFragmentManager(), "error_dialog");
}
}
"PropertyFetcher: AdbCommandRejectedException getting properties for
device 0043d8b5c84ed1f5: device unauthorized.
Please check the confirmation dialog on your device."
Error log
02-10 14:17:31.130 52-52/? I/qemu-props﹕ received: qemu.hw.mainkeys=0
02-10 14:17:33.180 56-56/? I/SurfaceFlinger﹕ SurfaceFlinger's main thread ready to run. Initializing graphics H/W...
02-10 14:18:51.060 624-624/? D/AndroidRuntime﹕ Calling main entry com.android.commands.pm.Pm
02-10 14:19:01.630 548-548/com.android.launcher I/Choreographer﹕ Skipped 346 frames! The application may be doing too much work on its main thread.
02-10 14:19:02.750 437-437/? I/Choreographer﹕ Skipped 1210 frames! The application may be doing too much work on its main thread.
02-10 14:19:04.920 386-386/system_process W/BroadcastQueue﹕ Failure sending broadcast Intent { act=android.intent.action.TIME_TICK flg=0x50000014
(has extras) } android.os.TransactionTooLargeException
at android.os.BinderProxy.transact(Native Method)
at android.app.ApplicationThreadProxy.scheduleRegisteredReceiver(ApplicationThreadNative.java:1059)
at com.android.server.am.BroadcastQueue.performReceiveLocked(BroadcastQueue.java:421)
at com.android.server.am.BroadcastQueue.deliverToRegisteredReceiverLocked(BroadcastQueue.java:507)
at com.android.server.am.BroadcastQueue.processNextBroadcast(BroadcastQueue.java:714)
at com.android.server.am.ActivityManagerService.finishReceiver(ActivityManagerService.java:13807)
at android.content.BroadcastReceiver$PendingResult.sendFinished(BroadcastReceiver.java:419)
at android.content.BroadcastReceiver$PendingResult.finish(BroadcastReceiver.java:395)
at android.app.LoadedApk$ReceiverDispatcher$Args.run(LoadedApk.java:785)
at android.os.Handler.handleCallback(Handler.java:733)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:136)
at com.android.server.ServerThread.initAndLoop(SystemServer.java:1093)
at com.android.server.SystemServer.main(SystemServer.java:1179)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
at dalvik.system.NativeStart.main(Native Method)
02-10 14:19:08.800 386-386/system_process I/Choreographer﹕ Skipped 34 frames! The application may be doing too much work on its main thread.
02-10 14:19:19.860 548-548/com.android.launcher I/Choreographer﹕ Skipped 1089 frames! The application may be doing too much work on its main thread.
02-10 14:19:23.320 718-718/com.android.systemui I/Choreographer﹕ Skipped 679 frames! The application may be doing too much work on its main thread.
02-10 14:19:25.100 718-718/com.android.systemui I/Choreographer﹕ Skipped 106 frames! The application may be doing too much work on its main thread.
02-10 14:19:27.700 718-718/com.android.systemui I/Choreographer﹕ Skipped 154 frames! The application may be doing too much work on its main thread.
02-10 14:19:30.720 548-548/com.android.launcher I/Choreographer﹕ Skipped 61 frames! The application may be doing too much work on its main thread.
02-10 14:19:57.300 893-893/? D/AndroidRuntime﹕ Calling main entry com.android.commands.am.Am
02-10 14:19:57.400 386-398/system_process I/ActivityManager﹕ START u0 {act=android.intent.action.MAIN cat=[android.intent.category.LAUNCHER] flg=0x10000000 cmp=aurielvilaire.com.stormy/.MainActivity} from pid 893
02-10 14:19:57.890 386-714/system_process I/ActivityManager﹕ Start proc aurielvilaire.com.stormy for activity aurielvilaire.com.stormy/.MainActivity: pid=928 uid=10054 gids={50054, 3003}
02-10 14:20:00.640 928-928/aurielvilaire.com.stormy D/MainActivity﹕ Main UI code is running!
02-10 14:20:02.170 386-400/system_process I/ActivityManager﹕ Displayed aurielvilaire.com.stormy/.MainActivity: +4s339ms
02-10 14:20:05.540 928-943/aurielvilaire.com.stormy D/MainActivity﹕ 1:20 PM
02-10 14:20:05.600 928-943/aurielvilaire.com.stormy E/AndroidRuntime﹕ FATAL EXCEPTION: OkHttp Dispatcher Process: aurielvilaire.com.stormy, PID: 928 android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.
at android.view.ViewRootImpl.checkThread(ViewRootImpl.java:6094)
at android.view.ViewRootImpl.requestLayout(ViewRootImpl.java:824)
at android.view.View.requestLayout(View.java:16431)
at android.view.View.requestLayout(View.java:16431)
at android.view.View.requestLayout(View.java:16431)
at android.view.View.requestLayout(View.java:16431)
at android.view.View.requestLayout(View.java:16431)
at android.view.View.requestLayout(View.java:16431)
at android.widget.RelativeLayout.requestLayout(RelativeLayout.java:352)
at android.view.View.requestLayout(View.java:16431)
at android.widget.TextView.checkForRelayout(TextView.java:6600)
at android.widget.TextView.setText(TextView.java:3813)
at android.widget.TextView.setText(TextView.java:3671)
at android.widget.TextView.setText(TextView.java:3646)
at aurielvilaire.com.stormy.MainActivity.updateDisplay(MainActivity.java:154)
at aurielvilaire.com.stormy.MainActivity.access$500(MainActivity.java:31)
at aurielvilaire.com.stormy.MainActivity$2.onResponse(MainActivity.java:122)
at com.squareup.okhttp.Call$AsyncCall.execute(Call.java:162)
at com.squareup.okhttp.internal.NamedRunnable.run(NamedRunnable.java:33)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
at java.lang.Thread.run(Thread.java:841)
02-10 14:20:05.650 386-397/system_process W/ActivityManager﹕ Force finishing activity aurielvilaire.com.stormy/.MainActivity
02-10 14:20:05.710 386-414/system_process W/InputDispatcher﹕ channel 'b20c7078 aurielvilaire.com.stormy/aurielvilaire.com.stormy.MainActivity (server)' ~ Consumer closed input channel or an error occurred. events=0x9
02-10 14:20:05.710 386-414/system_process E/InputDispatcher﹕ channel 'b20c7078 aurielvilaire.com.stormy/aurielvilaire.com.stormy.MainActivity (server)' ~ Channel is unrecoverably broken and will be disposed!
02-10 14:20:05.720 386-606/system_process W/InputDispatcher﹕ Attempted to unregister already unregistered input channel 'b20c7078 aurielvilaire.com.stormy/aurielvilaire.com.stormy.MainActivity (server)'
02-10 14:20:05.720 386-606/system_process I/WindowState﹕ WIN DEATH: Window{b20c7078 u0 aurielvilaire.com.stormy/aurielvilaire.com.stormy.MainActivity}
02-10 14:20:05.960 386-397/system_process I/WindowManager﹕ Screenshot max retries 4 of Token{b2051338 ActivityRecord{b207d380 u0 aurielvilaire.com.stormy/.MainActivity t2 f}} appWin=Window{b20c7078 u0 aurielvilaire.com.stormy/aurielvilaire.com.stormy.MainActivity EXITING} drawState=4
02-10 14:20:07.260 548-548/com.android.launcher I/Choreographer﹕ Skipped 59 frames! The application may be doing too much work on its main thread.
02-10 14:20:08.550 386-400/system_process W/WindowManager﹕ This window was lost: Window{b20c7078 u0 aurielvilaire.com.stormy/aurielvilaire.com.stormy.MainActivity}
02-10 14:20:08.550 386-400/system_process W/WindowManager﹕ mDisplayId=0 mSession=Session{b210e748 928:u0a10054}
mClient=android.os.BinderProxy#b2116298 mOwnerUid=10054
mShowToOwnerOnly=true package=aurielvilaire.com.stormy appop=NONE
mAttrs=WM.LayoutParams{(0,0)(fillxfill) sim=#120 ty=1 fl=#1810100
pfl=0x8 wanim=0x10302a1} Requested w=1080 h=1776 mLayoutSeq=71
mBaseLayer=21000 mSubLayer=0 mAnimLayer=21000+0=21000 mLastLayer=0
mToken=AppWindowToken{b208c460 token=Token{b2051338
ActivityRecord{b207d380 u0 aurielvilaire.com.stormy/.MainActivity
t2}}} mRootToken=AppWindowToken{b208c460 token=Token{b2051338
ActivityRecord{b207d380 u0 aurielvilaire.com.stormy/.MainActivity
t2}}} mAppToken=AppWindowToken{b208c460 token=Token{b2051338
ActivityRecord{b207d380 u0 aurielvilaire.com.stormy/.MainActivity
t2}}} mViewVisibility=0x0 mHaveFrame=true mObscured=true mSeq=0
mSystemUiVisibility=0x0 mPolicyVisibility=false
mPolicyVisibilityAfterAnim=false mAppOpVisibility=true
mAttachedHidden=false mGivenContentInsets=[0,0][0,0]
mGivenVisibleInsets=[0,0][0,0] mConfiguration={1.0 310mcc260mnc en_US
ldltr sw360dp w360dp h567dp 480dpi nrml port finger qwerty/v/v -nav/h
s.5} mHasSurface=true mShownFrame=[0.0,0.0][1080.0,1776.0]
isReadyForDisplay()=false mFrame=[0,0][1080,1776]
last=[0,0][1080,1776] mSystemDecorRect=[0,0][1080,1776]
last=[0,0][1080,1776] Frames: containing=[0,0][1080,1776]
parent=[0,0][1080,1776] display=[0,0][1080,1776]
overscan=[0,0][1080,1920] content=[0,75][1080,1776]
visible=[0,75][1080,1776] decor=[0,0][1080,1920] Cur insets:
overscan=[0,0][0,0] content=[0,75][0,0] visible=[0,75][0,0] Lst
insets: overscan=[0,0][0,0] content=[0,75][0,0] visible=[0,75][0,0]
WindowStateAnimator{b20db3d0
aurielvilaire.com.stormy/aurielvilaire.com.stormy.MainActivity}:
mSurface=Surface(name=aurielvilaire.com.stormy/aurielvilaire.com.stormy.MainActivity)
mDrawState=HAS_DRAWN mLastHidden=true Surface: shown=false layer=21005
alpha=0.0 rect=(0.0,0.0) 1080.0 x 1776.0 mShownAlpha=1.0 mAlpha=1.0
mLastAlpha=-1.0 mGlobalScale=1.0 mDsDx=1.0 mDtDx=0.0 mDsDy=0.0
mDtDy=1.0 mExiting=false mRemoveOnExit=false mDestroying=true
mRemoved=false
02-10 14:20:52.610 386-606/system_process I/ActivityManager﹕ Start proc com.android.email for broadcast com.android.email/.service.EmailBroadcastReceiver: pid=1049 uid=10024 gids={50024, 3003, 1028, 1015}
02-10 14:20:53.400 1049-1063/com.android.email D/ActivityThread﹕ Loading provider com.android.email.provider;com.android.email.notifier: com.android.email.provider.EmailProvider
02-10 14:20:58.452 386-583/system_process W/ActivityManager﹕ Unable to start service Intent { cmp=com.android.email/.service.AttachmentDownloadService } U=0: not found
02-10 14:20:58.522 1049-1103/com.android.email I/Email﹕Observing account changes for notifications
02-10 14:20:58.622 386-432/system_process I/ActivityManager﹕ Start proc com.android.exchange for service com.android.exchange/.service.EmailSyncAdapterService: pid=1104 uid=10025 gids={50025, 3003, 1028, 1015}
02-10 14:20:58.622 386-607/system_process W/ActivityManager﹕ Unable to start service Intent { cmp=com.android.email/.service.AttachmentDownloadService } U=0: not found
02-10 14:20:58.882 1049-1065/com.android.email D/dalvikvm﹕ GC_FOR_ALLOC freed 313K, 16% free 3359K/3960K, paused 231ms, total 254ms
02-10 14:21:49.352 718-718/com.android.systemui I/Choreographer﹕ Skipped 32 frames! The application may be doing too much work on its main thread.
After reading through that and looking at your code, I believe the main culprit here is that you are doing to much on the main thread. You should use the android AsyncTask to run especially network connections on a separate thread. For example you might use:
private class DownloadForecast extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... urls) {
getForecast(); //run all your network intensive methods
return response;
}
#Override
protected void onPostExecute(String result) {
//update all your UI stuff.
}
Can't seem to correctly intent the code. But thats what you should use. Good luck.

Getting an error when connecting from android to PHP server

I have an android application project that connect to PHP server that I write it in codeigniter.
My JSONparser is:
package com.example.com.tourism;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.List;
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.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;
import android.util.Log;
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
// function get json from url
// by making HTTP POST or GET method
public JSONObject makeHttpRequest(String url, String method,
List<NameValuePair> params) {
// Making HTTP request
try {
// check for request method
if(method == "POST"){
// request method is POST
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(params));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}else if(method == "GET"){
// request method is GET
DefaultHttpClient httpClient = new DefaultHttpClient();
String paramString = URLEncodedUtils.format(params, "utf-8");
url += "?" + paramString;
HttpGet httpGet = new HttpGet(url);
HttpResponse httpResponse = httpClient.execute(httpGet);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
}
and my activity java code that connect to the server is
package com.example.com.tourism;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
public class SignUp extends Activity {
EditText first,last,birth ,pass;
private ProgressDialog pDialog;
private static String url_create_user = "http://10.0.2.2/tourism/index.php/site/register";
JSONParser jsonParser = new JSONParser();
private static final String TAG_SUCCESS = "success";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.sign_up);
Button signUp=(Button)findViewById(R.id.sign_up);
first =(EditText) findViewById(R.id.edfname);
last =(EditText) findViewById(R.id.edlname);
pass =(EditText) findViewById(R.id.edpass);
signUp.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
new Createnewuser().execute();
}
});
}
class Createnewuser extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(SignUp.this);
pDialog.setMessage("Creating User..");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
/**
* Creating product
* */
protected String doInBackground(String... args) {
String name = first.getText().toString();
String price = last.getText().toString();
String description = pass.getText().toString();
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("first_name", name));
params.add(new BasicNameValuePair("last_name", price));
params.add(new BasicNameValuePair("password", description));
// getting JSON Object
// Note that create product url accepts POST method
JSONObject json = jsonParser.makeHttpRequest(url_create_user,
"POST", params);
// check log cat fro response
Log.d("Create Response", json.toString());
// check for success tag
try {
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// successfully created product
Intent i = new Intent(getApplicationContext(), MainActivity.class);
startActivity(i);
// closing this screen
finish();
} else {
// failed to create product
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
// dismiss the dialog once done
pDialog.dismiss();
}
}
and the error in log cat is
07-07 11:30:44.159: E/JSON Parser(20514): Error parsing data org.json.JSONException: Value <!DOCTYPE of type java.lang.String cannot be converted to JSONObject
07-07 11:30:44.189: W/dalvikvm(20514): threadid=11: thread exiting with uncaught exception (group=0x40a71930)
07-07 11:30:44.229: E/AndroidRuntime(20514): FATAL EXCEPTION: AsyncTask #1
07-07 11:30:44.229: E/AndroidRuntime(20514): java.lang.RuntimeException: An error occured while executing doInBackground()
07-07 11:30:44.229: E/AndroidRuntime(20514): at android.os.AsyncTask$3.done(AsyncTask.java:299)
07-07 11:30:44.229: E/AndroidRuntime(20514): at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:352)
07-07 11:30:44.229: E/AndroidRuntime(20514): at java.util.concurrent.FutureTask.setException(FutureTask.java:219)
07-07 11:30:44.229: E/AndroidRuntime(20514): at java.util.concurrent.FutureTask.run(FutureTask.java:239)
07-07 11:30:44.229: E/AndroidRuntime(20514): at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
07-07 11:30:44.229: E/AndroidRuntime(20514): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
07-07 11:30:44.229: E/AndroidRuntime(20514): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
07-07 11:30:44.229: E/AndroidRuntime(20514): at java.lang.Thread.run(Thread.java:856)
07-07 11:30:44.229: E/AndroidRuntime(20514): Caused by: java.lang.NullPointerException
07-07 11:30:44.229: E/AndroidRuntime(20514): at com.example.com.tourism.SignUp$Createnewuser.doInBackground(SignUp.java:98)
07-07 11:30:44.229: E/AndroidRuntime(20514): at com.example.com.tourism.SignUp$Createnewuser.doInBackground(SignUp.java:1)
07-07 11:30:44.229: E/AndroidRuntime(20514): at android.os.AsyncTask$2.call(AsyncTask.java:287)
07-07 11:30:44.229: E/AndroidRuntime(20514): at java.util.concurrent.FutureTask.run(FutureTask.java:234)
07-07 11:30:44.229: E/AndroidRuntime(20514): ... 4 more
07-07 11:30:44.429: I/Choreographer(20514): Skipped 49 frames! The application may be doing too much work on its main thread.
07-07 11:30:44.779: I/Choreographer(20514): Skipped 222 frames! The application may be doing too much work on its main thread.
07-07 11:30:45.069: I/Choreographer(20514): Skipped 149 frames! The application may be doing too much work on its main thread.
07-07 11:30:45.369: I/Choreographer(20514): Skipped 194 frames! The application may be doing too much work on its main thread.
07-07 11:30:45.459: I/Choreographer(20514): Skipped 50 frames! The application may be doing too much work on its main thread.
07-07 11:30:46.019: E/WindowManager(20514): Activity com.example.com.tourism.SignUp has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView{40d743a8 V.E..... R.....ID 0,0-304,96} that was originally added here
07-07 11:30:46.019: E/WindowManager(20514): android.view.WindowLeaked: Activity com.example.com.tourism.SignUp has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView{40d743a8 V.E..... R.....ID 0,0-304,96} that was originally added here
07-07 11:30:46.019: E/WindowManager(20514): at android.view.ViewRootImpl.<init>(ViewRootImpl.java:354)
07-07 11:30:46.019: E/WindowManager(20514): at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:216)
07-07 11:30:46.019: E/WindowManager(20514): at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:69)
07-07 11:30:46.019: E/WindowManager(20514): at android.app.Dialog.show(Dialog.java:281)
07-07 11:30:46.019: E/WindowManager(20514): at com.example.com.tourism.SignUp$Createnewuser.onPreExecute(SignUp.java:75)
07-07 11:30:46.019: E/WindowManager(20514): at android.os.AsyncTask.executeOnExecutor(AsyncTask.java:586)
07-07 11:30:46.019: E/WindowManager(20514): at android.os.AsyncTask.execute(AsyncTask.java:534)
07-07 11:30:46.019: E/WindowManager(20514): at com.example.com.tourism.SignUp$1.onClick(SignUp.java:57)
07-07 11:30:46.019: E/WindowManager(20514): at android.view.View.performClick(View.java:4204)
07-07 11:30:46.019: E/WindowManager(20514): at android.view.View$PerformClick.run(View.java:17355)
07-07 11:30:46.019: E/WindowManager(20514): at android.os.Handler.handleCallback(Handler.java:725)
07-07 11:30:46.019: E/WindowManager(20514): at android.os.Handler.dispatchMessage(Handler.java:92)
07-07 11:30:46.019: E/WindowManager(20514): at android.os.Looper.loop(Looper.java:137)
07-07 11:30:46.019: E/WindowManager(20514): at android.app.ActivityThread.main(ActivityThread.java:5041)
07-07 11:30:46.019: E/WindowManager(20514): at java.lang.reflect.Method.invokeNative(Native Method)
07-07 11:30:46.019: E/WindowManager(20514): at java.lang.reflect.Method.invoke(Method.java:511)
07-07 11:30:46.019: E/WindowManager(20514): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
07-07 11:30:46.019: E/WindowManager(20514): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
07-07 11:30:46.019: E/WindowManager(20514): at dalvik.system.NativeStart.main(Native Method)
i don't know where the problem is, please help me
is my code incorrect ???
if any one have correct code please give it to me i am using codeigniter for php and this is the code that i call it above
function register_get()
{
$json = array('status' => false );
if($this->input->post()==null){
$this -> response($json, 200);
}
$firstname = $this->post("first_name");
$lastname = $this->post("last_name");
$password = $this->post("password");
if(!$firstname || !$lastname || !$password){
$json['status'] = "wrong insert";
$this -> response($json, 200);
}
$this->load->model('Data_model');
$result = $this->Data_model->search($firstname, $lastname);
if($result)
{
$this->Data_model->insert($firstname,$lastname,$password);
$json['status'] = true;
}
// here if false..
$this -> response($json, 200);
}
There are issues with your PHP. You are not passing back any JSON. You will need to change your script to encode your array into JSON.
$result = json_encode($json)
Returning the actual JSON will help. Make sure you are not returning any HTML either. Your Java is trying to parse a JSON response, but you are responding with <!DOCTYPE...

Categories