-2

I'm trying to return string from Foo function, but it application crashes.

public String Foo (String email){
    String url_set = "http://****.php?email=" + email;
    String responseStr = "1";
    try {
        HttpClient httpClient = new DefaultHttpClient();
        HttpPost httpPost = new HttpPost(url_set);
        HttpResponse response = httpClient.execute(httpPost);
        return responseStr;
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
        return responseStr;
    } catch (ClientProtocolException e) {
        Log.e("ClientProtocolException", "Client");
        e.printStackTrace();
        return responseStr;
    } catch (IOException e) {
        Log.e("Ioexception", "Ioexption");
        e.printStackTrace();
        return responseStr;
    }
}

In general I want to convert response to string and return it to caller. But for now I can't ever return string.

UPD: logcat

04-28 14:13:57.220    2917-2917/com.example.lemon.onlineshop E/AndroidRuntime﹕ FATAL EXCEPTION: main
    Process: com.example.lemon.onlineshop, PID: 2917
    android.os.NetworkOnMainThreadException
            at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1147)
            at java.net.InetAddress.lookupHostByName(InetAddress.java:418)
            at java.net.InetAddress.getAllByNameImpl(InetAddress.java:252)
            at java.net.InetAddress.getAllByName(InetAddress.java:215)
            at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:137)
            at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164)
            at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119)
            at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:360)
            at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555)
            at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
            at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465)
            at com.example.lemon.onlineshop.Library.SessionManager.getString(SessionManager.java:88)
            at com.example.lemon.onlineshop.Library.SessionManager.createLoginSession(SessionManager.java:76)
            at com.example.lemon.onlineshop.MainActivity.executeLogIn(MainActivity.java:96)
            at com.example.lemon.onlineshop.MainActivity$LogIn.onPostExecute(MainActivity.java:191)
            at com.example.lemon.onlineshop.MainActivity$LogIn.onPostExecute(MainActivity.java:160)
            at android.os.AsyncTask.finish(AsyncTask.java:632)
            at android.os.AsyncTask.access$600(AsyncTask.java:177)
            at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:645)
            at android.os.Handler.dispatchMessage(Handler.java:102)
            at android.os.Looper.loop(Looper.java:135)
            at android.app.ActivityThread.main(ActivityThread.java:5221)
            at java.lang.reflect.Method.invoke(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:372)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)

UPD2: added whole class

public class SessionManager {
// Shared Preferences
SharedPreferences pref;

// Editor for Shared preferences
SharedPreferences.Editor editor;

// Context
Context _context;

// Shared pref mode
int PRIVATE_MODE = 0;

// Sharedpref file name
private static final String PREF_NAME = "SessionPref";

// All Shared Preferences Keys
private static final String IS_LOGIN = "IsLoggedIn";

// User name (make variable public to access from outside)
public static final String KEY_EMAIL = "email";

// Email address (make variable public to access from outside)
public static final String KEY_PASSWORD = "password";

//
public static final String KEY_ID = "id";

// Constructor
public SessionManager(Context context){
    this._context = context;
    pref = _context.getSharedPreferences(PREF_NAME, PRIVATE_MODE);
    editor = pref.edit();
}

/**
 * Create login session
 * */
public void createLoginSession(String email, String password){
    // Storing login value as TRUE
    editor.putBoolean(IS_LOGIN, true);

    // Storing name in pref
    editor.putString(KEY_EMAIL, email);

    // Storing email in pref
    editor.putString(KEY_PASSWORD, password);

    // Storing id in pref
    editor.putString(KEY_ID, getId(email));
    // commit changes
    editor.commit();
}

public String getId(String email){
    String url_set = "http://***.php?email=" + email;
    String responseStr = "1";
    try {
        HttpClient httpClient = new DefaultHttpClient();
        HttpPost httpPost = new HttpPost(url_set);
        httpClient.execute(httpPost);
        return responseStr;
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
        return responseStr;
    } catch (ClientProtocolException e) {
        Log.e("ClientProtocolException", "Client");
        e.printStackTrace();
        return responseStr;
    } catch (IOException e) {
        Log.e("Ioexception", "Ioexption");
        e.printStackTrace();
        return responseStr;
    }
}
angubenko
  • 264
  • 1
  • 3
  • 11
  • add a return reponseStr; after the last catch block. at this point, if any other exception then the ones you've caught is thrown, you are missing a return statement, making this method uncompilable. – Stultuske Apr 28 '15 at 21:05
  • 3
    @Stultuske: No - if there's a different exception, it will bubble up; if there *isn't* an exception, that means it must have reached the end of the `try` block and returned from there. – Jon Skeet Apr 28 '15 at 21:07
  • return reponseStr doesn't work, android studio says: "Unreachable statement". – angubenko Apr 28 '15 at 21:08
  • @JonSkeet: true. My mistake. but my statement of adding a return statement after the last catch block still stands :) – Stultuske Apr 28 '15 at 21:10
  • @Stultuske: *That* would make it uncompilable, because it would be an unreachable statement. So no, *don't* add an extra return statement after the last catch block... – Jon Skeet Apr 28 '15 at 21:13
  • hmmm, missed the one in the try block... – Stultuske Apr 28 '15 at 21:14
  • Why don't you place the return in a finally block? Finally always gets executed wheter there are exceptions or not. – Rafael R. S. Robles Apr 28 '15 at 21:17
  • `android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1147)` - that may be a clue. Are you trying to do something with the network when you don't have permission to do that? – Makoto Apr 28 '15 at 21:19
  • You must make the network call on `doInBackground()` method not on `onPostExecute()`, because this one is executed on the main thread. I guess this is why you get `NetworkOnMainThreadException`. Please post the full code of your asynctask. – Rami Apr 28 '15 at 21:23
  • @Rami I'm not doing it in AsyncTask. I am creating session and with this I'm trying to get userId from MySQL database by email. Please see updated post. – angubenko Apr 28 '15 at 21:30

1 Answers1

1

You cannot make a network call on the main thread. You need to create a separate thread to run this function.

Jacob Malachowski
  • 911
  • 1
  • 9
  • 18