Button is not working correctly (android studio) - android

I'm a little newbie on android, and my button it's not working properly when i run my app.
Here is my java code:
package com.example.neak.phore;
import android.content.Intent;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import org.json.JSONArray;
import org.json.JSONException;
import java.util.ArrayList;
import cz.msebera.android.httpclient.Header;
public class MainActivity extends ActionBarActivity {
Button btLoginL;
EditText etEmail, etPassL;
TextView tvRegistrarGo;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btLoginL = (Button) findViewById(R.id.btLoginL);
etEmail = (EditText) findViewById(R.id.etEmailL);
etPassL = (EditText) findViewById(R.id.etPassL);
tvRegistrarGo = (TextView) findViewById(R.id.tvRegistrarGo);
final String email = etEmail.getText().toString();
final String pass = etPassL.getText().toString();
btLoginL.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
EnviarDatos(email, pass);
}
});
tvRegistrarGo.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent registrar = new Intent(MainActivity.this, Registrar.class);
startActivity(registrar);
}
});
}
public void EnviarDatos(String email, String pass){
String URL = "192.168.2.15/android/login.php";
RequestParams params = new RequestParams();
params.put("email",email);
params.put("pass", pass);
AsyncHttpClient clienteL = new AsyncHttpClient();
clienteL.put(URL, params, new AsyncHttpResponseHandler() {
#Override
public void onSuccess(int i, Header[] headers, byte[] bytes) {
getDataJson(new String(bytes));
}
#Override
public void onFailure(int i, Header[] headers, byte[] bytes, Throwable throwable) {
Toast.makeText(getApplicationContext(), "Fallo en la conexion", Toast.LENGTH_SHORT);
}
});
}
public ArrayList<String> getDataJson(String response){
ArrayList<String> Logstat = new ArrayList<>();
try{
JSONArray recoger = new JSONArray(response);
String status;
status=recoger.getJSONObject(0).getString("estado");
comprobar(status);
} catch (Exception e) {
e.printStackTrace();
}
return Logstat;
}
public void comprobar(String status){
if(status.equals("0")){
Toast.makeText(getApplicationContext(),"Usuario o contraseña incorrectos",Toast.LENGTH_SHORT);
}else{
Toast.makeText(getApplicationContext(),"Login correcto",Toast.LENGTH_SHORT);
}
}
}
And here is my xml code:
<?xml version="1.0" encoding="utf-8"?>
<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:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:background="#25ae90"
tools:context="com.example.neak.phore.MainActivity">
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="textPersonName"
android:ems="10"
android:hint="Nombre de usuario"
android:id="#+id/etEmailL"
android:layout_marginTop="116dp"
android:background="#ffffff"
android:padding="10dp"
android:layout_alignParentTop="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginBottom="12dp" />
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="textPassword"
android:ems="10"
android:hint="Contraseña"
android:id="#+id/etPassL"
android:layout_below="#+id/etEmailL"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:padding="10dp"
android:background="#ffffff"
android:layout_marginBottom="10dp" />
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Entrar"
android:id="#+id/btLoginL"
android:background="#ffffff"
android:layout_below="#+id/etPassL"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:layout_marginTop="33dp"
android:textColor="#25ae90" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Aun no eres miembro? Registrate!"
android:id="#+id/tvRegistrarGo"
android:layout_below="#+id/btLoginL"
android:layout_centerHorizontal="true"
android:layout_marginTop="35dp"
android:textStyle="bold"
android:textSize="15dp"
android:textColor="#ffffff" />
</RelativeLayout>
The problem is when i run the app, the button does nothing, but if i change the button Onclick for
tvRegistrarGo.setText("Prueba");
the button works! I'm working with:
this sdk version and this build tools version
This is the logcat i get when i pressed one hundred times the button, but if i press once the edit text with the onclick it appears on the logcat:
01-26 23:21:51.309 6706-6706/? I/art: Late-enabling -Xcheck:jni
01-26 23:21:51.476 6706-6742/com.example.neak.phore D/OpenGLRenderer: Use EGL_SWAP_BEHAVIOR_PRESERVED: true
01-26 23:21:51.482 6706-6706/com.example.neak.phore D/Atlas: Validating map...
01-26 23:21:51.528 6706-6742/com.example.neak.phore I/Adreno-EGL: <qeglDrvAPI_eglInitialize:410>: EGL 1.4 QUALCOMM build: AU_LINUX_ANDROID_LA.BF.1.1.1_RB1.05.01.00.042.030_msm8974_LA.BF.1.1.1_RB1__release_AU ()
OpenGL ES Shader Compiler Version: E031.25.03.06
Build Date: 05/17/15 Sun
Local Branch: mybranch10089422
Remote Branch: quic/LA.BF.1.1.1_rb1.22
Local Patches: NONE
Reconstruct Branch: AU_LINUX_ANDROID_LA.BF.1.1.1_RB1.05.01.00.042.030 + 6151be1 + NOTHING
01-26 23:21:51.529 6706-6742/com.example.neak.phore I/OpenGLRenderer: Initialized EGL, version 1.4
01-26 23:21:51.555 6706-6742/com.example.neak.phore D/OpenGLRenderer: Enabling debug mode 0
01-26 23:21:51.627 6706-6706/com.example.neak.phore I/Timeline: Timeline: Activity_idle id: android.os.BinderProxy#1dfc7494 time:17054805
01-26 23:22:48.574 6706-6706/com.example.neak.phore I/Timeline: Timeline: Activity_launch_request id:com.example.neak.phore time:17111752
01-26 23:22:48.715 6706-6706/com.example.neak.phore I/Timeline: Timeline: Activity_idle id: android.os.BinderProxy#815ccf4 time:17111893
01-26 23:22:52.005 6706-6706/com.example.neak.phore I/Timeline: Timeline: Activity_idle id: android.os.BinderProxy#1dfc7494 time:17115184

The problem is that you are reading the values of your EditTexts before the user has a chance to enter them.
Change this:
final String email = etEmail.getText().toString();
final String pass = etPassL.getText().toString();
btLoginL.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
EnviarDatos(email, pass);
}
to this
btLoginL.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
EnviarDatos(
etEmail.getText().toString(),
etPassL.getText().toString() );
}

Related

How to send string from one activity to another

I am trying to make an app to list the schools in my area and I made a table in a database to contain these schools. I made a list view with clickable items to list the names of the schools and when I click on the item to move to another activity and send the clicked school name in order to list more information about the school, the app stops working. The following is one of the activities that contains this list view:
package com.example.welcome.madrasti;
import android.content.Intent;
import android.database.Cursor;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import java.util.ArrayList;
import java.util.List;
public class ListOfSchoolsPublic extends AppCompatActivity {
Intent redirect;
Intent item;
ListView list;
ArrayList<String> _sa;
DBAdapter db;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list_of_schools_public);
openDB();
list= (ListView) findViewById(R.id.usersList);
redirect = getIntent();
Cursor cursor = db.getAllRows();
_sa= new ArrayList<String>();
//cursor.moveToFirst();
Log.d("CURSORCOUNT","Number of rows in the Cursor is = " + String.valueOf(cursor.getCount()));
while(cursor.moveToNext()) {
if(cursor.getString(DBAdapter.COL_SChOOL_TYPE_TABLE_2).equals("حكومية"))
_sa.add(cursor.getString(DBAdapter.COL_SCHOOLNAME_TABLE_2));
}
cursor.close();
#SuppressWarnings("rawtypes")
ArrayAdapter adapter = new ArrayAdapter(this,android.R.layout.simple_list_item_1,_sa);
list.setAdapter(new TempLyaout(ListOfSchoolsPublic.this,_sa));
list.setOnItemClickListener(new AdapterView.OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> arg0, View arg1,int position, long arg3)
{
String selectedItem = (String) arg0.getItemAtPosition(position);
itemInfo(selectedItem);
}
});
}
///////////////////////////////////////////////////////////////
public void itemInfo(String selectedItem){
item = new Intent(getApplicationContext(), NewSchool.class);
item.putExtra("schoolName",selectedItem);
startActivity(item);
}
///////////////////////////////////////////////////////////////
#Override
protected void onDestroy() {
super.onDestroy();
closeDB();
}// end onDestroy method
///////////////////////////////////////////////////////////////
private void openDB() {
db = new DBAdapter(ListOfSchoolsPublic.this);
db.open();
} // end openDB method
//////////////////////////////////////////////////////////////
private void closeDB() {
db.close();
} // end closeDB method
}
The following is the activity that each list item should move to:
package com.example.welcome.madrasti;
import android.content.Intent;
import android.database.Cursor;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class NewSchool extends AppCompatActivity {
Intent intent;
Intent nextPage;
Button next;
DBAdapter db;
TextView t1;
TextView t2;
TextView t3;
TextView t4;
TextView t5;
String name;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_new_school);
t1=(TextView)findViewById(R.id.textView9) ;
t2=(TextView)findViewById(R.id.textView11) ;
t3=(TextView)findViewById(R.id.textView12) ;
t4=(TextView)findViewById(R.id.textView17) ;
t5=(TextView)findViewById(R.id.textView18) ;
next = (Button) findViewById(R.id.button);
intent = getIntent();
name = intent.getStringExtra("schoolName");
next.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
goNext();
}
});
Cursor cursor = db.getAllRows();
while(cursor.moveToNext()) {
if(cursor.getString(DBAdapter.COL_SCHOOLNAME_TABLE_2).equals(name)){
t1.setText(DBAdapter.COL_SCHOOLNAME_TABLE_2);
t2.setText(DBAdapter.COL_FOUNDATION_DATE_TABLE_2);
t3.setText(DBAdapter.COL_BUY_BOOKS_TABLE_2);
t4.setText(DBAdapter.COL_HEALTH_TABLE_2);
t5.setText(DBAdapter.COL_LOCATION_TABLE_2);
}
}
cursor.close();
}
public void goNext(){
nextPage = new Intent(getApplicationContext(),NewShoolAct2.class);
nextPage.putExtra("schoolName",name);
startActivity(nextPage);
}
///////////////////////////////////////////////////////////////
#Override
protected void onDestroy() {
super.onDestroy();
closeDB();
}// end onDestroy method
///////////////////////////////////////////////////////////////
private void openDB() {
db = new DBAdapter(NewSchool.this);
db.open();
} // end openDB method
//////////////////////////////////////////////////////////////
private void closeDB() {
db.close();
} // end closeDB method
}
The following is the XML of the previous activity:
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#drawable/login_background"
tools:context="com.example.welcome.madrasti.NewSchool">
<AbsoluteLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:layout_editor_absoluteX="16dp"
tools:layout_editor_absoluteY="0dp">
<TextView
android:id="#+id/textView"
android:layout_width="80dp"
android:layout_height="30dp"
android:layout_x="244dp"
android:layout_y="54dp"
android:text="إسم المدرسة:"
android:textAlignment="center"
android:textStyle="bold"
tools:layout_editor_absoluteX="dp"
tools:layout_editor_absoluteY="10dp" />
<TextView
android:id="#+id/textView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_x="240dp"
android:layout_y="127dp"
android:text="تاريخ التأسيس:"
android:textAlignment="center"
android:textStyle="bold"
tools:layout_editor_absoluteX="297dp"
tools:layout_editor_absoluteY="144dp" />
<TextView
android:id="#+id/textView4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_x="231dp"
android:layout_y="185dp"
android:text="كيفية شراء الكتب:"
android:textAlignment="center"
android:textStyle="bold"
tools:layout_editor_absoluteX="284dp"
tools:layout_editor_absoluteY="210dp" />
<TextView
android:id="#+id/textView5"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_x="215dp"
android:layout_y="265dp"
android:text="وضع المرافق الصحية:"
android:textAlignment="center"
android:textStyle="bold"
tools:layout_editor_absoluteX="265dp"
tools:layout_editor_absoluteY="288dp" />
<TextView
android:id="#+id/textView6"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_x="244dp"
android:layout_y="340dp"
android:text="موقع المدرسة:"
android:textAlignment="center"
android:textStyle="bold"
tools:layout_editor_absoluteX="300dp"
tools:layout_editor_absoluteY="368dp" />
<Button
android:id="#+id/button"
android:layout_width="98dp"
android:layout_height="34dp"
android:layout_x="133dp"
android:layout_y="434dp"
android:background="#drawable/button"
android:text="التالي"
android:textAlignment="center"
android:textColor="#ffff"
android:textStyle="bold"
tools:layout_editor_absoluteX="45dp"
tools:layout_editor_absoluteY="426dp" />
<TextView
android:id="#+id/textView9"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_x="11dp"
android:layout_y="77dp"
android:text="TextView"
tools:layout_editor_absoluteX="18dp"
tools:layout_editor_absoluteY="59dp" />
<TextView
android:id="#+id/textView11"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_x="12dp"
android:layout_y="148dp"
android:text="TextView"
tools:layout_editor_absoluteX="12dp"
tools:layout_editor_absoluteY="150dp" />
<TextView
android:id="#+id/textView12"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_x="32345dp"
android:layout_y="32418dp"
android:text="TextView"
tools:layout_editor_absoluteX="16dp"
tools:layout_editor_absoluteY="235dp" />
<TextView
android:id="#+id/textView17"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_x="15dp"
android:layout_y="299dp"
android:text="TextView"
tools:layout_editor_absoluteX="21dp"
tools:layout_editor_absoluteY="37dp" />
<TextView
android:id="#+id/textView18"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_x="16dp"
android:layout_y="372dp"
android:text="TextView"
tools:layout_editor_absoluteX="17dp"
tools:layout_editor_absoluteY="381dp" />
<TextView
android:id="#+id/textView20"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_x="16dp"
android:layout_y="219dp"
android:text="TextView"
tools:layout_editor_absoluteX="10dp"
tools:layout_editor_absoluteY="215dp" />
</AbsoluteLayout>
</android.support.constraint.ConstraintLayout>
The following is the log cat when the app is crashed:
04-13 17:57:49.245 5828-5828/? E/libprocessgroup: failed to make and chown /acct/uid_10059: Read-only file system
04-13 17:57:49.245 5828-5828/? W/Zygote: createProcessGroup failed, kernel missing CONFIG_CGROUP_CPUACCT?
04-13 17:57:49.245 5828-5828/? I/art: Late-enabling -Xcheck:jni
04-13 17:57:49.435 5828-5838/? I/art: Debugger is no longer active
04-13 17:57:49.492 5828-5828/? I/InstantRun: starting instant run server: is main process
04-13 17:57:49.602 5828-5843/? W/art: Suspending all threads took: 11.737ms
04-13 17:57:49.605 5828-5843/? I/art: Background sticky concurrent mark sweep GC freed 2038(168KB) AllocSpace objects, 0(0B) LOS objects, 25% free, 832KB/1117KB, paused 13.068ms total 21.305ms
04-13 17:57:49.630 5828-5828/? W/art: Before Android 4.1, method android.graphics.PorterDuffColorFilter android.support.graphics.drawable.VectorDrawableCompat.updateTintFilter(android.graphics.PorterDuffColorFilter, android.content.res.ColorStateList, android.graphics.PorterDuff$Mode) would have incorrectly overridden the package-private method in android.graphics.drawable.Drawable
04-13 17:57:49.779 5828-5847/? D/OpenGLRenderer: Use EGL_SWAP_BEHAVIOR_PRESERVED: true
04-13 17:57:49.784 5828-5828/? D/Atlas: Validating map...
04-13 17:57:49.810 5828-5847/? D/libEGL: loaded /system/lib/egl/libEGL_emulation.so
loaded /system/lib/egl/libGLESv1_CM_emulation.so
04-13 17:57:49.820 5828-5847/? D/libEGL: loaded /system/lib/egl/libGLESv2_emulation.so
04-13 17:57:49.848 5828-5847/? I/OpenGLRenderer: Initialized EGL, version 1.4
04-13 17:57:49.878 5828-5847/? D/OpenGLRenderer: Enabling debug mode 0
04-13 17:57:49.896 5828-5847/? W/EGL_emulation: eglSurfaceAttrib not implemented
04-13 17:57:49.896 5828-5847/? W/OpenGLRenderer: Failed to set EGL_SWAP_BEHAVIOR on surface 0xe2c15340, error=EGL_SUCCESS
What is the problem please? how to fix it?
Use intents and read basic android first. There are number of options already available for this.
You can Store your string into some other class like this:
Store string:
String selectedItem = (String) arg0.getItemAtPosition(position);
Share.love=selectedItem ;
Get string:
in Your next Activity
Textview textview=(Textview)findviewbyid(R.id.yourname);
textview.setText(Share.love);
Make class
public class Share {
public static String love = "";
}
Try the following example (It uses putExtra() to pass a string to another activity):
Demo15.class:------------
public class Demo15 extends AppCompatActivity {
private Button b;
private EditText edt;
private final String EXTRA_TEXT_ = "extra_text_";
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.demo17);
edt = (EditText) findViewById(R.id.edt);
b = (Button) findViewById(R.id.b);
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(Demo15.this, Demo16.class);
if (!edt.getText().toString().isEmpty()) {
i.putExtra(EXTRA_TEXT_, edt.getText().toString());
}
startActivity(i);
}
});
}
}
Demo16.class:-------
public class Demo16 extends AppCompatActivity {
private TextView tv;
private final String EXTRA_TEXT_ = "extra_text_";
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.demo18);
tv = (TextView) findViewById(R.id.tv);
if (getIntent() != null) {
if (getIntent().getStringExtra(EXTRA_TEXT_) != null) {
tv.setText(getIntent().getStringExtra(EXTRA_TEXT_));
}
}
}
}
demo17.xml:-------
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Enter text to pass"
android:id="#+id/edt"/>
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Start the other activity"
android:textAllCaps="false"
android:layout_marginTop="50dp"
android:id="#+id/b"/>
</LinearLayout>
demo18.xml:---------
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="####"
android:id="#+id/tv"/>
</android.support.constraint.ConstraintLayout>
Use bundle with intents as android standards.
Example:
Intent intent=new Intent(CurrentActivity.this,NewActivity.class);
intent.putExtra("schoolname","Name of school");
startActivity

Spinner not showing selected or default choice

I've created a spinner that takes some user-generated strings (in my case classes - the school type) and displays them in a typical spinner way. My problem occurs when trying to select an item from the spinner. I can tap on the spinner and select the class, but the spinner never shows that I have the class selected. Before adding user-generated strings, I had a string-array xml file that worked perfectly.
I've tried adding notifyDataSetChanged() at the end of the onCreate() method, created a spinner layout with a transparent background and black text, and setting an setOnItemSelectedListener(). None of these worked, so I reverted code back to original state.
Screenshot of problem:
addAssignment.java
package com.nbdeg.unityplanner;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.SeekBar;
import android.widget.Spinner;
import com.google.firebase.analytics.FirebaseAnalytics;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import com.nbdeg.unityplanner.data.Assignments;
import com.nbdeg.unityplanner.data.Classes;
import java.util.ArrayList;
public class addAssignment extends AppCompatActivity {
EditText mAssignmentName;
EditText mDueDate;
EditText mExtraInfo;
Spinner mDueClass;
SeekBar mPercentComplete;
int percentComplete = 0;
FirebaseAnalytics mFirebaseAnalytics;
DatabaseReference assignmentDb;
DatabaseReference classDb;
FirebaseUser user;
long assignmentCounter;
ArrayList<String> classList = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_assignment);
// Sets title to "Create an assignment"
try {getSupportActionBar().setTitle("Create An Assignment");}
catch (NullPointerException e) {
e.printStackTrace();
}
// Getting number of assignments (serves as assignment ID in database)
Bundle extras = getIntent().getExtras();
assignmentCounter = extras.getLong("counter");
// Finds firebase database
user = FirebaseAuth.getInstance().getCurrentUser();
mFirebaseAnalytics = FirebaseAnalytics.getInstance(this);
assignmentDb = FirebaseDatabase.getInstance().getReference().child("users").child(user.getUid()).child("assignments");
classDb = FirebaseDatabase.getInstance().getReference().child("users").child(user.getUid()).child("classes");
// Gets all classes
classDb.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot userSnapshot: dataSnapshot.getChildren()) {
Classes mClass = userSnapshot.getValue(Classes.class);
Log.i("Info", "Class loaded: " + mClass.getClassName());
classList.add(mClass.getClassName());
}
Log.i("Info", "Classes loaded: " + classList);
}
#Override
public void onCancelled(DatabaseError databaseError) {
Log.e("DB", "Error: " + databaseError.getMessage());
}
});
// Find view by ID calls
mAssignmentName = (EditText) findViewById(R.id.assignment_name);
mDueDate = (EditText) findViewById(R.id.due_date_edittext);
mExtraInfo = (EditText) findViewById(R.id.extra_homework_info);
mDueClass = (Spinner) findViewById(R.id.class_spinner);
mPercentComplete = (SeekBar) findViewById(R.id.percentComplete);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, R.layout.spinner_layout, classList);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
mDueClass.setAdapter(adapter);
// Sets DueDate EditText to open a datepicker when clicked
new EditTextDatePicker(this, R.id.due_date_edittext);
mPercentComplete.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean b) {
percentComplete = progress;
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
});
}
// Adds a SAVE button to the Action Bar
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.save, menu);
return true;
}
// Gets and saves information when SAVE is clicked
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Getting information from views
String dueDate = mDueDate.getText().toString();
String assignmentName = mAssignmentName.getText().toString();
String extraInfo = mExtraInfo.getText().toString();
String dueClass = mDueClass.getItemAtPosition(mDueClass.getSelectedItemPosition()).toString();
mFirebaseAnalytics.logEvent("Assignment Created", null);
Log.i("DB", "Creating assignment named " + assignmentName);
assignmentDb.child(Long.toString(assignmentCounter)).setValue
(new Assignments(assignmentName, dueClass, dueDate, extraInfo, percentComplete));
/*
// Test to make sure info is being collected correctly.
Log.i("Class", dueClass);
Log.i("Due", dueDate);
Log.i("Name", homeworkName);
Log.i("Extra", extraInfo);
*/
// Bring user back to MainActivity
startActivity(new Intent(addAssignment.this, MainActivity.class));
return super.onOptionsItemSelected(item);
}
}
activity_add_assignment.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/activity_add_homework"
android:layout_width="match_parent"
android:layout_height="match_parent"
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.nbdeg.unityplanner.addAssignment">
<EditText
android:layout_width="match_parent"
android:layout_height="40dp"
android:inputType="textCapSentences"
android:ems="10"
android:layout_alignParentTop="true"
android:layout_alignParentStart="true"
android:id="#+id/assignment_name"
android:hint="Assignment Name"
android:padding="5dp"
android:textSize="18sp"
android:background="#null" />
<View
android:layout_width="match_parent"
android:layout_height="1dp"
android:background="#c0c0c0"
android:layout_below="#id/assignment_name"/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="43dp"
android:orientation="horizontal"
android:layout_below="#id/assignment_name"
android:layout_alignParentStart="true"
android:id="#+id/linearLayout">
<Spinner
android:layout_width="0dp"
android:layout_height="match_parent"
android:id="#+id/class_spinner"
android:theme="#android:style/Theme.Holo.Light.DarkActionBar"
android:layout_weight="1"
android:background="#null"/>
<View
android:layout_width="1dp"
android:layout_height="match_parent"
android:background="#c0c0c0"/>
<EditText
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:id="#+id/due_date_edittext"
android:padding="5dp"
android:focusable="false"
android:hint="Due Date"
android:textSize="16sp"
android:background="#null" />
</LinearLayout>
<View
android:layout_width="match_parent"
android:layout_height="1dp"
android:background="#c0c0c0"
android:layout_below="#id/linearLayout"/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:layout_below="#+id/linearLayout"
android:layout_alignParentStart="true"
android:id="#+id/percentCompleteLayout"
android:layout_marginTop="2dp"
android:layout_marginBottom="2dp">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Completion"
android:padding="5dp"
android:textColor="#color/black"
android:textSize="15sp"/>
<SeekBar
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/percentComplete"
android:layout_marginBottom="1dp"/>
</LinearLayout>
<View
android:layout_width="match_parent"
android:layout_height="1dp"
android:background="#c0c0c0"
android:layout_below="#id/percentCompleteLayout"/>
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="textMultiLine"
android:ems="10"
android:id="#+id/extra_homework_info"
android:hint="Extra Infomation"
android:textSize="16sp"
android:layout_below="#id/percentCompleteLayout"
android:layout_alignParentStart="true"
android:layout_marginTop="2dp"
android:padding="5dp"
android:background="#null" />
</RelativeLayout>
spinner_layout.xml*
<?xml version="1.0" encoding="utf-8"?>
<TextView
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="16sp"
android:gravity="left"
android:padding="5dip"
android:textColor="#android:color/black"
android:background="#android:color/transparent"
/>
I'm wondering if there is a way to fix this and have the spinner display the default / user choice. If you need any more of the code, all of it can be found in the GitHub. Thanks in advance for all answers!
Solution: Try loading the classes prior to starting the activity, for example in the MainActivity. Then pass the values along through an intent.
Example:
MainActivty.java
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// Launch Add Homework Activity
Intent intent = new Intent(MainActivity.this, addAssignment.class);
intent.putExtra("classListNames", classListNames);
startActivity(intent);
...
classDb.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
classList.clear();
for (DataSnapshot userSnapshot: dataSnapshot.getChildren()) {
Classes mClass = userSnapshot.getValue(Classes.class);
Log.i(TAG, "Class loaded: " + mClass.getClassName());
classList.add(mClass);
classListNames.add(mClass.getClassName());
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
Log.e(TAG, "Error: " + databaseError.getMessage());
}
});
addAssignment.java
// Gets class list
Bundle extras = getIntent().getExtras();
classListNames = extras.getStringArrayList("classListNames");
...
mDueClass = (Spinner) findViewById(R.id.class_spinner);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, R.layout.spinner_layout, classListNames);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
mDueClass.setAdapter(adapter);
Cause: After some debugging, I discovered the cause of the problem to be timing differences. The app would request the classes be sent, create the spinner, then load the classes. The difference in timing was milliseconds, but just enough to cause the problem.

why is facebook login fragment always showing invalid key hash in android?

I am trying to login through facebook login in my android app but it is always giving me an invalid key hash. I have generated the hash key properly through the terminal on my mac using the command given at the facebook developer site and also used my facebook application id properly.Here is my code for the login activity class:
LoginActivity.java
package com.titmus.worldscope;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.Signature;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Base64;
import android.util.Log;
import android.webkit.WebView;
import android.widget.Toast;
import com.facebook.AccessToken;
import com.titmus.worldscope.model.WorldScopeUser;
import com.titmus.worldscope.utility.WorldScopeAPIService;
import com.titmus.worldscope.utility.WorldScopeRestAPI;
import java.security.MessageDigest;
import fragment.FacebookLoginFragment;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
public class LoginActivity extends AppCompatActivity implements FacebookLoginFragment.OnFragmentInteractionListener {
private static final String TAG = "LoginActivity";
private static final String WELCOME_GIF_LINK = "file:///android_asset/welcomeGifAssets/welcome.html";
private static final String APP_SERVER_AUTH_FAILED_MSG = "Authentication with WorldScope's server has failed, please check that you have internet connections and try again.";
private static Context context;
private FacebookLoginFragment facebookLoginFragment;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_facebook_login);
context = this;
loadGifIntoWebView();
}
#Override
public void onFacebookLoginSuccess(AccessToken accessToken) {
// Successful login -> Redirect to Main activity
Log.d(TAG, "Login Success!");
Log.d(TAG, "AccessToken: " + accessToken.getToken());
// Instantiate and make a call to login user into WorldScope servers
Call<WorldScopeUser> call = new WorldScopeRestAPI(context).buildWorldScopeAPIService().loginUser(new WorldScopeAPIService.LoginUserRequest(accessToken.getToken()));
call.enqueue(new Callback<WorldScopeUser>() {
#Override
public void onResponse(Response<WorldScopeUser> response) {
if(response.isSuccess()) {
Log.d(TAG, "Success!");
Log.d(TAG, "" + response.body().toString());
WorldScopeUser user = response.body();
WorldScopeAPIService.setUser(user);
// Redirect to MainActivity if successful
redirectToMainActivity();
} else {
Log.d(TAG, "Failure" + response.code() + ": " + response.message());
// Logout of Facebook
logoutOfFacebook();
}
}
#Override
public void onFailure(Throwable t) {
Log.d(TAG, "Failure: " + t.getMessage());
// Logout of Facebook
logoutOfFacebook();
}
});
}
//Redirects to MainActivity
protected void redirectToMainActivity() {
Intent intent = new Intent(context, MainActivity.class);
intent.putExtra("activity", TAG);
startActivity(intent);
}
// Called to logout of Facebook when attempt to authenticate with App server fails
private void logoutOfFacebook() {
if(facebookLoginFragment == null) {
// Get FacebookLoginFragment if missing
facebookLoginFragment = (FacebookLoginFragment) getSupportFragmentManager().findFragmentById(R.id.facebookLoginButtonFragment);
}
// Toast to inform user
Toast toast = Toast.makeText(context, APP_SERVER_AUTH_FAILED_MSG, Toast.LENGTH_LONG);
toast.show();
facebookLoginFragment.logoutFromFacebook();
}
// Method to load Gif's html data into WebView
private void loadGifIntoWebView() {
WebView welcomeGifWebView = (WebView) findViewById(R.id.welcomeGifWebView);
welcomeGifWebView.loadUrl(WELCOME_GIF_LINK);
}
}
activity_facebook_login.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:id="#+id/loginActivity"
tools:context="com.titmus.worldscope.LoginActivity">
<WebView
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:id="#+id/welcomeGifWebView"
android:layout_alignParentEnd="true"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true" />
<LinearLayout
android:orientation="horizontal"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="#+id/facebookLoginButtonFragment"
android:layout_centerHorizontal="true"
android:layout_marginBottom="48dp">
<ImageView
android:layout_width="32dp"
android:layout_height="match_parent"
android:id="#+id/imageView"
android:src="#drawable/ic_logo"
android:layout_alignBottom="#+id/textView4"
android:layout_toStartOf="#+id/textView4"
android:layout_marginEnd="4dp"
android:paddingTop="6dp"
android:paddingBottom="5dp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="WorldScope"
android:id="#+id/textView4"
android:textColor="#ffffff"
android:textStyle="bold"
android:textSize="32sp"
android:layout_above="#+id/facebookLoginButtonFragment"
android:layout_centerHorizontal="true" />
</LinearLayout>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="By logging in you agree to WorldScope&apos;s Privacy Policy and Terms of Use."
android:id="#+id/textView6"
android:textColor="#eeeeee"
android:textSize="14dp"
android:layout_marginLeft="16dp"
android:layout_marginRight="16dp"
android:textAlignment="center"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="57dp" />
<fragment
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:name="fragment.FacebookLoginFragment"
android:id="#+id/facebookLoginButtonFragment"
tools:layout="#layout/fragment_facebook_login"
android:layout_marginBottom="14dp"
android:layout_above="#+id/textView6"
android:layout_alignParentStart="true" />
</RelativeLayout>
The keyhash generated using cmd works fine for the first then it doesn't.
So use this method to generate keyHash in any of you class
public void printHashKey(){
// Add code to print out the key hash
try {
PackageInfo info = getPackageManager().getPackageInfo(
"net.simplifiedcoding.androidlogin",
PackageManager.GET_SIGNATURES);
for (Signature signature : info.signatures) {
MessageDigest md = MessageDigest.getInstance("SHA");
md.update(signature.toByteArray());
Log.d("KeyHash:", Base64.encodeToString(md.digest(), Base64.DEFAULT));
}
} catch (PackageManager.NameNotFoundException e) {
} catch (NoSuchAlgorithmException e) {
}
}
Then copy the key hash genrated, and paste it where you added keyhash generated by cmd in facebook developer console.
It will work, and dont restrict the application to only one device in facebook developer console

Sending contact form in android via email

I am trying to make a basic contact form app where people can fill in the needed information and press the send button and have the information sent to a specific E-mail. I have put it together but for some reason it is not working. The Java file has code in it from a similar app. The Java file has spinner code in it so I turned it into notes.. not sure if it's messing something up. Here is the code please let me know what I can do to make it work.
activity_main.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: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=".MainActivity" >
<EditText
android:id="#+id/etName"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/textView1"
android:layout_below="#+id/textView1"
android:ems="10"
android:hint="Enter First and Last Name"
android:inputType="textPersonName" >
<requestFocus />
</EditText>
<EditText
android:id="#+id/etPhone"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/etName"
android:layout_marginTop="14dp"
android:ems="10"
android:hint="Enter Phone #"
android:inputType="phone" />
<EditText
android:id="#+id/etEmail"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/etPhone"
android:layout_marginTop="17dp"
android:ems="10"
android:hint="Enter E-mail"
android:inputType="textEmailAddress" />
<EditText
android:id="#+id/etAdd"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/etEmail"
android:layout_marginTop="18dp"
android:ems="10"
android:hint="Enter Additional Information Here"
android:lines="3"
android:inputType="textMultiLine" />
<Button
android:id="#+id/send"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_below="#+id/etAdd"
android:text="Send" />
<TextView
android:id="#+id/textView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/etPhone"
android:layout_alignParentTop="true"
android:gravity="center"
android:text="Contact Form"
android:textAppearance="?android:attr/textAppearanceMedium" />
</RelativeLayout>
Here is the MainActivity.java file:
package com.example.contactform1;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.text.Html;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;
public class MainActivity extends Activity implements OnClickListener, OnItemSelectedListener{
/** Called when the activity is first created. */
EditText etname, etphone, etemail, etadd;
//Spinner subject;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
etname = (EditText) findViewById (R.id.etName);
etphone = (EditText) findViewById(R.id.etPhone);
etemail = (EditText) findViewById(R.id.etEmail);
etadd = (EditText)findViewById(R.id.etAdd);
//subject=(Spinner)findViewById(R.id.spinner);
//String subjects[]=new String[]{"Default","Klacht","Vraag","Opmerking","Applicatie"};
//subject.setOnItemSelectedListener(this);
//ArrayAdapter<String> sa = new ArrayAdapter<String>(getApplicationContext(),
//android.R.layout.simple_spinner_item, subjects);
//sa.setDropDownViewResource(android.R.layout.simple_dropdown_item_1line);
//subject.setAdapter(sa);;
final Button buttonSend= (Button)findViewById(R.id.send);
buttonSend.setOnClickListener(this);
}
public void onClick(View v)
{
//if(etname.getText().toString().length()==0)
//{
//etname.setError( "Vul uw naam in" );
//}
//else if(etphone.getText().toString().length()==0)
//{
//etphone.setError( "Vul uw email in" );
//}
//else if(etemail.getText().toString().length() != 10)
//{
//etemail.setError( "Vul een geldig telefoonnummer in" );
//}
//else if(etadd.getText().toString().length()==0)
//{
//etadd.setError( "Vul uw bericht in" );
//}
//else if(subject.getSelectedItemPosition()==0)
//{
//Toast.makeText(MainActivity.this,"Please select the Subject",Toast.LENGTH_SHORT).show();
//}
//else
//{
//String body=
//"Name : "+etname.getText().toString()+"<br>Mobile :"+etphone.getText().toString()+
//"<br>Email :"+etemail.getText().toString();//+"<br>Bericht :"+etadd.getText().toString();
//Intent email = new Intent(Intent.ACTION_SEND);
//email.putExtra(Intent.EXTRA_EMAIL, new String[]{"email here"});
//email.putExtra(Intent.EXTRA_SUBJECT, subject.getSelectedItem().toString());
//email.putExtra(Intent.EXTRA_TEXT, Html.fromHtml(body));
//email.setType("message/rfc822");
//startActivityForResult(Intent.createChooser(email, "marketing"),1);
}
// }
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
new AlertDialog.Builder(MainActivity.this)
.setMessage("Your requested has been Accepted\nThank You")
.setCancelable(false)
.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which)
{
dialog.cancel();
}
})
.show();
}
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
// TODO Auto-generated method stub
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
}
LogCat info:
12-04 18:19:15.574: W/IInputConnectionWrapper(28530): showStatusIcon on inactive InputConnection
12-04 18:19:21.190: D/AbsListView(28530): Get MotionRecognitionManager
12-04 18:19:21.220: D/AbsListView(28530): onVisibilityChanged() is called, visibility : 4
12-04 18:19:21.220: D/AbsListView(28530): unregisterIRListener() is called
12-04 18:19:21.230: D/AbsListView(28530): onVisibilityChanged() is called, visibility : 0
12-04 18:19:21.230: D/AbsListView(28530): unregisterIRListener() is called
12-04 18:19:21.240: D/AbsListView(28530): unregisterIRListener() is called
12-04 18:19:21.320: D/AbsListView(28530): unregisterIRListener() is called
12-04 18:19:21.330: D/AbsListView(28530): unregisterIRListener() is called
12-04 18:19:21.360: D/AbsListView(28530): unregisterIRListener() is called
12-04 18:19:21.390: D/AbsListView(28530): unregisterIRListener() is called
12-04 18:19:22.591: D/AbsListView(28530): unregisterIRListener() is called
12-04 18:19:22.861: W/IInputConnectionWrapper(28530): showStatusIcon on inactive InputConnection
12-04 18:19:22.982: D/AbsListView(28530): onDetachedFromWindow
12-04 18:19:22.982: D/AbsListView(28530): unregisterIRListener() is called
12-04 18:19:37.546: E/ViewRootImpl(28530): sendUserActionEvent() mView == null
12-04 18:19:40.499: W/IInputConnectionWrapper(28530): showStatusIcon on inactive InputConnection
12-04 18:19:40.519: E/OpenGLRenderer(28530): SFEffectCache:clear(), mSize = 0
I have the form appearing now but the information that you input is not getting sent to the email. I am getting prompted to a screen indication which email service i should use to execute this app. I just want the information entered to be directly sent to the email that is provided in the app.
Thanks in advance!
You're seeing that screen with the list of email clients because that's how Intents work.
An intent won't directly execute the action you want it to, all it can do is hand off the data to another Activity (perhaps in a different application) that can handle the data.

getting null pointer exception unable to start main activity

StockLedgerRpt Class showing null pointer exception. This class displays a list in spinner view to select a stock item.
package com.manacle.umma.activity;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import android.app.DatePickerDialog;
import android.app.DatePickerDialog.OnDateSetListener;
import android.app.ListActivity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.speech.tts.TextToSpeech;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.SimpleAdapter;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import com.manacle.umma.java.Constants;
import com.manacle.umma.java.DatabaseHelper;
import com.manacle.umma.java.Header;
import com.manacle.umma.java.Validation;
public class StockLedgerRep extends ListActivity {
Button srch_btn;
TextView stckldgr_header, stckldgr_cntr, frm_date, to_date,
stck_item;
EditText to_dt_edit, frm_dt_edit;
Spinner add_stcitm_spin;
RelativeLayout stckldgr_relative;
LinearLayout stckldgr_linearLayout;
HeaderDb headerDb;
ListAdapter adapter;
Header headerClass;
HashMap<String, String> map, categoryMap, unitMap;
String value, stockId, voucherId, code;
String stockItemsname[] = null;
String batchId = null;
DatabaseHelper databaseHelper;
Map stockItemMap;
SharedPreferences preferences;
String itemname;
String firstSelection;
private TextToSpeech tts;
String batchIDD;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.stck_ldgr_rpt);
final HeaderDb db = new HeaderDb(getApplicationContext());
headerDb = new HeaderDb(getApplicationContext());
stckldgr_relative = (RelativeLayout) findViewById(R.id.stckldgr_relative_layout);
stckldgr_linearLayout = (LinearLayout) findViewById(R.id.stckldgr_linear_layout);
stckldgr_header = (TextView) findViewById(R.id.stckldgr_header);
stckldgr_cntr = (TextView) findViewById(R.id.stckldgr_txt);
frm_date = (TextView) findViewById(R.id.stckldgr_frmdate_txt);
to_date= (TextView) findViewById(R.id.stckldgr_todate_txt);
stck_item=(TextView) findViewById(R.id.stckldgr_stockItem_txt);
add_stcitm_spin=(Spinner) findViewById(R.id.stckldgr_stock_item_spinner);
frm_dt_edit = (EditText) findViewById(R.id.stckldgr_frmdate_edit);
to_dt_edit = (EditText) findViewById(R.id.stckldgr_todate_edit);
DateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy");
Date date = new Date();
frm_dt_edit.setText(dateFormat.format(date));
frm_dt_edit.setFocusable(false);
to_dt_edit.setText(dateFormat.format(date));
to_dt_edit.setFocusable(false);
String dat = preferences.getString("STOCK_CODE", "");
if (!dat.equalsIgnoreCase("")) {
// Toast.makeText(getApplicationContext(), "Selected date="+dat,
// Toast.LENGTH_LONG).show();
stckldgr_cntr.setText(dat);
}
final OnDateSetListener odsl = new OnDateSetListener() {
#Override
public void onDateSet(DatePicker arg0, int year, int month, int day) {
String date_format = Validation.dateFormat(month, day, year);
frm_dt_edit.setText(date_format);
to_dt_edit.setText(date_format);
}
};
frm_dt_edit.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Calendar cal = Calendar.getInstance();
DatePickerDialog datePickDiag = new DatePickerDialog(
StockLedgerRep.this, odsl, cal.get(Calendar.YEAR), cal
.get(Calendar.MONTH), cal
.get(Calendar.DAY_OF_MONTH));
datePickDiag.show();
}
});
to_dt_edit.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Calendar cal = Calendar.getInstance();
DatePickerDialog datePickDiag = new DatePickerDialog(
StockLedgerRep.this, odsl, cal.get(Calendar.YEAR), cal
.get(Calendar.MONTH), cal
.get(Calendar.DAY_OF_MONTH));
datePickDiag.show();
}
});
com.manacle.umma.java.SpinnerAdapter adapter1 = new com.manacle.umma.java.SpinnerAdapter(
this, android.R.layout.simple_spinner_item, getStockItem());
add_stcitm_spin.setAdapter(adapter1);
add_stcitm_spin.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
// TODO Auto-generated method stub
Object item = arg0.getItemAtPosition(arg2);
if (item.equals("")) {
} else {
firstSelection = add_stcitm_spin.getSelectedItem()
.toString();
// tToast(""+firstSelection);
if (firstSelection.equals("All")) {
if (headerDb.getVouDateTransIdfromVouTableforAllItem(value, batchId).size() > 0) {
//showAllName_Id();
} else {
// tToast("No Record, Please add new Record.");
//showAllName_Id();
}
} else {
List stockItemList = headerDb
.getAllIRMStockItem(headerDb
.getAllIRMStockcategoryID());
Map mapItem = (Map) stockItemList.get(arg2 - 1);
code = (String) mapItem.get(add_stcitm_spin
.getSelectedItem().toString());
}
}
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
}); }
private void tToast(String s) {
Context context = getApplicationContext();
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, s, duration);
toast.show();
}
public String[] getStockItem() {
String arr_name[] = null;
List listCategoryId = headerDb.getAllIRMStockcategoryID();
List stockList = headerDb.getAllIRMStockItem(listCategoryId);
Iterator memberItemsItr = headerDb.getAllIRMStockItem(listCategoryId)
.iterator();
int i = 0;
arr_name = new String[stockList.size() + 1];
arr_name[0] = "All";
i++;
// tToast("ARRSIZE="+listCategoryId.size());
while (memberItemsItr.hasNext()) {
stockItemMap = (Map) memberItemsItr.next();
Iterator<?> iter = stockItemMap.entrySet().iterator();
// String arr_code[]=new String[memberItemsMap.size()+1];
while (iter.hasNext()) {
Map.Entry mEntry = (Map.Entry) iter.next();
// tToast(mEntry.getKey() + " : " + mEntry.getValue());
String stockName = (String) mEntry.getKey();
String stockCode = (String) mEntry.getValue();
arr_name[i] = stockName;
i++;
}
}
return arr_name;
}
public void showAllName_Id() {
adapter = new SimpleAdapter(this, headerDb.getVouDateTransIdfromVouTableforAllItem(value, batchId),
R.layout.stock_list_item, new String[] {
Constants.Bat_Acc_Voch_VOUCHER_DATE,
Constants.Bat_Acc_Voch_Trans_Id }, new int[] {
R.id.stock_list_code, R.id.stock_list_name });
setListAdapter(adapter);
// selecting single ListView item
ListView lv = getListView();
// lv.setBackgroundColor(Integer.parseInt(headerDb.getBgColor("KD125"),
// 16)+0xFF000000);
// lv.setChoiceMode(AbsListView.CHOICE_MODE_SINGLE);
try {
// lv.setSelector(R.drawable.sel);
} catch (Exception e) {
// TODO: handle exception
tToast("Error" + e);
}
// lv.setSelector(Color.RED);
lv.setOnTouchListener(new ListView.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
int action = event.getAction();
switch (action) {
case MotionEvent.ACTION_DOWN:
// Disallow ScrollView to intercept touch events.
v.getParent().requestDisallowInterceptTouchEvent(true);
// v.setBackgroundResource(R.drawable.sel);
break;
case MotionEvent.ACTION_UP:
// Allow ScrollView to intercept touch events.
v.getParent().requestDisallowInterceptTouchEvent(false);
// v.setBackgroundResource(R.drawable.sel);
break;
}
// Handle ListView touch events.
v.onTouchEvent(event);
return true;
}
});
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
String name = ((TextView) view
.findViewById(R.id.stock_list_code)).getText()
.toString();
voucherId = ((TextView) view.findViewById(R.id.stock_list_name))
.getText().toString();
String Vid[] = voucherId.split("-");
String vid = Vid[1];
String mobtrans = Vid[0];
// tToast("Voucher Id="+vid);
// tToast("Selected Value="+name+""+code);
Intent in = new Intent(getApplicationContext(),
IRM_add_preview.class);
in.putExtra("VOU_ID", vid);
in.putExtra("VALUE", value);
in.putExtra("MOBTRANS", mobtrans);
startActivity(in);
}
});
}
}
stck_ldgr Xml this xml shows three things one is the spinner stock items column and the other two are select dates. I am unable to get the error. pls help. even added in androidmanifest.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:focusableInTouchMode="true"
android:id="#+id/stckldgr_relative_layout"
>
<TextView
android:id="#+id/imageView1"
android:layout_width="match_parent"
android:layout_height="10dp"
/>
<TextView
android:id="#+id/imageView2"
android:layout_width="match_parent"
android:layout_height="1dp"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
/>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="#+id/imageView2"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:layout_below="#+id/imageView1"
android:orientation="vertical"
android:id="#+id/stckldgr_linear_layout"
>
<!-- -->
<ScrollView
android:id="#+id/scroller"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:fillViewport="true" >
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:paddingLeft="6dip"
android:paddingRight="6dip"
android:paddingTop="6dip"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="Stock Ledger Report"
android:textStyle="bold"
android:gravity="center"
android:id="#+id/stckldgr_header"
/>
<View
android:layout_width="fill_parent"
android:layout_height="1dip"
android:background="#ff106510"
android:layout_marginLeft="6dip"
android:layout_marginRight="6dip"
android:layout_marginTop="6dip"
android:layout_marginBottom="12dip" />
<LinearLayout
android:id="#+id/linearLayout_login_4"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
>
<TableLayout
android:layout_width="match_parent"
android:layout_height="match_parent" >
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:paddingLeft="6dip"
android:paddingRight="6dip"
android:id="#+id/stckldgr_txt"
android:textStyle="bold"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="Stock Center Code-Name"
android:gravity="center"
/>
<TableRow
android:id="#+id/tableRow1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
>
<TextView
android:text="Stock Item"
android:height="40dp"
android:width="150dp"
android:layout_marginTop="10dip"
android:textStyle="bold"
android:id="#+id/stckldgr_stockItem_txt"
android:layout_gravity="center_horizontal|bottom"
></TextView>
<Spinner
android:id="#+id/stckldgr_stock_item_spinner"
android:layout_width="match_parent"
android:layout_height="40dp"
android:layout_marginRight="6dip"
android:saveEnabled="true" >
</Spinner>
</TableRow>
<TableRow
android:id="#+id/tableRow1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="5dip"
>
<TextView
android:layout_width="150dp"
android:layout_height="40dp"
android:layout_marginTop="10dip"
android:text="From Date"
android:textStyle="bold"
android:id="#+id/stckldgr_frmdate_txt"
/>
<EditText
android:id="#+id/stckldgr_frmdate_edit"
android:layout_width="match_parent"
android:layout_height="40dp"
android:layout_marginLeft="0dip"
android:layout_marginRight="10dip"
android:editable="false"
>
<requestFocus />
</EditText>
</TableRow>
<TableRow
android:id="#+id/tableRow1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="5dip"
>
<TextView
android:layout_width="150dp"
android:layout_height="40dp"
android:layout_marginTop="10dip"
android:text="To Date"
android:textStyle="bold"
android:id="#+id/stckldgr_todate_txt"
/>
<EditText
android:id="#+id/stckldgr_todate_edit"
android:layout_width="match_parent"
android:layout_height="40dp"
android:layout_marginLeft="0dip"
android:layout_marginRight="10dip"
android:editable="false"
>
<requestFocus />
</EditText>
</TableRow>
</TableLayout>
<ListView
android:id="#android:id/list"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginBottom="15dp"
android:layout_marginTop="15dp"
android:layout_weight="1"
android:divider="#color/divider"
android:listSelector="#369659"
android:cacheColorHint="#369659"
android:dividerHeight="2px"
android:choiceMode="singleChoice"
android:gravity="center" >
</ListView>
</LinearLayout>
</LinearLayout>
</ScrollView>
</LinearLayout>
</RelativeLayout>
Logcat
10-10 10:44:55.832: D/AndroidRuntime(2639): Shutting down VM
10-10 10:44:55.865: W/dalvikvm(2639): threadid=1: thread exiting with uncaught exception (group=0x40a71930)
10-10 10:44:56.023: E/AndroidRuntime(2639): FATAL EXCEPTION: main
10-10 10:44:56.023: E/AndroidRuntime(2639): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.manacle.umma.activity/com.manacle.umma.activity.StockLedgerRep}: java.lang.NullPointerException
10-10 10:44:56.023: E/AndroidRuntime(2639): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2180)
10-10 10:44:56.023: E/AndroidRuntime(2639): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
10-10 10:44:56.023: E/AndroidRuntime(2639): at android.app.ActivityThread.access$600(ActivityThread.java:141)
10-10 10:44:56.023: E/AndroidRuntime(2639): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
10-10 10:44:56.023: E/AndroidRuntime(2639): at android.os.Handler.dispatchMessage(Handler.java:99)
10-10 10:44:56.023: E/AndroidRuntime(2639): at android.os.Looper.loop(Looper.java:137)
10-10 10:44:56.023: E/AndroidRuntime(2639): at android.app.ActivityThread.main(ActivityThread.java:5041)
10-10 10:44:56.023: E/AndroidRuntime(2639): at java.lang.reflect.Method.invokeNative(Native Method)
10-10 10:44:56.023: E/AndroidRuntime(2639): at java.lang.reflect.Method.invoke(Method.java:511)
10-10 10:44:56.023: E/AndroidRuntime(2639): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
10-10 10:44:56.023: E/AndroidRuntime(2639): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
10-10 10:44:56.023: E/AndroidRuntime(2639): at dalvik.system.NativeStart.main(Native Method)
10-10 10:44:56.023: E/AndroidRuntime(2639): Caused by: java.lang.NullPointerException
10-10 10:44:56.023: E/AndroidRuntime(2639): at com.manacle.umma.activity.StockLedgerRep.onCreate(StockLedgerRep.java:96)
10-10 10:44:56.023: E/AndroidRuntime(2639): at android.app.Activity.performCreate(Activity.java:5104)
10-10 10:44:56.023: E/AndroidRuntime(2639): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1080)
10-10 10:44:56.023: E/AndroidRuntime(2639): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2144)
10-10 10:44:56.023: E/AndroidRuntime(2639): ... 11 more
Your preferences object is null.
You need to initialise it before you use it. Something like this:
preferences = PreferenceManager.getDefaultSharedPreferences(this);
String dat = preferences.getString("STOCK_CODE", "");
Because you didn't initialize preferences. Here is the problem:
String dat = preferences.getString("STOCK_CODE", "");
If you use Eclipse or any other IDE, you should double-click on the error line so it will get you right on the source of the exception...
10-10 10:44:56.023: E/AndroidRuntime(2639): at com.manacle.umma.activity.StockLedgerRep.onCreate(StockLedgerRep.java:96)
Should be on the preferences thing like other users suggest...
Can you write this code before line 96.
preferences= getApplicationContext.getSharedPreferences("blablabla", Context.MODE_PRIVATE);

Categories

Resources