调用Api会导致Android应用程序崩溃

时间:2015-05-30 21:18:23

标签: android asp.net-web-api json.net

以下是我想从我的应用程序调用API的应用程序代码。这是一个Web API,我自己写了它的链接是projectbuddy-1.apphb.com/api/SignIn?email=ali@yahoo.com&pass=123 这是我的代码我想获取用户的数据并解析它并使用intent

将其发送到下一个活动
    package com.example.ali.projectbuddy;

import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.database.Cursor;
import android.widget.Toast;
import android.app.Activity;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ExpandableListView;
import android.widget.TextView;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONObject;
import android.media.Image;


public class SignIn extends Activity {


    String data = null;
    String url;
    Database.User user = null;
    Button Login=null;
    boolean verified=false;
    String id = null;
    String pass=null;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_sign_in);

        Toast.makeText(com.example.ali.projectbuddy.SignIn.this,"Hi",Toast.LENGTH_LONG).show();
        // get the Refferences of views


        }
    public void LoginClicked(View v)
    {


        boolean isConnected  = isNetworkAvailable();
        if(isConnected == true)
        {
            Toast.makeText(getApplicationContext() , "Is Connected" ,Toast.LENGTH_SHORT).show();
            EditText editTextUserName = (EditText) findViewById(R.id.Email);
            EditText editTextPassword = (EditText) findViewById(R.id.Password);

            // get The User name and Password
            id = editTextUserName.getText().toString();
            pass = editTextPassword.getText().toString();

            String id1;
            String pass1;
            id1=id;
            pass1=pass;



            if(id1.isEmpty() && pass1.isEmpty())
            {
                Toast.makeText(getApplicationContext() , "Please enter your username and password" ,Toast.LENGTH_SHORT).show();
            }
            else if(id1.isEmpty())
            {
                Toast.makeText(getApplicationContext() , "Please enter your username" ,Toast.LENGTH_SHORT).show();
            }
            else if(pass1.isEmpty())
            {
                Toast.makeText(getApplicationContext() , "Please enter your password" ,Toast.LENGTH_SHORT).show();
            }
            else
            {
                Toast.makeText(getApplicationContext() , "Calling Api" ,Toast.LENGTH_SHORT).show();
                url = "http://projectbuddy-1.apphb.com/api/SignIn?email=ali@yahoo.com&pass=123";

                MyAsynchTask task=new MyAsynchTask();
                task.execute();

            }
        }
        else
        {

            Toast.makeText(getApplicationContext() , "No Network connection, please try again." ,Toast.LENGTH_LONG).show();
        }

    }


    public boolean isNetworkAvailable() {
        ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(getApplicationContext().CONNECTIVITY_SERVICE);
        NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
        return activeNetworkInfo != null && activeNetworkInfo.isConnected();

    }

    public class MyAsynchTask extends AsyncTask<Void, Void, Void> {

        @Override
        protected void onPreExecute() {

            Toast.makeText(getApplicationContext() , "On PreExecute" ,Toast.LENGTH_SHORT).show();
            super.onPreExecute();


        }

        @Override
        protected Void doInBackground(Void... void0) {


            try {
                ServiceHandler obj = new ServiceHandler();
                data = obj.makeServiceCall(url, ServiceHandler.GET);
            } catch (Exception e) {
                data = "Unable to locate server.";
            }

            try {
                Toast.makeText(getApplicationContext() , "Getting JSON onject" ,Toast.LENGTH_SHORT).show();
                JSONObject object = new JSONObject(data);

                user.name = object.getString("name");
                user.country = object.getString("country");
                user.city = object.getString("city");
                user.id = object.getInt("user_id");
                user.mobileNo = object.getString("mobileNo");
                //  user.image=(Image)object.get("image");


            } catch (Exception ex) {

            }

            return null;
        }

        @Override
        protected void onPostExecute(Void abc) {
            super.onPostExecute(abc);

            if(user.equals(null))
            {
                verified=false;
                Toast.makeText(getApplicationContext(), "UserName or Password Incorrect", Toast.LENGTH_LONG).show();


            }
            else if(data.contains("Unable to locate server"))
            {
                verified=false;
                Toast.makeText(getApplicationContext(), "Unable to Locate Server.Check your Internet Connection.", Toast.LENGTH_LONG).show();


            }
            else
            {
                // Editor editor = sharedpreferences.edit();
                verified=true;
                Intent i = new Intent(getApplicationContext(),Welcome_Page.class);
                i.putExtra("username",user.name);
                i.putExtra("useremail",user.email);
                i.putExtra("userid",user.id);
                i.putExtra("usermobileno",user.mobileNo);
                i.putExtra("usercountry",user.country);
                i.putExtra("usercity",user.city);
                i.putExtra("Verified",verified);
                startActivity(i);
            }



        }



    }
    @Override
    protected void onDestroy() {
        // TODO Auto-generated method stub
        super.onDestroy();

    }

    /*
    public void SignInClick2(View v) {
   //     Toast.makeText(com.example.ali.projectbuddy.SignIn.this,"Hi3",Toast.LENGTH_LONG).show();
        Intent i = new Intent(SignIn.this,Welcome_Page.class);
        i.putExtra("username",user.name);
        i.putExtra("useremail",user.email);
        i.putExtra("userid",user.id);
        i.putExtra("usermobileno",user.mobileNo);
        i.putExtra("usercountry",user.country);
        i.putExtra("usercity",user.city);
        startActivity(i);
    }*/
        public void SignUpClick(View v) {
            Intent i = new Intent(this, SignUp.class);
            startActivity(i);
        }
    }

这是我的xml

<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:background="@color/material_blue_grey_800"
    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.ali.projectbuddy..Login" >
    <GridLayout
        android:layout_width="fill_parent"
        android:layout_height="300px"
        android:layout_alignParentStart="true"
        android:id="@+id/gridLayout">
        <ImageView
            android:layout_width="96dp"
            android:layout_height="143dp"
            android:id="@+id/imageView"
            android:layout_row="0"
            android:layout_column="0"
            android:background="@drawable/icon1"/>

        <TextView android:text="@string/Project"
            android:textSize="18pt"
            android:textAlignment="center"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textColor="#73e0f4"
            style="@style/Base.TextAppearance.AppCompat.Title"
            android:background="@color/material_blue_grey_800"
            android:id="@+id/textView"
            android:layout_alignParentTop="true"
            android:layout_alignParentEnd="true"
            android:layout_row="0"
            android:layout_column="8" />
    </GridLayout>
    <EditText
        android:id="@+id/Email"
        android:layout_width="match_parent"
        android:layout_height="32dp"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="200dp"
        android:textSize="22dp"
        android:textColor="#FFFFFF"
        android:background="#07000000"
        android:ems="10"
        android:hint="Email"

        android:inputType="textEmailAddress"

        >

        <requestFocus />
    </EditText>

    <EditText
        android:id="@+id/Password"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_below="@id/Email"
        android:layout_marginTop="27dp"
        android:ems="10"
        android:textSize="22dp"
        android:textColor="#FFFFFF"
        android:background="#07000000"
        android:hint="Password"
        android:inputType="textWebPassword" />


    <TextView
        android:id="@+id/ForgetPassword"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textColor="#FFFFFF"
        android:text="ForgetPassword"
        android:textSize="22dp"
        android:onClick="ForgetPasswordClick"
        android:layout_below="@+id/SignUp"
        android:layout_alignParentStart="true"
        android:layout_marginTop="10dp" />

    <TextView
        android:id="@+id/SignUp"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="New User? Want to SignUp?"
        android:textSize="22dp"
        android:onClick="SignUpClick"
        android:layout_marginTop="40dp"
        android:textColor="#FFFFFF"
        android:layout_below="@+id/Password"
        android:layout_alignParentStart="true" />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="New Button"
        android:id="@+id/button"
        android:clickable="true"

        android:layout_alignParentBottom="true"
        android:layout_alignEnd="@+id/Password" />

    </RelativeLayout>

请帮助。谢谢你们  我的Logcat显示了这个 06-01 00:02:23.717 3714-3714 / com.example.ali.projectbuddy E / AndroidRuntime:FATAL EXCEPTION:main     显示java.lang.NullPointerException             at com.example.ali.projectbuddy.SignIn $ MyAsynchTask.onPostExecute(SignIn.java:162)             at com.example.ali.projectbuddy.SignIn $ MyAsynchTask.onPostExecute(SignIn.java:117)             在android.os.AsyncTask.finish(AsyncTask.java:631)             在android.os.AsyncTask.access $ 600(AsyncTask.java:177)             在android.os.AsyncTask $ InternalHandler.handleMessage(AsyncTask.java:644)             在android.os.Handler.dispatchMessage(Handler.java:107)             在android.os.Looper.loop(Looper.java:194)             在android.app.ActivityThread.main(ActivityThread.java:5371)             at java.lang.reflect.Method.invokeNative(Native Method)             在java.lang.reflect.Method.invoke(Method.java:525)             在com.android.internal.os.ZygoteInit $ MethodAndArgsCaller.run(ZygoteInit.java:833)             在com.android.internal.os.ZygoteInit.main(ZygoteInit.java:600)             在dalvik.system.NativeStart.main(本地方法)

1 个答案:

答案 0 :(得分:1)

区域有一些错误: 如果user为null,那么这将抛出NullPoinerException

  

user.equals(空)

检查

  

user == null

代替 如果data为null,那么这将抛出NullPoinerException

  

(data.contains(“无法找到服务器”))

在调用对象上的方法之前检查是否为null。 另外我建议您阅读有关AsyncTask的内容,因为您需要检查您的活动是否仍然有效。 此外,建议不要在整个应用程序中使用ApplicationContext,否则可能会导致泄漏。