How to handle two tasks using thread in android? - android

I am getting stuck in emulator whenever i try to do display list of images which is in my server on list view and button on click for sorting images.It is listing out images one by one,at the time when i try clicking on sorting button that time my emulator is getting stuck for a while.
I want to work on that simultaneously.
I have two buttons on click function, one is for Asynctask execution with background process and another one for normal button click listener for sorting input components for reading from UI components.
WebServiceTask wst = new WebServiceTask(WebServiceTask.GET_TASK, this, "Loading.....");
wst.execute(new String[]{sampleURL});
try {
//Extract the data…
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(5);
nameValuePairs.add(new BasicNameValuePair("city", city_name));
nameValuePairs.add(new BasicNameValuePair("room_type", room_type));
nameValuePairs.add(new BasicNameValuePair("bed", no_bed));
nameValuePairs.add(new BasicNameValuePair("bedrooms", no_bedrooms));
nameValuePairs.add(new BasicNameValuePair("guest_allow", guest_allowed));
// Add your data
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
if (response.getStatusLine().getStatusCode() == 200) {
HttpEntity entity = response.getEntity();
json = EntityUtils.toString(entity);
try {
// JSONArray jso = new JSONArray(json);
JSONObject object = new JSONObject(json);
JSONArray jso = object.getJSONArray("search_result");
Toast.makeText(this, "jso length" + jso.length(), Toast.LENGTH_LONG).show();
if (jso.length() != 0) {
for (int i = 0; i < jso.length(); i++) {
if (jso.getJSONObject(i).getString("city").equalsIgnoreCase(city_name)) {
Person resultRow = new Person();
resultRow.id = jso.getJSONObject(i).getString("user_id");
resultRow.ProjectName = jso.getJSONObject(i).getString("user_name");
resultRow.Country = jso.getJSONObject(i).getString("bathrooms");
resultRow.city = jso.getJSONObject(i).getString("city");
resultRow.descrip = jso.getJSONObject(i).getString("price");
resultRow.bed = jso.getJSONObject(i).getString("bed");
resultRow.bedrooms = jso.getJSONObject(i).getString("bedrooms");
resultRow.guest_allow = jso.getJSONObject(i).getString("guest_allow");
resultRow.roomtype = jso.getJSONObject(i).getString("room_type");
resultRow.property_type = jso.getJSONObject(i).getString("property_type");
resultRow.logo = jso.getJSONObject(i).getString("property_image");
resultRow.user_ppty_id = jso.getJSONObject(i).getString("user_property_id");
resultRow.check_in_time = jso.getJSONObject(i).getString("check_in_time");
resultRow.check_out_time = jso.getJSONObject(i).getString("check_out_time");
resultRow.host_image = jso.getJSONObject(i).getString("host_image");
arrayOfwebData.add(resultRow);
Toast.makeText(this, "counting" + i, Toast.LENGTH_LONG).show();
}
}
} else {
Toast.makeText(this, "NOT found", Toast.LENGTH_LONG).show();
}
} catch (Exception e) {
Toast.makeText(this, "NOT found", Toast.LENGTH_LONG).show();
Log.e(TAG, e.getLocalizedMessage(), e);
}
ListView myListView = (ListView) findViewById(R.id.listview);
Toast.makeText(this, "updated" + up, Toast.LENGTH_LONG).show();
aa = new FancyAdapter();
myListView.setAdapter(aa);
up++;
} else {
Toast.makeText(this, "NOT found", Toast.LENGTH_LONG).show();
}
// ViewHolder aa1= new ViewHolder();
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
} catch (IOException e) {
// TODO Auto-generated catch block
}
and button click
btn_plus.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String val = (String) no_guest.getText();
int values = Integer.parseInt(val);
no_guest.setText("" + (values + 1));
guest_allowed = (String) no_guest.getText();
}
});

Related

Android HttpPost request to server

i want to send data from android SqLite database to my Codeigniter web App controller which take the post data and save it to MySql database
so i made buttn to make this sync task in android app and its code:
public void syncAttendance(View v) {
try
{
/** Retrieving data from database **/
//use cursor to keep all data
//cursor can keep data of any data type
Cursor c=db.rawQuery("select * from mytable", null);
int memNum = 1;
//move cursor to first position
c.moveToFirst();
//fetch all data one by one
do
{
//we can use c.getString(0) here
//or we can get data using column index
String memID = c.getString(c.getColumnIndex("memID"));
String currTime = c.getString(c.getColumnIndex("currTime"));
String dayName = c.getString(c.getColumnIndex("dayName"));
////////////////////////////////////////
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://mywebsite.com/index.php/admin/attendance/scan_qr");
JSONObject json = new JSONObject();
/** try {**/
// JSON data:
json.put("memID", memID);
json.put("currTime", currTime);
json.put("dayName", dayName);
JSONArray postjson=new JSONArray();
postjson.put(json);
// Post the data:
httppost.setHeader("json",json.toString());
httppost.getParams().setParameter("jsonpost",postjson);
// Execute HTTP Post Request
System.out.print(json);
HttpResponse response = httpclient.execute(httppost);
// for JSON:
if(response != null)
{
InputStream is = response.getEntity().getContent();
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();
}
}
text = sb.toString();
}
//tv.setText(text);
/**
}catch (ClientProtocolException e) {
// TODO Auto-generated catch block
} catch (IOException e) {
// TODO Auto-generated catch block
}
**/
//////////////////////////////////////////
/** show confirmation toast **/
Toast toast = Toast.makeText(this, memNum + memID + currTime + dayName, Toast.LENGTH_LONG);
toast.show();
memNum ++;
//move next position until end of the data
}while(c.moveToNext());
/** show confirmation toast **/
Toast toast = Toast.makeText(this, "Synchronization Completed", Toast.LENGTH_LONG);
toast.show();
}
catch(Exception e)
{
e.printStackTrace();
}
}
and the php codeigniter controller code is:
public function scan_qr()
{
$json = $_SERVER['HTTP_JSON'];
var_dump($json);
$data = json_decode($json);
var_dump($data);
$memID = $data->memID;
$currTime = $data->currTime;
$dayName = $data->dayName;
$ma7abawy_year = 3;
$data= array(
'member_id' => $memID,
//'points' => $points,
'presence_time' => $currTime,
//'event' => $eventname,
'event_date' => $dayName,
'ma7abawy_year' => $ma7abawy_year
);
$this->db->insert('attendance',$data);
}
i have no exception but nothing is happened
any ideas would be appreciated
I would suggest to use retrofit (see API docs) library to consume the service. Afterwards, see what you get back in the response and it will be a simple matter of saving the data to the sqlite3 db. See example for saving data.

Android and JSP Communication Error

I Have this JSP which just check the username and password and "out.write" 1 or 0 based on true or false.
<%# page import="java.io.*" %>
<%
if(request.getParameter("username").equals("anas") && request.getParameter("password").equals("azeem"))
{
out.write("1");
}
else
out.write("0");
%> </br>
Now my android code is somerhing like this
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_agent_login);
edit_username = (EditText) findViewById(R.id.edit_username);
edit_password = (EditText) findViewById(R.id.edit_password);
btn_login = (Button) findViewById(R.id.btnLogin);
if (android.os.Build.VERSION.SDK_INT > 9) { // must add this code in
// order not to get the
// Exception while executing
// program
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
.permitAll().build();
StrictMode.setThreadPolicy(policy);
}
btn_login.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
username = edit_username.getText().toString();
password = edit_password.getText().toString();
Log.d(TAG, "Username:" + username);
Log.d(TAG, "Password:" + password);
try {
new Thread() {
public void run() {
try {
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost("http://10.0.2.2:8080/MyApp/login.jsp");
List<NameValuePair> pairs = new ArrayList<NameValuePair>(2);
pairs.add(new BasicNameValuePair("username",edit_username.getText().toString()));
pairs.add(new BasicNameValuePair("password",edit_password.getText().toString()));
post.setEntity(new UrlEncodedFormEntity(pairs));
HttpResponse response = client.execute(post);
HttpEntity httpEntity = response.getEntity();
xml = EntityUtils.toString(httpEntity);
Log.d("xml", ""+xml.length()); //To confirm anything is there in the "xml"
} catch (Exception e) {
e.printStackTrace();
}
}
}.start();
} catch (Exception e) {
Log.d("xml", xml.toString());
Log.d("Server", e.toString());
}
try {
if (Integer.parseInt(String.valueOf(xml.charAt(10))) == 1) { //****HERE*******
Toast.makeText(getApplicationContext(), "LoginSuccessful",Toast.LENGTH_SHORT).show();
Intent intent = new Intent(Agent_Login.this,AgentHome.class);
startActivity(intent);
} else {
Toast.makeText(getApplicationContext(),"Invalid Username or Password", Toast.LENGTH_SHORT).show();
edit_password.setText("");
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
}
Now on HERE (in comment) there gives a NullPointerException, which is I think because the xml is empty.
So, my question is how can I get the reply from the JSP in Android. I tested it on PC with an HTML form and its working absolutely fine.
Any help would be greatly appreciated.
A varaible is named xml but it will probably not contain any XML, as far is I can see; you're returning HTML.
Why would the 1 be located at position 10 in the returned string?
You're logging the content of xml; what is its value?

Uploading Images to tumblr API from Android

One assumed using the Tumblr API to upload images would be easy. It isn't. (EDIT It is now, see Edit 2 at the end of this entry)
My app is supposed to upload an image to tumblr. I would prefer doing that from a service but for now I use an activity that closes itself as soon as its done uploading. In OnCreate() the user is authenticated:
consumer = new CommonsHttpOAuthConsumer(CONSUMER_KEY, CONSUMER_SECRET);
// It uses this signature by default
// consumer.setMessageSigner(new HmacSha1MessageSigner());
provider = new CommonsHttpOAuthProvider(REQUEST_TOKEN_URL,ACCESS_TOKEN_URL,AUTH_URL);
String authUrl;
try
{
authUrl = provider.retrieveRequestToken(consumer, CALLBACK_URL);
Log.d(TAG, "Auth url:" + authUrl);
startActivity(new Intent("android.intent.action.VIEW", Uri.parse(authUrl)));
}
This opens a browser activity where the user can add username and passoword and then the app returns to the activity (this is also why I have to use an activity, I don't know how to do this from a service)
Returning from the browser the data is extracted:
Uri uri = context.getIntent().getData();
if (uri != null && uri.toString().startsWith(CALLBACK_URL))
{
Log.d(TAG, "uri!=null");
String verifier = uri.getQueryParameter("oauth_verifier");
Log.d(TAG, "verifier"+verifier);
try
{
provider.setOAuth10a(true);
provider.retrieveAccessToken(consumer, verifier);
Log.d(TAG, "try");
}
catch (Exception e)
{
Log.e(TAG, e.toString());
e.printStackTrace();
}
OAUTH_TOKEN = consumer.getToken();
OAUTH_SECRET = consumer.getTokenSecret();
Most of these two snippets I got from here and they work well.
With these tokens I can now try putting data on tumblr. When I try to add Text this works fine using this method:
private void createText()
{
if(!OAUTH_TOKEN.equals(""))
{
HttpContext context = new BasicHttpContext();
HttpPost request = new HttpPost("http://api.tumblr.com/v2/blog/" + blogname + ".tumblr.com/post");
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("type", "text"));
nameValuePairs.add(new BasicNameValuePair("body", "this is just a test"));
try
{
request.setEntity(new UrlEncodedFormEntity(nameValuePairs));
}
catch (UnsupportedEncodingException e1)
{
Log.e(TAG, e1.toString());
e1.printStackTrace();
}
if (consumer == null)
{
consumer = new CommonsHttpOAuthConsumer(OAuthConstants.TUMBR_CONSUMERKEY, OAuthConstants.TUMBR_SECRETKEY);
}
if (OAUTH_TOKEN == null || OAUTH_SECRET == null)
{
Log.e(TAG, "Not logged in error");
}
consumer.setTokenWithSecret(OAUTH_TOKEN, OAUTH_SECRET);
try
{
consumer.sign(request);
}
catch (OAuthMessageSignerException e)
{
}
catch (OAuthExpectationFailedException e)
{
}
catch (OAuthCommunicationException e)
{
}
HttpClient client = new DefaultHttpClient();
//finally execute this request
try
{
HttpResponse response = client.execute(request, context);
HttpEntity responseEntity = response.getEntity();
if (responseEntity != null)
{
Log.d(TAG, "responseEntety!=null");
try
{
Log.d(TAG, EntityUtils.toString(responseEntity));
}
catch (ParseException e)
{
e.printStackTrace();
Log.e(TAG, e.toString());
}
catch (IOException e)
{
e.printStackTrace();
Log.e(TAG, e.toString());
} // gives me {"meta":{"status":401,"msg":"Not Authorized"},"response":[]} when I try to upload a photo
}
else
{
Log.d(TAG, "responseEntety==null");
}
}
catch (ClientProtocolException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
PostToTumblr.this.finish();
}
As you can see here http://www.tumblr.com/blog/snapnowandroid (at least as of this time) the text "this is just a test" is posted.
However, when I try to post images, it gets strange. Now I have checked around and apparently this is a well known issue with the tumblr API, which has excessively been discussed here and some have solved it in other programming languages (for example here) but I have been unable to repeat those successes.
The method (in its entirety below) has the exact same structure to the above method (that works), the nameValuePairs are just different
The method is given a Bitmap variable called photo:
private void uploadToTumblr(Bitmap photo)
This bitmap is converted into an array:
ByteArrayOutputStream stream = new ByteArrayOutputStream();
photo.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] bytes = stream.toByteArray();
The nameValuePairs are filled as follows:
nameValuePairs.add(new BasicNameValuePair(URLEncoder.encode("type", enc), URLEncoder.encode("photo", enc)));
nameValuePairs.add(new BasicNameValuePair(URLEncoder.encode("caption", enc), URLEncoder.encode(text, enc)));
nameValuePairs.add(new BasicNameValuePair("data", Base64.encodeToString(bytes, Base64.URL_SAFE)));
The result is a {"meta":{"status":400,"msg":"Bad Request"},"response":{"errors":["Error uploading photo."]}} from the tumblr api.
I have tries encoding the picture differently as discribed in this article but without any changes.
//http://www.coderanch.com/t/526487/java/java/Java-Byte-Hex-String
final char[] hexArray = {'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'};
char[] hexChars = new char[bytes.length * 3];
int v;
for ( int j = 0; j < bytes.length; j++ )
{
v = bytes[j] & 0xFF;
hexChars[j * 3] = '%';
hexChars[j * 3 + 1] = hexArray[v >>> 4];
hexChars[j * 3 + 2] = hexArray[v & 0x0F];
}
String s = new String(hexChars);
s = URLEncoder.encode(s, enc);
nameValuePairs.add(new BasicNameValuePair(URLEncoder.encode("data", enc), s));
Here the entire method (without the hex encoding):
private void uploadToTumblr(Bitmap photo)
{
if(!OAUTH_TOKEN.equals(""))
{
ByteArrayOutputStream stream = new ByteArrayOutputStream();
photo.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] bytes = stream.toByteArray();
String text ="SNAP";
HttpContext context = new BasicHttpContext();
HttpPost request = new HttpPost("http://api.tumblr.com/v2/blog/" + blogname + ".tumblr.com/post");
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
String enc = "UTF-8";
try
{
nameValuePairs.add(new BasicNameValuePair(URLEncoder.encode("type", enc), URLEncoder.encode("photo", enc)));
nameValuePairs.add(new BasicNameValuePair(URLEncoder.encode("caption", enc), URLEncoder.encode(text, enc)));
nameValuePairs.add(new BasicNameValuePair("data", Base64.encodeToString(bytes, Base64.URL_SAFE)));
}
catch (UnsupportedEncodingException e2)
{
Log.e(TAG, e2.toString());
e2.printStackTrace();
}
try
{
request.setEntity(new UrlEncodedFormEntity(nameValuePairs));
}
catch (UnsupportedEncodingException e1)
{
Log.e(TAG, e1.toString());
e1.printStackTrace();
}
if (consumer == null)
{
consumer = new CommonsHttpOAuthConsumer(OAuthConstants.TUMBR_CONSUMERKEY, OAuthConstants.TUMBR_SECRETKEY);
}
if (OAUTH_TOKEN == null || OAUTH_SECRET == null)
{
//throw new LoginErrorException(LoginErrorException.NOT_LOGGED_IN);
Log.e(TAG, "Not logged in error");
}
consumer.setTokenWithSecret(OAUTH_TOKEN, OAUTH_SECRET);
try
{
consumer.sign(request);
}
catch (OAuthMessageSignerException e)
{
}
catch (OAuthExpectationFailedException e)
{
}
catch (OAuthCommunicationException e)
{
}
HttpClient client = new DefaultHttpClient();
//finally execute this request
try
{
HttpResponse response = client.execute(request, context);
HttpEntity responseEntity = response.getEntity();
if (responseEntity != null)
{
Log.d(TAG, "responseEntety!=null");
try
{
Log.d(TAG, EntityUtils.toString(responseEntity));
}
catch (ParseException e)
{
e.printStackTrace();
Log.e(TAG, e.toString());
}
catch (IOException e)
{
e.printStackTrace();
Log.e(TAG, e.toString());
}
}
else
{
Log.d(TAG, "responseEntety==null");
}
}
catch (ClientProtocolException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
else
{
Log.d(TAG, "upload imposble... Toklen not set");
}
PostToTumblr.this.finish();
}
Now, while there are several things I am unhappy with (for example that this is done using an activity instead of a service) the big issue here is clearly the problem of uploading images. I am by no means the first to have this problem, so has anyone been able to get this done in java?
Edit 1
Have not made any progress with the problem at hand but created a workaround that might be nice for people who have the same issue. Tumblr offers posting via mail and you can programm android to send emails in the background as shown here. This works very well but you need to ask users to provide their mail account data and the Tumblr-mail Adress to post.
Edit 2
Years have pased and using email is no longer the easy way to do it. With jumblr there is finally a good API for Java that will work on android. OAuth-Authentication is no fun (it never is) but once you get past this, its fantastic.
Now, technically the question of how to do the authentication does not belong here but It's my overly long question, so I'll just paste some code here and if it's not interesting to you just skip it.
This uses a jar called jumblr-0.0.10-jar-with-dependencies.jar
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.util.Log;
import com.tumblr.jumblr.JumblrClient;
import com.tumblr.jumblr.request.RequestBuilder;
import com.tumblr.jumblr.types.Blog;
import com.tumblr.jumblr.types.User;
import org.scribe.builder.ServiceBuilder;
import org.scribe.builder.api.TumblrApi;
import org.scribe.model.Token;
import org.scribe.model.Verifier;
import org.scribe.oauth.OAuthService;
import java.io.File;
public class Tumblr
{
private static final String PROTECTED_RESOURCE_URL = "http://api.tumblr.com/v2/user/info";
static OAuthService service;
static Token requestToken=null;
public static void share(final Activity ctx, File file)
{
Thread tt = new Thread(new Runnable()
{
#Override
public void run()
{
JumblrClient client = new JumblrClient(Tumblr_Constants.CONSUMER_KEY, Tumblr_Constants.CONSUMER_SECRET);
RequestBuilder requestBuilder = client.getRequestBuilder();
requestBuilder.setConsumer(Tumblr_Constants.CONSUMER_KEY, Tumblr_Constants.CONSUMER_SECRET);
SharedPreferences settings = ctx.getSharedPreferences("TumblrData", 0);
String oauthToken=settings.getString("OauthToken", "");
String oauthTokenSecret=settings.getString("OauthSecret", "");
if(oauthToken.equals("") || oauthTokenSecret.equals(""))
{
authenticate(ctx);
while(WebViewFragment.verifier.equals(""))
{
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
String v = WebViewFragment.verifier;
Token accessToken = authenticatefurther(v);
SharedPreferences.Editor edit = settings.edit();
edit.putString("OauthToken", accessToken.getToken());
edit.putString("OauthSecret", accessToken.getSecret());
edit.commit();
oauthToken=settings.getString("OauthToken", "");
oauthTokenSecret=settings.getString("OauthSecret", "");
}
if(!oauthToken.equals("") && !oauthTokenSecret.equals(""))
{
client.setToken(oauthToken, oauthTokenSecret);
User user = client.user();
System.out.println(user.getName());
for (Blog blog : user.getBlogs()) {
Log.d("TUMBLR", blog.getTitle());
}
}
}
});
tt.start();
}
private static void authenticate(Context ctx) {
service = new ServiceBuilder()
.provider( TumblrApi.class )
.apiKey(Tumblr_Constants.CONSUMER_KEY)
.apiSecret(Tumblr_Constants.CONSUMER_SECRET)
.callback("snapnao://snapnao.de/ok") // OOB forbidden. We need an url and the better is on the tumblr website !
.build();
Log.d("TUMBLR", "=== Tumblr's OAuth Workflow ===" );
System.out.println();
// Obtain the Request Token
Log.d("TUMBLR", "Fetching the Request Token...");
requestToken = service.getRequestToken();
Log.d("TUMBLR", "Got the Request Token!");
Log.d("TUMBLR", "");
Log.d("TUMBLR", "Now go and authorize Scribe here:" );
Log.d("TUMBLR", service.getAuthorizationUrl( requestToken ) );
String url = service.getAuthorizationUrl(requestToken);
Intent i = new Intent(ctx, WebViewFragment.class);
i.putExtra("url", url);
ctx.startActivity(i);
}
private static Token authenticatefurther(String v)
{
Token accessToken = null;
Log.d("TUMBLR", "And paste the verifier here");
Log.d("TUMBLR", ">>");
Verifier verifier = new Verifier( v);
Log.d("TUMBLR", "");
// Trade the Request Token and Verfier for the Access Token
Log.d("TUMBLR", "Trading the Request Token for an Access Token...");
accessToken = service.getAccessToken( requestToken ,
verifier );
Log.d("TUMBLR", "Got the Access Token!");
Log.d("TUMBLR", "(if your curious it looks like this: " + accessToken + " )");
Log.d("TUMBLR", "");
return accessToken;
}
}
The WebViewFragement looks like this:
import android.app.Activity;
import android.graphics.Bitmap;
import android.net.http.SslError;
import android.os.Bundle;
import android.util.Log;
import android.webkit.SslErrorHandler;
import android.webkit.WebView;
import android.webkit.WebViewClient;
public class WebViewFragment extends Activity
{
public static String verifier="";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.webviewfragment);
String url = getIntent().getStringExtra("url");
Log.d("TUMBLR", "webview-> "+url);
WebView view = (WebView) findViewById(R.id.webView);
view.setWebViewClient(
new SSLTolerentWebViewClient()
);
view.getSettings().setJavaScriptEnabled(true);
view.loadUrl(url);
}
// SSL Error Tolerant Web View Client
private class SSLTolerentWebViewClient extends WebViewClient {
#Override
public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
handler.proceed(); // Ignore SSL certificate errors
}
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
super.onPageStarted(view, url, favicon);
Log.d("TUMBLR", "+++++"+url);
if(url.contains("oauth_verifier="))
{
String[] x = url.split("oauth_verifier=");
verifier=x[1].replace("#_=_", "");
WebViewFragment.this.finish();
}
}
}
}
Why don't you use Jumblr the official Java client for Tumblr.
Regards.
You can easily do this using jumblr - Tumblr java client
JumblrClient client = new JumblrClient(Constant.CONSUMER_KEY,Constant.CONSUMER_SECRET);
client.setToken(preferences.getString("token",null), preferences.getString("token_secret", null));
PhotoPost pp = client.newPost(client.user().getBlogs().get(0).getName(),PhotoPost.class);
pp.setCaption(caption);
// pp.setLinkUrl(link);
// pp.setSource(mImage); // String URL
pp.setPhoto(new Photo(imgFile));
pp.save();
This worked for me...
nameValuePairs.add(new BasicNameValuePair(URLEncoder
.encode("type", "UTF-8"),
URLEncoder.encode("photo", "UTF-8")));
Log.e("Tumblr", "Image shareing file path" + filePath);
nameValuePairs.add(new BasicNameValuePair("caption", caption));
nameValuePairs.add(new BasicNameValuePair("source", filePath));`
where filePath is http url.
I have use multipart
public class VideoUploader extends AsyncTask {
ProgressDialog progressDialog;
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
progressDialog = ProgressDialog.show(RecordingActivity.this, "",
"Uploading video.. ");
super.onPreExecute();
}
#Override
protected JSONObject doInBackground(String... params) {
JSONObject jsonObject = null;
StringBuilder builder = new StringBuilder();
try {
String url = UrlConst.VIDEO_URL;
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
FileBody filebodyVideo = new FileBody(new File(params[0]));
StringBody title = new StringBody("uploadedfile: " + params[0]);
StringBody description = new StringBody(
"This is a video of the agent");
// StringBody code = new StringBody(realtorCodeStr);
MultipartEntity reqEntity = new MultipartEntity();
reqEntity.addPart("uploadedfile", filebodyVideo);
reqEntity.addPart("title", title);
reqEntity.addPart("description", description);
// reqEntity.adddPart("code", code);
httppost.setEntity(reqEntity);
// DEBUG
System.out.println("executing request "
+ httppost.getRequestLine());
HttpResponse response = httpclient.execute(httppost);
HttpEntity resEntity = response.getEntity();
// DEBUG
StatusLine status = response.getStatusLine();
int statusCode = status.getStatusCode();
System.out.println(response.getStatusLine());
if (resEntity != null) {
System.out.println(EntityUtils.toString(resEntity));
} // end if
if (resEntity != null) {
resEntity.consumeContent();
} // end if
if (statusCode == 200) {
InputStream content = resEntity.getContent();
BufferedReader reader = new BufferedReader(
new InputStreamReader(content));
String line;
while ((line = reader.readLine()) != null) {
builder.append(line);
}
jsonObject = new JSONObject(builder.toString());
return jsonObject;
} else {
Log.e(LoginActivity.class.toString(),
"Failed to download file");
}
httpclient.getConnectionManager().shutdown();
} catch (Exception e) {
// TODO: handle exception
}
return null;
}
#Override
protected void onPostExecute(JSONObject result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
progressDialog.dismiss();
if (result != null) {
try {
JSONObject jsonObject = result
.getJSONObject(ParsingTagConst.COMMANDRESULT);
String strSuccess = jsonObject
.getString(ParsingTagConst.SUCCESS);
String responseString = jsonObject
.getString(ParsingTagConst.RESPONSE_STRING);
Toast.makeText(RecordingActivity.this, "" + responseString,
Toast.LENGTH_LONG).show();
if (strSuccess.equals("1")) {
// get here your response
}
} catch (Exception e) {
// TODO: handle exception
}
}
}
}
enter code here
I have done using following method. you can try this.
//paramString="text you want to put in caption"
private void postPhotoTumblr(String uploadedImagePhotoUrl, String paramString)
{
CommonsHttpOAuthConsumer localCommonsHttpOAuthConsumer = getTumblrConsumer();
String str1 = "logged in username";
String encodedImage = uploadedImagePhotoUrl;
DefaultHttpClient localDefaultHttpClient = new DefaultHttpClient();
HttpPost localHttpPost = new HttpPost("http://api.tumblr.com/v2/blog/" + str1 + ".tumblr.com/post");
try
{
ArrayList localArrayList = new ArrayList();
localArrayList.add(new BasicNameValuePair("type", "photo"));
BasicNameValuePair localBasicNameValuePair = new BasicNameValuePair("caption", paramString);
localArrayList.add(localBasicNameValuePair);
localArrayList.add(new BasicNameValuePair("data",encodedImage));
UrlEncodedFormEntity localUrlEncodedFormEntity = new UrlEncodedFormEntity(localArrayList);
localHttpPost.setEntity(localUrlEncodedFormEntity);
localCommonsHttpOAuthConsumer.sign(localHttpPost);
InputStream localInputStream = localDefaultHttpClient.execute(localHttpPost).getEntity().getContent();
InputStreamReader localInputStreamReader = new InputStreamReader(localInputStream);
BufferedReader localBufferedReader = new BufferedReader(localInputStreamReader);
StringBuilder localStringBuilder = new StringBuilder();
while (true)
{
String str2 = localBufferedReader.readLine();
if (str2 == null)
{
Log.i("DATA post resp", localStringBuilder.toString());
break;
}
localStringBuilder.append(str2);
}
}
catch (ClientProtocolException localClientProtocolException)
{
localClientProtocolException.printStackTrace();
}
catch (IOException localIOException)
{
localIOException.printStackTrace();
}
catch (OAuthMessageSignerException localOAuthMessageSignerException)
{
localOAuthMessageSignerException.printStackTrace();
}
catch (OAuthExpectationFailedException localOAuthExpectationFailedException)
{
localOAuthExpectationFailedException.printStackTrace();
}
catch (OAuthCommunicationException localOAuthCommunicationException)
{
localOAuthCommunicationException.printStackTrace();
}
}
EDIT : First Upload image to Web Server then get Url and try to Post with uploaded Url or File path. it will work fine sure... :)

restarting AsyncTask in Service

I have Service and AsyncTask in it, which due to check updatings on the server. It have to be reexecuted if it get some data and also if it doesn't. So my AsyncTask implementation is :
private class DklabExecute extends AsyncTask<Void, String, Void> {
int count;
Calendar calendar = Calendar.getInstance();
java.util.Date now = calendar.getTime();
java.sql.Timestamp currentTimestamp = new java.sql.Timestamp(now.getTime());
String url = "http://192.168.0.250:81/?identifier=nspid_"+md5(LoginActivity.passUserId)+
",nspc&ncrnd="+Long.toString(currentTimestamp.getTime());
HttpGet rplPost = new HttpGet(url);
protected Void doInBackground(Void... args)
{
Log.i("service count", Integer.toString(count));
count ++;
Log.i("md5 func", md5(LoginActivity.passUserId));
String testData = "http://192.168.0.250/app_dev.php/api/comet/testOrder/";
JSONParser parser = new JSONParser();
DefaultHttpClient testClient = new DefaultHttpClient();
DefaultHttpClient rplClient = new DefaultHttpClient();
try {
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("", ""));
HttpGet httpTest = new HttpGet(testData);
httpTest.setHeader("Cookie", CookieStorage.getInstance().getArrayList().get(0).toString());
rplPost.setHeader("Cookie", CookieStorage.getInstance().getArrayList().get(0).toString());
try {
httpResponse = rplClient.execute(rplPost);
}
catch (ClientProtocolException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
Header[] head = httpResponse.getAllHeaders();
Log.i("http Response",httpResponse.toString());
for (Header one:head)
{
Log.i("headers",one.toString());
}
Log.i("response code", Integer.toString(httpResponse.getStatusLine().getStatusCode()));
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null)
{
sb.append(line);// + "n");
}
try
{
is.close();
}
catch (IOException e)
{
e.printStackTrace();
}
json = sb.toString();
Log.i("rpl response",json);
if (new JSONArray(json) != null)
jArr = new JSONArray(json);
else
this.cancel(true);
JSONObject toObj = jArr.getJSONObject(0);
JSONObject data = toObj.getJSONObject(KEY_DATA);
if (data.has(KEY_ORDER))
{
for (Order a : ServiceMessages.orderExport)
{
Log.i("service before list", a.toString());
}
Log.i(" ", " ");
for (Order a : DashboardActivityAlt.forPrint)
{
Log.i("before dashboard list", a.toString());
}
JSONObject jsonOrder = data.getJSONObject(KEY_ORDER);
Gson gson = new Gson();
Order orderObj= gson.fromJson(jsonOrder.toString(), Order.class);
try
{
for (ListIterator<Order> itr = orderExport.listIterator(); itr.hasNext();)
{
Order a = itr.next();
Log.i("order count", a.toString());
if(orderObj.getOrderid()==a.getOrderid())
{
Log.i("Service","order was changed");
a = orderObj;
someMethod("Your order "+ orderObj.getTitle() + " was changed");
}
else
{
Log.i("Service","order"+ orderObj.getTitle()+" was added");
// DashboardActivityAlt.forPrint.add(0, orderObj);
ServiceMessages.orderExport.add(0,orderObj);
Log.i("status",Integer.toString(orderObj.getProcess_status().getProccessStatusId()));
someMethod("Your order "+ orderObj.getTitle() + " was added");
}
}
}
catch (Exception e)
{
e.printStackTrace();
}
for (Order a : ServiceMessages.orderExport)
{
Log.i("service after list", a.toString());
}
Log.i(" ", " ");
for (Order a : DashboardActivityAlt.forPrint)
{
Log.i("after dashboard list", a.toString());
}
// intentOrder.putParcelableArrayListExtra("ordersService", orderExport);
sendBroadcast(intentOrder);
Log.i("after parse order",orderObj.toString());
Log.i("orders after updating",DashboardActivityAlt.orders.toString() );
}
else if (data.has(KEY_MESSAGE))
{
JSONObject jsonMessage = data.getJSONObject(KEY_MESSAGE);
Gson gson = new Gson();
Log.i("messages before parse", jsonMessage.toString());
for (Order a: DashboardActivityAlt.forPrint)
{
Log.i("messages count", Integer.toString(a.getCusThread().getMessages().size()));
}
Log.i("disparse message",jsonMessage.toString());
Message message = gson.fromJson(jsonMessage.toString(),Message.class);
Log.i("incomming message",message.toString());
JSONObject jsonThread = jsonMessage.getJSONObject(KEY_THREAD);
Threads thread = gson.fromJson(jsonThread.toString(),Threads.class);
Log.i("incomming thread",thread.toString());
Order orderChanged = new Order();
String orderName = null;
for(Order as : DashboardActivityAlt.forPrint)
{
if (as.getOrderid() == thread.getTreadOrder().getOrderid())
{
orderName = as.getTitle();
orderChanged = as;
Log.i("messages count after", Integer.toString(as.getCusThread().getMessages().size()));
}
}
Log.i("orderchanged",orderChanged.toString());
someMethod("Your order "+ thread.getTreadOrder().getTitle() + " was changed. Message was added");
orderChanged.getCusThread().addMessage(message);
sendBroadcast(intentMessage);
Log.i("messages service", "before sleep");
Log.i("messages service", "after sleep");
}
else
{
this.cancel(true);
}
}
catch (IllegalStateException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
} catch (IOException e2) {
rplClient.getConnectionManager().shutdown();
testClient.getConnectionManager().shutdown();
someMethod("You've lost internet connection. You should try later.");
e2.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
protected void onPostExecute(Void bitmap) {
this.cancel(true);
new DklabExecute().execute();
}
}
If I send some data to the server, it gives me back in JSON format via rpl server. Everything works good, but the problem is when I get some data from the server, AsyncTask reexecuted in onPostExecute() method and it is the same reapeted one or two times data in my list of orders. If I do not reexecute AsyncTask the listening happens only in onStartCommand() method but not permanently. Tell me please how can I implement this in the best manner...
if it's a service there's no reason to use an AsyncTask.
AyncTasks were build to deliver content back on the original thread (normally a UI thread), but services don't have those.
I suggest you use a ScheduledExecutorService instead http://developer.android.com/reference/java/util/concurrent/ScheduledExecutorService.html
private ScheduledExecutorService executor;
// call those on startCommand
executor = Executors.newSingleThreadScheduledExecutor();
executor.scheduleWithFixedDelay(run, 250,3000, TimeUnit.MILLISECONDS);
and have a Runnable doing the work
private Runnable run = new Runnable() {
#Override
public void run() {
// do your network stuff
}
};
and don't forget to cancel everything when your service stops
executor.shutdown();
edit:
or to use a thread in loop you can:
boolean isRunning;
.
// this on your start
Thread t = new Thread(run);
isRunning = true;
t.start();
the runnable
private Runnable run = new Runnable() {
#Override
public void run() {
while(isRunning){
// do your network stuff
}
}
};
and again, don't forget to finish it whenever the service finishes with:
isRunning = false;

putting bitmap image into image view of listview

I want to put bitmap images into ImageView of ListView. i changed image from url to bitmap image. I have 10 images and i have to put the images in each item of the ListView. Is there any method other than Lazy Adapter ?? Thanks in advance!!!
this is my code
public class Propertylist extends ListActivity {
String proptype;
String prop;
String estimate;
String photo;
String get;
String[] data;
TextView text;
URL aURL;
InputStream is = null;
String result = "";
JSONObject jArray = null;
//Hashtable<String,Bitmap> imagemap;
private ArrayList<NameValuePair> nameValuePairs;
private LayoutInflater inflater;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main3);
text = (TextView) findViewById(R.id.text);
Toast.makeText(getApplicationContext(), "Displaying popertylist for zipcode "+get, Toast.LENGTH_LONG).show();
ArrayList<HashMap<String, String>> mylist = new ArrayList<HashMap<String, String>>();
//ArrayList<Hashtable<String, Bitmap>> mylist1 = new ArrayList<Hashtable<String, Bitmap>>();
Bundle bundle = this.getIntent().getExtras();
get = bundle.getString("name");
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://www.propertyhookup.com/mobile/propertylist.php");
nameValuePairs = new ArrayList<NameValuePair>(1);
nameValuePairs.add(new BasicNameValuePair("zipcode", get.trim()));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
}catch(Exception e){
Toast.makeText(getApplicationContext(), e.getMessage(), Toast.LENGTH_LONG).show();
}
//convert response to string
try{
BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result=sb.toString();
}catch(Exception e){
Toast.makeText(getApplicationContext(), e.getMessage(), Toast.LENGTH_LONG).show();
}
if(result.length()<= 7){
Toast.makeText(getApplicationContext(), "No properties for this zipcode or check your zipcode ", Toast.LENGTH_LONG).show();
text.setText("No properties for this zipcode or check your zipcode");
}
else{
try{
jArray = new JSONObject(result);
}catch(JSONException e){
Toast.makeText(getApplicationContext(), e.getMessage(), Toast.LENGTH_LONG).show();
}
//JSONObject json = JSONfunctions.getJSONfromURL("http://192.168.1.111/propertyhookup.com/mobile/propertylist.php");
try{
JSONArray earthquakes = jArray.getJSONArray("earthquakes");
for(int i=0;i<10;i++){
HashMap<String, String> map = new HashMap<String, String>();
//imagemap = new Hashtable<String, Bitmap>();
JSONObject e = earthquakes.getJSONObject(i);
if(e.getString("property_type").contains("1")) {
proptype ="Single Family Home";
}else if(e.getString("property_type").contains("2")) {
proptype="Condo";
}else if(e.getString("property_type").contains("3")) {
proptype="Townhouse";
}
if(e.getString("estimated_price").contains("0")) {
estimate = "Not Enough Market Value";
//estimat = (TextView) findViewById(R.id.estimat);
//estimat.setTextColor(Color.rgb(0, 0, 23));
}else {
estimate = "$"+e.getString("estimated_price");
}
photo = e.getString("photo1");
map.put("id", String.valueOf(i));
map.put("percent", e.getString("percentage_depreciation_value")+"%");
map.put("propertyid", "#"+e.getString("property_id")+" ");
map.put("cityname",e.getString("city_name")+",");
map.put("statecode",e.getString("state_code"));
map.put("propertytype","| "+ proptype);
map.put("footage", e.getString("house_square_footage")+" Sq.Ft");
map.put("bathroom", "| "+e.getString("bathrooms")+" Bath, ");
map.put("bedroom", e.getString("bathrooms")+" Bedrooms");
map.put("price", "List Price: $"+e.getString("property_price"));
map.put("estimated", "Base Market Value: "+estimate);
//map.put("photos",photo );
mylist.add(map);
}
}catch(JSONException e) {
Toast.makeText(getApplicationContext(),e.getMessage(), Toast.LENGTH_LONG).show();
}
try
{
aURL = new URL(photo);
}
catch (MalformedURLException e1)
{
// TODO Auto-generated catch block
e1.printStackTrace();
}
URLConnection conn = null;
try
{
conn = aURL.openConnection();
}
catch (IOException e1)
{
// TODO Auto-generated catch block
e1.printStackTrace();
}
try
{
conn.connect();
}
catch (IOException e1)
{
// TODO Auto-generated catch block
e1.printStackTrace();
}
InputStream is = null;
try
{
is = conn.getInputStream();
}
catch (IOException e1)
{
// TODO Auto-generated catch block
e1.printStackTrace();
}
BufferedInputStream bis = new
BufferedInputStream(is,8*1024);
Bitmap bm = BitmapFactory.decodeStream(bis);
//imagemap.put("im",bm);
// mylist1.add(imagemap);
ListAdapter adapter = new SimpleAdapter(this, mylist , R.layout.main4,
new String[] { "percent","propertyid", "cityname", "statecode", "propertytype", "footage", "bathroom", "bedroom", "price", "estimated" },
new int[] { R.id.percent, R.id.property_id, R.id.city_name, R.id.state_code, R.id.prop_type, R.id.foot, R.id.bath, R.id.bed, R.id.list, R.id.estimat});
setListAdapter(adapter);
final ListView lv = getListView();
lv.setTextFilterEnabled(true);
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
#SuppressWarnings("unchecked")
HashMap<String, String> o = (HashMap<String, String>) lv.getItemAtPosition(position);
Toast.makeText(Propertylist.this, "ID '" + o.get("id") + "' was clicked.", Toast.LENGTH_SHORT).show();
}
});
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.icon: //Toast.makeText(this, "You pressed the icon!", Toast.LENGTH_LONG).show();
displaylogin();
break;
case R.id.text: //Toast.makeText(this, "You pressed the text!", Toast.LENGTH_LONG).show();
displayproperty();
break;
// case R.id.icontext: Toast.makeText(this, "You pressed the icon and text!", Toast.LENGTH_LONG).show();
// break;
}
return true;
}
private void displaylogin() {
startActivity(new Intent(this,Changezip.class));
finish();
}
private void displayproperty() {
startActivity(new Intent(this,property.class));
}
}
You might want to check out the GreenDroid library; it makes doing things like this trivial.
Please note that you have asked 4 previous questions that received answers and you have not accepted any of them. This community functions based on people accepting answers and if you don't start accepting answers you've found useful, you may find that people stop answering you.

Categories

Resources