2015年11月4日 星期三

JSON in JAVA

1.Make the JSON more beautiful


https://jsonformatter.curiousconcept.com/

2. if we have the JSON content

{"city":{"id":3093133,"name":"Lodz","coord":{"lon":19.466669,"lat":51.75},"country":"PL","population":0},"cod":"200","message":0.0342,"cnt":7,"list":[{"dt":1446631200,"temp":{"day":4.92,"min":-0.39,"max":8.24,"night":-0.39,"eve":6.36,"morn":0},"pressure":1022.08,"humidity":80,"weather":[{"id":800,"main":"Clear","description":"sky is clear","icon":"01d"}],"speed":3.22,"deg":258,"clouds":0},{"dt":1446717600,"temp":{"day":5.21,"min":-1.21,"max":8.19,"night":2.32,"eve":6.73,"morn":-1.21},"pressure":1024.42,"humidity":87,"weather":[{"id":802,"main":"Clouds","description":"scattered clouds","icon":"03d"}],"speed":2.01,"deg":106,"clouds":36},{"dt":1446804000,"temp":{"day":4.36,"min":-1.3,"max":7.92,"night":4.97,"eve":7.28,"morn":0.46},"pressure":1024.22,"humidity":86,"weather":[{"id":500,"main":"Rain","description":"light rain","icon":"10d"}],"speed":1.97,"deg":228,"clouds":0,"rain":2.62},{"dt":1446890400,"temp":{"day":11.87,"min":7.09,"max":12.61,"night":11.64,"eve":12.61,"morn":7.09},"pressure":1020.33,"humidity":0,"weather":[{"id":501,"main":"Rain","description":"moderate rain","icon":"10d"}],"speed":3.46,"deg":231,"clouds":94,"rain":5.34},{"dt":1446976800,"temp":{"day":14.08,"min":9.52,"max":14.08,"night":9.52,"eve":13.85,"morn":11.8},"pressure":1013.83,"humidity":0,"weather":[{"id":501,"main":"Rain","description":"moderate rain","icon":"10d"}],"speed":5.22,"deg":226,"clouds":99,"rain":4.43},{"dt":1447063200,"temp":{"day":9.64,"min":5.93,"max":9.64,"night":5.93,"eve":8.59,"morn":8.38},"pressure":1016.45,"humidity":0,"weather":[{"id":500,"main":"Rain","description":"light rain","icon":"10d"}],"speed":8.81,"deg":284,"clouds":51,"rain":2.43},{"dt":1447149600,"temp":{"day":12.77,"min":6.13,"max":14.46,"night":14.46,"eve":14.18,"morn":6.13},"pressure":1005.35,"humidity":0,"weather":[{"id":500,"main":"Rain","description":"light rain","icon":"10d"}],"speed":7.09,"deg":225,"clouds":94,"rain":1.01}]}


we want to get the first day mix temp



JSONObject jsonObject = new JSONObject(weatherJsonStr);
        JSONArray jaLIST=(JSONArray)jsonObject.get("list");
       JSONObject joDay=jaLIST.getJSONObject(0);
        double max=joDay.getJSONObject("temp").getDouble("max");





UriBuilder

example of how to use UriBuilder

Let's say that I want to create the following URL:

https://www.myawesomesite.com/turtles/types?type=1&sort=relevance#section-name
To build this with the Uri.Builder I would do the following.

Uri.Builder builder = new Uri.Builder();
builder.scheme("https")
    .authority("www.myawesomesite.com")
    .appendPath("turtles")
    .appendPath("types")
    .appendQueryParameter("type", "1")
    .appendQueryParameter("sort", "relevance")
    .fragment("section-name");
String myUrl = builder.build().toString();

2015年11月3日 星期二

AsyncTask

when should we use the AsyncTask?
the task is 2-3 s.
not too log.
can finish before the activity end

If we want some action do in the background for a long time, we should use services.

1.


1.think what is the input of the AsyncTask.eg,int
2. what is the type to indicate the prohress.
3 what do it return.String



2.Create the AsyncTask class



private class MyTask extends AsyncTask<int, Void, String> { ... }

<Params,Progress,Result>


3. implement the method in AsyncTask



  1. onPreExecute(), invoked on the UI thread before the task is executed. This step is normally used to setup the task, for instance by showing a progress bar in the user interface.
  2. doInBackground(Params...), invoked on the background thread immediately after onPreExecute() finishes executing. This step is used to perform background computation that can take a long time. The parameters of the asynchronous task are passed to this step. The result of the computation must be returned by this step and will be passed back to the last step. This step can also usepublishProgress(Progress...) to publish one or more units of progress. These values are published on the UI thread, in the onProgressUpdate(Progress...) step.
  3. onProgressUpdate(Progress...), invoked on the UI thread after a call to publishProgress(Progress...). The timing of the execution is undefined. This method is used to display any form of progress in the user interface while the background computation is still executing. For instance, it can be used to animate a progress bar or show logs in a text field.
  4. onPostExecute(Result), invoked on the UI thread after the background computation finishes. The result of the background computation is passed to this step as a parameter.

4.Execute the asynctask

  • The task instance must be created on the UI thread.
new MyTask(int i).execute();






permission

Normal permission
http://developer.android.com/intl/zh-tw/guide/topics/security/normal-permissions.html

Dangerous permission

http://developer.android.com/intl/zh-tw/guide/topics/security/permissions.html

Menu Button

1.Add at the menu/main.xml


<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    tools:context=".MainActivity">
    <item
        android:id="@+id/action_settings"
        android:orderInCategory="100"
        android:title="@string/action_settings"
        app:showAsAction="never" />
    <item
        android:id="@+id/action_refresh"
        android:orderInCategory="10"
        android:title="@string/action_refresh"
        app:showAsAction="ifRoom" />
</menu>

2A  in Activity show the menu

@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 boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }


2B in Fragment show the menu

@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setHasOptionsMenu(true);
    }

@Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        super.onCreateOptionsMenu(menu, inflater);
        inflater.inflate(R.menu.forecastfragment,menu);

    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()){
            case R.id.action_refresh:

                break;
        }
        return super.onOptionsItemSelected(item);
    }



2015年11月2日 星期一

ignore R.java

at .gitignore file

app/build/generated/source/r/debug/pom/poly/com/project0/R.java

Since this file is also an automatically generated fileyour submission contains a lot of irrelevant codes and source files. This could be caused by setting gitignore improperly. Sometimes this can even cause you loss file for your submission. And most of the time, this will cause the size of your app's code increasing drastically. To know more about the mechanism, you can read this page:
http://stackoverflow.com/questions/16736856/what-should-be-in-my-gitignore-for-an-android-studio-project
Here is another fast tutorial page which can make you learn this faster:
http://gitready.com/beginner/2009/01/19/ignoring-files.html

Butter Knife

How to install.

step1

dependencies {
        classpath 'com.android.tools.build:gradle:2.1.2'
        classpath 'com.google.gms:google-services:3.0.0'
        classpath 'com.neenbedankt.gradle.plugins:android-apt:1.8'

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }

step2

It is important that you add apply plugin: 'android-apt' to top of the module-level build.gradlefile; most likely below the first line like this:
apply plugin: 'com.android.application'
apply plugin: 'android-apt'


step3

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    testCompile 'junit:junit:4.12'
    ....................

    compile 'com.jakewharton:butterknife:8.1.0'
    apt 'com.jakewharton:butterknife-compiler:8.1.0'

    ....................


}




How to use
http://www.w2bc.com/Article/55029

http://blog.ccjeng.com/2015/08/Android-ButterKnife.html


Need unbind!!!


Create a field in your fragment as
Unbinder unbinder;
in onCreateView you call
unbinder = Butterknife.bind(this, root);
and in onDestroyView you need to call
unbinder.unbind();
thats it you're done.


Important!!

ath the below, if ues the Butter Knif at the image button,will have error,why?

error show:
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ImageButton.setImageResource(int)' on a null object reference

solve:
imb1= (ImageButton) view.findViewById(R.id.imb1);

again in
on llick
package pom2.poly.com.trythemoviedbapi.Fragment;
import android.content.ContentValues;import android.database.Cursor;import android.graphics.Bitmap;import android.graphics.drawable.BitmapDrawable;import android.graphics.drawable.Drawable;import android.net.Uri;import android.os.Bundle;import android.support.annotation.Nullable;import android.support.v4.app.Fragment;import android.support.v4.app.LoaderManager;import android.support.v4.content.CursorLoader;import android.support.v4.content.Loader;import android.util.Log;import android.view.LayoutInflater;import android.view.View;import android.view.ViewGroup;import android.widget.ImageButton;import android.widget.ImageView;import android.widget.LinearLayout;import android.widget.ScrollView;import android.widget.TextView;
import com.squareup.picasso.Picasso;import com.squareup.picasso.Target;
import butterknife.Bind;import butterknife.ButterKnife;import pom2.poly.com.trythemoviedbapi.R;import pom2.poly.com.trythemoviedbapi.Sqlite.MovieDbContract;import pom2.poly.com.trythemoviedbapi.Utility;
/** * Created by User on 1/2/2016. */public class DetailFragment extends Fragment implements View.OnClickListener, LoaderManager.LoaderCallbacks<Cursor> {
    private static int CURSORLOADER_ID;//    @Bind(R.id.imb1)    ImageButton imb1;    @Bind(R.id.iv1)
    ImageView iv1;    @Bind(R.id.tvTitle)
    TextView tvTitle;    @Bind(R.id.tvRate)
    TextView tvRate;    @Bind(R.id.tvDate)
    TextView tvDate;    @Bind(R.id.tvOverview)
    TextView tvOverview;//    @Bind(R.id.scrollView)    ScrollView scrollView;    @Bind(R.id.lineayout1)
    LinearLayout lineayout1;    private String m_id = null;    private Boolean isTwoPlanMode = false;    private Bundle infBundle = null;
    public Boolean getIsTwoPlanMode() {
        return isTwoPlanMode;    }

    public DetailFragment setIsTwoPlanMode(Boolean isTwoPlanMode) {
        this.isTwoPlanMode = isTwoPlanMode;        return this;    }

    @Override    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);        //if do not save before ,infBundle will equal null        if (savedInstanceState != null) {
            infBundle = (Bundle) savedInstanceState.get(Utility.BUNDLE_KEY_RESTORE_DETAIL_BUNDLE);        }

    }

    @Override    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);        outState.putParcelable(Utility.BUNDLE_KEY_RESTORE_DETAIL_BUNDLE, infBundle);    }

    @Nullable    @Override    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_detail, container, false);        Log.i("DetailFragment","onCreateView");        ButterKnife.bind(this, view);        imb1= (ImageButton) view.findViewById(R.id.imb1);
        //        Movie aMovie = getIntent().getParcelableExtra(DetailActivity.class.getName());

        //if can't get infBundle from savedInstanceState        if (infBundle == null) {
            if (isTwoPlanMode) {
                infBundle = getArguments();            } else {
                infBundle = getActivity().getIntent().getExtras();            }

        }

        tvTitle.setText(infBundle.getString(Utility.BUNDLE_KEY_TITLE));
        Target target = new Target() {
            @Override            public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom loadedFrom) {
                BitmapDrawable backdround = new BitmapDrawable(getResources(), bitmap);                backdround.setAlpha(150);                lineayout1.setBackgroundDrawable(backdround);            }

            @Override            public void onBitmapFailed(Drawable errorDrawable) {    //當圖片加載失敗時調用            }

            @Override            public void onPrepareLoad(Drawable placeHolderDrawable) {     //當任務被提交時調用            }
        };

        Picasso.with(getContext()).load(infBundle.getString(Utility.BUNDLE_KEY_POSTERPATH)).into(target);        Picasso.with(getContext()).load(infBundle.getString(Utility.BUNDLE_KEY_BACKGROUNDPATH)).into(iv1);
        tvRate.setText(infBundle.getString(Utility.BUNDLE_KEY_RATE));        tvDate.setText(infBundle.getString(Utility.BUNDLE_KEY_DATE));        tvOverview.setText(infBundle.getString(Utility.BUNDLE_KEY_OVERVIEW));
        m_id = infBundle.getString(Utility.BUNDLE_KEY_M_ID);        CURSORLOADER_ID = Integer.parseInt(m_id);        imb1.setOnClickListener(this);
        getActivity().getSupportLoaderManager().initLoader(CURSORLOADER_ID, null, this);

        return view;    }

    @Override    public void onPause() {
        super.onPause();    }

    @Override    public void onDestroyView() {
        super.onDestroyView();        ButterKnife.unbind(this);    }

    @Override    public Loader<Cursor> onCreateLoader(int id, Bundle args) {
        Uri uri = MovieDbContract.FavouriteEntry.buildFavouriteWithID(Long.parseLong(m_id));        return new CursorLoader(getContext(), uri, null, null, null, null);    }

    @Override    public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
        int i = data.getCount();        if (i > 0) {
            //in the favourite table            imb1.setImageResource(R.drawable.ic_star_white_36dp);            imb1.setTag("R.drawable.ic_star_white_36dp");        } else {
            // not in the favourite table            imb1.setImageResource(R.drawable.ic_star_black_36dp);            imb1.setTag("(R.drawable.ic_star_black_36dp");        }

//        data.close();
    }

    @Override    public void onLoaderReset(Loader<Cursor> loader) {

    }

    @Override    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.imb1:
//                Toast.makeText(this,m_id,Toast.LENGTH_SHORT).show();

                if (imb1.getTag().equals("R.drawable.ic_star_white_36dp")) {
                    //the star button is white now
                    //delete the  m_id from the favourite table
                    getContext().getContentResolver().delete(MovieDbContract.FavouriteEntry.buildFavouriteWithID(Long.parseLong(m_id)), null, null);
                    imb1.setImageResource(R.drawable.ic_star_black_36dp);                } else {
                    //the star button is black now                    //insert the m_id to the favourite table                    ContentValues cv = new ContentValues();                    cv.put(MovieDbContract.FavouriteEntry.COLUMN_MOVIE_KEY, Long.parseLong(m_id));                    getContext().getContentResolver().insert(MovieDbContract.FavouriteEntry.CONTENT_URI, cv);
                    imb1.setImageResource(R.drawable.ic_star_white_36dp);                }

                break;        }

    }
}

Style

If many view use the same attribute,we can change it to astyle


<Button
        android:id="@+id/btBTB"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_margin="10dp"
        android:background="@drawable/orange_custom_button_background"
        android:padding="5dp"
        android:text="@string/ant_terminator"
        android:textColor="@color/textColor" />




change to a style


in styles.xml


<style name="OrangeButton">
        <item name="android:layout_width">wrap_content</item>
        <item name="android:layout_height">wrap_content</item>
        <item name="android:layout_margin">10dp</item>
        <item name="android:background">@drawable/orange_custom_button_background</item>
        <item name="android:padding">5dp</item>
        <item name="android:textColor">@color/textColor</item>
    </style>


After apply





<Button
        android:id="@+id/btBTB"
        style="@style/OrangeButton"
        android:text="@string/ant_terminator" />

example of send The HTTP request and read the HTTP response

 A goode website for JAVA IO

http://tutorials.jenkov.com/java-io/overview.html


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


           

 // These two need to be declared outside the try/catch
            // so that they can be closed in the finally block.
            HttpURLConnection urlConnection = null;
            BufferedReader reader = null;

            // Will contain the raw JSON response as a string.
            String forecastJsonStr = null;

            try {
                // Construct the URL for the OpenWeatherMap query
                // Possible parameters are avaiable at OWM's forecast API page, at
                // http://openweathermap.org/API#forecast
                Uri.Builder builder = new Uri.Builder();
                builder.scheme("http")
                        .authority("api.openweathermap.org")
                        .appendPath("data")
                        .appendPath("2.5")
                        .appendPath("forecast")
                        .appendPath("daily")
                        .appendQueryParameter("q", potoalCode + "")
                        .appendQueryParameter("mode", "json")
                        .appendQueryParameter("units", "metric")
                        .appendQueryParameter("cnt", "7")
                        .appendQueryParameter("appid", APPID);
                String myUrl = builder.build().toString();


                URL url = new URL(myUrl);

                // Create the request to OpenWeatherMap, and open the connection
                urlConnection = (HttpURLConnection) url.openConnection();
                urlConnection.setRequestMethod("GET");
                urlConnection.connect();

                // Read the input stream into a String
                InputStream inputStream = urlConnection.getInputStream();
                StringBuffer buffer = new StringBuffer();
                if (inputStream == null) {
                    // Nothing to do.
                    return null;
                }
                reader = new BufferedReader(new InputStreamReader(inputStream));

                String line;
                while ((line = reader.readLine()) != null) {
                    // Since it's JSON, adding a newline isn't necessary (it won't affect parsing)
                    // But it does make debugging a *lot* easier if you print out the completed
                    // buffer for debugging.
                    buffer.append(line + "\n");
                }

                if (buffer.length() == 0) {
                    // Stream was empty.  No point in parsing.
                    return null;
                }
                forecastJsonStr = buffer.toString();
            } catch (IOException e) {
                Log.e("PlaceholderFragment", "Error ", e);
                // If the code didn't successfully get the weather data, there's no point in attemping
                // to parse it.
                return null;
            } finally{
                if (urlConnection != null) {
                    urlConnection.disconnect();
                }
                if (reader != null) {
                    try {
                        reader.close();
                    } catch (final IOException e) {
                        Log.e("PlaceholderFragment", "Error closing stream", e);
                    }
                }
            }