Need Help..! I am working on Android Transliteration and I'm getting following 3 errors in my code.
1)GoogleAPI cannot be resolved
2)Translate cannot be resolved
3)Language cannot be resolved
I have properly imported all the required packages and also have added required external jar files. But unable to know where actually I'm going wrong..
Following is my code snippet-->
public class MainActivity extends Activity
{
EditText myInputText;
Button myTranslateButton;
TextView myOutputText;
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myInputText = (EditText)findViewById(R.id.inputText);
myTranslateButton = (Button)findViewById(R.id.translateButton);
myOutputText = (TextView)findViewById(R.id.outputText);
myTranslateButton.setOnClickListener(MyTranslateButtonOnClickListener);
}
private Button.OnClickListener MyTranslateButtonOnClickListener
= new Button.OnClickListener()
{
#Override
public void onClick(View v)
{
// TODO Auto-generated method stub
String InputString;
String OutputString = null;
InputString = myInputText.getText().toString();
try
{
GoogleAPI.setHttpReferrer("http:\\www.google.com");
GoogleAPI.setKey("API_KEY");
OutputString = Translate.DEFAULT.execute(InputString,Language.ENGLISH, Language.HINDI);
}
catch (Exception ex)
{
ex.printStackTrace();
OutputString = "Error";
}
Typeface customF = Typeface.createFromAsset(getAssets(), "akshar.ttf");
//final TextView textV = (TextView) findViewById(...);
myOutputText.setTypeface(customF);
myOutputText.setText(OutputString);
}
};
}
For your better understanding please have a look on following screenshots
Image-1 Packages Imported
Image-2 Code that Contains Error
Image-3 My Build Configuration
Please help.. Thanks...!!
Import these two:
import com.google.api.translate.Language;
import com.google.api.translate.Translate;
& I think it would be better if you use the translation as a separate method.Check this out.
Related
I'm trying to add a text file for a help page on my app but with the code I have it's just crashing the app when I select help from the options menu. I know it's to do with this code as when I comment it out it opens the help page fine.
The code is in my HelpActivity class:
public class HelpActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.help_page);
}
InputStream iFile = getResources().openRawResource(R.raw.gamehelp);
private String inputStreamToString(InputStream iFile) {
TextView helpText = (TextView) findViewById(R.id.tvHelpText);
String strFile = inputStreamToString(iFile);
helpText.setText(strFile);
return strFile;
}
}
Can anyone see any problem with how I'm trying to do this?
Thanks
Since you didn't include any error logs, I'm judging just from your code:
InputStream iFile = getResources().openRawResource(R.raw.gamehelp);
You are calling this in class body, but getResources() is not available here. What you should do is:
InputStream iFile;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.help_page);
iFile = getResources().openRawResource(R.raw.gamehelp);
}
I would like to use RTEditor in my app. but I have some errors in code. My question is what can I do with that? Instruction about RTEditor is here: https://github.com/1gravity/Android-RTEditor
and that's part of my code:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setTheme(R.style.RTE_BaseThemeDark);
setContentView(R.layout.activity_editor);
newRowEdit = (EditText) findViewById(R.id.editNote);
newRowEdit1 = (EditText) findViewById(R.id.rtEditText);
// create RTManager
RTApi rtApi = new RTApi(this, new RTProxyImpl(this), new RTMediaFactoryImpl(this, true));
RTManager rtManager = new RTManager(rtApi, savedInstanceState);
// register toolbar
ViewGroup toolbarContainer = (ViewGroup) findViewById(R.id.rte_toolbar_container);
RTToolbar rtToolbar = (RTToolbar) findViewById(R.id.rte_toolbar);
if (rtToolbar != null) {
rtManager.registerToolbar(toolbarContainer, rtToolbar);
}
// register editor & set text
RTEditText rtEditText = (RTEditText) findViewById(R.id.rtEditText);
rtManager.registerEditor(rtEditText, true);
rtEditText.setRichTextEditing(true, message);
String text = rtEditText.getText(RTFormat.HTML);
}
Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
mRTManager.onSaveInstanceState(outState);
}
#Override
public void onDestroy() {
super.onDestroy();
mRTManager.onDestroy(isFinishing());
}
The error is: cannot resolve symbol: message and cannot resolve symbol:mRTManager.
Can anyone help me please?
I can't see the whole code but it seems that both variables are not declared inside the corresponding methods. Make sure they are declared as class member variables
Replace mRTManager with rtManager, and make sure rtManager is declared outside onCreate method.
I want to create a connection through socket but I'm having trouble with the graphic of my App:
This is my activity:
public class Messaggi2 extends ActionBarActivity{
LinearLayout mLayout;
ScrollView scroll;
EditText scriviMessaggi;
Button invia;
Socket connessione;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.messaggi2);
mLayout = (LinearLayout) findViewById(R.id.LinearScrollLayout);
scroll = (ScrollView) findViewById(R.id.scrollView2);
scriviMessaggi = (EditText) findViewById(R.id.Scrivi);
invia = (Button) findViewById(R.id.Invia);
LavoraDietro asd = new LavoraDietro(connessione);
asd.execute();
}
private TextView createNewTextView(String text) {
final LinearLayout.LayoutParams lparams = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT); final TextView textView = new TextView(this);
textView.setLayoutParams(lparams);
textView.setText(text);
textView.setBackgroundResource(R.drawable.balloon_broadcast_incoming_pressed);
return textView;
}
private TextView createNewTextViewSent(String text) {
final LinearLayout.LayoutParams llparams = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
llparams.gravity = Gravity.RIGHT;
final TextView textViewSent = new TextView(this);
textViewSent.setLayoutParams(llparams);
textViewSent.setText(text);
textViewSent.setBackgroundResource(R.drawable.balloon_outgoing_normal);
return textViewSent;
}
public void AggiungiTextALlayout(String messaggio){
mLayout.addView(createNewTextView(messaggio));
aggiornaScroll();
}
public void AggiungiTextInviatoALlayout(String messaggio){
mLayout.addView(createNewTextViewSent(messaggio));
aggiornaScroll();
}
public void aggiornaScroll(){
scroll.post(new Runnable() {
#Override
public void run() {
scroll.fullScroll(View.FOCUS_DOWN);
}
});
}
}
This is my AsynTask class:
public class LavoraDietro extends AsyncTask<Void, Void, Socket> {
Socket connessione;
boolean vediSeDeviPartire;
Messaggi2 mess = new Messaggi2();
public LavoraDietro(Socket connessione){
this.connessione = connessione;
}
#Override
protected Socket doInBackground(Void... params){
try {
InetAddress local = InetAddress.getByName("192.168.1.71");
connessione = new Socket(local , 7000);
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
return null;
}catch(Exception e){
e.printStackTrace();
}
return connessione;
}
#Override
protected void onPostExecute(Socket result) {
super.onPostExecute(result);
if(result != null){
vediSeDeviPartire = true;
mess.AggiungiTextALlayout("Sono connesso al server");
mess.AggiungiTextALlayout("I canali sono aperi..");
}
else{
mess.AggiungiTextALlayout("ERRORE CONNESSIONE AL SERVER ");
}
}
}
Using this code when I start my app the connection is established and then it crashes. What I see on my Logcat is this Exception:
java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.res.Resources android.content.Context.getResources()' on a null object reference
So I tried to delete the content of my onPostExecute and everything works perfect. So the mistake is to try to call the method AggiungiTextAlLayout on my AsyncTask class.
Can someone help me with this? Can someone suggest me something? I'm new in this field so I know that this is a stupid thing but I need help.
Thanks guys in advance
EDITED WITH THE SOLUTION
Thanks to Ataulm I got the problem and I solved it I changed the costructor of my LavoraDietro class (unfortunatly I can't change the name of variables and classes in English. But next time I ll use english Name of course )
LavoraDietro Class
public class LavoraDietro extends AsyncTask<Void, Void, Socket> {
Socket connessione;
boolean vediSeDeviPartire;
Messaggi2 action;
public LavoraDietro(Socket connessione, Messaggi2 action){
this.connessione = connessione;
this.action = action;
}
#Override
protected Socket doInBackground(Void... params){
try {
InetAddress local = InetAddress.getByName("192.168.1.71");
connessione = new Socket(local , 7000);
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
return null;
}catch(Exception e){
e.printStackTrace();
}
return connessione;
}
#Override
protected void onPostExecute(Socket result) {
super.onPostExecute(result);
if(result != null){
vediSeDeviPartire = true;
action.AggiungiTextALlayout("Sono connesso al server");
action.AggiungiTextALlayout("I canali sono aperi..");
}
else{
action.AggiungiTextALlayout("ERRORE CONNESSIONE AL SERVER ");
}
}
}
And in the Messaggi2 class I changed the call of the constructor in this:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.messaggi2);
mLayout = (LinearLayout) findViewById(R.id.LinearScrollLayout);
scroll = (ScrollView) findViewById(R.id.scrollView2);
scriviMessaggi = (EditText) findViewById(R.id.Scrivi);
invia = (Button) findViewById(R.id.Invia);
LavoraDietro asd = new LavoraDietro(connessione, this);
asd.execute();
Your AsyncTask has a reference to mess which is an object of type Messaggi2.
Messaggi2 is a subclass of Activity. You attempt, inside your AsyncTask, to create a new instance of that class.
The Android system has no awareness of this object; it has called none of the life cycle methods, such as onCreate() where the activity's layout would typically be inflated. This means that none of your views are inflated nor even initialised.
When you call mess.AggiungiTextALlayout("Sono connesso al server");, mLayout is null.
The NPE you see may likely not even be this one.
TL;DR: don't instantiate your Activity objects like Java objects; use them as specified within the Android framework.
I suspect you have this Activity starting correctly somewhere. The mistake is that you've not associated that activity with your Asynctask. When you create LavoraDietro, you pass a reference to the Socket in the constructor; you can also pass a reference to your activity, and assign that to the mess field, instead of calling new Messaggi2(). I'm not advocating this structure. But that is the issue at hand.
A few general tips to help you avoid this in future / or spot it faster:
be consistent with your naming; it's difficult to read your code when you're switching between English and Italian.
it's equally difficult for others to read your code if you don't maintain follow Java conventions with class/method names.
When you're extending Activity, it's typical to append the word "Activity" after your class; in this example new Messaggi2Activity() would have been easier to spot.
Where you're able, pass a Class's dependencies as parameters in the constructor; don't rely on constructing these dependencies yourself inside that class. Once you do this, you can begin to draw lines around what your class is responsible for; the less it's responsible for, the harder it is for your class to mess up.
That problem is for put a variable with no "data", verify your variables
While I would like to make everything programatically whenever I can, and leave XML blank, that is not possible where I work (designers will not work with raw program code...)
So, to that extend, almost every one of my activity that I work with or built contains a large block of findViewById at the start somewhere.
This is especially painful if I had to create it from scratch and I am now allowed to programatically create an array of buttons and add it to the layout... Thankfully they will let me do that if it gets to 10+ elements and they are all the same type.
Is there a way to avoid this? Or a way to make it automatically cast it into what I am assigning it to? So I don't need to type Button mButton = (Button) findview...
If there is some way to automagically generate java instances of buttons and what nots from the XML given the layout that would be great (esp if the names were nice and autocompleteable).
Try to use Android annotations
AndroidAnnotations is an Open Source framework that speeds up Android development. It takes care of the plumbing, and lets you concentrate on what's really important. By simplifying your code, it facilitates its maintenance.
Here is a simple example of how your code can dramatically shrink, and become much easier to understand:
Before Android Annotations
public class BookmarksToClipboardActivity extends Activity {
BookmarkAdapter adapter;
ListView bookmarkList;
EditText search;
BookmarkApplication application;
Animation fadeIn;
ClipboardManager clipboardManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(FLAG_FULLSCREEN, FLAG_FULLSCREEN);
setContentView(R.layout.bookmarks);
bookmarkList = (ListView) findViewById(R.id.bookmarkList);
search = (EditText) findViewById(R.id.search);
application = (BookmarkApplication) getApplication();
fadeIn = AnimationUtils.loadAnimation(this, anim.fade_in);
clipboardManager = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
View updateBookmarksButton1 = findViewById(R.id.updateBookmarksButton1);
updateBookmarksButton1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
updateBookmarksClicked();
}
});
View updateBookmarksButton2 = findViewById(R.id.updateBookmarksButton2);
updateBookmarksButton2.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
updateBookmarksClicked();
}
});
bookmarkList.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView p, View v, int pos, long id) {
Bookmark selectedBookmark = (Bookmark) p.getAdapter().getItem(pos);
bookmarkListItemClicked(selectedBookmark);
}
});
initBookmarkList();
}
void initBookmarkList() {
adapter = new BookmarkAdapter(this);
bookmarkList.setAdapter(adapter);
}
void updateBookmarksClicked() {
UpdateBookmarksTask task = new UpdateBookmarksTask();
task.execute(search.getText().toString(), application.getUserId());
}
private static final String BOOKMARK_URL = //
"http://www.bookmarks.com/bookmarks/{userId}?search={search}";
class UpdateBookmarksTask extends AsyncTask {
#Override
protected Bookmarks doInBackground(String... params) {
String searchString = params[0];
String userId = params[1];
RestTemplate client = new RestTemplate();
HashMap args = new HashMap();
args.put("search", searchString);
args.put("userId", userId);
HttpHeaders httpHeaders = new HttpHeaders();
HttpEntity request = new HttpEntity(httpHeaders);
ResponseEntity response = client.exchange( //
BOOKMARK_URL, HttpMethod.GET, request, Bookmarks.class, args);
Bookmarks bookmarks = response.getBody();
return bookmarks;
}
#Override
protected void onPostExecute(Bookmarks result) {
adapter.updateBookmarks(result);
bookmarkList.startAnimation(fadeIn);
}
}
void bookmarkListItemClicked(Bookmark selectedBookmark) {
clipboardManager.setText(selectedBookmark.getUrl());
}
}
After:
#NoTitle
#Fullscreen
#EActivity(R.layout.bookmarks)
public class BookmarksToClipboardActivity extends Activity {
BookmarkAdapter adapter;
#ViewById
ListView bookmarkList;
#ViewById
EditText search;
#App
BookmarkApplication application;
#RestService
BookmarkClient restClient;
#AnimationRes
Animation fadeIn;
#SystemService
ClipboardManager clipboardManager;
#AfterViews
void initBookmarkList() {
adapter = new BookmarkAdapter(this);
bookmarkList.setAdapter(adapter);
}
#Click({R.id.updateBookmarksButton1, R.id.updateBookmarksButton2})
void updateBookmarksClicked() {
searchAsync(search.getText().toString(), application.getUserId());
}
#Background
void searchAsync(String searchString, String userId) {
Bookmarks bookmarks = restClient.getBookmarks(searchString, userId);
updateBookmarks(bookmarks);
}
#UiThread
void updateBookmarks(Bookmarks bookmarks) {
adapter.updateBookmarks(bookmarks);
bookmarkList.startAnimation(fadeIn);
}
#ItemClick
void bookmarkListItemClicked(Bookmark selectedBookmark) {
clipboardManager.setText(selectedBookmark.getUrl());
}
}
I'm a rookie programmer, and I'm trying to setup a function to pass a TextView or an array of TextViews to a function, so it can be called at various points in the activity.
public class ScoreboardActivity extends Activity {
...
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_scoreboard);
...
final TextView STATVIEW1A = (TextView) findViewById(R.id.place_stat1a); //Team 1
final TextView STATVIEW1B = (TextView) findViewById(R.id.place_stat1b);
final TextView STATVIEW1C = (TextView) findViewById(R.id.place_stat1c);
final TextView STATVIEW1D = (TextView) findViewById(R.id.place_stat1d);
final TextView STATVIEW2A = (TextView) findViewById(R.id.place_stat2a); //Team 2
final TextView STATVIEW2B = (TextView) findViewById(R.id.place_stat2b);
final TextView STATVIEW2C = (TextView) findViewById(R.id.place_stat2c);
final TextView STATVIEW2D = (TextView) findViewById(R.id.place_stat2d);
//final TextView[] STATVIEW = {STATVIEW1A,STATVIEW1B,STATVIEW1C,STATVIEW1D,
// STATVIEW2A,STATVIEW2B,STATVIEW2C,STATVIEW2D};
...
postStats();
... or
postStats(STATVIEW[]);
I want to have a routine to post the (8) TextViews on my activity_scoreobard layout. I have tried just referencing the STATVIEW1A in the function:
public void postStats () {
STATVIEW1AX.setText("#dumps: " + Integer.toString(DUMP1[GAME_NO]));
}
I have also tried referencing each of the TextViews from passing an array of TextViews in the function:
public void postStats (TextView[] VIEWSTAT) {
VIEWSTAT[6].setText("#dumps: "+ Integer.toString(DUMP2[GAME_NO]));
}
While both don't show errors in Eclipse, the program does not like either situation.
Generally it's not a good idea to pass them to function...
but if you want you can try something like this...
TextView[] STATVIEW = new TextView[SIZE];
then to initialize
STATVIEW[0] = (TextView) findViewById(R.id.place_stat1a); //Team 1
STATVIEW[1] = (TextView) findViewById(R.id.place_stat1b);
......
then pass your Array
postStats(STATVIEW);
Alternative would be
create a method and pass the values and set them to TextViews
something like this
public void fillData(String[] data)
{
for (int i=0;i<STATVIEW.length;i++)
{
STATVIEW[i].setText(data[i]);
}
}
It is better to use an array of WeakReference objects to hold the references to your Text views and initialize this array in the OnCreate method of your activity, using this method everytime that system destroy your activity the references to the items can be garbage collected automatically and you won't cause memory leaks. As far as i know the standard way for holding a reference to an ephemeral object like the activity itself or a views on it is to use WeakReference objects.
For understanding what a WeakReference is read the following article on Wikipedia:
http://en.wikipedia.org/wiki/Weak_reference
Also read this page:
https://developer.android.com/reference/java/lang/ref/WeakReference.html
Instead of Overloading postStats() function you can try using postStats(TextView... VIEWSTAT). In this function you can check the number of arguments by VIEWSTAT.length.
ArrayList<TextView> tmpArrayList = new ArrayList<TextView>();
for(int y=0; y<10; y++)
{
tmpArrayList.add(getTextView(txtBoxCount++));
}
this.postStats(tmpArrayList);
private TextView getTextView(int i)
{
int id=0;
try {
id = R.id.class.getField("textview" + i).getInt(0);
}
catch (IllegalArgumentException e) {
e.printStackTrace();
}
catch (SecurityException e) {
e.printStackTrace();
}
catch(IllegalAccessException e) {
e.printStackTrace();
}
catch (NoSuchFieldException e) {
e.printStackTrace();
}
textview = (TextView)findViewById(id);
textview.setTag("0");
return textview;
}
public void postStats (ArrayList<TextView> viewstat) {
//do some work here
}