在json中插入/显示/加载崩溃

时间:2018-01-24 20:01:40

标签: java android sqlite android-layout

首先:1。当我将空数据插入sql时崩溃2.当加载json崩溃时3.按空数据显示记录崩溃请帮助!

这是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();
    }
}

数据库

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:变量seinfo:默认灵敏度:NULL,cateogry:NULL   01-24 22:14:42.292 2421-2421 / com.example.user.notebook E / AndroidRuntime:FATAL EXCEPTION:main                                                                            处理:com.example.user.notebook,PID:2421                                                                            java.lang.NullPointerException:尝试调用虚方法&#39; int java.util.ArrayList.size()&#39;在null对象引用上                                                                                在com.example.user.notebook.MainActivity.updateTable(MainActivity.java:257)                                                                                在com.example.user.notebook.MainActivity $ 4.onClick(MainActivity.java:235)                                                                                在android.view.View.performClick(View.java:4808)                                                                                在android.view.View $ PerformClick.run(View.java:19918)                                                                                在android.os.Handler.handleCallback(Handler.java:739)                                                                                在android.os.Handler.dispatchMessage(Handler.java:95)                                                                                在android.os.Looper.loop(Looper.java:135)                                                                                在android.app.ActivityThread.main(ActivityThread.java:5608)                                                                                at java.lang.reflect.Method.invoke(Native Method)                                                                                在java.lang.reflect.Method.invoke(Method.java:372)                                                                                在com.android.internal.os.ZygoteInit $ MethodAndArgsCaller.run(ZygoteInit.java:1397)                                                                                在com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1192)

  

E / AndroidRuntime:致命异常:主要                         处理:com.example.user.notebook,PID:4373                         java.lang.NumberFormatException:无效的double:&#34;&#34;                             at java.lang.StringToReal.invalidReal(StringToReal.java:63)                             在java.lang.StringToReal.parseDouble(StringToReal.java:267)                             在java.lang.Double.parseDouble(Double.java:301)                             在com.example.user.notebook.MainActivity $ 3.onClick(MainActivity.java:230)                             在android.view.View.performClick(View.java:4808)                             在android.view.View $ PerformClick.run(View.java:19918)                             在android.os.Handler.handleCallback(Handler.java:739)                             在android.os.Handler.dispatchMessage(Handler.java:95)                             在android.os.Looper.loop(Looper.java:135)                             在android.app.ActivityThread.main(ActivityThread.java:5608)                             at java.lang.reflect.Method.invoke(Native Method)                             在java.lang.reflect.Method.invoke(Method.java:372)                             在com.android.internal.os.ZygoteInit $ MethodAndArgsCaller.run(ZygoteInit.java:1397)                             在com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1192)

2 个答案:

答案 0 :(得分:1)

你试图通过result.size(),它是null。按照你的代码。

.....
result=db.getResults();
                final JSONArray x=new JSONArray();
                int i;
                for(i=0;i<result.size();i++)
....

这将进入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;

    }

如果你看一下这个方法......你要返回x,但x是null。你没有向X添加任何东西。然后......你在最后返回null ....这就是你的问题所在。

PS:请为变量使用更好的名称。

ArrayList<Students> x= new ArrayList<Students>();
如果它像......那样可以更好更容易理解

ArrayList<Students> studentsResults = new ArrayList<Students>();

现在很明显你不必这样做,但它更容易阅读代码...而且更清洁...更清洁

答案 1 :(得分:1)

你有两个问题,第一个掩盖第二个问题,这个问题更加明显,因此最初尝试修复导致无效工作的问题。

  • 第一个问题是您在UPDATE my_table SET id = nextval(my_table_id_sequence) 中获取了结果数组,然后调用了updateTable()方法,其中检索到的结果数组不在onCLick方法的范围。因此,将updateTable移至result=db.getResults();方法,解决了该问题。

  • 第二个问题是,如果提取了任何行,updateTable将返回null。

所以要解决问题并压缩代码,而不是(解决问题2): -

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;
    }

此外,要在updateTable方法中修复(1),请添加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; } 例如

result=db.getResults();

public void updateTable() { result=db.getResults(); //<<<< ADDED resultLayout.removeAllViews(); makeTable(); int i; for(i=0;i<result.size();i++) { 的{​​{1}}方法移除现在不必要的result=db.getResults();

这既压缩代码也不会返回null,而是返回一个填充或大小为0的ArrayList。

因此绕过showRecords.setOnClickListener