안드로이드에서 php를 이용해 값을 가져오는 것이 안됩니다.
본문
이 코드일때는 실행이 되고 값이 가져와지는데
<?php
$con = mysqli_connect("localhost", "11", "11", "11");
if (!$con)
{
echo "MySQL 접속 에러 : ";
echo mysqli_connect_error();
exit();
}
mysqli_set_charset($con,"utf8");
$sql = "SELECT * FROM answer";
$result = mysqli_query($con, $sql);
$data = array();
if($result){
while($row=mysqli_fetch_array($result)){
array_push($data,
array('a_id'=>$row[0],
'a_title'=>$row[1],
'a_content'=>$row[2],
'a_completed'=>$row[3]
));
}
echo "<pre>"; print_r($data); echo '</pre>';
}
else{
echo "SQL문 처리중 에러 발생 : ";
echo mysqli_error($con);
}
mysqli_close($con);
?>
이 코드일때는 실행이 되어도 값이 아무런 값도 가져와지지 않습니다.
<?php
$con = mysqli_connect("localhost", "11", "11", "11");
if (!$con)
{
echo "MySQL 접속 에러 : ";
echo mysqli_connect_error();
exit();
}
mysqli_set_charset($con,"utf8");
$sql = "SELECT * FROM answer";
$result = mysqli_query($con, $sql);
$data = array();
if($result){
while($row=mysqli_fetch_array($result)){
array_push($data,
array('a_id'=>$row[0],
'a_title'=>$row[1],
'a_content'=>$row[2],
'a_completed'=>$row[3]
));
}
header('Content-Type: application/json; charset=utf8');
$json = json_encode(array("webnautes"=>$data), JSON_PRETTY_PRINT+JSON_UNESCAPED_UNICODE);
echo $json;
}
else{
echo "SQL문 처리중 에러 발생 : ";
echo mysqli_error($con);
}
mysqli_close($con);
?>
앱에서 값을 받는 코드 입니다.
import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProviders;
import androidx.navigation.fragment.NavHostFragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.toolbox.Volley;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
/**
* A simple {@link Fragment} subclass.
* Use the {@link QnAFragment#newInstance} factory method to
* create an instance of this fragment.
*/
public class QnAFragment extends Fragment {
private String q_id, q_time, q_title, q_content, a_completed; //아이디값 가져올 객체
private EditText e_title, e_content;
private Context mContext;
private SimpleAdapter mSAdapter;
private ListView mListView;
private ArrayList<HashMap<String,String>> mListData;
String mJsonString;
private static String TAG = "phptest_MainActivity";
private static final String TAG_JSON="webnautes";
private static final String TAG_id = "a_id";
private static final String TAG_title = "a_title";
private static final String TAG_content = "a_content";
private static final String TAG_comleted ="a_completed";
private TextView textView18;
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
public QnAFragment() {
// Required empty public constructor
}
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* @param param1 Parameter 1.
* @param param2 Parameter 2.
* @return A new instance of fragment QnAFragment.
*/
// TODO: Rename and change types and number of parameters
public static QnAFragment newInstance(String param1, String param2) {
QnAFragment fragment = new QnAFragment();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_qn_a, container, false);
}
@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
//리스트뷰 얻어오기
mListView = this.getActivity().findViewById(R.id.QnAList);
//에러 판단
textView18 = getActivity().findViewById(R.id.textView18);
//시간 얻어오기
long mNow = System.currentTimeMillis();
Date mReDate = new Date(mNow);
SimpleDateFormat mFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
q_time = mFormat.format(mReDate);
//문의 제목, 내용 받아오기
e_title = getActivity().findViewById(R.id.editTextQnAtitle);
e_content = getActivity().findViewById(R.id.editTextQnAcontent);
mContext = getActivity();
q_id = PreferenceManager.getString(mContext, "user_id");
//작성완료 버튼
Button buttonFinishWrite = getActivity().findViewById(R.id.buttonFinishWrite);
buttonFinishWrite.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
//문의 제목 또는 내용이 비어있는 경우
if(e_title.getText().toString().equals("") ||e_content.getText().toString().equals("")){
Toast.makeText(getActivity(),"문의 제목과 내용을 모두 입력해주세요.",Toast.LENGTH_SHORT).show();
return;
}
//editText에 입력된 값을 가져옴
q_title = e_title.getText().toString();
q_content = e_content.getText().toString();
//QnA 정보를 DB에 넣는것이 잘 완료되었는지 확인
Response.Listener<String> responseLisner = new Response.Listener<String>() {
@Override
public void onResponse(String response) {
try {
JSONObject jsonObject = new JSONObject(response);
boolean success = jsonObject.getBoolean("success"); //QnA 등록이 성공했는지 성공여부를 담음 (jsp에서 성공하면 response["success"] = true; 해준것을 받아옴)
if (success) { //QnA 등록에 성공한 경우
Toast.makeText(getActivity(), "질문 등록이 완료되었습니다.", Toast.LENGTH_SHORT).show();
} else{ //QnA 등록에 실패한 경우
Toast.makeText(getActivity(), "질문 등록에 실패하였습니다.", Toast.LENGTH_SHORT).show();
return;
}
} catch (JSONException e) {
e.printStackTrace();
}
}
};
//서버로 Volley를 이용해서 요청함
QnARequest qndRequest = new QnARequest(q_id, q_time, q_title, q_content, responseLisner);
RequestQueue queue = Volley.newRequestQueue(getActivity());
queue.add(qndRequest);
}
});
// //리스트
// mListData = new ArrayList<>();
// mSAdapter = new SimpleAdapter(this.getActivity(), mListData, R.layout.qna_list,
// new String[] {"Qtitle","Qcontent","Atitle","Answer"}, new int[] {R.id.textViewQtitle, R.id.textViewQcontent, R.id.textViewAtitle, R.id.textViewAnswer});
// mListView = this.getActivity().findViewById(R.id.QnAList);
// mListView.setAdapter(mSAdapter);
//리스트 안에 넣어질 값 (받아와야함)
// HashMap<String,String> hitem = new HashMap<>();
// hitem.put("Qtitle", "고객센터에 질문한 타이틀");
// hitem.put("Qcontent", "고객센터에 질문한 내용");
// hitem.put("Atitle", "답변 타이틀");
// hitem.put("Answer", "답변 내용");
// mListData.add(hitem);
// mSAdapter.notifyDataSetChanged();
GetData task = new GetData();
task.execute("http://ci2021ani.dongyangmirae.kr/lsj/answerapp2.php");
}
private class GetData extends AsyncTask<String, Void, String> {
ProgressDialog progressDialog;
String errorString = null;
@Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog = ProgressDialog.show(getActivity(),
"Please Wait", null, true, true);
}
@Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
progressDialog.dismiss();
textView18.setText(result);
Log.d(TAG, "response - " + result);
if (result == null){
textView18.setText(errorString);
}
else {
mJsonString = result;
showResult();
}
}
@Override
protected String doInBackground(String... params) {
String serverURL = params[0];
try {
URL url = new URL(serverURL);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setReadTimeout(5000);
httpURLConnection.setConnectTimeout(5000);
httpURLConnection.connect();
int responseStatusCode = httpURLConnection.getResponseCode();
Log.d(TAG, "response code - " + responseStatusCode);
InputStream inputStream;
if(responseStatusCode == HttpURLConnection.HTTP_OK) {
inputStream = httpURLConnection.getInputStream();
}
else{
inputStream = httpURLConnection.getErrorStream();
}
InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "UTF-8");
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
StringBuilder sb = new StringBuilder();
String line;
while((line = bufferedReader.readLine()) != null){
sb.append(line);
}
bufferedReader.close();
return sb.toString().trim();
} catch (Exception e) {
Log.d(TAG, "InsertData: Error ", e);
errorString = e.toString();
return null;
}
}
}
private void showResult(){
try {
//리스트
mListData = new ArrayList<>();
mSAdapter = new SimpleAdapter(this.getActivity(), mListData, R.layout.qna_list,
new String[] {"Qtitle","Qcontent","Atitle","Answer"}, new int[]
{R.id.textViewQtitle, R.id.textViewQcontent, R.id.textViewAtitle, R.id.textViewAnswer});
mListView.setAdapter(mSAdapter);
HashMap<String,String> hitem = new HashMap<>();
hitem.put("Qtitle", "고객센터에 질문한 타이틀");
hitem.put("Qcontent", "고객센터에 질문한 내용");
hitem.put("Atitle", "답변 타이틀");
hitem.put("Answer", "답변 내용");
mListData.add(hitem);
mSAdapter.notifyDataSetChanged();
JSONObject jsonObject = new JSONObject(mJsonString);
JSONArray jsonArray = jsonObject.getJSONArray(TAG_JSON);
for(int i=0;i<jsonArray.length();i++) {
JSONObject item = jsonArray.getJSONObject(i);
String id = item.getString(TAG_id);
String title = item.getString(TAG_title);
String content = item.getString(TAG_content);
String comleted = item.getString(TAG_comleted);
// Toast.makeText(getActivity(), mJsonString+" "+id+" dd",Toast.LENGTH_LONG).show();
// if (id.equals(q_id)) {
HashMap<String, String> hashMap = new HashMap<>();
hashMap.put(TAG_id, id);
hashMap.put(TAG_title, title);
hashMap.put(TAG_content, content);
hashMap.put(TAG_comleted, comleted);
mListData.add(hashMap);
mSAdapter.notifyDataSetChanged();
// }
}
} catch (JSONException e) {
Log.d(TAG, "showResult : ", e);
}
}
}
어떤 부분이 문제인지 모르겠습니다.
!-->!-->!-->
답변을 작성하시기 전에 로그인 해주세요.