why do this code not work. - Android Software Development

im using this code to pull a random string from my array .
Code:
import java.util.Random;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import java.util.*;
public class randomstring extends Activity {
private static final String rgenerator = null;
Button NextButton, PreviousButton;
TextView TextViewQuote;
private String[] myString;
myString = res.getStringArray(R.array.myArray);
String q = myString[rgenerator.nextInt(myString.length)];
i have 2 errors atm. one at the end of
Code:
private String[] myString;
. the error is this
Syntax error on token ";", , expected
Click to expand...
Click to collapse
the other error is.
The method nextInt(int) is undefined for the type String
Click to expand...
Click to collapse

private String[] myString;
Click to expand...
Click to collapse
Local variables can't have access flags - that doesn't make any sense. Remove "private".
You should have exactly the same error in the line defining rgenerator (illegal use of "private static").
The method nextInt(int) is undefined for the type String
Click to expand...
Click to collapse
I guess you wanted rgenerator to be of Random type, not String. Besides you didn't initialized that variable.
Change:
private static final String rgenerator = null;
Click to expand...
Click to collapse
to:
final Random rgenerator = new Random();
Click to expand...
Click to collapse
Get some decent IDE like Eclipse or Netbeans.
Learn Java. You don't even know, what is going on here - these errors was totally stupid ;-)

Related

[Q] Please help with tutorial code!

Good evening everyone! I am working on learning some java and I have made it to the notepad tutorial and when I go to run it on the emulator, I am getting a few errors, and I'm hoping someone here may be able to help.
Code:
package com.a8a.todolist;
import java.util.ArrayList;
import android.app.Activity;
import android.os.Bundle;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.ArrayAdapter;
import android.view.View.OnClickListener;
public class ToDoList extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle icicle) {
//Inflat your view
setContentView(R.layout.main);
//Get references to UI widgets
ListView myListView = (ListView)findViewById(R.id.myListView);
final EditText myEditText = (EditText)findViewById(R.id.myEditText);
//Create the array list of to do items
final ArrayList<String> todoItems = new ArrayList<String>();
//Create the array adapter to bind the array to the listview
final ArrayAdapter<String> aa;
[B]aa = new ArayAdapter<String>(this, android.R.layout.simple_list_item_1,todoItems);[/B] [I]Multiple markers at this line - ArayAdapter cannot be resolved to a type - Line breakpoint:ToDoList [line: 27] - onCreate[/I]
(Bundle)
//Bind the arary adapter to the listview.
myListView.setAdapter(aa);
[B]myEditText.setOnKeyListener(new OnKeyListener() {[/B] [I]OnKeyListener cannot be resolved to a type[/I]
public boolean onKey(View v, int keyCode, KeyEvent event) {
if (event.getAction() == KeyEvent.ACTION_DOWN)
if (keyCode == KeyEvent.KEYCODE_DPAD_CENTER)
{
todoItems.add(0, myEditText.getText().toString());
aa.notifyDataSetChanged();
myEditText.setText("");
return true;
}
return false;
}
});
}
}
The bolded text is whats getting the error and the italics are the error itself. Any help would be appreciated, if you are able to explain why the change needs to be made as well that would be much appreciated, so I can learn from my mistakes.
Thanks in advance!
ArayAdapter was miss-spelled ArrayAdapter
I was also missing an import for OnKeyListener (import android.view.View.OnKeyListener). If you don't import a class and try to use it, Java doesn't know what it is, so it tells you it doesn't recognize the type.

{Q} Web View inside a fragment

I have a viewpager with four webview fragments. Im trying to get a GoBack Action to my WebView which is inside of a fragment. But i cant implement it right into my code here is the code of my webview in my fragments. I also can't seem to get a downloadListener to work either. Sorry I am kinda new to fragments and trying to understand how they work.
Code:
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebSettings.RenderPriority;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.LinearLayout;
public class Fragment1 extends Fragment {
private static final String WebSettings = null;
private WebView webView;
private Bundle webViewBundle;
[user=439709]@override[/user]
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
LinearLayout ll = (LinearLayout) inflater.inflate(R.layout.fragment_1,
container, false);
webView = (WebView) ll.findViewById(R.id.webview);
webView.setWebViewClient(new WebViewClient());
webView.getSettings().setLoadWithOverviewMode(true);
webView.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
webView.getSettings().setJavaScriptEnabled(true);
webView.getSettings().setBuiltInZoomControls(true);
webView.getSettings().setSupportZoom(true);
webView.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
webView.getSettings().setAllowFileAccess(true);
webView.getSettings().setDomStorageEnabled(true);
webView.getSettings().setRenderPriority(RenderPriority.HIGH);
if (webViewBundle == null) {
try{
webView.loadUrl("http://www.google.com");
}catch (Exception e){
e.printStackTrace();}
} else {
webView.restoreState(webViewBundle);
}
return ll;
}
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
[user=439709]@override[/user]
public void onPause() {
super.onPause();
webViewBundle = new Bundle();
webView.saveState(webViewBundle);
}
}
dfuse06 said:
I have a viewpager with four webview fragments. Im trying to get a GoBack Action to my WebView which is inside of a fragment. But i cant implement it right into my code here is the code of my webview in my fragments. I also can't seem to get a downloadListener to work either. Sorry I am kinda new to fragments and trying to understand how they work.
Code:
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebSettings.RenderPriority;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.LinearLayout;
public class Fragment1 extends Fragment {
private static final String WebSettings = null;
private WebView webView;
private Bundle webViewBundle;
[user=439709]@override[/user]
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
LinearLayout ll = (LinearLayout) inflater.inflate(R.layout.fragment_1,
container, false);
webView = (WebView) ll.findViewById(R.id.webview);
webView.setWebViewClient(new WebViewClient());
webView.getSettings().setLoadWithOverviewMode(true);
webView.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
webView.getSettings().setJavaScriptEnabled(true);
webView.getSettings().setBuiltInZoomControls(true);
webView.getSettings().setSupportZoom(true);
webView.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
webView.getSettings().setAllowFileAccess(true);
webView.getSettings().setDomStorageEnabled(true);
webView.getSettings().setRenderPriority(RenderPriority.HIGH);
if (webViewBundle == null) {
try{
webView.loadUrl("http://www.google.com");
}catch (Exception e){
e.printStackTrace();}
} else {
webView.restoreState(webViewBundle);
}
return ll;
}
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
[user=439709]@override[/user]
public void onPause() {
super.onPause();
webViewBundle = new Bundle();
webView.saveState(webViewBundle);
}
}
Click to expand...
Click to collapse
You will need to override the onKeyUp method in the Activity. Then search for the fragment there and call a method of your subclass of Fragment which you want to be executed when the back key is pressed.
nikwen said:
You will need to override the onKeyUp method in the Activity. Then search for the fragment there and call a method of your subclass of Fragment which you want to be executed when the back key is pressed.
Click to expand...
Click to collapse
So I can't actually do this inside the fragment?
Sent from my SCH-I535 using Tapatalk 2
dfuse06 said:
So I can't actually do this inside the fragment?
Sent from my SCH-I535 using Tapatalk 2
Click to expand...
Click to collapse
I do not think so.
nikwen said:
I do not think so.
Click to expand...
Click to collapse
That must be all my errors then.
Sent from my SCH-I535 using Tapatalk 2
nikwen said:
You will need to override the onKeyUp method in the Activity. Then search for the fragment there and call a method of your subclass of Fragment which you want to be executed when the back key is pressed.
Click to expand...
Click to collapse
could you post a example on how it should look. This is driving me nuts nothing is working
dfuse06 said:
could you post a example on how it should look. This is driving me nuts nothing is working
Click to expand...
Click to collapse
Google!!!
Check those:
http://stackoverflow.com/questions/12210906/fragment-activity-catch-onkeydown-and-use-in-fragment
http://stackoverflow.com/questions/10631425/android-webview-inside-fragment-how-to-add-goback
nikwen said:
Google!!!
Check those:
http://stackoverflow.com/questions/12210906/fragment-activity-catch-onkeydown-and-use-in-fragment
http://stackoverflow.com/questions/10631425/android-webview-inside-fragment-how-to-add-goback
Click to expand...
Click to collapse
lol!!! I have googled it. Looked on stackoverflow posted on stack
http://stackoverflow.com/questions/16379973/goback-and-download-listener-in-webview-fragment
tried all kinda codes I found from there and no luck!
dfuse06 said:
lol!!! I have googled it. Looked on stackoverflow posted on stack
http://stackoverflow.com/questions/16379973/goback-and-download-listener-in-webview-fragment
tried all kinda codes I found from there and no luck!
Click to expand...
Click to collapse
Post your code (or the important parts of it) so that we can find your errors.
Having the same issue
dfuse06 said:
lol!!! I have googled it. Looked on stackoverflow posted on stack
tried all kinda codes I found from there and no luck!
Click to expand...
Click to collapse
I'm having the same issue. Did you find resolution? If so, please post it.

Android App Posting to HTTP

Alright so, this may get a bit confusing so feel free to ask me what the hell I'm talking about.
I am developing and app to run along side of a PHP web panel that is in development. I've been searching around for a way to hand logins on the app. The best method I could find that appears to suite our needs is to POST to HTTP. However while setting up the login file based on a tutorial I found, it doesn't seem to pull the data back properly. We are using a mysql database however we recently revamped the site and moved from mysql_query to PDO statements(not sure if that has anything to do with it).
Anyways what currently happens is you click login it checks the page and returns false all the time, unless the word "true" is echo'ed.
Here is my current code on the app side:
Code:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import android.app.Activity;
import android.os.Bundle;
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;
public class Login extends Activity implements OnClickListener{
Button ok,back,exit;
TextView result;
[user=439709]@override[/user]
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
ok = (Button)findViewById(R.id.button_login);
ok.setOnClickListener(this);
result = (TextView)findViewById(R.id.login_text);
}
public void postLoginData(){
new Thread(new Runnable(){
public void run(){
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("myurl");
try
{
EditText uname = (EditText)findViewById(R.id.usernamelogin);
String username = uname.getText().toString();
EditText pword = (EditText)findViewById(R.id.passwordlogin);
String password = pword.getText().toString();
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(3);
nameValuePairs.add(new BasicNameValuePair("submit", "login"));
nameValuePairs.add(new BasicNameValuePair("username", username));
nameValuePairs.add(new BasicNameValuePair("password", password));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
Log.w("TMCP", "Execute HTTP Post Request");
HttpResponse response = httpclient.execute(httppost);
String str = inputStreamToString(response.getEntity().getContent()).toString();
Log.w("TMCP", str);
if(str.toString().equalsIgnoreCase("true"))
{
Log.w("TMCP", "TRUE");
}
else
{
Log.w("TMCP", "FALSE");
}
} catch(ClientProtocolException e){
e.printStackTrace();
} catch(IOException e){
e.printStackTrace();
}
}
}).start();
}
private StringBuilder inputStreamToString(InputStream is) {
String line = "";
StringBuilder total = new StringBuilder();
// Wrap a BufferedReader around the InputStream
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
// Read response until the end
try {
while ((line = rd.readLine()) != null) {
total.append(line);
}
} catch (IOException e) {
e.printStackTrace();
}
// Return full string
return total;
}
[user=439709]@override[/user]
public void onClick(View view) {
if(view == ok){
postLoginData();
}
}
}
Is there another way I should go about tackling this project? Besides logins I'm going to need the app to pull results from the database to create Lists, and Various other functions.
Thanks in advance for the help.
JakeR
I believe you're on the right track - this is how I implemented client-server communications in my app.
For transferring more complex data, I would recommend using PHP to print JSON arrays containing the data. Your app can then simply parse it to extract the data. You'd essentially be making your own 'api'.
Finally, when debugging your PHP scripts, I'd recommend you check out the postman rest client - it's powerful and makes developing 100x faster. https://chrome.google.com/webstore/detail/postman-rest-client/fdmmgilgnpjigdojojpjoooidkmcomcm?hl=en
I hope that answered your question, please feel free to ask anything!
Sent from my LG-P500 using xda app-developers app
I have done exactly the same thing with my forum viewing app. You have to post all data required, also any hidden input for example. Are you sure you posted all inputs?
I agree with the response above to use JSON format to obtain data as it is extremely easy and fast to use.
Sent from my NexusHD2 using xda app-developers app
When you use JSON the gson library from Google is a great help.

camera app help..

Hello,
I am newbie to android programming.I am trying to make a simple app.The app window has 1 button and 1 ImageView.The button will capture the image and will set ImageView to it.So i wrote a little bit of the code and when I try to run it on emulator,after clicking the capture button I get an error saying application stopped.Please help me!
package com.example.file;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBar;
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.os.Build;
import android.widget.Button;
import android.widget.ImageView;
import java.io.InputStream;
public class MainActivity extends Activity {
Bitmap mImageBitmap;
Button Capture;
ImageView mImageView;
int actioncode=0;
Intent i;
@override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_main);
Capture=(Button)findViewById(R.id.c1);
Capture.setOnClickListener(new View.OnClickListener() {
@override
public void onClick(View view) {
dispatchTakePictureIntent(actioncode);
handleSmallCameraPhoto(i);
}
});
mImageView=(ImageView)findViewById(R.id.i);
}
private void dispatchTakePictureIntent(int actionCode) {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(takePictureIntent, actionCode);
}
private void handleSmallCameraPhoto(Intent intent) {
Bundle extras = intent.getExtras();
mImageBitmap = (Bitmap) extras.get("data");
mImageView.setImageBitmap(mImageBitmap);
}
}
Please use code-tags!!
Plz read your **LogCat**.
Regards
bhushan.crysis said:
Hello,
I am newbie to android programming.I am trying to make a simple app.The app window has 1 button and 1 ImageView.The button will capture the image and will set ImageView to it.So i wrote a little bit of the code and when I try to run it on emulator,after clicking the capture button I get an error saying application stopped.Please help me!
Click to expand...
Click to collapse
Looking at your code, you will get a NullPointerException on calling intent.getExtras() in the last method since you're calling it in the Button click. You should instead override the onActivityResult check request and Result code and call that method there
But in general, make sure to read This awesome guide on debugging, that way you can solve your problems yourself!

(Q) Load Custom system font from Extend TextView class.

Hello everyone.
i am trying to load a custom font from /system/fonts i use a custom extend TextView class
however i cant seem to let it load the font :/ i know i can load it through the assets but thats not what i want. i want it to load a custom ttf font from /system/fonts/***
because i would/will be using this Custom TextView class inside the frameworks.
Code:
package com.touchwizres.lifecompaniontext;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.graphics.Typeface;
import android.util.AttributeSet;
import android.widget.TextView;
public class LifeCompanionTextView extends TextView {
TextView profilename;
String name;
public LifeCompanionTextView(final Context context, AttributeSet attrs) {
super(context, attrs);
profilename = (TextView) findViewById(R.id.life_companion_tag);
SharedPreferences sharedPreferences = context.getSharedPreferences("LifeCompanionFile",Context.MODE_PRIVATE);
name = sharedPreferences.getString("companionName","Life Companion");
profilename.setText(name);
BroadcastReceiver mReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context c, Intent i) {
name = i.getStringExtra("NAME");
profilename.setText(name);
SharedPreferences sharedPreferences = context.getSharedPreferences("LifeCompanionFile",Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit(); //opens the editor
editor.putString("companionName", name); //true or false
editor.commit();
}
};
context.registerReceiver(mReceiver, new IntentFilter("lifecompanion.CHANGE_COMPANION"));
}
}
Here is my code.
if possible could someone help me ? i have tried some guides and couldnt seem to find a solution to this.
thanks
Best Regards Spacecaker.
SpaceCaker said:
Hello everyone.
i am trying to load a custom font from /system/fonts i use a custom extend TextView class
however i cant seem to let it load the font :/ i know i can load it through the assets but thats not what i want. i want it to load a custom ttf font from /system/fonts/***
because i would/will be using this Custom TextView class inside the frameworks.
Code:
package com.touchwizres.lifecompaniontext;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.graphics.Typeface;
import android.util.AttributeSet;
import android.widget.TextView;
public class LifeCompanionTextView extends TextView {
TextView profilename;
String name;
public LifeCompanionTextView(final Context context, AttributeSet attrs) {
super(context, attrs);
profilename = (TextView) findViewById(R.id.life_companion_tag);
SharedPreferences sharedPreferences = context.getSharedPreferences("LifeCompanionFile",Context.MODE_PRIVATE);
name = sharedPreferences.getString("companionName","Life Companion");
profilename.setText(name);
BroadcastReceiver mReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context c, Intent i) {
name = i.getStringExtra("NAME");
profilename.setText(name);
SharedPreferences sharedPreferences = context.getSharedPreferences("LifeCompanionFile",Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit(); //opens the editor
editor.putString("companionName", name); //true or false
editor.commit();
}
};
context.registerReceiver(mReceiver, new IntentFilter("lifecompanion.CHANGE_COMPANION"));
}
}
Here is my code.
if possible could someone help me ? i have tried some guides and couldnt seem to find a solution to this.
thanks
Best Regards Spacecaker.
Click to expand...
Click to collapse
i have fixed it.
Code:
package com.touchwizres.lifecompaniontext;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.graphics.Typeface;
import android.util.AttributeSet;
import android.widget.TextView;
public class LifeCompanionTextView extends TextView {
TextView profilename;
String name;
public LifeCompanionTextView(final Context context, AttributeSet attrs) {
super(context, attrs);
profilename = (TextView) findViewById(R.id.life_companion_tag);
SharedPreferences sharedPreferences = context.getSharedPreferences("LifeCompanionFile",Context.MODE_PRIVATE);
name = sharedPreferences.getString("companionName","Life Companion");
profilename.setText(name);
Typeface tf = Typeface.createFromFile("/system/fonts/Cooljazz.ttf");
profilename.setTypeface(tf);
BroadcastReceiver mReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context c, Intent i) {
name = i.getStringExtra("NAME");
profilename.setText(name);
SharedPreferences sharedPreferences = context.getSharedPreferences("LifeCompanionFile",Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit(); //opens the editor
editor.putString("companionName", name); //true or false
editor.commit();
}
};
context.registerReceiver(mReceiver, new IntentFilter("lifecompanion.CHANGE_COMPANION"));
}
}

Categories

Resources