Display to another activity json array result from onPostExecute - java

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

Related

volley timeout error...Data inserting two times

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);

Getting null object - send data from one activity to another

I have a class which implements serializable and I am trying to send it's object using intent , so I am getting null object when I set that object using putExtra();
Below is my code.
YelpSearch.java(fromClass)
import android.app.ListActivity;
import android.support.v4.app.Fragment;
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.view.Window;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class YelpSearch extends ListActivity implements Serializable {
#SuppressWarnings("serial")
class Business implements Serializable {
final String name;
final String url;
final String id;
public Business(String name, String url, String id) {
this.name = name;
this.url = url;
this.id = id;
}
#Override
public String toString() {
return name;
}
}
#Override
public void onCreate(Bundle savedInstanceState) {
requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
super.onCreate(savedInstanceState);
setTitle("Finding Tacos...");
setProgressBarIndeterminateVisibility(true);
Log.v("TAG","YelpSearchOnCreate");
new AsyncTask<Void, Void, List<Business>>() {
#Override
protected List<Business> doInBackground(Void... params) {
Log.v("TAG","Async List");
String businesses = Yelp.getYelp(YelpSearch.this).search("food", "91754");
Log.v("TAG","String businsesses"+businesses);
try {
Log.v("TAG","try");
return processJson(businesses);
} catch (JSONException e) {
return Collections.<Business>emptyList();
}
}
#Override
protected void onPostExecute(List<Business> businesses) {
Log.v("TAG","onPostExecute");
Log.v("BusinessesList","Businesses "+ businesses);
//setTitle("Tacos Found");
setProgressBarIndeterminateVisibility(false);
getListView().setAdapter(new ArrayAdapter<Business>(YelpSearch.this, android.R.layout.simple_list_item_1, businesses));
}
}.execute();
}
#Override
protected void onListItemClick(ListView listView, View view, int position, long id) {
Business biz = (Business) listView.getItemAtPosition(position);
Log.v("Sending data to Detail","hi "+biz);
//startActivity(new Intent(Intent.ACTION_VIEW,Uri.parse(biz.url)));
Intent intent = new Intent(getApplicationContext(), YelpBizDetail.class);
// Intent intent = new Intent(YelpSearch.this,YelpBizDetail.class).putExtra("myCustomerObj",biz);
intent.putExtra("Detailclass",biz);
Log.v("Sending data to Detail","sent "+biz);
startActivity(intent);
}
List<Business> processJson(String jsonStuff) throws JSONException {
JSONObject json = new JSONObject(jsonStuff);
JSONArray businesses = json.getJSONArray("businesses");
ArrayList<Business> businessObjs = new ArrayList<Business>(businesses.length());
for (int i = 0; i < businesses.length(); i++) {
JSONObject business = businesses.getJSONObject(i);
businessObjs.add(new Business(business.optString("name"), business.optString("mobile_url"),business.optString("id")));
}
return businessObjs;
}
}
YelpBizDetail(toClass)
import android.app.Activity;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.widget.ArrayAdapter;
import com.....projectmaw.YelpSearch.Business;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class YelpBizDetail extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.yelp_biz_detail);
Intent i = getIntent();
Business biz = (Business) i.getSerializableExtra("Detailclass");
// String biz = (String) i.getSerializableExtra("Detailclass");
//String biz = (String) i.getSerializableExtra("Detailclass");
Log.v("Received on Detail","data "+biz);
}
}
Try making some changes in onListItemClick in your YelpSearch.java, like change your startActivity(intent) with
startActivity(new Intent(getApplicationContext(), YelpBizDetail.class).putExtra("Detailclass",biz)); this will create new intent when new activity is started. and remove
Log.v("Sending data to Detail","hi "+biz);
//startActivity(new Intent(Intent.ACTION_VIEW,Uri.parse(biz.url)));
Intent intent = new Intent(getApplicationContext(), YelpBizDetail.class);
// Intent intent = new Intent(YelpSearch.this,YelpBizDetail.class).putExtra("myCustomerObj",biz);
intent.putExtra("Detailclass",biz);
Log.v("Sending data to Detail","sent "+biz);

onPostExecute gets called too late

First I will describe the process/problem briefly in words. Afterwards, I'll attach all of the code.
I start the android application in debug mode.
Main activity gets called.
It calls Activity2 via "intent".
Then (in onCreate) I start an Async activity in order to get information from a webserver. I do that with this command "new Kontakt(info1, info2, information).execute();"
I've put a break point at the onPostExecute method in "Kontakt" to see what happens. But!! It doesn't stop there. So then I figured, "okey, the doInBackground method didn't get called for some reason"
When I continue to run the code, as a surprise, onPostExecute gets called (somewhere at the end of onClick) and stops at the break point just the way I want it but than it's too late, because I'd like to have the output already in the onCreate method where I called "new Kontakt(info1, info2, information).execute();".
So why does it call onPostExecute too late and what can I do to make the process call it properly already in onCreate at the line "new Kontakt(info1, info2, information).execute();" in Activity2?
The code is below
MainActivity.java
package com.example.myapplication;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.graphics.PorterDuff;
import android.graphics.drawable.Drawable;
import android.preference.PreferenceManager;
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.Button;
import android.widget.TextView;
public class MainActivity extends ActionBarActivity implements View.OnClickListener {
Button button1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button1 = (Button) findViewById(R.id.button1);
button1.setOnClickListener(this);
}
#Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.button1:
Intent intent = new Intent(this, Activity2.class);
startActivity(intent);
break;
}
}
}
Activity2.java
package com.example.myapplication;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.preference.PreferenceManager;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.text.InputType;
import android.text.TextUtils;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
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 java.io.IOException;
import java.net.MalformedURLException;
import java.util.ArrayList;
public class Activty2 extends ActionBarActivity implements View.OnClickListener {
Button button;
Context information;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity2);
information=this;
String info1="Yeah";
String info2="Yeah";
new Kontakt(info1, info2, information).execute();
button = (Button) findViewById(R.id.button);
button.setOnClickListener(this);
}
#Override
public void onClick(View view) {
if (view.getId() == R.id.button) {
}
}
Kontakt.java
package com.example.myapplication;
import android.content.Context;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.util.Log;
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.json.JSONObject;
import java.util.ArrayList;
public class Kontakt extends AsyncTask<Void, Void, Integer> {
public static final int CONNECTION_TIMEOUT = 1000 * 15;
public static final String SERVER_ADDRESS = "http://test.site.net/";
String info1;
String info2;
private final Context information;
public Kontakt(String info1, String info2, Context context) {
this.info1=info1;
this.Info2=info2;
this.information=context;
}
#Override
protected Integer doInBackground(Void... params) {
ArrayList<NameValuePair> dataToSend = new ArrayList<>();
dataToSend.add(new BasicNameValuePair("user", info1));
dataToSend.add(new BasicNameValuePair("password", info2));
HttpParams httpRequestParams = getHttpRequestParams();
HttpClient client = new DefaultHttpClient(httpRequestParams);
HttpPost post = new HttpPost(SERVER_ADDRESS
+ "Register.php");
try {
post.setEntity(new UrlEncodedFormEntity(dataToSend));
client.execute(post);
int result=1;
return result;
} catch (Exception e) {
e.printStackTrace();
int result=0;
return result;
}
//return null;
}
private HttpParams getHttpRequestParams() {
HttpParams httpRequestParams = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpRequestParams,
CONNECTION_TIMEOUT);
HttpConnectionParams.setSoTimeout(httpRequestParams,
CONNECTION_TIMEOUT);
return httpRequestParams;
}
#Override
protected void onPostExecute(Integer result)
{
super.onPostExecute(result);
SharedPreferences.Editor editor = information.getSharedPreferences("INTERNET_KOLL", Context.MODE_PRIVATE).edit();
editor.putString("internet_status", String.valueOf(result));
editor.commit();
}
}
In Activity2, when onCreate() calls new Kontakt(info1, info2, information).execute();:
an asynchronous task (Kontakt) is started in the background
the execution of onCreate() continues
so it's normal that you don't have the response immediately.

List view project android

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/

Text-to-Speech Function not working

The Android does not talk despite my code being error free and accurate. I have used a toast function to see where the issue occurs. However, both toasts are called.
I have removed all irrelevant code.
The code below is mostly relevant.
package com.example.android.BluetoothChat;
import android.R.string;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.content.Context;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.speech.tts.TextToSpeech;
import android.speech.tts.TextToSpeech.OnInitListener;
import android.telephony.SmsManager;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import java.util.Locale;
import java.util.Set;
import android.bluetooth.BluetoothDevice;
import java.io.InputStream;
import java.io.OutputStream;
import android.bluetooth.BluetoothSocket;
import android.widget.EditText;
import java.io.IOException;
import java.util.UUID;
public class MainActivity extends Activity implements LocationListener{
Button start, stop;
TextView tv;
TextView tv2;
TextView sum;
LocationManager lm;
static TextToSpeech Talker;
TextView myLabel;
Handler mhandler = new Handler();
int i;
int sum1 = 0;
static BluetoothDevice mmDevice;
static BluetoothAdapter mBluetoothAdapter;
static BluetoothSocket mmSocket;
String lat;
String lon;
EditText myTextbox;
static OutputStream mmOutputStream;
static InputStream mmInputStream;
static Thread workerThread;
static byte[] readBuffer;
static int readBufferPosition;
static int counter;
static volatile boolean stopWorker;
TextToSpeech talker;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main2);
setTitle("Seizure Detection Helmet Application");
myTextbox = (EditText)this.findViewById(R.id.name);
talker = new TextToSpeech(getApplicationContext(),new TextToSpeech.OnInitListener() {
#Override
public void onInit(int status) {
if(status != TextToSpeech.ERROR)
{
talker.setLanguage(Locale.US);
}
}
});
Button talk = (Button)this.findViewById(R.id.talk);
talk.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
speakOut();
}
});
public void speakOut()
{
String toSpeak = myTextbox.getText().toString();
Toast.makeText(getApplicationContext(), toSpeak, Toast.LENGTH_SHORT).show();
String full = ("My name is"+toSpeak+ "and I am having a Seizure at 38.901 Latitude and -77.031 Longitude ");
Toast.makeText(getApplicationContext(), toSpeak, Toast.LENGTH_SHORT).show();
talker.speak(full, TextToSpeech.QUEUE_FLUSH, null);
Toast.makeText(getApplicationContext(), full, Toast.LENGTH_SHORT).show();
talker.speak("HELLO",TextToSpeech.QUEUE_FLUSH, null);
}
}
There are several problems with your code. You should check for error returned by setLanguage. You cannot call speakOut until onInit has been called. One way you can insure this is to disable the talk button in the xml layout file and enable it in onInit.

Categories