summaryrefslogtreecommitdiff
path: root/src/eu/deki/paste/PasteTask.java
blob: 9e285a595ff0ef7d0e68ddac21f3bce47582070b (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
package eu.deki.paste;

import java.io.IOException;
import android.os.AsyncTask;
import android.content.Context;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.util.Log;
import android.text.ClipboardManager;

public abstract class PasteTask extends AsyncTask<String, Void, String>
{
    private String errorMessage = "Fail";
    protected Context parentActivity = null;

    public PasteTask(Context parent)
    {
	super();
	parentActivity = parent;
    }

    @Override
    protected String doInBackground(String... params)
    {
	String title, content, expiration, result;

	if(params.length != 3)
	    return null;

	title = params[0];
	content = params[1];
	expiration = params[2];

	if(content.length() == 0)
	{
	    errorMessage = parentActivity.getResources().getString(R.string.contentTooShort);
	    cancel(false);
	    return null;
	}

	try
	{
	    result = paste(title, content, expiration);
	    if(result == null)
		cancel(false);
	}
	catch(IOException ex)
	{
	    cancel(false);
	    errorMessage = ex.getLocalizedMessage();
	    result = errorMessage;
	    Log.e("PasteIt", "doInBackground", ex);
	}

	return result;
    }

    private void copyToClipboard(String url)
    {
	ClipboardManager clipboard = (ClipboardManager) parentActivity.getSystemService(Context.CLIPBOARD_SERVICE);
	clipboard.setText(url);
    }

    @Override
    protected void onPostExecute(String result)
    {
	copyToClipboard(result);

	AlertDialog.Builder builder = new AlertDialog.Builder(parentActivity);
	String message = String.format(parentActivity.getResources().getString(R.string.pasteSuccessMessage), result);
	builder.setMessage(message);
	builder.setTitle(R.string.pasteSuccessTitle);
	builder.setPositiveButton("OK", null);
	builder.create().show();
    }

    @Override
    protected void onCancelled()
    {
	AlertDialog.Builder builder = new AlertDialog.Builder(parentActivity);
	String message = String.format(parentActivity.getResources().getString(R.string.pasteFailMessage), errorMessage);
	builder.setMessage(message);
	builder.setTitle(R.string.pasteFailTitle);
	builder.setPositiveButton("OK", null);
	builder.create().show();
    }

    protected abstract String paste(String title, String content, String delay) throws IOException;
}