android.app.Application 处的 android classcastException

发布于 2024-10-05 02:15:14 字数 7826 浏览 6 评论 0原文

当我运行以下应用程序活动时出现以下异常

package com.google.android.SmartStudentmCompanion;


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

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class Login extends  Activity{
    public static String ip_address="192.168.1.101";

    EditText username; 
    EditText password;
    Button login;
    Button exit;
    Toast toast;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.loginscreen);
        System.out.println("onCreate()...");
        username = (EditText) findViewById(R.id.username);
        password = (EditText) findViewById(R.id.password);

        this.login = (Button)findViewById(R.id.loginButton);
        this.login.setOnClickListener(new View.OnClickListener() {
            String usrnm;
            String pwd;

            @Override
            public void onClick(View v) {
                usrnm = username.getText().toString();
                pwd = password.getText().toString();
                System.out.println("onClick()...");
                int length = 0;
                try {
                    System.out.println("hello");
                    String page = executeHttpPost(usrnm,pwd);
                    System.out.println(page);
                    length = page.length();
                } catch (Exception e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }

                if (length == 0){
                    Toast.makeText(getApplicationContext(), 
                            "Invalid username and/or password", 
                            Toast.LENGTH_SHORT).show();
                }
                else {
                    /*Toast.makeText(getApplicationContext(), 
                            "Valid username and password", 
                            Toast.LENGTH_SHORT).show();*/
                    Intent myIntent = new Intent(v.getContext(), VideoViewer.class);
                    startActivityForResult(myIntent, 0);
                }

            }
        });

        this.exit = (Button)findViewById(R.id.exitButton);
        this.exit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
    }


    public String executeHttpPost(String username, String password) throws Exception {
        BufferedReader in = null;

        try {

            ApplicationEx app = (ApplicationEx)this.getApplication();

            HttpClient client = app.getHttpClient();
            HttpPost request = new HttpPost("http://"+ip_address+"/smartstudentmcompanion/check.php");
            List<NameValuePair> postParameters = new ArrayList<NameValuePair>();
            postParameters.add(new BasicNameValuePair("un", username));
            postParameters.add(new BasicNameValuePair("pwd", password));
            UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(postParameters);
            request.setEntity(formEntity);

            HttpResponse response = client.execute(request);

            /*in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
            StringBuffer sb = new StringBuffer("");
            String line = "";
            String NL = System.getProperty("line.separator");
            while ((line = in.readLine()) != null) {
                sb.append(line + NL);
            }
            in.close();*/
            String page = EntityUtils.toString(response.getEntity());
            System.out.println("page: " + page);
            return page;
            } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

应用程序:

package com.google.android.SmartStudentmCompanion;

import org.apache.http.HttpVersion;
import org.apache.http.client.HttpClient;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.scheme.PlainSocketFactory;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpParams;
import org.apache.http.params.HttpProtocolParams;
import org.apache.http.protocol.HTTP;
import android.app.Application;
import android.util.Log;

public class ApplicationEx extends Application {

    private static final String TAG = "ApplicationEx";
    private HttpClient httpClient;
    @Override
    public void onCreate(){
        super.onCreate();
        httpClient = createHttpClient();
    }

    @Override
    public void onLowMemory() {
        super.onLowMemory();
        shutdownHttpClient();
    }

    @Override
    public void onTerminate() {
        super.onTerminate();
        shutdownHttpClient();
    }
    private HttpClient createHttpClient(){
        Log.d(TAG,"createHttpClient()...");
        HttpParams params = new BasicHttpParams();
        HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
        HttpProtocolParams.setContentCharset(params, HTTP.DEFAULT_CONTENT_CHARSET);
        HttpProtocolParams.setUseExpectContinue(params, true);
        SchemeRegistry schReg = new SchemeRegistry();
        schReg.register(new Scheme("http",
                PlainSocketFactory.getSocketFactory(), 80));
        schReg.register(new Scheme("https",
                SSLSocketFactory.getSocketFactory(), 443));
        ClientConnectionManager conMgr = new ThreadSafeClientConnManager(params,schReg);
        return new DefaultHttpClient(conMgr, params);
    }

    public HttpClient getHttpClient() {
        return httpClient;
    }

    private void shutdownHttpClient() {
        if(httpClient!=null && httpClient.getConnectionManager()!=null) {
            httpClient.getConnectionManager().shutdown();
        }
    }
}

清单:

    <?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="com.google.android.SmartStudentmCompanion"
      android:versionCode="1"
      android:versionName="1.0">



    <application android:icon="@drawable/icon" android:label="@string/app_name">
        <activity android:name=".Login"
                  android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity android:name=".VideoViewer"></activity>


    </application>

     <uses-permission
        android:name="android.permission.INTERNET" />
     <uses-sdk android:minSdkVersion="8" />

</manifest> 

i have the following exception when i running the following application

Activity:

package com.google.android.SmartStudentmCompanion;


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

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class Login extends  Activity{
    public static String ip_address="192.168.1.101";

    EditText username; 
    EditText password;
    Button login;
    Button exit;
    Toast toast;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.loginscreen);
        System.out.println("onCreate()...");
        username = (EditText) findViewById(R.id.username);
        password = (EditText) findViewById(R.id.password);

        this.login = (Button)findViewById(R.id.loginButton);
        this.login.setOnClickListener(new View.OnClickListener() {
            String usrnm;
            String pwd;

            @Override
            public void onClick(View v) {
                usrnm = username.getText().toString();
                pwd = password.getText().toString();
                System.out.println("onClick()...");
                int length = 0;
                try {
                    System.out.println("hello");
                    String page = executeHttpPost(usrnm,pwd);
                    System.out.println(page);
                    length = page.length();
                } catch (Exception e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }

                if (length == 0){
                    Toast.makeText(getApplicationContext(), 
                            "Invalid username and/or password", 
                            Toast.LENGTH_SHORT).show();
                }
                else {
                    /*Toast.makeText(getApplicationContext(), 
                            "Valid username and password", 
                            Toast.LENGTH_SHORT).show();*/
                    Intent myIntent = new Intent(v.getContext(), VideoViewer.class);
                    startActivityForResult(myIntent, 0);
                }

            }
        });

        this.exit = (Button)findViewById(R.id.exitButton);
        this.exit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
    }


    public String executeHttpPost(String username, String password) throws Exception {
        BufferedReader in = null;

        try {

            ApplicationEx app = (ApplicationEx)this.getApplication();

            HttpClient client = app.getHttpClient();
            HttpPost request = new HttpPost("http://"+ip_address+"/smartstudentmcompanion/check.php");
            List<NameValuePair> postParameters = new ArrayList<NameValuePair>();
            postParameters.add(new BasicNameValuePair("un", username));
            postParameters.add(new BasicNameValuePair("pwd", password));
            UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(postParameters);
            request.setEntity(formEntity);

            HttpResponse response = client.execute(request);

            /*in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
            StringBuffer sb = new StringBuffer("");
            String line = "";
            String NL = System.getProperty("line.separator");
            while ((line = in.readLine()) != null) {
                sb.append(line + NL);
            }
            in.close();*/
            String page = EntityUtils.toString(response.getEntity());
            System.out.println("page: " + page);
            return page;
            } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

Application:

package com.google.android.SmartStudentmCompanion;

import org.apache.http.HttpVersion;
import org.apache.http.client.HttpClient;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.scheme.PlainSocketFactory;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpParams;
import org.apache.http.params.HttpProtocolParams;
import org.apache.http.protocol.HTTP;
import android.app.Application;
import android.util.Log;

public class ApplicationEx extends Application {

    private static final String TAG = "ApplicationEx";
    private HttpClient httpClient;
    @Override
    public void onCreate(){
        super.onCreate();
        httpClient = createHttpClient();
    }

    @Override
    public void onLowMemory() {
        super.onLowMemory();
        shutdownHttpClient();
    }

    @Override
    public void onTerminate() {
        super.onTerminate();
        shutdownHttpClient();
    }
    private HttpClient createHttpClient(){
        Log.d(TAG,"createHttpClient()...");
        HttpParams params = new BasicHttpParams();
        HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
        HttpProtocolParams.setContentCharset(params, HTTP.DEFAULT_CONTENT_CHARSET);
        HttpProtocolParams.setUseExpectContinue(params, true);
        SchemeRegistry schReg = new SchemeRegistry();
        schReg.register(new Scheme("http",
                PlainSocketFactory.getSocketFactory(), 80));
        schReg.register(new Scheme("https",
                SSLSocketFactory.getSocketFactory(), 443));
        ClientConnectionManager conMgr = new ThreadSafeClientConnManager(params,schReg);
        return new DefaultHttpClient(conMgr, params);
    }

    public HttpClient getHttpClient() {
        return httpClient;
    }

    private void shutdownHttpClient() {
        if(httpClient!=null && httpClient.getConnectionManager()!=null) {
            httpClient.getConnectionManager().shutdown();
        }
    }
}

manifest:

    <?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="com.google.android.SmartStudentmCompanion"
      android:versionCode="1"
      android:versionName="1.0">



    <application android:icon="@drawable/icon" android:label="@string/app_name">
        <activity android:name=".Login"
                  android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity android:name=".VideoViewer"></activity>


    </application>

     <uses-permission
        android:name="android.permission.INTERNET" />
     <uses-sdk android:minSdkVersion="8" />

</manifest> 

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

晨敛清荷 2024-10-12 02:15:14

在清单中更改

<application android:icon="@drawable/icon" android:label="@string/app_name">

<application android:icon="@drawable/icon" android:label="@string/app_name"
    android:name=".ApplicationEx">

由于您尚未指定 android:name,操作系统会查找默认的 Application 类。为了将其指向您的 Application 子类,您应该使用 android:name 属性。

In your manifest change

<application android:icon="@drawable/icon" android:label="@string/app_name">

to

<application android:icon="@drawable/icon" android:label="@string/app_name"
    android:name=".ApplicationEx">

Since you have not stated the android:name for the <applicaton> the OS looks for the default Application class. In order to point it to your Application subclass you should use android:name attribute.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文