I am trying to implement contact pciker in android, i am able to launch contact picker in android, but when i select the contact i get back null value, i.e. no number in my textfield. What am i doing wrong ?
Here is my code.
mainactivity.java
package com.example.textmessage;
import java.util.Timer;
import java.util.TimerTask;
import android.location.LocationManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.provider.Contacts.People;
import android.provider.ContactsContract;
import android.provider.ContactsContract.CommonDataKinds.Phone;
import android.provider.Settings;
import android.app.Activity;
import android.content.ContentResolver;
import android.content.Intent;
import android.database.Cursor;
import android.support.v4.app.FragmentActivity;
import android.telephony.SmsManager;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioButton;
import com.google.android.gms.maps.SupportMapFragment;
import android.widget.Toast;
public class MainActivity extends FragmentActivity{
protected static final int CONTACT_PICKER_RESULT = 0;
int count=0;
private RadioButton radioBtnten;
private RadioButton radioBtnone;
Button sendBtn,contact;
EditText txtphoneNo;
EditText txtMessage;
GPSTracker gps;
Timer timer;
TimerTask timerTask;
final Handler handler = new Handler();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
LocationManager service = (LocationManager) getSystemService(LOCATION_SERVICE);
boolean enabled = service.isProviderEnabled(LocationManager.GPS_PROVIDER);
if (!enabled)
{
Toast.makeText(getApplicationContext(), "Your GPS IS NOT ON SWITCH IT ON HERE",Toast.LENGTH_LONG).show();
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(intent);
}
radioBtnten=(RadioButton)findViewById(R.id.ten);
radioBtnone=(RadioButton)findViewById(R.id.one);
sendBtn = (Button) findViewById(R.id.btnSendSMS);
txtphoneNo= (EditText) findViewById(R.id.editTextPhoneNo);
contact = (Button)findViewById(R.id.contact);
//txtMessage //= (EditText) findViewById(R.id.editTextSMS);
gps = new GPSTracker(MainActivity.this);
contact.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Intent intent = new Intent(Intent.ACTION_PICK,ContactsContract.Contacts.CONTENT_URI);
intent.setType(ContactsContract.CommonDataKinds.Phone.CONTENT_TYPE);
startActivityForResult(intent, CONTACT_PICKER_RESULT);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
Uri contact = data.getData();
ContentResolver cr = getContentResolver();
Cursor c = managedQuery(contact, null, null, null, null);
// c.moveToFirst();
while(c.moveToNext()){
String id = c.getString(c.getColumnIndex(ContactsContract.Contacts._ID));
String name = c.getString(c.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
if (Integer.parseInt(c.getString(c.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0) {
Cursor pCur = cr.query(Phone.CONTENT_URI,null,Phone.CONTACT_ID +" = ?", new String[]{id}, null);
while(pCur.moveToNext()){
String phone = pCur.getString(pCur.getColumnIndex(Phone.NUMBER));
txtphoneNo.setText(phone);
}
}
}
sendBtn.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
startTimer();
sendSMSMessage();
Intent toAnotherActivity = new Intent(MainActivity.this, maps.class);
startActivityForResult(toAnotherActivity, 0);
}
});
}
public void startTimer() {
//set a new Timer
timer = new Timer();
//initialize the TimerTask's job
initializeTimerTask();
//schedule the timer, after the first 5000ms the TimerTask will run every 10000ms//
if(radioBtnten.isChecked()==true)
timer.schedule(timerTask, 5000, 10000);
// if(radioBtn2.isSelected()==true)
else if(radioBtnone.isChecked()==true)
timer.schedule(timerTask, 5000, 1000);
}
public void initializeTimerTask() {
timerTask = new TimerTask() {
public void run() {
//use a handler to run a toast that shows the current timestamp
handler.post(new Runnable() {
public void run() {
//get the current timeStamp
Toast.makeText(getApplicationContext(), "your message has been sent, the message(s) sent are:-"+count++,Toast.LENGTH_LONG).show();
sendSMSMessage();
//show the toast
}
});
}
};
}
public void stoptimertask(View v)
{
//stop the timer, if it's not already null
Toast.makeText(getApplicationContext(), "Stop button pressed",Toast.LENGTH_LONG).show();
if (timer != null)
{
timer.cancel();
timer = null;
}
}
protected void sendSMSMessage() {
Log.i("Send SMS", "");
double latitude = gps.getLatitude();
double longitude = gps.getLongitude();
String phoneNo = txtphoneNo.getText().toString();
String message = "These are my co-ordinates:-"+ latitude + ", " + longitude;
try {
SmsManager smsManager = SmsManager.getDefault();
smsManager.sendTextMessage(phoneNo, null, message, null, null);
Toast.makeText(getApplicationContext(), "SMS sent.",
Toast.LENGTH_LONG).show();
} catch (Exception e) {
Toast.makeText(getApplicationContext(),
"SMS faild, please try again.",
Toast.LENGTH_LONG).show();
e.printStackTrace();
}
}
#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;
}
}
P.S. i have mentioned the permission in manifest.
From your code it seems to be you have not added onActivityResult method. Put the following code in in onActivityResult method
public void onActivityResult(int reqCode, int resultCode, Intent data) {
super.onActivityResult(reqCode, resultCode, data);
Uri contact = data.getData();
ContentResolver cr = getContentResolver();
Cursor c = managedQuery(contact, null, null, null, null);
while(c.moveToNext()){
String id = c.getString(c.getColumnIndex(ContactsContract.Contacts._ID));
String name = c.getString(c.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
if (Integer.parseInt(c.getString(c.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0) {
Cursor pCur = cr.query(Phone.CONTENT_URI,null,Phone.CONTACT_ID +" = ?", new String[]{id}, null);
while(pCur.moveToNext()){
String phone = pCur.getString(pCur.getColumnIndex(Phone.NUMBER));
tv.setText( phone);
}
}
}}
Related
I am android developer .I have face issue ANR when multiple image send in background using intent service.I have call service on Resume() method.I have update UI when step by step image upload finish .My all code in service .But i don't understand why my UI hang.I have created ResultReceiver class for Update UI. Please tell me what is wrong i am doing.
public class UploadImageService extends IntentService {
public static final int STATUS_RUNNING = 0;
public static final int STATUS_FINISHED = 1;
public static final int STATUS_ERROR = 2;
private static final String TAG = "UploadImageService";
public static String SHOW_MSG = "showMsg";
public static String SET_IN_ADAPTER = "setData";
public static String UPLOAD_IMAGE = "uploadImage";
public static String RESULT = "result";
private String threadType, toUser, chatThreadId, gcmRegistrationId, openCloseChatWindowType, recipientName, threadTopicName, attachmentID, attachmentType, currentChunks, originalBase64Img, dateTime, classType, loginUserId;
// Declare Web services variable
private MultipartEntity multipartEntityBuilder;
Database database;
Bundle bundle;
ResultReceiver receiver;
public UploadImageService() {
super(UploadImageService.class.getName());
}
#Override
protected void onHandleIntent(Intent intent) {
//initialize database
database = new Database(UploadImageService.this, Database.DATABASE_NAME, null, Database.DATABASE_VERSION);
Log.d(TAG, "Service Started!");
receiver = intent.getParcelableExtra("receiver");
try {
bundle = new Bundle();
/* Update UI: upload Service is Running */
//receiver.send(STATUS_RUNNING, Bundle.EMPTY);
try {
new UploadThumbImageAsync().execute();
} catch (Exception e) {
e.printStackTrace();
bundle.putString(Intent.EXTRA_TEXT, e.toString());
receiver.send(STATUS_ERROR, bundle);
}
/* new Thread(new Runnable(){
public void run() {
// TODO Auto-generated method stub
while(true)
{
try {
new UploadThumbImageAsync().execute();
} catch (Exception e) {
e.printStackTrace();
bundle.putString(Intent.EXTRA_TEXT, e.toString());
receiver.send(STATUS_ERROR, bundle);
}
}
}
}).start();*/
} catch (Exception e) {
e.printStackTrace();
}
Log.e(TAG, "Service Stopping!");
//this.stopSelf();
}
private class UploadThumbImageAsync extends AsyncTask<String, Void, String> {
/*this method is use for initializing dialog(ProgressDialog,CustomDialog) and showing*/
String toUser, comTypeId, threadType, chatThreadId, threadTopicName, chatAttachmentType, chatMessage, thumbBase64AttachmentPath /*original_image*/, loginUserName, recipientName, originalBase64Image, originalFilePath;
#Override
protected void onPreExecute() {
super.onPreExecute();
//showProgressDialog();
}
/*starts the loading of the data in background in doInBackground() method */
#Override
protected String doInBackground(String... params) {
try {
toUser = params[0];
comTypeId = params[1];
threadType = params[2];
chatThreadId = params[3];
threadTopicName = params[4];
chatAttachmentType = params[5];
chatMessage = params[6];
thumbBase64AttachmentPath = params[7];
loginUserName = params[8];
recipientName = params[9];
originalBase64Image = params[10];
originalFilePath = params[11];
String url;
if (!TextUtils.isEmpty(threadType) && threadType.equals(RecentChatList.SIMPLE_TYPE)) {
url = WS.URL.concat(WS.SAVE_CHAT);
} else {
url = WS.URL.concat(WS.GROUP_SAVE_CHAT);
}
Log.e(TAG, "url_" + chatMessage + " = " + url);
String response = HttpClientExecuteMethod.executeMultipartPostMethod(url, multipartEntityBuilder);
//Log.e(TAG, "save_chat_history_response_" + threadType + "_" + chatMessage + " =" + response);
return response;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
/*This method is called after the background computation finishes.
The result of background process in passed in this method as parameters
and now you can dismiss progress dialog
and get the result and display on onPostExecute() method
*/
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
try {
// Log.e(TAG, "chatAttachmentType = " + chatAttachmentType);
updateCounter();
if (result != null) {
JSONObject jo = new JSONObject(result);
String success = null;
final int storeLimit = SharedPreference.getLimit(UploadImageService.this);
if (jo.has(WS.SUCCESS)) {
success = jo.getString(WS.SUCCESS);
if (!TextUtils.isEmpty(success) && success.equals("0")) {
return;
}
if (!TextUtils.isEmpty(success) && success.equals("100")) {
callWsSaveChat(chatAttachmentType, chatMessage, thumbBase64AttachmentPath, originalBase64Image, originalFilePath);
updateRecentChatAndThreadList();
return;
}
if (!TextUtils.isEmpty(success) && success.equals("99")) {
updateRecentChatAndThreadList();
return;
}
}
try {
ArrayList<Chat> saveChatArrayList = null;
if (!TextUtils.isEmpty(success) && success.equals("1")) {
saveChatArrayList = new Chat().getChatHistory(UploadImageService.this, result, TAG, "");
// Log.e(TAG, "onPostExecute_saveChatArrayList.size = " + saveChatArrayList);
ArrayList<Chat> chatHistoryWithoutMsgId = database.getWithoutMsgIdChatHistory(chatThreadId, "#");
//Log.e(TAG, "onPostExecute_chatHistoryWithoutMsgId.size = " + chatHistoryWithoutMsgId.size());
if (saveChatArrayList != null && !saveChatArrayList.isEmpty() && saveChatArrayList.size() > 0) {
for (int i = 0; i < saveChatArrayList.size(); i++) {
final Chat apiChat = saveChatArrayList.get(i);
String apiMsg = apiChat.getMessage();
String apiThumb = null;
if (!TextUtils.isEmpty(apiChat.getAttachment_thumb())) {
apiThumb = apiChat.getAttachment_thumb().concat("$");
}
if (chatHistoryWithoutMsgId != null && !chatHistoryWithoutMsgId.isEmpty() && chatHistoryWithoutMsgId.size() > 0) {
for (int j = 0; j < chatHistoryWithoutMsgId.size(); j++) {
Chat dbChat = chatHistoryWithoutMsgId.get(j);
final String db_message = dbChat.getMessage();
final String db_thumb = dbChat.getAttachment_thumb();
if (apiThumb.equals(db_thumb)) {
database.updateChatList(apiChat, result, "#", db_message, db_thumb, loginUserId, toUser, chatThreadId, threadType);
bundle.putString(RESULT, UPLOAD_IMAGE);
receiver.send(STATUS_FINISHED, bundle);
if (!TextUtils.isEmpty(chatAttachmentType) && chatAttachmentType.equals(getResources().getString(R.string.Image))) {
originalBase64Image = getBase64Image(originalFilePath);
}
int subLength = 1024 * 256;
//Log.e(TAG, "upload_subLength = " + subLength);
int index = 0;
int totalChunks = 0;
if (!TextUtils.isEmpty(originalBase64Image)) {
for (int k = 0; index < originalBase64Image.length(); k++) {
index = index + subLength;
totalChunks++;
}
database.insertOriginalUploadImageList(apiChat.getAttachment_id(), totalChunks, 0, originalFilePath, chatThreadId, apiChat.getDt_sender_created(), chatAttachmentType);
// database.deleteAttachmentImageList(originalBase64Image);
database.deleteAttachmentImageList(originalFilePath);
UploadOriginalImageList(apiChat.getAttachment_id());
}
break;
} else {
// Log.e(TAG, "onPostExecute_not_equal_image");
}
}
}
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
} else {
// Util.showAlertDialog(mContext, mContext.getResources().getString(R.string.No_internet_connection_available));
}
}
} catch (Exception e) {
e.printStackTrace();
Log.e(TAG, "error = " + e.getMessage());
}
}
There are many methods to upload more images to the server.. one could be including two libraries: apache-mime4j-0.6.jar and httpmime-4.0.1.jar.. After that create your java main code:
import java.io.File;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
public class FileUploadTest extends Activity {
private static final int SELECT_FILE1 = 1;
private static final int SELECT_FILE2 = 2;
String selectedPath1 = "NONE";
String selectedPath2 = "NONE";
TextView tv, res;
ProgressDialog progressDialog;
Button b1,b2,b3;
HttpEntity resEntity;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
tv = (TextView)findViewById(R.id.tv);
res = (TextView)findViewById(R.id.res);
tv.setText(tv.getText() + selectedPath1 + "," + selectedPath2);
b1 = (Button)findViewById(R.id.Button01);
b2 = (Button)findViewById(R.id.Button02);
b3 = (Button)findViewById(R.id.upload);
b1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
openGallery(SELECT_FILE1);
}
});
b2.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
openGallery(SELECT_FILE2);
}
});
b3.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if(!(selectedPath1.trim().equalsIgnoreCase("NONE")) && !(selectedPath2.trim().equalsIgnoreCase("NONE"))){
progressDialog = ProgressDialog.show(FileUploadTest.this, "", "Uploading files to server.....", false);
Thread thread=new Thread(new Runnable(){
public void run(){
doFileUpload();
runOnUiThread(new Runnable(){
public void run() {
if(progressDialog.isShowing())
progressDialog.dismiss();
}
});
}
});
thread.start();
}else{
Toast.makeText(getApplicationContext(),"Please select two files to upload.", Toast.LENGTH_SHORT).show();
}
}
});
}
public void openGallery(int req_code){
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent,"Select file to upload "), req_code);
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
Uri selectedImageUri = data.getData();
if (requestCode == SELECT_FILE1)
{
selectedPath1 = getPath(selectedImageUri);
System.out.println("selectedPath1 : " + selectedPath1);
}
if (requestCode == SELECT_FILE2)
{
selectedPath2 = getPath(selectedImageUri);
System.out.println("selectedPath2 : " + selectedPath2);
}
tv.setText("Selected File paths : " + selectedPath1 + "," + selectedPath2);
}
}
public String getPath(Uri uri) {
String[] projection = { MediaStore.Images.Media.DATA };
Cursor cursor = managedQuery(uri, projection, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
private void doFileUpload(){
File file1 = new File(selectedPath1);
File file2 = new File(selectedPath2);
import java.io.File;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
public class FileUploadTest extends Activity {
private static final int SELECT_FILE1 = 1;
private static final int SELECT_FILE2 = 2;
String selectedPath1 = "NONE";
String selectedPath2 = "NONE";
TextView tv, res;
ProgressDialog progressDialog;
Button b1,b2,b3;
HttpEntity resEntity;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
tv = (TextView)findViewById(R.id.tv);
res = (TextView)findViewById(R.id.res);
tv.setText(tv.getText() + selectedPath1 + "," + selectedPath2);
b1 = (Button)findViewById(R.id.Button01);
b2 = (Button)findViewById(R.id.Button02);
b3 = (Button)findViewById(R.id.upload);
b1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
openGallery(SELECT_FILE1);
}
});
b2.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
openGallery(SELECT_FILE2);
}
});
b3.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if(!(selectedPath1.trim().equalsIgnoreCase("NONE")) && !(selectedPath2.trim().equalsIgnoreCase("NONE"))){
progressDialog = ProgressDialog.show(FileUploadTest.this, "", "Uploading files to server.....", false);
Thread thread=new Thread(new Runnable(){
public void run(){
doFileUpload();
runOnUiThread(new Runnable(){
public void run() {
if(progressDialog.isShowing())
progressDialog.dismiss();
}
});
}
});
thread.start();
}else{
Toast.makeText(getApplicationContext(),"Please select two files to upload.", Toast.LENGTH_SHORT).show();
}
}
});
}
public void openGallery(int req_code){
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent,"Select file to upload "), req_code);
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
Uri selectedImageUri = data.getData();
if (requestCode == SELECT_FILE1)
{
selectedPath1 = getPath(selectedImageUri);
System.out.println("selectedPath1 : " + selectedPath1);
}
if (requestCode == SELECT_FILE2)
{
selectedPath2 = getPath(selectedImageUri);
System.out.println("selectedPath2 : " + selectedPath2);
}
tv.setText("Selected File paths : " + selectedPath1 + "," + selectedPath2);
}
}
public String getPath(Uri uri) {
String[] projection = { MediaStore.Images.Media.DATA };
Cursor cursor = managedQuery(uri, projection, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
private void doFileUpload(){
File file1 = new File(selectedPath1);
File file2 = new File(selectedPath2);
String urlString = "http://10.0.2.2/upload_test/upload_media_test.php";
try
{
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(urlString);
FileBody bin1 = new FileBody(file1);
FileBody bin2 = new FileBody(file2);
MultipartEntity reqEntity = new MultipartEntity();
reqEntity.addPart("uploadedfile1", bin1);
reqEntity.addPart("uploadedfile2", bin2);
reqEntity.addPart("user", new StringBody("User"));
post.setEntity(reqEntity);
HttpResponse response = client.execute(post);
resEntity = response.getEntity();
final String response_str = EntityUtils.toString(resEntity);
if (resEntity != null) {
Log.i("RESPONSE",response_str);
runOnUiThread(new Runnable(){
public void run() {
try {
res.setTextColor(Color.GREEN);
res.setText("n Response from server : n " + response_str);
Toast.makeText(getApplicationContext(),"Upload Complete. Check the server uploads directory.", Toast.LENGTH_LONG).show();
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
}
catch (Exception ex){
Log.e("Debug", "error: " + ex.getMessage(), ex);
}
}
}
Now your layout:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Multiple File Upload from CoderzHeaven"
/>
<Button
android:id="#+id/Button01"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Get First File">
</Button>
<Button
android:id="#+id/Button02"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Get Second File">
</Button>
<Button
android:id="#+id/upload"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Start Upload">
</Button>
<TextView
android:id="#+id/tv"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Selected File path : "
/>
<TextView
android:id="#+id/res"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text=""
/>
</LinearLayout>
of course, include the internet permission in your manifest:
<uses-permission android:name="android.permission.INTERNET" />
And voilĂ . Anyway i followed this example in my case: http://www.coderzheaven.com/2011/08/16/how-to-upload-multiple-files-in-one-request-along-with-other-string-parameters-in-android/ try to see there.. There are 4 methods to upload multiple files. See which you like
I am currently working with an Android content provider that i have created i use the query methode in a service because i have to update my result every 2 second my probleme is i want to get the last row in my databases, I put the sursor to the last position but every time his getting me all the data that he found in the database.
this is the service that I developed:
package fr.esigetel.echange.service;
import java.util.Timer;
import java.util.TimerTask;
import android.app.Service;
import android.content.ContentResolver;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.util.Log;
import fr.esigetel.mediatag.cp.WifiProvider;
public class informationService extends Service {
Timer mTimer;
private Handler mHandler = new Handler() {
#Override
public void handleMessage(Message msg) {
returnContentProvider();
}
};
#Override
public void onCreate() {
super.onCreate();
mTimer = new Timer();
Log.d("onCreate informationService", "onCreate informationService");
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
mTimer.scheduleAtFixedRate(new TimerTask() {
#Override
public void run() {
mHandler.sendEmptyMessage(0);
}
}, 0, 5000);
return super.onStartCommand(intent, flags, startId);
}
#Override
public void onDestroy() {
if (mTimer != null) {
mTimer.cancel();
mTimer = null;
}
if (mHandler != null) {
mHandler = null;
}
super.onDestroy();
}
#Override
public IBinder onBind(Intent intent) {
return null;
}
public informationService() {
}
private void returnContentProvider() {
Uri myuri = Uri.parse("content://fr.esigetel.mediatag.cp/maxdata");
ContentResolver cr = getContentResolver();
Cursor c = cr.query(myuri, null, null, null, null);
int idRech = c.getColumnIndex(WifiProvider.MAX_COL_ID);
int nameap = c.getColumnIndex(WifiProvider.MAX_COL_APName);
int adressemac = c.getColumnIndex(WifiProvider.MAX_COL_AdresseMac);
int rssi = c.getColumnIndex(WifiProvider.MAX_COL_RSSI);
int frequence = c.getColumnIndex(WifiProvider.MAX_COL_Freq);
int daterech = c.getColumnIndex(WifiProvider.MAX_Date);
c.moveToLast();
while (c.moveToPrevious()) {
int id = c.getInt(idRech);
String name = c.getString(nameap);
String mac = c.getString(adressemac);
int Rssi = c.getInt(rssi);
int Freq = c.getInt(frequence);
int Daterech = c.getInt(daterech);
try {
} catch (Exception e) {
System.out.println(e.getMessage());
}
Log.d("aaaaaa", name);
}
c.close();
}
How could i request only the last row of my database? this methode alway give me the whole data.
Cursor c = cr.query(myuri, null, null, null, null);
c.moveToLast();
Now Cursor Is At Last Possition And get The Last Record Data
int idRech = c.getColumnIndex(WifiProvider.MAX_COL_ID);
int nameap = c.getColumnIndex(WifiProvider.MAX_COL_APName);
int adressemac = c.getColumnIndex(WifiProvider.MAX_COL_AdresseMac);
int rssi = c.getColumnIndex(WifiProvider.MAX_COL_RSSI);
int frequence = c.getColumnIndex(WifiProvider.MAX_COL_Freq);
int daterech = c.getColumnIndex(WifiProvider.MAX_Date);
So here I want to have click event on pressing which i will have particular Category of location rather than search box for searching places. On pressing OnClickGPS it will open PlacePickerFragment of Facebook with search box at the top. But i want to search places category wise like Restaurent, Theatre, etc. on button click. Any assistance in this will be highly appreciable.
package com.priyank.checkin;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.pm.Signature;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.util.Base64;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import com.facebook.model.GraphLocation;
import com.facebook.model.GraphPlace;
import com.facebook.widget.PlacePickerFragment;
import com.facebook.Session;
public class PlacePickerSampleActivity extends FragmentActivity implements LocationListener {
private static final int PLACE_ACTIVITY = 1;
private static final Location SEATTLE_LOCATION = new Location("") {
{
setLatitude(47.6097);
setLongitude(-122.3331);
}
};
private static final Location SAN_FRANCISCO_LOCATION = new Location("") {
{
setLatitude(37.7750);
setLongitude(-122.4183);
}
};
private static final Location PARIS_LOCATION = new Location("") {
{
setLatitude(48.857875);
setLongitude(2.294635);
}
};
private TextView resultsTextView;
private LocationManager locationManager;
private Location lastKnownLocation;
private String NameEditTextValue;
private EditText NameEditText;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main7);
try {
PackageInfo info = getPackageManager().getPackageInfo(
"com.facebook.samples.hellofacebook",
PackageManager.GET_SIGNATURES);
for (Signature signature : info.signatures) {
MessageDigest md = MessageDigest.getInstance("SHA");
md.update(signature.toByteArray());
Log.d("KeyHash:", Base64.encodeToString(md.digest(), Base64.DEFAULT));
}
} catch (NameNotFoundException e) {
} catch (NoSuchAlgorithmException e) {
}
Button b=(Button) findViewById(R.id.button1);
b.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
NameEditTextValue = NameEditText.getText().toString();
Intent i = new Intent(Intent.ACTION_SEND);
i.setType("text/plain");
i.putExtra(Intent.EXTRA_SUBJECT, "Alert Message");
i.putExtra(Intent.EXTRA_TEXT, NameEditTextValue +"- via Security Android App");
startActivity(Intent.createChooser(i, "Alert Status"));
}
});
NameEditText = (EditText) findViewById(R.id.editText1);
resultsTextView = (TextView) findViewById(R.id.resultsTextView);
Button button = (Button) findViewById(R.id.seattleButton);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
onClickSeattle();
}
});
button = (Button) findViewById(R.id.sanFranciscoButton);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
onClickSanFrancisco();
}
});
button = (Button) findViewById(R.id.gpsButton);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
onClickGPS();
}
});
if (Session.getActiveSession() == null ||
Session.getActiveSession().isClosed()) {
Session.openActiveSession(this, true, null);
}
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
}
#Override
protected void onStart() {
super.onStart();
// Update the display every time we are started (this will be "no place selected" on first
// run, or possibly details of a place if the activity is being re-created).
displaySelectedPlace(RESULT_OK);
}
private void onError(Exception exception) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Error").setMessage(exception.getMessage()).setPositiveButton("OK", null);
builder.show();
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case PLACE_ACTIVITY:
displaySelectedPlace(resultCode);
break;
default:
Session.getActiveSession().onActivityResult(this, requestCode, resultCode, data);
break;
}
}
private void displaySelectedPlace(int resultCode) {
String results = "";
PlacePickerApplication application = (PlacePickerApplication) getApplication();
GraphPlace selection = application.getSelectedPlace();
if (selection != null) {
GraphLocation location = selection.getLocation();
results = String.format("Name: %s\nCategory: %s\nLocation: (%f,%f)\nStreet: %s, %s, %s, %s, %s",
selection.getName(), selection.getCategory(),
location.getLatitude(), location.getLongitude(),
location.getStreet(), location.getCity(), location.getState(), location.getZip(),
location.getCountry());
} else {
results = "<No place selected>";
}
resultsTextView.setText(results);
NameEditText.setText(results);
}
public void onLocationChanged(Location location) {
lastKnownLocation = location;
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
private void startPickPlaceActivity(Location location) {
PlacePickerApplication application = (PlacePickerApplication) getApplication();
application.setSelectedPlace(null);
Intent intent = new Intent(this, PickPlaceActivity.class);
PickPlaceActivity.populateParameters(intent, location, null);
startActivityForResult(intent, PLACE_ACTIVITY);
}
private void onClickSeattle() {
try {
startPickPlaceActivity(SEATTLE_LOCATION);
} catch (Exception ex) {
onError(ex);
}
}
private void onClickSanFrancisco() {
try {
startPickPlaceActivity(SAN_FRANCISCO_LOCATION);
} catch (Exception ex) {
onError(ex);
}
}
private void onClickGPS() {
try {
if (lastKnownLocation == null) {
Criteria criteria = new Criteria();
String bestProvider = locationManager.getBestProvider(criteria, false);
if (bestProvider != null) {
lastKnownLocation = locationManager.getLastKnownLocation(bestProvider);
}
}
if (lastKnownLocation == null) {
String model = android.os.Build.MODEL;
if (model.equals("sdk") || model.equals("google_sdk") || model.contains("x86")) {
// Looks like they are on an emulator, pretend we're in Paris if we don't have a
// location set.
lastKnownLocation = PARIS_LOCATION;
} else {
new AlertDialog.Builder(this)
.setTitle(R.string.error_dialog_title)
.setMessage(R.string.no_location)
.setPositiveButton(R.string.ok_button, null)
.show();
return;
}
}
startPickPlaceActivity(lastKnownLocation);
} catch (Exception ex) {
onError(ex);
}
}
}
The best way to do this is to use the PlacePickerFragment, and call setSearchText("restaurant"). While it doesn't necessarily restrict it to a category, it will search everything that is categorized as a restaurant.
You can also see an example of this in the Scrumptious sample app (in the PickerActivity class).
I'm trying to make speaking dictionary.
LogCat shows "Successfully bound to com.android.tts" but when the Speak button clicked, it shows "failed speak : not bound to tts engine".
But on AVD it runs smoothly, why?
This Is my goTranslator class:
package sk.team;
import android.app.Activity;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioButton;
import android.speech.tts.TextToSpeech;
import android.widget.Toast;
import android.content.Intent;
import android.content.res.Configuration;
import java.util.Locale;
public class goTranslator extends Activity implements TextToSpeech.OnInitListener{
private int MY_DATA_CHECK_CODE = 0;
private TextToSpeech tts;
private SQLiteDatabase db = null;
private Cursor translatorCursor = null;
private EditText txtSearch;
private EditText txtResult;
private AppDatabase dbtranslator = null;
private RadioButton Eng,Ind;
private Button Translate,Speak;
public static final String ENGLISH = "english";
public static final String INDONESIA = "indonesia";
public void onInit(int status) {
if (status == TextToSpeech.SUCCESS) {
Toast.makeText(goTranslator.this,
"Text-To-Speech engine is initialized", Toast.LENGTH_LONG).show();
} else if (status == TextToSpeech.ERROR) {
Toast.makeText(goTranslator.this,
"Error occurred while initializing Text-To-Speech engine",
Toast.LENGTH_LONG).show();
}
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == MY_DATA_CHECK_CODE) {
if (resultCode == TextToSpeech.Engine.CHECK_VOICE_DATA_PASS) {
tts = new TextToSpeech(this, this);
} else {
Intent installIntent = new Intent();
installIntent.setAction(TextToSpeech.Engine.ACTION_INSTALL_TTS_DATA);
startActivity(installIntent);
}
}
}
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
dbtranslator = new AppDatabase(this);
db = dbtranslator.getWritableDatabase();
setContentView(R.layout.main);
dbtranslator.createTable(db);
dbtranslator.generateData(db);
Eng = (RadioButton) findViewById(R.id.Eng);
Ind = (RadioButton) findViewById(R.id.Ind);
Translate = (Button) findViewById(R.id.Translate);
Speak = (Button) findViewById(R.id.Speak);
txtSearch = (EditText) findViewById(R.id.txtSearch);
txtResult = (EditText) findViewById(R.id.txtResult);
Intent checkIntent = new Intent();
checkIntent.setAction(TextToSpeech.Engine.ACTION_CHECK_TTS_DATA);
startActivityForResult(checkIntent, MY_DATA_CHECK_CODE);
Speak.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
String text = txtResult.getText().toString();
if (text!=null && text.length()>0) {
Toast.makeText(goTranslator.this, "Saying: " + text,
Toast.LENGTH_LONG).show();
tts.speak(text, TextToSpeech.QUEUE_ADD, null);
}
}
});
}
public void Translate (View view) {
if (view == Translate) {
if (Eng.isChecked()) {
txtSearch.setHint("Masukkan Kata");
Locale loc = new Locale ("es_ES");
tts.setLanguage(loc);
String result = "";
String englishword = txtSearch.getText().toString().trim().toLowerCase();
translatorCursor = db.rawQuery("SELECT ID, ENGLISH, INDONESIA "
+ "FROM translator where ENGLISH='" + englishword
+ "' ORDER BY ENGLISH", null);
if (translatorCursor.moveToFirst()) {
result = translatorCursor.getString(2);
for (; !translatorCursor.isAfterLast(); translatorCursor.moveToNext()) {
result = translatorCursor.getString(2);
}
}
if (result.equals("")) {
result = "Kata Tidak Tersedia";
}
txtResult.setText(result);
}
if (Ind.isChecked()) {
txtSearch.setHint("Enter Word");
Locale loc = new Locale ("en_US");
tts.setLanguage(loc);
String result = "";
String indonesiaword = txtSearch.getText().toString().trim().toLowerCase();
translatorCursor = db.rawQuery("SELECT ID, ENGLISH, INDONESIA "
+ "FROM translator where INDONESIA='" + indonesiaword
+ "' ORDER BY INDONESIA", null);
if (translatorCursor.moveToFirst()) {
result = translatorCursor.getString(1);
for (; !translatorCursor.isAfterLast(); translatorCursor.moveToNext()) {
result = translatorCursor.getString(1);
}
}
if (result.equals("")) {
result = "Result Not Found";
}
txtResult.setText(result);
}
}
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
setContentView(R.layout.main);
}
#Override
public void onDestroy() {
super.onDestroy();
if (tts != null) {
tts.stop();
tts.shutdown();
}
if (translatorCursor != null) {
translatorCursor.close();
db.close();
}
}
}
Log.w(TAG, method + " failed: not bound to TTS engine");
I caused by
mServiceConnection;
Being null
Does your testing device lack an internet connection?
I want to start an activity in my onReceive() method.
package com.splashscreenactivity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.telephony.SmsMessage;
import android.widget.Toast;
public class SMSReceiver extends BroadcastReceiver {
public static String trigger_message = "";
#Override
public void onReceive(Context context, Intent intent) {
// ---get the SMS message passed in---
Bundle bundle = intent.getExtras();
SmsMessage[] msgs = null;
String str = "";
if (bundle != null) {
// ---retrieve the SMS message received---
Object[] pdus = (Object[]) bundle.get("pdus");
msgs = new SmsMessage[pdus.length];
for (int i = 0; i < msgs.length; i++) {
msgs[i] = SmsMessage.createFromPdu((byte[]) pdus[i]);
str += "SMS from " + msgs[i].getOriginatingAddress();
str += " :";
trigger_message = msgs[i].getMessageBody().toString();
str += trigger_message;
str += "\n";
}
// ---display the new SMS message---
Toast.makeText(context, str, Toast.LENGTH_SHORT).show();
if (trigger_message.equals("dx")) {
Toast.makeText(context, "I am triggered", Toast.LENGTH_LONG)
.show();
// /////////////////////////
// i want to start here
// ////////////////////////
// MainScreenActivity.trigger="Now";
// Intent i = new Intent(context,GPS.class);
// i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
// context.startActivity(i);
} else {
Toast.makeText(context, "I am not triggered, Bbyz!!!",
Toast.LENGTH_LONG).show();
}
}
}
}
here is GPS.class
package com.splashscreenactivity;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.telephony.SmsManager;
import android.telephony.SmsMessage;
import android.widget.TextView;
import android.widget.Toast;
public class GPS extends Activity implements LocationListener {
TextView latitude, logitude;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.gps);
LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000L, 500.0f,
this);
Toast.makeText(this, "i m started", Toast.LENGTH_LONG);
// latitude = (TextView)findViewById(R.id.txtLat);
// logitude = (TextView)findViewById(R.id.txtLongi);
// latitude.setText("Loading...");
// logitude.setText("Loading...");
}
String LATTITUDE;
String LOGITUDE;
#Override
public void onLocationChanged(Location location) {
double lat = location.getLatitude();
double lag = location.getLongitude();
LATTITUDE = Double.toString(lat);
LOGITUDE = Double.toString(lag);
// latitude.setText(LATTITUDE);
// logitude.setText(LOGITUDE);
// SmsManager sm = SmsManager.getDefault();
// // here is where the destination of the text should go
// String number = "5556";
// sm.sendTextMessage(number, null,
// "latitude="+latitude.getText()+"\nlongitude="+logitude.getText(),
// null, null);
}
#Override
public void onProviderDisabled(String arg0) {
}
#Override
public void onProviderEnabled(String arg0) {
}
#Override
public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
}
// /** Register for the updates when Activity is in foreground */
// #Override
// protected void onResume()
// {
// super.onResume();
// lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000L, 500.0f,
// this);
// }
//
// /** Stop the updates when Activity is paused */
// #Override
// protected void onPause() {
// super.onPause();
// lm.removeUpdates(this);
// }
}
You have context passed as parameter to onRecieve() method, so just use:
#Override
public void onReceive(Context context, Intent intent) {
//start activity
Intent i = new Intent();
i.setClassName("com.test", "com.test.MainActivity");
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(i);
}
It works, of course you have to change package and activity class name to your own.
I am using this and its work on my site:
Intent intentone = new Intent(context.getApplicationContext(), DialogAct.class);
intentone.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intentone);
Intent intent1 = new Intent();
intent1.setClassName(context.getPackageName(), MainActivity.class.getName());
intent1.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent1);
to prevent those package exceptions