我正在和json合作。我解析了JSON,我可以在ListView上显示我的JSON(图像和文本)。现在我想在我的小部件中显示JSON的第一个项目的标题。
我成功创建了小部件,但我对JSON的第一个项目的标题有疑问。
这是我的代码:
public class AppWidget extends AppWidgetProvider {
public static String CLOCK_WIDGET_UPDATE = "CLOCK_WIDGET_UPDATE";
RemoteViews views;
int appWidgetId;
@Override
public void onReceive(Context context, Intent intent) {
super.onReceive(context, intent);
if (CLOCK_WIDGET_UPDATE.equals(intent.getAction())) {
Toast.makeText(context, "onReceiver()", Toast.LENGTH_LONG).show();
}
}
public void onUpdate(Context context, AppWidgetManager appWidgetManager,
int[] appWidgetIds) {
final int N = appWidgetIds.length;
for (int i = 0; i < N; i++) {
appWidgetId = appWidgetIds[i];
Intent intent = new Intent(context, MainActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(context, 0,
intent, 0);
views = new RemoteViews(context.getPackageName(),
R.layout.widget_demo);
String aa = (MainActivity.itemList.get(0)
.get(MainActivity.KEY_title)).toString();
views.setOnClickPendingIntent(R.id.widgetPic, pendingIntent);
views.setOnClickPendingIntent(R.id.widgetTitle, pendingIntent);
views.setOnClickPendingIntent(R.id.widgetDesc, pendingIntent);
views.setTextViewText(R.id.widgetDesc, aa);
views.setImageViewBitmap(
R.id.widgetPic,
((BitmapDrawable) context.getResources().getDrawable(
R.drawable.background)).getBitmap());
appWidgetManager.updateAppWidget(appWidgetId, views);
}
}
public void updateAppWidget(Context context,
AppWidgetManager appWidgetManager, int appWidgetId) {
RemoteViews updateViews = new RemoteViews(context.getPackageName(),
R.layout.widget_demo);
try {
} catch (Exception e) {
}
appWidgetManager.updateAppWidget(appWidgetId, updateViews);
}
}
BaseAdapter.java代码:
public class MyAdapter extends BaseAdapter {
Context mContext;
private ArrayList<HashMap<String, String>> data;
private static LayoutInflater inflater = null;
public ImageLoader imageLoader;
private int screenSize;
public MyAdapter(Context context, ArrayList<HashMap<String, String>> d,
int screenSize) {
this.mContext = context;
this.data = d;
this.screenSize = screenSize;
inflater = (LayoutInflater) mContext
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
imageLoader = new ImageLoader(context.getApplicationContext());
}
public int getCount() {
return data.size();
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
View vi = convertView;
if (convertView == null)
vi = inflater.inflate(R.layout.list_row, null);
TextView journal = (TextView) vi.findViewById(R.id.smalljournal);
TextView title = (TextView) vi.findViewById(R.id.smalltitle);
TextView description = (TextView) vi
.findViewById(R.id.smallDescription);
ImageView thumb_image = (ImageView) vi.findViewById(R.id.smallthumb);
TextView statId = (TextView) vi.findViewById(R.id.smallstatID);
TextView DateTime = (TextView) vi.findViewById(R.id.smallDateTime);
HashMap<String, String> itemList = new HashMap<String, String>();
itemList = data.get(position);
journal.setText(itemList.get(MainActivity.KEY_journal));
statId.setText(itemList.get(MainActivity.KEY_statID));
journal.setTypeface(MainActivity.tf2);
String titleString = itemList.get(MainActivity.KEY_title);
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
// coming date : 2014-02-03T18:45:00
String DateTimeTxt = itemList.get(MainActivity.KEY_pubDate).replace(
"T", " ");
// DateTimeTxt = date;
try {
Date _d = df.parse(DateTimeTxt);
SimpleDateFormat new_df = new SimpleDateFormat("dd.MM.yyyy");
String _s = new_df.format(_d);
DateTime.setText(_s);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (screenSize == Configuration.SCREENLAYOUT_SIZE_NORMAL)
description.setVisibility(View.INVISIBLE);
else
description.setVisibility(View.VISIBLE);
title.setText(titleString);
title.setTypeface(MainActivity.tf2);
description.setText(itemList.get(MainActivity.KEY_description));
description.setTypeface(MainActivity.tf2);
String url = itemList.get(MainActivity.KEY_image);
// url = url.replace("-c.jpg", ".jpg");
imageLoader.DisplayImage(url, thumb_image);
return vi;
}
}
MainActivity.java代码
public class MainActivity extends Activity {
public String URL = "********************";
public static String KEY_title = "title";
public static String KEY_description = "description";
public static String KEY_image = "image";
public static String KEY_journal = "journal";
public static String KEY_JournalID = "JournalID";
public static String KEY_pubDate = "pubDate";
public static String KEY_statID = "statID";
public JSONArray jsonarray;
public ListView list;
public JSONParser jsonparser;
static MyAdapter adapter;
ProgressDialog pDialog, pDialog1;
static String fontPath2 = "font.ttf";
public static Typeface tf2;
public static ArrayList<HashMap<String, String>> itemList = new ArrayList<HashMap<String, String>>();
public ImageLoader imageLoader;
static final int DIALOG_ERROR_CONNECTION = 1;
public static String dateTime;
private ArrayList<Content> contents = new ArrayList<Content>();
public ImageView image;
public EditText searchInput;
public LinearLayout mainLayout, SlideLayout;
public TransparentProgressDialog pd;
public Tools tools;
public static boolean CheckListview = true;
private int screenSize;
int windowWidth;
public LoadDataAllChanelsToServer loadData;
public TextView journal, tittle, description, smalllink, DateTime,
smallstatID;
private ConnectionDetector cd;
AlertDialogManager alert = new AlertDialogManager();
Writer writer;
public File yourFile;
View menu_Slide;
@SuppressLint("CutPasteId")
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.main);
screenSize = getResources().getConfiguration().screenLayout
& Configuration.SCREENLAYOUT_SIZE_MASK;
SlideLayout = (LinearLayout) findViewById(R.id.SlideLayout);
list = (ListView) findViewById(R.id.listView1);
cd = new ConnectionDetector(getApplicationContext());
adapter = new MyAdapter(MainActivity.this, itemList, screenSize);
Thread.setDefaultUncaughtExceptionHandler(new UnCaughtException(this,
this));
loadData = new LoadDataAllChanelsToServer();
menu_Slide = (findViewById(R.id.menu_button));
image = (ImageView) findViewById(R.id.imageView1);
searchInput = (EditText) findViewById(R.id.input_search_query);
tf2 = Typeface.createFromAsset(getAssets(), fontPath2);
pd = new TransparentProgressDialog(this, R.drawable.loader);
list.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
journal = (TextView) view.findViewById(R.id.smalljournal);
tittle = (TextView) view.findViewById(R.id.smalltitle);
description = (TextView) view
.findViewById(R.id.smallDescription);
smalllink = (TextView) view.findViewById(R.id.smalllink);
DateTime = (TextView) view.findViewById(R.id.smallDateTime);
smallstatID = (TextView) view.findViewById(R.id.smallstatID);
String Stringjournal = journal.getText().toString();
String Stringtittle = tittle.getText().toString();
String Stringdescription = description.getText().toString();
String Stringlink = smalllink.getText().toString();
String StringdateTime = DateTime.getText().toString();
String StringstatID = smallstatID.getText().toString();
HideKeyBoadr();
Intent in = new Intent(MainActivity.this, Result.class);
in.putExtra("KEY_journal", Stringjournal);
in.putExtra("KEY_title", Stringtittle);
in.putExtra("KEY_description", Stringdescription);
in.putExtra("KEY_link", Stringlink);
in.putExtra("KEY_pubDate", StringdateTime);
in.putExtra("KEY_statID", StringstatID);
String url = itemList.get(position).get(MainActivity.KEY_image);
if (!cd.isConnectingToInternet()) {
in.putExtra("Bitmap", url);
}
else {
if (url.endsWith("-c.jpg"))
url = url.replace("-c.jpg", ".jpg");
in.putExtra("Bitmap", url);
}
in.putExtra("Bitmap", url);
startActivity(in);
overridePendingTransition(R.anim.trans_left_in,
R.anim.trans_left_out);
}
});
if (!cd.isConnectingToInternet()) {
return;
} else {
loadData.execute();
}
}
public void HideKeyBoadr() {
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(searchInput.getWindowToken(), 0);
}
private class LoadDataAllChanelsToServer extends
AsyncTask<String, Integer, String> {
@Override
protected void onPreExecute() {
pd.show();
}
@Override
protected String doInBackground(String... urls) {
jsonparser = new JSONParser();
JSONObject jsonobject = jsonparser.getJSONfromURL(URL);
try {
jsonarray = jsonobject.getJSONArray("data");
for (int i = 0; i < jsonarray.length(); i++) {
jsonobject = jsonarray.getJSONObject(i);
HashMap<String, String> map = new HashMap<String, String>();
map.put("journal", jsonobject.getString(KEY_journal));
map.put("image", jsonobject.getString(KEY_image));
map.put("title", jsonobject.getString(KEY_title));
map.put("description",
jsonobject.getString(KEY_description));
map.put("JournalID", jsonobject.getString(KEY_JournalID));
map.put("pubDate", jsonobject.getString(KEY_pubDate));
map.put("statID", jsonobject.getString(KEY_statID));
Content cont = new Content(jsonobject.getString("journal"),
jsonobject.getString("image"),
jsonobject.getString("title"),
jsonobject.getString("pubDate"),
jsonobject.getString("description"),
jsonobject.getString("JournalID"),
jsonobject.getString("statID"));
contents.add(cont);
itemList.add(map);
dateTime = itemList.get(itemList.size() - 1).get(
KEY_pubDate);
}
} catch (JSONException e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return itemList.toString();
}
@Override
protected void onPostExecute(String result) {
try {
if (pd != null) {
pd.dismiss();
}
} catch (Exception e) {
}
try {
adapter = new MyAdapter(MainActivity.this, itemList, screenSize);
list.setAdapter(adapter);
} catch (NullPointerException e) {
e.printStackTrace();
}
}
}
@Override
public void onBackPressed() {
createDialog();
}
private void createDialog() {
AlertDialog.Builder alertDlg = new AlertDialog.Builder(this);
alertDlg.setMessage("Are you sure you want to exit?");
alertDlg.setCancelable(false);
alertDlg.setPositiveButton("Yes",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
MainActivity.super.onBackPressed();
}
}
);
alertDlg.setNegativeButton("No", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
}
});
alertDlg.create().show();
}
}
我的问题是:当我点击我得到的小部件时
indexofboundexception(无效索引0,大小为1)
有什么问题?
答案 0 :(得分:0)
我的问题是:当我点击我得到的小部件时
indexofboundexception(无效索引0,大小为1)
有什么问题?
要查看的代码太多了。请缩小您的问题并显示问题的确切位置。
使用调试器逐步执行代码。 1,确定问题发生的确切行。接下来,使用调试器检查该点的变量。错误是超出范围的索引,因此您访问的列表中的点大于列表的大小。