Example how to take photo and upload it’s thumbnail to your server using okhttp3 (first I convert it to jpeg)

//part when you click on item and start camera
imageView.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        Context context = v.getContext();

        if (takePictureIntent.resolveActivity(context.getPackageManager()) != null) {
            startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
        }
    }
});

//part when you get the thumbnail from camera
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == Activity.RESULT_OK) {
        Bundle extras = data.getExtras();
        Bitmap imageBitmap = (Bitmap) extras.get("data");

        new AsyncTask() {
            @Override
            protected Void doInBackground(Bitmap... bitmaps) {
                OkHttpClient client = new OkHttpClient();

                ByteArrayOutputStream stream = new ByteArrayOutputStream();
                bitmaps[0].compress(Bitmap.CompressFormat.JPEG, 100, stream);
                byte[] byteArray = stream.toByteArray();

                //there are some my custom fields form
                RequestBody requestBody = new MultipartBody.Builder()
                        .setType(MultipartBody.FORM)
                        .addFormDataPart("submit", "")
                        .addFormDataPart("name", "myPhotoName")
                        .addFormDataPart("photo", "tmp_photo_" + System.currentTimeMillis(), RequestBody.create(MediaType.parse("image/jpeg"), byteArray))
                        .build();

                Request request = new Request.Builder()
                        .url("www.example.com/upload_image.php")
                        .post(requestBody)
                        .build();

                Response response = null;
                try {
                    response = client.newCall(request).execute();
                    if (response.isSuccessful()) {
                        Log.d(TAG, "doInBackground: upload success");
                    } else {
                        Log.d(TAG, "doInBackground: upload failed");
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
                return null;
            }
        }.execute(imageBitmap);
    } else {
        //another results
        super.onActivityResult(requestCode, resultCode, data);
    }
}

Wireshark – filter out only results if they are method type POST or GET and not containing in url special word

Example of filtering only that results which have request method as GET or POST and special word is not in url:

(http.request.method == GET or http.request.method == POST) and !http.request.uri contains "css"

Notepad++ with regex, re-using match variables

Here is an simple example how to use regex in notepad++ with reusing selected match variables.

For example we have special code for simulating gcm notifications. We would like to see it in pretty style.
To achieve this we must to move all elements with minus to the new lines. How to do it? Here is the solution.

We have this string:
adb shell am broadcast -a com.google.android.c2dm.intent.RECEIVE -c com.example.android.debug -n com.example.android.google.debug/com.example.android.gcm.GcmBroadcastReceiver --es "aaa" "123" --es "mmm" "bla bla bla" --es "sss" "321" --es "from" "111" --es "type" "yesterday" --es "collapse_key" "do_not_collapse"

By using bellow command in notepad++:

Searching text:

\-[a-z]{0,2}\s

Replace with:

\n($0)

We get the quite pretty result:

adb shell am broadcast
-a com.google.android.c2dm.intent.RECEIVE
-c com.example.android.debug
-n com.example.android.google.debug/com.example.android.gcm.GcmBroadcastReceiver
--es "aaa" "123"
--es "mmm" "bla bla bla"
--es "sss" "321"
--es "from" "111"
--es "type" "yesterday"
--es "collapse_key" "do_not_collapse"

Working example POST in android

Here is another short (IMHO) example how to post in android app.

private void postSms(String text) {
URL url;
HttpURLConnection urlConnection = null;

try {
url = new URL("http://yourserver.com/sendsms");
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("POST");
urlConnection.setDoOutput(true);

List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("sms", text));//POST param as "sms"

OutputStream os = urlConnection.getOutputStream();
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
writer.write(getQuery(params));
writer.flush();
writer.close();
os.close();

String status = new String(Streams.getBytes(urlConnection.getInputStream()));
Log.d(TAG, new Exception().getStackTrace()[0].getMethodName() + ":insert status=" + status);

} catch (MalformedURLException | ProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}

This is a method for concatenating parameters for POST

Continue reading “Working example POST in android”

GCM notification with custom sound – shorter version (part)

Here is a short example how to create notification with default stuff but different sound:

NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.ic_launcher)
.setContentTitle("title")
.setStyle(new NotificationCompat.BigTextStyle()
.bigText("message"))
.setContentText("message")
.setAutoCancel(true)
.setSound(soundUri)
.setDefaults(NotificationCompat.DEFAULT_ALL ^ NotificationCompat.DEFAULT_SOUND);

The most important part is here:

.setDefaults(NotificationCompat.DEFAULT_ALL ^ NotificationCompat.DEFAULT_SOUND)

Symbol

^

says “except”, so the last part would say “give me default notification except sound setting”

Working example – changing drawable background in runtime, dynamically

Here is a short example code how to do it:
I’ve created xml file shape.xml and one method for flexible changing color of shape.

shape.xml:

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" >
<solid android:color="@android:color/holo_blue_bright" />
<corners android:radius="30dp" />
<size
android:height="15dp"
android:width="15dp" />
</shape>

And here is a method for flexible changing color:

Continue reading “Working example – changing drawable background in runtime, dynamically”

Working example of setting alarm with repeating stuff, checking if alarm was set with pendingIntent

Here is short and quite (imho) understanding part of code:

//starting #1
AlarmManager alarmManager = (AlarmManager) getActivity().getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(getActivity(), MyReceiver.class);
intent.setAction(MyReceiver.ACTION_ALARM_RECEIVER);//my custom string action name
PendingIntent pendingIntent = PendingIntent.getBroadcast(getActivity(), 1001, intent, PendingIntent.FLAG_CANCEL_CURRENT);//used unique ID as 1001
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), aroundInterval, pendingIntent);//first start will start asap

#1 – first we are getting alarm service. We create own intention and setting own action to it to be able handle in onReceive(), in our receiver class. Then the intention is putting into pendingIntent. The complete pendingIntent is used by alarmManager for a start.
I used System.currentTimeMillis() because I wanted start repeating asap.
I used flag PendingIntent.FLAG_CANCEL_CURRENT for pendingIntent but it might be also PendingIntent.FLAG_UPDATE_CURRENT. It is important to use the same flag everywhere, but when you want stop it, you use PendingIntent.FLAG_NO_CREATE. I will write about it later.
Number 1001 in pendingIntent was used just to be know that our intention has unique ID.

Continue reading “Working example of setting alarm with repeating stuff, checking if alarm was set with pendingIntent”

Custom checkable list item with checkbox (layout+code)

Here is simple example how to create simple checkable list item with checbox.

This a code for widget:

public class CheckableTextView extends LinearLayout {

private TextView checkLabel;
private CheckBox checkBox;

public CheckableTextView(Context context) {
super(context);
}

public CheckableTextView(Context context, AttributeSet attrs) {
super(context, attrs);
init();

}

public CheckableTextView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init();
}

private void init() {
View v = inflate(getContext(), R.layout.widget_checkabletextview_merged, this);
checkLabel = ((TextView) v.findViewById(R.id.checkLabel));
checkBox = ((CheckBox) v.findViewById(R.id.checkBox));

v.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View view) {
checkBox.setChecked(!checkBox.isChecked());
}
});
}

public void setText(CharSequence c) {
checkLabel.setText(c);
}

public void setText(String c) {
checkLabel.setText(c);
}

public void setChecked(boolean status)
{
checkBox.setChecked(status);
}

}

This is the widget’s layout:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center_vertical"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:background="?android:attr/selectableItemBackground">

<CheckedTextView
android:id="@+id/checkLabel"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="4"
android:text="Sample text" />

<CheckBox
android:clickable="false"
android:id="@+id/checkBox"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:focusable="false" />

</LinearLayout>

Example of one item:

layout-2015-01-07-115016