我使用API获取数据,存储&然后显示为列表视图。但我的应用显示空白活动。我正在使用ContentProvider。这是我的代码。请帮助。
MainActivity.java
package com.example.so;
import android.content.ContentValues;
import android.database.Cursor;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.ListView;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
private static final String LOG_TAG = MainActivity.class.getSimpleName();
Adapter adapter;
Model[] model;
DataDbHelperr dbHandler;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ListView listView = (ListView) findViewById(R.id.list_item);
dbHandler = new DataDbHelper(this);
Log.d(LOG_TAG, "Databse initialized");
FetchDataTask dataTask = new FetchDataTask();
dataTask.execute();
adapter = new Adapter(MainActivity.this);
listView.setAdapter(adapter);
}
public class FetchDataTask extends AsyncTask<String, Void, Model[]> {
private final String LOG_TAG = FetchDataTask.class.getSimpleName();
private Model[] getDataFromJson(String dataJsonStr)throws JSONException {
JSONObject object = new JSONObject(dataJsonStr);
JSONObject json_data = object.getJSONObject("data");
JSONArray json_feed = json_data.getJSONArray("feed");
Model[] model = new Model[json_feed.length()];
//final String POSTER_URL = "http://so-images/:";
for (int i = 0 ; i < json_feed.length(); i++){
model[i] = new Model(
json_feed.getJSONObject(i).getString("title"),
json_feed.getJSONObject(i).getString("imageUrl")
);
Log.d(LOG_TAG," title of data "+json_feed.getJSONObject(i).getString("title"));
Log.d(LOG_TAG,"image url "+json_feed.getJSONObject(i).getString("imageUrl"));
String title = model[i].getTitle();
String imageURL = model[i].getImageUrl();//
ContentValues contentValues = new ContentValues();
contentValues.put(com.example.so.data.DataContract.DataEntry.COLUMN_TITLE, title);
contentValues.put(com.example.so.data.DataContract.DataEntry.COLUMN_IMAGE_URL, imageURL);
Log.d(LOG_TAG, "Content Value contains data");
Log.d(LOG_TAG,"content uri checking "+ com.example.so.data.DataContract.DataEntry.CONTENT_URI);
getContentResolver().insert(com.example.so.data.DataContract.DataEntry.CONTENT_URI, contentValues);
Log.d(LOG_TAG,"Data is inserted successfully");
}
return model;
}
@Override
protected Model[] doInBackground(String... params) {
Log.d(LOG_TAG,"in the do in background task");
// These two need to be declared outside the try/catch
// so that they can be closed in the finally block.
HttpURLConnection urlConnection = null;
BufferedReader reader = null;
// Will contain the raw JSON response as a string.
String dataJsonStr = null;
try {
// Construct the URL for the OpenWeatherMap query
// Possible parameters are avaiable at OWM's forecast API page, at
// http://openweathermap.org/API#forecast
URL url = new URL("http://s-o.co.in:1302/api/v2/delhi/feed/5");
Log.d(LOG_TAG, "URL " + url.toString());
// Create the request to OpenWeatherMap, and open the connection
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.connect();
// Read the input stream into a String
InputStream inputStream = urlConnection.getInputStream();
StringBuffer buffer = new StringBuffer();
if (inputStream == null) {
// Nothing to do.
return null;
}
reader = new BufferedReader(new InputStreamReader(inputStream));
String line;
while ((line = reader.readLine()) != null) {
// Since it's JSON, adding a newline isn't necessary (it won't affect parsing)
// But it does make debugging a *lot* easier if you print out the completed
// buffer for debugging.
buffer.append(line + "\n");
}
if (buffer.length() == 0) {
// Stream was empty. No point in parsing.
return null;
}
dataJsonStr = buffer.toString();
Log.d(LOG_TAG,"JSON Data"+dataJsonStr);
} catch (IOException e) {
Log.e("PlaceholderFragment", "Error ", e);
return null;
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
if (reader != null) {
try {
reader.close();
} catch (final IOException e) {
Log.e("Fetch data task", "Error closing stream", e);
}
}
}
// Parsing the JSON string
try {
return getDataFromJson(dataJsonStr);
} catch (JSONException e) {
Log.e(LOG_TAG, e.getMessage(), e);
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(Model[] strings) {
Log.v(LOG_TAG,"ON POST EXECUTE METHOD IS CALLED");
Cursor cursor = getContentResolver().query(
com.example.so.data.DataContract.DataEntry.CONTENT_URI,
null,
null,
null,
null,
null
);
Model models = new Model();
while(cursor.moveToNext()){
models.setTitle(cursor.getString(1));
models.setImageUrl(cursor.getString(2));
Log.d(LOG_TAG, "Title here " + models.getTitle());
Log.d(LOG_TAG,"Image url here "+models.getImageUrl());
}
adapter.add(models);//
}
}
}
Adapter.java
package com.example.so;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import java.util.ArrayList;
public class Adapter extends BaseAdapter {
Context context;
ArrayList<Model> models = new ArrayList<>();
//Model[] models = new Model[];
LayoutInflater inflater;
public Adapter(Context context) {
this.context=context;
}
public Adapter(Context context, ArrayList<Model> models) {
this.context = context;
this.models = models;
inflater = LayoutInflater.from(this.context);
}
@Override
public int getCount() {
return models.size();
}
@Override
public Object getItem(int position) {
return models.get(position);
}
@Override
public long getItemId(int position) {
return 0;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
View rootView = convertView;
if (rootView == null){
rootView = inflater.inflate(R.layout.list_item,parent,false);
holder = new ViewHolder();
holder.image = (ImageView)rootView.findViewById(R.id.imageUrl);
holder.title = (TextView)rootView.findViewById(R.id.title);
rootView.setTag(holder);
}else {
holder = (ViewHolder)rootView.getTag();
}
Model model = (Model) getItem(position);
holder.image.setImageResource(Integer.parseInt(model.getImageUrl()));
return rootView;
}
class ViewHolder{
ImageView image;
TextView title;
}
public void add(Model model){
models.add(model);
}
}
Model.java
package com.example.so;
public class Model {
private String title;
private String imageUrl;
public Model() {
}
public Model(String title, String imageUrl) {
this.title = title;
this.imageUrl = imageUrl;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getImageUrl() {
return imageUrl;
}
public void setImageUrl(String imageUrl) {
this.imageUrl = imageUrl;
}
}
DataContract.java
package com.example.so.data;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.net.Uri;
import android.provider.BaseColumns;
public class DataContract {
public static final String CONTENT_AUTHORITY = "com.example.so";
public static final Uri BASE_CONTENT_URI = Uri.parse("content://" + CONTENT_AUTHORITY);
public static final class DataEntry implements BaseColumns {
// table name
public static final String TABLE_DATA = "data";
public static final String _ID = "_id";
public static final String COLUMN_TITLE = "title";
public static final String COLUMN_IMAGE_URL = "imageUrl";
// create content uri
public static final Uri CONTENT_URI = BASE_CONTENT_URI.buildUpon()
.appendPath(TABLE_DATA).build();
// create cursor of base type directory for multiple entries
public static final String CONTENT_DIR_TYPE =
ContentResolver.CURSOR_DIR_BASE_TYPE + "/" + CONTENT_AUTHORITY + "/" + TABLE_DATA;
// for building URIs on insertion
public static Uri buildDetailsUri(long id){
return ContentUris.withAppendedId(CONTENT_URI, id);
}
}
}
DataDbHelper.java
package com.example.so.data;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
public class DataDbHelper extends SQLiteOpenHelper{
public static final String LOG_TAG = com.example.so.data.DataDbHelper.class.getSimpleName();
//name & version
private static final String DATABASE_NAME = "delhiData.db";
private static final int DATABASE_VERSION = 1;
public DataDbHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
final String SQL_CREATE_DELHI_DATA_TABLE = "CREATE TABLE "+
DataContract.DataEntry.TABLE_DATA + "(" +
DataContract.DataEntry._ID+
" INTEGER PRIMARY KEY AUTOINCREMENT, " +
DataContract.DataEntry.COLUMN_TITLE+
" TEXT NOT NULL, " +
DataContract.DataEntry.COLUMN_IMAGE_URL+
" TEXT NOT NULL" +
");";
db.execSQL(SQL_CREATE_DELHI_DATA_TABLE);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Log.w(LOG_TAG, "Upgrading database from version " + oldVersion + " to " +
newVersion + ". OLD DATA WILL BE DESTROYED");
// Drop the table
db.execSQL("DROP TABLE IF EXISTS " + DataContract.DataEntry.TABLE_DATA);
db.execSQL("DELETE FROM SQLITE_SEQUENCE WHERE NAME = '" +
DataContract.DataEntry.TABLE_DATA + "'");
// re-create database
onCreate(db);
}
}
DataProvider.java
package com.example.so.data;
import android.content.ContentProvider;
import android.content.ContentValues;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;
import android.support.annotation.Nullable;
import android.util.Log;
public class DataProvider extends ContentProvider {
private static final String LOG_TAG = com.example.so.data.DataProvider.class.getSimpleName();
private static final UriMatcher sUriMatcher = buildUriMatcher();
private DataDbHelper dataDbHelper;
// Codes for the UriMatcher //////
private static final int DELHI = 100;
private static UriMatcher buildUriMatcher() {
// Build a UriMatcher by adding a specific code to return based on a match
// It's common to use NO_MATCH as the code for this case.
final UriMatcher matcher = new UriMatcher(UriMatcher.NO_MATCH);
final String authority = DataContract.CONTENT_AUTHORITY;
return null;
}
@Override
public boolean onCreate() {
dataDbHelper = new DataDbHelper(getContext());
return true;
}
@Nullable
@Override
public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) {
Cursor cursor = dataDbHelper.getReadableDatabase().query(
DataContract.DataEntry.TABLE_DATA,
projection,
selection,
selectionArgs,
null,
null,
sortOrder
);
return cursor;
}
@Nullable
@Override
public String getType(Uri uri) {
final int match = sUriMatcher.match(uri);
switch (match){
case DELHI:
return DataContract.DataEntry.CONTENT_DIR_TYPE;
default:{
throw new UnsupportedOperationException("Unknown uri: " + uri);
}
}
}
@Nullable
@Override
public Uri insert(Uri uri, ContentValues values) {
final SQLiteDatabase database = dataDbHelper.getWritableDatabase();
Uri returnUri;
Log.d(LOG_TAG,"in the insert method");
long _id = database.insert(DataContract.DataEntry.TABLE_DATA, null,values);
Log.d(LOG_TAG,"after inserting ");
// insert unless it is already contained in the databaseWeatherContract.LocationEntry.CONTENT_URI
if (_id > 0) {
returnUri = DataContract.DataEntry.buildDetailsUri(_id);
} else {
throw new android.database.SQLException("Failed to insert row into: " + uri);
}
getContext().getContentResolver().notifyChange(uri, null);
return returnUri;
}
@Override
public int delete(Uri uri, String selection, String[] selectionArgs) {
return 0;
}
@Override
public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {
return 0;
}
}
答案 0 :(得分:0)
我更新了MainActivity.java -
while(cursor.moveToNext()){
Model models = new Model();
models.setTitle(cursor.getString(1));
models.setImageUrl(cursor.getString(2));
Log.d(LOG_TAG, "Title here " + models.getTitle());
Log.d(LOG_TAG,"Image url here "+models.getImageUrl());
adapter.add(models);
}
adapter.notifyDataSetChanged();
<强> Adapter.java 强>
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
View rootView = convertView;
if (rootView == null){
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
rootView = inflater.inflate(R.layout.list_item,parent,false);
holder = new ViewHolder();
holder.image = (ImageView)rootView.findViewById(R.id.imageUrl);
holder.title = (TextView)rootView.findViewById(R.id.title);
rootView.setTag(holder);
}else {
holder = (ViewHolder)rootView.getTag();
}
Model model = (Model) getItem(position);
try {
holder.title.setText(model.getTitle());
//holder.image.setImageResource(Integer.parseInt(model.getImageUrl()));
Picasso.with(context)
.load(models.get(position).getImageUrl())
.into(holder.image);
holder.image.setAdjustViewBounds(true);
}catch (Exception e){
Log.e(LOG_TAG," Error here "+e);
}
return rootView;
}
现在我可以获取标题但仍然无法获取图片。请建议。