0

Here is the code of my application i want to call an API from my application. this is a web API and i have written it my self its link is projectbuddy-1.apphb.com/api/SignIn?email=ali@yahoo.com&pass=123 this is my code i want to get user's data and parse it and send it to next activity using 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);
        }
    }

this is my 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>

Please Help. Thank you all My Logcat shows this 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) at android.os.AsyncTask.finish(AsyncTask.java:631) at android.os.AsyncTask.access$600(AsyncTask.java:177) at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:644) at android.os.Handler.dispatchMessage(Handler.java:107) at android.os.Looper.loop(Looper.java:194) at android.app.ActivityThread.main(ActivityThread.java:5371) at java.lang.reflect.Method.invokeNative(Native Method) at java.lang.reflect.Method.invoke(Method.java:525) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:833) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:600) at dalvik.system.NativeStart.main(Native Method)

Ali Mohsan
  • 326
  • 2
  • 15

1 Answers1

1

There area a few erros: if user is null then this will throw NullPoinerException

user.equals(null)

check

user == null

instead if data is null then this will throw NullPoinerException

(data.contains("Unable to locate server"))

check if null before invoking methods on an object. In addition i suggest you read about AsyncTask because you need to check whether your activity is still active. Also, it is suggested not to use ApplicationContext all over the app, it may cause leaks.

EE66
  • 4,601
  • 1
  • 17
  • 20