I have been trying for hours to figure out why android crashes after loading Profile activity. The line that is causing the issue is :
mRowId = extras != null ? extras.getLong(OverLimitDbAdapter.KEY_ROWID): null;
located in Profile.java. so I have firstly
OvertheLimit.java which puts extras via a menu option intent:
package uk.co.obdesign.android.overthelimit;
import android.app.Activity;
import android.app.ListActivity;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.RadioButton;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;
import android.widget.Toast;
public class Overthelimit extends ListActivity {
private OverLimitDbAdapter dbHelper;
private static final int USER_CREATE = 0;
private static final int USER_EDIT = 1;
private Cursor cursor;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
this.getListView();
dbHelper = new OverLimitDbAdapter(this);
dbHelper.open();
fillData();
registerForContextMenu(getListView());
}
#Override
protected void onActivityResult(int requestCode, int resultCode,
Intent intent) {
super.onActivityResult(requestCode, resultCode, intent);
fillData();
}
private void fillData() {
cursor = dbHelper.fetchAllUserDrinks();
startManagingCursor(cursor);
String[] from = new String[] { OverLimitDbAdapter.KEY_USERNAME };
int[] to = new int[] { R.id.label };
// Now create an array adapter and set it to display using our row
SimpleCursorAdapter notes = new SimpleCursorAdapter(this,
R.layout.user_row, cursor, from, to);
setListAdapter(notes);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main_menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle item selection
switch (item.getItemId()) {
case R.id.profile:
Intent myIntent1 = new Intent(Overthelimit.this, Profile.class);
myIntent1.putExtra(OverLimitDbAdapter.KEY_ROWID, cursor.getString(cursor.getColumnIndexOrThrow(OverLimitDbAdapter.KEY_ROWID)));
startActivityForResult(myIntent1, 0);
return true;
case R.id.myusual:
Intent myIntent2 = new Intent(Overthelimit.this, MyUsual.class);
startActivityForResult(myIntent2, 0);
return true;
case R.id.trackme:
Intent myIntent3 = new Intent(Overthelimit.this, TrackMe.class);
startActivityForResult(myIntent3, 0);
return true;
case R.id.moreinfo:
Intent myIntent4 = new Intent(Overthelimit.this, MoreInfo.class);
startActivityForResult(myIntent4, 0);
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
protected void onDestroy() {
super.onDestroy();
if (dbHelper != null) {
dbHelper.close();
}
}
}
then selecting the profile menu option takes me to Profile, which crashes trying to get extras.
I have checked data using toast and it's there. any ideas?
package uk.co.obdesign.android.overthelimit;
import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Spinner;
import android.widget.Toast;
public class Profile extends Activity{
private EditText mUserName;
private RadioGroup mGender;
private EditText mAge;
private EditText mHeight;
private EditText mWeight;
private Spinner mDrinkerType;
private Long mRowId;
private OverLimitDbAdapter mDbHelper;
/** Called when the activity is first created. */
#Override
public void onCreate(final Bundle bundle) {
super.onCreate(bundle);
mDbHelper = new OverLimitDbAdapter(this);
mDbHelper.open();
setContentView(R.layout.profile);
mUserName = (EditText) findViewById(R.id.userName);
mAge = (EditText) findViewById(R.id.age);
mHeight = (EditText) findViewById(R.id.height);
mWeight = (EditText) findViewById(R.id.weight);
mGender = (RadioGroup) findViewById(R.id.gender);
mDrinkerType = (Spinner) findViewById(R.id.drinkerType);
Button next = (Button) findViewById(R.id.NextUsualDrinks);
mRowId = (bundle == null) ? null :
(Long) bundle.getSerializable(OverLimitDbAdapter.KEY_ROWID);
if (mRowId == null) {
Bundle extras = getIntent().getExtras();
mRowId = extras != null ? extras.getLong(OverLimitDbAdapter.KEY_ROWID)
: null;
}
populateFields();
next.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
setResult(RESULT_OK);
//finish();
Intent myIntent = new Intent(view.getContext(), MyUsual.class);
startActivityForResult(myIntent, 0);
}
});
}
private void populateFields() {
if (mRowId != null) {
Cursor todo = mDbHelper.fetchUserDrinks(mRowId);
startManagingCursor(todo);
mUserName.setText(todo.getString(todo
.getColumnIndexOrThrow(OverLimitDbAdapter.KEY_USERNAME)));
String gender = todo.getString(todo
.getColumnIndexOrThrow(OverLimitDbAdapter.KEY_GENDER));
// Returns an integer which represents the selected radio button's ID
int selected = mGender.getCheckedRadioButtonId();
// Gets a reference to our "selected" radio button
RadioButton b = (RadioButton) findViewById(selected);
// Now you can get the text or whatever you want from the "selected" radio button
String bn = (String) b.getText();
if (bn.equalsIgnoreCase(gender)) {
if(gender == "male")
((RadioButton) findViewById(R.id.male)).setChecked(true);
else if (gender == "female")
((RadioButton) findViewById(R.id.female)).setChecked(true);
}
mAge.setText(todo.getString(todo
.getColumnIndexOrThrow(OverLimitDbAdapter.KEY_AGE)));
mHeight.setText(todo.getString(todo
.getColumnIndexOrThrow(OverLimitDbAdapter.KEY_HEIGHT)));
mWeight.setText(todo.getString(todo
.getColumnIndexOrThrow(OverLimitDbAdapter.KEY_WEIGHT)));
String drinkerType = todo.getString(todo
.getColumnIndexOrThrow(OverLimitDbAdapter.KEY_TYPE));
for (int i = 0; i < mDrinkerType.getCount(); i++) {
String s = (String) mDrinkerType.getItemAtPosition(i);
Log.e(null, s + " " + drinkerType);
if (s.equalsIgnoreCase(drinkerType)) {
mDrinkerType.setSelection(i);
}
}
}
}
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
saveState();
outState.putSerializable(OverLimitDbAdapter.KEY_ROWID, mRowId);
}
#Override
protected void onPause() {
super.onPause();
saveState();
}
#Override
protected void onResume() {
super.onResume();
populateFields();
}
private void saveState() {
String username = mUserName.getText().toString();
// Returns an integer which represents the selected radio button's ID
int selected = mGender.getCheckedRadioButtonId();
// Gets a reference to our "selected" radio button
RadioButton b = (RadioButton) findViewById(selected);
// Now you can get the text or whatever you want from the "selected" radio button
String gender = (String) b.getText();
String age = mAge.getText().toString();
String height = mHeight.getText().toString();
String weight = mWeight.getText().toString();
String type = (String) mDrinkerType.getSelectedItem();
if (mRowId == null) {
long id = mDbHelper.createUserProfile(username, gender, age, height, weight, type);
if (id > 0) {
mRowId = id;
}
} else {
mDbHelper.updateUserProfile(mRowId, username, gender, age, height, weight, type);
}
}
}
Your problem is most likely that you add a String extra (as cursor.getString(cursor.getColumnIndexOrThrow(OverLimitDbAdapter.KEY_ROWID)) returns a String) - but try to get a Long extra - which does not compute.
The following should fix the problem:
mRowId = extras != null ? Long.parseLong( extras.getString(OverLimitDbAdapter.KEY_ROWID) ) : null;
In your Overthelimit class you set the value with the following line:
myIntent1.putExtra(OverLimitDbAdapter.KEY_ROWID, cursor.getString(cursor.getColumnIndexOrThrow(OverLimitDbAdapter.KEY_ROWID)));
This puts a String value into the intent extras. Trying to get the same value as a Long value will make you applications crash, as it does not exist as a Long value. If you instead convert the value you get from your cursor object (or gets it directly as a Long from your cursor), your application should not crash anymore. Alternatively, you can get your value from the intent extras by using getString(), not getLong().
I think it giving type casting error as you store the value as string in put try to type cast at putting the value time or get the as string and then convert to long value but for type casting may be you getting type casting error in this so put into the try catch block and see the logcat details to detecting the error
type cast here from string to long or
myIntent1.putExtra(OverLimitDbAdapter.KEY_ROWID,cursor.getString(cursor.getColumnIndexOrThrow(OverLimitDbAdapter.KEY_ROWID)));
or get as string here and then type cast from string to long
String s = extras.getString(OverLimitDbAdapter.KEY_ROWID);
mRowId = extras != null ? Long.parseLong(s): null;
Related
What I need is quite simple.
1- User types some info on EditTexts.
2- Uses intent and bundle to take the data to another activity
3- Shows the data stored from EditTexts to TextViews.
But, here's the problem. EditTexts are at MainActivity, the activity that will receive the data isn't the next one, but the last one, named finalizar_relatorio.class.
And also, I'm trying to send this bundle to the next activity when I call one method because if I use startActivity() inside onCreate, it will start that activity right after pressing play. How should I call the startActivity() from within the method?
There are 4 numeric EditTexts and a char one.
Which Bundle.putXX should I use for those?
Like for char: Bundle.putString("VariableBeingCalledInNextActivity", variableThatStoresEditTextdata);
Could you help me pointing out what I'm doing wrong? Code's kind of messy, sorry for that.
I've tried following other questions here, but I'm guessing my problem is when I'm saving EditText data to the Bundle
MainActivity (UPDATED)
package com.example.relatoriodeobras;
import android.content.Context;
import android.content.ContextWrapper;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.Spinner;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.Toast;
import java.io.File;
public class MainActivity extends AppCompatActivity {
public int tipo;
SharedPreferences dadosprocesso;
public static final String PREFERENCES = "MyPrefs" ;
public static final String processo = "processo" ;
public static final String requerente = "requerente" ;
public static final String portas = "portas" ;
public static final String janelas = "janelas" ;
public static final String unhab = "unhab" ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final EditText editText4 = (EditText)findViewById(R.id.editText4);
final EditText editText5 = (EditText)findViewById(R.id.editText5);
final EditText editText6 = (EditText)findViewById(R.id.editText6);
final EditText editText7 = (EditText)findViewById(R.id.editText7);
final EditText editText8 = (EditText)findViewById(R.id.editText8);
Spinner dynamicSpinner = (Spinner) findViewById(R.id.dynamic_spinner);
String[] items = new String[] { "Tipo de fiscalização","Alvará", "Habite-se" };
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, items);
dynamicSpinner.setAdapter(adapter);
dynamicSpinner.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view,
int position, long id) {
String processo1 = editText4.getText().toString();
String requerente1 = editText5.getText().toString();
String portas1 = editText6.getText().toString();
String janelas1 = editText7.getText().toString();
String unhab1 = editText8.getText().toString();
dadosprocesso = getSharedPreferences(PREFERENCES, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = dadosprocesso.edit();
editor.putString(processo, processo1);
editor.putString(requerente, requerente1);
editor.putString(portas, portas1);
editor.putString(janelas, janelas1);
editor.putString(unhab, unhab1);
editor.commit();
Log.v("item", (String) parent.getItemAtPosition(position));
boolean fieldsOK = validate(new EditText[]{editText4,editText5,editText6,editText7,editText8});
if(fieldsOK) {
switch (position) {
case 1:
tipo = 1;
Intent intent = new Intent(MainActivity.this, alvara.class);
startActivity(intent);
break;
case 2:
tipo = 2;
Intent intent1 = new Intent(MainActivity.this, habitese.class);
startActivity(intent1);
break;
}
}
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
// TODO Auto-generated method stub
}
});
obraFolder();
}
public void obraFolder(){ //Criar a pasta do projeto e o diretório em que os projetos estarão conditos, caso não tenha sido criado.
EditText projectName = (EditText) findViewById(R.id.editText4);
String obraName = projectName.getText().toString(); //obraName é a variável String que define o nome da pasta do projeto
obraName = obraName.trim();
File myInternalFile;
String filepath = "Projetos" + obraName;
String filename = obraName + ".txt";
ContextWrapper contextWrapper = new ContextWrapper(getApplicationContext());
File directory = contextWrapper.getDir(filepath, Context.MODE_PRIVATE);
myInternalFile = new File(directory, filename);
}
private boolean validate(EditText[] fields){
for(int i=0; i<fields.length; i++){
EditText currentField=fields[i];
if(currentField.getText().toString().length()<=0){
Context context = getApplicationContext();
CharSequence text = "Atenção! Exitem campos obrigatórios vazios!!";
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
//postDelayed
return false;
}
}
startActivity(dadosdaobra);
return true;
}
}
finalizar_relatorio.java (UPDATED)
package com.example.relatoriodeobras;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.TextView;
public class finalizar_relatorio extends AppCompatActivity{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_finalizar_relatorio);
SharedPreferences dadosprocesso = getSharedPreferences("MyPrefs.xml", MODE_PRIVATE);
String restoredtext = dadosprocesso.getString("text", null);
if(restoredtext != null){
String processo = dadosprocesso.getString("processo", "processo");
String requerente = dadosprocesso.getString("requerente", "requerente");
String portas = dadosprocesso.getString("portas", "portas");
String janelas = dadosprocesso.getString("janelas", "janelas");
String unhab = dadosprocesso.getString("unhab", "unhab");
((TextView)findViewById(R.id.textView18)).setText(processo);
((TextView)findViewById(R.id.textView20)).setText(requerente);
((TextView)findViewById(R.id.textView22)).setText(portas);
((TextView)findViewById(R.id.textView24)).setText(janelas);
((TextView)findViewById(R.id.textView26)).setText(unhab);
}
}
}
try This :-
Write this code in your main activity :-
public static final String KEY_PREFERNCE = "prefernce";
public static final String KEY_ID = "id";
SharedPrefernce shraedprefernce = MainActivity.this.getSharedPrefernce(KEY_PREFERNCE ,PRIVATEMODE);
SharedPrefernce.Editor editor = shraedprefernce.edit();
editor.putString(KEY_ID ,youredittext.getText.toString);
editor.commit;
the following code used in your last activity:-
SharedPrefernce shraedprefernce = YourActivity.this.getSharedPrefernce(MainActivity.KEY_PREFERNCE ,PRIVATEMODE);
String data = shraedprefernce.getString(MainActivity.KEY_ID,"");
yourTextView.setData(data);
Don't forget to commit the editor in your main activity.
I might be confused by your question, but if your starting the activity in the onCreate, try grabbing the EditText Values in an Overrided onResume()
e.g.
protected void onResume() {
String edittext4 = editText4.getText().toString();
String edittext5 = editText5.getText().toString();
String edittext6 = editText6.getText().toString();
String edittext7 = editText7.getText().toString();
String edittext8 = editText8.getText().toString();
Intent dadosdaobra = new Intent(MainActivity.this, finalizar_relatorio.class);
Bundle dados = new Bundle();
dados.putString("extra_processo", edittext5);
dados.putString("extra_requerente", edittext4);
dados.putString("extra_portas", edittext6);
dados.putString("extra_janelas", edittext7);
dados.putString("extra_unhab", edittext8);
dadosdaobra.putExtras(dados);
addSpinnerListeners();
}
private void addSpinnerListeners() {
dynamicSpinner.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view,
int position, long id) {
Log.v("item", (String) parent.getItemAtPosition(position));
boolean fieldsOK = validate(new EditText[] {editText4,editText5,editText6,editText7,editText8});
if(fieldsOK) {
switch (position) {
case 1:
tipo = 1;
Intent intent = new Intent(MainActivity.this, alvara.class);
startActivity(intent);
break;
case 2:
tipo = 2;
Intent intent1 = new Intent(MainActivity.this, habitese.class);
startActivity(intent1);
break;
}
}
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
// TODO Auto-generated method stub
}
});
Use shared preference for this.Save data in shared prefernce and retrieve from it.
i am programming for android an app and i want to call a random phone number from this app... so i got this, that you can enter a contact and his number is going to be saved in sharedPreferences.. dont know for what but it looks cool :D.. now i am trying to call the latest contact which the user added, but i dont know how to do that... i already copied much code of other questions in my programm without success...
hope you can help me adding a call function
ummm... ya i copied nearly the whole code.. so dont ask me pls what for some statements are... (i wont have anything against an explenation)
package com.example.getcontacts;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.provider.ContactsContract;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity {
protected static final String EXTRA_MESSAGE = "com.example.getcontacts";
private TextView tv;
private int i = loadI();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv = (TextView) findViewById(R.id.tv);
load(tv, i);
// this opens the activity. note the Intent.ACTION_GET_CONTENT
// and the intent.setType
((Button)findViewById(R.id.pick_person)).setOnClickListener( new OnClickListener() {
#Override
public void onClick(View v) {
// user BoD suggests using Intent.ACTION_PICK instead of .ACTION_GET_CONTENT to avoid the chooser
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
// BoD con't: CONTENT_TYPE instead of CONTENT_ITEM_TYPE
intent.setType(ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE);
startActivityForResult(intent, 1);
}
});
//get all saved phone numbers
((Button)findViewById(R.id.allNr)).setOnClickListener( new OnClickListener() {
#Override
public void onClick(View v) {
Intent inte = new Intent(null, Contacts.class);
inte.putExtra(EXTRA_MESSAGE, i);
startActivity(inte);
}
});
}
//doing random sh*t which i dont know whaat happens
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (data != null) {
//get some datas... ?
Uri uri = data.getData();
if (uri != null) {
//get more data
Cursor c = null;
try {
//initializing something
c = getContentResolver().query(uri, new String[]{
ContactsContract.CommonDataKinds.Phone.NUMBER,
ContactsContract.CommonDataKinds.Phone.TYPE },
null, null, null);
if (c != null && c.moveToFirst()) {
//initializing phone number
String number = c.getString(0);
//get the type... somehow
int type = c.getInt(1);
//save in shared preferences and show the latest nr
int i = save(number);
showSelectedNumber(type, number);
load(tv, i);
}
} finally {
if (c != null) {
c.close();
}
}
}
}
}
public void showSelectedNumber(int type, String number) {
Toast.makeText(this, "Saved Nr : " + number, Toast.LENGTH_LONG).show();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#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();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public String load(TextView tv, int i) {
String sharedNumber;
SharedPreferences sp = PreferenceManager
.getDefaultSharedPreferences(this);
String c = Integer.toString(i);
sharedNumber = sp.getString(c, "");
tv.setText("Number: " + sharedNumber);
return sharedNumber;
}
public int save(String value) {
SharedPreferences sp = PreferenceManager
.getDefaultSharedPreferences(this);
Editor edit = sp.edit();
int i = 0;
String c;
c = Integer.toString(i);
edit.putString(c, value);
edit.commit();
i =Integer.parseInt(c);
i++;
saveI("savedI", i);
return i;
}
public void saveI(String key, int value) {
SharedPreferences sp = PreferenceManager
.getDefaultSharedPreferences(this);
Editor edit = sp.edit();
edit.putInt(key, value);
edit.commit();
}
public int loadI() {
int sharedNumber;
SharedPreferences sp = PreferenceManager
.getDefaultSharedPreferences(this);
sharedNumber = sp.getInt("savedI", 0);
return sharedNumber;
}
}
I made a table in SQL that stores id as a string. Now when I want to retrieve a particular record by comparing the string id, it is returning null pointer exception.
I don't know how to solve this.
here is the activity that calls the database by passing the string
SearchDb.java
import android.app.Activity;
import android.app.Dialog;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class SearchDb extends Activity implements OnClickListener {
EditText enid;
Button search;
TextView id, name, age;
String s;
Bundle value;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.searchdb);
enid = (EditText) findViewById(R.id.et_enid);
search = (Button) findViewById(R.id.bsearch);
id = (TextView) findViewById(R.id.tv_enid);
name = (TextView) findViewById(R.id.tv_name);
age = (TextView) findViewById(R.id.tv_age);
search.setOnClickListener(this);
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.bsearch:
try {
s = enid.getText().toString();
CreateDB fetch = new CreateDB(this);
value = fetch.fetchData(s);
fetch.close();
id.setText(value.getString("id"));
name.setText(value.getString("name"));
age.setText(value.getString("age"));
} catch (Exception e) {
Dialog d = new Dialog(this);
TextView tv = new TextView(this);
tv.setText(e.toString());
d.setTitle("Error!!");
d.setContentView(tv);
d.show();
}
}
// TODO Auto-generated method stub
}
}
the CreateDB class constructor is--
public CreateDB(Context cxt) {
myContext = cxt;
myDB = myContext.openOrCreateDatabase(DbName, DbVersion, null);
}
and the method to search is like this--
public Bundle fetchData(String l) throws SQLException {
String[] chck=new String[]{l};
Cursor c = myDB.query(TbName, cols, KeyId+"=?", chck, null, null, null);
if (c != null) {
int iName = c.getColumnIndex(KeyName);
int iAge = c.getColumnIndex(KeyAge);
int iId = c.getColumnIndex(KeyId);
c.moveToFirst();
send.putString("id", c.getString(iId));
send.putString("name", c.getString(iName));
send.putString("age", c.getString(iAge));
return send;
}
// TODO Auto-generated method stub
return null;
}
Finally I am getting a java.lang.NullPointerException in LogCat.
Please help!
Your code is totally correct. It is returning error because the bundle in which the values are stored is not initialized. So it becomes null hence null pointer exception error. Just initialize your bundle as Bundle send=new Bundle();. Then your code will work fine.
It didn't showing up any error. however when I run my application, there is no result appear from my listView. I think,the mistake is because of i didn't use the correct way doing switch case statement. here is my code.
QuickSearch.java
package com.example.awesome;
import java.io.IOException;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.database.SQLException;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class QuickSearch extends Activity implements OnClickListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
//-------------------------------------------------------------------------
// Initiate database data
initiateDb();
//---------------------------------------------------------------------------
// Declaration of view
final Button qsfaculty, qscollege;
super.onCreate(savedInstanceState);
setContentView(R.layout.quick_search);
//---------------------------------------------------------------------------
// Get reference
qsfaculty = (Button) this.findViewById(R.id.button1);
qsfaculty.setOnClickListener(this);
qscollege = (Button) this.findViewById(R.id.button2);
qscollege.setOnClickListener(this);
}
public void onClick(View v) {
char ch = 0;
View qsfaculty = null;
View qscollege = null;
if(v == qsfaculty){
ch = 'a';
}
else if (v == qscollege)
{ch = 'b';}
Intent i = new Intent(this,SearchLocation.class);
i.putExtra("value",ch);
startActivity(i);
}
//---------------------------------------------------------------------------
// Initiate database data
public void initiateDb() {
DatabaseHandler myDbHandler = new DatabaseHandler(this);
try {
myDbHandler.createDataBase();
}
catch (IOException ioe) {
throw new Error("Unable to create database");
}
try {
myDbHandler.openDataBase();
}
catch(SQLException sqle) {
throw sqle;
}
Log.d("Initiate", "UKM Location Count: " + myDbHandler.getUkmLocationCount());
myDbHandler.close();
}
//------------------------------------------------------------------------------
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.quick_search, menu);
return true;
}
}
SearchLocation.java
package com.example.awesome;
import java.util.ArrayList;
import java.util.List;
import android.os.Bundle;
import android.app.Activity;
import android.app.ListActivity;
import android.content.Intent;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
public class SearchLocation extends ListActivity {
//------------------------------------------------------------------
// Declaration
public static UkmLocation selectedPOI = null;
final DatabaseHandler db = new DatabaseHandler(this);
private EditText filterText = null;
ArrayAdapter<String> adapter = null;
final ArrayList<String> results = new ArrayList<String>();
final ArrayList<String> results_id = new ArrayList<String>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.search_location);
final Intent c = new Intent(SearchLocation.this, LocationDetail.class);
//------------------------------------------------------------------
// Link editText to layout item
filterText = (EditText) findViewById(R.id.search_box);
filterText.addTextChangedListener(filterTextWatcher);
//------------------------------------------------------------------
// Reading Poi
Log.d("Reading", "Reading all Kategori ..");
int value = 0;
switch(value) {
case 'a' :
List<UkmLocation> faculty = db.getCategoryFaculty();
for(UkmLocation k : faculty) {
results.add(k.getName());
results_id.add(k.getID());
}
break;
case 'b' :
List<UkmLocation> college = db.getCategoryCollege();
for(UkmLocation k : college) {
results.add(k.getName());
results_id.add(k.getID());
}
break;
}
//------------------------------------------------------------------
// Set list arrayAdapter to adapter
adapter = new ArrayAdapter<String>(this, R.layout.list_item, R.id.textView1,results);
setListAdapter(adapter);
//------------------------------------------------------------------
// Set ListView from ListActivity
ListView lv = getListView();
lv.setTextFilterEnabled(true);
//------------------------------------------------------------------
// Set click event from listView
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// When clicked, show a toast with the TextView text
Toast.makeText(getApplicationContext(), ((TextView) view).getText(),
Toast.LENGTH_SHORT).show();
Log.d("test", "position:" + position);
Log.d("test", "actualname:" + db.getUkmLocationByName(adapter.getItem(position)).getName());
// String poiID = results_id.get(position);
String poiID = db.getUkmLocationByName(adapter.getItem(position)).getID();
setSelectedPoi(poiID);
startActivity(c);
}
});
}
private TextWatcher filterTextWatcher = new TextWatcher() {
public void afterTextChanged(Editable s) {
}
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
}
public void onTextChanged(CharSequence s, int start, int before,
int count) {
adapter.getFilter().filter(s);
}
};
#Override
protected void onDestroy() {
super.onDestroy();
filterText.removeTextChangedListener(filterTextWatcher);
}
public UkmLocation getSelectedPoi() {
return selectedPOI;
}
public void setSelectedPoi(String poiID) {
selectedPOI = db.getUkmLocation(poiID);
Log.d("test2", "_id:" + db.getUkmLocation(poiID).getID());
Log.d("test2", "Name:" + db.getUkmLocation(poiID).getName());
// Closing db
db.close();
}
}
i think,the if else statement inside QuickSearch.java is already correct. the problem at the switch case statement at SearchLocation.java
please help me solve this.
int value = 0;
switch(value) {
You are setting the value over which you switch to 0 so it is equivalent to doing switch(0) {...
Find out what that value is supposed to be and initialise it properly.
Also, value is of type int but your switch uses chars ('a', 'b'), so you need to either have value be a char and initialise it properly or have it be an int, initialise it properly and change your switch cases to use ints.
First you do int value = 0; so value is 0. So it is not 'a' nor 'b'.
You have to get the value from the intent as you put it in extras. i.putExtra("value",ch);
something like
char value;
Bundle extras = getIntent().getExtras();
if (extras != null) {
value = extras.getIntgetChar("value");
}
here, i already solve my problem..
QuickSearch.java
public void onClick(View v) {
int ch = 0;
/*View qsfaculty = null;
View qscollege = null;*/
if(v == qsfaculty){
ch = '1';
}
else if (v == qscollege)
{ch = '2';}
Intent i = new Intent(this,SearchLocation.class);
i.putExtra("value",ch);
startActivity(i);
}
SearchLocation.java
Bundle extras = getIntent().getExtras();
int value = extras.getInt("value");
switch(value) {
case '1' :
List<UkmLocation> faculty = db.getCategoryFaculty();
for(UkmLocation k : faculty) {
results.add(k.getName());
results_id.add(k.getID());
}
break;
case '2' :
List<UkmLocation> college = db.getCategoryCollege();
for(UkmLocation k : college) {
results.add(k.getName());
results_id.add(k.getID());
}
break;
}
I am trying the tutorial notepadv2 for android. I did everything the tutorial said (and used only the code they gave me)and i am getting errors all over the place. Help!!!!
this is my NoteEdit.java file in /src
package com.android.demo.notepad2;
import android.app.Activity;
import android.os.Bundle;
private EditText mTitleText;
private EditText mBodyText;
private Long mRowId;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.note_edit);
mTitleText = (EditText) findViewById(R.id.title);
mBodyText = (EditText) findViewById(R.id.body);
Button confirmButton = (Button) findViewById(R.id.confirm);
mRowId = null;
Bundle extras = getIntent().getExtras();
if (extras != null) {
String title = extras.getString(NotesDbAdapter.KEY_TITLE);
String body = extras.getString(NotesDbAdapter.KEY_BODY);
mRowId = extras.getLong(NotesDbAdapter.KEY_ROWID);
if (title != null) {
mTitleText.setText(title);
}
if (body != null) {
mBodyText.setText(body);
}
}
confirmButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Bundle bundle = new Bundle();
bundle.putString(NotesDbAdapter.KEY_TITLE, mTitleText.getText().toString());
bundle.putString(NotesDbAdapter.KEY_BODY, mBodyText.getText().toString());
if (mRowId != null) {
bundle.putLong(NotesDbAdapter.KEY_ROWID, mRowId);
}
Intent mIntent = new Intent();
mIntent.putExtras(bundle);
setResult(RESULT_OK, mIntent);
finish();
}
});
}
this is my Notepadv2.java file in /src
package com.android.demo.notepad2;
import android.app.ListActivity;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.view.ContextMenu;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ContextMenu.ContextMenuInfo;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
public class Notepadv2 extends ListActivity {
private static final int ACTIVITY_CREATE=0;
private static final int ACTIVITY_EDIT=1;
private static final int INSERT_ID = Menu.FIRST;
private static final int DELETE_ID = Menu.FIRST + 1;
private NotesDbAdapter mDbHelper;
private Cursor mNotesCursor;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.notes_list);
mDbHelper = new NotesDbAdapter(this);
mDbHelper.open();
fillData();
registerForContextMenu(getListView());
}
private void fillData() {
// Get all of the rows from the database and create the item list
mNotesCursor = mDbHelper.fetchAllNotes();
startManagingCursor(mNotesCursor);
// Create an array to specify the fields we want to display in the list (only TITLE)
String[] from = new String[]{NotesDbAdapter.KEY_TITLE};
// and an array of the fields we want to bind those fields to (in this case just text1)
int[] to = new int[]{R.id.text1};
// Now create a simple cursor adapter and set it to display
SimpleCursorAdapter notes =
new SimpleCursorAdapter(this, R.layout.notes_row, mNotesCursor, from, to);
setListAdapter(notes);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
menu.add(0, INSERT_ID,0, R.string.menu_insert);
return true;
}
#Override
public boolean onMenuItemSelected(int featureId, MenuItem item) {
switch(item.getItemId()) {
case INSERT_ID:
createNote();
return true;
}
return super.onMenuItemSelected(featureId, item);
}
#Override
public void onCreateContextMenu(Menu menu, View v,
ContextMenu.ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
menu.add(0, DELETE_ID, 0, R.string.menu_delete);
}
#Override
public boolean onContextItemSelected(MenuItem item) {
switch(item.getItemId()) {
case DELETE_ID:
AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
mDbHelper.deleteNote(info.id);
fillData();
return true;
}
return super.onContextItemSelected(item);
}
private void createNote() {
Intent i = new Intent(this, NoteEdit.class);
startActivityForResult(i, ACTIVITY_CREATE);
}
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
Cursor c = mNotesCursor;
c.moveToPosition(position);
Intent i = new Intent(this, NoteEdit.class);
i.putExtra(NotesDbAdapter.KEY_ROWID, id);
i.putExtra(NotesDbAdapter.KEY_TITLE, c.getString(
c.getColumnIndexOrThrow(NotesDbAdapter.KEY_TITLE)));
i.putExtra(NotesDbAdapter.KEY_BODY, c.getString(
c.getColumnIndexOrThrow(NotesDbAdapter.KEY_BODY)));
startActivityForResult(i, ACTIVITY_EDIT);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
super.onActivityResult(requestCode, resultCode, intent);
super.onActivityResult(requestCode, resultCode, intent);
Bundle extras = intent.getExtras();
switch(requestCode) {
case ACTIVITY_CREATE:
String title = extras.getString(NotesDbAdapter.KEY_TITLE);
String body = extras.getString(NotesDbAdapter.KEY_BODY);
mDbHelper.createNote(title, body);
fillData();
break;
case ACTIVITY_EDIT:
Long mRowId = extras.getLong(NotesDbAdapter.KEY_ROWID);
if (mRowId != null) {
String editTitle = extras.getString(NotesDbAdapter.KEY_TITLE);
String editBody = extras.getString(NotesDbAdapter.KEY_BODY);
mDbHelper.updateNote(mRowId, editTitle, editBody);
}
fillData();
break;
}
}
}
These are the two files that the errors are coming from
NoteEdit will not compile because it has no class declaration...
package com.android.demo.notepad2;
import android.app.Activity;
import android.os.Bundle;
//missing this line:
//public class NoteEdit extends Activity {
private EditText mTitleText;
private EditText mBodyText;
private Long mRowId;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.note_edit);
Without a class declaration, the parser will spit up errors all over the place, as nothing will make sense anymore.
I am not sure if there are any errors in Notepadv2 just by looking at it.