Getting java.lang.NullPointerException on customDialogBox - java

I am getting java.lang.NullPointerException for this method. I have check the adapter and lists are just fine and the list is ofcourse under fragment_phonelist xml file.
private void showCustomDialog() {
final Dialog dialog = new Dialog(SetupProfile.this);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setContentView(R.layout.fragment_phonelist);
Button done = (Button)dialog.findViewById(R.id.btn_done);
Button canCel = (Button)dialog.findViewById(R.id.btn_cancel);
ListView PhoneListView = (ListView)findViewById(R.id.list_phone);
MyCustomAdapter tst = new MyCustomAdapter(this,ContactName,ContactNumb);
PhoneListView.setAdapter(tst);
done.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
dialog.dismiss();
}
});
canCel.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
dialog.dismiss();
}
});
dialog.show();
}
Please any help..

This line
ListView PhoneListView = (ListView)findViewById(R.id.list_phone);
Shouldn't that be like this:
ListView PhoneListView = (ListView)dialog.findViewById(R.id.list_phone);

Related

Android: How to code an AlertDialog with onClickListener and onLongClickListener

Like the title says. I have coded onClickListener to my AlertDialog but i don't know how to put there onLongClickListener.
This is my code:
private void addRecipeMethod() {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Title");
adapter = new ArrayAdapter<>(getBaseContext(), android.R.layout.simple_list_item_1, getArrayList("ListOfRecipes"));
builder.setAdapter(adapter, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
List<String> list = new ArrayList<>(getArrayList("ListOfRecipes"));
getArrayListRecipes(list.get(which));
List<String> listMain = new ArrayList<>(getArrayList("ListMain"));
listMain.addAll(getArrayListRecipes(list.get(which)));
saveList(listMain, "ListMain");
adapter = new ArrayAdapter<>(getBaseContext(), android.R.layout.simple_list_item_1, getArrayList("ListMain"));
listView.setAdapter(adapter);
//Toast.makeText(getApplicationContext(), "you have clicked " + list.get(which) , Toast.LENGTH_SHORT).show();
}
});
builder.show();
}
PS. void addRecipeMethod is called when Menu Item is clicked
Create AlertDialog with custom layout like this
AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this);
// ...Irrelevant code for customizing the buttons and title
LayoutInflater inflater = this.getLayoutInflater();
View dialogView = inflater.inflate(R.layout.alert_label_editor, null);
dialogBuilder.setView(dialogView);
Button button = (Button)dialogBuilder.findViewById(R.id.btnName);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//Commond here......
}
});
button.setOnLongClickListener(new OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
// TODO Auto-generated method stub
return false;
}
});
AlertDialog alertDialog = dialogBuilder.create();
alertDialog.show();
Add Button in alert_label_editor xml and add setOnLongClickListener for that Button
Button button = (Button)dialogBuilder.findViewById(R.id.btnName);
button.setOnLongClickListener(new OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
// TODO Auto-generated method stub
return false;
}
});

I got an error : Android java.lang.NullPointerException when using cursor

this is my code....
StudentLogin.java class
public class StudentLogin extends Activity implements OnClickListener, OnItemSelectedListener{
Spinner sp1,sp2;
EditText reg;
Button b1,b2,b3;
String a1,a2,studreg,studdept,studyr;
SQLiteDatabase db1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_student_login);
reg=(EditText) findViewById(R.id.editText1);
sp1=(Spinner)findViewById(R.id.spinner1);
sp2=(Spinner)findViewById(R.id.spinner2);
b1=(Button)findViewById(R.id.button1);
b1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
Cursor c=db1.rawQuery("Select * from StudReg", null); // Im getting an error here
int count=c.getCount();
int flag=0;
c.moveToFirst();
String regno=reg.getText().toString();
String yr=a1;
String dept=a2;
Toast.makeText(getApplicationContext(), regno, Toast.LENGTH_LONG).show();
if(regno.trim().length()>0&&!yr.equals("Select Year")&&!dept.equals("Select Dept"))
{
for(int i=0;i<count;i++)
{
studreg=c.getString(c.getColumnIndex("register"));
studdept=c.getString(c.getColumnIndex("deptmt"));
studyr=c.getString(c.getColumnIndex("year"));
if(regno.equals(studreg)&&yr.equals(studyr)&&dept.equals(studdept))
{
flag=1;
break;
}
c.moveToNext();
}
c.close();
if(flag==1)
{
Intent inn=new Intent(StudentLogin.this,StudyMaterials.class);
startActivity(inn);
}
else
{
Toast.makeText(getApplicationContext(), "Invalid User!\nKindly try again..", Toast.LENGTH_SHORT).show();
}
}
else
{
Toast.makeText(getApplicationContext(), "Kindly fill all the fields..", Toast.LENGTH_SHORT).show();
}
}
});
b2=(Button)findViewById(R.id.button2);
b2.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intt=new Intent(StudentLogin.this,StudentRegister.class);
startActivity(intt);
}
});
b3=(Button)findViewById(R.id.button3);
b3.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent int1=new Intent(StudentLogin.this,Update.class);
startActivity(int1);
}
});
sp1.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> p, View v,
int a, long l) {
// TODO Auto-generated method stub
a1=p.getItemAtPosition(a).toString();
//Toast.makeText(getApplicationContext(), a1, Toast.LENGTH_LONG).show();
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
sp2.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> p, View v,
int a, long l) {
// TODO Auto-generated method stub
a2=p.getItemAtPosition(a).toString();
//Toast.makeText(getApplicationContext(), a2, Toast.LENGTH_LONG).show();
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
List<String> categories = new ArrayList<String>();
categories.add("Select Department");
categories.add("CSE");
categories.add("IT");
categories.add("CIVIL");
categories.add("MECH");
categories.add("ECE");
categories.add("EEE");
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_dropdown_item, categories);
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
sp2.setAdapter(dataAdapter);
List<String> categories1 = new ArrayList<String>();
categories1.add("Select Year");
categories1.add("I");
categories1.add("II");
categories1.add("III");
categories1.add("IV");
ArrayAdapter<String> dataAdapter1 = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_dropdown_item, categories1);
dataAdapter1.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
sp1.setAdapter(dataAdapter1);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.student_login, menu);
return true;
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
}
#Override
public void onItemSelected(AdapterView<?> p, View v, int it,
long l) {
// TODO Auto-generated method stub
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
}
This code validates whether the user is already registered or not..
Please help me solve this error...
you need to initialize database
//dbHelper its a helper class for database
database = dbHelper.getWritableDatabase();
You have given the table name but you are not saying it on which db the table exists(as db1 is not initialized).So follow #Madhur answer to solve this null pointer exception.Also a suggestion when working with db(better to use loaders instead of working on MainThread).

create AsyncTask for Android

Can I know how to create AsyncTask for Android from all of these? I would like to remove the buttons and let all of these run in the background then redirect to the MainPage.java after clicking Logout.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_main);
Button btnDelete = (Button)findViewById(R.id.delete);
Button btnSignUp = (Button)findViewById(R.id.btnSignUp);
Button btnLogin = (Button)findViewById(R.id.btnLogin);
btnLogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent = new Intent(getApplicationContext(),HomePage.class);
startActivity(intent);
}
});
btnSignUp.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent = new Intent(MainActivity.this,SignUp.class);
startActivity(intent);
}
});
btnDelete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
cDB.resetTables();
mDB.resetTables();
db.resetTables();
pDB.resetTables();
}
});
}
here is one AsyncTask Example. This will show a peogress dialog while executing the task.
private class LoginProcessing extends AsyncTask<Object, Void, Void> {
private LoginCredentials myLoginCredentials;
private ProgressDialog progressDialog;
public LoginProcessing(LoginCredentials Credentials) {
super();
myLoginCredentials=Credentials;
}
protected void onPreExecute (){
progressDialog = ProgressDialog.show(context, "", "Please Wait...",true);
}
#Override
protected Void doInBackground(Object... arg0) {
// TODO Auto-generated method stub
//Code to do the process in background
return null;
}
protected void onPostExecute(Void result){
progressDialog.dismiss();
//Your code after the process
}
}
You can call this Task as,
new LoginProcessing(loginCredentials).execute();
In this Example loginCredentials is the parameter I am passing to the AsyncTask. You can change it to your own parameter.

Can't get Double output in TextView

The main purpose of this Android app is to learn how to use spinners and parse data. I have tried a lot of things and it still is not working. I don't get the output of the resultFuel on the screen.
Here's the code in my MainActivity:
public class MainActivity extends Activity implements OnItemSelectedListener {
Spinner spinFrom,spinTo;
String[] paths ={"liters/100km","liters/100 miles","(US)gallons/100 miles","(US)gallons/100km","(UK)gallons/100miles",
"(UK)gallons/100km","kilometers/liter","miles/liter", "miles/gallon", "kilometers/gallon"
};
EditText etfrom;
TextView textview;
double fromFuel,resultFuel;
Button clik;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
spinFrom = (Spinner) findViewById(R.id.fromSpinner);
spinTo = (Spinner) findViewById(R.id.toSpinner);
etfrom = (EditText) findViewById(R.id.fromET);
textview = (TextView) findViewById(R.id.Results);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(MainActivity.this,android.R.layout.simple_spinner_item,paths);
spinFrom.setAdapter(adapter);
spinTo.setAdapter(adapter);
spinFrom.setOnItemSelectedListener(this);
spinTo.setOnItemSelectedListener(this);
if( etfrom.length() == 0 || etfrom.equals("") || etfrom == null){
}
clik = (Button) findViewById(R.id.button1);
clik.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if(selectedFrom.equals(selectedTo)){
//Do nothing
}else if(selectedFrom.equals("liters/100km")&& selectedTo.equals("liters/100 miles")){
fromFuel= Double.parseDouble(etfrom.getText().toString());
resultFuel = fromFuel* 1.61;
// String result = String.valueOf(resultFuel);
textview.setText("" +resultFuel );
}else{
}
}
});
}
String selectedFrom;
String selectedTo;
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
// TODO Auto-generated method stub
selectedFrom = spinFrom.getItemAtPosition(arg2).toString();
selectedTo = spinTo.getItemAtPosition(arg2).toString();
Toast.makeText(getBaseContext(),"From: " + selectedTo, Toast.LENGTH_LONG).show();
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
}
Please try :
textview.setText(Double.toString(resultFuel) );

Closing Custom Dialog Box

I am Using the following code for my custom dialog box.
Code is here
I am using a new layout by setCustomView Method.That layout contains a 'Ok' button and a 'Cancel' button.
I need to close the dialog box when click on cancel.
buttonCancel.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
Log.d("onClick" , "YYYYY");
//up to this comes , here what I can wright
}
});
dialogObject.dismiss();
You can use this method
Why not you create custom dialog from here:
http://developer.android.com/guide/topics/ui/dialogs.html#CustomLayout
Very clearly explained and easy to implement too.
try this :
buttonCancel.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
Log.d("onClick" , "YYYYY");
qustomDialogBuilder.dismiss();//this line will close the dialog
}
});
Replace your TestDialogActivity like below,
public class TestDialogActivity extends Activity {
private static final String HALLOWEEN_ORANGE = "#FF7F27";
private AlertDialog alertDialog;
private OnClickListener mShowDialogClickListener = new OnClickListener() {
public void onClick(View v) {
QustomDialogBuilder qustomDialogBuilder = new QustomDialogBuilder(
v.getContext())
.setTitle("Set IP Address")
.setTitleColor(HALLOWEEN_ORANGE)
.setDividerColor(HALLOWEEN_ORANGE)
.setMessage("You are now entering the 10th dimension.")
.setCustomView(R.layout.example_ip_address_layout,
v.getContext())
.setIcon(getResources().getDrawable(R.drawable.ic_launcher));
alertDialog=qustomDialogBuilder.create();
qustomDialogBuilder.setAlertDialog(alertDialog);
alertDialog.show();
}
};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button bt = (Button) findViewById(R.id.button1);
bt.setOnClickListener(mShowDialogClickListener);
}
and replace setCustomView of QustomDialogBuilder like below
public QustomDialogBuilder setCustomView(int resId, final Context context) {
View customView = View.inflate(context, resId, null);
((TextView)customView.findViewById(R.id.ip_text)).setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
alertDialog.dismiss();
}
});
((FrameLayout)mDialogView.findViewById(R.id.customPanel)).addView(customView);
return this;
}
finally add below line into your QustomDialogBuilder
private AlertDialog alertDialog;
public void setAlertDialog(AlertDialog alertDialog)
{
this.alertDialog=alertDialog;
}
To close your dialog click on IP Address text.
Using the QustomDialog Source here in your activity class (TestDialogActivity), you can set the "Ok" and "Cancel" button by setting the Negative and Positive button of the dialog like this:
private OnClickListener mShowDialogClickListener =new OnClickListener(){
public void onClick(View v){
QustomDialogBuilder qustomDialogBuilder = new QustomDialogBuilder(v.getContext()).
setTitle("Set IP Address").
setTitleColor(HALLOWEEN_ORANGE).
setDividerColor(HALLOWEEN_ORANGE).
setMessage("You are now entering the 10th dimension.").
setCustomView(R.layout.example_ip_address_layout, v.getContext()).
setIcon(getResources().getDrawable(R.drawable.ic_launcher));
qustomDialogBuilder.setNegativeButton("Cancel", new android.content.DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
qustomDialogBuilder.setPositiveButton("Ok", new android.content.DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
/**
* Do something here...
*/
}
});
qustomDialogBuilder.show();
}
};
And it will look like this:
Hope you'll find this helpful. Thanks!

Categories