我想将一个数组传递给doInbackground()函数并从中获取结果。实际上我不知道如何将数组传递给PhP文件以及如何在数据库中搜索它。如果您不想帮助不要让它复制或让其他人不帮助我,请。 这是我试过的代码。
首先我从服务器数据库中获取值并解析它并希望将其存储在数组中。 整个碎片代码
public class eventsFragment extends Fragment {
ImageView imageView;
ListView listEvents;
private TextView noevents;
SessionManager session;
String JSONString, json_string;
ArrayList<String> json_string1;
JSONObject jsonObject;
AdapterOwnEvents adapterOwnEvents;
JSONArray jsonArray;
public eventsFragment() {
// Required empty public constructor
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_news_feed, container, false);
listEvents = (ListView) view.findViewById(R.id.listEvents1);
noevents = (TextView) view.findViewById(R.id.noEvents);
return view;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
SearchFriends();
}
public void SearchFriends() {
session = new SessionManager(getActivity().getApplicationContext());
HashMap<String, String> user = session.getUserDetails();
String user_id = user.get(SessionManager.KEY_ID);
new BackgroundSearch().execute(user_id);
}
class BackgroundSearch extends AsyncTask<String, Void, String> {
String search_url;
@Override
protected void onPreExecute() {
search_url = "http://www.example.com/friendList.php";
}
@Override
protected String doInBackground(String... params) {
String user_id = params[0];
try {
URL url = new URL(search_url);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setDoOutput(true);
OutputStream outputStream = httpURLConnection.getOutputStream();
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
String data = URLEncoder.encode("user_id", "UTF-8") + "=" + URLEncoder.encode(user_id, "UTF-8");
bufferedWriter.write(data);
bufferedWriter.flush();
bufferedWriter.close();
outputStream.close();
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
StringBuilder stringBuilder = new StringBuilder();
while ((JSONString = bufferedReader.readLine()) != null) {
stringBuilder.append(JSONString).append("\n");
}
bufferedReader.close();
inputStream.close();
httpURLConnection.disconnect();
return stringBuilder.toString().trim();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
@Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
}
@Override
protected void onPostExecute(String result) {
json_string = result;
try {
jsonObject = new JSONObject(json_string);
jsonArray = jsonObject.getJSONArray("server_response");
int count = 0;
String friend_id;
ArrayList<String> array1 = new ArrayList<String>();
while (count < jsonArray.length()) {
JSONObject JO = jsonArray.getJSONObject(count);
friend_id = JO.getString("friend_id");
array1.add(friend_id);
count++;
}
new BackgroundSearchEvents().execute(array1);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
class BackgroundSearchEvents extends AsyncTask<ArrayList<String>, Void, String> {
String search_url;
@Override
protected void onPreExecute() {
search_url = "http://www.example.com/eventList.php";
}
@SafeVarargs
@Override
protected final String doInBackground(ArrayList<String>... passing) {
// ArrayList<String> result = new ArrayList<String>();
ArrayList<String> passed = passing[0];
try {
URL url = new URL(search_url);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setDoOutput(true);
OutputStream outputStream = httpURLConnection.getOutputStream();
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
// int count = 0;
String user_id;
for (int count = 0 ; count<passing.length; count++) {
user_id=passed.get(count);
String data = URLEncoder.encode("user_id", "UTF-8") + "=" + URLEncoder.encode(String.valueOf(user_id), "UTF-8");
bufferedWriter.write(data);
bufferedWriter.flush();
bufferedWriter.close();
outputStream.close();
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
StringBuilder stringBuilder = new StringBuilder();
while ((JSONString = bufferedReader.readLine()) != null) {
stringBuilder.append(JSONString).append("\n");
}
bufferedReader.close();
inputStream.close();
httpURLConnection.disconnect();
return stringBuilder.toString().trim();
// count++;
}
// return result;
//return stringBuilder.toString().trim();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
@Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
}
@Override
protected void onPostExecute(String result) {
json_string = result;
ParseJson();
}
}
public void ParseJson() {
if (json_string == null) {
Toast.makeText(getActivity(), "No Events", Toast.LENGTH_LONG).show();
} else {
// listEvents.setAdapter(adapterOwnEvents);
adapterOwnEvents = new AdapterOwnEvents(getActivity(), R.layout.own_event_list);
listEvents.setAdapter(adapterOwnEvents);
try {
jsonObject = new JSONObject(json_string);
jsonArray = jsonObject.getJSONArray("server_response");
int count = 0;
String event_id, event, event_type, date, image, friend_id;
while (count < jsonArray.length()) {
JSONObject JO = jsonArray.getJSONObject(count);
event_id = JO.getString("event_id");
event = JO.getString("event");
date = JO.getString("date");
event_type = JO.getString("event_type");
friend_id = JO.getString("user_id");
image = ("http://example.com/uploads/" + friend_id + ".png");
Own_EventListElements own_eventListElements = new Own_EventListElements(event_id, event, event_type, date, image);
adapterOwnEvents.add(own_eventListElements);
listEvents.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Own_EventListElements eventsElements = (Own_EventListElements) adapterOwnEvents.getItem(position);
Intent i = new Intent(getActivity(), SendGreetings.class);
startActivity(i);
}
});
count++;
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}
这是我的适配器
public class AdapterOwnEvents extends ArrayAdapter {
List list=new ArrayList();
public AdapterOwnEvents(Context context, int resource) {
super(context, resource);
}
public void add(Own_EventListElements object) {
super.add(object);
list.add(object);
}
@Override
public int getCount() {
return list.size();
}
@Override
public Object getItem(int position) {
return list.get(position);
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View view;
view=convertView;
ElementsHolder elemetsHolder=new ElementsHolder();
if (view==null){
LayoutInflater layoutInflater = (LayoutInflater)this.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = layoutInflater.inflate(R.layout.own_event_list,parent,false);
elemetsHolder.tx_Event=(TextView) view.findViewById(R.id.event_name);
elemetsHolder.tx_Date=(TextView) view.findViewById(R.id.event_date);
view.setTag(elemetsHolder);
}
else
{
elemetsHolder=(ElementsHolder) view.getTag();
}
Own_EventListElements own_eventListElements=(Own_EventListElements)this.getItem(position);
elemetsHolder.tx_Event.setText(own_eventListElements.getEvent());
elemetsHolder.tx_Date.setText(own_eventListElements.getDate());
return view;
}
static class ElementsHolder
{
TextView tx_Event,tx_Date;
}
}
这是php文件
$con = mysqli_connect($server_name, $mysql_user, $mysql_pass, $db_name);
$user_id = $_POST["user_id"];
$sql_query = "select event_id, event, event_type, date, user_id from events where user_id like '$user_id'";
$result = mysqli_query($con,$sql_query);
$response = array();
while($row = mysqli_fetch_array($result))
{
array_push($response,array("event_id"=>$row[0],"event"=>$row[1],"event_type"=>$row[2],"date"=>$row[3],"user_id"=>$row[4]));
}
echo json_encode(array("server_response"=>$response));
mysqli_close($con);
但它给了我错误
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ListView.setAdapter(android.widget.ListAdapter)' on a null object reference
请帮帮我。提前谢谢
编辑: 这是我初始化这个
View view = inflater.inflate(R.layout.fragment_news_feed, container, false);
ListView listEvents = (ListView) view.findViewById(R.id.listEvents1);
return view;
LOGCAT
FATAL EXCEPTION: main
05-14 11:37:00.733 17664-17664/com.example.bebo E/AndroidRuntime: Process: com.example.bebo, PID: 17664
05-14 11:37:00.733 17664-17664/com.example.bebo E/AndroidRuntime: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ListView.setAdapter(android.widget.ListAdapter)' on a null object reference
05-14 11:37:00.733 17664-17664/com.example.bebo E/AndroidRuntime: at com.example.bebo.eventsFragment.ParseJson(eventsFragment.java:230)
05-14 11:37:00.733 17664-17664/com.example.bebo E/AndroidRuntime: at com.example.bebo.eventsFragment$BackgroundSearchEvents.onPostExecute(eventsFragment.java:221)
05-14 11:37:00.733 17664-17664/com.example.bebo E/AndroidRuntime: at com.example.bebo.eventsFragment$BackgroundSearchEvents.onPostExecute(eventsFragment.java:155)
05-14 11:37:00.733 17664-17664/com.example.bebo E/AndroidRuntime: at android.os.AsyncTask.finish(AsyncTask.java:636)
05-14 11:37:00.733 17664-17664/com.example.bebo E/AndroidRuntime: at android.os.AsyncTask.access$500(AsyncTask.java:177)
05-14 11:37:00.733 17664-17664/com.example.bebo E/AndroidRuntime: at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:653)
05-14 11:37:00.733 17664-17664/com.example.bebo E/AndroidRuntime: at android.os.Handler.dispatchMessage(Handler.java:111)
05-14 11:37:00.733 17664-17664/com.example.bebo E/AndroidRuntime: at android.os.Looper.loop(Looper.java:194)
05-14 11:37:00.733 17664-17664/com.example.bebo E/AndroidRuntime: at android.app.ActivityThread.main(ActivityThread.java:5653)
05-14 11:37:00.733 17664-17664/com.example.bebo E/AndroidRuntime: at java.lang.reflect.Method.invoke(Native Method)
05-14 11:37:00.733 17664-17664/com.example.bebo E/AndroidRuntime: at java.lang.reflect.Method.invoke(Method.java:372)
05-14 11:37:00.733 17664-17664/com.example.bebo E/AndroidRuntime: at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:960)
05-14 11:37:00.733 17664-17664/com.example.bebo E/AndroidRuntime: at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)
答案 0 :(得分:0)
在ParsJson方法初始化adapterOwnEvents之前,你没有设置适配器。
adapterOwnEvents = new AdapterOwnEvents(getActivity(), R.layout.own_event_list);
listEvents.setAdapter(adapterOwnEvents);
而不是
listEvents.setAdapter(adapterOwnEvents);
adapterOwnEvents = new AdapterOwnEvents(getActivity(), R.layout.own_event_list);
listEvents.setAdapter(adapterOwnEvents);
我建议您使用Gson库来解析json。
答案 1 :(得分:0)
在 onCreate():
中初始化您的列表listEvents = (ListView)findViewById(R.id.list_id);
更改 ParseJson()方法,如下所示:
public void ParseJson() {
if (json_string == null) {
Toast.makeText(getActivity(), "No Events", Toast.LENGTH_LONG).show();
} else {
adapterOwnEvents = new AdapterOwnEvents(getActivity(), R.layout.own_event_list);
listEvents.setAdapter(adapterOwnEvents);
try {
jsonObject = new JSONObject(json_string);
jsonArray = jsonObject.getJSONArray("server_response");
int count = 0;
String event_id, event, event_type, date, image, friend_id;
while (count < jsonArray.length()) {
JSONObject JO = jsonArray.getJSONObject(count);
event_id = JO.getString("event_id");
event = JO.getString("event");
date = JO.getString("date");
event_type = JO.getString("event_type");
friend_id = JO.getString("user_id");
image = ("http://example.com/uploads/" + friend_id + ".png");
Own_EventListElements own_eventListElements = new Own_EventListElements(event_id, event, event_type, date, image);
adapterOwnEvents.add(own_eventListElements);
listEvents.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Own_EventListElements eventsElements = (Own_EventListElements) adapterOwnEvents.getItem(position);
Intent i = new Intent(getActivity(), SendGreetings.class);
startActivity(i);
}
});
count++;
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
尝试制作ListView Global
编辑:在 onCreateView()
中致电SearchFriends()
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_news_feed, container, false);
listEvents = (ListView) view.findViewById(R.id.listEvents1);
noevents = (TextView) view.findViewById(R.id.noEvents);
SearchFriends();
return view;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}