2013年10月1日火曜日

PHP掲示板アプリのサンプル

ページを表示する(テキストとWEBビュー)
ボタンを押すと書き込み⇒再表示



    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" >
    </uses-permission>
     <uses-permission android:name="android.permission.INTERNET" />


//activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" >

    <LinearLayout
        android:id="@+id/linearLayout1"
        android:layout_width="500px"
        android:layout_height="300px"
        android:layout_alignRight="@+id/button1"
        android:layout_marginTop="24dp"
        android:orientation="vertical" >

        <WebView
            android:id="@+id/webView1"
            android:layout_width="match_parent"
            android:layout_height="224dp" />
    </LinearLayout>

    <EditText
        android:id="@+id/editText2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBaseline="@+id/button1"
        android:layout_alignBottom="@+id/button1"
        android:layout_alignParentLeft="true"
        android:layout_toLeftOf="@+id/button1"
        android:ems="10" />

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_alignParentRight="true"
        android:layout_marginBottom="17dp"
        android:layout_marginRight="14dp"
        android:text="書き込み" />

    <EditText
        android:id="@+id/editText1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_above="@+id/button1"
        android:layout_alignLeft="@+id/linearLayout1"
        android:layout_alignRight="@+id/button1"
        android:layout_below="@+id/linearLayout1"
        android:ems="10"
        android:inputType="textMultiLine" >

        <requestFocus />
    </EditText>

</RelativeLayout>

//MainActivity

package com.example.testhttp;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.ResponseHandler;
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.apache.http.util.EntityUtils;

import com.example.testhttp.R.id;

import android.os.Bundle;
import android.app.Activity;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.webkit.WebView;
import android.widget.Button;
import android.widget.EditText;




public class MainActivity extends Activity implements OnClickListener{
private EditText ed1,ed2;
private Button  bt;
private WebView wv;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

ed1 = (EditText)findViewById(id.editText1);
ed2 = (EditText)findViewById(id.editText2);
bt= (Button)findViewById(id.button1);
wv = (WebView)findViewById(id.webView1);


bt.setOnClickListener(this);

exec_post(false);
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}

@Override
public void onClick(View v) {

exec_post(true);
}




   String ret = "";

   // URL
   URI url = null;
   try {
     url = new URI( "http://passepied.miraiserver.com/index.php" );
     Log.d("posttest", "URLはOK");
   } catch (URISyntaxException e) {
     e.printStackTrace();
     ret = e.toString();
   }

   HttpPost request = new HttpPost( url );
   List<NameValuePair> post_params = new ArrayList<NameValuePair>();
   if(fl){
   post_params.add(new BasicNameValuePair("post_2", ed2.getText().toString()));
   }
   try {

     request.setEntity(new UrlEncodedFormEntity(post_params, "UTF-8"));
   } catch (UnsupportedEncodingException e1) {
     e1.printStackTrace();
   }


   DefaultHttpClient httpClient = new DefaultHttpClient();
   try {

     ret = httpClient.execute(request, new ResponseHandler<String>() {

       @Override
       public String handleResponse(HttpResponse response) throws IOException
       {
         Log.d(
           "posttest",  "code:" + response.getStatusLine().getStatusCode()
         );


         switch (response.getStatusLine().getStatusCode()) {
         case HttpStatus.SC_OK:

           return EntityUtils.toString(response.getEntity(), "UTF-8");

         case HttpStatus.SC_NOT_FOUND:
           return null;

         default:
           return null;
         }

       }
     
     });

   } catch (IOException e) {
     Log.d("posttest", "sippai:" + e.toString());
   } finally {
     httpClient.getConnectionManager().shutdown();
   }

   ed1.setText( ret );
 
   wv.loadDataWithBaseURL("about:blank",ret, "text/html", "UTF-8",null);
 
 }


}

//Index.php
<html>
<head><title>PHP TEST</title></head>
<body>

<p></p>



<?php

if($_SERVER["REQUEST_METHOD"] == "POST"){
    writeData();
}

readData();

function readData(){
    $keijban_file = 'keijiban.txt';

    $fp = fopen($keijban_file, 'rb');

    if ($fp){
        if (flock($fp, LOCK_SH)){
            while (!feof($fp)) {
                $buffer = fgets($fp);
                print($buffer);
            }

            flock($fp, LOCK_UN);
        }else{
            print('haita');
        }
    }

    fclose($fp);
}

function writeData(){

    $contents = $_POST['post_2'];
    $contents = nl2br($contents);

    $data = "<hr>\r\n";
    $data = $data."<p>".$contents."</p>\r\n";

    $keijban_file = 'keijiban.txt';

    $fp = fopen($keijban_file, 'ab');

    if ($fp){
        if (flock($fp, LOCK_EX)){
            if (fwrite($fp,  $data) === FALSE){
                print('kakikomi');
            }

            flock($fp, LOCK_UN);
        }else{
            print('rokku');
        }
    }

    fclose($fp);
}

?>
</body>
</html>

0 件のコメント:

コメントを投稿