0

This is what i basically how my app function.

  1. this is an app to login to my university website and view student detail.
  2. username and password will post to the login url.
  3. after successful login, i will able to view the student detail in the webView.

I having some problem with my code. i insert the correct username and id but it failed to post the data. i tried some different method but it still not working. Can i know why?

package com.project;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

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 android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.webkit.WebView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class AndroidLogin extends Activity implements OnClickListener {

    Button ok,back,exit;
    TextView result;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        // Login button clicked
        ok = (Button)findViewById(R.id.btn_login);
        ok.setOnClickListener(this);

        result = (TextView)findViewById(R.id.lbl_result);

    }

    public void postLoginData() {
        // Create a new HttpClient and Post Header
        HttpClient httpclient = new DefaultHttpClient();

        /*  returns true if username and password is correct */
        HttpPost httppost = new HttpPost("https://icems.mmu.edu.my/sic/vlogin.jsp");

        try {
            // Add user name and password
            EditText uname = (EditText)findViewById(R.id.txt_username);
            String username = uname.getText().toString();

            EditText pword = (EditText)findViewById(R.id.txt_password);
            String password = pword.getText().toString();

            List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
            nameValuePairs.add(new BasicNameValuePair("form_loginUsername", username));
            nameValuePairs.add(new BasicNameValuePair("login-password", password));
            httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

            // Execute HTTP Post Request
            Log.w("MMU", "Execute HTTP Post Request");
            HttpResponse response = httpclient.execute(httppost);

            String str = inputStreamToString(response.getEntity().getContent()).toString();
            Log.w("MMU", str);

            if(str.toString().equalsIgnoreCase("true"))
            {
                Log.w("MMU", "Login success");

            }else
            {
                Log.w("MMU", "Login fail");

            }

        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    } 

    private StringBuilder inputStreamToString(InputStream is) {
        String line = "";
        StringBuilder total = new StringBuilder();
        // Wrap a BufferedReader around the InputStream
        BufferedReader rd = new BufferedReader(new InputStreamReader(is));
        // Read response until the end
        try {
            while ((line = rd.readLine()) != null) { 
                total.append(line); 
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        // Return full string
        return total;
    }

    @Override
    public void onClick(View view) {
        if(view == ok){
            postLoginData();
            WebView AchievementWeb = (WebView) findViewById(R.id.webViewAchievement);
            AchievementWeb.loadUrl("https://icems.mmu.edu.my/sic/vaas/vaas_main.jsp");
        }
    }

}

This is the logcat

02 03:38:11.502: D/dalvikvm(800): GC_FOR_ALLOC freed 86K, 8% free 2934K/3180K, paused 130ms, total 133ms
01-02 03:38:12.062: D/(800): HostConnection::get() New Host Connection established 0x2a207598, tid 800
01-02 03:38:13.202: E/cutils-trace(800): Error opening trace file: No such file or directory (2)
01-02 03:38:13.582: D/TilesManager(800): Starting TG #0, 0x2a2ea4c0
01-02 03:38:39.863: D/InputEventConsistencyVerifier(800): KeyEvent: ACTION_UP but key was not down.
01-02 03:38:39.863: D/InputEventConsistencyVerifier(800):   in android.widget.EditText{417107b8 VFED..CL .F....I. 102,114-252,162 #7f050004 app:id/txt_password}
01-02 03:38:39.863: D/InputEventConsistencyVerifier(800):   0: sent at 172536000000, KeyEvent { action=ACTION_UP, keyCode=KEYCODE_TAB, scanCode=15, metaState=0, flags=0x8, repeatCount=0, eventTime=172536, downTime=172448, deviceId=0, source=0x101 }
01-02 03:38:43.723: W/MMU(800): Execute HTTP Post Request
01-02 03:38:44.943: D/dalvikvm(800): GC_FOR_ALLOC freed 339K, 14% free 3108K/3608K, paused 39ms, total 42ms
01-02 03:38:45.163: W/MMU(800): <HTML><HEAD><TITLE>500 Internal Server Error</TITLE></HEAD><BODY><H1>500 Internal Server Error</H1><PRE>java.lang.NullPointerException<br></PRE></BODY></HTML>
01-02 03:38:45.163: W/MMU(800): Login fail
01-02 03:38:46.123: E/chromium_net(800): external/chromium/net/disk_cache/block_files.cc:81: [0102/033846:ERROR:block_files.cc(81)] Failing CreateMapBlock
01-02 03:38:46.132: E/chromium_net(800): external/chromium/net/disk_cache/entry_impl.cc:904: [0102/033846:ERROR:entry_impl.cc(904)] Failed to save user data
01-02 03:38:46.483: E/chromium_net(800): external/chromium/net/disk_cache/rankings.cc:762: [0102/033846:ERROR:rankings.cc(762)] Inconsistent LRU.
01-02 03:38:46.483: E/chromium_net(800): external/chromium/net/disk_cache/backend_impl.cc:1107: [0102/033846:ERROR:backend_impl.cc(1107)] Critical error found -8
01-02 03:38:46.483: W/chromium_net(800): external/chromium/net/disk_cache/storage_block-inl.h:119: [0102/033846:WARNING:storage_block-inl.h(119)] Failed data load.
01-02 03:38:46.513: W/chromium_net(800): external/chromium/net/disk_cache/storage_block-inl.h:119: [0102/033846:WARNING:storage_block-inl.h(119)] Failed data load.
01-02 03:38:46.533: W/chromium_net(800): external/chromium/net/disk_cache/storage_block-inl.h:119: [0102/033846:WARNING:storage_block-inl.h(119)] Failed data load.
01-02 03:38:46.553: D/chromium(800): Unknown chromium error: -401
cf chan
  • 108
  • 1
  • 6

3 Answers3

0

You should post your error message to solve your problem. But i think you get a "NetworkOnMainThreadException" because you are trying to perform a network operation on your applications main thread. You can use Async Task.

You can check this to solve your problem. How to fix android.os.NetworkOnMainThreadException?

If you get a different error please post error message.

Community
  • 1
  • 1
savepopulation
  • 11,736
  • 4
  • 55
  • 80
  • There's something wrong with your api. Check your name value pairs and backend code. To make a guess, can "login-password" be login_password"? – savepopulation Jan 02 '15 at 15:00
0
    HttpClient client = new DefaultHttpClient();
    HttpPost httppost = new HttpPost(
            "enterwebsite");

    httppost.setHeader("Content-Type", "application/x-www-form-urlencoded");
    // httppost.setHeader("Content-Type",
    // "application/x-www-form-urlencoded");
    List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
    nameValuePairs.add(new BasicNameValuePair("oauth_uid", oauth_uid));
    nameValuePairs.add(new BasicNameValuePair("group_id", group_id));
    nameValuePairs.add(new BasicNameValuePair("user_id", user_id));

    HttpResponse mresponce;

    try {
        httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs, "UTF-8"));
        mresponce = client.execute(httppost);

        HttpEntity mentity = mresponce.getEntity();
        mstream = mentity.getContent();
        BufferedReader reader = new BufferedReader(new InputStreamReader(
                mstream, "iso-8859-1"), 8);
        StringBuilder sb = new StringBuilder();
        String line = null;
        while ((line = reader.readLine()) != null) {
            sb.append(line);

        }

        String json = sb.toString();

        Log.v("JOIN", json);

        mList = new ArrayList<GetterSetteList>();
        Object obj = new JSONTokener(json).nextValue();
        if (obj instanceof JSONObject) {
            JSONObject objs = new JSONObject(json);

            messagex = (String) objs.opt("message");
        }

    } catch (Exception e) {
        // TODO Auto-generated catch block
        Log.v("ERROR", "API_JoinGroup" + e.toString());
        flag = 1;
        e.printStackTrace();
        Log.v("JOIN", e.toString());
    }
wadali
  • 2,221
  • 1
  • 20
  • 38
0

As others have mentioned you should wrap your call to "postLoginData()" in a asynctask otherwise this call will give you a NetworkOnMainThreadException". However from the logs you pasted I see this being printed.

> 01-02 03:38:45.163: W/MMU(800): <HTML><HEAD><TITLE>500 Internal Server
> Error</TITLE></HEAD><BODY><H1>500 Internal Server
> Error</H1><PRE>java.lang.NullPointerException<br></PRE></BODY></HTML>

Are you sure the URL that you are using "https://icems.mmu.edu.my/sic/vlogin.jsp" and the query-params "form_loginUserName" and "login-password" correct? Does it work from a normal POST client or anywhere else?

Sriram
  • 55
  • 6