I want to display the data of my database which is in txt file randomly one at a time, and it cannot repeat the data.
private void question() {
// TODO Auto-generated method stub
InputStreamReader inputStream = new InputStreamReader
(getResources().openRawResource(R.raw.question1));
BufferedReader br = new BufferedReader(inputStream);
//number of lines in the database numLines
int numLines= 10;
Random r = new Random();
int desiredLine = r.nextInt(numLines);
String theLine="";
int lineCtr = 0;
try {
while ((theLine = br.readLine()) != null) {
if (lineCtr == desiredLine) {
StringTokenizer st = new StringTokenizer(theLine,",");
while(st.hasMoreTokens())
{
//reading and getting data from the database","
String a = st.nextToken();
String b = st.nextToken();
String c = st.nextToken();
String d = st.nextToken();
String e = st.nextToken();
String f = st.nextToken();
//button setText
question.setText(a);
ca.setText(f);
firstbutton.setText(e);
secondbutton.setText(d);
thirdbutton.setText(b);
fourthbutton.setText(c);
//assigning
firstholder =e;
secondholder =d;
thirdholder=b;
fourthholder =c;
break;
}
}
lineCtr++;
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Related
I receive data in webservice and insert in sqlite database Android but if filed is empty repeat before filed As far as new filed no empty and repeat ...
please help me:
public class gfc extends AsyncTask {
private String Link = "";
private String Count = "";
private String tid = "";
private String tim = "";
private String tuser = "";
private String tusername = "";
private String tmatn = "";
private String tcomments = "";
private String tlikes = "";
private String tdate = "";
private String tip_addr = "";
private database db;
public gfc(String link, String count, Context c) {
Link = link;
Count = count;
db = new database(c);
}
#Override
protected String doInBackground(Object... arg0) {
try {
String data = URLEncoder.encode("count", "UTF8") + "=" + URLEncoder.encode(Count, "UTF8");
URL mylink = new URL(Link);
URLConnection connect = mylink.openConnection();
connect.setDoOutput(true);
OutputStreamWriter wr = new OutputStreamWriter(connect.getOutputStream());
wr.write(data);
wr.flush();
BufferedReader reader = new BufferedReader(new InputStreamReader(connect.getInputStream()));
StringBuilder sb = new StringBuilder();
String line = null;
db.open();
while ((line = reader.readLine()) != null) {
int f = 0;
int c = 0;
for (int i = 0; i < line.length(); i++) {
if (line.charAt(i) == '|') {
String temp = line.substring(f, i);
if (c == 0) {
tid = temp;
}
if (c == 1) {
tdate = temp;
}
if (c == 2) {
tuser = temp;
}
if (c == 3) {
tusername = temp;
}
if (c == 4) {
tip_addr = temp;
}
if (c == 5) {
tcomments = temp;
}
if (c == 6) {
tlikes = temp;
}
if (c == 7) {
tim = temp;
}
if (c == 8) {
tmatn = temp.replace("^", "\n");
}
c += 1;
f = i + 1;
}
}
db.insert(tid, tuser, tusername, tmatn, tcomments, tlikes, tdate, tip_addr, tim);
sb.append("t");
}
db.close();
index.res = sb.toString();
} catch (Exception e) {}
return "";
}
}
I am creating a book reader using siegmann epub library. I am not able to display anything on the screen but in the logcat. What type of layout to use for display?
Here is my main.java
public class MainActivity extends Activity {
private WebView webview;
private String line, line1="", finalstr="";
int i = 0;
private String fullBook;
private Book book;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
webview = (WebView) findViewById(R.id.webview);
AssetManager assetManager = getAssets();
try{
//find input Stream for book
InputStream epubInputStream = assetManager.open("oliver_twist.epub");
//Load book from input stream
book = (new EpubReader()).readEpub(epubInputStream);
Log.i("epublib", "title: "+book.getTitle());
//Log the book's cover image property
//Bitmap coverImage = BitmapFactory.decodeStream(book.getCoverImage().getInputStream());
//Log.i("epublib", "CoverImage is" + coverImage.getWidth()+" by "+coverImage.getHeight()+" pixels");
//Log the tables of contents
logTableOfContents(book.getTableOfContents().getTocReferences(),0);
fullBook = getEntireBook();
}
catch(IOException e){
Log.e("epublib", e.getMessage());
}
String javascrips = "";
try {
// InputStream input = getResources().openRawResource(R.raw.lights);
InputStream input = this.getAssets().open(
"poe-fall-of-the-house-of-usher.epub");
int size;
size = input.available();
byte[] buffer = new byte[size];
input.read(buffer);
input.close();
// byte buffer into a string
javascrips = new String(buffer);
} catch (IOException e) {
e.printStackTrace();
}
// String html = readFile(is);
webview.loadDataWithBaseURL("file:///android_asset/", javascrips,
"application/epub+zip", "UTF-8", null);
//webview.setwe
}
private void logTableOfContents(List<TOCReference> tocReferences, int depth){
if(tocReferences == null){
System.out.println("---->>>"+tocReferences);
return;
}
for(TOCReference tocReference:tocReferences){
StringBuilder tocString = new StringBuilder();
for(int i=0;i<depth;i++){
tocString.append("\t");
}
tocString.append(tocReference.getTitle());
Log.i("epulib", tocString.toString());
try {
InputStream is = tocReference.getResource().getInputStream();
BufferedReader r = new BufferedReader(new InputStreamReader(is));
while ((line = r.readLine()) != null) {
// line1 = Html.fromHtml(line).toString();
Log.v("line" + i, Html.fromHtml(line).toString());
// line1 = (tocString.append(Html.fromHtml(line).toString()+
// "\n")).toString();
line1 = line1.concat(Html.fromHtml(line).toString());
}
finalstr = finalstr.concat("\n").concat(line1);
Log.i("Content " + i, finalstr);
i++;
} catch (IOException e) {
}
logTableOfContents(tocReference.getChildren(), depth+1);
}
webview.loadDataWithBaseURL("", finalstr, "text/html", "UTF-8", "");
}
public String getEntireBook(){
String line, linez = null;
Spine spine = book.getSpine();
Resource res;
List<SpineReference> spineList = spine.getSpineReferences() ;
int count = spineList.size();
int start = 0;
StringBuilder string = new StringBuilder();
for (int i = start; count > i; i = i +1) {
res = spine.getResource(i);
try {
InputStream is = res.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
try {
while ((line = reader.readLine()) != null) {
linez = string.append(line + "\n").toString();
}
} catch (IOException e) {e.printStackTrace();}
} catch (IOException e) {
e.printStackTrace();
}
}
return linez;
}
}
In main.xml, I have just created a webview. What otehr elemnets I can add? Is it a text view on which book is displayed?
I solved it using the following code and it worked!!
public class MainActivity extends Activity {
private WebView webview;
private String line, line1="", finalstr="";
int i = 0;
private String fullBook;
private Book book;
private TextView tv;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
webview = (WebView) findViewById(R.id.webview);
WebSettings webSettings = webview.getSettings();
webSettings.setJavaScriptEnabled(true);
webSettings.setBuiltInZoomControls(true);
AssetManager assetManager = getAssets();
//tv = (TextView) findViewById(R.id.tv);
try{
//find input Stream for book
InputStream epubInputStream = assetManager.open("TheThreeBears.epub");
//Load book from input stream
book = (new EpubReader()).readEpub(epubInputStream);
Log.i("epublib", "title: "+book.getTitle());
//Log the book's cover image property
// Bitmap coverImage = BitmapFactory.decodeStream(book.getCoverImage().getInputStream());
//Log.i("epublib", "CoverImage is" + coverImage.getWidth()+" by "+coverImage.getHeight()+" pixels");
//Log the tables of contents
logTableOfContents(book.getTableOfContents().getTocReferences(),0);
getEntireBook();
}
catch(IOException e){
Log.e("epublib", e.getMessage());
}
}
private void logTableOfContents(List<TOCReference> tocReferences, int depth){
// Load entire text into particular no. of lines and display each
// then with next button navigate through pages
String lineXX = "p";
if(tocReferences == null){
System.out.println("---->>>"+tocReferences);
return ;
}
for(TOCReference tocReference:tocReferences){
StringBuilder tocString = new StringBuilder();
for(int i=0;i<depth;i++){
tocString.append("\t");
}
tocString.append(tocReference.getTitle());
//tv.setText(tocString.toString());
//Log.i("epulib", tocString.toString());
try {
InputStream is = tocReference.getResource().getInputStream();
BufferedReader r = new BufferedReader(new InputStreamReader(is));
while ((line = r.readLine()) != null) {
//String lineX = Html.fromHtml(line).toString();
//lineXX = lineX;
Log.v("line" + i, Html.fromHtml(line).toString());
line1 = line1.concat(Html.fromHtml(line).toString());
}
finalstr = finalstr.concat("\n").concat(line1);
//tv.setText(finalstr);
//Log.i("Content " + i, finalstr);
i++;
} catch (IOException e) {
}
logTableOfContents(tocReference.getChildren(), depth+1);
}
//return lineXX;
webview.loadDataWithBaseURL("", finalstr, "text/html", "UTF-8", "");
}
public void getEntireBook(){
String line, linez = null;
Spine spine = book.getSpine();
Resource res;
List<SpineReference> spineList = spine.getSpineReferences() ;
int count = spineList.size();
int start = 0;
StringBuilder string = new StringBuilder();
for (int i = start; count > i; i = i +1) {
res = spine.getResource(i);
try {
InputStream is = res.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
try {
while ((line = reader.readLine()) != null) {
linez = string.append(line + "\n").toString();
}
} catch (IOException e) {e.printStackTrace();}
} catch (IOException e) {
e.printStackTrace();
}
}
webview.loadData(linez, "text/html", "utf-8");
}
}
Im making question and answer. my question generate randomly but, the question repeated again.
im using txt file as my database when the int array generate randomly my holder get what is string line in my database. supposed to be int array = x, and string line = y;
{y==x}. my question is when i generate again the question get again, what supposed i will do guys?.
private void question() {
InputStreamReader inputStream = new InputStreamReader
(getResources().openRawResource(R.raw.question1));
BufferedReader br = new BufferedReader(inputStream);
ArrayList<Integer> ar= new ArrayList<Integer>();
int[] number= {1,2,3,4,5,6,7,8,9,10};
for (int i : number) {
ar.add(i);
}
Random r = new Random();
int select = r.nextInt(ar.size());
int random = ar.get(select);
ar.remove(select);
String theLine="";
int lineCtr = 0;
try {
while ((theLine = br.readLine()) != null) {
if (lineCtr == select) {
StringTokenizer st = new StringTokenizer(theLine,",");
while(st.hasMoreTokens())
{
//reading and getting data from the database","
String a = st.nextToken();
String b = st.nextToken();
String c = st.nextToken();
String d = st.nextToken();
String e = st.nextToken();
String f = st.nextToken();
//button setText
question.setText(a);
ca.setText(f);
firstbutton.setText(e);
secondbutton.setText(d);
thirdbutton.setText(b);
fourthbutton.setText(c);
//assigning
firstholder =e;
secondholder =d;
thirdholder=b;
fourthholder =c;
break;
}
}lineCtr++;
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Have you try below code for solve repeating question problem :-
Collections.shuffle(Arrays.asList(number));
I have an html file in assets, aaa.html.
I want to read the contents of html file and replace it from another string.
Is this way is right or is there any other option.
my code:
File f = new File("file:///android_asset/aaa.html");
FileReader fr = new FileReader(f);
BufferedReader br = new BufferedReader(fr);
But its giving file not found, where as loading in web view loads the file.
InputStream is = getAssets().open("aaa.html");
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
String str = new String(buffer);
str = str.replace("old string", "new string");
If you want to load file in webview then use this
mWebView.loadUrl("file:///android_asset/myfile.html");
you want to replace content inside Html file tags so the solution class code is here..
public class CardDetail {
public static String newHtmlString = "";
// private Context context;
#SuppressWarnings("rawtypes")
public String getNewHtmlString(String htmlString, HashMap hm) {
try {
StringTokenizer st = new StringTokenizer(htmlString, "##");
CardDetail.newHtmlString = "";
while (st.hasMoreTokens()) {
String token = st.nextToken();
CardDetail.newHtmlString += token;
if (st.hasMoreTokens()) {
String token2 = st.nextToken();
if (token2.equals("NAME") || token2.equals("POSITION") || token2.equals("COMPANY") || token2.equals("PHOTOURL"))
CardDetail.newHtmlString += hm.get(token2);
if (token2.equals("SKYPE_CONTAINER1")
|| token2.equals("TWITTER_CONTAINER1")
|| token2.equals("PHONENUMBER_CONTAINER1")
|| token2.equals("EMAIL_CONTAINER1")
|| token2.equals("ADDRESS_CONTAINER1")) {
String replaceString = st.nextToken();
String tokenMiddle = (String) hm.get(st.nextToken());
if (!tokenMiddle.equals("")) {
replaceString += tokenMiddle;
CardDetail.newHtmlString += replaceString + st.nextToken();
st.nextElement();
} else {
st.nextElement();
st.nextElement();
}
}
}
}
// Log.i("convertedHTMLString", newHtmlString);
return CardDetail.newHtmlString;
// htmlString = "<img src='" + hm.get("PHOTOURL") + "' width=80 height=80>";
// return htmlString;
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
return null;
}
#SuppressWarnings("unchecked")
public HashMap<?, ?> getProfileHashMap(JSONObject jsonObject) {
#SuppressWarnings("rawtypes")
HashMap hm = new HashMap();
jsonObject = (new JSONConverterClass()).convertJsonObjectToCardDetail(jsonObject);
try {
hm.put("EMAIL", jsonObject.getString("email"));
hm.put("NAME", jsonObject.getString("firstname") + " " + jsonObject.getString("lastname"));
hm.put("COMPANY", jsonObject.getString("company_name"));
hm.put("POSITION", jsonObject.getString("position"));
hm.put("WEBSITE", jsonObject.getString("website"));
hm.put("PHONENUMBER", jsonObject.getString("phonenumber"));
hm.put("PHOTOURL", jsonObject.getString("picture_url"));
hm.put("SKYPE", jsonObject.getString("skype_username"));
hm.put("TWITTER", jsonObject.getString("twitter_username"));
hm.put("ADDRESS", jsonObject.getString("generic_location"));
} catch (Exception e) {
e.printStackTrace();
}
return hm;
}
}
convertJsonObjectToCardDetail this class just replace string with values from Json
hope this solves your problem ....
I have a String that I try to split. The following code works
lsSagor = "some text\n Some more text\n More text~Text again\n Text\n text~Some text ..."
final String[] laList = lsSagor.split("~");
String[] laSaga = laList[0].split("\n");
Gives:
laSaga[0] => some text
laSaga[1] => some more text
laSaga[2] => More text
But if I download the textfile, it fails to split and gives:
laSaga[0] => "some text\n Some more text\n More text"
So it seems the first split works, but not the second.
Here is the code I use to download the file
String lsSagor = getFileFromUrl(BASEURL+"/sagor.txt");
public static String getFileFromUrl(String url)
{
InputStream content = null;
try
{
HttpGet httpGet = new HttpGet(url);
HttpClient httpclient = new DefaultHttpClient();
// Execute HTTP Get Request
HttpResponse response = httpclient.execute(httpGet);
content = response.getEntity().getContent();
}
catch (Exception e)
{
//handle the exception !
}
BufferedReader rd = new BufferedReader(new InputStreamReader(content), 4096);
String line;
StringBuilder sb = new StringBuilder();
try {
while ((line = rd.readLine()) != null) {
sb.append(line);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
rd.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return sb.toString();
}
From the documentation
I don't think you will find your string contains any newline character to split on, you would need to do
while ((line = rd.readLine()) != null) {
sb.append(line);
sb.append("\n");
}
to get that and I'm sure there is an easier way to just read it newlines and all in the first place.
Hi I think the problem is in String.split() function
Old method but work :)
public static String[] splitString(String str, char separator)
{
String[] retVal = null;
int length = str.length();
int size = 1;
int jIndx = 0;
int expressionLength = 0;
while ((jIndx = str.indexOf(separator, jIndx + 1)) != -1)
{
size++;
}
retVal = new String[size];
jIndx = 0;
char[] charArray = str.toCharArray() ;
for (int index = 0; index < length; index++)
{
if (charArray[index] == separator)
{
retVal[jIndx] = str.substring(index - expressionLength, index);
jIndx++;
expressionLength = 0;
}
else
expressionLength++;
if (index + 1 == length)
{
retVal[jIndx] = str.substring(index + 1 - expressionLength, index + 1);
}
}
return retVal;
}
This is the (not so beautiful) solution
lsSagor = "some text# Some more text# More text~Text again\n Text# text~Some text ..."
String lsSagor = getFileFromUrl(BASEURL+"/sagor.txt");
final String[] laList = lsSagor.split("~");
giAntalSagor = laList.length;
String[] laSaga = laList[0].split("#");
final String[] guiLaList = new String[giAntalSagor];
for (int i = 0; i < giAntalSagor; i++)
{
guiLaList[i] = laList[i].replaceAll("#", "\n");
}
guiLaList is used for layout with "\n" and the other list laList to get the information I wanted.