JSON array problem - Java for Android App Development

I used the application in the tutorial here(how to connect android with mySQL throw PHP) and it worked pretty well.
I wanted to try to make a easy social/blog as twitter, where the user input a post and it saves up in the DB, and this part works. The problem is that i also want to view all the post already posted in the application.
But it crash and i cant understand why:
Code:
package com.example.android;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
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.JSONObject;
import java.util.ArrayList;
import java.util.Calendar;
public class MainActivity extends Activity {
Button buttonGetData = null;
TextView textViewUser = null;
TextView textViewMessage = null;
TextView textViewDate= null;
EditText editTextMessage = null;
[user=439709]@override[/user]
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
buttonGetData = (Button) findViewById(R.id.buttonGetData);
textViewUser = (TextView) findViewById(R.id.textViewUser);
textViewMessage = (TextView) findViewById(R.id.textViewMessage);
textViewDate = (TextView) findViewById(R.id.textViewDate);
editTextMessage = (EditText) findViewById(R.id.editTextMessage);
buttonGetData.setOnClickListener(new View.OnClickListener() {
[user=439709]@override[/user]
public void onClick(View v) {
//Get the data
String mydate = java.text.DateFormat.getDateTimeInstance().format(Calendar.getInstance().getTime());
String message;
message = editTextMessage.getText().toString();
DoPOST mDoPOST = new DoPOST(MainActivity.this, message, mydate);
mDoPOST.execute("");
buttonGetData.setEnabled(false);
}
});
}
[user=439709]@override[/user]
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public class DoPOST extends AsyncTask <String,Void,Boolean>{
Context mContext = null;
String strMessage = "";
String strDate = "";
String[] resUser;
String[] resMessage;
String[] resDate;
DoPOST(Context context, String Message, String mydate){
mContext = context;
strMessage = Message;
strDate = mydate;
}
Exception exception = null;
[user=439709]@override[/user]
protected Boolean doInBackground(String... arg0) {
try{
//Setup the parameters
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("User", "Daniel"));
nameValuePairs.add(new BasicNameValuePair("Message", strMessage));
nameValuePairs.add(new BasicNameValuePair("Date", strDate));
//Add more parameters as necessary
//Create the HTTP request
HttpParams httpParameters = new BasicHttpParams();
//Setup timeouts
HttpConnectionParams.setConnectionTimeout(httpParameters, 15000);
HttpConnectionParams.setSoTimeout(httpParameters, 15000);
HttpClient httpclient = new DefaultHttpClient(httpParameters);
HttpPost httppost = new HttpPost("http://deeniel.altervista.org/blog.php");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
String result = EntityUtils.toString(entity);
// Create a JSON object from the request response
JSONArray jObject = new JSONArray(result);
for (int i = 0; i < jObject.length(); i++) {
JSONObject menuObject = jObject.getJSONObject(i);
//resUser[i] = menuObject.getString("User");
resMessage[i] = menuObject.getString("Message");
//resDate[i] = menuObject.getString("Date");
}
}
catch(Exception e){
Log.e("ClientServerDemo", "Error:", e);
exception = e;
}
return null;
}
[user=439709]@override[/user]
protected void onPostExecute(Boolean valid){
//Update the UI
// textViewUser.setText(resUser[0]);
textViewMessage.setText(resMessage[0]);
// textViewDate.setText(resDate[0]);
buttonGetData.setEnabled(true);
if(exception != null){
Toast.makeText(mContext, exception.getMessage(), Toast.LENGTH_LONG).show();
}
}
}
}
In the for loop i also tried instead of adding the json array into a string[]like this:
resMessage = menuObject.getString("Message");
i also tryied withoth a string array, by concatenating inside the for:
resMessage = resMessage + menuObject.getString("Message");
And it doesnt give me any problem to save all the array inside and show it up in the textView.
SO why like this it crash?
Code:
07-06 09:07:49.815 19475-19589/com.example.android E/ClientServerDemo: Error:
java.lang.NullPointerException
at com.example.android.MainActivity$DoPOST.doInBackground(MainActivity.java:130)
at com.example.android.MainActivity$DoPOST.doInBackground(MainActivity.java:77)
at android.os.AsyncTask$2.call(AsyncTask.java:287)
at java.util.concurrent.FutureTask.run(FutureTask.java:234)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
at java.lang.Thread.run(Thread.java:856)
07-06 09:07:49.815 19475-19475/com.example.android E/AndroidRuntime: FATAL EXCEPTION: main
java.lang.NullPointerException
at com.example.android.MainActivity$DoPOST.onPostExecute(MainActivity.java:151)
at com.example.android.MainActivity$DoPOST.onPostExecute(MainActivity.java:77)
at android.os.AsyncTask.finish(AsyncTask.java:631)
at android.os.AsyncTask.access$600(AsyncTask.java:177)
at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:644)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:5226)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:795)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:562)
at dalvik.system.NativeStart.main(Native Method)

don't you need to initialize resMessage before you use it?
Code:
resMessage = new String[jObject.length()]

I use Google's gson library for JSON. I think it is much easier.

Related

ProgressDialog don't appear

Hy please help me!!
My full code:
Code:
package com.android.skiptvad;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.List;
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.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.graphics.LightingColorFilter;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.android.skiptvad.*;
public class Login extends Activity {
private static final int DIALOG_LOADING = 0;
/** Called when the activity is first created. */
TextView tvuser;
String sessionid;
ProgressDialog pd = null;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.login);
tvuser = (TextView) findViewById(R.id.tvuser);
TextView tvpw = (TextView) findViewById(R.id.tvpw);
final EditText etuser = (EditText) findViewById(R.id.etuser);
final EditText etpw = (EditText) findViewById(R.id.etpw);
Button btlogin = (Button)findViewById(R.id.btlogin);
btlogin.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
if (etuser.getText() != null && etpw.getText()!= null)
{
pd = ProgressDialog.show(Login.this,"","Loading. Please wait...", true);
pd.show();
Thread t = new Thread() {
public void run(){
download(etuser.getText().toString(), md5(etpw.getText().toString()));
pd.dismiss();
}
};
t.run();
}
}
});
}
public void download (final String user, final String pw)
{
try{
HttpClient client = new DefaultHttpClient();
String postURL = "http://surfkid.redio.de/login";
HttpPost post = new HttpPost(postURL);
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("username", user));
params.add(new BasicNameValuePair("password", pw));
UrlEncodedFormEntity ent = new UrlEncodedFormEntity(params,HTTP.UTF_8);
post.setEntity(ent);
HttpResponse responsePOST = client.execute(post);
HttpEntity resEntity = responsePOST.getEntity();
final JSONObject jObject = new JSONObject(EntityUtils.toString(resEntity));
JSONObject menuObject = jObject.getJSONObject("responseData");
if (jObject.getInt("responseStatus")== 200 && jObject.get("responseDetails")!= null)
{
sessionid = menuObject.getString("session_id");
//dismissDialog(DIALOG_LOADING);
// pd.dismiss();
}
else
{
//dismissDialog(DIALOG_LOADING);
if (jObject.getInt("responseStatus")== 500)
{
throw new Exception("Server Error");
}
else if (jObject.getInt("responseStatus")== 400)
{
throw new Exception("Wrong User/Password");
}
else
{
throw new Exception();
}
}
//pd.dismiss();
} catch (Exception e) {
//dismissDialog(DIALOG_LOADING);
Toast toast ;
toast = Toast.makeText(getApplicationContext(), e.getMessage(), 500);
toast.show();
}
}
private String md5(String in) {
MessageDigest digest;
try {
digest = MessageDigest.getInstance("MD5");
digest.reset();
digest.update(in.getBytes());
byte[] a = digest.digest();
int len = a.length;
StringBuilder sb = new StringBuilder(len << 1);
for (int i = 0; i < len; i++) {
sb.append(Character.forDigit((a[i] & 0xf0) >> 4, 16));
sb.append(Character.forDigit(a[i] & 0x0f, 16));
}
return sb.toString();
} catch (NoSuchAlgorithmException e) { e.printStackTrace(); }
return null;
}
@Override
protected Dialog onCreateDialog(int id) {
Dialog dialog = null;
switch (id) {
case DIALOG_LOADING:
dialog = new ProgressDialog(this);
((ProgressDialog) dialog).setMessage("Loading, please wait...");
break;
}
return dialog;
}
}
My Problem is that the ProgressDialog don't appear.
Please help!!

client side error

package com.example.project10;
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.StrictMode;
import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapPrimitive;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;
import android.view.Menu;
import android.widget.TextView;
public class MainActivity extends Activity {
private static final String SOAP_ACTION = "http://Sample/customerData/";
private static final String METHOD_NAME = "customerData";
private static final String NAMESPACE = "http://Sample";
private static final String URL = "http://192.168.1.16:8080/Project10/services/SampleMain?wsdl";
/** Called when the activity is first created. */
private Thread thread;
public TextView tv;
public String resultArr[];
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv =(TextView)findViewById(R.id.textView1);
startWebAccess();
//for(int i = 0; i<resultArr.length;i++){
// tv.append(resultArr+"\n\n");
// }
// setContentView(tv);
}
public void startWebAccess(){
thread = new Thread(){
public void run(){
SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.setOutputSoapObject(request);
HttpTransportSE ht = new HttpTransportSE(URL);
try {
ht.call(SOAP_ACTION, envelope);
Object response= envelope.getResponse();
//SoapPrimitive response = (SoapPrimitive)envelope.getResponse();
//SoapPrimitive s = response;
String str = response.toString();
System.out.println(str);
if(str!=null){
System.out.println(".....");
}
String resultArr[] = str.split("&");//Result string will split & store in an array
for(int i = 0; i<resultArr.length;i++){
tv.append(resultArr+"\n\n");
// tv.append(str);
}
setContentView(tv);
} catch (Exception e) {
e.printStackTrace();
}
}
};
thread.start();
}
@override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
This is my source code ,i am getting error so help me..
Magesh.K said:
package com.example.project10;
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.StrictMode;
import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapPrimitive;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;
import android.view.Menu;
import android.widget.TextView;
public class MainActivity extends Activity {
private static final String SOAP_ACTION = "http://Sample/customerData/";
private static final String METHOD_NAME = "customerData";
private static final String NAMESPACE = "http://Sample";
private static final String URL = "http://192.168.1.16:8080/Project10/services/SampleMain?wsdl";
/** Called when the activity is first created. */
private Thread thread;
public TextView tv;
public String resultArr[];
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv =(TextView)findViewById(R.id.textView1);
startWebAccess();
//for(int i = 0; i<resultArr.length;i++){
// tv.append(resultArr+"\n\n");
// }
// setContentView(tv);
}
public void startWebAccess(){
thread = new Thread(){
public void run(){
SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.setOutputSoapObject(request);
HttpTransportSE ht = new HttpTransportSE(URL);
try {
ht.call(SOAP_ACTION, envelope);
Object response= envelope.getResponse();
//SoapPrimitive response = (SoapPrimitive)envelope.getResponse();
//SoapPrimitive s = response;
String str = response.toString();
System.out.println(str);
if(str!=null){
System.out.println(".....");
}
String resultArr[] = str.split("&");//Result string will split & store in an array
for(int i = 0; i<resultArr.length;i++){
tv.append(resultArr+"\n\n");
// tv.append(str);
}
setContentView(tv);
} catch (Exception e) {
e.printStackTrace();
}
}
};
thread.start();
}
@override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
This is my source code ,i am getting error so help me..
Click to expand...
Click to collapse
What is the error that you're getting ? .. A logcat would be appreciated !

Updating tabs to new tab fragments

Hi all,
I had an app that was working about 3 years ago that I decided to update for the latest android sdk.I was using tabs but have decided to update to tab fragments with swipe.The problem I'm having is how to lay out the code.I have updated my app but have a few errors.Specifically the Book Now tab usually has a book now form so people can fill it out and upon clicking submit it sms's it to me.Below is the code for BookNowFragmnet.java.
I should mention that the tab and swipe part works flawlessly.I dont have a logcat because it wont build without removing the code
PHP:
package com.deano.dfw;
import android.app.Activity;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.telephony.SmsManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class BookNowFragment extends Fragment implements OnClickListener {
Button buttonSubmit;
EditText edittextPhone;
EditText editTextProblem;
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_booknow, container, false);
buttonSubmit = (Button) rootView.findViewById(R.id.buttonSubmit);
edittextPhone = (EditText) rootView.findViewById(R.id.edittextPhone);
editTextProblem = (EditText) rootView.findViewById(R.id.editTextProblem);
buttonSubmit.setOnClickListener(new View.OnClickListener() {
public void onClick(View v)
{
String phoneNo = edittextPhone.getText().toString();
String message = editTextProblem.getText().toString();
if (phoneNo.length()>0 && message.length()>0)
sendSMS(phoneNo, message);
else
Toast.makeText(getBaseContext(),
"Please enter both phone number and message.",
Toast.LENGTH_SHORT).show();
}
});
return rootView;
}
// ---sends a SMS message to another device---
private void sendSMS(String phoneNumber, String message) {
/*
* PendingIntent pi = PendingIntent.getActivity(this, 0, new
* Intent(this, test.class), 0); SmsManager sms =
* SmsManager.getDefault(); sms.sendTextMessage(phoneNumber, null,
* message, pi, null);
*/
String SENT = "SMS_SENT";
// String DELIVERED = "SMS_DELIVERED";
PendingIntent sentPI = PendingIntent.getBroadcast(this, 0, new Intent(
SENT), 0);
/*
* PendingIntent deliveredPI = PendingIntent.getBroadcast(this, 0, new
* Intent(DELIVERED), 0);
*/
// ---when the SMS has been sent---
registerReceiver(new BroadcastReceiver() {
@Override
public void onReceive(Context arg0, Intent arg1) {
switch (getResultCode()) {
case Activity.RESULT_OK:
Toast.makeText(getBaseContext(), "Message Sent",
Toast.LENGTH_SHORT).show();
break;
case SmsManager.RESULT_ERROR_GENERIC_FAILURE:
Toast.makeText(getBaseContext(), "Generic failure",
Toast.LENGTH_SHORT).show();
break;
case SmsManager.RESULT_ERROR_NO_SERVICE:
Toast.makeText(getBaseContext(), "No service",
Toast.LENGTH_SHORT).show();
break;
case SmsManager.RESULT_ERROR_NULL_PDU:
Toast.makeText(getBaseContext(), "Null PDU",
Toast.LENGTH_SHORT).show();
break;
case SmsManager.RESULT_ERROR_RADIO_OFF:
Toast.makeText(getBaseContext(), "Radio off",
Toast.LENGTH_SHORT).show();
break;
}
}
}, new IntentFilter(SENT));
SmsManager sms = SmsManager.getDefault();
sms.sendTextMessage(phoneNumber, null, message, sentPI, null);
}
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
}
}
The problem areas are as follows;
1. getBaseContext has the error "The method getBaseContext is undefined for the type new View.OnClickListener"
PHP:
Toast.makeText(getBaseContext(),
"Please enter both phone number and message.",
Toast.LENGTH_SHORT).show();
2. getBroadcast has the error "The method getBroadcast(Context, int, Intent, int) in the type PendingIntent is not applicable for the arguments (BookNowFragment, int, Intent, int)"
PHP:
PendingIntent sentPI = PendingIntent.getBroadcast(this, 0, new Intent(SENT), 0);
3.registerReceiver has the error "The method registerReceiver(new BroadcastReceiver(){}, IntentFilter) is undefined for the type BookNowFragment"
PHP:
// ---when the SMS has been sent---
registerReceiver(new BroadcastReceiver() {
4. all of the getBaseContext under the following have the error "The method getBaseContext() is undefined for the type new BroadcastReceiver"
PHP:
public void onReceive(Context arg0, Intent arg1) {
switch (getResultCode()) {
case Activity.RESULT_OK:
Toast.makeText(getBaseContext(), "Message Sent",
Toast.LENGTH_SHORT).show();
break;
case SmsManager.RESULT_ERROR_GENERIC_FAILURE:
Toast.makeText(getBaseContext(), "Generic failure",
Toast.LENGTH_SHORT).show();
break;
case SmsManager.RESULT_ERROR_NO_SERVICE:
Toast.makeText(getBaseContext(), "No service",
Toast.LENGTH_SHORT).show();
break;
case SmsManager.RESULT_ERROR_NULL_PDU:
Toast.makeText(getBaseContext(), "Null PDU",
Toast.LENGTH_SHORT).show();
break;
case SmsManager.RESULT_ERROR_RADIO_OFF:
Toast.makeText(getBaseContext(), "Radio off",
Toast.LENGTH_SHORT).show();
break;
}
}
}, new IntentFilter(SENT));
any help would be appreciated I have searched for the last two days trying different things.
dfwcomputer said:
1. getBaseContext has the error "The method getBaseContext is undefined for the type new View.OnClickListener"
PHP:
Toast.makeText(getBaseContext(),
"Please enter both phone number and message.",
Toast.LENGTH_SHORT).show();
Click to expand...
Click to collapse
So you are asking for the method "getBaseContext" within an onClickListener... it does not have a method called that... like it's telling you it's undefined
It would probably be a better idea to use application context either by direct use of getApplicationContext or by a "final" reference maybe...
dfwcomputer said:
2. getBroadcast has the error "The method getBroadcast(Context, int, Intent, int) in the type PendingIntent is not applicable for the arguments (BookNowFragment, int, Intent, int)"
PHP:
PendingIntent sentPI = PendingIntent.getBroadcast(this, 0, new Intent(SENT), 0);
Click to expand...
Click to collapse
BookNowFragment is not extended from the base type of Context that is expected in the arguments.
dfwcomputer said:
3.registerReceiver has the error "The method registerReceiver(new BroadcastReceiver(){}, IntentFilter) is undefined for the type BookNowFragment"
PHP:
// ---when the SMS has been sent---
registerReceiver(new BroadcastReceiver() {
Click to expand...
Click to collapse
dfwcomputer said:
4. all of the getBaseContext under the following have the error "The method getBaseContext() is undefined for the type new BroadcastReceiver"
PHP:
public void onReceive(Context arg0, Intent arg1) {
switch (getResultCode()) {
case Activity.RESULT_OK:
Toast.makeText(getBaseContext(), "Message Sent",
Toast.LENGTH_SHORT).show();
break;
case SmsManager.RESULT_ERROR_GENERIC_FAILURE:
Toast.makeText(getBaseContext(), "Generic failure",
Toast.LENGTH_SHORT).show();
break;
case SmsManager.RESULT_ERROR_NO_SERVICE:
Toast.makeText(getBaseContext(), "No service",
Toast.LENGTH_SHORT).show();
break;
case SmsManager.RESULT_ERROR_NULL_PDU:
Toast.makeText(getBaseContext(), "Null PDU",
Toast.LENGTH_SHORT).show();
break;
case SmsManager.RESULT_ERROR_RADIO_OFF:
Toast.makeText(getBaseContext(), "Radio off",
Toast.LENGTH_SHORT).show();
break;
}
}
}, new IntentFilter(SENT));
any help would be appreciated I have searched for the last two days trying different things.
Click to expand...
Click to collapse
Actually the last to are just repeats of the previous really... I'm guessing here but it seems you may have skipped ahead of where you should be in a learning sense.. cause it seems to be like your running without being knowing how to jog kinda thing. Not attempting to be condescending, just I'm a trainer and always attempt to point this stuff out when I see it
Maybe go back and do some of the basics again, and include fragments etc
thanks, Im well aware i'm running before im born but this is the only app I intend to write as it's specifically for my business.
dfwcomputer said:
thanks, Im well aware i'm running before im born but this is the only app I intend to write as it's specifically for my business.
Click to expand...
Click to collapse
hmmm, well if thats all thats wrong with it, all I could offer is for you to send me the packaged src+res and I will have a look... if it takes less than 20 min to fix and get running I have no problem fixing it for you. If it doesn't and maybe takes longer then I may have to leave it. Should be quick though, up to you
But with the info I gave you should be able to fix those 4 issues...if not hit me up on hangouts and will talk you though it
thanks m8.Ill play around today but if I cant figure it out I might get you to have a look if time permits.I develop in eclipse.Is it a matter of just zipping up the project folder?
dfwcomputer said:
thanks m8.Ill play around today but if I cant figure it out I might get you to have a look if time permits.I develop in eclipse.Is it a matter of just zipping up the project folder?
Click to expand...
Click to collapse
Yeah, just zip the project.
But like I say just get a reference to the activity to use as the "context" part of the argument, either where you need it or as a final reference or member variable
so getActivity()
or memberVar
Context mContext = null;
(in onCreate) mContext = getActivity();
or as final
final Context c = getActivity();
deanwray said:
Yeah, just zip the project.
But like I say just get a reference to the activity to use as the "context" part of the argument, either where you need it or as a final reference or member variable
so getActivity()
or memberVar
Context mContext = null;
(in onCreate) mContext = getActivity();
or as final
final Context c = getActivity();
Click to expand...
Click to collapse
lol now I have less faith ill be fixing it..... Ill let you know thanks again
sent you a private message m8, because there is some personal info in the app
dfwcomputer said:
sent you a private message m8, because there is some personal info in the app
Click to expand...
Click to collapse
fixed and sent private msg with class
Thanks again, I apreciate it.I have changed the personal info and posted the working code here incase someone else has a similar issue.
PHP:
package com.deano.dfw;
import android.app.Activity;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.telephony.SmsManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class BookNowFragment extends Fragment implements OnClickListener {
Button buttonSubmit;
EditText edittextPhone;
EditText editTextProblem;
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final View rootView = inflater.inflate(R.layout.fragment_booknow, container, false);
buttonSubmit = (Button) rootView.findViewById(R.id.buttonSubmit);
//edittextPhone = (EditText) rootView.findViewById(R.id.edittextPhone);
//editTextProblem = (EditText) rootView.findViewById(R.id.editTextProblem);
buttonSubmit.setOnClickListener(new View.OnClickListener() {
public void onClick(View v)
{
String strPhoneNo = "0000000000";
TextView txtName = (TextView) rootView.findViewById(R.id.edittextName);
TextView txtPhone = (TextView) rootView.findViewById(R.id.edittextPhone);
TextView txtProblem = (TextView) rootView.findViewById(R.id.editTextProblem);
String strName = "Name: " + txtName.getText().toString();
String strPhone = "Phone: " + txtPhone.getText().toString();
String strProblem = "Problem: "
+ txtProblem.getText().toString();
String strMessage = strName + "\n" + strPhone + "\n"
+ strProblem;
BookNowSMS(strPhoneNo, strMessage);
}
});
return rootView;
}
// ---sends a SMS message to another device---
private void BookNowSMS(String phoneNumber, String message) {
/*
* PendingIntent pi = PendingIntent.getActivity(this, 0, new
* Intent(this, test.class), 0); SmsManager sms =
* SmsManager.getDefault(); sms.sendTextMessage(phoneNumber, null,
* message, pi, null);
*/
String SENT = "SMS_SENT";
// String DELIVERED = "SMS_DELIVERED";
PendingIntent sentPI = PendingIntent.getBroadcast(getActivity(), 0, new Intent(
SENT), 0);
/*
* PendingIntent deliveredPI = PendingIntent.getBroadcast(this, 0, new
* Intent(DELIVERED), 0);
*/
// ---when the SMS has been sent---
getActivity().registerReceiver(new BroadcastReceiver() {
@Override
public void onReceive(Context arg0, Intent arg1) {
switch (getResultCode()) {
case Activity.RESULT_OK:
Toast.makeText(getActivity(), "Message Sent",
Toast.LENGTH_SHORT).show();
break;
case SmsManager.RESULT_ERROR_GENERIC_FAILURE:
Toast.makeText(getActivity(), "Generic failure",
Toast.LENGTH_SHORT).show();
break;
case SmsManager.RESULT_ERROR_NO_SERVICE:
Toast.makeText(getActivity(), "No service",
Toast.LENGTH_SHORT).show();
break;
case SmsManager.RESULT_ERROR_NULL_PDU:
Toast.makeText(getActivity(), "Null PDU",
Toast.LENGTH_SHORT).show();
break;
case SmsManager.RESULT_ERROR_RADIO_OFF:
Toast.makeText(getActivity(), "Radio off",
Toast.LENGTH_SHORT).show();
break;
}
}
}, new IntentFilter(SENT));
SmsManager sms = SmsManager.getDefault();
sms.sendTextMessage(phoneNumber, null, message, sentPI, null);
}
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
}
}
I forgot the date and time picker arrrrrrrgh
I've added the following 2 classes which have no errors and seem to function fine.
DatePickerFragment.java
PHP:
package com.test.dfw;
import java.util.Calendar;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.widget.DatePicker;
import android.widget.TextView;
public class DatePickerFragment extends DialogFragment implements DatePickerDialog.OnDateSetListener{
TextView txtDate;
public DatePickerFragment(TextView txtDate) {
super();
this.txtDate = txtDate;
}
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
// Use the current date as the default date in the picker
final Calendar c = Calendar.getInstance();
int year = c.get(Calendar.YEAR);
int month = c.get(Calendar.MONTH);
int day = c.get(Calendar.DAY_OF_MONTH);
// Create a new instance of DatePickerDialog and return it
return new DatePickerDialog(getActivity(), this, year, month, day);
}
public void onDateSet(DatePicker view, int year, int month, int day) {
txtDate.setText(new StringBuilder().append(month + 1)
.append("-").append(day).append("-").append(year)
.append(" "));
}
}
TimePickerFragment.java
PHP:
package com.test.dfw;
import java.util.Calendar;
import android.app.Dialog;
import android.app.TimePickerDialog;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.text.format.DateFormat;
import android.widget.TextView;
import android.widget.TimePicker;
public class TimePickerFragment extends DialogFragment implements TimePickerDialog.OnTimeSetListener{
TextView txtTime;
public TimePickerFragment(TextView txtTime) {
super();
this.txtTime = txtTime;
}
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
// Use the current time as the default values for the picker
final Calendar c = Calendar.getInstance();
int hour = c.get(Calendar.HOUR_OF_DAY);
int minute = c.get(Calendar.MINUTE);
// Create a new instance of TimePickerDialog and return it
return new TimePickerDialog(getActivity(), this, hour, minute,
DateFormat.is24HourFormat(getActivity()));
}
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
txtTime.setText(hourOfDay+":"+minute);
}
}
I then updated BookNowFragment.java
PHP:
package com.test.dfw;
import java.util.Calendar;
import android.app.Activity;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.telephony.SmsManager;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;
public class BookNowFragment extends Fragment implements OnClickListener {
Button buttonSubmit;
EditText edittextPhone;
EditText editTextProblem;
Button btnChangeDate,btnChangeTime;
TextView txtDisplayDate,txtDisplayTime;
DatePicker datePicker;
TimePicker timePicker;
private int year;
private int month;
private int day;
private int hour;
private int minute;
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final View rootView = inflater.inflate(R.layout.fragment_booknow,
container, false);
showCurrentDateOnView();
showCurrentTimeOnView();
buttonSubmit = (Button) rootView.findViewById(R.id.buttonSubmit);
// edittextPhone = (EditText) rootView.findViewById(R.id.edittextPhone);
// editTextProblem = (EditText)
// rootView.findViewById(R.id.editTextProblem);
buttonSubmit.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
String strPhoneNo = "00000000";
TextView txtName = (TextView) rootView
.findViewById(R.id.edittextName);
TextView txtPhone = (TextView) rootView
.findViewById(R.id.edittextPhone);
//TextView txtDate = (TextView) rootView.findViewById(R.id.date);
TextView txtProblem = (TextView) rootView
.findViewById(R.id.editTextProblem);
String strName = "Name: " + txtName.getText().toString();
String strPhone = "Phone: " + txtPhone.getText().toString();
//String strDate = "Date: " + txtDate.getText().toString();
String strProblem = "Problem: "
+ txtProblem.getText().toString();
String strMessage = strName + "\n" + strPhone + "\n" + strProblem;
BookNowSMS(strPhoneNo, strMessage);
}
});
return rootView;
}
// ---sends a SMS message to another device---
private void BookNowSMS(String phoneNumber, String message) {
/*
* PendingIntent pi = PendingIntent.getActivity(this, 0, new
* Intent(this, test.class), 0); SmsManager sms =
* SmsManager.getDefault(); sms.sendTextMessage(phoneNumber, null,
* message, pi, null);
*/
String SENT = "SMS_SENT";
// String DELIVERED = "SMS_DELIVERED";
PendingIntent sentPI = PendingIntent.getBroadcast(getActivity(), 0,
new Intent(SENT), 0);
/*
* PendingIntent deliveredPI = PendingIntent.getBroadcast(this, 0, new
* Intent(DELIVERED), 0);
*/
// ---when the SMS has been sent---
getActivity().registerReceiver(new BroadcastReceiver() {
@Override
public void onReceive(Context arg0, Intent arg1) {
switch (getResultCode()) {
case Activity.RESULT_OK:
Toast.makeText(getActivity(), "Message Sent",
Toast.LENGTH_SHORT).show();
break;
case SmsManager.RESULT_ERROR_GENERIC_FAILURE:
Toast.makeText(getActivity(), "Generic failure",
Toast.LENGTH_SHORT).show();
break;
case SmsManager.RESULT_ERROR_NO_SERVICE:
Toast.makeText(getActivity(), "No service",
Toast.LENGTH_SHORT).show();
break;
case SmsManager.RESULT_ERROR_NULL_PDU:
Toast.makeText(getActivity(), "Null PDU",
Toast.LENGTH_SHORT).show();
break;
case SmsManager.RESULT_ERROR_RADIO_OFF:
Toast.makeText(getActivity(), "Radio off",
Toast.LENGTH_SHORT).show();
break;
}
}
}, new IntentFilter(SENT));
SmsManager sms = SmsManager.getDefault();
sms.sendTextMessage(phoneNumber, null, message, sentPI, null);
}
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
}
// display current date
public void showCurrentDateOnView() {
txtDisplayDate = (TextView) findViewById(R.id.txtDate);
datePicker = (DatePicker) findViewById(R.id.datePicker1);
final Calendar c = Calendar.getInstance();
year = c.get(Calendar.YEAR);
month = c.get(Calendar.MONTH);
day = c.get(Calendar.DAY_OF_MONTH);
// set current date into textview
txtDisplayDate.setText(new StringBuilder()
// Month is 0 based, just add 1
.append(month + 1).append("-").append(day).append("-")
.append(year).append(" "));
// set current date into datepicker
datePicker.init(year, month, day, null);
}
// display current time
public void showCurrentTimeOnView() {
txtDisplayTime = (TextView) findViewById(R.id.txtTime);
timePicker = (TimePicker) findViewById(R.id.timePicker1);
final Calendar c = Calendar.getInstance();
hour = c.get(Calendar.HOUR_OF_DAY);
minute = c.get(Calendar.MINUTE);
// set current time into textview
txtDisplayTime.setText(
new StringBuilder().append(hour)
.append(":").append(minute));
// set current time into timepicker
timePicker.setCurrentHour(hour);
timePicker.setCurrentMinute(minute);
}
public void showDatePickerDialog(View v) {
DialogFragment newFragment = new DatePickerFragment(txtDisplayDate);
newFragment.show(getSupportFragmentManager(), "datePicker");
}
public void showTimePickerDialog(View v) {
DialogFragment newFragment = new TimePickerFragment(txtDisplayTime);
newFragment.show(getSupportFragmentManager(), "timePicker");
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
The problem areas are all under BookNowFragment.java;
1. Under "showCurrentDateOnView" the both findViewById says undefined for the type.I have tried adding rootView but didnt work.
2. Under "showCurrentTimeOnView" both findViewById says undefined for the type.I have tried adding rootView but didnt work.
3. under "showDatePickerDialog" and "showTimePickerDialog" both the getSupportFragmentManager methods show the error "The method getSupportFragmentManager() is undefined for the type BookNowFragment"
4. I also have errors with "onCreateOptionsMenu".I worked out some of them by adding getActivity (see new code below) but it still shows the error "The method onCreateOptionsMenu(Menu) of type BookNowFragment must override or implement a supertype method"
PHP:
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getActivity().getMenuInflater().inflate(R.menu.main, menu);
return true;
}
Think there simple issues although I'm simple as well so I could be understating it.

[Q] How to pass image from one intent to another

Hi friends,
Here is my code for displaying details and images from MySQL database,All i want to do is pass the detail with image to other inner page through intent.Please help me im new in android.
Activity 1
Code:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.List;
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.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.annotation.SuppressLint;
import android.app.ActionBar.LayoutParams;
import android.app.Fragment;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
@SuppressLint("NewApi") public class News_events extends Fragment {
private String jsonResult;
private String url = "<URL PHP FILES>";
HttpPost httppost;
StringBuffer buffer;
HttpResponse response;
HttpClient httpclient;
List<NameValuePair> nameValuePairs;
ProgressDialog dialog = null;
ImageView img;
Bitmap bitmap;
ProgressDialog pDialog;
// alert dialog manager
AlertDialogManager alert = new AlertDialogManager();
// Internet detector
ConnectionDetector cd;
InputStream is=null;
String result=null;
String line=null;
int code;
public News_events(){}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
pDialog = new ProgressDialog(getActivity());
View rootView = inflater.inflate(R.layout.fragment_news_events, container, false);
cd = new ConnectionDetector(rootView.getContext());
// Check if Internet present
if (!cd.isConnectingToInternet()) {
// Internet Connection is not present
alert.showAlertDialog(getActivity(),
"Internet Connection Error",
"Please connect to working Internet connection", false);
// stop executing code by return
//return.rootView;
return rootView;
}
accessWebService();
return rootView;
}
// Async Task to access the web
private class JsonReadTask extends AsyncTask<String, Void, String> {
@Override
protected String doInBackground(String... params) {
List<NameValuePair> nameValuePair = new ArrayList<NameValuePair>(1);
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(params[0]);
try {
httppost.setEntity(new UrlEncodedFormEntity(nameValuePair));
HttpResponse response = httpclient.execute(httppost);
jsonResult = inputStreamToString(
response.getEntity().getContent()).toString();
}
catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
private StringBuilder inputStreamToString(InputStream is) {
String rLine = "";
StringBuilder answer = new StringBuilder();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
try {
while ((rLine = rd.readLine()) != null) {
answer.append(rLine);
}
}
catch (IOException e) {
// e.printStackTrace();
Toast.makeText(getActivity().getApplicationContext(),
"Error..." + e.toString(), Toast.LENGTH_LONG).show();
}
return answer;
}
@Override
protected void onPostExecute(String result) {
display();
}
}// end async task
public void accessWebService() {
JsonReadTask task = new JsonReadTask();
// passes values for the urls string array
task.execute(new String[] { url });
}
// build hash set for list view
public void display() {
try {
JSONObject jsonResponse = new JSONObject(jsonResult);
JSONArray jsonMainNode = jsonResponse.optJSONArray("news_details");
LinearLayout MainLL= (LinearLayout)getActivity().findViewById(R.id.newslayout);
//LinearLayout headLN=(LinearLayout)findViewById(R.id.headsection);
for (int i = 0; i < jsonMainNode.length(); i++) {
JSONObject jsonChildNode = jsonMainNode.getJSONObject(i);
final String head = jsonChildNode.optString("title");
final String details = jsonChildNode.optString("text");
final String date = jsonChildNode.optString("date");
final String image = jsonChildNode.optString("img");
//final String time = jsonChildNode.optString("time");
//img = new ImageView(this.getActivity());
//new LoadImage().execute("<URL IMAGE FOLDER>"+image);
img = new ImageView(this.getActivity());
LoadImage ldimg=new LoadImage();
ldimg.setImage(img);
ldimg.execute("<URL IMAGE FOLDER>"+image);
TextView headln = new TextView(this.getActivity());
headln.setText(head); // News Headlines
headln.setTextSize(16);
headln.setTextColor(Color.BLACK);
headln.setGravity(Gravity.CENTER);
headln.setBackgroundColor(Color.parseColor("#ffcd14"));
// headln.setBackgroundResource(R.drawable.menubg);
headln.setPadding(0, 20, 0, 0);
// headln.setHeight(50);
headln.setClickable(true);
TextView dateln = new TextView(this.getActivity());
dateln.setText(date); // News Headlines
dateln.setTextSize(12);
dateln.setTextColor(Color.BLACK);
dateln.setGravity(Gravity.RIGHT);
//dateln.setBackgroundColor(Color.parseColor("#f20056"));
dateln.setBackgroundColor(0x00000000);
dateln.setPadding(0, 0, 10, 10);
dateln.setWidth(100);
dateln.setClickable(true);
View sep=new View(this.getActivity());
sep.setBackgroundColor(Color.parseColor("#252525"));
sep.setMinimumHeight(10);
TextView detailsln = new TextView(this.getActivity());
detailsln.setText(details); // News Details
detailsln.setTextSize(12);
detailsln.setTextColor(Color.BLACK);
detailsln.setGravity(Gravity.CENTER);
detailsln.setPadding(10, 10, 10, 10);
int width = LayoutParams.WRAP_CONTENT;
int height = 200;
LinearLayout.LayoutParams parms = new LinearLayout.LayoutParams(width,height);
img.setLayoutParams(parms);
parms.gravity = Gravity.CENTER;
img.setPaddingRelative (15, 15, 15, 15);
MainLL.addView(headln);
MainLL.addView(dateln);
// MainLL.addView(photo);
MainLL.addView(img);
MainLL.addView(detailsln);
MainLL.addView(sep);
img.setClickable(true);
headln.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
//Toast.makeText(getBaseContext(), head, Toast.LENGTH_SHORT).show();
Intent intent = new Intent(getActivity().getApplicationContext(),InnerNewsAndEvents.class);
intent.putExtra("head",head.toString());
intent.putExtra("details",details.toString());
intent.putExtra("date",date.toString());
intent.putExtra("img",img.toString());
// intent.putExtra("time",time.toString());
startActivity(intent);
}
});
dateln.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent = new Intent(getActivity().getApplicationContext(),InnerNewsAndEvents.class);
intent.putExtra("head",head.toString());
intent.putExtra("details",details.toString());
intent.putExtra("date",date.toString());
intent.putExtra("img",img.toString());
// intent.putExtra("time",time.toString());
startActivity(intent);
}
});
img.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent = new Intent(getActivity().getApplicationContext(),InnerNewsAndEvents.class);
intent.putExtra("head",head.toString());
intent.putExtra("details",details.toString());
intent.putExtra("date",date.toString());
intent.putExtra("img",img.toString());
// intent.putExtra("time",time.toString());
startActivity(intent);
}
});
}
} catch (JSONException e) {
Toast.makeText(getActivity().getApplicationContext(), "Error" + e.toString(),
Toast.LENGTH_SHORT).show();
}
}
private class LoadImage extends AsyncTask<String, String, Bitmap> {
ImageView img;
@Override
protected void onPreExecute() {
super.onPreExecute();
pDialog.setMessage("Loading Image ....");
pDialog.show();
}
public void setImage(ImageView img ){
this.img=img;
}
protected Bitmap doInBackground(String... args) {
try {
bitmap = BitmapFactory.decodeStream((InputStream)new URL(args[0]).openStream());
}
catch (Exception e) { e.printStackTrace(); }
return bitmap;
}
protected void onPostExecute(Bitmap image) {
if(image != null){
img.setImageBitmap(image);
pDialog.dismiss();
}
pDialog.dismiss();
}
}
public static boolean isInternetReachable()
{
try {
//make a URL to a known source
URL url = new URL("google");
//open a connection to that source
HttpURLConnection urlConnect = (HttpURLConnection)url.openConnection();
//trying to retrieve data from the source. If there
//is no connection, this line will fail
Object objData = urlConnect.getContent();
} catch (UnknownHostException e) {
e.printStackTrace();
return false;
}
catch (IOException e) {
e.printStackTrace();
return false;
}
return true;
}
}
Activity 2
Code:
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.widget.ImageView;
import android.widget.TextView;
public class InnerNewsAndEvents extends Activity {
ProgressDialog pDialog;
ProgressDialog dialog = null;
Bitmap bitmap;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_inner_news_and_events);
TextView title=(TextView)findViewById(R.id.tvtitle);
TextView details=(TextView)findViewById(R.id.tvdetails);
ImageView img=(ImageView)findViewById(R.id.imgpic);
Intent intent = getIntent();
String strhead = intent.getStringExtra("head");
String strdetails = intent.getStringExtra("details");
String strdate = intent.getStringExtra("date");
String strimg = intent.getStringExtra("img");
title.setText(strhead);
details.setText(strdetails);
}
}
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.widget.ImageView;
import android.widget.TextView;
public class InnerNewsAndEvents extends Activity {
ProgressDialog pDialog;
ProgressDialog dialog = null;
Bitmap bitmap;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_inner_news_and_events);
TextView title=(TextView)findViewById(R.id.tvtitle);
TextView details=(TextView)findViewById(R.id.tvdetails);
ImageView img=(ImageView)findViewById(R.id.imgpic);
Intent intent = getIntent();
String strhead = intent.getStringExtra("head");
String strdetails = intent.getStringExtra("details");
String strdate = intent.getStringExtra("date");
String strimg = intent.getStringExtra("img");
title.setText(strhead);
details.setText(strdetails);
}
}

Custom List View Open New Activities

Hey everyone. Here is my code below. I have everything working. Got it to display the pictures and text in a list view. Only issue is that I want to be able to click on one of the list items and have it open an activity. When I added that part in, I get an error that states,
"Error44, 45) error: no suitable constructor found for Intent(<anonymous OnItemClickListener>,Class)
constructor Intent.Intent(String,Uri) is not applicable
(argument mismatch; <anonymous OnItemClickListener> cannot be converted to String)
constructor Intent.Intent(Context,Class<?>) is not applicable
(argument mismatch; <anonymous OnItemClickListener> cannot be converted to Context)"
Here is my code:
Code:
package com.example.matt.nootropicahandbook;
import android.net.Uri;
import android.app.Activity;
import android.app.ListActivity;
import android.os.Bundle;
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 android.content.Intent;
public class Biohack extends Activity
{
ListView list;
String[] itemname = {"Nootropics", "Supplements", "Metabolic Enhancement","Stacks", "Neuro Stimulation", "Diet", "Stay Away From",};
Integer[] imgid={R.drawable.piracetam1, R.drawable.piracetam2, R.drawable.piracetam3,
R.drawable.piracetam4, R.drawable.piracetam5, R.drawable.piracetam6, R.drawable.piracetam7,};
String[] classNames = {"Main", "Lifehack"};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_biohack);
biohacksAdapter adapter=new biohacksAdapter(this, itemname, imgid, classNames);
list=(ListView)findViewById(R.id.list);
list.setAdapter(adapter);
list.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// TODO Auto-generated method stub
String openClass = classNames[position];
try{
Class selected = Class.forName("com.example.matt.nootropicahandbook."+openClass);
Intent selectedIntent = new Intent(this, selected);
startActivity(selectedIntent);
}catch (ClassNotFoundException e)
{
e.printStackTrace();
}
}
});
}
}
The error is on the line:
Code:
Intent selectedIntent = new Intent(this, selected);
And here is my adapter class for refrence
Code:
package com.example.matt.nootropicahandbook;
import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
public class biohacksAdapter extends ArrayAdapter<String>{
private final Activity context;
private final String[] itemname;
private final Integer[] imgid;
private final String[] classNames;
public biohacksAdapter(Activity context,String[] itemname, Integer[] imgid, String[] classNames) {
super(context,R.layout.custom_row, itemname);
this.context = context;
this.itemname = itemname;
this.imgid = imgid;
this.classNames = classNames;
}
public View getView(int position, View view, ViewGroup parent)
{
LayoutInflater inflater = context.getLayoutInflater();
View rowView = inflater.inflate(R.layout.custom_row, null, true);
TextView txtTitle = (TextView) rowView.findViewById(R.id.item);
ImageView imageView = (ImageView) rowView.findViewById(R.id.icon);
TextView extratxt = (TextView) rowView.findViewById(R.id.textView1);
txtTitle.setText(itemname[position]);
imageView.setImageResource(imgid[position]);
extratxt.setText("Description "+itemname[position]);
return rowView;
}
}
replace
Intent selectedIntent = new Intent(this, selected);
to
Intent selectedIntent = new Intent(Biohack.this, selected);
because ...

Categories

Resources