나는 PHP 스크립트에서 데이터를 가져 오는 안드로이드 앱을 만들고 있지만 계속 충돌합니다. 내가 작성한 모든 파일을 확인했으며 오류를 발견 할 수 없습니다. 더욱이 오류없이 컴파일됩니다.
이것은 나의 MainActivity.java
package com.whitehouse.sms;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.ListActivity;
import android.net.ParseException;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.Toast;
public class MainActivity extends ListActivity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
String result = null;
InputStream is = null;
StringBuilder sb = null;
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
List<String> r = new ArrayList<String>();
try{
//http post
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://000.000.4.49/categories.php");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
}
catch(Exception e){
Toast.makeText(getBaseContext(),e.toString() ,Toast.LENGTH_LONG).show();
}
//Convert response to string
try
{
BufferedReader reader = new BufferedReader(new InputStreamReader(is,"UTF-8"));
sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
is.close();
result = sb.toString();
}
catch(Exception e)
{
Toast.makeText(getBaseContext(),e.toString() ,Toast.LENGTH_LONG).show();
}
//END Convert response to string
try{
JSONArray jArray = new JSONArray(result);
JSONObject json_data=null;
for(int i=0;i<jArray.length();i++)
{
json_data = jArray.getJSONObject(i);
r.add(json_data.getString("category"));
}
setListAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_expandable_list_item_1, r));
}
catch(JSONException e1){
Toast.makeText(getBaseContext(),e1.toString() ,Toast.LENGTH_LONG).show();
} catch (ParseException e1) {
Toast.makeText(getBaseContext(),e1.toString() ,Toast.LENGTH_LONG).show();
}
}
}
이것은 내 안드로이드 매니페스트입니다.
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.whitehouse.sms"
android:versionCode="1"
android:versionName="1.0">
<uses-permission android:name="android.permission.INTERNET" />
<application android:icon="@drawable/ic_launcher" android:label="@string/app_name">
<activity android:name=".Database_demo"
android:label="@string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
이것은 내 main.xml입니다.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello"
/>
</LinearLayout>
그리고 이것은 내 strings.xml입니다.
<?xml version="1.0" encoding="utf-8" standalone="no"?>
<resources>
<string name="hello">Hello World, Database_demo!</string>
<string name="app_name">Love Android Mobile Application</string>
</resources>
이것은 내 PHP 파일에서 얻은 것입니다.
[{"category":"france"},{"category":"england"},{"category":"germany"},{"category":"denamrk"}]
그리고 이것은 php 파일입니다
<?php
mysql_connect("localhost","root","");
mysql_select_db("test");
$sql=mysql_query("SELECT category from category");
while($row=mysql_fetch_assoc($sql))
$output[]=$row;
print(json_encode($output));
mysql_close();
?>
모든 것이 괜찮아 보이기 때문에 프로그램에 무엇이 잘못되었을 수 있습니까?.
GUI 용으로 예약 된 메인 스레드에서는 인터넷 연결 기능을 사용할 수 없습니다. LogCat을 읽었다면 작성되었을 것입니다.
gurinderhans가 제안한대로 AsyncTask를 사용하십시오.
내 MVC 호환 코드가 있습니다.
public class PHPRequestRetriever extends AsyncTask<Object, Void, String> {
public interface Listener {
void handlePHPRequestFinished(String result);
}
private Listener listener = null;
private Exception exception = null;
public PHPRequestRetriever(Listener listener) {
this.listener = listener;
}
@Override
protected String doInBackground(Object... params) {
String data = "";
String url = (String) params[0];
ArrayList<NameValuePair> args = (ArrayList<NameValuePair>) params[1];
InputStream is = null;
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
httppost.setEntity(new UrlEncodedFormEntity(args));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
} catch (Exception e) {
Log.e("PHPRequestRetriever", "Error in http connection " + e.toString());
exception = e;
}
try {
BufferedReader reader = new BufferedReader(
new InputStreamReader(is, "UTF-8"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
data = sb.toString();
} catch (Exception e) {
Log.e("log_tag", "Error converting result " + e.toString());
exception = e;
}finally{
is.close();
}
return data;
}
@Override
protected void onPostExecute(String data) {
if (exception == null && !data.equals("")) {
this.listener.handlePHPRequestFinished(data);
} else {
Toast.makeText((Context) listener, "Error", Toast.LENGTH_LONG).show();
}
}
}
주요 활동 :
public class MainActivity extends ListActivity implements PHPRequestRetriever.Listener {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
PHPRequestRetriever retriever = new PHPRequestRetriever(this);
ArrayList<NameValuePair> args = new ArrayList<NameValuePair>();
// Set your args here
retriever.execute("http://example.com/phpscript.php", args);
}
@Override
public void handlePHPRequestFinished(String data) {
// Handle the result
}
}
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다