Я наклеил свой код ниже и был бы признателен, если бы кто-то помог мне с этим справиться. Когда я запускаю свою деятельность, список должен обновляться внутри моего приложения. Однако я не смог получить никаких данных. Когда я регистрирую первый Я получаю [] и ничего больше. Если я проверю размер, он возвращается как .Извлечь данные с помощью Gson
* Я ожидаю, чтобы получить идентификатор, имя и размер и поместить их в TextViews в ListView.
Когда я получить доступ к моей URL строки из моего браузера, я получаю это:
{ "begin":
[
{"id":1,"name":"1","size":2},
{"id":2,"name":"2","size":2}],
"end":
[
{"id":1,"name":"1","size":2},
{"id":2,"name":"2","size":2}
]
}
модели/Main.java
import android.content.Context;
import ...Cement;
import ...utils.NetworkUtilities;
import ...utils.ServerErrorException;
import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import java.util.ArrayList;
import java.util.List;
public class Main {
private String id;
private String name;
private static List<Main> first;
public Main() {}
public String getId() {
return id;
}
public String getName() {
return name;
}
/**
* @return array of Main.
* @throws JSONException
*/
public static List<Main> updateMain(Context context) throws JSONException, ServerErrorException {
List<NameValuePair> params = new ArrayList<NameValuePair>();
if(Member.session(context) != null) {
params(new BasicNameValuePair(Cement.ACCESS_CODE, Member.session(context).getAccessCode()));
} else {
return null;
}
String URL = Cement.BASE_URL + Cement.MAIN_URI;
String jsonString = NetworkUtilities.SendHttpGet(URL, params);
if (jsonString == null) return main(context);
JSONParse parser = new JsonParser();
JSONObject jsonObject = parser.parse(jsonString).getAsJsonObject();
if (jsonObject != null && jsonObject.get("begin") != null) {
Gson gson = new Gson();
for (JSONElement mainObject : jsonObject.get("begin").getAsJsonArray()) {
Main spot = gson.fromJson(mainObject.getAsJsonObject().get("begin"), Main.class);
Main.setSpot(context,spot);
}
} else {
// Server error exception...
}
return first(context);
}
public static List<Main> first(Context context) {
if (first == null) {
try {
first = new ArrayList<Main>();
} finally {
if (first == null) {
first = new ArrayList<Main>();
}
}
}
return first;
}
public static void setMain(Context context, Main second) {
Main previous = find(context, second.getId());
if (previous != null) {
first.set(first.indexOf(previous), second);
} else {
first = first(context);
first.add(second);
}
}
public static Main find(Context context, String id) {
for(Main first : first(context)) {
if(second.getId().equals(id)) {
return second;
}
}
return null;
}
}
деятельность/Home.java
public class Home extends Fragment {
private GetMainListTask mGetMainListTask = null;
private ListView mMainListView;
private MainListAdapter mMainListAdapter;
private List<Main> mFirst;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment, container, false);
mFirst = First.first(mContext);
mMainListView = (ListView) rootView.findViewById(R.id.ListView);
mMainListAdapter = new MainListAdapter();
mMainListView.setAdapter(mMainListAdapter);
getFirst(true);
return rootView;
}
public void getFirst(Boolean showProgressDialog){
if (showProgressDialog) {
mProgressDialog = ProgressDialog.show(mContext, "", "Loading...", true);
}
mGetMainListTask = new GetMainListTask();
mGetMainListTask.execute();
}
public class GetMainListTask extends AsyncTask<Void, Void, List<Main>> {
private List<Exception> exceptions = new ArrayList<Exception>();
@Override
protected List<Main> doInBackground(Void... params) {
try {
return Main.updateMain(Home.this.getApplicationContext());
} catch (ServerErrorException e) {
exceptions.add(e);
return null;
} catch (JSONException e) {
exceptions.add(e);
return null;
} catch (Exception e) {
return null;
}
}
@Override
protected void onPostExecute(final List<Main> first) {
for (Exception e : exceptions) {
// Error...
}
if(first == null && exceptions.isEmpty()) {
if (getApplicationContext() != null) {
// Error...
}
}
onGetMainResult(first);
}
}
public void onGetMainResult(List<Main> first) {
boolean worked = (first != null && first.size() != 0);
mGetMainListTask = null;
if (worked) {
mFirst = first;
if (mMainListAdapter != null) {
mMainListAdapter.notifyDataSetChanged();
}
}
}
public class MainListAdapter extends BaseAdapter {
@Override
public int getCount() {
return mFirst.size();
}
@Override
public Object getItem(int i) {
return mFirst.get(i);
}
@Override
public long getItemId(int i) {
return i;
}
@Override
public View getView(int i, View convertView, ViewGroup parent) {
View view = View.inflate(getApplicationContext(), R.layout.list, null);
final Main first = mFirst.get(i);
if (mContext != null && first != null) {
// Do stuff...
}
return view;
}
}
Вы действительно не дали нам определение класса для Main.java. – Deadron
Можете ли вы дать понять, что вы ожидаете и что получаете? – webdev
Я обновил свой вопрос. Дайте мне знать, если вам все еще нужна дополнительная информация. – user2997853