I need to do one agenda about some events. I have one list view with all titles about the events for this I use json and mysql for this .
The problem is I am new on android , and I dont know how to do when I click one event title have on Activity with information about this event.
I have the information on database . Can you help me? I need this doing automatically .
My code now is this :
package com.eu.agendamarinhagrande;
import android.annotation.TargetApi;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Build;
import android.support.v7.app.ActionBar;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import com.eu.agendamarinhagrande.JSONParser;
import com.eu.agendamarinhagrande.R;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.text.Normalizer;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.regex.Pattern;
public class MainActivity extends ActionBarActivity {
// Progress Dialog
private ProgressDialog pDialog;
// Creating JSON Parser object
// JSONParser jParser = new JSONParser();
ArrayList<HashMap<String, String>> empresaList;
// url to get all products list
private static String url_all_empresas = "http://www.grifin.pt/projectoamg/Conexao.php";
// JSON Node names
private static final String TAG_TITULO = "Titulo";
// products JSONArray
String resultado = null;
ListView lista;
#TargetApi(Build.VERSION_CODES.HONEYCOMB)
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Hashmap para el ListView
empresaList = new ArrayList<HashMap<String, String>>();
new Download().execute();
// Cargar los productos en el Background Thread
lista = (ListView) findViewById(R.id.listView);
// ActionBar actionBar = getSupportActionBar();
// actionBar.setDisplayHomeAsUpEnabled(true);
}//fin onCreate
public class Download extends AsyncTask<Void, Void, String> {
#Override
protected String doInBackground(Void... params) {
String out = null;
try {
DefaultHttpClient httpClient = new DefaultHttpClient();
final HttpParams httpParameters = httpClient.getParams();
HttpConnectionParams.setConnectionTimeout(httpParameters, 15000);
HttpConnectionParams.setSoTimeout(httpParameters, 15000);
HttpGet httpPost = new HttpGet(url_all_empresas);
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
out = EntityUtils.toString(httpEntity, HTTP.UTF_8);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return out;
}
#TargetApi(Build.VERSION_CODES.GINGERBREAD)
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
ArrayList<String> list = new ArrayList<>();
try {
JSONArray jsonArray = new JSONArray(result);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsa = jsonArray.getJSONObject(i);
String str = jsa.getString("Titulo");
String data = jsa.getString("Datainicio");
Log.e("TAG", str);
Log.e("TAG", data);
String s1 = Normalizer.normalize(str, Normalizer.Form.NFKD);
String regex = Pattern.quote("[\\p{InCombiningDiacriticalMarks}\\p{IsLm}\\p{IsSk}]+");
str = new String(s1.replaceAll(regex, "").getBytes("ascii"), "ascii");
list.add(str+"\n"+data);
}
ArrayAdapter adapter = new ArrayAdapter<>(MainActivity.this, android.R.layout.simple_list_item_1, list);
// updating listview
//setListAdapter(adapter);
lista.setAdapter(adapter);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
Some information for you understand my code is portuguese so I translate for you
Titulo-- Title
Data---Date
Descricao---Information about event
Id_evento---Id_event
Imagem---image
You have to add an onItemClickListener to you listview.
mylistview.setOnItemClickListener(this);
where this is your activity`s instance. Make sure please, you activity is implementing the onItemClickListener interface.
public class MainActivity extends Activity implements onItemClickListener{
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main_activity);
listView= ((ListView) findViewById (R.id.list));
listView.setOnItemClickListener (this);
empresaList = new ArrayList<HashMap<String, String>>();
new Download().execute();
//download data to empresaList arrayList , and on PostExeCutre
// create a new adapter with it
// set it to list
}
public void onItemClick (AdapterView<?> parent, View view, int position, long id)
{
//do what you want in your code.
}
}
A long, but good example about onClickListeners:
http://www.mkyong.com/android/android-listview-example/
Related
I am creating quiz app from volley library in android. where I get data in Array list from external website. now problem is that how to set data in Textview and Buttons. I created one Textviewfor show question, four Buttions for options, and Two more Buttions for go to next question and go to previous question. here is image
I want that when i click one of the option button than his color will be blue and rest of button will be grey. when i click next button than load new question and all options button will be grey.
here is my main activity.java code. please help me in create quiz app.
package com.ravindra.excelrecycleview;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.app.ProgressDialog;
import android.os.Bundle;
import com.android.volley.DefaultRetryPolicy;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.RetryPolicy;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.net.URL;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
private RecyclerView mRecyclerView;
private QuestionAdapter mQuestionAdatpter;
private ArrayList<question> mquestion;
private RequestQueue mRequestQueue;
ProgressDialog loading;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mRecyclerView = findViewById(R.id.recylcer_view);
mRecyclerView.setHasFixedSize(true);
mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
mquestion = new ArrayList<>();
mRequestQueue = Volley.newRequestQueue(this);
parseJSON();
}
private void parseJSON(){
loading = ProgressDialog.show(this,"Loading","please wait",false,true);
String url ="https://script.google.com/macros/s/AKfycbw6eHqtKTxHoS9HPSdfTasY-iebLQXUgS3sHHiOpeuGxJfssBI/exec?action=getQuestions";
JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONArray jsonArray = response.getJSONArray("items");
for (int i =0;i<jsonArray.length();i++){
JSONObject items = jsonArray.getJSONObject(i);
String questions = items.getString("questions");
String optiona = items.getString("optiona");
String optionb = items.getString("optionb");
String optionc = items.getString("optionc");
String optiond = items.getString("optiond");
String correctans = items.getString("correctans");
String explain = items.getString("explain");
mquestion.add(new question(questions,optiona,optionb,optionc,optiond,correctans,explain));
}
mQuestionAdatpter = new QuestionAdapter(MainActivity.this,mquestion);
mRecyclerView.setAdapter(mQuestionAdatpter);
loading.dismiss();
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
} );
mRequestQueue.add(request);
int socketTimeOut = 50000;
RetryPolicy policy = new DefaultRetryPolicy(socketTimeOut, 0, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT);
request.setRetryPolicy(policy);
}
}
How do I get the json result from onPostExecute to another activity? I was able to get the user details from the database based on the username logged in. So in my HomePageActivity there is a button to go to profile and when I clicked on btnprofile it displays the user details on textviews in the current activity(HomePageActivity) but what I wanted to do is to get the user details and then display it to a new activity, which is in the Profile Activity. I tried using Intent but when I go to Profile Activity it displays nothing. Can you please help me? :(
Here is my HomePageActivity:
package com.example.androidmp;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;
import android.content.*;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONObject;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.view.Menu;
import android.view.View;
import android.widget.*;
import com.example.androidmp.User;
import java.util.ArrayList;
import java.util.List;
import com.example.androidmp.User;
import com.example.androidmp.Poem;
import java.util.ArrayList;
import java.util.HashMap;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.widget.ListView;
public class HomePageActivity extends Activity {
Button btnfeed, btnprofile;
User u = new User();
String Username,Password,Fullname,Email,Location,Bio,uname;
String getusername,getpw,getfn,getem,getloc,getb;
JSONObject jsonobject;
JSONArray jsonarray;
ListView listview;
ListViewAdapter adapter;
ProgressDialog mProgressDialog;
ArrayList<HashMap<String, String>> arraylist;
HashMap<String, String> hashMap = new HashMap<String, String>();
Intent i;
Bundle bundle;
private static final String USERNAME = "Username";
private static final String PASSWORD = "Password";
private static final String FULLNAME = "Fullname";
private static final String EMAIL = "Email";
private static final String BIO = "Bio";
private static final String LOCATION = "Location";
String s="";
TextView fn,em,loc,b;
private static final String TAG_PROFILE = "user";
private static final String PROFILE_URL = "http://192.168.1.5/webservices/mycontroller/getUser.php";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_homepage);
Intent intent = getIntent();
u.SetUsername(intent.getStringExtra(u.username()));
fn = (TextView) findViewById(R.id.textView1);
em = (TextView) findViewById(R.id.textView2);
loc = (TextView) findViewById(R.id.textView3);
b = (TextView) findViewById(R.id.textView4);
TextView textView = (TextView) findViewById(R.id.getusername);
textView.setText(u.getUsername());
uname = u.getUsername().toString();
//uname = textView.toString();
//u.SetUsername(uname.toString());
btnprofile = (Button) findViewById(R.id.btnprofile);
btnfeed = (Button) findViewById(R.id.btnfeed);
//getem = em.getText().toString();
//getloc = loc.getText().toString();
//getb = b.getText().toString();
btnprofile.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
new ProfileAsync().execute();
Intent i = new Intent(HomePageActivity.this,ProfileActivity.class);
i.putExtra("fullname",Fullname);
i.putExtra("email", Email);
i.putExtra("bio", Bio);
i.putExtra("location", Location);
startActivity(i);
finish();
}
});
btnfeed.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent a = new Intent(HomePageActivity.this,FeedActivity.class);
startActivity(a);
}
});
}
class ProfileAsync extends AsyncTask<String, String, String>{
private Dialog loadingDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
loadingDialog = ProgressDialog.show(HomePageActivity.this, "Please wait", "Loading...");
}
#Override
protected String doInBackground(String... params) {
String json=null;
byte[] data;
StringBuffer buffer = null;
InputStream is = null;
try{
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("Username", uname));
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(PROFILE_URL);
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpClient.execute(httpPost);
HttpEntity entity = response.getEntity();
json = EntityUtils.toString(entity);
Log.e("Profile JSON: ", json.toString());
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return json;
}
#Override
protected void onPostExecute(String json){
super.onPostExecute(json);
loadingDialog.dismiss();
try
{
jsonobject = new JSONObject(json);
jsonarray = jsonobject.getJSONArray("user");
JSONObject jb= jsonarray.getJSONObject(0);
//Username = jb.getString("Username");
//Password = jb.getString("Password");
Fullname = jb.getString("Fullname");
Email = jb.getString("Email");
Bio = jb.getString("Bio");
Location = jb.getString("Location");
fn.setText(Fullname);
em.setText(Email);
loc.setText(Location);
b.setText(Bio);
}catch(Exception e)
{
e.printStackTrace();
}
}
}//end of asynctask
}
Here is my ProfileActivity:
package com.example.androidmp;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;
import android.content.*;
import com.example.androidmp.User;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.view.Menu;
import android.view.View;
import android.widget.*;
public class ProfileActivity extends Activity {
Button btncreate;
private TextView _username,_password,_fullname,_Email,_bio,_location;
User u = new User();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.profileview);
//_username = (TextView) findViewById(R.id._username);
//_password = (TextView) findViewById(R.id._password);
_fullname = (TextView) findViewById(R.id._fullname);
_Email = (TextView) findViewById(R.id._Email);
_bio = (TextView) findViewById(R.id._bio);
_location = (TextView) findViewById(R.id._location);
Intent i = getIntent();
u.SetUsername(i.getStringExtra(u.username()));
_username.setText(u.getUsername());
String displayfullname = i.getExtras().getString("fullname");
String displayemail = i.getExtras().getString("email");
String displaybio = i.getExtras().getString("bio");
String displaylocation = i.getExtras().getString("location");
_fullname.setText(displayfullname);
_Email.setText(displayemail);
_bio.setText(displaybio);
_location.setText(displaylocation);
}
}
It is because new activity starts before async task is completed. Just call function for start new activity in onPostExecute() function.
Pass values after fetching the details. Is the settext working properly? then you can give the intent at that scope, in the onPostexecute method. Look before doing this.Look this
I am new to Java so please excuse any silly or obvious mistake. I have a activity that pulls a json encoded string from a PHP file and put it into a simple list view. I am getting the dreaded red squiggly lines and what is to me a cryptic error message. Here is my code. I appreciate any assistance.
package --Hidden--;
import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
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.ListView;
import android.widget.Toast;
import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.HashMap;
import java.util.Map;
public class tracklist extends Activity implements OnItemClickListener {
private static final String URL = "http://rickthompson.com/json/fetchtracks.php";
ListView lv;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_tracklist);
lv = (ListView) findViewById(R.id.displayTrackList);
ArrayAdapter<String> adapter = new ArrayAdapter<>(this,
R.layout.rowlayout, R.id.label, profileUserOptions);
lv.setAdapter(adapter);
lv.setOnItemClickListener(this);
Bundle bundle = getIntent().getExtras();
final String selectedSubGenre = bundle.getString("option");
///////////// login script
RequestQueue requestQueue = Volley.newRequestQueue(this);
StringRequest request = new StringRequest(Request.Method.POST, URL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonObject = new JSONObject(response);
if (jsonObject.names().get(0).equals("tracks")) {
Toast.makeText(getApplicationContext(), "tracks " + jsonObject.getString("tracks"), Toast.LENGTH_LONG).show();
/// save user id in prefs
JSONArray contacts = jsonObject.getJSONArray("tracks");
HashMap<String, String> trackview = null;
for (int i = 0; i < contacts.length(); i++) {
JSONObject c = contacts.getJSONObject(i);
String isrc = c.getString("isrc");
trackview = new HashMap<>();
trackview.put("isrc", isrc);
}
trackview.toString();
lv = (ListView) findViewById(R.id.displayTrackList);
ArrayAdapter<String> adapter = new ArrayAdapter<>(this, R.layout.rowlayout, R.id.label, trackview);
lv.setAdapter(adapter);
lv.setOnItemClickListener(this);
} else {
Toast.makeText(getApplicationContext(), "Error" + jsonObject.getString("error"), Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
HashMap<String, String> hashMap = new HashMap<>();
SharedPreferences userPrefs = getSharedPreferences("userInfo", Context.MODE_PRIVATE);
String userid = userPrefs.getString("memberid", "");
hashMap.put("u", userid);
Bundle bundle = getIntent().getExtras();
final String selectedSubGenre = bundle.getString("option");
hashMap.put("sg", selectedSubGenre);
return hashMap;
}
};
requestQueue.add(request);
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(getApplicationContext(), "something clicked", Toast.LENGTH_LONG).show();
}
}
JSONObject jsonObject = new JSONObject(response);
if(jsonObject.names().get(0).equals("tracks")){
//rest of the code
}
In the above code I hope you are trying to get "name" array which should be
JSONArray jso3 = new JSONArray (jsonObject.getString("names"));
Please provide the error details so that i can give you a detailed description.
I need help from anyone.. please respect my question..
ok, my problem is i want to use Glide for my listview but i dont know to do..
please constract my listviewadapter so that the Glide will work give me any other possible solution to achieve my goal..
my goal is i just want to display image and text in listview or gridview with Glide and JSON, the JSON result is from my php script..
here is my code..
CategoryFragment.java
package com.example.administrator.mosbeau;
import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ExpandableListView;
import android.widget.ListView;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
/**
* Created by Administrator on 9/18/2015.
*/
public class CategoryFragment extends Fragment {
public static CategoryFragment newInstance(String id,String name) {
CategoryFragment fragment = new CategoryFragment();
Bundle bundle = new Bundle();
bundle.putString("id", id);
bundle.putString("name", name);
fragment.setArguments(bundle);
return fragment;
}
public CategoryFragment () {
}
EditText tpid, tpname;
String cid;
String cname;
String myJSON;
JSONObject jsonobject;
JSONArray jsonarray;
ListView productlistview;
ListViewAdapter adapter;
ProgressDialog mProgressDialog;
ArrayList<HashMap<String, String>> arraylist;
public static String products_id = "products_id";
public static String products_name = "products_name";
public static String products_price = "products_price";
public static String products_image = "products_image";
Boolean InternetAvailable = false;
Seocnd detectconnection;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
View rootView = inflater.inflate(R.layout.categorylayout, container, false);
getActivity().invalidateOptionsMenu();
tpid = (EditText) rootView.findViewById(R.id.tpid);
tpname = (EditText) rootView.findViewById(R.id.tpname);
if(getArguments() != null) {
String catid = getArguments().getString("id");
String catname = getArguments().getString("name");
tpid.setText(catid);
tpname.setText(catname);
cid = catid;
cname = catname;
}
productlistview = (ListView) rootView.findViewById(R.id.productlistview);
//new DownloadJSON().execute();
detectconnection = new Seocnd(getActivity());
InternetAvailable = detectconnection.InternetConnecting();
if (InternetAvailable) {
getProduct();
} else {
NointernetFragment fragment = new NointernetFragment();
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.container, fragment)
.commit();
}
return rootView;
}
public void getProduct(){
class DownloadJSON extends AsyncTask<String, Void, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Create a progressdialog
mProgressDialog = new ProgressDialog(getActivity());
// Set progressdialog title
mProgressDialog.setTitle(cname);
// Set progressdialog message
mProgressDialog.setMessage("Loading...");
mProgressDialog.setIndeterminate(false);
// Show progressdialog
mProgressDialog.show();
}
#Override
protected String doInBackground(String... params) {
DefaultHttpClient httpclient = new DefaultHttpClient(new BasicHttpParams());
HttpPost httppost = new HttpPost("http://joehamirbalabadan.com/android/android/products.php");
// Depends on your web service
httppost.setHeader("Content-type", "application/json");
InputStream inputStream = null;
String result = null;
try {
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
inputStream = entity.getContent();
// json is UTF-8 by default
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
result = sb.toString();
} catch (Exception e) {
// Oops
}
finally {
try{if(inputStream != null)inputStream.close();}catch(Exception squish){}
}
return result;
}
#Override
protected void onPostExecute(String result){
myJSON=result;
try {
// Locate the array name in JSON
JSONObject jsonObj = new JSONObject(myJSON);
jsonarray = jsonObj.getJSONArray("products");
arraylist = new ArrayList<HashMap<String, String>>();
for (int i = 0; i < jsonarray.length(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
JSONObject p = jsonarray.getJSONObject(i);
// Retrive JSON Objects
map.put("products_id", p.getString("products_id"));
map.put("products_name", p.getString("products_name"));
map.put("products_price", p.getString("products_price"));
map.put("products_image", p.getString("products_image"));
// Set the JSON Objects into the array
arraylist.add(map);
}
} catch (JSONException e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
adapter = new ListViewAdapter(getActivity(), arraylist);
// Set the adapter to the ListView
productlistview.setAdapter(adapter);
// Close the progressdialog
mProgressDialog.dismiss();
}
}
DownloadJSON g = new DownloadJSON();
g.execute();
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
((MainActivity) activity).onSectionAttached(2);
}
}
ListViewAdapter.java
package com.example.administrator.mosbeau;
/**
* Created by Administrator on 9/28/2015.
*/
import android.content.Context;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.HashMap;
import com.bumptech.glide.Glide;
public class ListViewAdapter extends BaseAdapter {
// Declare Variables
Context context;
LayoutInflater inflater;
ArrayList<HashMap<String, String>> data;
ImageLoader imageLoader;
HashMap<String, String> resultp = new HashMap<String, String>();
public ListViewAdapter(Context context,
ArrayList<HashMap<String, String>> arraylist) {
this.context = context;
data = arraylist;
imageLoader = new ImageLoader(context);
}
#Override
public int getCount() {
return data.size();
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
public View getView(final int position, View convertView, ViewGroup parent) {
// Declare Variables
TextView products_id;
TextView products_name;
TextView products_price;
ImageView products_image;
inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View itemView = inflater.inflate(R.layout.product_listview_item, parent, false);
// Get the position
resultp = data.get(position);
// Locate the TextViews in product_listview_item.xml
products_id = (TextView) itemView.findViewById(R.id.products_id);
products_name = (TextView) itemView.findViewById(R.id.products_name);
products_price = (TextView) itemView.findViewById(R.id.products_price);
// Locate the ImageView in product_listview_item.xml
products_image = (ImageView) itemView.findViewById(R.id.products_image);
// Capture position and set results to the TextViews
products_id.setText(resultp.get(CategoryFragment.products_id));
products_name.setText(resultp.get(CategoryFragment.products_name));
products_price.setText(resultp.get(CategoryFragment.products_price));
// Capture position and set results to the ImageView
// Passes flag images URL into ImageLoader.class
imageLoader.DisplayImage(resultp.get(CategoryFragment.products_image), products_image);
// Capture ListView item click
itemView.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// Get the position
resultp = data.get(position);
Intent intent = new Intent(context, SingleItemView.class);
// Pass all data rank
intent.putExtra("products_id", resultp.get(CategoryFragment.products_id));
// Pass all data country
intent.putExtra("products_name", resultp.get(CategoryFragment.products_name));
// Pass all data population
intent.putExtra("products_price",resultp.get(CategoryFragment.products_price));
// Pass all data flag
intent.putExtra("products_image", resultp.get(CategoryFragment.products_image));
// Start SingleItemView Class
context.startActivity(intent);
}
});
return itemView;
}
}
Just use : Glide.with(context)
.load(resultp.get(CategoryFragment.products_image))
.into(products_image);
in place of
imageLoader.DisplayImage(resultp.get(CategoryFragment.products_image), products_image);
in your ListViewAdapter.java
I am building a search app using fragments for each screen. I have the search working and storing the JSON results in an ArrayList<Map<String, String>>in the main activity so the other fragments can access it. the current problem is on my resultsFragment I have a Google MapFragment embedded in the main ListFragment and a listView below that. The map is successfully populated, but the list is empty. I have spent hours trying to figure this out. Here is the code for resultsFragment
package com.wny.wecare.fragment;
import java.util.ArrayList;
import java.util.Map;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import com.wny.wecare.MainActivity;
import com.wny.wecare.R;
import android.app.ListFragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
public class ResultsFragment extends ListFragment {
ArrayList<Map<String, String>> resultsList = new ArrayList<Map<String, String>>();
private GoogleMap map;
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_results, container, false);
//Get search results from stored ArrayList
resultsList = MainActivity.getResultsList();
//Build listView from results
ListView lv =(ListView) getActivity().findViewById(android.R.id.list);
ListAdapter adapter = new SimpleAdapter(getActivity(), resultsList,
R.layout.custom_row_view, new String[] { "AgencyID", "AgencyName",
"Address1" }, new int[] { R.id.text1, R.id.text2,
R.id.text3 });
// updating listview
setListAdapter(adapter);
//Setup embedded Google Map fragment
map = ((MapFragment) getFragmentManager().findFragmentById(R.id.map))
.getMap();
map.setMapType(GoogleMap.MAP_TYPE_HYBRID);
//Add markers to the map from resultsList
for (int i = 0; i < resultsList.size(); i++) {
Double latitude = Double.valueOf(resultsList.get(i).get("Lat"));
Double longitude = Double.valueOf(resultsList.get(i).get("Lng"));
String mname = resultsList.get(i).get("AgencyName");
LatLng posit = new LatLng(latitude, longitude);
map.addMarker(new MarkerOptions()
.position(posit)
.title(mname));
}
return rootView;
}
}
In case its helpful here is the code from my homeFragment (where the search results are stored to the ArrayList)
package com.wny.wecare.fragment;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnKeyListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import com.wny.wecare.MainActivity;
import com.wny.wecare.R;
import com.wny.wecare.handler.JSONParser;
public class HomeFragment extends Fragment implements OnItemSelectedListener, OnClickListener{
private OnFragmentInteractionListener mListener;
private Spinner spinner;
private Button btnSubmit;
private static final String[] list={"Alden", "Amherst", "Angola",
"Blasdell", "Boston", "Bowmansville", "Buffalo", "Cheektowaga", "Clarence",
"Depew", "Derby", "East Aurora", "Eden", "Elma", "Getzville", "Gowanda",
"Grand Island", "Holland", "Irving", "Kenmore", "Lackawanna", "Lake View",
"Lancaster", "Lawtons", "North Collins", "Orchard Park", "Snyder", "Springville",
"Tonawanda", "West Seneca", "Williamsville"};
// Setup ArrayList from main activity to store results
ArrayList<Map<String, String>> resultsList = new ArrayList<Map<String, String>>();
// Creating JSON Parser object
JSONParser jParser = new JSONParser();
// products JSONArray
JSONArray agency = null;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_home, container, false);
btnSubmit = (Button) rootView.findViewById(R.id.town_search);
btnSubmit.setOnClickListener(this);
spinner =(Spinner)rootView.findViewById(R.id.spinner);
spinner.setOnItemSelectedListener(this);
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_spinner_item,list);
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(dataAdapter);
return rootView;
}
// Check if parent activity implements the interface
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
mListener =
(OnFragmentInteractionListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement OnFragmentInteractionListener");
}
}
//add items into spinner dynamically
/*public void addItemsOnSpinner2(View v) {
addItemsOnSpinner2(v);
final List<String> list = new ArrayList<String>();
list.add("list 1");
list.add("list 2");
list.add("list 3");
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_spinner_item,list);
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
}*/
#Override
public void onClick(View v) {
switch (v.getId()){
case R.id.town_search:
String town = (String) spinner.getSelectedItem().toString();
agencySearch(town);
mListener.onFragmentButton();
break;
case R.id.zip_search:
String strZip = ((EditText) v.findViewById(R.id.txt_zip)).getText().toString().trim();
int zip = Integer.parseInt(strZip);
agencySearch(zip);
mListener.onFragmentButton();
break;
/*case R.id.btn_location:
String strZip = v.findViewById(R.id.txt_zip).toString();
int zip = Integer.parseInt(strZip);
agencySearch(zip);
mListener.onFragmentButton();
break;*/
}
}
#Override
public void onItemSelected(AdapterView<?> parent,
View v, int position, long id) {
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
// TODO Auto-generated method stub
}
public void agencySearch(String tsearch) {
// Setting the URL for the Search by Town
String url_search_agency = "http://www.infinitycodeservices.com/get_agency_by_city.php";
// Building parameters for the search
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("City", tsearch));
// Getting JSON string from URL
JSONArray json = jParser.getJSONFromUrl(url_search_agency, params);
for (int i = 0; i < json.length(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
try {
JSONObject c = (JSONObject) json.get(i);
//Fill map
Iterator iter = c.keys();
while(iter.hasNext()) {
String currentKey = (String) iter.next();
map.put(currentKey, c.getString(currentKey));
}
resultsList.add(map);
}
catch (JSONException e) {
e.printStackTrace();
}
};
MainActivity.setResultsList(resultsList);
}
public void agencySearch(int zsearch) {
// Setting the URL for the Search by Zip
String url_search_agency = "http://www.infinitycodeservices.com/get_agency_by_zip.php";
// Building parameters for the search
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("zip", Integer.toString(zsearch)));
// Getting JSON string from URL
JSONArray json = jParser.getJSONFromUrl(url_search_agency, params);
for (int i = 0; i < json.length(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
try {
JSONObject c = (JSONObject) json.get(i);
//Fill map
Iterator iter = c.keys();
while(iter.hasNext()) {
String currentKey = (String) iter.next();
map.put(currentKey, c.getString(currentKey));
}
resultsList.add(map);
}
catch (JSONException e) {
e.printStackTrace();
}
};
MainActivity.setResultsList(resultsList);
}
}