Android Studio Error "Cannot resolve method for method .add" - java

I know this question is asked a lot, but I am genuinely stumped, I have looked at other methods, and tried everything...
My coding problem is as follows, I have a public class in java, and I made a string array in the global scope. I tried to add to it using array.add("somestringhere"), but it spits out an error saying (the title)... One more thing to note is this class is inside the main class for the file. so let's see if I can show it here:
public class see_schedule_activity extends AppCompatActivity {
.
..
.
.
.
// you can make this class as another java file so it will be separated from your main activity.
public class AsyncTaskParseJson extends AsyncTask<String, String, String> {
final String TAG = "AsyncTaskParseJson.java";
// set your json string url here
String yourJsonStringUrl = "http://www.xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxphp";
// contacts JSONArray
JSONArray dataJsonArr = null;
#Override
protected void onPreExecute() {
}
#Override
protected String doInBackground(String... arg0) {
try {
// I have a intent passed from teh main class
Bundle extras = getIntent().getExtras();
String[] tasks = extras.getStringArray("tasks");
// instantiate our json parser
JsonParser jParser = new JsonParser();
// get json string from url
JSONObject json = jParser.getJSONFromUrl(yourJsonStringUrl);
// get the array of users
dataJsonArr = json.getJSONArray("schedule");
// loop through all users
for (int i = 0; i < dataJsonArr.length(); i++) {
JSONObject c = dataJsonArr.getJSONObject(i);
// Storing each json item in variable
activityid = c.getString("activityid");
String yesno = c.getString("yesno");
String start = c.getString("start");
String stop = c.getString("stop");
String plusminus = c.getString("plusminus");
Log.e("Hash Map", "Routine ID #" + activityid);
if (!TextUtils.isEmpty(activityid) && TextUtils.isDigitsOnly(activityid)) {
routine = hm.get(Integer.valueOf(activityid));
} else {
routine = "";
}
// TODO: Make the PHP work with a variable residentID
//TODO: only make a string if the yes is checked
//TODO: make the routine name
// Log.e(TAG, "Value for yesno:" + yesno);
if (c.getString("yesno").equals("Yes")) {
schedule = routine + " starts at " + start + " and ends at " + stop + " with plusorminus " +
plusminus + " minutes ";
tasks.add(schedule);// This lines yeilds the problem
Log.e(TAG, "" + schedule);
}
// // show the values in our logcat
// Log.e(TAG, "activityid: " + activityid
// + ", yesno: " + yesno
// + ", start: " + start
// + ", stop: " + stop
// + ", plusminus: " + plusminus);
}
Intent intent = new Intent(getApplicationContext(),see_schedule_activity.class);
intent.putExtra("tasks_filled",tasks);
startActivity(intent);
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String strFromDoInBg) {
}
}
I would appreciate any help, I'm a newb to programming and android studio, and php..so yeah thanks in advance, Justin

tasks is an String array as you defined
String[] tasks = extras.getStringArray("tasks");
And Array doesn't have any add method.
You need to convert tasks to a list like following
List<String> list = Arrays.asList(tasks);
Then you can use list.add(schedule)

Related

How to return 2 values from one method and use both values in one class?

I'm trying out this code from Microsoft, however I wanted to combine the 2 features they made. One is analyzing image and one is detecting celebrities. However, I'm having a hard time on how will I return 2 values from one function.
Here is the process method...
private String process() throws VisionServiceException, IOException {
Gson gson = new Gson();
String model = "celebrities";
ByteArrayOutputStream output = new ByteArrayOutputStream();
bitmapPicture.compress(Bitmap.CompressFormat.JPEG, 100, output);
ByteArrayInputStream inputStream = new ByteArrayInputStream(output.toByteArray());
AnalysisResult v = this.client.describe(inputStream, 1);
AnalysisInDomainResult m = this.client.analyzeImageInDomain(inputStream,model);
String result = gson.toJson(v);
String result2 = gson.toJson(m);
Log.d("result", result);
return result, result2;
}
And combine the 2 results with this method...
#Override
protected void onPostExecute(String data) {
super.onPostExecute(data);
mEditText.setText("");
if (e != null) {
mEditText.setText("Error: " + e.getMessage());
this.e = null;
} else {
Gson gson = new Gson();
AnalysisResult result = gson.fromJson(data, AnalysisResult.class);
//pang detect ng peymus...
AnalysisInDomainResult result2 = gson.fromJson(data, AnalysisInDomainResult.class);
//decode the returned result
JsonArray detectedCelebs = result2.result.get("celebrities").getAsJsonArray();
if(result2.result != null){
mEditText.append("Celebrities detected: "+detectedCelebs.size()+"\n");
for(JsonElement celebElement: detectedCelebs) {
JsonObject celeb = celebElement.getAsJsonObject();
mEditText.append("Name: "+celeb.get("name").getAsString() +", score" +
celeb.get("confidence").getAsString() +"\n");
}
}else {
for (Caption caption: result.description.captions) {
mEditText.append("Your seeing " + caption.text + ", confidence: " + caption.confidence + "\n");
}
mEditText.append("\n");
}
/* for (String tag: result.description.tags) {
mEditText.append("Tag: " + tag + "\n");
}
mEditText.append("\n");
mEditText.append("\n--- Raw Data ---\n\n");
mEditText.append(data);*/
mEditText.setSelection(0);
}
}
Thanks in advance!
you can use. the parameter are two objects so can you can put everything
final Pair<String, String> pair = Pair.create("1", "2");
String a = pair.first;
String b = pair.second;
Simply use Bundle
Bundle bundle = new Bundle();
bundle.putString("key_one", "your_first_value");
bundle.putString("key_two", "your_second_value");
return bundle;
You can add multiple values with different types in Bundle.In this case your method's return type should be Bundle.
or AbstractMap#SimpleEntry (or as of Java-9 Map#entry)
You can always return two values via Arrays.asList(one, two) also

Populate JSON data to ListView

I am trying to display a retrieved data from MySQL database with the help of Volley, and populate it into a ListView.
So far as I tried every method I am unable to do it.
JsonArrayRequest req = new JsonArrayRequest(urlJsonArry, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d("TAG", response.toString());
try {
ArrayList<HashMap<String, String>> authorList = new ArrayList<>();
for (int i = 0; i < response.length(); i++) {
JSONObject obj = (JSONObject) response.get(i);
String username = obj.getString("username");
String email = obj.getString("email");
String password = obj.getString("password");
usernameAll += "UserName: " + username + "\n\n";
emailAll += "Email: " + email + "\n\n";
passwordAll += "Password: " + password + "\n\n";
}
As I have retrieved 'username', 'email', and 'password' I can successfully show it in TextView by myTextView.setText(usernameAll + " " + ..);. But for now I just want to print/populate 'username' in Simple ListView
HashMap<String, String> myData = new HashMap<>();
myData.put("justKey", usernameAll);
adapter1 = new ArrayAdapter<String>(getApplicationContext(), android.R.layout.simple_list_item_1, android.R.id.text1, myData);
listView.setAdapter(adapter1);
When I take some Array and call that array it works but why myData isn't working. Can you please help me understanding the actual problem.
My next step will be to use the Custom ListView but now I am eager "how actually stuff works"
I will really appreciate if you correct my approach of solving this problem.
Thank You.
PS: I am getting this error from Android Studio 2.1.2:
Cannot resolve constructor 'ArrayAdapter(android.content.Context, int,
int, java.lang.String)'
u can't pass hashmap to the array adapter
https://developer.android.com/reference/android/widget/ArrayAdapter.html
convert it to the list as mentioned in the documentation also
//Code Getting Collection of values from HashMap
Collection<String> values = myData.values();
//Creating an ArrayList of values
ArrayList<String> listOfValues = new ArrayList<String>(values);
For details check out the link below
http://javaconceptoftheday.com/how-to-convert-hashmap-to-arraylist-in-java/

Get View from Listview to String

I have a Listview and I need to get the String values of each row when I click the List view.
This is my code
public void ListDrwaer() {
List<Map<String, String>> employeeList = new ArrayList<Map<String, String>>();
try {
JSONObject jsonResponse = new JSONObject(jsonResult);
JSONArray jsonMainNode = jsonResponse.optJSONArray("lectureraccount");
for (int i = 0; i < jsonMainNode.length(); i++) {
JSONObject jsonChildNode = jsonMainNode.getJSONObject(i);
String name = jsonChildNode.optString("lecturerName");
String code = jsonChildNode.optString("lecturerCode");
String outPut = name + " --- " + code;
employeeList.add(createEmployee("lecturer", outPut));
}
} catch (JSONException e) {
Toast.makeText(getApplicationContext(), "Error" + e.toString(),
Toast.LENGTH_SHORT).show();
}
SimpleAdapter simpleAdapter = new SimpleAdapter(this, employeeList,android.R.layout.simple_list_item_1,new String[] { "lecturer" }, new int[] { android.R.id.text1 });
listView.setAdapter(simpleAdapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,int position, long id)
{
String str = parent.getAdapter().getItem(position).toString();
System.out.println(str);
}});
}
I Managed to get output like this.
{lecturer=MAGESWARY A/P MUNIANDI --- C-MAGESWARY}
My Question is how to get output like this
C-MAGESWARY
Thats all. I am new in programming and not know much. Do i need to change my code completly. If it is, How?
Thank you.
You can do this using split in your onItemClick method as below:
String str = parent.getAdapter().getItem(position).toString();
String[] parts = str.split("---");
String part1 = parts[0];
String part2 = parts[1]; // This is the part you want
String output = part2.replaceAll("\\s+","") //trim whitespace
String output2 = output.replace("}", ""); // remove the "}" character
System.out.println(output2);
Output:
C-MAGESWARY
This is a Java question. Look at link Class String Oracle. Besides the previous answer, look at methods substring, indexOf, and lastIndexof.
You can make it easy on yourself since you have control of the string format in your ListView. Simply add unique characters before your example "C-MAGESWARY", like "!#" . Then you can search the string for those characters. Remember this technique for future apps.

Android - Output List of events from Google calendar

I would ask You for a help. Now I am writing an app, which takes current events from Google calendars. But problem is there, when I'm trying to output events from more than one calendar. I know, that I'm doing something wrong, but really, can't get in the problem..
public class Main extends Activity {
//TextView mInfo;
TextView mEvents;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//mInfo = (TextView)findViewById(R.id.info);
mEvents = (TextView)findViewById(R.id.events);
String[] calendarName = {"Calendar1", "Calendar2", "Calendar3", "Calendar4", "Calendar5"};
readCalendars(calendarName);
}
private void readCalendars(String[] calendarName)
{
String[] projection =
new String[]{
CalendarContract.Calendars._ID,
CalendarContract.Calendars.NAME,
CalendarContract.Calendars.ACCOUNT_NAME,
CalendarContract.Calendars.ACCOUNT_TYPE};
Cursor calCursor =
getContentResolver().
query(CalendarContract.Calendars.CONTENT_URI,
projection,
CalendarContract.Calendars.VISIBLE + " = 1",
null,
CalendarContract.Calendars._ID + " ASC");
long calId = -1;
//String calendarAccount = "";
for(int i = 0; i 0)
{
if(cursor.moveToFirst())
{
do
{
long eventId = cursor.getLong(3);
events += getEventInfo(eventId,cursor.getLong(1),cursor.getLong(2),cursor.getString(4),cursor.getString(5),cursor.getString(6)) + "\n";
} while(cursor.moveToNext());
}
}
mEvents.setText(events);
}
}
#SuppressLint("SimpleDateFormat")
private String getEventInfo(long eventId,long startTime, long endTime,String description, String location,String title)
{
String eventInfo = "";
{
DateFormat df = new SimpleDateFormat("HH:mm");
String start = df.format( new Date(startTime));
String end = df.format( new Date(endTime));
eventInfo = start + "-" + end + " Class: "+ location + "\nLecture: " + title + "\nLecturer: " + description;
}
return eventInfo;
}
}
Tried to output all events with loop, but does not helps. If I pass in calendarName[i], where i is one of existing calendars, I get output of calendar, which I asked for, but that's only one calendar, but for example, I need to output 5 calendars.
Tried to do anything with ListView - failure again.
Hope, You would help with this problem or help somehow how to resolve it..
The CalendarContract.Calendars.CONTENT_URI can be used to retrieve calendars, but not actual events for those calendars. Once you have the calendar id, you must use either of the following URIs for event information:
CalendarContract.Events.CONTENT_URI
CalendarContract.Instances.CONTENT_URI

set "constant" after the fact

I'm wanting to set a final variable after starting the constant. This works if the variable is not final, but that kind of defeats the purpose.
Can I do something similar to this?
public static final String ASDF = null;
{
ASDF = "asdf";
}
My situation:
public static JSONArray CATEGORIES = null;
{
String str = "";
str += "\"" + FIRST_CATEGORY + "\"";
try {
CATEGORIES = new JSONArray("[" + str + "]");
} catch (JSONException e) {
e.printStackTrace();
}
};
You can use a static initialization block - at least, you can in regular Java SE (I'm assuing android can too):
public static final JSONArray CATEGORIES;
static {
String str = "\"" + FIRST_CATEGORY + "\"";
try {
CATEGORIES = new JSONArray("[" + str + "]");
} catch (JSONException e) {
e.printStackTrace();
}
}
Note that you are not first intializing CATEGORIES to null, it is left uninitialized until the static block happens.
Although, you're probably going to want to hard-fail if the intialization generates an exception, because otherwise you'll have an improperly initialized variable (serious problems possible).
And, unless the JSONArray class is immutable, declaring the instance final is ~sorta pointless.
Figured it out. I'm not exactly sure what's going on here, but it works.
public static final JSONArray CATEGORIES = new JSONArray() {
{
put(FIRST_CATEGORY);
// etc eg. put(SECOND_CATEGORY);
}
};
you can choose to not include "= null" on your variable declaration. just make sure that you assign a value to your variable once - be it inside an if-else, a loop, or whatever - the compiler will detect if you're breaking this rule, and won't let your program compile.
public static JSONArray CATEGORIES = null;
{
String str;
str += "\"" + FIRST_CATEGORY + "\"";
try {
CATEGORIES = new JSONArray("[" + str + "]");
} catch (JSONException e) {
e.printStackTrace();
}
};

Categories