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);
}
}
Related
I am not able to update the values when i click on the search button, The data is fetched but the old fetched data is not getting discards, the fetched data is overlapping over each other
SearchFragment.java
package com.example.recipeappandroid.Fragments;
import android.os.Bundle;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.SearchView;
import android.widget.TextView;
import android.widget.Toast;
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.JsonArrayRequest;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import com.example.recipeappandroid.Adapter.RecipeAdapter;
import com.example.recipeappandroid.Model.Recipe;
import com.example.recipeappandroid.R;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
public class SearchFragment extends Fragment {
Button click;
//public static TextView fetchedText;
ImageView searching_logo;
TextView searching_text;
SearchView searchbar;
String query="";
RecyclerView recyclerView;
public static ArrayList<Recipe> recipeList;
public static RecipeAdapter recipeAdapter;
private RequestQueue mRequestQueue;
private String Api_id= "3f335994";
private String Api_key = "8e99e327d1f2130dc6ab3422e26a95e8";
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_search, container, false);
click = (Button) view.findViewById(R.id.button1);
//fetchedText = (TextView) view.findViewById(R.id.fetcheddata);
searchbar = (SearchView) view.findViewById(R.id.searchbar);
searching_logo = view.findViewById(R.id.searching_logo);
searching_text = view.findViewById(R.id.searching_text);
recyclerView = view.findViewById(R.id.recycler_view);
recyclerView.setHasFixedSize(true);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getContext());
linearLayoutManager.setReverseLayout(true);
linearLayoutManager.setStackFromEnd(true);
recyclerView.setLayoutManager(linearLayoutManager);
//recipeAdapter = new RecipeAdapter();
recipeList = new ArrayList<>();
//getData();
click.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
query = searchbar.getQuery().toString();
String url = "https://api.edamam.com/search?q=" + query + "&app_id=" + Api_id + "&app_key=" + Api_key;
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, url,null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONArray hits = response.getJSONArray("hits");
for (int i =0;i<hits.length();i++) {
JSONObject jsonObject = hits.getJSONObject(i);
JSONObject recipe = jsonObject.getJSONObject("recipe");
String recipe_img = recipe.getString("image");
String recipe_title = recipe.getString("label");
String recipe_data = recipe.getString("source");
recipeList.add(new Recipe(recipe_img,recipe_title,recipe_data));
}
recipeAdapter = new RecipeAdapter(getContext(),recipeList);
recyclerView.setAdapter(recipeAdapter);
recipeAdapter.notifyDataSetChanged();
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
});
mRequestQueue = Volley.newRequestQueue(getContext());
mRequestQueue.add(jsonObjectRequest);
/*JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(url, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
try {
for (int i = 0; i < response.length(); i++) {
JSONObject jsonObject = response.getJSONObject(i);
JSONObject recipes = jsonObject.getJSONObject("recipe");
//Recipe recipe = new Recipe();
String recipe_img = recipes.getString("image");
String recipe_title = recipes.getString("label");
String recipe_data = recipes.getString("source");
recipeList.add(new Recipe(recipe_img,recipe_title,recipe_data));
Log.d("data",recipe_title);
}
//recipeAdapter = new RecipeAdapter(getContext(), recipeList);
//recyclerView.setAdapter(recipeAdapter);
recipeAdapter.notifyDataSetChanged();
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
//Toast.makeText(SearchFragment.this,"Error Occured",Toast.LENGTH_SHORT).show();
error.printStackTrace();
}
});*/
/*jsonArrayRequest.setRetryPolicy(new RetryPolicy() {
#Override
public int getCurrentTimeout() {
return 3000;
}
#Override
public int getCurrentRetryCount() {
return 3000;
}
#Override
public void retry(VolleyError error) throws VolleyError {
}
});*/
/* Log.d("QUEEEERRRYYYY",query);
ApiCall process = new ApiCall(searching_logo,searching_text);
process.execute(query);*/
}
});
return view;
}
}
I want to get rid of the old data after the new data is fetched and don't want to display it after the new one is called
looks like you are only adding items to your ArrayList<Recipe> recipeList;, so they may duplicate
maybe try to recipeList.clear(); it in first line of onResponse method
also notifyDataSetChanged isn't needed, setAdapter does it itself (and a lot more in fact)
I m getting volley timeout error every time i try to insert data..Despite of the error, the data is inserted correctly but its inserting two times every time i press the button.
I need to remove the error and insert data only once. Also it takes too much time after clicking button to display error.
package com.example.sumit.myapplication;
import android.content.Context;
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.CardView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
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 com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.MutableData;
import com.google.firebase.database.Transaction;
import com.google.firebase.database.ValueEventListener;
import java.sql.Connection;
import java.util.HashMap;
import java.util.Map;
/**
* Created by Sumit on 20-02-2018.
*/
public class register extends Fragment{
RequestQueue requestQueue;
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
getActivity().setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
View v = inflater.inflate(R.layout.login,container,false);
return v;
}
public void onCreate(Bundle savedInstancesState)
{
super.onCreate(savedInstancesState);
TextView t = (TextView) ((MainActivity) getActivity()).findViewById(R.id.textView3);
t.setText("Register");
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
final View vt = super.getView();
final CardView b=(CardView)vt.findViewById(R.id.cardView);
final TextView txt = (TextView)vt.findViewById(R.id.uid);
final EditText txt1 = (EditText) vt.findViewById(R.id.editText);
final EditText txt2 = (EditText) vt.findViewById(R.id.editText2);
final EditText txt3 = (EditText) vt.findViewById(R.id.editText3);
final EditText txt4 = (EditText) vt.findViewById(R.id.editText4);
final Spinner hostel1=(Spinner) vt.findViewById(R.id.spinner1);
final Spinner branch1=(Spinner) vt.findViewById(R.id.spinner2);
final String HttpUrl = "https://testzineapp.000webhostapp.com/insert_record.php";
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View vt) {
final String id=txt1.getText().toString().trim();
final String name=txt2.getText().toString().trim();
final String number=txt3.getText().toString().trim();
final String email=txt4.getText().toString().trim();
final String hostel=hostel1.getSelectedItem().toString().trim();
final String branch=branch1.getSelectedItem().toString().trim();
StringRequest stringRequest = new StringRequest(Request.Method.POST, HttpUrl,
new Response.Listener<String>() {
#Override
public void onResponse(String ServerResponse) {
// Showing response message coming from server.
Toast.makeText(getContext(), ServerResponse, Toast.LENGTH_LONG).show();
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError volleyError) {
// Showing error message if something goes wrong.
Toast.makeText(getContext(), volleyError.toString(), Toast.LENGTH_LONG).show();
}
}) {
#Override
protected Map<String, String> getParams() {
// Creating Map String Params.
Map<String, String> params = new HashMap<String, String>();
// Adding All values to Params.
params.put("College_ID", id);
params.put("Name", name);
params.put("Mobile_Number", number);
params.put("Email_ID", email);
params.put("Hosteller", hostel);
params.put("Branch", branch);
return params;
}
};
// Creating RequestQueue.
RequestQueue requestQueue = Volley.newRequestQueue(getContext());
// Adding the StringRequest object into requestQueue.
requestQueue.add(stringRequest);
txt1.setText("");
txt2.setText("");
txt3.setText("");
txt4.setText("");
};
});
super.onViewCreated(view, savedInstanceState);
}
}
Because of volley default retry policy your your request is processing two times, try this code to avoid it.
stringRequest.setRetryPolicy(new DefaultRetryPolicy(20 * 1000, 0, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
RequestQueue requestQueue = Volley.newRequestQueue(_context);
requestQueue.add(stringRequest);
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'm trying to build an app, that pastes an input from a previous activity(works with no problem) and then shows me some things from a database(when ButtonGet is pressed). The problem is that when I try to Run the project, I get
Java.lang.IllegalStateException: Already attached. What is wrong with my code?
package br.exemplozxingintegration;
import android.annotation.SuppressLint;
import android.app.ProgressDialog;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
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;
public class SecondActivity extends AppCompatActivity implements View.OnClickListener {
private EditText pastetext;
private ClipboardManager myClipboard;
private ClipData myClip;
private Button btn;
private EditText textView1;
private Button buttonGet;
private TextView textViewResult;
private ProgressDialog loading;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
myClipboard = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
pastetext = (EditText) findViewById(R.id.textView1);
btn = (Button)findViewById(R.id.buttonPaste);
btn.performClick();
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView1 = (EditText) findViewById(R.id.textView1);
buttonGet = (Button) findViewById(R.id.buttonGet);
textViewResult = (TextView) findViewById(R.id.textViewResult);
buttonGet.setOnClickListener(this);
}
#SuppressLint("NewApi")
public void paste(View view) {
ClipData cp = myClipboard.getPrimaryClip();
ClipData.Item item = cp.getItemAt(0);
String text = item.getText().toString();
pastetext.setText(text);
Toast.makeText(getApplicationContext(), "Text Pasted",
Toast.LENGTH_SHORT).show();
}
private void getData() {
String id = textView1.getText().toString().trim();
if (id.equals("")) {
Toast.makeText(this, "", Toast.LENGTH_LONG).show();
return;
}
loading = ProgressDialog.show(this,"Please wait...","Fetching...",false,false);
String url = Config.DATA_URL+textView1.getText().toString().trim();
StringRequest stringRequest = new StringRequest(url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
loading.dismiss();
showJSON(response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(SecondActivity.this,error.getMessage().toString(),Toast.LENGTH_LONG).show();
}
});
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
private void showJSON(String response){
String name="";
String image = "";
try {
JSONObject jsonObject = new JSONObject(response);
JSONArray result = jsonObject.getJSONArray(Config.JSON_ARRAY);
JSONObject collegeData = result.getJSONObject(0);
name = collegeData.getString(Config.KEY_NAME);
image = collegeData.getString(Config.KEY_IMAGE);
} catch (JSONException e) {
e.printStackTrace();
}
textViewResult.setText("Name:\t"+name+"\nImagine :\t"+ image);
}
#Override
public void onClick(View v) {
getData();
}
}
In your onCreate, you're calling super.onCreate() twice, and also setContentView() twice. I'm pretty sure that's not what you want to do.
Problem is you first initialize textView1, and perform the button click, at that point you are just resetting any previous settings by calling onCreate() again, and before perfomClick methods hits getData() method, inside here also tries to access the text from textView1 but you called onCreate after that and set the view from scratch. That is why you cannot get it work, delete the duplicate code
Please attach logcat message and if possible DB file.
This could be the possible problem, You might be reassign the already assigned db object while inserting in the table.
If none of the answers here helped - and the Log message makes no sense - I recommend you to File->Invalidate cahce
then run the app again and hopefully this time the log will show the correct stack trace.
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/