我使用Retrofit从服务器检索数据 现在我想用sqlite数据库存储。 但是程序没有在 BaseApter类和MainFragment
中运行获取错误我的模特课程
在那个班级我设置了getter和setter
public class Post {
@SerializedName("id")
@Expose
private int id;
@SerializedName("name")
@Expose
private String name;
@SerializedName("age")
@Expose
private String age;
@SerializedName("city")
@Expose
private String city;
@SerializedName("mob")
@Expose
private String mob;
我的界面
public interface ApiInterface {
@GET("fetch.php")
Call<List<Post>> getContacts();
}
改造客户
public class RetrofitClient {
private static Retrofit retrofit = null;
public static Retrofit getClient(String baseUrl) {
Gson gson = new GsonBuilder()
.setLenient()
.create();
if (retrofit == null) {
retrofit = new Retrofit.Builder()
.baseUrl(baseUrl)
.addConverterFactory(GsonConverterFactory.create(gson))
.build();
}
return retrofit;
}
}
我想存储数据的数据库类
public class DatabaseHelper extends SQLiteOpenHelper {
public static final String DATABASE_NAME = "ApointmentDb.db";
public static final String TABLE_NAME = "ApointList";
public static final String TAG_ID = "id";
public static final String TAG_NAME = "name";
public static final String TAG_AGE = "age";
public static final String TAG_CITY = "city";
public static final String TAG_MOB = "mob";
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, 1);
}
@Override
public void onCreate(SQLiteDatabase db) {
String createTable = "CREATE TABLE " + TABLE_NAME + "" +
"("
+ TAG_ID + " id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,"
+ TAG_NAME + " TEXT,"
+ TAG_AGE + " TEXT,"
+ TAG_CITY + " TEXT, "
+ TAG_MOB + " TEXT)";
db.execSQL(createTable);
}
@Override
public void onUpgrade(SQLiteDatabase db, int i, int i1) {
db.execSQL("DROP IF TABLE EXISTS" + TABLE_NAME);
}
public void addData(Post post) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(TAG_ID, post.getId());
contentValues.put(TAG_NAME, post.getName());
contentValues.put(TAG_AGE, post.getName());
contentValues.put(TAG_CITY, post.getName());
contentValues.put(TAG_MOB, post.getName());
db.insert(TABLE_NAME, null, contentValues);
db.close();
}
和适配器类
public class ApointmentAdapter extends BaseAdapter {
Context mContext;
private List<Post> mContact;
public ApointmentAdapter(List<Post> mContact, Context mContext) {
this.mContact = mContact;
this.mContext = mContext;
}
public class ViewHolder {
public TextView tvId;
public TextView tvName;
public TextView tvAge;
public TextView tvCity;
public TextView tvMob;
}
@Override
public int getCount() {
return mContact.size();
}
@Override
public Object getItem(int position) {
return mContact.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
public void addPost(Post post) {
mContact.add(post);
notifyDataSetChanged();
}
@Override
public View getView(int position, View convertView, ViewGroup viewGroup) {
View vi = convertView;
ViewHolder holder;
if (convertView == null) {
LayoutInflater inflater;
inflater = (LayoutInflater) mContext.getSystemService( Context.LAYOUT_INFLATER_SERVICE );
vi = inflater.inflate(R.layout.status_item_layout, null);
holder = new ViewHolder();
holder.tvId = (TextView) vi.findViewById(R.id.tv_status_id);
holder.tvName = (TextView) vi.findViewById(R.id.tv_status_name);
holder.tvAge = (TextView) vi.findViewById(R.id.tv_status_age);
holder.tvCity = (TextView) vi.findViewById(R.id.tv_status_city);
holder.tvMob = (TextView) vi.findViewById(R.id.tv_status_mob);
vi.setTag(holder);
} else
holder = (ViewHolder) vi.getTag();
// now set your text view here like
holder.tvId.setText(String.valueOf(mContact.get(position).getId()));
holder.tvName.setText(mContact.get(position).getName());
holder.tvAge.setText(mContact.get(position).getAge());
holder.tvCity.setText(mContact.get(position).getCity());
holder.tvMob.setText(mContact.get(position).getMob());
// return your view
return vi;
}
}
最后一个MainFragment类
public class StatusFragment extends Fragment implements LoaderManager.LoaderCallbacks<Post> {
private ListView listView;
private List<Post> contacts;
private ApointmentAdapter adapter;
private ApiInterface apiInterface;
private SimpleCursorAdapter mAdapter;
private boolean firstTimeLoad = false;
LoaderManager mLoaderManager;
private DatabaseHelper myDb;
private final String TAG = SaveToDatabase.class.getSimpleName();
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup v,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootView = inflater.inflate(R.layout.fragment_status, v, false);
LinearLayout linearLayout = (LinearLayout) rootView.findViewById(R.id.ly_apointment_status);
listView = (ListView)rootView.findViewById(R.id.lv_apnt_status);
((ViewGroup)linearLayout.getParent()).removeView(linearLayout);
adapter = new ApointmentAdapter(contacts,getActivity());
listView.setAdapter(adapter);
apiInterface = APIClient.getApiClient().create(ApiInterface.class);
Call<List<Post>> call = apiInterface.getContacts();
call.enqueue(new Callback<List<Post>>() {
@Override
public void onResponse(Call<List<Post>> call, Response<List<Post>> response) {
if (response.isSuccessful()){
List<Post> contacts = response.body();
for (int i=0; i < contacts.size(); i++){
Post post = contacts.get(i);
SaveToDatabase task = new SaveToDatabase();
task.execute(post);
adapter.addPost(post);
}
}else {
}
}
@Override
public void onFailure(Call<List<Post>> call, Throwable t) {
Toast.makeText(getActivity(), "Error" + t.toString(), Toast.LENGTH_SHORT).show();
}
});
return linearLayout;
}
public class SaveToDatabase extends AsyncTask<Post, Void , Void>{
@Override
protected Void doInBackground(Post... params) {
Post postt = params[0];
try{
myDb.addData(postt);
}catch (Exception e){
Log.d(TAG, e.getMessage());
Toast.makeText(getActivity(), "Error" +e.getMessage(), Toast.LENGTH_SHORT).show();
}
return null;
}
getcount方法
中的Adapter类中的错误@Override
public int getCount() {
return mContact.size();
}
并在主类
listView.setAdapter(adapter);
我在哪里犯了错误?
logcat的
FATAL EXCEPTION: main
Process: com.example.s2r1.appointment, PID: 6560
java.lang.NullPointerException
at com.example.s2r1.appointment.ApointmentAdapter.getCount(ApointmentAdapter.java:42)
at android.widget.ListView.setAdapter(ListView.java:480)
at com.example.s2r1.appointment.StatusFragment.onCreateView(StatusFragment.java:65)
at android.support.v4.app.Fragment.performCreateView(Fragment.java:2080)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1108)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1290)
at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:801)
at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1677)
at android.support.v4.app.FragmentManagerImpl$1.run(FragmentManager.java:536)
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:5241)
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:818)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java)
at dalvik.system.NativeStart.main(Native Method)