Example to convert csv format to Json in android. I found a solution in Converting an CSV file to a JSON object in Java but not working or I am missing anything.
Thanks in advance.
package com.example.readfilefromsdcard;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import java.util.List;
import org.codehaus.jackson.map.ObjectMapper;
import com.opencsv.bean.ColumnPositionMappingStrategy;
import com.opencsv.bean.CsvToBean;
import com.opencsv.bean.HeaderColumnNameMappingStrategy;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;
public class MainActivity extends Activity {
Button btnWriteSDFile;
Button btnReadSDFile;
String path = "/sdcard/mydocs/test.csv";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnReadSDFile = (Button) findViewById(R.id.btnReadSDFile);
btnReadSDFile.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
try {
ConvertCsvToJson(path,"TestJavaBeans");
// ConvertCsvToJson1(path);
} catch (Exception e) {
Toast.makeText(getBaseContext(), e.getMessage(), Toast.LENGTH_SHORT).show();
}
}
});
}
public void ConvertCsvToJson(String path, String clsName) throws IOException, ClassNotFoundException {
String pathToCsvFile = path;
String javaBeanClassName = "" + clsName;
final File file = new File(pathToCsvFile);
if (!file.exists()) {
System.out.println("The file you specified does not exist. path=" + pathToCsvFile);
}
Class<?> type = null;
try {
type = Class.forName(javaBeanClassName);
} catch (ClassNotFoundException e) {
System.out.println("The java bean you specified does not exist. className=" + javaBeanClassName);
}
HeaderColumnNameMappingStrategy<TestJavaBeans> strat = new HeaderColumnNameMappingStrategy<TestJavaBeans>();
//strat.setType(type);
CsvToBean<TestJavaBeans> csv = new CsvToBean<TestJavaBeans>();
List<TestJavaBeans> list = csv.parse(strat, new InputStreamReader(new FileInputStream(file)));
System.out.println(new ObjectMapper().writeValueAsString(list));
}
public void ConvertCsvToJson1(String path) throws IOException, ClassNotFoundException {
final ColumnPositionMappingStrategy<TestJavaBeans > strategy = new ColumnPositionMappingStrategy<TestJavaBeans>();
strategy.setType(TestJavaBeans .class);
strategy.setColumnMapping(new String[] { "name", "id", });
final CsvToBean<TestJavaBeans > csvToBean = new CsvToBean<TestJavaBeans >();
final List<TestJavaBeans > beanExamples;
try {
final Reader reader = new FileReader(path);
beanExamples = csvToBean.parse(strategy, reader);
System.out.println(new ObjectMapper().writeValueAsString(beanExamples));
} catch (IOException ex) {
throw new RuntimeException(ex);
}
}
}
package com.example.readfilefromsdcard;
public class TestJavaBeans {
private String name;
private String id;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
}
Referenced libraries : jackson-all-1.9.0.jar and opencsv-3.3.jar
log: Could not find method java.beans.Introspector.getBeanInfo, referenced from method com.opencsv.bean.HeaderColumnNameMappingStrategy.loadDescriptors
There's really no universal "convert": JSON is a heirarchical structure, while CSV is flat. You need to model the JSON object and map fields from the CSV to the JSON object one at a time. It's more a logic problem rather than a coding one.
I would suggest this approach
create a Java "wrapper" class that has a class variable List<TestJavaBeans> list
Then use Jackson to convert this "wrapper" to json
The link which i preferred for converting csv to json is as follows:
https://github.com/cparker15/csv-to-json?files=1
Related
I would like to use OpenNLP in my Android project. I imported the JAR and I can use it in my project but when I need to load a TokenizerModel (for example) I do not see how to proceed.
Cheers.
Putting my .bin model files in the assets folder and call the using getAssets() is working pretty fine.
Here is an example (originally written on Stack Overflow Documentation):
Sentence Detection using openNLP using CLI and Java API
using CLI:
$ opennlp SentenceDetector ./en-sent.bin < ./input.txt > output.txt
using API:
import static java.nio.file.Files.readAllBytes;
import static java.nio.file.Paths.get;
import java.io.IOException;
import java.util.Objects;
public class FileUtils {
/**
* Get file data as string
*
* #param fileName
* #return
*/
public static String getFileDataAsString(String fileName) {
Objects.nonNull(fileName);
try {
String data = new String(readAllBytes(get(fileName)));
return data;
} catch (IOException e) {
System.out.println(e.getMessage());
return null;
}
}
}
class sentecedetectorutil:
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.Objects;
import opennlp.tools.sentdetect.SentenceDetectorME;
import opennlp.tools.sentdetect.SentenceModel;
public class SentenceDetectorUtil {
private SentenceModel model = null;
SentenceDetectorME sentenceDetector = null;
public SentenceDetectorUtil(String modelFile) {
Objects.nonNull(modelFile);
initSentenceModel(modelFile);
initSentenceDetectorME();
}
private void initSentenceDetectorME() {
sentenceDetector = new SentenceDetectorME(model);
}
private SentenceModel initSentenceModel(String file) {
InputStream modelIn;
try {
modelIn = new FileInputStream(file);
} catch (FileNotFoundException e) {
System.out.println(e.getMessage());
return null;
}
try {
model = new SentenceModel(modelIn);
} catch (IOException e) {
e.printStackTrace();
} finally {
if (modelIn != null) {
try {
modelIn.close();
} catch (IOException e) {
}
}
}
return model;
}
public String[] getSentencesFromFile(String inputFile) {
String data = FileUtils.getFileDataAsString(inputFile);
return sentenceDetector.sentDetect(data);
}
public String[] getSentences(String data) {
return sentenceDetector.sentDetect(data);
}
}
}
main class:
public class Main {
public static void main(String args[]) {
SentenceDetectorUtil util = new SentenceDetectorUtil(
"path//to//your//en-sent.bin");
String data = "Welcome to Stackoverflow Documentation.This is the first example in OenNLP.";
String[] sentences = util.getSentences(data);
for (String s : sentences)
System.out.println(s +"\n");
}
}
output will be:
Welcome to Stackoverflow Documentation.
This is the first example in OpenNLP.
And you can find some basic stuff here
lot of examples are covered in the above examples. that must do the work for you.
I want to write the crash report in text file using latest Acra 4.9.0.
I can,t example for this latest version.
I tried using available documentation.
Acra is enabled
but it,s not writing in the file.
myApp
package com.myApp;
import org.acra.ACRA;
import android.app.AlertDialog;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.view.KeyEvent;
import android.view.View;
import com.myApp.Application.AppLauncher;
import com.myApp.interfaces.AppEvents;
import com.myApp.R;
import com.utils.Config;
import com.utils.Constants;
import com.utils.DeviceValidator;
public class myApp extends FragmentActivity
{
private AppLauncher appLauncher = null;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
if(!ACRA.isACRASenderServiceProcess())
{
setContentView(R.layout.activity_myApp);
appLauncher = new AppLauncher();
appLauncher.registerEventListener(appEventsListener);
appLauncher.initApp(this);
}
}
#Override
public void onPause() {
super.onPause();
if(!DeviceValidator.isDeviceValid())
{
return;
}
appLauncher.activityOnPause();
}
#Override
protected void onRestart() {
super.onRestart();
}
#Override
protected void onStart()
{
super.onStart();
}
#Override
public void onResume()
{
super.onResume();
appLauncher.activityOnResume();
}
}
AcraApplication
package com.myAPP;
import org.acra.ACRA;
import org.acra.ReportField;
import org.acra.ReportingInteractionMode;
import org.acra.annotation.ReportsCrashes;
import org.acra.sender.HttpSender.Method;
import android.app.Application;
#ReportsCrashes(
formUri = "http://staging.jemtv.com/variable_dump/index.php",
customReportContent = { ReportField.REPORT_ID, ReportField.DEVICE_ID, ReportField.APP_VERSION_NAME, ReportField.ANDROID_VERSION, ReportField.STACK_TRACE, ReportField.CUSTOM_DATA, ReportField.LOGCAT },
httpMethod = Method.POST,
reportSenderFactoryClasses = org.acra.util.MyOwnSenderFactory.class,
mode = ReportingInteractionMode.SILENT
)
public class AcraApplication extends Application
{
public AcraApplication()
{
super();
}
#Override
public void onCreate() {
super.onCreate();
ACRA.init(this);
}
}
MyOwnSender
package org.acra.util;
import java.io.File;
import java.io.FileOutputStream;
import org.acra.ReportField;
import org.acra.collector.CrashReportData;
import org.acra.config.ACRAConfiguration;
import org.acra.sender.ReportSender;
import org.acra.sender.ReportSenderException;
import android.content.Context;
import android.support.annotation.NonNull;
import android.util.Log;
public class MyOwnSender implements ReportSender {
private static final String FILE_NAME = "AcraReport.txt";
//private final Map<ReportField, String> mMapping = new HashMap<ReportField, String>();
//private FileWriter crashReport = null;
MyOwnSender(Context context, #NonNull ACRAConfiguration config)
{
Log.d("testAcra", "MyOwnSender created");
/* File logFile = new File(context.getFilesDir().getPath() + "/" + FILE_NAME, FILE_NAME);
try {
crashReport = new FileWriter(logFile, true);
} catch (IOException e) {
e.printStackTrace();
}*/
}
#Override
public void send(Context context, CrashReportData report) throws ReportSenderException
{
// Iterate over the CrashReportData instance and do whatever
// you need with each pair of ReportField key / String value
String finalReport = createCrashReport(report);
String tempFile = context.getFilesDir().getPath() + "/" + FILE_NAME;
try
{
File detailedFile = new File(tempFile);
if(!detailedFile.exists())
detailedFile.createNewFile();
FileOutputStream stream = new FileOutputStream(detailedFile, true);
stream.write(finalReport.getBytes());
Log.d("testAcra","adding to file: "+stream);
stream.close();
}
catch (Exception e)
{
e.printStackTrace();
}
/*final Map<String, String> finalReport = remap(report);
try {
BufferedWriter buf = new BufferedWriter(crashReport);
Set<Entry<String, String>> set = reportBody.entrySet();
Iterator<Entry<String, String>> i = set.iterator();
while (i.hasNext()) {
Map.Entry<String, String> me = (Entry<String, String>) i.next();
buf.append("[" + me.getKey() + "]=" + me.getValue());
}
buf.flush();
buf.close();
} catch (IOException e) {
Log.e("TAG", "IO ERROR", e);
}*/
}
private String createCrashReport(CrashReportData crashReportData){
StringBuilder body = new StringBuilder();
body.append("ReportID : " + crashReportData.getProperty(ReportField.REPORT_ID))
.append("\n")
.append("DeviceID : " + crashReportData.getProperty(ReportField.DEVICE_ID))
.append("\n")
.append("AppVersionName : " + crashReportData.getProperty(ReportField.APP_VERSION_NAME))
.append("\n")
.append("Android Version : " + crashReportData.getProperty(ReportField.ANDROID_VERSION))
.append("\n")
.append("CustomData : " + crashReportData.getProperty(ReportField.CUSTOM_DATA))
.append("\n")
.append("STACK TRACE : \n" + crashReportData.getProperty(ReportField.STACK_TRACE))
.append("\n")
.append("LogCAT : \n" + crashReportData.getProperty(ReportField.LOGCAT));
return body.toString();
}
/* private Map<String, String> remap(Map<ReportField, String> report) {
Set<ReportField>fields = ACRA.getConfig().getReportFields();
final Map<String, String> finalReport = new HashMap<String, String>(report.size());
for (ReportField field : fields)
{
if (mMapping == null || mMapping.get(field) == null)
finalReport.put(field.toString(), report.get(field));
else
finalReport.put(mMapping.get(field), report.get(field));
}
return finalReport;
}*/
}
MyOwnSenderFactory
package org.acra.util;
import org.acra.config.ACRAConfiguration;
import org.acra.sender.ReportSender;
import org.acra.sender.ReportSenderFactory;
import android.content.Context;
import android.support.annotation.NonNull;
public class MyOwnSenderFactory implements ReportSenderFactory {
// NB requires a no arg constructor.
/*MyOwnSenderFactory()
{
Log.e("testAcra", "MyOwnSenderFactory created");
}*/
#Override
#NonNull
public ReportSender create(#NonNull Context context, #NonNull ACRAConfiguration config) {
// TODO Auto-generated method stub
return new MyOwnSender(context, config);
}
}
Because i was using jar file instead of aar
in my manifest i was missing
<service
android:name="org.acra.sender.SenderService"
android:exported="false"
android:process=":acra" />
enter code here
That,s why SendeService used in Acra was not starting.
I want to write in application data folder
That is called internal data
I have created my own saver class to handle all of those savings:
import android.content.Context;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.math.BigDecimal;
import java.math.BigInteger;
public class Saver {
static FileOutputStream fos;
static FileInputStream fis;
public static void save(String filename, String data, Context c){
try {
fos = c.openFileOutput(filename, Context.MODE_PRIVATE);
fos.write(data.getBytes());
fos.close();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
String file;
public String getFile(){return file;}
public void setFile(String loc){
file = loc;
}
String result;
private static String mainLoad(String fn, Context c){
String collected = null;
try{
fis = c.openFileInput(fn);
byte[] dataArray = new byte[fis.available()];
while(fis.read(dataArray) != -1){
collected = new String(dataArray);
}
}catch(Exception e){
e.printStackTrace();
return null;
}finally{
try {
fis.close();
return collected;
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
}
}
}
public static int loadInt(String fn, Context c){
if(mainLoad(fn,c) == null) return 0;
else return Integer.parseInt(mainLoad(fn,c));
}
public static double loadDouble(String fn, Context c){
if(mainLoad(fn,c) == null) return 0;
else return Double.parseDouble(mainLoad(fn,c));
}
public static float loadFloat(String fn, Context c){
return Float.parseFloat(mainLoad(fn,c));
}
public static String loadString(String fn, Context c){
return mainLoad(fn, c);
}
public static Boolean loadBoolean(String fn, Context c){
if(mainLoad(fn,c) == null) return false;
else return Boolean.parseBoolean(mainLoad(fn,c));
}
public static BigInteger loadBigInteger(String fn, Context c){
return new BigInteger(mainLoad(fn,c));
}
public static BigDecimal loadBigDecimal(String fn, Context c){
return new BigDecimal(mainLoad(fn,c));
}
}
I want to write the crash report in text file using latest Acra 4.9.0. I can,t example for this latest version.
If you want to write to a .txt file on server, try this backend. Uses the default sender:
<?php
// Outputs all POST parameters to a text file. The file name is the date_time of the report reception
$fileName = date('Y-m-d_H-i-s').'.txt';
$file = fopen($fileName,'w') or die('Could not create report file: ' . $fileName);
foreach($_POST as $key => $value) {
$reportLine = $key." = ".$value."\n";
fwrite($file, $reportLine) or die ('Could not write to report file ' . $reportLine);
}
fclose($file);
?>
If you only want to write locally, then the point of ACRA disappears as you cannot get the files.
If you create .txt files to transmit them, it is actually better to use the backend I linked. It transmits the raw data, and you can get all your fields in a .txt file
I am finding it difficult to make this simple upload. I've used all encontrandos tutorials on the internet such as Bluelist and android-sync. I already have a database created within the service. My code is as follows:
MainActivity.java
package com.example.engenharia.replicator;
import android.content.Context;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.Toast;
import com.cloudant.sync.datastore.BasicDocumentRevision;
import com.cloudant.sync.datastore.Datastore;
import com.cloudant.sync.datastore.DatastoreException;
import com.cloudant.sync.datastore.DatastoreManager;
import com.cloudant.sync.datastore.DocumentBodyFactory;
import com.cloudant.sync.datastore.DocumentException;
import com.cloudant.sync.datastore.DocumentRevision;
import com.cloudant.sync.datastore.MutableDocumentRevision;
import com.cloudant.sync.query.IndexManager;
import com.cloudant.sync.replication.ReplicatorBuilder;
import com.cloudant.sync.replication.Replicator;
import java.io.File;
import java.net.URI;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.CountDownLatch;
public class MainActivity extends AppCompatActivity {
private static final String DATASTORE_MANGER_DIR = "data";
private Datastore DataStore;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
try {
URI uri = new URI(my_uri);
File path = getApplicationContext().getDir(DATASTORE_MANGER_DIR, Context.MODE_PRIVATE);
DatastoreManager manager = new DatastoreManager(path.getAbsolutePath());
DataStore = manager.openDatastore("banco0"); //banco0 is the DB created in Cloudant NoSQL service.
// Create a replicator that replicates changes from the local
// datastore to the remote database.
Replicator replicator = ReplicatorBuilder.push().to(uri).from(DataStore).build();
// Use a CountDownLatch to provide a lightweight way to wait for completion
CountDownLatch latch = new CountDownLatch(1);
Listener listener = new Listener(latch);
replicator.getEventBus().register(listener);
replicator.start();
latch.await();
replicator.getEventBus().unregister(listener);
if(replicator.getState() != Replicator.State.COMPLETE){
System.out.println("Error replicating TO remote");
System.out.println(listener.error);
} else {
System.out.println(String.format("Replicated %d documents in %d batches",
listener.documentsReplicated, listener.batchesReplicated));
}
}catch (Exception e){
e.printStackTrace();
}
}
public DocumentRevision createDocument() {
MutableDocumentRevision rev = new MutableDocumentRevision();
rev.body = DocumentBodyFactory.create(HashMap());
try {
return DataStore.createDocumentFromRevision(rev);
} catch (DocumentException e) {
//throw new RuntimeException(e);
e.printStackTrace();
return null;
}
}
public Map<String, Object> HashMap() {
HashMap<String, Object> map = new HashMap<String, Object>();
HashMap<String, String> map1 = new HashMap<String, String>();
map1.put("Street", "121");
map1.put("Street1", "12112");
map1.put("Street123", "1211111");
String[] array1 = new String[]{"Cloudant", "NoSQL", "JSON"};
map.put("address", map1);
map.put("description", "This is sample description");
map.put("skills", array1);
return map;
}
}
listener.java
package com.example.engenharia.replicator;
import com.cloudant.sync.notifications.ReplicationCompleted;
import com.cloudant.sync.notifications.ReplicationErrored;
import com.cloudant.sync.replication.ErrorInfo;
import com.google.common.eventbus.Subscribe;
import com.cloudant.sync.replication.ReplicatorBuilder;
import com.cloudant.sync.replication.Replicator;
import java.util.concurrent.CountDownLatch;
/**
* Created by engenharia on 19/08/16.
*/
public class Listener {
private final CountDownLatch latch;
public ErrorInfo error = null;
public int documentsReplicated;
public int batchesReplicated;
Listener(CountDownLatch latch) {
this.latch = latch;
}
#Subscribe
public void complete(ReplicationCompleted event) {
this.documentsReplicated = event.documentsReplicated;
this.batchesReplicated = event.batchesReplicated;
latch.countDown();
}
#Subscribe
public void error(ReplicationErrored event) {
this.error = event.errorInfo;
latch.countDown();
}
}
Executing this code I have the follow error:
CouchException: error: forbidden, reason: server_admin access is
required for this request, statusCode: 403, msg: null, cause: null
But I am the admin!
How do I fix the problem or what is the solution?
While working on a project I'm getting this error
Error : method gettext() must be call from UI thread is worker
on the following line :
String url = Util.send_chat_url+"?email_id="+editText_mail_id.getText().toString()+"&message="+editText_chat_message.getText().toString();
Please Help
This is my entire code for the class ChatActivity.java
package com.example.ankit.myapplication;
import android.app.Activity;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.support.annotation.NonNull;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;
import com.example.ankit.myapplication.XmppService;
import com.squareup.okhttp.OkHttpClient;
import org.jivesoftware.smack.packet.Message;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
import java.util.Scanner;
//import services.XmppService;
public class ChatActivity extends Activity {
EditText editText_mail_id;
EditText editText_chat_message;
ListView listView_chat_messages;
Button button_send_chat;
List<ChatObject> chat_list;
BroadcastReceiver recieve_chat;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_chat);
Scanner in = new Scanner(System.in);
XmppService xm= new XmppService();
Log.d("pavan","in chat "+getIntent().getStringExtra("user_id"));
Log.d("pavan","in chat server "+Util.SERVER);
XmppService.setupAndConnect(ChatActivity.this, Util.SERVER, "",
getIntent().getStringExtra("user_id"), Util.XMPP_PASSWORD);
editText_mail_id= (EditText) findViewById(R.id.editText_mail_id);
editText_chat_message= (EditText) findViewById(R.id.editText_chat_message);
listView_chat_messages= (ListView) findViewById(R.id.listView_chat_messages);
button_send_chat= (Button) findViewById(R.id.button_send_chat);
button_send_chat.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// send chat message to server
String message=editText_chat_message.getText().toString();
showChat("sent",message);
// new SendMessage().execute();
XmppService.sendMessage(ChatActivity.this, editText_mail_id.getText().toString() + Util.SUFFIX_CHAT, Message.Type.chat, message);
editText_chat_message.setText("");
}
});
recieve_chat=new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String message=intent.getStringExtra("message");
Log.d("pavan","in local braod "+message);
showChat("recieve",message);
}
};
LocalBroadcastManager.getInstance(this).registerReceiver(recieve_chat, new IntentFilter("message_recieved"));
}
private void showChat(String type, String message){
if(chat_list==null || chat_list.size()==0){
chat_list= new ArrayList<ChatObject>();
}
chat_list.add(new ChatObject(message,type));
ChatAdabter chatAdabter=new ChatAdabter(ChatActivity.this,R.layout.chat_view,chat_list);
listView_chat_messages.setAdapter(chatAdabter);
//chatAdabter.notifyDataSetChanged();
}
#Override
protected void onDestroy() {
super.onDestroy();
}
private class SendMessage extends AsyncTask<String, Void, String> {
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
}
#Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
String url = Util.send_chat_url+"?email_id="+editText_mail_id.getText().toString()+"&message="+editText_chat_message.getText().toString();
Log.i("pavan", "url" + url);
OkHttpClient client_for_getMyFriends = new OkHttpClient();
String response = null;
// String response=Utility.callhttpRequest(url);
try {
url = url.replace(" ", "%20");
response = callOkHttpRequest(new URL(url),
client_for_getMyFriends);
for (String subString : response.split("<script", 2)) {
response = subString;
break;
}
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return response;
}
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
//Toast.makeText(context,"response "+result,Toast.LENGTH_LONG).show();
}
}
// Http request using OkHttpClient
String callOkHttpRequest(URL url, OkHttpClient tempClient)
throws IOException {
HttpURLConnection connection = tempClient.open(url);
connection.setConnectTimeout(40000);
InputStream in = null;
try {
// Read the response.
in = connection.getInputStream();
byte[] response = readFully(in);
return new String(response, "UTF-8");
} finally {
if (in != null)
in.close();
}
}
byte[] readFully(InputStream in) throws IOException {
ByteArrayOutputStream out = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
for (int count; (count = in.read(buffer)) != -1;) {
out.write(buffer, 0, count);
}
return out.toByteArray();
}
}
Do not access the Android UI toolkit from outside the UI thread
Pass editText_mail_id.getText() and editText_chat_message.getText() as parameters to your async task or set it in onPreExecute to some variable
Like :
private class SendMessage extends AsyncTask<String, Void, String> {
private String mailId;
private String msgText;
#Override
protected void onPreExecute() {
super.onPreExecute();
mailId = editText_mail_id.getText().toString();
msgText = editText_chat_message.getText().toString();
}
Change url in doInBackground as :
String url = Util.send_chat_url+"?email_id="+mailId+"&message="+msgText;
you can create class for storing your parameter like i do,
Just create one class
example :
public class MyTaskParams
{
String mailId;
String message;
public MyTaskParams(String mailId, String message)
{
this.mailId = mailId;
this.message = message;
}
}
public class SendMessage extends AsyncTask<MyTaskParams, Void, String {
#Override
protected String doInBackground(MyTaskParams... params) {
String mailId = params[0].mailId;
String message = params[0].message;
String url = Util.send_chat_url+"?email_id="+ mailId +"&message="+ message;
}
}
so you can just call like this
MyTaskParams params = new MyTaskParams(editText_mail_id.getText().toString(),editText_chat_message.getText().toString());
SendMessage myTask = new SendMessage();
myTask.execute(params);
with this code you can call SendMessage Class from any activity, dont bind your asynctask with get text because if you do that you just can use SendMessage only in that activity
Hope this can help you.
I want show the maps of my places, based on a selection of area like business,favorites, etc.
I am using the following intent for search and display the result in the maps in Android
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://maps.google.com/maps"));
startActivity(intent);
When I click the maps place as favorites it shows that place in my places.
How can I divide the places based on category in Android?
You should use the place api for getting the selection of area.
Step by step,
How to get the list of nearest place of a location.
Step 1 : Go to API Console for obtaining the Place API
https://code.google.com/apis/console/
and select on services tab
on the place service
now select API Access tab and get the API KEY
now you have a API key for getting place
Now in programming
*Step 2 * : first create a class named Place.java. This class is used to contain the property of place which are provided by Place api.
package com.android.code.GoogleMap.NearsetLandmark;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.json.JSONException;
import org.json.JSONObject;
public class Place {
private String id;
private String icon;
private String name;
private String vicinity;
private Double latitude;
private Double longitude;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getIcon() {
return icon;
}
public void setIcon(String icon) {
this.icon = icon;
}
public Double getLatitude() {
return latitude;
}
public void setLatitude(Double latitude) {
this.latitude = latitude;
}
public Double getLongitude() {
return longitude;
}
public void setLongitude(Double longitude) {
this.longitude = longitude;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getVicinity() {
return vicinity;
}
public void setVicinity(String vicinity) {
this.vicinity = vicinity;
}
static Place jsonToPontoReferencia(JSONObject pontoReferencia) {
try {
Place result = new Place();
JSONObject geometry = (JSONObject) pontoReferencia.get("geometry");
JSONObject location = (JSONObject) geometry.get("location");
result.setLatitude((Double) location.get("lat"));
result.setLongitude((Double) location.get("lng"));
result.setIcon(pontoReferencia.getString("icon"));
result.setName(pontoReferencia.getString("name"));
result.setVicinity(pontoReferencia.getString("vicinity"));
result.setId(pontoReferencia.getString("id"));
return result;
} catch (JSONException ex) {
Logger.getLogger(Place.class.getName()).log(Level.SEVERE, null, ex);
}
return null;
}
#Override
public String toString() {
return "Place{" + "id=" + id + ", icon=" + icon + ", name=" + name + ", latitude=" + latitude + ", longitude=" + longitude + '}';
}
}
Now create a class named PlacesService
package com.android.code.GoogleMap.NearsetLandmark;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.util.Log;
public class PlacesService {
private String API_KEY;
public PlacesService(String apikey) {
this.API_KEY = apikey;
}
public void setApiKey(String apikey) {
this.API_KEY = apikey;
}
public List<Place> findPlaces(double latitude, double longitude,String placeSpacification)
{
String urlString = makeUrl(latitude, longitude,placeSpacification);
try {
String json = getJSON(urlString);
System.out.println(json);
JSONObject object = new JSONObject(json);
JSONArray array = object.getJSONArray("results");
ArrayList<Place> arrayList = new ArrayList<Place>();
for (int i = 0; i < array.length(); i++) {
try {
Place place = Place.jsonToPontoReferencia((JSONObject) array.get(i));
Log.v("Places Services ", ""+place);
arrayList.add(place);
} catch (Exception e) {
}
}
return arrayList;
} catch (JSONException ex) {
Logger.getLogger(PlacesService.class.getName()).log(Level.SEVERE, null, ex);
}
return null;
}
//https://maps.googleapis.com/maps/api/place/search/json?location=28.632808,77.218276&radius=500&types=atm&sensor=false&key=your_api_key
private String makeUrl(double latitude, double longitude,String place) {
StringBuilder urlString = new StringBuilder("https://maps.googleapis.com/maps/api/place/search/json?");
if (place.equals("")) {
urlString.append("&location=");
urlString.append(Double.toString(latitude));
urlString.append(",");
urlString.append(Double.toString(longitude));
urlString.append("&radius=1000");
// urlString.append("&types="+place);
urlString.append("&sensor=false&key=" + API_KEY);
} else {
urlString.append("&location=");
urlString.append(Double.toString(latitude));
urlString.append(",");
urlString.append(Double.toString(longitude));
urlString.append("&radius=1000");
urlString.append("&types="+place);
urlString.append("&sensor=false&key=" + API_KEY);
}
return urlString.toString();
}
protected String getJSON(String url) {
return getUrlContents(url);
}
private String getUrlContents(String theUrl)
{
StringBuilder content = new StringBuilder();
try {
URL url = new URL(theUrl);
URLConnection urlConnection = url.openConnection();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()), 8);
String line;
while ((line = bufferedReader.readLine()) != null)
{
content.append(line + "\n");
}
bufferedReader.close();
}
catch (Exception e)
{
e.printStackTrace();
}
return content.toString();
}
}
Now create a new Activity where you want to get the list of nearest places.
/**
*
*/
package com.android.code.GoogleMap.NearsetLandmark;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.List;
import android.app.AlertDialog;
import android.app.ListActivity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Point;
import android.graphics.drawable.Drawable;
import android.location.Address;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import com.android.code.R;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;
import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;
import com.google.android.maps.Overlay;
/**
* #author dwivedi ji *
* */
public class CheckInActivity extends ListActivity {
private String[] placeName;
private String[] imageUrl;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
new GetPlaces(this,getListView()).execute();
}
class GetPlaces extends AsyncTask<Void, Void, Void>{
Context context;
private ListView listView;
private ProgressDialog bar;
public GetPlaces(Context context, ListView listView) {
// TODO Auto-generated constructor stub
this.context = context;
this.listView = listView;
}
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
bar.dismiss();
this.listView.setAdapter(new ArrayAdapter<String>(context, android.R.layout.simple_list_item_1, placeName));
}
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
bar = new ProgressDialog(context);
bar.setIndeterminate(true);
bar.setTitle("Loading");
bar.show();
}
#Override
protected Void doInBackground(Void... arg0) {
// TODO Auto-generated method stub
findNearLocation();
return null;
}
}
public void findNearLocation() {
PlacesService service = new PlacesService("past your key");
/*
Hear you should call the method find nearst place near to central park new delhi then we pass the lat and lang of central park. hear you can be pass you current location lat and lang.The third argument is used to set the specific place if you pass the atm the it will return the list of nearest atm list. if you want to get the every thing then you should be pass "" only
*/
List<Place> findPlaces = service.findPlaces(28.632808,77.218276,"atm");
// Hear third argument, we pass the atm for getting atm , if you pass the hospital then this method return list of hospital , If you pass nothing then it will return all landmark
placeName = new String[findPlaces.size()];
imageUrl = new String[findPlaces.size()];
for (int i = 0; i < findPlaces.size(); i++) {
Place placeDetail = findPlaces.get(i);
placeDetail.getIcon();
System.out.println( placeDetail.getName());
placeName[i] =placeDetail.getName();
imageUrl[i] =placeDetail.getIcon();
}
}
}