I am new in creating apps. I am learning by doing courses on Udemy. So right now I am learning how to create a simple app where your can register, login and post a message, and I am doing all of this using Parse.com. Everything worked perfectly until today, when it was time to create a custom adapter that shows these posts.
The error is: cannot resolve symbol mStatus in the HomepageActivity class, though in the Udemy video, everything works perfectly.
Another strange error is in the line
ParseQuery<ParseObject> query = new ParseQuery <ParseObject> ("Status");
the second <ParseObject> is greyed out and it says Explicit type argument can be replaced with <>, though in the video its white(working).
The only explanation I thought of is that the video is old and something changed in the syntax, but I am not that great of a programmer to understand what to do. Or maybe im doing something wrong? Please help.
P.S . when I am trying to run the app, I am getting this message:
Note:C:\Users\User\AndroidStudioProjects\LiveUpdate\app\src\main\java\com\mycompany\liveupdate\StatusAdapter.java uses unchecked or unsafe operations.
Here is the adapter code:
package com.mycompany.liveupdate;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import com.parse.ParseObject;
import java.util.List;
/**
* Created by User on 2015-01-18.
*/
public class StatusAdapter extends ArrayAdapter {
protected Context mContext;
protected List<ParseObject> mStatus;
public StatusAdapter(Context context, List status) {
super(context, R.layout.homepagecustomlayout, status);
mContext = context;
mStatus = status;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
convertView = LayoutInflater.from(mContext).inflate(
R.layout.homepagecustomlayout, null);
holder = new ViewHolder();
holder.usernameHomepage = (TextView) convertView
.findViewById(R.id.usernameHP);
holder.statusHomepage = (TextView) convertView
.findViewById(R.id.statusHP);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
ParseObject statusObject = mStatus.get(position);
// title
String username = statusObject.getString("user");
holder.usernameHomepage.setText(username);
// content
String status = statusObject.getString("newStatus");
holder.statusHomepage.setText(status);
return convertView;
}
public static class ViewHolder {
TextView usernameHomepage;
TextView statusHomepage;
}
}
Here is the code, where im trying to call this adapter:
package com.mycompany.liveupdate;
import android.app.ListActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import com.parse.FindCallback;
import com.parse.Parse;
import com.parse.ParseException;
import com.parse.ParseObject;
import com.parse.ParseQuery;
import com.parse.ParseUser;
import java.util.List;
public class HomepageActivity extends ListActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_homepage);
Parse.initialize(this, "uinXCHcfbdm8zrbUT9y8Vu4R2qU5D22FZwkHs5HZ", "v1PL4oDu3ebtSidJFhjWRkkBQVAD8sefIB1WDFeq");
ParseUser currentUser = ParseUser.getCurrentUser();
if (currentUser != null) {
// show user the homepage
ParseQuery<ParseObject> query = new ParseQuery<ParseObject>("Status");
query.orderByDescending("createdAt");
query.findInBackground(new FindCallback<ParseObject>() {
#Override
public void done(List<ParseObject> status, ParseException e) {
if(e == null){
//success
mStatus = status;
StatusAdapter adapter = new StatusAdapter(getListView().getContext(), status);
setListAdapter(adapter);
}else {
//there was a problem
}
}
});
} else {
// show the signup or login screen
Intent takeUserToLogin = new Intent(HomepageActivity.this, LogInActivity.class);
startActivity(takeUserToLogin);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_homepage, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
switch (id){
case R.id.updateStatus:
//take user to updatestatus activity
Intent intent = new Intent(this, UpdateStatusActivity.class );
startActivity(intent);
break;
case R.id.logoutUser:
// log out user
ParseUser.logOut();
// take the user back to logout screen
Intent takeUserToLogin = new Intent(this, LogInActivity.class);
startActivity(takeUserToLogin);
break;
}
return super.onOptionsItemSelected(item);
}
}
Related
I migrated from the old Places SDK to the new Places SDK (including writing a new adapter), and now when typing an address into my AutoCompleteTextView it shows only the Place Names in the drop-down list (i.e. addresses but without city, state, country), but I need it to show the full address.
Here is my adapter:
import android.content.Context;
import android.graphics.Typeface;
import android.text.style.CharacterStyle;
import android.text.style.StyleSpan;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Filter;
import android.widget.Filterable;
import android.widget.TextView;
import androidx.annotation.NonNull;
import com.google.android.gms.common.api.ApiException;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.android.libraries.places.api.model.AutocompletePrediction;
import com.google.android.libraries.places.api.model.AutocompleteSessionToken;
import com.google.android.libraries.places.api.model.RectangularBounds;
import com.google.android.libraries.places.api.model.TypeFilter;
import com.google.android.libraries.places.api.net.FindAutocompletePredictionsRequest;
import com.google.android.libraries.places.api.net.FindAutocompletePredictionsResponse;
import com.google.android.libraries.places.api.net.PlacesClient;
import java.util.List;
public class PlaceAutocompleteAdapterNew extends ArrayAdapter<AutocompletePrediction> implements Filterable
{
PlacesClient placesClient;
AutocompleteSessionToken token;
private static final CharacterStyle STYLE_BOLD = new StyleSpan(Typeface.BOLD);
private List<AutocompletePrediction> mResultList;
private List<AutocompletePrediction> tempResult;
Context context;
private String TAG="PlaceAutoCompleteAdapter";
public PlaceAutocompleteAdapterNew(Context context,PlacesClient placesClient,AutocompleteSessionToken token) {
super(context,android.R.layout.simple_expandable_list_item_1,android.R.id.text1);
this.context=context;
this.placesClient=placesClient;
this.token=token;
}
public View getView(int position, View convertView, ViewGroup parent) {
View row = super.getView(position, convertView, parent);
AutocompletePrediction item = getItem(position);
TextView textView1 = (TextView) row.findViewById(android.R.id.text1);
textView1.setText(item.getPrimaryText(STYLE_BOLD));
return row;
}
#Override
public int getCount() {
return mResultList.size();
}
#Override
public AutocompletePrediction getItem(int position) {
return mResultList.get(position);
}
#Override
public Filter getFilter() {
return new Filter() {
#Override
protected FilterResults performFiltering(CharSequence constraint) {
FilterResults results = new FilterResults();
// Skip the autocomplete query if no constraints are given.
if (constraint != null) {
// Query the autocomplete API for the (constraint) search string.
mResultList = getAutoComplete(constraint);
if (mResultList != null) {
// The API successfully returned results.
results.values = mResultList;
results.count = mResultList.size();
}
}
return results;
}
#Override
protected void publishResults(CharSequence constraint, FilterResults results) {
if (results != null && results.count > 0) {
// The API returned at least one result, update the data.
notifyDataSetChanged();
} else {
// The API did not return any results, invalidate the data set.
notifyDataSetInvalidated();
}
}
#Override
public CharSequence convertResultToString(Object resultValue) {
// Override this method to display a readable result in the AutocompleteTextView
// when clicked.
if (resultValue instanceof AutocompletePrediction) {
return ((AutocompletePrediction) resultValue).getFullText(null);
} else {
return super.convertResultToString(resultValue);
}
}
};
}
private List<AutocompletePrediction> getAutoComplete(CharSequence constraint){
// Create a new token for the autocomplete session. Pass this to FindAutocompletePredictionsRequest,
// and once again when the user makes a selection (for example when calling fetchPlace()).
AutocompleteSessionToken token = AutocompleteSessionToken.newInstance();
// Create a RectangularBounds object.
// Use the builder to create a FindAutocompletePredictionsRequest.
FindAutocompletePredictionsRequest request = FindAutocompletePredictionsRequest.builder()
// Call either setLocationBias() OR setLocationRestriction().
//.setLocationBias(bounds)
//.setLocationRestriction(bounds)
.setTypeFilter(TypeFilter.ADDRESS)
.setSessionToken(token)
.setQuery(constraint.toString())
.build();
placesClient.findAutocompletePredictions(request).addOnSuccessListener(new OnSuccessListener<FindAutocompletePredictionsResponse>() {
#Override
public void onSuccess(FindAutocompletePredictionsResponse response) {
for (AutocompletePrediction prediction : response.getAutocompletePredictions()) {
Log.i(TAG, prediction.getPrimaryText(null).toString());
}
tempResult=response.getAutocompletePredictions();
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception exception) {
if (exception instanceof ApiException) {
ApiException apiException = (ApiException) exception;
Log.e(TAG, "Place not found: " + apiException.getStatusCode());
}
}
});
return tempResult;
}
}
How can I show the full addresses in the drop-down list?
getAutoComplete is returning tempResult. This is a List that contains fullText (the full address), primaryText (just the address without city, state, country), and other items. So the fullText is what I want, which is being returned, but the primaryText is what is being displayed in the AutoCompleteTextView. How can I fix this?
I changed this line:
textView1.setText(item.getPrimaryText(STYLE_BOLD));
to this:
textView1.setText(item.getFullText(STYLE_BOLD));
when i filter recyclerview it shows Not found .My Searchview not working.when i run the code its result in Not Found i think there is problem in onQueryTextChange
myfilter function also did not work
#Override
public boolean onQueryTextSubmit(String query) {
Toast.makeText(SecondActivity1.this, "Name is : " + query, Toast.LENGTH_SHORT).show();
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
final List<DatabaseModel> filteredModelList = filter(dbList, newText);
if (filteredModelList.size() > 0) {
// Toast.makeText(SecondActivity1.this, "Found", Toast.LENGTH_SHORT).show();
recyclerAdapter.setFilter(filteredModelList);
return true;
} else {
Toast.makeText(SecondActivity1.this, "Not Found", Toast.LENGTH_SHORT).show();
return false;
}
private List filter(List models, String query) {
query = query.toLowerCase();
recyclerAdapter.notifyDataSetChanged();
final List<DatabaseModel> filteredModelList = new ArrayList<>();
// mRecyclerView.setLayoutManager(new LinearLayoutManager(SecondActivity1.this));
// mRecyclerView.setAdapter(RecyclerAdapter);
for (DatabaseModel model : models) {
final String text = model.getName().toLowerCase();
if (text.contains(query)) {
filteredModelList.add(model);
}
}
return filteredModelList;
//
}
here is filter method which recieve parameter(dblist,newtext) filter method recieves these method when i use toast its show that it takes newText But didnot filter this.i checked many sites but this is same in many sites points.when i enter name toast shows name which i enter but it did not filter
RecyclerAdapter.java
package com.example.prabhu.databasedemo;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Filter;
import android.widget.Filterable;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
/**
* Created by user_adnig on 11/14/15.
*/
public class RecyclerAdapter extends RecyclerView.Adapter<RecyclerAdapter.ViewHolder> {
List<DatabaseModel> dbList;
static Context context;
RecyclerAdapter(Context context, List<DatabaseModel> dbList ){
this.dbList = new ArrayList<>();
this.context = context;
this.dbList = (ArrayList<DatabaseModel>) dbList;
}
#Override
public RecyclerAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemLayoutView = LayoutInflater.from(parent.getContext()).inflate(
R.layout.item_row, null);
// create ViewHolder
ViewHolder viewHolder = new ViewHolder(itemLayoutView);
return viewHolder;
}
#Override
public void onBindViewHolder(RecyclerAdapter.ViewHolder holder, int position) {
holder.name.setText(dbList.get(position).getName());
holder.email.setText(dbList.get(position).getEmail());
}
#Override
public int getItemCount() {
return dbList.size();
}
public void setFilter(List<DatabaseModel> countryModels) {
// Toast.makeText(RecyclerAdapter.this,"Method is called", Toast.LENGTH_SHORT).show();
dbList = new ArrayList<>();
dbList.addAll(countryModels);
notifyDataSetChanged();
}
public static class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
public TextView name,email;
public ViewHolder(View itemLayoutView) {
super(itemLayoutView);
name = (TextView) itemLayoutView
.findViewById(R.id.rvname);
email = (TextView)itemLayoutView.findViewById(R.id.rvemail);
itemLayoutView.setOnClickListener(this);
}
#Override
public void onClick(View v) {
Intent intent = new Intent(context,DetailsActivity.class);
Bundle extras = new Bundle();
extras.putInt("position",getAdapterPosition());
intent.putExtras(extras);
/*
int i=getAdapterPosition();
intent.putExtra("position", getAdapterPosition());*/
context.startActivity(intent);
Toast.makeText(RecyclerAdapter.context, "you have clicked Row " + getAdapterPosition(), Toast.LENGTH_LONG).show();
}
}
}
this is my recyclerAdapterCode.i also used Recycleradapter.setFilter(filterModeList) method but it did not work for me.i think in my set filter method error which i did not solve yet.
. But when I clear the search widget I don't get the full list instead I get the empty RecyclerView.
I have created a custom adapter that extends ArrayAdapter containing Listview with two TextView in a single row. I have SearchView on the ActionBar.In onQueryTextChange(String s) i have tried some methods which i have found, works but result is not correct, in the end i have only first row from ListView. How to make SearchView to work correctly?
Everything else working fine. This app is for minSdkVersion="9" and above. Any suggestion will be OK. Regards.
import android.app.SearchManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.view.MenuItemCompat;
import android.support.v7.app.ActionBar;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.widget.SearchView;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Filter;
import android.widget.ListView;
import android.widget.TextView;
public class A extends ActionBarActivity{
ListView list;
String[] titl;
String[] opis;
SearchView searchView;
VjuAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity);
ActionBar aB = getSupportActionBar();
aB.setDisplayHomeAsUpEnabled(true);
Resources res=getResources();
titl=res.getStringArray(R.array.naslov);
opis=res.getStringArray(R.array.podnaslov);
list=(ListView) findViewById(R.id.listView);
VjuAdapter adapter=new VjuAdapter(this, titl, opis);
adapter.getFilter().filter(null);
list.setAdapter(adapter);
list.setTextFilterEnabled(true);
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
}
#Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
finish();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// TODO Auto-generated method stub
MenuInflater men = getMenuInflater();
men.inflate(R.menu.main, menu);
SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
MenuItem searchItem = menu.findItem(R.id.trazi);
ComponentName cn = new ComponentName(this, A.class);
searchView = (SearchView) MenuItemCompat.getActionView(searchItem);
searchView.setSearchableInfo(searchManager.getSearchableInfo(cn));
//searchView.setOnQueryTextListener(this);
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String arg0) {
// TODO Auto-generated method stub
return false;
}
#Override
public boolean onQueryTextChange(String s) {
// Here i have tried some methods which i have found
// this works but result is not correct, in the end i have
// only first row from ListView
/*if (TextUtils.isEmpty(s)) {
((LayoutInflater) list.getAdapter()).getFilter().filter(s);
} else {
adapter.getFilter().filter(s.toString());
}
return true;
}
});*/
//s.toLowerCase(Locale.getDefault());
VjuAdapter vd = (VjuAdapter)list.getAdapter();
Ll.m("POCETAK VD "+ vd);
Filter filter = vd.getFilter();
Ll.m("SRED VD.GET "+ vd.getFilter());
filter.filter(s);
Ll.m("KRAJ FILTER "+ filter);
/*if (TextUtils.isEmpty(s)) {
list.clearTextFilter();
} else {
//adapter.setSelectionAfterHeaderView();
adapter.getFilter().filter(s.toString());
}*/
return true;
}
});
return super.onCreateOptionsMenu(menu);
}
public boolean onOptionsItemSelected(MenuItem item) {
// TODO Auto-generated method stub
int id = item.getItemId();
/*if (id == R.id.trazi){
onSearchRequested();
}*/
if (id == android.R.id.home){
onBackPressed();
}
if (id == R.id.about){
Intent i = new Intent("com.kanna.sanjarica.ABOUT");
startActivity(i);
}
if (id == R.id.oceni_apl){
Uri uri = Uri.parse("market://details?id=" + getApplicationContext().getPackageName());
Intent goToMarket = new Intent(Intent.ACTION_VIEW, uri);
startActivity(goToMarket);
}
if (id == R.id.kontakt){
String mailTo="kanjah77#gmail.com";
Intent email_intent = new Intent(Intent.ACTION_SENDTO, Uri.fromParts("mailto",mailTo, null));
email_intent.putExtra(android.content.Intent.EXTRA_SUBJECT, "");
email_intent.putExtra(android.content.Intent.EXTRA_TEXT,"");
startActivity(Intent.createChooser(email_intent, "PoĊĦalji email..."));
}
return true;
}
}
class VjuAdapter extends ArrayAdapter<String>{
Context context;
String [] titlArray;
String [] opisArray;
public VjuAdapter(Context c, String[] naslov, String[] podnaslov ) {
super(c,R.layout.single_row,R.id.textView1,naslov);
this.context=c;
this.titlArray=naslov;
this.opisArray=podnaslov;
}
class MyViewHolder{
TextView textVel;
TextView textMal;
MyViewHolder(View v){
textVel=(TextView) v.findViewById(R.id.textView1);
textMal=(TextView) v.findViewById(R.id.textView2);
}
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row=convertView;
MyViewHolder holder=null;
if(row==null){
LayoutInflater inf=(LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row=inf.inflate(R.layout.single_row, parent, false);
holder=new MyViewHolder(row);
row.setTag(holder);
}else{
holder=(MyViewHolder) row.getTag();
}
holder.textVel.setText(titlArray[position]);
holder.textMal.setText(opisArray[position]);
return row;
}
}
This is from http://developer.android.com/:
A concrete BaseAdapter that is backed by an array of arbitrary
objects. By default this class expects that the provided resource id
references a single TextView. If you want to use a more complex
layout, use the constructors that also takes a field id. That field id
should reference a TextView in the larger layout resource.
You have 2 TextView, and constructor class is this:
ArrayAdapter(Context context, int resource, int textViewResourceId)
I am working on an application that has a button which will lead to a new activity. I managed to make that work but when I am trying to add a button in the new activity with xml it is not showing up. I tried to make it work with programming but I was only able to make a button big as the whole screen. When I tried to change the size of the button with programming it could not work. Can someone please tell me how can I make that widgets show on the new activity preferably using XML.
This is the code of my first activity:
package com.example.user.myapp;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MenuInflater;
import android.view.View;
import android.content.Intent;
public class MainActivity extends ActionBarActivity {
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.activity_main_actions, menu);
return super.onCreateOptionsMenu(menu);
}
public void sendButton(View view){
Intent intent = new Intent(this, Ut.class);
startActivity(intent);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
And this is the code of my second activity:
package com.example.user.myapp;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.Button;
import android.content.Intent;
public class Ut extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent intent = getIntent();
setContentView(R.layout.activity_ut);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.activity_main_actions, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
and this is the code that I added after Intent intent = getIntent() when I tried to make it work with programming
Button button2 = new Button(this);
button2.setWidth(10);
button2.setHeight(10);
setContentView(button2);
With this code a button big as the whole screen showed up although I set the size of it.
Can somebody tell me how I can make this work?
I just would to customize my ListView with an image on the left
package com.project.test;
import java.net.URI;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import org.apache.http.NameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.R.id;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
public class ContactUs extends ListActivity {
// Progress Dialog
private ProgressDialog pDialog;
// Creating JSON Parser object
JSONParser jParser = new JSONParser();
ListView list;
LazyAdapter adapter;
ArrayList<HashMap<String, String>> contactsList;
// url to get all contacts list
private static String url_all_contacts = "http://10.0.2.2/test/get_all_staff.php";
// JSON Node names
private static final String TAG_SUCCESS = "success";
private static final String TAG_CONTACT = "contacts";
private static final String TAG_PID = "pid";
private static final String TAG_NAME = "name";
private static final String TAG_IMAGE = "image";
static final String KEY_SONG = "song"; // parent node
static final String KEY_ID = "id";
static final String KEY_TITLE = "title";
static final String KEY_ARTIST = "artist";
static final String KEY_DURATION = "duration";
static final String KEY_THUMB_URL = "thumb_url";
// contacts JSONArray
JSONArray contacts = null;
ImageView img = (ImageView)findViewById(R.id.image);
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.all_staff);
// Hashmap for ListView
contactsList = new ArrayList<HashMap<String, String>>();
// Loading contacts in Background Thread
new LoadAllcontacts().execute();
//list = getListView();
// Get listview
//ListView lv = getListView();
// on seleting single product
// launching Edit Product Screen
/*
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// getting values from selected ListItem
String pid = ((TextView) view.findViewById(R.id.pid)).getText()
.toString();
// Starting new intent
Intent in = new Intent(getApplicationContext(),
GetAllStaffDetails.class);
// sending pid to next activity
in.putExtra(TAG_PID, pid);
// starting new activity and expecting some response back
startActivityForResult(in, 100);
}
});
*/
}
// Response from Edit Product Activity
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// if result code 100
if (resultCode == 100) {
// if result code 100 is received
// means user edited/deleted product
// reload this screen again
Intent intent = getIntent();
finish();
startActivity(intent);
}
}
/**
* Background Async Task to Load all product by making HTTP Request
* */
class LoadAllcontacts extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(ContactUs.this);
pDialog.setMessage("Loading contacts. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
/**
* getting All contacts from url
* */
protected String doInBackground(String... args) {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
// getting JSON string from URL
JSONObject json = jParser.makeHttpRequest(url_all_contacts, "GET",
params);
// Check your log cat for JSON reponse
Log.d("All contacts: ", json.toString());
try {
// Checking for SUCCESS TAG
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// contacts found
// Getting Array of contacts
contacts = json.getJSONArray(TAG_CONTACT);
// looping through All contacts
for (int i = 0; i < contacts.length(); i++) {
JSONObject c = contacts.getJSONObject(i);
// Storing each json item in variable
String id = c.getString(TAG_PID);
String name = c.getString(TAG_NAME);
String image = c.getString(TAG_IMAGE);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_PID, id);
map.put(TAG_NAME, name);
// adding HashList to ArrayList
contactsList.add(map);
}
//list = (ListView)findViewById(id.list);
//list.setAdapter(contactsList);
} else {
// no contacts found
// Launch Add New product Activity
Intent i = new Intent(getApplicationContext(),
NewProductActivity.class);
// Closing all previous activities
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
// dismiss the dialog after getting all contacts
pDialog.dismiss();
// updating UI from Background Thread
runOnUiThread(new Runnable() {
public void run() {
/**
* Updating parsed JSON data into ListView
* */
//adapter=new LazyAdapter(this, contactsList);
ListAdapter adapter = new SimpleAdapter(ContactUs.this,
contactsList, R.layout.list_row, new String[] {
TAG_PID, TAG_NAME }, new int[] { R.id.pid,
R.id.name });
// updating listview
setListAdapter(adapter);
}
});
}
}
}
This is the code am using right now, but I had some difficulties in how to retrieve an image from data base using JSON then insert the image to the ListView. So any help please ??
Provide more details if you wonna get answer.
From which field you wonna get image? This is an url, filesystem ref or may be base64 data, or...
In your layout (R.layout.list_row) you should have an ImageView into which you can set any kind of Drawable object to be displayed.
And remove runOnUiThread call, because in onPostExecute you already on UI thread.