I have an activity that creates a list based on a list of series values returned by an http request. If the list includes a list of places, I call the next activity and pass some values through intents. However, if the response does not include a list of places, I need to repopulate my activity with a new list of series values, but I'm not sure how to call the same activity within the activity I'm already in. My attempt is below.
EDIT: the goal of refreshing the activity is to make an https request with new parameters in the url. I tried just recalling the http request earlier, but had no luck
protected void onPostExecute(JSONObject result){
ArrayList<String> modelNames = new ArrayList<>();
Log.d("JSON RESPONSE", result.toString());
final ArrayList<JSONObject> modelsObjectList = new ArrayList<>();
try {
JSONObject info = result.getJSONObject("info");
JSONArray models = info.getJSONArray("models");
for(int i = 0; i < models.length(); i++){
modelsObjectList.add(models.getJSONObject(i));
}
for(int i = 0; i < modelsObjectList.size(); i++){
modelNames.add(modelsObjectList.get(i).getString("name"));
}
} catch(JSONException e ){
Log.d("JSONEXCEPTION", e.getMessage().toString());
}
//TODO found problem, model names for whatever reason is passing in the names from previous activity
Log.d("MODEL NAMES", modelNames.toString());
Toast.makeText(AfterDestinationActivity.this, modelNames.toString(), Toast.LENGTH_LONG).show();
mList = (ListView) findViewById(android.R.id.list);
CustomMainAdapter mainAdapter = new CustomMainAdapter(AfterDestinationActivity.this, modelNames);
mList.setAdapter(mainAdapter);
setProgressBarIndeterminateVisibility(false);
mList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
String name;
Long id;
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
JSONObject passingObject = modelsObjectList.get(position);
ArrayList<String> nextPlacesList = new ArrayList<>();
Log.d("AD OBJECT PRESSED ON", passingObject.toString());
//TODO found issues with debugging
try {
JSONArray places;
JSONArray series = passingObject.getJSONArray("series");
name = passingObject.getString("name");
id = passingObject.getLong("id");
Log.d("NEXT ACTIVITY NAME", name);
System.out.println("NEXT ACTIVITY ID " + id);
Log.d("NEXT SERIES LIST", nextPlacesList.toString());
//if there are no places, launch http request again for series
if(passingObject.optJSONArray("places") == null){
ArrayList<String> sameSeries = new ArrayList();
System.out.println("WENT INTO FOR LOOP");
for(int i = 0; i < series.length(); i++){
sameSeries.add(series.getString(i));
Log.d("AD FOR LOOP SERIES", series.getString(i));
}
Intent refreshActivity = new Intent(AfterDestinationActivity.this, AfterDestinationActivity.class);
refreshActivity.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
refreshActivity.putExtra("id", id);
refreshActivity.putExtra("name", name);
refreshActivity.putExtra("placesList", nextPlacesList);
Log.v("RESTARTING ACTIVIY", "activity restating");
startActivity(refreshActivity);
}
} catch(JSONException e){
Log.d("JSONEXCEPTION", "IN THERE " + e.getMessage());
}
Intent intent = new Intent(AfterDestinationActivity.this, PlacesListActivity.class);
intent.putExtra("id", id);
intent.putExtra("name", name);
intent.putExtra("placesList", nextPlacesList);
startActivity(intent);
}
});
}
Simply use this,
add this in your manifest,
<activity android:name=".StartActivity" android:label="#string/app_name"
android:clearTaskOnLaunch="true">
</activity>
From JAVA code use this,
Intent refreshActivity = new Intent(AfterDestinationActivity.this, AfterDestinationActivity.class);
refreshActivity.putExtra("id", id);
refreshActivity.putExtra("name", name);
refreshActivity.putExtra("placesList", nextPlacesList);
Log.v("RESTARTING ACTIVIY", "activity restarting");
startActivity(refreshActivity);
You don't need to call the same activity. Just update the corresponding views with the new values in your activity.
I would access it via the "this pointer" or an interface:
EDIT
MyActivity extends Activity implements IUpdateListener
{
public void onCreate(Bundle onSaveInstanceState)
{
//code
}
#Override
void onUpdate(Result result)
{
//update data or do other stuff - like start another activity or populate urs.
}
}
Next The AsynTask:
MyAsyncTask extends AsyncTask<Void, Void, Result>
{
private IUpdateListener listener;
public MyAsyncTask(IUpdateListener listener)
{
this.listener = listener;
}
Result doInBackground(Void.. voids)
{
//http request and parse - an object Result
return result data;
}
void onPostExecute(Result result)
{
if(result!=null) - or other operation u want
{
listener.OnUpdate(result) - or other stuff you want.
}
}
Next the interface:
interface IOnUpdateListener
{
onUpdate(Result result);
}
"this pointer":
How can I access my Activity's instance variables from within an AlertDialog's onClickListener?
I hope I was clear enough.
Related
This question already has answers here:
Passing JSONObject into another activity
(7 answers)
Closed 6 years ago.
public class MainActivity extends **strong text**
AppCompatActivity {
private String TAG = MainActivity.class.getSimpleName();
private ListView lv;
ArrayList<HashMap<String, String>> companyList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
companyList = new ArrayList<>();
lv = (ListView) findViewById(R.id.list_row_xml);
new GetCompany().execute();
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
Intent i = new Intent(MainActivity.this, SingleView.class);
i.putExtra("venue", venue);
startActivity(i);
}
});
}
private class GetCompany extends AsyncTask<Void, Void, JSONObject> {
#Override
protected void onPreExecute() {
super.onPreExecute();
Toast.makeText(MainActivity.this,"Json Data is downloading",Toast.LENGTH_LONG).show();
}
#RequiresApi(api = Build.VERSION_CODES.KITKAT)
#Override
protected JSONObject doInBackground(Void... arg0) {
HttpHandler sh = new HttpHandler();
// Making a request to url and getting response
String url = "http://10.0.2.2:6060/api/v1/company/getInfo?limit=10&page=1";
JSONArray company = sh.makeServiceCall(url);
Log.e(TAG, "Response from url: " + company);
if (company != null) {
try {
// JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
//JSONArray company = new JSONArray(jsonStr);
// System.out.println("Reached");
// looping through All Contacts
for (int i = 0; i < company.length(); i++) {
//System.out.println("Reached1");
JSONObject c = company.getJSONObject(i);
String id = c.getString("id");
String name = c.getString("companyName");
// Walking Details in Json object
JSONObject walkingDetails=c.getJSONObject("walkingdetails");
String date = walkingDetails.getString("walkingdate");
String venue = walkingDetails.getString("venu");
// tmp hash map for single contact
HashMap<String, String> companyy = new HashMap<>();
// adding each child node to HashMap key => value
companyy.put("id",id);
companyy.put("date", date);
companyy.put("companyname", name);
companyy.put("venue", venue);
// adding contact to contact list
companyList.add(companyy);
}
} catch (final JSONException e) {
Log.e(TAG, "Json parsing error: " + e.getMessage());
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(), "Json parsing error: " + e.getMessage(), Toast.LENGTH_LONG).show();
}
});
}
} else {
Log.e(TAG, "Couldn't get json from server.");
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(), "Couldn't get json from server. Check LogCat for possible errors!", Toast.LENGTH_LONG).show();
}
});
}
return null;
}
/* #Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
ListAdapter adapter = new SimpleAdapter(MainActivity.this, companyList,
R.layout.list_row, new String[]{"date","companyname","venue"}, new int[]{ R.id.date, R.id.companyname, venue});
lv.setAdapter(adapter);*/
}
}
second acivity:
public class SingleView extends AppCompatActivity {
EditText txtVenue;
// String[] Venue;
int position;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_single_view);
Intent i = getIntent();
position = i.getExtras().getInt("positi`enter code here`on");
txtVenue = (EditText) findViewById(R.id.Venue);
}
}
You can not pass directly JSONObject to another activity. But you can convert json to string and pass it. Then in SecondActivity you can convert it to json again.
Start SecondActivity codes in FirstActivity:
Intent intent = new Intent(FirstActivity.this, SecondActivity.class);
intent.putExtra("data", json.toString());
startActivity(intent);
Then get this data from SecondActivity:
String data = getIntent().getStringExtra("data");
try {
JSONObject json = new JSONObject(data);
} catch (JSONException e) {
e.printStackTrace();
}
Good luck.
You can achieve by creating your own class by extending the JSONObject and implementing Serializable interface. So that you can pass through the intent.
You have 2 options:
1. Convert json to string and pass as string.
2. Make model class for json , make it parcelable. Pass this object to next activity.
HashMaps do not preserve ordering.
Better use a model class, it would also be easy to retrieve data.
public class CompanyData {
public String id;
public String date;
public String name;
public String venue;
}
then change arraylist,
ArrayList<CompanyData> companyList;
then store values,
CompanyData companyy = new CompanyData();
companyy.id = id;
companyy.date = date;
companyy.name = name;
companyy.venue = venue;
companyList.add(companyy);
then implement onitemclicklistener,
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
CompanyData data = companyList.get(position);
Intent i = new Intent(MainActivity.this, SingleView.class);
i.putExtra("venue", data.venue);
startActivity(i);
}
});
***To get position simply send position value inside onItemClickListener
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
CompanyData data = companyList.get(position);
Intent i = new Intent(MainActivity.this, SingleView.class);
i.putExtra("position", position);
startActivity(i);
}
});
You can also send all data of a specific position by
CompanyData data = companyList.get(position);
i.putExtra("data", data); //this will pass all data of clicked row
I use bundle before but it only return null,
how can i get the name of the student_name that populated from database using json of the clicked item and show it into new activity?
public void ListDrawer() {
final List<Map<String, String>> studentList = new ArrayList<Map<String, String>>();
try {
JSONObject jsonResponse = new JSONObject(jsonResult);
JSONArray jsonMainNode = jsonResponse.optJSONArray("student_info");
for (int i = 0; i < jsonMainNode.length(); i++) {
JSONObject jsonChildNode = jsonMainNode.getJSONObject(i);
String name = jsonChildNode.optString("student_name");
String number = jsonChildNode.optString("student_id");
String outPut = name + "-" + number;
studentList.add(createStudent("Students", outPut));
}
} catch (JSONException e) {
Toast.makeText(getApplicationContext(), "Error" + e.toString(),
Toast.LENGTH_SHORT).show();
}
////////////////////////////////// UPDATE LISTVIEW ITEMS ONCLICK
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//Do your logic for getting the student variables here
Intent intent = new Intent(MainPage.this,Profile.class);
intent.putExtra("student ", String.valueOf(id));
startActivity(intent);
}
});
//////////////////////////////////////UPDATE
SimpleAdapter simpleAdapter = new SimpleAdapter(this, studentList,
android.R.layout.simple_list_item_1,
new String[] { "Students" }, new int[] { android.R.id.text1 });
listView.setAdapter(simpleAdapter);
Toast.makeText(getApplication(), "Logged in Successfully", Toast.LENGTH_SHORT).show();
Above is mylistview and my onItemClicked function
i use json to retrieve the list of students from mysql and view it in listview and now im trying to pass data from the selected student in listview to new activity
[1]: http://i.stack.imgur.com/zc56O.jpg
To add on #brahmyadigopula comment, using POJO is way more simpler and if you are already using JSON as preferd way, you can use Googles library for transforming JSON strings in to Objects with one line of code.
https://github.com/google/gson
Then you can just transform the object into JSON String with the same library and pass it through the Intent as String and 'catch' it in the Activity as a string and transform it back to an Object and use it as you'd wish.
It would look something like this:
public class User {
private String name;
private String number;
(getters/setters)
}
And then in your adapter you would do:
User user = new Gson().fromJson(jsonMainNode, User.class);
so you can then have a cleaner code when getting the data. So when passing the data with an intent you can just transform the User object to string by doing this: String jsonString = new Gson().toJson(user); and pass it through the intent.
Hope this helps.
For your adapter, you're using "android.R.layout.simple_list_item_1" as a layout for your list items. This will give you a simple TextView as a result and this TextView will contain the whole student information (name-number) as a full String variable.
I have 3 solutions for your problem :
1- Get the text of the item TextView and use split function to get the students info as follows :
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//Get the item full text content
String studentInfo = listView.getItemAtPosition(position).toString();
//Split using the space " "
ArrayList<String> studentInfoArray = new ArrayList<>(Arrays.asList(studentInfo.split(" ")));
//Split using the dash "-"
String lastObject = studentInfoArray.get(studentInfoArray.size() - 1);
ArrayList<String> lastObjectInfoArray = new ArrayList<>(Arrays.asList(lastObject.split("-")));
//Rearrange the student name
//Sometimes the name is composed of more than two words
String studentName = "";
for (int i = 0; i < studentInfoArray.size() - 1; i++) {
studentName += " " + studentInfoArray.get(i);
}
studentName += " " + lastObjectInfoArray.get(0);
//Create the intent to start the Profile activity
//Add student info to extras
Intent intent = new Intent(MainPage.this,Profile.class);
intent.putExtra("studentName", studentName);
intent.putExtra("studentID", lastObjectInfoArray.get(lastObjectInfoArray.size() - 1));
startActivity(intent);
}
});
2- Create a custom layout for your ListView adapter that will contain 2 TextViews in a LinearLayout, One for the name and One for the number. Then, you can easily get each info separately like this :
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//Get the list item subviews using IDs of the custom item layout
TextView tvStudentName = (TextView)view.findViewById(R.id.tvStudentName);
TextView tvStudentNumber = (TextView)view.findViewById(R.id.tvStudentNumber);
//Create the intent to start the Profile activity
//Add student info to extras
Intent intent = new Intent(MainPage.this,Profile.class);
intent.putExtra("studentName", tvStudentName.getText());
intent.putExtra("studentID", tvStudentNumber.getText());
startActivity(intent);
}
});
3- Make your student list as a global variable, then just get the info directly from the array :
public class MainPage extends Activity {
//Declare studentList as a global variable
List<Map<String, String>> studentList = new ArrayList<>();
.
.
.
//Change the structure of your ListDrawer method
public void ListDrawer() {
try {
JSONObject jsonResponse = new JSONObject(jsonResult);
JSONArray jsonMainNode = jsonResponse.optJSONArray("student_info");
for (int i = 0; i < jsonMainNode.length(); i++) {
JSONObject jsonChildNode = jsonMainNode.getJSONObject(i);
String name = jsonChildNode.optString("student_name");
String number = jsonChildNode.optString("student_id");
//Add the student info to a new Hashmap object
//Add the student to the array
Map<String, String> studentInfo = new HashMap<>();
studentInfo.put("student_name", name);
studentInfo.put("student_id", number);
studentList.add(i, studentInfo);
}
} catch (JSONException e) {
Toast.makeText(getApplicationContext(), "Error" + e.toString(),
Toast.LENGTH_SHORT).show();
}
}
}
Then, send data to Profile activity :
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//Create the intent to start the Profile activity
//Add student info to extras
Intent intent = new Intent(MainPage.this,Profile.class);
intent.putExtra("studentName", studentList.get(position).get("student_name"));
intent.putExtra("studentID", studentList.get(position).get("student_id"));
startActivity(intent);
}
});
Finally, to retrieve the info sent from MainPage Activity to Profile Activity :
public class Profile extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
.
.
Log.e("EXTRA", "Student Name : " + getIntent().getExtras().getString("studentName"));
Log.e("EXTRA", "Student ID : " + getIntent().getExtras().getString("studentID"));
}
}
i want to pass the correct json object on the list item click in the first activity to the second activity. If i click any list item, the json object from JSONArray response should be passed to intent and my next activity must get it.
Here is my code
JsonArrayRequest postReq = new JsonArrayRequest(url,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d(TAG, response.toString());
hidePDialog();
// Parsing json
for (int i = 0; i < response.length(); i++) {
try {
JSONObject obj = response.getJSONObject(i);
Consumer user = new Consumer();
user.setTitle(obj.getString("name"));
user.setUserid(obj.getString("user"));
user.setThumbnailUrl(obj.getString("image"));
user.setAmountreq(obj.getString("price"));
user.setTime(obj.getString("date"));
user.setCounty(obj.getString("county"));
// adding request to consumer class
userList.add(user);
} catch (JSONException e) {
e.printStackTrace();
}
}
/*notifying list adapter about data changes
so that it renders the list view with updated data*/
adapter.notifyDataSetChanged();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
hidePDialog();
}
});
// Adding request to request queue
AppController.getInstance().addToRequestQueue(postReq);
// listening to single list item on click
listView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
if(!obj.isNull(position)){
//start new activity
Intent myIntent = new Intent(RequestFeedActivity.this,RequestFeed.class);
myIntent.putExtra("name", obj.getJSONObject(position).toString());
startActivity(myIntent);
}
// ListView Clicked
}
});
}
On the other activity here is my sample code of the variables i want to be passed
TextView rname, rtitle,rprice, rdate, rdesc, rcounty;
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.requestfeed);
rtitle = (TextView)findViewById(R.id.IDRproduct);
rprice = (TextView)findViewById(R.id.IDRquote);
rdate = (TextView)findViewById(R.id.IDRdate);
rdesc = (TextView)findViewById(R.id.IDRdesc);
rname = (TextView)findViewById(R.id.IDRname);
Intent myIntent = getIntent();
//Assign values
rname.setText(myIntent.getExtras().getString("name"));
rtitle.setText(myIntent.getExtras().getString("title"));
rprice.setText(myIntent.getExtras().getString("pricetag"));
rdate.setText(myIntent.getExtras().getString("timereq"));
rdesc.setText(myIntent.getExtras().getString("description"));
rcounty.setText(myIntent.getExtras().getString("county"));
}
I tried this answer but didnt work .Any much help is much appreciated
Try to replace this peace of code:
myIntent.getExtras().getString("name")
With this code:
myIntent.getStringExtra("name");
Just try this
Intent i =new Intent(this,ActivityA.class);
Bundle b =new Bundle();
i.putExtra("KEY","VALUE");
i.putExtras(b);
startActivity(i)
At the receiver side
Bundle b=getIntent().getExtras();
b.getInt("KEY") //useaccording to ur need
If it doesn't work check this answer
I'm having a this error Only the original thread that created a view hierarchy can touch its views.
But i don't know how to handle the ui in multithread, like list view and i don't know where to put it.
// Download JSON in Background
public class DownloadJSONFileAsync extends AsyncTask<String, Void, Void> {
protected void onPreExecute() {
super.onPreExecute();
showDialog(DIALOG_DOWNLOAD_JSON_PROGRESS);
}
#Override
protected Void doInBackground(String... params) {
deviceId = generateDeviceId();
elementsList.add(new BasicNameValuePair("DeviceID", deviceId));
JSONObject json = jsonParser.makeHttpRequest(
url_get_reports, "POST", elementsList);
Log.d("Create Response", json.toString());
// check for success tag
try {
int success = json.getInt(TAG_SUCCESS_REPORT);
// successfully created
// getting JSON string from URL
try {
if (success == 1) {
reports = json.getJSONArray(TAG_Report);
report_data = new Report[reports.length()];
// looping through All Products
for (int i = reports.length()-1; i >= 0; i--) {
JSONObject c = reports.getJSONObject(i);
reportID = c.getString("reportID");
Drawable drawable = LoadImageFromWeb(url+c.getString(TAG_IMAGE));
String state = "";
if(c.getString("state").equals("1")){
state = "Pinding";
}else if(c.getString("state").equals("2")){
state = "Inprogress";
}else{
state = "Completed";
}
if(c.getString(TAG_TITLE).equals("")){
report_data[i] = new Report(reportID,"Report "+(i+1),c.getString(TAG_TIME),drawable,url+c.getString(TAG_IMAGE),state,c.getString("coordination")) ;
}else{
report_data[i] = new Report(reportID,c.getString(TAG_TITLE),c.getString(TAG_TIME),drawable,url+c.getString(TAG_IMAGE),state,c.getString("coordination"));
}
if(json.getInt("successReplies")==1){
replies = json.getJSONArray(TAG_REPLIES);
ArrayList<String> arr = new ArrayList<String>();
for(int j=0;j<replies.length();j++){
JSONObject c2 = replies.getJSONObject(j);
if(reportID.equals(c2.getString("ReportID")))
{
arr.add(c2.getString("RepliesContent")+"\n"+c2.getString("RepliesTime"));
}
}
report_data[i].setRepliesArray(arr);
}
}
list = (ListView)findViewById(R.id.list);
ReportAdapter adapter = new ReportAdapter(Display_Reports.this,report_data);
list.setAdapter(adapter);
// Click event for single list row
list.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(
AdapterView<?> arg0, View arg1,
int position, long id) {
Intent intent = new Intent(Display_Reports.this, Display_Report_Details.class);
intent.putExtra("ID", report_data[position].ID);
intent.putExtra("Name", report_data[position].Name);
intent.putExtra("State", report_data[position].State);
intent.putExtra("Time", report_data[position].Time);
intent.putExtra("ImageUrl", report_data[position].ImageUrl);
intent.putExtra("Coordination", report_data[position].Coordination);
intent.putStringArrayListExtra("RepliesContent", report_data[position].getRepliesArray());
startActivity(intent);
}
});
} else {
// no Entities found
Toast.makeText(Display_Reports.this, "No reports found",
Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(Void unused) {
dismissDialog(DIALOG_DOWNLOAD_JSON_PROGRESS);
removeDialog(DIALOG_DOWNLOAD_JSON_PROGRESS);
}
}
You cannot modify the UI from a background thread. Whether you use AsyncTask, or a Handler, or runOnUiThread(), or post(), to have work done on the main application thread is up to you.
You may wish to review the documentation on threads and some of these techniques.
I have this ListView which fetches its data (image+text) from JSON on the web.
Now I have a task to make the ListView is accessible without internet connection. My idea is by saving the JSON data from the web when the app is run for the first time with internet, and when it can't find internet connection it will get the data from the persistent Storage.
Can anybody help me with this? I'm still a beginner can't find the example of SharedPreferences with JSON.
Thanks a lot
public class ProjectsList extends Activity {
/** Called when the activity is first created. */
//ListView that will hold our items references back to main.xml
ListView lstTest;
//Array Adapter that will hold our ArrayList and display the items on the ListView
ProjectAdapter arrayAdapter;
//List that will host our items and allow us to modify that array adapter
ArrayList<Project> prjcts=null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.projects_list);
//Initialize ListView
lstTest= (ListView)findViewById(R.id.lstText);
//Initialize our ArrayList
prjcts = new ArrayList<Project>();
//Initialize our array adapter notice how it references the listitems.xml layout
arrayAdapter = new ProjectAdapter(ProjectsList.this, R.layout.listitems,prjcts,ProjectsList.this);
//Set the above adapter as the adapter of choice for our list
//lstTest.setAdapter(arrayAdapter);
lstTest.setAdapter(arrayAdapter);
if (isOnline())
{
//Instantiate the Web Service Class with he URL of the web service not that you must pass
WebService webService = new WebService("http://liebenwald.spendino.net/admanager/dev/android/projects.json");
//Pass the parameters if needed , if not then pass dummy one as follows
Map<String, String> params = new HashMap<String, String>();
params.put("var", "");
//Get JSON response from server the "" are where the method name would normally go if needed example
// webService.webGet("getMoreAllerts", params);
String response = webService.webGet("", params);
try
{
//Parse Response into our object
Type collectionType = new TypeToken<ArrayList<Project>>(){}.getType();
//JSON expects an list so can't use our ArrayList from the lstart
List<Project> lst= new Gson().fromJson(response, collectionType);
//Now that we have that list lets add it to the ArrayList which will hold our items.
for(Project l : lst)
{
prjcts.add(l);
ConstantData.projectsList.add(l);
}
//Since we've modified the arrayList we now need to notify the adapter that
//its data has changed so that it updates the UI
arrayAdapter.notifyDataSetChanged();
}
catch(Exception e)
{
Log.d("Error: ", e.getMessage());
}
}
lstTest.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent care = new Intent(ProjectsList.this, ProjectDetail.class);
care.putExtra("spendino.de.ProjectDetail.position",position);
startActivity(care);
}
});
}
#Override
public void onDestroy()
{
yAdapter.imageLoader.stopThread();
lstTest.setAdapter(null);
super.onDestroy();
}
protected boolean isOnline() {
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
if (netInfo != null && netInfo.isConnected()) {
return true;
} else {
AlertDialog.Builder alertbox = new AlertDialog.Builder(this);
alertbox.setTitle("spendino Helfomat");
alertbox.setMessage ("Please check your internet connection");
alertbox.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
//Main.this.finish();
}
});
alertbox.show();
return false;
}
}
}
SharedPreferences has no methods for saving a JSON object as is, you must try to convert it to a String. Then when getting it you must parse this String back to JSON. Good luck!
JSON to String:
JSONObject o = new JSONObject(data.trim());
String name = o.getString(Constants.NAME);
long date = o.getLong(Constants.DATE);
String mes = o.getString(Constants.MESSAGE);
StringBuilder buf = new StringBuilder(text.getText());
buf.append(name).append(" (").append(dfTime.format(new Date(date))).append(")\n").append(mes).append("\n");
text.setText(buf.toString());
Making a JSON from a String is not a harder task, use StringTokenizer. Good luck!