Java 在json中插入/显示/加载
首先:1。当我将空数据插入sql时,它崩溃了。加载json时崩溃3。按空数据显示记录崩溃,请帮助 以下是主要活动:Java 在json中插入/显示/加载,java,android,sqlite,android-layout,Java,Android,Sqlite,Android Layout,首先:1。当我将空数据插入sql时,它崩溃了。加载json时崩溃3。按空数据显示记录崩溃,请帮助 以下是主要活动: 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 j
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;
导入java.io.BufferedReader;
导入java.io.BufferedWriter;
导入java.io.File;
导入java.io.FileInputStream;
导入java.io.FileOutputStream;
导入java.io.IOException;
导入java.io.InputStreamReader;
导入java.io.OutputStreamWriter;
导入java.io.Writer;
导入java.util.ArrayList;
导入org.json.JSONArray;
导入org.json.JSONException;
导入org.json.JSONObject;
导入android.app.Activity;
导入android.app.AlertDialog;
导入android.content.DialogInterface;
导入android.os.Bundle;
导入android.os.Environment;
导入android.util.Log;
导入android.view.Menu;
导入android.view.MenuItem;
导入android.view.view;
导入android.view.view.OnClickListener;
导入android.widget.Button;
导入android.widget.EditText;
导入android.widget.ImageView;
导入android.widget.LinearLayout;
导入android.widget.ScrollView;
导入android.widget.TableLayout;
导入android.widget.TableRow;
导入android.widget.TextView;
导入com.example.user.notebook.Students;
公共类MainActivity扩展了活动{
LinearLayout mainLayout=null;
EditText lessons=null,student=null,grade=null,observations=null;
按钮insertRecord=null,showRecords=null;
ArrayList结果=新建ArrayList();
TableLayout resultLayout=null;
数据库db=null;
LinearLayout jsonLayout=null;
按钮loadJSON=null,saveJSON=null;
public-void-makeJSON()
{
jsonLayout=新的线性布局(本);
mainLayout.addView(jsonLayout);
loadJSON=新建按钮(此按钮);
setText(“加载JSON”);
addView(loadJSON);
loadJSON.setOnClickListener(新的OnClickListener()
{
@凌驾
公共void onClick(视图v){
AlertDialog.Builder alert=新建
AlertDialog.Builder(MainActivity.this);
alert.setTitle(“加载文件”);
setMessage(“指定文件名:”);
最终编辑文本输入=新编辑文本(MainActivity.this);
alert.setView(输入);
alert.setPositiveButton(“确定”,
新建DialogInterface.OnClickListener()
{
public void onClick(对话框接口对话框,int whichButton)
{
字符串值=input.getText().toString();
File myfile=新文件(
getExternalStorageDirectory(),值);
试一试{
BufferedReader br=新的BufferedReader(
新的InputStreamReader(新的
FileInputStream(myfile),“utf8”),65536);
字符串行=”;
line=br.readLine();
试一试{
JSONArray x=新JSONArray(线);
Log.d(“测试”,“我读过”+x);
int i;
对于(i=0;i您正在尝试遍历results.size(),它为空。请按照您的代码进行操作
.....
result=db.getResults();
final JSONArray x=new JSONArray();
int i;
for(i=0;i<result.size();i++)
....
。。。。。
result=db.getResults();
final JSONArray x=新的JSONArray();
int i;
对于(i=0;i您正在尝试遍历results.size(),它为空。请按照您的代码进行操作
.....
result=db.getResults();
final JSONArray x=new JSONArray();
int i;
for(i=0;i<result.size();i++)
....
。。。。。
result=db.getResults();
final JSONArray x=新的JSONArray();
int i;
对于(i=0;i您有两个问题,第一个问题掩盖了第二个问题,第二个问题更为明显,因此最初尝试修复导致无效的问题
- 第一个问题是,您在
onCLick
中获取result数组,然后调用updateTable()方法,其中检索到的结果数组不在updateTable
方法的范围内。因此移动result=db.getResults();
转到updateTable
方法,解决了该问题
- 第二个问题是
getResults
如果提取了任何行,将返回null
因此,要解决问题并压缩代码,而不是(解决问题2):-
从showRecords.setOnClickListener
的onClick
方法中删除现在不必要的result=db.getResults();
这既压缩了代码,也不会返回null,而是返回一个已填充或大小为0的ArrayList
因此,绕过java.lang.NullPointerException:尝试在空对象引用上调用虚拟方法“int java.util.ArrayList.size()”
您有两个问题,第一个问题掩盖了第二个问题,这一点更为明显,因此最初尝试修复导致无效的问题
- 第一个问题是,您在
onCLick
中获取result数组,然后调用updateTable()方法,其中检索到的结果数组不在updateTable
方法的范围内。因此移动result=db.getResults();
转到updateTable
方法,解决了该问题
- 第二个问题是
getResults
如果提取了任何行,将返回null
因此,要解决问题并压缩代码,而不是(解决问题2):-
从showRecords.setOnClickListener
的onClick
方法中删除现在不必要的result=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;
}
ArrayList<Students> x= new ArrayList<Students>();
ArrayList<Students> studentsResults = new ArrayList<Students>();
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 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;
}
public void updateTable()
{
result=db.getResults(); //<<<< ADDED
resultLayout.removeAllViews();
makeTable();
int i;
for(i=0;i<result.size();i++)
{