안드로이드 개발 질문/답변
(글 수 45,052)
로그켓에 에러메세지는 다음과 같습니다.
08-21 21:38:26.171: E/log_tag(669): Error in http connectionandroid.os.NetworkOnMainThreadException
08-21 21:38:26.171: E/log_tag(669): Error converting result java.lang.NullPointerException
그리고 소스 코드입니다 :
AndroidManifest.xml :
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.http_post"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="15" />
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
<application
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name=".MainActivity"
android:label="@string/title_activity_main" >
<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"?>
<TabHost
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@android:id/tabhost"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical">
<TabWidget
android:id="@android:id/tabs"
android:layout_width="fill_parent"
android:layout_height="wrap_content"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<FrameLayout
android:id="@android:id/tabcontent"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TableLayout
android:id="@+id/page01"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:stretchColumns="1">
<TableRow>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="First Name :"/>
<EditText
android:id="@+id/edit_firstname"
android:layout_width="fill_parent"
android:layout_height="wrap_content"/>
</TableRow>
<TableRow>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Last Name : "/>
<EditText
android:id="@+id/edit_lastname"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:password="true"/>
</TableRow>
<TableRow>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Gender : "/>
<EditText
android:id="@+id/edit_gender"
android:layout_width="fill_parent"
android:layout_height="wrap_content"/>
</TableRow>
<TableRow>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Age : "/>
<EditText
android:id="@+id/edit_age"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:lines="4"/>
</TableRow>
<View
android:layout_height="2dip"
android:background="#AAAAAA"/>
<TableRow>
<Button
android:text=" Submit "
android:id="@+id/button_submit"
android:layout_column="1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
</TableRow>
</TableLayout>
<LinearLayout
android:id="@+id/page02"
android:layout_width="fill_parent"
android:layout_height="wrap_content">
<TextView
android:id="@+id/text_result"
android:layout_width="fill_parent"
android:layout_height="wrap_content"/>
</LinearLayout>
</FrameLayout>
</LinearLayout>
</TabHost>
MainActivity.java
package com.http_post;
import java.io.*;
import java.util.ArrayList;
import com.http_post.R;
import android.app.TabActivity;
import android.net.ParseException;
import android.os.*;
import android.util.*;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.*;
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.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.support.v4.app.FragmentActivity;
public class MainActivity extends TabActivity implements OnClickListener{
// Declare the public variables
TabHost mTabHost = null;
JSONArray jArray;
String result = null;
InputStream is = null;
StringBuilder sb = null;
EditText myFirstname, myLastname, myGender, myAge;
Button submit;
int c_id;
String c_firstname, c_lastname, c_gender, c_age;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mTabHost = getTabHost();
mTabHost.addTab(mTabHost.newTabSpec("tab_1").setIndicator("Send data to the Server").setContent(R.id.page01));
mTabHost.addTab(mTabHost.newTabSpec("tab_2").setIndicator("Data received at the Server ").setContent(R.id.page02));
myFirstname = (EditText) findViewById(R.id.edit_firstname);
myLastname = (EditText) findViewById(R.id.edit_firstname);
myGender = (EditText) findViewById(R.id.edit_firstname);
myAge = (EditText) findViewById(R.id.edit_firstname);
submit = (Button) findViewById(R.id.button_submit);
submit.setOnClickListener(this);
}
public void onClick(View v) {
// TODO Auto-generated method stub
switch(v.getId()){
case R.id.button_submit:
insert();
}
}
public void insert(){
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://127.0.0.1/contact_insert.php");
ArrayList<NameValuePair> param = new ArrayList<NameValuePair>();
param.add(new BasicNameValuePair("firstname", myFirstname.getText().toString()));
param.add(new BasicNameValuePair("lastname", myLastname.getText().toString()));
param.add(new BasicNameValuePair("gender", myGender.getText().toString()));
param.add(new BasicNameValuePair("age", myAge.getText().toString()));
try {
httppost.setEntity(new UrlEncodedFormEntity(param));
HttpResponse response = httpclient.execute(httppost);
HttpEntity httpEntity = response.getEntity();
is = httpEntity.getContent();
}//insert()
catch(Exception e){
Log.e("log_tag", "Error in http connection" +e.toString());
}//catch
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8);
sb = new StringBuilder();
sb.append(reader.readLine() + "\n");
String line = "0";
while((line = reader.readLine()) != null){
sb.append(line +"\n");
}//while
is.close();
result = sb.toString();
}//try
catch(Exception e) {
Log.e("log_tag", "Error converting result "+e.toString());
}//catch
//parsing data
/*주석처리 부분
try{
jArray = new JSONArray(result);
JSONObject json_data = null;
for(int i=0;i<jArray.length();i++){
json_data = jArray.getJSONObject(i);
c_id = json_data.getInt("C_ID");
c_firstname = json_data.getString("C_FIRSTNAME");
c_lastname = json_data.getString("C_LASTNAME");
c_gender = json_data.getString("C_GENDER");
c_age = json_data.getString("C_AGE");
}
((TextView)(findViewById(R.id.text_result))).setText(result);
Toast.makeText(MainActivity.this, "Transmission Complete", 0).show();
}catch(JSONException e1){
Toast.makeText(getBaseContext(),"No Records Found", Toast.LENGTH_LONG).show();
} catch(ParseException e1){
e1.printStackTrace();
}*/
}
}
그리고 다음은...
contact_insert.php입니다.
<?php
mysql_connect("http://127.0.0.1", "root", "password");
mysql_select_db("capstone");
$firstname = $_REQUEST['firstname'];
$lastname = $_REQUEST['lastname'];
$gender = $_REQUEST['gender'];
$age = $_REQUEST['age'];
if($firstname && $lastname && $gender && $age){
$string = "INSERT INTO capstone.contacts(C_FIRSTNAME, C_LASTNAME, C_GENDER, C_AGE) VALUES ('$firstname', '$lastname', '$gender', '$age')";
mysql_query($string);
}
$string = "SELECT * FROM capstone.contacts";
$my_string = mysql_query($string);
while($object = mysql_fetch_assoc($my_string)){
$output[] = $object;
echo json_encode($output);
}
mysql_close();
?>
입력하고 나서, 확인하고 싶어서 JSON 객체로 parsing하려고 했는데, 주석처리 부분 때문에 아예 정지가 되버리더군요.
로컬 DB client로 SQL 쿼리를 실행시키면 문제가 없이 잘 돌아가는데요.
HttpPost 부분이 문제가 있는 걸까요? 도저히 해결이 안 됩니다 ㅜㅜ
고수분들 도움을 부탁드려요 ^^;
2012.08.22 00:41:49
(추천:
1 / 0)
맨처음 로그 보시면 "NetworkOnMainThreadException" 이렇게 나와있죠? 안드로이드 3.0 부터는 네트워크 작업을 모두 백그라운드로 실행해야 합니다. HttpPost를 실행할 때 AsyncTask, Handler 이런 놈들을 활용해보세요.
2012.08.23 02:16:11
(추천:
1 / 0)
저 같으면, 1) AsyncTask를 상속받아 InsertTask라는 클래스를 만들고, 2) insert() 메소드를 통채로 InsertTask 클래스 안에 넣어버리겠습니다. 그리고 onClick() 메소드에서 insert() 메소드를 바로 호출하는 대신 이렇게 InsertTask 클래스를 실행시키면 되겠죠.
InsertTask task = new InsertTask();
task.execute(new String[] { 인자목록 });
그리고 추가하자면, execute() 메소드에 넘겨주는 문자열 배열은 현재 insert() 메소드 안에 있는 myXXX.getText().toString() 메소드를 순서대로 맞춰 넣어야 하겠습니다. 물론 insert() 연산에 사용할 (흔히 말하는) 엔티티 클래스를 정의해 사용하면 훨씬 낫구요.



