Value of EditText not appearing in my logs - java

I an new to Android. I have the following code for a Twitter Client search:
package com.michaelnares.twitterclient;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.*;
import twitter4j.*;
import twitter4j.conf.ConfigurationBuilder;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
/**
* Created by michael on 01/05/2014.
*/
public class SearchActivity extends Activity {
EditText queryEditText = null;
String queryText = null;
private Context context = this;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.search);
queryEditText = (EditText) findViewById(R.id.queryEditText);
queryText = (queryEditText.getText().toString());
final Context context = this;
Button queryButton = (Button) findViewById(R.id.queryButton);
queryButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Log.i(LogConstants.LOG, "Text value is " + queryText);
if (queryText.equals(null)) {
Toast.makeText(context, "You did not enter a query", Toast.LENGTH_SHORT).show();
} else {
new SearchAsyncTask().execute();
}
}
});
} // ends onCreate()
private class SearchAsyncTask extends AsyncTask<String, String, ArrayList<String>>
{
private ProgressDialog dialog = new ProgressDialog(SearchActivity.this);
private ArrayList<String> searchResults;
#Override
protected void onPreExecute()
{
super.onPreExecute();
dialog.setMessage("Getting data...");
dialog.setIndeterminate(false);
dialog.setCancelable(true);
dialog.show();
}
#Override
protected ArrayList<String> doInBackground(String... strings) {
APIClient client = new APIClient();
searchResults = client.getQueryResults(queryText);
return searchResults;
}
#Override
protected void onPostExecute(ArrayList<String> results)
{
dialog.dismiss();
results.addAll(searchResults);
if (searchResults == null)
{
Log.w(LogConstants.LOG, "searchResults is null");
}
final ListView searchListView = (ListView) findViewById(R.id.searchListView);
final ArrayAdapter adapter = new ArrayAdapter(context, android.R.layout.simple_list_item_1, results);
adapter.notifyDataSetChanged();
searchListView.setAdapter(adapter);
}
}
} //ends class
The issue is, I have tried to log the results of the EditText, however I never see that in the logs. What is going on here? I can't work out why I'm never seeing "Text value is " + queryText in the logs.

The problem is you initialize the String value queryText in the event of the screen being created (onCreate()) and not when you actually type in values (after screen creation & dynamic activity on the screen).
This is why the following would work
#Override
public void onClick(View view) {
queryText = (queryEditText.getText().toString());
Log.i(LogConstants.LOG, "Text value is " + queryText);
if (queryText.equals("")) {
Toast.makeText(context, "You did not enter a query", Toast.LENGTH_SHORT).show();
} else {
new SearchAsyncTask().execute();
}
}

Change
Log.i(LogConstants.LOG, "Text value is " + queryText);
to
Log.i(LogConstants.LOG, "Text value is " + queryEditText.getText().toString());

Move
queryText = (queryEditText.getText().toString());
inside the onClick
queryButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
queryText = (queryEditText.getText().toString());
Log.i(LogConstants.LOG, "Text value is " + queryText);
if ("".equals(queryText)) {
Toast.makeText(context, "You did not enter a query", Toast.LENGTH_SHORT).show();
} else {
new SearchAsyncTask().execute();
}
}
});

Related

How stop text to speech in Base adapter

I have a custom ListView with BaseAdapter. In this custom ListView when a user clicks on any particular text, it speaks the text but the problem is that when any user clicks on the back button how to stop this text from the BaseAdapter. I know how to stop from an Activity but don't know how to stop from BaseAdapter when the user presses back button. Here is my code:
package bible.swordof.God;
import android.app.Activity;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Color;
import android.os.Vibrator;
import android.speech.tts.TextToSpeech;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ToggleButton;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.zip.Inflater;
import es.dmoral.toasty.Toasty;
import petrov.kristiyan.colorpicker.ColorPicker;
import static android.content.Context.MODE_PRIVATE;
public class BaseAdopter extends BaseAdapter implements TextToSpeech.OnInitListener{
public BaseAdopter(Context context, List<String> versenumber, List<String> verseid, List<String> verselist, List<String> refernce) {
this.context = context;
this.versenumber = versenumber;
this.verseid = verseid;
this.verselist = verselist;
this.refernce = refernce;
}
ALLVERSE allverse;
ArrayList<String> colors;
private Context context;
private List<String> versenumber;
private List<String>verseid;
private List<String> verselist;
private List<String> refernce;
TextToSpeech textToSpeech;
private DatabaseHelper mDBHelper;
private SQLiteDatabase mDb;
#Override
public int getCount() {
return versenumber.size();
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater)context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
View view=inflater.inflate(R.layout.versedisplayrow,parent,false);
textToSpeech = new TextToSpeech(context, this);
final TextView verseno;
final TextView verselistview;
ImageView share;
ToggleButton addfavoruite;
ImageView speakverse;
final LinearLayout linearLayout;
verseno=(TextView)view.findViewById(R.id.versenumber);
verseno.setText(versenumber.get(position));
verselistview=(TextView)view.findViewById(R.id.verse);
verselistview.setText(verselist.get(position));
addfavoruite=(ToggleButton)view.findViewById(R.id.adbookmark);
linearLayout=(LinearLayout)view.findViewById(R.id.layout);
share=(ImageView)view.findViewById(R.id.share);
speakverse=(ImageView)view.findViewById(R.id.speak);
if(DefaultSettings.nightmode(context)){
linearLayout.setBackgroundColor(Color.parseColor("#363437"));
verselistview.setTextColor(Color.parseColor("#ffffff"));
verseno.setTextColor(Color.parseColor("#ffffff"));
}
speakverse.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
singleverse(verselist.get(position).toString());
}
});
int a=position+1;
colors=new ArrayList<>();
colors.add("#e0e0eb");
colors.add("#ccffff");
colors.add("#ffe6ff");
colors.add("#ffffcc");
colors.add("#ccffcc");
colors.add("#e6f2ff");
SharedPreferences sharedPreferences=context.getSharedPreferences("DATA",MODE_PRIVATE);
int getverse=sharedPreferences.getInt("versenumber",1);
if(a==getverse){
if(DefaultSettings.highlight(context)){
DefaultSettings.color(context);
linearLayout.setBackgroundColor(DefaultSettings.colorpicked);
}
}
if(Checkisfavourite("favourite","id",verseid.get(position)))
{
if(verseid.get(position).equals(verseid.get(position))){
addfavoruite.setChecked(true);
}else {
addfavoruite.setChecked(false);
}
}
addfavoruite.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if(isChecked){
mDBHelper = new DatabaseHelper(context);
mDb = mDBHelper.getWritableDatabase();
ContentValues contentValues=new ContentValues();
contentValues.put("id",verseid.get(position));
contentValues.put("bookname",refernce.get(position));
contentValues.put("versenumber",versenumber.get(position));
contentValues.put("verse",verselist.get(position));
long check=mDb.insert("favourite",null,contentValues);
Toasty.success(context, "Added in favouite", Toast.LENGTH_SHORT, true).show();
}
else {
mDBHelper = new DatabaseHelper(context);
mDb = mDBHelper.getWritableDatabase();
long delete= mDb.delete("favourite","id=?",new String[]{verseid.get(position)});
Toasty.error(context, "Remove in favouite", Toast.LENGTH_SHORT, true).show();
}
}
});
share.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toasty.info(context, "Sharing a verse.", Toast.LENGTH_SHORT, true).show();
Intent sendIntent = new Intent();
sendIntent.setAction(Intent.ACTION_SEND);
sendIntent.putExtra(Intent.EXTRA_TEXT, refernce.get(position) + ":" + versenumber.get(position) + '\n' + verselist.get(position) +
+'\n' +'\n' +'\n' +"https://play.google.com/store/apps/details?id=bible.swordof.God");
sendIntent.setType("text/plain");
context.startActivity(sendIntent);
}
});
/* linearLayout.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
//Toasty.success(activity, "PICK COLOR", Toast.LENGTH_SHORT, true).show();
Vibrator vibe = (Vibrator)context.getSystemService(Context.VIBRATOR_SERVICE);
vibe.vibrate(100);
mDBHelper = new DatabaseHelper(context);
mDb = mDBHelper.getWritableDatabase();
ContentValues contentValues=new ContentValues();
contentValues.put("verseid",colors.get(position));
final long check=mDb.insert("highlight",null,contentValues);
//id get
//postion
//Toast.makeText(activity, ""+getItemId(position), Toast.LENGTH_SHORT).show();
ColorPicker colorPicker = new ColorPicker(context);
colorPicker.setColors(colors).setColumns(4).setTitle("HIGHLIGHT VERSE").setRoundColorButton(true).setOnChooseColorListener(new ColorPicker.OnChooseColorListener() {
#Override
public void onChooseColor(int position, int color) {
linearLayout.setBackgroundColor(Color.parseColor(colors.get(position)));
}
#Override
public void onCancel() {
}
}).show();
return false;
}
});
*/
return view;
}
public boolean Checkisfavourite(String TableName, String dbfield, String fieldValue) {
mDBHelper = new DatabaseHelper(context);
mDb = mDBHelper.getReadableDatabase();
String Query = "Select * from " + TableName + " where " + dbfield + " = " + fieldValue;
Cursor cursor = mDb.rawQuery(Query, null);
if(cursor.getCount() <= 0){
cursor.close();
// Toast.makeText(activity, "false", Toast.LENGTH_SHORT).show();
return false;
}else {
// Toast.makeText(activity, "TRUE", Toast.LENGTH_SHORT).show();
}
cursor.close();
return true;
}
public boolean colorcheck(String TableName, String dbfield, String fieldValue) {
mDBHelper = new DatabaseHelper(context);
mDb = mDBHelper.getReadableDatabase();
String Query = "Select * from " + TableName + " where " + dbfield + " = " + fieldValue;
Cursor cursor = mDb.rawQuery(Query, null);
if(cursor.getCount() <= 0){
cursor.close();
// Toast.makeText(activity, "false", Toast.LENGTH_SHORT).show();
return false;
}else {
// Toast.makeText(activity, "TRUE", Toast.LENGTH_SHORT).show();
}
cursor.close();
return true;
}
#Override
public void onInit(int status) {
if (status == TextToSpeech.SUCCESS) {
int result = textToSpeech.setLanguage(Locale.US);
// tts.setPitch(5); // set pitch level
// tts.setSpeechRate(2); // set speech speed rate
if (result == TextToSpeech.LANG_MISSING_DATA
|| result == TextToSpeech.LANG_NOT_SUPPORTED) {
Log.e("TTS", "Language is not supported");
} else {
}
} else {
Log.e("TTS", "Initilization Failed");
}
}
private void singleverse(String text) {
DefaultSettings.speed(context);
textToSpeech.setPitch(DefaultSettings.pitchvalue);
textToSpeech.setSpeechRate(DefaultSettings.speedvalue);
textToSpeech.speak(text, TextToSpeech.QUEUE_FLUSH, null);
}
public void stop(){
if (textToSpeech != null) {
textToSpeech.stop();
textToSpeech.shutdown();
}
}
}
The main problem is that your TextToSpeech object belongs to your BaseAdapter when it should belong to the parent activity.
Instead of housing it in the adapter and calling speak on it every time the user clicks an item, I would instead house it in the parent activity and use an "interface callback" that sends a message to the parent when the user clicks an item, sending back the string to speak. This callback relationship works the exact same way as the TextToSpeech.OnInitListener callback that you're already using.
Once the TTS belongs to the parent activity, you can use the activity lifecycle functions to control the shutdown of the TTS like normal.
If you study and understand the following, you should be able to merge it into your code and get a working solution:
Make these changes to your custom BaseAdapter:
// Remove the TextToSpeech object from this class.
public class MyBaseAdapter {
// add this interface definition to your adapter
public interface SpeechClickSubscriber {
void stringNeedsToBeSpoken(String verse);
}
// add this property (the subscriber)
private SpeechClickSubscriber speechClickSubscriber;
// *add* this functionality to your adapter's existing constructor
MyBaseAdapter(SpeechClickSubscriber parent) {
speechClickSubscriber = parent;
}
//...
// change this section of code in your getView() method
speakverse.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick (View v){
// change this...
// singleverse(verselist.get(position).toString());
// to this:
speechClickSubscriber.stringNeedsToBeSpoken(verselist.get(position).toString());
}
});
// ...
}
Make these changes to your MainActivity (or whatever your parent activity is):
// add the SpeechClickSubscriber implementation
public class MainActivity extends AppCompatActivity implements MyBaseAdapter.SpeechClickSubscriber, TextToSpeech.OnInitListener {
MyBaseAdapter adapter;
TextToSpeech textToSpeech;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// using app context is better and less error prone.
textToSpeech = new TextToSpeech(getApplicationContext(), this);
}
// *add* this method to this activity (this is the answer to your question)
#Override
protected void onStop() {
super.onStop();
stopTTS();
}
// use this method as your "onStart()" method...
// this will help prevent any user input processing until the tts is initialized.
private void start_Activity_Because_TTS_Has_Initialized() {
adapter = new MyBaseAdapter(this);
}
// *MOVE* this method from your base adapter to this (parent) activity:
#Override
public void onInit(int status) {
if (status == TextToSpeech.SUCCESS) {
int result = textToSpeech.setLanguage(Locale.US);
// tts.setPitch(5); // set pitch level
// tts.setSpeechRate(2); // set speech speed rate
if (result == TextToSpeech.LANG_MISSING_DATA
|| result == TextToSpeech.LANG_NOT_SUPPORTED) {
Log.e("TTS", "Language is not supported");
} else {
}
} else {
Log.e("TTS", "Initilization Failed");
}
}
// *move* and *rename* this method from your adapter to the parent activity:
// from:
/*
private void singleverse(String text) {
DefaultSettings.speed(context);
textToSpeech.setPitch(DefaultSettings.pitchvalue);
textToSpeech.setSpeechRate(DefaultSettings.speedvalue);
textToSpeech.speak(text, TextToSpeech.QUEUE_FLUSH, null);
} */
// to:
#Override
public void stringNeedsToBeSpoken(String verse) {
Log.i("XXX","stringNeedsToBeSpoken() was called because the user clicked an item.");
Log.i("XXX","This method is being called because this activity subscribes to the callback we created and added to our base adapter.");
//DefaultSettings.speed(context); // <----------------- I don't know what this does.
// I'm assuming that DefaultSettings is a static class you have made.
textToSpeech.setPitch(DefaultSettings.pitchvalue);
textToSpeech.setSpeechRate(DefaultSettings.speedvalue);
textToSpeech.speak(verse, TextToSpeech.QUEUE_FLUSH, null);
}
public void stopTTS(){
if (textToSpeech != null) {
textToSpeech.stop();
textToSpeech.shutdown();
}
}
}

Why do I get an "unreachable code" and "variable not initialized" compilation error?

Hi I am New to java and trying to develop an already existing Anti-ragging application to support newer api like lollipop from gingerbread. I have decompiled the apk and extracted the source code and built it in Gradle system.
Although the source code is correct,I am getting 3 errors in java code...not been able to figure out from a week.
The app contains 4 screens. The main screen is with a send button to send message, the second settings screen with two buttons to set message which we want to send and set contacts whom we want to send the message... the other two screens are the custom dialog layouts of the Set Meaasge & contact.
No errors in this main Java file just giving it for a reference
MainActivity.java:
package com.eminem.sharath.antiragging;
import android.content.Intent;
import android.content.SharedPreferences;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.telephony.SmsManager;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageButton;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
String[] arrr1;
private ImageButton ib1;
private double latitude;
private LocationManager lm;
private double longitude;
private SharedPreferences sp;
private SharedPreferences sp1;
protected void onCreate(Bundle paramBundle) {
super.onCreate(paramBundle);
setContentView(R.layout.activity_main);
ActionBar actionBar = getSupportActionBar();
actionBar.setLogo(R.mipmap.ic_launcher);
actionBar.setDisplayShowHomeEnabled(true);
actionBar.setDisplayUseLogoEnabled(true);
this.ib1 = (ImageButton)findViewById(R.id.imageButton1);
this.lm = (LocationManager)getSystemService(LOCATION_SERVICE);
this.ib1.setOnClickListener(new View.OnClickListener() {
public void onClick(View paramAnonymousView) {
MainActivity.this.sp = MainActivity.this.getSharedPreferences("demo", 1);
final String str1 = MainActivity.this.sp.getString("aaa", "");
MainActivity.this.sp1 = MainActivity.this.getSharedPreferences("sdat", 1);
String str2 = MainActivity.this.sp1.getString("snum", "");
MainActivity.this.arrr1 = str2.split(",");
Toast.makeText(MainActivity.this.getApplicationContext(), str2 + str1, Toast.LENGTH_SHORT).show();
System.out.println("LLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLL" + str2 + str1);
MainActivity.this.lm.requestLocationUpdates("gps", 1000L, 5.0F, new LocationListener() {
public void onLocationChanged(Location paramAnonymous2Location) {
Location localLocation = MainActivity.this.lm.getLastKnownLocation("gps");
MainActivity.this.latitude = localLocation.getLatitude();
MainActivity.this.longitude = localLocation.getLongitude();
Toast.makeText(MainActivity.this.getApplicationContext(), "Latitude:" + MainActivity.this.latitude + "\n" + "Longitude:" + MainActivity.this.longitude, Toast.LENGTH_SHORT).show();
String str = "http://maps.google.com/maps?=" + MainActivity.this.latitude + "," + MainActivity.this.longitude;
for (int i = 0; ; i++) {
if (i >= MainActivity.this.arrr1.length) {
return;
}
System.out.println(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>" + MainActivity.this.arrr1);
SmsManager.getDefault().sendTextMessage(MainActivity.this.arrr1[i], null, str1 + " Come at this location" + str, null, null);
}
}
public void onProviderDisabled(String paramAnonymous2String) {
}
public void onProviderEnabled(String paramAnonymous2String) {
}
public void onStatusChanged(String paramAnonymous2String, int paramAnonymous2Int, Bundle paramAnonymous2Bundle) {
}
});
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
startActivity(new Intent(getApplicationContext(), Settingss.class));
return super.onOptionsItemSelected(item);
}
}
The three errors are in this settings file...i have commented the error name beside the error for reference.
Settings.java:
package com.eminem.sharath.antiragging;
import android.app.Dialog;
import android.content.ContentResolver;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.database.Cursor;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.provider.ContactsContract.CommonDataKinds.Phone;
import android.support.v7.app.AppCompatActivity;
import android.text.Editable;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.MultiAutoCompleteTextView;
import android.widget.MultiAutoCompleteTextView.CommaTokenizer;
import android.widget.Toast;
import java.io.PrintStream;
import java.util.ArrayList;
public class Settingss extends AppCompatActivity
{
private ArrayList<String> alist = new ArrayList();
private Button b1;
private Button b2;
SharedPreferences.Editor ed;
private String setnum = "";
SharedPreferences sp;
protected void onCreate(Bundle paramBundle) {
super.onCreate(paramBundle);
setContentView(R.layout.contact);
this.b1 = ((Button)findViewById(R.id.button1));
this.b2 = ((Button)findViewById(R.id.button2));
this.b1.setOnClickListener(new View.OnClickListener()
{
public void onClick(View paramAnonymousView)
{
Settingss.this.showDialog(1);
}
});
this.b2.setOnClickListener(new View.OnClickListener()
{
public void onClick(View paramAnonymousView)
{
Settingss.this.showDialog(2);
}
});
}
protected Dialog onCreateDialog(int paramInt) {
if (paramInt == 1) {
final Dialog localDialog1 = new Dialog(this);
localDialog1.setContentView(R.layout.tosetmessage);
localDialog1.setTitle("Set Message");
final EditText localEditText = (EditText)findViewById(R.id.editText1);
Button localButton1 = (Button)findViewById(R.id.button1);
Button localbutton2 = ((Button) findViewById(R.id.button2));
localbutton2.setOnClickListener(new View.OnClickListener() {
public void onClick(View paramAnonymousView) {
Settingss.this.sp = Settingss.this.getSharedPreferences("demo", 2);
Settingss.this.ed = Settingss.this.sp.edit();
Settingss.this.ed.putString("aaa", localEditText.getText().toString());
Settingss.this.ed.commit();
localDialog1.dismiss();
}
});
localButton1.setOnClickListener(new View.OnClickListener()
{
public void onClick(View paramAnonymousView)
{
localDialog1.dismiss();
}
});
localDialog1.show();
}
while(true)
{
return super.onCreateDialog(paramInt);
/*Error: unreachale statement*/ if (paramInt == 2)
{
final Dialog localDialog2 = new Dialog(this);
localDialog2.setContentView(R.layout.multiautotext);
localDialog2.setTitle("Set Contacts");
final MultiAutoCompleteTextView localMultiAutoCompleteTextView = (MultiAutoCompleteTextView)localDialog2.findViewById(R.id.multiAutoCompleteTextView1);
Button localButton2 = (Button)localDialog2.findViewById(R.id.button1);
Button localButton3 = (Button)localDialog2.findViewById(R.id.button2);
Cursor localCursor = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null, null, "display_name ASC");
if (localCursor.moveToFirst())
{
do
{
String str1 = localCursor.getString(localCursor.getColumnIndex("display_name"));
String str2 = localCursor.getString(localCursor.getColumnIndex("data1"));
String str3 = str1 + "%" + str2;
this.alist.add(str3);
} while (localCursor.moveToNext());
ArrayAdapter localArrayAdapter = new ArrayAdapter(this, R.layout.simple_list_item, this.alist);
localMultiAutoCompleteTextView.setTokenizer(new MultiAutoCompleteTextView.CommaTokenizer());
localMultiAutoCompleteTextView.setAdapter(localArrayAdapter);
}
localButton2.setOnClickListener(new View.OnClickListener()
{
public void onClick(View paramAnonymousView)
{
String[] arrayOfString = localMultiAutoCompleteTextView.getText().toString().split(",");
int i = 0;
if (i >= arrayOfString.length)
{
System.out.println("************************" + Settingss.this.setnum);
Toast.makeText(Settingss.this.getApplicationContext(), Settingss.this.setnum, Toast.LENGTH_SHORT).show();
Settingss.this.sp = Settingss.this.getSharedPreferences("sdat", 2);
Settingss.this.ed = Settingss.this.sp.edit();
Settingss.this.ed.putString("snum", Settingss.this.setnum);
Settingss.this.ed.commit();
Settingss.this.setnum = "";
Settingss.this.finish();
return;
}
String str2;
if (arrayOfString[i].contains("%"))
str2 = arrayOfString[i].split("%")[1];
String str1;
for (Settingss.this.setnum = (Settingss.this.setnum + /*Error: Variable Str2 might not have been initialized*/ str2 + ",");; Settingss.this.setnum = (Settingss.this.setnum + str1 + ","))
{
i++;
break;
/*Error: unreachale statement*/ str1 = arrayOfString[i];
}
}
});
localButton3.setOnClickListener(new View.OnClickListener()
{
public void onClick(View paramAnonymousView)
{
localDialog2.dismiss();
}
});
localDialog2.show();
}
}
}
}
Please help me debug the application.
I have no intention to take any credits for the application because as I haven't developed it...just want to play with the user interface and give it a taste of new api.
The return statement will cause the onCreateDialog method to return and any subsequent lines will not be executed. That's why you get the unreachable code error message. Similarly, the break statement will cause the for loop to end. Any subsequent lines will not be executed.
Finally, you get a /*Error: Variable Str2 might not have been initialized*/ error because all local variables must be initialized before they can be used for the first time.
For /*Error: Variable Str2 might not have been initialized*/:
Change String str2; to String str2 = "";
As for the other two errors, you have a return; and break; before those lines.
Any statements after a unconditional return and break will be unreachable, i.e. there is no way that the code there (subsequent lines) will execute.

Android Null Pointer Exception for onclick listener

The following code is giving me null pointer exception even though I can't find anything wrong with the code. Tried commenting it out and it seems to be working. But still not able to find out what is wrong with the code? tried my own trouble shooting of commenting out the code and such and right now the code below is giving me nullpointer exception
Log Cat
12-19 05:49:14.833: E/AndroidRuntime(3392): Caused by:
java.lang.NullPointerException: Attempt to invoke virtual method 'void
android.widget.Button.setOnClickListener(android.view.View$OnClickListener)'
on a null object reference 12-19 05:49:14.833: E/AndroidRuntime(3392):
at
com.techiequickie.bharath.boadraf.newBet_activity.onCreate(newBet_activity.java:80)
Code:
package com.techiequickie.bhr.boadraf;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.Gravity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.SeekBar;
import android.widget.Toast;
import org.json.JSONException;
import org.json.JSONObject;
import databasehandler.DatabaseHandler;
import databasehandler.UserFunctions;
/**
* Created by YP on 17-Nov-14.
*/
public class newBet_activity extends ActionBarActivity
{
EditText inputBetname, inputBetbrief, inputBetdescription;
SeekBar valueSeekbar; //= null;
Button placeBet;
// JSON Response node names
private static String KEY_SUCCESS = "success";
#SuppressWarnings("unused")
private static String KEY_ERROR = "error";
#SuppressWarnings("unused")
private static String KEY_ERROR_MSG = "error_msg";
//private static String KEY_UID = "uid";
private static String KEY_BETNAME = "bet_name";
private static String KEY_BETBRIEF = "bet_brief";
private static String KEY_BETDESCRIPTION = "bet_description";
private static String KEY_BETVALUE = "bet_value";
// private static String KEY_CREATED_AT = "created_at";
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.newbet);
// Importing all assets like buttons, text fields
inputBetname = (EditText) findViewById(R.id.betName_et);
inputBetbrief = (EditText) findViewById(R.id.betBriefDescription_et);
inputBetdescription = (EditText) findViewById(R.id.betDescription_et);
placeBet = (Button) findViewById(R.id.btn_newbet);
//valueSeekbar = (SeekBar) findViewById(R.id.betValue_bar);
/*
valueSeekbar.setOnSeekBarChangeListener
(
new SeekBar.OnSeekBarChangeListener()
{
int progressChanged = 0;
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
progressChanged = progress;
}
public void onStartTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
public void onStopTrackingTouch(SeekBar seekBar) {
Toast.makeText(newBet_activity.this, "seek bar progress:" + progressChanged, Toast.LENGTH_SHORT).show();
}
}
);*/
placeBet.setOnClickListener(new View.OnClickListener()
{
public void onClick(View view)
{
String betname = inputBetname.getText().toString();
String betBrief = inputBetbrief.getText().toString();
String betDescription = inputBetdescription.getText().toString();
//StringBuilder betValue = ((toString()) valueSeekbar.getProgress());
//new BetRegisterTask().execute(betname,betBrief,betDescription);
}
}
);
}
/*
class BetRegisterTask extends AsyncTask<String, Void, String>
{
#Override
protected String doInBackground(String... params)
{
UserFunctions userFunction = new UserFunctions();
JSONObject json = userFunction.createBet(params[0], params[1], params[2]);
// check for login response
try
{
if (json.getString(KEY_SUCCESS) != null)
{
String res = json.getString(KEY_SUCCESS);
if (Integer.parseInt(res) == 1)
{
// user successfully registred
// Store user details in SQLite Database
DatabaseHandler db = new DatabaseHandler(getApplicationContext());
JSONObject json_user = json.optJSONObject("user");
// Clear all previous data in database
userFunction.logoutUser(getApplicationContext());
db.newBet(json_user.getString(KEY_BETNAME), json_user.getString(KEY_BETBRIEF), json.getString(KEY_BETDESCRIPTION));
return "1";
}
}
} catch (JSONException e)
{
e.printStackTrace();
}
return "0";
}
#Override
protected void onPostExecute(String s)
{
super.onPostExecute(s);
if (s.equals("1"))
{
// Launch Dashboard Screen
Intent dashboard = new Intent(getApplicationContext(), Loginactivity.class);
// Close all views before launching Dashboard
dashboard.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(dashboard);
// Close Registration Screen
finish();
showToastforSucessfulBetCreation();
}
else
{
// Error in registration
//registerErrorMsg.setText("Error occurred in registration");
showToastforUnsucessfulBetCreation();
}
}
}*/
public void showToastforSucessfulBetCreation() {
Toast toast = Toast.makeText(this, "Registration Sucessfull", Toast.LENGTH_LONG);
toast.setGravity(Gravity.BOTTOM, 0, 30);
toast.show();
}
public void showToastforUnsucessfulBetCreation() {
Toast toast = Toast.makeText(this, "Registration UnSucessfull", Toast.LENGTH_LONG);
toast.setGravity(Gravity.BOTTOM, 0, 30);
toast.show();
}
}
placeBet is not yet initialized that's why it is giving null pointer exception
check the following line
palceBet=findViewId(R.id.btn_newbet);
It seems that you did not create Button with id btn_newbet in the .xml file.
so to find if you define this button in xml file or not you should take your cursor over btn_newbet in
placeBet = (Button) findViewById(R.id.btn_newbet);
and if onclicking ,it will redirect to correct xml .

Need to access method for 1 java class by another

I am trying to access a method from a java class by a another java class. I have created the object of the class and import the class into my java class but i am not able to access it my code.
package com.example.musicplayer;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import android.R.string;
import android.app.ListActivity;
import android.content.Intent;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.os.Bundle;
import android.provider.MediaStore.Audio.Playlists;
import android.test.suitebuilder.TestSuiteBuilder.FailedToCreateTests;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends ListActivity {
public static final String MEDIA_PATH = new String("/sdcard/");
private List<String> songs = new ArrayList<String>();
public MediaPlayer mp = new MediaPlayer();
private int currentPosition = 0;
public MediaPlayer getmp(){
return mp;
}
public void setmp(MediaPlayer mp){
this.mp = mp;
}
#Override
protected void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.activity_main);
updateSongList();
}
private void updateSongList() {
// TODO Auto-generated method stub
File home = new File(MEDIA_PATH);
if(home.listFiles(new Mp3Filter()).length > 0){
for(File file: home.listFiles(new Mp3Filter())){
songs.add(file.getName());
}
}
ArrayAdapter<String> songList = new ArrayAdapter<String>(this, R.layout.song_item, songs);
setListAdapter(songList);
}
#Override
protected void onListItemClick(ListView l, View v, int position, long id){
currentPosition = position;
playSong(MEDIA_PATH + songs.get(position));
//Toast.makeText(getApplicationContext(), songs.get(position).toString(), Toast.LENGTH_SHORT).show();
final String songName = songs.get(position).toString();
//final TextView textchange = (TextView) v.findViewById(R.id.current_song_name);
Intent in = new Intent(this, current_song.class);
in.putExtra("song_name", songName);
startActivity(in);
//Toast.makeText(getApplicationContext(), "End of Song List", Toast.LENGTH_SHORT).show();
//textchange.setText(songName);
}
private void playSong(String songPath) {
// TODO Auto-generated method stub
try{
mp.reset();
mp.setDataSource(songPath);
mp.prepare();
mp.start();
mp.setOnCompletionListener(new OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
// TODO Auto-generated method stub
auto_nextSong();
}
});
}
catch (Exception e) {
// TODO: handle exception
}
}
public void pause(){
mp.pause();
}
public void stop(){
mp.stop();
}
public void next(){
Toast.makeText(getApplicationContext(), "In Next()", Toast.LENGTH_SHORT).show();
if(currentPosition < songs.size()){
currentPosition = currentPosition + 1;
playSong(MEDIA_PATH + songs.get(currentPosition));
}
}
public void prv(){
if(currentPosition > songs.size()){
currentPosition = currentPosition - 1;
playSong(MEDIA_PATH + songs.get(currentPosition));
}
}
private void auto_nextSong() {
// TODO Auto-generated method stub
if(++currentPosition >= songs.size()){
currentPosition = 0;
Toast.makeText(getApplicationContext(), "End of Song List", Toast.LENGTH_SHORT).show();
}
else{
playSong(MEDIA_PATH + songs.get(currentPosition));
Toast.makeText(getApplicationContext(), "Next Song", Toast.LENGTH_SHORT).show();
}
}
}
from the above class i am trying to access pause() and stop()
this is my class where i am trying to access
package com.example.musicplayer;
import com.example.musicplayer.MainActivity;
import android.app.Activity;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
public class current_song extends Activity implements OnClickListener{
public MainActivity ma;
protected void onCreate(Bundle icicle, MainActivity ma) {
Bundle extra = getIntent().getExtras();
super.onCreate(icicle);
setContentView(R.layout.songplay_page);
if(extra != null){
String song_name = extra.getString("song_name");
TextView textchange = (TextView)findViewById(R.id.current_song_name);
textchange.setText(song_name);
textchange.setSelected(true);
}
//MainActivity ma = ((MainActivity)getApplicationContext());
//MediaPlayer mp = ma.getmp();
this.ma = ma;
Button btn_pause = (Button)findViewById(R.id.pause_btn);
btn_pause.setOnClickListener(this);
Button btn_next = (Button)findViewById(R.id.next_btn);
btn_next.setOnClickListener(this);
Button btn_prv = (Button)findViewById(R.id.prv_btn);
btn_prv.setOnClickListener(this);
Button btn_stop = (Button)findViewById(R.id.stop_btn);
btn_stop.setOnClickListener(this);
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
//Toast.makeText(getApplicationContext(), "In Onclick ()", Toast.LENGTH_SHORT).show();
switch(v.getId())
{
case R.id.pause_btn:
((MainActivity)ma).pause();
break;
case R.id.next_btn:
//ma.next();
break;
case R.id.prv_btn:
//ma.prv();
break;
case R.id.stop_btn:
((MainActivity)ma).stop();
break;
}
}
}
The concept is that i want to stop, pause the music which is playing. If my logic i wrong please guide me how to do it else please help me how to control my current music in Current music java class.
Please, move all your music playing code into Service. Activities don't work that way.
Consider the following:
http://developer.android.com/reference/android/app/Activity.html#ActivityLifecycle
http://developer.android.com/reference/android/app/Service.html
I think You are new to android but no problem: See you can not call the functions of activity from any other class like this (Object.method();)
SO For this type of handling You Should Create a inner Handler class which extends Handler inside your MainActivity. and override onHandle(message msg){} method of it.
And When You start current_song activity pass this handler object in the intent.
And when you want to perform any task from your MainActivity (like stop, pause), pass messages through that handler like object.sendmessage(new msgObject("stop"));
And inside you onHandle() method call your stop or pause methods through diffrentiating command received from the message object.
like if(message's content == stop) MainActivity.this.stop();

Making remote server calls in an Android application

I've made an apache thrift server and I have a service which contains several functions.
I'm trying to figure out what is the best way to make calls to the remote server from my android application.
My problem is that I can't make calls from the MainActivity thread (the main thread) - and I need to use most of the remote functions in my main activity methods.
I tried to make a static class with a static member called "Server" equals to the server object, and I set it in another thread and then I tried to call it in the main thread (the main activity class) - but I had errors because of jumping from one thread to another..
To be more specified I want something like that:
public class MainActivity extends Activity {
private service.Client myService;
#Override
protected void onCreate(Bundle savedInstanceState) {
..
... Some stuff that define myService (In a new thread ofcourse) ...
}
...
private void MyFunc1() {
myService.Method1();
}
private void MyFunc2() {
myService.Method2();
}
private void MyFunc3() {
myService.Method3();
}
}
I've got a library for talking to REST APIs. Feel free to slice, dice, and re-use: https://github.com/nedwidek/Android-Rest-API
The code is BSD or GPL.
Here's how I use what I have (I've trimmed MainActivity a bit, hopefully not too much):
package com.hatterassoftware.voterguide.api;
import java.util.HashMap;
public class GoogleCivicApi {
protected final String baseUrl = "https://www.googleapis.com/civicinfo/us_v1/";
protected String apiKey = "AIzaSyBZIP5uY_fMF35SVVrytpKgHtppBbj8J0I";
public static final String DATE_FORMAT = "yyyy-MM-dd";
protected static HashMap<String, String> headers;
static {
headers = new HashMap<String, String>();
headers.put("Content-Type", "application/json");
}
public String createUrl(String uri, HashMap<String, String> params) {
String url = baseUrl + uri + "?key=" + apiKey;
if (params != null) {
for (String hashKey: params.keySet()) {
url += hashKey + "=" + params.get(hashKey) + "&";
}
url = url.substring(0, url.length());
}
return url;
}
}
package com.hatterassoftware.voterguide.api;
import android.util.Log;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.hatterassoftware.restapi.GetTask;
import com.hatterassoftware.restapi.HttpReturn;
import com.hatterassoftware.restapi.RestCallback;
import com.hatterassoftware.voterguide.api.callbacks.ElectionCallback;
import com.hatterassoftware.voterguide.api.models.Election;
public class ElectionsQuery extends GoogleCivicApi implements RestCallback {
GetTask getTask;
ElectionCallback callback;
final String TAG = "ElectionQuery";
public ElectionsQuery(ElectionCallback callback) {
String url = this.createUrl("elections", null);
this.callback = callback;
Log.d(TAG, "Creating and executing task for: " + url);
getTask = new GetTask(url, this, null, null, null);
getTask.execute();
}
#Override
public void onPostSuccess() {
Log.d(TAG, "onPostSuccess entered");
}
#Override
public void onTaskComplete(HttpReturn httpReturn) {
Log.d(TAG, "onTaskComplete entered");
Log.d(TAG, "httpReturn.status = " + httpReturn.status);
if (httpReturn.content != null) Log.d(TAG, httpReturn.content);
if (httpReturn.restException != null) Log.d(TAG, "Exception in httpReturn", httpReturn.restException);
JsonParser parser = new JsonParser();
JsonElement electionArrayJson = ((JsonObject)parser.parse(httpReturn.content)).get("elections");
Log.d(TAG, electionArrayJson.toString());
Gson gson = new GsonBuilder().setDateFormat(GoogleCivicApi.DATE_FORMAT).create();
Election[] elections = gson.fromJson(electionArrayJson.toString(), Election[].class);
callback.retrievedElection(elections);
}
}
package com.hatterassoftware.voterguide;
import java.util.Calendar;
import java.util.List;
import com.actionbarsherlock.app.SherlockFragmentActivity;
import com.hatterassoftware.voterguide.api.ElectionsQuery;
import com.hatterassoftware.voterguide.api.VoterInfoQuery;
import com.hatterassoftware.voterguide.api.callbacks.ElectionCallback;
import com.hatterassoftware.voterguide.api.callbacks.VoterInfoCallback;
import com.hatterassoftware.voterguide.api.models.Election;
import com.hatterassoftware.voterguide.api.models.VoterInfo;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationManager;
import android.os.Bundle;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Resources;
import android.text.Editable;
import android.text.Html;
import android.text.TextWatcher;
import android.text.method.LinkMovementMethod;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ProgressBar;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends SherlockFragmentActivity implements ElectionCallback, VoterInfoCallback {
private ProgressBar mProgressBar;
public Button submit;
public Spinner state;
public Spinner election;
public EditText address;
public EditText city;
public EditText zip;
private int count=0;
private Object lock = new Object();
private static final String TAG = "MainActivity";
public static final String VOTER_INFO = "com.hatterassoftware.voterguide.VOTER_INFO";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mProgressBar = (ProgressBar) findViewById(R.id.home_progressBar);
Resources res = getResources();
SharedPreferences mPrefs = getApplicationSharedPreferences();
ImageButton gpsButton = (ImageButton) findViewById(R.id.locate);
try {
LocationManager manager = (LocationManager) getSystemService( Context.LOCATION_SERVICE );
if (!manager.isProviderEnabled(Context.LOCATION_SERVICE)) {
gpsButton.setClickable(false);
}
} catch(Exception e) {
Log.d(TAG, e.getMessage(), e);
gpsButton.setClickable(false);
gpsButton.setEnabled(false);
}
submit = (Button) findViewById(R.id.submit);
submit.setClickable(false);
submit.setEnabled(false);
state = (Spinner) findViewById(R.id.state);
election = (Spinner) findViewById(R.id.election);
address = (EditText) findViewById(R.id.streetAdress);
city = (EditText) findViewById(R.id.city);
zip = (EditText) findViewById(R.id.zip);
submit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
doSubmit();
}
});
gpsButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
doLocate();
}
});
// Let's check for network connectivity before we get down to business.
if (Utils.isNetworkAvailable(this, true)) {
// Show the disclaimer on first run.
if(mPrefs.getBoolean("firstRun", true)) {
AlertDialog alert = new AlertDialog.Builder(this).create();
alert.setCancelable(false);
alert.setTitle(res.getString(R.string.welcome));
LayoutInflater inflater = (LayoutInflater) this.getSystemService(LAYOUT_INFLATER_SERVICE);
View layout = inflater.inflate(R.layout.custom_dialog, null);
TextView alertContents = (TextView) layout.findViewById(R.id.custom_dialog_text);
alertContents.setMovementMethod(LinkMovementMethod.getInstance());
alertContents.setText(Html.fromHtml(res.getString(R.string.welcome_dialog_text)));
alert.setView(alertContents);
alert.setButton(AlertDialog.BUTTON_POSITIVE, "OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
SharedPreferences mPrefs = getApplicationSharedPreferences();
SharedPreferences.Editor editor = mPrefs.edit();
editor.putBoolean("firstRun", false);
editor.commit();
dialog.dismiss();
retrieveElections();
}
});
alert.show();
} else {
retrieveElections();
}
}
}
#Override
public void onResume() {
super.onResume();
// Let's check for network connectivity before we get down to business.
Utils.isNetworkAvailable(this, true);
LocationManager manager = (LocationManager) getSystemService( Context.LOCATION_SERVICE );
if (!(manager.isProviderEnabled(LocationManager.GPS_PROVIDER)
|| manager.isProviderEnabled(LocationManager.NETWORK_PROVIDER))) {
Toast.makeText(this, "GPS is not available", 2).show();
ImageButton gpsButton = (ImageButton) findViewById(R.id.locate);
gpsButton.setClickable(false);
}
}
public SharedPreferences getApplicationSharedPreferences() {
Context mContext = this.getApplicationContext();
return mContext.getSharedPreferences("com.hatterassoftware.voterguide", MODE_PRIVATE);
}
private void showSpinner() {
synchronized(lock) {
count++;
mProgressBar.setVisibility(View.VISIBLE);
}
}
private void hideSpinner() {
synchronized(lock) {
count--;
if(count < 0) { // Somehow we're trying to hide it more times than we've shown it.
count=0;
}
if (count == 0) {
mProgressBar.setVisibility(View.INVISIBLE);
}
}
}
public void retrieveElections() {
Log.d(TAG, "Retrieving the elections");
showSpinner();
ElectionsQuery query = new ElectionsQuery(this);
}
#Override
public void retrievedElection(Election... elections) {
Log.d(TAG, "Retrieved the elections");
hideSpinner();
for (int i=0; i<elections.length; i++) {
Log.d(TAG, elections[i].toString());
}
ArrayAdapter arrayAdapter = new ArrayAdapter(this, android.R.layout.simple_spinner_item, elections);
arrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
Spinner spinner = (Spinner) this.findViewById(R.id.election);
spinner.setAdapter(arrayAdapter);
}
}

Categories