How to solve this java.lang.NullPointerException - sqlite

Hi I'm new to android programming, and i don't know or i really can't figure out why do i get this error message after i click the button on the app that i created
java.lang.NullPointerException at
com.example.dailydoseofhappiness.MainActivity.searchRecord(MainActivity.java:62)
at
com.example.dailydoseofhappiness.MainActivity.searchRecord(MainActivity.java:52)
here is the code fragment.
public void onClick(View arg){
if(arg.getId()==R.id.btnfortune){ //this is line 52
searchRecord(count);
}
}
public void searchRecord(int count)
throws SQLException
{
Cursor rsCursor;
String [] rsFields = {"mesNum","Message"}; // this is line 62
rsCursor = dbm.dbase.query("MessageFile", rsFields, "mesNum = " + count, null, null, null, null, null);
rsCursor.moveToFirst();
if(rsCursor.isAfterLast()==false){
lblmessageS.setText(rsCursor.getString(0));
}
rsCursor.close();
}
can anyone check this code fragment if whats wrong thank you very much

Try this searchRecord method. I added some silly checks so if any variable is null it will warn you:
public void searchRecord(int count) throws SQLException {
Cursor rsCursor;
String [] rsFields = {"mesNum","Message"}; // this is line 62
if (dbm == null)
throw new Exception("dbm object is null");
if (dbm.dbase == null)
throw new Exception("dbm.dbase is null");
rsCursor = dbm.dbase.query("MessageFile", rsFields, "mesNum = " + count, null, null, null, null, null);
if (rsCursor == null)
throw new Exception("rsCursor is null");
rsCursor.moveToFirst();
if (rsCursor.isAfterLast()==false){
if (lblmessageS == null)
throw new Exception("lblmessageS is null");
lblmessageS.setText(rsCursor.getString(0));
}
rsCursor.close();
}

Related

Android : org json jsonexception no value for

i use this json url :
https://www.theaudiodb.com/api/v1/json/1/search.php?s=coldplay
{
"artists": [
{
"idArtist": "111239",
"strArtist": "Coldplay",
"strArtistStripped": null,
"strArtistAlternate": "",
"strLabel": "Parlophone",
"idLabel": "45114",
"intFormedYear": "1996",
"intBornYear": "1996",
"intDiedYear": null,
"strDisbanded": null,
"strStyle": "Rock/Pop",
"strGenre": "Alternative Rock",
etc
}
and this is my android java code :
void syncToUrl() {
AsyncHttpClient client = new AsyncHttpClient();
String url = "https://www.theaudiodb.com/api/v1/json/1/search.php?s=coldplay";
client.get(url, new TextHttpResponseHandler() {
#Override
public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
Toast.makeText(MainActivity.this, "Error", Toast.LENGTH_SHORT).show();
}
#Override
public void onSuccess(int statusCode, Header[] headers, String responseString) {
parseAndShow(responseString);
}
});
}
void parseAndShow(String responce) {
try {
JSONObject artistBio = new JSONObject(responce);
artistNickname.setText(artistBio.getString("strArtist"));
} catch (Exception e) {
Toast.makeText(MainActivity.this, e.toString(), Toast.LENGTH_SHORT).show();
Error.setText(e.toString());
}
}
But I still get this Error:
org.json.jsonexception no value for strArtist.
The strArtist has this value "Coldplay", but why do I get this error?
You can get the value of strArtist as follows:
JSONObject artistBio = new JSONObject(responce);
JSONArray artists = artistBio.getJSONArray("artists");
for (int i=0; i < artists.length(); i++) {
JSONObject object = artists.getJSONObject(i);
String name = actor.getString("strArtist");
artistNickname.setText(artistBio.getString("strArtist"));
}
EDIT
Since your json has only one object inside the array, you can skip the for loop implementation and directly use as follows:
JSONObject object = artists.getJSONObject(0);
String name = actor.getString("strArtist");
artistNickname.setText(artistBio.getString("strArtist"));

Read the database to MapProperty Javafx

I created MapProperty to read the information from the database as below.
The command runs fine with Map,ArrayList normal but error MapProperty.I want member to be ListProperty type so I can bind it to control
public MapProperty<String, ListProperty<String>> mapTaxonomy() {
MapProperty<String, ListProperty<String>> mapTaxonomy = new SimpleMapProperty<>();
try {
preparedStatement = connection.prepareStatement("");
resultSet = preparedStatement.executeQuery();
while (resultSet.next()) {
String taxonomy = resultSet.getString("Taxonomy");
ListProperty<String> memberSelector = mapTaxonomy.get(taxonomy);
if (memberSelector == null) {
memberSelector = new SimpleListProperty<>();
mapTaxonomy.put(taxonomy, memberSelector);
}
memberSelector.add(resultSet.getString("Selector"));
}
} catch (SQLException ex) {
Logger.getLogger(ParserService.class.getName()).log(Level.SEVERE, null, ex);
}
return mapTaxonomy;
}
#Override
public void initialize(URL location, ResourceBundle resources) {
MapProperty<String, ListProperty<String>> mapTaxonomy = mapTaxonomy();
}
After I run the following error statement,please help me
Caused by: java.lang.UnsupportedOperationException
at java.util.AbstractMap.put(AbstractMap.java:209)
at javafx.beans.binding.MapExpression.put(MapExpression.java:262)
at touya.akira.storages.database.table.parser.ParserService.mapTaxonomy(ParserService.java:70)
at touya.akira.parser.styles.fixed.method.pagination.PaginationPresenter.initialize(PaginationPresenter.java:64)
at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:2548)
... 67 more
The default value of a SimpleMapProperty is a empty unmodifiable map. An exception is thrown when you try to modify it. Specify a modifiable ObservableMap as initial value to fix this issue.
MapProperty<String, ListProperty<String>> mapTaxonomy = new SimpleMapProperty<>(FXCollections.observableHashMap());

Error occured while updating field in database: An unhandled exception of type 'System.StackOverflowException' occurred in Unknown Module.in mvc

I have a table with columns checkbox,Document name,Field & so on. In Field column I have displayed dropdown so as I change the values in dropdown it should be updated in table.I am passing DocumentId and crossponding fieldId (of row)through jquery to controller.But I get this error in Repository.cs file
An unhandled exception of type 'System.StackOverflowException' occurred in Unknown Module.
This is my Controller Code
public ActionResult FieldSubmitted(long VendorId, int DocumentId, int FieldId)
{
SubmittedDocument submittedDocument = new SubmittedDocument();
var requestedDocument = _requestedDocumentService.GetVendorDocuments(VendorId).Where(t => t.DocumentID == DocumentId).FirstOrDefault();
if (requestedDocument != null)
{
submittedDocument = _submittedDocumentService.GetVendorDocuments(VendorId).Where(t => t.RequestedDocumentID == requestedDocument.RequestedDocumentID).FirstOrDefault();
submittedDocument.FieldId = FieldId;
_submittedDocumentService.UpdateSubmittedDocument(submittedDocument);
}
return Json("", JsonRequestBehavior.AllowGet);
}
My Service
public int UpdateSubmittedDocument(SubmittedDocument submittedDocument)
{
int a= _submittedDocumentRepository.Update(submittedDocument, submittedDocument.SubmittedDocumentID);
return a;
}
Repository.cs
public class Repository<TObject> : IRepository<TObject>
public virtual void UpdateAuditedEntries(object obj)
{
if (CurrentUser == null)
return;
if (obj == null)
return;
var auditedEntity = obj as IAuditedEntity;
if (auditedEntity != null)
{
auditedEntity.ModifiedBy = CurrentUser.UserId;
auditedEntity.ModifiedDateTime = DateTime.Now;
obj.GetType().GetProperties().ToList().ForEach(x =>
{
var child = x.GetValue(obj);
UpdateAuditedEntries(child);
});
}
else
{
var propertyCollection = obj as ICollection;
if (propertyCollection != null)
{
foreach (object child in propertyCollection)
{
UpdateAuditedEntries(child);
}
}
}
}
I am getting error at var child = x.GetValue(obj); this line
An unhandled exception of type 'System.StackOverflowException' occurred in Unknown Module.
You are calling UpdateAuditedEntries(child); recursively within your function and it does not end. I suspect that is causing the stackoverflow exception

why sometime i get the cursor null or count equal to zero

My apliction works fine ,it updates my spinner but sometime when I start my activity cursor becomes null and spinner list will be blank ,why?.It seems like my cursor is null or its count is zero. Though it works fine most of the time so there is no chance of cursor being null or emplty.very strange behavior
public class MainActivity extends Activity {
String[] data = { MediaStore.Video.Media.DATA };
ArrayList<String> path;
Spinner path_spinner;
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.MainActivity);
path= new ArrayList<String>();
path_spinner = (Spinner) findViewById(R.id.folder_spinner);
Cursor cursor = managedQuery(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,data, null, null, null);
if(cursor != null && cursor.getCount() > 0)
{
cursor.moveToFirst();
do {
path.add(cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA))
} while (cursor.moveToNext());
}
ArrayAdapter<String> path_adapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1, path);
path_spinner.setAdapter(path_adapter);
}
}
Update
if any uri is accessd at this time it gives
ContentValues values = new ContentValues(4);
values.put(MediaStore.Audio.Media.TITLE,"audio" + audiofile.getName());
values.put(MediaStore.Audio.Media.MIME_TYPE, "audio/3gpp");
values.put(MediaStore.Audio.Media.DATA, audiofile.getAbsolutePath());
ContentResolver contentResolver = getContentResolver();
Uri base = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
Uri newUri = contentResolver.insert(base, values);
07-24 15:52:22.300: E/AndroidRuntime(2583): Caused by: java.lang.UnsupportedOperationException: Unknown URI: content://media/external/audio/media
it was all working fine before the cursor problem .It seems like content provider is not accesible at the moment. why?

Unreachable code

public void onClick(View v) {
String uname=tv1.getText().toString();
String pass=tv2.getText().toString();
//String copmare=uname.concat(pass);
Cursor cur = db.query("accountTable", // Where are we looking?
new String[]{ "colProject" }, // What do we want back?
"colName = ? AND colPass = ?", // What are we matching?
new String[]{ uname, pass }, // What to put in the "holes"?
null, null, null); // Everything else default...
if (cur != null) {
cur.moveToNext();
}
return;
Intent i = new Intent(FirstAssignmentActivity.this,success.class);
i.putExtra("v1", cur.getString(0));
startActivity(i);
}
Why do I have unreachable code?
You write return ;, so control will exit the function at that point and not reach the final 3 lines of the function (Intent i, etc)
You are returning from the method. None of the code after that will execute.
if (cur != null) {
cur.moveToNext();
}
return; // AFTER THIS NOTHING WILL EXECUTE

Resources