Remove string after second colon in Java - java

I would like to remove the string after the second colon and add a new string behind.
I have a maker when clicking on a marker I add the string using ALertDialog on the marker title so I can get those value to the process for a text file. But if I select that marker again I want to remove that text after colon so I don't add duplicate string again.
I checked this link but it uses a regular expression and I don't have any experience with that.
My String = W:3:ER1,ER2,ER3,,,,
Output = W:3
I would like to remove the string after the second colon so I can attach my string
Here is my onMarkerClick
#Override
public boolean onMarkerClick(final Marker marker) {
final String[] title = {marker.getTitle()};
Bitmap smallDot = Bitmap.createScaledBitmap(getBitmapFromVectorDrawable(getApplicationContext(),
R.drawable.blue_dot), 15, 15, false);
final String[] selectedItems = {"", "", "", "", ""};
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setTitle("Enable Relays");
// add a checkbox list
final String[] relays = {"Relay 1", "Relay 2", "Relay 3", "Relay 4", "Implement"};
boolean[] checkedItems = {true, false, false, true, false};
builder.setMultiChoiceItems(relays, null, new DialogInterface.OnMultiChoiceClickListener() {
#Override
public void onClick(DialogInterface dialog, int which, boolean isChecked) {
if (isChecked) {
// If the user checked the item, add it to the selected items
selectedItems[which] = "ER" + (which + 1);
} else if (!isChecked) {
// Else, if the item is already in the array, remove it
selectedItems[which] = "";
}
Toast.makeText(MainActivity.this, "" + Arrays.toString(selectedItems), Toast.LENGTH_LONG).show();
}
}).setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// title[0] += ":" + selectedItems[0] + "," + selectedItems[1] + "," + selectedItems[2] + "," + selectedItems[3] + "," + selectedItems[4];
int commas = 0;
for (int i = 0; i < title[0].length(); i++) {
if (title[0].charAt(i) == ',') commas++;
}
if (!title[0].contains("ER1") && commas <= 4)
title[0] += ":" + selectedItems[0];
if (!title[0].contains("ER2") && commas <= 4)
title[0] += "," + selectedItems[1];
if (!title[0].contains("ER3") && commas <= 4)
title[0] += "," + selectedItems[2];
if (!title[0].contains("ER4") && commas <= 4)
title[0] += "," + selectedItems[3];
if (!title[0].contains("ER5") && commas <= 4)
title[0] += "," + selectedItems[4];
marker.setTitle(title[0]);
marker.showInfoWindow();
Toast.makeText(MainActivity.this, "" + title[0], Toast.LENGTH_LONG).show();
}
}).setNegativeButton("CANCEL", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
}
});
// create and show the alert dialog
AlertDialog dialog = builder.create();
dialog.show();
return true;
}

First we split on the last : to get the title.
Then we parse on , from the last : to get items and we filter out empty ones.
import java.util.stream.Collectors;
public class Main {
public static void main(String[] args) {
String raw = "W:3:ER1,ER2,ER3,,,,";
String title = raw.substring(0, raw.lastIndexOf(":"));
String[] selectedItems = raw.substring(raw.lastIndexOf(":")+1).split(",");
List<String> items = Arrays.asList(selectedItems).stream().filter(str ->
! "".equals(str)
).collect(Collectors.toList());
System.out.println("Title "+ title);
System.out.println("Items "+ items);
}
}
Prints
Title W:3
Items [ER1, ER2, ER3]
Edit 1 : Should handle single colon
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
public class Main {
public static void main(String[] args) {
String raw = "W:3";
List<String> items;
String title;
if (raw.replaceAll("[^:]", "").length() > 1) { // String with every :
title = raw.substring(0, raw.lastIndexOf(":"));
String[] selectedItems = raw.substring(raw.lastIndexOf(":") + 1).split(",");
items = Arrays.asList(selectedItems).stream().filter(str ->
!"".equals(str)
).collect(Collectors.toList());
} else {
title = raw;
items = null;
}
System.out.println("Title "+ title);
System.out.println("Items "+ items);
}
}
And prints for raw = "W:3";
Title W:3
Items null

I found the trick to remove string after the second colon.
First, find the position for the second colon. Then remove the string after that position.
Here the method for finding the position
private static int findSecondColonPosition(String s) {
int result = -1;
int dotsToFind = 2;
char[] ca = s.toCharArray();
for (int i = 0; i < ca.length; ++i) {
if (ca[i] == ':') --colonsToFind;
if (dotsToFind == 0) return i;
}
return result;
}
Here my updated onMarkerClick code
#Override
public boolean onMarkerClick(final Marker marker) {
final String[] title = {marker.getTitle()};
Bitmap smallDot = Bitmap.createScaledBitmap(getBitmapFromVectorDrawable(getApplicationContext(),
R.drawable.blue_dot), 15, 15, false);
final String[] selectedItems = { "", "", "", ""};
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setTitle("Enable Relays");
// add a checkbox list
final String[] relays = {"Relay 2", "Relay 3", "Relay 4", "Implement"};
builder.setMultiChoiceItems(relays, null, new DialogInterface.OnMultiChoiceClickListener() {
#Override
public void onClick(DialogInterface dialog, int which, boolean isChecked) {
if (isChecked) {
// If the user checked the item, add it to the selected items
selectedItems[which] = "ER" + (which + 2);
} else if (!isChecked) {
// Else, if the item is already in the array, remove it
selectedItems[which] = "";
}
Toast.makeText(MainActivity.this, "" + Arrays.toString(selectedItems), Toast.LENGTH_LONG).show();
}
}).setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
int secoundColonPosition = findSecondColonPosition(title[0]);
if (secoundColonPosition > 0) {
System.out.println("title after remove: " + title[0].substring(0, secoundColonPosition));
title[0] = title[0].substring(0, secoundColonPosition);
} else {
System.out.println("ERROR: there is not a 2nd colon in " + title[0]);
}
title[0] += ":" + selectedItems[0] + "," + selectedItems[1] + "," + selectedItems[2] + "," + selectedItems[3];
marker.setTitle(title[0]);
marker.showInfoWindow();
Toast.makeText(MainActivity.this, "" + title[0], Toast.LENGTH_LONG).show();
}
}).setNegativeButton("CANCEL", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
}
});
// create and show the alert dialog
AlertDialog dialog = builder.create();
dialog.show();
// if (isEnable()) {
// title += ":Enable_Implement";
// marker.setTitle(title);
// marker.setIcon(BitmapDescriptorFactory.fromBitmap(smallDot));
// setEnable(false);
// setDisable(true);
// programStatusTextView.setText("Choose a stop actuation point");
// } else if (isDisable()) {
// title += ":Disable_Implement";
// marker.setTitle(title);
// marker.setIcon(BitmapDescriptorFactory.fromBitmap(smallDot));
// setDisable(false);
// programStatusTextView.setText("");
// }
return true;
}

Related

Add Correct answers to Alert Dialog

Please help. I want to display the correct answers in an alert dialog, if i type "rightAnswers" inside "builder.setMessage("Answer : " + rightAnswers);" an alert show "Answer: 1". Number 1 instead of the correct answer. please teach me what to put to be able to display the correct answer. thank you so much.
public class thisactivity extends AppCompatActivity {
Button choice1,choice2;
ImageView images;
List<Model> list;
int turn = 1;
int rightAnswers = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_thisactivity);
images = (ImageView) findViewById(R.id.images);
choice1 = (Button) findViewById(R.id.choice1);
choice2 = (Button) findViewById(R.id.choice2);
list = new ArrayList<>();
for (int i = 0; i < new Signsdatabase().answers.length; i++) {
list.add(new Model(new Signsdatabase().answers[i], new
Signsdatabase().signs[i]));
}
newQuestion(turn);
choice1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String alertTitle;
if(choice1.getText().toString().equalsIgnoreCase(list.get(turn -
1).getName())) {
rightAnswers = rightAnswers + 1;
alertTitle = "Correct!";
if (turn < list.size()) {
turn++;
newQuestion(turn);
} else {
Toast.makeText(thisactivity.this, "You have completed the Quiz!", Toast.LENGTH_SHORT).show();
}
}
AlertDialog.Builder builder = new
AlertDialog.Builder(thisactivity.this)
builder.setTitle(alertTitle);
builder.setMessage("Answer : " + **CORRECT ANSWERS**); <---I WANT TO DISPLAY THE CORRECT ANSWER HERE BUT I DO NOT KNOW HOW------->
builder.setIcon(R.drawable.pic);
builder.setPositiveButton("OK", new
DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int i) {
}
});
}
});
choice2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (choice2.getText().toString().equalsIgnoreCase(list.get(turn - 1).getName())) {
rightAnswers = rightAnswers + 1;
if (turn < list.size()) {
turn++;
newQuestion(turn);
} else {
Toast.makeText(thisactivity.this, "You have completed the Quiz!", Toast.LENGTH_SHORT).show();
getResults();
}
} else {
}
AlertDialog.Builder builder = new
AlertDialog.Builder(Roadsigns.this)
builder.setTitle(alertTitle);
builder.setMessage("Answer : " + **CORRECT ANSWERS**); <---I WANT TO DISPLAY THE CORRECT ANSWER HERE BUT I DO NOT KNOW HOW------->
builder.setIcon(R.drawable.pic);
builder.setPositiveButton("OK", new
DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int i) {
}
});
builder.setCancelable(false);
builder.show();
}
});
}
............
And this is my Signsdatabase
public class Signsdatabase {
Integer[] signs ={
R.drawable.q1,
R.drawable.q2,
R.drawable.q3,
};
String[] answers = {
"Ans1",
"Ans2",
"Ans3",
};
}
Make this change in alter dialog.
make Signsdatabase object or make static in answer array.
builder.setMessage("Answer : " + Signsdatabase.answers[rightAnswers]);
You display the index of the right answer, you need to get the item from the list at the corresponding position:
builder.setMessage("Answer : " + signsdatabase.answers[rightAnswers]);
builder.setMessage("Answer : " + list[rightAnswers]);// it also check.
And you also need to initialize signsdatabase before
signsdatabase = new Signsdatabase();
Suppose you have the correct index of the answer You can do one of the following :
One
Create an object of SignsDatabase :
signsDb = new Signsdatabase();
With index i of correct answer :
builder.setMessage("Answer : "+ signDb.answers[i];
Two
If you do not want to create an instance of SignDatabase, you can declare the answers as static variable so :
public class SignDatabase{
... //some code here
public static String[] answers = ["Abc","xyz"];
}
Then access it directly by calling :
builder.setMessage(SignDatabase.answers[i]);

Can ListView host TextView items that are also displayed in a separate TextView

I'm having a problem changing a TextView to a ListView. Originally, the app had a button that when clicked, runs tests to a bluetooth device and displays the results in a textview. I modified the app to contain two textviews that have the last text results and a separate xml file (connected with viewflipper) to go to a second textview that contains all of the test results, until the user clears the textview by clicking a button. I followed along with this example and checked what I was entering in the ArrayAdapter section of the code, and it appears to be what is required according to the developer's guide, but I still get his error:
Cannot resolve constructor 'ArrayAdapter(com.example.android.stardustscanner.ScannerFragment, int, int, java.lang.String)'
Why am I getting this error?
My .java file that I am making all the changes in is very long and contains a lot of thins that aren't relevant to this question and doesn't fit in the question box, so I'll try to only include the relevant parts. The error is towards the bottom with this line:
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(this, R.layout.fragment_bluetooth_scanner, R.id.textView, saveData);
ScannerFragment.java
public class ScannerFragment extends Fragment implements LocationListener {
ListView mListView;
//page switching things KG 8/24/17
private ViewFlipper mViewFlipper;
private float lastX;
private Button mViewLog;
private Button mReturnFlipper;
private TextView mShowData;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container,
#Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.flipper_holder, container, false);//kg 8/24/17
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
SP = PreferenceManager.getDefaultSharedPreferences(getContext());
mViewFlipper = (ViewFlipper) view.findViewById(R.id.viewFlip); //KG 8/24/17
mViewLog = (Button) view.findViewById(R.id.viewLog); //kg 8/24/17
mReturnFlipper = (Button) view.findViewById(R.id.flipperReturn); //kg 8/24/17
mShowData = (TextView) view.findViewById(R.id.textView) ; //kg 8/25/2017
mShowData.setText(readFromFile()); // kg 8/25/2017
mPowerOffButton = (Button) view.findViewById(R.id.button_poweroff);
mDisconnectButton = (Button) view.findViewById(R.id.button_disconnect);
mConnectButton = (Button) view.findViewById(R.id.button_connect);
mPresence = (Button) view.findViewById(R.id.button_present);
mBattery = (ProgressBar) view.findViewById(R.id.progressBar);
mBlinkConnect = (Button) view.findViewById(R.id.button_connectionblink);
mBlinkData = (Button) view.findViewById(R.id.button_communication);
mClearLog = (Button) view.findViewById(R.id.button_clear_log);
mDeviceName = (Button) view.findViewById(R.id.button_devicename);
mDeviceSN = (Button) view.findViewById(R.id.button_devicesn);
mBatteryPerc = (TextView) view.findViewById(R.id.label_batterypct);
mListView = (ListView) view.findViewById(R.id.scanLogView); //kg 8/28/17
// mReadingLog = (TextView) view.findViewById(R.id.scanLogView);
mReadingLog.setMovementMethod(new ScrollingMovementMethod());
mReadingLog.setText(readFromFile());
telephonyManager = (TelephonyManager)getContext().getSystemService(Context.TELEPHONY_SERVICE);
initLocationService(this.getContext());
final ActionBar actionBar = getActivity().getActionBar();
if (null == actionBar) {
return;
}
final Drawable D = getResources().getDrawable(R.drawable.stardust2);
actionBar.setBackgroundDrawable(D);
actionBar.setTitle("");
//KG 8/24/17
mViewLog.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view){
mViewFlipper.showNext();
}
});
mReturnFlipper.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view){
mViewFlipper.showPrevious();
}
});
}
private void setupScanner() {
Log.d(TAG, "setupScanner()");
// Initialize the send button with a listener that for click events
mPowerOffButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if(isIris) {
publishMessage(Constants.COMMAND_POWEROFF_IRIS);
} else {
publishMessage(Constants.COMMAND_POWEROFF);
}
mScannerService.stop();
}
});
// Initialize the send button with a listener that for click events
mDisconnectButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Send a message using content of the edit text widget
publishMessage(Constants.COMMAND_DISCONNECT);
mScannerService.stop();
}
});
// Initialize the send button with a listener that for click events
mConnectButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Send a message using content of the edit text widget
publishMessage(Constants.COMMAND_ON_CONNECT);
}
});
mClearLog.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Send a message using content of the edit text widget
mReadingLog.setText("");
if(SP.getBoolean("writeToFile", true)) {
writeToFile("", "", false);
}
}
});
// Initialize the ScannerService to perform bluetooth connections
mScannerService = new ScannerService(getActivity(), mHandler);
}
private TextView.OnEditorActionListener mWriteListener
= new TextView.OnEditorActionListener() {
public boolean onEditorAction(TextView view, int actionId, KeyEvent event) {
// If the action is a key-up event on the return key, send the message
if (actionId == EditorInfo.IME_NULL && event.getAction() == KeyEvent.ACTION_UP) {
String message = view.getText().toString();
publishMessage(message);
}
return true;
}
};
private final Handler mHandler = new Handler() {
#Override
public void handleMessage(Message msg) {
FragmentActivity activity = getActivity();
switch (msg.what) {
case Constants.MESSAGE_STATE_CHANGE:
switch (msg.arg1) {
case ScannerService.STATE_CONNECTED:
setStatus(mConnectedDeviceName);
if(mConnectedDeviceName.substring(0, 4).toLowerCase().equals("iris") || mConnectedDeviceName.substring(0, 8).toLowerCase().equals("stardust")) {
isIris = true;
mPresence.setClickable(true);
mPresence.setText("Click to detect taggant");
mPresence.setBackgroundColor(Color.parseColor("#0061ff"));
mPresence.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
readoutStarted = true;
publishMessage(Constants.COMMAND_RUN_IRIS);
}
});
mPowerOffButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
publishMessage(Constants.COMMAND_POWEROFF_IRIS);
mScannerService.stop();
}
});
} else {
isIris = false;
}
if(!isIris) {
mPresence.setClickable(false);
mPresence.setText("NO TAGGANT DETECTED");
mPresence.setBackgroundColor(Color.parseColor("#ffc4ab"));
publishMessage(Constants.COMMAND_ON_CONNECT);
timer = new Timer();
timerStarted = true;
timer.scheduleAtFixedRate(new TimerTask() {
synchronized public void run() {
publishMessage(Constants.COMMAND_READDATA);
}
}, 1000, 1000);
} else {
if(timerStarted) {
timer.cancel();
timer.purge();
timerStarted = false;
}
}
mBlinkConnect.setBackgroundColor(Color.parseColor("#11D901"));
break;
case ScannerService.STATE_CONNECTING:
setStatus("C");
break;
case ScannerService.STATE_LISTEN:
case ScannerService.STATE_NONE:
mBlinkConnect.setBackgroundColor(Color.parseColor("#ff2b0f"));
mBlinkData.setBackgroundColor(Color.parseColor("#CCCCCC"));
if(timerStarted) {
timer.cancel();
timer.purge();
timerStarted = false;
}
setStatus("D");
break;
}
break;
case Constants.MESSAGE_WRITE:
mBlinkData.setBackgroundColor(Color.parseColor("#CCCCCC"));
break;
case Constants.MESSAGE_READ:
mBlinkData.setBackgroundColor(Color.parseColor("#0091FA"));
String readMessage = (String)msg.obj;
if(isIris) {
readIris(readMessage);
} else {
readNormal(readMessage);
}
break;
case Constants.MESSAGE_DEVICE_NAME:
// save the connected device's name
mConnectedDeviceName = msg.getData().getString(Constants.DEVICE_NAME);
if (null != activity) {
Toast.makeText(activity, "Connected to "
+ mConnectedDeviceName, Toast.LENGTH_SHORT).show();
}
break;
case Constants.MESSAGE_TOAST:
if (null != activity) {
Toast.makeText(activity, msg.getData().getString(Constants.TOAST),
Toast.LENGTH_SHORT).show();
}
break;
}
}
};
public void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case REQUEST_CONNECT_DEVICE_SECURE:
// When DeviceListActivity returns with a device to connect
if (resultCode == Activity.RESULT_OK) {
connectDevice(data, true);
}
break;
case REQUEST_CONNECT_DEVICE_INSECURE:
// When DeviceListActivity returns with a device to connect
if (resultCode == Activity.RESULT_OK) {
connectDevice(data, false);
}
break;
case REQUEST_ENABLE_BT:
// When the request to enable Bluetooth returns
if (resultCode == Activity.RESULT_OK) {
// Bluetooth is now enabled, so set up a session
setupScanner();
} else {
// User did not enable Bluetooth or an error occurred
Log.d(TAG, "BT not enabled");
Toast.makeText(getActivity(), R.string.bt_not_enabled_leaving,
Toast.LENGTH_SHORT).show();
getActivity().finish();
}
}
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.secure_connect_scan: {
// Launch the DeviceListActivity to see devices and do scan
Intent serverIntent = new Intent(getActivity(), DeviceListActivity.class);
startActivityForResult(serverIntent, REQUEST_CONNECT_DEVICE_SECURE);
return true;
}
/*case R.id.insecure_connect_scan: {
// Launch the DeviceListActivity to see devices and do scan
Intent serverIntent = new Intent(getActivity(), DeviceListActivity.class);
startActivityForResult(serverIntent, REQUEST_CONNECT_DEVICE_INSECURE);
return true;
}*/
case R.id.settings_button: {
Intent serverIntent = new Intent(getActivity(), SettingsActivity.class);
startActivityForResult(serverIntent, REQUEST_SHOW_SETTINGS);
return true;
}
}
return false;
}
/**
*
* #param data String
* #param append boolean
*/
private void writeToFile(String data, String uploadData, boolean append) {
String root = Environment
.getExternalStorageDirectory().toString();
File myDir = new File(root);
String fname = "starDust.txt";
String fname2 = "starDust.csv";
File file = new File (myDir, fname);
File file2 = new File (myDir, fname2);
//if (file.exists ()) file.delete ();
try {
FileOutputStream out = new FileOutputStream(file, append);
out.write(data.getBytes(), 0, data.getBytes().length);
out.flush();
out.close();
FileOutputStream out2 = new FileOutputStream(file2, append);
out2.write(uploadData.getBytes(), 0, uploadData.getBytes().length);
out2.flush();
out2.close();
if(mConnectedDeviceName != null) {
Log.d(TAG, "Connecting " + SP.getString("server_ip", "") + SP.getString("server_username", "") + SP.getString("server_password", ""));
new FTPUploadTask().execute(mConnectedDeviceName, SP.getString("server_ip", ""), SP.getString("server_username", "") , SP.getString("server_password", ""));
}
} catch (Exception e) {
e.printStackTrace();
}
}
/**
*
*/
private String readFromFile() {
String root = Environment
.getExternalStorageDirectory().toString();
File myDir = new File(root);
String fname = "starDust.txt";
File file = new File (myDir, fname);
StringBuilder text = new StringBuilder();
if (file.exists ()) {
try {
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
while ((line = br.readLine()) != null) {
text.insert(0, line + System.getProperty("line.separator"));
}
br.close();
} catch (Exception e) {
}
}
return text.toString();
}
private void readNormal(String readMessage) {
String parsedData[];
if(readMessage.contains(";")) {
if(readMessage.equals(";")) {
parsedData = bufferedMessage.trim().split(",");
bufferedMessage = "";
} else {
String partialMessage[] = readMessage.split(";");
bufferedMessage += partialMessage[0];
parsedData = bufferedMessage.trim().split(",");
if (partialMessage.length > 1) {
bufferedMessage = partialMessage[1];
} else {
bufferedMessage = "";
}
}
} else {
bufferedMessage += readMessage.trim();
return;
}
if(parsedData.length == RESPONSE_SIZE && parsedData[0].equals("U")) {
if(parsedData[1].matches("[-+]?\\d*\\.?\\d+")) {
if(Integer.parseInt(parsedData[1]) > maxU1 || hitTrigger) {
maxU1 = Integer.parseInt(parsedData[1]);
}
}
if(parsedData[2].matches("[-+]?\\d*\\.?\\d+")) {
if(Integer.parseInt(parsedData[2]) > maxU2 || hitTrigger) {
maxU2 = Integer.parseInt(parsedData[2]);
}
}
if(parsedData[3].matches("[-+]?\\d*\\.?\\d+")) {
if(Integer.parseInt(parsedData[3]) > maxU3 || hitTrigger) {
maxU3 = Integer.parseInt(parsedData[3]);
}
}
double u1val = Double.parseDouble(parsedData[1]);
double u2val = Double.parseDouble(parsedData[2]);
double u1u2div = 0;
if(u2val > 0) {
u1u2div = ((u1val / u2val) * KFactor);
}
if(parsedData[4].matches("[-+]?\\d*\\.?\\d+")) {
mBatteryPerc.setText(parsedData[4] + "%");
mBattery.setProgress(Integer.parseInt(parsedData[4]));
}
}
taggantType = 0;
if(maxU1 > Integer.parseInt(SP.getString("maxThreshold", Integer.toString(MAX_TRIGGER)))) {
taggantType += 4;
} else {
taggantType += 0;
}
if(maxU2 > Integer.parseInt(SP.getString("maxThreshold", Integer.toString(MAX_TRIGGER)))) {
taggantType += 2;
} else {
taggantType += 0;
}
if(maxU3 > Integer.parseInt(SP.getString("maxThreshold", Integer.toString(MAX_TRIGGER)))) {
taggantType += 1;
} else {
taggantType += 0;
}
Log.d(TAG, Integer.toString(taggantType));
Log.d(TAG, Boolean.toString(hitTrigger));
Log.d(TAG, bufferedMessage);
// Check if hit threshold, if so hitTrigger is enabled.
if(taggantType > 0) {
savedTaggantType = taggantType;
hitTrigger = true;
mPresence.setText("VALID TAGGANT DETECTED");
mPresence.setBackgroundColor(Color.parseColor("#11D901"));
} else if(taggantType == 0 && hitTrigger) {
hitTrigger = false;
mPresence.setText("NO TAGGANT DETECTED");
mPresence.setBackgroundColor(Color.parseColor("#ffc4ab"));
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String currentDateandTime = sdf.format(new Date());
String saveData =
"Device: " + mConnectedDeviceName +
System.getProperty("line.separator") +
"Timestamp: " + currentDateandTime +
System.getProperty("line.separator") +
"Location: " + latitude + " (lat) / " + longitude + " (lon)" +
System.getProperty("line.separator") +
"Taggan Type: N" + Integer.toString(savedTaggantType) +
System.getProperty("line.separator") +
"Phone id: " + telephonyManager.getDeviceId() +
System.getProperty("line.separator") +
"=========================" +
System.getProperty("line.separator");
String csvData = mConnectedDeviceName + "," +
currentDateandTime + "," +
"\"http://maps.google.com/?q=" + latitude + "," + longitude + "\"," +
"N" + Integer.toString(savedTaggantType) + "," +
"\"" + telephonyManager.getDeviceId() + "\"" +
System.getProperty("line.separator");
mReadingLog.setText(saveData + mReadingLog.getText());
mShowData.setText(saveData); //kg 8/25/17
maxU1 = 0;
maxU2 = 0;
maxU3 = 0;
savedTaggantType = 0;
if(SP.getBoolean("writeToFile", true)) {
writeToFile(saveData, csvData, true);
}
}
}
/**
* #param readMessage String
*/
public void readIris(String readMessage) {
if(!readoutStarted) {
return;
}
String parsedData[];
if(readMessage.contains(";")) {
readoutStarted = false;
if(readMessage.equals(";")) {
parsedData = bufferedMessage.replaceAll("\n", "").replaceAll(" +", " ").trim().split("\\*");
bufferedMessage = "";
} else {
String partialMessage[] = readMessage.replaceAll("\n", "").replaceAll(" +", " ").trim().split(";");
bufferedMessage += partialMessage[0].trim();
parsedData = bufferedMessage.replaceAll("\n", "").replaceAll(" +", " ").trim().split("\\*");
bufferedMessage = "";
}
} else {
bufferedMessage += readMessage.trim().replaceAll("\n", "").replaceAll(" +", " ");
return;
}
Log.d(TAG, Arrays.toString(parsedData));
boolean passed = false;
int v1 = 0;
int v2 = 0;
if(parsedData[3].equals("S")) {
passed = true;
String values[] = parsedData[7].split("\\s+");
v1 = Integer.parseInt(values[0].replaceAll("[\\D]", ""));
v2 = Integer.parseInt(values[values.length-1]);
} else {
Log.d(TAG, Arrays.toString(parsedData));
String values[] = parsedData[5].split("\\s+");
v1 = Integer.parseInt(values[0].replaceAll("[\\D]", ""));
v2 = Integer.parseInt(values[values.length-1]);
}
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String currentDateandTime = sdf.format(new Date());
String saveData =
"Device: " + mConnectedDeviceName +
System.getProperty("line.separator") +
"Timestamp: " + currentDateandTime +
System.getProperty("line.separator") +
"Location: " + latitude + " (lat) / " + longitude + " (lon)" +
System.getProperty("line.separator") +
"Phone id: " + telephonyManager.getDeviceId() +
System.getProperty("line.separator") +
"Valid:" + (passed ? "YES" : "NO") +
System.getProperty("line.separator") +
"Values: " + "T" + v1 + " / " + v2 +
System.getProperty("line.separator") +
"=========================" +
System.getProperty("line.separator");
String csvData = mConnectedDeviceName + "," +
currentDateandTime + "," +
"\"http://maps.google.com/?q=" + latitude + "," + longitude + "\"," +
"Valid: " + (passed ? "YES" : "NO") + " - " + "T" + v1 + " / " + v2 + Integer.toString(savedTaggantType) + "," +
"\"" + telephonyManager.getDeviceId() + "\"" +
System.getProperty("line.separator");
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(this, R.layout.fragment_bluetooth_scanner, R.id.textView, saveData);
mListView.setAdapter(arrayAdapter);
mReadingLog.setText(saveData + mReadingLog.getText());
mShowData.setText(saveData); //kg 8/25/17
if(SP.getBoolean("writeToFile", true)) {
writeToFile(saveData, csvData, true);
}
}
}
I have three xml files associated with this problem, but because of space I'll only include the one that contains the ListView and remove the other buttons.
view_list.xml contains the ListView:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:id="#+id/viewList"
android:layout_width="match_parent"
android:layout_height="match_parent">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="fill_parent"
android:layout_gravity="center_horizontal"
android:paddingLeft="4dp"
android:paddingRight="4dp"
android:visibility="visible">
<LinearLayout
android:layout_width="match_parent"
android:id="#+id/listview_holder"
android:layout_alignParentTop="true"
android:layout_alignTop="#id/button_holder"
android:layout_weight=".1"
android:layout_height="wrap_content">
<ListView
android:id="#+id/scanLogView"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:maxLines="4096"
android:scrollbars="vertical"
android:text="#string/app_name"
android:textAppearance="?android:attr/textAppearanceSmall"/>
</LinearLayout>
</RelativeLayout>
</LinearLayout>
The error was with ArrayAdapter. I changed the decloration from
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(this,
R.layout.fragment_bluetooth_scanner, R.id.textView, saveData);
to
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(),
android.R.layout.simple_list_item_1, android.R.id.text1, listItems);
It now builds the project and displays the listview.

How to solve "Unreachable Statement"

This is my Android code.I have an error in below line Toast that say "Unreachable Statement" and I know this error come from return of my If but I don't know how solve it
Error part:
do
{
return;
if ((paramAnonymous2Int == 0) && (AndroidHTMLActivity.this.Count == 4))
{
Toast.makeText(getApplicationContext(),"نسخه رایگان",Toast.LENGTH_SHORT).show();
return;
}
}
The whole Function :
#JavascriptInterface
public void SaveDialog(final String paramString)
{
final SQLiteDatabase mydatabase = openOrCreateDatabase("CopyCollection", MODE_PRIVATE, null);
Object localObject = mydatabase.rawQuery("SELECT * FROM Details WHERE ID=" + paramString + ";", null);
if (((Cursor)localObject).moveToFirst()) {
do
{
AndroidHTMLActivity.this.appName = ((Cursor)localObject).getString(1);
AndroidHTMLActivity.this.txtClip = ((Cursor)localObject).getString(2);
AndroidHTMLActivity.this.text_Date = ((Cursor)localObject).getString(3);
} while (((Cursor)localObject).moveToNext());
}
localObject = new AlertDialog.Builder(AndroidHTMLActivity.this);
((AlertDialog.Builder)localObject).setTitle("ذخیره");
((AlertDialog.Builder)localObject).setPositiveButton("ذخیره", new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface paramAnonymousDialogInterface, int paramAnonymousInt)
{
final SQLiteDatabase mydatabase1 = openOrCreateDatabase("CopyCollection", MODE_PRIVATE, null);
Cursor crs = mydatabase1.rawQuery("SELECT * FROM Groups;",null);
String[] array = new String[crs.getCount()];
int[] arrayID = new int[crs.getCount()];
Count = crs.getCount();
int i = 0;
while(crs.moveToNext()){
String uname = crs.getString(crs.getColumnIndex("GroupName"));
int id = crs.getColumnIndex("ID");
arrayID[i] = id;
array[i] = uname;
i++;
}
final AlertDialog.Builder builder = new AlertDialog.Builder(AndroidHTMLActivity.this);
builder.setTitle("گروه خود را انتخاب کنید");
builder.setItems(paramAnonymousDialogInterface, new DialogInterface.OnClickListener()
{
public void onClick(final DialogInterface paramAnonymous2DialogInterface, int paramAnonymous2Int)
{
strI = String.valueOf(paramAnonymous2Int);
String localObject1 = String.valueOf(paramAnonymous2Int);
final SQLiteDatabase mydatabase = openOrCreateDatabase("CopyCollection", MODE_PRIVATE, null);
Cursor localObject2 = mydatabase.rawQuery("SELECT * FROM Status WHERE ID=1;", null);
if ((localObject2).moveToFirst()) {
do
{
AndroidHTMLActivity.this.Trial = (localObject2).getInt(1);
} while ((localObject2).moveToNext());
}
if ((paramAnonymous2Int == 0) && (AndroidHTMLActivity.this.Count != 4))
{
final AlertDialog.Builder builder1 = new AlertDialog.Builder(AndroidHTMLActivity.this);
builder1.setTitle("درج عنوان گروه");
final EditText input = new EditText(AndroidHTMLActivity.this);
input.setInputType(1);
builder1.setView(input);
builder1.setPositiveButton("تایید", new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface paramAnonymous3DialogInterface, int paramAnonymous3Int)
{
m_Text = input.getText().toString();
mydatabase.execSQL("INSERT INTO Groups (GroupName) VALUES('" + m_Text + "');");
Cursor c3 = mydatabase.rawQuery("SELECT * FROM Groups ORDER BY ID DESC LIMIT 1;", null);
if ((c3 != null) && (c3.moveToFirst()))
{
long l = c3.getLong(0);
LastDir = String.valueOf(l);
}
mydatabase.execSQL("INSERT INTO MainContent(AppName,Txt,GroupID,Time)VALUES('" + appName + "','" + txtClip + "','" + LastDir + "','" + text_Date + "');");
mydatabase.execSQL("DELETE FROM Details WHERE ID = " + paramString + ";");
mydatabase.close();
}
});
builder1.setNegativeButton("انصراف", new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface paramAnonymous3DialogInterface, int paramAnonymous3Int)
{
paramAnonymous3DialogInterface.cancel();
AndroidHTMLActivity.this.myBrowser.post(new Runnable()
{
public void run()
{
myBrowser.loadUrl("javascript:fill_comment()");
}
});
}
});
builder1.show();
}
do
{
return;
if ((paramAnonymous2Int == 0) && (AndroidHTMLActivity.this.Count == 4))
{
Toast.makeText(getApplicationContext(),"نسخه رایگان",Toast.LENGTH_SHORT).show();
return;
}
}
while (paramAnonymous2Int == 0);
Cursor c2 = mydatabase.rawQuery("SELECT count(*) FROM `MainContent` WHERE `GroupID` LIKE '" + localObject1 + "'", null);
(c2).moveToFirst();
if ((c2).getInt(0) < 5)
{
mydatabase.execSQL("INSERT INTO MainContent (AppName,Txt,GroupID,Time) VALUES('" + AndroidHTMLActivity.this.appName + "','" + AndroidHTMLActivity.this.txtClip + "','" + (String)localObject1 + "','" + text_Date + "');");
mydatabase.execSQL("DELETE FROM Details WHERE ID = " + paramString + ";");
mydatabase.close();
}
Toast.makeText(getApplicationContext(),"نسخه رایگان",Toast.LENGTH_SHORT).show();
AndroidHTMLActivity.this.myBrowser.post(new Runnable()
{
public void run()
{
AndroidHTMLActivity.this.myBrowser.loadUrl("javascript:fill_comment()");
}
});
}
});
builder.create().show();
}
});
((AlertDialog.Builder)localObject).setNegativeButton("اشتراک گذاری", new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface paramAnonymousDialogInterface, int paramAnonymousInt)
{
Intent intent = new Intent("android.intent.action.SEND");
intent.setType("text/plain");
String str = txtClip;
intent.putExtra("android.intent.extra.SUBJECT", "Subject");
intent.putExtra("android.intent.extra.TEXT", str);
startActivity(Intent.createChooser(intent, "Share via"));
}
});
((AlertDialog.Builder)localObject).show();
}
#JavascriptInterface
public void configuration()
{
Intent localIntent = new Intent(AndroidHTMLActivity.this, Directory.class);
AndroidHTMLActivity.this.startActivity(localIntent);
AndroidHTMLActivity.this.finish();
}
Look at this code
return;
if ((paramAnonymous2Int == 0) && (AndroidHTMLActivity.this.Count == 4))
You return right before the validation, hence will never reach it.
Simple remove the return statement at the begin of do block.
return means exit immediately so no other code after that line is reached.
Change ur do into this
do
{
if ((paramAnonymous2Int == 0) && (AndroidHTMLActivity.this.Count == 4))
{
Toast.makeText(getApplicationContext(),"نسخه رایگان",Toast.LENGTH_SHORT).show();
return;
}
}
It never reaches because u were returning on the beginning of the Do
In java when return is encountered it just exits the method at that point. Once return is executed, the rest of the code won't be executed. Java compiler detect the unreachable code and it will give error.
if(condition)
{
return;
yougetunreachableerror();//compiler gives error
}

Content Resolver pointing to wrong table with correct URI

I am having a problem on the line where I call the query to PostCategoryContent Provider
I get an error stating:
11-13 10:23:40.674: E/AndroidRuntime(26012): android.database.sqlite.SQLiteException: no such column: category_id (code 1): , while compiling: SELECT * FROM post WHERE (category_id=39)
Even though the URI points to another Table postCategory
Can anyone guide me on what I'm doing wrong?
public class PostFragment extends SherlockListFragment implements LoaderCallbacks<Cursor> {
private SimpleCursorAdapter adapter;
private boolean dataRetrieved;
private SlidingArea parent;
PullToRefreshListView pullToRefreshView;
EditText searchBox;
Bundle args = new Bundle();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
parent = (SlidingArea) getActivity();
setHasOptionsMenu(true);
fillData(false);
}
#Override
public void onResume() {
super.onResume();
parent.getSupportActionBar().setCustomView(R.layout.kpmg_actionbar_list_view);
parent.getSupportActionBar().setDisplayShowCustomEnabled(true);
parent.getSupportActionBar().setDisplayHomeAsUpEnabled(true);
final ImageView searchButton = (ImageView) parent.findViewById(R.id.kpmg_actionbar_image_search_list);
searchButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (searchBox.getVisibility() == View.GONE)
{
searchBox.setVisibility(View.VISIBLE);
searchBox.requestFocus();
InputMethodManager imm = (InputMethodManager) parent.getSystemService(Context.INPUT_METHOD_SERVICE);
imm.showSoftInput(searchBox, InputMethodManager.SHOW_IMPLICIT);
} else {
searchBox.setVisibility(View.GONE);
searchBox.clearFocus();
hideKeyboard(v);
}
}
});
final ImageView refreshButton = (ImageView) parent.findViewById(R.id.kpmg_actionbar_image_refresh_list);
refreshButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
getData(getString(R.string.kpmg_json_get_articles), true);
refreshButton.setImageResource(R.drawable.kpmg_actionbar_refresh_dark);
fillData(true);
}
});
searchBox.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence cs, int arg1, int arg2, int arg3) {
// When user changed the Text
filterData(cs);
}
#Override
public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
int arg3) {
// TODO Auto-generated method stub
}
#Override
public void afterTextChanged(Editable s) {
// TODO Auto-generated method stub
}
});
}
//Constant used as key for ID being passed in the bundle between fragments
public static final String NEWS_ID = "newsID";
private void getData(String url, boolean showProgressDialog) {
new Request(showProgressDialog).execute(new String[] {url});
}
public class Request extends AsyncTask<String, Void, String> {
ProgressDialog dialog;
/* This is the only file that needs to be edited */
private GetResponse response = null;
private boolean showProgressDialog = true;
public Request(boolean showProgressDialog)
{
super();
this.showProgressDialog = showProgressDialog;
response = new GetResponse();
}
#Override
protected void onPreExecute() {
if (showProgressDialog) {
dialog = new ProgressDialog(parent);
dialog.setMessage("Retrieving latest information...");
dialog.setIndeterminate(true);
dialog.setCancelable(false);
dialog.show();
}
}
//This method must return the type specified in the constructor
#Override
protected String doInBackground(String... url) {
response.setUrl(url[0]);
String res = response.execute();
// When it returns the "res" it will call onPostExecute
return res;
}
#Override
protected void onPostExecute(String result) {
// Here we have response from server
if ( isNetworkAvailable() ){
try {
JSONObject json = new JSONObject(result);
JSONArray arr = json.getJSONArray("posts");
for (int i = arr.length() - 1; i >= 0; --i) {
JSONObject row = arr.getJSONObject(i);
JSONArray arrCategories = row.getJSONArray("categories");
int Created = 0;
int Updated = 0;
for (int j = arrCategories.length() -1; j >= 0; --j){
JSONObject rowCategory = arrCategories.getJSONObject(j);
ContentValues categoryValues = new ContentValues();
categoryValues.put(PostCategoryTable.CATEGORY_ID, rowCategory.getInt("id"));
Cursor categoryCursor = parent.getContentResolver().query(PostCategoryContentProvider.CONTENT_URI, null, PostCategoryTable.CATEGORY_ID + "=" + categoryValues.getAsString(PostCategoryTable.CATEGORY_ID), null, null);
int categoryCount = categoryCursor.getCount();
if (categoryCount == 0) {
categoryValues.put(PostCategoryTable.ICON_NAME, rowCategory.getString("slug"));
categoryValues.put(PostCategoryTable.CATEGORY_NAME, rowCategory.getString("title"));
categoryValues.put(PostCategoryTable.PARENT_ID, rowCategory.getInt("parent"));
parent.getContentResolver().insert(PostCategoryContentProvider.CONTENT_URI, categoryValues);
Created++;
}
else {
categoryCursor.moveToFirst();
categoryValues.put(PostCategoryTable.ICON_NAME, rowCategory.getString("slug"));
categoryValues.put(PostCategoryTable.CATEGORY_NAME, rowCategory.getString("title"));
categoryValues.put(PostCategoryTable.PARENT_ID, rowCategory.getInt("parent"));
parent.getContentResolver().update(PostCategoryContentProvider.CONTENT_URI, categoryValues, PostCategoryTable.CATEGORY_ID + "=" + categoryValues.getAsString(PostCategoryTable.CATEGORY_ID), null);
Updated++;
}
categoryCursor.close();
}
Toast.makeText(parent,"Created : " + "" + Created + " | Updated : " + "" + Updated, Toast.LENGTH_SHORT).show();
if (row.getString("status").equals("publish")) {
ContentValues values = new ContentValues();
values.put(PostTable.POST_ID, row.getString("id"));
values.put(PostTable.CONTENT, Html.fromHtml(row.getString(PostTable.CONTENT)).toString());
values.put(PostTable.EXCERPT, Html.fromHtml(row.getString(PostTable.EXCERPT)).toString());
//image
//imageurl
values.put(PostTable.DATE_MODIFIED, row.getString(PostTable.DATE_MODIFIED));
values.put(PostTable.DATE_PUBLISHED, row.getString(PostTable.DATE_PUBLISHED));
//thumbnail
//thumbnailurl
values.put(PostTable.TITLE, row.getString(PostTable.TITLE));
values.put(PostTable.URL, row.getString("online-url"));
values.put(PostTable.VIDEO_URL, row.getString("video-url"));
//Check for new Categories
//getThumbnail
// byte[] image = AppHelper.getBlobFromURL(row.getString(BlogTable.THUMBNAIL));
// if (image != null) {
//
// values.put(BlogTable.THUMBNAIL, image);
//
// }
Cursor c = parent.getContentResolver().query(PostContentProvider.CONTENT_URI, null, PostTable.POST_ID + "=" + values.getAsString(PostTable.POST_ID), null, null);
int count = c.getCount();
if (count == 0) {
parent.getContentResolver().insert(PostContentProvider.CONTENT_URI, values);
}
else {
c.moveToFirst();
if (!(c.getString(c.getColumnIndex(PostTable.DATE_MODIFIED)).equalsIgnoreCase(values.getAsString(PostTable.DATE_MODIFIED)))) {
//
//
// if (c.getString(c.getColumnIndex(BlogTable.THUMBNAIL)) != values.get(BlogTable.THUMBNAIL)){
// //reset image
// }
//
parent.getContentResolver().update(PostContentProvider.CONTENT_URI, values, PostTable.POST_ID + "=" + values.getAsString(PostTable.POST_ID), null);
}
}
c.close();
//Here we should last retrieved time and used as part of the condition before retrieving data
}
else {
String currentID = row.getString("id");
// Delete unpublished fields
parent.getContentResolver().delete(PostContentProvider.CONTENT_URI, "_id = " + currentID, null);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
else {
Toast toast = Toast.makeText( parent , "You are not connected to the internet. Please check your connection, or try again later",
Toast.LENGTH_SHORT);
toast.show();
}
// Call onRefreshComplete when the list has been refreshed.
pullToRefreshView.onRefreshComplete();
super.onPostExecute(result);
ImageView refreshButton = (ImageView) parent.findViewById(R.id.kpmg_actionbar_image_refresh_list);
refreshButton.setImageResource(R.drawable.kpmg_actionbar_refresh);
if (showProgressDialog) {
dialog.dismiss();
}
}
}
private void fillData(boolean isRefresh){
//_id is expected from this method that is why we used it earlier
String[] from = new String[] { PostTable.TITLE, PostTable.DATE_PUBLISHED, PostTable.EXCERPT};
int[] to = new int[] { R.id.kpmg_text_news_title, R.id.kpmg_text_news_date, R.id.kpmg_text_news_excerpt};
//initialize loader to call this class with a callback
if (!isRefresh){
getLoaderManager().initLoader(0, null, this);
}
else {
if (searchBox.getText().length() == 0) {
getLoaderManager().restartLoader(0, null, this);
}
else {
getLoaderManager().restartLoader(0, args, this);
}
}
//We create adapter to fill list with data, but we don't provide any data as it will be done by loader
adapter = new SimpleCursorAdapter(parent, R.layout.kpmg_list_view, null, from, to, 0);
adapter.setViewBinder(new SimpleCursorAdapter.ViewBinder() {
#Override
public boolean setViewValue(View view, Cursor cursor, int column) {
if( column == cursor.getColumnIndex(PostTable.DATE_PUBLISHED) ){ // let's suppose that the column 0 is the date
TextView textDate = (TextView) view.findViewById(R.id.kpmg_text_news_date);
String dateStr = cursor.getString(cursor.getColumnIndex(PostTable.DATE_PUBLISHED));
String formattedDate = AppHelper.calculateRelativeDate(dateStr);
textDate.setText( "Posted - " + formattedDate);
return true;
}
return false;
}
});
setListAdapter(adapter);
}
private void filterData(CharSequence cs){
args.putString("Selection", cs.toString());
getLoaderManager().restartLoader(0, args, this /*LoaderCallbacks<Cursor>*/);
}
#Override
public Loader<Cursor> onCreateLoader(int arg0, Bundle args) {
String[] projection = new String[] { PostTable.TITLE, PostTable.DATE_PUBLISHED, PostTable.EXCERPT, PostTable.ID };
CursorLoader loader;
if (args == null) {
Log.i("Arguments","None");
loader = new CursorLoader(parent, PostContentProvider.CONTENT_URI, projection, null, null, PostTable.DATE_PUBLISHED + " DESC");
}
else {
Log.i("Arguments","Full");
String selectionKeyword = args.getString("Selection");
String selection = PostTable.TITLE + " LIKE ? OR " + PostTable.CONTENT + " LIKE ? OR " + PostTable.EXCERPT + " LIKE ?";
String[] selectionArgs = new String[] {"%" + selectionKeyword + "%","%" + selectionKeyword + "%","%" + selectionKeyword + "%"};
loader = new CursorLoader(parent, PostContentProvider.CONTENT_URI, projection, selection, selectionArgs, PostTable.DATE_PUBLISHED + " DESC");
}
return loader;
}
public void onLoadFinished(Loader<Cursor> arg0, Cursor data) {
adapter.swapCursor(data);
}
public void onLoaderReset(Loader<Cursor> arg0) {
adapter.swapCursor(null);
}
}
On which line is the exception thrown? The problem is more likely an issue with your SQLite syntax than with anything having to do with Loaders or Cursors. Make sure your table is getting initialized as you require. Do a DatabaseUtils.dumpCursor(cursor) to analyze the contents of the Cursor between the exception is thrown. Also, I would look into your use of LIKE... I have seen people having issues with that keyword before.

onListItemClick that shows description toast when title is clicked

not sure if I am on the correct section, but I needed help for my school project.
Currently I am doing a listview that display the titles of the latest school news, whenever I click any of the title, I want it to toast the description of the selected title correspondingly.
Anyone can help me on it? Thank you
package sp.buzz.rss;
import java.util.ArrayList;
import android.app.ListActivity;
import android.os.Bundle;
import android.util.EventLogTags.Description;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
import sp.buzz.rss.tools.*;
public class StringRss extends ListActivity {
HttpFetch a = new HttpFetch();
/** Called when the activity is first created. */
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
String strOrg = a
.DownloadText("http://www.sp.edu.sg/wps/wcm/connect/lib-spws/Site-SPWebsite/?srv=cmpnt&source=library&cmpntname=MNU-MobileRSSFeed-SPBuzz-Shine");
int start = strOrg.indexOf("<title>");
int end = strOrg.indexOf("</title>");
int startdesc = strOrg.indexOf("<![CDATA[");
int enddesc = strOrg.indexOf("]]>");
int count = 0;
ArrayList<String> value = new ArrayList();
ArrayList<String> cData = new ArrayList();
String title = strOrg.substring(start + 7, end);
String description = strOrg.substring(startdesc + 9, enddesc);
// Toast.makeText(this, title, Toast.LENGTH_LONG).show();// first title
Toast.makeText(this, description, Toast.LENGTH_LONG).show();// first
// desc
// value.add(title);
// count++;
cData.add(description);
String newContent = strOrg.substring(end + 5);
String newDesc = strOrg.substring(enddesc + 3);
start = newContent.indexOf("<title>");
end = newContent.indexOf("</title>");
startdesc = newDesc.indexOf("<![CDATA[");
enddesc = newDesc.indexOf("]]>");
title = newContent.substring(start + 7, end);
description = newDesc.substring(startdesc + 9, enddesc);
// Toast.makeText(this, title, Toast.LENGTH_LONG).show();// second title
Toast.makeText(this, description, Toast.LENGTH_LONG).show();// second
// desc
value.add(title);
cData.add(description);
count++;
while (true) {
newContent = newContent.substring(end + 5);
newDesc = newDesc.substring(enddesc + 3);
start = newContent.indexOf("<title>");
end = newContent.indexOf("</title>");
startdesc = newDesc.indexOf("<![CDATA[");
enddesc = newDesc.indexOf("]]>");
if (start == -1 || end == -1) {
break;
} else if (startdesc == -1 || enddesc == -1) {
break;
}
title = newContent.substring(start + 7, end);
description = newDesc.substring(startdesc + 9, enddesc);
// Toast.makeText(this, description, Toast.LENGTH_LONG).show();//
// for
count++;
value.add(title);
cData.add(description);
/*
* Toast.makeText(this, "Value array: " + title, Toast.LENGTH_LONG)
* .show();// for debugging
*/
// Toast.makeText(this, description, Toast.LENGTH_LONG).show();//
// for
// description
}
// Create an array of Strings, that will be put to our ListActivity
String[] names = new String[count];
String[] desc = new String[count];
// Create an ArrayAdapter, that will actually make the Strings above
// appear in the ListView
for (int i = 0; i < names.length; i++) {
names[i] = value.get(i);
}
for (int i = 0; i < desc.length; i++) {
desc[i] = cData.get(i).replaceAll("</P>", "\n")
.replaceAll("<P>", "");
}
this.setListAdapter(new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, names));
}
static String title = "";
static String desc = "";
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
// Get the item that was clicked
Object o = this.getListAdapter().getItem(position);
title = o.toString();
Toast.makeText(this, "You selected: " + title, Toast.LENGTH_LONG)
.show();
}
}
You can replace the method protected void onListItemClick with by putting into onCreate the code below. If it isn't working.
ListView lv = getListView();
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
String title = ((TextView) view).getText();
Toast.makeText(this, "You selected: " + title, Toast.LENGTH_LONG)
.show();
}});
Also I'm surprised that infinite while loop is working. You should do that part using threading otherwise the later parts of the method won't be reached.
String title = (String) parent.getItemAtPosition(position);
Toast.makeText(this, "You selected: " + title, Toast.LENGTH_LONG)
.show();

Categories

Resources