我正在尝试在Android应用程序中查询来自MySQL的数据,并将数据作为ArrayList返回。但是当我得到它的大小时,ArrayList是空的,就在return语句的上方。以下是我的代码。
public List<Application> getData(final Context cntx, final long startHere, String url) {
final List<Application> apps = new ArrayList<Application>();
AsyncHttpClient client = new AsyncHttpClient();
RequestParams params = new RequestParams();
params.put("startHere", startHere);
client.post(url,
params, new AsyncHttpResponseHandler() {
@Override
public void onFailure(int a0, Header[] a1, byte[] a2, Throwable a3) {
Toast.makeText(cntx,"Some Err", Toast.LENGTH_LONG).show();
}
@Override
public void onSuccess(int statusCode, Header[] header,
byte[] response) {
String s = new String(response);
try {
JSONArray aJson = new JSONArray(s);
for(int i=0; i<aJson.length(); i++) {
JSONObject json = aJson.getJSONObject(i);
Application app = new Application();
app.setTitle(json.getString("app_title"));
app.setIcon(json.getString("icon"));
// works here as expected, returns values > 0
Log.i("Debug 1", apps.size()+"");
apps.add(app);
}
Toast.makeText(cntx, apps.size()+"", Toast.LENGTH_LONG).show();
} catch (JSONException e) {
Toast.makeText(cntx, "Invalid JSON", Toast.LENGTH_LONG).show();
}
}
});
//Does not work at this point, returns a value of 0!
Log.i("Debug 2", apps.size()+"");
return apps;
}
答案 0 :(得分:-1)
试试这个:
public class HomeFragment extends Fragment {
private ListView mListView;
private ListViewNewsAdapter listViewNewsAdapter;
private ArrayList<ListViewNewsItem> listViewNewsItems;
private ImageView Right ;
private ImageView Left ;
private String NewsBody[] ;
private TimerTask mTimerTask;
private Timer timer = new Timer();
private boolean Switch = true ;
private final Handler timerHandler = new Handler();
private JSONParser jsonParser = new JSONParser();
private String READNEWS_URL =
"YOUR WEBSITE";
public HomeFragment() {
// Required empty public constructor
}
@TargetApi(Build.VERSION_CODES.JELLY_BEAN)
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_home, container, false);
mListView = (ListView) rootView.findViewById(R.id.mlv);
Right = (ImageView) rootView.findViewById(R.id.adv_right) ;
Left = (ImageView) rootView.findViewById(R.id.adv_left) ;
Animation LeftSideAnimation = AnimationUtils.loadAnimation(getActivity(), R.anim.blink);
Right.startAnimation(LeftSideAnimation);
Left.startAnimation(LeftSideAnimation);
Left.setBackground(getResources().getDrawable(R.drawable.facebook_icon));
Right.setBackground(getResources().getDrawable(R.drawable.home_icon));
new GetNewsTask().execute();
mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
Show_News_Body Show_News_Body = new Show_News_Body(getActivity(), NewsBody[position]);
Show_News_Body.show();
}
});
return rootView;
}
private class GetNewsTask extends AsyncTask<Void, Void, Boolean>
{
private ProgressDialog mProgressDialog;
private JSONObject jsonObjectResult = null;
private String error;
@Override
protected void onPreExecute()
{
super.onPreExecute();
listViewNewsItems = new ArrayList<ListViewNewsItem>();
mProgressDialog = ProgressDialog.show(getActivity(),
"Processing...", "Get last news", false, false);
}
@Override
protected Boolean doInBackground(Void... params)
{
jsonObjectResult = jsonParser.makeHttpRequest(READNEWS_URL, null);
if (jsonObjectResult == null)
{
error = "Error in the connection";
return false;
}
try
{
if (jsonObjectResult.getInt("success") == 1)
{
JSONArray jsonArray = jsonObjectResult.getJSONArray("posts");
NewsBody = new String[jsonArray.length()];
for (int i = 0; i < jsonArray.length(); i++)
{
JSONObject news = jsonArray.getJSONObject(i);
ListViewNewsItem listViewNewsItem = new ListViewNewsItem
(
news.getString("title"),
news.getString("type"),
news.getString("image_link"),
news.getString("news_body")
);
listViewNewsItems.add(listViewNewsItem);
NewsBody[i]= listViewNewsItem.getNews_body();
}
return true;
}
else
error = jsonObjectResult.getString("message");
}
catch (Exception ex)
{
}
return false;
}
@Override
protected void onPostExecute(Boolean aBoolean)
{
super.onPostExecute(aBoolean);
mProgressDialog.dismiss();
if (aBoolean)
{
listViewNewsAdapter = new ListViewNewsAdapter(getActivity(),
listViewNewsItems);
mListView.setAdapter(listViewNewsAdapter);
}
else
Toast.makeText(getActivity(), error, Toast.LENGTH_LONG).show();
}
}
}
这是我的布局包含这样的listView:
<ListView
android:layout_marginTop="2dp"
android:layout_below="@+id/line_adv"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background = "@android:color/transparent"
android:padding="3dp"
android:dividerHeight="1dp"
android:id="@+id/mlv"></ListView>
以及另外两个类:
public class ListViewNewsAdapter extends ArrayAdapter<ListViewNewsItem> {
private Context mContext;
private ArrayList<ListViewNewsItem> mData;
public ListViewNewsAdapter (Context mContext, ArrayList<ListViewNewsItem> mData) {
super(mContext, R.layout.data_shape, mData);
this.mContext = mContext;
this.mData = mData;
}
@Override
public int getCount() {
return mData.size();
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(final int position, View convertView, ViewGroup parent)
{
if (convertView == null)
{
LayoutInflater mInflater = (LayoutInflater)
mContext.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
convertView = mInflater.inflate(R.layout.data_shape, null);
}
TextView m_title = (TextView) convertView.findViewById(R.id.m_title);
m_title.setText(mData.get(position).getM_title());
TextView m_type = (TextView) convertView.findViewById(R.id.m_type);
m_type.setText(mData.get(position).getM_type());
UrlImageViewHelper.setUrlDrawable((ImageView) convertView.findViewById(R.id.NewsImage),
mData.get(position).getImage_link()
, R.drawable.ic_launcher, 60000);
return convertView;
}
和这一个:
public class ListViewNewsItem {
private String m_title ;
private String m_type;
private String image_link ;
private String news_body ;
public ListViewNewsItem( String m_title, String m_type,String image_link, String news_body ) {
this.m_title = m_title;
this.m_type = m_type ;
this.image_link = image_link ;
this.news_body = news_body ;
}
public String getNews_body() {
return news_body;
}
public void setNews_body(String news_body) {
this.news_body = news_body;
}
public String getImage_link() {
return image_link;
}
public void setImage_link(String image_link) {
this.image_link = image_link;
}
public void setM_title(String m_title) {
this.m_title = m_title;
}
public String getM_title() {
return m_title;
}
public void setM_type(String m_type) {
this.m_type = m_type;
}
public String getM_type() {
return m_type;
}
}
Data_Shape布局如下:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_margin="5dp"
android:paddingTop="10dp"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<LinearLayout
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="2"
android:orientation="vertical">
<TextView
android:layout_margin="5dp"
android:layout_width="match_parent"
android:layout_weight="1"
android:layout_height="0dp"
android:text="The Title Is Here"
android:textDirection="rtl"
android:textColor="#173966"
android:textSize="15dp"
android:id="@+id/m_title"/>
<TextView
android:layout_height="wrap_content"
android:id="@+id/m_type"
android:layout_marginLeft="5dp"
android:textSize="10dp"
android:layout_width="match_parent"
android:text="HERE IS THE TEXT"
android:textColor="@android:color/black"/>
</LinearLayout>
<ImageView
android:layout_width="70dp"
android:layout_height="70dp"
android:id="@+id/NewsImage"/>
</LinearLayout>
</LinearLayout>
请远离您的MYSQL表应包含以下列: 标题,类型,Image_link和正文。