Parsing a text file using Jsoup - android

I have a Continent.txt file placed in my res/raw folder. Inside it contains the following.
<div class="continents">
US
Canada
Europe
</div>
I am able to parse the text US, Canada, Europe using jsoup, but when I display them to a TextView, they show up in one line. The output looks like this.
US Canada Europe
I want the ouput to be like this.
US
Canada
Europe
This is my code.
package com.example.readfile;
import java.io.InputStream;
import java.util.ArrayList;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.content.res.Resources;
import android.widget.TextView;
public class MainActivity extends Activity {
TextView txtContinent;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
txtContinent = (TextView) findViewById(R.id.textView1);
new MyTask().execute();
}
class MyTask extends AsyncTask<Void, Void, ArrayList<String>> {
ArrayList<String> arr_linkText = new ArrayList<String>();
#Override
protected ArrayList<String> doInBackground(Void... params) {
Document doc;
try {
Resources res = getResources();
InputStream in_s = res.openRawResource(R.raw.continent);
byte[] b = new byte[in_s.available()];
in_s.read(b);
doc = Jsoup.parse(new String(b));
Element link = doc.select("a").first();
String text = doc.body().text();
arr_linkText.add(text);
} catch (Exception e) {
// e.printStackTrace();
txtContinent.setText("Error: can't open file.");
}
return arr_linkText; // << retrun ArrayList from here
}
#Override
protected void onPostExecute(ArrayList<String> result) {
for (String temp_result : result) {
txtContinent.append(temp_result + "\n");
}
}
}
}
I do not know how to read the file line by line, I hope someone can illustrate it to me. Thank you!

You are taking the text of the entire body of the document at once. You need to parse it out by each element, like so
Elements links = doc.select("a");
for (Element link : links) {
arr_linkText.add(link.text());
}
in case it wasn't clear, the above code is meant to replace the following --
Element link = doc.select("a").first();
String text = doc.body().text();
arr_linkText.add(text);

Have you set android:inputType to include textMultiLine?

Related

how can i print persian with bixolon printers

I create an app for android in this app i connect to a bixolon(350plusll) printer and i print a tiket when my String is in english it is ok and my tiket print good but when my String is in persian my result print is not ok and my characters is revers and not correct
i use screenshot it was ok but it was very slow and not logiacal
please help me for resolve this problem
thanks alot
this is my code
package com.example.bahram.myapplication;
import android.app.Activity;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.View;
import android.widget.Button;
import com.bixolon.printer.BixolonPrinter;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
public class PrintTicketActivity extends Activity {
Button btn;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_print_tiket);
btn= findViewById(R.id.button);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//I set code page of the printer here because i want the printer print persian so i set that on Farsi
MainActivity.mBixolonPrinter.setSingleByteFont(BixolonPrinter.CODE_PAGE_FARSI);
//i have a file it's name is new2.txt and readContentOfFile is a method which read all of text in new2.txt and at last print data on the paper
MainActivity.mBixolonPrinter.printText(readContentOfFile(),BixolonPrinter.ALIGNMENT_CENTER,BixolonPrinter.TEXT_ATTRIBUTE_FONT_A,BixolonPrinter.TEXT_SIZE_HORIZONTAL1,true);
}
});
}
//read all of the text in new2.txt and return text
String readContentOfFile() {
StringBuilder text = new StringBuilder();
InputStream inputStream = getResources().openRawResource(R.raw.new2);
try {
BufferedReader br = new BufferedReader(new InputStreamReader(inputStream));
String line;
while ((line = br.readLine()) != null) {
text.append(line);
text.append('\n');
}
br.close();
} catch (IOException e) {
//You'll need to add proper error handling here
}
return text.toString();
}
}
content of new2.txt is bottom text
اما جدیدترین شاهکار سازمان لیگ و هیات فوتبال استان تهران که از سوی همین سازمان لیگ به عنوان برترین هیات ایران انتخاب شد، جانمایی توپ شروع مسابقه روی قیف(یا کنز) بود که در دیدار سایپا و پیکان صورت گرفت.
You can use one of the Farsi options available for the Bixolon printer, for example one of the following:
// Farsi option : Mixed
MainActivity.mBixolonPrinter.setFarsiOption(BixolonPrinter.OPT_REORDER_FARSI_MIXED);
// Farsi option : Right to Left
MainActivity.mBixolonPrinter.setFarsiOption(BixolonPrinter.OPT_REORDER_FARSI_RTL);

Dictionary app using Oxford Dictionary API

I am trying to make a dictionary application using Oxford Dictionary api. There is something wrong with my code JSON. Can anyone tell me how do I extract only the definition of the searched word, rather getting the whole JSON file
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.squareup.okhttp.Callback;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import javax.net.ssl.HttpsURLConnection;
public class MainActivity extends AppCompatActivity {
private static final String APP_ID= "59028fc6";
private static final String API_KEY = "ad3e310307d7b2f8bf474c45e1efd01f";
private static final String TAG = MainActivity.class.getSimpleName();
private OkHttpClient okHttpClient;
private EditText textInput;
private Button submitButton;
private TextView definitionView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// initialize ok http
okHttpClient = new OkHttpClient();
textInput = findViewById(R.id.textInput);
submitButton = findViewById(R.id.submitButton);
definitionView = findViewById(R.id.textMeaning);
submitButton.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View view) {
findMeaningOfEnteredWord();
}
});
}
private void findMeaningOfEnteredWord() {
String word = textInput.getText().toString();
if (word.isEmpty()) {
Toast.makeText(this, "Nothing entered", Toast.LENGTH_SHORT).show();
return;
}
// create url from the word
String lowerCaseWord = word.toLowerCase();
String httpRequestUrl = "https://od-api.oxforddictionaries.com:443/api/v1/entries/en/" + lowerCaseWord;
// make request with REST url
new RequestAsyncTask().execute(httpRequestUrl);
}
private class RequestAsyncTask extends AsyncTask<String, Integer, String> {
#Override
protected String doInBackground(String... params) {
String requestUrl = params[0];
Request request = new Request.Builder()
.url(requestUrl)
.addHeader("Accept", "application/json")
.addHeader("app_id", APP_ID)
.addHeader("app_key", API_KEY)
.build();
Response response = null;
try {
response = okHttpClient.newCall(request).execute();
return response.body().string();
} catch (IOException ex) {
Log.e(TAG, "caught error: " + ex.getMessage());
}
return "";
}
#Override
protected void onPostExecute(String result) {
try {
JSONObject responseAsJson = new JSONObject(result);
JSONArray results = responseAsJson.getJSONArray("results");
if (results.length() > 0) { // valid definitions were found
String lexicalEntries = results.getJSONObject(0).getString("lexicalEntries");
definitionView.setText(lexicalEntries);
}
Log.d(TAG, " " + responseAsJson.toString());
} catch (Exception ex) {
Log.d(TAG, "exception during json parsing: " + ex.getMessage());
}
}
}
}
JSON:
{"id":"aeroplane",
"language":"en",
"lexicalEntries": [
{
"entries": [{"etymologies":["late 19th century: from French aéroplane, from aéro- ‘air’ + Greek -planos ‘wandering’"],
"grammaticalFeatures":[{"text":"Singular","type":"Number"}],
"homographNumber":"000",
"senses":[{"crossReferenceMarkers":["North American term airplane"],
"crossReferences":[{"id":"airplane","text":"airplane","type":"see also"}],
"definitions":["a powered flying vehicle with fixed wings and a weight greater than that of the air it displaces."],
"domains":["Aviation"],
"id":"m_en_gbus0013220.005",
"regions":["British"],
"short_definitions":["powered flying vehicle with fixed wings"],
"thesaurusLinks":[{"entry_id":"plane","sense_id":"t_en_gb0011151.001"}]}]}],"language":"en","lexicalCategory":"Noun","pronunciations":[{"audioFile":"http:\/\/audio.oxforddictionaries.com\/en\/mp3\/aeroplane_gb_2.mp3","dialects":["British English"],"phoneticNotation":"IPA","phoneticSpelling":"ˈɛːrəpleɪn"}],"text":"aeroplane"}],
"type":"headword","word":"aeroplane"
}
Modify these lines :
String lexicalEntries = results.getJSONObject(0).getString("lexicalEntries");
definitionView.setText(lexicalEntries);
to :
String definition = results.getJSONObject(0).getString("lexicalEntries")
.getJSONArray("entries").getJSONObject(0).getJSONArray("senses")
.getJSONObject(0).getJSONArray("definitions").getString(0);
definitionView.setText(definition);
Of course you may need to modify your UI based on the number of definitions a word has.
Also, you should probably consider using POJOs instead of directly dealing with the JSON response.
I'd recommend Jackson or GSON for doing this.
String definitions=results.getJSONArray("lexicalEntries")
.getJSONObject(0)
.getJSONArray("entries")
.getJSONObject(0)
.getJSONArray("senses")
.getJSONArray("definitions")
.get(0)
So , The thing is , There are a lot of gaps in the JSON for different words .
Which means a word may have an array of "synonyms" but others don't , So in your code you are trying to reach something that doesn't actually exist (a NULL value) which is likely to throw an exception every time you search for a word that the JSON returned doesn't match the JSON you are expecting , Because there are missing (NULL) values .
The app I made using oxford dictionary required a lot of work just to make sure there is no thrown exception .
I used retrofit with moshi converter factory , And then Do the following :
1-In your custom classes , Make sure you annotate every data member with
#Json and provide the name of the keys in the JSON of oxford
2-make sure that every declared type is nullable , including both List and the type inside of it
You'll then be able to get the result , And Now comes the part where you handle evey call that may be null
I know this is a bit old question , But It happened that I struggled with this api once , So I hope this may help someone :)

How to search for images in Android Programmatically?

I have some EditTexts in my Activity.First text the for the title, second is for author.Now the user loose focus from the second edittext ie author.I want to get the images related to that content (title and author).So what I did, I concat the title and author name and make HTTP request using Volley.And I print that response.But the response is so unpredictable that I can not fetch the images from it.
try {
String googleImageUrl = "http://images.google.com/images?q=";
String query = URLEncoder.encode(title + " " + author, "utf-8");
String url = googleImageUrl + query;
Toast.makeText(context, url, Toast.LENGTH_SHORT).show();
// Instantiate the RequestQueue.
RequestQueue queue = Volley.newRequestQueue(this);
// Request a string response from the provided URL.
StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
post_des.setText("Response is: " + response);
Log.i("Show me something awesome dude", response);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
post_des.setText("That didn't work!");
}
});
// Add the request to the RequestQueue.
queue.add(stringRequest);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
And the responce is like this:
Response is: <!doctype html><html itemscope="" itemtype="http://schema.org/SearchResultsPage" lang="en-IN"><head><meta content="text/html; charset=UTF-8" http-equiv="Content-Type"><meta content="/images/branding/googleg/1x/googleg_standard_color_128dp.png" itemprop="image"><link href="/images/branding/product/ico/googleg_lodp.ico" rel="shortcut icon"><title>something something - Google Search</title><style>#gb{font:13px/27px Arial,sans-serif;height:30px}#gbz,#gbg{position:absolute;white-space:nowrap;top:0;height:30px;z-index:1000}#gbz{left:0;padding-left:4px}#gbg{right:0;padding-right:5px}#gbs{background:transparent;position:absolute;top:-999px;visibility:hidden;z-index:998;right:0}.gbto #gbs{background:#fff}#gbx3,#gbx4{background-color:#2d2d2d;background-image:none;_background-image:none;background-position:0 -138px;background-repeat:repeat-x;border-bottom:1px solid #000;font-size:24px;height:29px;_height:30px;opacity:1;filter:alpha(opacity=100);position:absolute;top:0;width:100%;z-index:990}#gbx3{left:0}#gbx4{right:0}#gbb{position:relative}#gbbw{left:0;position:absolute;top:30px;width:100%}.gbtcb{position:absolute;visibility:hidden}#gbz .gbtcb{right:0}#gbg .gbtcb{left:0}.gbxx{display:none........like wise
I was expecting to get a Html doc.
So how to make a HTTP request for images with the content(title and author).
Edit
In layman language,
Suppose I am on images.google.com, and I typed in something in search bar, and make a search, now I want the data that Google return as the Url of the images on that webpage(I am doing all this in backend not showing it to the user.)
I think it is now understandable :)
You got html but of the whole search page. You can retrieve pictures' urls with css selectors and [JSOUP library][2] (easy to use). Just go to Chrome browser and then choose Settings - More tools - Developer tools. Then click the right mouse button on a picture and choose inspect and you'll see which container is for the pictures and what div contains src url of the images and then you right click this div and choose copy css selector. Then work with the library.
But be aware, it's not practical cause if they change the page html your code will beak. You better use specific api for this purpose, like Google Custom Search API as it was suggested in comments above.
To put image into UI you need to get its url address and then you can use Glide or Picasso or even Volley
// Retrieves an image with Volley specified by the URL, displays it in the UI.
ImageRequest request = new ImageRequest(url,
new Response.Listener<Bitmap>() {
#Override
public void onResponse(Bitmap bitmap) {
mImageView.setImageBitmap(bitmap);
}
}, 0, 0, null,
new Response.ErrorListener() {
public void onErrorResponse(VolleyError error) {
mImageView.setImageResource(R.drawable.image_load_error);
}
});
EDIT:
Here is CSS selector for all images on the google search page img.rg_ic. Using Jsoup and this selector you'll get access to all the image tags on the page
Jsoup example:
Document doc = Jsoup.connect(your link string).get();
Elements imgs = doc.select("img");//the selector
for (Element img : imgs) {
//add img urls to String array and then use to get imgs with them
String s = img.attr("src");
arr.add(s);
}
[![enter image description here][3]][3]
EDIT2 :
Your code with changes:
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import java.io.IOException;
public class MainActivity extends AppCompatActivity {
TextView textView;
String googleImageUrl = "https://www.google.co.in/search?biw=1366&bih=675&tbm=isch&sa=1&ei=qFSJWsuTNc-wzwKFrZHoCw&q=";
ArrayList<String> urls = new ArrayList<>();
String url;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
AsyncTask.execute(new Runnable() {
#Override
public void run() {
Log.i("someething" , "something");
getImages("https://www.google.co.in/search?biw=1366&bih=675&tbm=isch&sa=1&ei=qFSJWsuTNc-wzwKFrZHoCw&q=somethingsomething");
}
});
}
private void getImages(String url) {
Document doc = null;
try{
doc = Jsoup.connect(url).get();
}catch (IOException e){
e.printStackTrace();
}
Elements imgs = doc.select("img");
System.out.println("Damn images"+imgs);
for (Element img : imgs){
Log.d("image-src", img.attr("data-src"));//changed `src` to `data-src`
}
}
}
You can get a List of google search images using Jsoup .،. see official site here https://jsoup.org/
/**
* Extract images from google as ArrayList.
*
* #param searchQuery is the string to search for
* #return returnedURLS is the List of urls
*/
private List<String> extractImagesFromGoogle(String searchQuery) throws IOException {
final String encodedSearchUrl = "https://www.google.com/search?q=" + URLEncoder.encode(searchQuery, "UTF-8") + "&source=lnms&tbm=isch&sa=X&ved=0ahUKEwiUpP35yNXiAhU1BGMBHdDeBAgQ_AUIECgB";
Document document = Jsoup.connect(encodedSearchUrl).get();
String siteResponse = document.toString();
List<String> returnedURLS = new ArrayList<String>();
// parse the object and query the values (the urls) for specific keys ("ou")
Pattern pattern = Pattern.compile("\"ou\":\"(.*?)\"");
Matcher matcher = pattern.matcher(siteResponse);
while (matcher.find()) {
returnedURLS.add(matcher.group(1));
}
return returnedURLS;
}
// Test it now:
List<String> retrievedURLS = new ArrayList<String>();
try {
retrievedURLS = extractImagesFromGoogle("pyramids");
} catch (IOException e) {
e.printStackTrace();
}
System.out.println(">> List Size: " + retrievedURLS.size());
System.out.println(">> List of images urls: " + retrievedURLS);

Reading file from AVD sd card and displaying text view

I have a text file that has this information
Casino Canberra;21 Binara Street, Canberra ACT, 2601;Canberra Casino is a casino located in Civic in the central part of the Australian capital city of Canberra. The Casino is relatively small compared with other casinos in Australia.;(02) 6257 7074;www.canberracasino.com.au
National Museum of Canberra;Parkes Place, Canberra ACT, 2601;The National Museum of Australia explores the land, nation and people of Australia. Open 9am - 5pm every day except Christmas Day. General admission free.;(02) 6240 6411;www.nga.gov.au
which is stored in the sdcard
after this i retrieve the values using this method
package au.edu.canberra.g30813706;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import android.app.Activity;
import android.os.Environment;
public class FileReader extends Activity{{
ArrayList<read> sInfo = new ArrayList<read>();
ArrayList<String> sLines = new ArrayList<String>();
String line;
String[] saLineElements;
String txtName = "AccomodationTxt.txt";
File root = Environment.getExternalStorageDirectory();
File path = new File(root, "CanberraTourism/" + txtName);
try {
BufferedReader br = new BufferedReader (
new InputStreamReader(
new FileInputStream(path)));
while ((line = br.readLine()) != null)
{
sLines.add(line);
//The information is split into segments and stored into the array
saLineElements = line.split(";");
//for (int i = 0; i < saLineElements.length; i++)
// sInfo.add(new read(saLineElements[i]));
sInfo.add(new read(saLineElements[0], saLineElements[1], saLineElements[3], saLineElements[4], saLineElements[5]));
}
br.close();
}
catch (FileNotFoundException e) {
System.err.println("FileNotFoundException: " + e.getMessage());
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}}
}
But i also have and object class to store each individual item into
package au.edu.canberra.g30813706;
public class read {
public String name;
public String address;
public String info;
public String phone;
public String www;
public read (String name, String address, String info, String phone, String www)
{
this.name = name;
this.address = address;
this.info = info;
this.phone = phone;
this.www = www;
}
}
The only issue im having is trying to display the information in a text view which i have no idea how to call the values i need
This is where im trying to insert it
package au.edu.canberra.g30813706;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
import au.edu.canberra.g30813706.FileReader;
import au.edu.canberra.g30813706.read;
public class Accommodation_info extends Activity{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.accommodation_layout);
}}
You should probably look into using the Application class. You can think of Application as a GUI-less activity which works like the model in a program following the MVC pattern. You can put all of your read objects into a data structure in your Application and then access them with accessors and mutators of your own design.
Take a look at this official doc.
As your code stands, you can only access your instances of read by obtaining a reference to your FileReader class, but your two activities are separate entities. You'd have to do something like this:
// This is the main activity and should be launched first
// Check your manifest to make sure it launches with this activity
package au.edu.canberra.g30813706;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
import au.edu.canberra.g30813706.FileReader;
import au.edu.canberra.g30813706.read;
public class Accommodation_info extends Activity
{
// Declare the file reader so you'll have a reference
FileReader reader;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.accommodation_layout);
// Instantiate the file reader
reader = new FileReader();
// Now you can access the array inside FileReader
// obviously, you need to have a text view called my_textView defined in the
// layout file associated with this activity
TextView myTextView = (TextView)findViewById(R.id.my_textView);
// displays the first element in FileReader's array list
myTextView.setText((String)reader.get(0));
}}
At the moment, you might be in a bit deep for your current understanding of Android and/or Java. I would encourage you to follow as many code examples as possible, get comfortable with Android and then go back to your project when you have a little more experience.

How to make a connection with my ontology?

I created an ontology with Protégé. Then I created an Android interface which contains two edit texts and a button. The main function of my code is to make a connection between my application and the ontology and store these data into it. I use a triple store for storage.
But it didn't work correctly. I'm using Sesame as server but I don't know how to get the correct URL of the "update" service. I might have made other errors but here is my activity's code:
package com.example.ontologie1;
import com.hp.hpl.jena.ontology.DatatypeProperty;
import com.hp.hpl.jena.ontology.Individual;
import com.hp.hpl.jena.ontology.OntClass;
import com.hp.hpl.jena.ontology.OntModel;
import com.hp.hpl.jena.ontology.OntModelSpec;
import com.hp.hpl.jena.rdf.model.Literal;
import com.hp.hpl.jena.rdf.model.ModelFactory;
import com.hp.hpl.jena.rdf.model.Property;
import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import java.io.IOException;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.PostMethod;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends Activity {
private Button buttonconnexion;
private EditText editpseudo;
private EditText editpassword;
public String ps;
public String pa;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editpseudo = (EditText) findViewById(R.id.welcomeedittextlogin);
editpassword = (EditText) findViewById(R.id.welcomeedittextpassword);
buttonconnexion = (Button) findViewById(R.id.welcomebuttonconnexion);
buttonconnexion.setOnClickListener(click1);
}
protected OnClickListener click1 = new OnClickListener() {
public void onClick(View arg0) {
ps= editpseudo.getText().toString();
pa= editpassword.getText().toString();
try {
connexion(ps , pa);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
};
protected void connexion(String pseudo,String password) throws IOException {
String requete = "<http://www.w3.org/2002/07/owl#> .\n"
+ "INSERT DATA {\n"
+ " <http://www.owl-ontologies.com/Ontology_profile.owl#USER> a onto:USER;\n"
+ " onto:Login " + pseudo + ";\n"
+ " onto:Password " + password + ";\n"
+ "}";
PostMethod post = new PostMethod("<http://www.openrdf.org/config/repository#>");
NameValuePair[] paramRequete = {
new NameValuePair("query", requete),
};
post.setRequestBody(paramRequete);
InputStream in = post.getResponseBodyAsStream();
Toast t = null ;
t.setText(in.toString());
t=new Toast(null);
}
}
I don't have experience with Android programming, but there are some issues that suggest you need to rethink your goals.
An ontology is not a database. You don't store data in an ontology, and you don't need an ontology to store data in a triplestore.
To store data in a triplestore (using SPARQL), your triplestore needs a SPARQL endpoint. That endpoint has a URI that you send your POST or GET request to. If you installed Sesame on your local machine, that URI may look like http://localhost:8080/sparql. If you want to insert data, the triplestore needs to allow that.
You also need a valid SPARQL query, which your requete is not. The first line,
<http://www.w3.org/2002/07/owl#> .
is not complete. Usually there are PREFIXes on the first lines of a SPARQL query, but they don't end with a .. For example:
PREFIX owl: <http://www.w3.org/2002/07/owl#>
To use the prefix onto: as you do, you need to define it in the same way. For a complete SPARQL tutorial, see this.
Also, the lines
Toast t = null ;
t.setText(in.toString());
t=new Toast(null);
will generate a NullPointerException, as you call a method on t that is null.

Categories

Resources