This question already has answers here:
Unfortunately MyApp has stopped. How can I solve this?
(23 answers)
Closed 5 years ago.
I have a problem with my project. When I click the Search button, my application will crash on my phone. the "Search" button is a method where it retrieves information from SQLiteDatabase. This activity is Where Clause activity. Whenever I click the Search button, it crashes.
This is my coding:
package com.example.taza.rshinventorymanager;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class Homepage extends AppCompatActivity
{
TextView locationoutput, quantityoutput, size1output, size2output, size3output,
size4output, size5output, size6output, size7output, size8output, size9output,
size10output, size11output, size12output, size13output, sizeXSoutput, sizeSoutput,
sizeMoutput, sizeLoutput, sizeXLoutput, size2XLoutput;
EditText searchproduct;
ProductDBHelper productDBHelper;
SQLiteDatabase sqLiteDatabase;
String Searchproduct;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_homepage);
Button LoginButton = (Button)findViewById(R.id.HomepageLoginButton);
LoginButton.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
Intent startIntent = new Intent(getApplicationContext(), LoginPage.class);
startActivity(startIntent);
}
});
searchproduct = (EditText)findViewById(R.id.HomepageET);
locationoutput = (TextView)findViewById(R.id.HPLocation);
quantityoutput = (TextView)findViewById(R.id.HPQuantity);
size1output = (TextView)findViewById(R.id.HP1);
size2output = (TextView)findViewById(R.id.HP2);
size3output = (TextView)findViewById(R.id.HP3);
size4output = (TextView)findViewById(R.id.HP4);
size5output = (TextView)findViewById(R.id.HP5);
size6output = (TextView)findViewById(R.id.HP6);
size7output = (TextView)findViewById(R.id.HP7);
size8output = (TextView)findViewById(R.id.HP8);
size9output = (TextView)findViewById(R.id.HP9);
size10output = (TextView)findViewById(R.id.HP10);
size11output = (TextView)findViewById(R.id.HP11);
size12output = (TextView)findViewById(R.id.HP12);
size13output = (TextView)findViewById(R.id.HP13);
sizeXSoutput = (TextView)findViewById(R.id.HPXS);
sizeSoutput = (TextView)findViewById(R.id.HPS);
sizeMoutput = (TextView)findViewById(R.id.HPM);
sizeLoutput = (TextView)findViewById(R.id.HPL);
sizeXLoutput = (TextView)findViewById(R.id.HPXL);
size2XLoutput = (TextView)findViewById(R.id.HP2XL);
locationoutput.setVisibility(View.GONE);
quantityoutput.setVisibility(View.GONE);
size1output.setVisibility(View.GONE);
size1output.setVisibility(View.GONE);
size2output.setVisibility(View.GONE);
size3output.setVisibility(View.GONE);
size4output.setVisibility(View.GONE);
size5output.setVisibility(View.GONE);
size6output.setVisibility(View.GONE);
size7output.setVisibility(View.GONE);
size8output.setVisibility(View.GONE);
size9output.setVisibility(View.GONE);
size10output.setVisibility(View.GONE);
size11output.setVisibility(View.GONE);
size12output.setVisibility(View.GONE);
size13output.setVisibility(View.GONE);
sizeXSoutput.setVisibility(View.GONE);
sizeSoutput.setVisibility(View.GONE);
sizeMoutput.setVisibility(View.GONE);
sizeLoutput.setVisibility(View.GONE);
sizeXLoutput.setVisibility(View.GONE);
size2XLoutput.setVisibility(View.GONE);
}
public void SearchProduct (View view)
{
Searchproduct = searchproduct.getText().toString();
productDBHelper = new ProductDBHelper(getApplicationContext());
sqLiteDatabase = productDBHelper.getReadableDatabase();
Cursor cursor = productDBHelper.getProduct(Searchproduct, sqLiteDatabase);
if(cursor.moveToFirst())
{
String locationsearch = cursor.getString(0);
String quantitysearch = cursor.getString(1);
String size1search = cursor.getString(2);
String size2search = cursor.getString(3);
String size3search = cursor.getString(4);
String size4search = cursor.getString(5);
String size5search = cursor.getString(6);
String size6search = cursor.getString(7);
String size7search = cursor.getString(8);
String size8search = cursor.getString(9);
String size9search = cursor.getString(10);
String size10search = cursor.getString(11);
String size11search = cursor.getString(12);
String size12search = cursor.getString(13);
String size13search = cursor.getString(14);
String sizeXSsearch = cursor.getString(15);
String sizeSsearch = cursor.getString(16);
String sizeMsearch = cursor.getString(17);
String sizeLsearch = cursor.getString(18);
String sizeXLsearch = cursor.getString(19);
String size2XLsearch = cursor.getString(20);
locationoutput.setText(locationsearch);
quantityoutput.setText(quantitysearch);
size1output.setText(size1search);
size2output.setText(size2search);
size3output.setText(size3search);
size4output.setText(size4search);
size5output.setText(size5search);
size6output.setText(size6search);
size7output.setText(size7search);
size8output.setText(size8search);
size9output.setText(size9search);
size10output.setText(size10search);
size11output.setText(size11search);
size12output.setText(size12search);
size13output.setText(size13search);
sizeXSoutput.setText(sizeXSsearch);
sizeSoutput.setText(sizeSsearch);
sizeMoutput.setText(sizeMsearch);
sizeLoutput.setText(sizeLsearch);
sizeXLoutput.setText(sizeXLsearch);
size2XLoutput.setText(size2XLsearch);
locationoutput.setVisibility(View.VISIBLE);
quantityoutput.setVisibility(View.VISIBLE);
size1output.setVisibility(View.VISIBLE);
size1output.setVisibility(View.VISIBLE);
size2output.setVisibility(View.VISIBLE);
size3output.setVisibility(View.VISIBLE);
size4output.setVisibility(View.VISIBLE);
size5output.setVisibility(View.VISIBLE);
size6output.setVisibility(View.VISIBLE);
size7output.setVisibility(View.VISIBLE);
size8output.setVisibility(View.VISIBLE);
size9output.setVisibility(View.VISIBLE);
size10output.setVisibility(View.VISIBLE);
size11output.setVisibility(View.VISIBLE);
size12output.setVisibility(View.VISIBLE);
size13output.setVisibility(View.VISIBLE);
sizeXSoutput.setVisibility(View.VISIBLE);
sizeSoutput.setVisibility(View.VISIBLE);
sizeMoutput.setVisibility(View.VISIBLE);
sizeLoutput.setVisibility(View.VISIBLE);
sizeXLoutput.setVisibility(View.VISIBLE);
size2XLoutput.setVisibility(View.VISIBLE);
}
}
}
I found the Logcat after i debug. Here's the error:
01-24 12:07:21.692 3720-3720/? E/DATABASE OPERATIONS: Database created / opened...
01-24 12:07:21.695 3720-3720/? E/SQLiteLog: (1) near "TABLEproduct_information": syntax error
01-24 12:07:21.695 3720-3720/? D/AndroidRuntime: Shutting down VM
01-24 12:07:21.696 3720-3720/? E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.taza.rshinventorymanager, PID: 3720
java.lang.IllegalStateException: Could not execute method for android:onClick
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:293)
at android.view.View.performClick(View.java:4780)
at android.view.View$PerformClick.run(View.java:19866)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5254)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
Caused by: java.lang.reflect.InvocationTargetException
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:288)
at android.view.View.performClick(View.java:4780)
at android.view.View$PerformClick.run(View.java:19866)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5254)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
Caused by: android.database.sqlite.SQLiteException: near "TABLEproduct_information": syntax error (code 1): , while compiling: CREATE TABLEproduct_information(product_codeTEXT,product_locationTEXT,product_quantityTEXT,size_1TEXT,size_2TEXT,size_3TEXT,size_4TEXT,size_5TEXT,size_6TEXT,size_7TEXT,size_8TEXT,size_9TEXT,size_10TEXT,size_11TEXT,size_12TEXT,size_13TEXT,size_XSTEXT,size_STEXT,size_MTEXT,size_LTEXT,size_XLTEXT,size_2XLTEXT)
at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method)
at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:889)
at android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:500)
at android.database.sqlite.SQLiteSession.prepare(SQLiteSession.java:588)
at android.database.sqlite.SQLiteProgram.<init>(SQLiteProgram.java:58)
at android.database.sqlite.SQLiteStatement.<init>(SQLiteStatement.java:31)
at android.database.sqlite.SQLiteDatabase.executeSql(SQLiteDatabase.java:1674)
at android.database.sqlite.SQLiteDatabase.execSQL(SQLiteDatabase.java:1605)
at com.example.taza.rshinventorymanager.ProductDBHelper.onCreate(ProductDBHelper.java:52)
at android.database.sqlite.SQLiteOpenHelper.getDatabaseLocked(SQLiteOpenHelper.java:251)
at android.database.sqlite.SQLiteOpenHelper.getReadableDatabase(SQLiteOpenHelper.java:187)
at com.example.taza.rshinventorymanager.Homepage.SearchProduct(Homepage.java:101)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:288)
at android.view.View.performClick(View.java:4780)
at android.view.View$PerformClick.run(View.java:19866)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5254)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
You are writing onClick method inside onCreate
#Override
public void onClick(View v)
{
Intent startIntent = new Intent(getApplicationContext(), LoginPage.class);
startActivity(startIntent);
}
Related
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 4 years ago.
I am having trouble adding items to my spinner from an Arraylist. I have it working in other parts of my code, but it wont work when I put it in my dialog.
The exact problem is that it causes the app to crash. The crash happens when I press the button to open the dialog.
Here is the problematic code:
public void transferButton(View view) {
final Dialog dialog = new Dialog(this);
dialog.setContentView(R.layout.dialog_transfer);
ArrayList<String> file = new ArrayList();
List<String> accounts = new ArrayList();
File path = Environment.getExternalStorageDirectory();
File myExternalFile = new File(path.getAbsolutePath() + folderLoc, "accounts.txt");
try {
FileInputStream fis = new FileInputStream(myExternalFile);
DataInputStream in = new DataInputStream(fis);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine;
while ((strLine = br.readLine()) != null) {
file.add(strLine);
}
br.close();
in.close();
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
ArrayAdapter<String> adapter1 = new ArrayAdapter(this, android.R.layout.simple_spinner_item);
ArrayAdapter<String> adapter2 = new ArrayAdapter(this, android.R.layout.simple_spinner_item);
adapter1.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
adapter2.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
Spinner fromSpinner = (Spinner) view.findViewById(R.id.fromAccountSpinner);
Spinner toSpinner = (Spinner) view.findViewById(R.id.toAccountSpinner);
for (int i = 0; i < file.size(); i++) {
String[] splitArray = file.get(i).split("//");
adapter1.add(splitArray[0]);
adapter2.add(splitArray[0]);
}
adapter1.insert("From...", 0);
fromSpinner.setAdapter(adapter1);
adapter2.insert("To...", 0);
toSpinner.setAdapter(adapter2);
Button dialogButton = (Button) dialog.findViewById(R.id.closeButton);
// if button is clicked, close the custom dialog
dialogButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dialog.dismiss();
}
});
dialog.show();
}
Here is the error log:
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.gstraatsma.gsfinancetracker, PID: 14493
java.lang.IllegalStateException: Could not execute method for android:onClick
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:390)
at android.view.View.performClick(View.java:6205)
at android.widget.TextView.performClick(TextView.java:11103)
at android.view.View$PerformClick.run(View.java:23653)
at android.os.Handler.handleCallback(Handler.java:751)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6682)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1520)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1410)
Caused by: java.lang.reflect.InvocationTargetException
at java.lang.reflect.Method.invoke(Native Method)
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:385)
at android.view.View.performClick(View.java:6205)
at android.widget.TextView.performClick(TextView.java:11103)
at android.view.View$PerformClick.run(View.java:23653)
at android.os.Handler.handleCallback(Handler.java:751)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6682)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1520)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1410)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Spinner.setAdapter(android.widget.SpinnerAdapter)' on a null object reference
at com.gstraatsma.gsfinancetracker.MainActivity.transferButton(MainActivity.java:1258)
at java.lang.reflect.Method.invoke(Native Method)
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:385)
at android.view.View.performClick(View.java:6205)
at android.widget.TextView.performClick(TextView.java:11103)
at android.view.View$PerformClick.run(View.java:23653)
at android.os.Handler.handleCallback(Handler.java:751)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6682)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1520)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1410)
Change view.findViewById(R.id.fromAccountSpinner); to dialog.findViewById(R.id.fromAccountSpinner);
I'm new to programming and have been assigned to code a simple music player, there were slides to help guide and I have slightly altered them (can't use the exact same variables).
So now it's error free but when I click on the play button it crashes, no idea why. Here's my code for the page where I select the library:
package sg.edu.tp.project1;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import sg.edu.tp.project1.util.AppUtil;
public class myMusic extends AppCompatActivity {
private String[] Musicsong = new String[6];
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my_music);
//store values in array of the first song
Musicsong[0] = "s1001";
Musicsong[1] = "The Way You Look Tonight";
Musicsong[2] = "ed sheeran";
Musicsong[3] = "a5b8972e764025020625bbf9c1c2bbb06e394a60?cid=null";
Musicsong[4] = "4.39";
Musicsong[5] = "music to play";
}
public void sendDataToActiviy(String[] song)
{
//1.create intent and specify destination
Intent intent = new Intent(this, PlayMusicActivity.class);
//2.store song info in intent to send to destination
intent.putExtra("id", song[0]);
intent.putExtra("title",song[1]);
intent.putExtra("artist",song[2]);
intent.putExtra("fileLink",song[3]);
intent.putExtra("coverArt",song[5]);
//3. launch desntination activiy
startActivity(intent);
}
public void handleSelection(View view)
{
// 1. get id of selected song
String resourceId = AppUtil.getResourceId(this, view);
//2. Search for the selected song based on the ID so that
// all infomation of the song can be retreived
String[] selectedSong =searchById(resourceId);
//3.popup to show tittle of song
AppUtil.popMessage(this, "Streaming song:" + selectedSong[1]);
//4. send song data to player screen
sendDataToActiviy(selectedSong);
}
private Object[] songs = {Musicsong};
public String[] searchById(String id) {
//temporary empty array
String[] song = null;
//for loop to get song
for (int index = 0; index < songs.length; index++) {
//3. store each song item to song array.
song = (String[]) songs[index];
//4. match song id to see if its the one i want
if (song[0].equals(id)) {
return song;
}
}
//if song not found in array empty array will be returned
return song;
}
}
This part where the player is:
package sg.edu.tp.project1;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import java.io.IOException;
import sg.edu.tp.project1.util.AppUtil;
public class PlayMusicActivity extends AppCompatActivity
{
//streaming website
private static final String BASE_URL = "https://p.scdn.co/mp3-preview/";
private String songId ="";
private String title = "";
private String artist = "";
private String fileLink = "";
private String coverArt = "";
private String url = "";
//builtin media player
private MediaPlayer player = null;
//position of song in playback
private int musicPosition = 0;
//button variable to link to play btn
private Button btnPlayPause = null;
private String[] Musicsong = {
"s1001",
"The Way You Look Tonight",
"ed sheeran",
"a5b8972e764025020625bbf9c1c2bbb06e394a60?cid=null",
"4.39",
"music to play"};
private Object[] songs = {Musicsong};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_play_music);
btnPlayPause = (Button) findViewById(R.id.btnPlayPause);
retrieveData();
displaySong(title,artist,coverArt);
}
private void retrieveData() {
Bundle songData = this.getIntent().getExtras();
songId = songData.getString("id");
title = songData.getString("title");
artist = songData.getString("artist");
fileLink = songData.getString("fileLink");
coverArt = songData.getString("coverArt");
url = BASE_URL + fileLink;
}
private void displaySong(String title, String artist, String coverArt)
{
//retrieve song title
TextView txtTitle = (TextView) findViewById(R.id.txtSongTitle);
//set text of song title
txtTitle.setText(title);
//retrieve artist
TextView txtArtist = (TextView) findViewById(R.id.txtArtist);
//set text of artist
txtArtist.setText(artist);
//get id of coverart
int imageId = AppUtil.getImageIdFromDrawable(this,coverArt);
//retrieve coverart
ImageView ivCoverArt = (ImageView) findViewById(R.id.imgCoverArt);
ivCoverArt.setImageResource(imageId);
}
public void playOrPauseMusic(View view)
{// start player
player.start();
//2.
btnPlayPause.setText("PAUSE");
//3.set the heading title of played song
setTitle("Now Playing:" + title + "-" + artist);
}
private void preparePlayer() { //create a new player
player = new MediaPlayer();
try {
//set stream type to music
player.setAudioStreamType(AudioManager.STREAM_MUSIC);
//set source of music
player.setDataSource(url);
//prepare player for playback
player.prepare();
} catch (IOException e) {
e.printStackTrace();
}
}}
Logs:
08-10 16:04:02.478 2567-2567/sg.edu.tp.project1 I/art: Not late-enabling -Xcheck:jni (already on)
08-10 16:04:02.478 2567-2567/sg.edu.tp.project1 W/art: Unexpected CPU variant for X86 using defaults: x86
08-10 16:04:02.535 2567-2567/sg.edu.tp.project1 W/System: ClassLoader referenced unknown path: /data/app/sg.edu.tp.project1-2/lib/x86
08-10 16:04:02.539 2567-2567/sg.edu.tp.project1 I/InstantRun: Starting Instant Run Server for sg.edu.tp.project1
08-10 16:04:02.913 2567-2567/sg.edu.tp.project1 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
08-10 16:04:03.399 2567-2632/sg.edu.tp.project1 I/OpenGLRenderer: Initialized EGL, version 1.4
08-10 16:04:03.400 2567-2632/sg.edu.tp.project1 D/OpenGLRenderer: Swap behavior 1
08-10 16:04:03.400 2567-2632/sg.edu.tp.project1 W/OpenGLRenderer: Failed to choose config with EGL_SWAP_BEHAVIOR_PRESERVED, retrying without...
08-10 16:04:03.400 2567-2632/sg.edu.tp.project1 D/OpenGLRenderer: Swap behavior 0
08-10 16:04:03.490 2567-2567/sg.edu.tp.project1 W/art: Before Android 4.1, method int android.support.v7.widget.ListViewCompat.lookForSelectablePosition(int, boolean) would have incorrectly overridden the package-private method in android.widget.ListView
08-10 16:04:14.759 2567-2632/sg.edu.tp.project1 D/OpenGLRenderer: endAllActiveAnimators on 0x8d2e9b00 (RippleDrawable) with handle 0x8d2ff830
08-10 16:04:27.207 2567-2570/sg.edu.tp.project1 I/art: Do partial code cache collection, code=29KB, data=27KB
08-10 16:04:27.207 2567-2570/sg.edu.tp.project1 I/art: After code cache collection, code=29KB, data=27KB
08-10 16:04:27.207 2567-2570/sg.edu.tp.project1 I/art: Increasing code cache capacity to 128KB
08-10 16:04:27.463 2567-2632/sg.edu.tp.project1 D/OpenGLRenderer: endAllActiveAnimators on 0x8c313a00 (RippleDrawable) with handle 0x8d2ff420
08-10 16:04:29.695 2567-2567/sg.edu.tp.project1 D/AndroidRuntime: Shutting down VM
Beginning of crash:
08-10 16:04:29.696 2567-2567/sg.edu.tp.project1 E/AndroidRuntime: FATAL EXCEPTION: main
Process: sg.edu.tp.project1, PID: 2567
java.lang.IllegalStateException: Could not execute method for android:onClick
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:293)
at android.view.View.performClick(View.java:5637)
at android.view.View$PerformClick.run(View.java:22429)
at android.os.Handler.handleCallback(Handler.java:751)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6119)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
Caused by: java.lang.reflect.InvocationTargetException
at java.lang.reflect.Method.invoke(Native Method)
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:288)
at android.view.View.performClick(View.java:5637)
at android.view.View$PerformClick.run(View.java:22429)
at android.os.Handler.handleCallback(Handler.java:751)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6119)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.media.MediaPlayer.start()' on a null object reference
at sg.edu.tp.project1.PlayMusicActivity.playOrPauseMusic(PlayMusicActivity.java:106)
at java.lang.reflect.Method.invoke(Native Method)
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:288)
at android.view.View.performClick(View.java:5637)
at android.view.View$PerformClick.run(View.java:22429)
at android.os.Handler.handleCallback(Handler.java:751)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6119)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
The exception message is very clear:
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.media.MediaPlayer.start()' on a null object reference
at sg.edu.tp.project1.PlayMusicActivity.playOrPauseMusic(PlayMusicActivity.java:106)
So your player field is null because you've never called PlayMusicActivity's preparePlayer() before.
I'm begginer in Android programming, I'm trying to make the login function. This system will be accessed by two users which are admin and users. The admin just need to enter the "admin" for the username and password to access the system. However, the users needs to register their account before login the system.
I'm trying to find the errors but still don't know the error occurrence. Please help me to solve the errors. Thank You.
DatabaseOperations.java
public Cursor getInformation(DatabaseOperations dob)
{
SQLiteDatabase database=dob.getReadableDatabase();
String[] columns={TableInfo.USERNAME,TableInfo.USERPASS};
Cursor cr=database.query(TableInfo.TABLE_NAME,columns,null,null,null,null,null);
return cr;
}
MainActivity.java
public void onClick(View view)
Toast.makeText(getBaseContext(), "Please wait....", Toast.LENGTH_LONG).show();
txtusername = Username.getText().toString();
txtpassword = Password.getText().toString();
DatabaseOperations dop = new DatabaseOperations(this, null, null, 1);
Cursor CR = dop.getInformation(dop);
CR.moveToFirst();
boolean login_status = false;
String NAME = "";
if (txtusername.equals("Admin") && (txtpassword).equals("Admin")) {
Intent in = new Intent(MainActivity.this, AdminMenu.class);
startActivity(in);
} else {
do {
if (txtusername.equals(CR.getString(0)) && (txtpassword.equals(CR.getString(1)))) {
login_status = true;
NAME = CR.getString(0);
}
} while (CR.moveToNext());
if (login_status) {
Toast.makeText(getBaseContext(), "Login Success....\n Welcome " + NAME, Toast.LENGTH_LONG).show();
Intent i=new Intent(MainActivity.this,UserMenu.class);
Bundle bundle=new Bundle();
bundle.putString("username",NAME);
i.putExtras(bundle);
startActivity(i);
finish();
} else {
Toast.makeText(getBaseContext(), "Login Failed...", Toast.LENGTH_LONG).show();
Intent i = new Intent();
Bundle bundle=new Bundle();
bundle.putString("username",NAME);
i.putExtras(bundle);
startActivity(i);
finish();
}
}
}
This is the error...
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.google.mobile_flexi_parking, PID: 6777
java.lang.IllegalStateException: Could not execute method for android:onClick
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:293)
at android.view.View.performClick(View.java:5198)
at android.view.View$PerformClick.run(View.java:21147)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
Caused by: java.lang.reflect.InvocationTargetException
at java.lang.reflect.Method.invoke(Native Method)
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:288)
at android.view.View.performClick(View.java:5198)
at android.view.View$PerformClick.run(View.java:21147)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
Caused by: android.content.ActivityNotFoundException: No Activity found to handle Intent { (has extras) }
at android.app.Instrumentation.checkStartActivityResult(Instrumentation.java:1798)
at android.app.Instrumentation.execStartActivity(Instrumentation.java:1512)
at android.app.Activity.startActivityForResult(Activity.java:3917)
at android.app.Activity.startActivityForResult(Activity.java:3877)
at android.support.v4.app.FragmentActivity.startActivityForResult(FragmentActivity.java:842)
at android.app.Activity.startActivity(Activity.java:4200)
at android.app.Activity.startActivity(Activity.java:4168)
at com.google.mobile_flexi_parking.MainActivity.onclickLogin(MainActivity.java:67)
at java.lang.reflect.Method.invoke(Native Method)
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:288)
at android.view.View.performClick(View.java:5198)
at android.view.View$PerformClick.run(View.java:21147)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
In your else part you have blank intent which doesn't point any activity
Intent i = new Intent();
I think this is causing error.
I have one database but I want to make 2 tables for separate classes. One for saving new user data and one for saving user's sessions. The one I am trying to get to work is the table consisted of the Session Title, Time, Active. The table for User Username, First, Last works but the one for the session doesn't. Ultimately, I want to put 2 tables in one database/java class which is the "ListBaseHelper". Where did I go wrong?
Here is the Java Class with the database and tables:
public class ListBaseHelper extends SQLiteOpenHelper {
private static final String DATABASE_NAME = "listBase.db";
private static final int DATABASE_VERSION = 2;
//Define a query for creating table so you don't get lost
private static final String CREATE_QUERY =
"CREATE TABLE " + ListTable.TABLE_NAME + "(" + ListDbSchema.ListTable.USERNAME + " TEXT," +
ListDbSchema.ListTable.FIRST + " TEXT," + ListDbSchema.ListTable.LAST + " TEXT);";
private static final String CREATE_QUERY2 =
"CREATE TABLE " + ListTable.TABLE_NAME2 + "(" + ListDbSchema.ListTable.TITLE + " TEXT," +
ListDbSchema.ListTable.TIME + " TEXT," + ListDbSchema.ListTable.ACTIVE + " TEXT);";
public ListBaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
//Log message
Log.e("DATABASE OPERATIONS", "Database created /opened...");
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(CREATE_QUERY);
Log.e("DATABASE OPERATIONS", "Table created...");
db.execSQL(CREATE_QUERY2);
Log.e("DATABASE OPERATIONS", "Table created...");
}
public void addInformations(String username, String first, String last, SQLiteDatabase db) {
ContentValues contentValues = new ContentValues();
contentValues.put(ListTable.USERNAME, username);
contentValues.put(ListTable.FIRST, first);
contentValues.put(ListTable.LAST, last);
db.insert(ListDbSchema.ListTable.TABLE_NAME, null, contentValues);
Log.e("DATABASE OPERATIONS", "One row inserted...");
}
public void addSessionInfo(String title, String time, String active, SQLiteDatabase db) {
ContentValues contentValues = new ContentValues();
contentValues.put(ListTable.TITLE, title);
contentValues.put(ListTable.TIME, time);
contentValues.put(ListTable.ACTIVE, active);
db.insert(ListDbSchema.ListTable.TABLE_NAME2, null, contentValues);
Log.e("DATABASE OPERATIONS", "One row inserted...");
}
public Cursor getInformations(SQLiteDatabase db) {
Cursor cursor;
String[] projections = {ListTable.USERNAME, ListTable.FIRST, ListTable.LAST};
cursor = db.query(ListDbSchema.ListTable.TABLE_NAME, projections, null, null, null, null, null);
return cursor;
}
public Cursor SessionInformations(SQLiteDatabase db) {
Cursor cursor2;
String[] projections = {ListTable.TITLE, ListTable.TIME, ListTable.ACTIVE};
cursor2 = db.query(ListDbSchema.ListTable.TABLE_NAME2, projections, null, null, null, null, null);
return cursor2;
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS contacts");
onCreate(db);
}
}
When this java class runs, it will ask user for input.
public class NewSessionActivity extends AppCompatActivity {
EditText SessionTitle, SessionTime, SessionActive;
Context context = this;
ListBaseHelper sessionbasehelper;
SQLiteDatabase sqliteDatabase;
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main_options_menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.logoff_menu_item) {
super.onOptionsItemSelected(item);
Toast.makeText(this, "Logging You Off...", Toast.LENGTH_LONG).show();
startActivity(new Intent(NewSessionActivity.this, LaunchActivity.class));
}
return true;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_new_session);
SessionTitle = (EditText) findViewById(R.id.title);
SessionTime = (EditText) findViewById(R.id.time);
SessionActive = (EditText) findViewById(R.id.active);
}
public void btn_submit(View view) {
{
context = this;
String title = SessionTitle.getText().toString();
String time = SessionTime.getText().toString();
String active = SessionActive.getText().toString();
sessionbasehelper= new ListBaseHelper(context);
sqliteDatabase = sessionbasehelper.getWritableDatabase();
sessionbasehelper.addSessionInfo(title,time,active,sqliteDatabase);
Toast.makeText(getBaseContext(), "New Session Saved!", Toast.LENGTH_LONG).show();
Intent intent = new Intent(NewSessionActivity.this, ViewAllSessionsActivity.class);
startActivity(intent);
sessionbasehelper.close();
}
}
}
When java class runs, it's supposed to show the data the user entered from NewSessionActivity above.
public class ViewAllSessionsActivity extends AppCompatActivity{
//Create instance of database
ListBaseHelper myDb;
Button btn_logout;
ListView sessionlistView;
SQLiteDatabase sqLiteDatabase;
ListBaseHelper listbaseDbHelper;
Cursor cursor2;
SessionDataAdapter sessionDataAdapter;
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main_options_menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.logoff_menu_item) {
super.onOptionsItemSelected(item);
Toast.makeText(this, "Logging You Off...", Toast.LENGTH_LONG).show();
startActivity(new Intent(ViewAllSessionsActivity.this, LaunchActivity.class));
}
return true;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view_all_sessions);
sessionlistView = (ListView) findViewById(R.id.listViewSession);
sessionDataAdapter = new SessionDataAdapter(getApplicationContext(),R.layout.all_session_layout);
sessionlistView.setAdapter(sessionDataAdapter);
listbaseDbHelper = new ListBaseHelper(getApplicationContext());
sqLiteDatabase = listbaseDbHelper.getReadableDatabase();
cursor2 = listbaseDbHelper.SessionInformations(sqLiteDatabase);
if(cursor2.moveToFirst())
{
do {
String title, time, active;
title = cursor2.getString(0);
time = cursor2.getString(1);
active = cursor2.getString(2);
SessionList sessionlist = new SessionList(title, time, active);
sessionDataAdapter.add(sessionlist);
}while (cursor2.moveToNext());
}
btn_logout = (Button)findViewById(R.id.complete_button);
btn_logout.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
//Use the name of this class, and the name class where you want to be taken when the button is clicked.
Intent intent = new Intent(ViewAllSessionsActivity.this, PaymentActivity.class);
startActivity(intent);
}
});
}
}
This is the LogCat when I run my app:
09-26 10:54:06.071 2712-2712/com.bignerdranch.android.assignment2 E/DATABASE OPERATIONS: Database created /opened...
09-26 10:54:24.365 2712-2712/com.bignerdranch.android.assignment2 E/DATABASE OPERATIONS: Database created /opened...
09-26 10:54:24.368 2712-2712/com.bignerdranch.android.assignment2 E/SQLiteLog: (1) no such table: table_name2
09-26 10:54:24.369 2712-2712/com.bignerdranch.android.assignment2 E/SQLiteDatabase: Error inserting title=Hi time=10:22 active=yes
android.database.sqlite.SQLiteException: no such table: table_name2 (code 1): , while compiling: INSERT INTO table_name2(title,time,active) VALUES (?,?,?)
at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method)
at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:889)
at android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:500)
at android.database.sqlite.SQLiteSession.prepare(SQLiteSession.java:588)
at android.database.sqlite.SQLiteProgram.<init>(SQLiteProgram.java:58)
at android.database.sqlite.SQLiteStatement.<init>(SQLiteStatement.java:31)
at android.database.sqlite.SQLiteDatabase.insertWithOnConflict(SQLiteDatabase.java:1469)
at android.database.sqlite.SQLiteDatabase.insert(SQLiteDatabase.java:1341)
at com.bignerdranch.android.assignment2.database.ListBaseHelper.addSessionInfo(ListBaseHelper.java:65)
at com.bignerdranch.android.assignment2.NewSessionActivity.btn_submit(NewSessionActivity.java:62)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:288)
at android.view.View.performClick(View.java:4780)
at android.view.View$PerformClick.run(View.java:19866)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5254)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
09-26 10:54:24.370 2712-2712/com.bignerdranch.android.assignment2 E/DATABASE OPERATIONS: One row inserted...
09-26 10:54:24.919 2712-2712/com.bignerdranch.android.assignment2 E/DATABASE OPERATIONS: Database created /opened...
09-26 10:54:24.941 2712-2712/com.bignerdranch.android.assignment2 E/SQLiteLog: (1) no such table: table_name2
09-26 10:54:24.951 2712-2712/com.bignerdranch.android.assignment2 E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.bignerdranch.android.assignment2, PID: 2712
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.bignerdranch.android.assignment2/com.bignerdranch.android.assignment2.ViewAllSessionsActivity}: android.database.sqlite.SQLiteException: no such table: table_name2 (code 1): , while compiling: SELECT title, time, active FROM table_name2
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2325)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2387)
at android.app.ActivityThread.access$800(ActivityThread.java:151)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5254)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
Caused by: android.database.sqlite.SQLiteException: no such table: table_name2 (code 1): , while compiling: SELECT title, time, active FROM table_name2
at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method)
at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:889)
at android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:500)
at android.database.sqlite.SQLiteSession.prepare(SQLiteSession.java:588)
at android.database.sqlite.SQLiteProgram.<init>(SQLiteProgram.java:58)
at android.database.sqlite.SQLiteQuery.<init>(SQLiteQuery.java:37)
at android.database.sqlite.SQLiteDirectCursorDriver.query(SQLiteDirectCursorDriver.java:44)
at android.database.sqlite.SQLiteDatabase.rawQueryWithFactory(SQLiteDatabase.java:1316)
at android.database.sqlite.SQLiteDatabase.queryWithFactory(SQLiteDatabase.java:1163)
at android.database.sqlite.SQLiteDatabase.query(SQLiteDatabase.java:1034)
at android.database.sqlite.SQLiteDatabase.query(SQLiteDatabase.java:1202)
at com.bignerdranch.android.assignment2.database.ListBaseHelper.SessionInformations(ListBaseHelper.java:82)
at com.bignerdranch.android.assignment2.ViewAllSessionsActivity.onCreate(ViewAllSessionsActivity.java:60)
at android.app.Activity.performCreate(Activity.java:5990)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1106)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2278)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2387)
at android.app.ActivityThread.access$800(ActivityThread.java:151)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5254)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
09-26 10:54:38.877 3535-3535/com.bignerdranch.android.assignment2 E/DATABASE OPERATIONS: Database created /opened...
09-26 10:54:38.892 3535-3535/com.bignerdranch.android.assignment2 E/SQLiteLog: (1) no such table: table_name2
09-26 10:54:38.893 3535-3535/com.bignerdranch.android.assignment2 E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.bignerdranch.android.assignment2, PID: 3535
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.bignerdranch.android.assignment2/com.bignerdranch.android.assignment2.ViewAllSessionsActivity}: android.database.sqlite.SQLiteException: no such table: table_name2 (code 1): , while compiling: SELECT title, time, active FROM table_name2
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2325)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2387)
at android.app.ActivityThread.access$800(ActivityThread.java:151)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5254)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
Caused by: android.database.sqlite.SQLiteException: no such table: table_name2 (code 1): , while compiling: SELECT title, time, active FROM table_name2
at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method)
at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:889)
at android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:500)
at android.database.sqlite.SQLiteSession.prepare(SQLiteSession.java:588)
at android.database.sqlite.SQLiteProgram.<init>(SQLiteProgram.java:58)
at android.database.sqlite.SQLiteQuery.<init>(SQLiteQuery.java:37)
at android.database.sqlite.SQLiteDirectCursorDriver.query(SQLiteDirectCursorDriver.java:44)
at android.database.sqlite.SQLiteDatabase.rawQueryWithFactory(SQLiteDatabase.java:1316)
at android.database.sqlite.SQLiteDatabase.queryWithFactory(SQLiteDatabase.java:1163)
at android.database.sqlite.SQLiteDatabase.query(SQLiteDatabase.java:1034)
at android.database.sqlite.SQLiteDatabase.query(SQLiteDatabase.java:1202)
at com.bignerdranch.android.assignment2.database.ListBaseHelper.SessionInformations(ListBaseHelper.java:82)
at com.bignerdranch.android.assignment2.ViewAllSessionsActivity.onCreate(ViewAllSessionsActivity.java:60)
at android.app.Activity.performCreate(Activity.java:5990)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1106)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2278)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2387)
at android.app.ActivityThread.access$800(ActivityThread.java:151)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5254)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
I am a beginner and i am trying to learn how to use APIs on android. I am doing a bitcoin price app to learn APIs. But i have a few problems.I created a progressbar and a price TextView in mainactivity.xml . I set progressbar visible and textview invisible by default.My thought is very simple, i created a new AsyncTask class and after background things are done , i will set the progressbar invisible and the textview visible in the onPostExecute() to show price. But it didn't work. The progressbar keeps spinning, it doesn't show the price i dont understand why it doesn't work.
The API i am using
MainActivity
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.TextView;
import org.json.JSONObject;
import org.json.JSONTokener;
import java.net.URL;
import java.net.HttpURLConnection;
import java.io.InputStreamReader;
import java.io.BufferedReader;
public class MainActivity extends AppCompatActivity {
public static String line;
public static ProgressBar progressBar;
static String API_URL="https://api.coindesk.com/v1/bpi/currentprice/try.json";
static TextView priceTextView;
static TextView timeTextView;
static int priceInt;
#Override
protected void onCreate( Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
priceTextView=(TextView)findViewById(R.id.priceText);
timeTextView=(TextView)findViewById(R.id.timeText);
progressBar=(ProgressBar)findViewById(R.id.progressBar);
retrievePriceTask retrievePriceTask=new retrievePriceTask();
retrievePriceTask.execute();
}
}
class retrievePriceTask extends AsyncTask <Void,Void,String>{
#Override
protected void onPreExecute() {
MainActivity.progressBar.setVisibility(View.VISIBLE);
MainActivity.priceTextView.setVisibility(View.INVISIBLE);
}
#Override
protected String doInBackground(Void... urls) {
try {
URL url = new URL(MainActivity.API_URL);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
try {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
StringBuilder stringBuilder = new StringBuilder();
while ((MainActivity.line = bufferedReader.readLine()) != null) {
stringBuilder.append(MainActivity.line).append("\n");
}
bufferedReader.close();
return stringBuilder.toString();
}
finally{
urlConnection.disconnect();
}
}
catch(Exception e) {
Log.e("ERROR", e.getMessage(), e);
return null;
}
}
#Override
protected void onPostExecute(String s) {
MainActivity.priceTextView.setVisibility(View.VISIBLE);
MainActivity.progressBar.setVisibility(View.INVISIBLE);
try{
JSONObject jsonObject=(JSONObject)new JSONTokener(MainActivity.line).nextValue();
MainActivity.priceInt=jsonObject.getJSONObject("bpi").getJSONObject("TRY").getInt("rate");
MainActivity.priceTextView.setText(MainActivity.priceInt);
}
catch (Exception e){
e.printStackTrace();
}
}
}
My Logcat
07-16 10:20:08.884 2269-2269/zaaa.trinki E/AndroidRuntime: FATAL EXCEPTION: main
Process: zaaa.trinki, PID: 2269
java.lang.RuntimeException: Unable to start activity ComponentInfo{zaaa.trinki/zaaa.trinki.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ProgressBar.setVisibility(int)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2298)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2360)
at android.app.ActivityThread.access$800(ActivityThread.java:144)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1278)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5221)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ProgressBar.setVisibility(int)' on a null object reference
at zaaa.trinki.retrievePriceTask.onPreExecute(MainActivity.java:94)
at android.os.AsyncTask.executeOnExecutor(AsyncTask.java:587)
at android.os.AsyncTask.execute(AsyncTask.java:535)
at zaaa.trinki.MainActivity.onCreate(MainActivity.java:55)
at android.app.Activity.performCreate(Activity.java:5933)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1105)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2251)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2360)
at android.app.ActivityThread.access$800(ActivityThread.java:144)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1278)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5221)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
07-16 10:37:42.062 16262-16262/zaaa.trinki E/AndroidRuntime: FATAL EXCEPTION: main
Process: zaaa.trinki, PID: 16262
java.lang.RuntimeException: Unable to start activity ComponentInfo{zaaa.trinki/zaaa.trinki.MainActivity}: android.content.res.Resources$NotFoundException: String resource ID #0x0
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2298)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2360)
at android.app.ActivityThread.access$800(ActivityThread.java:144)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1278)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5221)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
Caused by: android.content.res.Resources$NotFoundException: String resource ID #0x0
at android.content.res.Resources.getText(Resources.java:274)
at android.support.v7.widget.ResourcesWrapper.getText(ResourcesWrapper.java:52)
at android.widget.TextView.setText(TextView.java:4122)
at zaaa.trinki.MainActivity.onCreate(MainActivity.java:63)
at android.app.Activity.performCreate(Activity.java:5933)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1105)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2251)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2360)
at android.app.ActivityThread.access$800(ActivityThread.java:144)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1278)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5221)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
Use a ProgressDialog instead of a ProgressBar:
ProgressDialog myProgressDialog = ProgressDialog.show(Context CONTEXT, String TITLE, String MESSAGE, boolean INDETERMINATE, boolean CANCELABLE);
myProgressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
and in your onPostExecute() just put myProgressDialog.dismiss()