I have Written all the code well but i dont know what is the erroe and how to slove it. While i run the programm the following error will occure
Login.java
public class Login extends ActionBarActivity {
final String MyPREFERENCES = "MyPrefs";
SharedPreferences sharedpreferences;
private static final String TAG = "abc";
TextView create;
//Drawer
private ListView mDrawerList;
private DrawerLayout mDrawerLayout;
private ActionBarDrawerToggle mDrawerToggle;
private String mActivityTitle;
//End Drawer
private Button createacc;
private TextView trouble;
private EditText uname;
private EditText pass;
//Asynchronous task variable
// Progress Dialog
private ProgressDialog pDialog;
// Creating JSON Parser object
JSONParser jParser = new JSONParser();
ArrayList<HashMap<String, String>> productsList;
// url to get all products list
private static String url_all_login = "http://surun.co/demo/rest/login";
//Globalstring
String username =null;
String password = null;
//Global Variable for login state checking
public static boolean loginflag = false;
// RelativeLayout relativeLayout=new RelativeLayout(this);
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
getSupportActionBar().setTitle("Surun Support");
// Start Drawer Settings
mDrawerList = (ListView) findViewById(R.id.navListlog);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout_login);
mActivityTitle = getTitle().toString();
addDrawerItems();
setupDrawer();
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
ActionBar bar = getSupportActionBar();
bar.setBackgroundDrawable(new ColorDrawable(Color.parseColor("#F58634")));
// End of Drawer Settings
//Click Text Animation
final Animation myanim, imganim;
myanim = AnimationUtils.loadAnimation(this, R.anim.link_text_anim);
imganim = AnimationUtils.loadAnimation(this, R.anim.rotate);
//End of animation
//Initialize the component
final TextView txtview = (TextView) findViewById(R.id.Login);
create=(TextView)findViewById(R.id.createacc);
uname = (EditText) findViewById(R.id.edituser);
uname.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void afterTextChanged(Editable s) {
validation.isValid(uname, ".+@.+\\.[a-z]+", "Invalid UserName", true);
}
});
pass = (EditText) findViewById(R.id.editpassword);
pass.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void afterTextChanged(Editable s) {
validation.isValid(pass, "[0-9]{10}", "Invalid Mobile No", true);
}
});
final ImageView ivlogo = (ImageView) findViewById(R.id.imageView2);
trouble = (TextView) findViewById(R.id.trouble_login);
//end of initializing component
//Creating underlined text
String udata = "Create Account";
SpannableString content = new SpannableString(udata);
content.setSpan(new UnderlineSpan(), 0, udata.length(), 0);
create.setText(content);
//end of creating underlined text
Toast.makeText(getApplicationContext(), "Create", Toast.LENGTH_LONG).show();
Log.v("TEST", "TEST");
create.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Toast.makeText(getApplicationContext(), "Create Click", Toast.LENGTH_LONG).show();
Intent i = new Intent(getApplicationContext(), Registration_user.class);
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(i);
}
});//End of On click for button
//starting font settings this has prone to error try catch is mandatory while setting font(Overriding native font interface).
try {
Typeface myTypeface = Typeface.createFromAsset(this.getAssets(), "fonts/robotoregular.ttf");
create.setTypeface(myTypeface);
} catch (Exception e) {
Log.v(TAG, "Exception " + e);
}
//End of font settings
sharedpreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
//load preferences if exist
String shareduser = sharedpreferences.getString("User", "");
String sharedpass = sharedpreferences.getString("Password", "");
if ((shareduser.length() > 0) || (sharedpass.length() > 0)) {
//Navigating to main page
Intent i = new Intent(getApplicationContext(), UserLogedIn.class);
i.putExtra("user", shareduser);
i.putExtra("pass", sharedpass);
//Starting An Activity
startActivity(i);
//finish();
} else {
login.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if (uname.getText().length() <= 0 || pass.getText().length() <= 0) {
Toast toast = Toast.makeText(getApplicationContext(), "All Fields Are Mandatory", Toast.LENGTH_SHORT);
toast.show();
trouble.setVisibility(View.VISIBLE);
if (pass.getText().length() > 10) {
Toast toast1 = Toast.makeText(getApplicationContext(), "Four Characters Only...", Toast.LENGTH_SHORT);
toast.show();
trouble.setVisibility(View.VISIBLE);
//Log.v(TAG,"Not Valid");
}
} else {
//Animate Button load animation from anim/rotate.xml
ivlogo.startAnimation(imganim);
username = uname.getText().toString();
password = pass.getText().toString();
//Sending Login Request To Server for validation Using Asynchronus Tasks where username and password as a parameter to method
Log.v(TAG, "Excuting check detail");
new CheckDetail().execute();
//Creating Shared Preferences
}//end of else_if fields are valid
}
});//End of On click for button
}//If no shared preferences found
}//End of onCreate function
/* public void startregistr(View v){
Log.v("IN CREATE", "TEST");
sharedpreferences=getSharedPreferences( MyPREFERENCES, Context.MODE_PRIVATE);
String name=sharedpreferences.getString("name","");
String email=sharedpreferences.getString("email","");
String mobile=sharedpreferences.getString("mobile","");
Intent i = new Intent(getApplicationContext(), Registration_user.class);
startActivity(i);
finish();
Toast.makeText(getApplicationContext(),"Click on Create",Toast.LENGTH_LONG).show();
Log.v(TAG,"Error Occured");
}*/
private void addDrawerItems() {
String[] menuitem = {"Home", "NewTicket", "MyTickets", "About Us", "Logout"};
Integer[] imgid = {
R.drawable.pc1,
R.drawable.pc2,
R.drawable.pc3,
R.drawable.pc4,
R.drawable.pc5,
};
CustomListAdapter adapter = new CustomListAdapter(this, menuitem, imgid);
mDrawerList.setAdapter(adapter);
mDrawerList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
if (position == 1) {
}
}
});
}//End of Add Drawer Items
private void setupDrawer() {
mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout, R.string.drawer_open, R.string.drawer_close) {
/** Called when a drawer has settled in a completely open state. */
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
getSupportActionBar().setTitle("Dashboard!");
invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
}
/** Called when a drawer has settled in a completely closed state. */
public void onDrawerClosed(View view) {
super.onDrawerClosed(view);
getSupportActionBar().setTitle("Surun Infocore");
invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
}
};
mDrawerToggle.setDrawerIndicatorEnabled(true);
mDrawerLayout.setDrawerListener(mDrawerToggle);
}//End of SetupDrawer
@Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
// Sync the toggle state after onRestoreInstanceState has occurred.
mDrawerToggle.syncState();
}//End od OnPostCreate
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
mDrawerToggle.onConfigurationChanged(newConfig);
}//End of onConfigurationChanged
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_admin_home, menu);
return true;
}//End of onCreateOptionMenu
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
//Remove Following Comment To Enable Drawer Toggling On Login Page
/*// Activate the navigation drawer toggle
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}*/
return super.onOptionsItemSelected(item);
}//End of onOptionItemSelected
/**
* Background Async Task to Login by making HTTP Request
*/
class CheckDetail extends AsyncTask<String,String, String> {
/**
* Before starting background thread Show Progress Dialog
*/
@Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(Login.this);
pDialog.setMessage("Logging in. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
/**
* getting All products from url
*/
protected String doInBackground(String... args) {
try {
Log.v(TAG, "In Do in Background");
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("email", username));
params.add(new BasicNameValuePair("pwd", password));
// getting JSON string from URL
JSONObject json =jParser.makeHttpRequest(url_all_login, "POST", params);
//Object Parsing Failed here hence by using trail guide using JSONParser.alternateJSONArray to parse user data.
//Hence not using json instance of object using a BACKUP static variable of Parser class for proccessing.
//To use this backup utility theme the process should be standard and return unique or two out put only or ether way use three logical step
if(json != null) {
// As if login fails it returns object handling fail logic here.
//We can make it general by sending array from server side so we can only use alternateJSONArray variable
}
if(JSONParser.alternateJSONArray != null)
{
Log.v(TAG,"USING BACKUP ARRAY");
//Check your log cat for JSON futher details
for (int jsonArrayElementIndex=0; jsonArrayElementIndex < JSONParser.alternateJSONArray.length(); jsonArrayElementIndex++) {
JSONObject jsonObjectAtJsonArrayElementIndex = JSONParser.alternateJSONArray.getJSONObject(jsonArrayElementIndex);
if(jsonObjectAtJsonArrayElementIndex.getString("email").equals(username) && jsonObjectAtJsonArrayElementIndex.getString("mobile").equals(password))
{
Log.v(TAG,"Login Successful Now setting loginflag true");
loginflag = true;
}
}
}
else
{
//JSON is null ether no data or 204 returned by server
}
} catch (Exception e) {
e.printStackTrace();
Log.v(TAG, "Exception at end :" + e.toString());
//Log.e("TAG", "Error......!RecoverIt");
}
return null ;
}
protected void onPostExecute(String result)
{
// dismiss the dialog after getting all products
//super.onPostExecute();
// pDialog.dismiss();
if(loginflag==true)
{
Log.v(TAG, "Executing Shared Preferences...");
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putString("User", uname.getText().toString());
editor.putString("Password", pass.getText().toString());
editor.commit();
Toast.makeText(getApplicationContext(), "Login Succeed",Toast.LENGTH_SHORT).show();
android.util.Log.v(TAG, "Login Succeed");
Intent i = new Intent(getApplicationContext(), UserLogedIn.class);
startActivity(i);
finish();
}
else
{
Toast.makeText(getApplicationContext(),"Login failed,Invalid Details...!",Toast.LENGTH_LONG).show();
trouble.setVisibility(View.VISIBLE);
}
pDialog.dismiss();
}
}
String getMD5(String pass) {
try {
MessageDigest md = MessageDigest.getInstance("MD5");
byte[] messageDigest = md.digest(pass.getBytes());
BigInteger number = new BigInteger(1, messageDigest);
String hashtext = number.toString(16);
// Now we need to zero pad it if you actually want the full 32 chars.
while (hashtext.length() < 32) {
hashtext = "0" + hashtext;
}
return hashtext;
} catch (NoSuchAlgorithmException e) {
throw new RuntimeException(e);
}
}
/* private int returnParsedJsonObject(String result) {
JSONObject resultObject = null;
int returnedResult = 0;
try {
resultObject = new JSONObject(result);
returnedResult = resultObject.getInt("success");
} catch (JSONException e) {
e.printStackTrace();
}
return returnedResult;
}*/
}
Error Please Slove the problem I have changed the name or package name for personal reason So consider it as right and give me soiution
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.surun.suruninfocore/com.example.surun.suruninfocore.Login}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2345)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2405)
at android.app.ActivityThread.access$800(ActivityThread.java:149)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1324)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:211)
at android.app.ActivityThread.main(ActivityThread.java:5315)
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:941)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:736)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference
at com.example.surun.suruninfocore.Login.onCreate(Login.java:161)
at android.app.Activity.performCreate(Activity.java:5933)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1105)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2298)
XML File
<android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/drawer_layout_login"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:background="#fff">
<android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/drawer_layout_login"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:background="#fff">
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/scrollView3"
android:foregroundGravity="center"
android:fillViewport="false">
<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:paddingLeft="16dp"
android:paddingRight="16dp"
android:paddingTop="7dp"
android:paddingBottom="30dp" tools:context=".AdminHome">
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/imageView2"
android:src="@drawable/surun"
android:paddingStart="30dp"
android:paddingEnd="0dp"
android:paddingLeft="0dp"
android:paddingTop="0dp"
android:paddingRight="0dp"
android:paddingBottom="0dp"
android:adjustViewBounds="true"
android:clickable="true"
android:maxHeight="130dp"
android:minHeight="100dp"
android:longClickable="false"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true" />
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@+id/imageView2"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:id="@+id/linearLayout"
android:gravity="center_horizontal"
android:weightSum="1">
<EditText
android:layout_width="match_parent"
android:layout_height="40dp"
android:id="@+id/edituser"
android:hint="Username-Email_ID"
android:layout_marginTop="20dp"
android:singleLine="true"
android:background="@drawable/edittext_surun"
android:textColor="#ff000005"
android:textColorHint="#71000000"
android:paddingLeft="20dp"
android:layout_marginLeft="20dp"
android:layout_marginRight="20dp" />
<EditText
android:layout_width="match_parent"
android:layout_height="40dp"
android:inputType="textPassword"
android:ems="10"
android:id="@+id/editpassword"
android:hint="Password-Mobile_No"
android:layout_marginTop="20dp"
android:singleLine="true"
android:background="@drawable/edittext_surun"
android:textColor="#ff000005"
android:textColorHint="#71000000"
android:paddingLeft="20dp"
android:layout_marginLeft="20dp"
android:layout_marginRight="20dp" />
<Button
android:layout_width="120dp"
android:layout_height="40dp"
android:text="Login"
android:id="@+id/Login"
android:layout_marginTop="20dp"
android:textColor="#ffffffff"
android:layout_marginLeft="20dp"
android:layout_marginRight="20dp"
android:textStyle="bold"
android:layout_gravity="center_horizontal"
android:background="@drawable/button" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="Create Account"
android:id="@+id/createacc"
android:layout_gravity="center_horizontal"
android:layout_marginTop="30dp"
android:textColor="#ffff"
android:textStyle="bold"
android:background="@drawable/button" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="Trouble In Signing In"
android:id="@+id/trouble_login"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_gravity="center"
android:layout_marginTop="30dp"
android:textColor="#ffff0000"
android:textStyle="bold"
android:visibility="invisible" />
</LinearLayout>
</RelativeLayout>
</ScrollView>
<ListView
android:id="@+id/navListlog"
android:layout_width="200dp"
android:layout_height="match_parent"
android:layout_gravity="left|start"
android:background="#FFFFFF"/>
</android.support.v4.widget.DrawerLayout>