Insert/show/load in json crashed - java

First of all: 1. When i insert empty data into sql it crashed 2. When load json crashed 3. Pressing with empty data show records crashed Please help!
Here is MainActivity:
package com.example.user.notebook;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.ArrayList;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;
import com.example.user.notebook.Students;
public class MainActivity extends Activity {
LinearLayout mainLayout=null;
EditText lessons=null,student=null,grade=null,observations=null;
Button insertRecord=null,showRecords=null;
ArrayList<Students> result= new ArrayList<>();
TableLayout resultLayout=null;
Database db=null;
LinearLayout jsonLayout=null;
Button loadJSON=null,saveJSON=null;
public void makeJSON()
{
jsonLayout=new LinearLayout(this);
mainLayout.addView(jsonLayout);
loadJSON=new Button(this);
loadJSON.setText("LOAD JSON");
jsonLayout.addView(loadJSON);
loadJSON.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v) {
AlertDialog.Builder alert = new
AlertDialog.Builder(MainActivity.this);
alert.setTitle("Load FILE");
alert.setMessage("Specify file name: ");
final EditText input = new EditText(MainActivity.this);
alert.setView(input);
alert.setPositiveButton("Ok",
new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int whichButton)
{
String value = input.getText().toString();
File myfile=new File(
Environment.getExternalStorageDirectory(),value);
try {
BufferedReader br = new BufferedReader(
new InputStreamReader(new
FileInputStream(myfile), "utf8"),65536);
String line="";
line=br.readLine();
try {
JSONArray x=new JSONArray(line);
Log.d("TEST","I have read "+x);
int i;
for(i=0;i<x.length();i++)
{
JSONObject p=x.getJSONObject(i);
String lessons=p.getString("lessons");
String student=p.getString("student");
String observations=p.getString("observations");
double grade =p.getDouble("grade");
db.insert(lessons, student, observations, grade);
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
br.close();
}catch(IOException e)
{
Log.d("TEST",e.getMessage());
}
}});
alert.setNegativeButton("Cancel", new
DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton)
{
}
});
alert.show();
}
});
saveJSON=new Button(this);
saveJSON.setText("SAVE JSON");
saveJSON.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v) {
result=db.getResults();
final JSONArray x=new JSONArray();
int i;
for(i=0;i<result.size();i++)
{
JSONObject p=new JSONObject();
try {
p.put("lessons", result.get(i).lessons);
p.put("student",result.get(i).student);
p.put("observations", result.get(i).observations);
p.put("grade", result.get(i).grade);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
x.put(p);
}
String s=x.toString();
AlertDialog.Builder alert = new
AlertDialog.Builder(MainActivity.this);
alert.setTitle("Create FILE");
alert.setMessage("Specify file name: ");
final EditText input = new EditText(MainActivity.this);
alert.setView(input);
alert.setPositiveButton("Ok",
new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int whichButton)
{
String value = input.getText().toString();
File myfile=new File(
Environment.getExternalStorageDirectory(),value);
try {
Writer out = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream(myfile), "UTF8"));
out.append(x.toString());
out.flush();
out.close();
Log.d("TEST", "Write "+x);
}catch(IOException e)
{
Log.d("TEST",e.getMessage());
}
}});
alert.setNegativeButton("Cancel", new
DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton)
{
}
});
alert.show();
}
});
jsonLayout.addView(saveJSON);
}
public void makeInputs()
{
LinearLayout l1=new LinearLayout(this);
mainLayout.addView(l1);
lessons=new EditText(this);
lessons.setHint("lessons");
l1.addView(lessons);
student=new EditText(this);
student.setHint("student");
l1.addView(student);
observations=new EditText(this);
observations.setHint("observations");
l1.addView(observations);
grade=new EditText(this);
l1.addView(grade);
grade.setHint("grade");
}
public void makeButtons()
{
LinearLayout l2=new LinearLayout(this);
mainLayout.addView(l2);
insertRecord=new Button(this);
insertRecord.setText("INSERT RECORD");
l2.addView(insertRecord);
showRecords=new Button(this);
showRecords.setText("SHOW RECORDS");
l2.addView(showRecords);
insertRecord.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v) {
db.insert(lessons.getText().toString(),
student.getText().toString(),
observations.getText().toString(),
Double.parseDouble(grade.getText().toString()));
}
});
showRecords.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v) {
result=db.getResults();
updateTable();
}
});
}
public void makeTable()
{
resultLayout=new TableLayout(this);
ScrollView scroll=new ScrollView(this);
mainLayout.addView(scroll);
scroll.addView(resultLayout);
TableRow r1=new TableRow(this);
resultLayout.addView(r1);
}
public void updateTable()
{
resultLayout.removeAllViews();
makeTable();
int i;
for(i=0;i<result.size();i++)
{
Students c=result.get(i);
TableRow r=new TableRow(this);
resultLayout.addView(r);
TextView t1,t2,t3,t4;
t1=new TextView(this);
t1.setText(c.lessons);
t2=new TextView(this);
t2.setText(c.student);
t3=new TextView(this);
t3.setText(c.observations);
t4=new TextView(this);
t4.setText(""+c.grade);
r.addView(t1);
r.addView(t2);
r.addView(t3);
r.addView(t4);
ImageView delimage=new ImageView(this);
r.addView(delimage);
delimage.setId(i);
delimage.setImageResource(R.drawable.remove);
delimage.setClickable(true);
delimage.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v) {
String cardetails="lessons: "+
result.get(v.getId()).lessons+
" lessons: "+
result.get(v.getId()).student+
" student: "+
result.get(v.getId()).observations+
"observations: "+
result.get(v.getId()).grade+
" grade: ";
Log.d("TEST","Delete school is "+cardetails);
}
});
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mainLayout=new LinearLayout(this);
setContentView(mainLayout);
mainLayout.setOrientation(LinearLayout.VERTICAL);
db=new Database(this, "school.db", null, 2);
makeInputs();
makeButtons();
makeJSON();
makeTable();
}
}
Database
package com.example.user.notebook;
import java.util.ArrayList;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;
public class Database extends SQLiteOpenHelper{
private Context mcontext;
private SQLiteDatabase database;
public Database(Context context, String name, CursorFactory factory,
int version) {
super(context, name, null, version);
mcontext=context;
database=this.getWritableDatabase();
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("create table school(lessons text,student text,observations text,grade double)");
}
public ArrayList<Students> getResults()
{
ArrayList<Students> x= new ArrayList<Students>();
Cursor cursor=database.rawQuery("select * from school",null);
if(cursor.getCount()==0)
{
cursor.close();
return x;
}
int lessonsindex=cursor.getColumnIndex("lessons");
int studentindex=cursor.getColumnIndex("student");
int observationsindex=cursor.getColumnIndex("observations");
int gradeindex=cursor.getColumnIndex("grade");
cursor.moveToFirst();
do
{
Students c;
c=new Students(cursor.getString(lessonsindex),
cursor.getString(studentindex),
cursor.getString(observationsindex),
cursor.getDouble(gradeindex));
x.add(c);
}while(cursor.moveToNext());
cursor.close();
return null;
}
public void delete(String lessons,String student, String observations, double grade)
{
database.execSQL("delete from school where lessons='"+lessons+"' and student='"+
student+"'and observations='"+observations+"' and grade = '"+grade);
}
public void insert(String lessons,String student, String observations, double grade)
{
database.execSQL("insert into school(lessons,student,observations,grade) values('"+
lessons+"','"+student+"','"+observations+"','"+grade+"')");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("drop table school");
onCreate(db);
}
public void clearData()
{
database.execSQL("delete from school");
}
}
LogCat:
01-24 22:10:49.962 2421-2421/? E/Zygote: v2
01-24 22:10:49.972 2421-2421/? E/SELinux: [DEBUG] get_category: variable seinfo: default sensitivity: NULL, cateogry: NULL
01-24 22:14:42.292 2421-2421/com.example.user.notebook E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.user.notebook, PID: 2421
java.lang.NullPointerException: Attempt to invoke virtual method 'int java.util.ArrayList.size()' on a null object reference
at com.example.user.notebook.MainActivity.updateTable(MainActivity.java:257)
at com.example.user.notebook.MainActivity$4.onClick(MainActivity.java:235)
at android.view.View.performClick(View.java:4808)
at android.view.View$PerformClick.run(View.java:19918)
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:5608)
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:1397)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1192)
also
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.user.notebook, PID: 4373
java.lang.NumberFormatException: Invalid double: ""
at java.lang.StringToReal.invalidReal(StringToReal.java:63)
at java.lang.StringToReal.parseDouble(StringToReal.java:267)
at java.lang.Double.parseDouble(Double.java:301)
at com.example.user.notebook.MainActivity$3.onClick(MainActivity.java:230)
at android.view.View.performClick(View.java:4808)
at android.view.View$PerformClick.run(View.java:19918)
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:5608)
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:1397)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1192)

Youre trying to go through results.size() which is null. Follow your code.
.....
result=db.getResults();
final JSONArray x=new JSONArray();
int i;
for(i=0;i<result.size();i++)
....
This will go into the db.getResults.
public ArrayList<Students> getResults()
{
ArrayList<Students> x= new ArrayList<Students>();
Cursor cursor=database.rawQuery("select * from school",null);
if(cursor.getCount()==0)
{
cursor.close();
return x;
}
int lessonsindex=cursor.getColumnIndex("lessons");
int studentindex=cursor.getColumnIndex("student");
int observationsindex=cursor.getColumnIndex("observations");
int gradeindex=cursor.getColumnIndex("grade");
cursor.moveToFirst();
do
{
Students c;
c=new Students(cursor.getString(lessonsindex),
cursor.getString(studentindex),
cursor.getString(observationsindex),
cursor.getDouble(gradeindex));
x.add(c);
}while(cursor.moveToNext());
cursor.close();
return null;
}
If you look at this method...you are returning x, but x is null. You are not adding anything to X. Then... you return null at the end.... this is where your issue is.
PS: please use better names for your variables.
ArrayList<Students> x= new ArrayList<Students>();
could be a lot better and easier to understand if it was something like....
ArrayList<Students> studentsResults = new ArrayList<Students>();
Now obviously you don't have to do it, but it makes more easier to read code...and its cleaner...way cleaner

You have two issues, the first masking the second which was more obvious and hence the initial attempts to fix that which resulted in nothing working.
The first issue is that you were getting the result array in the onCLick and then calling the updateTable() method, in which the result array retrieved was not in the scope of the updateTable method. So moving result=db.getResults(); onto the updateTable method, resolved that issue.
The second issue was that the getResults would, if any rows were extracted, return null.
So to fix the issues and also condense the code, instead of (to fix issue 2):-
public ArrayList<Students> getResults()
{
ArrayList<Students> x= new ArrayList<Students>();
Cursor cursor=database.rawQuery("select * from school",null);
if(cursor.getCount()==0)
{
cursor.close();
return x;
}
int lessonsindex=cursor.getColumnIndex("lessons");
int studentindex=cursor.getColumnIndex("student");
int observationsindex=cursor.getColumnIndex("observations");
int gradeindex=cursor.getColumnIndex("grade");
cursor.moveToFirst();
do
{
Students c;
c=new Students(cursor.getString(lessonsindex),
cursor.getString(studentindex),
cursor.getString(observationsindex),
cursor.getDouble(gradeindex));
x.add(c);
}while(cursor.moveToNext());
cursor.close();
return null;
}
It could instead be :-
public ArrayList<Students> getResults()
{
ArrayList<Students> x= new ArrayList<Students>();
Cursor cursor=database.rawQuery("select * from school",null);
while (cursor.moveToNext()) {
x.add(new Students(
cursor.getString(cursor.getColumnIndex("lessons")),
cursor.getString(cursor.getColumnIndex("student")),
cursor.getString(cursor.getColumnIndex("observations")),
cursor.getDouble(cursor.getColumnIndex("grade"))
));
}
cursor.close();
return x;
}
Additionally, to fix (1) in the updateTable method add result=db.getResults(); e.g.
public void updateTable()
{
result=db.getResults(); //<<<< ADDED
resultLayout.removeAllViews();
makeTable();
int i;
for(i=0;i<result.size();i++)
{
Remove the now unecessary result=db.getResults(); from the showRecords.setOnClickListener's onClick method.
This both condenses the code and also will not return a null but rather an ArrayList that is either populated or has a size of 0.
Thus circumventing the java.lang.NullPointerException: Attempt to invoke virtual method 'int java.util.ArrayList.size()' on a null object reference

Related

Error inflating class androidx.leanback.widget.BrowseFrameLayout

I'm testing the new support library leanback to design apps for TV, and i have a error ever android try to inflate the BrowseFragment and it throws this exception and don't know how to solve it. Thank you so much for your help.
Error -
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.directsportsnetwork.tv/com.directsportsnetwork.tv.ui.TeamSclActivity}: android.view.InflateException: Binary XML file line #67 in com.directsportsnetwork.tv:layout/activity_teamscl: Binary XML file line #24 in com.directsportsnetwork.tv:layout/lb_browse_fragment: Binary XML file line #24 in com.directsportsnetwork.tv:layout/lb_browse_fragment: Error inflating class androidx.leanback.widget.BrowseFrameLayout
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3449)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3601)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:85)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2066)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:223)
at android.app.ActivityThread.main(ActivityThread.java:7656)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947)
Caused by: android.view.InflateException: Binary XML file line #67 in com.directsportsnetwork.tv:layout/activity_teamscl: Binary XML file line #24 in com.directsportsnetwork.tv:layout/lb_browse_fragment: Binary XML file line #24 in com.directsportsnetwork.tv:layout/lb_browse_fragment: Error inflating class androidx.leanback.widget.BrowseFrameLayout
Caused by: android.view.InflateException: Binary XML file line #24 in com.directsportsnetwork.tv:layout/lb_browse_fragment: Binary XML file line #24 in com.directsportsnetwork.tv:layout/lb_browse_fragment: Error inflating class androidx.leanback.widget.BrowseFrameLayout
Caused by: android.view.InflateException: Binary XML file line #24 in com.directsportsnetwork.tv:layout/lb_browse_fragment: Error inflating class androidx.leanback.widget.BrowseFrameLayout
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.Object java.lang.reflect.Field.get(java.lang.Object)' on a null object reference
at uk.co.chrisjenx.calligraphy.ReflectionUtils.getValue(ReflectionUtils.java:29)
at uk.co.chrisjenx.calligraphy.CalligraphyLayoutInflater.createCustomViewInternal(CalligraphyLayoutInflater.java:203)
at uk.co.chrisjenx.calligraphy.CalligraphyLayoutInflater.access$000(CalligraphyLayoutInflater.java:20)
at uk.co.chrisjenx.calligraphy.CalligraphyLayoutInflater$PrivateWrapperFactory2.onCreateView(CalligraphyLayoutInflater.java:302)
at android.view.LayoutInflater$FactoryMerger.onCreateView(LayoutInflater.java:237)
at android.view.LayoutInflater.tryCreateView(LayoutInflater.java:1067)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:995)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:959)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:1121)
at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:1082)
at android.view.LayoutInflater.inflate(LayoutInflater.java:680)
at uk.co.chrisjenx.calligraphy.CalligraphyLayoutInflater.inflate(CalligraphyLayoutInflater.java:60)
at android.view.LayoutInflater.inflate(LayoutInflater.java:532)
at androidx.leanback.app.BrowseFragment.onCreateView(BrowseFragment.java:1318)
at android.app.Fragment.performCreateView(Fragment.java:2505)
at android.app.FragmentManagerImpl.ensureInflatedFragmentView(FragmentManager.java:1491)
at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:1274)
at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:1486)
at android.app.FragmentManagerImpl.addFragment(FragmentManager.java:1728)
E/AndroidRuntime: at android.app.FragmentManagerImpl.onCreateView(FragmentManager.java:3562)
at android.app.FragmentController.onCreateView(FragmentController.java:104)
at android.app.Activity.onCreateView(Activity.java:7112)
at androidx.fragment.app.FragmentActivity.onCreateView(FragmentActivity.java:229)
at uk.co.chrisjenx.calligraphy.CalligraphyLayoutInflater$PrivateWrapperFactory2.onCreateView(CalligraphyLayoutInflater.java:303)
at android.view.LayoutInflater$FactoryMerger.onCreateView(LayoutInflater.java:237)
at android.view.LayoutInflater.tryCreateView(LayoutInflater.java:1067)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:995)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:959)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:1121)
at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:1082)
at android.view.LayoutInflater.inflate(LayoutInflater.java:680)
at uk.co.chrisjenx.calligraphy.CalligraphyLayoutInflater.inflate(CalligraphyLayoutInflater.java:60)
at android.view.LayoutInflater.inflate(LayoutInflater.java:532)
at android.view.LayoutInflater.inflate(LayoutInflater.java:479)
at android.transition.Scene.enter(Scene.java:182)
at com.android.internal.policy.PhoneWindow.transitionTo(PhoneWindow.java:522)
at com.android.internal.policy.PhoneWindow.setContentView(PhoneWindow.java:453)
at android.app.Activity.setContentView(Activity.java:3468)
at androidx.activity.ComponentActivity.setContentView(ComponentActivity.java:448)
at com.directsportsnetwork.tv.ui.TeamSclActivity.onCreate(TeamSclActivity.java:55)
at android.app.Activity.performCreate(Activity.java:8000)
at android.app.Activity.performCreate(Activity.java:7984)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1309)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3422)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3601)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:85)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2066)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:223)
at android.app.ActivityThread.main(ActivityThread.java:7656)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947)
My Activity code is -
package com.directsportsnetwork.tv.ui;
import android.annotation.SuppressLint;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.view.KeyEvent;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.FragmentActivity;
import com.directsportsnetwork.tv.R;
import com.directsportsnetwork.tv.api.DeviceLogManager;
import com.directsportsnetwork.tv.api.Utils;
import org.json.JSONArray;
import java.util.HashMap;
import uk.co.chrisjenx.calligraphy.CalligraphyContextWrapper;
public class TeamSclActivity extends FragmentActivity {
private String TAG = TeamSclActivity.class.getSimpleName();
private ImageView topShelfImg, topShelfMask;
private TeamSclFragment mTeamSclFragment;
private BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
finish();
}
};
#SuppressWarnings("unchecked")
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_teamscl);
IntentFilter filter = new IntentFilter();
filter.addAction("com.directsportsnetwork.tv.STOP");
registerReceiver(broadcastReceiver, filter);
DeviceLogManager.instance().sendTeamSelectionPageData(TeamSclActivity.this);
topShelfImg = (ImageView) findViewById(R.id.top_shelf_image);
topShelfMask = (ImageView) findViewById(R.id.top_shelf_mask);
Intent intent = getIntent();
if (intent != null) {
try {
String channelData = intent.getStringExtra(Utils.EXTRA_CHANNEL_RESPONSE);
HashMap<String, Integer> teamTrnMap = (HashMap<String, Integer>) intent.getSerializableExtra(Utils.EXTRA_TEAM_TRN_MAP);
mTeamSclFragment = (TeamSclFragment) getFragmentManager().findFragmentById(R.id.main_browse_fragment);
mTeamSclFragment.onResponseData(new JSONArray(channelData), teamTrnMap);
} catch (Exception e) {
e.printStackTrace();
}
setTopShelfMask();
final Handler mHandler = new Handler();
mHandler.postDelayed(new Runnable() {
#Override
public void run() {
try {
mHandler.postDelayed(this, 300);
if (mTeamSclFragment.getView() != null && getCurrentFocus() instanceof RelativeLayout) {
mTeamSclFragment.getView().requestFocus();
mHandler.removeCallbacks(this);
mHandler.removeCallbacksAndMessages(null);
}
}catch (Exception e) {
e.printStackTrace();
}
}
}, 300); //Changes START HERE FOR NEW CHANGES - 10/20/2018
}
}
#Override
protected void attachBaseContext(Context newBase) {
super.attachBaseContext(CalligraphyContextWrapper.wrap(newBase));
}
#Override
protected void onResume() {
super.onResume();
}
#Override
protected void onPause() {
super.onPause();
}
#Override
protected void onDestroy() {
super.onDestroy();
unregisterReceiver(broadcastReceiver);
}
#SuppressLint("MissingSuperCall")
#Override
protected void onSaveInstanceState(Bundle outState) {
//No call for super(). Bug on API Level > 11.
}
// remot Button OnClickListener methods
#Override
public boolean onKeyUp(int keyCode, KeyEvent event) {
switch (keyCode) {
case KeyEvent.KEYCODE_DPAD_LEFT:
case KeyEvent.KEYCODE_DPAD_RIGHT:
case KeyEvent.KEYCODE_DPAD_UP:
case KeyEvent.KEYCODE_DPAD_DOWN:
// Remove shadow over topShelfImage at here
if (mTeamSclFragment != null) {
mTeamSclFragment.startBackgroundTimer();
}
default:
return super.onKeyUp(keyCode, event);
}
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_DPAD_LEFT || keyCode == KeyEvent.KEYCODE_DPAD_RIGHT
|| keyCode == KeyEvent.KEYCODE_DPAD_DOWN || keyCode == KeyEvent.KEYCODE_DPAD_UP) {
// Add shadow over topShelfImage at here
topShelfImg.setAlpha(0.3f);
}
if (mTeamSclFragment != null) {
mTeamSclFragment.onMyKeyDown(keyCode, event);
}
return false;
}
public ImageView getTopShelfImg() {
return topShelfImg;
}
public void setTopShelfMask() {
if (Utils.SHOW_TOP_SHELF_MASK) {
topShelfMask.setBackground(ContextCompat.getDrawable(TeamSclActivity.this, R.drawable.ic_mask_bottom));
}
}
}
My Fragment code -
package com.directsportsnetwork.tv.ui;
import static androidx.leanback.app.BackgroundManager.getInstance;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;
import androidx.leanback.app.BackgroundManager;
import androidx.leanback.app.BrowseFragment;
import androidx.leanback.widget.ArrayObjectAdapter;
import androidx.leanback.widget.FocusHighlight;
import androidx.leanback.widget.HeaderItem;
import androidx.leanback.widget.ListRow;
import androidx.leanback.widget.ListRowPresenter;
import androidx.leanback.widget.OnItemViewClickedListener;
import androidx.leanback.widget.OnItemViewSelectedListener;
import androidx.leanback.widget.Presenter;
import androidx.leanback.widget.Row;
import androidx.leanback.widget.RowPresenter;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.target.CustomTarget;
import com.bumptech.glide.request.transition.Transition;
import com.directsportsnetwork.tv.R;
import com.directsportsnetwork.tv.api.OnResponseReceived;
import com.directsportsnetwork.tv.api.TvApplication;
import com.directsportsnetwork.tv.api.Utils;
import com.directsportsnetwork.tv.model.Team;
import com.directsportsnetwork.tv.presenter.TeamPresenter;
import com.directsportsnetwork.tv.provider.DataBaseHelper;
import org.json.JSONArray;
import org.json.JSONObject;
import java.net.URI;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Random;
import java.util.Timer;
import java.util.TimerTask;
public class TeamSclFragment extends BrowseFragment implements OnResponseReceived {
private final String TAGS = "TeamSclFragment";
private final Handler mHandler = new Handler();
private Drawable mDefaultBackground;
private DisplayMetrics mMetrics;
private Timer mBackgroundTimer;
private URI mBackgroundURI;
private URI defaultBackgroundURI;
public Team selectedTeam;
private JSONArray teamData;
private HashMap<String, Integer> teamTrnMap;
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
}
private boolean isFavoriteDisable(String teamId) {
return !(teamTrnMap != null && teamTrnMap.get(teamId) != null);
}
private int getTrnByTeamId(String teamId) {
return teamTrnMap.get(teamId);
}
#Override
public void onResponseData(JSONArray data, HashMap<String, Integer> teamTrnMap) {
try {
Log.e(TAGS, "apiResponse: " + data);
teamData = data;
this.teamTrnMap = teamTrnMap;
prepareBackgroundManager();
setupUIElements();
// Set rows as per data fetched form API
loadTeamRows(teamData);
setupEventListeners();
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public void onDestroy() {
super.onDestroy();
if (null != mBackgroundTimer) {
mBackgroundTimer.cancel();
}
}
#Override
public void onResume() {
super.onResume();
if (TvApplication.isFavChanged && teamData != null) {
loadTeamRows(teamData);
TvApplication.isFavChanged = false;
if (getView() != null) {
getView().requestFocus();
setSelectedPosition(0, true);
startBackgroundTimer();
}
}
}
#Override
public void onPause() {
super.onPause();
}
public void onMyKeyDown(int keyCode, KeyEvent event) {
//do whatever you want here
switch (keyCode) {
case KeyEvent.KEYCODE_BACK:
getActivity().finish();
getActivity().overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out);
break;
}
}
private void loadTeamRows(JSONArray teamCategoryList) {
try {
ArrayList<Team> favTeamList = new ArrayList<>();
if (Utils.isStoragePermissionGranted(getActivity())) {
DataBaseHelper dataBase = DataBaseHelper.getInstance(getActivity());
favTeamList = dataBase.getAllFavorites();
} else {
favTeamList.add(null);
Utils.showToast(getActivity(), getResources().getString(R.string.no_storage_permission));
}
ListRowPresenter mListRowPresenter = new ListRowPresenter(FocusHighlight.ZOOM_FACTOR_NONE, true);
ArrayObjectAdapter mRowsAdapter = new ArrayObjectAdapter(mListRowPresenter);
TeamPresenter teamPresenter = new TeamPresenter();
for (int i = 0; i < teamCategoryList.length() + 1; i++) {
ArrayObjectAdapter listRowAdapter = new ArrayObjectAdapter(teamPresenter);
if (i == 0) {
// This is to create Favorite card row
for (int index = 0; index < favTeamList.size(); index++) {
if (favTeamList.get(index) == null) {
listRowAdapter.add(getResources().getString(R.string.favorites));
} else {
Team team = favTeamList.get(index);
team.setIsFavorite(1);
if (isFavoriteDisable(team.getId())) {
// TODO: Team is disabled, remove it from favorites
DataBaseHelper dataBase = DataBaseHelper.getInstance(getActivity());
dataBase.removeFavorite(team.getId());
TvApplication.isFavChanged = true;
continue;
} else {
team.setReleaseNo(getTrnByTeamId(team.getId()));
}
listRowAdapter.add(team);
}
}
HeaderItem header = new HeaderItem(i, "Favorites");
mRowsAdapter.add(new ListRow(header, listRowAdapter));
} else {
JSONArray teamList = teamCategoryList.getJSONObject(i - 1).getJSONArray("team");
String category = teamCategoryList.getJSONObject(i - 1).getString("name");
String categoryId = teamCategoryList.getJSONObject(i - 1).getString("id");
for (int index = 0; index < teamList.length(); index++) {
JSONObject teamObj = teamList.getJSONObject(index);
String id = teamObj.getString("id");
String name = teamObj.getString("name");
String shortdesc = teamObj.getString("shortdesc");
String longdesc = teamObj.getString("longdesc");
int trn = teamObj.getInt("trn");
//trn stands for Team Release Number
Team team = new Team();
team.setCatId(categoryId);
team.setCatName(category);
team.setId(id);
team.setName(name);
team.setShortdesc(shortdesc);
team.setLongdesc(longdesc);
team.setIsFavorite(0);
team.setReleaseNo(trn);
if (category.equalsIgnoreCase("NASCAR")) {
team.setIsNascar(1);
} else {
team.setIsNascar(0);
}
listRowAdapter.add(team);
}
HeaderItem header = new HeaderItem(i, category);
mRowsAdapter.add(new ListRow(header, listRowAdapter));
}
}
setAdapter(mRowsAdapter);
} catch (Exception e) {
e.printStackTrace();
}
}
private void prepareBackgroundManager() {
BackgroundManager mBackgroundManager = getInstance(getActivity());
mBackgroundManager.attach(getActivity().getWindow());
mDefaultBackground = ContextCompat.getDrawable(getActivity(), R.drawable.default_background);
mBackgroundManager.setColor(Color.BLACK);
mMetrics = new DisplayMetrics();
getActivity().getWindowManager().getDefaultDisplay().getMetrics(mMetrics);
}
private void setupUIElements() {
getTitleView().setVisibility(View.GONE);
// To hide left side header for BrowseFragment
setHeadersState(HEADERS_DISABLED);
setHeadersTransitionOnBackEnabled(true);
}
private void setupEventListeners() {
setOnItemViewClickedListener(new ItemViewClickedListener());
setOnItemViewSelectedListener(new ItemViewSelectedListener());
}
protected void updateBackground(String uri) {
try {
int width = mMetrics.widthPixels;
int height = mMetrics.heightPixels;
final TeamSclActivity activity = ((TeamSclActivity) getActivity());
if (activity.getTopShelfImg().getDrawable().getConstantState() == getResources().getDrawable(R.drawable.ic_start).getConstantState() && (uri == defaultBackgroundURI.toString())) {
} else {
//start
if (activity != null) {
Glide.with(activity).load(uri).error(mDefaultBackground).placeholder(R.drawable.teamblank).into(new CustomTarget<Drawable>(width, height) {
#Override
public void onResourceReady(#NonNull Drawable resource, #Nullable Transition<? super Drawable> transition) {
activity.getTopShelfImg().setImageDrawable(resource);
Utils.crossfade(activity.getTopShelfImg());
}
#Override
public void onLoadCleared(#Nullable Drawable placeholder) {
}
});
}
//end
}
mBackgroundTimer.cancel();
} catch (Exception e) {
e.printStackTrace();
}
}
public void startBackgroundTimer() {
if (mBackgroundTimer != null) {
mBackgroundTimer.cancel();
}
mBackgroundTimer = new Timer();
mBackgroundTimer.schedule(new UpdateBackgroundTask(), Utils.BACKGROUND_UPDATE_DELAY);
}
private final class ItemViewClickedListener implements OnItemViewClickedListener {
#Override
public void onItemClicked(Presenter.ViewHolder itemViewHolder, Object item, RowPresenter.ViewHolder rowViewHolder, Row row) {
if (item instanceof Team) {
Team team = (Team) item;
Intent intent = new Intent(getActivity(), TeamChnlActivity.class);
intent.putExtra(Utils.EXTRA_TEAM, team);
startActivity(intent);
} else if (item instanceof String) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setMessage(getResources().getString(R.string.favorite_alert_msg));
builder.setCancelable(true);
builder.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog alert = builder.create();
alert.show();
}
}
}
private final class ItemViewSelectedListener implements OnItemViewSelectedListener {
#Override
public void onItemSelected(Presenter.ViewHolder itemViewHolder, Object item, RowPresenter.ViewHolder rowViewHolder, Row row) {
if (item instanceof Team) {
Team team = ((Team) item);
try {
selectedTeam = team;
mBackgroundURI = new URI(team.getTopShelfImageUrl(team.getId(), team.getReleaseNo()));
defaultBackgroundURI = new URI(Utils.MEDIA_PREFIX_URL + "/tv/images/app/start.jpg?");
if (team.getIsFavorite() == 1) {
startBackgroundTimer();
}
} catch (Exception e) {
e.printStackTrace();
}
} else if (item instanceof String) {
try {
selectedTeam = null;
Random random = new Random();
mBackgroundURI = new URI(Utils.MEDIA_PREFIX_URL + "/tv/images/app/start.jpg?" + random.nextInt(100));
defaultBackgroundURI = mBackgroundURI;
startBackgroundTimer();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
private class UpdateBackgroundTask extends TimerTask {
#Override
public void run() {
mHandler.post(new Runnable() {
#Override
public void run() {
if (mBackgroundURI != null) {
updateBackground(mBackgroundURI.toString());
}
}
});
}
}
}
My activity_teamscl.xml code -
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent">
<fragment
android:id="#+id/main_browse_fragment"
android:name="com.directsportsnetwork.tv.ui.TeamSclFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentBottom="true"
android:layout_alignTop="#+id/center_baseline"
tools:context=".ui.TeamSclActivity"
tools:deviceIds="tv"
tools:ignore="MergeRootFrame" />
</RelativeLayout>

How can I reduce the time for retrieving data from postgresql?

The code is working but it is taking 14-16 seconds to retrieve data of just 1 video from postgresql server. I think there might be a proper way of retrieving the data. Please help me with this.
Thank you.
FreeClassesAdapter.java
import android.app.Activity;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.android.volley.RequestQueue;
import com.athrved.masterclass.PlayerActivity;
import com.athrved.masterclass.R;
import com.squareup.picasso.Picasso;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
public class FreeclassesAdapter extends RecyclerView.Adapter<FreeclassesAdapter.FreeViewHolder> {
ArrayList<FreeHelperClass> featloc;
public static String a,b="FAILED TO LOAD";
public static String videoId1;
RequestQueue requestQueue;
private static String V_id1;
public FreeclassesAdapter(ArrayList<FreeHelperClass> featloc) {
this.featloc = featloc;
}
#NonNull
#Override
public FreeViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.free_class_card_design,parent,false);
FreeViewHolder freeViewHolder = new FreeViewHolder(view);
return freeViewHolder;
}
#Override
public void onBindViewHolder(#NonNull FreeViewHolder holder, int position) {
FreeHelperClass freeHelperClass = featloc.get(position);
holder.imagesmall1.setImageResource(freeHelperClass.getImagesmall1());
holder.imagesmall2.setImageResource(freeHelperClass.getImagesmall2());
holder.title.setText(freeHelperClass.getTitle());
holder.topic.setText(freeHelperClass.getTopic());
holder.author.setText(freeHelperClass.getAuthor());
Database db=new Database();
videoId1=V_id1;
if(position==0){
Picasso.get().load("https://img.youtube.com/vi/"+videoId1+"/maxresdefault.jpg").into(holder.imagebig);
}
if(position==1){
Picasso.get().load("https://img.youtube.com/vi/lrcqt4RelJ4/maxresdefault.jpg").into(holder.imagebig);
}
}
#Override
public int getItemCount() {
return featloc.size();
}
public static class FreeViewHolder extends RecyclerView.ViewHolder{
ImageView imagebig, imagesmall1,imagesmall2;
TextView topic, author;
TextView title;
Button bookmark, bookmark_border;
public FreeViewHolder(#NonNull final View itemView){
super(itemView);
imagebig=itemView.findViewById(R.id.freeimgbig);
imagesmall1=itemView.findViewById(R.id.freec1_image);
imagesmall2=itemView.findViewById(R.id.freec2_image);
bookmark=itemView.findViewById(R.id.bookmarkfree);
bookmark_border=itemView.findViewById(R.id.bookmarkfree_border);
title=itemView.findViewById(R.id.freec_title);
topic=itemView.findViewById(R.id.freec_topic);
author=itemView.findViewById(R.id.freec_author);
bookmark_border.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(getAdapterPosition()==0){
bookmark_border.setVisibility(View.GONE);
bookmark.setVisibility(View.VISIBLE);
}
if(getAdapterPosition()==1){
bookmark_border.setVisibility(View.GONE);
bookmark.setVisibility(View.VISIBLE);
}
}
});
bookmark.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(getAdapterPosition()==0){
bookmark_border.setVisibility(View.VISIBLE);
bookmark.setVisibility(View.GONE);
}
if(getAdapterPosition()==1){
bookmark_border.setVisibility(View.VISIBLE);
bookmark.setVisibility(View.GONE);
}
}
});
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
videoId1=V_id1;
if (getAdapterPosition() == 0) {
Intent intent = new Intent(itemView.getContext(), PlayerActivity.class);
intent.putExtra("VIDEOID", videoId1);
itemView.getContext().startActivity(intent);
Activity activity = (Activity) itemView.getContext();
activity.overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out);
}
if (getAdapterPosition() == 1) {
Intent intent = new Intent(itemView.getContext(), PlayerActivity.class);
intent.putExtra("VIDEOID", "lrcqt4RelJ4");
itemView.getContext().startActivity(intent);
Activity activity = (Activity) itemView.getContext();
activity.overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out);
}
}
});
}
}
private class Database {
private Connection connection;
private final String host = "ec2-54-158-232-223.compute-1.amazonaws.com";
private final String database = "ddgaguv61p4m63";
private final int port = 5432;
private final String user = "jfeitasqnyuanh";
private final String pass = "d60b43b4e9ea924c91deb754cf18a51d5948b7a7e58b4e4d0045487767174ad8";
private String url = "jdbc:postgresql://ec2-54-158-232-223.compute-1.amazonaws.com:5432/ddgaguv61p4m63?sslmode=require&user=jfeitasqnyuanh&password=d60b43b4e9ea924c91deb754cf18a51d5948b7a7e58b4e4d0045487767174ad8";
private boolean status;
public Database() {
this.url = String.format(this.url, this.host, this.port, this.database);
connect();
//this.disconnect();
System.out.println("connection status:" + status);
}
private void connect() {
Thread thread = new Thread(new Runnable() {
#Override
public void run() {
try {
Class.forName("org.postgresql.Driver");
connection = DriverManager.getConnection(url, user, pass);
status = true;
getExtraConnection();
System.out.println("connected:" + status);
} catch (Exception e) {
status = false;
System.out.print(e.getMessage());
e.printStackTrace();
}
}
});
thread.start();
try {
thread.join();
} catch (Exception e) {
e.printStackTrace();
this.status = false;
}
}
public Connection getExtraConnection() {
Connection c = null;
Statement stmt = null;
try {
Class.forName("org.postgresql.Driver");
c = DriverManager.getConnection(url, user, pass);
c.setAutoCommit(false);
System.out.println("Opened database successfully");
stmt = c.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM videos WHERE access_count=1;");
while (rs.next()) {
V_id1 = rs.getString("video_id");
//
// System.out.println("NAME = " + Name);
// System.out.println("BIO = " + Bio);
// System.out.println("PHONE = " + Phone);
System.out.println();
}
rs.close();
stmt.close();
c.close();
} catch (Exception e) {
System.err.println(e.getClass().getName() + ": " + e.getMessage());
System.exit(0);
}
System.out.println("Records created successfully");
return c;
}
}
}
Code from the main activity where FreeClassesAdapter is used - UiUxActivity.java:
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.view.MenuItem;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.athrved.masterclass.FetchData;
import com.athrved.masterclass.R;
import java.util.ArrayList;
import java.util.List;
public class UiuxActivity extends AppCompatActivity {
TextView abcde;
TextView ak;
String tit;
String urlname,videoID,tita;
RecyclerView dataList2;
List<String> titles2;
List<Integer> images2;
ImgAdapter2 imgAdapter2;
RecyclerView popRecycler;
RecyclerView.Adapter adapter1;
RecyclerView freeRecycler;
RecyclerView.Adapter adapter2;
RecyclerView menRecycler;
RecyclerView.Adapter adapter3;
RecyclerView allFewRecycler;
RecyclerView.Adapter adapter4;
ArrayList<UiuxAllClasses> allCourseList=new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_uiux);
getSupportActionBar().setTitle("UI UX Design");
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setBackgroundDrawable(new ColorDrawable(getResources().getColor(R.color.greyy)));
// videoID="_vAmKNin0QM";
// urlname="https://noembed.com/embed?url=https://www.youtube.com/watch?v="+videoID;
// tita= respo(urlname);
popRecycler = findViewById(R.id.r1popclass);
featuredRecycler();
freeRecycler=findViewById(R.id.r1freeclass);
freeturedRecycler( tit);
menRecycler=findViewById(R.id.r3menclass);
mentoredRecycler();
allFewRecycler=findViewById(R.id.r4fewalllist);
allfewRecycler();
dataList2 = findViewById(R.id.dataList2);
abcde = findViewById(R.id.tvv1);
ak=findViewById(R.id.ak);
titles2 = new ArrayList<>();
images2 = new ArrayList<>();
titles2.add("Visual Design");
titles2.add("UX Design");
titles2.add("Motion Design");
titles2.add("Prototyping");
titles2.add("3D Design");
titles2.add("Webflow");
images2.add(R.drawable.visuald_logo);
images2.add(R.drawable.uiux_logo);
images2.add(R.drawable.motiond_logo);
images2.add(R.drawable.mach_logo);
images2.add(R.drawable.threed_logo);
images2.add(R.drawable.iot_logo);
imgAdapter2 = new ImgAdapter2(this,titles2,images2);
GridLayoutManager gridLayoutManager = new GridLayoutManager(this,2,GridLayoutManager.VERTICAL,false);
dataList2.setLayoutManager(gridLayoutManager);
dataList2.setAdapter(imgAdapter2);
}
private void featuredRecycler(){
FetchData fetchData = new FetchData();
fetchData.execute();
popRecycler.setHasFixedSize(true);
popRecycler.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false));
ArrayList<PopHelperClass> popLocatio = new ArrayList<>();
popLocatio.add(new PopHelperClass(R.drawable.secndone, R.drawable.ai_logo,0,"Color and Color Theory -\nFundamentals of Visual Design","VISUAL DESIGN","Goutham Naik","Um3BhY0oS2c"));
popLocatio.add(new PopHelperClass(R.drawable.firstone, R.drawable.ai_logo, R.drawable.motiond_logo,"Color and Color Theory -\nFundamentals of Visual Design","UX DESIGN"," Goutham Naik, S. M. Sudhanva Acharya","_vAmKNin0QM"));
adapter1=new PopclassesAdapter(popLocatio);
popRecycler.setAdapter(adapter1);
}
private void freeturedRecycler(String tita){
freeRecycler.setHasFixedSize(true);
freeRecycler.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false));
ArrayList<FreeHelperClass> freeLocatio = new ArrayList<>();
freeLocatio.add(new FreeHelperClass(R.drawable.ai_logo,0,"Top UX Design Interview Questions","VISUAL DESIGN","S M Sudhanva Acharya"));
freeLocatio.add(new FreeHelperClass(R.drawable.ai_logo,0,"White Space in Design","VISUAL DESIGN","Abhinav Chikkara"));
adapter2=new FreeclassesAdapter(freeLocatio);
freeRecycler.setAdapter(adapter2);
}
private void mentoredRecycler(){
menRecycler.setHasFixedSize(true);
menRecycler.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false));
ArrayList<MenHelperClass> menLocatio = new ArrayList<>();
menLocatio.add(new MenHelperClass(R.drawable.oneman,"Goutam Naik","CEO, AthrV-Ed"));
menLocatio.add(new MenHelperClass(R.drawable.twoman,"S M Sudhanva Acharya", "Product Designer, AthrV-Ed"));
menLocatio.add(new MenHelperClass(R.drawable.threeman,"Abhinav Chikkara", "Founder, 10kilogram"));
adapter2=new MenAdapter(menLocatio);
menRecycler.setAdapter(adapter2);
}
private void allfewRecycler(){
allFewRecycler.setHasFixedSize(true);
allFewRecycler.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
ArrayList<FewAllHelperClass> fewAllLocatio = new ArrayList<>();
fewAllLocatio.add(new FewAllHelperClass(R.drawable.webflow_l, R.drawable.ai_logo,"Playing with Grid-\nWeb Design Fundamentals","WEBFLOW","Goutham Naik"));
fewAllLocatio.add(new FewAllHelperClass(R.drawable.protopie_l, R.drawable.ai_logo,"Protopie for Prototyping","PROTOTYPING\n","Abhinav Chikkara"));
fewAllLocatio.add(new FewAllHelperClass(R.drawable.afepluslot_l, R.drawable.ai_logo,"Introduction to After Effects\nand Lottie Files","MOTION DESIGN","S.M Sudhanva Acharya"));
adapter4=new FewAllAdapter(fewAllLocatio);
allFewRecycler.setAdapter(adapter4);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
onBackPressed();
return true;
}
return super.onOptionsItemSelected(item);
}
}
Are you storing the video in your DB as a BLOB / CLOB.
What if you store the video in a different location, and save the address of the location in your DB. This way Db has to return a string, and UI / consumer can take care of rendering from the path.

Value on Spinner can't post to databae mySql

logcat doesn't give me a specific error, it only shows the error location, which is on line 155 {id_status = spStatus.getSelectedItem().toString();}
I don't know the right keyword to solve the error. I've been browsing, and I think this is the same as the tutorial I followed. where is my mistake? give me more detailed instructions
my java like this:
package src.bkkpost.loker;
import android.app.DatePickerDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import java.util.Calendar;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
import src.bkkpost.MainActivity;
import src.bkkpost.R;
import src.bkkpost.loker.adapter.AdapterStatus;
import src.bkkpost.model.Value;
import src.bkkpost.util.BaseApiService;
import src.bkkpost.util.SharedPrefManager;
import src.bkkpost.util.UtilsApi;
public class UpdateLoker extends AppCompatActivity implements AdapterView.OnItemSelectedListener {
//string spinner kelamin
String[] idStatus = {"10", "20"};
String[] nama_status = {"Buka", "Tutup"};
//string spinner kelamin
String[] id_kelamin = {"5001", "5002", "5003"};
String[] nama_kelamin = {"Pria/Wanita", "Pria", "Wanita"};
//string spinner pendidikan
String[] pendidikan_id = {"3001", "3002", "3003", "30004", "3005", "3006", "3007"};
String[] nama_pendidikan = {"SD", "SMP", "SMA", "SMK ", "Diploma/(D3)", "Sarjana/(S1)", "Master/(S2)"};
//string spinner pendidikan
String[] jurusan_id = {"30001", "300301", "300302", "3000401", "3000402", "3000403", "3000404",
"3000405", "3000406", "3000407", "3000408", "3000409", "3000410", "3000411", "3000412", "3000413", "3000414",
"3000415", "300501", "300502", "300503", "300504", "300505", "300506", "300075"};
String[] nama_jurusan = {"Semua Jurusan", "IPA", "IPS", "Administrasi Perkantoran ", "Akuntansi ", "ANalisis Kimia ",
"Animasi ", "Broadcasting ", "Elektronik ", "Farmasi ", "Multimedia ", "Otomotif ", "Pariwisata ", "Pemasaran ",
"Perbankan ", "Perhotelan", "Tata Boga ", "Tata Busana ", "Perpajakan(D3/S1) ", "Broadcasting(D3/S1)", "Teknik Mesin(D3/S1)",
"Pariwisata(D3/S1)", "Sekretaris (D3/S1)", "Hubungan Masyarakat (D3/S1)", "Akuntansi(D3/S1) "};
AutoCompleteTextView date;
DatePickerDialog datePickerDialog;
BaseApiService mApiservice;
ProgressDialog loading;
Context mContex;
SharedPrefManager sharedPrefManager;
public static final String URL = "http://192.168.43.164/gokerja/";
private ProgressDialog progress;
String bkk_id, posisi, nama_pt, alamat_pt, waktu_buka, id_status;
#BindView(R.id.post_btn_upload)
Button btnUpload;
#BindView(R.id.post_bkk_id)
TextView tvBkkid;
#BindView(R.id.post_posisi)
AutoCompleteTextView etPosisi;
#BindView(R.id.post_namaperusahaan)
AutoCompleteTextView etNamaperusahan;
#BindView(R.id.post_alamat_pt)
AutoCompleteTextView etAlamat;
#BindView(R.id.post_tanggal)
AutoCompleteTextView etTangggal;
#BindView(R.id.post_spin_statusup)
Spinner spStatus;
#OnClick(R.id.post_btn_upload)
void daftar() { }
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.loker_update_loker);
ButterKnife.bind(this);
sharedPrefManager = new SharedPrefManager(this);
tvBkkid.setText(sharedPrefManager.getSPNama());
mApiservice = UtilsApi.getAPIService();
mContex = this;
date = (AutoCompleteTextView) findViewById(R.id.post_tanggal);
date.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final java.util.Calendar c = java.util.Calendar.getInstance();
int mYear = c.get(java.util.Calendar.YEAR);
int mMont = c.get(Calendar.MONTH);
int mDay = c.get(java.util.Calendar.DAY_OF_MONTH);
//date picker dialog
datePickerDialog = new DatePickerDialog(UpdateLoker.this,
new DatePickerDialog.OnDateSetListener() {
#Override
public void onDateSet(DatePicker view, int year,
int month, int dayOfMonth) {
date.setText(year + "-"
+ (month + 1) + "-" + dayOfMonth);
}
}, mYear, mMont, mDay);
datePickerDialog.show();
}
});
//get spinner status
final Spinner spinnerStatus = (Spinner) findViewById(R.id.post_spin_statusup);
spinnerStatus.setOnItemSelectedListener(this);
AdapterStatus adapterStatus = new AdapterStatus(getApplicationContext(), idStatus);
spinnerStatus.setAdapter(adapterStatus);
progress = new ProgressDialog(this);
btnUpload.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (etPosisi.getText().toString().equals("")) {
etPosisi.setError("Posisi harus di isi");
} else if (etNamaperusahan.getText().toString().equals("")) {
etNamaperusahan.setError("Perusahaan harus di isi");
} else if (etAlamat.getText().toString().equals("")) {
etAlamat.setError("alamat harus di isi");
} else {
//Untuk menampilkan progress dialog
progress.setCancelable(false);
progress.setMessage("Loading...");
progress.show();
bkk_id = tvBkkid.getText().toString();
posisi = etPosisi.getText().toString();
nama_pt = etNamaperusahan.getText().toString();
alamat_pt = etAlamat.getText().toString();
waktu_buka = etTangggal.getText().toString();
id_status = spStatus.getSelectedItem().toString();
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
BaseApiService api = retrofit.create(BaseApiService.class);
Call<Value> call = api.post_loker(bkk_id, posisi, nama_pt, alamat_pt, waktu_buka, id_status);
call.enqueue(new Callback<Value>() {
#Override
public void onResponse(Call<Value> call, Response<Value> response) {
String value = response.body().getValue();
String message = response.body().getMessage();
progress.dismiss();
if (value.equals("1")) {
AlertDialog.Builder alert = new AlertDialog.Builder(UpdateLoker.this);
alert.setTitle("Confirm");
alert.setMessage("Iklan Lowongan kerja telah berhasil dibuat");
alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
startActivity(new Intent(mContex, MainActivity.class));
dialog.dismiss();
}
});
alert.show();
} else {
AlertDialog.Builder alert = new AlertDialog.Builder(UpdateLoker.this);
alert.setTitle("Confirm");
alert.setMessage("Terjadi Kesalahan Jaringan, Iklan gagal dibuat");
alert.setPositiveButton("Coba Lagi", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
startActivity(new Intent(mContex, UpdateLoker.class));
dialog.dismiss();
}
});
alert.show();
}
}
#Override
public void onFailure(Call<Value> call, Throwable t) {
t.printStackTrace();
progress.dismiss();
AlertDialog.Builder alert = new AlertDialog.Builder(UpdateLoker.this);
alert.setTitle("Error 301");
alert.setMessage("Terjadi kesalahan jaringan, Iklan gagal dibuat");
alert.setPositiveButton("Coba Lagi", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
alert.show();
//Toast.makeText(UpdateLoker.this, "semelekete", Toast.LENGTH_SHORT).show();
}
});
}
}
});
}
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
}
this my Logcat
09-04 17:13:15.904 16015-16015/src.bkkpost D/AndroidRuntime: Shutting down VM
09-04 17:13:15.904 16015-16015/src.bkkpost W/dalvikvm: threadid=1: thread exiting with uncaught exception (group=0x419f3d58)
--------- beginning of /dev/log/system
09-04 17:13:15.904 16015-16015/src.bkkpost E/AndroidRuntime: FATAL EXCEPTION: main
Process: src.bkkpost, PID: 16015
java.lang.NullPointerException
at src.bkkpost.loker.UpdateLoker$2.onClick(UpdateLoker.java:155)
at android.view.View.performClick(View.java:4444)
at android.view.View$PerformClick.run(View.java:18457)
at android.os.Handler.handleCallback(Handler.java:733)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5113)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:796)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:612)
at dalvik.system.NativeStart.main(Native Method)

Dilog not working in android apllication

I am having two classes SqlLiteExample.javaand HotOrNot.java.First one is for creating interface and second one is for Database creation.
SqlLiteExample.java
package com.thenewboston;
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 SqlLiteExample extends Activity implements OnClickListener{
EditText etName,etHotness;
Button btnSave,btnView;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.sqliteexample);
etName=(EditText) findViewById(R.id.editText1);
etName=(EditText) findViewById(R.id.editText2);
btnSave=(Button) findViewById(R.id.btnSQLUPDATE);
btnView=(Button) findViewById(R.id.btnSQLVIEW);
btnSave.setOnClickListener(this);
btnView.setOnClickListener(this);
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch(v.getId()){
case R.id.btnSQLUPDATE:
boolean didItWork=true;
try{
String name=etName.getText().toString();
String hotness=etHotness.getText().toString();
HotOrNot entry= new HotOrNot(SqlLiteExample.this);
entry.open();
entry.createEntry(name,hotness);
entry.close();
}catch(Exception e){
didItWork= false;
}finally{
if(didItWork){
Dialog d= new Dialog(this);
d.setTitle("Heck yea");
System.out.println("testing");
TextView tv= new TextView(this);
tv.setText("sucess");
d.setContentView(tv);
d.show();
}
}
break;
case R.id.btnSQLVIEW:
break;
}
}
}
HotOrNot.java
package com.thenewboston;
import android.content.ContentValues;
import android.content.Context;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class HotOrNot {
public static final String KEY_ROWID = "_id";
public static final String KEY_NAME = "persons_name";
public static final String KEY_HOTNESS = "persons_hotness";
private static final String DATABASE_NAME = "HotOrNotdb";
private static final String DATABASE_TABLE = "peopleTable";
private static final int DATABASE_VERSION = 1;
private DbHelper ourhelper;
private final Context ourContext;
private SQLiteDatabase ourDatabase;
private static class DbHelper extends SQLiteOpenHelper {
public DbHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
// TODO Auto-generated constructor stub
}
#Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
db.execSQL("CREATE TABLE " + DATABASE_TABLE + " (" + KEY_ROWID
+ " INTEGER PRIMARY KEY AUTOINCREMENT, " + KEY_NAME
+ " TEXT NOT NULL, " + KEY_HOTNESS + "TEXT NOT NULL);"
);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
db.execSQL("DROP TABLE IF EXIST "+ DATABASE_TABLE);
onCreate(db);
}
}
public HotOrNot(Context c) {
ourContext = c;
}
public HotOrNot open() throws SQLException{
ourhelper = new DbHelper(ourContext);
ourDatabase= ourhelper.getWritableDatabase();
return this;
}
public void close(){
ourhelper.close();
}
public long createEntry(String name, String hotness) {
// TODO Auto-generated method stub
ContentValues cv= new ContentValues();
cv.put(KEY_NAME, name);
cv.put(KEY_HOTNESS, hotness);
return ourDatabase.insert(DATABASE_TABLE, null, cv);
}
}
Problem in that whenever I press btnSave is should display a dilog which is defined in finally block of case R.id.btnSQLUPDATE:but it is not.I have tried to debug the code,after executing HotOrNot entry= new HotOrNot(SqlLiteExample.this); in the same case it is moving into catch block and catches exception.I am uable find where I am doing wrong.
I think you got NPL(null pointer exeption) in this line:
String hotness=etHotness.getText().toString();
you did not findViewById "etHotness" , look at your code:
in onCreate() you write this:
etName=(EditText) findViewById(R.id.editText1);
etName=(EditText) findViewById(R.id.editText2);
shoud change to:
etName=(EditText) findViewById(R.id.editText1);
etHotness=(EditText) findViewById(R.id.editText2);
I personnally use AlertDialog with AlertDialog.Builder for this kind of situation. Works pretty well...
new AlertDialog.Builder(this)
.setTitle("Your title")
.setMessage("Your message")
.setPositiveButton("OK", mOnClickListener)
.create()
.show();
You can also set a list of clickable item as view, or a list of checkboxes or radiobuttons with methods setAdapter, setSingleChoiceItems and setMultiChoiceItems. I find it simplier to use.
I use AlertDialog, it's better solution. Use this code:
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
LayoutInflater inflater = getActivity().getLayoutInflater();
View viewDialog = inflater.inflate(R.layout.alertdialog_gameover, null);
TextView title = (TextView)viewDialog.findViewById(R.id.title);
title.setText("Successfully");
builder.setView(viewDialog)
.setPositiveButton("Play again", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
//Set something for positive
}
})
.setNegativeButton("Close", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
//set something for negative
}
});
//create dialog
builder.create();
//show dialog
builder.show();
Edit:
try to change:
}catch(Exception e){
didItWork= false;
}
to:
}catch(Exception e){
didItWork= true;
}
your code for Dialog work for me.

Error on Android's rawQuery()

i got nullPointerException when trying to fetch some data from database with rawQuery.
Here's an error:
03-11 18:09:01.522: E/AndroidRuntime(2057): Uncaught handler: thread
main exiting due to uncaught exception 03-11 18:09:01.532:
E/AndroidRuntime(2057): java.lang.NullPointerException 03-11
18:09:01.532: E/AndroidRuntime(2057): at
com.math.scan.FormulaModel.setFormulaList(FormulaModel.java:27)
Look at my code:
DbHelper
package com.math.scan;
import java.io.IOException;
import java.io.InputStream;
import java.util.Scanner;
import android.content.Context;
import android.content.res.AssetManager;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
public class DbHelper extends SQLiteOpenHelper{
public static final String TABLE_NAME = "formulas";
public static final String COLUMN_ID = "_id";
public static final String COLUMN_UNKNOWN = "unknown";
public static final String COLUMN_FORMULA = "formula";
public static final String COLUMN_CTG = "ctg";
private static final String DB_NAME = "formulas.db";
private static int DB_VERSION = 1;
private static final String DB_CREATE = "CREATE TABLE "+TABLE_NAME+
"("+COLUMN_ID+" integer primary key autoincrement,"
+COLUMN_UNKNOWN+" text not null,"
+COLUMN_FORMULA+" text not null,"
+COLUMN_CTG+" text not null );";
public Context mCtx;
public DbHelper(Context context) {
super(context, DB_NAME, null, DB_VERSION);
this.mCtx = context;
}
#Override
public void onCreate(SQLiteDatabase database) {
database.execSQL(DB_CREATE);
// reading formulas
AssetManager asset = mCtx.getAssets();
try {
InputStream input = asset.open("formulas");
int size = input.available();
byte[] buffer = new byte[size];
input.read(buffer);
input.close();
String content = new String(buffer);
Scanner scan = new Scanner(content);
String current;
String[] f = new String[2];
String[] formula = new String[2];
while(scan.hasNextLine()) {
current = scan.nextLine();
// get category
f = current.split("!!");
formula = f[1].split(" = ");
database.execSQL("INSERT INTO `formulas` VALUES (NULL, '"+formula[0]+"', '"+formula[1]+"', '"+f[0]+"');");
Log.d("DB", "INSERT INTO `formulas` VALUES (NULL, '"+formula[0]+"', '"+formula[1]+"', '"+f[0]+"');");
}
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Log.w(DbHelper.class.getName(),
"Upgrading database from version " + oldVersion + " to "
+ newVersion + ", which will destroy all old data");
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
onCreate(db);
}
}
FormulaModel
package com.math.scan;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;
public class FormulaModel {
private SQLiteDatabase database;
private DbHelper dbHelper;
public FormulaModel(Context context) {
dbHelper = new DbHelper(context);
}
public void open() throws SQLException {
dbHelper.getWritableDatabase();
}
public void close() {
dbHelper.close();
}
public void setFormulaList(String ctg) {
open();
// app stops working here
Cursor cursor = database.rawQuery("SELECT unknown, formula FROM formulas WHERE ctg = '"+ctg+"'", null);
int results = cursor.getCount();
cursor.moveToFirst();
Global.FormuleResult = new String[results];
Global.FormuleTable = new String[results];
for(int i = 0; i < results; i++) {
Global.FormuleTable[i] = cursor.getString(1);
Global.FormuleResult[i] = cursor.getString(0);
}
close();
}
}
This is activity, where I call setFormulaList() method in FormulaModel class.
package com.math.scan;
import net.sourceforge.jeval.EvaluationException;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class ProblemActivity extends Activity {
private EditText prob;
private Button solve;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.problem);
// text field
prob = (EditText) findViewById(R.id.problem);
// confirm btn
solve = (Button) findViewById(R.id.solve);
// check if confirm button was pressed
solve.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// get text from the field
String problem = prob.getText().toString();
// check if expression is not empty
if(problem.length() == 0) {
// string is empty!
Toast.makeText(ProblemActivity.this, getString(R.string.empty_field), Toast.LENGTH_SHORT).show();
} else {
FormulaModel f = new FormulaModel(ProblemActivity.this);
f.setFormulaList("mech");
pears.doMagic(problem);
try {
String str = Global.eval.getVariableValue(Global.UNKNOWN);
TextView answ = (TextView) findViewById(R.id.answer);
answ.setText(getString(R.string.prob_answ) + str);
} catch (EvaluationException e) {
Toast.makeText(ProblemActivity.this, getString(R.string.prob_error), Toast.LENGTH_SHORT).show();
}
}
}
});
}
}
I can't figure out what is wrong here.
Any ideas?
You have to set your database variable in open():
database = dbHelper.getWritableDatabase();

Categories