2011. 3. 11. 11:23

public class Mainactivity extends Activity
{
 private SharedPreferences pref = null;
 SharedPreferences.Editor editor;
 
    @Override
 public void onCreate(Bundle savedInstanceState)
 {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.login);
       
        pref = getSharedPreferences("com.newkie",Activity.MODE_PRIVATE);
editor = pref.edit();
//각종작업
editor.commit();

 }
}

pref 는 불러올때 editor는 데이터관리

'안드로이드' 카테고리의 다른 글

로딩화면 띄우기  (0) 2011.03.14
쓰레드 내에서 뷰터치 실행  (0) 2011.03.14
어플 완전히 죽이기  (0) 2011.03.10
다이얼로그 타이틀바 없애기  (0) 2011.03.09
intent 여러액티비티 한방에 끄기  (0) 2011.03.08
Posted by newkie
2011. 3. 10. 18:16

android.os.Process.killProcess(android.os.Process.myPid());

System.Exit(0);도 되긴 되는데 쓰지 말라는듯
Posted by newkie
2011. 3. 9. 16:22

super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.cancelcall);

컨텐트뷰 전에 지정

super.onCreate(savedInstanceState);
setContentView(R.layout.cancelcall);

requestWindowFeature(Window.FEATURE_NO_TITLE);

이렇게 했다가 Exception이 계속 떠서 빡쳐서 적어둠
Posted by newkie
2011. 3. 8. 17:42
A.java
onCreate{
...
Intent intent = new Intent(ctx, B.class);
startActivityForResult(intent, 0);
...
}
public void onActivityResult(int requestCode, int resultCode, Intent intent)
{
super.onActivityResult(requestCode, resultCode, intent);
 
switch(requestCode)
{
case 0:
if(resultCode == RESULT_OK)
{
intent = getIntent();//반복할때
setResult(RESULT_OK,intent);//반복할때
finish();
}
}
}

B.java

Intent intent = getIntent();
setResult(RESULT_OK,intent);
finish();


B에서 위 코드가 실행되면 B와 A가 동시에 꺼짐

반복해서 여러 액티비티가 동시에 꺼지는것도 가능
Posted by newkie
2011. 3. 7. 11:25
보내는쪽
Intent intent = new Intent(ctx, 전달클래스.class);
intent.putExtra("파라미터","전달값");
startActivity(intent);

받는쪽
Intent intent = getIntent();
String s = intent.getStringExtra("파라미터");
Posted by newkie
2011. 2. 28. 18:21
          Intent i = new Intent(Intent.ACTION_VIEW);
    Log.i("url",Current.getURL());
    i.setData(Uri.parse(Current.getURL()));
//유튜브플레이어로 바로 보내기
    try{
    i.setPackage("com.google.android.youtube");
    }catch(Exception e){
    Log.i("youtubeplayer",e.getMessage());
    }
    startActivity(i);

유튜브 플레이어가 없으면 에러


Posted by newkie
2011. 2. 28. 16:30
안드로이드쪽 소스

RestClient.java

package com.newkie;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URLEncoder;
import java.util.ArrayList;
 
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
 
public class RestClient
{
    private ArrayList<NameValuePair> params;
    private ArrayList<NameValuePair> headers;
 
    private String url;
 
    private int responseCode;
    private String message;
 
    private String response;
 
    public String getResponse()
    {
        return response;
    }
 
    public String getErrorMessage()
    {
        return message;
    }
 
    public int getResponseCode()
    {
        return responseCode;
    }
 
    public RestClient(String url) {
        this.url = url;
        params = new ArrayList<NameValuePair>();
        headers = new ArrayList<NameValuePair>();
    }
 
    public void AddParam(String name, String value)
    {
        params.add(new BasicNameValuePair(name, value));
    }
 
    public void AddHeader(String name, String value)
    {
        headers.add(new BasicNameValuePair(name, value));
    }
 
    public void Execute(RequestMethod method) throws Exception
    {
        switch (method)
        {
        case GET:
        {
            // add parameters
            String combinedParams = "";
            if (!params.isEmpty())
            {
                combinedParams += "?";
                for (NameValuePair p : params)
                {
                    String paramString = p.getName() + "=" + URLEncoder.encode(p.getValue(),"UTF-8");
                    if (combinedParams.length() > 1)
                    {
                        combinedParams += "&" + paramString;
                    }
                    else
                    {
                        combinedParams += paramString;
                    }
                }
            }
 
            HttpGet request = new HttpGet(url + combinedParams);
 
            // add headers
            for (NameValuePair h : headers)
            {
                request.addHeader(h.getName(), h.getValue());
            }
 
            executeRequest(request, url);
            break;
        }
        case POST:
        {
            HttpPost request = new HttpPost(url);
 
            // add headers
            for (NameValuePair h : headers)
            {
                request.addHeader(h.getName(), h.getValue());
            }
 
            if (!params.isEmpty())
            {
                request.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
            }
 
            executeRequest(request, url);
            break;
        }
        }
    }
 
    private void executeRequest(HttpUriRequest request, String url)
    {
        HttpClient client = new DefaultHttpClient();
 
        HttpResponse httpResponse;
 
        try
        {
            httpResponse = client.execute(request);
            responseCode = httpResponse.getStatusLine().getStatusCode();
            message = httpResponse.getStatusLine().getReasonPhrase();
 
            HttpEntity entity = httpResponse.getEntity();
 
            if (entity != null)
            {
 
                InputStream instream = entity.getContent();
                response = convertStreamToString(instream);
 
                // Closing the input stream will trigger connection release
                instream.close();
            }
 
        }
        catch (ClientProtocolException e)
        {
            client.getConnectionManager().shutdown();
            e.printStackTrace();
        }
        catch (IOException e)
        {
            client.getConnectionManager().shutdown();
            e.printStackTrace();
        }
    }
 
    private static String convertStreamToString(InputStream is)
    {
 
        BufferedReader reader = new BufferedReader(new InputStreamReader(is));
        StringBuilder sb = new StringBuilder();
 
        String line = null;
        try
        {
            while ((line = reader.readLine()) != null)
            {
                sb.append(line + "\n");
            }
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
        finally
        {
            try
            {
                is.close();
            }
            catch (IOException e)
            {
                e.printStackTrace();
            }
        }
        return sb.toString();
    }
}


RequestMethod.java

package com.newkie;

public enum RequestMethod
{
    GET,
    POST
}


위 두개를 써서 직접 통신하는 파일
AndroidHTTPClient.java

package com.newkie;
 
import android.accounts.Account;
import android.accounts.AccountManager;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
 
public class AndroidHTTPClient extends Activity
{
private Context mContext;

@Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.androidhttpclient);
        
        TextView textView = (TextView)findViewById(R.id.outputTextView);
        
        RestClient client = new RestClient("http://어플리케이션.appspot.com/지정한주소");
        client.AddParam("파라미터", "1");
//추가가능
 
        try
        {
            client.Execute(RequestMethod.GET);
        }
        catch (Exception e)
        {
            textView.setText(e.getMessage());
        }
 
        String response = client.getResponse();
        textView.setText(response);
        
     Button button1 = (Button)findViewById(R.id.cancel);
        button1.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
             finish();
            }
        });
        
    }
}





앱엔진쪽 소스

DataStore.java

package com.newkie;

import com.google.appengine.api.datastore.Key;
//import com.google.appengine.api.ids.String;

import javax.jdo.annotations.IdGeneratorStrategy;
import javax.jdo.annotations.PersistenceCapable;
import javax.jdo.annotations.Persistent;
import javax.jdo.annotations.PrimaryKey;

@PersistenceCapable
public class DataStore {
    @PrimaryKey
    @Persistent(valueStrategy = IdGeneratorStrategy.IDENTITY)
    private Key key;

    @Persistent
    private String id;

    @Persistent
    private String content;

//임의로 계속 추가가능

    public DataStore(String id, String content) {
        this.id = id;
        this.content = content;
    }

    public Key getKey() {
        return key;
    }

    public String getId() {
        return id;
    }

    public String getContent() {
        return content;
    }

    public void setId(String id) {
        this.id = id;
    }

    public void setContent(String content) {
        this.content = content;
    }

}



Gae2AndroidServlet.java

package com.newkie;

import java.io.IOException;
import java.util.List;

import javax.jdo.PersistenceManager;

import javax.servlet.http.*;

import com.newkie.DataStore;
import com.newkie.PMF;
 
@SuppressWarnings("serial")
public class Gae2AndroidServlet extends HttpServlet
{
    public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException
    {
     String param= null;
     Boolean update = false;

        resp.setContentType("text/html; charset=UTF-8");

//각종 처리
//ex)if (req.getParameterMap().containsKey("파라미터"))
//         param = req.getParameter("파라미터");
//resp.getWriter().println(param + "데이터받음");
    }
}

Posted by newkie