Question

I have one main.xml in my android project which has following control

TextBox1 Button1 TextBox2 Button2

TextBox3
TextBox4 Label1

Button3

I have two activities name DatePickerDialogAppsActivity and JSONSampleAppActivity.

Datepickerdialogappsactivity has functionality to popup datapicker on button1 and button2 click event

Jsonsampleactivity connect with my sql database and bind data with label on button3 click event taking input from user in textbox3 and textbox4

Problem: My main.xml file access both the datepickerdialogappsactivity and jsonsampleactivity how should i define the activities and manifest file.

this is my code only one at a time activities run means what every activity i define on first node it works and secondly does not work. For e.g in below code datepickerdialogappsactivity works and jsonsampleactivity does not work if i define jsonsample activity on first it will work then second one will not work please guide

<application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name" >
        <activity
            android:name=".DatePickerDialogAppsActivity"

            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

    <activity
            android:name=".jsonsampleactivity"

            android:label="@string/app_name" >

        </activity>


    </application>

Main.xml code

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >
 <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="@string/hello" />

    <EditText
        android:id="@+id/editText1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" 
        android:hint="From Date"
        >

        <requestFocus />
    </EditText>


    <EditText
        android:id="@+id/editText2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" 
        android:hint="To Date"
        >

        <requestFocus />
    </EditText>

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
       android:width="150px"

        android:onClick="showDatePickerDialog"
        android:text="From Date" />

      <Button
        android:id="@+id/button2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"

          android:width="150px"

        android:onClick="showDatePickerDialogg"
        android:text="To Date" />

    <EditText
        android:id="@+id/txtUserName"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" 
        android:hint="User Name"
        >

        <requestFocus />
    </EditText>

    <EditText
        android:id="@+id/txtPassword"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" 
        android:hint="Password"
        android:inputType="textPassword"
        />


    <Button
        android:id="@+id/btnLogin"
        android:layout_width="128dp"
        android:layout_height="wrap_content"
        android:text="Button" />

    <TextView
        android:id="@+id/lblStatus"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Status"
        android:textAppearance="?android:attr/textAppearanceLarge" />


</LinearLayout>

Datepickercode

package com.Android.JSONApp;

import java.util.Calendar;

import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.os.Bundle;
import android.view.View;
import android.widget.DatePicker;
import android.widget.EditText;



public class DatePickerDialogAppsActivity extends Activity {
    /** Called when the activity is first created. */
    static final int DATE_DIALOG_ID=0;
    static final int DATE_DIALOG_IDD=1;
    int yr,mon,day, yrr, monn, dayy;



     @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);



    }


    public void showDatePickerDialog(View v)
    {
         Calendar today=Calendar.getInstance();
         yr=today.get(Calendar.YEAR);
         mon=today.get(Calendar.MONTH);
         day=today.get(Calendar.DAY_OF_MONTH);
        showDialog(DATE_DIALOG_ID);
    }

    public void showDatePickerDialogg(View v)
    {
         Calendar today=Calendar.getInstance();
         yrr=today.get(Calendar.YEAR);
         monn=today.get(Calendar.MONTH);
         dayy=today.get(Calendar.DAY_OF_MONTH);
        showDialog(DATE_DIALOG_IDD);
    }
    protected Dialog onCreateDialog(int id)
    {
        switch (id) {
        case DATE_DIALOG_ID:
            return new DatePickerDialog(this,dateSetListener,yr,mon+1,day);
        case DATE_DIALOG_IDD:
            return new DatePickerDialog(this,dateSetListenerr,yrr,monn+1,dayy);
        }
        return null;
    }
    private DatePickerDialog.OnDateSetListener dateSetListener=new DatePickerDialog.OnDateSetListener() {

        @Override
        public void onDateSet(DatePicker view, int year, int monthOfYear,
                int dayOfMonth) {
            // TODO Auto-generated method stub
            yr=year;
            mon=monthOfYear +1;
            day=dayOfMonth;
            EditText it=(EditText)findViewById(R.id.editText1);

            it.setText(day+" - "+mon+" - "+yr);
        }
    };

private DatePickerDialog.OnDateSetListener dateSetListenerr=new DatePickerDialog.OnDateSetListener() {

        @Override
        public void onDateSet(DatePicker view, int yearr, int monthOfYearr,
                int dayOfMonthh) {
            // TODO Auto-generated method stub
            yrr=yearr;
            monn=monthOfYearr +1;
            dayy=dayOfMonthh;
            EditText itt=(EditText)findViewById(R.id.editText2);

            itt.setText(dayy+" - "+monn+" - "+yrr);
        }
    };
}

jsonsample code

package com.Android.JSONApp;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class JSONSampleAppActivity extends Activity implements OnClickListener{
    /** Called when the activity is first created. */

    //Property declaration
    Button btnLogin;
    TextView lblStatus;
    EditText txtUserName,txtPassword;


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        btnLogin=(Button)findViewById(R.id.btnLogin);
        btnLogin.setOnClickListener(this);

        lblStatus=(TextView)findViewById(R.id.lblStatus);

        txtUserName=(EditText)findViewById(R.id.txtUserName);
        txtPassword=(EditText)findViewById(R.id.txtPassword);
    }

    @Override
    public void onClick(View v) {

        switch(v.getId())
        {
            case R.id.btnLogin:
                String userName=txtUserName.getText().toString();
                String password=txtPassword.getText().toString();
                if(verifyLogin(userName,password))
                {
                    lblStatus.setText("Login Successful");
                }
                else
                {
                    lblStatus.setText("Login Failed");
                }
                break;
        }
    }

    public static String convertStreamToString(InputStream is) 
    {
        BufferedReader reader = new BufferedReader(new InputStreamReader(is));
        StringBuilder sb = new StringBuilder();

        String line = null;
        try {
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
        } 
        catch (IOException e) {
            e.printStackTrace();
        } 
        finally {
            try {
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return sb.toString();
    }

    public static boolean verifyLogin(String UserName,String Password)
    {
        try
        {
            System.out.println("guru");
            DefaultHttpClient httpClient=new DefaultHttpClient();

            //Connect to the server
            HttpGet httpGet=new HttpGet("http://xxx/Service1.svc/checkLogin?name="+UserName+"&pass="+Password);
            //Get the response
            HttpResponse httpResponse = httpClient.execute(httpGet);
            HttpEntity httpEntity = httpResponse.getEntity();
            InputStream stream=httpEntity.getContent();

            //Convert the stream to readable format
            String result= convertStreamToString(stream);

            if(result.charAt(1)=='1')
            {
                return true;
            }
            else
            {
                return false;
            }
        }
        catch(Exception e)
        {
            return false;
        }

    }


}
Was it helpful?

Solution

You can use one Activity to do both, like this:

public class MainActivity extends Activity {
/** Called when the activity is first created. */
static final int DATE_DIALOG_ID=0;
static final int DATE_DIALOG_IDD=1;
int yr,mon,day, yrr, monn, dayy;

Button btnLogin;
TextView lblStatus;
EditText txtUserName,txtPassword;

 @Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);


    btnLogin=(Button)findViewById(R.id.btnLogin);
    btnLogin.setOnClickListener(this);

    lblStatus=(TextView)findViewById(R.id.lblStatus);

    txtUserName=(EditText)findViewById(R.id.txtUserName);
    txtPassword=(EditText)findViewById(R.id.txtPassword);
}


public void showDatePickerDialog(View v)
{
     Calendar today=Calendar.getInstance();
     yr=today.get(Calendar.YEAR);
     mon=today.get(Calendar.MONTH);
     day=today.get(Calendar.DAY_OF_MONTH);
    showDialog(DATE_DIALOG_ID);
}

public void showDatePickerDialogg(View v)
{
     Calendar today=Calendar.getInstance();
     yrr=today.get(Calendar.YEAR);
     monn=today.get(Calendar.MONTH);
     dayy=today.get(Calendar.DAY_OF_MONTH);
    showDialog(DATE_DIALOG_IDD);
}
protected Dialog onCreateDialog(int id)
{
    switch (id) {
    case DATE_DIALOG_ID:
        return new DatePickerDialog(this,dateSetListener,yr,mon+1,day);
    case DATE_DIALOG_IDD:
        return new DatePickerDialog(this,dateSetListenerr,yrr,monn+1,dayy);
    }
    return null;
}
private DatePickerDialog.OnDateSetListener dateSetListener=new DatePickerDialog.OnDateSetListener() {

    @Override
    public void onDateSet(DatePicker view, int year, int monthOfYear,
            int dayOfMonth) {
        // TODO Auto-generated method stub
        yr=year;
        mon=monthOfYear +1;
        day=dayOfMonth;
        EditText it=(EditText)findViewById(R.id.editText1);

        it.setText(day+" - "+mon+" - "+yr);
    }
};

private DatePickerDialog.OnDateSetListener dateSetListenerr=new     DatePickerDialog.OnDateSetListener() {

    @Override
    public void onDateSet(DatePicker view, int yearr, int monthOfYearr,
            int dayOfMonthh) {
        // TODO Auto-generated method stub
        yrr=yearr;
        monn=monthOfYearr +1;
        dayy=dayOfMonthh;
        EditText itt=(EditText)findViewById(R.id.editText2);

        itt.setText(dayy+" - "+monn+" - "+yrr);
    }
};

@Override
public void onClick(View v) {

    switch(v.getId())
    {
        case R.id.btnLogin:
            String userName=txtUserName.getText().toString();
            String password=txtPassword.getText().toString();
            if(verifyLogin(userName,password))
            {
                lblStatus.setText("Login Successful");
            }
            else
            {
                lblStatus.setText("Login Failed");
            }
            break;
    }
}

public static String convertStreamToString(InputStream is) 
{
    BufferedReader reader = new BufferedReader(new InputStreamReader(is));
    StringBuilder sb = new StringBuilder();

    String line = null;
    try {
        while ((line = reader.readLine()) != null) {
            sb.append(line + "\n");
        }
    } 
    catch (IOException e) {
        e.printStackTrace();
    } 
    finally {
        try {
            is.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    return sb.toString();
}

public static boolean verifyLogin(String UserName,String Password)
{
    try
    {
        System.out.println("guru");
        DefaultHttpClient httpClient=new DefaultHttpClient();

        //Connect to the server
        HttpGet httpGet=new HttpGet("http://xxx/Service1.svc/checkLogin?name="+UserName+"&pass="+Password);
        //Get the response
        HttpResponse httpResponse = httpClient.execute(httpGet);
        HttpEntity httpEntity = httpResponse.getEntity();
        InputStream stream=httpEntity.getContent();

        //Convert the stream to readable format
        String result= convertStreamToString(stream);

        if(result.charAt(1)=='1')
        {
            return true;
        }
        else
        {
            return false;
        }
    }
    catch(Exception e)
    {
        return false;
    }

}
}

OTHER TIPS

In both the activities, use:

setContentView(R.layout.main);

But, what are you trying to achieve if both activities have same layout?

As a rule of thumb, you should always use different xml for different activities.

If two Activities share the same layout, it's OK in terms of functionality (but at least strange in terms of design, because Activity class is aimed to interact with user via UI): in Android only one Activity can be displayed at the same time. So, you cannot have 2 activities displayed simultaneously. If you start one Activity from another, the first one will be paused. If you want both activities to be displayed in launcher, both of them should have the following:

<intent-filter>
    <action android:name="android.intent.action.MAIN" />

    <category android:name="android.intent.category.LAUNCHER" />
</intent-filter>

But one of them should also annotated as default:

<category android:name="android.intent.category.DEFAULT"/>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top