Я хочу передать массив в функцию 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)
Инициализируйте ваш список в 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 глобальным
РЕДАКТИРОВАТЬ: позвонить
SearchFriends()
в onCreateView ()
@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);
}
Вы не устанавливаете адаптер перед инициализацией adapterOwnEvents в вашем методе ParsJson.
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.